Class: OsCtl::Image::IpAllocator

Inherits:
Object
  • Object
show all
Defined in:
lib/osctl/image/ip_allocator.rb

Overview

Allocate unique IP addresses from network

Instance Method Summary collapse

Constructor Details

#initialize(addr) ⇒ IpAllocator

Returns a new instance of IpAllocator.

Parameters:

  • addr (String)

    IPv4 network address



7
8
9
10
11
# File 'lib/osctl/image/ip_allocator.rb', line 7

def initialize(addr)
  @available = IPAddress.parse(addr).hosts
  @taken = {}
  @mutex = Mutex.new
end

Instance Method Details

#getIPAddress::IPv4

Returns:

  • (IPAddress::IPv4)


14
15
16
17
18
19
20
# File 'lib/osctl/image/ip_allocator.rb', line 14

def get
  @mutex.synchronize do
    ip = @available.shift
    @taken[ip.u32] = ip
    ip
  end
end

#put(ip) ⇒ Object

Parameters:

  • ip (IPAddress::IPv4)


23
24
25
26
27
28
29
30
31
32
33
# File 'lib/osctl/image/ip_allocator.rb', line 23

def put(ip)
  @mutex.synchronize do
    unless @taken.has_key?(ip.u32)
      raise ArgumentError, "#{ip} was not allocated"
    end

    @taken.delete(ip.u32)
    @available << ip
    nil
  end
end