func (v *veth) initialize(config *network) error { peer := config.TempVethPeerName if peer == "" { return fmt.Errorf("peer is not specified") } child, err := net.InterfaceByName(peer) if err != nil { return err } if err := netlink.NetworkLinkDown(child); err != nil { return err } if err := netlink.NetworkChangeName(child, config.Name); err != nil { return err } // get the interface again after we changed the name as the index also changes. if child, err = net.InterfaceByName(config.Name); err != nil { return err } if config.MacAddress != "" { if err := netlink.NetworkSetMacAddress(child, config.MacAddress); err != nil { return err } } ip, ipNet, err := net.ParseCIDR(config.Address) if err != nil { return err } if err := netlink.NetworkLinkAddIp(child, ip, ipNet); err != nil { return err } if config.IPv6Address != "" { if ip, ipNet, err = net.ParseCIDR(config.IPv6Address); err != nil { return err } if err := netlink.NetworkLinkAddIp(child, ip, ipNet); err != nil { return err } } if err := netlink.NetworkSetMTU(child, config.Mtu); err != nil { return err } if err := netlink.NetworkLinkUp(child); err != nil { return err } if config.Gateway != "" { if err := netlink.AddDefaultGw(config.Gateway, config.Name); err != nil { return err } } if config.IPv6Gateway != "" { if err := netlink.AddDefaultGw(config.IPv6Gateway, config.Name); err != nil { return err } } return nil }
// SetLinkNetInNs configures network settings of the link in network namespace specified by PID. func (l *Link) SetLinkNetInNs(nspid int, ip net.IP, network *net.IPNet, gw *net.IP) error { origNs, _ := NetNsHandle(os.Getpid()) defer syscall.Close(int(origNs)) defer system.Setns(origNs, syscall.CLONE_NEWNET) if err := SetNetNsToPid(nspid); err != nil { return fmt.Errorf("Setting network namespace failed: %s", err) } if err := netlink.NetworkLinkAddIp(l.NetInterface(), ip, network); err != nil { return fmt.Errorf("Unable to set IP: %s in pid: %d network namespace", ip.String(), nspid) } if err := netlink.NetworkLinkUp(l.ifc); err != nil { return fmt.Errorf("Unable to bring %s interface UP: %s", l.ifc.Name, nspid) } if gw != nil { if err := netlink.AddDefaultGw(gw.String(), l.NetInterface().Name); err != nil { return fmt.Errorf("Unable to set Default gateway: %s in pid: %d network namespace", gw.String(), nspid) } } return nil }
// SetLinkDefaultGw configures the link's default Gateway. // It is equivalent of running: ip route add default via ${ip address} func (l *Link) SetLinkDefaultGw(gw *net.IP) error { return netlink.AddDefaultGw(gw.String(), l.NetInterface().Name) }