Class: OsVm::PortReservation

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/osvm/port_reservation.rb

Overview

Singleton class handling port reservations

Instance Method Summary collapse

Constructor Details

#initializePortReservation

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

Parameters:

  • key (any)

Returns:

  • (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>

Parameters:

  • key (any)
  • size (Integer)

    number of ports

Returns:

  • (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

Parameters:

  • key (any)
  • port (Integer)


37
38
39
# File 'lib/osvm/port_reservation.rb', line 37

def release_port(key:)
  release_ports(key:)
end

#release_ports(key:) ⇒ Object

Parameters:

  • key (any)


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.

Parameters:

  • ports (Array<Integer>)


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