Source

qemu-toolkit / lib / qemu-toolkit / vnic_collection.rb

Full commit
module QemuToolkit

  # A collection of vnics. This class keeps track of vnic allocations to 
  # devices, so that no vnic will be used twice. 
  #
  class VnicCollection
    def initialize(vnics=[])
      @vnics = Set.new(vnics)
      @used = Set.new
    end

    def << vnic
      @vnics << vnic
    end

    def map &block
      unused.map(&block)
    end

    def unused
      @vnics - @used
    end

    def allocate(via, mac_address=nil)
      vnic=unused.find { |vnic| 
        (!mac_address || 
          (normalize_mac_address(mac_address) == vnic.macaddr)) && 
        via == vnic.over }

      @used << vnic
      vnic
    end

    def empty?
      @used.size == @vnics.size
    end

    def normalize_mac_address mac_address
      mac_address.split(':').map { |n|
        if md=n.match(/0(.)/)
          md[1].downcase
        else
          n
        end
      }.join(':')
    end
  end
end