repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
docker/libnetwork
ipam/structures.go
UnmarshalJSON
func (p *PoolData) UnmarshalJSON(data []byte) error { var ( err error t struct { ParentKey SubnetKey Pool string Range *AddressRange `json:",omitempty"` RefCount int } ) if err = json.Unmarshal(data, &t); err != nil { return err } p.ParentKey = t.ParentKey p.Range = t.Range p.RefCount = t.RefCount if t.Pool != "" { if p.Pool, err = types.ParseCIDR(t.Pool); err != nil { return err } } return nil }
go
func (p *PoolData) UnmarshalJSON(data []byte) error { var ( err error t struct { ParentKey SubnetKey Pool string Range *AddressRange `json:",omitempty"` RefCount int } ) if err = json.Unmarshal(data, &t); err != nil { return err } p.ParentKey = t.ParentKey p.Range = t.Range p.RefCount = t.RefCount if t.Pool != "" { if p.Pool, err = types.ParseCIDR(t.Pool); err != nil { return err } } return nil }
[ "func", "(", "p", "*", "PoolData", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "error", "{", "var", "(", "err", "error", "\n", "t", "struct", "{", "ParentKey", "SubnetKey", "\n", "Pool", "string", "\n", "Range", "*", "AddressRange", "`json:\",omitempty\"`", "\n", "RefCount", "int", "\n", "}", "\n", ")", "\n\n", "if", "err", "=", "json", ".", "Unmarshal", "(", "data", ",", "&", "t", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "p", ".", "ParentKey", "=", "t", ".", "ParentKey", "\n", "p", ".", "Range", "=", "t", ".", "Range", "\n", "p", ".", "RefCount", "=", "t", ".", "RefCount", "\n", "if", "t", ".", "Pool", "!=", "\"", "\"", "{", "if", "p", ".", "Pool", ",", "err", "=", "types", ".", "ParseCIDR", "(", "t", ".", "Pool", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// UnmarshalJSON decodes data into the PoolData object
[ "UnmarshalJSON", "decodes", "data", "into", "the", "PoolData", "object" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipam/structures.go#L129-L154
train
docker/libnetwork
ipam/structures.go
MarshalJSON
func (aSpace *addrSpace) MarshalJSON() ([]byte, error) { aSpace.Lock() defer aSpace.Unlock() m := map[string]interface{}{ "Scope": string(aSpace.scope), } if aSpace.subnets != nil { s := map[string]*PoolData{} for k, v := range aSpace.subnets { s[k.String()] = v } m["Subnets"] = s } return json.Marshal(m) }
go
func (aSpace *addrSpace) MarshalJSON() ([]byte, error) { aSpace.Lock() defer aSpace.Unlock() m := map[string]interface{}{ "Scope": string(aSpace.scope), } if aSpace.subnets != nil { s := map[string]*PoolData{} for k, v := range aSpace.subnets { s[k.String()] = v } m["Subnets"] = s } return json.Marshal(m) }
[ "func", "(", "aSpace", "*", "addrSpace", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "aSpace", ".", "Lock", "(", ")", "\n", "defer", "aSpace", ".", "Unlock", "(", ")", "\n\n", "m", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "string", "(", "aSpace", ".", "scope", ")", ",", "}", "\n\n", "if", "aSpace", ".", "subnets", "!=", "nil", "{", "s", ":=", "map", "[", "string", "]", "*", "PoolData", "{", "}", "\n", "for", "k", ",", "v", ":=", "range", "aSpace", ".", "subnets", "{", "s", "[", "k", ".", "String", "(", ")", "]", "=", "v", "\n", "}", "\n", "m", "[", "\"", "\"", "]", "=", "s", "\n", "}", "\n\n", "return", "json", ".", "Marshal", "(", "m", ")", "\n", "}" ]
// MarshalJSON returns the JSON encoding of the addrSpace object
[ "MarshalJSON", "returns", "the", "JSON", "encoding", "of", "the", "addrSpace", "object" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipam/structures.go#L157-L174
train
docker/libnetwork
ipam/structures.go
UnmarshalJSON
func (aSpace *addrSpace) UnmarshalJSON(data []byte) error { aSpace.Lock() defer aSpace.Unlock() m := map[string]interface{}{} err := json.Unmarshal(data, &m) if err != nil { return err } aSpace.scope = datastore.LocalScope s := m["Scope"].(string) if s == string(datastore.GlobalScope) { aSpace.scope = datastore.GlobalScope } if v, ok := m["Subnets"]; ok { sb, _ := json.Marshal(v) var s map[string]*PoolData err := json.Unmarshal(sb, &s) if err != nil { return err } for ks, v := range s { k := SubnetKey{} k.FromString(ks) aSpace.subnets[k] = v } } return nil }
go
func (aSpace *addrSpace) UnmarshalJSON(data []byte) error { aSpace.Lock() defer aSpace.Unlock() m := map[string]interface{}{} err := json.Unmarshal(data, &m) if err != nil { return err } aSpace.scope = datastore.LocalScope s := m["Scope"].(string) if s == string(datastore.GlobalScope) { aSpace.scope = datastore.GlobalScope } if v, ok := m["Subnets"]; ok { sb, _ := json.Marshal(v) var s map[string]*PoolData err := json.Unmarshal(sb, &s) if err != nil { return err } for ks, v := range s { k := SubnetKey{} k.FromString(ks) aSpace.subnets[k] = v } } return nil }
[ "func", "(", "aSpace", "*", "addrSpace", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "error", "{", "aSpace", ".", "Lock", "(", ")", "\n", "defer", "aSpace", ".", "Unlock", "(", ")", "\n\n", "m", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "}", "\n", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "&", "m", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "aSpace", ".", "scope", "=", "datastore", ".", "LocalScope", "\n", "s", ":=", "m", "[", "\"", "\"", "]", ".", "(", "string", ")", "\n", "if", "s", "==", "string", "(", "datastore", ".", "GlobalScope", ")", "{", "aSpace", ".", "scope", "=", "datastore", ".", "GlobalScope", "\n", "}", "\n\n", "if", "v", ",", "ok", ":=", "m", "[", "\"", "\"", "]", ";", "ok", "{", "sb", ",", "_", ":=", "json", ".", "Marshal", "(", "v", ")", "\n", "var", "s", "map", "[", "string", "]", "*", "PoolData", "\n", "err", ":=", "json", ".", "Unmarshal", "(", "sb", ",", "&", "s", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "ks", ",", "v", ":=", "range", "s", "{", "k", ":=", "SubnetKey", "{", "}", "\n", "k", ".", "FromString", "(", "ks", ")", "\n", "aSpace", ".", "subnets", "[", "k", "]", "=", "v", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// UnmarshalJSON decodes data into the addrSpace object
[ "UnmarshalJSON", "decodes", "data", "into", "the", "addrSpace", "object" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipam/structures.go#L177-L208
train
docker/libnetwork
ipam/structures.go
CopyTo
func (p *PoolData) CopyTo(dstP *PoolData) error { dstP.ParentKey = p.ParentKey dstP.Pool = types.GetIPNetCopy(p.Pool) if p.Range != nil { dstP.Range = &AddressRange{} dstP.Range.Sub = types.GetIPNetCopy(p.Range.Sub) dstP.Range.Start = p.Range.Start dstP.Range.End = p.Range.End } dstP.RefCount = p.RefCount return nil }
go
func (p *PoolData) CopyTo(dstP *PoolData) error { dstP.ParentKey = p.ParentKey dstP.Pool = types.GetIPNetCopy(p.Pool) if p.Range != nil { dstP.Range = &AddressRange{} dstP.Range.Sub = types.GetIPNetCopy(p.Range.Sub) dstP.Range.Start = p.Range.Start dstP.Range.End = p.Range.End } dstP.RefCount = p.RefCount return nil }
[ "func", "(", "p", "*", "PoolData", ")", "CopyTo", "(", "dstP", "*", "PoolData", ")", "error", "{", "dstP", ".", "ParentKey", "=", "p", ".", "ParentKey", "\n", "dstP", ".", "Pool", "=", "types", ".", "GetIPNetCopy", "(", "p", ".", "Pool", ")", "\n\n", "if", "p", ".", "Range", "!=", "nil", "{", "dstP", ".", "Range", "=", "&", "AddressRange", "{", "}", "\n", "dstP", ".", "Range", ".", "Sub", "=", "types", ".", "GetIPNetCopy", "(", "p", ".", "Range", ".", "Sub", ")", "\n", "dstP", ".", "Range", ".", "Start", "=", "p", ".", "Range", ".", "Start", "\n", "dstP", ".", "Range", ".", "End", "=", "p", ".", "Range", ".", "End", "\n", "}", "\n\n", "dstP", ".", "RefCount", "=", "p", ".", "RefCount", "\n", "return", "nil", "\n", "}" ]
// CopyTo deep copies the pool data to the destination pooldata
[ "CopyTo", "deep", "copies", "the", "pool", "data", "to", "the", "destination", "pooldata" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipam/structures.go#L211-L224
train
docker/libnetwork
ipam/structures.go
updatePoolDBOnAdd
func (aSpace *addrSpace) updatePoolDBOnAdd(k SubnetKey, nw *net.IPNet, ipr *AddressRange, pdf bool) (func() error, error) { aSpace.Lock() defer aSpace.Unlock() // Check if already allocated if _, ok := aSpace.subnets[k]; ok { if pdf { return nil, types.InternalMaskableErrorf("predefined pool %s is already reserved", nw) } // This means the same pool is already allocated. updatePoolDBOnAdd is called when there // is request for a pool/subpool. It should ensure there is no overlap with existing pools return nil, ipamapi.ErrPoolOverlap } // If master pool, check for overlap if ipr == nil { if aSpace.contains(k.AddressSpace, nw) { return nil, ipamapi.ErrPoolOverlap } // This is a new master pool, add it along with corresponding bitmask aSpace.subnets[k] = &PoolData{Pool: nw, RefCount: 1} return func() error { return aSpace.alloc.insertBitMask(k, nw) }, nil } // This is a new non-master pool (subPool) p := &PoolData{ ParentKey: SubnetKey{AddressSpace: k.AddressSpace, Subnet: k.Subnet}, Pool: nw, Range: ipr, RefCount: 1, } aSpace.subnets[k] = p // Look for parent pool pp, ok := aSpace.subnets[p.ParentKey] if ok { aSpace.incRefCount(pp, 1) return func() error { return nil }, nil } // Parent pool does not exist, add it along with corresponding bitmask aSpace.subnets[p.ParentKey] = &PoolData{Pool: nw, RefCount: 1} return func() error { return aSpace.alloc.insertBitMask(p.ParentKey, nw) }, nil }
go
func (aSpace *addrSpace) updatePoolDBOnAdd(k SubnetKey, nw *net.IPNet, ipr *AddressRange, pdf bool) (func() error, error) { aSpace.Lock() defer aSpace.Unlock() // Check if already allocated if _, ok := aSpace.subnets[k]; ok { if pdf { return nil, types.InternalMaskableErrorf("predefined pool %s is already reserved", nw) } // This means the same pool is already allocated. updatePoolDBOnAdd is called when there // is request for a pool/subpool. It should ensure there is no overlap with existing pools return nil, ipamapi.ErrPoolOverlap } // If master pool, check for overlap if ipr == nil { if aSpace.contains(k.AddressSpace, nw) { return nil, ipamapi.ErrPoolOverlap } // This is a new master pool, add it along with corresponding bitmask aSpace.subnets[k] = &PoolData{Pool: nw, RefCount: 1} return func() error { return aSpace.alloc.insertBitMask(k, nw) }, nil } // This is a new non-master pool (subPool) p := &PoolData{ ParentKey: SubnetKey{AddressSpace: k.AddressSpace, Subnet: k.Subnet}, Pool: nw, Range: ipr, RefCount: 1, } aSpace.subnets[k] = p // Look for parent pool pp, ok := aSpace.subnets[p.ParentKey] if ok { aSpace.incRefCount(pp, 1) return func() error { return nil }, nil } // Parent pool does not exist, add it along with corresponding bitmask aSpace.subnets[p.ParentKey] = &PoolData{Pool: nw, RefCount: 1} return func() error { return aSpace.alloc.insertBitMask(p.ParentKey, nw) }, nil }
[ "func", "(", "aSpace", "*", "addrSpace", ")", "updatePoolDBOnAdd", "(", "k", "SubnetKey", ",", "nw", "*", "net", ".", "IPNet", ",", "ipr", "*", "AddressRange", ",", "pdf", "bool", ")", "(", "func", "(", ")", "error", ",", "error", ")", "{", "aSpace", ".", "Lock", "(", ")", "\n", "defer", "aSpace", ".", "Unlock", "(", ")", "\n\n", "// Check if already allocated", "if", "_", ",", "ok", ":=", "aSpace", ".", "subnets", "[", "k", "]", ";", "ok", "{", "if", "pdf", "{", "return", "nil", ",", "types", ".", "InternalMaskableErrorf", "(", "\"", "\"", ",", "nw", ")", "\n", "}", "\n", "// This means the same pool is already allocated. updatePoolDBOnAdd is called when there", "// is request for a pool/subpool. It should ensure there is no overlap with existing pools", "return", "nil", ",", "ipamapi", ".", "ErrPoolOverlap", "\n", "}", "\n\n", "// If master pool, check for overlap", "if", "ipr", "==", "nil", "{", "if", "aSpace", ".", "contains", "(", "k", ".", "AddressSpace", ",", "nw", ")", "{", "return", "nil", ",", "ipamapi", ".", "ErrPoolOverlap", "\n", "}", "\n", "// This is a new master pool, add it along with corresponding bitmask", "aSpace", ".", "subnets", "[", "k", "]", "=", "&", "PoolData", "{", "Pool", ":", "nw", ",", "RefCount", ":", "1", "}", "\n", "return", "func", "(", ")", "error", "{", "return", "aSpace", ".", "alloc", ".", "insertBitMask", "(", "k", ",", "nw", ")", "}", ",", "nil", "\n", "}", "\n\n", "// This is a new non-master pool (subPool)", "p", ":=", "&", "PoolData", "{", "ParentKey", ":", "SubnetKey", "{", "AddressSpace", ":", "k", ".", "AddressSpace", ",", "Subnet", ":", "k", ".", "Subnet", "}", ",", "Pool", ":", "nw", ",", "Range", ":", "ipr", ",", "RefCount", ":", "1", ",", "}", "\n", "aSpace", ".", "subnets", "[", "k", "]", "=", "p", "\n\n", "// Look for parent pool", "pp", ",", "ok", ":=", "aSpace", ".", "subnets", "[", "p", ".", "ParentKey", "]", "\n", "if", "ok", "{", "aSpace", ".", "incRefCount", "(", "pp", ",", "1", ")", "\n", "return", "func", "(", ")", "error", "{", "return", "nil", "}", ",", "nil", "\n", "}", "\n\n", "// Parent pool does not exist, add it along with corresponding bitmask", "aSpace", ".", "subnets", "[", "p", ".", "ParentKey", "]", "=", "&", "PoolData", "{", "Pool", ":", "nw", ",", "RefCount", ":", "1", "}", "\n", "return", "func", "(", ")", "error", "{", "return", "aSpace", ".", "alloc", ".", "insertBitMask", "(", "p", ".", "ParentKey", ",", "nw", ")", "}", ",", "nil", "\n", "}" ]
// updatePoolDBOnAdd returns a closure which will add the subnet k to the address space when executed.
[ "updatePoolDBOnAdd", "returns", "a", "closure", "which", "will", "add", "the", "subnet", "k", "to", "the", "address", "space", "when", "executed", "." ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipam/structures.go#L261-L304
train
docker/libnetwork
ipam/structures.go
contains
func (aSpace *addrSpace) contains(space string, nw *net.IPNet) bool { for k, v := range aSpace.subnets { if space == k.AddressSpace && k.ChildSubnet == "" { if nw.Contains(v.Pool.IP) || v.Pool.Contains(nw.IP) { return true } } } return false }
go
func (aSpace *addrSpace) contains(space string, nw *net.IPNet) bool { for k, v := range aSpace.subnets { if space == k.AddressSpace && k.ChildSubnet == "" { if nw.Contains(v.Pool.IP) || v.Pool.Contains(nw.IP) { return true } } } return false }
[ "func", "(", "aSpace", "*", "addrSpace", ")", "contains", "(", "space", "string", ",", "nw", "*", "net", ".", "IPNet", ")", "bool", "{", "for", "k", ",", "v", ":=", "range", "aSpace", ".", "subnets", "{", "if", "space", "==", "k", ".", "AddressSpace", "&&", "k", ".", "ChildSubnet", "==", "\"", "\"", "{", "if", "nw", ".", "Contains", "(", "v", ".", "Pool", ".", "IP", ")", "||", "v", ".", "Pool", ".", "Contains", "(", "nw", ".", "IP", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// Checks whether the passed subnet is a superset or subset of any of the subset in this config db
[ "Checks", "whether", "the", "passed", "subnet", "is", "a", "superset", "or", "subset", "of", "any", "of", "the", "subset", "in", "this", "config", "db" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipam/structures.go#L348-L357
train
docker/libnetwork
cmd/proxy/stub_proxy.go
NewStubProxy
func NewStubProxy(frontendAddr, backendAddr net.Addr) (Proxy, error) { return &StubProxy{ frontendAddr: frontendAddr, backendAddr: backendAddr, }, nil }
go
func NewStubProxy(frontendAddr, backendAddr net.Addr) (Proxy, error) { return &StubProxy{ frontendAddr: frontendAddr, backendAddr: backendAddr, }, nil }
[ "func", "NewStubProxy", "(", "frontendAddr", ",", "backendAddr", "net", ".", "Addr", ")", "(", "Proxy", ",", "error", ")", "{", "return", "&", "StubProxy", "{", "frontendAddr", ":", "frontendAddr", ",", "backendAddr", ":", "backendAddr", ",", "}", ",", "nil", "\n", "}" ]
// NewStubProxy creates a new StubProxy
[ "NewStubProxy", "creates", "a", "new", "StubProxy" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/cmd/proxy/stub_proxy.go#L26-L31
train
docker/libnetwork
netutils/utils_linux.go
CheckRouteOverlaps
func CheckRouteOverlaps(toCheck *net.IPNet) error { if networkGetRoutesFct == nil { networkGetRoutesFct = ns.NlHandle().RouteList } networks, err := networkGetRoutesFct(nil, netlink.FAMILY_V4) if err != nil { return err } for _, network := range networks { if network.Dst != nil && NetworkOverlaps(toCheck, network.Dst) { return ErrNetworkOverlaps } } return nil }
go
func CheckRouteOverlaps(toCheck *net.IPNet) error { if networkGetRoutesFct == nil { networkGetRoutesFct = ns.NlHandle().RouteList } networks, err := networkGetRoutesFct(nil, netlink.FAMILY_V4) if err != nil { return err } for _, network := range networks { if network.Dst != nil && NetworkOverlaps(toCheck, network.Dst) { return ErrNetworkOverlaps } } return nil }
[ "func", "CheckRouteOverlaps", "(", "toCheck", "*", "net", ".", "IPNet", ")", "error", "{", "if", "networkGetRoutesFct", "==", "nil", "{", "networkGetRoutesFct", "=", "ns", ".", "NlHandle", "(", ")", ".", "RouteList", "\n", "}", "\n", "networks", ",", "err", ":=", "networkGetRoutesFct", "(", "nil", ",", "netlink", ".", "FAMILY_V4", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "_", ",", "network", ":=", "range", "networks", "{", "if", "network", ".", "Dst", "!=", "nil", "&&", "NetworkOverlaps", "(", "toCheck", ",", "network", ".", "Dst", ")", "{", "return", "ErrNetworkOverlaps", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// CheckRouteOverlaps checks whether the passed network overlaps with any existing routes
[ "CheckRouteOverlaps", "checks", "whether", "the", "passed", "network", "overlaps", "with", "any", "existing", "routes" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/netutils/utils_linux.go#L25-L39
train
docker/libnetwork
netutils/utils_linux.go
GenerateIfaceName
func GenerateIfaceName(nlh *netlink.Handle, prefix string, len int) (string, error) { linkByName := netlink.LinkByName if nlh != nil { linkByName = nlh.LinkByName } for i := 0; i < 3; i++ { name, err := GenerateRandomName(prefix, len) if err != nil { continue } _, err = linkByName(name) if err != nil { if strings.Contains(err.Error(), "not found") { return name, nil } return "", err } } return "", types.InternalErrorf("could not generate interface name") }
go
func GenerateIfaceName(nlh *netlink.Handle, prefix string, len int) (string, error) { linkByName := netlink.LinkByName if nlh != nil { linkByName = nlh.LinkByName } for i := 0; i < 3; i++ { name, err := GenerateRandomName(prefix, len) if err != nil { continue } _, err = linkByName(name) if err != nil { if strings.Contains(err.Error(), "not found") { return name, nil } return "", err } } return "", types.InternalErrorf("could not generate interface name") }
[ "func", "GenerateIfaceName", "(", "nlh", "*", "netlink", ".", "Handle", ",", "prefix", "string", ",", "len", "int", ")", "(", "string", ",", "error", ")", "{", "linkByName", ":=", "netlink", ".", "LinkByName", "\n", "if", "nlh", "!=", "nil", "{", "linkByName", "=", "nlh", ".", "LinkByName", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "3", ";", "i", "++", "{", "name", ",", "err", ":=", "GenerateRandomName", "(", "prefix", ",", "len", ")", "\n", "if", "err", "!=", "nil", "{", "continue", "\n", "}", "\n", "_", ",", "err", "=", "linkByName", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "if", "strings", ".", "Contains", "(", "err", ".", "Error", "(", ")", ",", "\"", "\"", ")", "{", "return", "name", ",", "nil", "\n", "}", "\n", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "}", "\n", "return", "\"", "\"", ",", "types", ".", "InternalErrorf", "(", "\"", "\"", ")", "\n", "}" ]
// GenerateIfaceName returns an interface name using the passed in // prefix and the length of random bytes. The api ensures that the // there are is no interface which exists with that name.
[ "GenerateIfaceName", "returns", "an", "interface", "name", "using", "the", "passed", "in", "prefix", "and", "the", "length", "of", "random", "bytes", ".", "The", "api", "ensures", "that", "the", "there", "are", "is", "no", "interface", "which", "exists", "with", "that", "name", "." ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/netutils/utils_linux.go#L44-L63
train
docker/libnetwork
osl/namespace_linux.go
GC
func GC() { gpmLock.Lock() if len(garbagePathMap) == 0 { // No need for GC if map is empty gpmLock.Unlock() return } gpmLock.Unlock() // if content exists in the garbage paths // we can trigger GC to run, providing a // channel to be notified on completion waitGC := make(chan struct{}) gpmChan <- waitGC // wait for GC completion <-waitGC }
go
func GC() { gpmLock.Lock() if len(garbagePathMap) == 0 { // No need for GC if map is empty gpmLock.Unlock() return } gpmLock.Unlock() // if content exists in the garbage paths // we can trigger GC to run, providing a // channel to be notified on completion waitGC := make(chan struct{}) gpmChan <- waitGC // wait for GC completion <-waitGC }
[ "func", "GC", "(", ")", "{", "gpmLock", ".", "Lock", "(", ")", "\n", "if", "len", "(", "garbagePathMap", ")", "==", "0", "{", "// No need for GC if map is empty", "gpmLock", ".", "Unlock", "(", ")", "\n", "return", "\n", "}", "\n", "gpmLock", ".", "Unlock", "(", ")", "\n\n", "// if content exists in the garbage paths", "// we can trigger GC to run, providing a", "// channel to be notified on completion", "waitGC", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "gpmChan", "<-", "waitGC", "\n", "// wait for GC completion", "<-", "waitGC", "\n", "}" ]
// GC triggers garbage collection of namespace path right away // and waits for it.
[ "GC", "triggers", "garbage", "collection", "of", "namespace", "path", "right", "away", "and", "waits", "for", "it", "." ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/osl/namespace_linux.go#L138-L154
train
docker/libnetwork
osl/namespace_linux.go
GetSandboxForExternalKey
func GetSandboxForExternalKey(basePath string, key string) (Sandbox, error) { if err := createNamespaceFile(key); err != nil { return nil, err } if err := mountNetworkNamespace(basePath, key); err != nil { return nil, err } n := &networkNamespace{path: key, nextIfIndex: make(map[string]int)} sboxNs, err := netns.GetFromPath(n.path) if err != nil { return nil, fmt.Errorf("failed get network namespace %q: %v", n.path, err) } defer sboxNs.Close() n.nlHandle, err = netlink.NewHandleAt(sboxNs, syscall.NETLINK_ROUTE) if err != nil { return nil, fmt.Errorf("failed to create a netlink handle: %v", err) } err = n.nlHandle.SetSocketTimeout(ns.NetlinkSocketsTimeout) if err != nil { logrus.Warnf("Failed to set the timeout on the sandbox netlink handle sockets: %v", err) } // As starting point, disable IPv6 on all interfaces err = setIPv6(n.path, "all", false) if err != nil { logrus.Warnf("Failed to disable IPv6 on all interfaces on network namespace %q: %v", n.path, err) } if err = n.loopbackUp(); err != nil { n.nlHandle.Delete() return nil, err } return n, nil }
go
func GetSandboxForExternalKey(basePath string, key string) (Sandbox, error) { if err := createNamespaceFile(key); err != nil { return nil, err } if err := mountNetworkNamespace(basePath, key); err != nil { return nil, err } n := &networkNamespace{path: key, nextIfIndex: make(map[string]int)} sboxNs, err := netns.GetFromPath(n.path) if err != nil { return nil, fmt.Errorf("failed get network namespace %q: %v", n.path, err) } defer sboxNs.Close() n.nlHandle, err = netlink.NewHandleAt(sboxNs, syscall.NETLINK_ROUTE) if err != nil { return nil, fmt.Errorf("failed to create a netlink handle: %v", err) } err = n.nlHandle.SetSocketTimeout(ns.NetlinkSocketsTimeout) if err != nil { logrus.Warnf("Failed to set the timeout on the sandbox netlink handle sockets: %v", err) } // As starting point, disable IPv6 on all interfaces err = setIPv6(n.path, "all", false) if err != nil { logrus.Warnf("Failed to disable IPv6 on all interfaces on network namespace %q: %v", n.path, err) } if err = n.loopbackUp(); err != nil { n.nlHandle.Delete() return nil, err } return n, nil }
[ "func", "GetSandboxForExternalKey", "(", "basePath", "string", ",", "key", "string", ")", "(", "Sandbox", ",", "error", ")", "{", "if", "err", ":=", "createNamespaceFile", "(", "key", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "err", ":=", "mountNetworkNamespace", "(", "basePath", ",", "key", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "n", ":=", "&", "networkNamespace", "{", "path", ":", "key", ",", "nextIfIndex", ":", "make", "(", "map", "[", "string", "]", "int", ")", "}", "\n\n", "sboxNs", ",", "err", ":=", "netns", ".", "GetFromPath", "(", "n", ".", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "n", ".", "path", ",", "err", ")", "\n", "}", "\n", "defer", "sboxNs", ".", "Close", "(", ")", "\n\n", "n", ".", "nlHandle", ",", "err", "=", "netlink", ".", "NewHandleAt", "(", "sboxNs", ",", "syscall", ".", "NETLINK_ROUTE", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "err", "=", "n", ".", "nlHandle", ".", "SetSocketTimeout", "(", "ns", ".", "NetlinkSocketsTimeout", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "Warnf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// As starting point, disable IPv6 on all interfaces", "err", "=", "setIPv6", "(", "n", ".", "path", ",", "\"", "\"", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "Warnf", "(", "\"", "\"", ",", "n", ".", "path", ",", "err", ")", "\n", "}", "\n\n", "if", "err", "=", "n", ".", "loopbackUp", "(", ")", ";", "err", "!=", "nil", "{", "n", ".", "nlHandle", ".", "Delete", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "n", ",", "nil", "\n", "}" ]
// GetSandboxForExternalKey returns sandbox object for the supplied path
[ "GetSandboxForExternalKey", "returns", "sandbox", "object", "for", "the", "supplied", "path" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/osl/namespace_linux.go#L261-L299
train
docker/libnetwork
osl/namespace_linux.go
InitOSContext
func InitOSContext() func() { runtime.LockOSThread() if err := ns.SetNamespace(); err != nil { logrus.Error(err) } return runtime.UnlockOSThread }
go
func InitOSContext() func() { runtime.LockOSThread() if err := ns.SetNamespace(); err != nil { logrus.Error(err) } return runtime.UnlockOSThread }
[ "func", "InitOSContext", "(", ")", "func", "(", ")", "{", "runtime", ".", "LockOSThread", "(", ")", "\n", "if", "err", ":=", "ns", ".", "SetNamespace", "(", ")", ";", "err", "!=", "nil", "{", "logrus", ".", "Error", "(", "err", ")", "\n", "}", "\n", "return", "runtime", ".", "UnlockOSThread", "\n", "}" ]
// InitOSContext initializes OS context while configuring network resources
[ "InitOSContext", "initializes", "OS", "context", "while", "configuring", "network", "resources" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/osl/namespace_linux.go#L425-L431
train
docker/libnetwork
osl/namespace_linux.go
ApplyOSTweaks
func (n *networkNamespace) ApplyOSTweaks(types []SandboxType) { for _, t := range types { switch t { case SandboxTypeLoadBalancer: kernel.ApplyOSTweaks(loadBalancerConfig) } } }
go
func (n *networkNamespace) ApplyOSTweaks(types []SandboxType) { for _, t := range types { switch t { case SandboxTypeLoadBalancer: kernel.ApplyOSTweaks(loadBalancerConfig) } } }
[ "func", "(", "n", "*", "networkNamespace", ")", "ApplyOSTweaks", "(", "types", "[", "]", "SandboxType", ")", "{", "for", "_", ",", "t", ":=", "range", "types", "{", "switch", "t", "{", "case", "SandboxTypeLoadBalancer", ":", "kernel", ".", "ApplyOSTweaks", "(", "loadBalancerConfig", ")", "\n", "}", "\n", "}", "\n", "}" ]
// ApplyOSTweaks applies linux configs on the sandbox
[ "ApplyOSTweaks", "applies", "linux", "configs", "on", "the", "sandbox" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/osl/namespace_linux.go#L680-L687
train
docker/libnetwork
networkdb/watch.go
Watch
func (nDB *NetworkDB) Watch(tname, nid, key string) (*events.Channel, func()) { var matcher events.Matcher if tname != "" || nid != "" || key != "" { matcher = events.MatcherFunc(func(ev events.Event) bool { var evt event switch ev := ev.(type) { case CreateEvent: evt = event(ev) case UpdateEvent: evt = event(ev) case DeleteEvent: evt = event(ev) } if tname != "" && evt.Table != tname { return false } if nid != "" && evt.NetworkID != nid { return false } if key != "" && evt.Key != key { return false } return true }) } ch := events.NewChannel(0) sink := events.Sink(events.NewQueue(ch)) if matcher != nil { sink = events.NewFilter(sink, matcher) } nDB.broadcaster.Add(sink) return ch, func() { nDB.broadcaster.Remove(sink) ch.Close() sink.Close() } }
go
func (nDB *NetworkDB) Watch(tname, nid, key string) (*events.Channel, func()) { var matcher events.Matcher if tname != "" || nid != "" || key != "" { matcher = events.MatcherFunc(func(ev events.Event) bool { var evt event switch ev := ev.(type) { case CreateEvent: evt = event(ev) case UpdateEvent: evt = event(ev) case DeleteEvent: evt = event(ev) } if tname != "" && evt.Table != tname { return false } if nid != "" && evt.NetworkID != nid { return false } if key != "" && evt.Key != key { return false } return true }) } ch := events.NewChannel(0) sink := events.Sink(events.NewQueue(ch)) if matcher != nil { sink = events.NewFilter(sink, matcher) } nDB.broadcaster.Add(sink) return ch, func() { nDB.broadcaster.Remove(sink) ch.Close() sink.Close() } }
[ "func", "(", "nDB", "*", "NetworkDB", ")", "Watch", "(", "tname", ",", "nid", ",", "key", "string", ")", "(", "*", "events", ".", "Channel", ",", "func", "(", ")", ")", "{", "var", "matcher", "events", ".", "Matcher", "\n\n", "if", "tname", "!=", "\"", "\"", "||", "nid", "!=", "\"", "\"", "||", "key", "!=", "\"", "\"", "{", "matcher", "=", "events", ".", "MatcherFunc", "(", "func", "(", "ev", "events", ".", "Event", ")", "bool", "{", "var", "evt", "event", "\n", "switch", "ev", ":=", "ev", ".", "(", "type", ")", "{", "case", "CreateEvent", ":", "evt", "=", "event", "(", "ev", ")", "\n", "case", "UpdateEvent", ":", "evt", "=", "event", "(", "ev", ")", "\n", "case", "DeleteEvent", ":", "evt", "=", "event", "(", "ev", ")", "\n", "}", "\n\n", "if", "tname", "!=", "\"", "\"", "&&", "evt", ".", "Table", "!=", "tname", "{", "return", "false", "\n", "}", "\n\n", "if", "nid", "!=", "\"", "\"", "&&", "evt", ".", "NetworkID", "!=", "nid", "{", "return", "false", "\n", "}", "\n\n", "if", "key", "!=", "\"", "\"", "&&", "evt", ".", "Key", "!=", "key", "{", "return", "false", "\n", "}", "\n\n", "return", "true", "\n", "}", ")", "\n", "}", "\n\n", "ch", ":=", "events", ".", "NewChannel", "(", "0", ")", "\n", "sink", ":=", "events", ".", "Sink", "(", "events", ".", "NewQueue", "(", "ch", ")", ")", "\n\n", "if", "matcher", "!=", "nil", "{", "sink", "=", "events", ".", "NewFilter", "(", "sink", ",", "matcher", ")", "\n", "}", "\n\n", "nDB", ".", "broadcaster", ".", "Add", "(", "sink", ")", "\n", "return", "ch", ",", "func", "(", ")", "{", "nDB", ".", "broadcaster", ".", "Remove", "(", "sink", ")", "\n", "ch", ".", "Close", "(", ")", "\n", "sink", ".", "Close", "(", ")", "\n", "}", "\n", "}" ]
// Watch creates a watcher with filters for a particular table or // network or key or any combination of the tuple. If any of the // filter is an empty string it acts as a wildcard for that // field. Watch returns a channel of events, where the events will be // sent.
[ "Watch", "creates", "a", "watcher", "with", "filters", "for", "a", "particular", "table", "or", "network", "or", "key", "or", "any", "combination", "of", "the", "tuple", ".", "If", "any", "of", "the", "filter", "is", "an", "empty", "string", "it", "acts", "as", "a", "wildcard", "for", "that", "field", ".", "Watch", "returns", "a", "channel", "of", "events", "where", "the", "events", "will", "be", "sent", "." ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/networkdb/watch.go#L46-L90
train
docker/libnetwork
cmd/proxy/tcp_proxy.go
Run
func (proxy *TCPProxy) Run() { quit := make(chan bool) defer close(quit) for { client, err := proxy.listener.Accept() if err != nil { log.Printf("Stopping proxy on tcp/%v for tcp/%v (%s)", proxy.frontendAddr, proxy.backendAddr, err) return } go proxy.clientLoop(client.(*net.TCPConn), quit) } }
go
func (proxy *TCPProxy) Run() { quit := make(chan bool) defer close(quit) for { client, err := proxy.listener.Accept() if err != nil { log.Printf("Stopping proxy on tcp/%v for tcp/%v (%s)", proxy.frontendAddr, proxy.backendAddr, err) return } go proxy.clientLoop(client.(*net.TCPConn), quit) } }
[ "func", "(", "proxy", "*", "TCPProxy", ")", "Run", "(", ")", "{", "quit", ":=", "make", "(", "chan", "bool", ")", "\n", "defer", "close", "(", "quit", ")", "\n", "for", "{", "client", ",", "err", ":=", "proxy", ".", "listener", ".", "Accept", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "proxy", ".", "frontendAddr", ",", "proxy", ".", "backendAddr", ",", "err", ")", "\n", "return", "\n", "}", "\n", "go", "proxy", ".", "clientLoop", "(", "client", ".", "(", "*", "net", ".", "TCPConn", ")", ",", "quit", ")", "\n", "}", "\n", "}" ]
// Run starts forwarding the traffic using TCP.
[ "Run", "starts", "forwarding", "the", "traffic", "using", "TCP", "." ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/cmd/proxy/tcp_proxy.go#L69-L80
train
docker/libnetwork
bitseq/store.go
SetValue
func (h *Handle) SetValue(value []byte) error { return json.Unmarshal(value, h) }
go
func (h *Handle) SetValue(value []byte) error { return json.Unmarshal(value, h) }
[ "func", "(", "h", "*", "Handle", ")", "SetValue", "(", "value", "[", "]", "byte", ")", "error", "{", "return", "json", ".", "Unmarshal", "(", "value", ",", "h", ")", "\n", "}" ]
// SetValue unmarshals the data from the KV store
[ "SetValue", "unmarshals", "the", "data", "from", "the", "KV", "store" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/bitseq/store.go#L35-L37
train
docker/libnetwork
bitseq/store.go
New
func (h *Handle) New() datastore.KVObject { h.Lock() defer h.Unlock() return &Handle{ app: h.app, store: h.store, } }
go
func (h *Handle) New() datastore.KVObject { h.Lock() defer h.Unlock() return &Handle{ app: h.app, store: h.store, } }
[ "func", "(", "h", "*", "Handle", ")", "New", "(", ")", "datastore", ".", "KVObject", "{", "h", ".", "Lock", "(", ")", "\n", "defer", "h", ".", "Unlock", "(", ")", "\n\n", "return", "&", "Handle", "{", "app", ":", "h", ".", "app", ",", "store", ":", "h", ".", "store", ",", "}", "\n", "}" ]
// New method returns a handle based on the receiver handle
[ "New", "method", "returns", "a", "handle", "based", "on", "the", "receiver", "handle" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/bitseq/store.go#L62-L70
train
docker/libnetwork
bitseq/store.go
CopyTo
func (h *Handle) CopyTo(o datastore.KVObject) error { h.Lock() defer h.Unlock() dstH := o.(*Handle) if h == dstH { return nil } dstH.Lock() dstH.bits = h.bits dstH.unselected = h.unselected dstH.head = h.head.getCopy() dstH.app = h.app dstH.id = h.id dstH.dbIndex = h.dbIndex dstH.dbExists = h.dbExists dstH.store = h.store dstH.curr = h.curr dstH.Unlock() return nil }
go
func (h *Handle) CopyTo(o datastore.KVObject) error { h.Lock() defer h.Unlock() dstH := o.(*Handle) if h == dstH { return nil } dstH.Lock() dstH.bits = h.bits dstH.unselected = h.unselected dstH.head = h.head.getCopy() dstH.app = h.app dstH.id = h.id dstH.dbIndex = h.dbIndex dstH.dbExists = h.dbExists dstH.store = h.store dstH.curr = h.curr dstH.Unlock() return nil }
[ "func", "(", "h", "*", "Handle", ")", "CopyTo", "(", "o", "datastore", ".", "KVObject", ")", "error", "{", "h", ".", "Lock", "(", ")", "\n", "defer", "h", ".", "Unlock", "(", ")", "\n\n", "dstH", ":=", "o", ".", "(", "*", "Handle", ")", "\n", "if", "h", "==", "dstH", "{", "return", "nil", "\n", "}", "\n", "dstH", ".", "Lock", "(", ")", "\n", "dstH", ".", "bits", "=", "h", ".", "bits", "\n", "dstH", ".", "unselected", "=", "h", ".", "unselected", "\n", "dstH", ".", "head", "=", "h", ".", "head", ".", "getCopy", "(", ")", "\n", "dstH", ".", "app", "=", "h", ".", "app", "\n", "dstH", ".", "id", "=", "h", ".", "id", "\n", "dstH", ".", "dbIndex", "=", "h", ".", "dbIndex", "\n", "dstH", ".", "dbExists", "=", "h", ".", "dbExists", "\n", "dstH", ".", "store", "=", "h", ".", "store", "\n", "dstH", ".", "curr", "=", "h", ".", "curr", "\n", "dstH", ".", "Unlock", "(", ")", "\n\n", "return", "nil", "\n", "}" ]
// CopyTo deep copies the handle into the passed destination object
[ "CopyTo", "deep", "copies", "the", "handle", "into", "the", "passed", "destination", "object" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/bitseq/store.go#L73-L94
train
docker/libnetwork
drivers/ipvlan/ipvlan_setup.go
createIPVlan
func createIPVlan(containerIfName, parent, ipvlanMode string) (string, error) { // Set the ipvlan mode. Default is bridge mode mode, err := setIPVlanMode(ipvlanMode) if err != nil { return "", fmt.Errorf("Unsupported %s ipvlan mode: %v", ipvlanMode, 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", ipvlanType, parent, err) } // Create an ipvlan link ipvlan := &netlink.IPVlan{ LinkAttrs: netlink.LinkAttrs{ Name: containerIfName, ParentIndex: parentLink.Attrs().Index, }, Mode: mode, } if err := ns.NlHandle().LinkAdd(ipvlan); 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", ipvlanType, err) } return ipvlan.Attrs().Name, nil }
go
func createIPVlan(containerIfName, parent, ipvlanMode string) (string, error) { // Set the ipvlan mode. Default is bridge mode mode, err := setIPVlanMode(ipvlanMode) if err != nil { return "", fmt.Errorf("Unsupported %s ipvlan mode: %v", ipvlanMode, 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", ipvlanType, parent, err) } // Create an ipvlan link ipvlan := &netlink.IPVlan{ LinkAttrs: netlink.LinkAttrs{ Name: containerIfName, ParentIndex: parentLink.Attrs().Index, }, Mode: mode, } if err := ns.NlHandle().LinkAdd(ipvlan); 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", ipvlanType, err) } return ipvlan.Attrs().Name, nil }
[ "func", "createIPVlan", "(", "containerIfName", ",", "parent", ",", "ipvlanMode", "string", ")", "(", "string", ",", "error", ")", "{", "// Set the ipvlan mode. Default is bridge mode", "mode", ",", "err", ":=", "setIPVlanMode", "(", "ipvlanMode", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ipvlanMode", ",", "err", ")", "\n", "}", "\n", "// verify the Docker host interface acting as the macvlan parent iface exists", "if", "!", "parentExists", "(", "parent", ")", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "parent", ")", "\n", "}", "\n", "// Get the link for the master index (Example: the docker host eth iface)", "parentLink", ",", "err", ":=", "ns", ".", "NlHandle", "(", ")", ".", "LinkByName", "(", "parent", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ipvlanType", ",", "parent", ",", "err", ")", "\n", "}", "\n", "// Create an ipvlan link", "ipvlan", ":=", "&", "netlink", ".", "IPVlan", "{", "LinkAttrs", ":", "netlink", ".", "LinkAttrs", "{", "Name", ":", "containerIfName", ",", "ParentIndex", ":", "parentLink", ".", "Attrs", "(", ")", ".", "Index", ",", "}", ",", "Mode", ":", "mode", ",", "}", "\n", "if", "err", ":=", "ns", ".", "NlHandle", "(", ")", ".", "LinkAdd", "(", "ipvlan", ")", ";", "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", "(", "\"", "\"", ",", "ipvlanType", ",", "err", ")", "\n", "}", "\n\n", "return", "ipvlan", ".", "Attrs", "(", ")", ".", "Name", ",", "nil", "\n", "}" ]
// createIPVlan Create the ipvlan slave specifying the source name
[ "createIPVlan", "Create", "the", "ipvlan", "slave", "specifying", "the", "source", "name" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/ipvlan/ipvlan_setup.go#L20-L49
train
docker/libnetwork
drivers/ipvlan/ipvlan_setup.go
setIPVlanMode
func setIPVlanMode(mode string) (netlink.IPVlanMode, error) { switch mode { case modeL2: return netlink.IPVLAN_MODE_L2, nil case modeL3: return netlink.IPVLAN_MODE_L3, nil default: return 0, fmt.Errorf("Unknown ipvlan mode: %s", mode) } }
go
func setIPVlanMode(mode string) (netlink.IPVlanMode, error) { switch mode { case modeL2: return netlink.IPVLAN_MODE_L2, nil case modeL3: return netlink.IPVLAN_MODE_L3, nil default: return 0, fmt.Errorf("Unknown ipvlan mode: %s", mode) } }
[ "func", "setIPVlanMode", "(", "mode", "string", ")", "(", "netlink", ".", "IPVlanMode", ",", "error", ")", "{", "switch", "mode", "{", "case", "modeL2", ":", "return", "netlink", ".", "IPVLAN_MODE_L2", ",", "nil", "\n", "case", "modeL3", ":", "return", "netlink", ".", "IPVLAN_MODE_L3", ",", "nil", "\n", "default", ":", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "mode", ")", "\n", "}", "\n", "}" ]
// setIPVlanMode setter for one of the two ipvlan port types
[ "setIPVlanMode", "setter", "for", "one", "of", "the", "two", "ipvlan", "port", "types" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/ipvlan/ipvlan_setup.go#L52-L61
train
docker/libnetwork
drivers/ipvlan/ipvlan_setup.go
parentExists
func parentExists(ifaceStr string) bool { _, err := ns.NlHandle().LinkByName(ifaceStr) if err != nil { return false } return true }
go
func parentExists(ifaceStr string) bool { _, err := ns.NlHandle().LinkByName(ifaceStr) if err != nil { return false } return true }
[ "func", "parentExists", "(", "ifaceStr", "string", ")", "bool", "{", "_", ",", "err", ":=", "ns", ".", "NlHandle", "(", ")", ".", "LinkByName", "(", "ifaceStr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n\n", "return", "true", "\n", "}" ]
// parentExists check if the specified interface exists in the default namespace
[ "parentExists", "check", "if", "the", "specified", "interface", "exists", "in", "the", "default", "namespace" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/ipvlan/ipvlan_setup.go#L64-L71
train
docker/libnetwork
drivers/ipvlan/ipvlan_setup.go
createVlanLink
func createVlanLink(parentName string) error { if strings.Contains(parentName, ".") { parent, vidInt, err := parseVlan(parentName) if err != nil { return err } // VLAN identifier or VID is a 12-bit field specifying the VLAN to which the frame belongs if vidInt > 4094 || vidInt < 1 { return fmt.Errorf("vlan id must be between 1-4094, received: %d", vidInt) } // get the parent link to attach a vlan subinterface parentLink, err := ns.NlHandle().LinkByName(parent) if err != nil { return fmt.Errorf("failed to find master interface %s on the Docker host: %v", parent, err) } vlanLink := &netlink.Vlan{ LinkAttrs: netlink.LinkAttrs{ Name: parentName, ParentIndex: parentLink.Attrs().Index, }, VlanId: vidInt, } // create the subinterface if err := ns.NlHandle().LinkAdd(vlanLink); err != nil { return fmt.Errorf("failed to create %s vlan link: %v", vlanLink.Name, err) } // Bring the new netlink iface up if err := ns.NlHandle().LinkSetUp(vlanLink); err != nil { return fmt.Errorf("failed to enable %s the ipvlan parent link %v", vlanLink.Name, err) } logrus.Debugf("Added a vlan tagged netlink subinterface: %s with a vlan id: %d", parentName, vidInt) return nil } return fmt.Errorf("invalid subinterface vlan name %s, example formatting is eth0.10", parentName) }
go
func createVlanLink(parentName string) error { if strings.Contains(parentName, ".") { parent, vidInt, err := parseVlan(parentName) if err != nil { return err } // VLAN identifier or VID is a 12-bit field specifying the VLAN to which the frame belongs if vidInt > 4094 || vidInt < 1 { return fmt.Errorf("vlan id must be between 1-4094, received: %d", vidInt) } // get the parent link to attach a vlan subinterface parentLink, err := ns.NlHandle().LinkByName(parent) if err != nil { return fmt.Errorf("failed to find master interface %s on the Docker host: %v", parent, err) } vlanLink := &netlink.Vlan{ LinkAttrs: netlink.LinkAttrs{ Name: parentName, ParentIndex: parentLink.Attrs().Index, }, VlanId: vidInt, } // create the subinterface if err := ns.NlHandle().LinkAdd(vlanLink); err != nil { return fmt.Errorf("failed to create %s vlan link: %v", vlanLink.Name, err) } // Bring the new netlink iface up if err := ns.NlHandle().LinkSetUp(vlanLink); err != nil { return fmt.Errorf("failed to enable %s the ipvlan parent link %v", vlanLink.Name, err) } logrus.Debugf("Added a vlan tagged netlink subinterface: %s with a vlan id: %d", parentName, vidInt) return nil } return fmt.Errorf("invalid subinterface vlan name %s, example formatting is eth0.10", parentName) }
[ "func", "createVlanLink", "(", "parentName", "string", ")", "error", "{", "if", "strings", ".", "Contains", "(", "parentName", ",", "\"", "\"", ")", "{", "parent", ",", "vidInt", ",", "err", ":=", "parseVlan", "(", "parentName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "// VLAN identifier or VID is a 12-bit field specifying the VLAN to which the frame belongs", "if", "vidInt", ">", "4094", "||", "vidInt", "<", "1", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "vidInt", ")", "\n", "}", "\n", "// get the parent link to attach a vlan subinterface", "parentLink", ",", "err", ":=", "ns", ".", "NlHandle", "(", ")", ".", "LinkByName", "(", "parent", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "parent", ",", "err", ")", "\n", "}", "\n", "vlanLink", ":=", "&", "netlink", ".", "Vlan", "{", "LinkAttrs", ":", "netlink", ".", "LinkAttrs", "{", "Name", ":", "parentName", ",", "ParentIndex", ":", "parentLink", ".", "Attrs", "(", ")", ".", "Index", ",", "}", ",", "VlanId", ":", "vidInt", ",", "}", "\n", "// create the subinterface", "if", "err", ":=", "ns", ".", "NlHandle", "(", ")", ".", "LinkAdd", "(", "vlanLink", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "vlanLink", ".", "Name", ",", "err", ")", "\n", "}", "\n", "// Bring the new netlink iface up", "if", "err", ":=", "ns", ".", "NlHandle", "(", ")", ".", "LinkSetUp", "(", "vlanLink", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "vlanLink", ".", "Name", ",", "err", ")", "\n", "}", "\n", "logrus", ".", "Debugf", "(", "\"", "\"", ",", "parentName", ",", "vidInt", ")", "\n", "return", "nil", "\n", "}", "\n\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "parentName", ")", "\n", "}" ]
// createVlanLink parses sub-interfaces and vlan id for creation
[ "createVlanLink", "parses", "sub", "-", "interfaces", "and", "vlan", "id", "for", "creation" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/ipvlan/ipvlan_setup.go#L74-L109
train
docker/libnetwork
drivers/ipvlan/ipvlan_setup.go
createDummyLink
func createDummyLink(dummyName, truncNetID string) error { // create a parent interface since one was not specified parent := &netlink.Dummy{ LinkAttrs: netlink.LinkAttrs{ Name: dummyName, }, } if err := ns.NlHandle().LinkAdd(parent); err != nil { return err } parentDummyLink, err := ns.NlHandle().LinkByName(dummyName) if err != nil { return fmt.Errorf("error occurred looking up the %s parent iface %s error: %s", ipvlanType, dummyName, err) } // bring the new netlink iface up if err := ns.NlHandle().LinkSetUp(parentDummyLink); err != nil { return fmt.Errorf("failed to enable %s the ipvlan parent link: %v", dummyName, err) } return nil }
go
func createDummyLink(dummyName, truncNetID string) error { // create a parent interface since one was not specified parent := &netlink.Dummy{ LinkAttrs: netlink.LinkAttrs{ Name: dummyName, }, } if err := ns.NlHandle().LinkAdd(parent); err != nil { return err } parentDummyLink, err := ns.NlHandle().LinkByName(dummyName) if err != nil { return fmt.Errorf("error occurred looking up the %s parent iface %s error: %s", ipvlanType, dummyName, err) } // bring the new netlink iface up if err := ns.NlHandle().LinkSetUp(parentDummyLink); err != nil { return fmt.Errorf("failed to enable %s the ipvlan parent link: %v", dummyName, err) } return nil }
[ "func", "createDummyLink", "(", "dummyName", ",", "truncNetID", "string", ")", "error", "{", "// create a parent interface since one was not specified", "parent", ":=", "&", "netlink", ".", "Dummy", "{", "LinkAttrs", ":", "netlink", ".", "LinkAttrs", "{", "Name", ":", "dummyName", ",", "}", ",", "}", "\n", "if", "err", ":=", "ns", ".", "NlHandle", "(", ")", ".", "LinkAdd", "(", "parent", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "parentDummyLink", ",", "err", ":=", "ns", ".", "NlHandle", "(", ")", ".", "LinkByName", "(", "dummyName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ipvlanType", ",", "dummyName", ",", "err", ")", "\n", "}", "\n", "// bring the new netlink iface up", "if", "err", ":=", "ns", ".", "NlHandle", "(", ")", ".", "LinkSetUp", "(", "parentDummyLink", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "dummyName", ",", "err", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// createDummyLink creates a dummy0 parent link
[ "createDummyLink", "creates", "a", "dummy0", "parent", "link" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/ipvlan/ipvlan_setup.go#L160-L180
train
docker/libnetwork
drivers/ipvlan/ipvlan_setup.go
delDummyLink
func delDummyLink(linkName string) error { // delete the vlan subinterface dummyLink, err := ns.NlHandle().LinkByName(linkName) if err != nil { return fmt.Errorf("failed to find link %s on the Docker host : %v", linkName, err) } // verify a parent interface is being deleted if dummyLink.Attrs().ParentIndex != 0 { return fmt.Errorf("link %s is not a parent dummy interface", linkName) } // delete the ipvlan dummy device if err := ns.NlHandle().LinkDel(dummyLink); err != nil { return fmt.Errorf("failed to delete the dummy %s link: %v", linkName, err) } logrus.Debugf("Deleted a dummy parent link: %s", linkName) return nil }
go
func delDummyLink(linkName string) error { // delete the vlan subinterface dummyLink, err := ns.NlHandle().LinkByName(linkName) if err != nil { return fmt.Errorf("failed to find link %s on the Docker host : %v", linkName, err) } // verify a parent interface is being deleted if dummyLink.Attrs().ParentIndex != 0 { return fmt.Errorf("link %s is not a parent dummy interface", linkName) } // delete the ipvlan dummy device if err := ns.NlHandle().LinkDel(dummyLink); err != nil { return fmt.Errorf("failed to delete the dummy %s link: %v", linkName, err) } logrus.Debugf("Deleted a dummy parent link: %s", linkName) return nil }
[ "func", "delDummyLink", "(", "linkName", "string", ")", "error", "{", "// delete the vlan subinterface", "dummyLink", ",", "err", ":=", "ns", ".", "NlHandle", "(", ")", ".", "LinkByName", "(", "linkName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "linkName", ",", "err", ")", "\n", "}", "\n", "// verify a parent interface is being deleted", "if", "dummyLink", ".", "Attrs", "(", ")", ".", "ParentIndex", "!=", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "linkName", ")", "\n", "}", "\n", "// delete the ipvlan dummy device", "if", "err", ":=", "ns", ".", "NlHandle", "(", ")", ".", "LinkDel", "(", "dummyLink", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "linkName", ",", "err", ")", "\n", "}", "\n", "logrus", ".", "Debugf", "(", "\"", "\"", ",", "linkName", ")", "\n\n", "return", "nil", "\n", "}" ]
// delDummyLink deletes the link type dummy used when -o parent is not passed
[ "delDummyLink", "deletes", "the", "link", "type", "dummy", "used", "when", "-", "o", "parent", "is", "not", "passed" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/ipvlan/ipvlan_setup.go#L183-L200
train
docker/libnetwork
datastore/datastore.go
DefaultScopes
func DefaultScopes(dataDir string) map[string]*ScopeCfg { if dataDir != "" { defaultScopes[LocalScope].Client.Address = dataDir + "/network/files/local-kv.db" return defaultScopes } defaultScopes[LocalScope].Client.Address = defaultPrefix + "/local-kv.db" return defaultScopes }
go
func DefaultScopes(dataDir string) map[string]*ScopeCfg { if dataDir != "" { defaultScopes[LocalScope].Client.Address = dataDir + "/network/files/local-kv.db" return defaultScopes } defaultScopes[LocalScope].Client.Address = defaultPrefix + "/local-kv.db" return defaultScopes }
[ "func", "DefaultScopes", "(", "dataDir", "string", ")", "map", "[", "string", "]", "*", "ScopeCfg", "{", "if", "dataDir", "!=", "\"", "\"", "{", "defaultScopes", "[", "LocalScope", "]", ".", "Client", ".", "Address", "=", "dataDir", "+", "\"", "\"", "\n", "return", "defaultScopes", "\n", "}", "\n\n", "defaultScopes", "[", "LocalScope", "]", ".", "Client", ".", "Address", "=", "defaultPrefix", "+", "\"", "\"", "\n", "return", "defaultScopes", "\n", "}" ]
// DefaultScopes returns a map of default scopes and its config for clients to use.
[ "DefaultScopes", "returns", "a", "map", "of", "default", "scopes", "and", "its", "config", "for", "clients", "to", "use", "." ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/datastore/datastore.go#L156-L164
train
docker/libnetwork
datastore/datastore.go
IsValid
func (cfg *ScopeCfg) IsValid() bool { if cfg == nil || strings.TrimSpace(cfg.Client.Provider) == "" || strings.TrimSpace(cfg.Client.Address) == "" { return false } return true }
go
func (cfg *ScopeCfg) IsValid() bool { if cfg == nil || strings.TrimSpace(cfg.Client.Provider) == "" || strings.TrimSpace(cfg.Client.Address) == "" { return false } return true }
[ "func", "(", "cfg", "*", "ScopeCfg", ")", "IsValid", "(", ")", "bool", "{", "if", "cfg", "==", "nil", "||", "strings", ".", "TrimSpace", "(", "cfg", ".", "Client", ".", "Provider", ")", "==", "\"", "\"", "||", "strings", ".", "TrimSpace", "(", "cfg", ".", "Client", ".", "Address", ")", "==", "\"", "\"", "{", "return", "false", "\n", "}", "\n\n", "return", "true", "\n", "}" ]
// IsValid checks if the scope config has valid configuration.
[ "IsValid", "checks", "if", "the", "scope", "config", "has", "valid", "configuration", "." ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/datastore/datastore.go#L167-L175
train
docker/libnetwork
datastore/datastore.go
Key
func Key(key ...string) string { keychain := append(rootChain, key...) str := strings.Join(keychain, "/") return str + "/" }
go
func Key(key ...string) string { keychain := append(rootChain, key...) str := strings.Join(keychain, "/") return str + "/" }
[ "func", "Key", "(", "key", "...", "string", ")", "string", "{", "keychain", ":=", "append", "(", "rootChain", ",", "key", "...", ")", "\n", "str", ":=", "strings", ".", "Join", "(", "keychain", ",", "\"", "\"", ")", "\n", "return", "str", "+", "\"", "\"", "\n", "}" ]
//Key provides convenient method to create a Key
[ "Key", "provides", "convenient", "method", "to", "create", "a", "Key" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/datastore/datastore.go#L178-L182
train
docker/libnetwork
datastore/datastore.go
ParseKey
func ParseKey(key string) ([]string, error) { chain := strings.Split(strings.Trim(key, "/"), "/") // The key must at least be equal to the rootChain in order to be considered as valid if len(chain) <= len(rootChain) || !reflect.DeepEqual(chain[0:len(rootChain)], rootChain) { return nil, types.BadRequestErrorf("invalid Key : %s", key) } return chain[len(rootChain):], nil }
go
func ParseKey(key string) ([]string, error) { chain := strings.Split(strings.Trim(key, "/"), "/") // The key must at least be equal to the rootChain in order to be considered as valid if len(chain) <= len(rootChain) || !reflect.DeepEqual(chain[0:len(rootChain)], rootChain) { return nil, types.BadRequestErrorf("invalid Key : %s", key) } return chain[len(rootChain):], nil }
[ "func", "ParseKey", "(", "key", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "chain", ":=", "strings", ".", "Split", "(", "strings", ".", "Trim", "(", "key", ",", "\"", "\"", ")", ",", "\"", "\"", ")", "\n\n", "// The key must at least be equal to the rootChain in order to be considered as valid", "if", "len", "(", "chain", ")", "<=", "len", "(", "rootChain", ")", "||", "!", "reflect", ".", "DeepEqual", "(", "chain", "[", "0", ":", "len", "(", "rootChain", ")", "]", ",", "rootChain", ")", "{", "return", "nil", ",", "types", ".", "BadRequestErrorf", "(", "\"", "\"", ",", "key", ")", "\n", "}", "\n", "return", "chain", "[", "len", "(", "rootChain", ")", ":", "]", ",", "nil", "\n", "}" ]
//ParseKey provides convenient method to unpack the key to complement the Key function
[ "ParseKey", "provides", "convenient", "method", "to", "unpack", "the", "key", "to", "complement", "the", "Key", "function" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/datastore/datastore.go#L185-L193
train
docker/libnetwork
datastore/datastore.go
newClient
func newClient(scope string, kv string, addr string, config *store.Config, cached bool) (DataStore, error) { if cached && scope != LocalScope { return nil, fmt.Errorf("caching supported only for scope %s", LocalScope) } sequential := false if scope == LocalScope { sequential = true } if config == nil { config = &store.Config{} } var addrs []string if kv == string(store.BOLTDB) { // Parse file path addrs = strings.Split(addr, ",") } else { // Parse URI parts := strings.SplitN(addr, "/", 2) addrs = strings.Split(parts[0], ",") // Add the custom prefix to the root chain if len(parts) == 2 { rootChain = append([]string{parts[1]}, defaultRootChain...) } } store, err := libkv.NewStore(store.Backend(kv), addrs, config) if err != nil { return nil, err } ds := &datastore{scope: scope, store: store, active: true, watchCh: make(chan struct{}), sequential: sequential} if cached { ds.cache = newCache(ds) } return ds, nil }
go
func newClient(scope string, kv string, addr string, config *store.Config, cached bool) (DataStore, error) { if cached && scope != LocalScope { return nil, fmt.Errorf("caching supported only for scope %s", LocalScope) } sequential := false if scope == LocalScope { sequential = true } if config == nil { config = &store.Config{} } var addrs []string if kv == string(store.BOLTDB) { // Parse file path addrs = strings.Split(addr, ",") } else { // Parse URI parts := strings.SplitN(addr, "/", 2) addrs = strings.Split(parts[0], ",") // Add the custom prefix to the root chain if len(parts) == 2 { rootChain = append([]string{parts[1]}, defaultRootChain...) } } store, err := libkv.NewStore(store.Backend(kv), addrs, config) if err != nil { return nil, err } ds := &datastore{scope: scope, store: store, active: true, watchCh: make(chan struct{}), sequential: sequential} if cached { ds.cache = newCache(ds) } return ds, nil }
[ "func", "newClient", "(", "scope", "string", ",", "kv", "string", ",", "addr", "string", ",", "config", "*", "store", ".", "Config", ",", "cached", "bool", ")", "(", "DataStore", ",", "error", ")", "{", "if", "cached", "&&", "scope", "!=", "LocalScope", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "LocalScope", ")", "\n", "}", "\n", "sequential", ":=", "false", "\n", "if", "scope", "==", "LocalScope", "{", "sequential", "=", "true", "\n", "}", "\n\n", "if", "config", "==", "nil", "{", "config", "=", "&", "store", ".", "Config", "{", "}", "\n", "}", "\n\n", "var", "addrs", "[", "]", "string", "\n\n", "if", "kv", "==", "string", "(", "store", ".", "BOLTDB", ")", "{", "// Parse file path", "addrs", "=", "strings", ".", "Split", "(", "addr", ",", "\"", "\"", ")", "\n", "}", "else", "{", "// Parse URI", "parts", ":=", "strings", ".", "SplitN", "(", "addr", ",", "\"", "\"", ",", "2", ")", "\n", "addrs", "=", "strings", ".", "Split", "(", "parts", "[", "0", "]", ",", "\"", "\"", ")", "\n\n", "// Add the custom prefix to the root chain", "if", "len", "(", "parts", ")", "==", "2", "{", "rootChain", "=", "append", "(", "[", "]", "string", "{", "parts", "[", "1", "]", "}", ",", "defaultRootChain", "...", ")", "\n", "}", "\n", "}", "\n\n", "store", ",", "err", ":=", "libkv", ".", "NewStore", "(", "store", ".", "Backend", "(", "kv", ")", ",", "addrs", ",", "config", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "ds", ":=", "&", "datastore", "{", "scope", ":", "scope", ",", "store", ":", "store", ",", "active", ":", "true", ",", "watchCh", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "sequential", ":", "sequential", "}", "\n", "if", "cached", "{", "ds", ".", "cache", "=", "newCache", "(", "ds", ")", "\n", "}", "\n\n", "return", "ds", ",", "nil", "\n", "}" ]
// newClient used to connect to KV Store
[ "newClient", "used", "to", "connect", "to", "KV", "Store" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/datastore/datastore.go#L196-L237
train
docker/libnetwork
datastore/datastore.go
NewDataStore
func NewDataStore(scope string, cfg *ScopeCfg) (DataStore, error) { if cfg == nil || cfg.Client.Provider == "" || cfg.Client.Address == "" { c, ok := defaultScopes[scope] if !ok || c.Client.Provider == "" || c.Client.Address == "" { return nil, fmt.Errorf("unexpected scope %s without configuration passed", scope) } cfg = c } var cached bool if scope == LocalScope { cached = true } return newClient(scope, cfg.Client.Provider, cfg.Client.Address, cfg.Client.Config, cached) }
go
func NewDataStore(scope string, cfg *ScopeCfg) (DataStore, error) { if cfg == nil || cfg.Client.Provider == "" || cfg.Client.Address == "" { c, ok := defaultScopes[scope] if !ok || c.Client.Provider == "" || c.Client.Address == "" { return nil, fmt.Errorf("unexpected scope %s without configuration passed", scope) } cfg = c } var cached bool if scope == LocalScope { cached = true } return newClient(scope, cfg.Client.Provider, cfg.Client.Address, cfg.Client.Config, cached) }
[ "func", "NewDataStore", "(", "scope", "string", ",", "cfg", "*", "ScopeCfg", ")", "(", "DataStore", ",", "error", ")", "{", "if", "cfg", "==", "nil", "||", "cfg", ".", "Client", ".", "Provider", "==", "\"", "\"", "||", "cfg", ".", "Client", ".", "Address", "==", "\"", "\"", "{", "c", ",", "ok", ":=", "defaultScopes", "[", "scope", "]", "\n", "if", "!", "ok", "||", "c", ".", "Client", ".", "Provider", "==", "\"", "\"", "||", "c", ".", "Client", ".", "Address", "==", "\"", "\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "scope", ")", "\n", "}", "\n\n", "cfg", "=", "c", "\n", "}", "\n\n", "var", "cached", "bool", "\n", "if", "scope", "==", "LocalScope", "{", "cached", "=", "true", "\n", "}", "\n\n", "return", "newClient", "(", "scope", ",", "cfg", ".", "Client", ".", "Provider", ",", "cfg", ".", "Client", ".", "Address", ",", "cfg", ".", "Client", ".", "Config", ",", "cached", ")", "\n", "}" ]
// NewDataStore creates a new instance of LibKV data store
[ "NewDataStore", "creates", "a", "new", "instance", "of", "LibKV", "data", "store" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/datastore/datastore.go#L240-L256
train
docker/libnetwork
datastore/datastore.go
NewDataStoreFromConfig
func NewDataStoreFromConfig(dsc discoverapi.DatastoreConfigData) (DataStore, error) { var ( ok bool sCfgP *store.Config ) sCfgP, ok = dsc.Config.(*store.Config) if !ok && dsc.Config != nil { return nil, fmt.Errorf("cannot parse store configuration: %v", dsc.Config) } scopeCfg := &ScopeCfg{ Client: ScopeClientCfg{ Address: dsc.Address, Provider: dsc.Provider, Config: sCfgP, }, } ds, err := NewDataStore(dsc.Scope, scopeCfg) if err != nil { return nil, fmt.Errorf("failed to construct datastore client from datastore configuration %v: %v", dsc, err) } return ds, err }
go
func NewDataStoreFromConfig(dsc discoverapi.DatastoreConfigData) (DataStore, error) { var ( ok bool sCfgP *store.Config ) sCfgP, ok = dsc.Config.(*store.Config) if !ok && dsc.Config != nil { return nil, fmt.Errorf("cannot parse store configuration: %v", dsc.Config) } scopeCfg := &ScopeCfg{ Client: ScopeClientCfg{ Address: dsc.Address, Provider: dsc.Provider, Config: sCfgP, }, } ds, err := NewDataStore(dsc.Scope, scopeCfg) if err != nil { return nil, fmt.Errorf("failed to construct datastore client from datastore configuration %v: %v", dsc, err) } return ds, err }
[ "func", "NewDataStoreFromConfig", "(", "dsc", "discoverapi", ".", "DatastoreConfigData", ")", "(", "DataStore", ",", "error", ")", "{", "var", "(", "ok", "bool", "\n", "sCfgP", "*", "store", ".", "Config", "\n", ")", "\n\n", "sCfgP", ",", "ok", "=", "dsc", ".", "Config", ".", "(", "*", "store", ".", "Config", ")", "\n", "if", "!", "ok", "&&", "dsc", ".", "Config", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "dsc", ".", "Config", ")", "\n", "}", "\n\n", "scopeCfg", ":=", "&", "ScopeCfg", "{", "Client", ":", "ScopeClientCfg", "{", "Address", ":", "dsc", ".", "Address", ",", "Provider", ":", "dsc", ".", "Provider", ",", "Config", ":", "sCfgP", ",", "}", ",", "}", "\n\n", "ds", ",", "err", ":=", "NewDataStore", "(", "dsc", ".", "Scope", ",", "scopeCfg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "dsc", ",", "err", ")", "\n", "}", "\n\n", "return", "ds", ",", "err", "\n", "}" ]
// NewDataStoreFromConfig creates a new instance of LibKV data store starting from the datastore config data
[ "NewDataStoreFromConfig", "creates", "a", "new", "instance", "of", "LibKV", "data", "store", "starting", "from", "the", "datastore", "config", "data" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/datastore/datastore.go#L259-L284
train
docker/libnetwork
datastore/datastore.go
PutObjectAtomic
func (ds *datastore) PutObjectAtomic(kvObject KVObject) error { var ( previous *store.KVPair pair *store.KVPair err error ) if ds.sequential { ds.Lock() defer ds.Unlock() } if kvObject == nil { return types.BadRequestErrorf("invalid KV Object : nil") } kvObjValue := kvObject.Value() if kvObjValue == nil { return types.BadRequestErrorf("invalid KV Object with a nil Value for key %s", Key(kvObject.Key()...)) } if kvObject.Skip() { goto add_cache } if kvObject.Exists() { previous = &store.KVPair{Key: Key(kvObject.Key()...), LastIndex: kvObject.Index()} } else { previous = nil } _, pair, err = ds.store.AtomicPut(Key(kvObject.Key()...), kvObjValue, previous, nil) if err != nil { if err == store.ErrKeyExists { return ErrKeyModified } return err } kvObject.SetIndex(pair.LastIndex) add_cache: if ds.cache != nil { // If persistent store is skipped, sequencing needs to // happen in cache. return ds.cache.add(kvObject, kvObject.Skip()) } return nil }
go
func (ds *datastore) PutObjectAtomic(kvObject KVObject) error { var ( previous *store.KVPair pair *store.KVPair err error ) if ds.sequential { ds.Lock() defer ds.Unlock() } if kvObject == nil { return types.BadRequestErrorf("invalid KV Object : nil") } kvObjValue := kvObject.Value() if kvObjValue == nil { return types.BadRequestErrorf("invalid KV Object with a nil Value for key %s", Key(kvObject.Key()...)) } if kvObject.Skip() { goto add_cache } if kvObject.Exists() { previous = &store.KVPair{Key: Key(kvObject.Key()...), LastIndex: kvObject.Index()} } else { previous = nil } _, pair, err = ds.store.AtomicPut(Key(kvObject.Key()...), kvObjValue, previous, nil) if err != nil { if err == store.ErrKeyExists { return ErrKeyModified } return err } kvObject.SetIndex(pair.LastIndex) add_cache: if ds.cache != nil { // If persistent store is skipped, sequencing needs to // happen in cache. return ds.cache.add(kvObject, kvObject.Skip()) } return nil }
[ "func", "(", "ds", "*", "datastore", ")", "PutObjectAtomic", "(", "kvObject", "KVObject", ")", "error", "{", "var", "(", "previous", "*", "store", ".", "KVPair", "\n", "pair", "*", "store", ".", "KVPair", "\n", "err", "error", "\n", ")", "\n", "if", "ds", ".", "sequential", "{", "ds", ".", "Lock", "(", ")", "\n", "defer", "ds", ".", "Unlock", "(", ")", "\n", "}", "\n\n", "if", "kvObject", "==", "nil", "{", "return", "types", ".", "BadRequestErrorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "kvObjValue", ":=", "kvObject", ".", "Value", "(", ")", "\n\n", "if", "kvObjValue", "==", "nil", "{", "return", "types", ".", "BadRequestErrorf", "(", "\"", "\"", ",", "Key", "(", "kvObject", ".", "Key", "(", ")", "...", ")", ")", "\n", "}", "\n\n", "if", "kvObject", ".", "Skip", "(", ")", "{", "goto", "add_cache", "\n", "}", "\n\n", "if", "kvObject", ".", "Exists", "(", ")", "{", "previous", "=", "&", "store", ".", "KVPair", "{", "Key", ":", "Key", "(", "kvObject", ".", "Key", "(", ")", "...", ")", ",", "LastIndex", ":", "kvObject", ".", "Index", "(", ")", "}", "\n", "}", "else", "{", "previous", "=", "nil", "\n", "}", "\n\n", "_", ",", "pair", ",", "err", "=", "ds", ".", "store", ".", "AtomicPut", "(", "Key", "(", "kvObject", ".", "Key", "(", ")", "...", ")", ",", "kvObjValue", ",", "previous", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "store", ".", "ErrKeyExists", "{", "return", "ErrKeyModified", "\n", "}", "\n", "return", "err", "\n", "}", "\n\n", "kvObject", ".", "SetIndex", "(", "pair", ".", "LastIndex", ")", "\n\n", "add_cache", ":", "if", "ds", ".", "cache", "!=", "nil", "{", "// If persistent store is skipped, sequencing needs to", "// happen in cache.", "return", "ds", ".", "cache", ".", "add", "(", "kvObject", ",", "kvObject", ".", "Skip", "(", ")", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// PutObjectAtomic adds a new Record based on an object into the datastore
[ "PutObjectAtomic", "adds", "a", "new", "Record", "based", "on", "an", "object", "into", "the", "datastore" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/datastore/datastore.go#L384-L433
train
docker/libnetwork
datastore/datastore.go
PutObject
func (ds *datastore) PutObject(kvObject KVObject) error { if ds.sequential { ds.Lock() defer ds.Unlock() } if kvObject == nil { return types.BadRequestErrorf("invalid KV Object : nil") } if kvObject.Skip() { goto add_cache } if err := ds.putObjectWithKey(kvObject, kvObject.Key()...); err != nil { return err } add_cache: if ds.cache != nil { // If persistent store is skipped, sequencing needs to // happen in cache. return ds.cache.add(kvObject, kvObject.Skip()) } return nil }
go
func (ds *datastore) PutObject(kvObject KVObject) error { if ds.sequential { ds.Lock() defer ds.Unlock() } if kvObject == nil { return types.BadRequestErrorf("invalid KV Object : nil") } if kvObject.Skip() { goto add_cache } if err := ds.putObjectWithKey(kvObject, kvObject.Key()...); err != nil { return err } add_cache: if ds.cache != nil { // If persistent store is skipped, sequencing needs to // happen in cache. return ds.cache.add(kvObject, kvObject.Skip()) } return nil }
[ "func", "(", "ds", "*", "datastore", ")", "PutObject", "(", "kvObject", "KVObject", ")", "error", "{", "if", "ds", ".", "sequential", "{", "ds", ".", "Lock", "(", ")", "\n", "defer", "ds", ".", "Unlock", "(", ")", "\n", "}", "\n\n", "if", "kvObject", "==", "nil", "{", "return", "types", ".", "BadRequestErrorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "kvObject", ".", "Skip", "(", ")", "{", "goto", "add_cache", "\n", "}", "\n\n", "if", "err", ":=", "ds", ".", "putObjectWithKey", "(", "kvObject", ",", "kvObject", ".", "Key", "(", ")", "...", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "add_cache", ":", "if", "ds", ".", "cache", "!=", "nil", "{", "// If persistent store is skipped, sequencing needs to", "// happen in cache.", "return", "ds", ".", "cache", ".", "add", "(", "kvObject", ",", "kvObject", ".", "Skip", "(", ")", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// PutObject adds a new Record based on an object into the datastore
[ "PutObject", "adds", "a", "new", "Record", "based", "on", "an", "object", "into", "the", "datastore" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/datastore/datastore.go#L436-L462
train
docker/libnetwork
datastore/datastore.go
GetObject
func (ds *datastore) GetObject(key string, o KVObject) error { if ds.sequential { ds.Lock() defer ds.Unlock() } if ds.cache != nil { return ds.cache.get(key, o) } kvPair, err := ds.store.Get(key) if err != nil { return err } if err := o.SetValue(kvPair.Value); err != nil { return err } // Make sure the object has a correct view of the DB index in // case we need to modify it and update the DB. o.SetIndex(kvPair.LastIndex) return nil }
go
func (ds *datastore) GetObject(key string, o KVObject) error { if ds.sequential { ds.Lock() defer ds.Unlock() } if ds.cache != nil { return ds.cache.get(key, o) } kvPair, err := ds.store.Get(key) if err != nil { return err } if err := o.SetValue(kvPair.Value); err != nil { return err } // Make sure the object has a correct view of the DB index in // case we need to modify it and update the DB. o.SetIndex(kvPair.LastIndex) return nil }
[ "func", "(", "ds", "*", "datastore", ")", "GetObject", "(", "key", "string", ",", "o", "KVObject", ")", "error", "{", "if", "ds", ".", "sequential", "{", "ds", ".", "Lock", "(", ")", "\n", "defer", "ds", ".", "Unlock", "(", ")", "\n", "}", "\n\n", "if", "ds", ".", "cache", "!=", "nil", "{", "return", "ds", ".", "cache", ".", "get", "(", "key", ",", "o", ")", "\n", "}", "\n\n", "kvPair", ",", "err", ":=", "ds", ".", "store", ".", "Get", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "o", ".", "SetValue", "(", "kvPair", ".", "Value", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Make sure the object has a correct view of the DB index in", "// case we need to modify it and update the DB.", "o", ".", "SetIndex", "(", "kvPair", ".", "LastIndex", ")", "\n", "return", "nil", "\n", "}" ]
// GetObject returns a record matching the key
[ "GetObject", "returns", "a", "record", "matching", "the", "key" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/datastore/datastore.go#L474-L497
train
docker/libnetwork
datastore/datastore.go
DeleteObject
func (ds *datastore) DeleteObject(kvObject KVObject) error { if ds.sequential { ds.Lock() defer ds.Unlock() } // cleanup the cache first if ds.cache != nil { // If persistent store is skipped, sequencing needs to // happen in cache. ds.cache.del(kvObject, kvObject.Skip()) } if kvObject.Skip() { return nil } return ds.store.Delete(Key(kvObject.Key()...)) }
go
func (ds *datastore) DeleteObject(kvObject KVObject) error { if ds.sequential { ds.Lock() defer ds.Unlock() } // cleanup the cache first if ds.cache != nil { // If persistent store is skipped, sequencing needs to // happen in cache. ds.cache.del(kvObject, kvObject.Skip()) } if kvObject.Skip() { return nil } return ds.store.Delete(Key(kvObject.Key()...)) }
[ "func", "(", "ds", "*", "datastore", ")", "DeleteObject", "(", "kvObject", "KVObject", ")", "error", "{", "if", "ds", ".", "sequential", "{", "ds", ".", "Lock", "(", ")", "\n", "defer", "ds", ".", "Unlock", "(", ")", "\n", "}", "\n\n", "// cleanup the cache first", "if", "ds", ".", "cache", "!=", "nil", "{", "// If persistent store is skipped, sequencing needs to", "// happen in cache.", "ds", ".", "cache", ".", "del", "(", "kvObject", ",", "kvObject", ".", "Skip", "(", ")", ")", "\n", "}", "\n\n", "if", "kvObject", ".", "Skip", "(", ")", "{", "return", "nil", "\n", "}", "\n\n", "return", "ds", ".", "store", ".", "Delete", "(", "Key", "(", "kvObject", ".", "Key", "(", ")", "...", ")", ")", "\n", "}" ]
// DeleteObject unconditionally deletes a record from the store
[ "DeleteObject", "unconditionally", "deletes", "a", "record", "from", "the", "store" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/datastore/datastore.go#L586-L604
train
docker/libnetwork
datastore/datastore.go
DeleteObjectAtomic
func (ds *datastore) DeleteObjectAtomic(kvObject KVObject) error { if ds.sequential { ds.Lock() defer ds.Unlock() } if kvObject == nil { return types.BadRequestErrorf("invalid KV Object : nil") } previous := &store.KVPair{Key: Key(kvObject.Key()...), LastIndex: kvObject.Index()} if kvObject.Skip() { goto del_cache } if _, err := ds.store.AtomicDelete(Key(kvObject.Key()...), previous); err != nil { if err == store.ErrKeyExists { return ErrKeyModified } return err } del_cache: // cleanup the cache only if AtomicDelete went through successfully if ds.cache != nil { // If persistent store is skipped, sequencing needs to // happen in cache. return ds.cache.del(kvObject, kvObject.Skip()) } return nil }
go
func (ds *datastore) DeleteObjectAtomic(kvObject KVObject) error { if ds.sequential { ds.Lock() defer ds.Unlock() } if kvObject == nil { return types.BadRequestErrorf("invalid KV Object : nil") } previous := &store.KVPair{Key: Key(kvObject.Key()...), LastIndex: kvObject.Index()} if kvObject.Skip() { goto del_cache } if _, err := ds.store.AtomicDelete(Key(kvObject.Key()...), previous); err != nil { if err == store.ErrKeyExists { return ErrKeyModified } return err } del_cache: // cleanup the cache only if AtomicDelete went through successfully if ds.cache != nil { // If persistent store is skipped, sequencing needs to // happen in cache. return ds.cache.del(kvObject, kvObject.Skip()) } return nil }
[ "func", "(", "ds", "*", "datastore", ")", "DeleteObjectAtomic", "(", "kvObject", "KVObject", ")", "error", "{", "if", "ds", ".", "sequential", "{", "ds", ".", "Lock", "(", ")", "\n", "defer", "ds", ".", "Unlock", "(", ")", "\n", "}", "\n\n", "if", "kvObject", "==", "nil", "{", "return", "types", ".", "BadRequestErrorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "previous", ":=", "&", "store", ".", "KVPair", "{", "Key", ":", "Key", "(", "kvObject", ".", "Key", "(", ")", "...", ")", ",", "LastIndex", ":", "kvObject", ".", "Index", "(", ")", "}", "\n\n", "if", "kvObject", ".", "Skip", "(", ")", "{", "goto", "del_cache", "\n", "}", "\n\n", "if", "_", ",", "err", ":=", "ds", ".", "store", ".", "AtomicDelete", "(", "Key", "(", "kvObject", ".", "Key", "(", ")", "...", ")", ",", "previous", ")", ";", "err", "!=", "nil", "{", "if", "err", "==", "store", ".", "ErrKeyExists", "{", "return", "ErrKeyModified", "\n", "}", "\n", "return", "err", "\n", "}", "\n\n", "del_cache", ":", "// cleanup the cache only if AtomicDelete went through successfully", "if", "ds", ".", "cache", "!=", "nil", "{", "// If persistent store is skipped, sequencing needs to", "// happen in cache.", "return", "ds", ".", "cache", ".", "del", "(", "kvObject", ",", "kvObject", ".", "Skip", "(", ")", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// DeleteObjectAtomic performs atomic delete on a record
[ "DeleteObjectAtomic", "performs", "atomic", "delete", "on", "a", "record" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/datastore/datastore.go#L607-L639
train
docker/libnetwork
datastore/datastore.go
DeleteTree
func (ds *datastore) DeleteTree(kvObject KVObject) error { if ds.sequential { ds.Lock() defer ds.Unlock() } // cleanup the cache first if ds.cache != nil { // If persistent store is skipped, sequencing needs to // happen in cache. ds.cache.del(kvObject, kvObject.Skip()) } if kvObject.Skip() { return nil } return ds.store.DeleteTree(Key(kvObject.KeyPrefix()...)) }
go
func (ds *datastore) DeleteTree(kvObject KVObject) error { if ds.sequential { ds.Lock() defer ds.Unlock() } // cleanup the cache first if ds.cache != nil { // If persistent store is skipped, sequencing needs to // happen in cache. ds.cache.del(kvObject, kvObject.Skip()) } if kvObject.Skip() { return nil } return ds.store.DeleteTree(Key(kvObject.KeyPrefix()...)) }
[ "func", "(", "ds", "*", "datastore", ")", "DeleteTree", "(", "kvObject", "KVObject", ")", "error", "{", "if", "ds", ".", "sequential", "{", "ds", ".", "Lock", "(", ")", "\n", "defer", "ds", ".", "Unlock", "(", ")", "\n", "}", "\n\n", "// cleanup the cache first", "if", "ds", ".", "cache", "!=", "nil", "{", "// If persistent store is skipped, sequencing needs to", "// happen in cache.", "ds", ".", "cache", ".", "del", "(", "kvObject", ",", "kvObject", ".", "Skip", "(", ")", ")", "\n", "}", "\n\n", "if", "kvObject", ".", "Skip", "(", ")", "{", "return", "nil", "\n", "}", "\n\n", "return", "ds", ".", "store", ".", "DeleteTree", "(", "Key", "(", "kvObject", ".", "KeyPrefix", "(", ")", "...", ")", ")", "\n", "}" ]
// DeleteTree unconditionally deletes a record from the store
[ "DeleteTree", "unconditionally", "deletes", "a", "record", "from", "the", "store" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/datastore/datastore.go#L642-L660
train
docker/libnetwork
drivers/remote/driver.go
Init
func Init(dc driverapi.DriverCallback, config map[string]interface{}) error { newPluginHandler := func(name string, client *plugins.Client) { // negotiate driver capability with client d := newDriver(name, client) c, err := d.(*driver).getCapabilities() if err != nil { logrus.Errorf("error getting capability for %s due to %v", name, err) return } if err = dc.RegisterDriver(name, d, *c); err != nil { logrus.Errorf("error registering driver for %s due to %v", name, err) } } // Unit test code is unaware of a true PluginStore. So we fall back to v1 plugins. handleFunc := plugins.Handle if pg := dc.GetPluginGetter(); pg != nil { handleFunc = pg.Handle activePlugins := pg.GetAllManagedPluginsByCap(driverapi.NetworkPluginEndpointType) for _, ap := range activePlugins { client, err := getPluginClient(ap) if err != nil { return err } newPluginHandler(ap.Name(), client) } } handleFunc(driverapi.NetworkPluginEndpointType, newPluginHandler) return nil }
go
func Init(dc driverapi.DriverCallback, config map[string]interface{}) error { newPluginHandler := func(name string, client *plugins.Client) { // negotiate driver capability with client d := newDriver(name, client) c, err := d.(*driver).getCapabilities() if err != nil { logrus.Errorf("error getting capability for %s due to %v", name, err) return } if err = dc.RegisterDriver(name, d, *c); err != nil { logrus.Errorf("error registering driver for %s due to %v", name, err) } } // Unit test code is unaware of a true PluginStore. So we fall back to v1 plugins. handleFunc := plugins.Handle if pg := dc.GetPluginGetter(); pg != nil { handleFunc = pg.Handle activePlugins := pg.GetAllManagedPluginsByCap(driverapi.NetworkPluginEndpointType) for _, ap := range activePlugins { client, err := getPluginClient(ap) if err != nil { return err } newPluginHandler(ap.Name(), client) } } handleFunc(driverapi.NetworkPluginEndpointType, newPluginHandler) return nil }
[ "func", "Init", "(", "dc", "driverapi", ".", "DriverCallback", ",", "config", "map", "[", "string", "]", "interface", "{", "}", ")", "error", "{", "newPluginHandler", ":=", "func", "(", "name", "string", ",", "client", "*", "plugins", ".", "Client", ")", "{", "// negotiate driver capability with client", "d", ":=", "newDriver", "(", "name", ",", "client", ")", "\n", "c", ",", "err", ":=", "d", ".", "(", "*", "driver", ")", ".", "getCapabilities", "(", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "Errorf", "(", "\"", "\"", ",", "name", ",", "err", ")", "\n", "return", "\n", "}", "\n", "if", "err", "=", "dc", ".", "RegisterDriver", "(", "name", ",", "d", ",", "*", "c", ")", ";", "err", "!=", "nil", "{", "logrus", ".", "Errorf", "(", "\"", "\"", ",", "name", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "// Unit test code is unaware of a true PluginStore. So we fall back to v1 plugins.", "handleFunc", ":=", "plugins", ".", "Handle", "\n", "if", "pg", ":=", "dc", ".", "GetPluginGetter", "(", ")", ";", "pg", "!=", "nil", "{", "handleFunc", "=", "pg", ".", "Handle", "\n", "activePlugins", ":=", "pg", ".", "GetAllManagedPluginsByCap", "(", "driverapi", ".", "NetworkPluginEndpointType", ")", "\n", "for", "_", ",", "ap", ":=", "range", "activePlugins", "{", "client", ",", "err", ":=", "getPluginClient", "(", "ap", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "newPluginHandler", "(", "ap", ".", "Name", "(", ")", ",", "client", ")", "\n", "}", "\n", "}", "\n", "handleFunc", "(", "driverapi", ".", "NetworkPluginEndpointType", ",", "newPluginHandler", ")", "\n\n", "return", "nil", "\n", "}" ]
// Init makes sure a remote driver is registered when a network driver // plugin is activated.
[ "Init", "makes", "sure", "a", "remote", "driver", "is", "registered", "when", "a", "network", "driver", "plugin", "is", "activated", "." ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/remote/driver.go#L33-L63
train
docker/libnetwork
drivers/remote/driver.go
getCapabilities
func (d *driver) getCapabilities() (*driverapi.Capability, error) { var capResp api.GetCapabilityResponse if err := d.call("GetCapabilities", nil, &capResp); err != nil { return nil, err } c := &driverapi.Capability{} switch capResp.Scope { case "global": c.DataScope = datastore.GlobalScope case "local": c.DataScope = datastore.LocalScope default: return nil, fmt.Errorf("invalid capability: expecting 'local' or 'global', got %s", capResp.Scope) } switch capResp.ConnectivityScope { case "global": c.ConnectivityScope = datastore.GlobalScope case "local": c.ConnectivityScope = datastore.LocalScope case "": c.ConnectivityScope = c.DataScope default: return nil, fmt.Errorf("invalid capability: expecting 'local' or 'global', got %s", capResp.Scope) } return c, nil }
go
func (d *driver) getCapabilities() (*driverapi.Capability, error) { var capResp api.GetCapabilityResponse if err := d.call("GetCapabilities", nil, &capResp); err != nil { return nil, err } c := &driverapi.Capability{} switch capResp.Scope { case "global": c.DataScope = datastore.GlobalScope case "local": c.DataScope = datastore.LocalScope default: return nil, fmt.Errorf("invalid capability: expecting 'local' or 'global', got %s", capResp.Scope) } switch capResp.ConnectivityScope { case "global": c.ConnectivityScope = datastore.GlobalScope case "local": c.ConnectivityScope = datastore.LocalScope case "": c.ConnectivityScope = c.DataScope default: return nil, fmt.Errorf("invalid capability: expecting 'local' or 'global', got %s", capResp.Scope) } return c, nil }
[ "func", "(", "d", "*", "driver", ")", "getCapabilities", "(", ")", "(", "*", "driverapi", ".", "Capability", ",", "error", ")", "{", "var", "capResp", "api", ".", "GetCapabilityResponse", "\n", "if", "err", ":=", "d", ".", "call", "(", "\"", "\"", ",", "nil", ",", "&", "capResp", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "c", ":=", "&", "driverapi", ".", "Capability", "{", "}", "\n", "switch", "capResp", ".", "Scope", "{", "case", "\"", "\"", ":", "c", ".", "DataScope", "=", "datastore", ".", "GlobalScope", "\n", "case", "\"", "\"", ":", "c", ".", "DataScope", "=", "datastore", ".", "LocalScope", "\n", "default", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "capResp", ".", "Scope", ")", "\n", "}", "\n\n", "switch", "capResp", ".", "ConnectivityScope", "{", "case", "\"", "\"", ":", "c", ".", "ConnectivityScope", "=", "datastore", ".", "GlobalScope", "\n", "case", "\"", "\"", ":", "c", ".", "ConnectivityScope", "=", "datastore", ".", "LocalScope", "\n", "case", "\"", "\"", ":", "c", ".", "ConnectivityScope", "=", "c", ".", "DataScope", "\n", "default", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "capResp", ".", "Scope", ")", "\n", "}", "\n\n", "return", "c", ",", "nil", "\n", "}" ]
// Get capability from client
[ "Get", "capability", "from", "client" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/remote/driver.go#L88-L116
train
docker/libnetwork
drivers/remote/driver.go
ProgramExternalConnectivity
func (d *driver) ProgramExternalConnectivity(nid, eid string, options map[string]interface{}) error { data := &api.ProgramExternalConnectivityRequest{ NetworkID: nid, EndpointID: eid, Options: options, } err := d.call("ProgramExternalConnectivity", data, &api.ProgramExternalConnectivityResponse{}) if err != nil && plugins.IsNotFound(err) { // It is not mandatory yet to support this method return nil } return err }
go
func (d *driver) ProgramExternalConnectivity(nid, eid string, options map[string]interface{}) error { data := &api.ProgramExternalConnectivityRequest{ NetworkID: nid, EndpointID: eid, Options: options, } err := d.call("ProgramExternalConnectivity", data, &api.ProgramExternalConnectivityResponse{}) if err != nil && plugins.IsNotFound(err) { // It is not mandatory yet to support this method return nil } return err }
[ "func", "(", "d", "*", "driver", ")", "ProgramExternalConnectivity", "(", "nid", ",", "eid", "string", ",", "options", "map", "[", "string", "]", "interface", "{", "}", ")", "error", "{", "data", ":=", "&", "api", ".", "ProgramExternalConnectivityRequest", "{", "NetworkID", ":", "nid", ",", "EndpointID", ":", "eid", ",", "Options", ":", "options", ",", "}", "\n", "err", ":=", "d", ".", "call", "(", "\"", "\"", ",", "data", ",", "&", "api", ".", "ProgramExternalConnectivityResponse", "{", "}", ")", "\n", "if", "err", "!=", "nil", "&&", "plugins", ".", "IsNotFound", "(", "err", ")", "{", "// It is not mandatory yet to support this method", "return", "nil", "\n", "}", "\n", "return", "err", "\n", "}" ]
// ProgramExternalConnectivity is invoked to program the rules to allow external connectivity for the endpoint.
[ "ProgramExternalConnectivity", "is", "invoked", "to", "program", "the", "rules", "to", "allow", "external", "connectivity", "for", "the", "endpoint", "." ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/remote/driver.go#L326-L338
train
docker/libnetwork
drivers/remote/driver.go
RevokeExternalConnectivity
func (d *driver) RevokeExternalConnectivity(nid, eid string) error { data := &api.RevokeExternalConnectivityRequest{ NetworkID: nid, EndpointID: eid, } err := d.call("RevokeExternalConnectivity", data, &api.RevokeExternalConnectivityResponse{}) if err != nil && plugins.IsNotFound(err) { // It is not mandatory yet to support this method return nil } return err }
go
func (d *driver) RevokeExternalConnectivity(nid, eid string) error { data := &api.RevokeExternalConnectivityRequest{ NetworkID: nid, EndpointID: eid, } err := d.call("RevokeExternalConnectivity", data, &api.RevokeExternalConnectivityResponse{}) if err != nil && plugins.IsNotFound(err) { // It is not mandatory yet to support this method return nil } return err }
[ "func", "(", "d", "*", "driver", ")", "RevokeExternalConnectivity", "(", "nid", ",", "eid", "string", ")", "error", "{", "data", ":=", "&", "api", ".", "RevokeExternalConnectivityRequest", "{", "NetworkID", ":", "nid", ",", "EndpointID", ":", "eid", ",", "}", "\n", "err", ":=", "d", ".", "call", "(", "\"", "\"", ",", "data", ",", "&", "api", ".", "RevokeExternalConnectivityResponse", "{", "}", ")", "\n", "if", "err", "!=", "nil", "&&", "plugins", ".", "IsNotFound", "(", "err", ")", "{", "// It is not mandatory yet to support this method", "return", "nil", "\n", "}", "\n", "return", "err", "\n", "}" ]
// RevokeExternalConnectivity method is invoked to remove any external connectivity programming related to the endpoint.
[ "RevokeExternalConnectivity", "method", "is", "invoked", "to", "remove", "any", "external", "connectivity", "programming", "related", "to", "the", "endpoint", "." ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/remote/driver.go#L341-L352
train
docker/libnetwork
drivers/remote/driver.go
parseInterface
func parseInterface(r api.CreateEndpointResponse) (*api.Interface, error) { var outIf *api.Interface inIf := r.Interface if inIf != nil { var err error outIf = &api.Interface{} if inIf.Address != "" { if outIf.Address, err = types.ParseCIDR(inIf.Address); err != nil { return nil, err } } if inIf.AddressIPv6 != "" { if outIf.AddressIPv6, err = types.ParseCIDR(inIf.AddressIPv6); err != nil { return nil, err } } if inIf.MacAddress != "" { if outIf.MacAddress, err = net.ParseMAC(inIf.MacAddress); err != nil { return nil, err } } } return outIf, nil }
go
func parseInterface(r api.CreateEndpointResponse) (*api.Interface, error) { var outIf *api.Interface inIf := r.Interface if inIf != nil { var err error outIf = &api.Interface{} if inIf.Address != "" { if outIf.Address, err = types.ParseCIDR(inIf.Address); err != nil { return nil, err } } if inIf.AddressIPv6 != "" { if outIf.AddressIPv6, err = types.ParseCIDR(inIf.AddressIPv6); err != nil { return nil, err } } if inIf.MacAddress != "" { if outIf.MacAddress, err = net.ParseMAC(inIf.MacAddress); err != nil { return nil, err } } } return outIf, nil }
[ "func", "parseInterface", "(", "r", "api", ".", "CreateEndpointResponse", ")", "(", "*", "api", ".", "Interface", ",", "error", ")", "{", "var", "outIf", "*", "api", ".", "Interface", "\n\n", "inIf", ":=", "r", ".", "Interface", "\n", "if", "inIf", "!=", "nil", "{", "var", "err", "error", "\n", "outIf", "=", "&", "api", ".", "Interface", "{", "}", "\n", "if", "inIf", ".", "Address", "!=", "\"", "\"", "{", "if", "outIf", ".", "Address", ",", "err", "=", "types", ".", "ParseCIDR", "(", "inIf", ".", "Address", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "if", "inIf", ".", "AddressIPv6", "!=", "\"", "\"", "{", "if", "outIf", ".", "AddressIPv6", ",", "err", "=", "types", ".", "ParseCIDR", "(", "inIf", ".", "AddressIPv6", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "if", "inIf", ".", "MacAddress", "!=", "\"", "\"", "{", "if", "outIf", ".", "MacAddress", ",", "err", "=", "net", ".", "ParseMAC", "(", "inIf", ".", "MacAddress", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "outIf", ",", "nil", "\n", "}" ]
// parseInterfaces validates all the parameters of an Interface and returns them.
[ "parseInterfaces", "validates", "all", "the", "parameters", "of", "an", "Interface", "and", "returns", "them", "." ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/remote/driver.go#L411-L436
train
docker/libnetwork
cmd/proxy/udp_proxy.go
Close
func (proxy *UDPProxy) Close() { proxy.listener.Close() proxy.connTrackLock.Lock() defer proxy.connTrackLock.Unlock() for _, conn := range proxy.connTrackTable { conn.Close() } }
go
func (proxy *UDPProxy) Close() { proxy.listener.Close() proxy.connTrackLock.Lock() defer proxy.connTrackLock.Unlock() for _, conn := range proxy.connTrackTable { conn.Close() } }
[ "func", "(", "proxy", "*", "UDPProxy", ")", "Close", "(", ")", "{", "proxy", ".", "listener", ".", "Close", "(", ")", "\n", "proxy", ".", "connTrackLock", ".", "Lock", "(", ")", "\n", "defer", "proxy", ".", "connTrackLock", ".", "Unlock", "(", ")", "\n", "for", "_", ",", "conn", ":=", "range", "proxy", ".", "connTrackTable", "{", "conn", ".", "Close", "(", ")", "\n", "}", "\n", "}" ]
// Close stops forwarding the traffic.
[ "Close", "stops", "forwarding", "the", "traffic", "." ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/cmd/proxy/udp_proxy.go#L145-L152
train
docker/libnetwork
agent.go
getKeys
func (c *controller) getKeys(subsys string) ([][]byte, []uint64) { c.Lock() defer c.Unlock() sort.Sort(ByTime(c.keys)) keys := [][]byte{} tags := []uint64{} for _, key := range c.keys { if key.Subsystem == subsys { keys = append(keys, key.Key) tags = append(tags, key.LamportTime) } } keys[0], keys[1] = keys[1], keys[0] tags[0], tags[1] = tags[1], tags[0] return keys, tags }
go
func (c *controller) getKeys(subsys string) ([][]byte, []uint64) { c.Lock() defer c.Unlock() sort.Sort(ByTime(c.keys)) keys := [][]byte{} tags := []uint64{} for _, key := range c.keys { if key.Subsystem == subsys { keys = append(keys, key.Key) tags = append(tags, key.LamportTime) } } keys[0], keys[1] = keys[1], keys[0] tags[0], tags[1] = tags[1], tags[0] return keys, tags }
[ "func", "(", "c", "*", "controller", ")", "getKeys", "(", "subsys", "string", ")", "(", "[", "]", "[", "]", "byte", ",", "[", "]", "uint64", ")", "{", "c", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "Unlock", "(", ")", "\n\n", "sort", ".", "Sort", "(", "ByTime", "(", "c", ".", "keys", ")", ")", "\n\n", "keys", ":=", "[", "]", "[", "]", "byte", "{", "}", "\n", "tags", ":=", "[", "]", "uint64", "{", "}", "\n", "for", "_", ",", "key", ":=", "range", "c", ".", "keys", "{", "if", "key", ".", "Subsystem", "==", "subsys", "{", "keys", "=", "append", "(", "keys", ",", "key", ".", "Key", ")", "\n", "tags", "=", "append", "(", "tags", ",", "key", ".", "LamportTime", ")", "\n", "}", "\n", "}", "\n\n", "keys", "[", "0", "]", ",", "keys", "[", "1", "]", "=", "keys", "[", "1", "]", ",", "keys", "[", "0", "]", "\n", "tags", "[", "0", "]", ",", "tags", "[", "1", "]", "=", "tags", "[", "1", "]", ",", "tags", "[", "0", "]", "\n", "return", "keys", ",", "tags", "\n", "}" ]
// For a given subsystem getKeys sorts the keys by lamport time and returns // slice of keys and lamport time which can used as a unique tag for the keys
[ "For", "a", "given", "subsystem", "getKeys", "sorts", "the", "keys", "by", "lamport", "time", "and", "returns", "slice", "of", "keys", "and", "lamport", "time", "which", "can", "used", "as", "a", "unique", "tag", "for", "the", "keys" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/agent.go#L241-L259
train
docker/libnetwork
agent.go
getPrimaryKeyTag
func (c *controller) getPrimaryKeyTag(subsys string) ([]byte, uint64, error) { c.Lock() defer c.Unlock() sort.Sort(ByTime(c.keys)) keys := []*types.EncryptionKey{} for _, key := range c.keys { if key.Subsystem == subsys { keys = append(keys, key) } } return keys[1].Key, keys[1].LamportTime, nil }
go
func (c *controller) getPrimaryKeyTag(subsys string) ([]byte, uint64, error) { c.Lock() defer c.Unlock() sort.Sort(ByTime(c.keys)) keys := []*types.EncryptionKey{} for _, key := range c.keys { if key.Subsystem == subsys { keys = append(keys, key) } } return keys[1].Key, keys[1].LamportTime, nil }
[ "func", "(", "c", "*", "controller", ")", "getPrimaryKeyTag", "(", "subsys", "string", ")", "(", "[", "]", "byte", ",", "uint64", ",", "error", ")", "{", "c", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "Unlock", "(", ")", "\n", "sort", ".", "Sort", "(", "ByTime", "(", "c", ".", "keys", ")", ")", "\n", "keys", ":=", "[", "]", "*", "types", ".", "EncryptionKey", "{", "}", "\n", "for", "_", ",", "key", ":=", "range", "c", ".", "keys", "{", "if", "key", ".", "Subsystem", "==", "subsys", "{", "keys", "=", "append", "(", "keys", ",", "key", ")", "\n", "}", "\n", "}", "\n", "return", "keys", "[", "1", "]", ".", "Key", ",", "keys", "[", "1", "]", ".", "LamportTime", ",", "nil", "\n", "}" ]
// getPrimaryKeyTag returns the primary key for a given subsystem from the // list of sorted key and the associated tag
[ "getPrimaryKeyTag", "returns", "the", "primary", "key", "for", "a", "given", "subsystem", "from", "the", "list", "of", "sorted", "key", "and", "the", "associated", "tag" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/agent.go#L263-L274
train
docker/libnetwork
drivers/ipvlan/ipvlan_joinleave.go
getSubnetforIPv4
func (n *network) getSubnetforIPv4(ip *net.IPNet) *ipv4Subnet { for _, s := range n.config.Ipv4Subnets { _, snet, err := net.ParseCIDR(s.SubnetIP) if err != nil { return nil } // first check if the mask lengths are the same i, _ := snet.Mask.Size() j, _ := ip.Mask.Size() if i != j { continue } if snet.Contains(ip.IP) { return s } } return nil }
go
func (n *network) getSubnetforIPv4(ip *net.IPNet) *ipv4Subnet { for _, s := range n.config.Ipv4Subnets { _, snet, err := net.ParseCIDR(s.SubnetIP) if err != nil { return nil } // first check if the mask lengths are the same i, _ := snet.Mask.Size() j, _ := ip.Mask.Size() if i != j { continue } if snet.Contains(ip.IP) { return s } } return nil }
[ "func", "(", "n", "*", "network", ")", "getSubnetforIPv4", "(", "ip", "*", "net", ".", "IPNet", ")", "*", "ipv4Subnet", "{", "for", "_", ",", "s", ":=", "range", "n", ".", "config", ".", "Ipv4Subnets", "{", "_", ",", "snet", ",", "err", ":=", "net", ".", "ParseCIDR", "(", "s", ".", "SubnetIP", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", "\n", "}", "\n", "// first check if the mask lengths are the same", "i", ",", "_", ":=", "snet", ".", "Mask", ".", "Size", "(", ")", "\n", "j", ",", "_", ":=", "ip", ".", "Mask", ".", "Size", "(", ")", "\n", "if", "i", "!=", "j", "{", "continue", "\n", "}", "\n", "if", "snet", ".", "Contains", "(", "ip", ".", "IP", ")", "{", "return", "s", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// getSubnetforIPv4 returns the ipv4 subnet to which the given IP belongs
[ "getSubnetforIPv4", "returns", "the", "ipv4", "subnet", "to", "which", "the", "given", "IP", "belongs" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/ipvlan/ipvlan_joinleave.go#L160-L178
train
docker/libnetwork
drivers/ipvlan/ipvlan_joinleave.go
getSubnetforIPv6
func (n *network) getSubnetforIPv6(ip *net.IPNet) *ipv6Subnet { for _, s := range n.config.Ipv6Subnets { _, snet, err := net.ParseCIDR(s.SubnetIP) if err != nil { return nil } // first check if the mask lengths are the same i, _ := snet.Mask.Size() j, _ := ip.Mask.Size() if i != j { continue } if snet.Contains(ip.IP) { return s } } return nil }
go
func (n *network) getSubnetforIPv6(ip *net.IPNet) *ipv6Subnet { for _, s := range n.config.Ipv6Subnets { _, snet, err := net.ParseCIDR(s.SubnetIP) if err != nil { return nil } // first check if the mask lengths are the same i, _ := snet.Mask.Size() j, _ := ip.Mask.Size() if i != j { continue } if snet.Contains(ip.IP) { return s } } return nil }
[ "func", "(", "n", "*", "network", ")", "getSubnetforIPv6", "(", "ip", "*", "net", ".", "IPNet", ")", "*", "ipv6Subnet", "{", "for", "_", ",", "s", ":=", "range", "n", ".", "config", ".", "Ipv6Subnets", "{", "_", ",", "snet", ",", "err", ":=", "net", ".", "ParseCIDR", "(", "s", ".", "SubnetIP", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", "\n", "}", "\n", "// first check if the mask lengths are the same", "i", ",", "_", ":=", "snet", ".", "Mask", ".", "Size", "(", ")", "\n", "j", ",", "_", ":=", "ip", ".", "Mask", ".", "Size", "(", ")", "\n", "if", "i", "!=", "j", "{", "continue", "\n", "}", "\n", "if", "snet", ".", "Contains", "(", "ip", ".", "IP", ")", "{", "return", "s", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// getSubnetforIPv6 returns the ipv6 subnet to which the given IP belongs
[ "getSubnetforIPv6", "returns", "the", "ipv6", "subnet", "to", "which", "the", "given", "IP", "belongs" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/ipvlan/ipvlan_joinleave.go#L181-L199
train
docker/libnetwork
client/mflag/flag.go
Out
func (fs *FlagSet) Out() io.Writer { if fs.output == nil { return os.Stderr } return fs.output }
go
func (fs *FlagSet) Out() io.Writer { if fs.output == nil { return os.Stderr } return fs.output }
[ "func", "(", "fs", "*", "FlagSet", ")", "Out", "(", ")", "io", ".", "Writer", "{", "if", "fs", ".", "output", "==", "nil", "{", "return", "os", ".", "Stderr", "\n", "}", "\n", "return", "fs", ".", "output", "\n", "}" ]
// Out returns the destination for usage and error messages.
[ "Out", "returns", "the", "destination", "for", "usage", "and", "error", "messages", "." ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/mflag/flag.go#L384-L389
train
docker/libnetwork
client/mflag/flag.go
IsSet
func (fs *FlagSet) IsSet(name string) bool { return fs.actual[name] != nil }
go
func (fs *FlagSet) IsSet(name string) bool { return fs.actual[name] != nil }
[ "func", "(", "fs", "*", "FlagSet", ")", "IsSet", "(", "name", "string", ")", "bool", "{", "return", "fs", ".", "actual", "[", "name", "]", "!=", "nil", "\n", "}" ]
// IsSet indicates whether the specified flag is set in the given FlagSet
[ "IsSet", "indicates", "whether", "the", "specified", "flag", "is", "set", "in", "the", "given", "FlagSet" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/mflag/flag.go#L431-L433
train
docker/libnetwork
client/mflag/flag.go
Set
func (fs *FlagSet) Set(name, value string) error { flag, ok := fs.formal[name] if !ok { return fmt.Errorf("no such flag -%v", name) } if err := flag.Value.Set(value); err != nil { return err } if fs.actual == nil { fs.actual = make(map[string]*Flag) } fs.actual[name] = flag return nil }
go
func (fs *FlagSet) Set(name, value string) error { flag, ok := fs.formal[name] if !ok { return fmt.Errorf("no such flag -%v", name) } if err := flag.Value.Set(value); err != nil { return err } if fs.actual == nil { fs.actual = make(map[string]*Flag) } fs.actual[name] = flag return nil }
[ "func", "(", "fs", "*", "FlagSet", ")", "Set", "(", "name", ",", "value", "string", ")", "error", "{", "flag", ",", "ok", ":=", "fs", ".", "formal", "[", "name", "]", "\n", "if", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "if", "err", ":=", "flag", ".", "Value", ".", "Set", "(", "value", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "fs", ".", "actual", "==", "nil", "{", "fs", ".", "actual", "=", "make", "(", "map", "[", "string", "]", "*", "Flag", ")", "\n", "}", "\n", "fs", ".", "actual", "[", "name", "]", "=", "flag", "\n", "return", "nil", "\n", "}" ]
// Set sets the value of the named flag.
[ "Set", "sets", "the", "value", "of", "the", "named", "flag", "." ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/mflag/flag.go#L503-L516
train
docker/libnetwork
client/mflag/flag.go
PrintDefaults
func (fs *FlagSet) PrintDefaults() { writer := tabwriter.NewWriter(fs.Out(), 20, 1, 3, ' ', 0) home := homedir.Get() // Don't substitute when HOME is / if runtime.GOOS != "windows" && home == "/" { home = "" } // Add a blank line between cmd description and list of options if fs.FlagCount() > 0 { fmt.Fprintln(writer, "") } fs.VisitAll(func(flag *Flag) { names := []string{} for _, name := range flag.Names { if name[0] != '#' { names = append(names, name) } } if len(names) > 0 && len(flag.Usage) > 0 { val := flag.DefValue if home != "" && strings.HasPrefix(val, home) { val = homedir.GetShortcutString() + val[len(home):] } if isZeroValue(val) { format := " -%s" fmt.Fprintf(writer, format, strings.Join(names, ", -")) } else { format := " -%s=%s" fmt.Fprintf(writer, format, strings.Join(names, ", -"), val) } for _, line := range strings.Split(flag.Usage, "\n") { fmt.Fprintln(writer, "\t", line) } } }) writer.Flush() }
go
func (fs *FlagSet) PrintDefaults() { writer := tabwriter.NewWriter(fs.Out(), 20, 1, 3, ' ', 0) home := homedir.Get() // Don't substitute when HOME is / if runtime.GOOS != "windows" && home == "/" { home = "" } // Add a blank line between cmd description and list of options if fs.FlagCount() > 0 { fmt.Fprintln(writer, "") } fs.VisitAll(func(flag *Flag) { names := []string{} for _, name := range flag.Names { if name[0] != '#' { names = append(names, name) } } if len(names) > 0 && len(flag.Usage) > 0 { val := flag.DefValue if home != "" && strings.HasPrefix(val, home) { val = homedir.GetShortcutString() + val[len(home):] } if isZeroValue(val) { format := " -%s" fmt.Fprintf(writer, format, strings.Join(names, ", -")) } else { format := " -%s=%s" fmt.Fprintf(writer, format, strings.Join(names, ", -"), val) } for _, line := range strings.Split(flag.Usage, "\n") { fmt.Fprintln(writer, "\t", line) } } }) writer.Flush() }
[ "func", "(", "fs", "*", "FlagSet", ")", "PrintDefaults", "(", ")", "{", "writer", ":=", "tabwriter", ".", "NewWriter", "(", "fs", ".", "Out", "(", ")", ",", "20", ",", "1", ",", "3", ",", "' '", ",", "0", ")", "\n", "home", ":=", "homedir", ".", "Get", "(", ")", "\n\n", "// Don't substitute when HOME is /", "if", "runtime", ".", "GOOS", "!=", "\"", "\"", "&&", "home", "==", "\"", "\"", "{", "home", "=", "\"", "\"", "\n", "}", "\n\n", "// Add a blank line between cmd description and list of options", "if", "fs", ".", "FlagCount", "(", ")", ">", "0", "{", "fmt", ".", "Fprintln", "(", "writer", ",", "\"", "\"", ")", "\n", "}", "\n\n", "fs", ".", "VisitAll", "(", "func", "(", "flag", "*", "Flag", ")", "{", "names", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "name", ":=", "range", "flag", ".", "Names", "{", "if", "name", "[", "0", "]", "!=", "'#'", "{", "names", "=", "append", "(", "names", ",", "name", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "names", ")", ">", "0", "&&", "len", "(", "flag", ".", "Usage", ")", ">", "0", "{", "val", ":=", "flag", ".", "DefValue", "\n\n", "if", "home", "!=", "\"", "\"", "&&", "strings", ".", "HasPrefix", "(", "val", ",", "home", ")", "{", "val", "=", "homedir", ".", "GetShortcutString", "(", ")", "+", "val", "[", "len", "(", "home", ")", ":", "]", "\n", "}", "\n\n", "if", "isZeroValue", "(", "val", ")", "{", "format", ":=", "\"", "\"", "\n", "fmt", ".", "Fprintf", "(", "writer", ",", "format", ",", "strings", ".", "Join", "(", "names", ",", "\"", "\"", ")", ")", "\n", "}", "else", "{", "format", ":=", "\"", "\"", "\n", "fmt", ".", "Fprintf", "(", "writer", ",", "format", ",", "strings", ".", "Join", "(", "names", ",", "\"", "\"", ")", ",", "val", ")", "\n", "}", "\n", "for", "_", ",", "line", ":=", "range", "strings", ".", "Split", "(", "flag", ".", "Usage", ",", "\"", "\\n", "\"", ")", "{", "fmt", ".", "Fprintln", "(", "writer", ",", "\"", "\\t", "\"", ",", "line", ")", "\n", "}", "\n", "}", "\n", "}", ")", "\n", "writer", ".", "Flush", "(", ")", "\n", "}" ]
// PrintDefaults prints, to standard error unless configured // otherwise, the default values of all defined flags in the set.
[ "PrintDefaults", "prints", "to", "standard", "error", "unless", "configured", "otherwise", "the", "default", "values", "of", "all", "defined", "flags", "in", "the", "set", "." ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/mflag/flag.go#L539-L580
train
docker/libnetwork
client/mflag/flag.go
FlagCountUndeprecated
func (fs *FlagSet) FlagCountUndeprecated() int { count := 0 for _, flag := range sortFlags(fs.formal) { for _, name := range flag.Names { if name[0] != '#' { count++ break } } } return count }
go
func (fs *FlagSet) FlagCountUndeprecated() int { count := 0 for _, flag := range sortFlags(fs.formal) { for _, name := range flag.Names { if name[0] != '#' { count++ break } } } return count }
[ "func", "(", "fs", "*", "FlagSet", ")", "FlagCountUndeprecated", "(", ")", "int", "{", "count", ":=", "0", "\n", "for", "_", ",", "flag", ":=", "range", "sortFlags", "(", "fs", ".", "formal", ")", "{", "for", "_", ",", "name", ":=", "range", "flag", ".", "Names", "{", "if", "name", "[", "0", "]", "!=", "'#'", "{", "count", "++", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "count", "\n", "}" ]
// FlagCountUndeprecated returns the number of undeprecated flags that have been defined.
[ "FlagCountUndeprecated", "returns", "the", "number", "of", "undeprecated", "flags", "that", "have", "been", "defined", "." ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/mflag/flag.go#L618-L629
train
docker/libnetwork
client/mflag/flag.go
usage
func (fs *FlagSet) usage() { if fs == CommandLine { Usage() } else if fs.Usage == nil { defaultUsage(fs) } else { fs.Usage() } }
go
func (fs *FlagSet) usage() { if fs == CommandLine { Usage() } else if fs.Usage == nil { defaultUsage(fs) } else { fs.Usage() } }
[ "func", "(", "fs", "*", "FlagSet", ")", "usage", "(", ")", "{", "if", "fs", "==", "CommandLine", "{", "Usage", "(", ")", "\n", "}", "else", "if", "fs", ".", "Usage", "==", "nil", "{", "defaultUsage", "(", "fs", ")", "\n", "}", "else", "{", "fs", ".", "Usage", "(", ")", "\n", "}", "\n", "}" ]
// usage calls the Usage method for the flag set, or the usage function if // the flag set is CommandLine.
[ "usage", "calls", "the", "Usage", "method", "for", "the", "flag", "set", "or", "the", "usage", "function", "if", "the", "flag", "set", "is", "CommandLine", "." ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/mflag/flag.go#L952-L960
train
docker/libnetwork
client/mflag/flag.go
ReportError
func (fs *FlagSet) ReportError(str string, withHelp bool) { if withHelp { if os.Args[0] == fs.Name() { str += ".\nSee '" + os.Args[0] + " --help'" } else { str += ".\nSee '" + os.Args[0] + " " + fs.Name() + " --help'" } } fmt.Fprintf(fs.Out(), "%s: %s.\n", os.Args[0], str) }
go
func (fs *FlagSet) ReportError(str string, withHelp bool) { if withHelp { if os.Args[0] == fs.Name() { str += ".\nSee '" + os.Args[0] + " --help'" } else { str += ".\nSee '" + os.Args[0] + " " + fs.Name() + " --help'" } } fmt.Fprintf(fs.Out(), "%s: %s.\n", os.Args[0], str) }
[ "func", "(", "fs", "*", "FlagSet", ")", "ReportError", "(", "str", "string", ",", "withHelp", "bool", ")", "{", "if", "withHelp", "{", "if", "os", ".", "Args", "[", "0", "]", "==", "fs", ".", "Name", "(", ")", "{", "str", "+=", "\"", "\\n", "\"", "+", "os", ".", "Args", "[", "0", "]", "+", "\"", "\"", "\n", "}", "else", "{", "str", "+=", "\"", "\\n", "\"", "+", "os", ".", "Args", "[", "0", "]", "+", "\"", "\"", "+", "fs", ".", "Name", "(", ")", "+", "\"", "\"", "\n", "}", "\n", "}", "\n", "fmt", ".", "Fprintf", "(", "fs", ".", "Out", "(", ")", ",", "\"", "\\n", "\"", ",", "os", ".", "Args", "[", "0", "]", ",", "str", ")", "\n", "}" ]
// ReportError is a utility method that prints a user-friendly message // containing the error that occurred during parsing and a suggestion to get help
[ "ReportError", "is", "a", "utility", "method", "that", "prints", "a", "user", "-", "friendly", "message", "containing", "the", "error", "that", "occurred", "during", "parsing", "and", "a", "suggestion", "to", "get", "help" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/mflag/flag.go#L1158-L1167
train
docker/libnetwork
client/mflag/flag.go
Name
func (v mergeVal) Name() string { type namedValue interface { Name() string } if nVal, ok := v.Value.(namedValue); ok { return nVal.Name() } return v.key }
go
func (v mergeVal) Name() string { type namedValue interface { Name() string } if nVal, ok := v.Value.(namedValue); ok { return nVal.Name() } return v.key }
[ "func", "(", "v", "mergeVal", ")", "Name", "(", ")", "string", "{", "type", "namedValue", "interface", "{", "Name", "(", ")", "string", "\n", "}", "\n", "if", "nVal", ",", "ok", ":=", "v", ".", "Value", ".", "(", "namedValue", ")", ";", "ok", "{", "return", "nVal", ".", "Name", "(", ")", "\n", "}", "\n", "return", "v", ".", "key", "\n", "}" ]
// Name returns the name of a mergeVal. // If the original value had a name, return the original name, // otherwise, return the key assigned to this mergeVal.
[ "Name", "returns", "the", "name", "of", "a", "mergeVal", ".", "If", "the", "original", "value", "had", "a", "name", "return", "the", "original", "name", "otherwise", "return", "the", "key", "assigned", "to", "this", "mergeVal", "." ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/mflag/flag.go#L1229-L1237
train
docker/libnetwork
client/mflag/flag.go
Merge
func Merge(dest *FlagSet, flagsets ...*FlagSet) error { for _, fset := range flagsets { if fset.formal == nil { continue } for k, f := range fset.formal { if _, ok := dest.formal[k]; ok { var err error if fset.name == "" { err = fmt.Errorf("flag redefined: %s", k) } else { err = fmt.Errorf("%s flag redefined: %s", fset.name, k) } fmt.Fprintln(fset.Out(), err.Error()) // Happens only if flags are declared with identical names switch dest.errorHandling { case ContinueOnError: return err case ExitOnError: os.Exit(2) case PanicOnError: panic(err) } } newF := *f newF.Value = mergeVal{f.Value, k, fset} if dest.formal == nil { dest.formal = make(map[string]*Flag) } dest.formal[k] = &newF } } return nil }
go
func Merge(dest *FlagSet, flagsets ...*FlagSet) error { for _, fset := range flagsets { if fset.formal == nil { continue } for k, f := range fset.formal { if _, ok := dest.formal[k]; ok { var err error if fset.name == "" { err = fmt.Errorf("flag redefined: %s", k) } else { err = fmt.Errorf("%s flag redefined: %s", fset.name, k) } fmt.Fprintln(fset.Out(), err.Error()) // Happens only if flags are declared with identical names switch dest.errorHandling { case ContinueOnError: return err case ExitOnError: os.Exit(2) case PanicOnError: panic(err) } } newF := *f newF.Value = mergeVal{f.Value, k, fset} if dest.formal == nil { dest.formal = make(map[string]*Flag) } dest.formal[k] = &newF } } return nil }
[ "func", "Merge", "(", "dest", "*", "FlagSet", ",", "flagsets", "...", "*", "FlagSet", ")", "error", "{", "for", "_", ",", "fset", ":=", "range", "flagsets", "{", "if", "fset", ".", "formal", "==", "nil", "{", "continue", "\n", "}", "\n", "for", "k", ",", "f", ":=", "range", "fset", ".", "formal", "{", "if", "_", ",", "ok", ":=", "dest", ".", "formal", "[", "k", "]", ";", "ok", "{", "var", "err", "error", "\n", "if", "fset", ".", "name", "==", "\"", "\"", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "k", ")", "\n", "}", "else", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "fset", ".", "name", ",", "k", ")", "\n", "}", "\n", "fmt", ".", "Fprintln", "(", "fset", ".", "Out", "(", ")", ",", "err", ".", "Error", "(", ")", ")", "\n", "// Happens only if flags are declared with identical names", "switch", "dest", ".", "errorHandling", "{", "case", "ContinueOnError", ":", "return", "err", "\n", "case", "ExitOnError", ":", "os", ".", "Exit", "(", "2", ")", "\n", "case", "PanicOnError", ":", "panic", "(", "err", ")", "\n", "}", "\n", "}", "\n", "newF", ":=", "*", "f", "\n", "newF", ".", "Value", "=", "mergeVal", "{", "f", ".", "Value", ",", "k", ",", "fset", "}", "\n", "if", "dest", ".", "formal", "==", "nil", "{", "dest", ".", "formal", "=", "make", "(", "map", "[", "string", "]", "*", "Flag", ")", "\n", "}", "\n", "dest", ".", "formal", "[", "k", "]", "=", "&", "newF", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Merge is an helper function that merges n FlagSets into a single dest FlagSet // In case of name collision between the flagsets it will apply // the destination FlagSet's errorHandling behavior.
[ "Merge", "is", "an", "helper", "function", "that", "merges", "n", "FlagSets", "into", "a", "single", "dest", "FlagSet", "In", "case", "of", "name", "collision", "between", "the", "flagsets", "it", "will", "apply", "the", "destination", "FlagSet", "s", "errorHandling", "behavior", "." ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/mflag/flag.go#L1242-L1275
train
docker/libnetwork
sandbox_dns_unix.go
rebuildDNS
func (sb *sandbox) rebuildDNS() error { currRC, err := resolvconf.GetSpecific(sb.config.resolvConfPath) if err != nil { return err } if len(sb.extDNS) == 0 { sb.setExternalResolvers(currRC.Content, types.IPv4, false) } var ( dnsList = []string{sb.resolver.NameServer()} dnsOptionsList = resolvconf.GetOptions(currRC.Content) dnsSearchList = resolvconf.GetSearchDomains(currRC.Content) ) // external v6 DNS servers has to be listed in resolv.conf dnsList = append(dnsList, resolvconf.GetNameservers(currRC.Content, types.IPv6)...) // If the user config and embedded DNS server both have ndots option set, // remember the user's config so that unqualified names not in the docker // domain can be dropped. resOptions := sb.resolver.ResolverOptions() dnsOpt: for _, resOpt := range resOptions { if strings.Contains(resOpt, "ndots") { for _, option := range dnsOptionsList { if strings.Contains(option, "ndots") { parts := strings.Split(option, ":") if len(parts) != 2 { return fmt.Errorf("invalid ndots option %v", option) } if num, err := strconv.Atoi(parts[1]); err != nil { return fmt.Errorf("invalid number for ndots option: %v", parts[1]) } else if num >= 0 { // if the user sets ndots, use the user setting sb.ndotsSet = true break dnsOpt } else { return fmt.Errorf("invalid number for ndots option: %v", num) } } } } } if !sb.ndotsSet { // if the user did not set the ndots, set it to 0 to prioritize the service name resolution // Ref: https://linux.die.net/man/5/resolv.conf dnsOptionsList = append(dnsOptionsList, resOptions...) } _, err = resolvconf.Build(sb.config.resolvConfPath, dnsList, dnsSearchList, dnsOptionsList) return err }
go
func (sb *sandbox) rebuildDNS() error { currRC, err := resolvconf.GetSpecific(sb.config.resolvConfPath) if err != nil { return err } if len(sb.extDNS) == 0 { sb.setExternalResolvers(currRC.Content, types.IPv4, false) } var ( dnsList = []string{sb.resolver.NameServer()} dnsOptionsList = resolvconf.GetOptions(currRC.Content) dnsSearchList = resolvconf.GetSearchDomains(currRC.Content) ) // external v6 DNS servers has to be listed in resolv.conf dnsList = append(dnsList, resolvconf.GetNameservers(currRC.Content, types.IPv6)...) // If the user config and embedded DNS server both have ndots option set, // remember the user's config so that unqualified names not in the docker // domain can be dropped. resOptions := sb.resolver.ResolverOptions() dnsOpt: for _, resOpt := range resOptions { if strings.Contains(resOpt, "ndots") { for _, option := range dnsOptionsList { if strings.Contains(option, "ndots") { parts := strings.Split(option, ":") if len(parts) != 2 { return fmt.Errorf("invalid ndots option %v", option) } if num, err := strconv.Atoi(parts[1]); err != nil { return fmt.Errorf("invalid number for ndots option: %v", parts[1]) } else if num >= 0 { // if the user sets ndots, use the user setting sb.ndotsSet = true break dnsOpt } else { return fmt.Errorf("invalid number for ndots option: %v", num) } } } } } if !sb.ndotsSet { // if the user did not set the ndots, set it to 0 to prioritize the service name resolution // Ref: https://linux.die.net/man/5/resolv.conf dnsOptionsList = append(dnsOptionsList, resOptions...) } _, err = resolvconf.Build(sb.config.resolvConfPath, dnsList, dnsSearchList, dnsOptionsList) return err }
[ "func", "(", "sb", "*", "sandbox", ")", "rebuildDNS", "(", ")", "error", "{", "currRC", ",", "err", ":=", "resolvconf", ".", "GetSpecific", "(", "sb", ".", "config", ".", "resolvConfPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "len", "(", "sb", ".", "extDNS", ")", "==", "0", "{", "sb", ".", "setExternalResolvers", "(", "currRC", ".", "Content", ",", "types", ".", "IPv4", ",", "false", ")", "\n", "}", "\n", "var", "(", "dnsList", "=", "[", "]", "string", "{", "sb", ".", "resolver", ".", "NameServer", "(", ")", "}", "\n", "dnsOptionsList", "=", "resolvconf", ".", "GetOptions", "(", "currRC", ".", "Content", ")", "\n", "dnsSearchList", "=", "resolvconf", ".", "GetSearchDomains", "(", "currRC", ".", "Content", ")", "\n", ")", "\n\n", "// external v6 DNS servers has to be listed in resolv.conf", "dnsList", "=", "append", "(", "dnsList", ",", "resolvconf", ".", "GetNameservers", "(", "currRC", ".", "Content", ",", "types", ".", "IPv6", ")", "...", ")", "\n\n", "// If the user config and embedded DNS server both have ndots option set,", "// remember the user's config so that unqualified names not in the docker", "// domain can be dropped.", "resOptions", ":=", "sb", ".", "resolver", ".", "ResolverOptions", "(", ")", "\n\n", "dnsOpt", ":", "for", "_", ",", "resOpt", ":=", "range", "resOptions", "{", "if", "strings", ".", "Contains", "(", "resOpt", ",", "\"", "\"", ")", "{", "for", "_", ",", "option", ":=", "range", "dnsOptionsList", "{", "if", "strings", ".", "Contains", "(", "option", ",", "\"", "\"", ")", "{", "parts", ":=", "strings", ".", "Split", "(", "option", ",", "\"", "\"", ")", "\n", "if", "len", "(", "parts", ")", "!=", "2", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "option", ")", "\n", "}", "\n", "if", "num", ",", "err", ":=", "strconv", ".", "Atoi", "(", "parts", "[", "1", "]", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "parts", "[", "1", "]", ")", "\n", "}", "else", "if", "num", ">=", "0", "{", "// if the user sets ndots, use the user setting", "sb", ".", "ndotsSet", "=", "true", "\n", "break", "dnsOpt", "\n", "}", "else", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "num", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "if", "!", "sb", ".", "ndotsSet", "{", "// if the user did not set the ndots, set it to 0 to prioritize the service name resolution", "// Ref: https://linux.die.net/man/5/resolv.conf", "dnsOptionsList", "=", "append", "(", "dnsOptionsList", ",", "resOptions", "...", ")", "\n", "}", "\n\n", "_", ",", "err", "=", "resolvconf", ".", "Build", "(", "sb", ".", "config", ".", "resolvConfPath", ",", "dnsList", ",", "dnsSearchList", ",", "dnsOptionsList", ")", "\n", "return", "err", "\n", "}" ]
// Embedded DNS server has to be enabled for this sandbox. Rebuild the container's // resolv.conf by doing the following // - Add only the embedded server's IP to container's resolv.conf // - If the embedded server needs any resolv.conf options add it to the current list
[ "Embedded", "DNS", "server", "has", "to", "be", "enabled", "for", "this", "sandbox", ".", "Rebuild", "the", "container", "s", "resolv", ".", "conf", "by", "doing", "the", "following", "-", "Add", "only", "the", "embedded", "server", "s", "IP", "to", "container", "s", "resolv", ".", "conf", "-", "If", "the", "embedded", "server", "needs", "any", "resolv", ".", "conf", "options", "add", "it", "to", "the", "current", "list" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/sandbox_dns_unix.go#L351-L405
train
docker/libnetwork
client/client.go
NewNetworkCli
func NewNetworkCli(out, err io.Writer, call CallFunc) *NetworkCli { return &NetworkCli{ out: out, err: err, call: call, } }
go
func NewNetworkCli(out, err io.Writer, call CallFunc) *NetworkCli { return &NetworkCli{ out: out, err: err, call: call, } }
[ "func", "NewNetworkCli", "(", "out", ",", "err", "io", ".", "Writer", ",", "call", "CallFunc", ")", "*", "NetworkCli", "{", "return", "&", "NetworkCli", "{", "out", ":", "out", ",", "err", ":", "err", ",", "call", ":", "call", ",", "}", "\n", "}" ]
// NewNetworkCli is a convenient function to create a NetworkCli object
[ "NewNetworkCli", "is", "a", "convenient", "function", "to", "create", "a", "NetworkCli", "object" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/client.go#L25-L31
train
docker/libnetwork
client/client.go
getMethod
func (cli *NetworkCli) getMethod(args ...string) (func(string, ...string) error, bool) { camelArgs := make([]string, len(args)) for i, s := range args { if len(s) == 0 { return nil, false } camelArgs[i] = strings.ToUpper(s[:1]) + strings.ToLower(s[1:]) } methodName := "Cmd" + strings.Join(camelArgs, "") method := reflect.ValueOf(cli).MethodByName(methodName) if !method.IsValid() { return nil, false } return method.Interface().(func(string, ...string) error), true }
go
func (cli *NetworkCli) getMethod(args ...string) (func(string, ...string) error, bool) { camelArgs := make([]string, len(args)) for i, s := range args { if len(s) == 0 { return nil, false } camelArgs[i] = strings.ToUpper(s[:1]) + strings.ToLower(s[1:]) } methodName := "Cmd" + strings.Join(camelArgs, "") method := reflect.ValueOf(cli).MethodByName(methodName) if !method.IsValid() { return nil, false } return method.Interface().(func(string, ...string) error), true }
[ "func", "(", "cli", "*", "NetworkCli", ")", "getMethod", "(", "args", "...", "string", ")", "(", "func", "(", "string", ",", "...", "string", ")", "error", ",", "bool", ")", "{", "camelArgs", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "args", ")", ")", "\n", "for", "i", ",", "s", ":=", "range", "args", "{", "if", "len", "(", "s", ")", "==", "0", "{", "return", "nil", ",", "false", "\n", "}", "\n", "camelArgs", "[", "i", "]", "=", "strings", ".", "ToUpper", "(", "s", "[", ":", "1", "]", ")", "+", "strings", ".", "ToLower", "(", "s", "[", "1", ":", "]", ")", "\n", "}", "\n", "methodName", ":=", "\"", "\"", "+", "strings", ".", "Join", "(", "camelArgs", ",", "\"", "\"", ")", "\n", "method", ":=", "reflect", ".", "ValueOf", "(", "cli", ")", ".", "MethodByName", "(", "methodName", ")", "\n", "if", "!", "method", ".", "IsValid", "(", ")", "{", "return", "nil", ",", "false", "\n", "}", "\n", "return", "method", ".", "Interface", "(", ")", ".", "(", "func", "(", "string", ",", "...", "string", ")", "error", ")", ",", "true", "\n", "}" ]
// getMethod is Borrowed from Docker UI which uses reflection to identify the UI Handler
[ "getMethod", "is", "Borrowed", "from", "Docker", "UI", "which", "uses", "reflection", "to", "identify", "the", "UI", "Handler" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/client.go#L34-L48
train
docker/libnetwork
client/client.go
Cmd
func (cli *NetworkCli) Cmd(chain string, args ...string) error { if len(args) > 2 { method, exists := cli.getMethod(args[:3]...) if exists { return method(chain+" "+args[0]+" "+args[1], args[3:]...) } } if len(args) > 1 { method, exists := cli.getMethod(args[:2]...) if exists { return method(chain+" "+args[0], args[2:]...) } } if len(args) > 0 { method, exists := cli.getMethod(args[0]) if !exists { return fmt.Errorf("%s: '%s' is not a %s command. See '%s --help'", chain, args[0], chain, chain) } return method(chain, args[1:]...) } flag.Usage() return nil }
go
func (cli *NetworkCli) Cmd(chain string, args ...string) error { if len(args) > 2 { method, exists := cli.getMethod(args[:3]...) if exists { return method(chain+" "+args[0]+" "+args[1], args[3:]...) } } if len(args) > 1 { method, exists := cli.getMethod(args[:2]...) if exists { return method(chain+" "+args[0], args[2:]...) } } if len(args) > 0 { method, exists := cli.getMethod(args[0]) if !exists { return fmt.Errorf("%s: '%s' is not a %s command. See '%s --help'", chain, args[0], chain, chain) } return method(chain, args[1:]...) } flag.Usage() return nil }
[ "func", "(", "cli", "*", "NetworkCli", ")", "Cmd", "(", "chain", "string", ",", "args", "...", "string", ")", "error", "{", "if", "len", "(", "args", ")", ">", "2", "{", "method", ",", "exists", ":=", "cli", ".", "getMethod", "(", "args", "[", ":", "3", "]", "...", ")", "\n", "if", "exists", "{", "return", "method", "(", "chain", "+", "\"", "\"", "+", "args", "[", "0", "]", "+", "\"", "\"", "+", "args", "[", "1", "]", ",", "args", "[", "3", ":", "]", "...", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "args", ")", ">", "1", "{", "method", ",", "exists", ":=", "cli", ".", "getMethod", "(", "args", "[", ":", "2", "]", "...", ")", "\n", "if", "exists", "{", "return", "method", "(", "chain", "+", "\"", "\"", "+", "args", "[", "0", "]", ",", "args", "[", "2", ":", "]", "...", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "args", ")", ">", "0", "{", "method", ",", "exists", ":=", "cli", ".", "getMethod", "(", "args", "[", "0", "]", ")", "\n", "if", "!", "exists", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "chain", ",", "args", "[", "0", "]", ",", "chain", ",", "chain", ")", "\n", "}", "\n", "return", "method", "(", "chain", ",", "args", "[", "1", ":", "]", "...", ")", "\n", "}", "\n", "flag", ".", "Usage", "(", ")", "\n", "return", "nil", "\n", "}" ]
// Cmd is borrowed from Docker UI and acts as the entry point for network UI commands. // network UI commands are designed to be invoked from multiple parent chains
[ "Cmd", "is", "borrowed", "from", "Docker", "UI", "and", "acts", "as", "the", "entry", "point", "for", "network", "UI", "commands", ".", "network", "UI", "commands", "are", "designed", "to", "be", "invoked", "from", "multiple", "parent", "chains" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/client.go#L52-L74
train
docker/libnetwork
client/client.go
Subcmd
func (cli *NetworkCli) Subcmd(chain, name, signature, description string, exitOnError bool) *flag.FlagSet { var errorHandling flag.ErrorHandling if exitOnError { errorHandling = flag.ExitOnError } else { errorHandling = flag.ContinueOnError } flags := flag.NewFlagSet(name, errorHandling) flags.Usage = func() { flags.ShortUsage() flags.PrintDefaults() } flags.ShortUsage = func() { options := "" if signature != "" { signature = " " + signature } if flags.FlagCountUndeprecated() > 0 { options = " [OPTIONS]" } fmt.Fprintf(cli.out, "\nUsage: %s %s%s%s\n\n%s\n\n", chain, name, options, signature, description) flags.SetOutput(cli.out) } return flags }
go
func (cli *NetworkCli) Subcmd(chain, name, signature, description string, exitOnError bool) *flag.FlagSet { var errorHandling flag.ErrorHandling if exitOnError { errorHandling = flag.ExitOnError } else { errorHandling = flag.ContinueOnError } flags := flag.NewFlagSet(name, errorHandling) flags.Usage = func() { flags.ShortUsage() flags.PrintDefaults() } flags.ShortUsage = func() { options := "" if signature != "" { signature = " " + signature } if flags.FlagCountUndeprecated() > 0 { options = " [OPTIONS]" } fmt.Fprintf(cli.out, "\nUsage: %s %s%s%s\n\n%s\n\n", chain, name, options, signature, description) flags.SetOutput(cli.out) } return flags }
[ "func", "(", "cli", "*", "NetworkCli", ")", "Subcmd", "(", "chain", ",", "name", ",", "signature", ",", "description", "string", ",", "exitOnError", "bool", ")", "*", "flag", ".", "FlagSet", "{", "var", "errorHandling", "flag", ".", "ErrorHandling", "\n", "if", "exitOnError", "{", "errorHandling", "=", "flag", ".", "ExitOnError", "\n", "}", "else", "{", "errorHandling", "=", "flag", ".", "ContinueOnError", "\n", "}", "\n", "flags", ":=", "flag", ".", "NewFlagSet", "(", "name", ",", "errorHandling", ")", "\n", "flags", ".", "Usage", "=", "func", "(", ")", "{", "flags", ".", "ShortUsage", "(", ")", "\n", "flags", ".", "PrintDefaults", "(", ")", "\n", "}", "\n", "flags", ".", "ShortUsage", "=", "func", "(", ")", "{", "options", ":=", "\"", "\"", "\n", "if", "signature", "!=", "\"", "\"", "{", "signature", "=", "\"", "\"", "+", "signature", "\n", "}", "\n", "if", "flags", ".", "FlagCountUndeprecated", "(", ")", ">", "0", "{", "options", "=", "\"", "\"", "\n", "}", "\n", "fmt", ".", "Fprintf", "(", "cli", ".", "out", ",", "\"", "\\n", "\\n", "\\n", "\\n", "\\n", "\"", ",", "chain", ",", "name", ",", "options", ",", "signature", ",", "description", ")", "\n", "flags", ".", "SetOutput", "(", "cli", ".", "out", ")", "\n", "}", "\n", "return", "flags", "\n", "}" ]
// Subcmd is borrowed from Docker UI and performs the same function of configuring the subCmds
[ "Subcmd", "is", "borrowed", "from", "Docker", "UI", "and", "performs", "the", "same", "function", "of", "configuring", "the", "subCmds" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/client.go#L77-L101
train
docker/libnetwork
etchosts/etchosts.go
WriteTo
func (r Record) WriteTo(w io.Writer) (int64, error) { n, err := fmt.Fprintf(w, "%s\t%s\n", r.IP, r.Hosts) return int64(n), err }
go
func (r Record) WriteTo(w io.Writer) (int64, error) { n, err := fmt.Fprintf(w, "%s\t%s\n", r.IP, r.Hosts) return int64(n), err }
[ "func", "(", "r", "Record", ")", "WriteTo", "(", "w", "io", ".", "Writer", ")", "(", "int64", ",", "error", ")", "{", "n", ",", "err", ":=", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\t", "\\n", "\"", ",", "r", ".", "IP", ",", "r", ".", "Hosts", ")", "\n", "return", "int64", "(", "n", ")", ",", "err", "\n", "}" ]
// WriteTo writes record to file and returns bytes written or error
[ "WriteTo", "writes", "record", "to", "file", "and", "returns", "bytes", "written", "or", "error" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/etchosts/etchosts.go#L22-L25
train
docker/libnetwork
etchosts/etchosts.go
Drop
func Drop(path string) { pathMutex.Lock() defer pathMutex.Unlock() delete(pathMap, path) }
go
func Drop(path string) { pathMutex.Lock() defer pathMutex.Unlock() delete(pathMap, path) }
[ "func", "Drop", "(", "path", "string", ")", "{", "pathMutex", ".", "Lock", "(", ")", "\n", "defer", "pathMutex", ".", "Unlock", "(", ")", "\n\n", "delete", "(", "pathMap", ",", "path", ")", "\n", "}" ]
// Drop drops the path string from the path cache
[ "Drop", "drops", "the", "path", "string", "from", "the", "path", "cache" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/etchosts/etchosts.go#L63-L68
train
docker/libnetwork
etchosts/etchosts.go
Build
func Build(path, IP, hostname, domainname string, extraContent []Record) error { defer pathLock(path)() content := bytes.NewBuffer(nil) if IP != "" { //set main record var mainRec Record mainRec.IP = IP // User might have provided a FQDN in hostname or split it across hostname // and domainname. We want the FQDN and the bare hostname. fqdn := hostname if domainname != "" { fqdn = fmt.Sprintf("%s.%s", fqdn, domainname) } parts := strings.SplitN(fqdn, ".", 2) if len(parts) == 2 { mainRec.Hosts = fmt.Sprintf("%s %s", fqdn, parts[0]) } else { mainRec.Hosts = fqdn } if _, err := mainRec.WriteTo(content); err != nil { return err } } // Write defaultContent slice to buffer for _, r := range defaultContent { if _, err := r.WriteTo(content); err != nil { return err } } // Write extra content from function arguments for _, r := range extraContent { if _, err := r.WriteTo(content); err != nil { return err } } return ioutil.WriteFile(path, content.Bytes(), 0644) }
go
func Build(path, IP, hostname, domainname string, extraContent []Record) error { defer pathLock(path)() content := bytes.NewBuffer(nil) if IP != "" { //set main record var mainRec Record mainRec.IP = IP // User might have provided a FQDN in hostname or split it across hostname // and domainname. We want the FQDN and the bare hostname. fqdn := hostname if domainname != "" { fqdn = fmt.Sprintf("%s.%s", fqdn, domainname) } parts := strings.SplitN(fqdn, ".", 2) if len(parts) == 2 { mainRec.Hosts = fmt.Sprintf("%s %s", fqdn, parts[0]) } else { mainRec.Hosts = fqdn } if _, err := mainRec.WriteTo(content); err != nil { return err } } // Write defaultContent slice to buffer for _, r := range defaultContent { if _, err := r.WriteTo(content); err != nil { return err } } // Write extra content from function arguments for _, r := range extraContent { if _, err := r.WriteTo(content); err != nil { return err } } return ioutil.WriteFile(path, content.Bytes(), 0644) }
[ "func", "Build", "(", "path", ",", "IP", ",", "hostname", ",", "domainname", "string", ",", "extraContent", "[", "]", "Record", ")", "error", "{", "defer", "pathLock", "(", "path", ")", "(", ")", "\n\n", "content", ":=", "bytes", ".", "NewBuffer", "(", "nil", ")", "\n", "if", "IP", "!=", "\"", "\"", "{", "//set main record", "var", "mainRec", "Record", "\n", "mainRec", ".", "IP", "=", "IP", "\n", "// User might have provided a FQDN in hostname or split it across hostname", "// and domainname. We want the FQDN and the bare hostname.", "fqdn", ":=", "hostname", "\n", "if", "domainname", "!=", "\"", "\"", "{", "fqdn", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "fqdn", ",", "domainname", ")", "\n", "}", "\n", "parts", ":=", "strings", ".", "SplitN", "(", "fqdn", ",", "\"", "\"", ",", "2", ")", "\n", "if", "len", "(", "parts", ")", "==", "2", "{", "mainRec", ".", "Hosts", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "fqdn", ",", "parts", "[", "0", "]", ")", "\n", "}", "else", "{", "mainRec", ".", "Hosts", "=", "fqdn", "\n", "}", "\n", "if", "_", ",", "err", ":=", "mainRec", ".", "WriteTo", "(", "content", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "// Write defaultContent slice to buffer", "for", "_", ",", "r", ":=", "range", "defaultContent", "{", "if", "_", ",", "err", ":=", "r", ".", "WriteTo", "(", "content", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "// Write extra content from function arguments", "for", "_", ",", "r", ":=", "range", "extraContent", "{", "if", "_", ",", "err", ":=", "r", ".", "WriteTo", "(", "content", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "ioutil", ".", "WriteFile", "(", "path", ",", "content", ".", "Bytes", "(", ")", ",", "0644", ")", "\n", "}" ]
// Build function // path is path to host file string required // IP, hostname, and domainname set main record leave empty for no master record // extraContent is an array of extra host records.
[ "Build", "function", "path", "is", "path", "to", "host", "file", "string", "required", "IP", "hostname", "and", "domainname", "set", "main", "record", "leave", "empty", "for", "no", "master", "record", "extraContent", "is", "an", "array", "of", "extra", "host", "records", "." ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/etchosts/etchosts.go#L74-L112
train
docker/libnetwork
etchosts/etchosts.go
Update
func Update(path, IP, hostname string) error { defer pathLock(path)() old, err := ioutil.ReadFile(path) if err != nil { return err } var re = regexp.MustCompile(fmt.Sprintf("(\\S*)(\\t%s)(\\s|\\.)", regexp.QuoteMeta(hostname))) return ioutil.WriteFile(path, re.ReplaceAll(old, []byte(IP+"$2"+"$3")), 0644) }
go
func Update(path, IP, hostname string) error { defer pathLock(path)() old, err := ioutil.ReadFile(path) if err != nil { return err } var re = regexp.MustCompile(fmt.Sprintf("(\\S*)(\\t%s)(\\s|\\.)", regexp.QuoteMeta(hostname))) return ioutil.WriteFile(path, re.ReplaceAll(old, []byte(IP+"$2"+"$3")), 0644) }
[ "func", "Update", "(", "path", ",", "IP", ",", "hostname", "string", ")", "error", "{", "defer", "pathLock", "(", "path", ")", "(", ")", "\n\n", "old", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "var", "re", "=", "regexp", ".", "MustCompile", "(", "fmt", ".", "Sprintf", "(", "\"", "\\\\", "\\\\", "\\\\", "\\\\", "\"", ",", "regexp", ".", "QuoteMeta", "(", "hostname", ")", ")", ")", "\n", "return", "ioutil", ".", "WriteFile", "(", "path", ",", "re", ".", "ReplaceAll", "(", "old", ",", "[", "]", "byte", "(", "IP", "+", "\"", "\"", "+", "\"", "\"", ")", ")", ",", "0644", ")", "\n", "}" ]
// Update all IP addresses where hostname matches. // path is path to host file // IP is new IP address // hostname is hostname to search for to replace IP
[ "Update", "all", "IP", "addresses", "where", "hostname", "matches", ".", "path", "is", "path", "to", "host", "file", "IP", "is", "new", "IP", "address", "hostname", "is", "hostname", "to", "search", "for", "to", "replace", "IP" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/etchosts/etchosts.go#L199-L208
train
docker/libnetwork
drivers/overlay/overlay.go
restoreEndpoints
func (d *driver) restoreEndpoints() error { if d.localStore == nil { logrus.Warn("Cannot restore overlay endpoints because local datastore is missing") return nil } kvol, err := d.localStore.List(datastore.Key(overlayEndpointPrefix), &endpoint{}) if err != nil && err != datastore.ErrKeyNotFound { return fmt.Errorf("failed to read overlay endpoint from store: %v", err) } if err == datastore.ErrKeyNotFound { return nil } for _, kvo := range kvol { ep := kvo.(*endpoint) n := d.network(ep.nid) if n == nil { logrus.Debugf("Network (%.7s) not found for restored endpoint (%.7s)", ep.nid, ep.id) logrus.Debugf("Deleting stale overlay endpoint (%.7s) from store", ep.id) if err := d.deleteEndpointFromStore(ep); err != nil { logrus.Debugf("Failed to delete stale overlay endpoint (%.7s) from store", ep.id) } continue } n.addEndpoint(ep) s := n.getSubnetforIP(ep.addr) if s == nil { return fmt.Errorf("could not find subnet for endpoint %s", ep.id) } if err := n.joinSandbox(s, true, true); err != nil { return fmt.Errorf("restore network sandbox failed: %v", err) } Ifaces := make(map[string][]osl.IfaceOption) vethIfaceOption := make([]osl.IfaceOption, 1) vethIfaceOption = append(vethIfaceOption, n.sbox.InterfaceOptions().Master(s.brName)) Ifaces["veth+veth"] = vethIfaceOption err := n.sbox.Restore(Ifaces, nil, nil, nil) if err != nil { n.leaveSandbox() return fmt.Errorf("failed to restore overlay sandbox: %v", err) } d.peerAdd(ep.nid, ep.id, ep.addr.IP, ep.addr.Mask, ep.mac, net.ParseIP(d.advertiseAddress), false, false, true) } return nil }
go
func (d *driver) restoreEndpoints() error { if d.localStore == nil { logrus.Warn("Cannot restore overlay endpoints because local datastore is missing") return nil } kvol, err := d.localStore.List(datastore.Key(overlayEndpointPrefix), &endpoint{}) if err != nil && err != datastore.ErrKeyNotFound { return fmt.Errorf("failed to read overlay endpoint from store: %v", err) } if err == datastore.ErrKeyNotFound { return nil } for _, kvo := range kvol { ep := kvo.(*endpoint) n := d.network(ep.nid) if n == nil { logrus.Debugf("Network (%.7s) not found for restored endpoint (%.7s)", ep.nid, ep.id) logrus.Debugf("Deleting stale overlay endpoint (%.7s) from store", ep.id) if err := d.deleteEndpointFromStore(ep); err != nil { logrus.Debugf("Failed to delete stale overlay endpoint (%.7s) from store", ep.id) } continue } n.addEndpoint(ep) s := n.getSubnetforIP(ep.addr) if s == nil { return fmt.Errorf("could not find subnet for endpoint %s", ep.id) } if err := n.joinSandbox(s, true, true); err != nil { return fmt.Errorf("restore network sandbox failed: %v", err) } Ifaces := make(map[string][]osl.IfaceOption) vethIfaceOption := make([]osl.IfaceOption, 1) vethIfaceOption = append(vethIfaceOption, n.sbox.InterfaceOptions().Master(s.brName)) Ifaces["veth+veth"] = vethIfaceOption err := n.sbox.Restore(Ifaces, nil, nil, nil) if err != nil { n.leaveSandbox() return fmt.Errorf("failed to restore overlay sandbox: %v", err) } d.peerAdd(ep.nid, ep.id, ep.addr.IP, ep.addr.Mask, ep.mac, net.ParseIP(d.advertiseAddress), false, false, true) } return nil }
[ "func", "(", "d", "*", "driver", ")", "restoreEndpoints", "(", ")", "error", "{", "if", "d", ".", "localStore", "==", "nil", "{", "logrus", ".", "Warn", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\n", "kvol", ",", "err", ":=", "d", ".", "localStore", ".", "List", "(", "datastore", ".", "Key", "(", "overlayEndpointPrefix", ")", ",", "&", "endpoint", "{", "}", ")", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "datastore", ".", "ErrKeyNotFound", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "if", "err", "==", "datastore", ".", "ErrKeyNotFound", "{", "return", "nil", "\n", "}", "\n", "for", "_", ",", "kvo", ":=", "range", "kvol", "{", "ep", ":=", "kvo", ".", "(", "*", "endpoint", ")", "\n", "n", ":=", "d", ".", "network", "(", "ep", ".", "nid", ")", "\n", "if", "n", "==", "nil", "{", "logrus", ".", "Debugf", "(", "\"", "\"", ",", "ep", ".", "nid", ",", "ep", ".", "id", ")", "\n", "logrus", ".", "Debugf", "(", "\"", "\"", ",", "ep", ".", "id", ")", "\n", "if", "err", ":=", "d", ".", "deleteEndpointFromStore", "(", "ep", ")", ";", "err", "!=", "nil", "{", "logrus", ".", "Debugf", "(", "\"", "\"", ",", "ep", ".", "id", ")", "\n", "}", "\n", "continue", "\n", "}", "\n", "n", ".", "addEndpoint", "(", "ep", ")", "\n\n", "s", ":=", "n", ".", "getSubnetforIP", "(", "ep", ".", "addr", ")", "\n", "if", "s", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ep", ".", "id", ")", "\n", "}", "\n\n", "if", "err", ":=", "n", ".", "joinSandbox", "(", "s", ",", "true", ",", "true", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "Ifaces", ":=", "make", "(", "map", "[", "string", "]", "[", "]", "osl", ".", "IfaceOption", ")", "\n", "vethIfaceOption", ":=", "make", "(", "[", "]", "osl", ".", "IfaceOption", ",", "1", ")", "\n", "vethIfaceOption", "=", "append", "(", "vethIfaceOption", ",", "n", ".", "sbox", ".", "InterfaceOptions", "(", ")", ".", "Master", "(", "s", ".", "brName", ")", ")", "\n", "Ifaces", "[", "\"", "\"", "]", "=", "vethIfaceOption", "\n\n", "err", ":=", "n", ".", "sbox", ".", "Restore", "(", "Ifaces", ",", "nil", ",", "nil", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "n", ".", "leaveSandbox", "(", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "d", ".", "peerAdd", "(", "ep", ".", "nid", ",", "ep", ".", "id", ",", "ep", ".", "addr", ".", "IP", ",", "ep", ".", "addr", ".", "Mask", ",", "ep", ".", "mac", ",", "net", ".", "ParseIP", "(", "d", ".", "advertiseAddress", ")", ",", "false", ",", "false", ",", "true", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Endpoints are stored in the local store. Restore them and reconstruct the overlay sandbox
[ "Endpoints", "are", "stored", "in", "the", "local", "store", ".", "Restore", "them", "and", "reconstruct", "the", "overlay", "sandbox" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/overlay/overlay.go#L111-L160
train
docker/libnetwork
drivers/overlay/overlay.go
Fini
func Fini(drv driverapi.Driver) { d := drv.(*driver) // Notify the peer go routine to return if d.peerOpCancel != nil { d.peerOpCancel() } if d.exitCh != nil { waitCh := make(chan struct{}) d.exitCh <- waitCh <-waitCh } }
go
func Fini(drv driverapi.Driver) { d := drv.(*driver) // Notify the peer go routine to return if d.peerOpCancel != nil { d.peerOpCancel() } if d.exitCh != nil { waitCh := make(chan struct{}) d.exitCh <- waitCh <-waitCh } }
[ "func", "Fini", "(", "drv", "driverapi", ".", "Driver", ")", "{", "d", ":=", "drv", ".", "(", "*", "driver", ")", "\n\n", "// Notify the peer go routine to return", "if", "d", ".", "peerOpCancel", "!=", "nil", "{", "d", ".", "peerOpCancel", "(", ")", "\n", "}", "\n\n", "if", "d", ".", "exitCh", "!=", "nil", "{", "waitCh", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n\n", "d", ".", "exitCh", "<-", "waitCh", "\n\n", "<-", "waitCh", "\n", "}", "\n", "}" ]
// Fini cleans up the driver resources
[ "Fini", "cleans", "up", "the", "driver", "resources" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/overlay/overlay.go#L163-L178
train
docker/libnetwork
drivers/host/host.go
Init
func Init(dc driverapi.DriverCallback, config map[string]interface{}) error { c := driverapi.Capability{ DataScope: datastore.LocalScope, ConnectivityScope: datastore.LocalScope, } return dc.RegisterDriver(networkType, &driver{}, c) }
go
func Init(dc driverapi.DriverCallback, config map[string]interface{}) error { c := driverapi.Capability{ DataScope: datastore.LocalScope, ConnectivityScope: datastore.LocalScope, } return dc.RegisterDriver(networkType, &driver{}, c) }
[ "func", "Init", "(", "dc", "driverapi", ".", "DriverCallback", ",", "config", "map", "[", "string", "]", "interface", "{", "}", ")", "error", "{", "c", ":=", "driverapi", ".", "Capability", "{", "DataScope", ":", "datastore", ".", "LocalScope", ",", "ConnectivityScope", ":", "datastore", ".", "LocalScope", ",", "}", "\n", "return", "dc", ".", "RegisterDriver", "(", "networkType", ",", "&", "driver", "{", "}", ",", "c", ")", "\n", "}" ]
// Init registers a new instance of host driver
[ "Init", "registers", "a", "new", "instance", "of", "host", "driver" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/host/host.go#L20-L26
train
docker/libnetwork
drivers/bridge/interface.go
newInterface
func newInterface(nlh *netlink.Handle, config *networkConfiguration) (*bridgeInterface, error) { var err error i := &bridgeInterface{nlh: nlh} // Initialize the bridge name to the default if unspecified. if config.BridgeName == "" { config.BridgeName = DefaultBridgeName } // Attempt to find an existing bridge named with the specified name. i.Link, err = nlh.LinkByName(config.BridgeName) if err != nil { logrus.Debugf("Did not find any interface with name %s: %v", config.BridgeName, err) } else if _, ok := i.Link.(*netlink.Bridge); !ok { return nil, fmt.Errorf("existing interface %s is not a bridge", i.Link.Attrs().Name) } return i, nil }
go
func newInterface(nlh *netlink.Handle, config *networkConfiguration) (*bridgeInterface, error) { var err error i := &bridgeInterface{nlh: nlh} // Initialize the bridge name to the default if unspecified. if config.BridgeName == "" { config.BridgeName = DefaultBridgeName } // Attempt to find an existing bridge named with the specified name. i.Link, err = nlh.LinkByName(config.BridgeName) if err != nil { logrus.Debugf("Did not find any interface with name %s: %v", config.BridgeName, err) } else if _, ok := i.Link.(*netlink.Bridge); !ok { return nil, fmt.Errorf("existing interface %s is not a bridge", i.Link.Attrs().Name) } return i, nil }
[ "func", "newInterface", "(", "nlh", "*", "netlink", ".", "Handle", ",", "config", "*", "networkConfiguration", ")", "(", "*", "bridgeInterface", ",", "error", ")", "{", "var", "err", "error", "\n", "i", ":=", "&", "bridgeInterface", "{", "nlh", ":", "nlh", "}", "\n\n", "// Initialize the bridge name to the default if unspecified.", "if", "config", ".", "BridgeName", "==", "\"", "\"", "{", "config", ".", "BridgeName", "=", "DefaultBridgeName", "\n", "}", "\n\n", "// Attempt to find an existing bridge named with the specified name.", "i", ".", "Link", ",", "err", "=", "nlh", ".", "LinkByName", "(", "config", ".", "BridgeName", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "Debugf", "(", "\"", "\"", ",", "config", ".", "BridgeName", ",", "err", ")", "\n", "}", "else", "if", "_", ",", "ok", ":=", "i", ".", "Link", ".", "(", "*", "netlink", ".", "Bridge", ")", ";", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "i", ".", "Link", ".", "Attrs", "(", ")", ".", "Name", ")", "\n", "}", "\n", "return", "i", ",", "nil", "\n", "}" ]
// newInterface creates a new bridge interface structure. It attempts to find // an already existing device identified by the configuration BridgeName field, // or the default bridge name when unspecified, but doesn't attempt to create // one when missing
[ "newInterface", "creates", "a", "new", "bridge", "interface", "structure", ".", "It", "attempts", "to", "find", "an", "already", "existing", "device", "identified", "by", "the", "configuration", "BridgeName", "field", "or", "the", "default", "bridge", "name", "when", "unspecified", "but", "doesn", "t", "attempt", "to", "create", "one", "when", "missing" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/bridge/interface.go#L31-L48
train
docker/libnetwork
drivers/bridge/interface.go
addresses
func (i *bridgeInterface) addresses() ([]netlink.Addr, []netlink.Addr, error) { v4addr, err := i.nlh.AddrList(i.Link, netlink.FAMILY_V4) if err != nil { return nil, nil, fmt.Errorf("Failed to retrieve V4 addresses: %v", err) } v6addr, err := i.nlh.AddrList(i.Link, netlink.FAMILY_V6) if err != nil { return nil, nil, fmt.Errorf("Failed to retrieve V6 addresses: %v", err) } if len(v4addr) == 0 { return nil, v6addr, nil } return v4addr, v6addr, nil }
go
func (i *bridgeInterface) addresses() ([]netlink.Addr, []netlink.Addr, error) { v4addr, err := i.nlh.AddrList(i.Link, netlink.FAMILY_V4) if err != nil { return nil, nil, fmt.Errorf("Failed to retrieve V4 addresses: %v", err) } v6addr, err := i.nlh.AddrList(i.Link, netlink.FAMILY_V6) if err != nil { return nil, nil, fmt.Errorf("Failed to retrieve V6 addresses: %v", err) } if len(v4addr) == 0 { return nil, v6addr, nil } return v4addr, v6addr, nil }
[ "func", "(", "i", "*", "bridgeInterface", ")", "addresses", "(", ")", "(", "[", "]", "netlink", ".", "Addr", ",", "[", "]", "netlink", ".", "Addr", ",", "error", ")", "{", "v4addr", ",", "err", ":=", "i", ".", "nlh", ".", "AddrList", "(", "i", ".", "Link", ",", "netlink", ".", "FAMILY_V4", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "v6addr", ",", "err", ":=", "i", ".", "nlh", ".", "AddrList", "(", "i", ".", "Link", ",", "netlink", ".", "FAMILY_V6", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "if", "len", "(", "v4addr", ")", "==", "0", "{", "return", "nil", ",", "v6addr", ",", "nil", "\n", "}", "\n", "return", "v4addr", ",", "v6addr", ",", "nil", "\n", "}" ]
// addresses returns all IPv4 addresses and all IPv6 addresses for the bridge interface.
[ "addresses", "returns", "all", "IPv4", "addresses", "and", "all", "IPv6", "addresses", "for", "the", "bridge", "interface", "." ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/bridge/interface.go#L56-L71
train
docker/libnetwork
diagnostic/server.go
Init
func (s *Server) Init() { s.mux = http.NewServeMux() // Register local handlers s.RegisterHandler(s, diagPaths2Func) }
go
func (s *Server) Init() { s.mux = http.NewServeMux() // Register local handlers s.RegisterHandler(s, diagPaths2Func) }
[ "func", "(", "s", "*", "Server", ")", "Init", "(", ")", "{", "s", ".", "mux", "=", "http", ".", "NewServeMux", "(", ")", "\n\n", "// Register local handlers", "s", ".", "RegisterHandler", "(", "s", ",", "diagPaths2Func", ")", "\n", "}" ]
// Init initialize the mux for the http handling and register the base hooks
[ "Init", "initialize", "the", "mux", "for", "the", "http", "handling", "and", "register", "the", "base", "hooks" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/diagnostic/server.go#L55-L60
train
docker/libnetwork
diagnostic/server.go
RegisterHandler
func (s *Server) RegisterHandler(ctx interface{}, hdlrs map[string]HTTPHandlerFunc) { s.Lock() defer s.Unlock() for path, fun := range hdlrs { if _, ok := s.registeredHanders[path]; ok { continue } s.mux.Handle(path, httpHandlerCustom{ctx, fun}) s.registeredHanders[path] = true } }
go
func (s *Server) RegisterHandler(ctx interface{}, hdlrs map[string]HTTPHandlerFunc) { s.Lock() defer s.Unlock() for path, fun := range hdlrs { if _, ok := s.registeredHanders[path]; ok { continue } s.mux.Handle(path, httpHandlerCustom{ctx, fun}) s.registeredHanders[path] = true } }
[ "func", "(", "s", "*", "Server", ")", "RegisterHandler", "(", "ctx", "interface", "{", "}", ",", "hdlrs", "map", "[", "string", "]", "HTTPHandlerFunc", ")", "{", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n", "for", "path", ",", "fun", ":=", "range", "hdlrs", "{", "if", "_", ",", "ok", ":=", "s", ".", "registeredHanders", "[", "path", "]", ";", "ok", "{", "continue", "\n", "}", "\n", "s", ".", "mux", ".", "Handle", "(", "path", ",", "httpHandlerCustom", "{", "ctx", ",", "fun", "}", ")", "\n", "s", ".", "registeredHanders", "[", "path", "]", "=", "true", "\n", "}", "\n", "}" ]
// RegisterHandler allows to register new handlers to the mux and to a specific path
[ "RegisterHandler", "allows", "to", "register", "new", "handlers", "to", "the", "mux", "and", "to", "a", "specific", "path" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/diagnostic/server.go#L63-L73
train
docker/libnetwork
diagnostic/server.go
EnableDiagnostic
func (s *Server) EnableDiagnostic(ip string, port int) { s.Lock() defer s.Unlock() s.port = port if s.enable == 1 { logrus.Info("The server is already up and running") return } logrus.Infof("Starting the diagnostic server listening on %d for commands", port) srv := &http.Server{Addr: fmt.Sprintf("%s:%d", ip, port), Handler: s} s.srv = srv s.enable = 1 go func(n *Server) { // Ignore ErrServerClosed that is returned on the Shutdown call if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed { logrus.Errorf("ListenAndServe error: %s", err) atomic.SwapInt32(&n.enable, 0) } }(s) }
go
func (s *Server) EnableDiagnostic(ip string, port int) { s.Lock() defer s.Unlock() s.port = port if s.enable == 1 { logrus.Info("The server is already up and running") return } logrus.Infof("Starting the diagnostic server listening on %d for commands", port) srv := &http.Server{Addr: fmt.Sprintf("%s:%d", ip, port), Handler: s} s.srv = srv s.enable = 1 go func(n *Server) { // Ignore ErrServerClosed that is returned on the Shutdown call if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed { logrus.Errorf("ListenAndServe error: %s", err) atomic.SwapInt32(&n.enable, 0) } }(s) }
[ "func", "(", "s", "*", "Server", ")", "EnableDiagnostic", "(", "ip", "string", ",", "port", "int", ")", "{", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n\n", "s", ".", "port", "=", "port", "\n\n", "if", "s", ".", "enable", "==", "1", "{", "logrus", ".", "Info", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "logrus", ".", "Infof", "(", "\"", "\"", ",", "port", ")", "\n", "srv", ":=", "&", "http", ".", "Server", "{", "Addr", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "ip", ",", "port", ")", ",", "Handler", ":", "s", "}", "\n", "s", ".", "srv", "=", "srv", "\n", "s", ".", "enable", "=", "1", "\n", "go", "func", "(", "n", "*", "Server", ")", "{", "// Ignore ErrServerClosed that is returned on the Shutdown call", "if", "err", ":=", "srv", ".", "ListenAndServe", "(", ")", ";", "err", "!=", "nil", "&&", "err", "!=", "http", ".", "ErrServerClosed", "{", "logrus", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "atomic", ".", "SwapInt32", "(", "&", "n", ".", "enable", ",", "0", ")", "\n", "}", "\n", "}", "(", "s", ")", "\n", "}" ]
// EnableDiagnostic opens a TCP socket to debug the passed network DB
[ "EnableDiagnostic", "opens", "a", "TCP", "socket", "to", "debug", "the", "passed", "network", "DB" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/diagnostic/server.go#L82-L104
train
docker/libnetwork
diagnostic/server.go
DisableDiagnostic
func (s *Server) DisableDiagnostic() { s.Lock() defer s.Unlock() s.srv.Shutdown(context.Background()) s.srv = nil s.enable = 0 logrus.Info("Disabling the diagnostic server") }
go
func (s *Server) DisableDiagnostic() { s.Lock() defer s.Unlock() s.srv.Shutdown(context.Background()) s.srv = nil s.enable = 0 logrus.Info("Disabling the diagnostic server") }
[ "func", "(", "s", "*", "Server", ")", "DisableDiagnostic", "(", ")", "{", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n\n", "s", ".", "srv", ".", "Shutdown", "(", "context", ".", "Background", "(", ")", ")", "\n", "s", ".", "srv", "=", "nil", "\n", "s", ".", "enable", "=", "0", "\n", "logrus", ".", "Info", "(", "\"", "\"", ")", "\n", "}" ]
// DisableDiagnostic stop the dubug and closes the tcp socket
[ "DisableDiagnostic", "stop", "the", "dubug", "and", "closes", "the", "tcp", "socket" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/diagnostic/server.go#L107-L115
train
docker/libnetwork
diagnostic/server.go
IsDiagnosticEnabled
func (s *Server) IsDiagnosticEnabled() bool { s.Lock() defer s.Unlock() return s.enable == 1 }
go
func (s *Server) IsDiagnosticEnabled() bool { s.Lock() defer s.Unlock() return s.enable == 1 }
[ "func", "(", "s", "*", "Server", ")", "IsDiagnosticEnabled", "(", ")", "bool", "{", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n", "return", "s", ".", "enable", "==", "1", "\n", "}" ]
// IsDiagnosticEnabled returns true when the debug is enabled
[ "IsDiagnosticEnabled", "returns", "true", "when", "the", "debug", "is", "enabled" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/diagnostic/server.go#L118-L122
train
docker/libnetwork
diagnostic/server.go
DebugHTTPForm
func DebugHTTPForm(r *http.Request) { for k, v := range r.Form { logrus.Debugf("Form[%q] = %q\n", k, v) } }
go
func DebugHTTPForm(r *http.Request) { for k, v := range r.Form { logrus.Debugf("Form[%q] = %q\n", k, v) } }
[ "func", "DebugHTTPForm", "(", "r", "*", "http", ".", "Request", ")", "{", "for", "k", ",", "v", ":=", "range", "r", ".", "Form", "{", "logrus", ".", "Debugf", "(", "\"", "\\n", "\"", ",", "k", ",", "v", ")", "\n", "}", "\n", "}" ]
// DebugHTTPForm helper to print the form url parameters
[ "DebugHTTPForm", "helper", "to", "print", "the", "form", "url", "parameters" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/diagnostic/server.go#L183-L187
train
docker/libnetwork
diagnostic/server.go
ParseHTTPFormOptions
func ParseHTTPFormOptions(r *http.Request) (bool, *JSONOutput) { _, unsafe := r.Form["unsafe"] v, json := r.Form["json"] var pretty bool if len(v) > 0 { pretty = v[0] == "pretty" } return unsafe, &JSONOutput{enable: json, prettyPrint: pretty} }
go
func ParseHTTPFormOptions(r *http.Request) (bool, *JSONOutput) { _, unsafe := r.Form["unsafe"] v, json := r.Form["json"] var pretty bool if len(v) > 0 { pretty = v[0] == "pretty" } return unsafe, &JSONOutput{enable: json, prettyPrint: pretty} }
[ "func", "ParseHTTPFormOptions", "(", "r", "*", "http", ".", "Request", ")", "(", "bool", ",", "*", "JSONOutput", ")", "{", "_", ",", "unsafe", ":=", "r", ".", "Form", "[", "\"", "\"", "]", "\n", "v", ",", "json", ":=", "r", ".", "Form", "[", "\"", "\"", "]", "\n", "var", "pretty", "bool", "\n", "if", "len", "(", "v", ")", ">", "0", "{", "pretty", "=", "v", "[", "0", "]", "==", "\"", "\"", "\n", "}", "\n", "return", "unsafe", ",", "&", "JSONOutput", "{", "enable", ":", "json", ",", "prettyPrint", ":", "pretty", "}", "\n", "}" ]
// ParseHTTPFormOptions easily parse the JSON printing options
[ "ParseHTTPFormOptions", "easily", "parse", "the", "JSON", "printing", "options" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/diagnostic/server.go#L196-L204
train
docker/libnetwork
diagnostic/server.go
HTTPReply
func HTTPReply(w http.ResponseWriter, r *HTTPResult, j *JSONOutput) (int, error) { var response []byte if j.enable { w.Header().Set("Content-Type", "application/json") var err error if j.prettyPrint { response, err = json.MarshalIndent(r, "", " ") if err != nil { response, _ = json.MarshalIndent(FailCommand(err), "", " ") } } else { response, err = json.Marshal(r) if err != nil { response, _ = json.Marshal(FailCommand(err)) } } } else { response = []byte(r.String()) } return fmt.Fprint(w, string(response)) }
go
func HTTPReply(w http.ResponseWriter, r *HTTPResult, j *JSONOutput) (int, error) { var response []byte if j.enable { w.Header().Set("Content-Type", "application/json") var err error if j.prettyPrint { response, err = json.MarshalIndent(r, "", " ") if err != nil { response, _ = json.MarshalIndent(FailCommand(err), "", " ") } } else { response, err = json.Marshal(r) if err != nil { response, _ = json.Marshal(FailCommand(err)) } } } else { response = []byte(r.String()) } return fmt.Fprint(w, string(response)) }
[ "func", "HTTPReply", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "HTTPResult", ",", "j", "*", "JSONOutput", ")", "(", "int", ",", "error", ")", "{", "var", "response", "[", "]", "byte", "\n", "if", "j", ".", "enable", "{", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "var", "err", "error", "\n", "if", "j", ".", "prettyPrint", "{", "response", ",", "err", "=", "json", ".", "MarshalIndent", "(", "r", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "response", ",", "_", "=", "json", ".", "MarshalIndent", "(", "FailCommand", "(", "err", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "else", "{", "response", ",", "err", "=", "json", ".", "Marshal", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "response", ",", "_", "=", "json", ".", "Marshal", "(", "FailCommand", "(", "err", ")", ")", "\n", "}", "\n", "}", "\n", "}", "else", "{", "response", "=", "[", "]", "byte", "(", "r", ".", "String", "(", ")", ")", "\n", "}", "\n", "return", "fmt", ".", "Fprint", "(", "w", ",", "string", "(", "response", ")", ")", "\n", "}" ]
// HTTPReply helper function that takes care of sending the message out
[ "HTTPReply", "helper", "function", "that", "takes", "care", "of", "sending", "the", "message", "out" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/diagnostic/server.go#L207-L227
train
docker/libnetwork
ipams/remote/remote.go
GetDefaultAddressSpaces
func (a *allocator) GetDefaultAddressSpaces() (string, string, error) { res := &api.GetAddressSpacesResponse{} if err := a.call("GetDefaultAddressSpaces", nil, res); err != nil { return "", "", err } return res.LocalDefaultAddressSpace, res.GlobalDefaultAddressSpace, nil }
go
func (a *allocator) GetDefaultAddressSpaces() (string, string, error) { res := &api.GetAddressSpacesResponse{} if err := a.call("GetDefaultAddressSpaces", nil, res); err != nil { return "", "", err } return res.LocalDefaultAddressSpace, res.GlobalDefaultAddressSpace, nil }
[ "func", "(", "a", "*", "allocator", ")", "GetDefaultAddressSpaces", "(", ")", "(", "string", ",", "string", ",", "error", ")", "{", "res", ":=", "&", "api", ".", "GetAddressSpacesResponse", "{", "}", "\n", "if", "err", ":=", "a", ".", "call", "(", "\"", "\"", ",", "nil", ",", "res", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "res", ".", "LocalDefaultAddressSpace", ",", "res", ".", "GlobalDefaultAddressSpace", ",", "nil", "\n", "}" ]
// GetDefaultAddressSpaces returns the local and global default address spaces
[ "GetDefaultAddressSpaces", "returns", "the", "local", "and", "global", "default", "address", "spaces" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipams/remote/remote.go#L111-L117
train
docker/libnetwork
ipams/remote/remote.go
RequestPool
func (a *allocator) RequestPool(addressSpace, pool, subPool string, options map[string]string, v6 bool) (string, *net.IPNet, map[string]string, error) { req := &api.RequestPoolRequest{AddressSpace: addressSpace, Pool: pool, SubPool: subPool, Options: options, V6: v6} res := &api.RequestPoolResponse{} if err := a.call("RequestPool", req, res); err != nil { return "", nil, nil, err } retPool, err := types.ParseCIDR(res.Pool) return res.PoolID, retPool, res.Data, err }
go
func (a *allocator) RequestPool(addressSpace, pool, subPool string, options map[string]string, v6 bool) (string, *net.IPNet, map[string]string, error) { req := &api.RequestPoolRequest{AddressSpace: addressSpace, Pool: pool, SubPool: subPool, Options: options, V6: v6} res := &api.RequestPoolResponse{} if err := a.call("RequestPool", req, res); err != nil { return "", nil, nil, err } retPool, err := types.ParseCIDR(res.Pool) return res.PoolID, retPool, res.Data, err }
[ "func", "(", "a", "*", "allocator", ")", "RequestPool", "(", "addressSpace", ",", "pool", ",", "subPool", "string", ",", "options", "map", "[", "string", "]", "string", ",", "v6", "bool", ")", "(", "string", ",", "*", "net", ".", "IPNet", ",", "map", "[", "string", "]", "string", ",", "error", ")", "{", "req", ":=", "&", "api", ".", "RequestPoolRequest", "{", "AddressSpace", ":", "addressSpace", ",", "Pool", ":", "pool", ",", "SubPool", ":", "subPool", ",", "Options", ":", "options", ",", "V6", ":", "v6", "}", "\n", "res", ":=", "&", "api", ".", "RequestPoolResponse", "{", "}", "\n", "if", "err", ":=", "a", ".", "call", "(", "\"", "\"", ",", "req", ",", "res", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "retPool", ",", "err", ":=", "types", ".", "ParseCIDR", "(", "res", ".", "Pool", ")", "\n", "return", "res", ".", "PoolID", ",", "retPool", ",", "res", ".", "Data", ",", "err", "\n", "}" ]
// RequestPool requests an address pool in the specified address space
[ "RequestPool", "requests", "an", "address", "pool", "in", "the", "specified", "address", "space" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipams/remote/remote.go#L120-L128
train
docker/libnetwork
ipams/remote/remote.go
ReleasePool
func (a *allocator) ReleasePool(poolID string) error { req := &api.ReleasePoolRequest{PoolID: poolID} res := &api.ReleasePoolResponse{} return a.call("ReleasePool", req, res) }
go
func (a *allocator) ReleasePool(poolID string) error { req := &api.ReleasePoolRequest{PoolID: poolID} res := &api.ReleasePoolResponse{} return a.call("ReleasePool", req, res) }
[ "func", "(", "a", "*", "allocator", ")", "ReleasePool", "(", "poolID", "string", ")", "error", "{", "req", ":=", "&", "api", ".", "ReleasePoolRequest", "{", "PoolID", ":", "poolID", "}", "\n", "res", ":=", "&", "api", ".", "ReleasePoolResponse", "{", "}", "\n", "return", "a", ".", "call", "(", "\"", "\"", ",", "req", ",", "res", ")", "\n", "}" ]
// ReleasePool removes an address pool from the specified address space
[ "ReleasePool", "removes", "an", "address", "pool", "from", "the", "specified", "address", "space" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipams/remote/remote.go#L131-L135
train
docker/libnetwork
ipams/remote/remote.go
RequestAddress
func (a *allocator) RequestAddress(poolID string, address net.IP, options map[string]string) (*net.IPNet, map[string]string, error) { var ( prefAddress string retAddress *net.IPNet err error ) if address != nil { prefAddress = address.String() } req := &api.RequestAddressRequest{PoolID: poolID, Address: prefAddress, Options: options} res := &api.RequestAddressResponse{} if err := a.call("RequestAddress", req, res); err != nil { return nil, nil, err } if res.Address != "" { retAddress, err = types.ParseCIDR(res.Address) } else { return nil, nil, ipamapi.ErrNoIPReturned } return retAddress, res.Data, err }
go
func (a *allocator) RequestAddress(poolID string, address net.IP, options map[string]string) (*net.IPNet, map[string]string, error) { var ( prefAddress string retAddress *net.IPNet err error ) if address != nil { prefAddress = address.String() } req := &api.RequestAddressRequest{PoolID: poolID, Address: prefAddress, Options: options} res := &api.RequestAddressResponse{} if err := a.call("RequestAddress", req, res); err != nil { return nil, nil, err } if res.Address != "" { retAddress, err = types.ParseCIDR(res.Address) } else { return nil, nil, ipamapi.ErrNoIPReturned } return retAddress, res.Data, err }
[ "func", "(", "a", "*", "allocator", ")", "RequestAddress", "(", "poolID", "string", ",", "address", "net", ".", "IP", ",", "options", "map", "[", "string", "]", "string", ")", "(", "*", "net", ".", "IPNet", ",", "map", "[", "string", "]", "string", ",", "error", ")", "{", "var", "(", "prefAddress", "string", "\n", "retAddress", "*", "net", ".", "IPNet", "\n", "err", "error", "\n", ")", "\n", "if", "address", "!=", "nil", "{", "prefAddress", "=", "address", ".", "String", "(", ")", "\n", "}", "\n", "req", ":=", "&", "api", ".", "RequestAddressRequest", "{", "PoolID", ":", "poolID", ",", "Address", ":", "prefAddress", ",", "Options", ":", "options", "}", "\n", "res", ":=", "&", "api", ".", "RequestAddressResponse", "{", "}", "\n", "if", "err", ":=", "a", ".", "call", "(", "\"", "\"", ",", "req", ",", "res", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "if", "res", ".", "Address", "!=", "\"", "\"", "{", "retAddress", ",", "err", "=", "types", ".", "ParseCIDR", "(", "res", ".", "Address", ")", "\n", "}", "else", "{", "return", "nil", ",", "nil", ",", "ipamapi", ".", "ErrNoIPReturned", "\n", "}", "\n", "return", "retAddress", ",", "res", ".", "Data", ",", "err", "\n", "}" ]
// RequestAddress requests an address from the address pool
[ "RequestAddress", "requests", "an", "address", "from", "the", "address", "pool" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipams/remote/remote.go#L138-L158
train
docker/libnetwork
ipams/remote/remote.go
ReleaseAddress
func (a *allocator) ReleaseAddress(poolID string, address net.IP) error { var relAddress string if address != nil { relAddress = address.String() } req := &api.ReleaseAddressRequest{PoolID: poolID, Address: relAddress} res := &api.ReleaseAddressResponse{} return a.call("ReleaseAddress", req, res) }
go
func (a *allocator) ReleaseAddress(poolID string, address net.IP) error { var relAddress string if address != nil { relAddress = address.String() } req := &api.ReleaseAddressRequest{PoolID: poolID, Address: relAddress} res := &api.ReleaseAddressResponse{} return a.call("ReleaseAddress", req, res) }
[ "func", "(", "a", "*", "allocator", ")", "ReleaseAddress", "(", "poolID", "string", ",", "address", "net", ".", "IP", ")", "error", "{", "var", "relAddress", "string", "\n", "if", "address", "!=", "nil", "{", "relAddress", "=", "address", ".", "String", "(", ")", "\n", "}", "\n", "req", ":=", "&", "api", ".", "ReleaseAddressRequest", "{", "PoolID", ":", "poolID", ",", "Address", ":", "relAddress", "}", "\n", "res", ":=", "&", "api", ".", "ReleaseAddressResponse", "{", "}", "\n", "return", "a", ".", "call", "(", "\"", "\"", ",", "req", ",", "res", ")", "\n", "}" ]
// ReleaseAddress releases the address from the specified address pool
[ "ReleaseAddress", "releases", "the", "address", "from", "the", "specified", "address", "pool" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipams/remote/remote.go#L161-L169
train
docker/libnetwork
diagnostic/types.go
FailCommand
func FailCommand(err error) *HTTPResult { return &HTTPResult{ Message: "FAIL", Details: &ErrorCmd{Error: err.Error()}, } }
go
func FailCommand(err error) *HTTPResult { return &HTTPResult{ Message: "FAIL", Details: &ErrorCmd{Error: err.Error()}, } }
[ "func", "FailCommand", "(", "err", "error", ")", "*", "HTTPResult", "{", "return", "&", "HTTPResult", "{", "Message", ":", "\"", "\"", ",", "Details", ":", "&", "ErrorCmd", "{", "Error", ":", "err", ".", "Error", "(", ")", "}", ",", "}", "\n", "}" ]
// FailCommand creates a failure message with error
[ "FailCommand", "creates", "a", "failure", "message", "with", "error" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/diagnostic/types.go#L19-L24
train
docker/libnetwork
diagnostic/types.go
WrongCommand
func WrongCommand(message, usage string) *HTTPResult { return &HTTPResult{ Message: message, Details: &UsageCmd{Usage: usage}, } }
go
func WrongCommand(message, usage string) *HTTPResult { return &HTTPResult{ Message: message, Details: &UsageCmd{Usage: usage}, } }
[ "func", "WrongCommand", "(", "message", ",", "usage", "string", ")", "*", "HTTPResult", "{", "return", "&", "HTTPResult", "{", "Message", ":", "message", ",", "Details", ":", "&", "UsageCmd", "{", "Usage", ":", "usage", "}", ",", "}", "\n", "}" ]
// WrongCommand creates a wrong command response
[ "WrongCommand", "creates", "a", "wrong", "command", "response" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/diagnostic/types.go#L27-L32
train
docker/libnetwork
drivers/bridge/bridge.go
Init
func Init(dc driverapi.DriverCallback, config map[string]interface{}) error { d := newDriver() if err := d.configure(config); err != nil { return err } c := driverapi.Capability{ DataScope: datastore.LocalScope, ConnectivityScope: datastore.LocalScope, } return dc.RegisterDriver(networkType, d, c) }
go
func Init(dc driverapi.DriverCallback, config map[string]interface{}) error { d := newDriver() if err := d.configure(config); err != nil { return err } c := driverapi.Capability{ DataScope: datastore.LocalScope, ConnectivityScope: datastore.LocalScope, } return dc.RegisterDriver(networkType, d, c) }
[ "func", "Init", "(", "dc", "driverapi", ".", "DriverCallback", ",", "config", "map", "[", "string", "]", "interface", "{", "}", ")", "error", "{", "d", ":=", "newDriver", "(", ")", "\n", "if", "err", ":=", "d", ".", "configure", "(", "config", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "c", ":=", "driverapi", ".", "Capability", "{", "DataScope", ":", "datastore", ".", "LocalScope", ",", "ConnectivityScope", ":", "datastore", ".", "LocalScope", ",", "}", "\n", "return", "dc", ".", "RegisterDriver", "(", "networkType", ",", "d", ",", "c", ")", "\n", "}" ]
// Init registers a new instance of bridge driver
[ "Init", "registers", "a", "new", "instance", "of", "bridge", "driver" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/bridge/bridge.go#L159-L170
train
docker/libnetwork
drivers/bridge/bridge.go
Validate
func (c *networkConfiguration) Validate() error { if c.Mtu < 0 { return ErrInvalidMtu(c.Mtu) } // If bridge v4 subnet is specified if c.AddressIPv4 != nil { // If default gw is specified, it must be part of bridge subnet if c.DefaultGatewayIPv4 != nil { if !c.AddressIPv4.Contains(c.DefaultGatewayIPv4) { return &ErrInvalidGateway{} } } } // If default v6 gw is specified, AddressIPv6 must be specified and gw must belong to AddressIPv6 subnet if c.EnableIPv6 && c.DefaultGatewayIPv6 != nil { if c.AddressIPv6 == nil || !c.AddressIPv6.Contains(c.DefaultGatewayIPv6) { return &ErrInvalidGateway{} } } return nil }
go
func (c *networkConfiguration) Validate() error { if c.Mtu < 0 { return ErrInvalidMtu(c.Mtu) } // If bridge v4 subnet is specified if c.AddressIPv4 != nil { // If default gw is specified, it must be part of bridge subnet if c.DefaultGatewayIPv4 != nil { if !c.AddressIPv4.Contains(c.DefaultGatewayIPv4) { return &ErrInvalidGateway{} } } } // If default v6 gw is specified, AddressIPv6 must be specified and gw must belong to AddressIPv6 subnet if c.EnableIPv6 && c.DefaultGatewayIPv6 != nil { if c.AddressIPv6 == nil || !c.AddressIPv6.Contains(c.DefaultGatewayIPv6) { return &ErrInvalidGateway{} } } return nil }
[ "func", "(", "c", "*", "networkConfiguration", ")", "Validate", "(", ")", "error", "{", "if", "c", ".", "Mtu", "<", "0", "{", "return", "ErrInvalidMtu", "(", "c", ".", "Mtu", ")", "\n", "}", "\n\n", "// If bridge v4 subnet is specified", "if", "c", ".", "AddressIPv4", "!=", "nil", "{", "// If default gw is specified, it must be part of bridge subnet", "if", "c", ".", "DefaultGatewayIPv4", "!=", "nil", "{", "if", "!", "c", ".", "AddressIPv4", ".", "Contains", "(", "c", ".", "DefaultGatewayIPv4", ")", "{", "return", "&", "ErrInvalidGateway", "{", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// If default v6 gw is specified, AddressIPv6 must be specified and gw must belong to AddressIPv6 subnet", "if", "c", ".", "EnableIPv6", "&&", "c", ".", "DefaultGatewayIPv6", "!=", "nil", "{", "if", "c", ".", "AddressIPv6", "==", "nil", "||", "!", "c", ".", "AddressIPv6", ".", "Contains", "(", "c", ".", "DefaultGatewayIPv6", ")", "{", "return", "&", "ErrInvalidGateway", "{", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Validate performs a static validation on the network configuration parameters. // Whatever can be assessed a priori before attempting any programming.
[ "Validate", "performs", "a", "static", "validation", "on", "the", "network", "configuration", "parameters", ".", "Whatever", "can", "be", "assessed", "a", "priori", "before", "attempting", "any", "programming", "." ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/bridge/bridge.go#L174-L196
train
docker/libnetwork
drivers/bridge/bridge.go
Conflicts
func (c *networkConfiguration) Conflicts(o *networkConfiguration) error { if o == nil { return errors.New("same configuration") } // Also empty, because only one network with empty name is allowed if c.BridgeName == o.BridgeName { return errors.New("networks have same bridge name") } // They must be in different subnets if (c.AddressIPv4 != nil && o.AddressIPv4 != nil) && (c.AddressIPv4.Contains(o.AddressIPv4.IP) || o.AddressIPv4.Contains(c.AddressIPv4.IP)) { return errors.New("networks have overlapping IPv4") } // They must be in different v6 subnets if (c.AddressIPv6 != nil && o.AddressIPv6 != nil) && (c.AddressIPv6.Contains(o.AddressIPv6.IP) || o.AddressIPv6.Contains(c.AddressIPv6.IP)) { return errors.New("networks have overlapping IPv6") } return nil }
go
func (c *networkConfiguration) Conflicts(o *networkConfiguration) error { if o == nil { return errors.New("same configuration") } // Also empty, because only one network with empty name is allowed if c.BridgeName == o.BridgeName { return errors.New("networks have same bridge name") } // They must be in different subnets if (c.AddressIPv4 != nil && o.AddressIPv4 != nil) && (c.AddressIPv4.Contains(o.AddressIPv4.IP) || o.AddressIPv4.Contains(c.AddressIPv4.IP)) { return errors.New("networks have overlapping IPv4") } // They must be in different v6 subnets if (c.AddressIPv6 != nil && o.AddressIPv6 != nil) && (c.AddressIPv6.Contains(o.AddressIPv6.IP) || o.AddressIPv6.Contains(c.AddressIPv6.IP)) { return errors.New("networks have overlapping IPv6") } return nil }
[ "func", "(", "c", "*", "networkConfiguration", ")", "Conflicts", "(", "o", "*", "networkConfiguration", ")", "error", "{", "if", "o", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Also empty, because only one network with empty name is allowed", "if", "c", ".", "BridgeName", "==", "o", ".", "BridgeName", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// They must be in different subnets", "if", "(", "c", ".", "AddressIPv4", "!=", "nil", "&&", "o", ".", "AddressIPv4", "!=", "nil", ")", "&&", "(", "c", ".", "AddressIPv4", ".", "Contains", "(", "o", ".", "AddressIPv4", ".", "IP", ")", "||", "o", ".", "AddressIPv4", ".", "Contains", "(", "c", ".", "AddressIPv4", ".", "IP", ")", ")", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// They must be in different v6 subnets", "if", "(", "c", ".", "AddressIPv6", "!=", "nil", "&&", "o", ".", "AddressIPv6", "!=", "nil", ")", "&&", "(", "c", ".", "AddressIPv6", ".", "Contains", "(", "o", ".", "AddressIPv6", ".", "IP", ")", "||", "o", ".", "AddressIPv6", ".", "Contains", "(", "c", ".", "AddressIPv6", ".", "IP", ")", ")", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Conflicts check if two NetworkConfiguration objects overlap
[ "Conflicts", "check", "if", "two", "NetworkConfiguration", "objects", "overlap" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/bridge/bridge.go#L199-L222
train
docker/libnetwork
drivers/bridge/bridge.go
getV6Network
func getV6Network(config *networkConfiguration, i *bridgeInterface) *net.IPNet { if config.AddressIPv6 != nil { return config.AddressIPv6 } if i.bridgeIPv6 != nil && i.bridgeIPv6.IP != nil && !i.bridgeIPv6.IP.IsLinkLocalUnicast() { return i.bridgeIPv6 } return nil }
go
func getV6Network(config *networkConfiguration, i *bridgeInterface) *net.IPNet { if config.AddressIPv6 != nil { return config.AddressIPv6 } if i.bridgeIPv6 != nil && i.bridgeIPv6.IP != nil && !i.bridgeIPv6.IP.IsLinkLocalUnicast() { return i.bridgeIPv6 } return nil }
[ "func", "getV6Network", "(", "config", "*", "networkConfiguration", ",", "i", "*", "bridgeInterface", ")", "*", "net", ".", "IPNet", "{", "if", "config", ".", "AddressIPv6", "!=", "nil", "{", "return", "config", ".", "AddressIPv6", "\n", "}", "\n", "if", "i", ".", "bridgeIPv6", "!=", "nil", "&&", "i", ".", "bridgeIPv6", ".", "IP", "!=", "nil", "&&", "!", "i", ".", "bridgeIPv6", ".", "IP", ".", "IsLinkLocalUnicast", "(", ")", "{", "return", "i", ".", "bridgeIPv6", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Returns the non link-local IPv6 subnet for the containers attached to this bridge if found, nil otherwise
[ "Returns", "the", "non", "link", "-", "local", "IPv6", "subnet", "for", "the", "containers", "attached", "to", "this", "bridge", "if", "found", "nil", "otherwise" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/bridge/bridge.go#L509-L518
train
docker/libnetwork
drivers/bridge/bridge.go
CreateNetwork
func (d *driver) CreateNetwork(id string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error { if len(ipV4Data) == 0 || ipV4Data[0].Pool.String() == "0.0.0.0/0" { return types.BadRequestErrorf("ipv4 pool is empty") } // Sanity checks d.Lock() if _, ok := d.networks[id]; ok { d.Unlock() return types.ForbiddenErrorf("network %s exists", id) } d.Unlock() // Parse and validate the config. It should not be conflict with existing networks' config config, err := parseNetworkOptions(id, option) if err != nil { return err } if err = config.processIPAM(id, ipV4Data, ipV6Data); err != nil { return err } // start the critical section, from this point onward we are dealing with the list of networks // so to be consistent we cannot allow that the list changes d.configNetwork.Lock() defer d.configNetwork.Unlock() // check network conflicts if err = d.checkConflict(config); err != nil { nerr, ok := err.(defaultBridgeNetworkConflict) if !ok { return err } // Got a conflict with a stale default network, clean that up and continue logrus.Warn(nerr) d.deleteNetwork(nerr.ID) } // there is no conflict, now create the network if err = d.createNetwork(config); err != nil { return err } return d.storeUpdate(config) }
go
func (d *driver) CreateNetwork(id string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error { if len(ipV4Data) == 0 || ipV4Data[0].Pool.String() == "0.0.0.0/0" { return types.BadRequestErrorf("ipv4 pool is empty") } // Sanity checks d.Lock() if _, ok := d.networks[id]; ok { d.Unlock() return types.ForbiddenErrorf("network %s exists", id) } d.Unlock() // Parse and validate the config. It should not be conflict with existing networks' config config, err := parseNetworkOptions(id, option) if err != nil { return err } if err = config.processIPAM(id, ipV4Data, ipV6Data); err != nil { return err } // start the critical section, from this point onward we are dealing with the list of networks // so to be consistent we cannot allow that the list changes d.configNetwork.Lock() defer d.configNetwork.Unlock() // check network conflicts if err = d.checkConflict(config); err != nil { nerr, ok := err.(defaultBridgeNetworkConflict) if !ok { return err } // Got a conflict with a stale default network, clean that up and continue logrus.Warn(nerr) d.deleteNetwork(nerr.ID) } // there is no conflict, now create the network if err = d.createNetwork(config); err != nil { return err } return d.storeUpdate(config) }
[ "func", "(", "d", "*", "driver", ")", "CreateNetwork", "(", "id", "string", ",", "option", "map", "[", "string", "]", "interface", "{", "}", ",", "nInfo", "driverapi", ".", "NetworkInfo", ",", "ipV4Data", ",", "ipV6Data", "[", "]", "driverapi", ".", "IPAMData", ")", "error", "{", "if", "len", "(", "ipV4Data", ")", "==", "0", "||", "ipV4Data", "[", "0", "]", ".", "Pool", ".", "String", "(", ")", "==", "\"", "\"", "{", "return", "types", ".", "BadRequestErrorf", "(", "\"", "\"", ")", "\n", "}", "\n", "// Sanity checks", "d", ".", "Lock", "(", ")", "\n", "if", "_", ",", "ok", ":=", "d", ".", "networks", "[", "id", "]", ";", "ok", "{", "d", ".", "Unlock", "(", ")", "\n", "return", "types", ".", "ForbiddenErrorf", "(", "\"", "\"", ",", "id", ")", "\n", "}", "\n", "d", ".", "Unlock", "(", ")", "\n\n", "// Parse and validate the config. It should not be conflict with existing networks' config", "config", ",", "err", ":=", "parseNetworkOptions", "(", "id", ",", "option", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", "=", "config", ".", "processIPAM", "(", "id", ",", "ipV4Data", ",", "ipV6Data", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// start the critical section, from this point onward we are dealing with the list of networks", "// so to be consistent we cannot allow that the list changes", "d", ".", "configNetwork", ".", "Lock", "(", ")", "\n", "defer", "d", ".", "configNetwork", ".", "Unlock", "(", ")", "\n\n", "// check network conflicts", "if", "err", "=", "d", ".", "checkConflict", "(", "config", ")", ";", "err", "!=", "nil", "{", "nerr", ",", "ok", ":=", "err", ".", "(", "defaultBridgeNetworkConflict", ")", "\n", "if", "!", "ok", "{", "return", "err", "\n", "}", "\n", "// Got a conflict with a stale default network, clean that up and continue", "logrus", ".", "Warn", "(", "nerr", ")", "\n", "d", ".", "deleteNetwork", "(", "nerr", ".", "ID", ")", "\n", "}", "\n\n", "// there is no conflict, now create the network", "if", "err", "=", "d", ".", "createNetwork", "(", "config", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "d", ".", "storeUpdate", "(", "config", ")", "\n", "}" ]
// Create a new network using bridge plugin
[ "Create", "a", "new", "network", "using", "bridge", "plugin" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/bridge/bridge.go#L548-L592
train
docker/libnetwork
service.go
assignIPToEndpoint
func (s *service) assignIPToEndpoint(ip, eID string) (bool, int) { return s.ipToEndpoint.Insert(ip, eID) }
go
func (s *service) assignIPToEndpoint(ip, eID string) (bool, int) { return s.ipToEndpoint.Insert(ip, eID) }
[ "func", "(", "s", "*", "service", ")", "assignIPToEndpoint", "(", "ip", ",", "eID", "string", ")", "(", "bool", ",", "int", ")", "{", "return", "s", ".", "ipToEndpoint", ".", "Insert", "(", "ip", ",", "eID", ")", "\n", "}" ]
// assignIPToEndpoint inserts the mapping between the IP and the endpoint identifier // returns true if the mapping was not present, false otherwise // returns also the number of endpoints associated to the IP
[ "assignIPToEndpoint", "inserts", "the", "mapping", "between", "the", "IP", "and", "the", "endpoint", "identifier", "returns", "true", "if", "the", "mapping", "was", "not", "present", "false", "otherwise", "returns", "also", "the", "number", "of", "endpoints", "associated", "to", "the", "IP" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/service.go#L67-L69
train
docker/libnetwork
service.go
removeIPToEndpoint
func (s *service) removeIPToEndpoint(ip, eID string) (bool, int) { return s.ipToEndpoint.Remove(ip, eID) }
go
func (s *service) removeIPToEndpoint(ip, eID string) (bool, int) { return s.ipToEndpoint.Remove(ip, eID) }
[ "func", "(", "s", "*", "service", ")", "removeIPToEndpoint", "(", "ip", ",", "eID", "string", ")", "(", "bool", ",", "int", ")", "{", "return", "s", ".", "ipToEndpoint", ".", "Remove", "(", "ip", ",", "eID", ")", "\n", "}" ]
// removeIPToEndpoint removes the mapping between the IP and the endpoint identifier // returns true if the mapping was deleted, false otherwise // returns also the number of endpoints associated to the IP
[ "removeIPToEndpoint", "removes", "the", "mapping", "between", "the", "IP", "and", "the", "endpoint", "identifier", "returns", "true", "if", "the", "mapping", "was", "deleted", "false", "otherwise", "returns", "also", "the", "number", "of", "endpoints", "associated", "to", "the", "IP" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/service.go#L74-L76
train
docker/libnetwork
controller.go
New
func New(cfgOptions ...config.Option) (NetworkController, error) { c := &controller{ id: stringid.GenerateRandomID(), cfg: config.ParseConfigOptions(cfgOptions...), sandboxes: sandboxTable{}, svcRecords: make(map[string]svcInfo), serviceBindings: make(map[serviceKey]*service), agentInitDone: make(chan struct{}), networkLocker: locker.New(), DiagnosticServer: diagnostic.New(), } c.DiagnosticServer.Init() if err := c.initStores(); err != nil { return nil, err } drvRegistry, err := drvregistry.New(c.getStore(datastore.LocalScope), c.getStore(datastore.GlobalScope), c.RegisterDriver, nil, c.cfg.PluginGetter) if err != nil { return nil, err } for _, i := range getInitializers(c.cfg.Daemon.Experimental) { var dcfg map[string]interface{} // External plugins don't need config passed through daemon. They can // bootstrap themselves if i.ntype != "remote" { dcfg = c.makeDriverConfig(i.ntype) } if err := drvRegistry.AddDriver(i.ntype, i.fn, dcfg); err != nil { return nil, err } } if err = initIPAMDrivers(drvRegistry, nil, c.getStore(datastore.GlobalScope), c.cfg.Daemon.DefaultAddressPool); err != nil { return nil, err } c.drvRegistry = drvRegistry if c.cfg != nil && c.cfg.Cluster.Watcher != nil { if err := c.initDiscovery(c.cfg.Cluster.Watcher); err != nil { // Failing to initialize discovery is a bad situation to be in. // But it cannot fail creating the Controller logrus.Errorf("Failed to Initialize Discovery : %v", err) } } c.WalkNetworks(populateSpecial) // Reserve pools first before doing cleanup. Otherwise the // cleanups of endpoint/network and sandbox below will // generate many unnecessary warnings c.reservePools() // Cleanup resources c.sandboxCleanup(c.cfg.ActiveSandboxes) c.cleanupLocalEndpoints() c.networkCleanup() if err := c.startExternalKeyListener(); err != nil { return nil, err } return c, nil }
go
func New(cfgOptions ...config.Option) (NetworkController, error) { c := &controller{ id: stringid.GenerateRandomID(), cfg: config.ParseConfigOptions(cfgOptions...), sandboxes: sandboxTable{}, svcRecords: make(map[string]svcInfo), serviceBindings: make(map[serviceKey]*service), agentInitDone: make(chan struct{}), networkLocker: locker.New(), DiagnosticServer: diagnostic.New(), } c.DiagnosticServer.Init() if err := c.initStores(); err != nil { return nil, err } drvRegistry, err := drvregistry.New(c.getStore(datastore.LocalScope), c.getStore(datastore.GlobalScope), c.RegisterDriver, nil, c.cfg.PluginGetter) if err != nil { return nil, err } for _, i := range getInitializers(c.cfg.Daemon.Experimental) { var dcfg map[string]interface{} // External plugins don't need config passed through daemon. They can // bootstrap themselves if i.ntype != "remote" { dcfg = c.makeDriverConfig(i.ntype) } if err := drvRegistry.AddDriver(i.ntype, i.fn, dcfg); err != nil { return nil, err } } if err = initIPAMDrivers(drvRegistry, nil, c.getStore(datastore.GlobalScope), c.cfg.Daemon.DefaultAddressPool); err != nil { return nil, err } c.drvRegistry = drvRegistry if c.cfg != nil && c.cfg.Cluster.Watcher != nil { if err := c.initDiscovery(c.cfg.Cluster.Watcher); err != nil { // Failing to initialize discovery is a bad situation to be in. // But it cannot fail creating the Controller logrus.Errorf("Failed to Initialize Discovery : %v", err) } } c.WalkNetworks(populateSpecial) // Reserve pools first before doing cleanup. Otherwise the // cleanups of endpoint/network and sandbox below will // generate many unnecessary warnings c.reservePools() // Cleanup resources c.sandboxCleanup(c.cfg.ActiveSandboxes) c.cleanupLocalEndpoints() c.networkCleanup() if err := c.startExternalKeyListener(); err != nil { return nil, err } return c, nil }
[ "func", "New", "(", "cfgOptions", "...", "config", ".", "Option", ")", "(", "NetworkController", ",", "error", ")", "{", "c", ":=", "&", "controller", "{", "id", ":", "stringid", ".", "GenerateRandomID", "(", ")", ",", "cfg", ":", "config", ".", "ParseConfigOptions", "(", "cfgOptions", "...", ")", ",", "sandboxes", ":", "sandboxTable", "{", "}", ",", "svcRecords", ":", "make", "(", "map", "[", "string", "]", "svcInfo", ")", ",", "serviceBindings", ":", "make", "(", "map", "[", "serviceKey", "]", "*", "service", ")", ",", "agentInitDone", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "networkLocker", ":", "locker", ".", "New", "(", ")", ",", "DiagnosticServer", ":", "diagnostic", ".", "New", "(", ")", ",", "}", "\n", "c", ".", "DiagnosticServer", ".", "Init", "(", ")", "\n\n", "if", "err", ":=", "c", ".", "initStores", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "drvRegistry", ",", "err", ":=", "drvregistry", ".", "New", "(", "c", ".", "getStore", "(", "datastore", ".", "LocalScope", ")", ",", "c", ".", "getStore", "(", "datastore", ".", "GlobalScope", ")", ",", "c", ".", "RegisterDriver", ",", "nil", ",", "c", ".", "cfg", ".", "PluginGetter", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "for", "_", ",", "i", ":=", "range", "getInitializers", "(", "c", ".", "cfg", ".", "Daemon", ".", "Experimental", ")", "{", "var", "dcfg", "map", "[", "string", "]", "interface", "{", "}", "\n\n", "// External plugins don't need config passed through daemon. They can", "// bootstrap themselves", "if", "i", ".", "ntype", "!=", "\"", "\"", "{", "dcfg", "=", "c", ".", "makeDriverConfig", "(", "i", ".", "ntype", ")", "\n", "}", "\n\n", "if", "err", ":=", "drvRegistry", ".", "AddDriver", "(", "i", ".", "ntype", ",", "i", ".", "fn", ",", "dcfg", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "if", "err", "=", "initIPAMDrivers", "(", "drvRegistry", ",", "nil", ",", "c", ".", "getStore", "(", "datastore", ".", "GlobalScope", ")", ",", "c", ".", "cfg", ".", "Daemon", ".", "DefaultAddressPool", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "c", ".", "drvRegistry", "=", "drvRegistry", "\n\n", "if", "c", ".", "cfg", "!=", "nil", "&&", "c", ".", "cfg", ".", "Cluster", ".", "Watcher", "!=", "nil", "{", "if", "err", ":=", "c", ".", "initDiscovery", "(", "c", ".", "cfg", ".", "Cluster", ".", "Watcher", ")", ";", "err", "!=", "nil", "{", "// Failing to initialize discovery is a bad situation to be in.", "// But it cannot fail creating the Controller", "logrus", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "c", ".", "WalkNetworks", "(", "populateSpecial", ")", "\n\n", "// Reserve pools first before doing cleanup. Otherwise the", "// cleanups of endpoint/network and sandbox below will", "// generate many unnecessary warnings", "c", ".", "reservePools", "(", ")", "\n\n", "// Cleanup resources", "c", ".", "sandboxCleanup", "(", "c", ".", "cfg", ".", "ActiveSandboxes", ")", "\n", "c", ".", "cleanupLocalEndpoints", "(", ")", "\n", "c", ".", "networkCleanup", "(", ")", "\n\n", "if", "err", ":=", "c", ".", "startExternalKeyListener", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "c", ",", "nil", "\n", "}" ]
// New creates a new instance of network controller.
[ "New", "creates", "a", "new", "instance", "of", "network", "controller", "." ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/controller.go#L189-L256
train
docker/libnetwork
controller.go
SetKeys
func (c *controller) SetKeys(keys []*types.EncryptionKey) error { subsysKeys := make(map[string]int) for _, key := range keys { if key.Subsystem != subsysGossip && key.Subsystem != subsysIPSec { return fmt.Errorf("key received for unrecognized subsystem") } subsysKeys[key.Subsystem]++ } for s, count := range subsysKeys { if count != keyringSize { return fmt.Errorf("incorrect number of keys for subsystem %v", s) } } agent := c.getAgent() if agent == nil { c.Lock() c.keys = keys c.Unlock() return nil } return c.handleKeyChange(keys) }
go
func (c *controller) SetKeys(keys []*types.EncryptionKey) error { subsysKeys := make(map[string]int) for _, key := range keys { if key.Subsystem != subsysGossip && key.Subsystem != subsysIPSec { return fmt.Errorf("key received for unrecognized subsystem") } subsysKeys[key.Subsystem]++ } for s, count := range subsysKeys { if count != keyringSize { return fmt.Errorf("incorrect number of keys for subsystem %v", s) } } agent := c.getAgent() if agent == nil { c.Lock() c.keys = keys c.Unlock() return nil } return c.handleKeyChange(keys) }
[ "func", "(", "c", "*", "controller", ")", "SetKeys", "(", "keys", "[", "]", "*", "types", ".", "EncryptionKey", ")", "error", "{", "subsysKeys", ":=", "make", "(", "map", "[", "string", "]", "int", ")", "\n", "for", "_", ",", "key", ":=", "range", "keys", "{", "if", "key", ".", "Subsystem", "!=", "subsysGossip", "&&", "key", ".", "Subsystem", "!=", "subsysIPSec", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "subsysKeys", "[", "key", ".", "Subsystem", "]", "++", "\n", "}", "\n", "for", "s", ",", "count", ":=", "range", "subsysKeys", "{", "if", "count", "!=", "keyringSize", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "s", ")", "\n", "}", "\n", "}", "\n\n", "agent", ":=", "c", ".", "getAgent", "(", ")", "\n\n", "if", "agent", "==", "nil", "{", "c", ".", "Lock", "(", ")", "\n", "c", ".", "keys", "=", "keys", "\n", "c", ".", "Unlock", "(", ")", "\n", "return", "nil", "\n", "}", "\n", "return", "c", ".", "handleKeyChange", "(", "keys", ")", "\n", "}" ]
// libnetwork side of agent depends on the keys. On the first receipt of // keys setup the agent. For subsequent key set handle the key change
[ "libnetwork", "side", "of", "agent", "depends", "on", "the", "keys", ".", "On", "the", "first", "receipt", "of", "keys", "setup", "the", "agent", ".", "For", "subsequent", "key", "set", "handle", "the", "key", "change" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/controller.go#L285-L309
train
docker/libnetwork
controller.go
AgentInitWait
func (c *controller) AgentInitWait() { c.Lock() agentInitDone := c.agentInitDone c.Unlock() if agentInitDone != nil { <-agentInitDone } }
go
func (c *controller) AgentInitWait() { c.Lock() agentInitDone := c.agentInitDone c.Unlock() if agentInitDone != nil { <-agentInitDone } }
[ "func", "(", "c", "*", "controller", ")", "AgentInitWait", "(", ")", "{", "c", ".", "Lock", "(", ")", "\n", "agentInitDone", ":=", "c", ".", "agentInitDone", "\n", "c", ".", "Unlock", "(", ")", "\n\n", "if", "agentInitDone", "!=", "nil", "{", "<-", "agentInitDone", "\n", "}", "\n", "}" ]
// AgentInitWait waits for agent initialization to be completed in the controller.
[ "AgentInitWait", "waits", "for", "agent", "initialization", "to", "be", "completed", "in", "the", "controller", "." ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/controller.go#L367-L375
train
docker/libnetwork
controller.go
AgentStopWait
func (c *controller) AgentStopWait() { c.Lock() agentStopDone := c.agentStopDone c.Unlock() if agentStopDone != nil { <-agentStopDone } }
go
func (c *controller) AgentStopWait() { c.Lock() agentStopDone := c.agentStopDone c.Unlock() if agentStopDone != nil { <-agentStopDone } }
[ "func", "(", "c", "*", "controller", ")", "AgentStopWait", "(", ")", "{", "c", ".", "Lock", "(", ")", "\n", "agentStopDone", ":=", "c", ".", "agentStopDone", "\n", "c", ".", "Unlock", "(", ")", "\n", "if", "agentStopDone", "!=", "nil", "{", "<-", "agentStopDone", "\n", "}", "\n", "}" ]
// AgentStopWait waits for the Agent stop to be completed in the controller
[ "AgentStopWait", "waits", "for", "the", "Agent", "stop", "to", "be", "completed", "in", "the", "controller" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/controller.go#L378-L385
train
docker/libnetwork
controller.go
agentOperationStart
func (c *controller) agentOperationStart() { c.Lock() if c.agentInitDone == nil { c.agentInitDone = make(chan struct{}) } if c.agentStopDone == nil { c.agentStopDone = make(chan struct{}) } c.Unlock() }
go
func (c *controller) agentOperationStart() { c.Lock() if c.agentInitDone == nil { c.agentInitDone = make(chan struct{}) } if c.agentStopDone == nil { c.agentStopDone = make(chan struct{}) } c.Unlock() }
[ "func", "(", "c", "*", "controller", ")", "agentOperationStart", "(", ")", "{", "c", ".", "Lock", "(", ")", "\n", "if", "c", ".", "agentInitDone", "==", "nil", "{", "c", ".", "agentInitDone", "=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "}", "\n", "if", "c", ".", "agentStopDone", "==", "nil", "{", "c", ".", "agentStopDone", "=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "}", "\n", "c", ".", "Unlock", "(", ")", "\n", "}" ]
// agentOperationStart marks the start of an Agent Init or Agent Stop
[ "agentOperationStart", "marks", "the", "start", "of", "an", "Agent", "Init", "or", "Agent", "Stop" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/controller.go#L388-L397
train
docker/libnetwork
controller.go
agentInitComplete
func (c *controller) agentInitComplete() { c.Lock() if c.agentInitDone != nil { close(c.agentInitDone) c.agentInitDone = nil } c.Unlock() }
go
func (c *controller) agentInitComplete() { c.Lock() if c.agentInitDone != nil { close(c.agentInitDone) c.agentInitDone = nil } c.Unlock() }
[ "func", "(", "c", "*", "controller", ")", "agentInitComplete", "(", ")", "{", "c", ".", "Lock", "(", ")", "\n", "if", "c", ".", "agentInitDone", "!=", "nil", "{", "close", "(", "c", ".", "agentInitDone", ")", "\n", "c", ".", "agentInitDone", "=", "nil", "\n", "}", "\n", "c", ".", "Unlock", "(", ")", "\n", "}" ]
// agentInitComplete notifies the successful completion of the Agent initialization
[ "agentInitComplete", "notifies", "the", "successful", "completion", "of", "the", "Agent", "initialization" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/controller.go#L400-L407
train
docker/libnetwork
controller.go
agentStopComplete
func (c *controller) agentStopComplete() { c.Lock() if c.agentStopDone != nil { close(c.agentStopDone) c.agentStopDone = nil } c.Unlock() }
go
func (c *controller) agentStopComplete() { c.Lock() if c.agentStopDone != nil { close(c.agentStopDone) c.agentStopDone = nil } c.Unlock() }
[ "func", "(", "c", "*", "controller", ")", "agentStopComplete", "(", ")", "{", "c", ".", "Lock", "(", ")", "\n", "if", "c", ".", "agentStopDone", "!=", "nil", "{", "close", "(", "c", ".", "agentStopDone", ")", "\n", "c", ".", "agentStopDone", "=", "nil", "\n", "}", "\n", "c", ".", "Unlock", "(", ")", "\n", "}" ]
// agentStopComplete notifies the successful completion of the Agent stop
[ "agentStopComplete", "notifies", "the", "successful", "completion", "of", "the", "Agent", "stop" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/controller.go#L410-L417
train
docker/libnetwork
controller.go
SandboxDestroy
func (c *controller) SandboxDestroy(id string) error { var sb *sandbox c.Lock() for _, s := range c.sandboxes { if s.containerID == id { sb = s break } } c.Unlock() // It is not an error if sandbox is not available if sb == nil { return nil } return sb.Delete() }
go
func (c *controller) SandboxDestroy(id string) error { var sb *sandbox c.Lock() for _, s := range c.sandboxes { if s.containerID == id { sb = s break } } c.Unlock() // It is not an error if sandbox is not available if sb == nil { return nil } return sb.Delete() }
[ "func", "(", "c", "*", "controller", ")", "SandboxDestroy", "(", "id", "string", ")", "error", "{", "var", "sb", "*", "sandbox", "\n", "c", ".", "Lock", "(", ")", "\n", "for", "_", ",", "s", ":=", "range", "c", ".", "sandboxes", "{", "if", "s", ".", "containerID", "==", "id", "{", "sb", "=", "s", "\n", "break", "\n", "}", "\n", "}", "\n", "c", ".", "Unlock", "(", ")", "\n\n", "// It is not an error if sandbox is not available", "if", "sb", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "return", "sb", ".", "Delete", "(", ")", "\n", "}" ]
// SandboxDestroy destroys a sandbox given a container ID
[ "SandboxDestroy", "destroys", "a", "sandbox", "given", "a", "container", "ID" ]
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/controller.go#L1231-L1248
train