/
device_utils_network.go
822 lines (684 loc) · 24 KB
/
device_utils_network.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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
package device
import (
"bufio"
"crypto/rand"
"encoding/hex"
"fmt"
"io/ioutil"
"net"
"os"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/pkg/errors"
deviceConfig "github.com/lxc/lxd/lxd/device/config"
"github.com/lxc/lxd/lxd/instance"
"github.com/lxc/lxd/lxd/instance/instancetype"
"github.com/lxc/lxd/lxd/network"
"github.com/lxc/lxd/lxd/revert"
"github.com/lxc/lxd/lxd/state"
"github.com/lxc/lxd/lxd/util"
"github.com/lxc/lxd/shared"
"github.com/lxc/lxd/shared/logger"
"github.com/lxc/lxd/shared/units"
)
// Instances can be started in parallel, so lock the creation of VLANs.
var networkCreateSharedDeviceLock sync.Mutex
// NetworkSetDevMTU sets the MTU setting for a named network device if different from current.
func NetworkSetDevMTU(devName string, mtu uint64) error {
curMTU, err := network.GetDevMTU(devName)
if err != nil {
return err
}
// Only try and change the MTU if the requested mac is different to current one.
if curMTU != mtu {
_, err := shared.RunCommand("ip", "link", "set", "dev", devName, "mtu", fmt.Sprintf("%d", mtu))
if err != nil {
return err
}
}
return nil
}
// NetworkGetDevMAC retrieves the current MAC setting for a named network device.
func NetworkGetDevMAC(devName string) (string, error) {
content, err := ioutil.ReadFile(fmt.Sprintf("/sys/class/net/%s/address", devName))
if err != nil {
return "", err
}
return strings.TrimSpace(fmt.Sprintf("%s", content)), nil
}
// NetworkSetDevMAC sets the MAC setting for a named network device if different from current.
func NetworkSetDevMAC(devName string, mac string) error {
curMac, err := NetworkGetDevMAC(devName)
if err != nil {
return err
}
// Only try and change the MAC if the requested mac is different to current one.
if curMac != mac {
_, err := shared.RunCommand("ip", "link", "set", "dev", devName, "address", mac)
if err != nil {
return err
}
}
return nil
}
// NetworkRemoveInterface removes a network interface by name.
func NetworkRemoveInterface(nic string) error {
_, err := shared.RunCommand("ip", "link", "del", "dev", nic)
return err
}
// networkRemoveInterfaceIfNeeded removes a network interface by name but only if no other instance is using it.
func networkRemoveInterfaceIfNeeded(state *state.State, nic string, current instance.Instance, parent string, vlanID string) error {
// Check if it's used by another instance.
instances, err := instance.LoadNodeAll(state, instancetype.Any)
if err != nil {
return err
}
for _, inst := range instances {
if inst.Name() == current.Name() && inst.Project() == current.Project() {
continue
}
for devName, dev := range inst.ExpandedDevices() {
if dev["type"] != "nic" || dev["vlan"] != vlanID || dev["parent"] != parent {
continue
}
// Check if another running instance created the device, if so, don't touch it.
if shared.IsTrue(inst.ExpandedConfig()[fmt.Sprintf("volatile.%s.last_state.created", devName)]) {
return nil
}
}
}
return NetworkRemoveInterface(nic)
}
// networkCreateVlanDeviceIfNeeded creates a VLAN device if doesn't already exist.
func networkCreateVlanDeviceIfNeeded(state *state.State, parent string, vlanDevice string, vlanID string) (string, error) {
if vlanID != "" {
if !shared.PathExists(fmt.Sprintf("/sys/class/net/%s", vlanDevice)) {
// Bring the parent interface up so we can add a vlan to it.
_, err := shared.RunCommand("ip", "link", "set", "dev", parent, "up")
if err != nil {
return "", fmt.Errorf("Failed to bring up parent %s: %v", parent, err)
}
// Add VLAN interface on top of parent.
_, err = shared.RunCommand("ip", "link", "add", "link", parent, "name", vlanDevice, "up", "type", "vlan", "id", vlanID)
if err != nil {
return "", err
}
// Attempt to disable IPv6 router advertisement acceptance.
util.SysctlSet(fmt.Sprintf("net/ipv6/conf/%s/accept_ra", vlanDevice), "0")
// We created a new vlan interface, return true.
return "created", nil
}
// Check if it was created for another running instance.
instances, err := instance.LoadNodeAll(state, instancetype.Any)
if err != nil {
return "", err
}
for _, inst := range instances {
for devName, dev := range inst.ExpandedDevices() {
if dev["type"] != "nic" || dev["vlan"] != vlanID || dev["parent"] != parent {
continue
}
// Check if another running instance created the device, if so, mark it as created.
if shared.IsTrue(inst.ExpandedConfig()[fmt.Sprintf("volatile.%s.last_state.created", devName)]) {
return "reused", nil
}
}
}
}
return "existing", nil
}
// networkSnapshotPhysicalNic records properties of the NIC to volatile so they can be restored later.
func networkSnapshotPhysicalNic(hostName string, volatile map[string]string) error {
// Store current MTU for restoration on detach.
mtu, err := network.GetDevMTU(hostName)
if err != nil {
return err
}
volatile["last_state.mtu"] = fmt.Sprintf("%d", mtu)
// Store current MAC for restoration on detach
mac, err := NetworkGetDevMAC(hostName)
if err != nil {
return err
}
volatile["last_state.hwaddr"] = mac
return nil
}
// networkRestorePhysicalNic restores NIC properties from volatile to what they were before it was attached.
func networkRestorePhysicalNic(hostName string, volatile map[string]string) error {
// If we created the "physical" device and then it should be removed.
if shared.IsTrue(volatile["last_state.created"]) {
return NetworkRemoveInterface(hostName)
}
// Bring the interface down, as this is sometimes needed to change settings on the nic.
_, err := shared.RunCommand("ip", "link", "set", "dev", hostName, "down")
if err != nil {
return fmt.Errorf("Failed to bring down \"%s\": %v", hostName, err)
}
// If MTU value is specified then there is an original MTU that needs restoring.
if volatile["last_state.mtu"] != "" {
mtuInt, err := strconv.ParseUint(volatile["last_state.mtu"], 10, 32)
if err != nil {
return fmt.Errorf("Failed to convert mtu for \"%s\" mtu \"%s\": %v", hostName, volatile["last_state.mtu"], err)
}
err = NetworkSetDevMTU(hostName, mtuInt)
if err != nil {
return fmt.Errorf("Failed to restore physical dev \"%s\" mtu to \"%d\": %v", hostName, mtuInt, err)
}
}
// If MAC value is specified then there is an original MAC that needs restoring.
if volatile["last_state.hwaddr"] != "" {
err := NetworkSetDevMAC(hostName, volatile["last_state.hwaddr"])
if err != nil {
return fmt.Errorf("Failed to restore physical dev \"%s\" mac to \"%s\": %v", hostName, volatile["last_state.hwaddr"], err)
}
}
return nil
}
// networkRandomDevName returns a random device name with prefix.
// If the random string combined with the prefix exceeds 13 characters then empty string is returned.
// This is to ensure we support buggy dhclient applications: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=858580
func networkRandomDevName(prefix string) string {
// Return a new random veth device name
randBytes := make([]byte, 4)
rand.Read(randBytes)
iface := prefix + hex.EncodeToString(randBytes)
if len(iface) > 13 {
return ""
}
return iface
}
// networkCreateVethPair creates and configures a veth pair. It will set the hwaddr and mtu settings
// in the supplied config to the newly created peer interface. If mtu is not specified, but parent
// is supplied in config, then the MTU of the new peer interface will inherit the parent MTU.
// Accepts the name of the host side interface as a parameter and returns the peer interface name.
func networkCreateVethPair(hostName string, m deviceConfig.Device) (string, error) {
peerName := networkRandomDevName("veth")
_, err := shared.RunCommand("ip", "link", "add", "dev", hostName, "type", "veth", "peer", "name", peerName)
if err != nil {
return "", fmt.Errorf("Failed to create the veth interfaces %s and %s: %v", hostName, peerName, err)
}
_, err = shared.RunCommand("ip", "link", "set", "dev", hostName, "up")
if err != nil {
NetworkRemoveInterface(hostName)
return "", fmt.Errorf("Failed to bring up the veth interface %s: %v", hostName, err)
}
// Set the MAC address on peer.
if m["hwaddr"] != "" {
_, err := shared.RunCommand("ip", "link", "set", "dev", peerName, "address", m["hwaddr"])
if err != nil {
NetworkRemoveInterface(peerName)
return "", fmt.Errorf("Failed to set the MAC address: %v", err)
}
}
// Set the MTU on peer. If not specified and has parent, will inherit MTU from parent.
if m["mtu"] != "" {
MTU, err := strconv.ParseUint(m["mtu"], 10, 32)
if err != nil {
return "", fmt.Errorf("Invalid MTU specified: %v", err)
}
err = NetworkSetDevMTU(peerName, MTU)
if err != nil {
NetworkRemoveInterface(peerName)
return "", fmt.Errorf("Failed to set the MTU: %v", err)
}
err = NetworkSetDevMTU(hostName, MTU)
if err != nil {
NetworkRemoveInterface(peerName)
return "", fmt.Errorf("Failed to set the MTU: %v", err)
}
} else if m["parent"] != "" {
parentMTU, err := network.GetDevMTU(m["parent"])
if err != nil {
return "", fmt.Errorf("Failed to get the parent MTU: %v", err)
}
err = NetworkSetDevMTU(peerName, parentMTU)
if err != nil {
NetworkRemoveInterface(peerName)
return "", fmt.Errorf("Failed to set the MTU: %v", err)
}
err = NetworkSetDevMTU(hostName, parentMTU)
if err != nil {
NetworkRemoveInterface(peerName)
return "", fmt.Errorf("Failed to set the MTU: %v", err)
}
}
return peerName, nil
}
// networkCreateTap creates and configures a TAP device.
func networkCreateTap(hostName string, m deviceConfig.Device) error {
_, err := shared.RunCommand("ip", "tuntap", "add", "name", hostName, "mode", "tap")
if err != nil {
return errors.Wrapf(err, "Failed to create the tap interfaces %s", hostName)
}
revert := revert.New()
defer revert.Fail()
_, err = shared.RunCommand("ip", "link", "set", "dev", hostName, "up")
if err != nil {
return errors.Wrapf(err, "Failed to bring up the tap interface %s", hostName)
}
revert.Add(func() { NetworkRemoveInterface(hostName) })
// Set the MTU on peer. If not specified and has parent, will inherit MTU from parent.
if m["mtu"] != "" {
MTU, err := strconv.ParseUint(m["mtu"], 10, 32)
if err != nil {
return errors.Wrap(err, "Invalid MTU specified")
}
err = NetworkSetDevMTU(hostName, MTU)
if err != nil {
return errors.Wrap(err, "Failed to set the MTU")
}
} else if m["parent"] != "" {
parentMTU, err := network.GetDevMTU(m["parent"])
if err != nil {
return errors.Wrap(err, "Failed to get the parent MTU")
}
err = NetworkSetDevMTU(hostName, parentMTU)
if err != nil {
return errors.Wrap(err, "Failed to set the MTU")
}
}
revert.Success()
return nil
}
// networkSetupHostVethDevice configures a nic device's host side veth settings.
func networkSetupHostVethDevice(device deviceConfig.Device, oldDevice deviceConfig.Device, v map[string]string) error {
// If not configured, check if volatile data contains the most recently added host_name.
if device["host_name"] == "" {
device["host_name"] = v["host_name"]
}
// If not configured, check if volatile data contains the most recently added hwaddr.
if device["hwaddr"] == "" {
device["hwaddr"] = v["hwaddr"]
}
// Check whether host device resolution succeeded.
if device["host_name"] == "" {
return fmt.Errorf("Failed to find host side veth name for device \"%s\"", device["name"])
}
// Refresh tc limits.
err := networkSetVethLimits(device)
if err != nil {
return err
}
// If oldDevice provided, remove old routes if any remain.
if oldDevice != nil {
// If not configured, copy the volatile host_name into old device to support live updates.
if oldDevice["host_name"] == "" {
oldDevice["host_name"] = v["host_name"]
}
// If not configured, copy the volatile hwaddr into old device to support live updates.
if oldDevice["hwaddr"] == "" {
oldDevice["hwaddr"] = v["hwaddr"]
}
networkRemoveVethRoutes(oldDevice)
}
// Setup static routes to container.
err = networkSetVethRoutes(device)
if err != nil {
return err
}
return nil
}
// networkSetVethRoutes applies any static routes configured from the host to the container nic.
func networkSetVethRoutes(m deviceConfig.Device) error {
// Decide whether the route should point to the veth parent or the bridge parent.
routeDev := m["host_name"]
if m.NICType() == "bridged" {
routeDev = m["parent"]
}
if !shared.PathExists(fmt.Sprintf("/sys/class/net/%s", routeDev)) {
return fmt.Errorf("Unknown or missing host side route interface: %s", routeDev)
}
// Add additional IPv4 routes (using boot proto to avoid conflicts with network static routes)
if m["ipv4.routes"] != "" {
for _, route := range strings.Split(m["ipv4.routes"], ",") {
route = strings.TrimSpace(route)
_, err := shared.RunCommand("ip", "-4", "route", "add", route, "dev", routeDev, "proto", "boot")
if err != nil {
return err
}
}
}
// Add additional IPv6 routes (using boot proto to avoid conflicts with network static routes)
if m["ipv6.routes"] != "" {
for _, route := range strings.Split(m["ipv6.routes"], ",") {
route = strings.TrimSpace(route)
_, err := shared.RunCommand("ip", "-6", "route", "add", route, "dev", routeDev, "proto", "boot")
if err != nil {
return err
}
}
}
return nil
}
// networkRemoveVethRoutes removes any routes created for this device on the host that were first added
// with networkSetVethRoutes(). Expects to be passed the device config from the oldExpandedDevices.
func networkRemoveVethRoutes(m deviceConfig.Device) {
// Decide whether the route should point to the veth parent or the bridge parent
routeDev := m["host_name"]
if m.NICType() == "bridged" {
routeDev = m["parent"]
}
if m["ipv4.routes"] != "" || m["ipv6.routes"] != "" {
if routeDev == "" {
logger.Errorf("Failed to remove static routes as route dev isn't set")
return
}
if !shared.PathExists(fmt.Sprintf("/sys/class/net/%s", routeDev)) {
return //Routes will already be gone if device doesn't exist.
}
}
// Remove IPv4 routes
if m["ipv4.routes"] != "" {
for _, route := range strings.Split(m["ipv4.routes"], ",") {
route = strings.TrimSpace(route)
_, err := shared.RunCommand("ip", "-4", "route", "flush", route, "dev", routeDev, "proto", "boot")
if err != nil {
logger.Errorf("Failed to remove static route: %s to %s: %s", route, routeDev, err)
}
}
}
// Remove IPv6 routes
if m["ipv6.routes"] != "" {
for _, route := range strings.Split(m["ipv6.routes"], ",") {
route = strings.TrimSpace(route)
_, err := shared.RunCommand("ip", "-6", "route", "flush", route, "dev", routeDev, "proto", "boot")
if err != nil {
logger.Errorf("Failed to remove static route: %s to %s: %s", route, routeDev, err)
}
}
}
}
// networkSetVethLimits applies any network rate limits to the veth device specified in the config.
func networkSetVethLimits(m deviceConfig.Device) error {
var err error
veth := m["host_name"]
if !shared.PathExists(fmt.Sprintf("/sys/class/net/%s", veth)) {
return fmt.Errorf("Unknown or missing host side veth: %s", veth)
}
// Apply max limit
if m["limits.max"] != "" {
m["limits.ingress"] = m["limits.max"]
m["limits.egress"] = m["limits.max"]
}
// Parse the values
var ingressInt int64
if m["limits.ingress"] != "" {
ingressInt, err = units.ParseBitSizeString(m["limits.ingress"])
if err != nil {
return err
}
}
var egressInt int64
if m["limits.egress"] != "" {
egressInt, err = units.ParseBitSizeString(m["limits.egress"])
if err != nil {
return err
}
}
// Clean any existing entry
shared.RunCommand("tc", "qdisc", "del", "dev", veth, "root")
shared.RunCommand("tc", "qdisc", "del", "dev", veth, "ingress")
// Apply new limits
if m["limits.ingress"] != "" {
out, err := shared.RunCommand("tc", "qdisc", "add", "dev", veth, "root", "handle", "1:0", "htb", "default", "10")
if err != nil {
return fmt.Errorf("Failed to create root tc qdisc: %s", out)
}
out, err = shared.RunCommand("tc", "class", "add", "dev", veth, "parent", "1:0", "classid", "1:10", "htb", "rate", fmt.Sprintf("%dbit", ingressInt))
if err != nil {
return fmt.Errorf("Failed to create limit tc class: %s", out)
}
out, err = shared.RunCommand("tc", "filter", "add", "dev", veth, "parent", "1:0", "protocol", "all", "u32", "match", "u32", "0", "0", "flowid", "1:1")
if err != nil {
return fmt.Errorf("Failed to create tc filter: %s", out)
}
}
if m["limits.egress"] != "" {
out, err := shared.RunCommand("tc", "qdisc", "add", "dev", veth, "handle", "ffff:0", "ingress")
if err != nil {
return fmt.Errorf("Failed to create ingress tc qdisc: %s", out)
}
out, err = shared.RunCommand("tc", "filter", "add", "dev", veth, "parent", "ffff:0", "protocol", "all", "u32", "match", "u32", "0", "0", "police", "rate", fmt.Sprintf("%dbit", egressInt), "burst", "1024k", "mtu", "64kb", "drop")
if err != nil {
return fmt.Errorf("Failed to create ingress tc qdisc: %s", out)
}
}
return nil
}
// networkValidMAC validates an ethernet MAC address. e.g. "32:47:ae:06:22:f9".
func networkValidMAC(value string) error {
regexHwaddr, err := regexp.Compile("^([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}$")
if err != nil {
return err
}
if regexHwaddr.MatchString(value) {
return nil
}
return fmt.Errorf("Invalid value, must 6 bytes of lower case hex separated by colons")
}
// NetworkValidAddress validates an IP address string. If string is empty, returns valid.
func NetworkValidAddress(value string) error {
if value == "" {
return nil
}
ip := net.ParseIP(value)
if ip == nil {
return fmt.Errorf("Not an IP address: %s", value)
}
return nil
}
// NetworkValidAddressV4 validates an IPv4 addresss string. If string is empty, returns valid.
func NetworkValidAddressV4(value string) error {
if value == "" {
return nil
}
ip := net.ParseIP(value)
if ip == nil || ip.To4() == nil {
return fmt.Errorf("Not an IPv4 address: %s", value)
}
return nil
}
// NetworkValidAddressV6 validates an IPv6 addresss string. If string is empty, returns valid.
func NetworkValidAddressV6(value string) error {
if value == "" {
return nil
}
ip := net.ParseIP(value)
if ip == nil || ip.To4() != nil {
return fmt.Errorf("Not an IPv6 address: %s", value)
}
return nil
}
// NetworkValidAddressV4List validates a comma delimited list of IPv4 addresses.
func NetworkValidAddressV4List(value string) error {
for _, v := range strings.Split(value, ",") {
v = strings.TrimSpace(v)
err := NetworkValidAddressV4(v)
if err != nil {
return err
}
}
return nil
}
//NetworkValidAddressV6List validates a comma delimited list of IPv6 addresses.
func NetworkValidAddressV6List(value string) error {
for _, v := range strings.Split(value, ",") {
v = strings.TrimSpace(v)
err := NetworkValidAddressV6(v)
if err != nil {
return err
}
}
return nil
}
// NetworkValidNetworkV4 validates an IPv4 CIDR string. If string is empty, returns valid.
func NetworkValidNetworkV4(value string) error {
if value == "" {
return nil
}
ip, subnet, err := net.ParseCIDR(value)
if err != nil {
return err
}
if ip.To4() == nil {
return fmt.Errorf("Not an IPv4 network: %s", value)
}
if ip.String() != subnet.IP.String() {
return fmt.Errorf("Not an IPv4 network address: %s", value)
}
return nil
}
// NetworkValidNetworkV6 validates an IPv6 CIDR string. If string is empty, returns valid.
func NetworkValidNetworkV6(value string) error {
if value == "" {
return nil
}
ip, subnet, err := net.ParseCIDR(value)
if err != nil {
return err
}
if ip == nil || ip.To4() != nil {
return fmt.Errorf("Not an IPv6 network: %s", value)
}
if ip.String() != subnet.IP.String() {
return fmt.Errorf("Not an IPv6 network address: %s", value)
}
return nil
}
// NetworkValidNetworkV4List validates a comma delimited list of IPv4 CIDR strings.
func NetworkValidNetworkV4List(value string) error {
for _, network := range strings.Split(value, ",") {
network = strings.TrimSpace(network)
err := NetworkValidNetworkV4(network)
if err != nil {
return err
}
}
return nil
}
// NetworkValidNetworkV6List validates a comma delimited list of IPv6 CIDR strings.
func NetworkValidNetworkV6List(value string) error {
for _, network := range strings.Split(value, ",") {
network = strings.TrimSpace(network)
err := NetworkValidNetworkV6(network)
if err != nil {
return err
}
}
return nil
}
// networkParsePortRange validates a port range in the form n-n.
func networkParsePortRange(r string) (int64, int64, error) {
entries := strings.Split(r, "-")
if len(entries) > 2 {
return -1, -1, fmt.Errorf("Invalid port range %s", r)
}
base, err := strconv.ParseInt(entries[0], 10, 64)
if err != nil {
return -1, -1, err
}
size := int64(1)
if len(entries) > 1 {
size, err = strconv.ParseInt(entries[1], 10, 64)
if err != nil {
return -1, -1, err
}
size -= base
size++
}
return base, size, nil
}
// pciDevice represents info about a PCI uevent device.
type pciDevice struct {
ID string
SlotName string
Driver string
}
// networkGetDevicePCISlot returns the PCI device info for a given uevent file.
func networkGetDevicePCIDevice(ueventFilePath string) (pciDevice, error) {
dev := pciDevice{}
file, err := os.Open(ueventFilePath)
if err != nil {
return dev, err
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
// Looking for something like this "PCI_SLOT_NAME=0000:05:10.0"
fields := strings.SplitN(scanner.Text(), "=", 2)
if len(fields) == 2 {
if fields[0] == "PCI_SLOT_NAME" {
dev.SlotName = fields[1]
} else if fields[0] == "PCI_ID" {
dev.ID = fields[1]
} else if fields[0] == "DRIVER" {
dev.Driver = fields[1]
}
}
}
err = scanner.Err()
if err != nil {
return dev, err
}
if dev.SlotName == "" {
return dev, fmt.Errorf("Device uevent file could not be parsed")
}
return dev, nil
}
// networkDeviceUnbind unbinds a network device from the OS using its PCI Slot Name and driver name.
func networkDeviceUnbind(pciDev pciDevice) error {
driverUnbindPath := fmt.Sprintf("/sys/bus/pci/drivers/%s/unbind", pciDev.Driver)
err := ioutil.WriteFile(driverUnbindPath, []byte(pciDev.SlotName), 0600)
if err != nil {
return errors.Wrapf(err, "Failed unbinding device %q via %q", pciDev.SlotName, driverUnbindPath)
}
return nil
}
// networkDeviceBind binds a network device to the OS using its PCI Slot Name and driver name.
func networkDeviceBind(pciDev pciDevice) error {
driverBindPath := fmt.Sprintf("/sys/bus/pci/drivers/%s/bind", pciDev.Driver)
err := ioutil.WriteFile(driverBindPath, []byte(pciDev.SlotName), 0600)
if err != nil {
return errors.Wrapf(err, "Failed binding device %q via %q", pciDev.SlotName, driverBindPath)
}
return nil
}
// networkDeviceBindWait waits for network device to appear after being binded to a driver.
func networkDeviceBindWait(pciDev pciDevice) error {
devicePath := fmt.Sprintf("/sys/bus/pci/drivers/%s/%s", pciDev.Driver, pciDev.SlotName)
for i := 0; i < 10; i++ {
if shared.PathExists(devicePath) {
return nil
}
time.Sleep(50 * time.Millisecond)
}
return fmt.Errorf("Bind of device %q took too long", devicePath)
}
// networkInterfaceBindWait waits for network interface to appear after being binded to a driver.
func networkInterfaceBindWait(ifName string) error {
for i := 0; i < 10; i++ {
if shared.PathExists(fmt.Sprintf("/sys/class/net/%s", ifName)) {
return nil
}
time.Sleep(50 * time.Millisecond)
}
return fmt.Errorf("Bind of interface %q took too long", ifName)
}
// networkVFIOPCIRegister registers the PCI device with the VFIO-PCI driver.
// Should also bind the device to the vfio-pci driver if it is present. Requires the vfio-pci module is loaded.
func networkVFIOPCIRegister(pciDev pciDevice) error {
// vfio-pci module takes device IDs as "n n" but networkGetDevicePCIDevice returns them as "n:n".
devIDParts := strings.SplitN(pciDev.ID, ":", 2)
if len(devIDParts) < 2 {
return fmt.Errorf("Invalid device ID from %q", pciDev.ID)
}
vfioPCINewIDPath := "/sys/bus/pci/drivers/vfio-pci/new_id"
err := ioutil.WriteFile(vfioPCINewIDPath, []byte(fmt.Sprintf("%s %s", devIDParts[0], devIDParts[1])), 0600)
if err != nil {
return errors.Wrapf(err, "Failed registering PCI device ID %q to %q", pciDev.ID, vfioPCINewIDPath)
}
return nil
}