github.com/adityamillind98/moby@v23.0.0-rc.4+incompatible/libnetwork/drivers/bridge/setup_device.go (about)

     1  //go:build linux
     2  // +build linux
     3  
     4  package bridge
     5  
     6  import (
     7  	"fmt"
     8  	"os"
     9  	"path/filepath"
    10  
    11  	"github.com/docker/docker/libnetwork/netutils"
    12  	"github.com/sirupsen/logrus"
    13  	"github.com/vishvananda/netlink"
    14  )
    15  
    16  // SetupDevice create a new bridge interface/
    17  func setupDevice(config *networkConfiguration, i *bridgeInterface) error {
    18  	// We only attempt to create the bridge when the requested device name is
    19  	// the default one.
    20  	if config.BridgeName != DefaultBridgeName && config.DefaultBridge {
    21  		return NonDefaultBridgeExistError(config.BridgeName)
    22  	}
    23  
    24  	// Set the bridgeInterface netlink.Bridge.
    25  	i.Link = &netlink.Bridge{
    26  		LinkAttrs: netlink.LinkAttrs{
    27  			Name: config.BridgeName,
    28  		},
    29  	}
    30  
    31  	// Set the bridge's MAC address. Requires kernel version 3.3 or up.
    32  	hwAddr := netutils.GenerateRandomMAC()
    33  	i.Link.Attrs().HardwareAddr = hwAddr
    34  	logrus.Debugf("Setting bridge mac address to %s", hwAddr)
    35  
    36  	if err := i.nlh.LinkAdd(i.Link); err != nil {
    37  		logrus.Debugf("Failed to create bridge %s via netlink. Trying ioctl", config.BridgeName)
    38  		return ioctlCreateBridge(config.BridgeName, hwAddr.String())
    39  	}
    40  
    41  	return nil
    42  }
    43  
    44  func setupDefaultSysctl(config *networkConfiguration, i *bridgeInterface) error {
    45  	// Disable IPv6 router advertisements originating on the bridge
    46  	sysPath := filepath.Join("/proc/sys/net/ipv6/conf/", config.BridgeName, "accept_ra")
    47  	if _, err := os.Stat(sysPath); err != nil {
    48  		logrus.
    49  			WithField("bridge", config.BridgeName).
    50  			WithField("syspath", sysPath).
    51  			Info("failed to read ipv6 net.ipv6.conf.<bridge>.accept_ra")
    52  		return nil
    53  	}
    54  	if err := os.WriteFile(sysPath, []byte{'0', '\n'}, 0644); err != nil {
    55  		logrus.WithError(err).Warn("unable to disable IPv6 router advertisement")
    56  	}
    57  	return nil
    58  }
    59  
    60  // SetupDeviceUp ups the given bridge interface.
    61  func setupDeviceUp(config *networkConfiguration, i *bridgeInterface) error {
    62  	err := i.nlh.LinkSetUp(i.Link)
    63  	if err != nil {
    64  		return fmt.Errorf("Failed to set link up for %s: %v", config.BridgeName, err)
    65  	}
    66  
    67  	// Attempt to update the bridge interface to refresh the flags status,
    68  	// ignoring any failure to do so.
    69  	if lnk, err := i.nlh.LinkByName(config.BridgeName); err == nil {
    70  		i.Link = lnk
    71  	} else {
    72  		logrus.Warnf("Failed to retrieve link for interface (%s): %v", config.BridgeName, err)
    73  	}
    74  	return nil
    75  }