|
4 | 4 | package network
|
5 | 5 |
|
6 | 6 | import (
|
| 7 | + "net" |
| 8 | + |
7 | 9 | "github.com/Azure/azure-container-networking/cni"
|
8 | 10 | "github.com/Azure/azure-container-networking/common"
|
9 | 11 | "github.com/Azure/azure-container-networking/log"
|
@@ -87,6 +89,34 @@ func (plugin *netPlugin) getEndpointID(args *cniSkel.CmdArgs) string {
|
87 | 89 | return args.ContainerID[:8] + "-" + args.IfName
|
88 | 90 | }
|
89 | 91 |
|
| 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 | + |
90 | 120 | //
|
91 | 121 | // CNI implementation
|
92 | 122 | // https://github.com/containernetworking/cni/blob/master/SPEC.md
|
@@ -131,8 +161,15 @@ func (plugin *netPlugin) Add(args *cniSkel.CmdArgs) error {
|
131 | 161 | subnetPrefix := resultImpl.IP4.IP
|
132 | 162 | subnetPrefix.IP = subnetPrefix.IP.Mask(subnetPrefix.Mask)
|
133 | 163 |
|
| 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 | + |
134 | 171 | // Add the master as an external interface.
|
135 |
| - err = plugin.nm.AddExternalInterface(nwCfg.Master, subnetPrefix.String()) |
| 172 | + err = plugin.nm.AddExternalInterface(masterIfName, subnetPrefix.String()) |
136 | 173 | if err != nil {
|
137 | 174 | return plugin.Errorf("Failed to add external interface: %v", err)
|
138 | 175 | }
|
|
0 commit comments