Class: CemAcpt::LocalPortAllocator
- Inherits:
-
Object
- Object
- CemAcpt::LocalPortAllocator
- Defined in:
- lib/cem_acpt/shared_objects.rb
Overview
Handles local port allocation for things like local SSH tunnels. This class is thread-safe as the port range is a Concurrent::Array, which blocks when modified. When this class is initialized, it's total assignable ports are set to all ports in the ephemeral port range. When a port is allocated, it's removed from the port range.
Constant Summary collapse
- EPHEMERAL_PORT_RANGE =
(49_152..65_535).to_a.freeze
Instance Method Summary collapse
-
#allocate(number_of_ports = 1) ⇒ Integer+
Returns an open port(s) in the ephemeral port range on the local machine.
-
#initialize ⇒ LocalPortAllocator
constructor
A new instance of LocalPortAllocator.
Constructor Details
#initialize ⇒ LocalPortAllocator
Returns a new instance of LocalPortAllocator.
370 371 372 |
# File 'lib/cem_acpt/shared_objects.rb', line 370 def initialize @port_range = Concurrent::Array.new(EPHEMERAL_PORT_RANGE.dup).shuffle! end |
Instance Method Details
#allocate(number_of_ports = 1) ⇒ Integer+
Returns an open port(s) in the ephemeral port range on the local machine. If 'number_of_ports' is specified and greater than one, returns an array of ports. If 'number_of_ports' is not specified or is one, returns a single port.
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 |
# File 'lib/cem_acpt/shared_objects.rb', line 381 def allocate(number_of_ports = 1) unless number_of_ports.is_a?(Integer) && number_of_ports.positive? raise ArgumentError, 'number_of_ports must be a positive integer' end raise LocalPortAllocationError, 'No ports available' if @port_range.empty? ports = [] while ports.length < number_of_ports port = @port_range.pop next unless local_port_open?(port) ports << port end return ports[0] if ports.length == 1 ports end |