repo
stringlengths
5
67
sha
stringlengths
40
40
path
stringlengths
4
234
url
stringlengths
85
339
language
stringclasses
6 values
split
stringclasses
3 values
doc
stringlengths
3
51.2k
sign
stringlengths
5
8.01k
problem
stringlengths
13
51.2k
output
stringlengths
0
3.87M
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
client/service.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/service.go#L294-L324
go
train
// CmdServiceInfo handles service info UI
func (cli *NetworkCli) CmdServiceInfo(chain string, args ...string) error
// CmdServiceInfo handles service info UI func (cli *NetworkCli) CmdServiceInfo(chain string, args ...string) error
{ cmd := cli.Subcmd(chain, "info", "SERVICE[.NETWORK]", "Displays detailed information about a service", false) cmd.Require(flag.Min, 1) err := cmd.ParseFlags(args, true) if err != nil { return err } sn, nn := parseServiceName(cmd.Arg(0)) serviceID, err := lookupServiceID(cli, nn, sn) if err != nil { return err } obj, _, err := readBody(cli.call("GET", "/services/"+serviceID, nil, nil)) if err != nil { return err } sr := &serviceResource{} if err := json.NewDecoder(bytes.NewReader(obj)).Decode(sr); err != nil { return err } fmt.Fprintf(cli.out, "Service Id: %s\n", sr.ID) fmt.Fprintf(cli.out, "\tName: %s\n", sr.Name) fmt.Fprintf(cli.out, "\tNetwork: %s\n", sr.Network) return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
client/service.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/service.go#L327-L358
go
train
// CmdServiceAttach handles service attach UI
func (cli *NetworkCli) CmdServiceAttach(chain string, args ...string) error
// CmdServiceAttach handles service attach UI func (cli *NetworkCli) CmdServiceAttach(chain string, args ...string) error
{ cmd := cli.Subcmd(chain, "attach", "CONTAINER SERVICE[.NETWORK]", "Sets a container as a service backend", false) flAlias := opts.NewListOpts(netutils.ValidateAlias) cmd.Var(&flAlias, []string{"-alias"}, "Add alias for another container") cmd.Require(flag.Min, 2) err := cmd.ParseFlags(args, true) if err != nil { return err } containerID, err := lookupContainerID(cli, cmd.Arg(0)) if err != nil { return err } sandboxID, err := lookupSandboxID(cli, containerID) if err != nil { return err } sn, nn := parseServiceName(cmd.Arg(1)) serviceID, err := lookupServiceID(cli, nn, sn) if err != nil { return err } nc := serviceAttach{SandboxID: sandboxID, Aliases: flAlias.GetAll()} _, _, err = readBody(cli.call("POST", "/services/"+serviceID+"/backend", nc, nil)) return err }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
client/service.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/service.go#L361-L390
go
train
// CmdServiceDetach handles service detach UI
func (cli *NetworkCli) CmdServiceDetach(chain string, args ...string) error
// CmdServiceDetach handles service detach UI func (cli *NetworkCli) CmdServiceDetach(chain string, args ...string) error
{ cmd := cli.Subcmd(chain, "detach", "CONTAINER SERVICE", "Removes a container from service backend", false) cmd.Require(flag.Min, 2) err := cmd.ParseFlags(args, true) if err != nil { return err } sn, nn := parseServiceName(cmd.Arg(1)) containerID, err := lookupContainerID(cli, cmd.Arg(0)) if err != nil { return err } sandboxID, err := lookupSandboxID(cli, containerID) if err != nil { return err } serviceID, err := lookupServiceID(cli, nn, sn) if err != nil { return err } _, _, err = readBody(cli.call("DELETE", "/services/"+serviceID+"/backend/"+sandboxID, nil, nil)) if err != nil { return err } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
netutils/utils_freebsd.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/netutils/utils_freebsd.go#L15-L17
go
train
// ElectInterfaceAddresses looks for an interface on the OS with the specified name // and returns returns all its IPv4 and IPv6 addresses in CIDR notation. // If a failure in retrieving the addresses or no IPv4 address is found, an error is returned. // If the interface does not exist, it chooses from a predefined // list the first IPv4 address which does not conflict with other // interfaces on the system.
func ElectInterfaceAddresses(name string) ([]*net.IPNet, []*net.IPNet, error)
// ElectInterfaceAddresses looks for an interface on the OS with the specified name // and returns returns all its IPv4 and IPv6 addresses in CIDR notation. // If a failure in retrieving the addresses or no IPv4 address is found, an error is returned. // If the interface does not exist, it chooses from a predefined // list the first IPv4 address which does not conflict with other // interfaces on the system. func ElectInterfaceAddresses(name string) ([]*net.IPNet, []*net.IPNet, error)
{ return nil, nil, types.NotImplementedErrorf("not supported on freebsd") }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
netutils/utils_freebsd.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/netutils/utils_freebsd.go#L21-L23
go
train
// FindAvailableNetwork returns a network from the passed list which does not // overlap with existing interfaces in the system
func FindAvailableNetwork(list []*net.IPNet) (*net.IPNet, error)
// FindAvailableNetwork returns a network from the passed list which does not // overlap with existing interfaces in the system func FindAvailableNetwork(list []*net.IPNet) (*net.IPNet, error)
{ return nil, types.NotImplementedErrorf("not supported on freebsd") }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
ipam/store.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipam/store.go#L12-L16
go
train
// Key provides the Key to be used in KV Store
func (aSpace *addrSpace) Key() []string
// Key provides the Key to be used in KV Store func (aSpace *addrSpace) Key() []string
{ aSpace.Lock() defer aSpace.Unlock() return []string{aSpace.id} }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
ipam/store.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipam/store.go#L19-L23
go
train
// KeyPrefix returns the immediate parent key that can be used for tree walk
func (aSpace *addrSpace) KeyPrefix() []string
// KeyPrefix returns the immediate parent key that can be used for tree walk func (aSpace *addrSpace) KeyPrefix() []string
{ aSpace.Lock() defer aSpace.Unlock() return []string{dsConfigKey} }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
ipam/store.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipam/store.go#L26-L33
go
train
// Value marshals the data to be stored in the KV store
func (aSpace *addrSpace) Value() []byte
// Value marshals the data to be stored in the KV store func (aSpace *addrSpace) Value() []byte
{ b, err := json.Marshal(aSpace) if err != nil { logrus.Warnf("Failed to marshal ipam configured pools: %v", err) return nil } return b }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
ipam/store.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipam/store.go#L36-L43
go
train
// SetValue unmarshalls the data from the KV store.
func (aSpace *addrSpace) SetValue(value []byte) error
// SetValue unmarshalls the data from the KV store. func (aSpace *addrSpace) SetValue(value []byte) error
{ rc := &addrSpace{subnets: make(map[SubnetKey]*PoolData)} if err := json.Unmarshal(value, rc); err != nil { return err } aSpace.subnets = rc.subnets return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
ipam/store.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipam/store.go#L46-L50
go
train
// Index returns the latest DB Index as seen by this object
func (aSpace *addrSpace) Index() uint64
// Index returns the latest DB Index as seen by this object func (aSpace *addrSpace) Index() uint64
{ aSpace.Lock() defer aSpace.Unlock() return aSpace.dbIndex }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
ipam/store.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipam/store.go#L53-L58
go
train
// SetIndex method allows the datastore to store the latest DB Index into this object
func (aSpace *addrSpace) SetIndex(index uint64)
// SetIndex method allows the datastore to store the latest DB Index into this object func (aSpace *addrSpace) SetIndex(index uint64)
{ aSpace.Lock() aSpace.dbIndex = index aSpace.dbExists = true aSpace.Unlock() }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
ipam/store.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipam/store.go#L61-L65
go
train
// Exists method is true if this object has been stored in the DB.
func (aSpace *addrSpace) Exists() bool
// Exists method is true if this object has been stored in the DB. func (aSpace *addrSpace) Exists() bool
{ aSpace.Lock() defer aSpace.Unlock() return aSpace.dbExists }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
ipam/store.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipam/store.go#L131-L136
go
train
// DataScope method returns the storage scope of the datastore
func (aSpace *addrSpace) DataScope() string
// DataScope method returns the storage scope of the datastore func (aSpace *addrSpace) DataScope() string
{ aSpace.Lock() defer aSpace.Unlock() return aSpace.scope }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
firewall_linux.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/firewall_linux.go#L24-L40
go
train
// This chain allow users to configure firewall policies in a way that persists // docker operations/restarts. Docker will not delete or modify any pre-existing // rules from the DOCKER-USER filter chain.
func arrangeUserFilterRule()
// This chain allow users to configure firewall policies in a way that persists // docker operations/restarts. Docker will not delete or modify any pre-existing // rules from the DOCKER-USER filter chain. func arrangeUserFilterRule()
{ _, err := iptables.NewChain(userChain, iptables.Filter, false) if err != nil { logrus.Warnf("Failed to create %s chain: %v", userChain, err) return } if err = iptables.AddReturnRule(userChain); err != nil { logrus.Warnf("Failed to add the RETURN rule for %s: %v", userChain, err) return } err = iptables.EnsureJumpRule("FORWARD", userChain) if err != nil { logrus.Warnf("Failed to ensure the jump rule for %s: %v", userChain, err) } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
ipvs/ipvs.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipvs/ipvs.go#L88-L116
go
train
// New provides a new ipvs handle in the namespace pointed to by the // passed path. It will return a valid handle or an error in case an // error occurred while creating the handle.
func New(path string) (*Handle, error)
// New provides a new ipvs handle in the namespace pointed to by the // passed path. It will return a valid handle or an error in case an // error occurred while creating the handle. func New(path string) (*Handle, error)
{ setup() n := netns.None() if path != "" { var err error n, err = netns.GetFromPath(path) if err != nil { return nil, err } } defer n.Close() sock, err := nl.GetNetlinkSocketAt(n, netns.None(), syscall.NETLINK_GENERIC) if err != nil { return nil, err } // Add operation timeout to avoid deadlocks tv := syscall.NsecToTimeval(netlinkSendSocketTimeout.Nanoseconds()) if err := sock.SetSendTimeout(&tv); err != nil { return nil, err } tv = syscall.NsecToTimeval(netlinkRecvSocketsTimeout.Nanoseconds()) if err := sock.SetReceiveTimeout(&tv); err != nil { return nil, err } return &Handle{sock: sock}, nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
ipvs/ipvs.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipvs/ipvs.go#L127-L129
go
train
// NewService creates a new ipvs service in the passed handle.
func (i *Handle) NewService(s *Service) error
// NewService creates a new ipvs service in the passed handle. func (i *Handle) NewService(s *Service) error
{ return i.doCmd(s, nil, ipvsCmdNewService) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
ipvs/ipvs.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipvs/ipvs.go#L132-L134
go
train
// IsServicePresent queries for the ipvs service in the passed handle.
func (i *Handle) IsServicePresent(s *Service) bool
// IsServicePresent queries for the ipvs service in the passed handle. func (i *Handle) IsServicePresent(s *Service) bool
{ return nil == i.doCmd(s, nil, ipvsCmdGetService) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
ipvs/ipvs.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipvs/ipvs.go#L138-L140
go
train
// UpdateService updates an already existing service in the passed // handle.
func (i *Handle) UpdateService(s *Service) error
// UpdateService updates an already existing service in the passed // handle. func (i *Handle) UpdateService(s *Service) error
{ return i.doCmd(s, nil, ipvsCmdSetService) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
ipvs/ipvs.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipvs/ipvs.go#L144-L146
go
train
// DelService deletes an already existing service in the passed // handle.
func (i *Handle) DelService(s *Service) error
// DelService deletes an already existing service in the passed // handle. func (i *Handle) DelService(s *Service) error
{ return i.doCmd(s, nil, ipvsCmdDelService) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
ipvs/ipvs.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipvs/ipvs.go#L150-L153
go
train
// Flush deletes all existing services in the passed // handle.
func (i *Handle) Flush() error
// Flush deletes all existing services in the passed // handle. func (i *Handle) Flush() error
{ _, err := i.doCmdWithoutAttr(ipvsCmdFlush) return err }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
ipvs/ipvs.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipvs/ipvs.go#L157-L159
go
train
// NewDestination creates a new real server in the passed ipvs // service which should already be existing in the passed handle.
func (i *Handle) NewDestination(s *Service, d *Destination) error
// NewDestination creates a new real server in the passed ipvs // service which should already be existing in the passed handle. func (i *Handle) NewDestination(s *Service, d *Destination) error
{ return i.doCmd(s, d, ipvsCmdNewDest) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
ipvs/ipvs.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipvs/ipvs.go#L163-L165
go
train
// UpdateDestination updates an already existing real server in the // passed ipvs service in the passed handle.
func (i *Handle) UpdateDestination(s *Service, d *Destination) error
// UpdateDestination updates an already existing real server in the // passed ipvs service in the passed handle. func (i *Handle) UpdateDestination(s *Service, d *Destination) error
{ return i.doCmd(s, d, ipvsCmdSetDest) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
ipvs/ipvs.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipvs/ipvs.go#L169-L171
go
train
// DelDestination deletes an already existing real server in the // passed ipvs service in the passed handle.
func (i *Handle) DelDestination(s *Service, d *Destination) error
// DelDestination deletes an already existing real server in the // passed ipvs service in the passed handle. func (i *Handle) DelDestination(s *Service, d *Destination) error
{ return i.doCmd(s, d, ipvsCmdDelDest) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
ipvs/ipvs.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipvs/ipvs.go#L179-L181
go
train
// GetDestinations returns an array of Destinations configured for this Service
func (i *Handle) GetDestinations(s *Service) ([]*Destination, error)
// GetDestinations returns an array of Destinations configured for this Service func (i *Handle) GetDestinations(s *Service) ([]*Destination, error)
{ return i.doGetDestinationsCmd(s, nil) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
ipvs/ipvs.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipvs/ipvs.go#L184-L197
go
train
// GetService gets details of a specific IPVS services, useful in updating statisics etc.,
func (i *Handle) GetService(s *Service) (*Service, error)
// GetService gets details of a specific IPVS services, useful in updating statisics etc., func (i *Handle) GetService(s *Service) (*Service, error)
{ res, err := i.doGetServicesCmd(s) if err != nil { return nil, err } // We are looking for exactly one service otherwise error out if len(res) != 1 { return nil, fmt.Errorf("Expected only one service obtained=%d", len(res)) } return res[0], nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drivers/overlay/overlayutils/utils.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/overlay/overlayutils/utils.go#L23-L39
go
train
// ConfigVXLANUDPPort configures the VXLAN UDP port (data path port) number. // If no port is set, the default (4789) is returned. Valid port numbers are // between 1024 and 49151.
func ConfigVXLANUDPPort(vxlanPort uint32) error
// ConfigVXLANUDPPort configures the VXLAN UDP port (data path port) number. // If no port is set, the default (4789) is returned. Valid port numbers are // between 1024 and 49151. func ConfigVXLANUDPPort(vxlanPort uint32) error
{ if vxlanPort == 0 { vxlanPort = defaultVXLANUDPPort } // IANA procedures for each range in detail // The Well Known Ports, aka the System Ports, from 0-1023 // The Registered Ports, aka the User Ports, from 1024-49151 // The Dynamic Ports, aka the Private Ports, from 49152-65535 // So we can allow range between 1024 to 49151 if vxlanPort < 1024 || vxlanPort > 49151 { return fmt.Errorf("VXLAN UDP port number is not in valid range (1024-49151): %d", vxlanPort) } mutex.Lock() vxlanUDPPort = vxlanPort mutex.Unlock() return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drivers/macvlan/macvlan_network.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/macvlan/macvlan_network.go#L18-L80
go
train
// CreateNetwork the network for the specified driver type
func (d *driver) CreateNetwork(nid string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error
// CreateNetwork the network for the specified driver type func (d *driver) CreateNetwork(nid string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error
{ defer osl.InitOSContext()() kv, err := kernel.GetKernelVersion() if err != nil { return fmt.Errorf("failed to check kernel version for %s driver support: %v", macvlanType, err) } // ensure Kernel version is >= v3.9 for macvlan support if kv.Kernel < macvlanKernelVer || (kv.Kernel == macvlanKernelVer && kv.Major < macvlanMajorVer) { return fmt.Errorf("kernel version failed to meet the minimum macvlan kernel requirement of %d.%d, found %d.%d.%d", macvlanKernelVer, macvlanMajorVer, kv.Kernel, kv.Major, kv.Minor) } // reject a null v4 network if len(ipV4Data) == 0 || ipV4Data[0].Pool.String() == "0.0.0.0/0" { return fmt.Errorf("ipv4 pool is empty") } // parse and validate the config and bind to networkConfiguration config, err := parseNetworkOptions(nid, option) if err != nil { return err } config.ID = nid err = config.processIPAM(nid, ipV4Data, ipV6Data) if err != nil { return err } // verify the macvlan mode from -o macvlan_mode option switch config.MacvlanMode { case "", modeBridge: // default to macvlan bridge mode if -o macvlan_mode is empty config.MacvlanMode = modeBridge case modePrivate: config.MacvlanMode = modePrivate case modePassthru: config.MacvlanMode = modePassthru case modeVepa: config.MacvlanMode = modeVepa default: return fmt.Errorf("requested macvlan mode '%s' is not valid, 'bridge' mode is the macvlan driver default", config.MacvlanMode) } // loopback is not a valid parent link if config.Parent == "lo" { return fmt.Errorf("loopback interface is not a valid %s parent link", macvlanType) } // if parent interface not specified, create a dummy type link to use named dummy+net_id if config.Parent == "" { config.Parent = getDummyName(stringid.TruncateID(config.ID)) // empty parent and --internal are handled the same. Set here to update k/v config.Internal = true } err = d.createNetwork(config) if err != nil { return err } // update persistent db, rollback on fail err = d.storeUpdate(config) if err != nil { d.deleteNetwork(config.ID) logrus.Debugf("encountered an error rolling back a network create for %s : %v", config.ID, err) return err } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
portmapper/mapper_windows.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/portmapper/mapper_windows.go#L24-L26
go
train
// AppendForwardingTableEntry adds a port mapping to the forwarding table
func (pm *PortMapper) AppendForwardingTableEntry(proto string, sourceIP net.IP, sourcePort int, containerIP string, containerPort int) error
// AppendForwardingTableEntry adds a port mapping to the forwarding table func (pm *PortMapper) AppendForwardingTableEntry(proto string, sourceIP net.IP, sourcePort int, containerIP string, containerPort int) error
{ return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
portmapper/mapper.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/portmapper/mapper.go#L39-L45
go
train
// NewWithPortAllocator returns a new instance of PortMapper which will use the specified PortAllocator
func NewWithPortAllocator(allocator *portallocator.PortAllocator, proxyPath string) *PortMapper
// NewWithPortAllocator returns a new instance of PortMapper which will use the specified PortAllocator func NewWithPortAllocator(allocator *portallocator.PortAllocator, proxyPath string) *PortMapper
{ return &PortMapper{ currentMappings: make(map[string]*mapping), Allocator: allocator, proxyPath: proxyPath, } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
portmapper/mapper.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/portmapper/mapper.go#L48-L50
go
train
// Map maps the specified container transport address to the host's network address and transport port
func (pm *PortMapper) Map(container net.Addr, hostIP net.IP, hostPort int, useProxy bool) (host net.Addr, err error)
// Map maps the specified container transport address to the host's network address and transport port func (pm *PortMapper) Map(container net.Addr, hostIP net.IP, hostPort int, useProxy bool) (host net.Addr, err error)
{ return pm.MapRange(container, hostIP, hostPort, hostPort, useProxy) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
portmapper/mapper.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/portmapper/mapper.go#L53-L182
go
train
// MapRange maps the specified container transport address to the host's network address and transport port range
func (pm *PortMapper) MapRange(container net.Addr, hostIP net.IP, hostPortStart, hostPortEnd int, useProxy bool) (host net.Addr, err error)
// MapRange maps the specified container transport address to the host's network address and transport port range func (pm *PortMapper) MapRange(container net.Addr, hostIP net.IP, hostPortStart, hostPortEnd int, useProxy bool) (host net.Addr, err error)
{ pm.lock.Lock() defer pm.lock.Unlock() var ( m *mapping proto string allocatedHostPort int ) switch container.(type) { case *net.TCPAddr: proto = "tcp" if allocatedHostPort, err = pm.Allocator.RequestPortInRange(hostIP, proto, hostPortStart, hostPortEnd); err != nil { return nil, err } m = &mapping{ proto: proto, host: &net.TCPAddr{IP: hostIP, Port: allocatedHostPort}, container: container, } if useProxy { m.userlandProxy, err = newProxy(proto, hostIP, allocatedHostPort, container.(*net.TCPAddr).IP, container.(*net.TCPAddr).Port, pm.proxyPath) if err != nil { return nil, err } } else { m.userlandProxy, err = newDummyProxy(proto, hostIP, allocatedHostPort) if err != nil { return nil, err } } case *net.UDPAddr: proto = "udp" if allocatedHostPort, err = pm.Allocator.RequestPortInRange(hostIP, proto, hostPortStart, hostPortEnd); err != nil { return nil, err } m = &mapping{ proto: proto, host: &net.UDPAddr{IP: hostIP, Port: allocatedHostPort}, container: container, } if useProxy { m.userlandProxy, err = newProxy(proto, hostIP, allocatedHostPort, container.(*net.UDPAddr).IP, container.(*net.UDPAddr).Port, pm.proxyPath) if err != nil { return nil, err } } else { m.userlandProxy, err = newDummyProxy(proto, hostIP, allocatedHostPort) if err != nil { return nil, err } } case *sctp.SCTPAddr: proto = "sctp" if allocatedHostPort, err = pm.Allocator.RequestPortInRange(hostIP, proto, hostPortStart, hostPortEnd); err != nil { return nil, err } m = &mapping{ proto: proto, host: &sctp.SCTPAddr{IP: []net.IP{hostIP}, Port: allocatedHostPort}, container: container, } if useProxy { sctpAddr := container.(*sctp.SCTPAddr) if len(sctpAddr.IP) == 0 { return nil, ErrSCTPAddrNoIP } m.userlandProxy, err = newProxy(proto, hostIP, allocatedHostPort, sctpAddr.IP[0], sctpAddr.Port, pm.proxyPath) if err != nil { return nil, err } } else { m.userlandProxy, err = newDummyProxy(proto, hostIP, allocatedHostPort) if err != nil { return nil, err } } default: return nil, ErrUnknownBackendAddressType } // release the allocated port on any further error during return. defer func() { if err != nil { pm.Allocator.ReleasePort(hostIP, proto, allocatedHostPort) } }() key := getKey(m.host) if _, exists := pm.currentMappings[key]; exists { return nil, ErrPortMappedForIP } containerIP, containerPort := getIPAndPort(m.container) if hostIP.To4() != nil { if err := pm.AppendForwardingTableEntry(m.proto, hostIP, allocatedHostPort, containerIP.String(), containerPort); err != nil { return nil, err } } cleanup := func() error { // need to undo the iptables rules before we return m.userlandProxy.Stop() if hostIP.To4() != nil { pm.DeleteForwardingTableEntry(m.proto, hostIP, allocatedHostPort, containerIP.String(), containerPort) if err := pm.Allocator.ReleasePort(hostIP, m.proto, allocatedHostPort); err != nil { return err } } return nil } if err := m.userlandProxy.Start(); err != nil { if err := cleanup(); err != nil { return nil, fmt.Errorf("Error during port allocation cleanup: %v", err) } return nil, err } pm.currentMappings[key] = m return m.host, nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
portmapper/mapper.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/portmapper/mapper.go#L185-L219
go
train
// Unmap removes stored mapping for the specified host transport address
func (pm *PortMapper) Unmap(host net.Addr) error
// Unmap removes stored mapping for the specified host transport address func (pm *PortMapper) Unmap(host net.Addr) error
{ pm.lock.Lock() defer pm.lock.Unlock() key := getKey(host) data, exists := pm.currentMappings[key] if !exists { return ErrPortNotMapped } if data.userlandProxy != nil { data.userlandProxy.Stop() } delete(pm.currentMappings, key) containerIP, containerPort := getIPAndPort(data.container) hostIP, hostPort := getIPAndPort(data.host) if err := pm.DeleteForwardingTableEntry(data.proto, hostIP, hostPort, containerIP.String(), containerPort); err != nil { logrus.Errorf("Error on iptables delete: %s", err) } switch a := host.(type) { case *net.TCPAddr: return pm.Allocator.ReleasePort(a.IP, "tcp", a.Port) case *net.UDPAddr: return pm.Allocator.ReleasePort(a.IP, "udp", a.Port) case *sctp.SCTPAddr: if len(a.IP) == 0 { return ErrSCTPAddrNoIP } return pm.Allocator.ReleasePort(a.IP[0], "sctp", a.Port) } return ErrUnknownBackendAddressType }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
portmapper/mapper.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/portmapper/mapper.go#L222-L233
go
train
//ReMapAll will re-apply all port mappings
func (pm *PortMapper) ReMapAll()
//ReMapAll will re-apply all port mappings func (pm *PortMapper) ReMapAll()
{ pm.lock.Lock() defer pm.lock.Unlock() logrus.Debugln("Re-applying all port mappings.") for _, data := range pm.currentMappings { containerIP, containerPort := getIPAndPort(data.container) hostIP, hostPort := getIPAndPort(data.host) if err := pm.AppendForwardingTableEntry(data.proto, hostIP, hostPort, containerIP.String(), containerPort); err != nil { logrus.Errorf("Error on iptables add: %s", err) } } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
datastore/mock_store.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/datastore/mock_store.go#L34-L41
go
train
// Get the value at "key", returns the last modified index // to use in conjunction to CAS calls
func (s *MockStore) Get(key string) (*store.KVPair, error)
// Get the value at "key", returns the last modified index // to use in conjunction to CAS calls func (s *MockStore) Get(key string) (*store.KVPair, error)
{ mData := s.db[key] if mData == nil { return nil, nil } return &store.KVPair{Value: mData.Data, LastIndex: mData.Index}, nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
datastore/mock_store.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/datastore/mock_store.go#L44-L52
go
train
// Put a value at "key"
func (s *MockStore) Put(key string, value []byte, options *store.WriteOptions) error
// Put a value at "key" func (s *MockStore) Put(key string, value []byte, options *store.WriteOptions) error
{ mData := s.db[key] if mData == nil { mData = &MockData{value, 0} } mData.Index = mData.Index + 1 s.db[key] = mData return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
datastore/mock_store.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/datastore/mock_store.go#L55-L58
go
train
// Delete a value at "key"
func (s *MockStore) Delete(key string) error
// Delete a value at "key" func (s *MockStore) Delete(key string) error
{ delete(s.db, key) return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
datastore/mock_store.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/datastore/mock_store.go#L61-L64
go
train
// Exists checks that the key exists inside the store
func (s *MockStore) Exists(key string) (bool, error)
// Exists checks that the key exists inside the store func (s *MockStore) Exists(key string) (bool, error)
{ _, ok := s.db[key] return ok, nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
datastore/mock_store.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/datastore/mock_store.go#L67-L69
go
train
// List gets a range of values at "directory"
func (s *MockStore) List(prefix string) ([]*store.KVPair, error)
// List gets a range of values at "directory" func (s *MockStore) List(prefix string) ([]*store.KVPair, error)
{ return nil, ErrNotImplemented }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
datastore/mock_store.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/datastore/mock_store.go#L72-L75
go
train
// DeleteTree deletes a range of values at "directory"
func (s *MockStore) DeleteTree(prefix string) error
// DeleteTree deletes a range of values at "directory" func (s *MockStore) DeleteTree(prefix string) error
{ delete(s.db, prefix) return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
datastore/mock_store.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/datastore/mock_store.go#L78-L80
go
train
// Watch a single key for modifications
func (s *MockStore) Watch(key string, stopCh <-chan struct{}) (<-chan *store.KVPair, error)
// Watch a single key for modifications func (s *MockStore) Watch(key string, stopCh <-chan struct{}) (<-chan *store.KVPair, error)
{ return nil, ErrNotImplemented }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
datastore/mock_store.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/datastore/mock_store.go#L83-L85
go
train
// WatchTree triggers a watch on a range of values at "directory"
func (s *MockStore) WatchTree(prefix string, stopCh <-chan struct{}) (<-chan []*store.KVPair, error)
// WatchTree triggers a watch on a range of values at "directory" func (s *MockStore) WatchTree(prefix string, stopCh <-chan struct{}) (<-chan []*store.KVPair, error)
{ return nil, ErrNotImplemented }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
datastore/mock_store.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/datastore/mock_store.go#L88-L90
go
train
// NewLock exposed
func (s *MockStore) NewLock(key string, options *store.LockOptions) (store.Locker, error)
// NewLock exposed func (s *MockStore) NewLock(key string, options *store.LockOptions) (store.Locker, error)
{ return nil, ErrNotImplemented }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
datastore/mock_store.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/datastore/mock_store.go#L94-L114
go
train
// AtomicPut put a value at "key" if the key has not been // modified in the meantime, throws an error if this is the case
func (s *MockStore) AtomicPut(key string, newValue []byte, previous *store.KVPair, options *store.WriteOptions) (bool, *store.KVPair, error)
// AtomicPut put a value at "key" if the key has not been // modified in the meantime, throws an error if this is the case func (s *MockStore) AtomicPut(key string, newValue []byte, previous *store.KVPair, options *store.WriteOptions) (bool, *store.KVPair, error)
{ mData := s.db[key] if previous == nil { if mData != nil { return false, nil, types.BadRequestErrorf("atomic put failed because key exists") } // Else OK. } else { if mData == nil { return false, nil, types.BadRequestErrorf("atomic put failed because key exists") } if mData != nil && mData.Index != previous.LastIndex { return false, nil, types.BadRequestErrorf("atomic put failed due to mismatched Index") } // Else OK. } err := s.Put(key, newValue, nil) if err != nil { return false, nil, err } return true, &store.KVPair{Key: key, Value: newValue, LastIndex: s.db[key].Index}, nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
datastore/mock_store.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/datastore/mock_store.go#L118-L124
go
train
// AtomicDelete deletes a value at "key" if the key has not // been modified in the meantime, throws an error if this is the case
func (s *MockStore) AtomicDelete(key string, previous *store.KVPair) (bool, error)
// AtomicDelete deletes a value at "key" if the key has not // been modified in the meantime, throws an error if this is the case func (s *MockStore) AtomicDelete(key string, previous *store.KVPair) (bool, error)
{ mData := s.db[key] if mData != nil && mData.Index != previous.LastIndex { return false, types.BadRequestErrorf("atomic delete failed due to mismatched Index") } return true, s.Delete(key) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
resolver.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/resolver.go#L102-L111
go
train
// NewResolver creates a new instance of the Resolver
func NewResolver(address string, proxyDNS bool, resolverKey string, backend DNSBackend) Resolver
// NewResolver creates a new instance of the Resolver func NewResolver(address string, proxyDNS bool, resolverKey string, backend DNSBackend) Resolver
{ return &resolver{ backend: backend, proxyDNS: proxyDNS, listenAddress: address, resolverKey: resolverKey, err: fmt.Errorf("setup not done yet"), startCh: make(chan struct{}, 1), } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
ipam/utils.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipam/utils.go#L41-L55
go
train
// It generates the ip address in the passed subnet specified by // the passed host address ordinal
func generateAddress(ordinal uint64, network *net.IPNet) net.IP
// It generates the ip address in the passed subnet specified by // the passed host address ordinal func generateAddress(ordinal uint64, network *net.IPNet) net.IP
{ var address [16]byte // Get network portion of IP if getAddressVersion(network.IP) == v4 { copy(address[:], network.IP.To4()) } else { copy(address[:], network.IP) } end := len(network.Mask) addIntToIP(address[:end], ordinal) return net.IP(address[:end]) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
ipam/utils.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipam/utils.go#L66-L71
go
train
// Adds the ordinal IP to the current array // 192.168.0.0 + 53 => 192.168.0.53
func addIntToIP(array []byte, ordinal uint64)
// Adds the ordinal IP to the current array // 192.168.0.0 + 53 => 192.168.0.53 func addIntToIP(array []byte, ordinal uint64)
{ for i := len(array) - 1; i >= 0; i-- { array[i] |= (byte)(ordinal & 0xff) ordinal >>= 8 } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
ipam/utils.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipam/utils.go#L74-L81
go
train
// Convert an ordinal to the respective IP address
func ipToUint64(ip []byte) (value uint64)
// Convert an ordinal to the respective IP address func ipToUint64(ip []byte) (value uint64)
{ cip := types.GetMinimalIP(ip) for i := 0; i < len(cip); i++ { j := len(cip) - 1 - i value += uint64(cip[i]) << uint(j*8) } return value }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
netlabel/labels.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/netlabel/labels.go#L105-L110
go
train
// Key extracts the key portion of the label
func Key(label string) (key string)
// Key extracts the key portion of the label func Key(label string) (key string)
{ if kv := strings.SplitN(label, "=", 2); len(kv) > 0 { key = kv[0] } return }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
netlabel/labels.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/netlabel/labels.go#L113-L118
go
train
// Value extracts the value portion of the label
func Value(label string) (value string)
// Value extracts the value portion of the label func Value(label string) (value string)
{ if kv := strings.SplitN(label, "=", 2); len(kv) > 1 { value = kv[1] } return }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
netlabel/labels.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/netlabel/labels.go#L121-L129
go
train
// KeyValue decomposes the label in the (key,value) pair
func KeyValue(label string) (key string, value string)
// KeyValue decomposes the label in the (key,value) pair func KeyValue(label string) (key string, value string)
{ if kv := strings.SplitN(label, "=", 2); len(kv) > 0 { key = kv[0] if len(kv) > 1 { value = kv[1] } } return }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
ipams/windowsipam/windowsipam.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipams/windowsipam/windowsipam.go#L28-L32
go
train
// GetInit registers the built-in ipam service with libnetwork
func GetInit(ipamName string) func(ic ipamapi.Callback, l, g interface{}) error
// GetInit registers the built-in ipam service with libnetwork func GetInit(ipamName string) func(ic ipamapi.Callback, l, g interface{}) error
{ return func(ic ipamapi.Callback, l, g interface{}) error { return ic.RegisterIpamDriver(ipamName, &allocator{}) } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
ipams/windowsipam/windowsipam.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipams/windowsipam/windowsipam.go#L40-L59
go
train
// RequestPool returns an address pool along with its unique id. This is a null ipam driver. It allocates the // subnet user asked and does not validate anything. Doesn't support subpool allocation
func (a *allocator) RequestPool(addressSpace, pool, subPool string, options map[string]string, v6 bool) (string, *net.IPNet, map[string]string, error)
// RequestPool returns an address pool along with its unique id. This is a null ipam driver. It allocates the // subnet user asked and does not validate anything. Doesn't support subpool allocation func (a *allocator) RequestPool(addressSpace, pool, subPool string, options map[string]string, v6 bool) (string, *net.IPNet, map[string]string, error)
{ logrus.Debugf("RequestPool(%s, %s, %s, %v, %t)", addressSpace, pool, subPool, options, v6) if subPool != "" || v6 { return "", nil, nil, types.InternalErrorf("This request is not supported by null ipam driver") } var ipNet *net.IPNet var err error if pool != "" { _, ipNet, err = net.ParseCIDR(pool) if err != nil { return "", nil, nil, err } } else { ipNet = defaultPool } return ipNet.String(), ipNet, nil, nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
ipams/windowsipam/windowsipam.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipams/windowsipam/windowsipam.go#L62-L65
go
train
// ReleasePool releases the address pool - always succeeds
func (a *allocator) ReleasePool(poolID string) error
// ReleasePool releases the address pool - always succeeds func (a *allocator) ReleasePool(poolID string) error
{ logrus.Debugf("ReleasePool(%s)", poolID) return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
ipams/windowsipam/windowsipam.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipams/windowsipam/windowsipam.go#L69-L82
go
train
// RequestAddress returns an address from the specified pool ID. // Always allocate the 0.0.0.0/32 ip if no preferred address was specified
func (a *allocator) RequestAddress(poolID string, prefAddress net.IP, opts map[string]string) (*net.IPNet, map[string]string, error)
// RequestAddress returns an address from the specified pool ID. // Always allocate the 0.0.0.0/32 ip if no preferred address was specified func (a *allocator) RequestAddress(poolID string, prefAddress net.IP, opts map[string]string) (*net.IPNet, map[string]string, error)
{ logrus.Debugf("RequestAddress(%s, %v, %v)", poolID, prefAddress, opts) _, ipNet, err := net.ParseCIDR(poolID) if err != nil { return nil, nil, err } if prefAddress != nil { return &net.IPNet{IP: prefAddress, Mask: ipNet.Mask}, nil, nil } return nil, nil, nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
ipams/windowsipam/windowsipam.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipams/windowsipam/windowsipam.go#L85-L88
go
train
// ReleaseAddress releases the address - always succeeds
func (a *allocator) ReleaseAddress(poolID string, address net.IP) error
// ReleaseAddress releases the address - always succeeds func (a *allocator) ReleaseAddress(poolID string, address net.IP) error
{ logrus.Debugf("ReleaseAddress(%s, %v)", poolID, address) return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
ipams/remote/api/api.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipams/remote/api/api.go#L30-L35
go
train
// ToCapability converts the capability response into the internal ipam driver capability structure
func (capRes GetCapabilityResponse) ToCapability() *ipamapi.Capability
// ToCapability converts the capability response into the internal ipam driver capability structure func (capRes GetCapabilityResponse) ToCapability() *ipamapi.Capability
{ return &ipamapi.Capability{ RequiresMACAddress: capRes.RequiresMACAddress, RequiresRequestReplay: capRes.RequiresRequestReplay, } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
driverapi/driverapi.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/driverapi/driverapi.go#L203-L213
go
train
// IsValidType validates the passed in type against the valid object types
func IsValidType(objType ObjectType) bool
// IsValidType validates the passed in type against the valid object types func IsValidType(objType ObjectType) bool
{ switch objType { case EndpointObject: fallthrough case NetworkObject: fallthrough case OpaqueObject: return true } return false }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
ipams/builtin/builtin_windows.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipams/builtin/builtin_windows.go#L53-L62
go
train
// Init registers the built-in ipam service with libnetwork
func Init(ic ipamapi.Callback, l, g interface{}) error
// Init registers the built-in ipam service with libnetwork func Init(ic ipamapi.Callback, l, g interface{}) error
{ initFunc := windowsipam.GetInit(windowsipam.DefaultIPAM) err := InitDockerDefault(ic, l, g) if err != nil { return err } return initFunc(ic, l, g) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
network.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/network.go#L146-L151
go
train
// Validate checks whether the configuration is valid
func (c *IpamConf) Validate() error
// Validate checks whether the configuration is valid func (c *IpamConf) Validate() error
{ if c.Gateway != "" && nil == net.ParseIP(c.Gateway) { return types.BadRequestErrorf("invalid gateway address %s in Ipam configuration", c.Gateway) } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
network.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/network.go#L161-L175
go
train
// MarshalJSON encodes IpamInfo into json message
func (i *IpamInfo) MarshalJSON() ([]byte, error)
// MarshalJSON encodes IpamInfo into json message func (i *IpamInfo) MarshalJSON() ([]byte, error)
{ m := map[string]interface{}{ "PoolID": i.PoolID, } v, err := json.Marshal(&i.IPAMData) if err != nil { return nil, err } m["IPAMData"] = string(v) if i.Meta != nil { m["Meta"] = i.Meta } return json.Marshal(m) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
network.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/network.go#L178-L199
go
train
// UnmarshalJSON decodes json message into PoolData
func (i *IpamInfo) UnmarshalJSON(data []byte) error
// UnmarshalJSON decodes json message into PoolData func (i *IpamInfo) UnmarshalJSON(data []byte) error
{ var ( m map[string]interface{} err error ) if err = json.Unmarshal(data, &m); err != nil { return err } i.PoolID = m["PoolID"].(string) if v, ok := m["Meta"]; ok { b, _ := json.Marshal(v) if err = json.Unmarshal(b, &i.Meta); err != nil { return err } } if v, ok := m["IPAMData"]; ok { if err = json.Unmarshal([]byte(v.(string)), &i.IPAMData); err != nil { return err } } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
network.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/network.go#L335-L346
go
train
// CopyTo deep copies to the destination IpamConfig
func (c *IpamConf) CopyTo(dstC *IpamConf) error
// CopyTo deep copies to the destination IpamConfig func (c *IpamConf) CopyTo(dstC *IpamConf) error
{ dstC.PreferredPool = c.PreferredPool dstC.SubPool = c.SubPool dstC.Gateway = c.Gateway if c.AuxAddresses != nil { dstC.AuxAddresses = make(map[string]string, len(c.AuxAddresses)) for k, v := range c.AuxAddresses { dstC.AuxAddresses[k] = v } } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
network.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/network.go#L349-L370
go
train
// CopyTo deep copies to the destination IpamInfo
func (i *IpamInfo) CopyTo(dstI *IpamInfo) error
// CopyTo deep copies to the destination IpamInfo func (i *IpamInfo) CopyTo(dstI *IpamInfo) error
{ dstI.PoolID = i.PoolID if i.Meta != nil { dstI.Meta = make(map[string]string) for k, v := range i.Meta { dstI.Meta[k] = v } } dstI.AddressSpace = i.AddressSpace dstI.Pool = types.GetIPNetCopy(i.Pool) dstI.Gateway = types.GetIPNetCopy(i.Gateway) if i.AuxAddresses != nil { dstI.AuxAddresses = make(map[string]*net.IPNet) for k, v := range i.AuxAddresses { dstI.AuxAddresses[k] = types.GetIPNetCopy(v) } } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
network.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/network.go#L420-L456
go
train
// Applies network specific configurations
func (n *network) applyConfigurationTo(to *network) error
// Applies network specific configurations func (n *network) applyConfigurationTo(to *network) error
{ to.enableIPv6 = n.enableIPv6 if len(n.labels) > 0 { to.labels = make(map[string]string, len(n.labels)) for k, v := range n.labels { if _, ok := to.labels[k]; !ok { to.labels[k] = v } } } if len(n.ipamType) != 0 { to.ipamType = n.ipamType } if len(n.ipamOptions) > 0 { to.ipamOptions = make(map[string]string, len(n.ipamOptions)) for k, v := range n.ipamOptions { if _, ok := to.ipamOptions[k]; !ok { to.ipamOptions[k] = v } } } if len(n.ipamV4Config) > 0 { to.ipamV4Config = make([]*IpamConf, 0, len(n.ipamV4Config)) to.ipamV4Config = append(to.ipamV4Config, n.ipamV4Config...) } if len(n.ipamV6Config) > 0 { to.ipamV6Config = make([]*IpamConf, 0, len(n.ipamV6Config)) to.ipamV6Config = append(to.ipamV6Config, n.ipamV6Config...) } if len(n.generic) > 0 { to.generic = options.Generic{} for k, v := range n.generic { to.generic[k] = v } } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
network.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/network.go#L549-L603
go
train
// TODO : Can be made much more generic with the help of reflection (but has some golang limitations)
func (n *network) MarshalJSON() ([]byte, error)
// TODO : Can be made much more generic with the help of reflection (but has some golang limitations) func (n *network) MarshalJSON() ([]byte, error)
{ netMap := make(map[string]interface{}) netMap["name"] = n.name netMap["id"] = n.id netMap["created"] = n.created netMap["networkType"] = n.networkType netMap["scope"] = n.scope netMap["labels"] = n.labels netMap["ipamType"] = n.ipamType netMap["ipamOptions"] = n.ipamOptions netMap["addrSpace"] = n.addrSpace netMap["enableIPv6"] = n.enableIPv6 if n.generic != nil { netMap["generic"] = n.generic } netMap["persist"] = n.persist netMap["postIPv6"] = n.postIPv6 if len(n.ipamV4Config) > 0 { ics, err := json.Marshal(n.ipamV4Config) if err != nil { return nil, err } netMap["ipamV4Config"] = string(ics) } if len(n.ipamV4Info) > 0 { iis, err := json.Marshal(n.ipamV4Info) if err != nil { return nil, err } netMap["ipamV4Info"] = string(iis) } if len(n.ipamV6Config) > 0 { ics, err := json.Marshal(n.ipamV6Config) if err != nil { return nil, err } netMap["ipamV6Config"] = string(ics) } if len(n.ipamV6Info) > 0 { iis, err := json.Marshal(n.ipamV6Info) if err != nil { return nil, err } netMap["ipamV6Info"] = string(iis) } netMap["internal"] = n.internal netMap["attachable"] = n.attachable netMap["inDelete"] = n.inDelete netMap["ingress"] = n.ingress netMap["configOnly"] = n.configOnly netMap["configFrom"] = n.configFrom netMap["loadBalancerIP"] = n.loadBalancerIP netMap["loadBalancerMode"] = n.loadBalancerMode return json.Marshal(netMap) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
network.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/network.go#L606-L724
go
train
// TODO : Can be made much more generic with the help of reflection (but has some golang limitations)
func (n *network) UnmarshalJSON(b []byte) (err error)
// TODO : Can be made much more generic with the help of reflection (but has some golang limitations) func (n *network) UnmarshalJSON(b []byte) (err error)
{ var netMap map[string]interface{} if err := json.Unmarshal(b, &netMap); err != nil { return err } n.name = netMap["name"].(string) n.id = netMap["id"].(string) // "created" is not available in older versions if v, ok := netMap["created"]; ok { // n.created is time.Time but marshalled as string if err = n.created.UnmarshalText([]byte(v.(string))); err != nil { logrus.Warnf("failed to unmarshal creation time %v: %v", v, err) n.created = time.Time{} } } n.networkType = netMap["networkType"].(string) n.enableIPv6 = netMap["enableIPv6"].(bool) // if we weren't unmarshaling to netMap we could simply set n.labels // unfortunately, we can't because map[string]interface{} != map[string]string if labels, ok := netMap["labels"].(map[string]interface{}); ok { n.labels = make(map[string]string, len(labels)) for label, value := range labels { n.labels[label] = value.(string) } } if v, ok := netMap["ipamOptions"]; ok { if iOpts, ok := v.(map[string]interface{}); ok { n.ipamOptions = make(map[string]string, len(iOpts)) for k, v := range iOpts { n.ipamOptions[k] = v.(string) } } } if v, ok := netMap["generic"]; ok { n.generic = v.(map[string]interface{}) // Restore opts in their map[string]string form if v, ok := n.generic[netlabel.GenericData]; ok { var lmap map[string]string ba, err := json.Marshal(v) if err != nil { return err } if err := json.Unmarshal(ba, &lmap); err != nil { return err } n.generic[netlabel.GenericData] = lmap } } if v, ok := netMap["persist"]; ok { n.persist = v.(bool) } if v, ok := netMap["postIPv6"]; ok { n.postIPv6 = v.(bool) } if v, ok := netMap["ipamType"]; ok { n.ipamType = v.(string) } else { n.ipamType = ipamapi.DefaultIPAM } if v, ok := netMap["addrSpace"]; ok { n.addrSpace = v.(string) } if v, ok := netMap["ipamV4Config"]; ok { if err := json.Unmarshal([]byte(v.(string)), &n.ipamV4Config); err != nil { return err } } if v, ok := netMap["ipamV4Info"]; ok { if err := json.Unmarshal([]byte(v.(string)), &n.ipamV4Info); err != nil { return err } } if v, ok := netMap["ipamV6Config"]; ok { if err := json.Unmarshal([]byte(v.(string)), &n.ipamV6Config); err != nil { return err } } if v, ok := netMap["ipamV6Info"]; ok { if err := json.Unmarshal([]byte(v.(string)), &n.ipamV6Info); err != nil { return err } } if v, ok := netMap["internal"]; ok { n.internal = v.(bool) } if v, ok := netMap["attachable"]; ok { n.attachable = v.(bool) } if s, ok := netMap["scope"]; ok { n.scope = s.(string) } if v, ok := netMap["inDelete"]; ok { n.inDelete = v.(bool) } if v, ok := netMap["ingress"]; ok { n.ingress = v.(bool) } if v, ok := netMap["configOnly"]; ok { n.configOnly = v.(bool) } if v, ok := netMap["configFrom"]; ok { n.configFrom = v.(string) } if v, ok := netMap["loadBalancerIP"]; ok { n.loadBalancerIP = net.ParseIP(v.(string)) } n.loadBalancerMode = loadBalancerModeDefault if v, ok := netMap["loadBalancerMode"]; ok { n.loadBalancerMode = v.(string) } // Reconcile old networks with the recently added `--ipv6` flag if !n.enableIPv6 { n.enableIPv6 = len(n.ipamV6Info) > 0 } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
network.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/network.go#L733-L748
go
train
// NetworkOptionGeneric function returns an option setter for a Generic option defined // in a Dictionary of Key-Value pair
func NetworkOptionGeneric(generic map[string]interface{}) NetworkOption
// NetworkOptionGeneric function returns an option setter for a Generic option defined // in a Dictionary of Key-Value pair func NetworkOptionGeneric(generic map[string]interface{}) NetworkOption
{ return func(n *network) { if n.generic == nil { n.generic = make(map[string]interface{}) } if val, ok := generic[netlabel.EnableIPv6]; ok { n.enableIPv6 = val.(bool) } if val, ok := generic[netlabel.Internal]; ok { n.internal = val.(bool) } for k, v := range generic { n.generic[k] = v } } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
network.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/network.go#L766-L774
go
train
// NetworkOptionEnableIPv6 returns an option setter to explicitly configure IPv6
func NetworkOptionEnableIPv6(enableIPv6 bool) NetworkOption
// NetworkOptionEnableIPv6 returns an option setter to explicitly configure IPv6 func NetworkOptionEnableIPv6(enableIPv6 bool) NetworkOption
{ return func(n *network) { if n.generic == nil { n.generic = make(map[string]interface{}) } n.enableIPv6 = enableIPv6 n.generic[netlabel.EnableIPv6] = enableIPv6 } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
network.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/network.go#L778-L786
go
train
// NetworkOptionInternalNetwork returns an option setter to config the network // to be internal which disables default gateway service
func NetworkOptionInternalNetwork() NetworkOption
// NetworkOptionInternalNetwork returns an option setter to config the network // to be internal which disables default gateway service func NetworkOptionInternalNetwork() NetworkOption
{ return func(n *network) { if n.generic == nil { n.generic = make(map[string]interface{}) } n.internal = true n.generic[netlabel.Internal] = true } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
network.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/network.go#L804-L817
go
train
// NetworkOptionIpam function returns an option setter for the ipam configuration for this network
func NetworkOptionIpam(ipamDriver string, addrSpace string, ipV4 []*IpamConf, ipV6 []*IpamConf, opts map[string]string) NetworkOption
// NetworkOptionIpam function returns an option setter for the ipam configuration for this network func NetworkOptionIpam(ipamDriver string, addrSpace string, ipV4 []*IpamConf, ipV6 []*IpamConf, opts map[string]string) NetworkOption
{ return func(n *network) { if ipamDriver != "" { n.ipamType = ipamDriver if ipamDriver == ipamapi.DefaultIPAM { n.ipamType = defaultIpamForNetworkType(n.Type()) } } n.ipamOptions = opts n.addrSpace = addrSpace n.ipamV4Config = ipV4 n.ipamV6Config = ipV6 } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
network.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/network.go#L820-L824
go
train
// NetworkOptionLBEndpoint function returns an option setter for the configuration of the load balancer endpoint for this network
func NetworkOptionLBEndpoint(ip net.IP) NetworkOption
// NetworkOptionLBEndpoint function returns an option setter for the configuration of the load balancer endpoint for this network func NetworkOptionLBEndpoint(ip net.IP) NetworkOption
{ return func(n *network) { n.loadBalancerIP = ip } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
network.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/network.go#L827-L838
go
train
// NetworkOptionDriverOpts function returns an option setter for any driver parameter described by a map
func NetworkOptionDriverOpts(opts map[string]string) NetworkOption
// NetworkOptionDriverOpts function returns an option setter for any driver parameter described by a map func NetworkOptionDriverOpts(opts map[string]string) NetworkOption
{ return func(n *network) { if n.generic == nil { n.generic = make(map[string]interface{}) } if opts == nil { opts = make(map[string]string) } // Store the options n.generic[netlabel.GenericData] = opts } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
network.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/network.go#L841-L845
go
train
// NetworkOptionLabels function returns an option setter for labels specific to a network
func NetworkOptionLabels(labels map[string]string) NetworkOption
// NetworkOptionLabels function returns an option setter for labels specific to a network func NetworkOptionLabels(labels map[string]string) NetworkOption
{ return func(n *network) { n.labels = labels } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
network.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/network.go#L990-L1107
go
train
// This function gets called in 3 ways: // * Delete() -- (false, false) // remove if endpoint count == 0 or endpoint count == 1 and // there is a load balancer IP // * Delete(libnetwork.NetworkDeleteOptionRemoveLB) -- (false, true) // remove load balancer and network if endpoint count == 1 // * controller.networkCleanup() -- (true, true) // remove the network no matter what
func (n *network) delete(force bool, rmLBEndpoint bool) error
// This function gets called in 3 ways: // * Delete() -- (false, false) // remove if endpoint count == 0 or endpoint count == 1 and // there is a load balancer IP // * Delete(libnetwork.NetworkDeleteOptionRemoveLB) -- (false, true) // remove load balancer and network if endpoint count == 1 // * controller.networkCleanup() -- (true, true) // remove the network no matter what func (n *network) delete(force bool, rmLBEndpoint bool) error
{ n.Lock() c := n.ctrlr name := n.name id := n.id n.Unlock() c.networkLocker.Lock(id) defer c.networkLocker.Unlock(id) n, err := c.getNetworkFromStore(id) if err != nil { return &UnknownNetworkError{name: name, id: id} } // Only remove ingress on force removal or explicit LB endpoint removal if n.ingress && !force && !rmLBEndpoint { return &ActiveEndpointsError{name: n.name, id: n.id} } // Check that the network is empty var emptyCount uint64 if n.hasLoadBalancerEndpoint() { emptyCount = 1 } if !force && n.getEpCnt().EndpointCnt() > emptyCount { if n.configOnly { return types.ForbiddenErrorf("configuration network %q is in use", n.Name()) } return &ActiveEndpointsError{name: n.name, id: n.id} } if n.hasLoadBalancerEndpoint() { // If we got to this point, then the following must hold: // * force is true OR endpoint count == 1 if err := n.deleteLoadBalancerSandbox(); err != nil { if !force { return err } // continue deletion when force is true even on error logrus.Warnf("Error deleting load balancer sandbox: %v", err) } //Reload the network from the store to update the epcnt. n, err = c.getNetworkFromStore(id) if err != nil { return &UnknownNetworkError{name: name, id: id} } } // Up to this point, errors that we returned were recoverable. // From here on, any errors leave us in an inconsistent state. // This is unfortunate, but there isn't a safe way to // reconstitute a load-balancer endpoint after removing it. // Mark the network for deletion n.inDelete = true if err = c.updateToStore(n); err != nil { return fmt.Errorf("error marking network %s (%s) for deletion: %v", n.Name(), n.ID(), err) } if n.ConfigFrom() != "" { if t, err := c.getConfigNetwork(n.ConfigFrom()); err == nil { if err := t.getEpCnt().DecEndpointCnt(); err != nil { logrus.Warnf("Failed to update reference count for configuration network %q on removal of network %q: %v", t.Name(), n.Name(), err) } } else { logrus.Warnf("Could not find configuration network %q during removal of network %q", n.configOnly, n.Name()) } } if n.configOnly { goto removeFromStore } if err = n.deleteNetwork(); err != nil { if !force { return err } logrus.Debugf("driver failed to delete stale network %s (%s): %v", n.Name(), n.ID(), err) } n.ipamRelease() if err = c.updateToStore(n); err != nil { logrus.Warnf("Failed to update store after ipam release for network %s (%s): %v", n.Name(), n.ID(), err) } // We are about to delete the network. Leave the gossip // cluster for the network to stop all incoming network // specific gossip updates before cleaning up all the service // bindings for the network. But cleanup service binding // before deleting the network from the store since service // bindings cleanup requires the network in the store. n.cancelDriverWatches() if err = n.leaveCluster(); err != nil { logrus.Errorf("Failed leaving network %s from the agent cluster: %v", n.Name(), err) } // Cleanup the service discovery for this network c.cleanupServiceDiscovery(n.ID()) removeFromStore: // deleteFromStore performs an atomic delete operation and the // network.epCnt will help prevent any possible // race between endpoint join and network delete if err = c.deleteFromStore(n.getEpCnt()); err != nil { if !force { return fmt.Errorf("error deleting network endpoint count from store: %v", err) } logrus.Debugf("Error deleting endpoint count from store for stale network %s (%s) for deletion: %v", n.Name(), n.ID(), err) } if err = c.deleteFromStore(n); err != nil { return fmt.Errorf("error deleting network from store: %v", err) } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
network.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/network.go#L2105-L2123
go
train
// config-only network is looked up by name
func (c *controller) getConfigNetwork(name string) (*network, error)
// config-only network is looked up by name func (c *controller) getConfigNetwork(name string) (*network, error)
{ var n Network s := func(current Network) bool { if current.Info().ConfigOnly() && current.Name() == name { n = current return true } return false } c.WalkNetworks(s) if n == nil { return nil, types.NotFoundErrorf("configuration network %q not found", name) } return n.(*network), nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drivers/overlay/joinleave.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/overlay/joinleave.go#L16-L137
go
train
// Join method is invoked when a Sandbox is attached to an endpoint.
func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error
// Join method is invoked when a Sandbox is attached to an endpoint. func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error
{ if err := validateID(nid, eid); err != nil { return err } n := d.network(nid) if n == nil { return fmt.Errorf("could not find network with id %s", nid) } ep := n.endpoint(eid) if ep == nil { return fmt.Errorf("could not find endpoint with id %s", eid) } if n.secure && len(d.keys) == 0 { return fmt.Errorf("cannot join secure network: encryption keys not present") } nlh := ns.NlHandle() if n.secure && !nlh.SupportsNetlinkFamily(syscall.NETLINK_XFRM) { return fmt.Errorf("cannot join secure network: required modules to install IPSEC rules are missing on host") } s := n.getSubnetforIP(ep.addr) if s == nil { return fmt.Errorf("could not find subnet for endpoint %s", eid) } if err := n.obtainVxlanID(s); err != nil { return fmt.Errorf("couldn't get vxlan id for %q: %v", s.subnetIP.String(), err) } if err := n.joinSandbox(s, false, true); err != nil { return fmt.Errorf("network sandbox join failed: %v", err) } sbox := n.sandbox() overlayIfName, containerIfName, err := createVethPair() if err != nil { return err } ep.ifName = containerIfName if err = d.writeEndpointToStore(ep); err != nil { return fmt.Errorf("failed to update overlay endpoint %.7s to local data store: %v", ep.id, err) } // Set the container interface and its peer MTU to 1450 to allow // for 50 bytes vxlan encap (inner eth header(14) + outer IP(20) + // outer UDP(8) + vxlan header(8)) mtu := n.maxMTU() veth, err := nlh.LinkByName(overlayIfName) if err != nil { return fmt.Errorf("cound not find link by name %s: %v", overlayIfName, err) } err = nlh.LinkSetMTU(veth, mtu) if err != nil { return err } if err = sbox.AddInterface(overlayIfName, "veth", sbox.InterfaceOptions().Master(s.brName)); err != nil { return fmt.Errorf("could not add veth pair inside the network sandbox: %v", err) } veth, err = nlh.LinkByName(containerIfName) if err != nil { return fmt.Errorf("could not find link by name %s: %v", containerIfName, err) } err = nlh.LinkSetMTU(veth, mtu) if err != nil { return err } if err = nlh.LinkSetHardwareAddr(veth, ep.mac); err != nil { return fmt.Errorf("could not set mac address (%v) to the container interface: %v", ep.mac, err) } for _, sub := range n.subnets { if sub == s { continue } if err = jinfo.AddStaticRoute(sub.subnetIP, types.NEXTHOP, s.gwIP.IP); err != nil { logrus.Errorf("Adding subnet %s static route in network %q failed\n", s.subnetIP, n.id) } } if iNames := jinfo.InterfaceName(); iNames != nil { err = iNames.SetNames(containerIfName, "eth") if err != nil { return err } } d.peerAdd(nid, eid, ep.addr.IP, ep.addr.Mask, ep.mac, net.ParseIP(d.advertiseAddress), false, false, true) if err = d.checkEncryption(nid, nil, n.vxlanID(s), true, true); err != nil { logrus.Warn(err) } buf, err := proto.Marshal(&PeerRecord{ EndpointIP: ep.addr.String(), EndpointMAC: ep.mac.String(), TunnelEndpointIP: d.advertiseAddress, }) if err != nil { return err } if err := jinfo.AddTableEntry(ovPeerTable, eid, buf); err != nil { logrus.Errorf("overlay: Failed adding table entry to joininfo: %v", err) } d.pushLocalEndpointEvent("join", nid, eid) return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drivers/overlay/joinleave.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/overlay/joinleave.go#L203-L232
go
train
// Leave method is invoked when a Sandbox detaches from an endpoint.
func (d *driver) Leave(nid, eid string) error
// Leave method is invoked when a Sandbox detaches from an endpoint. func (d *driver) Leave(nid, eid string) error
{ if err := validateID(nid, eid); err != nil { return err } n := d.network(nid) if n == nil { return fmt.Errorf("could not find network with id %s", nid) } ep := n.endpoint(eid) if ep == nil { return types.InternalMaskableErrorf("could not find endpoint with id %s", eid) } if d.notifyCh != nil { d.notifyCh <- ovNotify{ action: "leave", nw: n, ep: ep, } } d.peerDelete(nid, eid, ep.addr.IP, ep.addr.Mask, ep.mac, net.ParseIP(d.advertiseAddress), true) n.leaveSandbox() return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
iptables/iptables.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/iptables/iptables.go#L120-L139
go
train
// NewChain adds a new chain to ip table.
func NewChain(name string, table Table, hairpinMode bool) (*ChainInfo, error)
// NewChain adds a new chain to ip table. func NewChain(name string, table Table, hairpinMode bool) (*ChainInfo, error)
{ c := &ChainInfo{ Name: name, Table: table, HairpinMode: hairpinMode, } if string(c.Table) == "" { c.Table = Filter } // Add chain if it doesn't exist if _, err := Raw("-t", string(c.Table), "-n", "-L", c.Name); err != nil { if output, err := Raw("-t", string(c.Table), "-N", c.Name); err != nil { return nil, err } else if len(output) != 0 { return nil, fmt.Errorf("Could not create %s/%s chain: %s", c.Table, c.Name, output) } } return c, nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
iptables/iptables.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/iptables/iptables.go#L142-L224
go
train
// ProgramChain is used to add rules to a chain
func ProgramChain(c *ChainInfo, bridgeName string, hairpinMode, enable bool) error
// ProgramChain is used to add rules to a chain func ProgramChain(c *ChainInfo, bridgeName string, hairpinMode, enable bool) error
{ if c.Name == "" { return errors.New("Could not program chain, missing chain name") } switch c.Table { case Nat: preroute := []string{ "-m", "addrtype", "--dst-type", "LOCAL", "-j", c.Name} if !Exists(Nat, "PREROUTING", preroute...) && enable { if err := c.Prerouting(Append, preroute...); err != nil { return fmt.Errorf("Failed to inject %s in PREROUTING chain: %s", c.Name, err) } } else if Exists(Nat, "PREROUTING", preroute...) && !enable { if err := c.Prerouting(Delete, preroute...); err != nil { return fmt.Errorf("Failed to remove %s in PREROUTING chain: %s", c.Name, err) } } output := []string{ "-m", "addrtype", "--dst-type", "LOCAL", "-j", c.Name} if !hairpinMode { output = append(output, "!", "--dst", "127.0.0.0/8") } if !Exists(Nat, "OUTPUT", output...) && enable { if err := c.Output(Append, output...); err != nil { return fmt.Errorf("Failed to inject %s in OUTPUT chain: %s", c.Name, err) } } else if Exists(Nat, "OUTPUT", output...) && !enable { if err := c.Output(Delete, output...); err != nil { return fmt.Errorf("Failed to inject %s in OUTPUT chain: %s", c.Name, err) } } case Filter: if bridgeName == "" { return fmt.Errorf("Could not program chain %s/%s, missing bridge name", c.Table, c.Name) } link := []string{ "-o", bridgeName, "-j", c.Name} if !Exists(Filter, "FORWARD", link...) && enable { insert := append([]string{string(Insert), "FORWARD"}, link...) if output, err := Raw(insert...); err != nil { return err } else if len(output) != 0 { return fmt.Errorf("Could not create linking rule to %s/%s: %s", c.Table, c.Name, output) } } else if Exists(Filter, "FORWARD", link...) && !enable { del := append([]string{string(Delete), "FORWARD"}, link...) if output, err := Raw(del...); err != nil { return err } else if len(output) != 0 { return fmt.Errorf("Could not delete linking rule from %s/%s: %s", c.Table, c.Name, output) } } establish := []string{ "-o", bridgeName, "-m", "conntrack", "--ctstate", "RELATED,ESTABLISHED", "-j", "ACCEPT"} if !Exists(Filter, "FORWARD", establish...) && enable { insert := append([]string{string(Insert), "FORWARD"}, establish...) if output, err := Raw(insert...); err != nil { return err } else if len(output) != 0 { return fmt.Errorf("Could not create establish rule to %s: %s", c.Table, output) } } else if Exists(Filter, "FORWARD", establish...) && !enable { del := append([]string{string(Delete), "FORWARD"}, establish...) if output, err := Raw(del...); err != nil { return err } else if len(output) != 0 { return fmt.Errorf("Could not delete establish rule from %s: %s", c.Table, output) } } } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
iptables/iptables.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/iptables/iptables.go#L227-L236
go
train
// RemoveExistingChain removes existing chain from the table.
func RemoveExistingChain(name string, table Table) error
// RemoveExistingChain removes existing chain from the table. func RemoveExistingChain(name string, table Table) error
{ c := &ChainInfo{ Name: name, Table: table, } if string(c.Table) == "" { c.Table = Filter } return c.Remove() }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
iptables/iptables.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/iptables/iptables.go#L239-L305
go
train
// Forward adds forwarding rule to 'filter' table and corresponding nat rule to 'nat' table.
func (c *ChainInfo) Forward(action Action, ip net.IP, port int, proto, destAddr string, destPort int, bridgeName string) error
// Forward adds forwarding rule to 'filter' table and corresponding nat rule to 'nat' table. func (c *ChainInfo) Forward(action Action, ip net.IP, port int, proto, destAddr string, destPort int, bridgeName string) error
{ daddr := ip.String() if ip.IsUnspecified() { // iptables interprets "0.0.0.0" as "0.0.0.0/32", whereas we // want "0.0.0.0/0". "0/0" is correctly interpreted as "any // value" by both iptables and ip6tables. daddr = "0/0" } args := []string{ "-p", proto, "-d", daddr, "--dport", strconv.Itoa(port), "-j", "DNAT", "--to-destination", net.JoinHostPort(destAddr, strconv.Itoa(destPort))} if !c.HairpinMode { args = append(args, "!", "-i", bridgeName) } if err := ProgramRule(Nat, c.Name, action, args); err != nil { return err } args = []string{ "!", "-i", bridgeName, "-o", bridgeName, "-p", proto, "-d", destAddr, "--dport", strconv.Itoa(destPort), "-j", "ACCEPT", } if err := ProgramRule(Filter, c.Name, action, args); err != nil { return err } args = []string{ "-p", proto, "-s", destAddr, "-d", destAddr, "--dport", strconv.Itoa(destPort), "-j", "MASQUERADE", } if err := ProgramRule(Nat, "POSTROUTING", action, args); err != nil { return err } if proto == "sctp" { // Linux kernel v4.9 and below enables NETIF_F_SCTP_CRC for veth by // the following commit. // This introduces a problem when conbined with a physical NIC without // NETIF_F_SCTP_CRC. As for a workaround, here we add an iptables entry // to fill the checksum. // // https://github.com/torvalds/linux/commit/c80fafbbb59ef9924962f83aac85531039395b18 args = []string{ "-p", proto, "--sport", strconv.Itoa(destPort), "-j", "CHECKSUM", "--checksum-fill", } if err := ProgramRule(Mangle, "POSTROUTING", action, args); err != nil { return err } } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
iptables/iptables.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/iptables/iptables.go#L309-L326
go
train
// Link adds reciprocal ACCEPT rule for two supplied IP addresses. // Traffic is allowed from ip1 to ip2 and vice-versa
func (c *ChainInfo) Link(action Action, ip1, ip2 net.IP, port int, proto string, bridgeName string) error
// Link adds reciprocal ACCEPT rule for two supplied IP addresses. // Traffic is allowed from ip1 to ip2 and vice-versa func (c *ChainInfo) Link(action Action, ip1, ip2 net.IP, port int, proto string, bridgeName string) error
{ // forward args := []string{ "-i", bridgeName, "-o", bridgeName, "-p", proto, "-s", ip1.String(), "-d", ip2.String(), "--dport", strconv.Itoa(port), "-j", "ACCEPT", } if err := ProgramRule(Filter, c.Name, action, args); err != nil { return err } // reverse args[7], args[9] = args[9], args[7] args[10] = "--sport" return ProgramRule(Filter, c.Name, action, args) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
iptables/iptables.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/iptables/iptables.go#L331-L336
go
train
// ProgramRule adds the rule specified by args only if the // rule is not already present in the chain. Reciprocally, // it removes the rule only if present.
func ProgramRule(table Table, chain string, action Action, args []string) error
// ProgramRule adds the rule specified by args only if the // rule is not already present in the chain. Reciprocally, // it removes the rule only if present. func ProgramRule(table Table, chain string, action Action, args []string) error
{ if Exists(table, chain, args...) != (action == Delete) { return nil } return RawCombinedOutput(append([]string{"-t", string(table), string(action), chain}, args...)...) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
iptables/iptables.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/iptables/iptables.go#L339-L350
go
train
// Prerouting adds linking rule to nat/PREROUTING chain.
func (c *ChainInfo) Prerouting(action Action, args ...string) error
// Prerouting adds linking rule to nat/PREROUTING chain. func (c *ChainInfo) Prerouting(action Action, args ...string) error
{ a := []string{"-t", string(Nat), string(action), "PREROUTING"} if len(args) > 0 { a = append(a, args...) } if output, err := Raw(a...); err != nil { return err } else if len(output) != 0 { return ChainError{Chain: "PREROUTING", Output: output} } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
iptables/iptables.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/iptables/iptables.go#L367-L380
go
train
// Remove removes the chain.
func (c *ChainInfo) Remove() error
// Remove removes the chain. func (c *ChainInfo) Remove() error
{ // Ignore errors - This could mean the chains were never set up if c.Table == Nat { c.Prerouting(Delete, "-m", "addrtype", "--dst-type", "LOCAL", "-j", c.Name) c.Output(Delete, "-m", "addrtype", "--dst-type", "LOCAL", "!", "--dst", "127.0.0.0/8", "-j", c.Name) c.Output(Delete, "-m", "addrtype", "--dst-type", "LOCAL", "-j", c.Name) // Created in versions <= 0.1.6 c.Prerouting(Delete) c.Output(Delete) } Raw("-t", string(c.Table), "-F", c.Name) Raw("-t", string(c.Table), "-X", c.Name) return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
iptables/iptables.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/iptables/iptables.go#L383-L385
go
train
// Exists checks if a rule exists
func Exists(table Table, chain string, rule ...string) bool
// Exists checks if a rule exists func Exists(table Table, chain string, rule ...string) bool
{ return exists(false, table, chain, rule...) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
iptables/iptables.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/iptables/iptables.go#L389-L391
go
train
// ExistsNative behaves as Exists with the difference it // will always invoke `iptables` binary.
func ExistsNative(table Table, chain string, rule ...string) bool
// ExistsNative behaves as Exists with the difference it // will always invoke `iptables` binary. func ExistsNative(table Table, chain string, rule ...string) bool
{ return exists(true, table, chain, rule...) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
iptables/iptables.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/iptables/iptables.go#L447-L456
go
train
// Raw calls 'iptables' system command, passing supplied arguments.
func Raw(args ...string) ([]byte, error)
// Raw calls 'iptables' system command, passing supplied arguments. func Raw(args ...string) ([]byte, error)
{ if firewalldRunning { startTime := time.Now() output, err := Passthrough(Iptables, args...) if err == nil || !strings.Contains(err.Error(), "was not provided by any .service files") { return filterOutput(startTime, output, args...), err } } return raw(args...) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
iptables/iptables.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/iptables/iptables.go#L482-L487
go
train
// RawCombinedOutput internally calls the Raw function and returns a non nil // error if Raw returned a non nil error or a non empty output
func RawCombinedOutput(args ...string) error
// RawCombinedOutput internally calls the Raw function and returns a non nil // error if Raw returned a non nil error or a non empty output func RawCombinedOutput(args ...string) error
{ if output, err := Raw(args...); err != nil || len(output) != 0 { return fmt.Errorf("%s (%v)", string(output), err) } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
iptables/iptables.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/iptables/iptables.go#L491-L496
go
train
// RawCombinedOutputNative behave as RawCombinedOutput with the difference it // will always invoke `iptables` binary
func RawCombinedOutputNative(args ...string) error
// RawCombinedOutputNative behave as RawCombinedOutput with the difference it // will always invoke `iptables` binary func RawCombinedOutputNative(args ...string) error
{ if output, err := raw(args...); err != nil || len(output) != 0 { return fmt.Errorf("%s (%v)", string(output), err) } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
iptables/iptables.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/iptables/iptables.go#L499-L504
go
train
// ExistChain checks if a chain exists
func ExistChain(chain string, table Table) bool
// ExistChain checks if a chain exists func ExistChain(chain string, table Table) bool
{ if _, err := Raw("-t", string(table), "-nL", chain); err == nil { return true } return false }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
iptables/iptables.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/iptables/iptables.go#L507-L513
go
train
// GetVersion reads the iptables version numbers during initialization
func GetVersion() (major, minor, micro int, err error)
// GetVersion reads the iptables version numbers during initialization func GetVersion() (major, minor, micro int, err error)
{ out, err := exec.Command(iptablesPath, "--version").CombinedOutput() if err == nil { major, minor, micro = parseVersionNumbers(string(out)) } return }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
iptables/iptables.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/iptables/iptables.go#L516-L521
go
train
// SetDefaultPolicy sets the passed default policy for the table/chain
func SetDefaultPolicy(table Table, chain string, policy Policy) error
// SetDefaultPolicy sets the passed default policy for the table/chain func SetDefaultPolicy(table Table, chain string, policy Policy) error
{ if err := RawCombinedOutput("-t", string(table), "-P", chain, string(policy)); err != nil { return fmt.Errorf("setting default policy to %v in %v chain failed: %v", policy, chain, err) } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
iptables/iptables.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/iptables/iptables.go#L532-L534
go
train
// iptables -C, --check option was added in v.1.4.11 // http://ftp.netfilter.org/pub/iptables/changes-iptables-1.4.11.txt
func supportsCOption(mj, mn, mc int) bool
// iptables -C, --check option was added in v.1.4.11 // http://ftp.netfilter.org/pub/iptables/changes-iptables-1.4.11.txt func supportsCOption(mj, mn, mc int) bool
{ return mj > 1 || (mj == 1 && (mn > 4 || (mn == 4 && mc >= 11))) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
iptables/iptables.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/iptables/iptables.go#L537-L553
go
train
// AddReturnRule adds a return rule for the chain in the filter table
func AddReturnRule(chain string) error
// AddReturnRule adds a return rule for the chain in the filter table func AddReturnRule(chain string) error
{ var ( table = Filter args = []string{"-j", "RETURN"} ) if Exists(table, chain, args...) { return nil } err := RawCombinedOutput(append([]string{"-A", chain}, args...)...) if err != nil { return fmt.Errorf("unable to add return rule in %s chain: %s", chain, err.Error()) } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
iptables/iptables.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/iptables/iptables.go#L556-L575
go
train
// EnsureJumpRule ensures the jump rule is on top
func EnsureJumpRule(fromChain, toChain string) error
// EnsureJumpRule ensures the jump rule is on top func EnsureJumpRule(fromChain, toChain string) error
{ var ( table = Filter args = []string{"-j", toChain} ) if Exists(table, fromChain, args...) { err := RawCombinedOutput(append([]string{"-D", fromChain}, args...)...) if err != nil { return fmt.Errorf("unable to remove jump to %s rule in %s chain: %s", toChain, fromChain, err.Error()) } } err := RawCombinedOutput(append([]string{"-I", fromChain}, args...)...) if err != nil { return fmt.Errorf("unable to insert jump to %s rule in %s chain: %s", toChain, fromChain, err.Error()) } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
client/network.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/network.go#L31-L40
go
train
// CmdNetwork handles the root Network UI
func (cli *NetworkCli) CmdNetwork(chain string, args ...string) error
// CmdNetwork handles the root Network UI func (cli *NetworkCli) CmdNetwork(chain string, args ...string) error
{ cmd := cli.Subcmd(chain, "network", "COMMAND [OPTIONS] [arg...]", networkUsage(chain), false) cmd.Require(flag.Min, 1) err := cmd.ParseFlags(args, true) if err == nil { cmd.Usage() return fmt.Errorf("invalid command : %v", args) } return err }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
client/network.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/network.go#L43-L100
go
train
// CmdNetworkCreate handles Network Create UI
func (cli *NetworkCli) CmdNetworkCreate(chain string, args ...string) error
// CmdNetworkCreate handles Network Create UI func (cli *NetworkCli) CmdNetworkCreate(chain string, args ...string) error
{ cmd := cli.Subcmd(chain, "create", "NETWORK-NAME", "Creates a new network with a name specified by the user", false) flDriver := cmd.String([]string{"d", "-driver"}, "", "Driver to manage the Network") flID := cmd.String([]string{"-id"}, "", "Network ID string") flOpts := cmd.String([]string{"o", "-opt"}, "", "Network options") flInternal := cmd.Bool([]string{"-internal"}, false, "Config the network to be internal") flIPv6 := cmd.Bool([]string{"-ipv6"}, false, "Enable IPv6 on the network") flSubnet := cmd.String([]string{"-subnet"}, "", "Subnet option") flRange := cmd.String([]string{"-ip-range"}, "", "Range option") cmd.Require(flag.Exact, 1) err := cmd.ParseFlags(args, true) if err != nil { return err } networkOpts := make(map[string]string) if *flInternal { networkOpts[netlabel.Internal] = "true" } if *flIPv6 { networkOpts[netlabel.EnableIPv6] = "true" } driverOpts := make(map[string]string) if *flOpts != "" { opts := strings.Split(*flOpts, ",") for _, opt := range opts { driverOpts[netlabel.Key(opt)] = netlabel.Value(opt) } } var icList []ipamConf if *flSubnet != "" { ic := ipamConf{ PreferredPool: *flSubnet, } if *flRange != "" { ic.SubPool = *flRange } icList = append(icList, ic) } // Construct network create request body nc := networkCreate{Name: cmd.Arg(0), NetworkType: *flDriver, ID: *flID, IPv4Conf: icList, DriverOpts: driverOpts, NetworkOpts: networkOpts} obj, _, err := readBody(cli.call("POST", "/networks", nc, nil)) if err != nil { return err } var replyID string err = json.Unmarshal(obj, &replyID) if err != nil { return err } fmt.Fprintf(cli.out, "%s\n", replyID) return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
client/network.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/network.go#L103-L119
go
train
// CmdNetworkRm handles Network Delete UI
func (cli *NetworkCli) CmdNetworkRm(chain string, args ...string) error
// CmdNetworkRm handles Network Delete UI func (cli *NetworkCli) CmdNetworkRm(chain string, args ...string) error
{ cmd := cli.Subcmd(chain, "rm", "NETWORK", "Deletes a network", false) cmd.Require(flag.Exact, 1) err := cmd.ParseFlags(args, true) if err != nil { return err } id, err := lookupNetworkID(cli, cmd.Arg(0)) if err != nil { return err } _, _, err = readBody(cli.call("DELETE", "/networks/"+id, nil, nil)) if err != nil { return err } return nil }