repo
stringlengths
5
67
sha
stringlengths
40
40
path
stringlengths
4
234
url
stringlengths
85
339
language
stringclasses
6 values
split
stringclasses
3 values
doc
stringlengths
3
51.2k
sign
stringlengths
5
8.01k
problem
stringlengths
13
51.2k
output
stringlengths
0
3.87M
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
client/network.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/network.go#L122-L172
go
train
// CmdNetworkLs handles Network List UI
func (cli *NetworkCli) CmdNetworkLs(chain string, args ...string) error
// CmdNetworkLs handles Network List UI func (cli *NetworkCli) CmdNetworkLs(chain string, args ...string) error
{ cmd := cli.Subcmd(chain, "ls", "", "Lists all the networks created by the user", false) quiet := cmd.Bool([]string{"q", "-quiet"}, false, "Only display numeric IDs") noTrunc := cmd.Bool([]string{"#notrunc", "-no-trunc"}, false, "Do not truncate the output") nLatest := cmd.Bool([]string{"l", "-latest"}, false, "Show the latest network created") last := cmd.Int([]string{"n"}, -1, "Show n last created networks") err := cmd.ParseFlags(args, true) if err != nil { return err } obj, _, err := readBody(cli.call("GET", "/networks", nil, nil)) if err != nil { return err } if *last == -1 && *nLatest { *last = 1 } var networkResources []networkResource err = json.Unmarshal(obj, &networkResources) if err != nil { return err } wr := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0) // unless quiet (-q) is specified, print field titles if !*quiet { fmt.Fprintln(wr, "NETWORK ID\tNAME\tTYPE") } for _, networkResource := range networkResources { ID := networkResource.ID netName := networkResource.Name if !*noTrunc { ID = stringid.TruncateID(ID) } if *quiet { fmt.Fprintln(wr, ID) continue } netType := networkResource.Type fmt.Fprintf(wr, "%s\t%s\t%s\t", ID, netName, netType) fmt.Fprint(wr, "\n") } wr.Flush() return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
client/network.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/network.go#L175-L207
go
train
// CmdNetworkInfo handles Network Info UI
func (cli *NetworkCli) CmdNetworkInfo(chain string, args ...string) error
// CmdNetworkInfo handles Network Info UI func (cli *NetworkCli) CmdNetworkInfo(chain string, args ...string) error
{ cmd := cli.Subcmd(chain, "info", "NETWORK", "Displays detailed information on a network", false) cmd.Require(flag.Exact, 1) err := cmd.ParseFlags(args, true) if err != nil { return err } id, err := lookupNetworkID(cli, cmd.Arg(0)) if err != nil { return err } obj, _, err := readBody(cli.call("GET", "/networks/"+id, nil, nil)) if err != nil { return err } networkResource := &networkResource{} if err := json.NewDecoder(bytes.NewReader(obj)).Decode(networkResource); err != nil { return err } fmt.Fprintf(cli.out, "Network Id: %s\n", networkResource.ID) fmt.Fprintf(cli.out, "Name: %s\n", networkResource.Name) fmt.Fprintf(cli.out, "Type: %s\n", networkResource.Type) if networkResource.Services != nil { for _, serviceResource := range networkResource.Services { fmt.Fprintf(cli.out, " Service Id: %s\n", serviceResource.ID) fmt.Fprintf(cli.out, "\tName: %s\n", serviceResource.Name) } } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
client/network.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/network.go#L215-L256
go
train
// Helper function to predict if a string is a name or id or partial-id // This provides a best-effort mechanism to identify an id with the help of GET Filter APIs // Being a UI, its most likely that name will be used by the user, which is used to lookup // the corresponding ID. If ID is not found, this function will assume that the passed string // is an ID by itself.
func lookupNetworkID(cli *NetworkCli, nameID string) (string, error)
// Helper function to predict if a string is a name or id or partial-id // This provides a best-effort mechanism to identify an id with the help of GET Filter APIs // Being a UI, its most likely that name will be used by the user, which is used to lookup // the corresponding ID. If ID is not found, this function will assume that the passed string // is an ID by itself. func lookupNetworkID(cli *NetworkCli, nameID string) (string, error)
{ obj, statusCode, err := readBody(cli.call("GET", "/networks?name="+nameID, nil, nil)) if err != nil { return "", err } if statusCode != http.StatusOK { return "", fmt.Errorf("name query failed for %s due to : statuscode(%d) %v", nameID, statusCode, string(obj)) } var list []*networkResource err = json.Unmarshal(obj, &list) if err != nil { return "", err } if len(list) > 0 { // name query filter will always return a single-element collection return list[0].ID, nil } // Check for Partial-id obj, statusCode, err = readBody(cli.call("GET", "/networks?partial-id="+nameID, nil, nil)) if err != nil { return "", err } if statusCode != http.StatusOK { return "", fmt.Errorf("partial-id match query failed for %s due to : statuscode(%d) %v", nameID, statusCode, string(obj)) } err = json.Unmarshal(obj, &list) if err != nil { return "", err } if len(list) == 0 { return "", fmt.Errorf("resource not found %s", nameID) } if len(list) > 1 { return "", fmt.Errorf("multiple Networks matching the partial identifier (%s). Please use full identifier", nameID) } return list[0].ID, nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drivers/ipvlan/ipvlan.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/ipvlan/ipvlan.go#L59-L70
go
train
// Init initializes and registers the libnetwork ipvlan driver
func Init(dc driverapi.DriverCallback, config map[string]interface{}) error
// Init initializes and registers the libnetwork ipvlan driver func Init(dc driverapi.DriverCallback, config map[string]interface{}) error
{ c := driverapi.Capability{ DataScope: datastore.LocalScope, ConnectivityScope: datastore.GlobalScope, } d := &driver{ networks: networkTable{}, } d.initStore(config) return dc.RegisterDriver(ipvlanType, d, c) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
ipams/builtin/builtin_unix.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipams/builtin/builtin_unix.go#L20-L48
go
train
// Init registers the built-in ipam service with libnetwork
func Init(ic ipamapi.Callback, l, g interface{}) error
// Init registers the built-in ipam service with libnetwork func Init(ic ipamapi.Callback, l, g interface{}) error
{ var ( ok bool localDs, globalDs datastore.DataStore ) if l != nil { if localDs, ok = l.(datastore.DataStore); !ok { return errors.New("incorrect local datastore passed to built-in ipam init") } } if g != nil { if globalDs, ok = g.(datastore.DataStore); !ok { return errors.New("incorrect global datastore passed to built-in ipam init") } } ipamutils.ConfigLocalScopeDefaultNetworks(GetDefaultIPAddressPool()) a, err := ipam.NewAllocator(localDs, globalDs) if err != nil { return err } cps := &ipamapi.Capability{RequiresRequestReplay: true} return ic.RegisterIpamDriverWithCapabilities(ipamapi.DefaultIPAM, a, cps) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
networkdb/networkdb.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/networkdb/networkdb.go#L225-L236
go
train
// DefaultConfig returns a NetworkDB config with default values
func DefaultConfig() *Config
// DefaultConfig returns a NetworkDB config with default values func DefaultConfig() *Config
{ hostname, _ := os.Hostname() return &Config{ NodeID: stringid.TruncateID(stringid.GenerateRandomID()), Hostname: hostname, BindAddr: "0.0.0.0", PacketBufferSize: 1400, StatsPrintPeriod: 5 * time.Minute, HealthPrintPeriod: 1 * time.Minute, reapEntryInterval: 30 * time.Minute, } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
networkdb/networkdb.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/networkdb/networkdb.go#L240-L267
go
train
// New creates a new instance of NetworkDB using the Config passed by // the caller.
func New(c *Config) (*NetworkDB, error)
// New creates a new instance of NetworkDB using the Config passed by // the caller. func New(c *Config) (*NetworkDB, error)
{ // The garbage collection logic for entries leverage the presence of the network. // For this reason the expiration time of the network is put slightly higher than the entry expiration so that // there is at least 5 extra cycle to make sure that all the entries are properly deleted before deleting the network. c.reapNetworkInterval = c.reapEntryInterval + 5*reapPeriod nDB := &NetworkDB{ config: c, indexes: make(map[int]*radix.Tree), networks: make(map[string]map[string]*network), nodes: make(map[string]*node), failedNodes: make(map[string]*node), leftNodes: make(map[string]*node), networkNodes: make(map[string][]string), bulkSyncAckTbl: make(map[string]chan struct{}), broadcaster: events.NewBroadcaster(), } nDB.indexes[byTable] = radix.New() nDB.indexes[byNetwork] = radix.New() logrus.Infof("New memberlist node - Node:%v will use memberlist nodeID:%v with config:%+v", c.Hostname, c.NodeID, c) if err := nDB.clusterInit(); err != nil { return nil, err } return nDB, nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
networkdb/networkdb.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/networkdb/networkdb.go#L271-L277
go
train
// Join joins this NetworkDB instance with a list of peer NetworkDB // instances passed by the caller in the form of addr:port
func (nDB *NetworkDB) Join(members []string) error
// Join joins this NetworkDB instance with a list of peer NetworkDB // instances passed by the caller in the form of addr:port func (nDB *NetworkDB) Join(members []string) error
{ nDB.Lock() nDB.bootStrapIP = append([]string(nil), members...) logrus.Infof("The new bootstrap node list is:%v", nDB.bootStrapIP) nDB.Unlock() return nDB.clusterJoin(members) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
networkdb/networkdb.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/networkdb/networkdb.go#L281-L288
go
train
// Close destroys this NetworkDB instance by leave the cluster, // stopping timers, canceling goroutines etc.
func (nDB *NetworkDB) Close()
// Close destroys this NetworkDB instance by leave the cluster, // stopping timers, canceling goroutines etc. func (nDB *NetworkDB) Close()
{ if err := nDB.clusterLeave(); err != nil { logrus.Errorf("%v(%v) Could not close DB: %v", nDB.config.Hostname, nDB.config.NodeID, err) } //Avoid (*Broadcaster).run goroutine leak nDB.broadcaster.Close() }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
networkdb/networkdb.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/networkdb/networkdb.go#L291-L302
go
train
// ClusterPeers returns all the gossip cluster peers.
func (nDB *NetworkDB) ClusterPeers() []PeerInfo
// ClusterPeers returns all the gossip cluster peers. func (nDB *NetworkDB) ClusterPeers() []PeerInfo
{ nDB.RLock() defer nDB.RUnlock() peers := make([]PeerInfo, 0, len(nDB.nodes)) for _, node := range nDB.nodes { peers = append(peers, PeerInfo{ Name: node.Name, IP: node.Node.Addr.String(), }) } return peers }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
networkdb/networkdb.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/networkdb/networkdb.go#L305-L322
go
train
// Peers returns the gossip peers for a given network.
func (nDB *NetworkDB) Peers(nid string) []PeerInfo
// Peers returns the gossip peers for a given network. func (nDB *NetworkDB) Peers(nid string) []PeerInfo
{ nDB.RLock() defer nDB.RUnlock() peers := make([]PeerInfo, 0, len(nDB.networkNodes[nid])) for _, nodeName := range nDB.networkNodes[nid] { if node, ok := nDB.nodes[nodeName]; ok { peers = append(peers, PeerInfo{ Name: node.Name, IP: node.Addr.String(), }) } else { // Added for testing purposes, this condition should never happen else mean that the network list // is out of sync with the node list peers = append(peers, PeerInfo{Name: nodeName, IP: "unknown"}) } } return peers }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
networkdb/networkdb.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/networkdb/networkdb.go#L326-L338
go
train
// GetEntry retrieves the value of a table entry in a given (network, // table, key) tuple
func (nDB *NetworkDB) GetEntry(tname, nid, key string) ([]byte, error)
// GetEntry retrieves the value of a table entry in a given (network, // table, key) tuple func (nDB *NetworkDB) GetEntry(tname, nid, key string) ([]byte, error)
{ nDB.RLock() defer nDB.RUnlock() entry, err := nDB.getEntry(tname, nid, key) if err != nil { return nil, err } if entry != nil && entry.deleting { return nil, types.NotFoundErrorf("entry in table %s network id %s and key %s deleted and pending garbage collection", tname, nid, key) } return entry.value, nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
networkdb/networkdb.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/networkdb/networkdb.go#L354-L376
go
train
// CreateEntry creates a table entry in NetworkDB for given (network, // table, key) tuple and if the NetworkDB is part of the cluster // propagates this event to the cluster. It is an error to create an // entry for the same tuple for which there is already an existing // entry unless the current entry is deleting state.
func (nDB *NetworkDB) CreateEntry(tname, nid, key string, value []byte) error
// CreateEntry creates a table entry in NetworkDB for given (network, // table, key) tuple and if the NetworkDB is part of the cluster // propagates this event to the cluster. It is an error to create an // entry for the same tuple for which there is already an existing // entry unless the current entry is deleting state. func (nDB *NetworkDB) CreateEntry(tname, nid, key string, value []byte) error
{ nDB.Lock() oldEntry, err := nDB.getEntry(tname, nid, key) if err == nil || (oldEntry != nil && !oldEntry.deleting) { nDB.Unlock() return fmt.Errorf("cannot create entry in table %s with network id %s and key %s, already exists", tname, nid, key) } entry := &entry{ ltime: nDB.tableClock.Increment(), node: nDB.config.NodeID, value: value, } nDB.createOrUpdateEntry(nid, tname, key, entry) nDB.Unlock() if err := nDB.sendTableEvent(TableEventTypeCreate, nid, tname, key, entry); err != nil { return fmt.Errorf("cannot send create event for table %s, %v", tname, err) } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
networkdb/networkdb.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/networkdb/networkdb.go#L382-L403
go
train
// UpdateEntry updates a table entry in NetworkDB for given (network, // table, key) tuple and if the NetworkDB is part of the cluster // propagates this event to the cluster. It is an error to update a // non-existent entry.
func (nDB *NetworkDB) UpdateEntry(tname, nid, key string, value []byte) error
// UpdateEntry updates a table entry in NetworkDB for given (network, // table, key) tuple and if the NetworkDB is part of the cluster // propagates this event to the cluster. It is an error to update a // non-existent entry. func (nDB *NetworkDB) UpdateEntry(tname, nid, key string, value []byte) error
{ nDB.Lock() if _, err := nDB.getEntry(tname, nid, key); err != nil { nDB.Unlock() return fmt.Errorf("cannot update entry as the entry in table %s with network id %s and key %s does not exist", tname, nid, key) } entry := &entry{ ltime: nDB.tableClock.Increment(), node: nDB.config.NodeID, value: value, } nDB.createOrUpdateEntry(nid, tname, key, entry) nDB.Unlock() if err := nDB.sendTableEvent(TableEventTypeUpdate, nid, tname, key, entry); err != nil { return fmt.Errorf("cannot send table update event: %v", err) } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
networkdb/networkdb.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/networkdb/networkdb.go#L413-L425
go
train
// GetTableByNetwork walks the networkdb by the give table and network id and // returns a map of keys and values
func (nDB *NetworkDB) GetTableByNetwork(tname, nid string) map[string]*TableElem
// GetTableByNetwork walks the networkdb by the give table and network id and // returns a map of keys and values func (nDB *NetworkDB) GetTableByNetwork(tname, nid string) map[string]*TableElem
{ entries := make(map[string]*TableElem) nDB.indexes[byTable].WalkPrefix(fmt.Sprintf("/%s/%s", tname, nid), func(k string, v interface{}) bool { entry := v.(*entry) if entry.deleting { return false } key := k[strings.LastIndex(k, "/")+1:] entries[key] = &TableElem{Value: entry.value, owner: entry.node} return false }) return entries }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
networkdb/networkdb.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/networkdb/networkdb.go#L430-L455
go
train
// DeleteEntry deletes a table entry in NetworkDB for given (network, // table, key) tuple and if the NetworkDB is part of the cluster // propagates this event to the cluster.
func (nDB *NetworkDB) DeleteEntry(tname, nid, key string) error
// DeleteEntry deletes a table entry in NetworkDB for given (network, // table, key) tuple and if the NetworkDB is part of the cluster // propagates this event to the cluster. func (nDB *NetworkDB) DeleteEntry(tname, nid, key string) error
{ nDB.Lock() oldEntry, err := nDB.getEntry(tname, nid, key) if err != nil || oldEntry == nil || oldEntry.deleting { nDB.Unlock() return fmt.Errorf("cannot delete entry %s with network id %s and key %s "+ "does not exist or is already being deleted", tname, nid, key) } entry := &entry{ ltime: nDB.tableClock.Increment(), node: nDB.config.NodeID, value: oldEntry.value, deleting: true, reapTime: nDB.config.reapEntryInterval, } nDB.createOrUpdateEntry(nid, tname, key, entry) nDB.Unlock() if err := nDB.sendTableEvent(TableEventTypeDelete, nid, tname, key, entry); err != nil { return fmt.Errorf("cannot send table delete event: %v", err) } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
networkdb/networkdb.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/networkdb/networkdb.go#L487-L543
go
train
// deleteNodeNetworkEntries is called in 2 conditions with 2 different outcomes: // 1) when a notification is coming of a node leaving the network // - Walk all the network entries and mark the leaving node's entries for deletion // These will be garbage collected when the reap timer will expire // 2) when the local node is leaving the network // - Walk all the network entries: // A) if the entry is owned by the local node // then we will mark it for deletion. This will ensure that if a node did not // yet received the notification that the local node is leaving, will be aware // of the entries to be deleted. // B) if the entry is owned by a remote node, then we can safely delete it. This // ensures that if we join back this network as we receive the CREATE event for // entries owned by remote nodes, we will accept them and we notify the application
func (nDB *NetworkDB) deleteNodeNetworkEntries(nid, node string)
// deleteNodeNetworkEntries is called in 2 conditions with 2 different outcomes: // 1) when a notification is coming of a node leaving the network // - Walk all the network entries and mark the leaving node's entries for deletion // These will be garbage collected when the reap timer will expire // 2) when the local node is leaving the network // - Walk all the network entries: // A) if the entry is owned by the local node // then we will mark it for deletion. This will ensure that if a node did not // yet received the notification that the local node is leaving, will be aware // of the entries to be deleted. // B) if the entry is owned by a remote node, then we can safely delete it. This // ensures that if we join back this network as we receive the CREATE event for // entries owned by remote nodes, we will accept them and we notify the application func (nDB *NetworkDB) deleteNodeNetworkEntries(nid, node string)
{ // Indicates if the delete is triggered for the local node isNodeLocal := node == nDB.config.NodeID nDB.indexes[byNetwork].WalkPrefix(fmt.Sprintf("/%s", nid), func(path string, v interface{}) bool { oldEntry := v.(*entry) params := strings.Split(path[1:], "/") nid := params[0] tname := params[1] key := params[2] // If the entry is owned by a remote node and this node is not leaving the network if oldEntry.node != node && !isNodeLocal { // Don't do anything because the event is triggered for a node that does not own this entry return false } // If this entry is already marked for deletion and this node is not leaving the network if oldEntry.deleting && !isNodeLocal { // Don't do anything this entry will be already garbage collected using the old reapTime return false } entry := &entry{ ltime: oldEntry.ltime, node: oldEntry.node, value: oldEntry.value, deleting: true, reapTime: nDB.config.reapEntryInterval, } // we arrived at this point in 2 cases: // 1) this entry is owned by the node that is leaving the network // 2) the local node is leaving the network if oldEntry.node == node { if isNodeLocal { // TODO fcrisciani: this can be removed if there is no way to leave the network // without doing a delete of all the objects entry.ltime++ } if !oldEntry.deleting { nDB.createOrUpdateEntry(nid, tname, key, entry) } } else { // the local node is leaving the network, all the entries of remote nodes can be safely removed nDB.deleteEntry(nid, tname, key) } // Notify to the upper layer only entries not already marked for deletion if !oldEntry.deleting { nDB.broadcaster.Write(makeEvent(opDelete, tname, nid, key, entry.value)) } return false }) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
networkdb/networkdb.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/networkdb/networkdb.go#L569-L588
go
train
// WalkTable walks a single table in NetworkDB and invokes the passed // function for each entry in the table passing the network, key, // value. The walk stops if the passed function returns a true.
func (nDB *NetworkDB) WalkTable(tname string, fn func(string, string, []byte, bool) bool) error
// WalkTable walks a single table in NetworkDB and invokes the passed // function for each entry in the table passing the network, key, // value. The walk stops if the passed function returns a true. func (nDB *NetworkDB) WalkTable(tname string, fn func(string, string, []byte, bool) bool) error
{ nDB.RLock() values := make(map[string]interface{}) nDB.indexes[byTable].WalkPrefix(fmt.Sprintf("/%s", tname), func(path string, v interface{}) bool { values[path] = v return false }) nDB.RUnlock() for k, v := range values { params := strings.Split(k[1:], "/") nid := params[1] key := params[2] if fn(nid, key, v.(*entry).value, v.(*entry).deleting) { return nil } } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
networkdb/networkdb.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/networkdb/networkdb.go#L594-L641
go
train
// JoinNetwork joins this node to a given network and propagates this // event across the cluster. This triggers this node joining the // sub-cluster of this network and participates in the network-scoped // gossip and bulk sync for this network.
func (nDB *NetworkDB) JoinNetwork(nid string) error
// JoinNetwork joins this node to a given network and propagates this // event across the cluster. This triggers this node joining the // sub-cluster of this network and participates in the network-scoped // gossip and bulk sync for this network. func (nDB *NetworkDB) JoinNetwork(nid string) error
{ ltime := nDB.networkClock.Increment() nDB.Lock() nodeNetworks, ok := nDB.networks[nDB.config.NodeID] if !ok { nodeNetworks = make(map[string]*network) nDB.networks[nDB.config.NodeID] = nodeNetworks } n, ok := nodeNetworks[nid] var entries int if ok { entries = n.entriesNumber } nodeNetworks[nid] = &network{id: nid, ltime: ltime, entriesNumber: entries} nodeNetworks[nid].tableBroadcasts = &memberlist.TransmitLimitedQueue{ NumNodes: func() int { //TODO fcrisciani this can be optimized maybe avoiding the lock? // this call is done each GetBroadcasts call to evaluate the number of // replicas for the message nDB.RLock() defer nDB.RUnlock() return len(nDB.networkNodes[nid]) }, RetransmitMult: 4, } nDB.addNetworkNode(nid, nDB.config.NodeID) networkNodes := nDB.networkNodes[nid] n = nodeNetworks[nid] nDB.Unlock() if err := nDB.sendNetworkEvent(nid, NetworkEventTypeJoin, ltime); err != nil { return fmt.Errorf("failed to send leave network event for %s: %v", nid, err) } logrus.Debugf("%v(%v): joined network %s", nDB.config.Hostname, nDB.config.NodeID, nid) if _, err := nDB.bulkSync(networkNodes, true); err != nil { logrus.Errorf("Error bulk syncing while joining network %s: %v", nid, err) } // Mark the network as being synced // note this is a best effort, we are not checking the result of the bulk sync nDB.Lock() n.inSync = true nDB.Unlock() return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
networkdb/networkdb.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/networkdb/networkdb.go#L649-L679
go
train
// LeaveNetwork leaves this node from a given network and propagates // this event across the cluster. This triggers this node leaving the // sub-cluster of this network and as a result will no longer // participate in the network-scoped gossip and bulk sync for this // network. Also remove all the table entries for this network from // networkdb
func (nDB *NetworkDB) LeaveNetwork(nid string) error
// LeaveNetwork leaves this node from a given network and propagates // this event across the cluster. This triggers this node leaving the // sub-cluster of this network and as a result will no longer // participate in the network-scoped gossip and bulk sync for this // network. Also remove all the table entries for this network from // networkdb func (nDB *NetworkDB) LeaveNetwork(nid string) error
{ ltime := nDB.networkClock.Increment() if err := nDB.sendNetworkEvent(nid, NetworkEventTypeLeave, ltime); err != nil { return fmt.Errorf("failed to send leave network event for %s: %v", nid, err) } nDB.Lock() defer nDB.Unlock() // Remove myself from the list of the nodes participating to the network nDB.deleteNetworkNode(nid, nDB.config.NodeID) // Update all the local entries marking them for deletion and delete all the remote entries nDB.deleteNodeNetworkEntries(nid, nDB.config.NodeID) nodeNetworks, ok := nDB.networks[nDB.config.NodeID] if !ok { return fmt.Errorf("could not find self node for network %s while trying to leave", nid) } n, ok := nodeNetworks[nid] if !ok { return fmt.Errorf("could not find network %s while trying to leave", nid) } logrus.Debugf("%v(%v): leaving network %s", nDB.config.Hostname, nDB.config.NodeID, nid) n.ltime = ltime n.reapTime = nDB.config.reapNetworkInterval n.leaving = true return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
networkdb/networkdb.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/networkdb/networkdb.go#L684-L693
go
train
// addNetworkNode adds the node to the list of nodes which participate // in the passed network only if it is not already present. Caller // should hold the NetworkDB lock while calling this
func (nDB *NetworkDB) addNetworkNode(nid string, nodeName string)
// addNetworkNode adds the node to the list of nodes which participate // in the passed network only if it is not already present. Caller // should hold the NetworkDB lock while calling this func (nDB *NetworkDB) addNetworkNode(nid string, nodeName string)
{ nodes := nDB.networkNodes[nid] for _, node := range nodes { if node == nodeName { return } } nDB.networkNodes[nid] = append(nDB.networkNodes[nid], nodeName) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
networkdb/networkdb.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/networkdb/networkdb.go#L698-L711
go
train
// Deletes the node from the list of nodes which participate in the // passed network. Caller should hold the NetworkDB lock while calling // this
func (nDB *NetworkDB) deleteNetworkNode(nid string, nodeName string)
// Deletes the node from the list of nodes which participate in the // passed network. Caller should hold the NetworkDB lock while calling // this func (nDB *NetworkDB) deleteNetworkNode(nid string, nodeName string)
{ nodes, ok := nDB.networkNodes[nid] if !ok || len(nodes) == 0 { return } newNodes := make([]string, 0, len(nodes)-1) for _, name := range nodes { if name == nodeName { continue } newNodes = append(newNodes, name) } nDB.networkNodes[nid] = newNodes }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
networkdb/networkdb.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/networkdb/networkdb.go#L715-L729
go
train
// findCommonnetworks find the networks that both this node and the // passed node have joined.
func (nDB *NetworkDB) findCommonNetworks(nodeName string) []string
// findCommonnetworks find the networks that both this node and the // passed node have joined. func (nDB *NetworkDB) findCommonNetworks(nodeName string) []string
{ nDB.RLock() defer nDB.RUnlock() var networks []string for nid := range nDB.networks[nDB.config.NodeID] { if n, ok := nDB.networks[nodeName][nid]; ok { if !n.leaving { networks = append(networks, nid) } } } return networks }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
networkdb/networkdb.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/networkdb/networkdb.go#L743-L754
go
train
// createOrUpdateEntry this function handles the creation or update of entries into the local // tree store. It is also used to keep in sync the entries number of the network (all tables are aggregated)
func (nDB *NetworkDB) createOrUpdateEntry(nid, tname, key string, entry interface{}) (bool, bool)
// createOrUpdateEntry this function handles the creation or update of entries into the local // tree store. It is also used to keep in sync the entries number of the network (all tables are aggregated) func (nDB *NetworkDB) createOrUpdateEntry(nid, tname, key string, entry interface{}) (bool, bool)
{ _, okTable := nDB.indexes[byTable].Insert(fmt.Sprintf("/%s/%s/%s", tname, nid, key), entry) _, okNetwork := nDB.indexes[byNetwork].Insert(fmt.Sprintf("/%s/%s/%s", nid, tname, key), entry) if !okNetwork { // Add only if it is an insert not an update n, ok := nDB.networks[nDB.config.NodeID][nid] if ok { n.entriesNumber++ } } return okTable, okNetwork }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
networkdb/cluster.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/networkdb/cluster.go#L57-L70
go
train
// SetKey adds a new key to the key ring
func (nDB *NetworkDB) SetKey(key []byte)
// SetKey adds a new key to the key ring func (nDB *NetworkDB) SetKey(key []byte)
{ logrus.Debugf("Adding key %.5s", hex.EncodeToString(key)) nDB.Lock() defer nDB.Unlock() for _, dbKey := range nDB.config.Keys { if bytes.Equal(key, dbKey) { return } } nDB.config.Keys = append(nDB.config.Keys, key) if nDB.keyring != nil { nDB.keyring.AddKey(key) } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
networkdb/cluster.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/networkdb/cluster.go#L74-L86
go
train
// SetPrimaryKey sets the given key as the primary key. This should have // been added apriori through SetKey
func (nDB *NetworkDB) SetPrimaryKey(key []byte)
// SetPrimaryKey sets the given key as the primary key. This should have // been added apriori through SetKey func (nDB *NetworkDB) SetPrimaryKey(key []byte)
{ logrus.Debugf("Primary Key %.5s", hex.EncodeToString(key)) nDB.RLock() defer nDB.RUnlock() for _, dbKey := range nDB.config.Keys { if bytes.Equal(key, dbKey) { if nDB.keyring != nil { nDB.keyring.UseKey(dbKey) } break } } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
networkdb/cluster.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/networkdb/cluster.go#L90-L103
go
train
// RemoveKey removes a key from the key ring. The key being removed // can't be the primary key
func (nDB *NetworkDB) RemoveKey(key []byte)
// RemoveKey removes a key from the key ring. The key being removed // can't be the primary key func (nDB *NetworkDB) RemoveKey(key []byte)
{ logrus.Debugf("Remove Key %.5s", hex.EncodeToString(key)) nDB.Lock() defer nDB.Unlock() for i, dbKey := range nDB.config.Keys { if bytes.Equal(key, dbKey) { nDB.config.Keys = append(nDB.config.Keys[:i], nDB.config.Keys[i+1:]...) if nDB.keyring != nil { nDB.keyring.RemoveKey(dbKey) } break } } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
networkdb/cluster.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/networkdb/cluster.go#L284-L330
go
train
// rejoinClusterBootStrap is called periodically to check if all bootStrap nodes are active in the cluster, // if not, call the cluster join to merge 2 separate clusters that are formed when all managers // stopped/started at the same time
func (nDB *NetworkDB) rejoinClusterBootStrap()
// rejoinClusterBootStrap is called periodically to check if all bootStrap nodes are active in the cluster, // if not, call the cluster join to merge 2 separate clusters that are formed when all managers // stopped/started at the same time func (nDB *NetworkDB) rejoinClusterBootStrap()
{ nDB.RLock() if len(nDB.bootStrapIP) == 0 { nDB.RUnlock() return } myself, ok := nDB.nodes[nDB.config.NodeID] if !ok { nDB.RUnlock() logrus.Warnf("rejoinClusterBootstrap unable to find local node info using ID:%v", nDB.config.NodeID) return } bootStrapIPs := make([]string, 0, len(nDB.bootStrapIP)) for _, bootIP := range nDB.bootStrapIP { // botostrap IPs are usually IP:port from the Join var bootstrapIP net.IP ipStr, _, err := net.SplitHostPort(bootIP) if err != nil { // try to parse it as an IP with port // Note this seems to be the case for swarm that do not specify any port ipStr = bootIP } bootstrapIP = net.ParseIP(ipStr) if bootstrapIP != nil { for _, node := range nDB.nodes { if node.Addr.Equal(bootstrapIP) && !node.Addr.Equal(myself.Addr) { // One of the bootstrap nodes (and not myself) is part of the cluster, return nDB.RUnlock() return } } bootStrapIPs = append(bootStrapIPs, bootIP) } } nDB.RUnlock() if len(bootStrapIPs) == 0 { // this will also avoid to call the Join with an empty list erasing the current bootstrap ip list logrus.Debug("rejoinClusterBootStrap did not find any valid IP") return } // None of the bootStrap nodes are in the cluster, call memberlist join logrus.Debugf("rejoinClusterBootStrap, calling cluster join with bootStrap %v", bootStrapIPs) ctx, cancel := context.WithTimeout(nDB.ctx, rejoinClusterDuration) defer cancel() nDB.retryJoin(ctx, bootStrapIPs) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
networkdb/cluster.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/networkdb/cluster.go#L615-L714
go
train
// Bulk sync all the table entries belonging to a set of networks to a // single peer node. It can be unsolicited or can be in response to an // unsolicited bulk sync
func (nDB *NetworkDB) bulkSyncNode(networks []string, node string, unsolicited bool) error
// Bulk sync all the table entries belonging to a set of networks to a // single peer node. It can be unsolicited or can be in response to an // unsolicited bulk sync func (nDB *NetworkDB) bulkSyncNode(networks []string, node string, unsolicited bool) error
{ var msgs [][]byte var unsolMsg string if unsolicited { unsolMsg = "unsolicited" } logrus.Debugf("%v(%v): Initiating %s bulk sync for networks %v with node %s", nDB.config.Hostname, nDB.config.NodeID, unsolMsg, networks, node) nDB.RLock() mnode := nDB.nodes[node] if mnode == nil { nDB.RUnlock() return nil } for _, nid := range networks { nDB.indexes[byNetwork].WalkPrefix(fmt.Sprintf("/%s", nid), func(path string, v interface{}) bool { entry, ok := v.(*entry) if !ok { return false } eType := TableEventTypeCreate if entry.deleting { eType = TableEventTypeDelete } params := strings.Split(path[1:], "/") tEvent := TableEvent{ Type: eType, LTime: entry.ltime, NodeName: entry.node, NetworkID: nid, TableName: params[1], Key: params[2], Value: entry.value, // The duration in second is a float that below would be truncated ResidualReapTime: int32(entry.reapTime.Seconds()), } msg, err := encodeMessage(MessageTypeTableEvent, &tEvent) if err != nil { logrus.Errorf("Encode failure during bulk sync: %#v", tEvent) return false } msgs = append(msgs, msg) return false }) } nDB.RUnlock() // Create a compound message compound := makeCompoundMessage(msgs) bsm := BulkSyncMessage{ LTime: nDB.tableClock.Time(), Unsolicited: unsolicited, NodeName: nDB.config.NodeID, Networks: networks, Payload: compound, } buf, err := encodeMessage(MessageTypeBulkSync, &bsm) if err != nil { return fmt.Errorf("failed to encode bulk sync message: %v", err) } nDB.Lock() ch := make(chan struct{}) nDB.bulkSyncAckTbl[node] = ch nDB.Unlock() err = nDB.memberlist.SendReliable(&mnode.Node, buf) if err != nil { nDB.Lock() delete(nDB.bulkSyncAckTbl, node) nDB.Unlock() return fmt.Errorf("failed to send a TCP message during bulk sync: %v", err) } // Wait on a response only if it is unsolicited. if unsolicited { startTime := time.Now() t := time.NewTimer(30 * time.Second) select { case <-t.C: logrus.Errorf("Bulk sync to node %s timed out", node) case <-ch: logrus.Debugf("%v(%v): Bulk sync to node %s took %s", nDB.config.Hostname, nDB.config.NodeID, node, time.Since(startTime)) } t.Stop() } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
networkdb/cluster.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/networkdb/cluster.go#L717-L729
go
train
// Returns a random offset between 0 and n
func randomOffset(n int) int
// Returns a random offset between 0 and n func randomOffset(n int) int
{ if n == 0 { return 0 } val, err := rand.Int(rand.Reader, big.NewInt(int64(n))) if err != nil { logrus.Errorf("Failed to get a random offset: %v", err) return 0 } return int(val.Int64()) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
networkdb/cluster.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/networkdb/cluster.go#L733-L761
go
train
// mRandomNodes is used to select up to m random nodes. It is possible // that less than m nodes are returned.
func (nDB *NetworkDB) mRandomNodes(m int, nodes []string) []string
// mRandomNodes is used to select up to m random nodes. It is possible // that less than m nodes are returned. func (nDB *NetworkDB) mRandomNodes(m int, nodes []string) []string
{ n := len(nodes) mNodes := make([]string, 0, m) OUTER: // Probe up to 3*n times, with large n this is not necessary // since k << n, but with small n we want search to be // exhaustive for i := 0; i < 3*n && len(mNodes) < m; i++ { // Get random node idx := randomOffset(n) node := nodes[idx] if node == nDB.config.NodeID { continue } // Check if we have this node already for j := 0; j < len(mNodes); j++ { if node == mNodes[j] { continue OUTER } } // Append the node mNodes = append(mNodes, node) } return mNodes }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drvregistry/drvregistry.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drvregistry/drvregistry.go#L58-L68
go
train
// New returns a new driver registry handle.
func New(lDs, gDs interface{}, dfn DriverNotifyFunc, ifn IPAMNotifyFunc, pg plugingetter.PluginGetter) (*DrvRegistry, error)
// New returns a new driver registry handle. func New(lDs, gDs interface{}, dfn DriverNotifyFunc, ifn IPAMNotifyFunc, pg plugingetter.PluginGetter) (*DrvRegistry, error)
{ r := &DrvRegistry{ drivers: make(driverTable), ipamDrivers: make(ipamTable), dfn: dfn, ifn: ifn, pluginGetter: pg, } return r, nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drvregistry/drvregistry.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drvregistry/drvregistry.go#L71-L73
go
train
// AddDriver adds a network driver to the registry.
func (r *DrvRegistry) AddDriver(ntype string, fn InitFunc, config map[string]interface{}) error
// AddDriver adds a network driver to the registry. func (r *DrvRegistry) AddDriver(ntype string, fn InitFunc, config map[string]interface{}) error
{ return fn(r, config) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drvregistry/drvregistry.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drvregistry/drvregistry.go#L76-L94
go
train
// WalkIPAMs walks the IPAM drivers registered in the registry and invokes the passed walk function and each one of them.
func (r *DrvRegistry) WalkIPAMs(ifn IPAMWalkFunc)
// WalkIPAMs walks the IPAM drivers registered in the registry and invokes the passed walk function and each one of them. func (r *DrvRegistry) WalkIPAMs(ifn IPAMWalkFunc)
{ type ipamVal struct { name string data *ipamData } r.Lock() ivl := make([]ipamVal, 0, len(r.ipamDrivers)) for k, v := range r.ipamDrivers { ivl = append(ivl, ipamVal{name: k, data: v}) } r.Unlock() for _, iv := range ivl { if ifn(iv.name, iv.data.driver, iv.data.capability) { break } } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drvregistry/drvregistry.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drvregistry/drvregistry.go#L97-L115
go
train
// WalkDrivers walks the network drivers registered in the registry and invokes the passed walk function and each one of them.
func (r *DrvRegistry) WalkDrivers(dfn DriverWalkFunc)
// WalkDrivers walks the network drivers registered in the registry and invokes the passed walk function and each one of them. func (r *DrvRegistry) WalkDrivers(dfn DriverWalkFunc)
{ type driverVal struct { name string data *driverData } r.Lock() dvl := make([]driverVal, 0, len(r.drivers)) for k, v := range r.drivers { dvl = append(dvl, driverVal{name: k, data: v}) } r.Unlock() for _, dv := range dvl { if dfn(dv.name, dv.data.driver, dv.data.capability) { break } } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drvregistry/drvregistry.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drvregistry/drvregistry.go#L118-L128
go
train
// Driver returns the actual network driver instance and its capability which registered with the passed name.
func (r *DrvRegistry) Driver(name string) (driverapi.Driver, *driverapi.Capability)
// Driver returns the actual network driver instance and its capability which registered with the passed name. func (r *DrvRegistry) Driver(name string) (driverapi.Driver, *driverapi.Capability)
{ r.Lock() defer r.Unlock() d, ok := r.drivers[name] if !ok { return nil, nil } return d.driver, &d.capability }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drvregistry/drvregistry.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drvregistry/drvregistry.go#L131-L141
go
train
// IPAM returns the actual IPAM driver instance and its capability which registered with the passed name.
func (r *DrvRegistry) IPAM(name string) (ipamapi.Ipam, *ipamapi.Capability)
// IPAM returns the actual IPAM driver instance and its capability which registered with the passed name. func (r *DrvRegistry) IPAM(name string) (ipamapi.Ipam, *ipamapi.Capability)
{ r.Lock() defer r.Unlock() i, ok := r.ipamDrivers[name] if !ok { return nil, nil } return i.driver, i.capability }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drvregistry/drvregistry.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drvregistry/drvregistry.go#L144-L154
go
train
// IPAMDefaultAddressSpaces returns the default address space strings for the passed IPAM driver name.
func (r *DrvRegistry) IPAMDefaultAddressSpaces(name string) (string, string, error)
// IPAMDefaultAddressSpaces returns the default address space strings for the passed IPAM driver name. func (r *DrvRegistry) IPAMDefaultAddressSpaces(name string) (string, string, error)
{ r.Lock() defer r.Unlock() i, ok := r.ipamDrivers[name] if !ok { return "", "", fmt.Errorf("ipam %s not found", name) } return i.defaultLocalAddressSpace, i.defaultGlobalAddressSpace, nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drvregistry/drvregistry.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drvregistry/drvregistry.go#L162-L188
go
train
// RegisterDriver registers the network driver when it gets discovered.
func (r *DrvRegistry) RegisterDriver(ntype string, driver driverapi.Driver, capability driverapi.Capability) error
// RegisterDriver registers the network driver when it gets discovered. func (r *DrvRegistry) RegisterDriver(ntype string, driver driverapi.Driver, capability driverapi.Capability) error
{ if strings.TrimSpace(ntype) == "" { return errors.New("network type string cannot be empty") } r.Lock() dd, ok := r.drivers[ntype] r.Unlock() if ok && dd.driver.IsBuiltIn() { return driverapi.ErrActiveRegistration(ntype) } if r.dfn != nil { if err := r.dfn(ntype, driver, capability); err != nil { return err } } dData := &driverData{driver, capability} r.Lock() r.drivers[ntype] = dData r.Unlock() return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drvregistry/drvregistry.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drvregistry/drvregistry.go#L221-L223
go
train
// RegisterIpamDriver registers the IPAM driver discovered with default capabilities.
func (r *DrvRegistry) RegisterIpamDriver(name string, driver ipamapi.Ipam) error
// RegisterIpamDriver registers the IPAM driver discovered with default capabilities. func (r *DrvRegistry) RegisterIpamDriver(name string, driver ipamapi.Ipam) error
{ return r.registerIpamDriver(name, driver, &ipamapi.Capability{}) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drvregistry/drvregistry.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drvregistry/drvregistry.go#L226-L228
go
train
// RegisterIpamDriverWithCapabilities registers the IPAM driver discovered with specified capabilities.
func (r *DrvRegistry) RegisterIpamDriverWithCapabilities(name string, driver ipamapi.Ipam, caps *ipamapi.Capability) error
// RegisterIpamDriverWithCapabilities registers the IPAM driver discovered with specified capabilities. func (r *DrvRegistry) RegisterIpamDriverWithCapabilities(name string, driver ipamapi.Ipam, caps *ipamapi.Capability) error
{ return r.registerIpamDriver(name, driver, caps) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drivers/bridge/netlink_deprecated_linux.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/bridge/netlink_deprecated_linux.go#L35-L49
go
train
// THIS CODE DOES NOT COMMUNICATE WITH KERNEL VIA RTNETLINK INTERFACE // IT IS HERE FOR BACKWARDS COMPATIBILITY WITH OLDER LINUX KERNELS // WHICH SHIP WITH OLDER NOT ENTIRELY FUNCTIONAL VERSION OF NETLINK
func getIfSocket() (fd int, err error)
// THIS CODE DOES NOT COMMUNICATE WITH KERNEL VIA RTNETLINK INTERFACE // IT IS HERE FOR BACKWARDS COMPATIBILITY WITH OLDER LINUX KERNELS // WHICH SHIP WITH OLDER NOT ENTIRELY FUNCTIONAL VERSION OF NETLINK func getIfSocket() (fd int, err error)
{ for _, socket := range []int{ syscall.AF_INET, syscall.AF_PACKET, syscall.AF_INET6, } { if fd, err = syscall.Socket(socket, syscall.SOCK_DGRAM, 0); err == nil { break } } if err == nil { return fd, nil } return -1, err }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drivers/bridge/netlink_deprecated_linux.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/bridge/netlink_deprecated_linux.go#L75-L77
go
train
// Add a slave to a bridge device. This is more backward-compatible than // netlink.NetworkSetMaster and works on RHEL 6.
func ioctlAddToBridge(iface, master *net.Interface) error
// Add a slave to a bridge device. This is more backward-compatible than // netlink.NetworkSetMaster and works on RHEL 6. func ioctlAddToBridge(iface, master *net.Interface) error
{ return ifIoctBridge(iface, master, ioctlBrAddIf) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
cmd/dnet/dnet.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/cmd/dnet/dnet.go#L72-L83
go
train
// ParseConfig parses the libnetwork configuration file
func (d *dnetConnection) parseOrchestrationConfig(tomlCfgFile string) error
// ParseConfig parses the libnetwork configuration file func (d *dnetConnection) parseOrchestrationConfig(tomlCfgFile string) error
{ dummy := &dnetConnection{} if _, err := toml.DecodeFile(tomlCfgFile, dummy); err != nil { return err } if dummy.Orchestration != nil { d.Orchestration = dummy.Orchestration } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
sandbox.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/sandbox.go#L1001-L1015
go
train
// joinLeaveStart waits to ensure there are no joins or leaves in progress and // marks this join/leave in progress without race
func (sb *sandbox) joinLeaveStart()
// joinLeaveStart waits to ensure there are no joins or leaves in progress and // marks this join/leave in progress without race func (sb *sandbox) joinLeaveStart()
{ sb.Lock() defer sb.Unlock() for sb.joinLeaveDone != nil { joinLeaveDone := sb.joinLeaveDone sb.Unlock() <-joinLeaveDone sb.Lock() } sb.joinLeaveDone = make(chan struct{}) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
sandbox.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/sandbox.go#L1019-L1027
go
train
// joinLeaveEnd marks the end of this join/leave operation and // signals the same without race to other join and leave waiters
func (sb *sandbox) joinLeaveEnd()
// joinLeaveEnd marks the end of this join/leave operation and // signals the same without race to other join and leave waiters func (sb *sandbox) joinLeaveEnd()
{ sb.Lock() defer sb.Unlock() if sb.joinLeaveDone != nil { close(sb.joinLeaveDone) sb.joinLeaveDone = nil } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
sandbox.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/sandbox.go#L1038-L1042
go
train
// OptionHostname function returns an option setter for hostname option to // be passed to NewSandbox method.
func OptionHostname(name string) SandboxOption
// OptionHostname function returns an option setter for hostname option to // be passed to NewSandbox method. func OptionHostname(name string) SandboxOption
{ return func(sb *sandbox) { sb.config.hostName = name } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
sandbox.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/sandbox.go#L1046-L1050
go
train
// OptionDomainname function returns an option setter for domainname option to // be passed to NewSandbox method.
func OptionDomainname(name string) SandboxOption
// OptionDomainname function returns an option setter for domainname option to // be passed to NewSandbox method. func OptionDomainname(name string) SandboxOption
{ return func(sb *sandbox) { sb.config.domainName = name } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
sandbox.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/sandbox.go#L1054-L1058
go
train
// OptionHostsPath function returns an option setter for hostspath option to // be passed to NewSandbox method.
func OptionHostsPath(path string) SandboxOption
// OptionHostsPath function returns an option setter for hostspath option to // be passed to NewSandbox method. func OptionHostsPath(path string) SandboxOption
{ return func(sb *sandbox) { sb.config.hostsPath = path } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
sandbox.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/sandbox.go#L1062-L1066
go
train
// OptionOriginHostsPath function returns an option setter for origin hosts file path // to be passed to NewSandbox method.
func OptionOriginHostsPath(path string) SandboxOption
// OptionOriginHostsPath function returns an option setter for origin hosts file path // to be passed to NewSandbox method. func OptionOriginHostsPath(path string) SandboxOption
{ return func(sb *sandbox) { sb.config.originHostsPath = path } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
sandbox.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/sandbox.go#L1070-L1074
go
train
// OptionExtraHost function returns an option setter for extra /etc/hosts options // which is a name and IP as strings.
func OptionExtraHost(name string, IP string) SandboxOption
// OptionExtraHost function returns an option setter for extra /etc/hosts options // which is a name and IP as strings. func OptionExtraHost(name string, IP string) SandboxOption
{ return func(sb *sandbox) { sb.config.extraHosts = append(sb.config.extraHosts, extraHost{name: name, IP: IP}) } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
sandbox.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/sandbox.go#L1078-L1082
go
train
// OptionParentUpdate function returns an option setter for parent container // which needs to update the IP address for the linked container.
func OptionParentUpdate(cid string, name, ip string) SandboxOption
// OptionParentUpdate function returns an option setter for parent container // which needs to update the IP address for the linked container. func OptionParentUpdate(cid string, name, ip string) SandboxOption
{ return func(sb *sandbox) { sb.config.parentUpdates = append(sb.config.parentUpdates, parentUpdate{cid: cid, name: name, ip: ip}) } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
sandbox.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/sandbox.go#L1086-L1090
go
train
// OptionResolvConfPath function returns an option setter for resolvconfpath option to // be passed to net container methods.
func OptionResolvConfPath(path string) SandboxOption
// OptionResolvConfPath function returns an option setter for resolvconfpath option to // be passed to net container methods. func OptionResolvConfPath(path string) SandboxOption
{ return func(sb *sandbox) { sb.config.resolvConfPath = path } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
sandbox.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/sandbox.go#L1094-L1098
go
train
// OptionOriginResolvConfPath function returns an option setter to set the path to the // origin resolv.conf file to be passed to net container methods.
func OptionOriginResolvConfPath(path string) SandboxOption
// OptionOriginResolvConfPath function returns an option setter to set the path to the // origin resolv.conf file to be passed to net container methods. func OptionOriginResolvConfPath(path string) SandboxOption
{ return func(sb *sandbox) { sb.config.originResolvConfPath = path } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
sandbox.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/sandbox.go#L1102-L1106
go
train
// OptionDNS function returns an option setter for dns entry option to // be passed to container Create method.
func OptionDNS(dns string) SandboxOption
// OptionDNS function returns an option setter for dns entry option to // be passed to container Create method. func OptionDNS(dns string) SandboxOption
{ return func(sb *sandbox) { sb.config.dnsList = append(sb.config.dnsList, dns) } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
sandbox.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/sandbox.go#L1110-L1114
go
train
// OptionDNSSearch function returns an option setter for dns search entry option to // be passed to container Create method.
func OptionDNSSearch(search string) SandboxOption
// OptionDNSSearch function returns an option setter for dns search entry option to // be passed to container Create method. func OptionDNSSearch(search string) SandboxOption
{ return func(sb *sandbox) { sb.config.dnsSearchList = append(sb.config.dnsSearchList, search) } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
sandbox.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/sandbox.go#L1118-L1122
go
train
// OptionDNSOptions function returns an option setter for dns options entry option to // be passed to container Create method.
func OptionDNSOptions(options string) SandboxOption
// OptionDNSOptions function returns an option setter for dns options entry option to // be passed to container Create method. func OptionDNSOptions(options string) SandboxOption
{ return func(sb *sandbox) { sb.config.dnsOptionsList = append(sb.config.dnsOptionsList, options) } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
sandbox.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/sandbox.go#L1143-L1152
go
train
// OptionGeneric function returns an option setter for Generic configuration // that is not managed by libNetwork but can be used by the Drivers during the call to // net container creation method. Container Labels are a good example.
func OptionGeneric(generic map[string]interface{}) SandboxOption
// OptionGeneric function returns an option setter for Generic configuration // that is not managed by libNetwork but can be used by the Drivers during the call to // net container creation method. Container Labels are a good example. func OptionGeneric(generic map[string]interface{}) SandboxOption
{ return func(sb *sandbox) { if sb.config.generic == nil { sb.config.generic = make(map[string]interface{}, len(generic)) } for k, v := range generic { sb.config.generic[k] = v } } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
sandbox.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/sandbox.go#L1156-L1168
go
train
// OptionExposedPorts function returns an option setter for the container exposed // ports option to be passed to container Create method.
func OptionExposedPorts(exposedPorts []types.TransportPort) SandboxOption
// OptionExposedPorts function returns an option setter for the container exposed // ports option to be passed to container Create method. func OptionExposedPorts(exposedPorts []types.TransportPort) SandboxOption
{ return func(sb *sandbox) { if sb.config.generic == nil { sb.config.generic = make(map[string]interface{}) } // Defensive copy eps := make([]types.TransportPort, len(exposedPorts)) copy(eps, exposedPorts) // Store endpoint label and in generic because driver needs it sb.config.exposedPorts = eps sb.config.generic[netlabel.ExposedPorts] = eps } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
sandbox.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/sandbox.go#L1172-L1182
go
train
// OptionPortMapping function returns an option setter for the mapping // ports option to be passed to container Create method.
func OptionPortMapping(portBindings []types.PortBinding) SandboxOption
// OptionPortMapping function returns an option setter for the mapping // ports option to be passed to container Create method. func OptionPortMapping(portBindings []types.PortBinding) SandboxOption
{ return func(sb *sandbox) { if sb.config.generic == nil { sb.config.generic = make(map[string]interface{}) } // Store a copy of the bindings as generic data to pass to the driver pbs := make([]types.PortBinding, len(portBindings)) copy(pbs, portBindings) sb.config.generic[netlabel.PortMap] = pbs } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
sandbox.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/sandbox.go#L1186-L1191
go
train
// OptionIngress function returns an option setter for marking a // sandbox as the controller's ingress sandbox.
func OptionIngress() SandboxOption
// OptionIngress function returns an option setter for marking a // sandbox as the controller's ingress sandbox. func OptionIngress() SandboxOption
{ return func(sb *sandbox) { sb.ingress = true sb.oslTypes = append(sb.oslTypes, osl.SandboxTypeIngress) } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
sandbox.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/sandbox.go#L1195-L1200
go
train
// OptionLoadBalancer function returns an option setter for marking a // sandbox as a load balancer sandbox.
func OptionLoadBalancer(nid string) SandboxOption
// OptionLoadBalancer function returns an option setter for marking a // sandbox as a load balancer sandbox. func OptionLoadBalancer(nid string) SandboxOption
{ return func(sb *sandbox) { sb.loadBalancerNID = nid sb.oslTypes = append(sb.oslTypes, osl.SandboxTypeLoadBalancer) } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
sandbox.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/sandbox.go#L1208-L1265
go
train
// <=> Returns true if a < b, false if a > b and advances to next level if a == b // epi.prio <=> epj.prio # 2 < 1 // epi.gw <=> epj.gw # non-gw < gw // epi.internal <=> epj.internal # non-internal < internal // epi.joininfo <=> epj.joininfo # ipv6 < ipv4 // epi.name <=> epj.name # bar < foo
func (epi *endpoint) Less(epj *endpoint) bool
// <=> Returns true if a < b, false if a > b and advances to next level if a == b // epi.prio <=> epj.prio # 2 < 1 // epi.gw <=> epj.gw # non-gw < gw // epi.internal <=> epj.internal # non-internal < internal // epi.joininfo <=> epj.joininfo # ipv6 < ipv4 // epi.name <=> epj.name # bar < foo func (epi *endpoint) Less(epj *endpoint) bool
{ var ( prioi, prioj int ) sbi, _ := epi.getSandbox() sbj, _ := epj.getSandbox() // Prio defaults to 0 if sbi != nil { prioi = sbi.epPriority[epi.ID()] } if sbj != nil { prioj = sbj.epPriority[epj.ID()] } if prioi != prioj { return prioi > prioj } gwi := epi.endpointInGWNetwork() gwj := epj.endpointInGWNetwork() if gwi != gwj { return gwj } inti := epi.getNetwork().Internal() intj := epj.getNetwork().Internal() if inti != intj { return intj } jii := 0 if epi.joinInfo != nil { if epi.joinInfo.gw != nil { jii = jii + 1 } if epi.joinInfo.gw6 != nil { jii = jii + 2 } } jij := 0 if epj.joinInfo != nil { if epj.joinInfo.gw != nil { jij = jij + 1 } if epj.joinInfo.gw6 != nil { jij = jij + 2 } } if jii != jij { return jii > jij } return epi.network.Name() < epj.network.Name() }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
cmd/dnet/dnet_windows.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/cmd/dnet/dnet_windows.go#L13-L27
go
train
// Copied over from docker/daemon/debugtrap_windows.go
func setupDumpStackTrap()
// Copied over from docker/daemon/debugtrap_windows.go func setupDumpStackTrap()
{ go func() { sa := windows.SecurityAttributes{ Length: 0, } ev, _ := windows.UTF16PtrFromString("Global\\docker-daemon-" + fmt.Sprint(os.Getpid())) if h, _ := windows.CreateEvent(&sa, 0, 0, ev); h != 0 { logrus.Debugf("Stackdump - waiting signal at %s", ev) for { windows.WaitForSingleObject(h, windows.INFINITE) signal.DumpStacks("") } } }() }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
ns/init_linux.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ns/init_linux.go#L26-L40
go
train
// Init initializes a new network namespace
func Init()
// Init initializes a new network namespace func Init()
{ var err error initNs, err = netns.Get() if err != nil { logrus.Errorf("could not get initial namespace: %v", err) } initNl, err = netlink.NewHandle(getSupportedNlFamilies()...) if err != nil { logrus.Errorf("could not create netlink handle on initial namespace: %v", err) } err = initNl.SetSocketTimeout(NetlinkSocketsTimeout) if err != nil { logrus.Warnf("Failed to set the timeout on the default netlink handle sockets: %v", err) } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
ns/init_linux.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ns/init_linux.go#L43-L53
go
train
// SetNamespace sets the initial namespace handler
func SetNamespace() error
// SetNamespace sets the initial namespace handler func SetNamespace() error
{ initOnce.Do(Init) if err := netns.Set(initNs); err != nil { linkInfo, linkErr := getLink() if linkErr != nil { linkInfo = linkErr.Error() } return fmt.Errorf("failed to set to initial namespace, %v, initns fd %d: %v", linkInfo, initNs, err) } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
ns/init_linux.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ns/init_linux.go#L113-L120
go
train
// API check on required xfrm modules (xfrm_user, xfrm_algo)
func checkXfrmSocket() error
// API check on required xfrm modules (xfrm_user, xfrm_algo) func checkXfrmSocket() error
{ fd, err := syscall.Socket(syscall.AF_NETLINK, syscall.SOCK_RAW, syscall.NETLINK_XFRM) if err != nil { return err } syscall.Close(fd) return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
ns/init_linux.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ns/init_linux.go#L133-L140
go
train
// API check on required nf_conntrack* modules (nf_conntrack, nf_conntrack_netlink)
func checkNfSocket() error
// API check on required nf_conntrack* modules (nf_conntrack, nf_conntrack_netlink) func checkNfSocket() error
{ fd, err := syscall.Socket(syscall.AF_NETLINK, syscall.SOCK_RAW, syscall.NETLINK_NETFILTER) if err != nil { return err } syscall.Close(fd) return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
osl/route_linux.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/osl/route_linux.go#L114-L126
go
train
// Program a route in to the namespace routing table.
func (n *networkNamespace) programRoute(path string, dest *net.IPNet, nh net.IP) error
// Program a route in to the namespace routing table. func (n *networkNamespace) programRoute(path string, dest *net.IPNet, nh net.IP) error
{ gwRoutes, err := n.nlHandle.RouteGet(nh) if err != nil { return fmt.Errorf("route for the next hop %s could not be found: %v", nh, err) } return n.nlHandle.RouteAdd(&netlink.Route{ Scope: netlink.SCOPE_UNIVERSE, LinkIndex: gwRoutes[0].LinkIndex, Gw: nh, Dst: dest, }) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
cmd/proxy/sctp_proxy.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/cmd/proxy/sctp_proxy.go#L21-L33
go
train
// NewSCTPProxy creates a new SCTPProxy.
func NewSCTPProxy(frontendAddr, backendAddr *sctp.SCTPAddr) (*SCTPProxy, error)
// NewSCTPProxy creates a new SCTPProxy. func NewSCTPProxy(frontendAddr, backendAddr *sctp.SCTPAddr) (*SCTPProxy, error)
{ listener, err := sctp.ListenSCTP("sctp", frontendAddr) if err != nil { return nil, err } // If the port in frontendAddr was 0 then ListenSCTP will have a picked // a port to listen on, hence the call to Addr to get that actual port: return &SCTPProxy{ listener: listener, frontendAddr: listener.Addr().(*sctp.SCTPAddr), backendAddr: backendAddr, }, nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
cmd/proxy/sctp_proxy.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/cmd/proxy/sctp_proxy.go#L73-L84
go
train
// Run starts forwarding the traffic using SCTP.
func (proxy *SCTPProxy) Run()
// Run starts forwarding the traffic using SCTP. func (proxy *SCTPProxy) Run()
{ quit := make(chan bool) defer close(quit) for { client, err := proxy.listener.Accept() if err != nil { log.Printf("Stopping proxy on sctp/%v for sctp/%v (%s)", proxy.frontendAddr, proxy.backendAddr, err) return } go proxy.clientLoop(client.(*sctp.SCTPConn), quit) } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drivers/windows/port_mapping.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/windows/port_mapping.go#L29-L43
go
train
// AllocatePorts allocates ports specified in bindings from the portMapper
func AllocatePorts(portMapper *portmapper.PortMapper, bindings []types.PortBinding, containerIP net.IP) ([]types.PortBinding, error)
// AllocatePorts allocates ports specified in bindings from the portMapper func AllocatePorts(portMapper *portmapper.PortMapper, bindings []types.PortBinding, containerIP net.IP) ([]types.PortBinding, error)
{ bs := make([]types.PortBinding, 0, len(bindings)) for _, c := range bindings { b := c.GetCopy() if err := allocatePort(portMapper, &b, containerIP); err != nil { // On allocation failure, release previously allocated ports. On cleanup error, just log a warning message if cuErr := ReleasePorts(portMapper, bs); cuErr != nil { logrus.Warnf("Upon allocation failure for %v, failed to clear previously allocated port bindings: %v", b, cuErr) } return nil, err } bs = append(bs, b) } return bs, nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drivers/windows/port_mapping.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/windows/port_mapping.go#L102-L116
go
train
// ReleasePorts releases ports specified in bindings from the portMapper
func ReleasePorts(portMapper *portmapper.PortMapper, bindings []types.PortBinding) error
// ReleasePorts releases ports specified in bindings from the portMapper func ReleasePorts(portMapper *portmapper.PortMapper, bindings []types.PortBinding) error
{ var errorBuf bytes.Buffer // Attempt to release all port bindings, do not stop on failure for _, m := range bindings { if err := releasePort(portMapper, m); err != nil { errorBuf.WriteString(fmt.Sprintf("\ncould not release %v because of %v", m, err)) } } if errorBuf.Len() != 0 { return errors.New(errorBuf.String()) } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
api/api.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/api/api.go#L60-L64
go
train
// NewHTTPHandler creates and initialize the HTTP handler to serve the requests for libnetwork
func NewHTTPHandler(c libnetwork.NetworkController) func(w http.ResponseWriter, req *http.Request)
// NewHTTPHandler creates and initialize the HTTP handler to serve the requests for libnetwork func NewHTTPHandler(c libnetwork.NetworkController) func(w http.ResponseWriter, req *http.Request)
{ h := &httpHandler{c: c} h.initRouter() return h.handleRequest }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
api/api.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/api/api.go#L184-L198
go
train
/***************** Resource Builders ******************/
func buildNetworkResource(nw libnetwork.Network) *networkResource
/***************** Resource Builders ******************/ func buildNetworkResource(nw libnetwork.Network) *networkResource
{ r := &networkResource{} if nw != nil { r.Name = nw.Name() r.ID = nw.ID() r.Type = nw.Type() epl := nw.Endpoints() r.Endpoints = make([]*endpointResource, 0, len(epl)) for _, e := range epl { epr := buildEndpointResource(e) r.Endpoints = append(r.Endpoints, epr) } } return r }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
api/api.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/api/api.go#L224-L261
go
train
/**************** Options Parsers *****************/
func (sc *sandboxCreate) parseOptions() []libnetwork.SandboxOption
/**************** Options Parsers *****************/ func (sc *sandboxCreate) parseOptions() []libnetwork.SandboxOption
{ var setFctList []libnetwork.SandboxOption if sc.HostName != "" { setFctList = append(setFctList, libnetwork.OptionHostname(sc.HostName)) } if sc.DomainName != "" { setFctList = append(setFctList, libnetwork.OptionDomainname(sc.DomainName)) } if sc.HostsPath != "" { setFctList = append(setFctList, libnetwork.OptionHostsPath(sc.HostsPath)) } if sc.ResolvConfPath != "" { setFctList = append(setFctList, libnetwork.OptionResolvConfPath(sc.ResolvConfPath)) } if sc.UseDefaultSandbox { setFctList = append(setFctList, libnetwork.OptionUseDefaultSandbox()) } if sc.UseExternalKey { setFctList = append(setFctList, libnetwork.OptionUseExternalKey()) } if sc.DNS != nil { for _, d := range sc.DNS { setFctList = append(setFctList, libnetwork.OptionDNS(d)) } } if sc.ExtraHosts != nil { for _, e := range sc.ExtraHosts { setFctList = append(setFctList, libnetwork.OptionExtraHost(e.Name, e.Address)) } } if sc.ExposedPorts != nil { setFctList = append(setFctList, libnetwork.OptionExposedPorts(sc.ExposedPorts)) } if sc.PortMapping != nil { setFctList = append(setFctList, libnetwork.OptionPortMapping(sc.PortMapping)) } return setFctList }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
api/api.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/api/api.go#L272-L276
go
train
/****************** Process functions *******************/
func processCreateDefaults(c libnetwork.NetworkController, nc *networkCreate)
/****************** Process functions *******************/ func processCreateDefaults(c libnetwork.NetworkController, nc *networkCreate)
{ if nc.NetworkType == "" { nc.NetworkType = c.Config().Daemon.DefaultDriver } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
api/api.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/api/api.go#L281-L326
go
train
/*************************** NetworkController interface ****************************/
func procCreateNetwork(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus)
/*************************** NetworkController interface ****************************/ func procCreateNetwork(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus)
{ var create networkCreate err := json.Unmarshal(body, &create) if err != nil { return nil, &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest} } processCreateDefaults(c, &create) options := []libnetwork.NetworkOption{} if val, ok := create.NetworkOpts[netlabel.Internal]; ok { internal, err := strconv.ParseBool(val) if err != nil { return nil, &responseStatus{Status: err.Error(), StatusCode: http.StatusBadRequest} } if internal { options = append(options, libnetwork.NetworkOptionInternalNetwork()) } } if val, ok := create.NetworkOpts[netlabel.EnableIPv6]; ok { enableIPv6, err := strconv.ParseBool(val) if err != nil { return nil, &responseStatus{Status: err.Error(), StatusCode: http.StatusBadRequest} } options = append(options, libnetwork.NetworkOptionEnableIPv6(enableIPv6)) } if len(create.DriverOpts) > 0 { options = append(options, libnetwork.NetworkOptionDriverOpts(create.DriverOpts)) } if len(create.IPv4Conf) > 0 { ipamV4Conf := &libnetwork.IpamConf{ PreferredPool: create.IPv4Conf[0].PreferredPool, SubPool: create.IPv4Conf[0].SubPool, } options = append(options, libnetwork.NetworkOptionIpam("default", "", []*libnetwork.IpamConf{ipamV4Conf}, nil, nil)) } nw, err := c.NewNetwork(create.NetworkType, create.Name, create.ID, options...) if err != nil { return nil, convertNetworkError(err) } return nw.ID(), &createdResponse }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
api/api.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/api/api.go#L388-L413
go
train
/****************** Network interface *******************/
func procCreateEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus)
/****************** Network interface *******************/ func procCreateEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus)
{ var ec endpointCreate err := json.Unmarshal(body, &ec) if err != nil { return "", &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest} } nwT, nwBy := detectNetworkTarget(vars) n, errRsp := findNetwork(c, nwT, nwBy) if !errRsp.isOK() { return "", errRsp } var setFctList []libnetwork.EndpointOption for _, str := range ec.MyAliases { setFctList = append(setFctList, libnetwork.CreateOptionMyAlias(str)) } ep, err := n.CreateEndpoint(ec.Name, setFctList...) if err != nil { return "", convertNetworkError(err) } return ep.ID(), &createdResponse }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
api/api.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/api/api.go#L486-L520
go
train
/****************** Endpoint interface *******************/
func procJoinEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus)
/****************** Endpoint interface *******************/ func procJoinEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus)
{ var ej endpointJoin var setFctList []libnetwork.EndpointOption err := json.Unmarshal(body, &ej) if err != nil { return nil, &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest} } nwT, nwBy := detectNetworkTarget(vars) epT, epBy := detectEndpointTarget(vars) ep, errRsp := findEndpoint(c, nwT, epT, nwBy, epBy) if !errRsp.isOK() { return nil, errRsp } sb, errRsp := findSandbox(c, ej.SandboxID, byID) if !errRsp.isOK() { return nil, errRsp } for _, str := range ej.Aliases { name, alias, err := netutils.ParseAlias(str) if err != nil { return "", convertNetworkError(err) } setFctList = append(setFctList, libnetwork.CreateOptionAlias(name, alias)) } err = ep.Join(sb, setFctList...) if err != nil { return nil, convertNetworkError(err) } return sb.Key(), &successResponse }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
api/api.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/api/api.go#L564-L620
go
train
/****************** Service interface *******************/
func procGetServices(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus)
/****************** Service interface *******************/ func procGetServices(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus)
{ // Look for query filters and validate nwName, filterByNwName := vars[urlNwName] svName, queryBySvName := vars[urlEpName] shortID, queryBySvPID := vars[urlEpPID] if filterByNwName && queryBySvName || filterByNwName && queryBySvPID || queryBySvName && queryBySvPID { return nil, &badQueryResponse } var list []*endpointResource switch { case filterByNwName: // return all service present on the specified network nw, errRsp := findNetwork(c, nwName, byName) if !errRsp.isOK() { return list, &successResponse } for _, ep := range nw.Endpoints() { epr := buildEndpointResource(ep) list = append(list, epr) } case queryBySvName: // Look in each network for the service with the specified name l := func(ep libnetwork.Endpoint) bool { if ep.Name() == svName { list = append(list, buildEndpointResource(ep)) return true } return false } for _, nw := range c.Networks() { nw.WalkEndpoints(l) } case queryBySvPID: // Return all the prefix-matching services l := func(ep libnetwork.Endpoint) bool { if strings.HasPrefix(ep.ID(), shortID) { list = append(list, buildEndpointResource(ep)) } return false } for _, nw := range c.Networks() { nw.WalkEndpoints(l) } default: for _, nw := range c.Networks() { for _, ep := range nw.Endpoints() { epr := buildEndpointResource(ep) list = append(list, epr) } } } return list, &successResponse }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
api/api.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/api/api.go#L737-L752
go
train
/****************** Sandbox interface *******************/
func procGetSandbox(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus)
/****************** Sandbox interface *******************/ func procGetSandbox(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus)
{ if epT, ok := vars[urlEpID]; ok { sv, errRsp := findService(c, epT, byID) if !errRsp.isOK() { return nil, endpointToService(errRsp) } return buildSandboxResource(sv.Info().Sandbox()), &successResponse } sbT, by := detectSandboxTarget(vars) sb, errRsp := findSandbox(c, sbT, by) if !errRsp.isOK() { return nil, errRsp } return buildSandboxResource(sb), &successResponse }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
sandbox_externalkey_unix.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/sandbox_externalkey_unix.go#L31-L64
go
train
// processSetKeyReexec is a private function that must be called only on an reexec path // It expects 3 args { [0] = "libnetwork-setkey", [1] = <container-id>, [2] = <controller-id> } // It also expects specs.State as a json string in <stdin> // Refer to https://github.com/opencontainers/runc/pull/160/ for more information // The docker exec-root can be specified as "-exec-root" flag. The default value is "/run/docker".
func processSetKeyReexec()
// processSetKeyReexec is a private function that must be called only on an reexec path // It expects 3 args { [0] = "libnetwork-setkey", [1] = <container-id>, [2] = <controller-id> } // It also expects specs.State as a json string in <stdin> // Refer to https://github.com/opencontainers/runc/pull/160/ for more information // The docker exec-root can be specified as "-exec-root" flag. The default value is "/run/docker". func processSetKeyReexec()
{ var err error // Return a failure to the calling process via ExitCode defer func() { if err != nil { logrus.Fatalf("%v", err) } }() execRoot := flag.String("exec-root", defaultExecRoot, "docker exec root") flag.Parse() // expecting 3 os.Args {[0]="libnetwork-setkey", [1]=<container-id>, [2]=<controller-id> } // (i.e. expecting 2 flag.Args()) args := flag.Args() if len(args) < 2 { err = fmt.Errorf("Re-exec expects 2 args (after parsing flags), received : %d", len(args)) return } containerID, controllerID := args[0], args[1] // We expect specs.State as a json string in <stdin> stateBuf, err := ioutil.ReadAll(os.Stdin) if err != nil { return } var state specs.State if err = json.Unmarshal(stateBuf, &state); err != nil { return } err = SetExternalKey(controllerID, containerID, fmt.Sprintf("/proc/%d/ns/net", state.Pid), *execRoot) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
sandbox_externalkey_unix.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/sandbox_externalkey_unix.go#L67-L83
go
train
// SetExternalKey provides a convenient way to set an External key to a sandbox
func SetExternalKey(controllerID string, containerID string, key string, execRoot string) error
// SetExternalKey provides a convenient way to set an External key to a sandbox func SetExternalKey(controllerID string, containerID string, key string, execRoot string) error
{ keyData := setKeyData{ ContainerID: containerID, Key: key} uds := filepath.Join(execRoot, execSubdir, controllerID+".sock") c, err := net.Dial("unix", uds) if err != nil { return err } defer c.Close() if err = sendKey(c, keyData); err != nil { return fmt.Errorf("sendKey failed with : %v", err) } return processReturn(c) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
networkdb/nodemgmt.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/networkdb/nodemgmt.go#L28-L39
go
train
// findNode search the node into the 3 node lists and returns the node pointer and the list // where it got found
func (nDB *NetworkDB) findNode(nodeName string) (*node, nodeState, map[string]*node)
// findNode search the node into the 3 node lists and returns the node pointer and the list // where it got found func (nDB *NetworkDB) findNode(nodeName string) (*node, nodeState, map[string]*node)
{ for i, nodes := range []map[string]*node{ nDB.nodes, nDB.leftNodes, nDB.failedNodes, } { if n, ok := nodes[nodeName]; ok { return n, nodeState(i), nodes } } return nil, nodeNotFound, nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
networkdb/nodemgmt.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/networkdb/nodemgmt.go#L44-L92
go
train
// changeNodeState changes the state of the node specified, returns true if the node was moved, // false if there was no need to change the node state. Error will be returned if the node does not // exists
func (nDB *NetworkDB) changeNodeState(nodeName string, newState nodeState) (bool, error)
// changeNodeState changes the state of the node specified, returns true if the node was moved, // false if there was no need to change the node state. Error will be returned if the node does not // exists func (nDB *NetworkDB) changeNodeState(nodeName string, newState nodeState) (bool, error)
{ n, currState, m := nDB.findNode(nodeName) if n == nil { return false, fmt.Errorf("node %s not found", nodeName) } switch newState { case nodeActiveState: if currState == nodeActiveState { return false, nil } delete(m, nodeName) // reset the node reap time n.reapTime = 0 nDB.nodes[nodeName] = n case nodeLeftState: if currState == nodeLeftState { return false, nil } delete(m, nodeName) nDB.leftNodes[nodeName] = n case nodeFailedState: if currState == nodeFailedState { return false, nil } delete(m, nodeName) nDB.failedNodes[nodeName] = n } logrus.Infof("Node %s change state %s --> %s", nodeName, nodeStateName[currState], nodeStateName[newState]) if newState == nodeLeftState || newState == nodeFailedState { // set the node reap time, if not already set // It is possible that a node passes from failed to left and the reaptime was already set so keep that value if n.reapTime == 0 { n.reapTime = nodeReapInterval } // The node leave or fails, delete all the entries created by it. // If the node was temporary down, deleting the entries will guarantee that the CREATE events will be accepted // If the node instead left because was going down, then it makes sense to just delete all its state nDB.deleteNodeFromNetworks(n.Name) nDB.deleteNodeTableEntries(n.Name) } return true, nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
networkdb/message.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/networkdb/message.go#L56-L82
go
train
// makeCompoundMessage takes a list of messages and generates // a single compound message containing all of them
func makeCompoundMessage(msgs [][]byte) []byte
// makeCompoundMessage takes a list of messages and generates // a single compound message containing all of them func makeCompoundMessage(msgs [][]byte) []byte
{ cMsg := CompoundMessage{} cMsg.Messages = make([]*CompoundMessage_SimpleMessage, 0, len(msgs)) for _, m := range msgs { cMsg.Messages = append(cMsg.Messages, &CompoundMessage_SimpleMessage{ Payload: m, }) } buf, err := proto.Marshal(&cMsg) if err != nil { return nil } gMsg := GossipMessage{ Type: MessageTypeCompound, Data: buf, } buf, err = proto.Marshal(&gMsg) if err != nil { return nil } return buf }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
networkdb/message.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/networkdb/message.go#L86-L98
go
train
// decodeCompoundMessage splits a compound message and returns // the slices of individual messages. Returns any potential error.
func decodeCompoundMessage(buf []byte) ([][]byte, error)
// decodeCompoundMessage splits a compound message and returns // the slices of individual messages. Returns any potential error. func decodeCompoundMessage(buf []byte) ([][]byte, error)
{ var cMsg CompoundMessage if err := proto.Unmarshal(buf, &cMsg); err != nil { return nil, err } parts := make([][]byte, 0, len(cMsg.Messages)) for _, m := range cMsg.Messages { parts = append(parts, m.Payload) } return parts, nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
bitseq/sequence.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/bitseq/sequence.go#L50-L80
go
train
// NewHandle returns a thread-safe instance of the bitmask handler
func NewHandle(app string, ds datastore.DataStore, id string, numElements uint64) (*Handle, error)
// NewHandle returns a thread-safe instance of the bitmask handler func NewHandle(app string, ds datastore.DataStore, id string, numElements uint64) (*Handle, error)
{ h := &Handle{ app: app, id: id, store: ds, bits: numElements, unselected: numElements, head: &sequence{ block: 0x0, count: getNumBlocks(numElements), }, } if h.store == nil { return h, nil } // Get the initial status from the ds if present. if err := h.store.GetObject(datastore.Key(h.Key()...), h); err != nil && err != datastore.ErrKeyNotFound { return nil, err } // If the handle is not in store, write it. if !h.Exists() { if err := h.writeToStore(); err != nil { return nil, fmt.Errorf("failed to write bitsequence to store: %v", err) } } return h, nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
bitseq/sequence.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/bitseq/sequence.go#L90-L98
go
train
// String returns a string representation of the block sequence starting from this block
func (s *sequence) toString() string
// String returns a string representation of the block sequence starting from this block func (s *sequence) toString() string
{ var nextBlock string if s.next == nil { nextBlock = "end" } else { nextBlock = s.next.toString() } return fmt.Sprintf("(0x%x, %d)->%s", s.block, s.count, nextBlock) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
bitseq/sequence.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/bitseq/sequence.go#L101-L118
go
train
// GetAvailableBit returns the position of the first unset bit in the bitmask represented by this sequence
func (s *sequence) getAvailableBit(from uint64) (uint64, uint64, error)
// GetAvailableBit returns the position of the first unset bit in the bitmask represented by this sequence func (s *sequence) getAvailableBit(from uint64) (uint64, uint64, error)
{ if s.block == blockMAX || s.count == 0 { return invalidPos, invalidPos, ErrNoBitAvailable } bits := from bitSel := blockFirstBit >> from for bitSel > 0 && s.block&bitSel != 0 { bitSel >>= 1 bits++ } // Check if the loop exited because it could not // find any available bit int block starting from // "from". Return invalid pos in that case. if bitSel == 0 { return invalidPos, invalidPos, ErrNoBitAvailable } return bits / 8, bits % 8, nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
bitseq/sequence.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/bitseq/sequence.go#L121-L131
go
train
// GetCopy returns a copy of the linked list rooted at this node
func (s *sequence) getCopy() *sequence
// GetCopy returns a copy of the linked list rooted at this node func (s *sequence) getCopy() *sequence
{ n := &sequence{block: s.block, count: s.count} pn := n ps := s.next for ps != nil { pn.next = &sequence{block: ps.block, count: ps.count} pn = pn.next ps = ps.next } return n }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
bitseq/sequence.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/bitseq/sequence.go#L134-L152
go
train
// Equal checks if this sequence is equal to the passed one
func (s *sequence) equal(o *sequence) bool
// Equal checks if this sequence is equal to the passed one func (s *sequence) equal(o *sequence) bool
{ this := s other := o for this != nil { if other == nil { return false } if this.block != other.block || this.count != other.count { return false } this = this.next other = other.next } // Check if other is longer than this if other != nil { return false } return true }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
bitseq/sequence.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/bitseq/sequence.go#L155-L168
go
train
// ToByteArray converts the sequence into a byte array
func (s *sequence) toByteArray() ([]byte, error)
// ToByteArray converts the sequence into a byte array func (s *sequence) toByteArray() ([]byte, error)
{ var bb []byte p := s for p != nil { b := make([]byte, 12) binary.BigEndian.PutUint32(b[0:], p.block) binary.BigEndian.PutUint64(b[4:], p.count) bb = append(bb, b...) p = p.next } return bb, nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
bitseq/sequence.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/bitseq/sequence.go#L171-L191
go
train
// fromByteArray construct the sequence from the byte array
func (s *sequence) fromByteArray(data []byte) error
// fromByteArray construct the sequence from the byte array func (s *sequence) fromByteArray(data []byte) error
{ l := len(data) if l%12 != 0 { return fmt.Errorf("cannot deserialize byte sequence of length %d (%v)", l, data) } p := s i := 0 for { p.block = binary.BigEndian.Uint32(data[i : i+4]) p.count = binary.BigEndian.Uint64(data[i+4 : i+12]) i += 12 if i == l { break } p.next = &sequence{} p = p.next } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
bitseq/sequence.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/bitseq/sequence.go#L208-L216
go
train
// SetAnyInRange atomically sets the first unset bit in the specified range in the sequence and returns the corresponding ordinal
func (h *Handle) SetAnyInRange(start, end uint64, serial bool) (uint64, error)
// SetAnyInRange atomically sets the first unset bit in the specified range in the sequence and returns the corresponding ordinal func (h *Handle) SetAnyInRange(start, end uint64, serial bool) (uint64, error)
{ if end < start || end >= h.bits { return invalidPos, fmt.Errorf("invalid bit range [%d, %d]", start, end) } if h.Unselected() == 0 { return invalidPos, ErrNoBitAvailable } return h.set(0, start, end, true, false, serial) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
bitseq/sequence.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/bitseq/sequence.go#L219-L224
go
train
// SetAny atomically sets the first unset bit in the sequence and returns the corresponding ordinal
func (h *Handle) SetAny(serial bool) (uint64, error)
// SetAny atomically sets the first unset bit in the sequence and returns the corresponding ordinal func (h *Handle) SetAny(serial bool) (uint64, error)
{ if h.Unselected() == 0 { return invalidPos, ErrNoBitAvailable } return h.set(0, 0, h.bits-1, true, false, serial) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
bitseq/sequence.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/bitseq/sequence.go#L227-L233
go
train
// Set atomically sets the corresponding bit in the sequence
func (h *Handle) Set(ordinal uint64) error
// Set atomically sets the corresponding bit in the sequence func (h *Handle) Set(ordinal uint64) error
{ if err := h.validateOrdinal(ordinal); err != nil { return err } _, err := h.set(ordinal, 0, 0, false, false, false) return err }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
bitseq/sequence.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/bitseq/sequence.go#L236-L242
go
train
// Unset atomically unsets the corresponding bit in the sequence
func (h *Handle) Unset(ordinal uint64) error
// Unset atomically unsets the corresponding bit in the sequence func (h *Handle) Unset(ordinal uint64) error
{ if err := h.validateOrdinal(ordinal); err != nil { return err } _, err := h.set(ordinal, 0, 0, false, true, false) return err }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
bitseq/sequence.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/bitseq/sequence.go#L246-L254
go
train
// IsSet atomically checks if the ordinal bit is set. In case ordinal // is outside of the bit sequence limits, false is returned.
func (h *Handle) IsSet(ordinal uint64) bool
// IsSet atomically checks if the ordinal bit is set. In case ordinal // is outside of the bit sequence limits, false is returned. func (h *Handle) IsSet(ordinal uint64) bool
{ if err := h.validateOrdinal(ordinal); err != nil { return false } h.Lock() _, _, err := checkIfAvailable(h.head, ordinal) h.Unlock() return err != nil }