Commits

Kaspar Schiess committed e3886c3

Refactor some of the code, better mac matching

Illumos lists mac addresses in normalized style. This normalizes the
mac address we're looking for before matching it, so that a match
is made in all cases where the mac address matches.

  • Participants
  • Parent commits ca6c930

Comments (0)

Files changed (4)

lib/qemu-toolkit.rb

 require 'qemu-toolkit/vm'
 require 'qemu-toolkit/vm_storage'
 require 'qemu-toolkit/backend/illumos'
-require 'qemu-toolkit/vnic'
+require 'qemu-toolkit/vnic'
+require 'qemu-toolkit/vnic_collection'

lib/qemu-toolkit/vnic.rb

 
 module QemuToolkit
   class Vnic
-    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 || (mac_address == vnic.macaddr)) && 
-          via == vnic.over }
-
-        @used << vnic
-        vnic
-      end
-
-      def empty?
-        @used.size == @vnics.size
-      end
-    end
-
     class << self
       def for_prefix(prefix, background)
         vnics = VnicCollection.new

lib/qemu-toolkit/vnic_collection.rb

+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
+    

spec/lib/qemu-toolkit/vnic_collection_spec.rb

+require 'spec_helper'
+
+describe QemuToolkit::VnicCollection do
+  let(:coll) { described_class.new }
+
+  describe "#normalize_mac_address" do
+    it 'replaces 0a with a' do
+      coll.normalize_mac_address('01:02:03:04:05:06:07:08:09:0a:0B:0C:0D:0e:0f').
+        should == '1:2:3:4:5:6:7:8:9:a:b:c:d:e:f'
+    end
+  end
+  describe "allocate" do
+    let(:vnic) { flexmock(macaddr: '1:2:a', over: 'igb0') }
+    before(:each) { coll << vnic }
+    
+    it "filters for normalized mac address" do
+      coll.allocate('igb0', '01:02:0a').should == vnic
+    end
+  end
+end