forked from genuinetools/netns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bridge.go
73 lines (61 loc) · 1.68 KB
/
bridge.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
package main
import (
"fmt"
"net"
"strings"
"github.com/docker/libnetwork/iptables"
"github.com/vishvananda/netlink"
)
// initBridge creates a bridge if it does not exist
func initBridge() error {
_, err := net.InterfaceByName(bridgeName)
if err == nil {
return nil
}
if !strings.Contains(err.Error(), "no such network interface") {
return err
}
// Create *netlink.Bridge object
la := netlink.NewLinkAttrs()
la.Name = bridgeName
la.MTU = mtu
br := &netlink.Bridge{LinkAttrs: la}
if err := netlink.LinkAdd(br); err != nil {
return fmt.Errorf("Bridge creation failed: %v", err)
}
// Setup ip address for bridge
addr, err := netlink.ParseAddr(ipAddr)
if err != nil {
return fmt.Errorf("Parsing address %s: %v", ipAddr, err)
}
if err := netlink.AddrAdd(br, addr); err != nil {
return fmt.Errorf("Adding address %v to bridge %s failed: %v", addr, bridgeName, err)
}
// Validate that the IPAddress is there!
_, err = getIfaceAddr(bridgeName)
if err != nil {
return fmt.Errorf("No IP address found on bridge %s", bridgeName)
}
// Add NAT rules for iptables
if err = natOut(ipAddr, iptables.Insert); err != nil {
return fmt.Errorf("Could not set NAT rules for bridge %s", bridgeName)
}
// Bring the bridge up
if err := netlink.LinkSetUp(br); err != nil {
return err
}
return nil
}
// deleteBridge deletes the bridge.
func deleteBridge() error {
// Get the link
l, err := netlink.LinkByName(bridgeName)
if err != nil {
return fmt.Errorf("Getting link with name %s failed: %v", bridgeName, err)
}
// Delete the link
if err := netlink.LinkDel(l); err != nil {
return fmt.Errorf("Failed to remove bridge interface %s delete: %v", bridgeName, err)
}
return nil
}