-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
netlink.go
320 lines (276 loc) · 9.15 KB
/
netlink.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
// SPDX-License-Identifier: Apache-2.0
// Copyright 2017-2018 Authors of Cilium
package loader
import (
"context"
"fmt"
"net"
"github.com/cilium/cilium/pkg/bpf"
"github.com/cilium/cilium/pkg/command/exec"
"github.com/cilium/cilium/pkg/defaults"
"github.com/cilium/cilium/pkg/logging/logfields"
"github.com/cilium/cilium/pkg/mac"
"github.com/cilium/cilium/pkg/option"
"github.com/cilium/cilium/pkg/sysctl"
"github.com/sirupsen/logrus"
"github.com/vishvananda/netlink"
)
type baseDeviceMode string
const (
ipvlanMode = baseDeviceMode("ipvlan")
directMode = baseDeviceMode("direct")
tunnelMode = baseDeviceMode("tunnel")
libbpfFixupMsg = "struct bpf_elf_map fixup performed due to size mismatch!"
)
func replaceQdisc(ifName string) error {
link, err := netlink.LinkByName(ifName)
if err != nil {
return err
}
attrs := netlink.QdiscAttrs{
LinkIndex: link.Attrs().Index,
Handle: netlink.MakeHandle(0xffff, 0),
Parent: netlink.HANDLE_CLSACT,
}
qdisc := &netlink.GenericQdisc{
QdiscAttrs: attrs,
QdiscType: "clsact",
}
if err = netlink.QdiscReplace(qdisc); err != nil {
return fmt.Errorf("netlink: Replacing qdisc for %s failed: %s", ifName, err)
} else {
log.Debugf("netlink: Replacing qdisc for %s succeeded", ifName)
}
return nil
}
// replaceDatapath replaces the qdisc and BPF program for an endpoint or XDP program.
//
// When successful, returns a finalizer to allow the map cleanup operation to be
// deferred by the caller. On error, any maps pending migration are immediately
// re-pinned to their original paths and a finalizer is not returned.
//
// When replacing multiple programs from the same ELF in a loop, the finalizer
// should only be run when all the interface's programs have been replaced
// since they might share one or more tail call maps.
//
// For example, this is the case with from-netdev and to-netdev. If eth0:to-netdev
// gets its program and maps replaced and unpinned, its eth0:from-netdev counterpart
// will miss tail calls (and drop packets) until it has been replaced as well.
func replaceDatapath(ctx context.Context, ifName, objPath, progSec, progDirection string, xdp bool, xdpMode string) (func(), error) {
var (
loaderProg string
args []string
)
if !xdp {
if err := replaceQdisc(ifName); err != nil {
return nil, fmt.Errorf("Failed to replace Qdisc for %s: %s", ifName, err)
}
}
// Temporarily rename bpffs pins of maps whose definitions have changed in
// a new version of a datapath ELF.
if err := bpf.StartBPFFSMigration(bpf.MapPrefixPath(), objPath); err != nil {
return nil, fmt.Errorf("Failed to start bpffs map migration: %w", err)
}
// FIXME: replace exec with native call
if xdp {
loaderProg = "ip"
args = []string{"-force", "link", "set", "dev", ifName, xdpMode,
"obj", objPath, "sec", progSec}
} else {
loaderProg = "tc"
args = []string{"filter", "replace", "dev", ifName, progDirection,
"prio", "1", "handle", "1", "bpf", "da", "obj", objPath,
"sec", progSec,
}
}
// If the iproute2 call below is successful, any 'pending' map pins will be removed.
// If not, any pending maps will be re-pinned back to their initial paths.
cmd := exec.CommandContext(ctx, loaderProg, args...).WithFilters(libbpfFixupMsg)
if _, err := cmd.CombinedOutput(log, true); err != nil {
// Program/object replacement unsuccessful, revert bpffs migration.
if err := bpf.FinalizeBPFFSMigration(bpf.MapPrefixPath(), objPath, true); err != nil {
return nil, fmt.Errorf("Failed to revert bpffs map migration: %w", err)
}
return nil, fmt.Errorf("Failed to load prog with %s: %w", loaderProg, err)
}
finalize := func() {
l := log.WithField("device", ifName).WithField("objPath", objPath)
l.Debug("Finalizing bpffs map migration")
if err := bpf.FinalizeBPFFSMigration(bpf.MapPrefixPath(), objPath, false); err != nil {
l.WithError(err).Error("Could not finalize bpffs map migration")
}
}
return finalize, nil
}
// graftDatapath replaces obj in tail call map
func graftDatapath(ctx context.Context, mapPath, objPath, progSec string) error {
if err := bpf.StartBPFFSMigration(bpf.MapPrefixPath(), objPath); err != nil {
return fmt.Errorf("Failed to start bpffs map migration: %w", err)
}
var revert bool
defer func() {
if err := bpf.FinalizeBPFFSMigration(bpf.MapPrefixPath(), objPath, revert); err != nil {
log.WithError(err).WithFields(logrus.Fields{logfields.BPFMapPath: mapPath, "objPath": objPath}).
Error("Could not finalize bpffs map migration")
}
}()
// FIXME: replace exec with native call
// FIXME: only key 0 right now, could be made more flexible
args := []string{"exec", "bpf", "graft", mapPath, "key", "0",
"obj", objPath, "sec", progSec,
}
cmd := exec.CommandContext(ctx, "tc", args...).WithFilters(libbpfFixupMsg)
if _, err := cmd.CombinedOutput(log, true); err != nil {
revert = true
return fmt.Errorf("Failed to graft tc object: %s", err)
}
return nil
}
// RemoveTCFilters removes all tc filters from the given interface.
// Direction is passed as netlink.HANDLE_MIN_{INGRESS,EGRESS} via tcDir.
func RemoveTCFilters(ifName string, tcDir uint32) error {
link, err := netlink.LinkByName(ifName)
if err != nil {
return err
}
filters, err := netlink.FilterList(link, tcDir)
if err != nil {
return err
}
for _, f := range filters {
if err := netlink.FilterDel(f); err != nil {
return err
}
}
return nil
}
func setupDev(link netlink.Link) error {
ifName := link.Attrs().Name
if err := netlink.LinkSetUp(link); err != nil {
log.WithError(err).WithField("device", ifName).Warn("Could not set up the link")
return err
}
sysSettings := make([]sysctl.Setting, 0, 5)
if option.Config.EnableIPv6 {
sysSettings = append(sysSettings, sysctl.Setting{
Name: fmt.Sprintf("net.ipv6.conf.%s.forwarding", ifName), Val: "1", IgnoreErr: false})
}
if option.Config.EnableIPv4 {
sysSettings = append(sysSettings, []sysctl.Setting{
{Name: fmt.Sprintf("net.ipv4.conf.%s.forwarding", ifName), Val: "1", IgnoreErr: false},
{Name: fmt.Sprintf("net.ipv4.conf.%s.rp_filter", ifName), Val: "0", IgnoreErr: false},
{Name: fmt.Sprintf("net.ipv4.conf.%s.accept_local", ifName), Val: "1", IgnoreErr: false},
{Name: fmt.Sprintf("net.ipv4.conf.%s.send_redirects", ifName), Val: "0", IgnoreErr: false},
}...)
}
if err := sysctl.ApplySettings(sysSettings); err != nil {
return err
}
return nil
}
func setupVethPair(name, peerName string) error {
// Create the veth pair if it doesn't exist.
if _, err := netlink.LinkByName(name); err != nil {
hostMac, err := mac.GenerateRandMAC()
if err != nil {
return err
}
peerMac, err := mac.GenerateRandMAC()
if err != nil {
return err
}
veth := &netlink.Veth{
LinkAttrs: netlink.LinkAttrs{
Name: name,
HardwareAddr: net.HardwareAddr(hostMac),
TxQLen: 1000,
},
PeerName: peerName,
PeerHardwareAddr: net.HardwareAddr(peerMac),
}
if err := netlink.LinkAdd(veth); err != nil {
return err
}
}
veth, err := netlink.LinkByName(name)
if err != nil {
return err
}
if err := setupDev(veth); err != nil {
return err
}
peer, err := netlink.LinkByName(peerName)
if err != nil {
return err
}
if err := setupDev(peer); err != nil {
return err
}
return nil
}
func setupIpvlan(name string, nativeLink netlink.Link) (*netlink.IPVlan, error) {
hostLink, err := netlink.LinkByName(name)
if err == nil {
// Ignore the error.
netlink.LinkDel(hostLink)
}
ipvlan := &netlink.IPVlan{
LinkAttrs: netlink.LinkAttrs{
Name: name,
ParentIndex: nativeLink.Attrs().Index,
TxQLen: 1000,
},
Mode: netlink.IPVLAN_MODE_L3,
}
if err := netlink.LinkAdd(ipvlan); err != nil {
return nil, err
}
if err := setupDev(ipvlan); err != nil {
return nil, err
}
return ipvlan, nil
}
// setupBaseDevice decides which and what kind of interfaces should be set up as
// the first step of datapath initialization, then performs the setup (and
// creation, if needed) of those interfaces. It returns two links and an error.
// By default, it sets up the veth pair - cilium_host and cilium_net.
// In ipvlan mode, it creates the cilium_host ipvlan with the native device as a
// parent.
func setupBaseDevice(nativeDevs []netlink.Link, mode baseDeviceMode, mtu int) (netlink.Link, netlink.Link, error) {
switch mode {
case ipvlanMode:
ipvlan, err := setupIpvlan(defaults.HostDevice, nativeDevs[0])
if err != nil {
return nil, nil, err
}
if err := netlink.LinkSetMTU(ipvlan, mtu); err != nil {
return nil, nil, err
}
return ipvlan, ipvlan, nil
default:
if err := setupVethPair(defaults.HostDevice, defaults.SecondHostDevice); err != nil {
return nil, nil, err
}
linkHost, err := netlink.LinkByName(defaults.HostDevice)
if err != nil {
return nil, nil, err
}
linkNet, err := netlink.LinkByName(defaults.SecondHostDevice)
if err != nil {
return nil, nil, err
}
if err := netlink.LinkSetARPOff(linkHost); err != nil {
return nil, nil, err
}
if err := netlink.LinkSetARPOff(linkNet); err != nil {
return nil, nil, err
}
if err := netlink.LinkSetMTU(linkHost, mtu); err != nil {
return nil, nil, err
}
if err := netlink.LinkSetMTU(linkNet, mtu); err != nil {
return nil, nil, err
}
return linkHost, linkNet, nil
}
}