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 | default_gateway.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/default_gateway.go#L32-L95 | go | train | /*
libnetwork creates a bridge network "docker_gw_bridge" for providing
default gateway for the containers if none of the container's endpoints
have GW set by the driver. ICC is set to false for the GW_bridge network.
If a driver can't provide external connectivity it can choose to not set
the GW IP for the endpoint.
endpoint on the GW_bridge network is managed dynamically by libnetwork.
ie:
- its created when an endpoint without GW joins the container
- its deleted when an endpoint with GW joins the container
*/ | func (sb *sandbox) setupDefaultGW() error | /*
libnetwork creates a bridge network "docker_gw_bridge" for providing
default gateway for the containers if none of the container's endpoints
have GW set by the driver. ICC is set to false for the GW_bridge network.
If a driver can't provide external connectivity it can choose to not set
the GW IP for the endpoint.
endpoint on the GW_bridge network is managed dynamically by libnetwork.
ie:
- its created when an endpoint without GW joins the container
- its deleted when an endpoint with GW joins the container
*/
func (sb *sandbox) setupDefaultGW() error | {
// check if the container already has a GW endpoint
if ep := sb.getEndpointInGWNetwork(); ep != nil {
return nil
}
c := sb.controller
// Look for default gw network. In case of error (includes not found),
// retry and create it if needed in a serialized execution.
n, err := c.NetworkByName(libnGWNetwork)
if err != nil {
if n, err = c.defaultGwNetwork(); err != nil {
return err
}
}
createOptions := []EndpointOption{CreateOptionAnonymous()}
var gwName string
if len(sb.containerID) <= gwEPlen {
gwName = "gateway_" + sb.containerID
} else {
gwName = "gateway_" + sb.id[:gwEPlen]
}
sbLabels := sb.Labels()
if sbLabels[netlabel.PortMap] != nil {
createOptions = append(createOptions, CreateOptionPortMapping(sbLabels[netlabel.PortMap].([]types.PortBinding)))
}
if sbLabels[netlabel.ExposedPorts] != nil {
createOptions = append(createOptions, CreateOptionExposedPorts(sbLabels[netlabel.ExposedPorts].([]types.TransportPort)))
}
epOption := getPlatformOption()
if epOption != nil {
createOptions = append(createOptions, epOption)
}
newEp, err := n.CreateEndpoint(gwName, createOptions...)
if err != nil {
return fmt.Errorf("container %s: endpoint create on GW Network failed: %v", sb.containerID, err)
}
defer func() {
if err != nil {
if err2 := newEp.Delete(true); err2 != nil {
logrus.Warnf("Failed to remove gw endpoint for container %s after failing to join the gateway network: %v",
sb.containerID, err2)
}
}
}()
epLocal := newEp.(*endpoint)
if err = epLocal.sbJoin(sb); err != nil {
return fmt.Errorf("container %s: endpoint join on GW Network failed: %v", sb.containerID, err)
}
return nil
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | default_gateway.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/default_gateway.go#L98-L111 | go | train | // If present, detach and remove the endpoint connecting the sandbox to the default gw network. | func (sb *sandbox) clearDefaultGW() error | // If present, detach and remove the endpoint connecting the sandbox to the default gw network.
func (sb *sandbox) clearDefaultGW() error | {
var ep *endpoint
if ep = sb.getEndpointInGWNetwork(); ep == nil {
return nil
}
if err := ep.sbLeave(sb, false); err != nil {
return fmt.Errorf("container %s: endpoint leaving GW Network failed: %v", sb.containerID, err)
}
if err := ep.Delete(false); err != nil {
return fmt.Errorf("container %s: deleting endpoint on GW Network failed: %v", sb.containerID, err)
}
return nil
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | default_gateway.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/default_gateway.go#L117-L147 | go | train | // Evaluate whether the sandbox requires a default gateway based
// on the endpoints to which it is connected. It does not account
// for the default gateway network endpoint. | func (sb *sandbox) needDefaultGW() bool | // Evaluate whether the sandbox requires a default gateway based
// on the endpoints to which it is connected. It does not account
// for the default gateway network endpoint.
func (sb *sandbox) needDefaultGW() bool | {
var needGW bool
for _, ep := range sb.getConnectedEndpoints() {
if ep.endpointInGWNetwork() {
continue
}
if ep.getNetwork().Type() == "null" || ep.getNetwork().Type() == "host" {
continue
}
if ep.getNetwork().Internal() {
continue
}
// During stale sandbox cleanup, joinInfo may be nil
if ep.joinInfo != nil && ep.joinInfo.disableGatewayService {
continue
}
// TODO v6 needs to be handled.
if len(ep.Gateway()) > 0 {
return false
}
for _, r := range ep.StaticRoutes() {
if r.Destination != nil && r.Destination.String() == "0.0.0.0/0" {
return false
}
}
needGW = true
}
return needGW
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | default_gateway.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/default_gateway.go#L179-L188 | go | train | // Looks for the default gw network and creates it if not there.
// Parallel executions are serialized. | func (c *controller) defaultGwNetwork() (Network, error) | // Looks for the default gw network and creates it if not there.
// Parallel executions are serialized.
func (c *controller) defaultGwNetwork() (Network, error) | {
procGwNetwork <- true
defer func() { <-procGwNetwork }()
n, err := c.NetworkByName(libnGWNetwork)
if _, ok := err.(types.NotFoundError); ok {
n, err = c.createGWNetwork()
}
return n, err
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | default_gateway.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/default_gateway.go#L191-L201 | go | train | // Returns the endpoint which is providing external connectivity to the sandbox | func (sb *sandbox) getGatewayEndpoint() *endpoint | // Returns the endpoint which is providing external connectivity to the sandbox
func (sb *sandbox) getGatewayEndpoint() *endpoint | {
for _, ep := range sb.getConnectedEndpoints() {
if ep.getNetwork().Type() == "null" || ep.getNetwork().Type() == "host" {
continue
}
if len(ep.Gateway()) != 0 {
return ep
}
}
return nil
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | drivers/macvlan/macvlan_joinleave.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/macvlan/macvlan_joinleave.go#L15-L84 | 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 | {
defer osl.InitOSContext()()
n, err := d.getNetwork(nid)
if err != nil {
return err
}
endpoint := n.endpoint(eid)
if endpoint == nil {
return fmt.Errorf("could not find endpoint with id %s", eid)
}
// generate a name for the iface that will be renamed to eth0 in the sbox
containerIfName, err := netutils.GenerateIfaceName(ns.NlHandle(), vethPrefix, vethLen)
if err != nil {
return fmt.Errorf("error generating an interface name: %s", err)
}
// create the netlink macvlan interface
vethName, err := createMacVlan(containerIfName, n.config.Parent, n.config.MacvlanMode)
if err != nil {
return err
}
// bind the generated iface name to the endpoint
endpoint.srcName = vethName
ep := n.endpoint(eid)
if ep == nil {
return fmt.Errorf("could not find endpoint with id %s", eid)
}
// parse and match the endpoint address with the available v4 subnets
if len(n.config.Ipv4Subnets) > 0 {
s := n.getSubnetforIPv4(ep.addr)
if s == nil {
return fmt.Errorf("could not find a valid ipv4 subnet for endpoint %s", eid)
}
v4gw, _, err := net.ParseCIDR(s.GwIP)
if err != nil {
return fmt.Errorf("gateway %s is not a valid ipv4 address: %v", s.GwIP, err)
}
err = jinfo.SetGateway(v4gw)
if err != nil {
return err
}
logrus.Debugf("Macvlan Endpoint Joined with IPv4_Addr: %s, Gateway: %s, MacVlan_Mode: %s, Parent: %s",
ep.addr.IP.String(), v4gw.String(), n.config.MacvlanMode, n.config.Parent)
}
// parse and match the endpoint address with the available v6 subnets
if len(n.config.Ipv6Subnets) > 0 {
s := n.getSubnetforIPv6(ep.addrv6)
if s == nil {
return fmt.Errorf("could not find a valid ipv6 subnet for endpoint %s", eid)
}
v6gw, _, err := net.ParseCIDR(s.GwIP)
if err != nil {
return fmt.Errorf("gateway %s is not a valid ipv6 address: %v", s.GwIP, err)
}
err = jinfo.SetGatewayIPv6(v6gw)
if err != nil {
return err
}
logrus.Debugf("Macvlan Endpoint Joined with IPv6_Addr: %s Gateway: %s MacVlan_Mode: %s, Parent: %s",
ep.addrv6.IP.String(), v6gw.String(), n.config.MacvlanMode, n.config.Parent)
}
iNames := jinfo.InterfaceName()
err = iNames.SetNames(vethName, containerVethPrefix)
if err != nil {
return err
}
if err := d.storeUpdate(ep); err != nil {
return fmt.Errorf("failed to save macvlan endpoint %.7s to store: %v", ep.id, err)
}
return nil
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | netutils/utils.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/netutils/utils.go#L27-L40 | go | train | // CheckNameserverOverlaps checks whether the passed network overlaps with any of the nameservers | func CheckNameserverOverlaps(nameservers []string, toCheck *net.IPNet) error | // CheckNameserverOverlaps checks whether the passed network overlaps with any of the nameservers
func CheckNameserverOverlaps(nameservers []string, toCheck *net.IPNet) error | {
if len(nameservers) > 0 {
for _, ns := range nameservers {
_, nsNetwork, err := net.ParseCIDR(ns)
if err != nil {
return err
}
if NetworkOverlaps(toCheck, nsNetwork) {
return ErrNetworkOverlapsWithNameservers
}
}
}
return nil
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | netutils/utils.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/netutils/utils.go#L43-L45 | go | train | // NetworkOverlaps detects overlap between one IPNet and another | func NetworkOverlaps(netX *net.IPNet, netY *net.IPNet) bool | // NetworkOverlaps detects overlap between one IPNet and another
func NetworkOverlaps(netX *net.IPNet, netY *net.IPNet) bool | {
return netX.Contains(netY.IP) || netY.Contains(netX.IP)
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | netutils/utils.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/netutils/utils.go#L48-L65 | go | train | // NetworkRange calculates the first and last IP addresses in an IPNet | func NetworkRange(network *net.IPNet) (net.IP, net.IP) | // NetworkRange calculates the first and last IP addresses in an IPNet
func NetworkRange(network *net.IPNet) (net.IP, net.IP) | {
if network == nil {
return nil, nil
}
firstIP := network.IP.Mask(network.Mask)
lastIP := types.GetIPCopy(firstIP)
for i := 0; i < len(firstIP); i++ {
lastIP[i] = firstIP[i] | ^network.Mask[i]
}
if network.IP.To4() != nil {
firstIP = firstIP.To4()
lastIP = lastIP.To4()
}
return firstIP, lastIP
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | netutils/utils.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/netutils/utils.go#L68-L95 | go | train | // GetIfaceAddr returns the first IPv4 address and slice of IPv6 addresses for the specified network interface | func GetIfaceAddr(name string) (net.Addr, []net.Addr, error) | // GetIfaceAddr returns the first IPv4 address and slice of IPv6 addresses for the specified network interface
func GetIfaceAddr(name string) (net.Addr, []net.Addr, error) | {
iface, err := net.InterfaceByName(name)
if err != nil {
return nil, nil, err
}
addrs, err := iface.Addrs()
if err != nil {
return nil, nil, err
}
var addrs4 []net.Addr
var addrs6 []net.Addr
for _, addr := range addrs {
ip := (addr.(*net.IPNet)).IP
if ip4 := ip.To4(); ip4 != nil {
addrs4 = append(addrs4, addr)
} else if ip6 := ip.To16(); len(ip6) == net.IPv6len {
addrs6 = append(addrs6, addr)
}
}
switch {
case len(addrs4) == 0:
return nil, nil, fmt.Errorf("Interface %v has no IPv4 addresses", name)
case len(addrs4) > 1:
fmt.Printf("Interface %v has more than 1 IPv4 address. Defaulting to using %v\n",
name, (addrs4[0].(*net.IPNet)).IP)
}
return addrs4[0], addrs6, nil
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | netutils/utils.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/netutils/utils.go#L129-L135 | go | train | // GenerateRandomName returns a new name joined with a prefix. This size
// specified is used to truncate the randomly generated value | func GenerateRandomName(prefix string, size int) (string, error) | // GenerateRandomName returns a new name joined with a prefix. This size
// specified is used to truncate the randomly generated value
func GenerateRandomName(prefix string, size int) (string, error) | {
id := make([]byte, 32)
if _, err := io.ReadFull(rand.Reader, id); err != nil {
return "", err
}
return prefix + hex.EncodeToString(id)[:size], nil
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | netutils/utils.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/netutils/utils.go#L140-L171 | go | train | // ReverseIP accepts a V4 or V6 IP string in the canonical form and returns a reversed IP in
// the dotted decimal form . This is used to setup the IP to service name mapping in the optimal
// way for the DNS PTR queries. | func ReverseIP(IP string) string | // ReverseIP accepts a V4 or V6 IP string in the canonical form and returns a reversed IP in
// the dotted decimal form . This is used to setup the IP to service name mapping in the optimal
// way for the DNS PTR queries.
func ReverseIP(IP string) string | {
var reverseIP []string
if net.ParseIP(IP).To4() != nil {
reverseIP = strings.Split(IP, ".")
l := len(reverseIP)
for i, j := 0, l-1; i < l/2; i, j = i+1, j-1 {
reverseIP[i], reverseIP[j] = reverseIP[j], reverseIP[i]
}
} else {
reverseIP = strings.Split(IP, ":")
// Reversed IPv6 is represented in dotted decimal instead of the typical
// colon hex notation
for key := range reverseIP {
if len(reverseIP[key]) == 0 { // expand the compressed 0s
reverseIP[key] = strings.Repeat("0000", 8-strings.Count(IP, ":"))
} else if len(reverseIP[key]) < 4 { // 0-padding needed
reverseIP[key] = strings.Repeat("0", 4-len(reverseIP[key])) + reverseIP[key]
}
}
reverseIP = strings.Split(strings.Join(reverseIP, ""), "")
l := len(reverseIP)
for i, j := 0, l-1; i < l/2; i, j = i+1, j-1 {
reverseIP[i], reverseIP[j] = reverseIP[j], reverseIP[i]
}
}
return strings.Join(reverseIP, ".")
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | netutils/utils.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/netutils/utils.go#L174-L186 | go | train | // ParseAlias parses and validates the specified string as an alias format (name:alias) | func ParseAlias(val string) (string, string, error) | // ParseAlias parses and validates the specified string as an alias format (name:alias)
func ParseAlias(val string) (string, string, error) | {
if val == "" {
return "", "", errors.New("empty string specified for alias")
}
arr := strings.Split(val, ":")
if len(arr) > 2 {
return "", "", fmt.Errorf("bad format for alias: %s", val)
}
if len(arr) == 1 {
return val, val, nil
}
return arr[0], arr[1], nil
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | netutils/utils.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/netutils/utils.go#L189-L194 | go | train | // ValidateAlias validates that the specified string has a valid alias format (containerName:alias). | func ValidateAlias(val string) (string, error) | // ValidateAlias validates that the specified string has a valid alias format (containerName:alias).
func ValidateAlias(val string) (string, error) | {
if _, _, err := ParseAlias(val); err != nil {
return val, err
}
return val, nil
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | ipvs/netlink.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipvs/netlink.go#L277-L312 | go | train | // parseStats | func assembleStats(msg []byte) (SvcStats, error) | // parseStats
func assembleStats(msg []byte) (SvcStats, error) | {
var s SvcStats
attrs, err := nl.ParseRouteAttr(msg)
if err != nil {
return s, err
}
for _, attr := range attrs {
attrType := int(attr.Attr.Type)
switch attrType {
case ipvsSvcStatsConns:
s.Connections = native.Uint32(attr.Value)
case ipvsSvcStatsPktsIn:
s.PacketsIn = native.Uint32(attr.Value)
case ipvsSvcStatsPktsOut:
s.PacketsOut = native.Uint32(attr.Value)
case ipvsSvcStatsBytesIn:
s.BytesIn = native.Uint64(attr.Value)
case ipvsSvcStatsBytesOut:
s.BytesOut = native.Uint64(attr.Value)
case ipvsSvcStatsCPS:
s.CPS = native.Uint32(attr.Value)
case ipvsSvcStatsPPSIn:
s.PPSIn = native.Uint32(attr.Value)
case ipvsSvcStatsPPSOut:
s.PPSOut = native.Uint32(attr.Value)
case ipvsSvcStatsBPSIn:
s.BPSIn = native.Uint32(attr.Value)
case ipvsSvcStatsBPSOut:
s.BPSOut = native.Uint32(attr.Value)
}
}
return s, nil
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | ipvs/netlink.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipvs/netlink.go#L315-L357 | go | train | // assembleService assembles a services back from a hain of netlink attributes | func assembleService(attrs []syscall.NetlinkRouteAttr) (*Service, error) | // assembleService assembles a services back from a hain of netlink attributes
func assembleService(attrs []syscall.NetlinkRouteAttr) (*Service, error) | {
var s Service
for _, attr := range attrs {
attrType := int(attr.Attr.Type)
switch attrType {
case ipvsSvcAttrAddressFamily:
s.AddressFamily = native.Uint16(attr.Value)
case ipvsSvcAttrProtocol:
s.Protocol = native.Uint16(attr.Value)
case ipvsSvcAttrAddress:
ip, err := parseIP(attr.Value, s.AddressFamily)
if err != nil {
return nil, err
}
s.Address = ip
case ipvsSvcAttrPort:
s.Port = binary.BigEndian.Uint16(attr.Value)
case ipvsSvcAttrFWMark:
s.FWMark = native.Uint32(attr.Value)
case ipvsSvcAttrSchedName:
s.SchedName = nl.BytesToString(attr.Value)
case ipvsSvcAttrFlags:
s.Flags = native.Uint32(attr.Value)
case ipvsSvcAttrTimeout:
s.Timeout = native.Uint32(attr.Value)
case ipvsSvcAttrNetmask:
s.Netmask = native.Uint32(attr.Value)
case ipvsSvcAttrStats:
stats, err := assembleStats(attr.Value)
if err != nil {
return nil, err
}
s.Stats = stats
}
}
return &s, nil
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | ipvs/netlink.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipvs/netlink.go#L360-L387 | go | train | // parseService given a ipvs netlink response this function will respond with a valid service entry, an error otherwise | func (i *Handle) parseService(msg []byte) (*Service, error) | // parseService given a ipvs netlink response this function will respond with a valid service entry, an error otherwise
func (i *Handle) parseService(msg []byte) (*Service, error) | {
var s *Service
//Remove General header for this message and parse the NetLink message
hdr := deserializeGenlMsg(msg)
NetLinkAttrs, err := nl.ParseRouteAttr(msg[hdr.Len():])
if err != nil {
return nil, err
}
if len(NetLinkAttrs) == 0 {
return nil, fmt.Errorf("error no valid netlink message found while parsing service record")
}
//Now Parse and get IPVS related attributes messages packed in this message.
ipvsAttrs, err := nl.ParseRouteAttr(NetLinkAttrs[0].Value)
if err != nil {
return nil, err
}
//Assemble all the IPVS related attribute messages and create a service record
s, err = assembleService(ipvsAttrs)
if err != nil {
return nil, err
}
return s, nil
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | ipvs/netlink.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipvs/netlink.go#L390-L407 | go | train | // doGetServicesCmd a wrapper which could be used commonly for both GetServices() and GetService(*Service) | func (i *Handle) doGetServicesCmd(svc *Service) ([]*Service, error) | // doGetServicesCmd a wrapper which could be used commonly for both GetServices() and GetService(*Service)
func (i *Handle) doGetServicesCmd(svc *Service) ([]*Service, error) | {
var res []*Service
msgs, err := i.doCmdwithResponse(svc, nil, ipvsCmdGetService)
if err != nil {
return nil, err
}
for _, msg := range msgs {
srv, err := i.parseService(msg)
if err != nil {
return nil, err
}
res = append(res, srv)
}
return res, nil
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | ipvs/netlink.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipvs/netlink.go#L410-L414 | go | train | // doCmdWithoutAttr a simple wrapper of netlink socket execute command | func (i *Handle) doCmdWithoutAttr(cmd uint8) ([][]byte, error) | // doCmdWithoutAttr a simple wrapper of netlink socket execute command
func (i *Handle) doCmdWithoutAttr(cmd uint8) ([][]byte, error) | {
req := newIPVSRequest(cmd)
req.Seq = atomic.AddUint32(&i.seq, 1)
return execute(i.sock, req, 0)
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | ipvs/netlink.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipvs/netlink.go#L459-L485 | go | train | // parseDestination given a ipvs netlink response this function will respond with a valid destination entry, an error otherwise | func (i *Handle) parseDestination(msg []byte) (*Destination, error) | // parseDestination given a ipvs netlink response this function will respond with a valid destination entry, an error otherwise
func (i *Handle) parseDestination(msg []byte) (*Destination, error) | {
var dst *Destination
//Remove General header for this message
hdr := deserializeGenlMsg(msg)
NetLinkAttrs, err := nl.ParseRouteAttr(msg[hdr.Len():])
if err != nil {
return nil, err
}
if len(NetLinkAttrs) == 0 {
return nil, fmt.Errorf("error no valid netlink message found while parsing destination record")
}
//Now Parse and get IPVS related attributes messages packed in this message.
ipvsAttrs, err := nl.ParseRouteAttr(NetLinkAttrs[0].Value)
if err != nil {
return nil, err
}
//Assemble netlink attributes and create a Destination record
dst, err = assembleDestination(ipvsAttrs)
if err != nil {
return nil, err
}
return dst, nil
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | ipvs/netlink.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipvs/netlink.go#L488-L505 | go | train | // doGetDestinationsCmd a wrapper function to be used by GetDestinations and GetDestination(d) apis | func (i *Handle) doGetDestinationsCmd(s *Service, d *Destination) ([]*Destination, error) | // doGetDestinationsCmd a wrapper function to be used by GetDestinations and GetDestination(d) apis
func (i *Handle) doGetDestinationsCmd(s *Service, d *Destination) ([]*Destination, error) | {
var res []*Destination
msgs, err := i.doCmdwithResponse(s, d, ipvsCmdGetDest)
if err != nil {
return nil, err
}
for _, msg := range msgs {
dest, err := i.parseDestination(msg)
if err != nil {
return res, err
}
res = append(res, dest)
}
return res, nil
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | ipvs/netlink.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipvs/netlink.go#L508-L531 | go | train | // parseConfig given a ipvs netlink response this function will respond with a valid config entry, an error otherwise | func (i *Handle) parseConfig(msg []byte) (*Config, error) | // parseConfig given a ipvs netlink response this function will respond with a valid config entry, an error otherwise
func (i *Handle) parseConfig(msg []byte) (*Config, error) | {
var c Config
//Remove General header for this message
hdr := deserializeGenlMsg(msg)
attrs, err := nl.ParseRouteAttr(msg[hdr.Len():])
if err != nil {
return nil, err
}
for _, attr := range attrs {
attrType := int(attr.Attr.Type)
switch attrType {
case ipvsCmdAttrTimeoutTCP:
c.TimeoutTCP = time.Duration(native.Uint32(attr.Value)) * time.Second
case ipvsCmdAttrTimeoutTCPFin:
c.TimeoutTCPFin = time.Duration(native.Uint32(attr.Value)) * time.Second
case ipvsCmdAttrTimeoutUDP:
c.TimeoutUDP = time.Duration(native.Uint32(attr.Value)) * time.Second
}
}
return &c, nil
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | ipvs/netlink.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipvs/netlink.go#L534-L545 | go | train | // doGetConfigCmd a wrapper function to be used by GetConfig | func (i *Handle) doGetConfigCmd() (*Config, error) | // doGetConfigCmd a wrapper function to be used by GetConfig
func (i *Handle) doGetConfigCmd() (*Config, error) | {
msg, err := i.doCmdWithoutAttr(ipvsCmdGetConfig)
if err != nil {
return nil, err
}
res, err := i.parseConfig(msg[0])
if err != nil {
return res, err
}
return res, nil
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | ipvs/netlink.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipvs/netlink.go#L548-L559 | go | train | // doSetConfigCmd a wrapper function to be used by SetConfig | func (i *Handle) doSetConfigCmd(c *Config) error | // doSetConfigCmd a wrapper function to be used by SetConfig
func (i *Handle) doSetConfigCmd(c *Config) error | {
req := newIPVSRequest(ipvsCmdSetConfig)
req.Seq = atomic.AddUint32(&i.seq, 1)
req.AddData(nl.NewRtAttr(ipvsCmdAttrTimeoutTCP, nl.Uint32Attr(uint32(c.TimeoutTCP.Seconds()))))
req.AddData(nl.NewRtAttr(ipvsCmdAttrTimeoutTCPFin, nl.Uint32Attr(uint32(c.TimeoutTCPFin.Seconds()))))
req.AddData(nl.NewRtAttr(ipvsCmdAttrTimeoutUDP, nl.Uint32Attr(uint32(c.TimeoutUDP.Seconds()))))
_, err := execute(i.sock, req, 0)
return err
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | drivers/bridge/setup_ip_tables.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/bridge/setup_ip_tables.go#L282-L315 | go | train | // Control Inter Network Communication. Install[Remove] only if it is [not] present. | func setINC(iface string, enable bool) error | // Control Inter Network Communication. Install[Remove] only if it is [not] present.
func setINC(iface string, enable bool) error | {
var (
action = iptables.Insert
actionMsg = "add"
chains = []string{IsolationChain1, IsolationChain2}
rules = [][]string{
{"-i", iface, "!", "-o", iface, "-j", IsolationChain2},
{"-o", iface, "-j", "DROP"},
}
)
if !enable {
action = iptables.Delete
actionMsg = "remove"
}
for i, chain := range chains {
if err := iptables.ProgramRule(iptables.Filter, chain, action, rules[i]); err != nil {
msg := fmt.Sprintf("unable to %s inter-network communication rule: %v", actionMsg, err)
if enable {
if i == 1 {
// Rollback the rule installed on first chain
if err2 := iptables.ProgramRule(iptables.Filter, chains[0], iptables.Delete, rules[0]); err2 != nil {
logrus.Warn("Failed to rollback iptables rule after failure (%v): %v", err, err2)
}
}
return fmt.Errorf(msg)
}
logrus.Warn(msg)
}
}
return nil
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | drivers/bridge/setup_device.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/bridge/setup_device.go#L13-L51 | go | train | // SetupDevice create a new bridge interface/ | func setupDevice(config *networkConfiguration, i *bridgeInterface) error | // SetupDevice create a new bridge interface/
func setupDevice(config *networkConfiguration, i *bridgeInterface) error | {
var setMac bool
// We only attempt to create the bridge when the requested device name is
// the default one.
if config.BridgeName != DefaultBridgeName && config.DefaultBridge {
return NonDefaultBridgeExistError(config.BridgeName)
}
// Set the bridgeInterface netlink.Bridge.
i.Link = &netlink.Bridge{
LinkAttrs: netlink.LinkAttrs{
Name: config.BridgeName,
},
}
// Only set the bridge's MAC address if the kernel version is > 3.3, as it
// was not supported before that.
kv, err := kernel.GetKernelVersion()
if err != nil {
logrus.Errorf("Failed to check kernel versions: %v. Will not assign a MAC address to the bridge interface", err)
} else {
setMac = kv.Kernel > 3 || (kv.Kernel == 3 && kv.Major >= 3)
}
if err = i.nlh.LinkAdd(i.Link); err != nil {
logrus.Debugf("Failed to create bridge %s via netlink. Trying ioctl", config.BridgeName)
return ioctlCreateBridge(config.BridgeName, setMac)
}
if setMac {
hwAddr := netutils.GenerateRandomMAC()
if err = i.nlh.LinkSetHardwareAddr(i.Link, hwAddr); err != nil {
return fmt.Errorf("failed to set bridge mac-address %s : %s", hwAddr, err.Error())
}
logrus.Debugf("Setting bridge mac address to %s", hwAddr)
}
return err
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | drivers/bridge/setup_device.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/bridge/setup_device.go#L54-L68 | go | train | // SetupDeviceUp ups the given bridge interface. | func setupDeviceUp(config *networkConfiguration, i *bridgeInterface) error | // SetupDeviceUp ups the given bridge interface.
func setupDeviceUp(config *networkConfiguration, i *bridgeInterface) error | {
err := i.nlh.LinkSetUp(i.Link)
if err != nil {
return fmt.Errorf("Failed to set link up for %s: %v", config.BridgeName, err)
}
// Attempt to update the bridge interface to refresh the flags status,
// ignoring any failure to do so.
if lnk, err := i.nlh.LinkByName(config.BridgeName); err == nil {
i.Link = lnk
} else {
logrus.Warnf("Failed to retrieve link for interface (%s): %v", config.BridgeName, err)
}
return nil
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | portallocator/portallocator.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/portallocator/portallocator.go#L54-L56 | go | train | // IPPort returns the address and the port in the form ip:port | func (e ErrPortAlreadyAllocated) IPPort() string | // IPPort returns the address and the port in the form ip:port
func (e ErrPortAlreadyAllocated) IPPort() string | {
return fmt.Sprintf("%s:%d", e.ip, e.port)
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | portallocator/portallocator.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/portallocator/portallocator.go#L59-L61 | go | train | // Error is the implementation of error.Error interface | func (e ErrPortAlreadyAllocated) Error() string | // Error is the implementation of error.Error interface
func (e ErrPortAlreadyAllocated) Error() string | {
return fmt.Sprintf("Bind for %s:%d failed: port is already allocated", e.ip, e.port)
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | portallocator/portallocator.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/portallocator/portallocator.go#L110-L112 | go | train | // RequestPort requests new port from global ports pool for specified ip and proto.
// If port is 0 it returns first free port. Otherwise it checks port availability
// in proto's pool and returns that port or error if port is already busy. | func (p *PortAllocator) RequestPort(ip net.IP, proto string, port int) (int, error) | // RequestPort requests new port from global ports pool for specified ip and proto.
// If port is 0 it returns first free port. Otherwise it checks port availability
// in proto's pool and returns that port or error if port is already busy.
func (p *PortAllocator) RequestPort(ip net.IP, proto string, port int) (int, error) | {
return p.RequestPortInRange(ip, proto, port, port)
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | portallocator/portallocator.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/portallocator/portallocator.go#L119-L155 | go | train | // RequestPortInRange requests new port from global ports pool for specified ip and proto.
// If portStart and portEnd are 0 it returns the first free port in the default ephemeral range.
// If portStart != portEnd it returns the first free port in the requested range.
// Otherwise (portStart == portEnd) it checks port availability in the requested proto's port-pool
// and returns that port or error if port is already busy. | func (p *PortAllocator) RequestPortInRange(ip net.IP, proto string, portStart, portEnd int) (int, error) | // RequestPortInRange requests new port from global ports pool for specified ip and proto.
// If portStart and portEnd are 0 it returns the first free port in the default ephemeral range.
// If portStart != portEnd it returns the first free port in the requested range.
// Otherwise (portStart == portEnd) it checks port availability in the requested proto's port-pool
// and returns that port or error if port is already busy.
func (p *PortAllocator) RequestPortInRange(ip net.IP, proto string, portStart, portEnd int) (int, error) | {
p.mutex.Lock()
defer p.mutex.Unlock()
if proto != "tcp" && proto != "udp" && proto != "sctp" {
return 0, ErrUnknownProtocol
}
if ip == nil {
ip = defaultIP
}
ipstr := ip.String()
protomap, ok := p.ipMap[ipstr]
if !ok {
protomap = protoMap{
"tcp": p.newPortMap(),
"udp": p.newPortMap(),
"sctp": p.newPortMap(),
}
p.ipMap[ipstr] = protomap
}
mapping := protomap[proto]
if portStart > 0 && portStart == portEnd {
if _, ok := mapping.p[portStart]; !ok {
mapping.p[portStart] = struct{}{}
return portStart, nil
}
return 0, newErrPortAlreadyAllocated(ipstr, portStart)
}
port, err := mapping.findPort(portStart, portEnd)
if err != nil {
return 0, err
}
return port, nil
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | portallocator/portallocator.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/portallocator/portallocator.go#L158-L171 | go | train | // ReleasePort releases port from global ports pool for specified ip and proto. | func (p *PortAllocator) ReleasePort(ip net.IP, proto string, port int) error | // ReleasePort releases port from global ports pool for specified ip and proto.
func (p *PortAllocator) ReleasePort(ip net.IP, proto string, port int) error | {
p.mutex.Lock()
defer p.mutex.Unlock()
if ip == nil {
ip = defaultIP
}
protomap, ok := p.ipMap[ip.String()]
if !ok {
return nil
}
delete(protomap[proto].p, port)
return nil
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | portallocator/portallocator.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/portallocator/portallocator.go#L186-L191 | go | train | // ReleaseAll releases all ports for all ips. | func (p *PortAllocator) ReleaseAll() error | // ReleaseAll releases all ports for all ips.
func (p *PortAllocator) ReleaseAll() error | {
p.mutex.Lock()
p.ipMap = ipMapping{}
p.mutex.Unlock()
return nil
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | drivers/macvlan/macvlan_setup.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/macvlan/macvlan_setup.go#L20-L49 | go | train | // Create the macvlan slave specifying the source name | func createMacVlan(containerIfName, parent, macvlanMode string) (string, error) | // Create the macvlan slave specifying the source name
func createMacVlan(containerIfName, parent, macvlanMode string) (string, error) | {
// Set the macvlan mode. Default is bridge mode
mode, err := setMacVlanMode(macvlanMode)
if err != nil {
return "", fmt.Errorf("Unsupported %s macvlan mode: %v", macvlanMode, err)
}
// verify the Docker host interface acting as the macvlan parent iface exists
if !parentExists(parent) {
return "", fmt.Errorf("the requested parent interface %s was not found on the Docker host", parent)
}
// Get the link for the master index (Example: the docker host eth iface)
parentLink, err := ns.NlHandle().LinkByName(parent)
if err != nil {
return "", fmt.Errorf("error occurred looking up the %s parent iface %s error: %s", macvlanType, parent, err)
}
// Create a macvlan link
macvlan := &netlink.Macvlan{
LinkAttrs: netlink.LinkAttrs{
Name: containerIfName,
ParentIndex: parentLink.Attrs().Index,
},
Mode: mode,
}
if err := ns.NlHandle().LinkAdd(macvlan); err != nil {
// If a user creates a macvlan and ipvlan on same parent, only one slave iface can be active at a time.
return "", fmt.Errorf("failed to create the %s port: %v", macvlanType, err)
}
return macvlan.Attrs().Name, nil
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | drivers/macvlan/macvlan_setup.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/macvlan/macvlan_setup.go#L52-L65 | go | train | // setMacVlanMode setter for one of the four macvlan port types | func setMacVlanMode(mode string) (netlink.MacvlanMode, error) | // setMacVlanMode setter for one of the four macvlan port types
func setMacVlanMode(mode string) (netlink.MacvlanMode, error) | {
switch mode {
case modePrivate:
return netlink.MACVLAN_MODE_PRIVATE, nil
case modeVepa:
return netlink.MACVLAN_MODE_VEPA, nil
case modeBridge:
return netlink.MACVLAN_MODE_BRIDGE, nil
case modePassthru:
return netlink.MACVLAN_MODE_PASSTHRU, nil
default:
return 0, fmt.Errorf("unknown macvlan mode: %s", mode)
}
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | drivers/macvlan/macvlan_setup.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/macvlan/macvlan_setup.go#L116-L140 | go | train | // delVlanLink verifies only sub-interfaces with a vlan id get deleted | func delVlanLink(linkName string) error | // delVlanLink verifies only sub-interfaces with a vlan id get deleted
func delVlanLink(linkName string) error | {
if strings.Contains(linkName, ".") {
_, _, err := parseVlan(linkName)
if err != nil {
return err
}
// delete the vlan subinterface
vlanLink, err := ns.NlHandle().LinkByName(linkName)
if err != nil {
return fmt.Errorf("failed to find interface %s on the Docker host : %v", linkName, err)
}
// verify a parent interface isn't being deleted
if vlanLink.Attrs().ParentIndex == 0 {
return fmt.Errorf("interface %s does not appear to be a slave device: %v", linkName, err)
}
// delete the macvlan slave device
if err := ns.NlHandle().LinkDel(vlanLink); err != nil {
return fmt.Errorf("failed to delete %s link: %v", linkName, err)
}
logrus.Debugf("Deleted a vlan tagged netlink subinterface: %s", linkName)
}
// if the subinterface doesn't parse to iface.vlan_id leave the interface in
// place since it could be a user specified name not created by the driver.
return nil
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | resolvconf/resolvconf.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/resolvconf/resolvconf.go#L62-L72 | go | train | // GetSpecific returns the contents of the user specified resolv.conf file and its hash | func GetSpecific(path string) (*File, error) | // GetSpecific returns the contents of the user specified resolv.conf file and its hash
func GetSpecific(path string) (*File, error) | {
resolv, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
hash, err := ioutils.HashData(bytes.NewReader(resolv))
if err != nil {
return nil, err
}
return &File{Content: resolv, Hash: hash}, nil
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | resolvconf/resolvconf.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/resolvconf/resolvconf.go#L77-L96 | go | train | // GetIfChanged retrieves the host /etc/resolv.conf file, checks against the last hash
// and, if modified since last check, returns the bytes and new hash.
// This feature is used by the resolv.conf updater for containers | func GetIfChanged() (*File, error) | // GetIfChanged retrieves the host /etc/resolv.conf file, checks against the last hash
// and, if modified since last check, returns the bytes and new hash.
// This feature is used by the resolv.conf updater for containers
func GetIfChanged() (*File, error) | {
lastModified.Lock()
defer lastModified.Unlock()
resolv, err := ioutil.ReadFile("/etc/resolv.conf")
if err != nil {
return nil, err
}
newHash, err := ioutils.HashData(bytes.NewReader(resolv))
if err != nil {
return nil, err
}
if lastModified.sha256 != newHash {
lastModified.sha256 = newHash
lastModified.contents = resolv
return &File{Content: resolv, Hash: newHash}, nil
}
// nothing changed, so return no data
return nil, nil
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | resolvconf/resolvconf.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/resolvconf/resolvconf.go#L100-L105 | go | train | // GetLastModified retrieves the last used contents and hash of the host resolv.conf.
// Used by containers updating on restart | func GetLastModified() *File | // GetLastModified retrieves the last used contents and hash of the host resolv.conf.
// Used by containers updating on restart
func GetLastModified() *File | {
lastModified.Lock()
defer lastModified.Unlock()
return &File{Content: lastModified.contents, Hash: lastModified.sha256}
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | resolvconf/resolvconf.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/resolvconf/resolvconf.go#L114-L136 | go | train | // FilterResolvDNS cleans up the config in resolvConf. It has two main jobs:
// 1. It looks for localhost (127.*|::1) entries in the provided
// resolv.conf, removing local nameserver entries, and, if the resulting
// cleaned config has no defined nameservers left, adds default DNS entries
// 2. Given the caller provides the enable/disable state of IPv6, the filter
// code will remove all IPv6 nameservers if it is not enabled for containers
// | func FilterResolvDNS(resolvConf []byte, ipv6Enabled bool) (*File, error) | // FilterResolvDNS cleans up the config in resolvConf. It has two main jobs:
// 1. It looks for localhost (127.*|::1) entries in the provided
// resolv.conf, removing local nameserver entries, and, if the resulting
// cleaned config has no defined nameservers left, adds default DNS entries
// 2. Given the caller provides the enable/disable state of IPv6, the filter
// code will remove all IPv6 nameservers if it is not enabled for containers
//
func FilterResolvDNS(resolvConf []byte, ipv6Enabled bool) (*File, error) | {
cleanedResolvConf := localhostNSRegexp.ReplaceAll(resolvConf, []byte{})
// if IPv6 is not enabled, also clean out any IPv6 address nameserver
if !ipv6Enabled {
cleanedResolvConf = nsIPv6Regexp.ReplaceAll(cleanedResolvConf, []byte{})
}
// if the resulting resolvConf has no more nameservers defined, add appropriate
// default DNS servers for IPv4 and (optionally) IPv6
if len(GetNameservers(cleanedResolvConf, types.IP)) == 0 {
logrus.Infof("No non-localhost DNS nameservers are left in resolv.conf. Using default external servers: %v", defaultIPv4Dns)
dns := defaultIPv4Dns
if ipv6Enabled {
logrus.Infof("IPv6 enabled; Adding default IPv6 external servers: %v", defaultIPv6Dns)
dns = append(dns, defaultIPv6Dns...)
}
cleanedResolvConf = append(cleanedResolvConf, []byte("\n"+strings.Join(dns, "\n"))...)
}
hash, err := ioutils.HashData(bytes.NewReader(cleanedResolvConf))
if err != nil {
return nil, err
}
return &File{Content: cleanedResolvConf, Hash: hash}, nil
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | resolvconf/resolvconf.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/resolvconf/resolvconf.go#L139-L151 | go | train | // getLines parses input into lines and strips away comments. | func getLines(input []byte, commentMarker []byte) [][]byte | // getLines parses input into lines and strips away comments.
func getLines(input []byte, commentMarker []byte) [][]byte | {
lines := bytes.Split(input, []byte("\n"))
var output [][]byte
for _, currentLine := range lines {
var commentIndex = bytes.Index(currentLine, commentMarker)
if commentIndex == -1 {
output = append(output, currentLine)
} else {
output = append(output, currentLine[:commentIndex])
}
}
return output
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | resolvconf/resolvconf.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/resolvconf/resolvconf.go#L154-L170 | go | train | // GetNameservers returns nameservers (if any) listed in /etc/resolv.conf | func GetNameservers(resolvConf []byte, kind int) []string | // GetNameservers returns nameservers (if any) listed in /etc/resolv.conf
func GetNameservers(resolvConf []byte, kind int) []string | {
nameservers := []string{}
for _, line := range getLines(resolvConf, []byte("#")) {
var ns [][]byte
if kind == types.IP {
ns = nsRegexp.FindSubmatch(line)
} else if kind == types.IPv4 {
ns = nsIPv4Regexpmatch.FindSubmatch(line)
} else if kind == types.IPv6 {
ns = nsIPv6Regexpmatch.FindSubmatch(line)
}
if len(ns) > 0 {
nameservers = append(nameservers, string(ns[1]))
}
}
return nameservers
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | resolvconf/resolvconf.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/resolvconf/resolvconf.go#L175-L188 | go | train | // GetNameserversAsCIDR returns nameservers (if any) listed in
// /etc/resolv.conf as CIDR blocks (e.g., "1.2.3.4/32")
// This function's output is intended for net.ParseCIDR | func GetNameserversAsCIDR(resolvConf []byte) []string | // GetNameserversAsCIDR returns nameservers (if any) listed in
// /etc/resolv.conf as CIDR blocks (e.g., "1.2.3.4/32")
// This function's output is intended for net.ParseCIDR
func GetNameserversAsCIDR(resolvConf []byte) []string | {
nameservers := []string{}
for _, nameserver := range GetNameservers(resolvConf, types.IP) {
var address string
// If IPv6, strip zone if present
if strings.Contains(nameserver, ":") {
address = strings.Split(nameserver, "%")[0] + "/128"
} else {
address = nameserver + "/32"
}
nameservers = append(nameservers, address)
}
return nameservers
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | resolvconf/resolvconf.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/resolvconf/resolvconf.go#L193-L203 | go | train | // GetSearchDomains returns search domains (if any) listed in /etc/resolv.conf
// If more than one search line is encountered, only the contents of the last
// one is returned. | func GetSearchDomains(resolvConf []byte) []string | // GetSearchDomains returns search domains (if any) listed in /etc/resolv.conf
// If more than one search line is encountered, only the contents of the last
// one is returned.
func GetSearchDomains(resolvConf []byte) []string | {
domains := []string{}
for _, line := range getLines(resolvConf, []byte("#")) {
match := searchRegexp.FindSubmatch(line)
if match == nil {
continue
}
domains = strings.Fields(string(match[1]))
}
return domains
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | resolvconf/resolvconf.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/resolvconf/resolvconf.go#L208-L218 | go | train | // GetOptions returns options (if any) listed in /etc/resolv.conf
// If more than one options line is encountered, only the contents of the last
// one is returned. | func GetOptions(resolvConf []byte) []string | // GetOptions returns options (if any) listed in /etc/resolv.conf
// If more than one options line is encountered, only the contents of the last
// one is returned.
func GetOptions(resolvConf []byte) []string | {
options := []string{}
for _, line := range getLines(resolvConf, []byte("#")) {
match := optionsRegexp.FindSubmatch(line)
if match == nil {
continue
}
options = strings.Fields(string(match[1]))
}
return options
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | resolvconf/resolvconf.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/resolvconf/resolvconf.go#L223-L251 | go | train | // Build writes a configuration file to path containing a "nameserver" entry
// for every element in dns, a "search" entry for every element in
// dnsSearch, and an "options" entry for every element in dnsOptions. | func Build(path string, dns, dnsSearch, dnsOptions []string) (*File, error) | // Build writes a configuration file to path containing a "nameserver" entry
// for every element in dns, a "search" entry for every element in
// dnsSearch, and an "options" entry for every element in dnsOptions.
func Build(path string, dns, dnsSearch, dnsOptions []string) (*File, error) | {
content := bytes.NewBuffer(nil)
if len(dnsSearch) > 0 {
if searchString := strings.Join(dnsSearch, " "); strings.Trim(searchString, " ") != "." {
if _, err := content.WriteString("search " + searchString + "\n"); err != nil {
return nil, err
}
}
}
for _, dns := range dns {
if _, err := content.WriteString("nameserver " + dns + "\n"); err != nil {
return nil, err
}
}
if len(dnsOptions) > 0 {
if optsString := strings.Join(dnsOptions, " "); strings.Trim(optsString, " ") != "" {
if _, err := content.WriteString("options " + optsString + "\n"); err != nil {
return nil, err
}
}
}
hash, err := ioutils.HashData(bytes.NewReader(content.Bytes()))
if err != nil {
return nil, err
}
return &File{Content: content.Bytes(), Hash: hash}, ioutil.WriteFile(path, content.Bytes(), 0644)
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | ipam/allocator.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipam/allocator.go#L44-L73 | go | train | // NewAllocator returns an instance of libnetwork ipam | func NewAllocator(lcDs, glDs datastore.DataStore) (*Allocator, error) | // NewAllocator returns an instance of libnetwork ipam
func NewAllocator(lcDs, glDs datastore.DataStore) (*Allocator, error) | {
a := &Allocator{}
// Load predefined subnet pools
a.predefined = map[string][]*net.IPNet{
localAddressSpace: ipamutils.GetLocalScopeDefaultNetworks(),
globalAddressSpace: ipamutils.GetGlobalScopeDefaultNetworks(),
}
// Initialize asIndices map
a.predefinedStartIndices = make(map[string]int)
// Initialize bitseq map
a.addresses = make(map[SubnetKey]*bitseq.Handle)
// Initialize address spaces
a.addrSpaces = make(map[string]*addrSpace)
for _, aspc := range []struct {
as string
ds datastore.DataStore
}{
{localAddressSpace, lcDs},
{globalAddressSpace, glDs},
} {
a.initializeAddressSpace(aspc.as, aspc.ds)
}
return a, nil
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | ipam/allocator.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipam/allocator.go#L118-L148 | go | train | // Checks for and fixes damaged bitmask. | func (a *Allocator) checkConsistency(as string) | // Checks for and fixes damaged bitmask.
func (a *Allocator) checkConsistency(as string) | {
var sKeyList []SubnetKey
// Retrieve this address space's configuration and bitmasks from the datastore
a.refresh(as)
a.Lock()
aSpace, ok := a.addrSpaces[as]
a.Unlock()
if !ok {
return
}
a.updateBitMasks(aSpace)
aSpace.Lock()
for sk, pd := range aSpace.subnets {
if pd.Range != nil {
continue
}
sKeyList = append(sKeyList, sk)
}
aSpace.Unlock()
for _, sk := range sKeyList {
a.Lock()
bm := a.addresses[sk]
a.Unlock()
if err := bm.CheckConsistency(); err != nil {
logrus.Warnf("Error while running consistency check for %s: %v", sk, err)
}
}
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | ipam/allocator.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipam/allocator.go#L178-L194 | go | train | // DiscoverNew informs the allocator about a new global scope datastore | func (a *Allocator) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error | // DiscoverNew informs the allocator about a new global scope datastore
func (a *Allocator) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error | {
if dType != discoverapi.DatastoreConfig {
return nil
}
dsc, ok := data.(discoverapi.DatastoreConfigData)
if !ok {
return types.InternalErrorf("incorrect data in datastore update notification: %v", data)
}
ds, err := datastore.NewDataStoreFromConfig(dsc)
if err != nil {
return err
}
return a.initializeAddressSpace(globalAddressSpace, ds)
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | ipam/allocator.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipam/allocator.go#L211-L256 | go | train | // RequestPool returns an address pool along with its unique id.
// addressSpace must be a valid address space name and must not be the empty string.
// If pool is the empty string then the default predefined pool for addressSpace will be used, otherwise pool must be a valid IP address and length in CIDR notation.
// If subPool is not empty, it must be a valid IP address and length in CIDR notation which is a sub-range of pool.
// subPool must be empty if pool is empty. | 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.
// addressSpace must be a valid address space name and must not be the empty string.
// If pool is the empty string then the default predefined pool for addressSpace will be used, otherwise pool must be a valid IP address and length in CIDR notation.
// If subPool is not empty, it must be a valid IP address and length in CIDR notation which is a sub-range of pool.
// subPool must be empty if pool is empty.
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)
k, nw, ipr, err := a.parsePoolRequest(addressSpace, pool, subPool, v6)
if err != nil {
return "", nil, nil, types.InternalErrorf("failed to parse pool request for address space %q pool %q subpool %q: %v", addressSpace, pool, subPool, err)
}
pdf := k == nil
retry:
if pdf {
if nw, err = a.getPredefinedPool(addressSpace, v6); err != nil {
return "", nil, nil, err
}
k = &SubnetKey{AddressSpace: addressSpace, Subnet: nw.String()}
}
if err := a.refresh(addressSpace); err != nil {
return "", nil, nil, err
}
aSpace, err := a.getAddrSpace(addressSpace)
if err != nil {
return "", nil, nil, err
}
insert, err := aSpace.updatePoolDBOnAdd(*k, nw, ipr, pdf)
if err != nil {
if _, ok := err.(types.MaskableError); ok {
logrus.Debugf("Retrying predefined pool search: %v", err)
goto retry
}
return "", nil, nil, err
}
if err := a.writeToStore(aSpace); err != nil {
if _, ok := err.(types.RetryError); !ok {
return "", nil, nil, types.InternalErrorf("pool configuration failed because of %s", err.Error())
}
goto retry
}
return k.String(), nw, nil, insert()
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | ipam/allocator.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipam/allocator.go#L259-L289 | go | train | // ReleasePool releases the address pool identified by the passed id | func (a *Allocator) ReleasePool(poolID string) error | // ReleasePool releases the address pool identified by the passed id
func (a *Allocator) ReleasePool(poolID string) error | {
logrus.Debugf("ReleasePool(%s)", poolID)
k := SubnetKey{}
if err := k.FromString(poolID); err != nil {
return types.BadRequestErrorf("invalid pool id: %s", poolID)
}
retry:
if err := a.refresh(k.AddressSpace); err != nil {
return err
}
aSpace, err := a.getAddrSpace(k.AddressSpace)
if err != nil {
return err
}
remove, err := aSpace.updatePoolDBOnRemoval(k)
if err != nil {
return err
}
if err = a.writeToStore(aSpace); err != nil {
if _, ok := err.(types.RetryError); !ok {
return types.InternalErrorf("pool (%s) removal failed because of %v", poolID, err)
}
goto retry
}
return remove()
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | ipam/allocator.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipam/allocator.go#L293-L301 | go | train | // Given the address space, returns the local or global PoolConfig based on whether the
// address space is local or global. AddressSpace locality is registered with IPAM out of band. | func (a *Allocator) getAddrSpace(as string) (*addrSpace, error) | // Given the address space, returns the local or global PoolConfig based on whether the
// address space is local or global. AddressSpace locality is registered with IPAM out of band.
func (a *Allocator) getAddrSpace(as string) (*addrSpace, error) | {
a.Lock()
defer a.Unlock()
aSpace, ok := a.addrSpaces[as]
if !ok {
return nil, types.BadRequestErrorf("cannot find address space %s (most likely the backing datastore is not configured)", as)
}
return aSpace, nil
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | ipam/allocator.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipam/allocator.go#L305-L335 | go | train | // parsePoolRequest parses and validates a request to create a new pool under addressSpace and returns
// a SubnetKey, network and range describing the request. | func (a *Allocator) parsePoolRequest(addressSpace, pool, subPool string, v6 bool) (*SubnetKey, *net.IPNet, *AddressRange, error) | // parsePoolRequest parses and validates a request to create a new pool under addressSpace and returns
// a SubnetKey, network and range describing the request.
func (a *Allocator) parsePoolRequest(addressSpace, pool, subPool string, v6 bool) (*SubnetKey, *net.IPNet, *AddressRange, error) | {
var (
nw *net.IPNet
ipr *AddressRange
err error
)
if addressSpace == "" {
return nil, nil, nil, ipamapi.ErrInvalidAddressSpace
}
if pool == "" && subPool != "" {
return nil, nil, nil, ipamapi.ErrInvalidSubPool
}
if pool == "" {
return nil, nil, nil, nil
}
if _, nw, err = net.ParseCIDR(pool); err != nil {
return nil, nil, nil, ipamapi.ErrInvalidPool
}
if subPool != "" {
if ipr, err = getAddressRange(subPool, nw); err != nil {
return nil, nil, nil, err
}
}
return &SubnetKey{AddressSpace: addressSpace, Subnet: nw.String(), ChildSubnet: subPool}, nw, ipr, nil
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | ipam/allocator.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipam/allocator.go#L451-L505 | go | train | // RequestAddress returns an address from the specified pool ID | 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
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)
k := SubnetKey{}
if err := k.FromString(poolID); err != nil {
return nil, nil, types.BadRequestErrorf("invalid pool id: %s", poolID)
}
if err := a.refresh(k.AddressSpace); err != nil {
return nil, nil, err
}
aSpace, err := a.getAddrSpace(k.AddressSpace)
if err != nil {
return nil, nil, err
}
aSpace.Lock()
p, ok := aSpace.subnets[k]
if !ok {
aSpace.Unlock()
return nil, nil, types.NotFoundErrorf("cannot find address pool for poolID:%s", poolID)
}
if prefAddress != nil && !p.Pool.Contains(prefAddress) {
aSpace.Unlock()
return nil, nil, ipamapi.ErrIPOutOfRange
}
c := p
for c.Range != nil {
k = c.ParentKey
c = aSpace.subnets[k]
}
aSpace.Unlock()
bm, err := a.retrieveBitmask(k, c.Pool)
if err != nil {
return nil, nil, types.InternalErrorf("could not find bitmask in datastore for %s on address %v request from pool %s: %v",
k.String(), prefAddress, poolID, err)
}
// In order to request for a serial ip address allocation, callers can pass in the option to request
// IP allocation serially or first available IP in the subnet
var serial bool
if opts != nil {
if val, ok := opts[ipamapi.AllocSerialPrefix]; ok {
serial = (val == "true")
}
}
ip, err := a.getAddress(p.Pool, bm, prefAddress, p.Range, serial)
if err != nil {
return nil, nil, err
}
return &net.IPNet{IP: ip, Mask: p.Pool.Mask}, nil, nil
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | ipam/allocator.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipam/allocator.go#L508-L563 | go | train | // ReleaseAddress releases the address from the specified pool ID | func (a *Allocator) ReleaseAddress(poolID string, address net.IP) error | // ReleaseAddress releases the address from the specified pool ID
func (a *Allocator) ReleaseAddress(poolID string, address net.IP) error | {
logrus.Debugf("ReleaseAddress(%s, %v)", poolID, address)
k := SubnetKey{}
if err := k.FromString(poolID); err != nil {
return types.BadRequestErrorf("invalid pool id: %s", poolID)
}
if err := a.refresh(k.AddressSpace); err != nil {
return err
}
aSpace, err := a.getAddrSpace(k.AddressSpace)
if err != nil {
return err
}
aSpace.Lock()
p, ok := aSpace.subnets[k]
if !ok {
aSpace.Unlock()
return types.NotFoundErrorf("cannot find address pool for poolID:%s", poolID)
}
if address == nil {
aSpace.Unlock()
return types.BadRequestErrorf("invalid address: nil")
}
if !p.Pool.Contains(address) {
aSpace.Unlock()
return ipamapi.ErrIPOutOfRange
}
c := p
for c.Range != nil {
k = c.ParentKey
c = aSpace.subnets[k]
}
aSpace.Unlock()
mask := p.Pool.Mask
h, err := types.GetHostPartIP(address, mask)
if err != nil {
return types.InternalErrorf("failed to release address %s: %v", address.String(), err)
}
bm, err := a.retrieveBitmask(k, c.Pool)
if err != nil {
return types.InternalErrorf("could not find bitmask in datastore for %s on address %v release from pool %s: %v",
k.String(), address, poolID, err)
}
defer logrus.Debugf("Released address PoolID:%s, Address:%v Sequence:%s", poolID, address, bm.String())
return bm.Unset(ipToUint64(h))
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | ipam/allocator.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipam/allocator.go#L605-L637 | go | train | // DumpDatabase dumps the internal info | func (a *Allocator) DumpDatabase() string | // DumpDatabase dumps the internal info
func (a *Allocator) DumpDatabase() string | {
a.Lock()
aspaces := make(map[string]*addrSpace, len(a.addrSpaces))
orderedAS := make([]string, 0, len(a.addrSpaces))
for as, aSpace := range a.addrSpaces {
orderedAS = append(orderedAS, as)
aspaces[as] = aSpace
}
a.Unlock()
sort.Strings(orderedAS)
var s string
for _, as := range orderedAS {
aSpace := aspaces[as]
s = fmt.Sprintf("\n\n%s Config", as)
aSpace.Lock()
for k, config := range aSpace.subnets {
s += fmt.Sprintf("\n%v: %v", k, config)
if config.Range == nil {
a.retrieveBitmask(k, config.Pool)
}
}
aSpace.Unlock()
}
s = fmt.Sprintf("%s\n\nBitmasks", s)
for k, bm := range a.addresses {
s += fmt.Sprintf("\n%s: %s", k, bm)
}
return s
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | service_linux.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/service_linux.go#L35-L49 | go | train | // Populate all loadbalancers on the network that the passed endpoint
// belongs to, into this sandbox. | func (sb *sandbox) populateLoadBalancers(ep *endpoint) | // Populate all loadbalancers on the network that the passed endpoint
// belongs to, into this sandbox.
func (sb *sandbox) populateLoadBalancers(ep *endpoint) | {
// This is an interface less endpoint. Nothing to do.
if ep.Iface() == nil {
return
}
n := ep.getNetwork()
eIP := ep.Iface().Address()
if n.ingress {
if err := addRedirectRules(sb.Key(), eIP, ep.ingressPorts); err != nil {
logrus.Errorf("Failed to add redirect rules for ep %s (%.7s): %v", ep.Name(), ep.ID(), err)
}
}
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | service_linux.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/service_linux.go#L80-L88 | go | train | // Searches the OS sandbox for the name of the endpoint interface
// within the sandbox. This is required for adding/removing IP
// aliases to the interface. | func findIfaceDstName(sb *sandbox, ep *endpoint) string | // Searches the OS sandbox for the name of the endpoint interface
// within the sandbox. This is required for adding/removing IP
// aliases to the interface.
func findIfaceDstName(sb *sandbox, ep *endpoint) string | {
srcName := ep.Iface().SrcName()
for _, i := range sb.osSbox.Info().Interfaces() {
if i.SrcName() == srcName {
return i.DstName()
}
}
return ""
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | service_linux.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/service_linux.go#L92-L171 | go | train | // Add loadbalancer backend to the loadbalncer sandbox for the network.
// If needed add the service as well. | func (n *network) addLBBackend(ip net.IP, lb *loadBalancer) | // Add loadbalancer backend to the loadbalncer sandbox for the network.
// If needed add the service as well.
func (n *network) addLBBackend(ip net.IP, lb *loadBalancer) | {
if len(lb.vip) == 0 {
return
}
ep, sb, err := n.findLBEndpointSandbox()
if err != nil {
logrus.Errorf("addLBBackend %s/%s: %v", n.ID(), n.Name(), err)
return
}
if sb.osSbox == nil {
return
}
eIP := ep.Iface().Address()
i, err := ipvs.New(sb.Key())
if err != nil {
logrus.Errorf("Failed to create an ipvs handle for sbox %.7s (%.7s,%s) for lb addition: %v", sb.ID(), sb.ContainerID(), sb.Key(), err)
return
}
defer i.Close()
s := &ipvs.Service{
AddressFamily: nl.FAMILY_V4,
FWMark: lb.fwMark,
SchedName: ipvs.RoundRobin,
}
if !i.IsServicePresent(s) {
// Add IP alias for the VIP to the endpoint
ifName := findIfaceDstName(sb, ep)
if ifName == "" {
logrus.Errorf("Failed find interface name for endpoint %s(%s) to create LB alias", ep.ID(), ep.Name())
return
}
err := sb.osSbox.AddAliasIP(ifName, &net.IPNet{IP: lb.vip, Mask: net.CIDRMask(32, 32)})
if err != nil {
logrus.Errorf("Failed add IP alias %s to network %s LB endpoint interface %s: %v", lb.vip, n.ID(), ifName, err)
return
}
if sb.ingress {
var gwIP net.IP
if ep := sb.getGatewayEndpoint(); ep != nil {
gwIP = ep.Iface().Address().IP
}
if err := programIngress(gwIP, lb.service.ingressPorts, false); err != nil {
logrus.Errorf("Failed to add ingress: %v", err)
return
}
}
logrus.Debugf("Creating service for vip %s fwMark %d ingressPorts %#v in sbox %.7s (%.7s)", lb.vip, lb.fwMark, lb.service.ingressPorts, sb.ID(), sb.ContainerID())
if err := invokeFWMarker(sb.Key(), lb.vip, lb.fwMark, lb.service.ingressPorts, eIP, false, n.loadBalancerMode); err != nil {
logrus.Errorf("Failed to add firewall mark rule in sbox %.7s (%.7s): %v", sb.ID(), sb.ContainerID(), err)
return
}
if err := i.NewService(s); err != nil && err != syscall.EEXIST {
logrus.Errorf("Failed to create a new service for vip %s fwmark %d in sbox %.7s (%.7s): %v", lb.vip, lb.fwMark, sb.ID(), sb.ContainerID(), err)
return
}
}
d := &ipvs.Destination{
AddressFamily: nl.FAMILY_V4,
Address: ip,
Weight: 1,
}
if n.loadBalancerMode == loadBalancerModeDSR {
d.ConnectionFlags = ipvs.ConnFwdDirectRoute
}
// Remove the sched name before using the service to add
// destination.
s.SchedName = ""
if err := i.NewDestination(s, d); err != nil && err != syscall.EEXIST {
logrus.Errorf("Failed to create real server %s for vip %s fwmark %d in sbox %.7s (%.7s): %v", ip, lb.vip, lb.fwMark, sb.ID(), sb.ContainerID(), err)
}
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | service_linux.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/service_linux.go#L177-L255 | go | train | // Remove loadbalancer backend the load balancing endpoint for this
// network. If 'rmService' is true, then remove the service entry as well.
// If 'fullRemove' is true then completely remove the entry, otherwise
// just deweight it for now. | func (n *network) rmLBBackend(ip net.IP, lb *loadBalancer, rmService bool, fullRemove bool) | // Remove loadbalancer backend the load balancing endpoint for this
// network. If 'rmService' is true, then remove the service entry as well.
// If 'fullRemove' is true then completely remove the entry, otherwise
// just deweight it for now.
func (n *network) rmLBBackend(ip net.IP, lb *loadBalancer, rmService bool, fullRemove bool) | {
if len(lb.vip) == 0 {
return
}
ep, sb, err := n.findLBEndpointSandbox()
if err != nil {
logrus.Debugf("rmLBBackend for %s/%s: %v -- probably transient state", n.ID(), n.Name(), err)
return
}
if sb.osSbox == nil {
return
}
eIP := ep.Iface().Address()
i, err := ipvs.New(sb.Key())
if err != nil {
logrus.Errorf("Failed to create an ipvs handle for sbox %.7s (%.7s,%s) for lb removal: %v", sb.ID(), sb.ContainerID(), sb.Key(), err)
return
}
defer i.Close()
s := &ipvs.Service{
AddressFamily: nl.FAMILY_V4,
FWMark: lb.fwMark,
}
d := &ipvs.Destination{
AddressFamily: nl.FAMILY_V4,
Address: ip,
Weight: 1,
}
if n.loadBalancerMode == loadBalancerModeDSR {
d.ConnectionFlags = ipvs.ConnFwdDirectRoute
}
if fullRemove {
if err := i.DelDestination(s, d); err != nil && err != syscall.ENOENT {
logrus.Errorf("Failed to delete real server %s for vip %s fwmark %d in sbox %.7s (%.7s): %v", ip, lb.vip, lb.fwMark, sb.ID(), sb.ContainerID(), err)
}
} else {
d.Weight = 0
if err := i.UpdateDestination(s, d); err != nil && err != syscall.ENOENT {
logrus.Errorf("Failed to set LB weight of real server %s to 0 for vip %s fwmark %d in sbox %.7s (%.7s): %v", ip, lb.vip, lb.fwMark, sb.ID(), sb.ContainerID(), err)
}
}
if rmService {
s.SchedName = ipvs.RoundRobin
if err := i.DelService(s); err != nil && err != syscall.ENOENT {
logrus.Errorf("Failed to delete service for vip %s fwmark %d in sbox %.7s (%.7s): %v", lb.vip, lb.fwMark, sb.ID(), sb.ContainerID(), err)
}
if sb.ingress {
var gwIP net.IP
if ep := sb.getGatewayEndpoint(); ep != nil {
gwIP = ep.Iface().Address().IP
}
if err := programIngress(gwIP, lb.service.ingressPorts, true); err != nil {
logrus.Errorf("Failed to delete ingress: %v", err)
}
}
if err := invokeFWMarker(sb.Key(), lb.vip, lb.fwMark, lb.service.ingressPorts, eIP, true, n.loadBalancerMode); err != nil {
logrus.Errorf("Failed to delete firewall mark rule in sbox %.7s (%.7s): %v", sb.ID(), sb.ContainerID(), err)
}
// Remove IP alias from the VIP to the endpoint
ifName := findIfaceDstName(sb, ep)
if ifName == "" {
logrus.Errorf("Failed find interface name for endpoint %s(%s) to create LB alias", ep.ID(), ep.Name())
return
}
err := sb.osSbox.RemoveAliasIP(ifName, &net.IPNet{IP: lb.vip, Mask: net.CIDRMask(32, 32)})
if err != nil {
logrus.Errorf("Failed add IP alias %s to network %s LB endpoint interface %s: %v", lb.vip, n.ID(), ifName, err)
}
}
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | service_linux.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/service_linux.go#L463-L474 | go | train | // In the filter table FORWARD chain the first rule should be to jump to
// DOCKER-USER so the user is able to filter packet first.
// The second rule should be jump to INGRESS-CHAIN.
// This chain has the rules to allow access to the published ports for swarm tasks
// from local bridge networks and docker_gwbridge (ie:taks on other swarm networks) | func arrangeIngressFilterRule() | // In the filter table FORWARD chain the first rule should be to jump to
// DOCKER-USER so the user is able to filter packet first.
// The second rule should be jump to INGRESS-CHAIN.
// This chain has the rules to allow access to the published ports for swarm tasks
// from local bridge networks and docker_gwbridge (ie:taks on other swarm networks)
func arrangeIngressFilterRule() | {
if iptables.ExistChain(ingressChain, iptables.Filter) {
if iptables.Exists(iptables.Filter, "FORWARD", "-j", ingressChain) {
if err := iptables.RawCombinedOutput("-D", "FORWARD", "-j", ingressChain); err != nil {
logrus.Warnf("failed to delete jump rule to ingressChain in filter table: %v", err)
}
}
if err := iptables.RawCombinedOutput("-I", "FORWARD", "-j", ingressChain); err != nil {
logrus.Warnf("failed to add jump rule to ingressChain in filter table: %v", err)
}
}
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | service_linux.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/service_linux.go#L575-L605 | go | train | // Invoke fwmarker reexec routine to mark vip destined packets with
// the passed firewall mark. | func invokeFWMarker(path string, vip net.IP, fwMark uint32, ingressPorts []*PortConfig, eIP *net.IPNet, isDelete bool, lbMode string) error | // Invoke fwmarker reexec routine to mark vip destined packets with
// the passed firewall mark.
func invokeFWMarker(path string, vip net.IP, fwMark uint32, ingressPorts []*PortConfig, eIP *net.IPNet, isDelete bool, lbMode string) error | {
var ingressPortsFile string
if len(ingressPorts) != 0 {
var err error
ingressPortsFile, err = writePortsToFile(ingressPorts)
if err != nil {
return err
}
defer os.Remove(ingressPortsFile)
}
addDelOpt := "-A"
if isDelete {
addDelOpt = "-D"
}
cmd := &exec.Cmd{
Path: reexec.Self(),
Args: append([]string{"fwmarker"}, path, vip.String(), fmt.Sprintf("%d", fwMark), addDelOpt, ingressPortsFile, eIP.String(), lbMode),
Stdout: os.Stdout,
Stderr: os.Stderr,
}
if err := cmd.Run(); err != nil {
return fmt.Errorf("reexec failed: %v", err)
}
return nil
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | service_linux.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/service_linux.go#L608-L684 | go | train | // Firewall marker reexec function. | func fwMarker() | // Firewall marker reexec function.
func fwMarker() | {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
if len(os.Args) < 8 {
logrus.Error("invalid number of arguments..")
os.Exit(1)
}
var ingressPorts []*PortConfig
if os.Args[5] != "" {
var err error
ingressPorts, err = readPortsFromFile(os.Args[5])
if err != nil {
logrus.Errorf("Failed reading ingress ports file: %v", err)
os.Exit(2)
}
}
vip := os.Args[2]
fwMark, err := strconv.ParseUint(os.Args[3], 10, 32)
if err != nil {
logrus.Errorf("bad fwmark value(%s) passed: %v", os.Args[3], err)
os.Exit(3)
}
addDelOpt := os.Args[4]
rules := [][]string{}
for _, iPort := range ingressPorts {
rule := strings.Fields(fmt.Sprintf("-t mangle %s PREROUTING -p %s --dport %d -j MARK --set-mark %d",
addDelOpt, strings.ToLower(PortConfig_Protocol_name[int32(iPort.Protocol)]), iPort.PublishedPort, fwMark))
rules = append(rules, rule)
}
ns, err := netns.GetFromPath(os.Args[1])
if err != nil {
logrus.Errorf("failed get network namespace %q: %v", os.Args[1], err)
os.Exit(4)
}
defer ns.Close()
if err := netns.Set(ns); err != nil {
logrus.Errorf("setting into container net ns %v failed, %v", os.Args[1], err)
os.Exit(5)
}
lbMode := os.Args[7]
if addDelOpt == "-A" && lbMode == loadBalancerModeNAT {
eIP, subnet, err := net.ParseCIDR(os.Args[6])
if err != nil {
logrus.Errorf("Failed to parse endpoint IP %s: %v", os.Args[6], err)
os.Exit(6)
}
ruleParams := strings.Fields(fmt.Sprintf("-m ipvs --ipvs -d %s -j SNAT --to-source %s", subnet, eIP))
if !iptables.Exists("nat", "POSTROUTING", ruleParams...) {
rule := append(strings.Fields("-t nat -A POSTROUTING"), ruleParams...)
rules = append(rules, rule)
err := ioutil.WriteFile("/proc/sys/net/ipv4/vs/conntrack", []byte{'1', '\n'}, 0644)
if err != nil {
logrus.Errorf("Failed to write to /proc/sys/net/ipv4/vs/conntrack: %v", err)
os.Exit(7)
}
}
}
rule := strings.Fields(fmt.Sprintf("-t mangle %s INPUT -d %s/32 -j MARK --set-mark %d", addDelOpt, vip, fwMark))
rules = append(rules, rule)
for _, rule := range rules {
if err := iptables.RawCombinedOutputNative(rule...); err != nil {
logrus.Errorf("set up rule failed, %v: %v", rule, err)
os.Exit(8)
}
}
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | service_linux.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/service_linux.go#L713-L796 | go | train | // Redirector reexec function. | func redirector() | // Redirector reexec function.
func redirector() | {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
if len(os.Args) < 4 {
logrus.Error("invalid number of arguments..")
os.Exit(1)
}
var ingressPorts []*PortConfig
if os.Args[3] != "" {
var err error
ingressPorts, err = readPortsFromFile(os.Args[3])
if err != nil {
logrus.Errorf("Failed reading ingress ports file: %v", err)
os.Exit(2)
}
}
eIP, _, err := net.ParseCIDR(os.Args[2])
if err != nil {
logrus.Errorf("Failed to parse endpoint IP %s: %v", os.Args[2], err)
os.Exit(3)
}
rules := [][]string{}
for _, iPort := range ingressPorts {
rule := strings.Fields(fmt.Sprintf("-t nat -A PREROUTING -d %s -p %s --dport %d -j REDIRECT --to-port %d",
eIP.String(), strings.ToLower(PortConfig_Protocol_name[int32(iPort.Protocol)]), iPort.PublishedPort, iPort.TargetPort))
rules = append(rules, rule)
// Allow only incoming connections to exposed ports
iRule := strings.Fields(fmt.Sprintf("-I INPUT -d %s -p %s --dport %d -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT",
eIP.String(), strings.ToLower(PortConfig_Protocol_name[int32(iPort.Protocol)]), iPort.TargetPort))
rules = append(rules, iRule)
// Allow only outgoing connections from exposed ports
oRule := strings.Fields(fmt.Sprintf("-I OUTPUT -s %s -p %s --sport %d -m conntrack --ctstate ESTABLISHED -j ACCEPT",
eIP.String(), strings.ToLower(PortConfig_Protocol_name[int32(iPort.Protocol)]), iPort.TargetPort))
rules = append(rules, oRule)
}
ns, err := netns.GetFromPath(os.Args[1])
if err != nil {
logrus.Errorf("failed get network namespace %q: %v", os.Args[1], err)
os.Exit(4)
}
defer ns.Close()
if err := netns.Set(ns); err != nil {
logrus.Errorf("setting into container net ns %v failed, %v", os.Args[1], err)
os.Exit(5)
}
for _, rule := range rules {
if err := iptables.RawCombinedOutputNative(rule...); err != nil {
logrus.Errorf("set up rule failed, %v: %v", rule, err)
os.Exit(6)
}
}
if len(ingressPorts) == 0 {
return
}
// Ensure blocking rules for anything else in/to ingress network
for _, rule := range [][]string{
{"-d", eIP.String(), "-p", "sctp", "-j", "DROP"},
{"-d", eIP.String(), "-p", "udp", "-j", "DROP"},
{"-d", eIP.String(), "-p", "tcp", "-j", "DROP"},
} {
if !iptables.ExistsNative(iptables.Filter, "INPUT", rule...) {
if err := iptables.RawCombinedOutputNative(append([]string{"-A", "INPUT"}, rule...)...); err != nil {
logrus.Errorf("set up rule failed, %v: %v", rule, err)
os.Exit(7)
}
}
rule[0] = "-s"
if !iptables.ExistsNative(iptables.Filter, "OUTPUT", rule...) {
if err := iptables.RawCombinedOutputNative(append([]string{"-A", "OUTPUT"}, rule...)...); err != nil {
logrus.Errorf("set up rule failed, %v: %v", rule, err)
os.Exit(8)
}
}
}
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | drivers/windows/windows.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/windows/windows.go#L113-L119 | go | train | // IsBuiltinLocalDriver validates if network-type is a builtin local-scoped driver | func IsBuiltinLocalDriver(networkType string) bool | // IsBuiltinLocalDriver validates if network-type is a builtin local-scoped driver
func IsBuiltinLocalDriver(networkType string) bool | {
if "l2bridge" == networkType || "l2tunnel" == networkType || "nat" == networkType || "ics" == networkType || "transparent" == networkType {
return true
}
return false
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | drivers/windows/windows.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/windows/windows.go#L122-L124 | go | train | // New constructs a new bridge driver | func newDriver(networkType string) *driver | // New constructs a new bridge driver
func newDriver(networkType string) *driver | {
return &driver{name: networkType, networks: map[string]*hnsNetwork{}}
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | drivers/windows/windows.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/windows/windows.go#L127-L145 | go | train | // GetInit returns an initializer for the given network type | func GetInit(networkType string) func(dc driverapi.DriverCallback, config map[string]interface{}) error | // GetInit returns an initializer for the given network type
func GetInit(networkType string) func(dc driverapi.DriverCallback, config map[string]interface{}) error | {
return func(dc driverapi.DriverCallback, config map[string]interface{}) error {
if !IsBuiltinLocalDriver(networkType) {
return types.BadRequestErrorf("Network type not supported: %s", networkType)
}
d := newDriver(networkType)
err := d.initStore(config)
if err != nil {
return err
}
return dc.RegisterDriver(networkType, d, driverapi.Capability{
DataScope: datastore.LocalScope,
ConnectivityScope: datastore.LocalScope,
})
}
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | drivers/windows/windows.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/windows/windows.go#L272-L395 | go | train | // Create a new network | func (d *driver) CreateNetwork(id string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error | // Create a new network
func (d *driver) CreateNetwork(id string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error | {
if _, err := d.getNetwork(id); err == nil {
return types.ForbiddenErrorf("network %s exists", id)
}
genData, ok := option[netlabel.GenericData].(map[string]string)
if !ok {
return fmt.Errorf("Unknown generic data option")
}
// Parse and validate the config. It should not conflict with existing networks' config
config, err := d.parseNetworkOptions(id, genData)
if err != nil {
return err
}
err = config.processIPAM(id, ipV4Data, ipV6Data)
if err != nil {
return err
}
err = d.createNetwork(config)
if err != nil {
return err
}
// A non blank hnsid indicates that the network was discovered
// from HNS. No need to call HNS if this network was discovered
// from HNS
if config.HnsID == "" {
subnets := []hcsshim.Subnet{}
for _, ipData := range ipV4Data {
subnet := hcsshim.Subnet{
AddressPrefix: ipData.Pool.String(),
}
if ipData.Gateway != nil {
subnet.GatewayAddress = ipData.Gateway.IP.String()
}
subnets = append(subnets, subnet)
}
network := &hcsshim.HNSNetwork{
Name: config.Name,
Type: d.name,
Subnets: subnets,
DNSServerList: config.DNSServers,
DNSSuffix: config.DNSSuffix,
MacPools: config.MacPools,
SourceMac: config.SourceMac,
NetworkAdapterName: config.NetworkAdapterName,
}
if config.VLAN != 0 {
vlanPolicy, err := json.Marshal(hcsshim.VlanPolicy{
Type: "VLAN",
VLAN: config.VLAN,
})
if err != nil {
return err
}
network.Policies = append(network.Policies, vlanPolicy)
}
if config.VSID != 0 {
vsidPolicy, err := json.Marshal(hcsshim.VsidPolicy{
Type: "VSID",
VSID: config.VSID,
})
if err != nil {
return err
}
network.Policies = append(network.Policies, vsidPolicy)
}
if network.Name == "" {
network.Name = id
}
configurationb, err := json.Marshal(network)
if err != nil {
return err
}
configuration := string(configurationb)
logrus.Debugf("HNSNetwork Request =%v Address Space=%v", configuration, subnets)
hnsresponse, err := hcsshim.HNSNetworkRequest("POST", "", configuration)
if err != nil {
return err
}
config.HnsID = hnsresponse.Id
genData[HNSID] = config.HnsID
} else {
// Delete any stale HNS endpoints for this network.
if endpoints, err := hcsshim.HNSListEndpointRequest(); err == nil {
for _, ep := range endpoints {
if ep.VirtualNetwork == config.HnsID {
logrus.Infof("Removing stale HNS endpoint %s", ep.Id)
_, err = hcsshim.HNSEndpointRequest("DELETE", ep.Id, "")
if err != nil {
logrus.Warnf("Error removing HNS endpoint %s", ep.Id)
}
}
}
} else {
logrus.Warnf("Error listing HNS endpoints for network %s", config.HnsID)
}
}
n, err := d.getNetwork(id)
if err != nil {
return err
}
n.created = true
return d.storeUpdate(config)
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | drivers/windows/windows.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/windows/windows.go#L449-L482 | go | train | // ConvertPortBindings converts PortBindings to JSON for HNS request | func ConvertPortBindings(portBindings []types.PortBinding) ([]json.RawMessage, error) | // ConvertPortBindings converts PortBindings to JSON for HNS request
func ConvertPortBindings(portBindings []types.PortBinding) ([]json.RawMessage, error) | {
var pbs []json.RawMessage
// Enumerate through the port bindings specified by the user and convert
// them into the internal structure matching the JSON blob that can be
// understood by the HCS.
for _, elem := range portBindings {
proto := strings.ToUpper(elem.Proto.String())
if proto != "TCP" && proto != "UDP" {
return nil, fmt.Errorf("invalid protocol %s", elem.Proto.String())
}
if elem.HostPort != elem.HostPortEnd {
return nil, fmt.Errorf("Windows does not support more than one host port in NAT settings")
}
if len(elem.HostIP) != 0 {
return nil, fmt.Errorf("Windows does not support host IP addresses in NAT settings")
}
encodedPolicy, err := json.Marshal(hcsshim.NatPolicy{
Type: "NAT",
ExternalPort: elem.HostPort,
InternalPort: elem.Port,
Protocol: elem.Proto.String(),
})
if err != nil {
return nil, err
}
pbs = append(pbs, encodedPolicy)
}
return pbs, nil
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | drivers/windows/windows.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/windows/windows.go#L485-L507 | go | train | // ParsePortBindingPolicies parses HNS endpoint response message to PortBindings | func ParsePortBindingPolicies(policies []json.RawMessage) ([]types.PortBinding, error) | // ParsePortBindingPolicies parses HNS endpoint response message to PortBindings
func ParsePortBindingPolicies(policies []json.RawMessage) ([]types.PortBinding, error) | {
var bindings []types.PortBinding
hcsPolicy := &hcsshim.NatPolicy{}
for _, elem := range policies {
if err := json.Unmarshal([]byte(elem), &hcsPolicy); err != nil || hcsPolicy.Type != "NAT" {
continue
}
binding := types.PortBinding{
HostPort: hcsPolicy.ExternalPort,
HostPortEnd: hcsPolicy.ExternalPort,
Port: hcsPolicy.InternalPort,
Proto: types.ParseProtocol(hcsPolicy.Protocol),
HostIP: net.IPv4(0, 0, 0, 0),
}
bindings = append(bindings, binding)
}
return bindings, nil
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | drivers/windows/windows.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/windows/windows.go#L560-L583 | go | train | // ParseEndpointConnectivity parses options passed to CreateEndpoint, specifically port bindings, and store in a endpointConnectivity object. | func ParseEndpointConnectivity(epOptions map[string]interface{}) (*EndpointConnectivity, error) | // ParseEndpointConnectivity parses options passed to CreateEndpoint, specifically port bindings, and store in a endpointConnectivity object.
func ParseEndpointConnectivity(epOptions map[string]interface{}) (*EndpointConnectivity, error) | {
if epOptions == nil {
return nil, nil
}
ec := &EndpointConnectivity{}
if opt, ok := epOptions[netlabel.PortMap]; ok {
if bs, ok := opt.([]types.PortBinding); ok {
ec.PortBindings = bs
} else {
return nil, fmt.Errorf("Invalid endpoint configuration")
}
}
if opt, ok := epOptions[netlabel.ExposedPorts]; ok {
if ports, ok := opt.([]types.TransportPort); ok {
ec.ExposedPorts = ports
} else {
return nil, fmt.Errorf("Invalid endpoint configuration")
}
}
return ec, nil
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | drivers/windows/windows.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/windows/windows.go#L808-L837 | 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 | {
network, err := d.getNetwork(nid)
if err != nil {
return err
}
// Ensure that the endpoint exists
endpoint, err := network.getEndpoint(eid)
if err != nil {
return err
}
err = jinfo.SetGateway(endpoint.gateway)
if err != nil {
return err
}
endpoint.sandboxID = sboxKey
err = hcsshim.HotAttachEndpoint(endpoint.sandboxID, endpoint.profileID)
if err != nil {
// If container doesn't exists in hcs, do not throw error for hot add/remove
if err != hcsshim.ErrComputeSystemDoesNotExist {
return err
}
}
jinfo.DisableGatewayService()
return nil
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | drivers/windows/windows.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/windows/windows.go#L840-L860 | 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 | {
network, err := d.getNetwork(nid)
if err != nil {
return types.InternalMaskableErrorf("%s", err)
}
// Ensure that the endpoint exists
endpoint, err := network.getEndpoint(eid)
if err != nil {
return err
}
err = hcsshim.HotDetachEndpoint(endpoint.sandboxID, endpoint.profileID)
if err != nil {
// If container doesn't exists in hcs, do not throw error for hot add/remove
if err != hcsshim.ErrComputeSystemDoesNotExist {
return err
}
}
return nil
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | sandbox_externalkey_windows.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/sandbox_externalkey_windows.go#L20-L22 | go | train | // SetExternalKey provides a convenient way to set an External key to a sandbox | func SetExternalKey(controllerID string, containerID string, key string) error | // SetExternalKey provides a convenient way to set an External key to a sandbox
func SetExternalKey(controllerID string, containerID string, key string) error | {
return types.NotImplementedErrorf("SetExternalKey isn't supported on non linux systems")
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | service_common.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/service_common.go#L167-L177 | go | train | // cleanupServiceDiscovery when the network is being deleted, erase all the associated service discovery records | func (c *controller) cleanupServiceDiscovery(cleanupNID string) | // cleanupServiceDiscovery when the network is being deleted, erase all the associated service discovery records
func (c *controller) cleanupServiceDiscovery(cleanupNID string) | {
c.Lock()
defer c.Unlock()
if cleanupNID == "" {
logrus.Debugf("cleanupServiceDiscovery for all networks")
c.svcRecords = make(map[string]svcInfo)
return
}
logrus.Debugf("cleanupServiceDiscovery for network:%s", cleanupNID)
delete(c.svcRecords, cleanupNID)
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | drivers/bridge/setup_bridgenetfiltering.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/bridge/setup_bridgenetfiltering.go#L24-L30 | go | train | //Gets the IP version in use ( [ipv4], [ipv6] or [ipv4 and ipv6] ) | func getIPVersion(config *networkConfiguration) ipVersion | //Gets the IP version in use ( [ipv4], [ipv6] or [ipv4 and ipv6] )
func getIPVersion(config *networkConfiguration) ipVersion | {
ipVersion := ipv4
if config.AddressIPv6 != nil || config.EnableIPv6 {
ipVersion |= ipv6
}
return ipVersion
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | drivers/bridge/setup_bridgenetfiltering.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/bridge/setup_bridgenetfiltering.go#L53-L89 | go | train | //Enable bridge net filtering if ip forwarding is enabled. See github issue #11404 | func checkBridgeNetFiltering(config *networkConfiguration, i *bridgeInterface) error | //Enable bridge net filtering if ip forwarding is enabled. See github issue #11404
func checkBridgeNetFiltering(config *networkConfiguration, i *bridgeInterface) error | {
ipVer := getIPVersion(config)
iface := config.BridgeName
doEnable := func(ipVer ipVersion) error {
var ipVerName string
if ipVer == ipv4 {
ipVerName = "IPv4"
} else {
ipVerName = "IPv6"
}
enabled, err := isPacketForwardingEnabled(ipVer, iface)
if err != nil {
logrus.Warnf("failed to check %s forwarding: %v", ipVerName, err)
} else if enabled {
enabled, err := getKernelBoolParam(getBridgeNFKernelParam(ipVer))
if err != nil || enabled {
return err
}
return setKernelBoolParam(getBridgeNFKernelParam(ipVer), true)
}
return nil
}
switch ipVer {
case ipv4, ipv6:
return doEnable(ipVer)
case ipvboth:
v4err := doEnable(ipv4)
v6err := doEnable(ipv6)
if v4err == nil {
return v6err
}
return v4err
default:
return nil
}
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | drivers/bridge/setup_bridgenetfiltering.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/bridge/setup_bridgenetfiltering.go#L95-L107 | go | train | // Get kernel param path saying whether IPv${ipVer} traffic is being forwarded
// on particular interface. Interface may be specified for IPv6 only. If
// `iface` is empty, `default` will be assumed, which represents default value
// for new interfaces. | func getForwardingKernelParam(ipVer ipVersion, iface string) string | // Get kernel param path saying whether IPv${ipVer} traffic is being forwarded
// on particular interface. Interface may be specified for IPv6 only. If
// `iface` is empty, `default` will be assumed, which represents default value
// for new interfaces.
func getForwardingKernelParam(ipVer ipVersion, iface string) string | {
switch ipVer {
case ipv4:
return "/proc/sys/net/ipv4/ip_forward"
case ipv6:
if iface == "" {
iface = "default"
}
return fmt.Sprintf("/proc/sys/net/ipv6/conf/%s/forwarding", iface)
default:
return ""
}
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | drivers/bridge/setup_bridgenetfiltering.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/bridge/setup_bridgenetfiltering.go#L123-L133 | go | train | //Gets the value of the kernel parameters located at the given path | func getKernelBoolParam(path string) (bool, error) | //Gets the value of the kernel parameters located at the given path
func getKernelBoolParam(path string) (bool, error) | {
enabled := false
line, err := ioutil.ReadFile(path)
if err != nil {
return false, err
}
if len(line) > 0 {
enabled = line[0] == '1'
}
return enabled, err
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | drivers/bridge/setup_bridgenetfiltering.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/bridge/setup_bridgenetfiltering.go#L136-L142 | go | train | //Sets the value of the kernel parameter located at the given path | func setKernelBoolParam(path string, on bool) error | //Sets the value of the kernel parameter located at the given path
func setKernelBoolParam(path string, on bool) error | {
value := byte('0')
if on {
value = byte('1')
}
return ioutil.WriteFile(path, []byte{value, '\n'}, 0644)
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | drivers/bridge/setup_bridgenetfiltering.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/bridge/setup_bridgenetfiltering.go#L145-L158 | go | train | //Checks to see if packet forwarding is enabled | func isPacketForwardingEnabled(ipVer ipVersion, iface string) (bool, error) | //Checks to see if packet forwarding is enabled
func isPacketForwardingEnabled(ipVer ipVersion, iface string) (bool, error) | {
switch ipVer {
case ipv4, ipv6:
return getKernelBoolParam(getForwardingKernelParam(ipVer, iface))
case ipvboth:
enabled, err := getKernelBoolParam(getForwardingKernelParam(ipv4, ""))
if err != nil || !enabled {
return enabled, err
}
return getKernelBoolParam(getForwardingKernelParam(ipv6, iface))
default:
return true, nil
}
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | endpoint.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/endpoint.go#L314-L318 | go | train | // isServiceEnabled check if service is enabled on the endpoint | func (ep *endpoint) isServiceEnabled() bool | // isServiceEnabled check if service is enabled on the endpoint
func (ep *endpoint) isServiceEnabled() bool | {
ep.Lock()
defer ep.Unlock()
return ep.serviceEnabled
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | endpoint.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/endpoint.go#L321-L325 | go | train | // enableService sets service enabled on the endpoint | func (ep *endpoint) enableService() | // enableService sets service enabled on the endpoint
func (ep *endpoint) enableService() | {
ep.Lock()
defer ep.Unlock()
ep.serviceEnabled = true
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | endpoint.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/endpoint.go#L328-L332 | go | train | // disableService disables service on the endpoint | func (ep *endpoint) disableService() | // disableService disables service on the endpoint
func (ep *endpoint) disableService() | {
ep.Lock()
defer ep.Unlock()
ep.serviceEnabled = false
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | endpoint.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/endpoint.go#L341-L347 | go | train | // endpoint Key structure : endpoint/network-id/endpoint-id | func (ep *endpoint) Key() []string | // endpoint Key structure : endpoint/network-id/endpoint-id
func (ep *endpoint) Key() []string | {
if ep.network == nil {
return nil
}
return []string{datastore.EndpointKeyPrefix, ep.network.id, ep.id}
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | endpoint.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/endpoint.go#L928-L934 | go | train | // EndpointOptionGeneric function returns an option setter for a Generic option defined
// in a Dictionary of Key-Value pair | func EndpointOptionGeneric(generic map[string]interface{}) EndpointOption | // EndpointOptionGeneric function returns an option setter for a Generic option defined
// in a Dictionary of Key-Value pair
func EndpointOptionGeneric(generic map[string]interface{}) EndpointOption | {
return func(ep *endpoint) {
for k, v := range generic {
ep.generic[k] = v
}
}
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | endpoint.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/endpoint.go#L942-L957 | go | train | // CreateOptionIpam function returns an option setter for the ipam configuration for this endpoint | func CreateOptionIpam(ipV4, ipV6 net.IP, llIPs []net.IP, ipamOptions map[string]string) EndpointOption | // CreateOptionIpam function returns an option setter for the ipam configuration for this endpoint
func CreateOptionIpam(ipV4, ipV6 net.IP, llIPs []net.IP, ipamOptions map[string]string) EndpointOption | {
return func(ep *endpoint) {
ep.prefAddress = ipV4
ep.prefAddressV6 = ipV6
if len(llIPs) != 0 {
for _, ip := range llIPs {
nw := &net.IPNet{IP: ip, Mask: linkLocalMask}
if ip.To4() == nil {
nw.Mask = linkLocalMaskIPv6
}
ep.iface.llAddrs = append(ep.iface.llAddrs, nw)
}
}
ep.ipamOptions = ipamOptions
}
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | endpoint.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/endpoint.go#L961-L970 | go | train | // CreateOptionExposedPorts function returns an option setter for the container exposed
// ports option to be passed to network.CreateEndpoint() method. | func CreateOptionExposedPorts(exposedPorts []types.TransportPort) EndpointOption | // CreateOptionExposedPorts function returns an option setter for the container exposed
// ports option to be passed to network.CreateEndpoint() method.
func CreateOptionExposedPorts(exposedPorts []types.TransportPort) EndpointOption | {
return func(ep *endpoint) {
// Defensive copy
eps := make([]types.TransportPort, len(exposedPorts))
copy(eps, exposedPorts)
// Store endpoint label and in generic because driver needs it
ep.exposedPorts = eps
ep.generic[netlabel.ExposedPorts] = eps
}
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | endpoint.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/endpoint.go#L974-L981 | go | train | // CreateOptionPortMapping function returns an option setter for the mapping
// ports option to be passed to network.CreateEndpoint() method. | func CreateOptionPortMapping(portBindings []types.PortBinding) EndpointOption | // CreateOptionPortMapping function returns an option setter for the mapping
// ports option to be passed to network.CreateEndpoint() method.
func CreateOptionPortMapping(portBindings []types.PortBinding) EndpointOption | {
return func(ep *endpoint) {
// Store a copy of the bindings as generic data to pass to the driver
pbs := make([]types.PortBinding, len(portBindings))
copy(pbs, portBindings)
ep.generic[netlabel.PortMap] = pbs
}
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | endpoint.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/endpoint.go#L985-L989 | go | train | // CreateOptionDNS function returns an option setter for dns entry option to
// be passed to container Create method. | func CreateOptionDNS(dns []string) EndpointOption | // CreateOptionDNS function returns an option setter for dns entry option to
// be passed to container Create method.
func CreateOptionDNS(dns []string) EndpointOption | {
return func(ep *endpoint) {
ep.generic[netlabel.DNSServers] = dns
}
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | endpoint.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/endpoint.go#L1008-L1015 | go | train | // CreateOptionAlias function returns an option setter for setting endpoint alias | func CreateOptionAlias(name string, alias string) EndpointOption | // CreateOptionAlias function returns an option setter for setting endpoint alias
func CreateOptionAlias(name string, alias string) EndpointOption | {
return func(ep *endpoint) {
if ep.aliases == nil {
ep.aliases = make(map[string]string)
}
ep.aliases[alias] = name
}
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | endpoint.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/endpoint.go#L1018-L1026 | go | train | // CreateOptionService function returns an option setter for setting service binding configuration | func CreateOptionService(name, id string, vip net.IP, ingressPorts []*PortConfig, aliases []string) EndpointOption | // CreateOptionService function returns an option setter for setting service binding configuration
func CreateOptionService(name, id string, vip net.IP, ingressPorts []*PortConfig, aliases []string) EndpointOption | {
return func(ep *endpoint) {
ep.svcName = name
ep.svcID = id
ep.virtualIP = vip
ep.ingressPorts = ingressPorts
ep.svcAliases = aliases
}
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | endpoint.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/endpoint.go#L1029-L1033 | go | train | // CreateOptionMyAlias function returns an option setter for setting endpoint's self alias | func CreateOptionMyAlias(alias string) EndpointOption | // CreateOptionMyAlias function returns an option setter for setting endpoint's self alias
func CreateOptionMyAlias(alias string) EndpointOption | {
return func(ep *endpoint) {
ep.myAliases = append(ep.myAliases, alias)
}
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | endpoint.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/endpoint.go#L1044-L1057 | go | train | // JoinOptionPriority function returns an option setter for priority option to
// be passed to the endpoint.Join() method. | func JoinOptionPriority(ep Endpoint, prio int) EndpointOption | // JoinOptionPriority function returns an option setter for priority option to
// be passed to the endpoint.Join() method.
func JoinOptionPriority(ep Endpoint, prio int) EndpointOption | {
return func(ep *endpoint) {
// ep lock already acquired
c := ep.network.getController()
c.Lock()
sb, ok := c.sandboxes[ep.sandboxID]
c.Unlock()
if !ok {
logrus.Errorf("Could not set endpoint priority value during Join to endpoint %s: No sandbox id present in endpoint", ep.id)
return
}
sb.epPriority[ep.id] = prio
}
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | iptables/conntrack.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/iptables/conntrack.go#L24-L51 | go | train | // DeleteConntrackEntries deletes all the conntrack connections on the host for the specified IP
// Returns the number of flows deleted for IPv4, IPv6 else error | func DeleteConntrackEntries(nlh *netlink.Handle, ipv4List []net.IP, ipv6List []net.IP) (uint, uint, error) | // DeleteConntrackEntries deletes all the conntrack connections on the host for the specified IP
// Returns the number of flows deleted for IPv4, IPv6 else error
func DeleteConntrackEntries(nlh *netlink.Handle, ipv4List []net.IP, ipv6List []net.IP) (uint, uint, error) | {
if !IsConntrackProgrammable(nlh) {
return 0, 0, ErrConntrackNotConfigurable
}
var totalIPv4FlowPurged uint
for _, ipAddress := range ipv4List {
flowPurged, err := purgeConntrackState(nlh, syscall.AF_INET, ipAddress)
if err != nil {
logrus.Warnf("Failed to delete conntrack state for %s: %v", ipAddress, err)
continue
}
totalIPv4FlowPurged += flowPurged
}
var totalIPv6FlowPurged uint
for _, ipAddress := range ipv6List {
flowPurged, err := purgeConntrackState(nlh, syscall.AF_INET6, ipAddress)
if err != nil {
logrus.Warnf("Failed to delete conntrack state for %s: %v", ipAddress, err)
continue
}
totalIPv6FlowPurged += flowPurged
}
logrus.Debugf("DeleteConntrackEntries purged ipv4:%d, ipv6:%d", totalIPv4FlowPurged, totalIPv6FlowPurged)
return totalIPv4FlowPurged, totalIPv6FlowPurged, nil
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | drivers/overlay/ovmanager/ovmanager.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/overlay/ovmanager/ovmanager.go#L49-L67 | go | train | // Init registers a new instance of overlay driver | func Init(dc driverapi.DriverCallback, config map[string]interface{}) error | // Init registers a new instance of overlay driver
func Init(dc driverapi.DriverCallback, config map[string]interface{}) error | {
var err error
c := driverapi.Capability{
DataScope: datastore.GlobalScope,
ConnectivityScope: datastore.GlobalScope,
}
d := &driver{
networks: networkTable{},
config: config,
}
d.vxlanIdm, err = idm.New(nil, "vxlan-id", 0, vxlanIDEnd)
if err != nil {
return fmt.Errorf("failed to initialize vxlan id manager: %v", err)
}
return dc.RegisterDriver(networkType, d, c)
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | client/service.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/service.go#L152-L162 | go | train | // Parse service name for "SERVICE[.NETWORK]" format | func parseServiceName(name string) (string, string) | // Parse service name for "SERVICE[.NETWORK]" format
func parseServiceName(name string) (string, string) | {
s := strings.Split(name, ".")
var sName, nName string
if len(s) > 1 {
nName = s[len(s)-1]
sName = strings.Join(s[:len(s)-1], ".")
} else {
sName = s[0]
}
return sName, nName
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | client/service.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/service.go#L165-L190 | go | train | // CmdServicePublish handles service create UI | func (cli *NetworkCli) CmdServicePublish(chain string, args ...string) error | // CmdServicePublish handles service create UI
func (cli *NetworkCli) CmdServicePublish(chain string, args ...string) error | {
cmd := cli.Subcmd(chain, "publish", "SERVICE[.NETWORK]", "Publish a new service on a network", false)
flAlias := opts.NewListOpts(netutils.ValidateAlias)
cmd.Var(&flAlias, []string{"-alias"}, "Add alias to self")
cmd.Require(flag.Exact, 1)
err := cmd.ParseFlags(args, true)
if err != nil {
return err
}
sn, nn := parseServiceName(cmd.Arg(0))
sc := serviceCreate{Name: sn, Network: nn, MyAliases: flAlias.GetAll()}
obj, _, err := readBody(cli.call("POST", "/services", sc, 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/service.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/service.go#L193-L212 | go | train | // CmdServiceUnpublish handles service delete UI | func (cli *NetworkCli) CmdServiceUnpublish(chain string, args ...string) error | // CmdServiceUnpublish handles service delete UI
func (cli *NetworkCli) CmdServiceUnpublish(chain string, args ...string) error | {
cmd := cli.Subcmd(chain, "unpublish", "SERVICE[.NETWORK]", "Removes a service", false)
force := cmd.Bool([]string{"f", "-force"}, false, "force unpublish service")
cmd.Require(flag.Exact, 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
}
sd := serviceDelete{Name: sn, Force: *force}
_, _, err = readBody(cli.call("DELETE", "/services/"+serviceID, sd, nil))
return err
} |
docker/libnetwork | 9ff9b57c344df5cd47443ad9e65702ec85c5aeb0 | client/service.go | https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/service.go#L215-L269 | go | train | // CmdServiceLs handles service list UI | func (cli *NetworkCli) CmdServiceLs(chain string, args ...string) error | // CmdServiceLs handles service list UI
func (cli *NetworkCli) CmdServiceLs(chain string, args ...string) error | {
cmd := cli.Subcmd(chain, "ls", "SERVICE", "Lists all the services on a network", false)
flNetwork := cmd.String([]string{"net", "-network"}, "", "Only show the services that are published on the specified network")
quiet := cmd.Bool([]string{"q", "-quiet"}, false, "Only display numeric IDs")
noTrunc := cmd.Bool([]string{"#notrunc", "-no-trunc"}, false, "Do not truncate the output")
err := cmd.ParseFlags(args, true)
if err != nil {
return err
}
var obj []byte
if *flNetwork == "" {
obj, _, err = readBody(cli.call("GET", "/services", nil, nil))
} else {
obj, _, err = readBody(cli.call("GET", "/services?network="+*flNetwork, nil, nil))
}
if err != nil {
return err
}
var serviceResources []serviceResource
err = json.Unmarshal(obj, &serviceResources)
if err != nil {
fmt.Println(err)
return err
}
wr := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
// unless quiet (-q) is specified, print field titles
if !*quiet {
fmt.Fprintln(wr, "SERVICE ID\tNAME\tNETWORK\tCONTAINER\tSANDBOX")
}
for _, sr := range serviceResources {
ID := sr.ID
bkID, sbID, err := getBackendID(cli, ID)
if err != nil {
return err
}
if !*noTrunc {
ID = stringid.TruncateID(ID)
bkID = stringid.TruncateID(bkID)
sbID = stringid.TruncateID(sbID)
}
if !*quiet {
fmt.Fprintf(wr, "%s\t%s\t%s\t%s\t%s\n", ID, sr.Name, sr.Network, bkID, sbID)
} else {
fmt.Fprintln(wr, ID)
}
}
wr.Flush()
return nil
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.