Skip to content

Commit eb6d0bb

Browse files
committed
fix encap ip when the tunnel interface has multiple addresses (#2340)
1 parent 53df20f commit eb6d0bb

File tree

1 file changed

+36
-4
lines changed

1 file changed

+36
-4
lines changed

pkg/daemon/config.go

+36-4
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,25 @@ func ParseFlags(nicBridgeMappings map[string]string) (*Configuration, error) {
130130
return config, nil
131131
}
132132

133+
func getSrcIPsByRoutes(iface *net.Interface) ([]string, error) {
134+
link, err := netlink.LinkByName(iface.Name)
135+
if err != nil {
136+
return nil, fmt.Errorf("failed to get link %s: %v", iface.Name, err)
137+
}
138+
routes, err := netlink.RouteList(link, netlink.FAMILY_ALL)
139+
if err != nil {
140+
return nil, fmt.Errorf("failed to get routes on link %s: %v", iface.Name, err)
141+
}
142+
143+
srcIPs := make([]string, 0, 2)
144+
for _, r := range routes {
145+
if r.Src != nil && r.Scope == netlink.SCOPE_LINK {
146+
srcIPs = append(srcIPs, r.Src.String())
147+
}
148+
}
149+
return srcIPs, nil
150+
}
151+
133152
func (config *Configuration) initNicConfig(nicBridgeMappings map[string]string) error {
134153
var (
135154
iface *net.Interface
@@ -171,16 +190,29 @@ func (config *Configuration) initNicConfig(nicBridgeMappings map[string]string)
171190
klog.Errorf("failed to find iface %s, %v", tunnelNic, err)
172191
return err
173192
}
193+
srcIPs, err := getSrcIPsByRoutes(iface)
194+
if err != nil {
195+
return fmt.Errorf("failed to get src IPs by routes on interface %s: %v", iface.Name, err)
196+
}
174197
addrs, err := iface.Addrs()
175198
if err != nil {
176199
return fmt.Errorf("failed to get iface addr. %v", err)
177200
}
178-
if len(addrs) == 0 {
179-
return fmt.Errorf("iface %s has no ip address", tunnelNic)
201+
for _, addr := range addrs {
202+
ipStr := strings.Split(addr.String(), "/")[0]
203+
if ip := net.ParseIP(ipStr); ip == nil || ip.IsLinkLocalUnicast() {
204+
continue
205+
}
206+
if len(srcIPs) == 0 || util.ContainsString(srcIPs, ipStr) {
207+
encapIP = ipStr
208+
break
209+
}
210+
}
211+
if len(encapIP) == 0 {
212+
return fmt.Errorf("iface %s has no valid IP address", tunnelNic)
180213
}
181-
encapIP = strings.Split(addrs[0].String(), "/")[0]
182214

183-
klog.Infof("use %s as tunnel interface", iface.Name)
215+
klog.Infof("use %s on %s as tunnel address", encapIP, iface.Name)
184216
config.tunnelIface = iface.Name
185217
}
186218

0 commit comments

Comments
 (0)