/
link.go
461 lines (369 loc) · 10.5 KB
/
link.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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
package ip
import (
"bufio"
"encoding/json"
"fmt"
"io"
"net"
"os/exec"
"regexp"
"strconv"
"github.com/lxc/lxd/shared"
)
// Link represents base arguments for link device.
type Link struct {
Name string
MTU uint32
Parent string
Address net.HardwareAddr
TXQueueLength uint32
AllMutlicast bool
Master string
Up bool
}
// args generate common arguments for the virtual link.
func (l *Link) args() []string {
var result []string
if l.Name != "" {
result = append(result, "name", l.Name)
}
if l.Parent != "" {
result = append(result, "link", l.Parent)
}
if l.MTU > 0 {
result = append(result, "mtu", fmt.Sprintf("%d", l.MTU))
}
if l.Address != nil {
result = append(result, "address", l.Address.String())
}
if l.TXQueueLength > 0 {
result = append(result, "txqueuelen", fmt.Sprintf("%d", l.TXQueueLength))
}
if l.AllMutlicast {
result = append(result, "allmulticast", "on")
}
if l.Master != "" {
result = append(result, "master", l.Master)
}
if l.Up {
result = append(result, "up")
}
return result
}
// add adds new virtual link.
func (l *Link) add(linkType string, additionalArgs []string) error {
cmd := append([]string{"link", "add"}, l.args()...)
cmd = append(cmd, "type", linkType)
cmd = append(cmd, additionalArgs...)
_, err := shared.RunCommand("ip", cmd...)
if err != nil {
return fmt.Errorf("Failed adding link: %w", err)
}
return nil
}
// SetUp enables the link device.
func (l *Link) SetUp() error {
_, err := shared.RunCommand("ip", "link", "set", "dev", l.Name, "up")
if err != nil {
return err
}
return nil
}
// SetDown disables the link device.
func (l *Link) SetDown() error {
_, err := shared.RunCommand("ip", "link", "set", "dev", l.Name, "down")
if err != nil {
return err
}
return nil
}
// SetMTU sets the MTU of the link device.
func (l *Link) SetMTU(mtu uint32) error {
_, err := shared.RunCommand("ip", "link", "set", "dev", l.Name, "mtu", fmt.Sprintf("%d", mtu))
if err != nil {
return err
}
return nil
}
// SetTXQueueLength sets the txqueuelen of the link device.
func (l *Link) SetTXQueueLength(queueLength uint32) error {
_, err := shared.RunCommand("ip", "link", "set", "dev", l.Name, "txqueuelen", fmt.Sprintf("%d", queueLength))
if err != nil {
return err
}
return nil
}
// SetAddress sets the address of the link device.
func (l *Link) SetAddress(address net.HardwareAddr) error {
_, err := shared.RunCommand("ip", "link", "set", "dev", l.Name, "address", address.String())
if err != nil {
return err
}
return nil
}
// SetAllMulticast when enabled instructs network driver to retrieve all multicast packets from the network to the
// kernel for further processing.
func (l *Link) SetAllMulticast(enabled bool) error {
mode := "off"
if enabled {
mode = "on"
}
_, err := shared.RunCommand("ip", "link", "set", "dev", l.Name, "allmulticast", mode)
return err
}
// SetMaster sets the master of the link device.
func (l *Link) SetMaster(master string) error {
_, err := shared.RunCommand("ip", "link", "set", "dev", l.Name, "master", master)
if err != nil {
return err
}
return nil
}
// SetNoMaster removes the master of the link device.
func (l *Link) SetNoMaster() error {
_, err := shared.RunCommand("ip", "link", "set", "dev", l.Name, "nomaster")
if err != nil {
return err
}
return nil
}
// SetName sets the name of the link device.
func (l *Link) SetName(newName string) error {
_, err := shared.RunCommand("ip", "link", "set", "dev", l.Name, "name", newName)
if err != nil {
return err
}
return nil
}
// SetNetns moves the link to the selected network namespace.
func (l *Link) SetNetns(netns string) error {
_, err := shared.RunCommand("ip", "link", "set", "dev", l.Name, "netns", netns)
if err != nil {
return err
}
return nil
}
// SetVfAddress changes the address for the specified vf.
func (l *Link) SetVfAddress(vf string, address string) error {
_, err := shared.TryRunCommand("ip", "link", "set", "dev", l.Name, "vf", vf, "mac", address)
if err != nil {
return err
}
return nil
}
// SetVfVlan changes the assigned VLAN for the specified vf.
func (l *Link) SetVfVlan(vf string, vlan string) error {
_, err := shared.TryRunCommand("ip", "link", "set", "dev", l.Name, "vf", vf, "vlan", vlan)
if err != nil {
return err
}
return nil
}
// SetVfSpoofchk turns packet spoof checking on or off for the specified VF.
func (l *Link) SetVfSpoofchk(vf string, mode string) error {
_, err := shared.TryRunCommand("ip", "link", "set", "dev", l.Name, "vf", vf, "spoofchk", mode)
if err != nil {
return err
}
return nil
}
// VirtFuncInfo holds information about vf.
type VirtFuncInfo struct {
VF int `json:"vf"`
Address string `json:"address"`
MAC string `json:"mac"` // Deprecated
VLANs []map[string]int `json:"vlan_list"`
SpoofCheck bool `json:"spoofchk"`
}
// GetVFInfo returns info about virtual function.
func (l *Link) GetVFInfo(vfID int) (VirtFuncInfo, error) {
vf := VirtFuncInfo{}
vfNotFoundErr := fmt.Errorf("no matching virtual function found")
ipPath, err := exec.LookPath("ip")
if err != nil {
return vf, fmt.Errorf("ip command not found")
}
// Function to get VF info using regex matching, for older versions of ip tool. Less reliable.
vfFindByRegex := func(devName string, vfID int) (VirtFuncInfo, error) {
cmd := exec.Command(ipPath, "link", "show", devName)
stdout, err := cmd.StdoutPipe()
if err != nil {
return vf, err
}
defer func() { _ = stdout.Close() }()
err = cmd.Start()
if err != nil {
return vf, err
}
defer func() { _ = cmd.Wait() }()
// Try and match: "vf 1 MAC 00:00:00:00:00:00, vlan 4095, spoof checking off"
reVlan, err := regexp.Compile(fmt.Sprintf(`vf %d MAC ((?:[[:xdigit:]]{2}:){5}[[:xdigit:]]{2}).*, vlan (\d+), spoof checking (\w+)`, vfID))
if err != nil {
return vf, err
}
// IP link command doesn't show the vlan property if its set to 0, so we need to detect that.
// Try and match: "vf 1 MAC 00:00:00:00:00:00, spoof checking off"
reNoVlan, err := regexp.Compile(fmt.Sprintf(`vf %d MAC ((?:[[:xdigit:]]{2}:){5}[[:xdigit:]]{2}).*, spoof checking (\w+)`, vfID))
if err != nil {
return vf, err
}
scanner := bufio.NewScanner(stdout)
for scanner.Scan() {
// First try and find VF and read its properties with VLAN activated.
res := reVlan.FindStringSubmatch(scanner.Text())
if len(res) == 4 {
vlan, err := strconv.Atoi(res[2])
if err != nil {
return vf, err
}
vf.Address = res[1]
vf.VLANs = append(vf.VLANs, map[string]int{"vlan": vlan})
vf.SpoofCheck = shared.IsTrue(res[3])
return vf, err
}
// Next try and find VF and read its properties with VLAN missing.
res = reNoVlan.FindStringSubmatch(scanner.Text())
if len(res) == 3 {
vf.Address = res[1]
// Missing VLAN ID means 0 when resetting later.
vf.VLANs = append(vf.VLANs, map[string]int{"vlan": 0})
vf.SpoofCheck = shared.IsTrue(res[2])
return vf, err
}
}
err = scanner.Err()
if err != nil {
return vf, err
}
return vf, vfNotFoundErr
}
// First try using the JSON output format as is more reliable to parse.
cmd := exec.Command(ipPath, "-j", "link", "show", l.Name)
stdout, err := cmd.StdoutPipe()
if err != nil {
return vf, err
}
defer func() { _ = stdout.Close() }()
err = cmd.Start()
if err != nil {
return vf, err
}
defer func() { _ = cmd.Wait() }()
// Temporary struct to decode ip output into.
var ifInfo []struct {
VFList []VirtFuncInfo `json:"vfinfo_list"`
}
// Decode JSON output.
dec := json.NewDecoder(stdout)
err = dec.Decode(&ifInfo)
if err != nil && err != io.EOF {
return vf, err
}
err = cmd.Wait()
if err != nil {
// If JSON command fails, fallback to using regex match mode for older versions of ip tool.
// This does not support the newer VF "link/ether" output prefix.
return vfFindByRegex(l.Name, vfID)
}
if len(ifInfo) == 0 {
return vf, vfNotFoundErr
}
// Search VFs returned for match.
found := false
for _, vfInfo := range ifInfo[0].VFList {
if vfInfo.VF == vfID {
vf = vfInfo // Found a match.
found = true
}
}
if !found {
return vf, vfNotFoundErr
}
// Always populate VLANs slice if not already populated. Missing VLAN ID means 0 when resetting later.
if len(vf.VLANs) == 0 {
vf.VLANs = append(vf.VLANs, map[string]int{"vlan": 0})
}
// Ensure empty VLAN entry is consistently populated.
if _, found = vf.VLANs[0]["vlan"]; !found {
vf.VLANs[0]["vlan"] = 0
}
// If ip tool has provided old mac field, copy into newer address field.
if vf.MAC != "" && vf.Address == "" {
vf.Address = vf.MAC
}
return vf, nil
}
// Change sets map for link device.
func (l *Link) Change(devType string, fanMap string) error {
_, err := shared.RunCommand("ip", "link", "change", "dev", l.Name, "type", devType, "fan-map", fanMap)
if err != nil {
return err
}
return nil
}
// Delete deletes the link device.
func (l *Link) Delete() error {
_, err := shared.RunCommand("ip", "link", "delete", "dev", l.Name)
if err != nil {
return err
}
return nil
}
// BridgeVLANAdd adds a new vlan filter entry.
func (l *Link) BridgeVLANAdd(vid string, pvid bool, untagged bool, self bool) error {
cmd := []string{"vlan", "add", "dev", l.Name, "vid", vid}
if pvid {
cmd = append(cmd, "pvid")
}
if untagged {
cmd = append(cmd, "untagged")
}
if self {
cmd = append(cmd, "self")
} else {
cmd = append(cmd, "master")
}
_, err := shared.RunCommand("bridge", cmd...)
if err != nil {
return err
}
return nil
}
// BridgeVLANDelete removes an existing vlan filter entry.
func (l *Link) BridgeVLANDelete(vid string, self bool) error {
cmd := []string{"vlan", "del", "dev", l.Name, "vid", vid}
if self {
cmd = append(cmd, "self")
} else {
cmd = append(cmd, "master")
}
_, err := shared.RunCommand("bridge", cmd...)
if err != nil {
return err
}
return nil
}
// BridgeLinkSetIsolated sets bridge 'isolated' attribute on a port.
func (l *Link) BridgeLinkSetIsolated(isolated bool) error {
isolatedState := "on"
if !isolated {
isolatedState = "off"
}
_, err := shared.RunCommand("bridge", "link", "set", "dev", l.Name, "isolated", isolatedState)
if err != nil {
return err
}
return nil
}
// BridgeLinkSetHairpin sets bridge 'hairpin' attribute on a port.
func (l *Link) BridgeLinkSetHairpin(hairpin bool) error {
hairpinState := "on"
if !hairpin {
hairpinState = "off"
}
_, err := shared.RunCommand("bridge", "link", "set", "dev", l.Name, "hairpin", hairpinState)
if err != nil {
return err
}
return nil
}