Class: OsVm::PortReservation
- Inherits:
-
Object
- Object
- OsVm::PortReservation
- Includes:
- Singleton
- Defined in:
- lib/osvm/port_reservation.rb
Overview
Singleton class handling port reservations
Instance Method Summary collapse
- #get_port(key:) ⇒ Integer
- #get_ports(key:, size:) ⇒ Array<Integer>
-
#initialize ⇒ PortReservation
constructor
A new instance of PortReservation.
- #release_port(key:) ⇒ Object
- #release_ports(key:) ⇒ Object
-
#reset_to_ports(ports) ⇒ Object
Reset this class and scope available ports to ‘ports`.
Constructor Details
#initialize ⇒ PortReservation
Returns a new instance of PortReservation.
16 17 18 19 20 |
# File 'lib/osvm/port_reservation.rb', line 16 def initialize @ports = (10_000..30_000).to_a @allocations = {} @mutex = Mutex.new end |
Instance Method Details
#get_port(key:) ⇒ Integer
24 25 26 27 28 29 30 31 32 33 |
# File 'lib/osvm/port_reservation.rb', line 24 def get_port(key:) @mutex.synchronize do alloc = @allocations[key] next(alloc.first) if alloc port = @ports.shift @allocations[key] = [port] port end end |
#get_ports(key:, size:) ⇒ Array<Integer>
44 45 46 47 48 49 50 51 52 53 |
# File 'lib/osvm/port_reservation.rb', line 44 def get_ports(key:, size:) @mutex.synchronize do alloc = @allocations[key] next(alloc) if alloc ports = size.times.map { @ports.shift } @allocations[key] = ports ports end end |
#release_port(key:) ⇒ Object
37 38 39 |
# File 'lib/osvm/port_reservation.rb', line 37 def release_port(key:) release_ports(key:) end |
#release_ports(key:) ⇒ Object
56 57 58 59 60 61 62 63 64 65 66 |
# File 'lib/osvm/port_reservation.rb', line 56 def release_ports(key:) @mutex.synchronize do alloc = @allocations[key] next if alloc.nil? @allocations.delete(key) alloc.each { |port| @ports << port } end nil end |
#reset_to_ports(ports) ⇒ Object
Reset this class and scope available ports to ‘ports`
This is useful when forking processes: the parent process calls #get_ports, forks and the child process can be scoped to the reservation using this method.
74 75 76 77 78 79 80 81 |
# File 'lib/osvm/port_reservation.rb', line 74 def reset_to_ports(ports) @mutex.synchronize do @ports = ports @allocations = {} end nil end |