-
Notifications
You must be signed in to change notification settings - Fork 737
/
driver.go
352 lines (298 loc) · 12.1 KB
/
driver.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may
// not use this file except in compliance with the License. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license" file accompanying this file. This file is distributed
// on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing
// permissions and limitations under the License.
package driver
import (
"net"
"syscall"
"github.com/pkg/errors"
"golang.org/x/sys/unix"
"github.com/containernetworking/cni/pkg/ns"
"github.com/vishvananda/netlink"
log "github.com/cihub/seelog"
"github.com/aws/amazon-vpc-cni-k8s/pkg/ipwrapper"
"github.com/aws/amazon-vpc-cni-k8s/pkg/netlinkwrapper"
"github.com/aws/amazon-vpc-cni-k8s/pkg/networkutils"
"github.com/aws/amazon-vpc-cni-k8s/pkg/nswrapper"
)
const (
// ip rules priority and leave 512 gap for future
toContainerRulePriority = 512
// 1024 is reserved for (ip rule not to <vpc's subnet> table main)
fromContainerRulePriority = 1536
// main routing table number
mainRouteTable = unix.RT_TABLE_MAIN
// MTU of veth - ENI MTU defined in pkg/networkutils/network.go
ethernetMTU = 9001
)
// NetworkAPIs defines network API calls
type NetworkAPIs interface {
SetupNS(hostVethName string, contVethName string, netnsPath string, addr *net.IPNet, table int, vpcCIDRs []string, useExternalSNAT bool) error
TeardownNS(addr *net.IPNet, table int) error
}
type linuxNetwork struct {
netLink netlinkwrapper.NetLink
ns nswrapper.NS
}
// New creates linuxNetwork object
func New() NetworkAPIs {
return &linuxNetwork{
netLink: netlinkwrapper.NewNetLink(),
ns: nswrapper.NewNS(),
}
}
// createVethPairContext wraps the parameters and the method to create the
// veth pair to attach the container namespace
type createVethPairContext struct {
contVethName string
hostVethName string
addr *net.IPNet
netLink netlinkwrapper.NetLink
ip ipwrapper.IP
}
func newCreateVethPairContext(contVethName string, hostVethName string, addr *net.IPNet) *createVethPairContext {
return &createVethPairContext{
contVethName: contVethName,
hostVethName: hostVethName,
addr: addr,
netLink: netlinkwrapper.NewNetLink(),
ip: ipwrapper.NewIP(),
}
}
// run defines the closure to execute within the container's namespace to
// create the veth pair
func (createVethContext *createVethPairContext) run(hostNS ns.NetNS) error {
veth := &netlink.Veth{
LinkAttrs: netlink.LinkAttrs{
Name: createVethContext.contVethName,
Flags: net.FlagUp,
MTU: ethernetMTU,
},
PeerName: createVethContext.hostVethName,
}
if err := createVethContext.netLink.LinkAdd(veth); err != nil {
return err
}
hostVeth, err := createVethContext.netLink.LinkByName(createVethContext.hostVethName)
if err != nil {
return errors.Wrapf(err, "setup NS network: failed to find link %q", createVethContext.hostVethName)
}
// Explicitly set the veth to UP state, because netlink doesn't always do that on all the platforms with net.FlagUp.
// veth won't get a link local address unless it's set to UP state.
if err = createVethContext.netLink.LinkSetUp(hostVeth); err != nil {
return errors.Wrapf(err, "setup NS network: failed to set link %q up", createVethContext.hostVethName)
}
contVeth, err := createVethContext.netLink.LinkByName(createVethContext.contVethName)
if err != nil {
return errors.Wrapf(err, "setup NS network: failed to find link %q", createVethContext.contVethName)
}
// Explicitly set the veth to UP state, because netlink doesn't always do that on all the platforms with net.FlagUp.
// veth won't get a link local address unless it's set to UP state.
if err = createVethContext.netLink.LinkSetUp(contVeth); err != nil {
return errors.Wrapf(err, "setup NS network: failed to set link %q up", createVethContext.contVethName)
}
// Add a connected route to a dummy next hop (169.254.1.1)
// # ip route show
// default via 169.254.1.1 dev eth0
// 169.254.1.1 dev eth0
gw := net.IPv4(169, 254, 1, 1)
gwNet := &net.IPNet{IP: gw, Mask: net.CIDRMask(32, 32)}
if err = createVethContext.netLink.RouteReplace(&netlink.Route{
LinkIndex: contVeth.Attrs().Index,
Scope: netlink.SCOPE_LINK,
Dst: gwNet}); err != nil {
return errors.Wrap(err, "setup NS network: failed to add default gateway")
}
// Add a default route via dummy next hop(169.254.1.1). Then all outgoing traffic will be routed by this
// default route via dummy next hop (169.254.1.1).
if err = createVethContext.ip.AddDefaultRoute(gwNet.IP, contVeth); err != nil {
return errors.Wrap(err, "setup NS network: failed to add default route")
}
if err = createVethContext.netLink.AddrAdd(contVeth, &netlink.Addr{IPNet: createVethContext.addr}); err != nil {
return errors.Wrapf(err, "setup NS network: failed to add IP addr to %q", createVethContext.contVethName)
}
// add static ARP entry for default gateway
// we are using routed mode on the host and container need this static ARP entry to resolve its default gateway.
neigh := &netlink.Neigh{
LinkIndex: contVeth.Attrs().Index,
State: netlink.NUD_PERMANENT,
IP: gwNet.IP,
HardwareAddr: hostVeth.Attrs().HardwareAddr,
}
if err = createVethContext.netLink.NeighAdd(neigh); err != nil {
return errors.Wrap(err, "setup NS network: failed to add static ARP")
}
// Now that the everything has been successfully set up in the container, move the "host" end of the
// veth into the host namespace.
if err = createVethContext.netLink.LinkSetNsFd(hostVeth, int(hostNS.Fd())); err != nil {
return errors.Wrap(err, "setup NS network: failed to move veth to host netns")
}
return nil
}
// SetupNS wires up linux networking for a pod's network
func (os *linuxNetwork) SetupNS(hostVethName string, contVethName string, netnsPath string, addr *net.IPNet, table int, vpcCIDRs []string, useExternalSNAT bool) error {
log.Debugf("SetupNS: hostVethName=%s,contVethName=%s, netnsPath=%s table=%d\n", hostVethName, contVethName, netnsPath, table)
return setupNS(hostVethName, contVethName, netnsPath, addr, table, vpcCIDRs, useExternalSNAT, os.netLink, os.ns)
}
func setupNS(hostVethName string, contVethName string, netnsPath string, addr *net.IPNet, table int, vpcCIDRs []string, useExternalSNAT bool,
netLink netlinkwrapper.NetLink, ns nswrapper.NS) error {
// Clean up if hostVeth exists.
if oldHostVeth, err := netLink.LinkByName(hostVethName); err == nil {
if err = netLink.LinkDel(oldHostVeth); err != nil {
return errors.Wrapf(err, "setupNS network: failed to delete old hostVeth %q", hostVethName)
}
log.Debugf("Clean up old hostVeth: %v\n", hostVethName)
}
createVethContext := newCreateVethPairContext(contVethName, hostVethName, addr)
if err := ns.WithNetNSPath(netnsPath, createVethContext.run); err != nil {
log.Errorf("Failed to setup NS network %v", err)
return errors.Wrap(err, "setupNS network: failed to setup NS network")
}
hostVeth, err := netLink.LinkByName(hostVethName)
if err != nil {
return errors.Wrapf(err, "setupNS network: failed to find link %q", hostVethName)
}
// Explicitly set the veth to UP state, because netlink doesn't always do that on all the platforms with net.FlagUp.
// veth won't get a link local address unless it's set to UP state.
if err = netLink.LinkSetUp(hostVeth); err != nil {
return errors.Wrapf(err, "setupNS network: failed to set link %q up", hostVethName)
}
log.Debugf("Setup host route outgoing hostVeth, LinkIndex %d\n", hostVeth.Attrs().Index)
addrHostAddr := &net.IPNet{
IP: addr.IP,
Mask: net.CIDRMask(32, 32)}
// Add host route
route := netlink.Route{
LinkIndex: hostVeth.Attrs().Index,
Scope: netlink.SCOPE_LINK,
Dst: addrHostAddr}
// Add or replace route
if err := netLink.RouteReplace(&route); err != nil {
return errors.Wrapf(err, "setupNS: unable to add or replace route entry for %s", route.Dst.IP.String())
}
log.Debugf("Successfully set host route to be %s/0", route.Dst.IP.String())
toContainerFlag := true
err = addContainerRule(netLink, toContainerFlag, addr, toContainerRulePriority, mainRouteTable)
if err != nil {
log.Errorf("Failed to add toContainer rule for %s err=%v, ", addr.String(), err)
return errors.Wrap(err, "setupNS network: failed to add toContainer")
}
log.Infof("Added toContainer rule for %s", addr.String())
// add from-pod rule, only need it when it is not primary ENI
if table > 0 {
if useExternalSNAT {
// add rule: 1536: from <podIP> use table <table>
toContainerFlag = false
err = addContainerRule(netLink, toContainerFlag, addr, fromContainerRulePriority, table)
if err != nil {
log.Errorf("Failed to add fromContainer rule for %s err: %v", addr.String(), err)
return errors.Wrap(err, "add NS network: failed to add fromContainer rule")
}
log.Infof("Added rule priority %d from %s table %d", fromContainerRulePriority, addr.String(), table)
} else {
// add rule: 1536: list of from <podIP> to <vpcCIDR> use table <table>
for _, cidr := range vpcCIDRs {
podRule := netLink.NewRule()
_, podRule.Dst, _ = net.ParseCIDR(cidr)
podRule.Src = addr
podRule.Table = table
podRule.Priority = fromContainerRulePriority
err = netLink.RuleAdd(podRule)
if isRuleExistsError(err) {
log.Warn("Rule already exists [%v]", podRule)
} else {
if err != nil {
log.Errorf("Failed to add pod IP rule [%v]: %v", podRule, err)
return errors.Wrapf(err, "setupNS: failed to add pod rule [%v]", podRule)
}
}
var toDst string
if podRule.Dst != nil {
toDst = podRule.Dst.String()
}
log.Infof("Successfully added pod rule[%v] to %s", podRule, toDst)
}
}
}
return nil
}
func addContainerRule(netLink netlinkwrapper.NetLink, isToContainer bool, addr *net.IPNet, priority int, table int) error {
containerRule := netLink.NewRule()
if isToContainer {
containerRule.Dst = addr
} else {
containerRule.Src = addr
}
containerRule.Table = table
containerRule.Priority = priority
err := netLink.RuleDel(containerRule)
if err != nil && !containsNoSuchRule(err) {
return errors.Wrapf(err, "addContainerRule: failed to delete old container rule for %s", addr.String())
}
err = netLink.RuleAdd(containerRule)
if err != nil {
return errors.Wrapf(err, "addContainerRule: failed to add container rule for %s", addr.String())
}
return nil
}
// TeardownPodNetwork cleanup ip rules
func (os *linuxNetwork) TeardownNS(addr *net.IPNet, table int) error {
log.Debugf("TeardownNS: addr %s, table %d", addr.String(), table)
return tearDownNS(addr, table, os.netLink)
}
func tearDownNS(addr *net.IPNet, table int, netLink netlinkwrapper.NetLink) error {
// remove to-pod rule
toContainerRule := netLink.NewRule()
toContainerRule.Dst = addr
toContainerRule.Priority = toContainerRulePriority
err := netLink.RuleDel(toContainerRule)
if err != nil {
log.Errorf("Failed to delete toContainer rule for %s err %v", addr.String(), err)
} else {
log.Infof("Delete toContainer rule for %s ", addr.String())
}
if table > 0 {
// remove from-pod rule only for non main table
err := deleteRuleListBySrc(*addr)
if err != nil {
log.Errorf("Failed to delete fromContainer for %s %v", addr.String(), err)
return errors.Wrapf(err, "delete NS network: failed to delete fromContainer rule for %s", addr.String())
}
log.Infof("Delete fromContainer rule for %s in table %d", addr.String(), table)
}
addrHostAddr := &net.IPNet{
IP: addr.IP,
Mask: net.CIDRMask(32, 32)}
// cleanup host route:
if err = netLink.RouteDel(&netlink.Route{
Scope: netlink.SCOPE_LINK,
Dst: addrHostAddr}); err != nil {
log.Errorf("delete NS network: failed to delete host route for %s, %v", addr.String(), err)
}
return nil
}
func deleteRuleListBySrc(src net.IPNet) error {
networkClient := networkutils.New()
return networkClient.DeleteRuleListBySrc(src)
}
func containsNoSuchRule(err error) bool {
if errno, ok := err.(syscall.Errno); ok {
return errno == syscall.ENOENT
}
return false
}
func isRuleExistsError(err error) bool {
if errno, ok := err.(syscall.Errno); ok {
return errno == syscall.EEXIST
}
return false
}