Skip to content

Commit 69510c9

Browse files
committed
Added ability to find the master interface by address pool
1 parent 2fad3bb commit 69510c9

File tree

1 file changed

+38
-1
lines changed

1 file changed

+38
-1
lines changed

cni/network/network.go

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
package network
55

66
import (
7+
"net"
8+
79
"github.com/Azure/azure-container-networking/cni"
810
"github.com/Azure/azure-container-networking/common"
911
"github.com/Azure/azure-container-networking/log"
@@ -87,6 +89,34 @@ func (plugin *netPlugin) getEndpointID(args *cniSkel.CmdArgs) string {
8789
return args.ContainerID[:8] + "-" + args.IfName
8890
}
8991

92+
// FindMasterInterface returns the name of the master interface.
93+
func (plugin *netPlugin) findMasterInterface(nwCfg *cni.NetworkConfig, subnetPrefix *net.IPNet) string {
94+
// An explicit master configuration wins. Explicitly specifying a master is
95+
// useful if host has multiple interfaces with addresses in the same subnet.
96+
if nwCfg.Master != "" {
97+
return nwCfg.Master
98+
}
99+
100+
// Otherwise, pick the first interface with an IP address in the given subnet.
101+
subnetPrefixString := subnetPrefix.String()
102+
interfaces, _ := net.Interfaces()
103+
for _, iface := range interfaces {
104+
addrs, _ := iface.Addrs()
105+
for _, addr := range addrs {
106+
_, ipnet, err := net.ParseCIDR(addr.String())
107+
if err != nil {
108+
continue
109+
}
110+
if subnetPrefixString == ipnet.String() {
111+
return iface.Name
112+
}
113+
}
114+
}
115+
116+
// Failed to find a suitable interface.
117+
return ""
118+
}
119+
90120
//
91121
// CNI implementation
92122
// https://github.com/containernetworking/cni/blob/master/SPEC.md
@@ -131,8 +161,15 @@ func (plugin *netPlugin) Add(args *cniSkel.CmdArgs) error {
131161
subnetPrefix := resultImpl.IP4.IP
132162
subnetPrefix.IP = subnetPrefix.IP.Mask(subnetPrefix.Mask)
133163

164+
// Find the master interface.
165+
masterIfName := plugin.findMasterInterface(nwCfg, &subnetPrefix)
166+
if masterIfName == "" {
167+
return plugin.Errorf("Failed to find the master interface")
168+
}
169+
log.Printf("[cni-net] Found master interface %v.", masterIfName)
170+
134171
// Add the master as an external interface.
135-
err = plugin.nm.AddExternalInterface(nwCfg.Master, subnetPrefix.String())
172+
err = plugin.nm.AddExternalInterface(masterIfName, subnetPrefix.String())
136173
if err != nil {
137174
return plugin.Errorf("Failed to add external interface: %v", err)
138175
}

0 commit comments

Comments
 (0)