2015-02-23 01:24:22 +00:00
|
|
|
package bridge
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"math/rand"
|
|
|
|
"net"
|
|
|
|
|
|
|
|
log "github.com/Sirupsen/logrus"
|
|
|
|
"github.com/docker/docker/pkg/parsers/kernel"
|
|
|
|
"github.com/vishvananda/netlink"
|
|
|
|
)
|
|
|
|
|
2015-02-23 05:11:12 +00:00
|
|
|
// SetupDevice create a new bridge interface/
|
2015-02-23 01:58:52 +00:00
|
|
|
func SetupDevice(i *Interface) error {
|
2015-02-23 01:24:22 +00:00
|
|
|
// We only attempt to create the bridge when the requested device name is
|
|
|
|
// the default one.
|
2015-02-23 01:58:52 +00:00
|
|
|
if i.Config.BridgeName != DefaultBridgeName {
|
|
|
|
return fmt.Errorf("bridge device with non default name %q must be created manually", i.Config.BridgeName)
|
2015-02-23 01:24:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Set the Interface netlink.Bridge.
|
2015-02-23 01:58:52 +00:00
|
|
|
i.Link = &netlink.Bridge{
|
2015-02-23 01:24:22 +00:00
|
|
|
LinkAttrs: netlink.LinkAttrs{
|
2015-02-23 01:58:52 +00:00
|
|
|
Name: i.Config.BridgeName,
|
2015-02-23 01:24:22 +00:00
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
// Only set the bridge's MAC address if the kernel version is > 3.3, as it
|
|
|
|
// was not supported before that.
|
|
|
|
kv, err := kernel.GetKernelVersion()
|
|
|
|
if err == nil && (kv.Kernel >= 3 && kv.Major >= 3) {
|
2015-02-23 01:58:52 +00:00
|
|
|
i.Link.Attrs().HardwareAddr = generateRandomMAC()
|
|
|
|
log.Debugf("Setting bridge mac address to %s", i.Link.Attrs().HardwareAddr)
|
2015-02-23 01:24:22 +00:00
|
|
|
}
|
|
|
|
|
2015-02-23 05:11:12 +00:00
|
|
|
// Call out to netlink to create the device.
|
2015-02-23 01:58:52 +00:00
|
|
|
return netlink.LinkAdd(i.Link)
|
2015-02-23 01:24:22 +00:00
|
|
|
}
|
|
|
|
|
2015-02-23 05:11:12 +00:00
|
|
|
// SetupDeviceUp ups the given bridge interface.
|
2015-02-23 01:58:52 +00:00
|
|
|
func SetupDeviceUp(i *Interface) error {
|
2015-02-24 19:19:00 +00:00
|
|
|
err := netlink.LinkSetUp(i.Link)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Attempt to update the bridge interface to refresh the flags status,
|
|
|
|
// ignoring any failure to do so.
|
|
|
|
if lnk, err := netlink.LinkByName(i.Config.BridgeName); err == nil {
|
|
|
|
i.Link = lnk
|
|
|
|
}
|
|
|
|
return nil
|
2015-02-23 01:24:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func generateRandomMAC() net.HardwareAddr {
|
|
|
|
hw := make(net.HardwareAddr, 6)
|
|
|
|
for i := 0; i < 6; i++ {
|
|
|
|
hw[i] = byte(rand.Intn(255))
|
|
|
|
}
|
|
|
|
hw[0] &^= 0x1 // clear multicast bit
|
|
|
|
hw[0] |= 0x2 // set local assignment bit (IEEE802)
|
|
|
|
return hw
|
|
|
|
}
|