From a6c1645d47b18d335fbfd77087af62f4b899f48b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Morten=20M=C3=B8ller=20Riis?= Date: Tue, 12 Mar 2019 08:57:34 +0100 Subject: [PATCH] Added wildcard matching on MAC addresses. --- pkg/netconf/netconf_linux.go | 5 +++ pkg/netconf/netconf_linux_test.go | 70 +++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 pkg/netconf/netconf_linux_test.go diff --git a/pkg/netconf/netconf_linux.go b/pkg/netconf/netconf_linux.go index e228797a..d99b4506 100644 --- a/pkg/netconf/netconf_linux.go +++ b/pkg/netconf/netconf_linux.go @@ -111,6 +111,11 @@ func findMatch(link netlink.Link, netCfg *NetworkConfig) (InterfaceConfig, bool) } if strings.HasPrefix(netConf.Match, "mac") { + if strings.Contains(netConf.Match, "*") { + // If selector contains wildcard * and MAC address matches wildcard then return + return netConf, glob.Glob(netConf.Match[4:], link.Attrs().HardwareAddr.String()) + } + haAddr, err := net.ParseMAC(netConf.Match[4:]) if err != nil { log.Errorf("Failed to parse mac %s: %v", netConf.Match[4:], err) diff --git a/pkg/netconf/netconf_linux_test.go b/pkg/netconf/netconf_linux_test.go new file mode 100644 index 00000000..68d3c9ed --- /dev/null +++ b/pkg/netconf/netconf_linux_test.go @@ -0,0 +1,70 @@ +package netconf + +import ( + "net" + "testing" + + "github.com/vishvananda/netlink" +) + +type mockLink struct { + attrs netlink.LinkAttrs +} + +func (l mockLink) Attrs() *netlink.LinkAttrs { + return &l.attrs +} + +func (l mockLink) Type() string { + return "fake" +} + +func TestFindMatch(t *testing.T) { + testCases := []struct { + match string + mac string + expected bool + }{ + { + "mac:aa:bb:cc:dd:ee:ff", + "aa:bb:cc:dd:ee:ff", + true, + }, + { + "mac:aa:bb:cc:*", + "aa:bb:cc:12:34:56", + true, + }, + { + "mac:aa:bb:cc:*", + "11:bb:cc:dd:ee:ff", + false, + }, + { + "mac:aa:bb:cc:dd:ee:ff", + "aa:bb:cc:dd:ee:11", + false, + }, + } + + for i, tt := range testCases { + netCfg := NetworkConfig{ + Interfaces: map[string]InterfaceConfig{ + "eth0": InterfaceConfig{ + Match: tt.match, + }, + }, + } + + linkAttrs := netlink.NewLinkAttrs() + linkAttrs.Name = "eth0" + linkAttrs.HardwareAddr, _ = net.ParseMAC(tt.mac) + link := mockLink{attrs: linkAttrs} + + _, match := findMatch(link, &netCfg) + + if match != tt.expected { + t.Errorf("Test case %d failed: mac: '%s' match '%s' expected: '%v' got: '%v'", i, tt.mac, tt.match, tt.expected, match) + } + } +}