diff --git a/vendor.conf b/vendor.conf index 3f75e55cda..ac9c989cca 100644 --- a/vendor.conf +++ b/vendor.conf @@ -145,7 +145,7 @@ github.com/klauspost/compress a3b7545c88eea469c2246bee0e6c github.com/pelletier/go-toml 65ca8064882c8c308e5c804c5d5443d409e0738c # v1.8.1 # cluster -github.com/docker/swarmkit 5a5494a9a7b408b790533a5e4e1cb43ca1c32aad +github.com/docker/swarmkit 60d87cb7cdb070801ec550d7f4d7dc1210fb7e9f git://github.com/cpuguy83/swarmkit.git github.com/gogo/protobuf b03c65ea87cdc3521ede29f62fe3ce239267c1bc # v1.3.2 github.com/golang/protobuf 84668698ea25b64748563aa20726db66a6b8d299 # v1.3.5 github.com/cloudflare/cfssl 5d63dbd981b5c408effbb58c442d54761ff94fbd # 1.3.2 diff --git a/vendor/github.com/docker/libnetwork/agent.go b/vendor/github.com/docker/libnetwork/agent.go deleted file mode 100644 index 4a5c215624..0000000000 --- a/vendor/github.com/docker/libnetwork/agent.go +++ /dev/null @@ -1,988 +0,0 @@ -package libnetwork - -//go:generate protoc -I.:Godeps/_workspace/src/github.com/gogo/protobuf --gogo_out=import_path=github.com/docker/libnetwork,Mgogoproto/gogo.proto=github.com/gogo/protobuf/gogoproto:. agent.proto - -import ( - "encoding/json" - "fmt" - "net" - "sort" - "sync" - - "github.com/docker/go-events" - "github.com/docker/libnetwork/cluster" - "github.com/docker/libnetwork/datastore" - "github.com/docker/libnetwork/discoverapi" - "github.com/docker/libnetwork/driverapi" - "github.com/docker/libnetwork/networkdb" - "github.com/docker/libnetwork/types" - "github.com/gogo/protobuf/proto" - "github.com/sirupsen/logrus" -) - -const ( - subsysGossip = "networking:gossip" - subsysIPSec = "networking:ipsec" - keyringSize = 3 -) - -// ByTime implements sort.Interface for []*types.EncryptionKey based on -// the LamportTime field. -type ByTime []*types.EncryptionKey - -func (b ByTime) Len() int { return len(b) } -func (b ByTime) Swap(i, j int) { b[i], b[j] = b[j], b[i] } -func (b ByTime) Less(i, j int) bool { return b[i].LamportTime < b[j].LamportTime } - -type agent struct { - networkDB *networkdb.NetworkDB - bindAddr string - advertiseAddr string - dataPathAddr string - coreCancelFuncs []func() - driverCancelFuncs map[string][]func() - sync.Mutex -} - -func (a *agent) dataPathAddress() string { - a.Lock() - defer a.Unlock() - if a.dataPathAddr != "" { - return a.dataPathAddr - } - return a.advertiseAddr -} - -const libnetworkEPTable = "endpoint_table" - -func getBindAddr(ifaceName string) (string, error) { - iface, err := net.InterfaceByName(ifaceName) - if err != nil { - return "", fmt.Errorf("failed to find interface %s: %v", ifaceName, err) - } - - addrs, err := iface.Addrs() - if err != nil { - return "", fmt.Errorf("failed to get interface addresses: %v", err) - } - - for _, a := range addrs { - addr, ok := a.(*net.IPNet) - if !ok { - continue - } - addrIP := addr.IP - - if addrIP.IsLinkLocalUnicast() { - continue - } - - return addrIP.String(), nil - } - - return "", fmt.Errorf("failed to get bind address") -} - -func resolveAddr(addrOrInterface string) (string, error) { - // Try and see if this is a valid IP address - if net.ParseIP(addrOrInterface) != nil { - return addrOrInterface, nil - } - - addr, err := net.ResolveIPAddr("ip", addrOrInterface) - if err != nil { - // If not a valid IP address, it should be a valid interface - return getBindAddr(addrOrInterface) - } - return addr.String(), nil -} - -func (c *controller) handleKeyChange(keys []*types.EncryptionKey) error { - drvEnc := discoverapi.DriverEncryptionUpdate{} - - a := c.getAgent() - if a == nil { - logrus.Debug("Skipping key change as agent is nil") - return nil - } - - // Find the deleted key. If the deleted key was the primary key, - // a new primary key should be set before removing if from keyring. - c.Lock() - added := []byte{} - deleted := []byte{} - j := len(c.keys) - for i := 0; i < j; { - same := false - for _, key := range keys { - if same = key.LamportTime == c.keys[i].LamportTime; same { - break - } - } - if !same { - cKey := c.keys[i] - if cKey.Subsystem == subsysGossip { - deleted = cKey.Key - } - - if cKey.Subsystem == subsysIPSec { - drvEnc.Prune = cKey.Key - drvEnc.PruneTag = cKey.LamportTime - } - c.keys[i], c.keys[j-1] = c.keys[j-1], c.keys[i] - c.keys[j-1] = nil - j-- - } - i++ - } - c.keys = c.keys[:j] - - // Find the new key and add it to the key ring - for _, key := range keys { - same := false - for _, cKey := range c.keys { - if same = cKey.LamportTime == key.LamportTime; same { - break - } - } - if !same { - c.keys = append(c.keys, key) - if key.Subsystem == subsysGossip { - added = key.Key - } - - if key.Subsystem == subsysIPSec { - drvEnc.Key = key.Key - drvEnc.Tag = key.LamportTime - } - } - } - c.Unlock() - - if len(added) > 0 { - a.networkDB.SetKey(added) - } - - key, _, err := c.getPrimaryKeyTag(subsysGossip) - if err != nil { - return err - } - a.networkDB.SetPrimaryKey(key) - - key, tag, err := c.getPrimaryKeyTag(subsysIPSec) - if err != nil { - return err - } - drvEnc.Primary = key - drvEnc.PrimaryTag = tag - - if len(deleted) > 0 { - a.networkDB.RemoveKey(deleted) - } - - c.drvRegistry.WalkDrivers(func(name string, driver driverapi.Driver, capability driverapi.Capability) bool { - err := driver.DiscoverNew(discoverapi.EncryptionKeysUpdate, drvEnc) - if err != nil { - logrus.Warnf("Failed to update datapath keys in driver %s: %v", name, err) - // Attempt to reconfigure keys in case of a update failure - // which can arise due to a mismatch of keys - // if worker nodes get temporarily disconnected - logrus.Warnf("Reconfiguring datapath keys for %s", name) - drvCfgEnc := discoverapi.DriverEncryptionConfig{} - drvCfgEnc.Keys, drvCfgEnc.Tags = c.getKeys(subsysIPSec) - err = driver.DiscoverNew(discoverapi.EncryptionKeysConfig, drvCfgEnc) - if err != nil { - logrus.Warnf("Failed to reset datapath keys in driver %s: %v", name, err) - } - } - return false - }) - - return nil -} - -func (c *controller) agentSetup(clusterProvider cluster.Provider) error { - agent := c.getAgent() - - // If the agent is already present there is no need to try to initialize it again - if agent != nil { - return nil - } - - bindAddr := clusterProvider.GetLocalAddress() - advAddr := clusterProvider.GetAdvertiseAddress() - dataAddr := clusterProvider.GetDataPathAddress() - remoteList := clusterProvider.GetRemoteAddressList() - remoteAddrList := make([]string, 0, len(remoteList)) - for _, remote := range remoteList { - addr, _, _ := net.SplitHostPort(remote) - remoteAddrList = append(remoteAddrList, addr) - } - - listen := clusterProvider.GetListenAddress() - listenAddr, _, _ := net.SplitHostPort(listen) - - logrus.Infof("Initializing Libnetwork Agent Listen-Addr=%s Local-addr=%s Adv-addr=%s Data-addr=%s Remote-addr-list=%v MTU=%d", - listenAddr, bindAddr, advAddr, dataAddr, remoteAddrList, c.Config().Daemon.NetworkControlPlaneMTU) - if advAddr != "" && agent == nil { - if err := c.agentInit(listenAddr, bindAddr, advAddr, dataAddr); err != nil { - logrus.Errorf("error in agentInit: %v", err) - return err - } - c.drvRegistry.WalkDrivers(func(name string, driver driverapi.Driver, capability driverapi.Capability) bool { - if capability.ConnectivityScope == datastore.GlobalScope { - c.agentDriverNotify(driver) - } - return false - }) - } - - if len(remoteAddrList) > 0 { - if err := c.agentJoin(remoteAddrList); err != nil { - logrus.Errorf("Error in joining gossip cluster : %v(join will be retried in background)", err) - } - } - - return nil -} - -// For a given subsystem getKeys sorts the keys by lamport time and returns -// slice of keys and lamport time which can used as a unique tag for the keys -func (c *controller) getKeys(subsys string) ([][]byte, []uint64) { - c.Lock() - defer c.Unlock() - - sort.Sort(ByTime(c.keys)) - - keys := [][]byte{} - tags := []uint64{} - for _, key := range c.keys { - if key.Subsystem == subsys { - keys = append(keys, key.Key) - tags = append(tags, key.LamportTime) - } - } - - keys[0], keys[1] = keys[1], keys[0] - tags[0], tags[1] = tags[1], tags[0] - return keys, tags -} - -// getPrimaryKeyTag returns the primary key for a given subsystem from the -// list of sorted key and the associated tag -func (c *controller) getPrimaryKeyTag(subsys string) ([]byte, uint64, error) { - c.Lock() - defer c.Unlock() - sort.Sort(ByTime(c.keys)) - keys := []*types.EncryptionKey{} - for _, key := range c.keys { - if key.Subsystem == subsys { - keys = append(keys, key) - } - } - return keys[1].Key, keys[1].LamportTime, nil -} - -func (c *controller) agentInit(listenAddr, bindAddrOrInterface, advertiseAddr, dataPathAddr string) error { - bindAddr, err := resolveAddr(bindAddrOrInterface) - if err != nil { - return err - } - - keys, _ := c.getKeys(subsysGossip) - - netDBConf := networkdb.DefaultConfig() - netDBConf.BindAddr = listenAddr - netDBConf.AdvertiseAddr = advertiseAddr - netDBConf.Keys = keys - if c.Config().Daemon.NetworkControlPlaneMTU != 0 { - // Consider the MTU remove the IP hdr (IPv4 or IPv6) and the TCP/UDP hdr. - // To be on the safe side let's cut 100 bytes - netDBConf.PacketBufferSize = (c.Config().Daemon.NetworkControlPlaneMTU - 100) - logrus.Debugf("Control plane MTU: %d will initialize NetworkDB with: %d", - c.Config().Daemon.NetworkControlPlaneMTU, netDBConf.PacketBufferSize) - } - nDB, err := networkdb.New(netDBConf) - if err != nil { - return err - } - - // Register the diagnostic handlers - c.DiagnosticServer.RegisterHandler(nDB, networkdb.NetDbPaths2Func) - - var cancelList []func() - ch, cancel := nDB.Watch(libnetworkEPTable, "", "") - cancelList = append(cancelList, cancel) - nodeCh, cancel := nDB.Watch(networkdb.NodeTable, "", "") - cancelList = append(cancelList, cancel) - - c.Lock() - c.agent = &agent{ - networkDB: nDB, - bindAddr: bindAddr, - advertiseAddr: advertiseAddr, - dataPathAddr: dataPathAddr, - coreCancelFuncs: cancelList, - driverCancelFuncs: make(map[string][]func()), - } - c.Unlock() - - go c.handleTableEvents(ch, c.handleEpTableEvent) - go c.handleTableEvents(nodeCh, c.handleNodeTableEvent) - - drvEnc := discoverapi.DriverEncryptionConfig{} - keys, tags := c.getKeys(subsysIPSec) - drvEnc.Keys = keys - drvEnc.Tags = tags - - c.drvRegistry.WalkDrivers(func(name string, driver driverapi.Driver, capability driverapi.Capability) bool { - err := driver.DiscoverNew(discoverapi.EncryptionKeysConfig, drvEnc) - if err != nil { - logrus.Warnf("Failed to set datapath keys in driver %s: %v", name, err) - } - return false - }) - - c.WalkNetworks(joinCluster) - - return nil -} - -func (c *controller) agentJoin(remoteAddrList []string) error { - agent := c.getAgent() - if agent == nil { - return nil - } - return agent.networkDB.Join(remoteAddrList) -} - -func (c *controller) agentDriverNotify(d driverapi.Driver) { - agent := c.getAgent() - if agent == nil { - return - } - - if err := d.DiscoverNew(discoverapi.NodeDiscovery, discoverapi.NodeDiscoveryData{ - Address: agent.dataPathAddress(), - BindAddress: agent.bindAddr, - Self: true, - }); err != nil { - logrus.Warnf("Failed the node discovery in driver: %v", err) - } - - drvEnc := discoverapi.DriverEncryptionConfig{} - keys, tags := c.getKeys(subsysIPSec) - drvEnc.Keys = keys - drvEnc.Tags = tags - - if err := d.DiscoverNew(discoverapi.EncryptionKeysConfig, drvEnc); err != nil { - logrus.Warnf("Failed to set datapath keys in driver: %v", err) - } -} - -func (c *controller) agentClose() { - // Acquire current agent instance and reset its pointer - // then run closing functions - c.Lock() - agent := c.agent - c.agent = nil - c.Unlock() - - // when the agent is closed the cluster provider should be cleaned up - c.SetClusterProvider(nil) - - if agent == nil { - return - } - - var cancelList []func() - - agent.Lock() - for _, cancelFuncs := range agent.driverCancelFuncs { - cancelList = append(cancelList, cancelFuncs...) - } - - // Add also the cancel functions for the network db - cancelList = append(cancelList, agent.coreCancelFuncs...) - agent.Unlock() - - for _, cancel := range cancelList { - cancel() - } - - agent.networkDB.Close() -} - -// Task has the backend container details -type Task struct { - Name string - EndpointID string - EndpointIP string - Info map[string]string -} - -// ServiceInfo has service specific details along with the list of backend tasks -type ServiceInfo struct { - VIP string - LocalLBIndex int - Tasks []Task - Ports []string -} - -type epRecord struct { - ep EndpointRecord - info map[string]string - lbIndex int -} - -func (n *network) Services() map[string]ServiceInfo { - eps := make(map[string]epRecord) - - if !n.isClusterEligible() { - return nil - } - agent := n.getController().getAgent() - if agent == nil { - return nil - } - - // Walk through libnetworkEPTable and fetch the driver agnostic endpoint info - entries := agent.networkDB.GetTableByNetwork(libnetworkEPTable, n.id) - for eid, value := range entries { - var epRec EndpointRecord - nid := n.ID() - if err := proto.Unmarshal(value.Value, &epRec); err != nil { - logrus.Errorf("Unmarshal of libnetworkEPTable failed for endpoint %s in network %s, %v", eid, nid, err) - continue - } - i := n.getController().getLBIndex(epRec.ServiceID, nid, epRec.IngressPorts) - eps[eid] = epRecord{ - ep: epRec, - lbIndex: i, - } - } - - // Walk through the driver's tables, have the driver decode the entries - // and return the tuple {ep ID, value}. value is a string that coveys - // relevant info about the endpoint. - d, err := n.driver(true) - if err != nil { - logrus.Errorf("Could not resolve driver for network %s/%s while fetching services: %v", n.networkType, n.ID(), err) - return nil - } - for _, table := range n.driverTables { - if table.objType != driverapi.EndpointObject { - continue - } - entries := agent.networkDB.GetTableByNetwork(table.name, n.id) - for key, value := range entries { - epID, info := d.DecodeTableEntry(table.name, key, value.Value) - if ep, ok := eps[epID]; !ok { - logrus.Errorf("Inconsistent driver and libnetwork state for endpoint %s", epID) - } else { - ep.info = info - eps[epID] = ep - } - } - } - - // group the endpoints into a map keyed by the service name - sinfo := make(map[string]ServiceInfo) - for ep, epr := range eps { - var ( - s ServiceInfo - ok bool - ) - if s, ok = sinfo[epr.ep.ServiceName]; !ok { - s = ServiceInfo{ - VIP: epr.ep.VirtualIP, - LocalLBIndex: epr.lbIndex, - } - } - ports := []string{} - if s.Ports == nil { - for _, port := range epr.ep.IngressPorts { - p := fmt.Sprintf("Target: %d, Publish: %d", port.TargetPort, port.PublishedPort) - ports = append(ports, p) - } - s.Ports = ports - } - s.Tasks = append(s.Tasks, Task{ - Name: epr.ep.Name, - EndpointID: ep, - EndpointIP: epr.ep.EndpointIP, - Info: epr.info, - }) - sinfo[epr.ep.ServiceName] = s - } - return sinfo -} - -func (n *network) isClusterEligible() bool { - if n.scope != datastore.SwarmScope || !n.driverIsMultihost() { - return false - } - return n.getController().getAgent() != nil -} - -func (n *network) joinCluster() error { - if !n.isClusterEligible() { - return nil - } - - agent := n.getController().getAgent() - if agent == nil { - return nil - } - - return agent.networkDB.JoinNetwork(n.ID()) -} - -func (n *network) leaveCluster() error { - if !n.isClusterEligible() { - return nil - } - - agent := n.getController().getAgent() - if agent == nil { - return nil - } - - return agent.networkDB.LeaveNetwork(n.ID()) -} - -func (ep *endpoint) addDriverInfoToCluster() error { - n := ep.getNetwork() - if !n.isClusterEligible() { - return nil - } - if ep.joinInfo == nil { - return nil - } - - agent := n.getController().getAgent() - if agent == nil { - return nil - } - - for _, te := range ep.joinInfo.driverTableEntries { - if err := agent.networkDB.CreateEntry(te.tableName, n.ID(), te.key, te.value); err != nil { - return err - } - } - return nil -} - -func (ep *endpoint) deleteDriverInfoFromCluster() error { - n := ep.getNetwork() - if !n.isClusterEligible() { - return nil - } - if ep.joinInfo == nil { - return nil - } - - agent := n.getController().getAgent() - if agent == nil { - return nil - } - - for _, te := range ep.joinInfo.driverTableEntries { - if err := agent.networkDB.DeleteEntry(te.tableName, n.ID(), te.key); err != nil { - return err - } - } - return nil -} - -func (ep *endpoint) addServiceInfoToCluster(sb *sandbox) error { - if ep.isAnonymous() && len(ep.myAliases) == 0 || ep.Iface() == nil || ep.Iface().Address() == nil { - return nil - } - - n := ep.getNetwork() - if !n.isClusterEligible() { - return nil - } - - sb.Service.Lock() - defer sb.Service.Unlock() - logrus.Debugf("addServiceInfoToCluster START for %s %s", ep.svcName, ep.ID()) - - // Check that the endpoint is still present on the sandbox before adding it to the service discovery. - // This is to handle a race between the EnableService and the sbLeave - // It is possible that the EnableService starts, fetches the list of the endpoints and - // by the time the addServiceInfoToCluster is called the endpoint got removed from the sandbox - // The risk is that the deleteServiceInfoToCluster happens before the addServiceInfoToCluster. - // This check under the Service lock of the sandbox ensure the correct behavior. - // If the addServiceInfoToCluster arrives first may find or not the endpoint and will proceed or exit - // but in any case the deleteServiceInfoToCluster will follow doing the cleanup if needed. - // In case the deleteServiceInfoToCluster arrives first, this one is happening after the endpoint is - // removed from the list, in this situation the delete will bail out not finding any data to cleanup - // and the add will bail out not finding the endpoint on the sandbox. - if e := sb.getEndpoint(ep.ID()); e == nil { - logrus.Warnf("addServiceInfoToCluster suppressing service resolution ep is not anymore in the sandbox %s", ep.ID()) - return nil - } - - c := n.getController() - agent := c.getAgent() - - name := ep.Name() - if ep.isAnonymous() { - name = ep.MyAliases()[0] - } - - var ingressPorts []*PortConfig - if ep.svcID != "" { - // This is a task part of a service - // Gossip ingress ports only in ingress network. - if n.ingress { - ingressPorts = ep.ingressPorts - } - if err := c.addServiceBinding(ep.svcName, ep.svcID, n.ID(), ep.ID(), name, ep.virtualIP, ingressPorts, ep.svcAliases, ep.myAliases, ep.Iface().Address().IP, "addServiceInfoToCluster"); err != nil { - return err - } - } else { - // This is a container simply attached to an attachable network - if err := c.addContainerNameResolution(n.ID(), ep.ID(), name, ep.myAliases, ep.Iface().Address().IP, "addServiceInfoToCluster"); err != nil { - return err - } - } - - buf, err := proto.Marshal(&EndpointRecord{ - Name: name, - ServiceName: ep.svcName, - ServiceID: ep.svcID, - VirtualIP: ep.virtualIP.String(), - IngressPorts: ingressPorts, - Aliases: ep.svcAliases, - TaskAliases: ep.myAliases, - EndpointIP: ep.Iface().Address().IP.String(), - ServiceDisabled: false, - }) - if err != nil { - return err - } - - if agent != nil { - if err := agent.networkDB.CreateEntry(libnetworkEPTable, n.ID(), ep.ID(), buf); err != nil { - logrus.Warnf("addServiceInfoToCluster NetworkDB CreateEntry failed for %s %s err:%s", ep.id, n.id, err) - return err - } - } - - logrus.Debugf("addServiceInfoToCluster END for %s %s", ep.svcName, ep.ID()) - - return nil -} - -func (ep *endpoint) deleteServiceInfoFromCluster(sb *sandbox, fullRemove bool, method string) error { - if ep.isAnonymous() && len(ep.myAliases) == 0 { - return nil - } - - n := ep.getNetwork() - if !n.isClusterEligible() { - return nil - } - - sb.Service.Lock() - defer sb.Service.Unlock() - logrus.Debugf("deleteServiceInfoFromCluster from %s START for %s %s", method, ep.svcName, ep.ID()) - - // Avoid a race w/ with a container that aborts preemptively. This would - // get caught in disableServceInNetworkDB, but we check here to make the - // nature of the condition more clear. - // See comment in addServiceInfoToCluster() - if e := sb.getEndpoint(ep.ID()); e == nil { - logrus.Warnf("deleteServiceInfoFromCluster suppressing service resolution ep is not anymore in the sandbox %s", ep.ID()) - return nil - } - - c := n.getController() - agent := c.getAgent() - - name := ep.Name() - if ep.isAnonymous() { - name = ep.MyAliases()[0] - } - - if agent != nil { - // First update the networkDB then locally - if fullRemove { - if err := agent.networkDB.DeleteEntry(libnetworkEPTable, n.ID(), ep.ID()); err != nil { - logrus.Warnf("deleteServiceInfoFromCluster NetworkDB DeleteEntry failed for %s %s err:%s", ep.id, n.id, err) - } - } else { - disableServiceInNetworkDB(agent, n, ep) - } - } - - if ep.Iface() != nil && ep.Iface().Address() != nil { - if ep.svcID != "" { - // This is a task part of a service - var ingressPorts []*PortConfig - if n.ingress { - ingressPorts = ep.ingressPorts - } - if err := c.rmServiceBinding(ep.svcName, ep.svcID, n.ID(), ep.ID(), name, ep.virtualIP, ingressPorts, ep.svcAliases, ep.myAliases, ep.Iface().Address().IP, "deleteServiceInfoFromCluster", true, fullRemove); err != nil { - return err - } - } else { - // This is a container simply attached to an attachable network - if err := c.delContainerNameResolution(n.ID(), ep.ID(), name, ep.myAliases, ep.Iface().Address().IP, "deleteServiceInfoFromCluster"); err != nil { - return err - } - } - } - - logrus.Debugf("deleteServiceInfoFromCluster from %s END for %s %s", method, ep.svcName, ep.ID()) - - return nil -} - -func disableServiceInNetworkDB(a *agent, n *network, ep *endpoint) { - var epRec EndpointRecord - - logrus.Debugf("disableServiceInNetworkDB for %s %s", ep.svcName, ep.ID()) - - // Update existing record to indicate that the service is disabled - inBuf, err := a.networkDB.GetEntry(libnetworkEPTable, n.ID(), ep.ID()) - if err != nil { - logrus.Warnf("disableServiceInNetworkDB GetEntry failed for %s %s err:%s", ep.id, n.id, err) - return - } - // Should never fail - if err := proto.Unmarshal(inBuf, &epRec); err != nil { - logrus.Errorf("disableServiceInNetworkDB unmarshal failed for %s %s err:%s", ep.id, n.id, err) - return - } - epRec.ServiceDisabled = true - // Should never fail - outBuf, err := proto.Marshal(&epRec) - if err != nil { - logrus.Errorf("disableServiceInNetworkDB marshalling failed for %s %s err:%s", ep.id, n.id, err) - return - } - // Send update to the whole cluster - if err := a.networkDB.UpdateEntry(libnetworkEPTable, n.ID(), ep.ID(), outBuf); err != nil { - logrus.Warnf("disableServiceInNetworkDB UpdateEntry failed for %s %s err:%s", ep.id, n.id, err) - } -} - -func (n *network) addDriverWatches() { - if !n.isClusterEligible() { - return - } - - c := n.getController() - agent := c.getAgent() - if agent == nil { - return - } - for _, table := range n.driverTables { - ch, cancel := agent.networkDB.Watch(table.name, n.ID(), "") - agent.Lock() - agent.driverCancelFuncs[n.ID()] = append(agent.driverCancelFuncs[n.ID()], cancel) - agent.Unlock() - go c.handleTableEvents(ch, n.handleDriverTableEvent) - d, err := n.driver(false) - if err != nil { - logrus.Errorf("Could not resolve driver %s while walking driver tabl: %v", n.networkType, err) - return - } - - agent.networkDB.WalkTable(table.name, func(nid, key string, value []byte, deleted bool) bool { - // skip the entries that are mark for deletion, this is safe because this function is - // called at initialization time so there is no state to delete - if nid == n.ID() && !deleted { - d.EventNotify(driverapi.Create, nid, table.name, key, value) - } - return false - }) - } -} - -func (n *network) cancelDriverWatches() { - if !n.isClusterEligible() { - return - } - - agent := n.getController().getAgent() - if agent == nil { - return - } - - agent.Lock() - cancelFuncs := agent.driverCancelFuncs[n.ID()] - delete(agent.driverCancelFuncs, n.ID()) - agent.Unlock() - - for _, cancel := range cancelFuncs { - cancel() - } -} - -func (c *controller) handleTableEvents(ch *events.Channel, fn func(events.Event)) { - for { - select { - case ev := <-ch.C: - fn(ev) - case <-ch.Done(): - return - } - } -} - -func (n *network) handleDriverTableEvent(ev events.Event) { - d, err := n.driver(false) - if err != nil { - logrus.Errorf("Could not resolve driver %s while handling driver table event: %v", n.networkType, err) - return - } - - var ( - etype driverapi.EventType - tname string - key string - value []byte - ) - - switch event := ev.(type) { - case networkdb.CreateEvent: - tname = event.Table - key = event.Key - value = event.Value - etype = driverapi.Create - case networkdb.DeleteEvent: - tname = event.Table - key = event.Key - value = event.Value - etype = driverapi.Delete - case networkdb.UpdateEvent: - tname = event.Table - key = event.Key - value = event.Value - etype = driverapi.Delete - } - - d.EventNotify(etype, n.ID(), tname, key, value) -} - -func (c *controller) handleNodeTableEvent(ev events.Event) { - var ( - value []byte - isAdd bool - nodeAddr networkdb.NodeAddr - ) - switch event := ev.(type) { - case networkdb.CreateEvent: - value = event.Value - isAdd = true - case networkdb.DeleteEvent: - value = event.Value - case networkdb.UpdateEvent: - logrus.Errorf("Unexpected update node table event = %#v", event) - } - - err := json.Unmarshal(value, &nodeAddr) - if err != nil { - logrus.Errorf("Error unmarshalling node table event %v", err) - return - } - c.processNodeDiscovery([]net.IP{nodeAddr.Addr}, isAdd) - -} - -func (c *controller) handleEpTableEvent(ev events.Event) { - var ( - nid string - eid string - value []byte - epRec EndpointRecord - ) - - switch event := ev.(type) { - case networkdb.CreateEvent: - nid = event.NetworkID - eid = event.Key - value = event.Value - case networkdb.DeleteEvent: - nid = event.NetworkID - eid = event.Key - value = event.Value - case networkdb.UpdateEvent: - nid = event.NetworkID - eid = event.Key - value = event.Value - default: - logrus.Errorf("Unexpected update service table event = %#v", event) - return - } - - err := proto.Unmarshal(value, &epRec) - if err != nil { - logrus.Errorf("Failed to unmarshal service table value: %v", err) - return - } - - containerName := epRec.Name - svcName := epRec.ServiceName - svcID := epRec.ServiceID - vip := net.ParseIP(epRec.VirtualIP) - ip := net.ParseIP(epRec.EndpointIP) - ingressPorts := epRec.IngressPorts - serviceAliases := epRec.Aliases - taskAliases := epRec.TaskAliases - - if containerName == "" || ip == nil { - logrus.Errorf("Invalid endpoint name/ip received while handling service table event %s", value) - return - } - - switch ev.(type) { - case networkdb.CreateEvent: - logrus.Debugf("handleEpTableEvent ADD %s R:%v", eid, epRec) - if svcID != "" { - // This is a remote task part of a service - if err := c.addServiceBinding(svcName, svcID, nid, eid, containerName, vip, ingressPorts, serviceAliases, taskAliases, ip, "handleEpTableEvent"); err != nil { - logrus.Errorf("failed adding service binding for %s epRec:%v err:%v", eid, epRec, err) - return - } - } else { - // This is a remote container simply attached to an attachable network - if err := c.addContainerNameResolution(nid, eid, containerName, taskAliases, ip, "handleEpTableEvent"); err != nil { - logrus.Errorf("failed adding container name resolution for %s epRec:%v err:%v", eid, epRec, err) - } - } - - case networkdb.DeleteEvent: - logrus.Debugf("handleEpTableEvent DEL %s R:%v", eid, epRec) - if svcID != "" { - // This is a remote task part of a service - if err := c.rmServiceBinding(svcName, svcID, nid, eid, containerName, vip, ingressPorts, serviceAliases, taskAliases, ip, "handleEpTableEvent", true, true); err != nil { - logrus.Errorf("failed removing service binding for %s epRec:%v err:%v", eid, epRec, err) - return - } - } else { - // This is a remote container simply attached to an attachable network - if err := c.delContainerNameResolution(nid, eid, containerName, taskAliases, ip, "handleEpTableEvent"); err != nil { - logrus.Errorf("failed removing container name resolution for %s epRec:%v err:%v", eid, epRec, err) - } - } - case networkdb.UpdateEvent: - logrus.Debugf("handleEpTableEvent UPD %s R:%v", eid, epRec) - // We currently should only get these to inform us that an endpoint - // is disabled. Report if otherwise. - if svcID == "" || !epRec.ServiceDisabled { - logrus.Errorf("Unexpected update table event for %s epRec:%v", eid, epRec) - return - } - // This is a remote task that is part of a service that is now disabled - if err := c.rmServiceBinding(svcName, svcID, nid, eid, containerName, vip, ingressPorts, serviceAliases, taskAliases, ip, "handleEpTableEvent", true, false); err != nil { - logrus.Errorf("failed disabling service binding for %s epRec:%v err:%v", eid, epRec, err) - return - } - } -} diff --git a/vendor/github.com/docker/libnetwork/agent.pb.go b/vendor/github.com/docker/libnetwork/agent.pb.go deleted file mode 100644 index 4092973c9b..0000000000 --- a/vendor/github.com/docker/libnetwork/agent.pb.go +++ /dev/null @@ -1,1095 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: agent.proto - -/* - Package libnetwork is a generated protocol buffer package. - - It is generated from these files: - agent.proto - - It has these top-level messages: - EndpointRecord - PortConfig -*/ -package libnetwork - -import proto "github.com/gogo/protobuf/proto" -import fmt "fmt" -import math "math" -import _ "github.com/gogo/protobuf/gogoproto" - -import strings "strings" -import reflect "reflect" - -import io "io" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package - -type PortConfig_Protocol int32 - -const ( - ProtocolTCP PortConfig_Protocol = 0 - ProtocolUDP PortConfig_Protocol = 1 - ProtocolSCTP PortConfig_Protocol = 2 -) - -var PortConfig_Protocol_name = map[int32]string{ - 0: "TCP", - 1: "UDP", - 2: "SCTP", -} -var PortConfig_Protocol_value = map[string]int32{ - "TCP": 0, - "UDP": 1, - "SCTP": 2, -} - -func (x PortConfig_Protocol) String() string { - return proto.EnumName(PortConfig_Protocol_name, int32(x)) -} -func (PortConfig_Protocol) EnumDescriptor() ([]byte, []int) { return fileDescriptorAgent, []int{1, 0} } - -// EndpointRecord specifies all the endpoint specific information that -// needs to gossiped to nodes participating in the network. -type EndpointRecord struct { - // Name of the container - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - // Service name of the service to which this endpoint belongs. - ServiceName string `protobuf:"bytes,2,opt,name=service_name,json=serviceName,proto3" json:"service_name,omitempty"` - // Service ID of the service to which this endpoint belongs. - ServiceID string `protobuf:"bytes,3,opt,name=service_id,json=serviceId,proto3" json:"service_id,omitempty"` - // Virtual IP of the service to which this endpoint belongs. - VirtualIP string `protobuf:"bytes,4,opt,name=virtual_ip,json=virtualIp,proto3" json:"virtual_ip,omitempty"` - // IP assigned to this endpoint. - EndpointIP string `protobuf:"bytes,5,opt,name=endpoint_ip,json=endpointIp,proto3" json:"endpoint_ip,omitempty"` - // IngressPorts exposed by the service to which this endpoint belongs. - IngressPorts []*PortConfig `protobuf:"bytes,6,rep,name=ingress_ports,json=ingressPorts" json:"ingress_ports,omitempty"` - // A list of aliases which are alternate names for the service - Aliases []string `protobuf:"bytes,7,rep,name=aliases" json:"aliases,omitempty"` - // List of aliases task specific aliases - TaskAliases []string `protobuf:"bytes,8,rep,name=task_aliases,json=taskAliases" json:"task_aliases,omitempty"` - // Whether this enpoint's service has been disabled - ServiceDisabled bool `protobuf:"varint,9,opt,name=service_disabled,json=serviceDisabled,proto3" json:"service_disabled,omitempty"` -} - -func (m *EndpointRecord) Reset() { *m = EndpointRecord{} } -func (*EndpointRecord) ProtoMessage() {} -func (*EndpointRecord) Descriptor() ([]byte, []int) { return fileDescriptorAgent, []int{0} } - -func (m *EndpointRecord) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *EndpointRecord) GetServiceName() string { - if m != nil { - return m.ServiceName - } - return "" -} - -func (m *EndpointRecord) GetServiceID() string { - if m != nil { - return m.ServiceID - } - return "" -} - -func (m *EndpointRecord) GetVirtualIP() string { - if m != nil { - return m.VirtualIP - } - return "" -} - -func (m *EndpointRecord) GetEndpointIP() string { - if m != nil { - return m.EndpointIP - } - return "" -} - -func (m *EndpointRecord) GetIngressPorts() []*PortConfig { - if m != nil { - return m.IngressPorts - } - return nil -} - -func (m *EndpointRecord) GetAliases() []string { - if m != nil { - return m.Aliases - } - return nil -} - -func (m *EndpointRecord) GetTaskAliases() []string { - if m != nil { - return m.TaskAliases - } - return nil -} - -func (m *EndpointRecord) GetServiceDisabled() bool { - if m != nil { - return m.ServiceDisabled - } - return false -} - -// PortConfig specifies an exposed port which can be -// addressed using the given name. This can be later queried -// using a service discovery api or a DNS SRV query. The node -// port specifies a port that can be used to address this -// service external to the cluster by sending a connection -// request to this port to any node on the cluster. -type PortConfig struct { - // Name for the port. If provided the port information can - // be queried using the name as in a DNS SRV query. - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - // Protocol for the port which is exposed. - Protocol PortConfig_Protocol `protobuf:"varint,2,opt,name=protocol,proto3,enum=libnetwork.PortConfig_Protocol" json:"protocol,omitempty"` - // The port which the application is exposing and is bound to. - TargetPort uint32 `protobuf:"varint,3,opt,name=target_port,json=targetPort,proto3" json:"target_port,omitempty"` - // PublishedPort specifies the port on which the service is - // exposed on all nodes on the cluster. If not specified an - // arbitrary port in the node port range is allocated by the - // system. If specified it should be within the node port - // range and it should be available. - PublishedPort uint32 `protobuf:"varint,4,opt,name=published_port,json=publishedPort,proto3" json:"published_port,omitempty"` -} - -func (m *PortConfig) Reset() { *m = PortConfig{} } -func (*PortConfig) ProtoMessage() {} -func (*PortConfig) Descriptor() ([]byte, []int) { return fileDescriptorAgent, []int{1} } - -func (m *PortConfig) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *PortConfig) GetProtocol() PortConfig_Protocol { - if m != nil { - return m.Protocol - } - return ProtocolTCP -} - -func (m *PortConfig) GetTargetPort() uint32 { - if m != nil { - return m.TargetPort - } - return 0 -} - -func (m *PortConfig) GetPublishedPort() uint32 { - if m != nil { - return m.PublishedPort - } - return 0 -} - -func init() { - proto.RegisterType((*EndpointRecord)(nil), "libnetwork.EndpointRecord") - proto.RegisterType((*PortConfig)(nil), "libnetwork.PortConfig") - proto.RegisterEnum("libnetwork.PortConfig_Protocol", PortConfig_Protocol_name, PortConfig_Protocol_value) -} -func (this *EndpointRecord) GoString() string { - if this == nil { - return "nil" - } - s := make([]string, 0, 13) - s = append(s, "&libnetwork.EndpointRecord{") - s = append(s, "Name: "+fmt.Sprintf("%#v", this.Name)+",\n") - s = append(s, "ServiceName: "+fmt.Sprintf("%#v", this.ServiceName)+",\n") - s = append(s, "ServiceID: "+fmt.Sprintf("%#v", this.ServiceID)+",\n") - s = append(s, "VirtualIP: "+fmt.Sprintf("%#v", this.VirtualIP)+",\n") - s = append(s, "EndpointIP: "+fmt.Sprintf("%#v", this.EndpointIP)+",\n") - if this.IngressPorts != nil { - s = append(s, "IngressPorts: "+fmt.Sprintf("%#v", this.IngressPorts)+",\n") - } - s = append(s, "Aliases: "+fmt.Sprintf("%#v", this.Aliases)+",\n") - s = append(s, "TaskAliases: "+fmt.Sprintf("%#v", this.TaskAliases)+",\n") - s = append(s, "ServiceDisabled: "+fmt.Sprintf("%#v", this.ServiceDisabled)+",\n") - s = append(s, "}") - return strings.Join(s, "") -} -func (this *PortConfig) GoString() string { - if this == nil { - return "nil" - } - s := make([]string, 0, 8) - s = append(s, "&libnetwork.PortConfig{") - s = append(s, "Name: "+fmt.Sprintf("%#v", this.Name)+",\n") - s = append(s, "Protocol: "+fmt.Sprintf("%#v", this.Protocol)+",\n") - s = append(s, "TargetPort: "+fmt.Sprintf("%#v", this.TargetPort)+",\n") - s = append(s, "PublishedPort: "+fmt.Sprintf("%#v", this.PublishedPort)+",\n") - s = append(s, "}") - return strings.Join(s, "") -} -func valueToGoStringAgent(v interface{}, typ string) string { - rv := reflect.ValueOf(v) - if rv.IsNil() { - return "nil" - } - pv := reflect.Indirect(rv).Interface() - return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv) -} -func (m *EndpointRecord) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalTo(dAtA) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *EndpointRecord) MarshalTo(dAtA []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if len(m.Name) > 0 { - dAtA[i] = 0xa - i++ - i = encodeVarintAgent(dAtA, i, uint64(len(m.Name))) - i += copy(dAtA[i:], m.Name) - } - if len(m.ServiceName) > 0 { - dAtA[i] = 0x12 - i++ - i = encodeVarintAgent(dAtA, i, uint64(len(m.ServiceName))) - i += copy(dAtA[i:], m.ServiceName) - } - if len(m.ServiceID) > 0 { - dAtA[i] = 0x1a - i++ - i = encodeVarintAgent(dAtA, i, uint64(len(m.ServiceID))) - i += copy(dAtA[i:], m.ServiceID) - } - if len(m.VirtualIP) > 0 { - dAtA[i] = 0x22 - i++ - i = encodeVarintAgent(dAtA, i, uint64(len(m.VirtualIP))) - i += copy(dAtA[i:], m.VirtualIP) - } - if len(m.EndpointIP) > 0 { - dAtA[i] = 0x2a - i++ - i = encodeVarintAgent(dAtA, i, uint64(len(m.EndpointIP))) - i += copy(dAtA[i:], m.EndpointIP) - } - if len(m.IngressPorts) > 0 { - for _, msg := range m.IngressPorts { - dAtA[i] = 0x32 - i++ - i = encodeVarintAgent(dAtA, i, uint64(msg.Size())) - n, err := msg.MarshalTo(dAtA[i:]) - if err != nil { - return 0, err - } - i += n - } - } - if len(m.Aliases) > 0 { - for _, s := range m.Aliases { - dAtA[i] = 0x3a - i++ - l = len(s) - for l >= 1<<7 { - dAtA[i] = uint8(uint64(l)&0x7f | 0x80) - l >>= 7 - i++ - } - dAtA[i] = uint8(l) - i++ - i += copy(dAtA[i:], s) - } - } - if len(m.TaskAliases) > 0 { - for _, s := range m.TaskAliases { - dAtA[i] = 0x42 - i++ - l = len(s) - for l >= 1<<7 { - dAtA[i] = uint8(uint64(l)&0x7f | 0x80) - l >>= 7 - i++ - } - dAtA[i] = uint8(l) - i++ - i += copy(dAtA[i:], s) - } - } - if m.ServiceDisabled { - dAtA[i] = 0x48 - i++ - if m.ServiceDisabled { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i++ - } - return i, nil -} - -func (m *PortConfig) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalTo(dAtA) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *PortConfig) MarshalTo(dAtA []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if len(m.Name) > 0 { - dAtA[i] = 0xa - i++ - i = encodeVarintAgent(dAtA, i, uint64(len(m.Name))) - i += copy(dAtA[i:], m.Name) - } - if m.Protocol != 0 { - dAtA[i] = 0x10 - i++ - i = encodeVarintAgent(dAtA, i, uint64(m.Protocol)) - } - if m.TargetPort != 0 { - dAtA[i] = 0x18 - i++ - i = encodeVarintAgent(dAtA, i, uint64(m.TargetPort)) - } - if m.PublishedPort != 0 { - dAtA[i] = 0x20 - i++ - i = encodeVarintAgent(dAtA, i, uint64(m.PublishedPort)) - } - return i, nil -} - -func encodeVarintAgent(dAtA []byte, offset int, v uint64) int { - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return offset + 1 -} -func (m *EndpointRecord) Size() (n int) { - var l int - _ = l - l = len(m.Name) - if l > 0 { - n += 1 + l + sovAgent(uint64(l)) - } - l = len(m.ServiceName) - if l > 0 { - n += 1 + l + sovAgent(uint64(l)) - } - l = len(m.ServiceID) - if l > 0 { - n += 1 + l + sovAgent(uint64(l)) - } - l = len(m.VirtualIP) - if l > 0 { - n += 1 + l + sovAgent(uint64(l)) - } - l = len(m.EndpointIP) - if l > 0 { - n += 1 + l + sovAgent(uint64(l)) - } - if len(m.IngressPorts) > 0 { - for _, e := range m.IngressPorts { - l = e.Size() - n += 1 + l + sovAgent(uint64(l)) - } - } - if len(m.Aliases) > 0 { - for _, s := range m.Aliases { - l = len(s) - n += 1 + l + sovAgent(uint64(l)) - } - } - if len(m.TaskAliases) > 0 { - for _, s := range m.TaskAliases { - l = len(s) - n += 1 + l + sovAgent(uint64(l)) - } - } - if m.ServiceDisabled { - n += 2 - } - return n -} - -func (m *PortConfig) Size() (n int) { - var l int - _ = l - l = len(m.Name) - if l > 0 { - n += 1 + l + sovAgent(uint64(l)) - } - if m.Protocol != 0 { - n += 1 + sovAgent(uint64(m.Protocol)) - } - if m.TargetPort != 0 { - n += 1 + sovAgent(uint64(m.TargetPort)) - } - if m.PublishedPort != 0 { - n += 1 + sovAgent(uint64(m.PublishedPort)) - } - return n -} - -func sovAgent(x uint64) (n int) { - for { - n++ - x >>= 7 - if x == 0 { - break - } - } - return n -} -func sozAgent(x uint64) (n int) { - return sovAgent(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (this *EndpointRecord) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&EndpointRecord{`, - `Name:` + fmt.Sprintf("%v", this.Name) + `,`, - `ServiceName:` + fmt.Sprintf("%v", this.ServiceName) + `,`, - `ServiceID:` + fmt.Sprintf("%v", this.ServiceID) + `,`, - `VirtualIP:` + fmt.Sprintf("%v", this.VirtualIP) + `,`, - `EndpointIP:` + fmt.Sprintf("%v", this.EndpointIP) + `,`, - `IngressPorts:` + strings.Replace(fmt.Sprintf("%v", this.IngressPorts), "PortConfig", "PortConfig", 1) + `,`, - `Aliases:` + fmt.Sprintf("%v", this.Aliases) + `,`, - `TaskAliases:` + fmt.Sprintf("%v", this.TaskAliases) + `,`, - `ServiceDisabled:` + fmt.Sprintf("%v", this.ServiceDisabled) + `,`, - `}`, - }, "") - return s -} -func (this *PortConfig) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&PortConfig{`, - `Name:` + fmt.Sprintf("%v", this.Name) + `,`, - `Protocol:` + fmt.Sprintf("%v", this.Protocol) + `,`, - `TargetPort:` + fmt.Sprintf("%v", this.TargetPort) + `,`, - `PublishedPort:` + fmt.Sprintf("%v", this.PublishedPort) + `,`, - `}`, - }, "") - return s -} -func valueToStringAgent(v interface{}) string { - rv := reflect.ValueOf(v) - if rv.IsNil() { - return "nil" - } - pv := reflect.Indirect(rv).Interface() - return fmt.Sprintf("*%v", pv) -} -func (m *EndpointRecord) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAgent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: EndpointRecord: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: EndpointRecord: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAgent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthAgent - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Name = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ServiceName", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAgent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthAgent - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ServiceName = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ServiceID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAgent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthAgent - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ServiceID = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field VirtualIP", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAgent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthAgent - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.VirtualIP = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field EndpointIP", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAgent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthAgent - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.EndpointIP = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IngressPorts", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAgent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAgent - } - postIndex := iNdEx + msglen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.IngressPorts = append(m.IngressPorts, &PortConfig{}) - if err := m.IngressPorts[len(m.IngressPorts)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Aliases", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAgent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthAgent - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Aliases = append(m.Aliases, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TaskAliases", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAgent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthAgent - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.TaskAliases = append(m.TaskAliases, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex - case 9: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ServiceDisabled", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAgent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - m.ServiceDisabled = bool(v != 0) - default: - iNdEx = preIndex - skippy, err := skipAgent(dAtA[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthAgent - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *PortConfig) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAgent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: PortConfig: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: PortConfig: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAgent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthAgent - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Name = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Protocol", wireType) - } - m.Protocol = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAgent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Protocol |= (PortConfig_Protocol(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field TargetPort", wireType) - } - m.TargetPort = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAgent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.TargetPort |= (uint32(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - case 4: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field PublishedPort", wireType) - } - m.PublishedPort = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAgent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.PublishedPort |= (uint32(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipAgent(dAtA[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthAgent - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipAgent(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowAgent - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowAgent - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - return iNdEx, nil - case 1: - iNdEx += 8 - return iNdEx, nil - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowAgent - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - iNdEx += length - if length < 0 { - return 0, ErrInvalidLengthAgent - } - return iNdEx, nil - case 3: - for { - var innerWire uint64 - var start int = iNdEx - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowAgent - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - innerWire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - innerWireType := int(innerWire & 0x7) - if innerWireType == 4 { - break - } - next, err := skipAgent(dAtA[start:]) - if err != nil { - return 0, err - } - iNdEx = start + next - } - return iNdEx, nil - case 4: - return iNdEx, nil - case 5: - iNdEx += 4 - return iNdEx, nil - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - } - panic("unreachable") -} - -var ( - ErrInvalidLengthAgent = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowAgent = fmt.Errorf("proto: integer overflow") -) - -func init() { proto.RegisterFile("agent.proto", fileDescriptorAgent) } - -var fileDescriptorAgent = []byte{ - // 459 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x6c, 0x91, 0x31, 0x6f, 0xd3, 0x4c, - 0x18, 0xc7, 0xe3, 0xc4, 0x6f, 0x1b, 0x3f, 0x4e, 0x52, 0xeb, 0xf4, 0x0a, 0x59, 0x1e, 0x1c, 0x13, - 0x09, 0x29, 0x48, 0x28, 0x95, 0xca, 0xd8, 0x89, 0x26, 0x0c, 0x5e, 0x90, 0x75, 0x4d, 0x59, 0x83, - 0x13, 0x1f, 0xe6, 0x54, 0xe3, 0xb3, 0xee, 0xae, 0x65, 0x65, 0x03, 0xf5, 0x3b, 0x74, 0xe2, 0xcb, - 0x30, 0x32, 0x32, 0x55, 0xd4, 0x9f, 0x80, 0x95, 0x0d, 0xdd, 0xf9, 0xae, 0x11, 0x52, 0xb7, 0xf3, - 0xef, 0xff, 0x3b, 0xeb, 0xb9, 0xff, 0x03, 0x7e, 0x5e, 0x92, 0x5a, 0x2e, 0x1a, 0xce, 0x24, 0x43, - 0x50, 0xd1, 0x6d, 0x4d, 0xe4, 0x27, 0xc6, 0x2f, 0xa3, 0xff, 0x4b, 0x56, 0x32, 0x8d, 0x8f, 0xd5, - 0xa9, 0x33, 0x66, 0x7f, 0xfa, 0x30, 0x79, 0x5d, 0x17, 0x0d, 0xa3, 0xb5, 0xc4, 0x64, 0xc7, 0x78, - 0x81, 0x10, 0xb8, 0x75, 0xfe, 0x91, 0x84, 0x4e, 0xe2, 0xcc, 0x3d, 0xac, 0xcf, 0xe8, 0x29, 0x8c, - 0x04, 0xe1, 0xd7, 0x74, 0x47, 0x36, 0x3a, 0xeb, 0xeb, 0xcc, 0x37, 0xec, 0x8d, 0x52, 0x5e, 0x00, - 0x58, 0x85, 0x16, 0xe1, 0x40, 0x09, 0x67, 0xe3, 0xf6, 0x6e, 0xea, 0x9d, 0x77, 0x34, 0x5d, 0x61, - 0xcf, 0x08, 0x69, 0xa1, 0xec, 0x6b, 0xca, 0xe5, 0x55, 0x5e, 0x6d, 0x68, 0x13, 0xba, 0x7b, 0xfb, - 0x6d, 0x47, 0xd3, 0x0c, 0x7b, 0x46, 0x48, 0x1b, 0x74, 0x0c, 0x3e, 0x31, 0x43, 0x2a, 0xfd, 0x3f, - 0xad, 0x4f, 0xda, 0xbb, 0x29, 0xd8, 0xd9, 0xd3, 0x0c, 0x83, 0x55, 0xd2, 0x06, 0x9d, 0xc2, 0x98, - 0xd6, 0x25, 0x27, 0x42, 0x6c, 0x1a, 0xc6, 0xa5, 0x08, 0x0f, 0x92, 0xc1, 0xdc, 0x3f, 0x79, 0xb2, - 0xd8, 0x17, 0xb2, 0xc8, 0x18, 0x97, 0x4b, 0x56, 0xbf, 0xa7, 0x25, 0x1e, 0x19, 0x59, 0x21, 0x81, - 0x42, 0x38, 0xcc, 0x2b, 0x9a, 0x0b, 0x22, 0xc2, 0xc3, 0x64, 0x30, 0xf7, 0xb0, 0xfd, 0x54, 0x35, - 0xc8, 0x5c, 0x5c, 0x6e, 0x6c, 0x3c, 0xd4, 0xb1, 0xaf, 0xd8, 0x2b, 0xa3, 0x3c, 0x87, 0xc0, 0xd6, - 0x50, 0x50, 0x91, 0x6f, 0x2b, 0x52, 0x84, 0x5e, 0xe2, 0xcc, 0x87, 0xf8, 0xc8, 0xf0, 0x95, 0xc1, - 0xb3, 0x2f, 0x7d, 0x80, 0xfd, 0x10, 0x8f, 0xf6, 0x7e, 0x0a, 0x43, 0xbd, 0xa7, 0x1d, 0xab, 0x74, - 0xe7, 0x93, 0x93, 0xe9, 0xe3, 0x4f, 0x58, 0x64, 0x46, 0xc3, 0x0f, 0x17, 0xd0, 0x14, 0x7c, 0x99, - 0xf3, 0x92, 0x48, 0xdd, 0x81, 0x5e, 0xc9, 0x18, 0x43, 0x87, 0xd4, 0x4d, 0xf4, 0x0c, 0x26, 0xcd, - 0xd5, 0xb6, 0xa2, 0xe2, 0x03, 0x29, 0x3a, 0xc7, 0xd5, 0xce, 0xf8, 0x81, 0x2a, 0x6d, 0xf6, 0x0e, - 0x86, 0xf6, 0xef, 0x28, 0x84, 0xc1, 0x7a, 0x99, 0x05, 0xbd, 0xe8, 0xe8, 0xe6, 0x36, 0xf1, 0x2d, - 0x5e, 0x2f, 0x33, 0x95, 0x5c, 0xac, 0xb2, 0xc0, 0xf9, 0x37, 0xb9, 0x58, 0x65, 0x28, 0x02, 0xf7, - 0x7c, 0xb9, 0xce, 0x82, 0x7e, 0x14, 0xdc, 0xdc, 0x26, 0x23, 0x1b, 0x29, 0x16, 0xb9, 0x5f, 0xbf, - 0xc5, 0xbd, 0xb3, 0xf0, 0xe7, 0x7d, 0xdc, 0xfb, 0x7d, 0x1f, 0x3b, 0x9f, 0xdb, 0xd8, 0xf9, 0xde, - 0xc6, 0xce, 0x8f, 0x36, 0x76, 0x7e, 0xb5, 0xb1, 0xb3, 0x3d, 0xd0, 0xaf, 0x79, 0xf9, 0x37, 0x00, - 0x00, 0xff, 0xff, 0x55, 0x29, 0x75, 0x5c, 0xd7, 0x02, 0x00, 0x00, -} diff --git a/vendor/github.com/docker/libnetwork/agent.proto b/vendor/github.com/docker/libnetwork/agent.proto deleted file mode 100644 index f9c46c7a98..0000000000 --- a/vendor/github.com/docker/libnetwork/agent.proto +++ /dev/null @@ -1,76 +0,0 @@ -syntax = "proto3"; - -import "gogoproto/gogo.proto"; - -package libnetwork; - -option (gogoproto.marshaler_all) = true; -option (gogoproto.unmarshaler_all) = true; -option (gogoproto.stringer_all) = true; -option (gogoproto.gostring_all) = true; -option (gogoproto.sizer_all) = true; -option (gogoproto.goproto_stringer_all) = false; - -// EndpointRecord specifies all the endpoint specific information that -// needs to gossiped to nodes participating in the network. -message EndpointRecord { - // Name of the container - string name = 1; - - // Service name of the service to which this endpoint belongs. - string service_name = 2; - - // Service ID of the service to which this endpoint belongs. - string service_id = 3 [(gogoproto.customname) = "ServiceID"]; - - // Virtual IP of the service to which this endpoint belongs. - string virtual_ip = 4 [(gogoproto.customname) = "VirtualIP"]; - - // IP assigned to this endpoint. - string endpoint_ip = 5 [(gogoproto.customname) = "EndpointIP"]; - - // IngressPorts exposed by the service to which this endpoint belongs. - repeated PortConfig ingress_ports = 6; - - // A list of aliases which are alternate names for the service - repeated string aliases = 7; - - // List of aliases task specific aliases - repeated string task_aliases = 8; - - // Whether this enpoint's service has been disabled - bool service_disabled = 9; -} - -// PortConfig specifies an exposed port which can be -// addressed using the given name. This can be later queried -// using a service discovery api or a DNS SRV query. The node -// port specifies a port that can be used to address this -// service external to the cluster by sending a connection -// request to this port to any node on the cluster. -message PortConfig { - enum Protocol { - option (gogoproto.goproto_enum_prefix) = false; - - TCP = 0 [(gogoproto.enumvalue_customname) = "ProtocolTCP"]; - UDP = 1 [(gogoproto.enumvalue_customname) = "ProtocolUDP"]; - SCTP = 2 [(gogoproto.enumvalue_customname) = "ProtocolSCTP"]; - } - - // Name for the port. If provided the port information can - // be queried using the name as in a DNS SRV query. - string name = 1; - - // Protocol for the port which is exposed. - Protocol protocol = 2; - - // The port which the application is exposing and is bound to. - uint32 target_port = 3; - - // PublishedPort specifies the port on which the service is - // exposed on all nodes on the cluster. If not specified an - // arbitrary port in the node port range is allocated by the - // system. If specified it should be within the node port - // range and it should be available. - uint32 published_port = 4; -} diff --git a/vendor/github.com/docker/libnetwork/bitseq/sequence.go b/vendor/github.com/docker/libnetwork/bitseq/sequence.go deleted file mode 100644 index e10b2eedc0..0000000000 --- a/vendor/github.com/docker/libnetwork/bitseq/sequence.go +++ /dev/null @@ -1,736 +0,0 @@ -// Package bitseq provides a structure and utilities for representing long bitmask -// as sequence of run-length encoded blocks. It operates directly on the encoded -// representation, it does not decode/encode. -package bitseq - -import ( - "encoding/binary" - "encoding/json" - "errors" - "fmt" - "sync" - - "github.com/docker/libnetwork/datastore" - "github.com/docker/libnetwork/types" - "github.com/sirupsen/logrus" -) - -// block sequence constants -// If needed we can think of making these configurable -const ( - blockLen = uint32(32) - blockBytes = uint64(blockLen / 8) - blockMAX = uint32(1<%s", s.block, s.count, nextBlock) -} - -// 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 -} - -// 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 -} - -// 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 -} - -// 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 -} - -// 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 -} - -func (h *Handle) getCopy() *Handle { - return &Handle{ - bits: h.bits, - unselected: h.unselected, - head: h.head.getCopy(), - app: h.app, - id: h.id, - dbIndex: h.dbIndex, - dbExists: h.dbExists, - store: h.store, - curr: h.curr, - } -} - -// 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) -} - -// 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) -} - -// 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 -} - -// 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 -} - -// 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 -} - -func (h *Handle) runConsistencyCheck() bool { - corrupted := false - for p, c := h.head, h.head.next; c != nil; c = c.next { - if c.count == 0 { - corrupted = true - p.next = c.next - continue // keep same p - } - p = c - } - return corrupted -} - -// CheckConsistency checks if the bit sequence is in an inconsistent state and attempts to fix it. -// It looks for a corruption signature that may happen in docker 1.9.0 and 1.9.1. -func (h *Handle) CheckConsistency() error { - for { - h.Lock() - store := h.store - h.Unlock() - - if store != nil { - if err := store.GetObject(datastore.Key(h.Key()...), h); err != nil && err != datastore.ErrKeyNotFound { - return err - } - } - - h.Lock() - nh := h.getCopy() - h.Unlock() - - if !nh.runConsistencyCheck() { - return nil - } - - if err := nh.writeToStore(); err != nil { - if _, ok := err.(types.RetryError); !ok { - return fmt.Errorf("internal failure while fixing inconsistent bitsequence: %v", err) - } - continue - } - - logrus.Infof("Fixed inconsistent bit sequence in datastore:\n%s\n%s", h, nh) - - h.Lock() - h.head = nh.head - h.Unlock() - - return nil - } -} - -// set/reset the bit -func (h *Handle) set(ordinal, start, end uint64, any bool, release bool, serial bool) (uint64, error) { - var ( - bitPos uint64 - bytePos uint64 - ret uint64 - err error - ) - - for { - var store datastore.DataStore - curr := uint64(0) - h.Lock() - store = h.store - if store != nil { - h.Unlock() // The lock is acquired in the GetObject - if err := store.GetObject(datastore.Key(h.Key()...), h); err != nil && err != datastore.ErrKeyNotFound { - return ret, err - } - h.Lock() // Acquire the lock back - } - if serial { - curr = h.curr - } - // Get position if available - if release { - bytePos, bitPos = ordinalToPos(ordinal) - } else { - if any { - bytePos, bitPos, err = getAvailableFromCurrent(h.head, start, curr, end) - ret = posToOrdinal(bytePos, bitPos) - if err == nil { - h.curr = ret + 1 - } - } else { - bytePos, bitPos, err = checkIfAvailable(h.head, ordinal) - ret = ordinal - } - } - if err != nil { - h.Unlock() - return ret, err - } - - // Create a private copy of h and work on it - nh := h.getCopy() - - nh.head = pushReservation(bytePos, bitPos, nh.head, release) - if release { - nh.unselected++ - } else { - nh.unselected-- - } - - if h.store != nil { - h.Unlock() - // Attempt to write private copy to store - if err := nh.writeToStore(); err != nil { - if _, ok := err.(types.RetryError); !ok { - return ret, fmt.Errorf("internal failure while setting the bit: %v", err) - } - // Retry - continue - } - h.Lock() - } - - // Previous atomic push was successful. Save private copy to local copy - h.unselected = nh.unselected - h.head = nh.head - h.dbExists = nh.dbExists - h.dbIndex = nh.dbIndex - h.Unlock() - return ret, nil - } -} - -// checks is needed because to cover the case where the number of bits is not a multiple of blockLen -func (h *Handle) validateOrdinal(ordinal uint64) error { - h.Lock() - defer h.Unlock() - if ordinal >= h.bits { - return errors.New("bit does not belong to the sequence") - } - return nil -} - -// Destroy removes from the datastore the data belonging to this handle -func (h *Handle) Destroy() error { - for { - if err := h.deleteFromStore(); err != nil { - if _, ok := err.(types.RetryError); !ok { - return fmt.Errorf("internal failure while destroying the sequence: %v", err) - } - // Fetch latest - if err := h.store.GetObject(datastore.Key(h.Key()...), h); err != nil { - if err == datastore.ErrKeyNotFound { // already removed - return nil - } - return fmt.Errorf("failed to fetch from store when destroying the sequence: %v", err) - } - continue - } - return nil - } -} - -// ToByteArray converts this handle's data into a byte array -func (h *Handle) ToByteArray() ([]byte, error) { - - h.Lock() - defer h.Unlock() - ba := make([]byte, 16) - binary.BigEndian.PutUint64(ba[0:], h.bits) - binary.BigEndian.PutUint64(ba[8:], h.unselected) - bm, err := h.head.toByteArray() - if err != nil { - return nil, fmt.Errorf("failed to serialize head: %s", err.Error()) - } - ba = append(ba, bm...) - - return ba, nil -} - -// FromByteArray reads his handle's data from a byte array -func (h *Handle) FromByteArray(ba []byte) error { - if ba == nil { - return errors.New("nil byte array") - } - - nh := &sequence{} - err := nh.fromByteArray(ba[16:]) - if err != nil { - return fmt.Errorf("failed to deserialize head: %s", err.Error()) - } - - h.Lock() - h.head = nh - h.bits = binary.BigEndian.Uint64(ba[0:8]) - h.unselected = binary.BigEndian.Uint64(ba[8:16]) - h.Unlock() - - return nil -} - -// Bits returns the length of the bit sequence -func (h *Handle) Bits() uint64 { - return h.bits -} - -// Unselected returns the number of bits which are not selected -func (h *Handle) Unselected() uint64 { - h.Lock() - defer h.Unlock() - return h.unselected -} - -func (h *Handle) String() string { - h.Lock() - defer h.Unlock() - return fmt.Sprintf("App: %s, ID: %s, DBIndex: 0x%x, Bits: %d, Unselected: %d, Sequence: %s Curr:%d", - h.app, h.id, h.dbIndex, h.bits, h.unselected, h.head.toString(), h.curr) -} - -// MarshalJSON encodes Handle into json message -func (h *Handle) MarshalJSON() ([]byte, error) { - m := map[string]interface{}{ - "id": h.id, - } - - b, err := h.ToByteArray() - if err != nil { - return nil, err - } - m["sequence"] = b - return json.Marshal(m) -} - -// UnmarshalJSON decodes json message into Handle -func (h *Handle) UnmarshalJSON(data []byte) error { - var ( - m map[string]interface{} - b []byte - err error - ) - if err = json.Unmarshal(data, &m); err != nil { - return err - } - h.id = m["id"].(string) - bi, _ := json.Marshal(m["sequence"]) - if err := json.Unmarshal(bi, &b); err != nil { - return err - } - return h.FromByteArray(b) -} - -// getFirstAvailable looks for the first unset bit in passed mask starting from start -func getFirstAvailable(head *sequence, start uint64) (uint64, uint64, error) { - // Find sequence which contains the start bit - byteStart, bitStart := ordinalToPos(start) - current, _, precBlocks, inBlockBytePos := findSequence(head, byteStart) - // Derive the this sequence offsets - byteOffset := byteStart - inBlockBytePos - bitOffset := inBlockBytePos*8 + bitStart - for current != nil { - if current.block != blockMAX { - // If the current block is not full, check if there is any bit - // from the current bit in the current block. If not, before proceeding to the - // next block node, make sure we check for available bit in the next - // instance of the same block. Due to RLE same block signature will be - // compressed. - retry: - bytePos, bitPos, err := current.getAvailableBit(bitOffset) - if err != nil && precBlocks == current.count-1 { - // This is the last instance in the same block node, - // so move to the next block. - goto next - } - if err != nil { - // There are some more instances of the same block, so add the offset - // and be optimistic that you will find the available bit in the next - // instance of the same block. - bitOffset = 0 - byteOffset += blockBytes - precBlocks++ - goto retry - } - return byteOffset + bytePos, bitPos, err - } - // Moving to next block: Reset bit offset. - next: - bitOffset = 0 - byteOffset += (current.count * blockBytes) - (precBlocks * blockBytes) - precBlocks = 0 - current = current.next - } - return invalidPos, invalidPos, ErrNoBitAvailable -} - -// getAvailableFromCurrent will look for available ordinal from the current ordinal. -// If none found then it will loop back to the start to check of the available bit. -// This can be further optimized to check from start till curr in case of a rollover -func getAvailableFromCurrent(head *sequence, start, curr, end uint64) (uint64, uint64, error) { - var bytePos, bitPos uint64 - var err error - if curr != 0 && curr > start { - bytePos, bitPos, err = getFirstAvailable(head, curr) - ret := posToOrdinal(bytePos, bitPos) - if end < ret || err != nil { - goto begin - } - return bytePos, bitPos, nil - } - -begin: - bytePos, bitPos, err = getFirstAvailable(head, start) - ret := posToOrdinal(bytePos, bitPos) - if end < ret || err != nil { - return invalidPos, invalidPos, ErrNoBitAvailable - } - return bytePos, bitPos, nil -} - -// checkIfAvailable checks if the bit correspondent to the specified ordinal is unset -// If the ordinal is beyond the sequence limits, a negative response is returned -func checkIfAvailable(head *sequence, ordinal uint64) (uint64, uint64, error) { - bytePos, bitPos := ordinalToPos(ordinal) - - // Find the sequence containing this byte - current, _, _, inBlockBytePos := findSequence(head, bytePos) - if current != nil { - // Check whether the bit corresponding to the ordinal address is unset - bitSel := blockFirstBit >> (inBlockBytePos*8 + bitPos) - if current.block&bitSel == 0 { - return bytePos, bitPos, nil - } - } - - return invalidPos, invalidPos, ErrBitAllocated -} - -// Given the byte position and the sequences list head, return the pointer to the -// sequence containing the byte (current), the pointer to the previous sequence, -// the number of blocks preceding the block containing the byte inside the current sequence. -// If bytePos is outside of the list, function will return (nil, nil, 0, invalidPos) -func findSequence(head *sequence, bytePos uint64) (*sequence, *sequence, uint64, uint64) { - // Find the sequence containing this byte - previous := head - current := head - n := bytePos - for current.next != nil && n >= (current.count*blockBytes) { // Nil check for less than 32 addresses masks - n -= (current.count * blockBytes) - previous = current - current = current.next - } - - // If byte is outside of the list, let caller know - if n >= (current.count * blockBytes) { - return nil, nil, 0, invalidPos - } - - // Find the byte position inside the block and the number of blocks - // preceding the block containing the byte inside this sequence - precBlocks := n / blockBytes - inBlockBytePos := bytePos % blockBytes - - return current, previous, precBlocks, inBlockBytePos -} - -// PushReservation pushes the bit reservation inside the bitmask. -// Given byte and bit positions, identify the sequence (current) which holds the block containing the affected bit. -// Create a new block with the modified bit according to the operation (allocate/release). -// Create a new sequence containing the new block and insert it in the proper position. -// Remove current sequence if empty. -// Check if new sequence can be merged with neighbour (previous/next) sequences. -// -// -// Identify "current" sequence containing block: -// [prev seq] [current seq] [next seq] -// -// Based on block position, resulting list of sequences can be any of three forms: -// -// block position Resulting list of sequences -// A) block is first in current: [prev seq] [new] [modified current seq] [next seq] -// B) block is last in current: [prev seq] [modified current seq] [new] [next seq] -// C) block is in the middle of current: [prev seq] [curr pre] [new] [curr post] [next seq] -func pushReservation(bytePos, bitPos uint64, head *sequence, release bool) *sequence { - // Store list's head - newHead := head - - // Find the sequence containing this byte - current, previous, precBlocks, inBlockBytePos := findSequence(head, bytePos) - if current == nil { - return newHead - } - - // Construct updated block - bitSel := blockFirstBit >> (inBlockBytePos*8 + bitPos) - newBlock := current.block - if release { - newBlock &^= bitSel - } else { - newBlock |= bitSel - } - - // Quit if it was a redundant request - if current.block == newBlock { - return newHead - } - - // Current sequence inevitably looses one block, upadate count - current.count-- - - // Create new sequence - newSequence := &sequence{block: newBlock, count: 1} - - // Insert the new sequence in the list based on block position - if precBlocks == 0 { // First in sequence (A) - newSequence.next = current - if current == head { - newHead = newSequence - previous = newHead - } else { - previous.next = newSequence - } - removeCurrentIfEmpty(&newHead, newSequence, current) - mergeSequences(previous) - } else if precBlocks == current.count { // Last in sequence (B) - newSequence.next = current.next - current.next = newSequence - mergeSequences(current) - } else { // In between the sequence (C) - currPre := &sequence{block: current.block, count: precBlocks, next: newSequence} - currPost := current - currPost.count -= precBlocks - newSequence.next = currPost - if currPost == head { - newHead = currPre - } else { - previous.next = currPre - } - // No merging or empty current possible here - } - - return newHead -} - -// Removes the current sequence from the list if empty, adjusting the head pointer if needed -func removeCurrentIfEmpty(head **sequence, previous, current *sequence) { - if current.count == 0 { - if current == *head { - *head = current.next - } else { - previous.next = current.next - current = current.next - } - } -} - -// Given a pointer to a sequence, it checks if it can be merged with any following sequences -// It stops when no more merging is possible. -// TODO: Optimization: only attempt merge from start to end sequence, no need to scan till the end of the list -func mergeSequences(seq *sequence) { - if seq != nil { - // Merge all what possible from seq - for seq.next != nil && seq.block == seq.next.block { - seq.count += seq.next.count - seq.next = seq.next.next - } - // Move to next - mergeSequences(seq.next) - } -} - -func getNumBlocks(numBits uint64) uint64 { - numBlocks := numBits / uint64(blockLen) - if numBits%uint64(blockLen) != 0 { - numBlocks++ - } - return numBlocks -} - -func ordinalToPos(ordinal uint64) (uint64, uint64) { - return ordinal / 8, ordinal % 8 -} - -func posToOrdinal(bytePos, bitPos uint64) uint64 { - return bytePos*8 + bitPos -} diff --git a/vendor/github.com/docker/libnetwork/bitseq/store.go b/vendor/github.com/docker/libnetwork/bitseq/store.go deleted file mode 100644 index cdb7f04264..0000000000 --- a/vendor/github.com/docker/libnetwork/bitseq/store.go +++ /dev/null @@ -1,142 +0,0 @@ -package bitseq - -import ( - "encoding/json" - "fmt" - - "github.com/docker/libnetwork/datastore" - "github.com/docker/libnetwork/types" -) - -// Key provides the Key to be used in KV Store -func (h *Handle) Key() []string { - h.Lock() - defer h.Unlock() - return []string{h.app, h.id} -} - -// KeyPrefix returns the immediate parent key that can be used for tree walk -func (h *Handle) KeyPrefix() []string { - h.Lock() - defer h.Unlock() - return []string{h.app} -} - -// Value marshals the data to be stored in the KV store -func (h *Handle) Value() []byte { - b, err := json.Marshal(h) - if err != nil { - return nil - } - return b -} - -// SetValue unmarshals the data from the KV store -func (h *Handle) SetValue(value []byte) error { - return json.Unmarshal(value, h) -} - -// Index returns the latest DB Index as seen by this object -func (h *Handle) Index() uint64 { - h.Lock() - defer h.Unlock() - return h.dbIndex -} - -// SetIndex method allows the datastore to store the latest DB Index into this object -func (h *Handle) SetIndex(index uint64) { - h.Lock() - h.dbIndex = index - h.dbExists = true - h.Unlock() -} - -// Exists method is true if this object has been stored in the DB. -func (h *Handle) Exists() bool { - h.Lock() - defer h.Unlock() - return h.dbExists -} - -// New method returns a handle based on the receiver handle -func (h *Handle) New() datastore.KVObject { - h.Lock() - defer h.Unlock() - - return &Handle{ - app: h.app, - store: h.store, - } -} - -// CopyTo deep copies the handle into the passed destination object -func (h *Handle) CopyTo(o datastore.KVObject) error { - h.Lock() - defer h.Unlock() - - dstH := o.(*Handle) - if h == dstH { - return nil - } - dstH.Lock() - dstH.bits = h.bits - dstH.unselected = h.unselected - dstH.head = h.head.getCopy() - dstH.app = h.app - dstH.id = h.id - dstH.dbIndex = h.dbIndex - dstH.dbExists = h.dbExists - dstH.store = h.store - dstH.curr = h.curr - dstH.Unlock() - - return nil -} - -// Skip provides a way for a KV Object to avoid persisting it in the KV Store -func (h *Handle) Skip() bool { - return false -} - -// DataScope method returns the storage scope of the datastore -func (h *Handle) DataScope() string { - h.Lock() - defer h.Unlock() - - return h.store.Scope() -} - -func (h *Handle) fromDsValue(value []byte) error { - var ba []byte - if err := json.Unmarshal(value, &ba); err != nil { - return fmt.Errorf("failed to decode json: %s", err.Error()) - } - if err := h.FromByteArray(ba); err != nil { - return fmt.Errorf("failed to decode handle: %s", err.Error()) - } - return nil -} - -func (h *Handle) writeToStore() error { - h.Lock() - store := h.store - h.Unlock() - if store == nil { - return nil - } - err := store.PutObjectAtomic(h) - if err == datastore.ErrKeyModified { - return types.RetryErrorf("failed to perform atomic write (%v). Retry might fix the error", err) - } - return err -} - -func (h *Handle) deleteFromStore() error { - h.Lock() - store := h.store - h.Unlock() - if store == nil { - return nil - } - return store.DeleteObjectAtomic(h) -} diff --git a/vendor/github.com/docker/libnetwork/cluster/provider.go b/vendor/github.com/docker/libnetwork/cluster/provider.go deleted file mode 100644 index 0259eb7005..0000000000 --- a/vendor/github.com/docker/libnetwork/cluster/provider.go +++ /dev/null @@ -1,37 +0,0 @@ -package cluster - -import ( - "context" - - "github.com/docker/docker/api/types/network" -) - -const ( - // EventSocketChange control socket changed - EventSocketChange = iota - // EventNodeReady cluster node in ready state - EventNodeReady - // EventNodeLeave node is leaving the cluster - EventNodeLeave - // EventNetworkKeysAvailable network keys correctly configured in the networking layer - EventNetworkKeysAvailable -) - -// ConfigEventType type of the event produced by the cluster -type ConfigEventType uint8 - -// Provider provides clustering config details -type Provider interface { - IsManager() bool - IsAgent() bool - GetLocalAddress() string - GetListenAddress() string - GetAdvertiseAddress() string - GetDataPathAddress() string - GetRemoteAddressList() []string - ListenClusterEvents() <-chan ConfigEventType - AttachNetwork(string, string, []string) (*network.NetworkingConfig, error) - DetachNetwork(string, string) error - UpdateAttachment(string, string, *network.NetworkingConfig) error - WaitForDetachment(context.Context, string, string, string, string) error -} diff --git a/vendor/github.com/docker/libnetwork/config/config.go b/vendor/github.com/docker/libnetwork/config/config.go deleted file mode 100644 index 6af5a01953..0000000000 --- a/vendor/github.com/docker/libnetwork/config/config.go +++ /dev/null @@ -1,328 +0,0 @@ -package config - -import ( - "fmt" - "strings" - - "github.com/BurntSushi/toml" - "github.com/docker/docker/pkg/discovery" - "github.com/docker/docker/pkg/plugingetter" - "github.com/docker/go-connections/tlsconfig" - "github.com/docker/libkv/store" - "github.com/docker/libnetwork/cluster" - "github.com/docker/libnetwork/datastore" - "github.com/docker/libnetwork/ipamutils" - "github.com/docker/libnetwork/netlabel" - "github.com/docker/libnetwork/osl" - "github.com/docker/libnetwork/portallocator" - "github.com/sirupsen/logrus" -) - -const ( - warningThNetworkControlPlaneMTU = 1500 - minimumNetworkControlPlaneMTU = 500 -) - -// Config encapsulates configurations of various Libnetwork components -type Config struct { - Daemon DaemonCfg - Cluster ClusterCfg - Scopes map[string]*datastore.ScopeCfg - ActiveSandboxes map[string]interface{} - PluginGetter plugingetter.PluginGetter -} - -// DaemonCfg represents libnetwork core configuration -type DaemonCfg struct { - Debug bool - Experimental bool - DataDir string - ExecRoot string - DefaultNetwork string - DefaultDriver string - Labels []string - DriverCfg map[string]interface{} - ClusterProvider cluster.Provider - NetworkControlPlaneMTU int - DefaultAddressPool []*ipamutils.NetworkToSplit -} - -// ClusterCfg represents cluster configuration -type ClusterCfg struct { - Watcher discovery.Watcher - Address string - Discovery string - Heartbeat uint64 -} - -// LoadDefaultScopes loads default scope configs for scopes which -// doesn't have explicit user specified configs. -func (c *Config) LoadDefaultScopes(dataDir string) { - for k, v := range datastore.DefaultScopes(dataDir) { - if _, ok := c.Scopes[k]; !ok { - c.Scopes[k] = v - } - } -} - -// ParseConfig parses the libnetwork configuration file -func ParseConfig(tomlCfgFile string) (*Config, error) { - cfg := &Config{ - Scopes: map[string]*datastore.ScopeCfg{}, - } - - if _, err := toml.DecodeFile(tomlCfgFile, cfg); err != nil { - return nil, err - } - - cfg.LoadDefaultScopes(cfg.Daemon.DataDir) - return cfg, nil -} - -// ParseConfigOptions parses the configuration options and returns -// a reference to the corresponding Config structure -func ParseConfigOptions(cfgOptions ...Option) *Config { - cfg := &Config{ - Daemon: DaemonCfg{ - DriverCfg: make(map[string]interface{}), - }, - Scopes: make(map[string]*datastore.ScopeCfg), - } - - cfg.ProcessOptions(cfgOptions...) - cfg.LoadDefaultScopes(cfg.Daemon.DataDir) - - return cfg -} - -// Option is an option setter function type used to pass various configurations -// to the controller -type Option func(c *Config) - -// OptionDefaultNetwork function returns an option setter for a default network -func OptionDefaultNetwork(dn string) Option { - return func(c *Config) { - logrus.Debugf("Option DefaultNetwork: %s", dn) - c.Daemon.DefaultNetwork = strings.TrimSpace(dn) - } -} - -// OptionDefaultDriver function returns an option setter for default driver -func OptionDefaultDriver(dd string) Option { - return func(c *Config) { - logrus.Debugf("Option DefaultDriver: %s", dd) - c.Daemon.DefaultDriver = strings.TrimSpace(dd) - } -} - -// OptionDefaultAddressPoolConfig function returns an option setter for default address pool -func OptionDefaultAddressPoolConfig(addressPool []*ipamutils.NetworkToSplit) Option { - return func(c *Config) { - c.Daemon.DefaultAddressPool = addressPool - } -} - -// OptionDriverConfig returns an option setter for driver configuration. -func OptionDriverConfig(networkType string, config map[string]interface{}) Option { - return func(c *Config) { - c.Daemon.DriverCfg[networkType] = config - } -} - -// OptionLabels function returns an option setter for labels -func OptionLabels(labels []string) Option { - return func(c *Config) { - for _, label := range labels { - if strings.HasPrefix(label, netlabel.Prefix) { - c.Daemon.Labels = append(c.Daemon.Labels, label) - } - } - } -} - -// OptionKVProvider function returns an option setter for kvstore provider -func OptionKVProvider(provider string) Option { - return func(c *Config) { - logrus.Debugf("Option OptionKVProvider: %s", provider) - if _, ok := c.Scopes[datastore.GlobalScope]; !ok { - c.Scopes[datastore.GlobalScope] = &datastore.ScopeCfg{} - } - c.Scopes[datastore.GlobalScope].Client.Provider = strings.TrimSpace(provider) - } -} - -// OptionKVProviderURL function returns an option setter for kvstore url -func OptionKVProviderURL(url string) Option { - return func(c *Config) { - logrus.Debugf("Option OptionKVProviderURL: %s", url) - if _, ok := c.Scopes[datastore.GlobalScope]; !ok { - c.Scopes[datastore.GlobalScope] = &datastore.ScopeCfg{} - } - c.Scopes[datastore.GlobalScope].Client.Address = strings.TrimSpace(url) - } -} - -// OptionKVOpts function returns an option setter for kvstore options -func OptionKVOpts(opts map[string]string) Option { - return func(c *Config) { - if opts["kv.cacertfile"] != "" && opts["kv.certfile"] != "" && opts["kv.keyfile"] != "" { - logrus.Info("Option Initializing KV with TLS") - tlsConfig, err := tlsconfig.Client(tlsconfig.Options{ - CAFile: opts["kv.cacertfile"], - CertFile: opts["kv.certfile"], - KeyFile: opts["kv.keyfile"], - }) - if err != nil { - logrus.Errorf("Unable to set up TLS: %s", err) - return - } - if _, ok := c.Scopes[datastore.GlobalScope]; !ok { - c.Scopes[datastore.GlobalScope] = &datastore.ScopeCfg{} - } - if c.Scopes[datastore.GlobalScope].Client.Config == nil { - c.Scopes[datastore.GlobalScope].Client.Config = &store.Config{TLS: tlsConfig} - } else { - c.Scopes[datastore.GlobalScope].Client.Config.TLS = tlsConfig - } - // Workaround libkv/etcd bug for https - c.Scopes[datastore.GlobalScope].Client.Config.ClientTLS = &store.ClientTLSConfig{ - CACertFile: opts["kv.cacertfile"], - CertFile: opts["kv.certfile"], - KeyFile: opts["kv.keyfile"], - } - } else { - logrus.Info("Option Initializing KV without TLS") - } - } -} - -// OptionDiscoveryWatcher function returns an option setter for discovery watcher -func OptionDiscoveryWatcher(watcher discovery.Watcher) Option { - return func(c *Config) { - c.Cluster.Watcher = watcher - } -} - -// OptionDiscoveryAddress function returns an option setter for self discovery address -func OptionDiscoveryAddress(address string) Option { - return func(c *Config) { - c.Cluster.Address = address - } -} - -// OptionDataDir function returns an option setter for data folder -func OptionDataDir(dataDir string) Option { - return func(c *Config) { - c.Daemon.DataDir = dataDir - } -} - -// OptionExecRoot function returns an option setter for exec root folder -func OptionExecRoot(execRoot string) Option { - return func(c *Config) { - c.Daemon.ExecRoot = execRoot - osl.SetBasePath(execRoot) - } -} - -// OptionPluginGetter returns a plugingetter for remote drivers. -func OptionPluginGetter(pg plugingetter.PluginGetter) Option { - return func(c *Config) { - c.PluginGetter = pg - } -} - -// OptionExperimental function returns an option setter for experimental daemon -func OptionExperimental(exp bool) Option { - return func(c *Config) { - logrus.Debugf("Option Experimental: %v", exp) - c.Daemon.Experimental = exp - } -} - -// OptionDynamicPortRange function returns an option setter for service port allocation range -func OptionDynamicPortRange(in string) Option { - return func(c *Config) { - start, end := 0, 0 - if len(in) > 0 { - n, err := fmt.Sscanf(in, "%d-%d", &start, &end) - if n != 2 || err != nil { - logrus.Errorf("Failed to parse range string with err %v", err) - return - } - } - if err := portallocator.Get().SetPortRange(start, end); err != nil { - logrus.Errorf("Failed to set port range with err %v", err) - } - } -} - -// OptionNetworkControlPlaneMTU function returns an option setter for control plane MTU -func OptionNetworkControlPlaneMTU(exp int) Option { - return func(c *Config) { - logrus.Debugf("Network Control Plane MTU: %d", exp) - if exp < warningThNetworkControlPlaneMTU { - logrus.Warnf("Received a MTU of %d, this value is very low, the network control plane can misbehave,"+ - " defaulting to minimum value (%d)", exp, minimumNetworkControlPlaneMTU) - if exp < minimumNetworkControlPlaneMTU { - exp = minimumNetworkControlPlaneMTU - } - } - c.Daemon.NetworkControlPlaneMTU = exp - } -} - -// ProcessOptions processes options and stores it in config -func (c *Config) ProcessOptions(options ...Option) { - for _, opt := range options { - if opt != nil { - opt(c) - } - } -} - -// IsValidName validates configuration objects supported by libnetwork -func IsValidName(name string) bool { - return strings.TrimSpace(name) != "" -} - -// OptionLocalKVProvider function returns an option setter for kvstore provider -func OptionLocalKVProvider(provider string) Option { - return func(c *Config) { - logrus.Debugf("Option OptionLocalKVProvider: %s", provider) - if _, ok := c.Scopes[datastore.LocalScope]; !ok { - c.Scopes[datastore.LocalScope] = &datastore.ScopeCfg{} - } - c.Scopes[datastore.LocalScope].Client.Provider = strings.TrimSpace(provider) - } -} - -// OptionLocalKVProviderURL function returns an option setter for kvstore url -func OptionLocalKVProviderURL(url string) Option { - return func(c *Config) { - logrus.Debugf("Option OptionLocalKVProviderURL: %s", url) - if _, ok := c.Scopes[datastore.LocalScope]; !ok { - c.Scopes[datastore.LocalScope] = &datastore.ScopeCfg{} - } - c.Scopes[datastore.LocalScope].Client.Address = strings.TrimSpace(url) - } -} - -// OptionLocalKVProviderConfig function returns an option setter for kvstore config -func OptionLocalKVProviderConfig(config *store.Config) Option { - return func(c *Config) { - logrus.Debugf("Option OptionLocalKVProviderConfig: %v", config) - if _, ok := c.Scopes[datastore.LocalScope]; !ok { - c.Scopes[datastore.LocalScope] = &datastore.ScopeCfg{} - } - c.Scopes[datastore.LocalScope].Client.Config = config - } -} - -// OptionActiveSandboxes function returns an option setter for passing the sandboxes -// which were active during previous daemon life -func OptionActiveSandboxes(sandboxes map[string]interface{}) Option { - return func(c *Config) { - c.ActiveSandboxes = sandboxes - } -} diff --git a/vendor/github.com/docker/libnetwork/controller.go b/vendor/github.com/docker/libnetwork/controller.go deleted file mode 100644 index 5e8594eecb..0000000000 --- a/vendor/github.com/docker/libnetwork/controller.go +++ /dev/null @@ -1,1389 +0,0 @@ -/* -Package libnetwork provides the basic functionality and extension points to -create network namespaces and allocate interfaces for containers to use. - - networkType := "bridge" - - // Create a new controller instance - driverOptions := options.Generic{} - genericOption := make(map[string]interface{}) - genericOption[netlabel.GenericData] = driverOptions - controller, err := libnetwork.New(config.OptionDriverConfig(networkType, genericOption)) - if err != nil { - return - } - - // Create a network for containers to join. - // NewNetwork accepts Variadic optional arguments that libnetwork and Drivers can make use of - network, err := controller.NewNetwork(networkType, "network1", "") - if err != nil { - return - } - - // For each new container: allocate IP and interfaces. The returned network - // settings will be used for container infos (inspect and such), as well as - // iptables rules for port publishing. This info is contained or accessible - // from the returned endpoint. - ep, err := network.CreateEndpoint("Endpoint1") - if err != nil { - return - } - - // Create the sandbox for the container. - // NewSandbox accepts Variadic optional arguments which libnetwork can use. - sbx, err := controller.NewSandbox("container1", - libnetwork.OptionHostname("test"), - libnetwork.OptionDomainname("docker.io")) - - // A sandbox can join the endpoint via the join api. - err = ep.Join(sbx) - if err != nil { - return - } -*/ -package libnetwork - -import ( - "fmt" - "net" - "path/filepath" - "runtime" - "strings" - "sync" - "time" - - "github.com/docker/docker/pkg/discovery" - "github.com/docker/docker/pkg/plugingetter" - "github.com/docker/docker/pkg/plugins" - "github.com/docker/docker/pkg/stringid" - "github.com/docker/libnetwork/cluster" - "github.com/docker/libnetwork/config" - "github.com/docker/libnetwork/datastore" - "github.com/docker/libnetwork/diagnostic" - "github.com/docker/libnetwork/discoverapi" - "github.com/docker/libnetwork/driverapi" - "github.com/docker/libnetwork/drvregistry" - "github.com/docker/libnetwork/hostdiscovery" - "github.com/docker/libnetwork/ipamapi" - "github.com/docker/libnetwork/netlabel" - "github.com/docker/libnetwork/options" - "github.com/docker/libnetwork/osl" - "github.com/docker/libnetwork/types" - "github.com/moby/locker" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" -) - -// NetworkController provides the interface for controller instance which manages -// networks. -type NetworkController interface { - // ID provides a unique identity for the controller - ID() string - - // BuiltinDrivers returns list of builtin drivers - BuiltinDrivers() []string - - // BuiltinIPAMDrivers returns list of builtin ipam drivers - BuiltinIPAMDrivers() []string - - // Config method returns the bootup configuration for the controller - Config() config.Config - - // Create a new network. The options parameter carries network specific options. - NewNetwork(networkType, name string, id string, options ...NetworkOption) (Network, error) - - // Networks returns the list of Network(s) managed by this controller. - Networks() []Network - - // WalkNetworks uses the provided function to walk the Network(s) managed by this controller. - WalkNetworks(walker NetworkWalker) - - // NetworkByName returns the Network which has the passed name. If not found, the error ErrNoSuchNetwork is returned. - NetworkByName(name string) (Network, error) - - // NetworkByID returns the Network which has the passed id. If not found, the error ErrNoSuchNetwork is returned. - NetworkByID(id string) (Network, error) - - // NewSandbox creates a new network sandbox for the passed container id - NewSandbox(containerID string, options ...SandboxOption) (Sandbox, error) - - // Sandboxes returns the list of Sandbox(s) managed by this controller. - Sandboxes() []Sandbox - - // WalkSandboxes uses the provided function to walk the Sandbox(s) managed by this controller. - WalkSandboxes(walker SandboxWalker) - - // SandboxByID returns the Sandbox which has the passed id. If not found, a types.NotFoundError is returned. - SandboxByID(id string) (Sandbox, error) - - // SandboxDestroy destroys a sandbox given a container ID - SandboxDestroy(id string) error - - // Stop network controller - Stop() - - // ReloadConfiguration updates the controller configuration - ReloadConfiguration(cfgOptions ...config.Option) error - - // SetClusterProvider sets cluster provider - SetClusterProvider(provider cluster.Provider) - - // Wait for agent initialization complete in libnetwork controller - AgentInitWait() - - // Wait for agent to stop if running - AgentStopWait() - - // SetKeys configures the encryption key for gossip and overlay data path - SetKeys(keys []*types.EncryptionKey) error - - // StartDiagnostic start the network diagnostic mode - StartDiagnostic(port int) - // StopDiagnostic start the network diagnostic mode - StopDiagnostic() - // IsDiagnosticEnabled returns true if the diagnostic is enabled - IsDiagnosticEnabled() bool -} - -// NetworkWalker is a client provided function which will be used to walk the Networks. -// When the function returns true, the walk will stop. -type NetworkWalker func(nw Network) bool - -// SandboxWalker is a client provided function which will be used to walk the Sandboxes. -// When the function returns true, the walk will stop. -type SandboxWalker func(sb Sandbox) bool - -type sandboxTable map[string]*sandbox - -type controller struct { - id string - drvRegistry *drvregistry.DrvRegistry - sandboxes sandboxTable - cfg *config.Config - stores []datastore.DataStore - discovery hostdiscovery.HostDiscovery - extKeyListener net.Listener - watchCh chan *endpoint - unWatchCh chan *endpoint - svcRecords map[string]svcInfo - nmap map[string]*netWatch - serviceBindings map[serviceKey]*service - defOsSbox osl.Sandbox - ingressSandbox *sandbox - sboxOnce sync.Once - agent *agent - networkLocker *locker.Locker - agentInitDone chan struct{} - agentStopDone chan struct{} - keys []*types.EncryptionKey - clusterConfigAvailable bool - DiagnosticServer *diagnostic.Server - sync.Mutex -} - -type initializer struct { - fn drvregistry.InitFunc - ntype string -} - -// New creates a new instance of network controller. -func New(cfgOptions ...config.Option) (NetworkController, error) { - c := &controller{ - id: stringid.GenerateRandomID(), - cfg: config.ParseConfigOptions(cfgOptions...), - sandboxes: sandboxTable{}, - svcRecords: make(map[string]svcInfo), - serviceBindings: make(map[serviceKey]*service), - agentInitDone: make(chan struct{}), - networkLocker: locker.New(), - DiagnosticServer: diagnostic.New(), - } - c.DiagnosticServer.Init() - - if err := c.initStores(); err != nil { - return nil, err - } - - drvRegistry, err := drvregistry.New(c.getStore(datastore.LocalScope), c.getStore(datastore.GlobalScope), c.RegisterDriver, nil, c.cfg.PluginGetter) - if err != nil { - return nil, err - } - - for _, i := range getInitializers(c.cfg.Daemon.Experimental) { - var dcfg map[string]interface{} - - // External plugins don't need config passed through daemon. They can - // bootstrap themselves - if i.ntype != "remote" { - dcfg = c.makeDriverConfig(i.ntype) - } - - if err := drvRegistry.AddDriver(i.ntype, i.fn, dcfg); err != nil { - return nil, err - } - } - - if err = initIPAMDrivers(drvRegistry, nil, c.getStore(datastore.GlobalScope), c.cfg.Daemon.DefaultAddressPool); err != nil { - return nil, err - } - - c.drvRegistry = drvRegistry - - if c.cfg != nil && c.cfg.Cluster.Watcher != nil { - if err := c.initDiscovery(c.cfg.Cluster.Watcher); err != nil { - // Failing to initialize discovery is a bad situation to be in. - // But it cannot fail creating the Controller - logrus.Errorf("Failed to Initialize Discovery : %v", err) - } - } - - c.WalkNetworks(populateSpecial) - - // Reserve pools first before doing cleanup. Otherwise the - // cleanups of endpoint/network and sandbox below will - // generate many unnecessary warnings - c.reservePools() - - // Cleanup resources - c.sandboxCleanup(c.cfg.ActiveSandboxes) - c.cleanupLocalEndpoints() - c.networkCleanup() - - if err := c.startExternalKeyListener(); err != nil { - return nil, err - } - - setupArrangeUserFilterRule(c) - return c, nil -} - -func (c *controller) SetClusterProvider(provider cluster.Provider) { - var sameProvider bool - c.Lock() - // Avoids to spawn multiple goroutine for the same cluster provider - if c.cfg.Daemon.ClusterProvider == provider { - // If the cluster provider is already set, there is already a go routine spawned - // that is listening for events, so nothing to do here - sameProvider = true - } else { - c.cfg.Daemon.ClusterProvider = provider - } - c.Unlock() - - if provider == nil || sameProvider { - return - } - // We don't want to spawn a new go routine if the previous one did not exit yet - c.AgentStopWait() - go c.clusterAgentInit() -} - -func isValidClusteringIP(addr string) bool { - return addr != "" && !net.ParseIP(addr).IsLoopback() && !net.ParseIP(addr).IsUnspecified() -} - -// libnetwork side of agent depends on the keys. On the first receipt of -// keys setup the agent. For subsequent key set handle the key change -func (c *controller) SetKeys(keys []*types.EncryptionKey) error { - subsysKeys := make(map[string]int) - for _, key := range keys { - if key.Subsystem != subsysGossip && - key.Subsystem != subsysIPSec { - return fmt.Errorf("key received for unrecognized subsystem") - } - subsysKeys[key.Subsystem]++ - } - for s, count := range subsysKeys { - if count != keyringSize { - return fmt.Errorf("incorrect number of keys for subsystem %v", s) - } - } - - agent := c.getAgent() - - if agent == nil { - c.Lock() - c.keys = keys - c.Unlock() - return nil - } - return c.handleKeyChange(keys) -} - -func (c *controller) getAgent() *agent { - c.Lock() - defer c.Unlock() - return c.agent -} - -func (c *controller) clusterAgentInit() { - clusterProvider := c.cfg.Daemon.ClusterProvider - var keysAvailable bool - for { - eventType := <-clusterProvider.ListenClusterEvents() - // The events: EventSocketChange, EventNodeReady and EventNetworkKeysAvailable are not ordered - // when all the condition for the agent initialization are met then proceed with it - switch eventType { - case cluster.EventNetworkKeysAvailable: - // Validates that the keys are actually available before starting the initialization - // This will handle old spurious messages left on the channel - c.Lock() - keysAvailable = c.keys != nil - c.Unlock() - fallthrough - case cluster.EventSocketChange, cluster.EventNodeReady: - if keysAvailable && !c.isDistributedControl() { - c.agentOperationStart() - if err := c.agentSetup(clusterProvider); err != nil { - c.agentStopComplete() - } else { - c.agentInitComplete() - } - } - case cluster.EventNodeLeave: - c.agentOperationStart() - c.Lock() - c.keys = nil - c.Unlock() - - // We are leaving the cluster. Make sure we - // close the gossip so that we stop all - // incoming gossip updates before cleaning up - // any remaining service bindings. But before - // deleting the networks since the networks - // should still be present when cleaning up - // service bindings - c.agentClose() - c.cleanupServiceDiscovery("") - c.cleanupServiceBindings("") - - c.agentStopComplete() - - return - } - } -} - -// AgentInitWait waits for agent initialization to be completed in the controller. -func (c *controller) AgentInitWait() { - c.Lock() - agentInitDone := c.agentInitDone - c.Unlock() - - if agentInitDone != nil { - <-agentInitDone - } -} - -// AgentStopWait waits for the Agent stop to be completed in the controller -func (c *controller) AgentStopWait() { - c.Lock() - agentStopDone := c.agentStopDone - c.Unlock() - if agentStopDone != nil { - <-agentStopDone - } -} - -// agentOperationStart marks the start of an Agent Init or Agent Stop -func (c *controller) agentOperationStart() { - c.Lock() - if c.agentInitDone == nil { - c.agentInitDone = make(chan struct{}) - } - if c.agentStopDone == nil { - c.agentStopDone = make(chan struct{}) - } - c.Unlock() -} - -// agentInitComplete notifies the successful completion of the Agent initialization -func (c *controller) agentInitComplete() { - c.Lock() - if c.agentInitDone != nil { - close(c.agentInitDone) - c.agentInitDone = nil - } - c.Unlock() -} - -// agentStopComplete notifies the successful completion of the Agent stop -func (c *controller) agentStopComplete() { - c.Lock() - if c.agentStopDone != nil { - close(c.agentStopDone) - c.agentStopDone = nil - } - c.Unlock() -} - -func (c *controller) makeDriverConfig(ntype string) map[string]interface{} { - if c.cfg == nil { - return nil - } - - config := make(map[string]interface{}) - - for _, label := range c.cfg.Daemon.Labels { - if !strings.HasPrefix(netlabel.Key(label), netlabel.DriverPrefix+"."+ntype) { - continue - } - - config[netlabel.Key(label)] = netlabel.Value(label) - } - - drvCfg, ok := c.cfg.Daemon.DriverCfg[ntype] - if ok { - for k, v := range drvCfg.(map[string]interface{}) { - config[k] = v - } - } - - for k, v := range c.cfg.Scopes { - if !v.IsValid() { - continue - } - config[netlabel.MakeKVClient(k)] = discoverapi.DatastoreConfigData{ - Scope: k, - Provider: v.Client.Provider, - Address: v.Client.Address, - Config: v.Client.Config, - } - } - - return config -} - -var procReloadConfig = make(chan (bool), 1) - -func (c *controller) ReloadConfiguration(cfgOptions ...config.Option) error { - procReloadConfig <- true - defer func() { <-procReloadConfig }() - - // For now we accept the configuration reload only as a mean to provide a global store config after boot. - // Refuse the configuration if it alters an existing datastore client configuration. - update := false - cfg := config.ParseConfigOptions(cfgOptions...) - - for s := range c.cfg.Scopes { - if _, ok := cfg.Scopes[s]; !ok { - return types.ForbiddenErrorf("cannot accept new configuration because it removes an existing datastore client") - } - } - for s, nSCfg := range cfg.Scopes { - if eSCfg, ok := c.cfg.Scopes[s]; ok { - if eSCfg.Client.Provider != nSCfg.Client.Provider || - eSCfg.Client.Address != nSCfg.Client.Address { - return types.ForbiddenErrorf("cannot accept new configuration because it modifies an existing datastore client") - } - } else { - if err := c.initScopedStore(s, nSCfg); err != nil { - return err - } - update = true - } - } - if !update { - return nil - } - - c.Lock() - c.cfg = cfg - c.Unlock() - - var dsConfig *discoverapi.DatastoreConfigData - for scope, sCfg := range cfg.Scopes { - if scope == datastore.LocalScope || !sCfg.IsValid() { - continue - } - dsConfig = &discoverapi.DatastoreConfigData{ - Scope: scope, - Provider: sCfg.Client.Provider, - Address: sCfg.Client.Address, - Config: sCfg.Client.Config, - } - break - } - if dsConfig == nil { - return nil - } - - c.drvRegistry.WalkIPAMs(func(name string, driver ipamapi.Ipam, cap *ipamapi.Capability) bool { - err := driver.DiscoverNew(discoverapi.DatastoreConfig, *dsConfig) - if err != nil { - logrus.Errorf("Failed to set datastore in driver %s: %v", name, err) - } - return false - }) - - c.drvRegistry.WalkDrivers(func(name string, driver driverapi.Driver, capability driverapi.Capability) bool { - err := driver.DiscoverNew(discoverapi.DatastoreConfig, *dsConfig) - if err != nil { - logrus.Errorf("Failed to set datastore in driver %s: %v", name, err) - } - return false - }) - - if c.discovery == nil && c.cfg.Cluster.Watcher != nil { - if err := c.initDiscovery(c.cfg.Cluster.Watcher); err != nil { - logrus.Errorf("Failed to Initialize Discovery after configuration update: %v", err) - } - } - - return nil -} - -func (c *controller) ID() string { - return c.id -} - -func (c *controller) BuiltinDrivers() []string { - drivers := []string{} - c.drvRegistry.WalkDrivers(func(name string, driver driverapi.Driver, capability driverapi.Capability) bool { - if driver.IsBuiltIn() { - drivers = append(drivers, name) - } - return false - }) - return drivers -} - -func (c *controller) BuiltinIPAMDrivers() []string { - drivers := []string{} - c.drvRegistry.WalkIPAMs(func(name string, driver ipamapi.Ipam, cap *ipamapi.Capability) bool { - if driver.IsBuiltIn() { - drivers = append(drivers, name) - } - return false - }) - return drivers -} - -func (c *controller) validateHostDiscoveryConfig() bool { - if c.cfg == nil || c.cfg.Cluster.Discovery == "" || c.cfg.Cluster.Address == "" { - return false - } - return true -} - -func (c *controller) clusterHostID() string { - c.Lock() - defer c.Unlock() - if c.cfg == nil || c.cfg.Cluster.Address == "" { - return "" - } - addr := strings.Split(c.cfg.Cluster.Address, ":") - return addr[0] -} - -func (c *controller) isNodeAlive(node string) bool { - if c.discovery == nil { - return false - } - - nodes := c.discovery.Fetch() - for _, n := range nodes { - if n.String() == node { - return true - } - } - - return false -} - -func (c *controller) initDiscovery(watcher discovery.Watcher) error { - if c.cfg == nil { - return fmt.Errorf("discovery initialization requires a valid configuration") - } - - c.discovery = hostdiscovery.NewHostDiscovery(watcher) - return c.discovery.Watch(c.activeCallback, c.hostJoinCallback, c.hostLeaveCallback) -} - -func (c *controller) activeCallback() { - ds := c.getStore(datastore.GlobalScope) - if ds != nil && !ds.Active() { - ds.RestartWatch() - } -} - -func (c *controller) hostJoinCallback(nodes []net.IP) { - c.processNodeDiscovery(nodes, true) -} - -func (c *controller) hostLeaveCallback(nodes []net.IP) { - c.processNodeDiscovery(nodes, false) -} - -func (c *controller) processNodeDiscovery(nodes []net.IP, add bool) { - c.drvRegistry.WalkDrivers(func(name string, driver driverapi.Driver, capability driverapi.Capability) bool { - c.pushNodeDiscovery(driver, capability, nodes, add) - return false - }) -} - -func (c *controller) pushNodeDiscovery(d driverapi.Driver, cap driverapi.Capability, nodes []net.IP, add bool) { - var self net.IP - if c.cfg != nil { - addr := strings.Split(c.cfg.Cluster.Address, ":") - self = net.ParseIP(addr[0]) - // if external kvstore is not configured, try swarm-mode config - if self == nil { - if agent := c.getAgent(); agent != nil { - self = net.ParseIP(agent.advertiseAddr) - } - } - } - - if d == nil || cap.ConnectivityScope != datastore.GlobalScope || nodes == nil { - return - } - - for _, node := range nodes { - nodeData := discoverapi.NodeDiscoveryData{Address: node.String(), Self: node.Equal(self)} - var err error - if add { - err = d.DiscoverNew(discoverapi.NodeDiscovery, nodeData) - } else { - err = d.DiscoverDelete(discoverapi.NodeDiscovery, nodeData) - } - if err != nil { - logrus.Debugf("discovery notification error: %v", err) - } - } -} - -func (c *controller) Config() config.Config { - c.Lock() - defer c.Unlock() - if c.cfg == nil { - return config.Config{} - } - return *c.cfg -} - -func (c *controller) isManager() bool { - c.Lock() - defer c.Unlock() - if c.cfg == nil || c.cfg.Daemon.ClusterProvider == nil { - return false - } - return c.cfg.Daemon.ClusterProvider.IsManager() -} - -func (c *controller) isAgent() bool { - c.Lock() - defer c.Unlock() - if c.cfg == nil || c.cfg.Daemon.ClusterProvider == nil { - return false - } - return c.cfg.Daemon.ClusterProvider.IsAgent() -} - -func (c *controller) isDistributedControl() bool { - return !c.isManager() && !c.isAgent() -} - -func (c *controller) GetPluginGetter() plugingetter.PluginGetter { - return c.drvRegistry.GetPluginGetter() -} - -func (c *controller) RegisterDriver(networkType string, driver driverapi.Driver, capability driverapi.Capability) error { - c.Lock() - hd := c.discovery - c.Unlock() - - if hd != nil { - c.pushNodeDiscovery(driver, capability, hd.Fetch(), true) - } - - c.agentDriverNotify(driver) - return nil -} - -// XXX This should be made driver agnostic. See comment below. -const overlayDSROptionString = "dsr" - -// NewNetwork creates a new network of the specified network type. The options -// are network specific and modeled in a generic way. -func (c *controller) NewNetwork(networkType, name string, id string, options ...NetworkOption) (Network, error) { - var ( - cap *driverapi.Capability - err error - t *network - skipCfgEpCount bool - ) - - if id != "" { - c.networkLocker.Lock(id) - defer c.networkLocker.Unlock(id) - - if _, err = c.NetworkByID(id); err == nil { - return nil, NetworkNameError(id) - } - } - - if !config.IsValidName(name) { - return nil, ErrInvalidName(name) - } - - if id == "" { - id = stringid.GenerateRandomID() - } - - defaultIpam := defaultIpamForNetworkType(networkType) - // Construct the network object - network := &network{ - name: name, - networkType: networkType, - generic: map[string]interface{}{netlabel.GenericData: make(map[string]string)}, - ipamType: defaultIpam, - id: id, - created: time.Now(), - ctrlr: c, - persist: true, - drvOnce: &sync.Once{}, - loadBalancerMode: loadBalancerModeDefault, - } - - network.processOptions(options...) - if err = network.validateConfiguration(); err != nil { - return nil, err - } - - // Reset network types, force local scope and skip allocation and - // plumbing for configuration networks. Reset of the config-only - // network drivers is needed so that this special network is not - // usable by old engine versions. - if network.configOnly { - network.scope = datastore.LocalScope - network.networkType = "null" - goto addToStore - } - - _, cap, err = network.resolveDriver(network.networkType, true) - if err != nil { - return nil, err - } - - if network.scope == datastore.LocalScope && cap.DataScope == datastore.GlobalScope { - return nil, types.ForbiddenErrorf("cannot downgrade network scope for %s networks", networkType) - - } - if network.ingress && cap.DataScope != datastore.GlobalScope { - return nil, types.ForbiddenErrorf("Ingress network can only be global scope network") - } - - // At this point the network scope is still unknown if not set by user - if (cap.DataScope == datastore.GlobalScope || network.scope == datastore.SwarmScope) && - !c.isDistributedControl() && !network.dynamic { - if c.isManager() { - // For non-distributed controlled environment, globalscoped non-dynamic networks are redirected to Manager - return nil, ManagerRedirectError(name) - } - return nil, types.ForbiddenErrorf("Cannot create a multi-host network from a worker node. Please create the network from a manager node.") - } - - if network.scope == datastore.SwarmScope && c.isDistributedControl() { - return nil, types.ForbiddenErrorf("cannot create a swarm scoped network when swarm is not active") - } - - // Make sure we have a driver available for this network type - // before we allocate anything. - if _, err := network.driver(true); err != nil { - return nil, err - } - - // From this point on, we need the network specific configuration, - // which may come from a configuration-only network - if network.configFrom != "" { - t, err = c.getConfigNetwork(network.configFrom) - if err != nil { - return nil, types.NotFoundErrorf("configuration network %q does not exist", network.configFrom) - } - if err = t.applyConfigurationTo(network); err != nil { - return nil, types.InternalErrorf("Failed to apply configuration: %v", err) - } - network.generic[netlabel.Internal] = network.internal - defer func() { - if err == nil && !skipCfgEpCount { - if err := t.getEpCnt().IncEndpointCnt(); err != nil { - logrus.Warnf("Failed to update reference count for configuration network %q on creation of network %q: %v", - t.Name(), network.Name(), err) - } - } - }() - } - - err = network.ipamAllocate() - if err != nil { - return nil, err - } - defer func() { - if err != nil { - network.ipamRelease() - } - }() - - err = c.addNetwork(network) - if err != nil { - if _, ok := err.(types.MaskableError); ok { - // This error can be ignored and set this boolean - // value to skip a refcount increment for configOnly networks - skipCfgEpCount = true - } else { - return nil, err - } - } - defer func() { - if err != nil { - if e := network.deleteNetwork(); e != nil { - logrus.Warnf("couldn't roll back driver network on network %s creation failure: %v", network.name, err) - } - } - }() - - // XXX If the driver type is "overlay" check the options for DSR - // being set. If so, set the network's load balancing mode to DSR. - // This should really be done in a network option, but due to - // time pressure to get this in without adding changes to moby, - // swarm and CLI, it is being implemented as a driver-specific - // option. Unfortunately, drivers can't influence the core - // "libnetwork.network" data type. Hence we need this hack code - // to implement in this manner. - if gval, ok := network.generic[netlabel.GenericData]; ok && network.networkType == "overlay" { - optMap := gval.(map[string]string) - if _, ok := optMap[overlayDSROptionString]; ok { - network.loadBalancerMode = loadBalancerModeDSR - } - } - -addToStore: - // First store the endpoint count, then the network. To avoid to - // end up with a datastore containing a network and not an epCnt, - // in case of an ungraceful shutdown during this function call. - epCnt := &endpointCnt{n: network} - if err = c.updateToStore(epCnt); err != nil { - return nil, err - } - defer func() { - if err != nil { - if e := c.deleteFromStore(epCnt); e != nil { - logrus.Warnf("could not rollback from store, epCnt %v on failure (%v): %v", epCnt, err, e) - } - } - }() - - network.epCnt = epCnt - if err = c.updateToStore(network); err != nil { - return nil, err - } - defer func() { - if err != nil { - if e := c.deleteFromStore(network); e != nil { - logrus.Warnf("could not rollback from store, network %v on failure (%v): %v", network, err, e) - } - } - }() - - if network.configOnly { - return network, nil - } - - joinCluster(network) - defer func() { - if err != nil { - network.cancelDriverWatches() - if e := network.leaveCluster(); e != nil { - logrus.Warnf("Failed to leave agent cluster on network %s on failure (%v): %v", network.name, err, e) - } - } - }() - - if network.hasLoadBalancerEndpoint() { - if err = network.createLoadBalancerSandbox(); err != nil { - return nil, err - } - } - - if !c.isDistributedControl() { - c.Lock() - arrangeIngressFilterRule() - c.Unlock() - } - arrangeUserFilterRule() - - return network, nil -} - -var joinCluster NetworkWalker = func(nw Network) bool { - n := nw.(*network) - if n.configOnly { - return false - } - if err := n.joinCluster(); err != nil { - logrus.Errorf("Failed to join network %s (%s) into agent cluster: %v", n.Name(), n.ID(), err) - } - n.addDriverWatches() - return false -} - -func (c *controller) reservePools() { - networks, err := c.getNetworksForScope(datastore.LocalScope) - if err != nil { - logrus.Warnf("Could not retrieve networks from local store during ipam allocation for existing networks: %v", err) - return - } - - for _, n := range networks { - if n.configOnly { - continue - } - if !doReplayPoolReserve(n) { - continue - } - // Construct pseudo configs for the auto IP case - autoIPv4 := (len(n.ipamV4Config) == 0 || (len(n.ipamV4Config) == 1 && n.ipamV4Config[0].PreferredPool == "")) && len(n.ipamV4Info) > 0 - autoIPv6 := (len(n.ipamV6Config) == 0 || (len(n.ipamV6Config) == 1 && n.ipamV6Config[0].PreferredPool == "")) && len(n.ipamV6Info) > 0 - if autoIPv4 { - n.ipamV4Config = []*IpamConf{{PreferredPool: n.ipamV4Info[0].Pool.String()}} - } - if n.enableIPv6 && autoIPv6 { - n.ipamV6Config = []*IpamConf{{PreferredPool: n.ipamV6Info[0].Pool.String()}} - } - // Account current network gateways - for i, c := range n.ipamV4Config { - if c.Gateway == "" && n.ipamV4Info[i].Gateway != nil { - c.Gateway = n.ipamV4Info[i].Gateway.IP.String() - } - } - if n.enableIPv6 { - for i, c := range n.ipamV6Config { - if c.Gateway == "" && n.ipamV6Info[i].Gateway != nil { - c.Gateway = n.ipamV6Info[i].Gateway.IP.String() - } - } - } - // Reserve pools - if err := n.ipamAllocate(); err != nil { - logrus.Warnf("Failed to allocate ipam pool(s) for network %q (%s): %v", n.Name(), n.ID(), err) - } - // Reserve existing endpoints' addresses - ipam, _, err := n.getController().getIPAMDriver(n.ipamType) - if err != nil { - logrus.Warnf("Failed to retrieve ipam driver for network %q (%s) during address reservation", n.Name(), n.ID()) - continue - } - epl, err := n.getEndpointsFromStore() - if err != nil { - logrus.Warnf("Failed to retrieve list of current endpoints on network %q (%s)", n.Name(), n.ID()) - continue - } - for _, ep := range epl { - if ep.Iface() == nil { - logrus.Warnf("endpoint interface is empty for %q (%s)", ep.Name(), ep.ID()) - continue - } - if err := ep.assignAddress(ipam, true, ep.Iface().AddressIPv6() != nil); err != nil { - logrus.Warnf("Failed to reserve current address for endpoint %q (%s) on network %q (%s)", - ep.Name(), ep.ID(), n.Name(), n.ID()) - } - } - } -} - -func doReplayPoolReserve(n *network) bool { - _, caps, err := n.getController().getIPAMDriver(n.ipamType) - if err != nil { - logrus.Warnf("Failed to retrieve ipam driver for network %q (%s): %v", n.Name(), n.ID(), err) - return false - } - return caps.RequiresRequestReplay -} - -func (c *controller) addNetwork(n *network) error { - d, err := n.driver(true) - if err != nil { - return err - } - - // Create the network - if err := d.CreateNetwork(n.id, n.generic, n, n.getIPData(4), n.getIPData(6)); err != nil { - return err - } - - n.startResolver() - - return nil -} - -func (c *controller) Networks() []Network { - var list []Network - - for _, n := range c.getNetworksFromStore() { - if n.inDelete { - continue - } - list = append(list, n) - } - - return list -} - -func (c *controller) WalkNetworks(walker NetworkWalker) { - for _, n := range c.Networks() { - if walker(n) { - return - } - } -} - -func (c *controller) NetworkByName(name string) (Network, error) { - if name == "" { - return nil, ErrInvalidName(name) - } - var n Network - - s := func(current Network) bool { - if current.Name() == name { - n = current - return true - } - return false - } - - c.WalkNetworks(s) - - if n == nil { - return nil, ErrNoSuchNetwork(name) - } - - return n, nil -} - -func (c *controller) NetworkByID(id string) (Network, error) { - if id == "" { - return nil, ErrInvalidID(id) - } - - n, err := c.getNetworkFromStore(id) - if err != nil { - return nil, ErrNoSuchNetwork(id) - } - - return n, nil -} - -// NewSandbox creates a new sandbox for the passed container id -func (c *controller) NewSandbox(containerID string, options ...SandboxOption) (Sandbox, error) { - if containerID == "" { - return nil, types.BadRequestErrorf("invalid container ID") - } - - var sb *sandbox - c.Lock() - for _, s := range c.sandboxes { - if s.containerID == containerID { - // If not a stub, then we already have a complete sandbox. - if !s.isStub { - sbID := s.ID() - c.Unlock() - return nil, types.ForbiddenErrorf("container %s is already present in sandbox %s", containerID, sbID) - } - - // We already have a stub sandbox from the - // store. Make use of it so that we don't lose - // the endpoints from store but reset the - // isStub flag. - sb = s - sb.isStub = false - break - } - } - c.Unlock() - - sandboxID := stringid.GenerateRandomID() - if runtime.GOOS == "windows" { - sandboxID = containerID - } - - // Create sandbox and process options first. Key generation depends on an option - if sb == nil { - sb = &sandbox{ - id: sandboxID, - containerID: containerID, - endpoints: []*endpoint{}, - epPriority: map[string]int{}, - populatedEndpoints: map[string]struct{}{}, - config: containerConfig{}, - controller: c, - extDNS: []extDNSEntry{}, - } - } - - sb.processOptions(options...) - - c.Lock() - if sb.ingress && c.ingressSandbox != nil { - c.Unlock() - return nil, types.ForbiddenErrorf("ingress sandbox already present") - } - - if sb.ingress { - c.ingressSandbox = sb - sb.config.hostsPath = filepath.Join(c.cfg.Daemon.DataDir, "/network/files/hosts") - sb.config.resolvConfPath = filepath.Join(c.cfg.Daemon.DataDir, "/network/files/resolv.conf") - sb.id = "ingress_sbox" - } else if sb.loadBalancerNID != "" { - sb.id = "lb_" + sb.loadBalancerNID - } - c.Unlock() - - var err error - defer func() { - if err != nil { - c.Lock() - if sb.ingress { - c.ingressSandbox = nil - } - c.Unlock() - } - }() - - if err = sb.setupResolutionFiles(); err != nil { - return nil, err - } - - if sb.config.useDefaultSandBox { - c.sboxOnce.Do(func() { - c.defOsSbox, err = osl.NewSandbox(sb.Key(), false, false) - }) - - if err != nil { - c.sboxOnce = sync.Once{} - return nil, fmt.Errorf("failed to create default sandbox: %v", err) - } - - sb.osSbox = c.defOsSbox - } - - if sb.osSbox == nil && !sb.config.useExternalKey { - if sb.osSbox, err = osl.NewSandbox(sb.Key(), !sb.config.useDefaultSandBox, false); err != nil { - return nil, fmt.Errorf("failed to create new osl sandbox: %v", err) - } - } - - if sb.osSbox != nil { - // Apply operating specific knobs on the load balancer sandbox - sb.osSbox.ApplyOSTweaks(sb.oslTypes) - } - - c.Lock() - c.sandboxes[sb.id] = sb - c.Unlock() - defer func() { - if err != nil { - c.Lock() - delete(c.sandboxes, sb.id) - c.Unlock() - } - }() - - err = sb.storeUpdate() - if err != nil { - return nil, fmt.Errorf("failed to update the store state of sandbox: %v", err) - } - - return sb, nil -} - -func (c *controller) Sandboxes() []Sandbox { - c.Lock() - defer c.Unlock() - - list := make([]Sandbox, 0, len(c.sandboxes)) - for _, s := range c.sandboxes { - // Hide stub sandboxes from libnetwork users - if s.isStub { - continue - } - - list = append(list, s) - } - - return list -} - -func (c *controller) WalkSandboxes(walker SandboxWalker) { - for _, sb := range c.Sandboxes() { - if walker(sb) { - return - } - } -} - -func (c *controller) SandboxByID(id string) (Sandbox, error) { - if id == "" { - return nil, ErrInvalidID(id) - } - c.Lock() - s, ok := c.sandboxes[id] - c.Unlock() - if !ok { - return nil, types.NotFoundErrorf("sandbox %s not found", id) - } - return s, nil -} - -// SandboxDestroy destroys a sandbox given a container ID -func (c *controller) SandboxDestroy(id string) error { - var sb *sandbox - c.Lock() - for _, s := range c.sandboxes { - if s.containerID == id { - sb = s - break - } - } - c.Unlock() - - // It is not an error if sandbox is not available - if sb == nil { - return nil - } - - return sb.Delete() -} - -// SandboxContainerWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed containerID -func SandboxContainerWalker(out *Sandbox, containerID string) SandboxWalker { - return func(sb Sandbox) bool { - if sb.ContainerID() == containerID { - *out = sb - return true - } - return false - } -} - -// SandboxKeyWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed key -func SandboxKeyWalker(out *Sandbox, key string) SandboxWalker { - return func(sb Sandbox) bool { - if sb.Key() == key { - *out = sb - return true - } - return false - } -} - -func (c *controller) loadDriver(networkType string) error { - var err error - - if pg := c.GetPluginGetter(); pg != nil { - _, err = pg.Get(networkType, driverapi.NetworkPluginEndpointType, plugingetter.Lookup) - } else { - _, err = plugins.Get(networkType, driverapi.NetworkPluginEndpointType) - } - - if err != nil { - if errors.Cause(err) == plugins.ErrNotFound { - return types.NotFoundErrorf(err.Error()) - } - return err - } - - return nil -} - -func (c *controller) loadIPAMDriver(name string) error { - var err error - - if pg := c.GetPluginGetter(); pg != nil { - _, err = pg.Get(name, ipamapi.PluginEndpointType, plugingetter.Lookup) - } else { - _, err = plugins.Get(name, ipamapi.PluginEndpointType) - } - - if err != nil { - if errors.Cause(err) == plugins.ErrNotFound { - return types.NotFoundErrorf(err.Error()) - } - return err - } - - return nil -} - -func (c *controller) getIPAMDriver(name string) (ipamapi.Ipam, *ipamapi.Capability, error) { - id, cap := c.drvRegistry.IPAM(name) - if id == nil { - // Might be a plugin name. Try loading it - if err := c.loadIPAMDriver(name); err != nil { - return nil, nil, err - } - - // Now that we resolved the plugin, try again looking up the registry - id, cap = c.drvRegistry.IPAM(name) - if id == nil { - return nil, nil, types.BadRequestErrorf("invalid ipam driver: %q", name) - } - } - - return id, cap, nil -} - -func (c *controller) Stop() { - c.closeStores() - c.stopExternalKeyListener() - osl.GC() -} - -// StartDiagnostic start the network dias mode -func (c *controller) StartDiagnostic(port int) { - c.Lock() - if !c.DiagnosticServer.IsDiagnosticEnabled() { - c.DiagnosticServer.EnableDiagnostic("127.0.0.1", port) - } - c.Unlock() -} - -// StopDiagnostic start the network dias mode -func (c *controller) StopDiagnostic() { - c.Lock() - if c.DiagnosticServer.IsDiagnosticEnabled() { - c.DiagnosticServer.DisableDiagnostic() - } - c.Unlock() -} - -// IsDiagnosticEnabled returns true if the dias is enabled -func (c *controller) IsDiagnosticEnabled() bool { - c.Lock() - defer c.Unlock() - return c.DiagnosticServer.IsDiagnosticEnabled() -} - -func (c *controller) iptablesEnabled() bool { - c.Lock() - defer c.Unlock() - - if c.cfg == nil { - return false - } - // parse map cfg["bridge"]["generic"]["EnableIPTable"] - cfgBridge, ok := c.cfg.Daemon.DriverCfg["bridge"].(map[string]interface{}) - if !ok { - return false - } - cfgGeneric, ok := cfgBridge[netlabel.GenericData].(options.Generic) - if !ok { - return false - } - enabled, ok := cfgGeneric["EnableIPTables"].(bool) - if !ok { - // unless user explicitly stated, assume iptable is enabled - enabled = true - } - return enabled -} diff --git a/vendor/github.com/docker/libnetwork/datastore/cache.go b/vendor/github.com/docker/libnetwork/datastore/cache.go deleted file mode 100644 index 49839ae8f2..0000000000 --- a/vendor/github.com/docker/libnetwork/datastore/cache.go +++ /dev/null @@ -1,178 +0,0 @@ -package datastore - -import ( - "errors" - "fmt" - "sync" - - "github.com/docker/libkv/store" -) - -type kvMap map[string]KVObject - -type cache struct { - sync.Mutex - kmm map[string]kvMap - ds *datastore -} - -func newCache(ds *datastore) *cache { - return &cache{kmm: make(map[string]kvMap), ds: ds} -} - -func (c *cache) kmap(kvObject KVObject) (kvMap, error) { - var err error - - c.Lock() - keyPrefix := Key(kvObject.KeyPrefix()...) - kmap, ok := c.kmm[keyPrefix] - c.Unlock() - - if ok { - return kmap, nil - } - - kmap = kvMap{} - - // Bail out right away if the kvObject does not implement KVConstructor - ctor, ok := kvObject.(KVConstructor) - if !ok { - return nil, errors.New("error while populating kmap, object does not implement KVConstructor interface") - } - - kvList, err := c.ds.store.List(keyPrefix) - if err != nil { - if err == store.ErrKeyNotFound { - // If the store doesn't have anything then there is nothing to - // populate in the cache. Just bail out. - goto out - } - - return nil, fmt.Errorf("error while populating kmap: %v", err) - } - - for _, kvPair := range kvList { - // Ignore empty kvPair values - if len(kvPair.Value) == 0 { - continue - } - - dstO := ctor.New() - err = dstO.SetValue(kvPair.Value) - if err != nil { - return nil, err - } - - // Make sure the object has a correct view of the DB index in - // case we need to modify it and update the DB. - dstO.SetIndex(kvPair.LastIndex) - - kmap[Key(dstO.Key()...)] = dstO - } - -out: - // There may multiple go routines racing to fill the - // cache. The one which places the kmap in c.kmm first - // wins. The others should just use what the first populated. - c.Lock() - kmapNew, ok := c.kmm[keyPrefix] - if ok { - c.Unlock() - return kmapNew, nil - } - - c.kmm[keyPrefix] = kmap - c.Unlock() - - return kmap, nil -} - -func (c *cache) add(kvObject KVObject, atomic bool) error { - kmap, err := c.kmap(kvObject) - if err != nil { - return err - } - - c.Lock() - // If atomic is true, cache needs to maintain its own index - // for atomicity and the add needs to be atomic. - if atomic { - if prev, ok := kmap[Key(kvObject.Key()...)]; ok { - if prev.Index() != kvObject.Index() { - c.Unlock() - return ErrKeyModified - } - } - - // Increment index - index := kvObject.Index() - index++ - kvObject.SetIndex(index) - } - - kmap[Key(kvObject.Key()...)] = kvObject - c.Unlock() - return nil -} - -func (c *cache) del(kvObject KVObject, atomic bool) error { - kmap, err := c.kmap(kvObject) - if err != nil { - return err - } - - c.Lock() - // If atomic is true, cache needs to maintain its own index - // for atomicity and del needs to be atomic. - if atomic { - if prev, ok := kmap[Key(kvObject.Key()...)]; ok { - if prev.Index() != kvObject.Index() { - c.Unlock() - return ErrKeyModified - } - } - } - - delete(kmap, Key(kvObject.Key()...)) - c.Unlock() - return nil -} - -func (c *cache) get(key string, kvObject KVObject) error { - kmap, err := c.kmap(kvObject) - if err != nil { - return err - } - - c.Lock() - defer c.Unlock() - - o, ok := kmap[Key(kvObject.Key()...)] - if !ok { - return ErrKeyNotFound - } - - ctor, ok := o.(KVConstructor) - if !ok { - return errors.New("kvobject does not implement KVConstructor interface. could not get object") - } - - return ctor.CopyTo(kvObject) -} - -func (c *cache) list(kvObject KVObject) ([]KVObject, error) { - kmap, err := c.kmap(kvObject) - if err != nil { - return nil, err - } - - c.Lock() - defer c.Unlock() - - var kvol []KVObject - for _, v := range kmap { - kvol = append(kvol, v) - } - - return kvol, nil -} diff --git a/vendor/github.com/docker/libnetwork/datastore/datastore.go b/vendor/github.com/docker/libnetwork/datastore/datastore.go deleted file mode 100644 index e35dc43b2e..0000000000 --- a/vendor/github.com/docker/libnetwork/datastore/datastore.go +++ /dev/null @@ -1,660 +0,0 @@ -package datastore - -import ( - "fmt" - "log" - "reflect" - "strings" - "sync" - "time" - - "github.com/docker/libkv" - "github.com/docker/libkv/store" - "github.com/docker/libnetwork/discoverapi" - "github.com/docker/libnetwork/types" -) - -//DataStore exported -type DataStore interface { - // GetObject gets data from datastore and unmarshals to the specified object - GetObject(key string, o KVObject) error - // PutObject adds a new Record based on an object into the datastore - PutObject(kvObject KVObject) error - // PutObjectAtomic provides an atomic add and update operation for a Record - PutObjectAtomic(kvObject KVObject) error - // DeleteObject deletes a record - DeleteObject(kvObject KVObject) error - // DeleteObjectAtomic performs an atomic delete operation - DeleteObjectAtomic(kvObject KVObject) error - // DeleteTree deletes a record - DeleteTree(kvObject KVObject) error - // Watchable returns whether the store is watchable or not - Watchable() bool - // Watch for changes on a KVObject - Watch(kvObject KVObject, stopCh <-chan struct{}) (<-chan KVObject, error) - // RestartWatch retriggers stopped Watches - RestartWatch() - // Active returns if the store is active - Active() bool - // List returns of a list of KVObjects belonging to the parent - // key. The caller must pass a KVObject of the same type as - // the objects that need to be listed - List(string, KVObject) ([]KVObject, error) - // Map returns a Map of KVObjects - Map(key string, kvObject KVObject) (map[string]KVObject, error) - // Scope returns the scope of the store - Scope() string - // KVStore returns access to the KV Store - KVStore() store.Store - // Close closes the data store - Close() -} - -// ErrKeyModified is raised for an atomic update when the update is working on a stale state -var ( - ErrKeyModified = store.ErrKeyModified - ErrKeyNotFound = store.ErrKeyNotFound -) - -type datastore struct { - scope string - store store.Store - cache *cache - watchCh chan struct{} - active bool - sequential bool - sync.Mutex -} - -// KVObject is Key/Value interface used by objects to be part of the DataStore -type KVObject interface { - // Key method lets an object provide the Key to be used in KV Store - Key() []string - // KeyPrefix method lets an object return immediate parent key that can be used for tree walk - KeyPrefix() []string - // Value method lets an object marshal its content to be stored in the KV store - Value() []byte - // SetValue is used by the datastore to set the object's value when loaded from the data store. - SetValue([]byte) error - // Index method returns the latest DB Index as seen by the object - Index() uint64 - // SetIndex method allows the datastore to store the latest DB Index into the object - SetIndex(uint64) - // True if the object exists in the datastore, false if it hasn't been stored yet. - // When SetIndex() is called, the object has been stored. - Exists() bool - // DataScope indicates the storage scope of the KV object - DataScope() string - // Skip provides a way for a KV Object to avoid persisting it in the KV Store - Skip() bool -} - -// KVConstructor interface defines methods which can construct a KVObject from another. -type KVConstructor interface { - // New returns a new object which is created based on the - // source object - New() KVObject - // CopyTo deep copies the contents of the implementing object - // to the passed destination object - CopyTo(KVObject) error -} - -// ScopeCfg represents Datastore configuration. -type ScopeCfg struct { - Client ScopeClientCfg -} - -// ScopeClientCfg represents Datastore Client-only mode configuration -type ScopeClientCfg struct { - Provider string - Address string - Config *store.Config -} - -const ( - // LocalScope indicates to store the KV object in local datastore such as boltdb - LocalScope = "local" - // GlobalScope indicates to store the KV object in global datastore such as consul/etcd/zookeeper - GlobalScope = "global" - // SwarmScope is not indicating a datastore location. It is defined here - // along with the other two scopes just for consistency. - SwarmScope = "swarm" - defaultPrefix = "/var/lib/docker/network/files" -) - -const ( - // NetworkKeyPrefix is the prefix for network key in the kv store - NetworkKeyPrefix = "network" - // EndpointKeyPrefix is the prefix for endpoint key in the kv store - EndpointKeyPrefix = "endpoint" -) - -var ( - defaultScopes = makeDefaultScopes() -) - -func makeDefaultScopes() map[string]*ScopeCfg { - def := make(map[string]*ScopeCfg) - def[LocalScope] = &ScopeCfg{ - Client: ScopeClientCfg{ - Provider: string(store.BOLTDB), - Address: defaultPrefix + "/local-kv.db", - Config: &store.Config{ - Bucket: "libnetwork", - ConnectionTimeout: time.Minute, - }, - }, - } - - return def -} - -var defaultRootChain = []string{"docker", "network", "v1.0"} -var rootChain = defaultRootChain - -// DefaultScopes returns a map of default scopes and its config for clients to use. -func DefaultScopes(dataDir string) map[string]*ScopeCfg { - if dataDir != "" { - defaultScopes[LocalScope].Client.Address = dataDir + "/network/files/local-kv.db" - return defaultScopes - } - - defaultScopes[LocalScope].Client.Address = defaultPrefix + "/local-kv.db" - return defaultScopes -} - -// IsValid checks if the scope config has valid configuration. -func (cfg *ScopeCfg) IsValid() bool { - if cfg == nil || - strings.TrimSpace(cfg.Client.Provider) == "" || - strings.TrimSpace(cfg.Client.Address) == "" { - return false - } - - return true -} - -//Key provides convenient method to create a Key -func Key(key ...string) string { - keychain := append(rootChain, key...) - str := strings.Join(keychain, "/") - return str + "/" -} - -//ParseKey provides convenient method to unpack the key to complement the Key function -func ParseKey(key string) ([]string, error) { - chain := strings.Split(strings.Trim(key, "/"), "/") - - // The key must at least be equal to the rootChain in order to be considered as valid - if len(chain) <= len(rootChain) || !reflect.DeepEqual(chain[0:len(rootChain)], rootChain) { - return nil, types.BadRequestErrorf("invalid Key : %s", key) - } - return chain[len(rootChain):], nil -} - -// newClient used to connect to KV Store -func newClient(scope string, kv string, addr string, config *store.Config, cached bool) (DataStore, error) { - - if cached && scope != LocalScope { - return nil, fmt.Errorf("caching supported only for scope %s", LocalScope) - } - sequential := false - if scope == LocalScope { - sequential = true - } - - if config == nil { - config = &store.Config{} - } - - var addrs []string - - if kv == string(store.BOLTDB) { - // Parse file path - addrs = strings.Split(addr, ",") - } else { - // Parse URI - parts := strings.SplitN(addr, "/", 2) - addrs = strings.Split(parts[0], ",") - - // Add the custom prefix to the root chain - if len(parts) == 2 { - rootChain = append([]string{parts[1]}, defaultRootChain...) - } - } - - store, err := libkv.NewStore(store.Backend(kv), addrs, config) - if err != nil { - return nil, err - } - - ds := &datastore{scope: scope, store: store, active: true, watchCh: make(chan struct{}), sequential: sequential} - if cached { - ds.cache = newCache(ds) - } - - return ds, nil -} - -// NewDataStore creates a new instance of LibKV data store -func NewDataStore(scope string, cfg *ScopeCfg) (DataStore, error) { - if cfg == nil || cfg.Client.Provider == "" || cfg.Client.Address == "" { - c, ok := defaultScopes[scope] - if !ok || c.Client.Provider == "" || c.Client.Address == "" { - return nil, fmt.Errorf("unexpected scope %s without configuration passed", scope) - } - - cfg = c - } - - var cached bool - if scope == LocalScope { - cached = true - } - - return newClient(scope, cfg.Client.Provider, cfg.Client.Address, cfg.Client.Config, cached) -} - -// NewDataStoreFromConfig creates a new instance of LibKV data store starting from the datastore config data -func NewDataStoreFromConfig(dsc discoverapi.DatastoreConfigData) (DataStore, error) { - var ( - ok bool - sCfgP *store.Config - ) - - sCfgP, ok = dsc.Config.(*store.Config) - if !ok && dsc.Config != nil { - return nil, fmt.Errorf("cannot parse store configuration: %v", dsc.Config) - } - - scopeCfg := &ScopeCfg{ - Client: ScopeClientCfg{ - Address: dsc.Address, - Provider: dsc.Provider, - Config: sCfgP, - }, - } - - ds, err := NewDataStore(dsc.Scope, scopeCfg) - if err != nil { - return nil, fmt.Errorf("failed to construct datastore client from datastore configuration %v: %v", dsc, err) - } - - return ds, err -} - -func (ds *datastore) Close() { - ds.store.Close() -} - -func (ds *datastore) Scope() string { - return ds.scope -} - -func (ds *datastore) Active() bool { - return ds.active -} - -func (ds *datastore) Watchable() bool { - return ds.scope != LocalScope -} - -func (ds *datastore) Watch(kvObject KVObject, stopCh <-chan struct{}) (<-chan KVObject, error) { - sCh := make(chan struct{}) - - ctor, ok := kvObject.(KVConstructor) - if !ok { - return nil, fmt.Errorf("error watching object type %T, object does not implement KVConstructor interface", kvObject) - } - - kvpCh, err := ds.store.Watch(Key(kvObject.Key()...), sCh) - if err != nil { - return nil, err - } - - kvoCh := make(chan KVObject) - - go func() { - retry_watch: - var err error - - // Make sure to get a new instance of watch channel - ds.Lock() - watchCh := ds.watchCh - ds.Unlock() - - loop: - for { - select { - case <-stopCh: - close(sCh) - return - case kvPair := <-kvpCh: - // If the backend KV store gets reset libkv's go routine - // for the watch can exit resulting in a nil value in - // channel. - if kvPair == nil { - ds.Lock() - ds.active = false - ds.Unlock() - break loop - } - - dstO := ctor.New() - - if err = dstO.SetValue(kvPair.Value); err != nil { - log.Printf("Could not unmarshal kvpair value = %s", string(kvPair.Value)) - break - } - - dstO.SetIndex(kvPair.LastIndex) - kvoCh <- dstO - } - } - - // Wait on watch channel for a re-trigger when datastore becomes active - <-watchCh - - kvpCh, err = ds.store.Watch(Key(kvObject.Key()...), sCh) - if err != nil { - log.Printf("Could not watch the key %s in store: %v", Key(kvObject.Key()...), err) - } - - goto retry_watch - }() - - return kvoCh, nil -} - -func (ds *datastore) RestartWatch() { - ds.Lock() - defer ds.Unlock() - - ds.active = true - watchCh := ds.watchCh - ds.watchCh = make(chan struct{}) - close(watchCh) -} - -func (ds *datastore) KVStore() store.Store { - return ds.store -} - -// PutObjectAtomic adds a new Record based on an object into the datastore -func (ds *datastore) PutObjectAtomic(kvObject KVObject) error { - var ( - previous *store.KVPair - pair *store.KVPair - err error - ) - if ds.sequential { - ds.Lock() - defer ds.Unlock() - } - - if kvObject == nil { - return types.BadRequestErrorf("invalid KV Object : nil") - } - - kvObjValue := kvObject.Value() - - if kvObjValue == nil { - return types.BadRequestErrorf("invalid KV Object with a nil Value for key %s", Key(kvObject.Key()...)) - } - - if kvObject.Skip() { - goto add_cache - } - - if kvObject.Exists() { - previous = &store.KVPair{Key: Key(kvObject.Key()...), LastIndex: kvObject.Index()} - } else { - previous = nil - } - - _, pair, err = ds.store.AtomicPut(Key(kvObject.Key()...), kvObjValue, previous, nil) - if err != nil { - if err == store.ErrKeyExists { - return ErrKeyModified - } - return err - } - - kvObject.SetIndex(pair.LastIndex) - -add_cache: - if ds.cache != nil { - // If persistent store is skipped, sequencing needs to - // happen in cache. - return ds.cache.add(kvObject, kvObject.Skip()) - } - - return nil -} - -// PutObject adds a new Record based on an object into the datastore -func (ds *datastore) PutObject(kvObject KVObject) error { - if ds.sequential { - ds.Lock() - defer ds.Unlock() - } - - if kvObject == nil { - return types.BadRequestErrorf("invalid KV Object : nil") - } - - if kvObject.Skip() { - goto add_cache - } - - if err := ds.putObjectWithKey(kvObject, kvObject.Key()...); err != nil { - return err - } - -add_cache: - if ds.cache != nil { - // If persistent store is skipped, sequencing needs to - // happen in cache. - return ds.cache.add(kvObject, kvObject.Skip()) - } - - return nil -} - -func (ds *datastore) putObjectWithKey(kvObject KVObject, key ...string) error { - kvObjValue := kvObject.Value() - - if kvObjValue == nil { - return types.BadRequestErrorf("invalid KV Object with a nil Value for key %s", Key(kvObject.Key()...)) - } - return ds.store.Put(Key(key...), kvObjValue, nil) -} - -// GetObject returns a record matching the key -func (ds *datastore) GetObject(key string, o KVObject) error { - if ds.sequential { - ds.Lock() - defer ds.Unlock() - } - - if ds.cache != nil { - return ds.cache.get(key, o) - } - - kvPair, err := ds.store.Get(key) - if err != nil { - return err - } - - if err := o.SetValue(kvPair.Value); err != nil { - return err - } - - // Make sure the object has a correct view of the DB index in - // case we need to modify it and update the DB. - o.SetIndex(kvPair.LastIndex) - return nil -} - -func (ds *datastore) ensureParent(parent string) error { - exists, err := ds.store.Exists(parent) - if err != nil { - return err - } - if exists { - return nil - } - return ds.store.Put(parent, []byte{}, &store.WriteOptions{IsDir: true}) -} - -func (ds *datastore) List(key string, kvObject KVObject) ([]KVObject, error) { - if ds.sequential { - ds.Lock() - defer ds.Unlock() - } - - if ds.cache != nil { - return ds.cache.list(kvObject) - } - - var kvol []KVObject - cb := func(key string, val KVObject) { - kvol = append(kvol, val) - } - err := ds.iterateKVPairsFromStore(key, kvObject, cb) - if err != nil { - return nil, err - } - return kvol, nil -} - -func (ds *datastore) iterateKVPairsFromStore(key string, kvObject KVObject, callback func(string, KVObject)) error { - // Bail out right away if the kvObject does not implement KVConstructor - ctor, ok := kvObject.(KVConstructor) - if !ok { - return fmt.Errorf("error listing objects, object does not implement KVConstructor interface") - } - - // Make sure the parent key exists - if err := ds.ensureParent(key); err != nil { - return err - } - - kvList, err := ds.store.List(key) - if err != nil { - return err - } - - for _, kvPair := range kvList { - if len(kvPair.Value) == 0 { - continue - } - - dstO := ctor.New() - if err := dstO.SetValue(kvPair.Value); err != nil { - return err - } - - // Make sure the object has a correct view of the DB index in - // case we need to modify it and update the DB. - dstO.SetIndex(kvPair.LastIndex) - callback(kvPair.Key, dstO) - } - - return nil -} - -func (ds *datastore) Map(key string, kvObject KVObject) (map[string]KVObject, error) { - if ds.sequential { - ds.Lock() - defer ds.Unlock() - } - - kvol := make(map[string]KVObject) - cb := func(key string, val KVObject) { - // Trim the leading & trailing "/" to make it consistent across all stores - kvol[strings.Trim(key, "/")] = val - } - err := ds.iterateKVPairsFromStore(key, kvObject, cb) - if err != nil { - return nil, err - } - return kvol, nil -} - -// DeleteObject unconditionally deletes a record from the store -func (ds *datastore) DeleteObject(kvObject KVObject) error { - if ds.sequential { - ds.Lock() - defer ds.Unlock() - } - - // cleanup the cache first - if ds.cache != nil { - // If persistent store is skipped, sequencing needs to - // happen in cache. - ds.cache.del(kvObject, kvObject.Skip()) - } - - if kvObject.Skip() { - return nil - } - - return ds.store.Delete(Key(kvObject.Key()...)) -} - -// DeleteObjectAtomic performs atomic delete on a record -func (ds *datastore) DeleteObjectAtomic(kvObject KVObject) error { - if ds.sequential { - ds.Lock() - defer ds.Unlock() - } - - if kvObject == nil { - return types.BadRequestErrorf("invalid KV Object : nil") - } - - previous := &store.KVPair{Key: Key(kvObject.Key()...), LastIndex: kvObject.Index()} - - if kvObject.Skip() { - goto del_cache - } - - if _, err := ds.store.AtomicDelete(Key(kvObject.Key()...), previous); err != nil { - if err == store.ErrKeyExists { - return ErrKeyModified - } - return err - } - -del_cache: - // cleanup the cache only if AtomicDelete went through successfully - if ds.cache != nil { - // If persistent store is skipped, sequencing needs to - // happen in cache. - return ds.cache.del(kvObject, kvObject.Skip()) - } - - return nil -} - -// DeleteTree unconditionally deletes a record from the store -func (ds *datastore) DeleteTree(kvObject KVObject) error { - if ds.sequential { - ds.Lock() - defer ds.Unlock() - } - - // cleanup the cache first - if ds.cache != nil { - // If persistent store is skipped, sequencing needs to - // happen in cache. - ds.cache.del(kvObject, kvObject.Skip()) - } - - if kvObject.Skip() { - return nil - } - - return ds.store.DeleteTree(Key(kvObject.KeyPrefix()...)) -} diff --git a/vendor/github.com/docker/libnetwork/datastore/mock_store.go b/vendor/github.com/docker/libnetwork/datastore/mock_store.go deleted file mode 100644 index 215cc4fd01..0000000000 --- a/vendor/github.com/docker/libnetwork/datastore/mock_store.go +++ /dev/null @@ -1,129 +0,0 @@ -package datastore - -import ( - "errors" - - "github.com/docker/libkv/store" - "github.com/docker/libnetwork/types" -) - -var ( - // ErrNotImplemented exported - ErrNotImplemented = errors.New("Functionality not implemented") -) - -// MockData exported -type MockData struct { - Data []byte - Index uint64 -} - -// MockStore exported -type MockStore struct { - db map[string]*MockData -} - -// NewMockStore creates a Map backed Datastore that is useful for mocking -func NewMockStore() *MockStore { - db := make(map[string]*MockData) - return &MockStore{db} -} - -// Get the value at "key", returns the last modified index -// to use in conjunction to CAS calls -func (s *MockStore) Get(key string) (*store.KVPair, error) { - mData := s.db[key] - if mData == nil { - return nil, nil - } - return &store.KVPair{Value: mData.Data, LastIndex: mData.Index}, nil - -} - -// Put a value at "key" -func (s *MockStore) Put(key string, value []byte, options *store.WriteOptions) error { - mData := s.db[key] - if mData == nil { - mData = &MockData{value, 0} - } - mData.Index = mData.Index + 1 - s.db[key] = mData - return nil -} - -// Delete a value at "key" -func (s *MockStore) Delete(key string) error { - delete(s.db, key) - return nil -} - -// Exists checks that the key exists inside the store -func (s *MockStore) Exists(key string) (bool, error) { - _, ok := s.db[key] - return ok, nil -} - -// List gets a range of values at "directory" -func (s *MockStore) List(prefix string) ([]*store.KVPair, error) { - return nil, ErrNotImplemented -} - -// DeleteTree deletes a range of values at "directory" -func (s *MockStore) DeleteTree(prefix string) error { - delete(s.db, prefix) - return nil -} - -// Watch a single key for modifications -func (s *MockStore) Watch(key string, stopCh <-chan struct{}) (<-chan *store.KVPair, error) { - return nil, ErrNotImplemented -} - -// WatchTree triggers a watch on a range of values at "directory" -func (s *MockStore) WatchTree(prefix string, stopCh <-chan struct{}) (<-chan []*store.KVPair, error) { - return nil, ErrNotImplemented -} - -// NewLock exposed -func (s *MockStore) NewLock(key string, options *store.LockOptions) (store.Locker, error) { - return nil, ErrNotImplemented -} - -// AtomicPut put a value at "key" if the key has not been -// modified in the meantime, throws an error if this is the case -func (s *MockStore) AtomicPut(key string, newValue []byte, previous *store.KVPair, options *store.WriteOptions) (bool, *store.KVPair, error) { - mData := s.db[key] - - if previous == nil { - if mData != nil { - return false, nil, types.BadRequestErrorf("atomic put failed because key exists") - } // Else OK. - } else { - if mData == nil { - return false, nil, types.BadRequestErrorf("atomic put failed because key exists") - } - if mData != nil && mData.Index != previous.LastIndex { - return false, nil, types.BadRequestErrorf("atomic put failed due to mismatched Index") - } // Else OK. - } - err := s.Put(key, newValue, nil) - if err != nil { - return false, nil, err - } - return true, &store.KVPair{Key: key, Value: newValue, LastIndex: s.db[key].Index}, nil -} - -// AtomicDelete deletes a value at "key" if the key has not -// been modified in the meantime, throws an error if this is the case -func (s *MockStore) AtomicDelete(key string, previous *store.KVPair) (bool, error) { - mData := s.db[key] - if mData != nil && mData.Index != previous.LastIndex { - return false, types.BadRequestErrorf("atomic delete failed due to mismatched Index") - } - return true, s.Delete(key) -} - -// Close closes the client connection -func (s *MockStore) Close() { - return -} diff --git a/vendor/github.com/docker/libnetwork/default_gateway.go b/vendor/github.com/docker/libnetwork/default_gateway.go deleted file mode 100644 index b3336ebbe8..0000000000 --- a/vendor/github.com/docker/libnetwork/default_gateway.go +++ /dev/null @@ -1,201 +0,0 @@ -package libnetwork - -import ( - "fmt" - "strings" - - "github.com/docker/libnetwork/netlabel" - "github.com/docker/libnetwork/types" - "github.com/sirupsen/logrus" -) - -const ( - gwEPlen = 12 -) - -var procGwNetwork = make(chan (bool), 1) - -/* - libnetwork creates a bridge network "docker_gw_bridge" for providing - default gateway for the containers if none of the container's endpoints - have GW set by the driver. ICC is set to false for the GW_bridge network. - - If a driver can't provide external connectivity it can choose to not set - the GW IP for the endpoint. - - endpoint on the GW_bridge network is managed dynamically by libnetwork. - ie: - - its created when an endpoint without GW joins the container - - its deleted when an endpoint with GW joins the container -*/ - -func (sb *sandbox) setupDefaultGW() error { - - // check if the container already has a GW endpoint - if ep := sb.getEndpointInGWNetwork(); ep != nil { - return nil - } - - c := sb.controller - - // Look for default gw network. In case of error (includes not found), - // retry and create it if needed in a serialized execution. - n, err := c.NetworkByName(libnGWNetwork) - if err != nil { - if n, err = c.defaultGwNetwork(); err != nil { - return err - } - } - - createOptions := []EndpointOption{CreateOptionAnonymous()} - - var gwName string - if len(sb.containerID) <= gwEPlen { - gwName = "gateway_" + sb.containerID - } else { - gwName = "gateway_" + sb.id[:gwEPlen] - } - - sbLabels := sb.Labels() - - if sbLabels[netlabel.PortMap] != nil { - createOptions = append(createOptions, CreateOptionPortMapping(sbLabels[netlabel.PortMap].([]types.PortBinding))) - } - - if sbLabels[netlabel.ExposedPorts] != nil { - createOptions = append(createOptions, CreateOptionExposedPorts(sbLabels[netlabel.ExposedPorts].([]types.TransportPort))) - } - - epOption := getPlatformOption() - if epOption != nil { - createOptions = append(createOptions, epOption) - } - - newEp, err := n.CreateEndpoint(gwName, createOptions...) - if err != nil { - return fmt.Errorf("container %s: endpoint create on GW Network failed: %v", sb.containerID, err) - } - - defer func() { - if err != nil { - if err2 := newEp.Delete(true); err2 != nil { - logrus.Warnf("Failed to remove gw endpoint for container %s after failing to join the gateway network: %v", - sb.containerID, err2) - } - } - }() - - epLocal := newEp.(*endpoint) - - if err = epLocal.sbJoin(sb); err != nil { - return fmt.Errorf("container %s: endpoint join on GW Network failed: %v", sb.containerID, err) - } - - return nil -} - -// If present, detach and remove the endpoint connecting the sandbox to the default gw network. -func (sb *sandbox) clearDefaultGW() error { - var ep *endpoint - - if ep = sb.getEndpointInGWNetwork(); ep == nil { - return nil - } - if err := ep.sbLeave(sb, false); err != nil { - return fmt.Errorf("container %s: endpoint leaving GW Network failed: %v", sb.containerID, err) - } - if err := ep.Delete(false); err != nil { - return fmt.Errorf("container %s: deleting endpoint on GW Network failed: %v", sb.containerID, err) - } - return nil -} - -// Evaluate whether the sandbox requires a default gateway based -// on the endpoints to which it is connected. It does not account -// for the default gateway network endpoint. - -func (sb *sandbox) needDefaultGW() bool { - var needGW bool - - for _, ep := range sb.getConnectedEndpoints() { - if ep.endpointInGWNetwork() { - continue - } - if ep.getNetwork().Type() == "null" || ep.getNetwork().Type() == "host" { - continue - } - if ep.getNetwork().Internal() { - continue - } - // During stale sandbox cleanup, joinInfo may be nil - if ep.joinInfo != nil && ep.joinInfo.disableGatewayService { - continue - } - // TODO v6 needs to be handled. - if len(ep.Gateway()) > 0 { - return false - } - for _, r := range ep.StaticRoutes() { - if r.Destination != nil && r.Destination.String() == "0.0.0.0/0" { - return false - } - } - needGW = true - } - - return needGW -} - -func (sb *sandbox) getEndpointInGWNetwork() *endpoint { - for _, ep := range sb.getConnectedEndpoints() { - if ep.getNetwork().name == libnGWNetwork && strings.HasPrefix(ep.Name(), "gateway_") { - return ep - } - } - return nil -} - -func (ep *endpoint) endpointInGWNetwork() bool { - if ep.getNetwork().name == libnGWNetwork && strings.HasPrefix(ep.Name(), "gateway_") { - return true - } - return false -} - -func (sb *sandbox) getEPwithoutGateway() *endpoint { - for _, ep := range sb.getConnectedEndpoints() { - if ep.getNetwork().Type() == "null" || ep.getNetwork().Type() == "host" { - continue - } - if len(ep.Gateway()) == 0 { - return ep - } - } - return nil -} - -// Looks for the default gw network and creates it if not there. -// Parallel executions are serialized. -func (c *controller) defaultGwNetwork() (Network, error) { - procGwNetwork <- true - defer func() { <-procGwNetwork }() - - n, err := c.NetworkByName(libnGWNetwork) - if _, ok := err.(types.NotFoundError); ok { - n, err = c.createGWNetwork() - } - return n, err -} - -// Returns the endpoint which is providing external connectivity to the sandbox -func (sb *sandbox) getGatewayEndpoint() *endpoint { - for _, ep := range sb.getConnectedEndpoints() { - if ep.getNetwork().Type() == "null" || ep.getNetwork().Type() == "host" { - continue - } - if len(ep.Gateway()) != 0 { - return ep - } - } - return nil -} diff --git a/vendor/github.com/docker/libnetwork/default_gateway_freebsd.go b/vendor/github.com/docker/libnetwork/default_gateway_freebsd.go deleted file mode 100644 index dc4b1bd592..0000000000 --- a/vendor/github.com/docker/libnetwork/default_gateway_freebsd.go +++ /dev/null @@ -1,13 +0,0 @@ -package libnetwork - -import "github.com/docker/libnetwork/types" - -const libnGWNetwork = "docker_gwbridge" - -func getPlatformOption() EndpointOption { - return nil -} - -func (c *controller) createGWNetwork() (Network, error) { - return nil, types.NotImplementedErrorf("default gateway functionality is not implemented in freebsd") -} diff --git a/vendor/github.com/docker/libnetwork/default_gateway_linux.go b/vendor/github.com/docker/libnetwork/default_gateway_linux.go deleted file mode 100644 index 60df856722..0000000000 --- a/vendor/github.com/docker/libnetwork/default_gateway_linux.go +++ /dev/null @@ -1,32 +0,0 @@ -package libnetwork - -import ( - "fmt" - "strconv" - - "github.com/docker/libnetwork/drivers/bridge" -) - -const libnGWNetwork = "docker_gwbridge" - -func getPlatformOption() EndpointOption { - return nil -} - -func (c *controller) createGWNetwork() (Network, error) { - netOption := map[string]string{ - bridge.BridgeName: libnGWNetwork, - bridge.EnableICC: strconv.FormatBool(false), - bridge.EnableIPMasquerade: strconv.FormatBool(true), - } - - n, err := c.NewNetwork("bridge", libnGWNetwork, "", - NetworkOptionDriverOpts(netOption), - NetworkOptionEnableIPv6(false), - ) - - if err != nil { - return nil, fmt.Errorf("error creating external connectivity network: %v", err) - } - return n, err -} diff --git a/vendor/github.com/docker/libnetwork/default_gateway_windows.go b/vendor/github.com/docker/libnetwork/default_gateway_windows.go deleted file mode 100644 index f4ba198e57..0000000000 --- a/vendor/github.com/docker/libnetwork/default_gateway_windows.go +++ /dev/null @@ -1,22 +0,0 @@ -package libnetwork - -import ( - windriver "github.com/docker/libnetwork/drivers/windows" - "github.com/docker/libnetwork/options" - "github.com/docker/libnetwork/types" -) - -const libnGWNetwork = "nat" - -func getPlatformOption() EndpointOption { - - epOption := options.Generic{ - windriver.DisableICC: true, - windriver.DisableDNS: true, - } - return EndpointOptionGeneric(epOption) -} - -func (c *controller) createGWNetwork() (Network, error) { - return nil, types.NotImplementedErrorf("default gateway functionality is not implemented in windows") -} diff --git a/vendor/github.com/docker/libnetwork/diagnostic/server.go b/vendor/github.com/docker/libnetwork/diagnostic/server.go deleted file mode 100644 index 6c9372d682..0000000000 --- a/vendor/github.com/docker/libnetwork/diagnostic/server.go +++ /dev/null @@ -1,227 +0,0 @@ -package diagnostic - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "sync" - "sync/atomic" - - stackdump "github.com/docker/docker/pkg/signal" - "github.com/docker/libnetwork/internal/caller" - "github.com/sirupsen/logrus" -) - -// HTTPHandlerFunc TODO -type HTTPHandlerFunc func(interface{}, http.ResponseWriter, *http.Request) - -type httpHandlerCustom struct { - ctx interface{} - F func(interface{}, http.ResponseWriter, *http.Request) -} - -// ServeHTTP TODO -func (h httpHandlerCustom) ServeHTTP(w http.ResponseWriter, r *http.Request) { - h.F(h.ctx, w, r) -} - -var diagPaths2Func = map[string]HTTPHandlerFunc{ - "/": notImplemented, - "/help": help, - "/ready": ready, - "/stackdump": stackTrace, -} - -// Server when the debug is enabled exposes a -// This data structure is protected by the Agent mutex so does not require and additional mutex here -type Server struct { - enable int32 - srv *http.Server - port int - mux *http.ServeMux - registeredHanders map[string]bool - sync.Mutex -} - -// New creates a new diagnostic server -func New() *Server { - return &Server{ - registeredHanders: make(map[string]bool), - } -} - -// Init initialize the mux for the http handling and register the base hooks -func (s *Server) Init() { - s.mux = http.NewServeMux() - - // Register local handlers - s.RegisterHandler(s, diagPaths2Func) -} - -// RegisterHandler allows to register new handlers to the mux and to a specific path -func (s *Server) RegisterHandler(ctx interface{}, hdlrs map[string]HTTPHandlerFunc) { - s.Lock() - defer s.Unlock() - for path, fun := range hdlrs { - if _, ok := s.registeredHanders[path]; ok { - continue - } - s.mux.Handle(path, httpHandlerCustom{ctx, fun}) - s.registeredHanders[path] = true - } -} - -// ServeHTTP this is the method called bu the ListenAndServe, and is needed to allow us to -// use our custom mux -func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { - s.mux.ServeHTTP(w, r) -} - -// EnableDiagnostic opens a TCP socket to debug the passed network DB -func (s *Server) EnableDiagnostic(ip string, port int) { - s.Lock() - defer s.Unlock() - - s.port = port - - if s.enable == 1 { - logrus.Info("The server is already up and running") - return - } - - logrus.Infof("Starting the diagnostic server listening on %d for commands", port) - srv := &http.Server{Addr: fmt.Sprintf("%s:%d", ip, port), Handler: s} - s.srv = srv - s.enable = 1 - go func(n *Server) { - // Ignore ErrServerClosed that is returned on the Shutdown call - if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed { - logrus.Errorf("ListenAndServe error: %s", err) - atomic.SwapInt32(&n.enable, 0) - } - }(s) -} - -// DisableDiagnostic stop the dubug and closes the tcp socket -func (s *Server) DisableDiagnostic() { - s.Lock() - defer s.Unlock() - - s.srv.Shutdown(context.Background()) - s.srv = nil - s.enable = 0 - logrus.Info("Disabling the diagnostic server") -} - -// IsDiagnosticEnabled returns true when the debug is enabled -func (s *Server) IsDiagnosticEnabled() bool { - s.Lock() - defer s.Unlock() - return s.enable == 1 -} - -func notImplemented(ctx interface{}, w http.ResponseWriter, r *http.Request) { - r.ParseForm() - _, json := ParseHTTPFormOptions(r) - rsp := WrongCommand("not implemented", fmt.Sprintf("URL path: %s no method implemented check /help\n", r.URL.Path)) - - // audit logs - log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) - log.Info("command not implemented done") - - HTTPReply(w, rsp, json) -} - -func help(ctx interface{}, w http.ResponseWriter, r *http.Request) { - r.ParseForm() - _, json := ParseHTTPFormOptions(r) - - // audit logs - log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) - log.Info("help done") - - n, ok := ctx.(*Server) - var result string - if ok { - for path := range n.registeredHanders { - result += fmt.Sprintf("%s\n", path) - } - HTTPReply(w, CommandSucceed(&StringCmd{Info: result}), json) - } -} - -func ready(ctx interface{}, w http.ResponseWriter, r *http.Request) { - r.ParseForm() - _, json := ParseHTTPFormOptions(r) - - // audit logs - log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) - log.Info("ready done") - HTTPReply(w, CommandSucceed(&StringCmd{Info: "OK"}), json) -} - -func stackTrace(ctx interface{}, w http.ResponseWriter, r *http.Request) { - r.ParseForm() - _, json := ParseHTTPFormOptions(r) - - // audit logs - log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) - log.Info("stack trace") - - path, err := stackdump.DumpStacks("/tmp/") - if err != nil { - log.WithError(err).Error("failed to write goroutines dump") - HTTPReply(w, FailCommand(err), json) - } else { - log.Info("stack trace done") - HTTPReply(w, CommandSucceed(&StringCmd{Info: fmt.Sprintf("goroutine stacks written to %s", path)}), json) - } -} - -// DebugHTTPForm helper to print the form url parameters -func DebugHTTPForm(r *http.Request) { - for k, v := range r.Form { - logrus.Debugf("Form[%q] = %q\n", k, v) - } -} - -// JSONOutput contains details on JSON output printing -type JSONOutput struct { - enable bool - prettyPrint bool -} - -// ParseHTTPFormOptions easily parse the JSON printing options -func ParseHTTPFormOptions(r *http.Request) (bool, *JSONOutput) { - _, unsafe := r.Form["unsafe"] - v, json := r.Form["json"] - var pretty bool - if len(v) > 0 { - pretty = v[0] == "pretty" - } - return unsafe, &JSONOutput{enable: json, prettyPrint: pretty} -} - -// HTTPReply helper function that takes care of sending the message out -func HTTPReply(w http.ResponseWriter, r *HTTPResult, j *JSONOutput) (int, error) { - var response []byte - if j.enable { - w.Header().Set("Content-Type", "application/json") - var err error - if j.prettyPrint { - response, err = json.MarshalIndent(r, "", " ") - if err != nil { - response, _ = json.MarshalIndent(FailCommand(err), "", " ") - } - } else { - response, err = json.Marshal(r) - if err != nil { - response, _ = json.Marshal(FailCommand(err)) - } - } - } else { - response = []byte(r.String()) - } - return fmt.Fprint(w, string(response)) -} diff --git a/vendor/github.com/docker/libnetwork/diagnostic/types.go b/vendor/github.com/docker/libnetwork/diagnostic/types.go deleted file mode 100644 index e6b4831263..0000000000 --- a/vendor/github.com/docker/libnetwork/diagnostic/types.go +++ /dev/null @@ -1,132 +0,0 @@ -package diagnostic - -import "fmt" - -// StringInterface interface that has to be implemented by messages -type StringInterface interface { - String() string -} - -// CommandSucceed creates a success message -func CommandSucceed(result StringInterface) *HTTPResult { - return &HTTPResult{ - Message: "OK", - Details: result, - } -} - -// FailCommand creates a failure message with error -func FailCommand(err error) *HTTPResult { - return &HTTPResult{ - Message: "FAIL", - Details: &ErrorCmd{Error: err.Error()}, - } -} - -// WrongCommand creates a wrong command response -func WrongCommand(message, usage string) *HTTPResult { - return &HTTPResult{ - Message: message, - Details: &UsageCmd{Usage: usage}, - } -} - -// HTTPResult Diagnostic Server HTTP result operation -type HTTPResult struct { - Message string `json:"message"` - Details StringInterface `json:"details"` -} - -func (h *HTTPResult) String() string { - rsp := h.Message - if h.Details != nil { - rsp += "\n" + h.Details.String() - } - return rsp -} - -// UsageCmd command with usage field -type UsageCmd struct { - Usage string `json:"usage"` -} - -func (u *UsageCmd) String() string { - return "Usage: " + u.Usage -} - -// StringCmd command with info string -type StringCmd struct { - Info string `json:"info"` -} - -func (s *StringCmd) String() string { - return s.Info -} - -// ErrorCmd command with error -type ErrorCmd struct { - Error string `json:"error"` -} - -func (e *ErrorCmd) String() string { - return "Error: " + e.Error -} - -// TableObj network db table object -type TableObj struct { - Length int `json:"size"` - Elements []StringInterface `json:"entries"` -} - -func (t *TableObj) String() string { - output := fmt.Sprintf("total entries: %d\n", t.Length) - for _, e := range t.Elements { - output += e.String() - } - return output -} - -// PeerEntryObj entry in the networkdb peer table -type PeerEntryObj struct { - Index int `json:"-"` - Name string `json:"-=name"` - IP string `json:"ip"` -} - -func (p *PeerEntryObj) String() string { - return fmt.Sprintf("%d) %s -> %s\n", p.Index, p.Name, p.IP) -} - -// TableEntryObj network db table entry object -type TableEntryObj struct { - Index int `json:"-"` - Key string `json:"key"` - Value string `json:"value"` - Owner string `json:"owner"` -} - -func (t *TableEntryObj) String() string { - return fmt.Sprintf("%d) k:`%s` -> v:`%s` owner:`%s`\n", t.Index, t.Key, t.Value, t.Owner) -} - -// TableEndpointsResult fully typed message for proper unmarshaling on the client side -type TableEndpointsResult struct { - TableObj - Elements []TableEntryObj `json:"entries"` -} - -// TablePeersResult fully typed message for proper unmarshaling on the client side -type TablePeersResult struct { - TableObj - Elements []PeerEntryObj `json:"entries"` -} - -// NetworkStatsResult network db stats related to entries and queue len for a network -type NetworkStatsResult struct { - Entries int `json:"entries"` - QueueLen int `jsoin:"qlen"` -} - -func (n *NetworkStatsResult) String() string { - return fmt.Sprintf("entries: %d, qlen: %d\n", n.Entries, n.QueueLen) -} diff --git a/vendor/github.com/docker/libnetwork/discoverapi/discoverapi.go b/vendor/github.com/docker/libnetwork/discoverapi/discoverapi.go deleted file mode 100644 index 7ac36155db..0000000000 --- a/vendor/github.com/docker/libnetwork/discoverapi/discoverapi.go +++ /dev/null @@ -1,60 +0,0 @@ -package discoverapi - -// Discover is an interface to be implemented by the component interested in receiving discover events -// like new node joining the cluster or datastore updates -type Discover interface { - // DiscoverNew is a notification for a new discovery event, Example:a new node joining a cluster - DiscoverNew(dType DiscoveryType, data interface{}) error - - // DiscoverDelete is a notification for a discovery delete event, Example:a node leaving a cluster - DiscoverDelete(dType DiscoveryType, data interface{}) error -} - -// DiscoveryType represents the type of discovery element the DiscoverNew function is invoked on -type DiscoveryType int - -const ( - // NodeDiscovery represents Node join/leave events provided by discovery - NodeDiscovery = iota + 1 - // DatastoreConfig represents an add/remove datastore event - DatastoreConfig - // EncryptionKeysConfig represents the initial key(s) for performing datapath encryption - EncryptionKeysConfig - // EncryptionKeysUpdate represents an update to the datapath encryption key(s) - EncryptionKeysUpdate -) - -// NodeDiscoveryData represents the structure backing the node discovery data json string -type NodeDiscoveryData struct { - Address string - BindAddress string - Self bool -} - -// DatastoreConfigData is the data for the datastore update event message -type DatastoreConfigData struct { - Scope string - Provider string - Address string - Config interface{} -} - -// DriverEncryptionConfig contains the initial datapath encryption key(s) -// Key in first position is the primary key, the one to be used in tx. -// Original key and tag types are []byte and uint64 -type DriverEncryptionConfig struct { - Keys [][]byte - Tags []uint64 -} - -// DriverEncryptionUpdate carries an update to the encryption key(s) as: -// a new key and/or set a primary key and/or a removal of an existing key. -// Original key and tag types are []byte and uint64 -type DriverEncryptionUpdate struct { - Key []byte - Tag uint64 - Primary []byte - PrimaryTag uint64 - Prune []byte - PruneTag uint64 -} diff --git a/vendor/github.com/docker/libnetwork/driverapi/driverapi.go b/vendor/github.com/docker/libnetwork/driverapi/driverapi.go deleted file mode 100644 index ea1175299e..0000000000 --- a/vendor/github.com/docker/libnetwork/driverapi/driverapi.go +++ /dev/null @@ -1,218 +0,0 @@ -package driverapi - -import ( - "net" - - "github.com/docker/docker/pkg/plugingetter" - "github.com/docker/libnetwork/discoverapi" -) - -// NetworkPluginEndpointType represents the Endpoint Type used by Plugin system -const NetworkPluginEndpointType = "NetworkDriver" - -// Driver is an interface that every plugin driver needs to implement. -type Driver interface { - discoverapi.Discover - - // NetworkAllocate invokes the driver method to allocate network - // specific resources passing network id and network specific config. - // It returns a key,value pair of network specific driver allocations - // to the caller. - NetworkAllocate(nid string, options map[string]string, ipV4Data, ipV6Data []IPAMData) (map[string]string, error) - - // NetworkFree invokes the driver method to free network specific resources - // associated with a given network id. - NetworkFree(nid string) error - - // CreateNetwork invokes the driver method to create a network - // passing the network id and network specific config. The - // config mechanism will eventually be replaced with labels - // which are yet to be introduced. The driver can return a - // list of table names for which it is interested in receiving - // notification when a CRUD operation is performed on any - // entry in that table. This will be ignored for local scope - // drivers. - CreateNetwork(nid string, options map[string]interface{}, nInfo NetworkInfo, ipV4Data, ipV6Data []IPAMData) error - - // DeleteNetwork invokes the driver method to delete network passing - // the network id. - DeleteNetwork(nid string) error - - // CreateEndpoint invokes the driver method to create an endpoint - // passing the network id, endpoint id endpoint information and driver - // specific config. The endpoint information can be either consumed by - // the driver or populated by the driver. The config mechanism will - // eventually be replaced with labels which are yet to be introduced. - CreateEndpoint(nid, eid string, ifInfo InterfaceInfo, options map[string]interface{}) error - - // DeleteEndpoint invokes the driver method to delete an endpoint - // passing the network id and endpoint id. - DeleteEndpoint(nid, eid string) error - - // EndpointOperInfo retrieves from the driver the operational data related to the specified endpoint - EndpointOperInfo(nid, eid string) (map[string]interface{}, error) - - // Join method is invoked when a Sandbox is attached to an endpoint. - Join(nid, eid string, sboxKey string, jinfo JoinInfo, options map[string]interface{}) error - - // Leave method is invoked when a Sandbox detaches from an endpoint. - Leave(nid, eid string) error - - // ProgramExternalConnectivity invokes the driver method which does the necessary - // programming to allow the external connectivity dictated by the passed options - ProgramExternalConnectivity(nid, eid string, options map[string]interface{}) error - - // RevokeExternalConnectivity asks the driver to remove any external connectivity - // programming that was done so far - RevokeExternalConnectivity(nid, eid string) error - - // EventNotify notifies the driver when a CRUD operation has - // happened on a table of its interest as soon as this node - // receives such an event in the gossip layer. This method is - // only invoked for the global scope driver. - EventNotify(event EventType, nid string, tableName string, key string, value []byte) - - // DecodeTableEntry passes the driver a key, value pair from table it registered - // with libnetwork. Driver should return {object ID, map[string]string} tuple. - // If DecodeTableEntry is called for a table associated with NetworkObject or - // EndpointObject the return object ID should be the network id or endpoint id - // associated with that entry. map should have information about the object that - // can be presented to the user. - // For example: overlay driver returns the VTEP IP of the host that has the endpoint - // which is shown in 'network inspect --verbose' - DecodeTableEntry(tablename string, key string, value []byte) (string, map[string]string) - - // Type returns the type of this driver, the network type this driver manages - Type() string - - // IsBuiltIn returns true if it is a built-in driver - IsBuiltIn() bool -} - -// NetworkInfo provides a go interface for drivers to provide network -// specific information to libnetwork. -type NetworkInfo interface { - // TableEventRegister registers driver interest in a given - // table name. - TableEventRegister(tableName string, objType ObjectType) error - - // UpdateIPamConfig updates the networks IPAM configuration - // based on information from the driver. In windows, the OS (HNS) chooses - // the IP address space if the user does not specify an address space. - UpdateIpamConfig(ipV4Data []IPAMData) -} - -// InterfaceInfo provides a go interface for drivers to retrieve -// network information to interface resources. -type InterfaceInfo interface { - // SetMacAddress allows the driver to set the mac address to the endpoint interface - // during the call to CreateEndpoint, if the mac address is not already set. - SetMacAddress(mac net.HardwareAddr) error - - // SetIPAddress allows the driver to set the ip address to the endpoint interface - // during the call to CreateEndpoint, if the address is not already set. - // The API is to be used to assign both the IPv4 and IPv6 address types. - SetIPAddress(ip *net.IPNet) error - - // MacAddress returns the MAC address. - MacAddress() net.HardwareAddr - - // Address returns the IPv4 address. - Address() *net.IPNet - - // AddressIPv6 returns the IPv6 address. - AddressIPv6() *net.IPNet -} - -// InterfaceNameInfo provides a go interface for the drivers to assign names -// to interfaces. -type InterfaceNameInfo interface { - // SetNames method assigns the srcName and dstPrefix for the interface. - SetNames(srcName, dstPrefix string) error -} - -// JoinInfo represents a set of resources that the driver has the ability to provide during -// join time. -type JoinInfo interface { - // InterfaceName returns an InterfaceNameInfo go interface to facilitate - // setting the names for the interface. - InterfaceName() InterfaceNameInfo - - // SetGateway sets the default IPv4 gateway when a container joins the endpoint. - SetGateway(net.IP) error - - // SetGatewayIPv6 sets the default IPv6 gateway when a container joins the endpoint. - SetGatewayIPv6(net.IP) error - - // AddStaticRoute adds a route to the sandbox. - // It may be used in addition to or instead of a default gateway (as above). - AddStaticRoute(destination *net.IPNet, routeType int, nextHop net.IP) error - - // DisableGatewayService tells libnetwork not to provide Default GW for the container - DisableGatewayService() - - // AddTableEntry adds a table entry to the gossip layer - // passing the table name, key and an opaque value. - AddTableEntry(tableName string, key string, value []byte) error -} - -// DriverCallback provides a Callback interface for Drivers into LibNetwork -type DriverCallback interface { - // GetPluginGetter returns the pluginv2 getter. - GetPluginGetter() plugingetter.PluginGetter - // RegisterDriver provides a way for Remote drivers to dynamically register new NetworkType and associate with a driver instance - RegisterDriver(name string, driver Driver, capability Capability) error -} - -// Capability represents the high level capabilities of the drivers which libnetwork can make use of -type Capability struct { - DataScope string - ConnectivityScope string -} - -// IPAMData represents the per-network ip related -// operational information libnetwork will send -// to the network driver during CreateNetwork() -type IPAMData struct { - AddressSpace string - Pool *net.IPNet - Gateway *net.IPNet - AuxAddresses map[string]*net.IPNet -} - -// EventType defines a type for the CRUD event -type EventType uint8 - -const ( - // Create event is generated when a table entry is created, - Create EventType = 1 + iota - // Update event is generated when a table entry is updated. - Update - // Delete event is generated when a table entry is deleted. - Delete -) - -// ObjectType represents the type of object driver wants to store in libnetwork's networkDB -type ObjectType int - -const ( - // EndpointObject should be set for libnetwork endpoint object related data - EndpointObject ObjectType = 1 + iota - // NetworkObject should be set for libnetwork network object related data - NetworkObject - // OpaqueObject is for driver specific data with no corresponding libnetwork object - OpaqueObject -) - -// IsValidType validates the passed in type against the valid object types -func IsValidType(objType ObjectType) bool { - switch objType { - case EndpointObject: - fallthrough - case NetworkObject: - fallthrough - case OpaqueObject: - return true - } - return false -} diff --git a/vendor/github.com/docker/libnetwork/driverapi/errors.go b/vendor/github.com/docker/libnetwork/driverapi/errors.go deleted file mode 100644 index 041ef41506..0000000000 --- a/vendor/github.com/docker/libnetwork/driverapi/errors.go +++ /dev/null @@ -1,56 +0,0 @@ -package driverapi - -import ( - "fmt" -) - -// ErrNoNetwork is returned if no network with the specified id exists -type ErrNoNetwork string - -func (enn ErrNoNetwork) Error() string { - return fmt.Sprintf("No network (%s) exists", string(enn)) -} - -// NotFound denotes the type of this error -func (enn ErrNoNetwork) NotFound() {} - -// ErrEndpointExists is returned if more than one endpoint is added to the network -type ErrEndpointExists string - -func (ee ErrEndpointExists) Error() string { - return fmt.Sprintf("Endpoint (%s) already exists (Only one endpoint allowed)", string(ee)) -} - -// Forbidden denotes the type of this error -func (ee ErrEndpointExists) Forbidden() {} - -// ErrNotImplemented is returned when a Driver has not implemented an API yet -type ErrNotImplemented struct{} - -func (eni *ErrNotImplemented) Error() string { - return "The API is not implemented yet" -} - -// NotImplemented denotes the type of this error -func (eni *ErrNotImplemented) NotImplemented() {} - -// ErrNoEndpoint is returned if no endpoint with the specified id exists -type ErrNoEndpoint string - -func (ene ErrNoEndpoint) Error() string { - return fmt.Sprintf("No endpoint (%s) exists", string(ene)) -} - -// NotFound denotes the type of this error -func (ene ErrNoEndpoint) NotFound() {} - -// ErrActiveRegistration represents an error when a driver is registered to a networkType that is previously registered -type ErrActiveRegistration string - -// Error interface for ErrActiveRegistration -func (ar ErrActiveRegistration) Error() string { - return fmt.Sprintf("Driver already registered for type %q", string(ar)) -} - -// Forbidden denotes the type of this error -func (ar ErrActiveRegistration) Forbidden() {} diff --git a/vendor/github.com/docker/libnetwork/driverapi/ipamdata.go b/vendor/github.com/docker/libnetwork/driverapi/ipamdata.go deleted file mode 100644 index fc1c2af441..0000000000 --- a/vendor/github.com/docker/libnetwork/driverapi/ipamdata.go +++ /dev/null @@ -1,103 +0,0 @@ -package driverapi - -import ( - "encoding/json" - "fmt" - "net" - - "github.com/docker/libnetwork/types" -) - -// MarshalJSON encodes IPAMData into json message -func (i *IPAMData) MarshalJSON() ([]byte, error) { - m := map[string]interface{}{} - m["AddressSpace"] = i.AddressSpace - if i.Pool != nil { - m["Pool"] = i.Pool.String() - } - if i.Gateway != nil { - m["Gateway"] = i.Gateway.String() - } - if i.AuxAddresses != nil { - am := make(map[string]string, len(i.AuxAddresses)) - for k, v := range i.AuxAddresses { - am[k] = v.String() - } - m["AuxAddresses"] = am - } - return json.Marshal(m) -} - -// UnmarshalJSON decodes a json message into IPAMData -func (i *IPAMData) UnmarshalJSON(data []byte) error { - var ( - m map[string]interface{} - err error - ) - if err := json.Unmarshal(data, &m); err != nil { - return err - } - i.AddressSpace = m["AddressSpace"].(string) - if v, ok := m["Pool"]; ok { - if i.Pool, err = types.ParseCIDR(v.(string)); err != nil { - return err - } - } - if v, ok := m["Gateway"]; ok { - if i.Gateway, err = types.ParseCIDR(v.(string)); err != nil { - return err - } - } - if v, ok := m["AuxAddresses"]; ok { - b, _ := json.Marshal(v) - var am map[string]string - if err = json.Unmarshal(b, &am); err != nil { - return err - } - i.AuxAddresses = make(map[string]*net.IPNet, len(am)) - for k, v := range am { - if i.AuxAddresses[k], err = types.ParseCIDR(v); err != nil { - return err - } - } - } - return nil -} - -// Validate checks whether the IPAMData structure contains congruent data -func (i *IPAMData) Validate() error { - var isV6 bool - if i.Pool == nil { - return types.BadRequestErrorf("invalid pool") - } - if i.Gateway == nil { - return types.BadRequestErrorf("invalid gateway address") - } - isV6 = i.IsV6() - if isV6 && i.Gateway.IP.To4() != nil || !isV6 && i.Gateway.IP.To4() == nil { - return types.BadRequestErrorf("incongruent ip versions for pool and gateway") - } - for k, sip := range i.AuxAddresses { - if isV6 && sip.IP.To4() != nil || !isV6 && sip.IP.To4() == nil { - return types.BadRequestErrorf("incongruent ip versions for pool and secondary ip address %s", k) - } - } - if !i.Pool.Contains(i.Gateway.IP) { - return types.BadRequestErrorf("invalid gateway address (%s) does not belong to the pool (%s)", i.Gateway, i.Pool) - } - for k, sip := range i.AuxAddresses { - if !i.Pool.Contains(sip.IP) { - return types.BadRequestErrorf("invalid secondary address %s (%s) does not belong to the pool (%s)", k, i.Gateway, i.Pool) - } - } - return nil -} - -// IsV6 returns whether this is an IPv6 IPAMData structure -func (i *IPAMData) IsV6() bool { - return nil == i.Pool.IP.To4() -} - -func (i *IPAMData) String() string { - return fmt.Sprintf("AddressSpace: %s\nPool: %v\nGateway: %v\nAddresses: %v", i.AddressSpace, i.Pool, i.Gateway, i.AuxAddresses) -} diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/bridge.go b/vendor/github.com/docker/libnetwork/drivers/bridge/bridge.go deleted file mode 100644 index f2e771a94b..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/bridge/bridge.go +++ /dev/null @@ -1,1579 +0,0 @@ -package bridge - -import ( - "errors" - "fmt" - "io/ioutil" - "net" - "os" - "os/exec" - "path/filepath" - "strconv" - "sync" - "syscall" - - "github.com/docker/libnetwork/datastore" - "github.com/docker/libnetwork/discoverapi" - "github.com/docker/libnetwork/driverapi" - "github.com/docker/libnetwork/iptables" - "github.com/docker/libnetwork/netlabel" - "github.com/docker/libnetwork/netutils" - "github.com/docker/libnetwork/ns" - "github.com/docker/libnetwork/options" - "github.com/docker/libnetwork/osl" - "github.com/docker/libnetwork/portmapper" - "github.com/docker/libnetwork/types" - "github.com/sirupsen/logrus" - "github.com/vishvananda/netlink" -) - -const ( - networkType = "bridge" - vethPrefix = "veth" - vethLen = 7 - defaultContainerVethPrefix = "eth" - maxAllocatePortAttempts = 10 -) - -const ( - // DefaultGatewayV4AuxKey represents the default-gateway configured by the user - DefaultGatewayV4AuxKey = "DefaultGatewayIPv4" - // DefaultGatewayV6AuxKey represents the ipv6 default-gateway configured by the user - DefaultGatewayV6AuxKey = "DefaultGatewayIPv6" -) - -type defaultBridgeNetworkConflict struct { - ID string -} - -func (d defaultBridgeNetworkConflict) Error() string { - return fmt.Sprintf("Stale default bridge network %s", d.ID) -} - -type iptableCleanFunc func() error -type iptablesCleanFuncs []iptableCleanFunc - -// configuration info for the "bridge" driver. -type configuration struct { - EnableIPForwarding bool - EnableIPTables bool - EnableIP6Tables bool - EnableUserlandProxy bool - UserlandProxyPath string -} - -// networkConfiguration for network specific configuration -type networkConfiguration struct { - ID string - BridgeName string - EnableIPv6 bool - EnableIPMasquerade bool - EnableICC bool - InhibitIPv4 bool - Mtu int - DefaultBindingIP net.IP - DefaultBridge bool - HostIP net.IP - ContainerIfacePrefix string - // Internal fields set after ipam data parsing - AddressIPv4 *net.IPNet - AddressIPv6 *net.IPNet - DefaultGatewayIPv4 net.IP - DefaultGatewayIPv6 net.IP - dbIndex uint64 - dbExists bool - Internal bool - - BridgeIfaceCreator ifaceCreator -} - -// ifaceCreator represents how the bridge interface was created -type ifaceCreator int8 - -const ( - ifaceCreatorUnknown ifaceCreator = iota - ifaceCreatedByLibnetwork - ifaceCreatedByUser -) - -// endpointConfiguration represents the user specified configuration for the sandbox endpoint -type endpointConfiguration struct { - MacAddress net.HardwareAddr -} - -// containerConfiguration represents the user specified configuration for a container -type containerConfiguration struct { - ParentEndpoints []string - ChildEndpoints []string -} - -// connectivityConfiguration represents the user specified configuration regarding the external connectivity -type connectivityConfiguration struct { - PortBindings []types.PortBinding - ExposedPorts []types.TransportPort -} - -type bridgeEndpoint struct { - id string - nid string - srcName string - addr *net.IPNet - addrv6 *net.IPNet - macAddress net.HardwareAddr - config *endpointConfiguration // User specified parameters - containerConfig *containerConfiguration - extConnConfig *connectivityConfiguration - portMapping []types.PortBinding // Operation port bindings - dbIndex uint64 - dbExists bool -} - -type bridgeNetwork struct { - id string - bridge *bridgeInterface // The bridge's L3 interface - config *networkConfiguration - endpoints map[string]*bridgeEndpoint // key: endpoint id - portMapper *portmapper.PortMapper - portMapperV6 *portmapper.PortMapper - driver *driver // The network's driver - iptCleanFuncs iptablesCleanFuncs - sync.Mutex -} - -type driver struct { - config *configuration - network *bridgeNetwork - natChain *iptables.ChainInfo - filterChain *iptables.ChainInfo - isolationChain1 *iptables.ChainInfo - isolationChain2 *iptables.ChainInfo - natChainV6 *iptables.ChainInfo - filterChainV6 *iptables.ChainInfo - isolationChain1V6 *iptables.ChainInfo - isolationChain2V6 *iptables.ChainInfo - networks map[string]*bridgeNetwork - store datastore.DataStore - nlh *netlink.Handle - configNetwork sync.Mutex - sync.Mutex -} - -// New constructs a new bridge driver -func newDriver() *driver { - return &driver{networks: map[string]*bridgeNetwork{}, config: &configuration{}} -} - -// Init registers a new instance of bridge driver -func Init(dc driverapi.DriverCallback, config map[string]interface{}) error { - d := newDriver() - if err := d.configure(config); err != nil { - return err - } - - c := driverapi.Capability{ - DataScope: datastore.LocalScope, - ConnectivityScope: datastore.LocalScope, - } - return dc.RegisterDriver(networkType, d, c) -} - -// Validate performs a static validation on the network configuration parameters. -// Whatever can be assessed a priori before attempting any programming. -func (c *networkConfiguration) Validate() error { - if c.Mtu < 0 { - return ErrInvalidMtu(c.Mtu) - } - - // If bridge v4 subnet is specified - if c.AddressIPv4 != nil { - // If default gw is specified, it must be part of bridge subnet - if c.DefaultGatewayIPv4 != nil { - if !c.AddressIPv4.Contains(c.DefaultGatewayIPv4) { - return &ErrInvalidGateway{} - } - } - } - - // If default v6 gw is specified, AddressIPv6 must be specified and gw must belong to AddressIPv6 subnet - if c.EnableIPv6 && c.DefaultGatewayIPv6 != nil { - if c.AddressIPv6 == nil || !c.AddressIPv6.Contains(c.DefaultGatewayIPv6) { - return &ErrInvalidGateway{} - } - } - return nil -} - -// Conflicts check if two NetworkConfiguration objects overlap -func (c *networkConfiguration) Conflicts(o *networkConfiguration) error { - if o == nil { - return errors.New("same configuration") - } - - // Also empty, because only one network with empty name is allowed - if c.BridgeName == o.BridgeName { - return errors.New("networks have same bridge name") - } - - // They must be in different subnets - if (c.AddressIPv4 != nil && o.AddressIPv4 != nil) && - (c.AddressIPv4.Contains(o.AddressIPv4.IP) || o.AddressIPv4.Contains(c.AddressIPv4.IP)) { - return errors.New("networks have overlapping IPv4") - } - - // They must be in different v6 subnets - if (c.AddressIPv6 != nil && o.AddressIPv6 != nil) && - (c.AddressIPv6.Contains(o.AddressIPv6.IP) || o.AddressIPv6.Contains(c.AddressIPv6.IP)) { - return errors.New("networks have overlapping IPv6") - } - - return nil -} - -func (c *networkConfiguration) fromLabels(labels map[string]string) error { - var err error - for label, value := range labels { - switch label { - case BridgeName: - c.BridgeName = value - case netlabel.DriverMTU: - if c.Mtu, err = strconv.Atoi(value); err != nil { - return parseErr(label, value, err.Error()) - } - case netlabel.EnableIPv6: - if c.EnableIPv6, err = strconv.ParseBool(value); err != nil { - return parseErr(label, value, err.Error()) - } - case EnableIPMasquerade: - if c.EnableIPMasquerade, err = strconv.ParseBool(value); err != nil { - return parseErr(label, value, err.Error()) - } - case EnableICC: - if c.EnableICC, err = strconv.ParseBool(value); err != nil { - return parseErr(label, value, err.Error()) - } - case InhibitIPv4: - if c.InhibitIPv4, err = strconv.ParseBool(value); err != nil { - return parseErr(label, value, err.Error()) - } - case DefaultBridge: - if c.DefaultBridge, err = strconv.ParseBool(value); err != nil { - return parseErr(label, value, err.Error()) - } - case DefaultBindingIP: - if c.DefaultBindingIP = net.ParseIP(value); c.DefaultBindingIP == nil { - return parseErr(label, value, "nil ip") - } - case netlabel.ContainerIfacePrefix: - c.ContainerIfacePrefix = value - case netlabel.HostIP: - if c.HostIP = net.ParseIP(value); c.HostIP == nil { - return parseErr(label, value, "nil ip") - } - } - } - - return nil -} - -func parseErr(label, value, errString string) error { - return types.BadRequestErrorf("failed to parse %s value: %v (%s)", label, value, errString) -} - -func (n *bridgeNetwork) registerIptCleanFunc(clean iptableCleanFunc) { - n.iptCleanFuncs = append(n.iptCleanFuncs, clean) -} - -func (n *bridgeNetwork) getDriverChains(version iptables.IPVersion) (*iptables.ChainInfo, *iptables.ChainInfo, *iptables.ChainInfo, *iptables.ChainInfo, error) { - n.Lock() - defer n.Unlock() - - if n.driver == nil { - return nil, nil, nil, nil, types.BadRequestErrorf("no driver found") - } - - if version == iptables.IPv6 { - return n.driver.natChainV6, n.driver.filterChainV6, n.driver.isolationChain1V6, n.driver.isolationChain2V6, nil - } - - return n.driver.natChain, n.driver.filterChain, n.driver.isolationChain1, n.driver.isolationChain2, nil -} - -func (n *bridgeNetwork) getNetworkBridgeName() string { - n.Lock() - config := n.config - n.Unlock() - - return config.BridgeName -} - -func (n *bridgeNetwork) getEndpoint(eid string) (*bridgeEndpoint, error) { - n.Lock() - defer n.Unlock() - - if eid == "" { - return nil, InvalidEndpointIDError(eid) - } - - if ep, ok := n.endpoints[eid]; ok { - return ep, nil - } - - return nil, nil -} - -// Install/Removes the iptables rules needed to isolate this network -// from each of the other networks -func (n *bridgeNetwork) isolateNetwork(others []*bridgeNetwork, enable bool) error { - n.Lock() - thisConfig := n.config - n.Unlock() - - if thisConfig.Internal { - return nil - } - - // Install the rules to isolate this network against each of the other networks - if n.driver.config.EnableIP6Tables { - err := setINC(iptables.IPv6, thisConfig.BridgeName, enable) - if err != nil { - return err - } - } - - if n.driver.config.EnableIPTables { - return setINC(iptables.IPv4, thisConfig.BridgeName, enable) - } - return nil -} - -func (d *driver) configure(option map[string]interface{}) error { - var ( - config *configuration - err error - natChain *iptables.ChainInfo - filterChain *iptables.ChainInfo - isolationChain1 *iptables.ChainInfo - isolationChain2 *iptables.ChainInfo - natChainV6 *iptables.ChainInfo - filterChainV6 *iptables.ChainInfo - isolationChain1V6 *iptables.ChainInfo - isolationChain2V6 *iptables.ChainInfo - ) - - genericData, ok := option[netlabel.GenericData] - if !ok || genericData == nil { - return nil - } - - switch opt := genericData.(type) { - case options.Generic: - opaqueConfig, err := options.GenerateFromModel(opt, &configuration{}) - if err != nil { - return err - } - config = opaqueConfig.(*configuration) - case *configuration: - config = opt - default: - return &ErrInvalidDriverConfig{} - } - - if config.EnableIPTables || config.EnableIP6Tables { - if _, err := os.Stat("/proc/sys/net/bridge"); err != nil { - if out, err := exec.Command("modprobe", "-va", "bridge", "br_netfilter").CombinedOutput(); err != nil { - logrus.Warnf("Running modprobe bridge br_netfilter failed with message: %s, error: %v", out, err) - } - } - } - - if config.EnableIPTables { - removeIPChains(iptables.IPv4) - - natChain, filterChain, isolationChain1, isolationChain2, err = setupIPChains(config, iptables.IPv4) - if err != nil { - return err - } - - // Make sure on firewall reload, first thing being re-played is chains creation - iptables.OnReloaded(func() { - logrus.Debugf("Recreating iptables chains on firewall reload") - setupIPChains(config, iptables.IPv4) - }) - } - - if config.EnableIP6Tables { - removeIPChains(iptables.IPv6) - - natChainV6, filterChainV6, isolationChain1V6, isolationChain2V6, err = setupIPChains(config, iptables.IPv6) - if err != nil { - return err - } - - // Make sure on firewall reload, first thing being re-played is chains creation - iptables.OnReloaded(func() { - logrus.Debugf("Recreating ip6tables chains on firewall reload") - setupIPChains(config, iptables.IPv6) - }) - } - - if config.EnableIPForwarding { - err = setupIPForwarding(config.EnableIPTables, config.EnableIP6Tables) - if err != nil { - logrus.Warn(err) - return err - } - } - - d.Lock() - d.natChain = natChain - d.filterChain = filterChain - d.isolationChain1 = isolationChain1 - d.isolationChain2 = isolationChain2 - d.natChainV6 = natChainV6 - d.filterChainV6 = filterChainV6 - d.isolationChain1V6 = isolationChain1V6 - d.isolationChain2V6 = isolationChain2V6 - d.config = config - d.Unlock() - - err = d.initStore(option) - if err != nil { - return err - } - - return nil -} - -func (d *driver) getNetwork(id string) (*bridgeNetwork, error) { - d.Lock() - defer d.Unlock() - - if id == "" { - return nil, types.BadRequestErrorf("invalid network id: %s", id) - } - - if nw, ok := d.networks[id]; ok { - return nw, nil - } - - return nil, types.NotFoundErrorf("network not found: %s", id) -} - -func parseNetworkGenericOptions(data interface{}) (*networkConfiguration, error) { - var ( - err error - config *networkConfiguration - ) - - switch opt := data.(type) { - case *networkConfiguration: - config = opt - case map[string]string: - config = &networkConfiguration{ - EnableICC: true, - EnableIPMasquerade: true, - } - err = config.fromLabels(opt) - case options.Generic: - var opaqueConfig interface{} - if opaqueConfig, err = options.GenerateFromModel(opt, config); err == nil { - config = opaqueConfig.(*networkConfiguration) - } - default: - err = types.BadRequestErrorf("do not recognize network configuration format: %T", opt) - } - - return config, err -} - -func (c *networkConfiguration) processIPAM(id string, ipamV4Data, ipamV6Data []driverapi.IPAMData) error { - if len(ipamV4Data) > 1 || len(ipamV6Data) > 1 { - return types.ForbiddenErrorf("bridge driver doesn't support multiple subnets") - } - - if len(ipamV4Data) == 0 { - return types.BadRequestErrorf("bridge network %s requires ipv4 configuration", id) - } - - if ipamV4Data[0].Gateway != nil { - c.AddressIPv4 = types.GetIPNetCopy(ipamV4Data[0].Gateway) - } - - if gw, ok := ipamV4Data[0].AuxAddresses[DefaultGatewayV4AuxKey]; ok { - c.DefaultGatewayIPv4 = gw.IP - } - - if len(ipamV6Data) > 0 { - c.AddressIPv6 = ipamV6Data[0].Pool - - if ipamV6Data[0].Gateway != nil { - c.AddressIPv6 = types.GetIPNetCopy(ipamV6Data[0].Gateway) - } - - if gw, ok := ipamV6Data[0].AuxAddresses[DefaultGatewayV6AuxKey]; ok { - c.DefaultGatewayIPv6 = gw.IP - } - } - - return nil -} - -func parseNetworkOptions(id string, option options.Generic) (*networkConfiguration, error) { - var ( - err error - config = &networkConfiguration{} - ) - - // Parse generic label first, config will be re-assigned - if genData, ok := option[netlabel.GenericData]; ok && genData != nil { - if config, err = parseNetworkGenericOptions(genData); err != nil { - return nil, err - } - } - - // Process well-known labels next - if val, ok := option[netlabel.EnableIPv6]; ok { - config.EnableIPv6 = val.(bool) - } - - if val, ok := option[netlabel.Internal]; ok { - if internal, ok := val.(bool); ok && internal { - config.Internal = true - } - } - - // Finally validate the configuration - if err = config.Validate(); err != nil { - return nil, err - } - - if config.BridgeName == "" && config.DefaultBridge == false { - config.BridgeName = "br-" + id[:12] - } - - exists, err := bridgeInterfaceExists(config.BridgeName) - if err != nil { - return nil, err - } - - if !exists { - config.BridgeIfaceCreator = ifaceCreatedByLibnetwork - } else { - config.BridgeIfaceCreator = ifaceCreatedByUser - } - - config.ID = id - return config, nil -} - -// Returns the non link-local IPv6 subnet for the containers attached to this bridge if found, nil otherwise -func getV6Network(config *networkConfiguration, i *bridgeInterface) *net.IPNet { - if config.AddressIPv6 != nil { - return config.AddressIPv6 - } - if i.bridgeIPv6 != nil && i.bridgeIPv6.IP != nil && !i.bridgeIPv6.IP.IsLinkLocalUnicast() { - return i.bridgeIPv6 - } - - return nil -} - -// Return a slice of networks over which caller can iterate safely -func (d *driver) getNetworks() []*bridgeNetwork { - d.Lock() - defer d.Unlock() - - ls := make([]*bridgeNetwork, 0, len(d.networks)) - for _, nw := range d.networks { - ls = append(ls, nw) - } - return ls -} - -func (d *driver) NetworkAllocate(id string, option map[string]string, ipV4Data, ipV6Data []driverapi.IPAMData) (map[string]string, error) { - return nil, types.NotImplementedErrorf("not implemented") -} - -func (d *driver) NetworkFree(id string) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) EventNotify(etype driverapi.EventType, nid, tableName, key string, value []byte) { -} - -func (d *driver) DecodeTableEntry(tablename string, key string, value []byte) (string, map[string]string) { - return "", nil -} - -// Create a new network using bridge plugin -func (d *driver) CreateNetwork(id string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error { - if len(ipV4Data) == 0 || ipV4Data[0].Pool.String() == "0.0.0.0/0" { - return types.BadRequestErrorf("ipv4 pool is empty") - } - // Sanity checks - d.Lock() - if _, ok := d.networks[id]; ok { - d.Unlock() - return types.ForbiddenErrorf("network %s exists", id) - } - d.Unlock() - - // Parse and validate the config. It should not be conflict with existing networks' config - config, err := parseNetworkOptions(id, option) - if err != nil { - return err - } - - if err = config.processIPAM(id, ipV4Data, ipV6Data); err != nil { - return err - } - - // start the critical section, from this point onward we are dealing with the list of networks - // so to be consistent we cannot allow that the list changes - d.configNetwork.Lock() - defer d.configNetwork.Unlock() - - // check network conflicts - if err = d.checkConflict(config); err != nil { - nerr, ok := err.(defaultBridgeNetworkConflict) - if !ok { - return err - } - // Got a conflict with a stale default network, clean that up and continue - logrus.Warn(nerr) - d.deleteNetwork(nerr.ID) - } - - // there is no conflict, now create the network - if err = d.createNetwork(config); err != nil { - return err - } - - return d.storeUpdate(config) -} - -func (d *driver) checkConflict(config *networkConfiguration) error { - networkList := d.getNetworks() - for _, nw := range networkList { - nw.Lock() - nwConfig := nw.config - nw.Unlock() - if err := nwConfig.Conflicts(config); err != nil { - if nwConfig.DefaultBridge { - // We encountered and identified a stale default network - // We must delete it as libnetwork is the source of truth - // The default network being created must be the only one - // This can happen only from docker 1.12 on ward - logrus.Infof("Found stale default bridge network %s (%s)", nwConfig.ID, nwConfig.BridgeName) - return defaultBridgeNetworkConflict{nwConfig.ID} - } - - return types.ForbiddenErrorf("cannot create network %s (%s): conflicts with network %s (%s): %s", - config.ID, config.BridgeName, nwConfig.ID, nwConfig.BridgeName, err.Error()) - } - } - return nil -} - -func (d *driver) createNetwork(config *networkConfiguration) (err error) { - defer osl.InitOSContext()() - - networkList := d.getNetworks() - - // Initialize handle when needed - d.Lock() - if d.nlh == nil { - d.nlh = ns.NlHandle() - } - d.Unlock() - - // Create or retrieve the bridge L3 interface - bridgeIface, err := newInterface(d.nlh, config) - if err != nil { - return err - } - - // Create and set network handler in driver - network := &bridgeNetwork{ - id: config.ID, - endpoints: make(map[string]*bridgeEndpoint), - config: config, - portMapper: portmapper.New(d.config.UserlandProxyPath), - portMapperV6: portmapper.New(d.config.UserlandProxyPath), - bridge: bridgeIface, - driver: d, - } - - d.Lock() - d.networks[config.ID] = network - d.Unlock() - - // On failure make sure to reset driver network handler to nil - defer func() { - if err != nil { - d.Lock() - delete(d.networks, config.ID) - d.Unlock() - } - }() - - // Add inter-network communication rules. - setupNetworkIsolationRules := func(config *networkConfiguration, i *bridgeInterface) error { - if err := network.isolateNetwork(networkList, true); err != nil { - if err = network.isolateNetwork(networkList, false); err != nil { - logrus.Warnf("Failed on removing the inter-network iptables rules on cleanup: %v", err) - } - return err - } - // register the cleanup function - network.registerIptCleanFunc(func() error { - nwList := d.getNetworks() - return network.isolateNetwork(nwList, false) - }) - return nil - } - - // Prepare the bridge setup configuration - bridgeSetup := newBridgeSetup(config, bridgeIface) - - // If the bridge interface doesn't exist, we need to start the setup steps - // by creating a new device and assigning it an IPv4 address. - bridgeAlreadyExists := bridgeIface.exists() - if !bridgeAlreadyExists { - bridgeSetup.queueStep(setupDevice) - bridgeSetup.queueStep(setupDefaultSysctl) - } - - // For the default bridge, set expected sysctls - if config.DefaultBridge { - bridgeSetup.queueStep(setupDefaultSysctl) - } - - // Even if a bridge exists try to setup IPv4. - bridgeSetup.queueStep(setupBridgeIPv4) - - enableIPv6Forwarding := d.config.EnableIPForwarding && config.AddressIPv6 != nil - - // Conditionally queue setup steps depending on configuration values. - for _, step := range []struct { - Condition bool - Fn setupStep - }{ - // Enable IPv6 on the bridge if required. We do this even for a - // previously existing bridge, as it may be here from a previous - // installation where IPv6 wasn't supported yet and needs to be - // assigned an IPv6 link-local address. - {config.EnableIPv6, setupBridgeIPv6}, - - // We ensure that the bridge has the expectedIPv4 and IPv6 addresses in - // the case of a previously existing device. - {bridgeAlreadyExists && !config.InhibitIPv4, setupVerifyAndReconcile}, - - // Enable IPv6 Forwarding - {enableIPv6Forwarding, setupIPv6Forwarding}, - - // Setup Loopback Addresses Routing - {!d.config.EnableUserlandProxy, setupLoopbackAddressesRouting}, - - // Setup IPTables. - {d.config.EnableIPTables, network.setupIP4Tables}, - - // Setup IP6Tables. - {config.EnableIPv6 && d.config.EnableIP6Tables, network.setupIP6Tables}, - - //We want to track firewalld configuration so that - //if it is started/reloaded, the rules can be applied correctly - {d.config.EnableIPTables, network.setupFirewalld}, - // same for IPv6 - {config.EnableIPv6 && d.config.EnableIP6Tables, network.setupFirewalld6}, - - // Setup DefaultGatewayIPv4 - {config.DefaultGatewayIPv4 != nil, setupGatewayIPv4}, - - // Setup DefaultGatewayIPv6 - {config.DefaultGatewayIPv6 != nil, setupGatewayIPv6}, - - // Add inter-network communication rules. - {d.config.EnableIPTables, setupNetworkIsolationRules}, - - //Configure bridge networking filtering if ICC is off and IP tables are enabled - {!config.EnableICC && d.config.EnableIPTables, setupBridgeNetFiltering}, - } { - if step.Condition { - bridgeSetup.queueStep(step.Fn) - } - } - - // Apply the prepared list of steps, and abort at the first error. - bridgeSetup.queueStep(setupDeviceUp) - return bridgeSetup.apply() -} - -func (d *driver) DeleteNetwork(nid string) error { - - d.configNetwork.Lock() - defer d.configNetwork.Unlock() - - return d.deleteNetwork(nid) -} - -func (d *driver) deleteNetwork(nid string) error { - var err error - - defer osl.InitOSContext()() - // Get network handler and remove it from driver - d.Lock() - n, ok := d.networks[nid] - d.Unlock() - - if !ok { - return types.InternalMaskableErrorf("network %s does not exist", nid) - } - - n.Lock() - config := n.config - n.Unlock() - - // delele endpoints belong to this network - for _, ep := range n.endpoints { - if err := n.releasePorts(ep); err != nil { - logrus.Warn(err) - } - if link, err := d.nlh.LinkByName(ep.srcName); err == nil { - if err := d.nlh.LinkDel(link); err != nil { - logrus.WithError(err).Errorf("Failed to delete interface (%s)'s link on endpoint (%s) delete", ep.srcName, ep.id) - } - } - - if err := d.storeDelete(ep); err != nil { - logrus.Warnf("Failed to remove bridge endpoint %.7s from store: %v", ep.id, err) - } - } - - d.Lock() - delete(d.networks, nid) - d.Unlock() - - // On failure set network handler back in driver, but - // only if is not already taken over by some other thread - defer func() { - if err != nil { - d.Lock() - if _, ok := d.networks[nid]; !ok { - d.networks[nid] = n - } - d.Unlock() - } - }() - - switch config.BridgeIfaceCreator { - case ifaceCreatedByLibnetwork, ifaceCreatorUnknown: - // We only delete the bridge if it was created by the bridge driver and - // it is not the default one (to keep the backward compatible behavior.) - if !config.DefaultBridge { - if err := d.nlh.LinkDel(n.bridge.Link); err != nil { - logrus.Warnf("Failed to remove bridge interface %s on network %s delete: %v", config.BridgeName, nid, err) - } - } - case ifaceCreatedByUser: - // Don't delete the bridge interface if it was not created by libnetwork. - } - - // clean all relevant iptables rules - for _, cleanFunc := range n.iptCleanFuncs { - if errClean := cleanFunc(); errClean != nil { - logrus.Warnf("Failed to clean iptables rules for bridge network: %v", errClean) - } - } - return d.storeDelete(config) -} - -func addToBridge(nlh *netlink.Handle, ifaceName, bridgeName string) error { - link, err := nlh.LinkByName(ifaceName) - if err != nil { - return fmt.Errorf("could not find interface %s: %v", ifaceName, err) - } - if err = nlh.LinkSetMaster(link, - &netlink.Bridge{LinkAttrs: netlink.LinkAttrs{Name: bridgeName}}); err != nil { - logrus.Debugf("Failed to add %s to bridge via netlink.Trying ioctl: %v", ifaceName, err) - iface, err := net.InterfaceByName(ifaceName) - if err != nil { - return fmt.Errorf("could not find network interface %s: %v", ifaceName, err) - } - - master, err := net.InterfaceByName(bridgeName) - if err != nil { - return fmt.Errorf("could not find bridge %s: %v", bridgeName, err) - } - - return ioctlAddToBridge(iface, master) - } - return nil -} - -func setHairpinMode(nlh *netlink.Handle, link netlink.Link, enable bool) error { - err := nlh.LinkSetHairpin(link, enable) - if err != nil && err != syscall.EINVAL { - // If error is not EINVAL something else went wrong, bail out right away - return fmt.Errorf("unable to set hairpin mode on %s via netlink: %v", - link.Attrs().Name, err) - } - - // Hairpin mode successfully set up - if err == nil { - return nil - } - - // The netlink method failed with EINVAL which is probably because of an older - // kernel. Try one more time via the sysfs method. - path := filepath.Join("/sys/class/net", link.Attrs().Name, "brport/hairpin_mode") - - var val []byte - if enable { - val = []byte{'1', '\n'} - } else { - val = []byte{'0', '\n'} - } - - if err := ioutil.WriteFile(path, val, 0644); err != nil { - return fmt.Errorf("unable to set hairpin mode on %s via sysfs: %v", link.Attrs().Name, err) - } - - return nil -} - -func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo, epOptions map[string]interface{}) error { - defer osl.InitOSContext()() - - if ifInfo == nil { - return errors.New("invalid interface info passed") - } - - // Get the network handler and make sure it exists - d.Lock() - n, ok := d.networks[nid] - dconfig := d.config - d.Unlock() - - if !ok { - return types.NotFoundErrorf("network %s does not exist", nid) - } - if n == nil { - return driverapi.ErrNoNetwork(nid) - } - - // Sanity check - n.Lock() - if n.id != nid { - n.Unlock() - return InvalidNetworkIDError(nid) - } - n.Unlock() - - // Check if endpoint id is good and retrieve correspondent endpoint - ep, err := n.getEndpoint(eid) - if err != nil { - return err - } - - // Endpoint with that id exists either on desired or other sandbox - if ep != nil { - return driverapi.ErrEndpointExists(eid) - } - - // Try to convert the options to endpoint configuration - epConfig, err := parseEndpointOptions(epOptions) - if err != nil { - return err - } - - // Create and add the endpoint - n.Lock() - endpoint := &bridgeEndpoint{id: eid, nid: nid, config: epConfig} - n.endpoints[eid] = endpoint - n.Unlock() - - // On failure make sure to remove the endpoint - defer func() { - if err != nil { - n.Lock() - delete(n.endpoints, eid) - n.Unlock() - } - }() - - // Generate a name for what will be the host side pipe interface - hostIfName, err := netutils.GenerateIfaceName(d.nlh, vethPrefix, vethLen) - if err != nil { - return err - } - - // Generate a name for what will be the sandbox side pipe interface - containerIfName, err := netutils.GenerateIfaceName(d.nlh, vethPrefix, vethLen) - if err != nil { - return err - } - - // Generate and add the interface pipe host <-> sandbox - veth := &netlink.Veth{ - LinkAttrs: netlink.LinkAttrs{Name: hostIfName, TxQLen: 0}, - PeerName: containerIfName} - if err = d.nlh.LinkAdd(veth); err != nil { - return types.InternalErrorf("failed to add the host (%s) <=> sandbox (%s) pair interfaces: %v", hostIfName, containerIfName, err) - } - - // Get the host side pipe interface handler - host, err := d.nlh.LinkByName(hostIfName) - if err != nil { - return types.InternalErrorf("failed to find host side interface %s: %v", hostIfName, err) - } - defer func() { - if err != nil { - if err := d.nlh.LinkDel(host); err != nil { - logrus.WithError(err).Warnf("Failed to delete host side interface (%s)'s link", hostIfName) - } - } - }() - - // Get the sandbox side pipe interface handler - sbox, err := d.nlh.LinkByName(containerIfName) - if err != nil { - return types.InternalErrorf("failed to find sandbox side interface %s: %v", containerIfName, err) - } - defer func() { - if err != nil { - if err := d.nlh.LinkDel(sbox); err != nil { - logrus.WithError(err).Warnf("Failed to delete sandbox side interface (%s)'s link", containerIfName) - } - } - }() - - n.Lock() - config := n.config - n.Unlock() - - // Add bridge inherited attributes to pipe interfaces - if config.Mtu != 0 { - err = d.nlh.LinkSetMTU(host, config.Mtu) - if err != nil { - return types.InternalErrorf("failed to set MTU on host interface %s: %v", hostIfName, err) - } - err = d.nlh.LinkSetMTU(sbox, config.Mtu) - if err != nil { - return types.InternalErrorf("failed to set MTU on sandbox interface %s: %v", containerIfName, err) - } - } - - // Attach host side pipe interface into the bridge - if err = addToBridge(d.nlh, hostIfName, config.BridgeName); err != nil { - return fmt.Errorf("adding interface %s to bridge %s failed: %v", hostIfName, config.BridgeName, err) - } - - if !dconfig.EnableUserlandProxy { - err = setHairpinMode(d.nlh, host, true) - if err != nil { - return err - } - } - - // Store the sandbox side pipe interface parameters - endpoint.srcName = containerIfName - endpoint.macAddress = ifInfo.MacAddress() - endpoint.addr = ifInfo.Address() - endpoint.addrv6 = ifInfo.AddressIPv6() - - // Set the sbox's MAC if not provided. If specified, use the one configured by user, otherwise generate one based on IP. - if endpoint.macAddress == nil { - endpoint.macAddress = electMacAddress(epConfig, endpoint.addr.IP) - if err = ifInfo.SetMacAddress(endpoint.macAddress); err != nil { - return err - } - } - - // Up the host interface after finishing all netlink configuration - if err = d.nlh.LinkSetUp(host); err != nil { - return fmt.Errorf("could not set link up for host interface %s: %v", hostIfName, err) - } - - if endpoint.addrv6 == nil && config.EnableIPv6 { - var ip6 net.IP - network := n.bridge.bridgeIPv6 - if config.AddressIPv6 != nil { - network = config.AddressIPv6 - } - - ones, _ := network.Mask.Size() - if ones > 80 { - err = types.ForbiddenErrorf("Cannot self generate an IPv6 address on network %v: At least 48 host bits are needed.", network) - return err - } - - ip6 = make(net.IP, len(network.IP)) - copy(ip6, network.IP) - for i, h := range endpoint.macAddress { - ip6[i+10] = h - } - - endpoint.addrv6 = &net.IPNet{IP: ip6, Mask: network.Mask} - if err = ifInfo.SetIPAddress(endpoint.addrv6); err != nil { - return err - } - } - - if err = d.storeUpdate(endpoint); err != nil { - return fmt.Errorf("failed to save bridge endpoint %.7s to store: %v", endpoint.id, err) - } - - return nil -} - -func (d *driver) DeleteEndpoint(nid, eid string) error { - var err error - - defer osl.InitOSContext()() - - // Get the network handler and make sure it exists - d.Lock() - n, ok := d.networks[nid] - d.Unlock() - - if !ok { - return types.InternalMaskableErrorf("network %s does not exist", nid) - } - if n == nil { - return driverapi.ErrNoNetwork(nid) - } - - // Sanity Check - n.Lock() - if n.id != nid { - n.Unlock() - return InvalidNetworkIDError(nid) - } - n.Unlock() - - // Check endpoint id and if an endpoint is actually there - ep, err := n.getEndpoint(eid) - if err != nil { - return err - } - if ep == nil { - return EndpointNotFoundError(eid) - } - - // Remove it - n.Lock() - delete(n.endpoints, eid) - n.Unlock() - - // On failure make sure to set back ep in n.endpoints, but only - // if it hasn't been taken over already by some other thread. - defer func() { - if err != nil { - n.Lock() - if _, ok := n.endpoints[eid]; !ok { - n.endpoints[eid] = ep - } - n.Unlock() - } - }() - - // Try removal of link. Discard error: it is a best effort. - // Also make sure defer does not see this error either. - if link, err := d.nlh.LinkByName(ep.srcName); err == nil { - if err := d.nlh.LinkDel(link); err != nil { - logrus.WithError(err).Errorf("Failed to delete interface (%s)'s link on endpoint (%s) delete", ep.srcName, ep.id) - } - } - - if err := d.storeDelete(ep); err != nil { - logrus.Warnf("Failed to remove bridge endpoint %.7s from store: %v", ep.id, err) - } - - return nil -} - -func (d *driver) EndpointOperInfo(nid, eid string) (map[string]interface{}, error) { - // Get the network handler and make sure it exists - d.Lock() - n, ok := d.networks[nid] - d.Unlock() - if !ok { - return nil, types.NotFoundErrorf("network %s does not exist", nid) - } - if n == nil { - return nil, driverapi.ErrNoNetwork(nid) - } - - // Sanity check - n.Lock() - if n.id != nid { - n.Unlock() - return nil, InvalidNetworkIDError(nid) - } - n.Unlock() - - // Check if endpoint id is good and retrieve correspondent endpoint - ep, err := n.getEndpoint(eid) - if err != nil { - return nil, err - } - if ep == nil { - return nil, driverapi.ErrNoEndpoint(eid) - } - - m := make(map[string]interface{}) - - if ep.extConnConfig != nil && ep.extConnConfig.ExposedPorts != nil { - // Return a copy of the config data - epc := make([]types.TransportPort, 0, len(ep.extConnConfig.ExposedPorts)) - for _, tp := range ep.extConnConfig.ExposedPorts { - epc = append(epc, tp.GetCopy()) - } - m[netlabel.ExposedPorts] = epc - } - - if ep.portMapping != nil { - // Return a copy of the operational data - pmc := make([]types.PortBinding, 0, len(ep.portMapping)) - for _, pm := range ep.portMapping { - pmc = append(pmc, pm.GetCopy()) - } - m[netlabel.PortMap] = pmc - } - - if len(ep.macAddress) != 0 { - m[netlabel.MacAddress] = ep.macAddress - } - - return m, nil -} - -// Join method is invoked when a Sandbox is attached to an endpoint. -func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error { - defer osl.InitOSContext()() - - network, err := d.getNetwork(nid) - if err != nil { - return err - } - - endpoint, err := network.getEndpoint(eid) - if err != nil { - return err - } - - if endpoint == nil { - return EndpointNotFoundError(eid) - } - - endpoint.containerConfig, err = parseContainerOptions(options) - if err != nil { - return err - } - - iNames := jinfo.InterfaceName() - containerVethPrefix := defaultContainerVethPrefix - if network.config.ContainerIfacePrefix != "" { - containerVethPrefix = network.config.ContainerIfacePrefix - } - err = iNames.SetNames(endpoint.srcName, containerVethPrefix) - if err != nil { - return err - } - - err = jinfo.SetGateway(network.bridge.gatewayIPv4) - if err != nil { - return err - } - - err = jinfo.SetGatewayIPv6(network.bridge.gatewayIPv6) - if err != nil { - return err - } - - return nil -} - -// Leave method is invoked when a Sandbox detaches from an endpoint. -func (d *driver) Leave(nid, eid string) error { - defer osl.InitOSContext()() - - network, err := d.getNetwork(nid) - if err != nil { - return types.InternalMaskableErrorf("%s", err) - } - - endpoint, err := network.getEndpoint(eid) - if err != nil { - return err - } - - if endpoint == nil { - return EndpointNotFoundError(eid) - } - - if !network.config.EnableICC { - if err = d.link(network, endpoint, false); err != nil { - return err - } - } - - return nil -} - -func (d *driver) ProgramExternalConnectivity(nid, eid string, options map[string]interface{}) error { - defer osl.InitOSContext()() - - network, err := d.getNetwork(nid) - if err != nil { - return err - } - - endpoint, err := network.getEndpoint(eid) - if err != nil { - return err - } - - if endpoint == nil { - return EndpointNotFoundError(eid) - } - - endpoint.extConnConfig, err = parseConnectivityOptions(options) - if err != nil { - return err - } - - // Program any required port mapping and store them in the endpoint - endpoint.portMapping, err = network.allocatePorts(endpoint, network.config.DefaultBindingIP, d.config.EnableUserlandProxy) - if err != nil { - return err - } - - defer func() { - if err != nil { - if e := network.releasePorts(endpoint); e != nil { - logrus.Errorf("Failed to release ports allocated for the bridge endpoint %s on failure %v because of %v", - eid, err, e) - } - endpoint.portMapping = nil - } - }() - - if err = d.storeUpdate(endpoint); err != nil { - return fmt.Errorf("failed to update bridge endpoint %.7s to store: %v", endpoint.id, err) - } - - if !network.config.EnableICC { - return d.link(network, endpoint, true) - } - - return nil -} - -func (d *driver) RevokeExternalConnectivity(nid, eid string) error { - defer osl.InitOSContext()() - - network, err := d.getNetwork(nid) - if err != nil { - return err - } - - endpoint, err := network.getEndpoint(eid) - if err != nil { - return err - } - - if endpoint == nil { - return EndpointNotFoundError(eid) - } - - err = network.releasePorts(endpoint) - if err != nil { - logrus.Warn(err) - } - - endpoint.portMapping = nil - - // Clean the connection tracker state of the host for the specific endpoint - // The host kernel keeps track of the connections (TCP and UDP), so if a new endpoint gets the same IP of - // this one (that is going down), is possible that some of the packets would not be routed correctly inside - // the new endpoint - // Deeper details: https://github.com/docker/docker/issues/8795 - clearEndpointConnections(d.nlh, endpoint) - - if err = d.storeUpdate(endpoint); err != nil { - return fmt.Errorf("failed to update bridge endpoint %.7s to store: %v", endpoint.id, err) - } - - return nil -} - -func (d *driver) link(network *bridgeNetwork, endpoint *bridgeEndpoint, enable bool) error { - var err error - - cc := endpoint.containerConfig - if cc == nil { - return nil - } - ec := endpoint.extConnConfig - if ec == nil { - return nil - } - - if ec.ExposedPorts != nil { - for _, p := range cc.ParentEndpoints { - var parentEndpoint *bridgeEndpoint - parentEndpoint, err = network.getEndpoint(p) - if err != nil { - return err - } - if parentEndpoint == nil { - err = InvalidEndpointIDError(p) - return err - } - - l := newLink(parentEndpoint.addr.IP.String(), - endpoint.addr.IP.String(), - ec.ExposedPorts, network.config.BridgeName) - if enable { - err = l.Enable() - if err != nil { - return err - } - defer func() { - if err != nil { - l.Disable() - } - }() - } else { - l.Disable() - } - } - } - - for _, c := range cc.ChildEndpoints { - var childEndpoint *bridgeEndpoint - childEndpoint, err = network.getEndpoint(c) - if err != nil { - return err - } - if childEndpoint == nil { - err = InvalidEndpointIDError(c) - return err - } - if childEndpoint.extConnConfig == nil || childEndpoint.extConnConfig.ExposedPorts == nil { - continue - } - - l := newLink(endpoint.addr.IP.String(), - childEndpoint.addr.IP.String(), - childEndpoint.extConnConfig.ExposedPorts, network.config.BridgeName) - if enable { - err = l.Enable() - if err != nil { - return err - } - defer func() { - if err != nil { - l.Disable() - } - }() - } else { - l.Disable() - } - } - - return nil -} - -func (d *driver) Type() string { - return networkType -} - -func (d *driver) IsBuiltIn() bool { - return true -} - -// DiscoverNew is a notification for a new discovery event, such as a new node joining a cluster -func (d *driver) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error { - return nil -} - -// DiscoverDelete is a notification for a discovery delete event, such as a node leaving a cluster -func (d *driver) DiscoverDelete(dType discoverapi.DiscoveryType, data interface{}) error { - return nil -} - -func parseEndpointOptions(epOptions map[string]interface{}) (*endpointConfiguration, error) { - if epOptions == nil { - return nil, nil - } - - ec := &endpointConfiguration{} - - if opt, ok := epOptions[netlabel.MacAddress]; ok { - if mac, ok := opt.(net.HardwareAddr); ok { - ec.MacAddress = mac - } else { - return nil, &ErrInvalidEndpointConfig{} - } - } - - return ec, nil -} - -func parseContainerOptions(cOptions map[string]interface{}) (*containerConfiguration, error) { - if cOptions == nil { - return nil, nil - } - genericData := cOptions[netlabel.GenericData] - if genericData == nil { - return nil, nil - } - switch opt := genericData.(type) { - case options.Generic: - opaqueConfig, err := options.GenerateFromModel(opt, &containerConfiguration{}) - if err != nil { - return nil, err - } - return opaqueConfig.(*containerConfiguration), nil - case *containerConfiguration: - return opt, nil - default: - return nil, nil - } -} - -func parseConnectivityOptions(cOptions map[string]interface{}) (*connectivityConfiguration, error) { - if cOptions == nil { - return nil, nil - } - - cc := &connectivityConfiguration{} - - if opt, ok := cOptions[netlabel.PortMap]; ok { - if pb, ok := opt.([]types.PortBinding); ok { - cc.PortBindings = pb - } else { - return nil, types.BadRequestErrorf("Invalid port mapping data in connectivity configuration: %v", opt) - } - } - - if opt, ok := cOptions[netlabel.ExposedPorts]; ok { - if ports, ok := opt.([]types.TransportPort); ok { - cc.ExposedPorts = ports - } else { - return nil, types.BadRequestErrorf("Invalid exposed ports data in connectivity configuration: %v", opt) - } - } - - return cc, nil -} - -func electMacAddress(epConfig *endpointConfiguration, ip net.IP) net.HardwareAddr { - if epConfig != nil && epConfig.MacAddress != nil { - return epConfig.MacAddress - } - return netutils.GenerateMACFromIP(ip) -} diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/bridge_store.go b/vendor/github.com/docker/libnetwork/drivers/bridge/bridge_store.go deleted file mode 100644 index 4e75b3a138..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/bridge/bridge_store.go +++ /dev/null @@ -1,398 +0,0 @@ -package bridge - -import ( - "encoding/json" - "fmt" - "net" - - "github.com/docker/libnetwork/datastore" - "github.com/docker/libnetwork/discoverapi" - "github.com/docker/libnetwork/netlabel" - "github.com/docker/libnetwork/types" - "github.com/sirupsen/logrus" -) - -const ( - // network config prefix was not specific enough. - // To be backward compatible, need custom endpoint - // prefix with different root - bridgePrefix = "bridge" - bridgeEndpointPrefix = "bridge-endpoint" -) - -func (d *driver) initStore(option map[string]interface{}) error { - if data, ok := option[netlabel.LocalKVClient]; ok { - var err error - dsc, ok := data.(discoverapi.DatastoreConfigData) - if !ok { - return types.InternalErrorf("incorrect data in datastore configuration: %v", data) - } - d.store, err = datastore.NewDataStoreFromConfig(dsc) - if err != nil { - return types.InternalErrorf("bridge driver failed to initialize data store: %v", err) - } - - err = d.populateNetworks() - if err != nil { - return err - } - - err = d.populateEndpoints() - if err != nil { - return err - } - } - - return nil -} - -func (d *driver) populateNetworks() error { - kvol, err := d.store.List(datastore.Key(bridgePrefix), &networkConfiguration{}) - if err != nil && err != datastore.ErrKeyNotFound { - return fmt.Errorf("failed to get bridge network configurations from store: %v", err) - } - - // It's normal for network configuration state to be empty. Just return. - if err == datastore.ErrKeyNotFound { - return nil - } - - for _, kvo := range kvol { - ncfg := kvo.(*networkConfiguration) - if err = d.createNetwork(ncfg); err != nil { - logrus.Warnf("could not create bridge network for id %s bridge name %s while booting up from persistent state: %v", ncfg.ID, ncfg.BridgeName, err) - } - logrus.Debugf("Network (%.7s) restored", ncfg.ID) - } - - return nil -} - -func (d *driver) populateEndpoints() error { - kvol, err := d.store.List(datastore.Key(bridgeEndpointPrefix), &bridgeEndpoint{}) - if err != nil && err != datastore.ErrKeyNotFound { - return fmt.Errorf("failed to get bridge endpoints from store: %v", err) - } - - if err == datastore.ErrKeyNotFound { - return nil - } - - for _, kvo := range kvol { - ep := kvo.(*bridgeEndpoint) - n, ok := d.networks[ep.nid] - if !ok { - logrus.Debugf("Network (%.7s) not found for restored bridge endpoint (%.7s)", ep.nid, ep.id) - logrus.Debugf("Deleting stale bridge endpoint (%.7s) from store", ep.id) - if err := d.storeDelete(ep); err != nil { - logrus.Debugf("Failed to delete stale bridge endpoint (%.7s) from store", ep.id) - } - continue - } - n.endpoints[ep.id] = ep - n.restorePortAllocations(ep) - logrus.Debugf("Endpoint (%.7s) restored to network (%.7s)", ep.id, ep.nid) - } - - return nil -} - -func (d *driver) storeUpdate(kvObject datastore.KVObject) error { - if d.store == nil { - logrus.Warnf("bridge store not initialized. kv object %s is not added to the store", datastore.Key(kvObject.Key()...)) - return nil - } - - if err := d.store.PutObjectAtomic(kvObject); err != nil { - return fmt.Errorf("failed to update bridge store for object type %T: %v", kvObject, err) - } - - return nil -} - -func (d *driver) storeDelete(kvObject datastore.KVObject) error { - if d.store == nil { - logrus.Debugf("bridge store not initialized. kv object %s is not deleted from store", datastore.Key(kvObject.Key()...)) - return nil - } - -retry: - if err := d.store.DeleteObjectAtomic(kvObject); err != nil { - if err == datastore.ErrKeyModified { - if err := d.store.GetObject(datastore.Key(kvObject.Key()...), kvObject); err != nil { - return fmt.Errorf("could not update the kvobject to latest when trying to delete: %v", err) - } - goto retry - } - return err - } - - return nil -} - -func (ncfg *networkConfiguration) MarshalJSON() ([]byte, error) { - nMap := make(map[string]interface{}) - nMap["ID"] = ncfg.ID - nMap["BridgeName"] = ncfg.BridgeName - nMap["EnableIPv6"] = ncfg.EnableIPv6 - nMap["EnableIPMasquerade"] = ncfg.EnableIPMasquerade - nMap["EnableICC"] = ncfg.EnableICC - nMap["InhibitIPv4"] = ncfg.InhibitIPv4 - nMap["Mtu"] = ncfg.Mtu - nMap["Internal"] = ncfg.Internal - nMap["DefaultBridge"] = ncfg.DefaultBridge - nMap["DefaultBindingIP"] = ncfg.DefaultBindingIP.String() - nMap["HostIP"] = ncfg.HostIP.String() - nMap["DefaultGatewayIPv4"] = ncfg.DefaultGatewayIPv4.String() - nMap["DefaultGatewayIPv6"] = ncfg.DefaultGatewayIPv6.String() - nMap["ContainerIfacePrefix"] = ncfg.ContainerIfacePrefix - nMap["BridgeIfaceCreator"] = ncfg.BridgeIfaceCreator - - if ncfg.AddressIPv4 != nil { - nMap["AddressIPv4"] = ncfg.AddressIPv4.String() - } - - if ncfg.AddressIPv6 != nil { - nMap["AddressIPv6"] = ncfg.AddressIPv6.String() - } - - return json.Marshal(nMap) -} - -func (ncfg *networkConfiguration) UnmarshalJSON(b []byte) error { - var ( - err error - nMap map[string]interface{} - ) - - if err = json.Unmarshal(b, &nMap); err != nil { - return err - } - - if v, ok := nMap["AddressIPv4"]; ok { - if ncfg.AddressIPv4, err = types.ParseCIDR(v.(string)); err != nil { - return types.InternalErrorf("failed to decode bridge network address IPv4 after json unmarshal: %s", v.(string)) - } - } - - if v, ok := nMap["AddressIPv6"]; ok { - if ncfg.AddressIPv6, err = types.ParseCIDR(v.(string)); err != nil { - return types.InternalErrorf("failed to decode bridge network address IPv6 after json unmarshal: %s", v.(string)) - } - } - - if v, ok := nMap["ContainerIfacePrefix"]; ok { - ncfg.ContainerIfacePrefix = v.(string) - } - - if v, ok := nMap["HostIP"]; ok { - ncfg.HostIP = net.ParseIP(v.(string)) - } - - ncfg.DefaultBridge = nMap["DefaultBridge"].(bool) - ncfg.DefaultBindingIP = net.ParseIP(nMap["DefaultBindingIP"].(string)) - ncfg.DefaultGatewayIPv4 = net.ParseIP(nMap["DefaultGatewayIPv4"].(string)) - ncfg.DefaultGatewayIPv6 = net.ParseIP(nMap["DefaultGatewayIPv6"].(string)) - ncfg.ID = nMap["ID"].(string) - ncfg.BridgeName = nMap["BridgeName"].(string) - ncfg.EnableIPv6 = nMap["EnableIPv6"].(bool) - ncfg.EnableIPMasquerade = nMap["EnableIPMasquerade"].(bool) - ncfg.EnableICC = nMap["EnableICC"].(bool) - if v, ok := nMap["InhibitIPv4"]; ok { - ncfg.InhibitIPv4 = v.(bool) - } - - ncfg.Mtu = int(nMap["Mtu"].(float64)) - if v, ok := nMap["Internal"]; ok { - ncfg.Internal = v.(bool) - } - - if v, ok := nMap["BridgeIfaceCreator"]; ok { - ncfg.BridgeIfaceCreator = ifaceCreator(v.(float64)) - } - - return nil -} - -func (ncfg *networkConfiguration) Key() []string { - return []string{bridgePrefix, ncfg.ID} -} - -func (ncfg *networkConfiguration) KeyPrefix() []string { - return []string{bridgePrefix} -} - -func (ncfg *networkConfiguration) Value() []byte { - b, err := json.Marshal(ncfg) - if err != nil { - return nil - } - return b -} - -func (ncfg *networkConfiguration) SetValue(value []byte) error { - return json.Unmarshal(value, ncfg) -} - -func (ncfg *networkConfiguration) Index() uint64 { - return ncfg.dbIndex -} - -func (ncfg *networkConfiguration) SetIndex(index uint64) { - ncfg.dbIndex = index - ncfg.dbExists = true -} - -func (ncfg *networkConfiguration) Exists() bool { - return ncfg.dbExists -} - -func (ncfg *networkConfiguration) Skip() bool { - return false -} - -func (ncfg *networkConfiguration) New() datastore.KVObject { - return &networkConfiguration{} -} - -func (ncfg *networkConfiguration) CopyTo(o datastore.KVObject) error { - dstNcfg := o.(*networkConfiguration) - *dstNcfg = *ncfg - return nil -} - -func (ncfg *networkConfiguration) DataScope() string { - return datastore.LocalScope -} - -func (ep *bridgeEndpoint) MarshalJSON() ([]byte, error) { - epMap := make(map[string]interface{}) - epMap["id"] = ep.id - epMap["nid"] = ep.nid - epMap["SrcName"] = ep.srcName - epMap["MacAddress"] = ep.macAddress.String() - epMap["Addr"] = ep.addr.String() - if ep.addrv6 != nil { - epMap["Addrv6"] = ep.addrv6.String() - } - epMap["Config"] = ep.config - epMap["ContainerConfig"] = ep.containerConfig - epMap["ExternalConnConfig"] = ep.extConnConfig - epMap["PortMapping"] = ep.portMapping - - return json.Marshal(epMap) -} - -func (ep *bridgeEndpoint) UnmarshalJSON(b []byte) error { - var ( - err error - epMap map[string]interface{} - ) - - if err = json.Unmarshal(b, &epMap); err != nil { - return fmt.Errorf("Failed to unmarshal to bridge endpoint: %v", err) - } - - if v, ok := epMap["MacAddress"]; ok { - if ep.macAddress, err = net.ParseMAC(v.(string)); err != nil { - return types.InternalErrorf("failed to decode bridge endpoint MAC address (%s) after json unmarshal: %v", v.(string), err) - } - } - if v, ok := epMap["Addr"]; ok { - if ep.addr, err = types.ParseCIDR(v.(string)); err != nil { - return types.InternalErrorf("failed to decode bridge endpoint IPv4 address (%s) after json unmarshal: %v", v.(string), err) - } - } - if v, ok := epMap["Addrv6"]; ok { - if ep.addrv6, err = types.ParseCIDR(v.(string)); err != nil { - return types.InternalErrorf("failed to decode bridge endpoint IPv6 address (%s) after json unmarshal: %v", v.(string), err) - } - } - ep.id = epMap["id"].(string) - ep.nid = epMap["nid"].(string) - ep.srcName = epMap["SrcName"].(string) - d, _ := json.Marshal(epMap["Config"]) - if err := json.Unmarshal(d, &ep.config); err != nil { - logrus.Warnf("Failed to decode endpoint config %v", err) - } - d, _ = json.Marshal(epMap["ContainerConfig"]) - if err := json.Unmarshal(d, &ep.containerConfig); err != nil { - logrus.Warnf("Failed to decode endpoint container config %v", err) - } - d, _ = json.Marshal(epMap["ExternalConnConfig"]) - if err := json.Unmarshal(d, &ep.extConnConfig); err != nil { - logrus.Warnf("Failed to decode endpoint external connectivity configuration %v", err) - } - d, _ = json.Marshal(epMap["PortMapping"]) - if err := json.Unmarshal(d, &ep.portMapping); err != nil { - logrus.Warnf("Failed to decode endpoint port mapping %v", err) - } - - return nil -} - -func (ep *bridgeEndpoint) Key() []string { - return []string{bridgeEndpointPrefix, ep.id} -} - -func (ep *bridgeEndpoint) KeyPrefix() []string { - return []string{bridgeEndpointPrefix} -} - -func (ep *bridgeEndpoint) Value() []byte { - b, err := json.Marshal(ep) - if err != nil { - return nil - } - return b -} - -func (ep *bridgeEndpoint) SetValue(value []byte) error { - return json.Unmarshal(value, ep) -} - -func (ep *bridgeEndpoint) Index() uint64 { - return ep.dbIndex -} - -func (ep *bridgeEndpoint) SetIndex(index uint64) { - ep.dbIndex = index - ep.dbExists = true -} - -func (ep *bridgeEndpoint) Exists() bool { - return ep.dbExists -} - -func (ep *bridgeEndpoint) Skip() bool { - return false -} - -func (ep *bridgeEndpoint) New() datastore.KVObject { - return &bridgeEndpoint{} -} - -func (ep *bridgeEndpoint) CopyTo(o datastore.KVObject) error { - dstEp := o.(*bridgeEndpoint) - *dstEp = *ep - return nil -} - -func (ep *bridgeEndpoint) DataScope() string { - return datastore.LocalScope -} - -func (n *bridgeNetwork) restorePortAllocations(ep *bridgeEndpoint) { - if ep.extConnConfig == nil || - ep.extConnConfig.ExposedPorts == nil || - ep.extConnConfig.PortBindings == nil { - return - } - tmp := ep.extConnConfig.PortBindings - ep.extConnConfig.PortBindings = ep.portMapping - _, err := n.allocatePorts(ep, n.config.DefaultBindingIP, n.driver.config.EnableUserlandProxy) - if err != nil { - logrus.Warnf("Failed to reserve existing port mapping for endpoint %.7s:%v", ep.id, err) - } - ep.extConnConfig.PortBindings = tmp -} diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/brmanager/brmanager.go b/vendor/github.com/docker/libnetwork/drivers/bridge/brmanager/brmanager.go deleted file mode 100644 index 74bb95c001..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/bridge/brmanager/brmanager.go +++ /dev/null @@ -1,88 +0,0 @@ -package brmanager - -import ( - "github.com/docker/libnetwork/datastore" - "github.com/docker/libnetwork/discoverapi" - "github.com/docker/libnetwork/driverapi" - "github.com/docker/libnetwork/types" -) - -const networkType = "bridge" - -type driver struct{} - -// Init registers a new instance of bridge manager driver -func Init(dc driverapi.DriverCallback, config map[string]interface{}) error { - c := driverapi.Capability{ - DataScope: datastore.LocalScope, - ConnectivityScope: datastore.LocalScope, - } - return dc.RegisterDriver(networkType, &driver{}, c) -} - -func (d *driver) NetworkAllocate(id string, option map[string]string, ipV4Data, ipV6Data []driverapi.IPAMData) (map[string]string, error) { - return nil, types.NotImplementedErrorf("not implemented") -} - -func (d *driver) NetworkFree(id string) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) CreateNetwork(id string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) EventNotify(etype driverapi.EventType, nid, tableName, key string, value []byte) { -} - -func (d *driver) DecodeTableEntry(tablename string, key string, value []byte) (string, map[string]string) { - return "", nil -} - -func (d *driver) DeleteNetwork(nid string) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo, epOptions map[string]interface{}) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) DeleteEndpoint(nid, eid string) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) EndpointOperInfo(nid, eid string) (map[string]interface{}, error) { - return nil, types.NotImplementedErrorf("not implemented") -} - -func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) Leave(nid, eid string) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) Type() string { - return networkType -} - -func (d *driver) IsBuiltIn() bool { - return true -} - -func (d *driver) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) DiscoverDelete(dType discoverapi.DiscoveryType, data interface{}) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) ProgramExternalConnectivity(nid, eid string, options map[string]interface{}) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) RevokeExternalConnectivity(nid, eid string) error { - return types.NotImplementedErrorf("not implemented") -} diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/errors.go b/vendor/github.com/docker/libnetwork/drivers/bridge/errors.go deleted file mode 100644 index 93960794cb..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/bridge/errors.go +++ /dev/null @@ -1,341 +0,0 @@ -package bridge - -import ( - "fmt" - "net" -) - -// ErrConfigExists error is returned when driver already has a config applied. -type ErrConfigExists struct{} - -func (ece *ErrConfigExists) Error() string { - return "configuration already exists, bridge configuration can be applied only once" -} - -// Forbidden denotes the type of this error -func (ece *ErrConfigExists) Forbidden() {} - -// ErrInvalidDriverConfig error is returned when Bridge Driver is passed an invalid config -type ErrInvalidDriverConfig struct{} - -func (eidc *ErrInvalidDriverConfig) Error() string { - return "Invalid configuration passed to Bridge Driver" -} - -// BadRequest denotes the type of this error -func (eidc *ErrInvalidDriverConfig) BadRequest() {} - -// ErrInvalidNetworkConfig error is returned when a network is created on a driver without valid config. -type ErrInvalidNetworkConfig struct{} - -func (einc *ErrInvalidNetworkConfig) Error() string { - return "trying to create a network on a driver without valid config" -} - -// Forbidden denotes the type of this error -func (einc *ErrInvalidNetworkConfig) Forbidden() {} - -// ErrInvalidContainerConfig error is returned when an endpoint create is attempted with an invalid configuration. -type ErrInvalidContainerConfig struct{} - -func (eicc *ErrInvalidContainerConfig) Error() string { - return "Error in joining a container due to invalid configuration" -} - -// BadRequest denotes the type of this error -func (eicc *ErrInvalidContainerConfig) BadRequest() {} - -// ErrInvalidEndpointConfig error is returned when an endpoint create is attempted with an invalid endpoint configuration. -type ErrInvalidEndpointConfig struct{} - -func (eiec *ErrInvalidEndpointConfig) Error() string { - return "trying to create an endpoint with an invalid endpoint configuration" -} - -// BadRequest denotes the type of this error -func (eiec *ErrInvalidEndpointConfig) BadRequest() {} - -// ErrNetworkExists error is returned when a network already exists and another network is created. -type ErrNetworkExists struct{} - -func (ene *ErrNetworkExists) Error() string { - return "network already exists, bridge can only have one network" -} - -// Forbidden denotes the type of this error -func (ene *ErrNetworkExists) Forbidden() {} - -// ErrIfaceName error is returned when a new name could not be generated. -type ErrIfaceName struct{} - -func (ein *ErrIfaceName) Error() string { - return "failed to find name for new interface" -} - -// InternalError denotes the type of this error -func (ein *ErrIfaceName) InternalError() {} - -// ErrNoIPAddr error is returned when bridge has no IPv4 address configured. -type ErrNoIPAddr struct{} - -func (enip *ErrNoIPAddr) Error() string { - return "bridge has no IPv4 address configured" -} - -// InternalError denotes the type of this error -func (enip *ErrNoIPAddr) InternalError() {} - -// ErrInvalidGateway is returned when the user provided default gateway (v4/v6) is not not valid. -type ErrInvalidGateway struct{} - -func (eig *ErrInvalidGateway) Error() string { - return "default gateway ip must be part of the network" -} - -// BadRequest denotes the type of this error -func (eig *ErrInvalidGateway) BadRequest() {} - -// ErrInvalidContainerSubnet is returned when the container subnet (FixedCIDR) is not valid. -type ErrInvalidContainerSubnet struct{} - -func (eis *ErrInvalidContainerSubnet) Error() string { - return "container subnet must be a subset of bridge network" -} - -// BadRequest denotes the type of this error -func (eis *ErrInvalidContainerSubnet) BadRequest() {} - -// ErrInvalidMtu is returned when the user provided MTU is not valid. -type ErrInvalidMtu int - -func (eim ErrInvalidMtu) Error() string { - return fmt.Sprintf("invalid MTU number: %d", int(eim)) -} - -// BadRequest denotes the type of this error -func (eim ErrInvalidMtu) BadRequest() {} - -// ErrInvalidPort is returned when the container or host port specified in the port binding is not valid. -type ErrInvalidPort string - -func (ip ErrInvalidPort) Error() string { - return fmt.Sprintf("invalid transport port: %s", string(ip)) -} - -// BadRequest denotes the type of this error -func (ip ErrInvalidPort) BadRequest() {} - -// ErrUnsupportedAddressType is returned when the specified address type is not supported. -type ErrUnsupportedAddressType string - -func (uat ErrUnsupportedAddressType) Error() string { - return fmt.Sprintf("unsupported address type: %s", string(uat)) -} - -// BadRequest denotes the type of this error -func (uat ErrUnsupportedAddressType) BadRequest() {} - -// ErrInvalidAddressBinding is returned when the host address specified in the port binding is not valid. -type ErrInvalidAddressBinding string - -func (iab ErrInvalidAddressBinding) Error() string { - return fmt.Sprintf("invalid host address in port binding: %s", string(iab)) -} - -// BadRequest denotes the type of this error -func (iab ErrInvalidAddressBinding) BadRequest() {} - -// ActiveEndpointsError is returned when there are -// still active endpoints in the network being deleted. -type ActiveEndpointsError string - -func (aee ActiveEndpointsError) Error() string { - return fmt.Sprintf("network %s has active endpoint", string(aee)) -} - -// Forbidden denotes the type of this error -func (aee ActiveEndpointsError) Forbidden() {} - -// InvalidNetworkIDError is returned when the passed -// network id for an existing network is not a known id. -type InvalidNetworkIDError string - -func (inie InvalidNetworkIDError) Error() string { - return fmt.Sprintf("invalid network id %s", string(inie)) -} - -// NotFound denotes the type of this error -func (inie InvalidNetworkIDError) NotFound() {} - -// InvalidEndpointIDError is returned when the passed -// endpoint id is not valid. -type InvalidEndpointIDError string - -func (ieie InvalidEndpointIDError) Error() string { - return fmt.Sprintf("invalid endpoint id: %s", string(ieie)) -} - -// BadRequest denotes the type of this error -func (ieie InvalidEndpointIDError) BadRequest() {} - -// InvalidSandboxIDError is returned when the passed -// sandbox id is not valid. -type InvalidSandboxIDError string - -func (isie InvalidSandboxIDError) Error() string { - return fmt.Sprintf("invalid sandbox id: %s", string(isie)) -} - -// BadRequest denotes the type of this error -func (isie InvalidSandboxIDError) BadRequest() {} - -// EndpointNotFoundError is returned when the no endpoint -// with the passed endpoint id is found. -type EndpointNotFoundError string - -func (enfe EndpointNotFoundError) Error() string { - return fmt.Sprintf("endpoint not found: %s", string(enfe)) -} - -// NotFound denotes the type of this error -func (enfe EndpointNotFoundError) NotFound() {} - -// NonDefaultBridgeExistError is returned when a non-default -// bridge config is passed but it does not already exist. -type NonDefaultBridgeExistError string - -func (ndbee NonDefaultBridgeExistError) Error() string { - return fmt.Sprintf("bridge device with non default name %s must be created manually", string(ndbee)) -} - -// Forbidden denotes the type of this error -func (ndbee NonDefaultBridgeExistError) Forbidden() {} - -// NonDefaultBridgeNeedsIPError is returned when a non-default -// bridge config is passed but it has no ip configured -type NonDefaultBridgeNeedsIPError string - -func (ndbee NonDefaultBridgeNeedsIPError) Error() string { - return fmt.Sprintf("bridge device with non default name %s must have a valid IP address", string(ndbee)) -} - -// Forbidden denotes the type of this error -func (ndbee NonDefaultBridgeNeedsIPError) Forbidden() {} - -// FixedCIDRv4Error is returned when fixed-cidrv4 configuration -// failed. -type FixedCIDRv4Error struct { - Net *net.IPNet - Subnet *net.IPNet - Err error -} - -func (fcv4 *FixedCIDRv4Error) Error() string { - return fmt.Sprintf("setup FixedCIDRv4 failed for subnet %s in %s: %v", fcv4.Subnet, fcv4.Net, fcv4.Err) -} - -// InternalError denotes the type of this error -func (fcv4 *FixedCIDRv4Error) InternalError() {} - -// FixedCIDRv6Error is returned when fixed-cidrv6 configuration -// failed. -type FixedCIDRv6Error struct { - Net *net.IPNet - Err error -} - -func (fcv6 *FixedCIDRv6Error) Error() string { - return fmt.Sprintf("setup FixedCIDRv6 failed for subnet %s in %s: %v", fcv6.Net, fcv6.Net, fcv6.Err) -} - -// InternalError denotes the type of this error -func (fcv6 *FixedCIDRv6Error) InternalError() {} - -// IPTableCfgError is returned when an unexpected ip tables configuration is entered -type IPTableCfgError string - -func (name IPTableCfgError) Error() string { - return fmt.Sprintf("unexpected request to set IP tables for interface: %s", string(name)) -} - -// BadRequest denotes the type of this error -func (name IPTableCfgError) BadRequest() {} - -// InvalidIPTablesCfgError is returned when an invalid ip tables configuration is entered -type InvalidIPTablesCfgError string - -func (action InvalidIPTablesCfgError) Error() string { - return fmt.Sprintf("Invalid IPTables action '%s'", string(action)) -} - -// BadRequest denotes the type of this error -func (action InvalidIPTablesCfgError) BadRequest() {} - -// IPv4AddrRangeError is returned when a valid IP address range couldn't be found. -type IPv4AddrRangeError string - -func (name IPv4AddrRangeError) Error() string { - return fmt.Sprintf("can't find an address range for interface %q", string(name)) -} - -// BadRequest denotes the type of this error -func (name IPv4AddrRangeError) BadRequest() {} - -// IPv4AddrAddError is returned when IPv4 address could not be added to the bridge. -type IPv4AddrAddError struct { - IP *net.IPNet - Err error -} - -func (ipv4 *IPv4AddrAddError) Error() string { - return fmt.Sprintf("failed to add IPv4 address %s to bridge: %v", ipv4.IP, ipv4.Err) -} - -// InternalError denotes the type of this error -func (ipv4 *IPv4AddrAddError) InternalError() {} - -// IPv6AddrAddError is returned when IPv6 address could not be added to the bridge. -type IPv6AddrAddError struct { - IP *net.IPNet - Err error -} - -func (ipv6 *IPv6AddrAddError) Error() string { - return fmt.Sprintf("failed to add IPv6 address %s to bridge: %v", ipv6.IP, ipv6.Err) -} - -// InternalError denotes the type of this error -func (ipv6 *IPv6AddrAddError) InternalError() {} - -// IPv4AddrNoMatchError is returned when the bridge's IPv4 address does not match configured. -type IPv4AddrNoMatchError struct { - IP net.IP - CfgIP net.IP -} - -func (ipv4 *IPv4AddrNoMatchError) Error() string { - return fmt.Sprintf("bridge IPv4 (%s) does not match requested configuration %s", ipv4.IP, ipv4.CfgIP) -} - -// BadRequest denotes the type of this error -func (ipv4 *IPv4AddrNoMatchError) BadRequest() {} - -// IPv6AddrNoMatchError is returned when the bridge's IPv6 address does not match configured. -type IPv6AddrNoMatchError net.IPNet - -func (ipv6 *IPv6AddrNoMatchError) Error() string { - return fmt.Sprintf("bridge IPv6 addresses do not match the expected bridge configuration %s", (*net.IPNet)(ipv6).String()) -} - -// BadRequest denotes the type of this error -func (ipv6 *IPv6AddrNoMatchError) BadRequest() {} - -// InvalidLinkIPAddrError is returned when a link is configured to a container with an invalid ip address -type InvalidLinkIPAddrError string - -func (address InvalidLinkIPAddrError) Error() string { - return fmt.Sprintf("Cannot link to a container with Invalid IP Address '%s'", string(address)) -} - -// BadRequest denotes the type of this error -func (address InvalidLinkIPAddrError) BadRequest() {} diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/interface.go b/vendor/github.com/docker/libnetwork/drivers/bridge/interface.go deleted file mode 100644 index c9f3e8dfb7..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/bridge/interface.go +++ /dev/null @@ -1,86 +0,0 @@ -package bridge - -import ( - "fmt" - "net" - - "github.com/sirupsen/logrus" - "github.com/vishvananda/netlink" -) - -const ( - // DefaultBridgeName is the default name for the bridge interface managed - // by the driver when unspecified by the caller. - DefaultBridgeName = "docker0" -) - -// Interface models the bridge network device. -type bridgeInterface struct { - Link netlink.Link - bridgeIPv4 *net.IPNet - bridgeIPv6 *net.IPNet - gatewayIPv4 net.IP - gatewayIPv6 net.IP - nlh *netlink.Handle -} - -// newInterface creates a new bridge interface structure. It attempts to find -// an already existing device identified by the configuration BridgeName field, -// or the default bridge name when unspecified, but doesn't attempt to create -// one when missing -func newInterface(nlh *netlink.Handle, config *networkConfiguration) (*bridgeInterface, error) { - var err error - i := &bridgeInterface{nlh: nlh} - - // Initialize the bridge name to the default if unspecified. - if config.BridgeName == "" { - config.BridgeName = DefaultBridgeName - } - - // Attempt to find an existing bridge named with the specified name. - i.Link, err = nlh.LinkByName(config.BridgeName) - if err != nil { - logrus.Debugf("Did not find any interface with name %s: %v", config.BridgeName, err) - } else if _, ok := i.Link.(*netlink.Bridge); !ok { - return nil, fmt.Errorf("existing interface %s is not a bridge", i.Link.Attrs().Name) - } - return i, nil -} - -// exists indicates if the existing bridge interface exists on the system. -func (i *bridgeInterface) exists() bool { - return i.Link != nil -} - -// addresses returns all IPv4 addresses and all IPv6 addresses for the bridge interface. -func (i *bridgeInterface) addresses() ([]netlink.Addr, []netlink.Addr, error) { - v4addr, err := i.nlh.AddrList(i.Link, netlink.FAMILY_V4) - if err != nil { - return nil, nil, fmt.Errorf("Failed to retrieve V4 addresses: %v", err) - } - - v6addr, err := i.nlh.AddrList(i.Link, netlink.FAMILY_V6) - if err != nil { - return nil, nil, fmt.Errorf("Failed to retrieve V6 addresses: %v", err) - } - - if len(v4addr) == 0 { - return nil, v6addr, nil - } - return v4addr, v6addr, nil -} - -func (i *bridgeInterface) programIPv6Address() error { - _, nlAddressList, err := i.addresses() - if err != nil { - return &IPv6AddrAddError{IP: i.bridgeIPv6, Err: fmt.Errorf("failed to retrieve address list: %v", err)} - } - nlAddr := netlink.Addr{IPNet: i.bridgeIPv6} - if findIPv6Address(nlAddr, nlAddressList) { - return nil - } - if err := i.nlh.AddrAdd(i.Link, &nlAddr); err != nil { - return &IPv6AddrAddError{IP: i.bridgeIPv6, Err: err} - } - return nil -} diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/labels.go b/vendor/github.com/docker/libnetwork/drivers/bridge/labels.go deleted file mode 100644 index b938a75477..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/bridge/labels.go +++ /dev/null @@ -1,21 +0,0 @@ -package bridge - -const ( - // BridgeName label for bridge driver - BridgeName = "com.docker.network.bridge.name" - - // EnableIPMasquerade label for bridge driver - EnableIPMasquerade = "com.docker.network.bridge.enable_ip_masquerade" - - // EnableICC label - EnableICC = "com.docker.network.bridge.enable_icc" - - // InhibitIPv4 label - InhibitIPv4 = "com.docker.network.bridge.inhibit_ipv4" - - // DefaultBindingIP label - DefaultBindingIP = "com.docker.network.bridge.host_binding_ipv4" - - // DefaultBridge label - DefaultBridge = "com.docker.network.bridge.default_bridge" -) diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/link.go b/vendor/github.com/docker/libnetwork/drivers/bridge/link.go deleted file mode 100644 index d364516f1a..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/bridge/link.go +++ /dev/null @@ -1,85 +0,0 @@ -package bridge - -import ( - "fmt" - "net" - - "github.com/docker/libnetwork/iptables" - "github.com/docker/libnetwork/types" - "github.com/sirupsen/logrus" -) - -type link struct { - parentIP string - childIP string - ports []types.TransportPort - bridge string -} - -func (l *link) String() string { - return fmt.Sprintf("%s <-> %s [%v] on %s", l.parentIP, l.childIP, l.ports, l.bridge) -} - -func newLink(parentIP, childIP string, ports []types.TransportPort, bridge string) *link { - return &link{ - childIP: childIP, - parentIP: parentIP, - ports: ports, - bridge: bridge, - } - -} - -func (l *link) Enable() error { - // -A == iptables append flag - linkFunction := func() error { - return linkContainers("-A", l.parentIP, l.childIP, l.ports, l.bridge, false) - } - - iptables.OnReloaded(func() { linkFunction() }) - return linkFunction() -} - -func (l *link) Disable() { - // -D == iptables delete flag - err := linkContainers("-D", l.parentIP, l.childIP, l.ports, l.bridge, true) - if err != nil { - logrus.Errorf("Error removing IPTables rules for a link %s due to %s", l.String(), err.Error()) - } - // Return proper error once we move to use a proper iptables package - // that returns typed errors -} - -func linkContainers(action, parentIP, childIP string, ports []types.TransportPort, bridge string, - ignoreErrors bool) error { - var nfAction iptables.Action - - switch action { - case "-A": - nfAction = iptables.Append - case "-I": - nfAction = iptables.Insert - case "-D": - nfAction = iptables.Delete - default: - return InvalidIPTablesCfgError(action) - } - - ip1 := net.ParseIP(parentIP) - if ip1 == nil { - return InvalidLinkIPAddrError(parentIP) - } - ip2 := net.ParseIP(childIP) - if ip2 == nil { - return InvalidLinkIPAddrError(childIP) - } - - chain := iptables.ChainInfo{Name: DockerChain} - for _, port := range ports { - err := chain.Link(nfAction, ip1, ip2, int(port.Port), port.Proto.String(), bridge) - if !ignoreErrors && err != nil { - return err - } - } - return nil -} diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/netlink_deprecated_linux.go b/vendor/github.com/docker/libnetwork/drivers/bridge/netlink_deprecated_linux.go deleted file mode 100644 index c3cc6ba80a..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/bridge/netlink_deprecated_linux.go +++ /dev/null @@ -1,126 +0,0 @@ -package bridge - -import ( - "fmt" - "math/rand" - "net" - "syscall" - "time" - "unsafe" -) - -const ( - ifNameSize = 16 - ioctlBrAdd = 0x89a0 - ioctlBrAddIf = 0x89a2 -) - -type ifreqIndex struct { - IfrnName [ifNameSize]byte - IfruIndex int32 -} - -type ifreqHwaddr struct { - IfrnName [ifNameSize]byte - IfruHwaddr syscall.RawSockaddr -} - -var rnd = rand.New(rand.NewSource(time.Now().UnixNano())) - -// 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 -} - -func ifIoctBridge(iface, master *net.Interface, op uintptr) error { - if len(master.Name) >= ifNameSize { - return fmt.Errorf("Interface name %s too long", master.Name) - } - - s, err := getIfSocket() - if err != nil { - return err - } - defer syscall.Close(s) - - ifr := ifreqIndex{} - copy(ifr.IfrnName[:len(ifr.IfrnName)-1], master.Name) - ifr.IfruIndex = int32(iface.Index) - - if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(s), op, uintptr(unsafe.Pointer(&ifr))); err != 0 { - return err - } - - return nil -} - -// 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) -} - -func ioctlSetMacAddress(name, addr string) error { - if len(name) >= ifNameSize { - return fmt.Errorf("Interface name %s too long", name) - } - - hw, err := net.ParseMAC(addr) - if err != nil { - return err - } - - s, err := getIfSocket() - if err != nil { - return err - } - defer syscall.Close(s) - - ifr := ifreqHwaddr{} - ifr.IfruHwaddr.Family = syscall.ARPHRD_ETHER - copy(ifr.IfrnName[:len(ifr.IfrnName)-1], name) - - for i := 0; i < 6; i++ { - ifr.IfruHwaddr.Data[i] = ifrDataByte(hw[i]) - } - - if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(s), syscall.SIOCSIFHWADDR, uintptr(unsafe.Pointer(&ifr))); err != 0 { - return err - } - return nil -} - -func ioctlCreateBridge(name, macAddr string) error { - if len(name) >= ifNameSize { - return fmt.Errorf("Interface name %s too long", name) - } - - s, err := getIfSocket() - if err != nil { - return err - } - defer syscall.Close(s) - - nameBytePtr, err := syscall.BytePtrFromString(name) - if err != nil { - return err - } - if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(s), ioctlBrAdd, uintptr(unsafe.Pointer(nameBytePtr))); err != 0 { - return err - } - return ioctlSetMacAddress(name, macAddr) -} diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/netlink_deprecated_linux_rawsockaddr_data_int8.go b/vendor/github.com/docker/libnetwork/drivers/bridge/netlink_deprecated_linux_rawsockaddr_data_int8.go deleted file mode 100644 index 68d368c915..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/bridge/netlink_deprecated_linux_rawsockaddr_data_int8.go +++ /dev/null @@ -1,7 +0,0 @@ -// +build !arm,!ppc64,!ppc64le,!riscv64 - -package bridge - -func ifrDataByte(b byte) int8 { - return int8(b) -} diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/netlink_deprecated_linux_rawsockaddr_data_uint8.go b/vendor/github.com/docker/libnetwork/drivers/bridge/netlink_deprecated_linux_rawsockaddr_data_uint8.go deleted file mode 100644 index a937f5016c..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/bridge/netlink_deprecated_linux_rawsockaddr_data_uint8.go +++ /dev/null @@ -1,7 +0,0 @@ -// +build arm ppc64 ppc64le riscv64 - -package bridge - -func ifrDataByte(b byte) uint8 { - return uint8(b) -} diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/netlink_deprecated_unsupported.go b/vendor/github.com/docker/libnetwork/drivers/bridge/netlink_deprecated_unsupported.go deleted file mode 100644 index 7e2d57b660..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/bridge/netlink_deprecated_unsupported.go +++ /dev/null @@ -1,18 +0,0 @@ -// +build !linux - -package bridge - -import ( - "errors" - "net" -) - -// 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 errors.New("not implemented") -} - -func ioctlCreateBridge(name string, setMacAddr bool) error { - return errors.New("not implemented") -} diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/port_mapping.go b/vendor/github.com/docker/libnetwork/drivers/bridge/port_mapping.go deleted file mode 100644 index 17bf36f9dd..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/bridge/port_mapping.go +++ /dev/null @@ -1,244 +0,0 @@ -package bridge - -import ( - "bytes" - "errors" - "fmt" - "net" - "sync" - - "github.com/docker/libnetwork/types" - "github.com/ishidawataru/sctp" - "github.com/sirupsen/logrus" -) - -func (n *bridgeNetwork) allocatePorts(ep *bridgeEndpoint, reqDefBindIP net.IP, ulPxyEnabled bool) ([]types.PortBinding, error) { - if ep.extConnConfig == nil || ep.extConnConfig.PortBindings == nil { - return nil, nil - } - - defHostIP := net.IPv4zero // 0.0.0.0 - if reqDefBindIP != nil { - defHostIP = reqDefBindIP - } - - var containerIPv6 net.IP - if ep.addrv6 != nil { - containerIPv6 = ep.addrv6.IP - } - - pb, err := n.allocatePortsInternal(ep.extConnConfig.PortBindings, ep.addr.IP, containerIPv6, defHostIP, ulPxyEnabled) - if err != nil { - return nil, err - } - return pb, nil -} - -func (n *bridgeNetwork) allocatePortsInternal(bindings []types.PortBinding, containerIPv4, containerIPv6, defHostIP net.IP, ulPxyEnabled bool) ([]types.PortBinding, error) { - bs := make([]types.PortBinding, 0, len(bindings)) - for _, c := range bindings { - bIPv4 := c.GetCopy() - bIPv6 := c.GetCopy() - // Allocate IPv4 Port mappings - if ok := n.validatePortBindingIPv4(&bIPv4, containerIPv4, defHostIP); ok { - if err := n.allocatePort(&bIPv4, ulPxyEnabled); err != nil { - // On allocation failure, release previously allocated ports. On cleanup error, just log a warning message - if cuErr := n.releasePortsInternal(bs); cuErr != nil { - logrus.Warnf("allocation failure for %v, failed to clear previously allocated ipv4 port bindings: %v", bIPv4, cuErr) - } - return nil, err - } - bs = append(bs, bIPv4) - } - - // skip adding implicit v6 addr, when the kernel was booted with `ipv6.disable=1` - // https://github.com/moby/moby/issues/42288 - isV6Binding := c.HostIP != nil && c.HostIP.To4() == nil - if !isV6Binding && !IsV6Listenable() { - continue - } - - // Allocate IPv6 Port mappings - // If the container has no IPv6 address, allow proxying host IPv6 traffic to it - // by setting up the binding with the IPv4 interface if the userland proxy is enabled - // This change was added to keep backward compatibility - containerIP := containerIPv6 - if ulPxyEnabled && (containerIPv6 == nil) { - containerIP = containerIPv4 - } - if ok := n.validatePortBindingIPv6(&bIPv6, containerIP, defHostIP); ok { - if err := n.allocatePort(&bIPv6, ulPxyEnabled); err != nil { - // On allocation failure, release previously allocated ports. On cleanup error, just log a warning message - if cuErr := n.releasePortsInternal(bs); cuErr != nil { - logrus.Warnf("allocation failure for %v, failed to clear previously allocated ipv6 port bindings: %v", bIPv6, cuErr) - } - return nil, err - } - bs = append(bs, bIPv6) - } - } - return bs, nil -} - -// validatePortBindingIPv4 validates the port binding, populates the missing Host IP field and returns true -// if this is a valid IPv4 binding, else returns false -func (n *bridgeNetwork) validatePortBindingIPv4(bnd *types.PortBinding, containerIPv4, defHostIP net.IP) bool { - //Return early if there is a valid Host IP, but its not a IPv4 address - if len(bnd.HostIP) > 0 && bnd.HostIP.To4() == nil { - return false - } - // Adjust the host address in the operational binding - if len(bnd.HostIP) == 0 { - // Return early if the default binding address is an IPv6 address - if defHostIP.To4() == nil { - return false - } - bnd.HostIP = defHostIP - } - bnd.IP = containerIPv4 - return true - -} - -// validatePortBindingIPv6 validates the port binding, populates the missing Host IP field and returns true -// if this is a valid IPv6 binding, else returns false -func (n *bridgeNetwork) validatePortBindingIPv6(bnd *types.PortBinding, containerIP, defHostIP net.IP) bool { - // Return early if there is no container endpoint - if containerIP == nil { - return false - } - // Return early if there is a valid Host IP, which is a IPv4 address - if len(bnd.HostIP) > 0 && bnd.HostIP.To4() != nil { - return false - } - - // Setup a binding to "::" if Host IP is empty and the default binding IP is 0.0.0.0 - if len(bnd.HostIP) == 0 { - if defHostIP.Equal(net.IPv4zero) { - bnd.HostIP = net.IPv6zero - // If the default binding IP is an IPv6 address, use it - } else if defHostIP.To4() == nil { - bnd.HostIP = defHostIP - // Return false if default binding ip is an IPv4 address - } else { - return false - } - } - bnd.IP = containerIP - return true -} - -func (n *bridgeNetwork) allocatePort(bnd *types.PortBinding, ulPxyEnabled bool) error { - var ( - host net.Addr - err error - ) - - // Adjust HostPortEnd if this is not a range. - if bnd.HostPortEnd == 0 { - bnd.HostPortEnd = bnd.HostPort - } - - // Construct the container side transport address - container, err := bnd.ContainerAddr() - if err != nil { - return err - } - - portmapper := n.portMapper - - if bnd.HostIP.To4() == nil { - portmapper = n.portMapperV6 - } - - // Try up to maxAllocatePortAttempts times to get a port that's not already allocated. - for i := 0; i < maxAllocatePortAttempts; i++ { - if host, err = portmapper.MapRange(container, bnd.HostIP, int(bnd.HostPort), int(bnd.HostPortEnd), ulPxyEnabled); err == nil { - break - } - // There is no point in immediately retrying to map an explicitly chosen port. - if bnd.HostPort != 0 { - logrus.Warnf("Failed to allocate and map port %d-%d: %s", bnd.HostPort, bnd.HostPortEnd, err) - break - } - logrus.Warnf("Failed to allocate and map port: %s, retry: %d", err, i+1) - } - if err != nil { - return err - } - - // Save the host port (regardless it was or not specified in the binding) - switch netAddr := host.(type) { - case *net.TCPAddr: - bnd.HostPort = uint16(host.(*net.TCPAddr).Port) - return nil - case *net.UDPAddr: - bnd.HostPort = uint16(host.(*net.UDPAddr).Port) - return nil - case *sctp.SCTPAddr: - bnd.HostPort = uint16(host.(*sctp.SCTPAddr).Port) - return nil - default: - // For completeness - return ErrUnsupportedAddressType(fmt.Sprintf("%T", netAddr)) - } -} - -func (n *bridgeNetwork) releasePorts(ep *bridgeEndpoint) error { - return n.releasePortsInternal(ep.portMapping) -} - -func (n *bridgeNetwork) releasePortsInternal(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 := n.releasePort(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 -} - -func (n *bridgeNetwork) releasePort(bnd types.PortBinding) error { - // Construct the host side transport address - host, err := bnd.HostAddr() - if err != nil { - return err - } - - portmapper := n.portMapper - - if bnd.HostIP.To4() == nil { - portmapper = n.portMapperV6 - } - - return portmapper.Unmap(host) -} - -var ( - v6ListenableCached bool - v6ListenableOnce sync.Once -) - -// IsV6Listenable returns true when `[::1]:0` is listenable. -// IsV6Listenable returns false mostly when the kernel was booted with `ipv6.disable=1` option. -func IsV6Listenable() bool { - v6ListenableOnce.Do(func() { - ln, err := net.Listen("tcp6", "[::1]:0") - if err != nil { - // When the kernel was booted with `ipv6.disable=1`, - // we get err "listen tcp6 [::1]:0: socket: address family not supported by protocol" - // https://github.com/moby/moby/issues/42288 - logrus.Debugf("port_mapping: v6Listenable=false (%v)", err) - } else { - v6ListenableCached = true - ln.Close() - } - }) - return v6ListenableCached -} diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/setup.go b/vendor/github.com/docker/libnetwork/drivers/bridge/setup.go deleted file mode 100644 index eeb3611b78..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/bridge/setup.go +++ /dev/null @@ -1,26 +0,0 @@ -package bridge - -type setupStep func(*networkConfiguration, *bridgeInterface) error - -type bridgeSetup struct { - config *networkConfiguration - bridge *bridgeInterface - steps []setupStep -} - -func newBridgeSetup(c *networkConfiguration, i *bridgeInterface) *bridgeSetup { - return &bridgeSetup{config: c, bridge: i} -} - -func (b *bridgeSetup) apply() error { - for _, fn := range b.steps { - if err := fn(b.config, b.bridge); err != nil { - return err - } - } - return nil -} - -func (b *bridgeSetup) queueStep(step setupStep) { - b.steps = append(b.steps, step) -} diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/setup_bridgenetfiltering.go b/vendor/github.com/docker/libnetwork/drivers/bridge/setup_bridgenetfiltering.go deleted file mode 100644 index 9b90acfac2..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/bridge/setup_bridgenetfiltering.go +++ /dev/null @@ -1,163 +0,0 @@ -package bridge - -import ( - "errors" - "fmt" - "io/ioutil" - "os" - "syscall" - - "github.com/sirupsen/logrus" -) - -// Enumeration type saying which versions of IP protocol to process. -type ipVersion int - -const ( - ipvnone ipVersion = iota - ipv4 - ipv6 - ipvboth -) - -//Gets the IP version in use ( [ipv4], [ipv6] or [ipv4 and ipv6] ) -func getIPVersion(config *networkConfiguration) ipVersion { - ipVersion := ipv4 - if config.AddressIPv6 != nil || config.EnableIPv6 { - ipVersion |= ipv6 - } - return ipVersion -} - -func setupBridgeNetFiltering(config *networkConfiguration, i *bridgeInterface) error { - err := checkBridgeNetFiltering(config, i) - if err != nil { - if ptherr, ok := err.(*os.PathError); ok { - if errno, ok := ptherr.Err.(syscall.Errno); ok && errno == syscall.ENOENT { - if isRunningInContainer() { - logrus.Warnf("running inside docker container, ignoring missing kernel params: %v", err) - err = nil - } else { - err = errors.New("please ensure that br_netfilter kernel module is loaded") - } - } - } - if err != nil { - return fmt.Errorf("cannot restrict inter-container communication: %v", err) - } - } - return nil -} - -//Enable bridge net filtering if ip forwarding is enabled. See github issue #11404 -func checkBridgeNetFiltering(config *networkConfiguration, i *bridgeInterface) error { - ipVer := getIPVersion(config) - iface := config.BridgeName - doEnable := func(ipVer ipVersion) error { - var ipVerName string - if ipVer == ipv4 { - ipVerName = "IPv4" - } else { - ipVerName = "IPv6" - } - enabled, err := isPacketForwardingEnabled(ipVer, iface) - if err != nil { - logrus.Warnf("failed to check %s forwarding: %v", ipVerName, err) - } else if enabled { - enabled, err := getKernelBoolParam(getBridgeNFKernelParam(ipVer)) - if err != nil || enabled { - return err - } - return setKernelBoolParam(getBridgeNFKernelParam(ipVer), true) - } - return nil - } - - switch ipVer { - case ipv4, ipv6: - return doEnable(ipVer) - case ipvboth: - v4err := doEnable(ipv4) - v6err := doEnable(ipv6) - if v4err == nil { - return v6err - } - return v4err - default: - return nil - } -} - -// Get kernel param path saying whether IPv${ipVer} traffic is being forwarded -// on particular interface. Interface may be specified for IPv6 only. If -// `iface` is empty, `default` will be assumed, which represents default value -// for new interfaces. -func getForwardingKernelParam(ipVer ipVersion, iface string) string { - switch ipVer { - case ipv4: - return "/proc/sys/net/ipv4/ip_forward" - case ipv6: - if iface == "" { - iface = "default" - } - return fmt.Sprintf("/proc/sys/net/ipv6/conf/%s/forwarding", iface) - default: - return "" - } -} - -// Get kernel param path saying whether bridged IPv${ipVer} traffic shall be -// passed to ip${ipVer}tables' chains. -func getBridgeNFKernelParam(ipVer ipVersion) string { - switch ipVer { - case ipv4: - return "/proc/sys/net/bridge/bridge-nf-call-iptables" - case ipv6: - return "/proc/sys/net/bridge/bridge-nf-call-ip6tables" - default: - return "" - } -} - -//Gets the value of the kernel parameters located at the given path -func getKernelBoolParam(path string) (bool, error) { - enabled := false - line, err := ioutil.ReadFile(path) - if err != nil { - return false, err - } - if len(line) > 0 { - enabled = line[0] == '1' - } - return enabled, err -} - -//Sets the value of the kernel parameter located at the given path -func setKernelBoolParam(path string, on bool) error { - value := byte('0') - if on { - value = byte('1') - } - return ioutil.WriteFile(path, []byte{value, '\n'}, 0644) -} - -//Checks to see if packet forwarding is enabled -func isPacketForwardingEnabled(ipVer ipVersion, iface string) (bool, error) { - switch ipVer { - case ipv4, ipv6: - return getKernelBoolParam(getForwardingKernelParam(ipVer, iface)) - case ipvboth: - enabled, err := getKernelBoolParam(getForwardingKernelParam(ipv4, "")) - if err != nil || !enabled { - return enabled, err - } - return getKernelBoolParam(getForwardingKernelParam(ipv6, iface)) - default: - return true, nil - } -} - -func isRunningInContainer() bool { - _, err := os.Stat("/.dockerenv") - return !os.IsNotExist(err) -} diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/setup_device.go b/vendor/github.com/docker/libnetwork/drivers/bridge/setup_device.go deleted file mode 100644 index 338ac60ab0..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/bridge/setup_device.go +++ /dev/null @@ -1,73 +0,0 @@ -package bridge - -import ( - "fmt" - "io/ioutil" - "os" - "path/filepath" - - "github.com/docker/libnetwork/netutils" - "github.com/sirupsen/logrus" - "github.com/vishvananda/netlink" -) - -// SetupDevice create a new bridge interface/ -func setupDevice(config *networkConfiguration, i *bridgeInterface) error { - // We only attempt to create the bridge when the requested device name is - // the default one. - if config.BridgeName != DefaultBridgeName && config.DefaultBridge { - return NonDefaultBridgeExistError(config.BridgeName) - } - - // Set the bridgeInterface netlink.Bridge. - i.Link = &netlink.Bridge{ - LinkAttrs: netlink.LinkAttrs{ - Name: config.BridgeName, - }, - } - - // Set the bridge's MAC address. Requires kernel version 3.3 or up. - hwAddr := netutils.GenerateRandomMAC() - i.Link.Attrs().HardwareAddr = hwAddr - logrus.Debugf("Setting bridge mac address to %s", hwAddr) - - if err := i.nlh.LinkAdd(i.Link); err != nil { - logrus.Debugf("Failed to create bridge %s via netlink. Trying ioctl", config.BridgeName) - return ioctlCreateBridge(config.BridgeName, hwAddr.String()) - } - - return nil -} - -func setupDefaultSysctl(config *networkConfiguration, i *bridgeInterface) error { - // Disable IPv6 router advertisements originating on the bridge - sysPath := filepath.Join("/proc/sys/net/ipv6/conf/", config.BridgeName, "accept_ra") - if _, err := os.Stat(sysPath); err != nil { - logrus. - WithField("bridge", config.BridgeName). - WithField("syspath", sysPath). - Info("failed to read ipv6 net.ipv6.conf..accept_ra") - return nil - } - if err := ioutil.WriteFile(sysPath, []byte{'0', '\n'}, 0644); err != nil { - logrus.WithError(err).Warn("unable to disable IPv6 router advertisement") - } - return nil -} - -// SetupDeviceUp ups the given bridge interface. -func setupDeviceUp(config *networkConfiguration, i *bridgeInterface) error { - err := i.nlh.LinkSetUp(i.Link) - if err != nil { - return fmt.Errorf("Failed to set link up for %s: %v", config.BridgeName, err) - } - - // Attempt to update the bridge interface to refresh the flags status, - // ignoring any failure to do so. - if lnk, err := i.nlh.LinkByName(config.BridgeName); err == nil { - i.Link = lnk - } else { - logrus.Warnf("Failed to retrieve link for interface (%s): %v", config.BridgeName, err) - } - return nil -} diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/setup_firewalld.go b/vendor/github.com/docker/libnetwork/drivers/bridge/setup_firewalld.go deleted file mode 100644 index 82ed712b67..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/bridge/setup_firewalld.go +++ /dev/null @@ -1,35 +0,0 @@ -package bridge - -import "github.com/docker/libnetwork/iptables" - -func (n *bridgeNetwork) setupFirewalld(config *networkConfiguration, i *bridgeInterface) error { - d := n.driver - d.Lock() - driverConfig := d.config - d.Unlock() - - // Sanity check. - if !driverConfig.EnableIPTables { - return IPTableCfgError(config.BridgeName) - } - - iptables.OnReloaded(func() { n.setupIP4Tables(config, i) }) - iptables.OnReloaded(n.portMapper.ReMapAll) - return nil -} - -func (n *bridgeNetwork) setupFirewalld6(config *networkConfiguration, i *bridgeInterface) error { - d := n.driver - d.Lock() - driverConfig := d.config - d.Unlock() - - // Sanity check. - if !driverConfig.EnableIP6Tables { - return IPTableCfgError(config.BridgeName) - } - - iptables.OnReloaded(func() { n.setupIP6Tables(config, i) }) - iptables.OnReloaded(n.portMapperV6.ReMapAll) - return nil -} diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/setup_ip_forwarding.go b/vendor/github.com/docker/libnetwork/drivers/bridge/setup_ip_forwarding.go deleted file mode 100644 index 2c6e080ed1..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/bridge/setup_ip_forwarding.go +++ /dev/null @@ -1,71 +0,0 @@ -package bridge - -import ( - "fmt" - "io/ioutil" - - "github.com/docker/libnetwork/iptables" - "github.com/sirupsen/logrus" -) - -const ( - ipv4ForwardConf = "/proc/sys/net/ipv4/ip_forward" - ipv4ForwardConfPerm = 0644 -) - -func configureIPForwarding(enable bool) error { - var val byte - if enable { - val = '1' - } - return ioutil.WriteFile(ipv4ForwardConf, []byte{val, '\n'}, ipv4ForwardConfPerm) -} - -func setupIPForwarding(enableIPTables bool, enableIP6Tables bool) error { - // Get current IPv4 forward setup - ipv4ForwardData, err := ioutil.ReadFile(ipv4ForwardConf) - if err != nil { - return fmt.Errorf("Cannot read IP forwarding setup: %v", err) - } - - // Enable IPv4 forwarding only if it is not already enabled - if ipv4ForwardData[0] != '1' { - // Enable IPv4 forwarding - if err := configureIPForwarding(true); err != nil { - return fmt.Errorf("Enabling IP forwarding failed: %v", err) - } - // When enabling ip_forward set the default policy on forward chain to - // drop only if the daemon option iptables is not set to false. - if enableIPTables { - iptable := iptables.GetIptable(iptables.IPv4) - if err := iptable.SetDefaultPolicy(iptables.Filter, "FORWARD", iptables.Drop); err != nil { - if err := configureIPForwarding(false); err != nil { - logrus.Errorf("Disabling IP forwarding failed, %v", err) - } - return err - } - iptables.OnReloaded(func() { - logrus.Debug("Setting the default DROP policy on firewall reload") - if err := iptable.SetDefaultPolicy(iptables.Filter, "FORWARD", iptables.Drop); err != nil { - logrus.Warnf("Setting the default DROP policy on firewall reload failed, %v", err) - } - }) - } - } - - // add only iptables rules - forwarding is handled by setupIPv6Forwarding in setup_ipv6 - if enableIP6Tables { - iptable := iptables.GetIptable(iptables.IPv6) - if err := iptable.SetDefaultPolicy(iptables.Filter, "FORWARD", iptables.Drop); err != nil { - logrus.Warnf("Setting the default DROP policy on firewall reload failed, %v", err) - } - iptables.OnReloaded(func() { - logrus.Debug("Setting the default DROP policy on firewall reload") - if err := iptable.SetDefaultPolicy(iptables.Filter, "FORWARD", iptables.Drop); err != nil { - logrus.Warnf("Setting the default DROP policy on firewall reload failed, %v", err) - } - }) - } - - return nil -} diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/setup_ip_tables.go b/vendor/github.com/docker/libnetwork/drivers/bridge/setup_ip_tables.go deleted file mode 100644 index 1d20ecbe13..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/bridge/setup_ip_tables.go +++ /dev/null @@ -1,429 +0,0 @@ -package bridge - -import ( - "errors" - "fmt" - "net" - - "github.com/docker/libnetwork/iptables" - "github.com/sirupsen/logrus" - "github.com/vishvananda/netlink" -) - -// DockerChain: DOCKER iptable chain name -const ( - DockerChain = "DOCKER" - // Isolation between bridge networks is achieved in two stages by means - // of the following two chains in the filter table. The first chain matches - // on the source interface being a bridge network's bridge and the - // destination being a different interface. A positive match leads to the - // second isolation chain. No match returns to the parent chain. The second - // isolation chain matches on destination interface being a bridge network's - // bridge. A positive match identifies a packet originated from one bridge - // network's bridge destined to another bridge network's bridge and will - // result in the packet being dropped. No match returns to the parent chain. - IsolationChain1 = "DOCKER-ISOLATION-STAGE-1" - IsolationChain2 = "DOCKER-ISOLATION-STAGE-2" -) - -func setupIPChains(config *configuration, version iptables.IPVersion) (*iptables.ChainInfo, *iptables.ChainInfo, *iptables.ChainInfo, *iptables.ChainInfo, error) { - // Sanity check. - if config.EnableIPTables == false { - return nil, nil, nil, nil, errors.New("cannot create new chains, EnableIPTable is disabled") - } - - hairpinMode := !config.EnableUserlandProxy - - iptable := iptables.GetIptable(version) - - natChain, err := iptable.NewChain(DockerChain, iptables.Nat, hairpinMode) - if err != nil { - return nil, nil, nil, nil, fmt.Errorf("failed to create NAT chain %s: %v", DockerChain, err) - } - defer func() { - if err != nil { - if err := iptable.RemoveExistingChain(DockerChain, iptables.Nat); err != nil { - logrus.Warnf("failed on removing iptables NAT chain %s on cleanup: %v", DockerChain, err) - } - } - }() - - filterChain, err := iptable.NewChain(DockerChain, iptables.Filter, false) - if err != nil { - return nil, nil, nil, nil, fmt.Errorf("failed to create FILTER chain %s: %v", DockerChain, err) - } - defer func() { - if err != nil { - if err := iptable.RemoveExistingChain(DockerChain, iptables.Filter); err != nil { - logrus.Warnf("failed on removing iptables FILTER chain %s on cleanup: %v", DockerChain, err) - } - } - }() - - isolationChain1, err := iptable.NewChain(IsolationChain1, iptables.Filter, false) - if err != nil { - return nil, nil, nil, nil, fmt.Errorf("failed to create FILTER isolation chain: %v", err) - } - defer func() { - if err != nil { - if err := iptable.RemoveExistingChain(IsolationChain1, iptables.Filter); err != nil { - logrus.Warnf("failed on removing iptables FILTER chain %s on cleanup: %v", IsolationChain1, err) - } - } - }() - - isolationChain2, err := iptable.NewChain(IsolationChain2, iptables.Filter, false) - if err != nil { - return nil, nil, nil, nil, fmt.Errorf("failed to create FILTER isolation chain: %v", err) - } - defer func() { - if err != nil { - if err := iptable.RemoveExistingChain(IsolationChain2, iptables.Filter); err != nil { - logrus.Warnf("failed on removing iptables FILTER chain %s on cleanup: %v", IsolationChain2, err) - } - } - }() - - if err := iptable.AddReturnRule(IsolationChain1); err != nil { - return nil, nil, nil, nil, err - } - - if err := iptable.AddReturnRule(IsolationChain2); err != nil { - return nil, nil, nil, nil, err - } - - return natChain, filterChain, isolationChain1, isolationChain2, nil -} - -func (n *bridgeNetwork) setupIP4Tables(config *networkConfiguration, i *bridgeInterface) error { - d := n.driver - d.Lock() - driverConfig := d.config - d.Unlock() - - // Sanity check. - if !driverConfig.EnableIPTables { - return errors.New("Cannot program chains, EnableIPTable is disabled") - } - - maskedAddrv4 := &net.IPNet{ - IP: i.bridgeIPv4.IP.Mask(i.bridgeIPv4.Mask), - Mask: i.bridgeIPv4.Mask, - } - return n.setupIPTables(iptables.IPv4, maskedAddrv4, config, i) -} - -func (n *bridgeNetwork) setupIP6Tables(config *networkConfiguration, i *bridgeInterface) error { - d := n.driver - d.Lock() - driverConfig := d.config - d.Unlock() - - // Sanity check. - if !driverConfig.EnableIP6Tables { - return errors.New("Cannot program chains, EnableIP6Tables is disabled") - } - - maskedAddrv6 := &net.IPNet{ - IP: i.bridgeIPv6.IP.Mask(i.bridgeIPv6.Mask), - Mask: i.bridgeIPv6.Mask, - } - - return n.setupIPTables(iptables.IPv6, maskedAddrv6, config, i) -} - -func (n *bridgeNetwork) setupIPTables(ipVersion iptables.IPVersion, maskedAddr *net.IPNet, config *networkConfiguration, i *bridgeInterface) error { - var err error - - d := n.driver - d.Lock() - driverConfig := d.config - d.Unlock() - - // Pickup this configuration option from driver - hairpinMode := !driverConfig.EnableUserlandProxy - - iptable := iptables.GetIptable(ipVersion) - - if config.Internal { - if err = setupInternalNetworkRules(config.BridgeName, maskedAddr, config.EnableICC, true); err != nil { - return fmt.Errorf("Failed to Setup IP tables: %s", err.Error()) - } - n.registerIptCleanFunc(func() error { - return setupInternalNetworkRules(config.BridgeName, maskedAddr, config.EnableICC, false) - }) - } else { - if err = setupIPTablesInternal(config.HostIP, config.BridgeName, maskedAddr, config.EnableICC, config.EnableIPMasquerade, hairpinMode, true); err != nil { - return fmt.Errorf("Failed to Setup IP tables: %s", err.Error()) - } - n.registerIptCleanFunc(func() error { - return setupIPTablesInternal(config.HostIP, config.BridgeName, maskedAddr, config.EnableICC, config.EnableIPMasquerade, hairpinMode, false) - }) - natChain, filterChain, _, _, err := n.getDriverChains(ipVersion) - if err != nil { - return fmt.Errorf("Failed to setup IP tables, cannot acquire chain info %s", err.Error()) - } - - err = iptable.ProgramChain(natChain, config.BridgeName, hairpinMode, true) - if err != nil { - return fmt.Errorf("Failed to program NAT chain: %s", err.Error()) - } - - err = iptable.ProgramChain(filterChain, config.BridgeName, hairpinMode, true) - if err != nil { - return fmt.Errorf("Failed to program FILTER chain: %s", err.Error()) - } - - n.registerIptCleanFunc(func() error { - return iptable.ProgramChain(filterChain, config.BridgeName, hairpinMode, false) - }) - - if ipVersion == iptables.IPv4 { - n.portMapper.SetIptablesChain(natChain, n.getNetworkBridgeName()) - } else { - n.portMapperV6.SetIptablesChain(natChain, n.getNetworkBridgeName()) - } - } - - d.Lock() - err = iptable.EnsureJumpRule("FORWARD", IsolationChain1) - d.Unlock() - return err -} - -type iptRule struct { - table iptables.Table - chain string - preArgs []string - args []string -} - -func setupIPTablesInternal(hostIP net.IP, bridgeIface string, addr *net.IPNet, icc, ipmasq, hairpin, enable bool) error { - - var ( - address = addr.String() - skipDNAT = iptRule{table: iptables.Nat, chain: DockerChain, preArgs: []string{"-t", "nat"}, args: []string{"-i", bridgeIface, "-j", "RETURN"}} - outRule = iptRule{table: iptables.Filter, chain: "FORWARD", args: []string{"-i", bridgeIface, "!", "-o", bridgeIface, "-j", "ACCEPT"}} - natArgs []string - hpNatArgs []string - ) - // if hostIP is set use this address as the src-ip during SNAT - if hostIP != nil { - hostAddr := hostIP.String() - natArgs = []string{"-s", address, "!", "-o", bridgeIface, "-j", "SNAT", "--to-source", hostAddr} - hpNatArgs = []string{"-m", "addrtype", "--src-type", "LOCAL", "-o", bridgeIface, "-j", "SNAT", "--to-source", hostAddr} - // Else use MASQUERADE which picks the src-ip based on NH from the route table - } else { - natArgs = []string{"-s", address, "!", "-o", bridgeIface, "-j", "MASQUERADE"} - hpNatArgs = []string{"-m", "addrtype", "--src-type", "LOCAL", "-o", bridgeIface, "-j", "MASQUERADE"} - } - - natRule := iptRule{table: iptables.Nat, chain: "POSTROUTING", preArgs: []string{"-t", "nat"}, args: natArgs} - hpNatRule := iptRule{table: iptables.Nat, chain: "POSTROUTING", preArgs: []string{"-t", "nat"}, args: hpNatArgs} - - ipVersion := iptables.IPv4 - - if addr.IP.To4() == nil { - ipVersion = iptables.IPv6 - } - - // Set NAT. - if ipmasq { - if err := programChainRule(ipVersion, natRule, "NAT", enable); err != nil { - return err - } - } - - if ipmasq && !hairpin { - if err := programChainRule(ipVersion, skipDNAT, "SKIP DNAT", enable); err != nil { - return err - } - } - - // In hairpin mode, masquerade traffic from localhost - if hairpin { - if err := programChainRule(ipVersion, hpNatRule, "MASQ LOCAL HOST", enable); err != nil { - return err - } - } - - // Set Inter Container Communication. - if err := setIcc(ipVersion, bridgeIface, icc, enable); err != nil { - return err - } - - // Set Accept on all non-intercontainer outgoing packets. - return programChainRule(ipVersion, outRule, "ACCEPT NON_ICC OUTGOING", enable) -} - -func programChainRule(version iptables.IPVersion, rule iptRule, ruleDescr string, insert bool) error { - - iptable := iptables.GetIptable(version) - - var ( - prefix []string - operation string - condition bool - doesExist = iptable.Exists(rule.table, rule.chain, rule.args...) - ) - - if insert { - condition = !doesExist - prefix = []string{"-I", rule.chain} - operation = "enable" - } else { - condition = doesExist - prefix = []string{"-D", rule.chain} - operation = "disable" - } - if rule.preArgs != nil { - prefix = append(rule.preArgs, prefix...) - } - - if condition { - if err := iptable.RawCombinedOutput(append(prefix, rule.args...)...); err != nil { - return fmt.Errorf("Unable to %s %s rule: %s", operation, ruleDescr, err.Error()) - } - } - - return nil -} - -func setIcc(version iptables.IPVersion, bridgeIface string, iccEnable, insert bool) error { - iptable := iptables.GetIptable(version) - var ( - table = iptables.Filter - chain = "FORWARD" - args = []string{"-i", bridgeIface, "-o", bridgeIface, "-j"} - acceptArgs = append(args, "ACCEPT") - dropArgs = append(args, "DROP") - ) - - if insert { - if !iccEnable { - iptable.Raw(append([]string{"-D", chain}, acceptArgs...)...) - - if !iptable.Exists(table, chain, dropArgs...) { - if err := iptable.RawCombinedOutput(append([]string{"-A", chain}, dropArgs...)...); err != nil { - return fmt.Errorf("Unable to prevent intercontainer communication: %s", err.Error()) - } - } - } else { - iptable.Raw(append([]string{"-D", chain}, dropArgs...)...) - - if !iptable.Exists(table, chain, acceptArgs...) { - if err := iptable.RawCombinedOutput(append([]string{"-I", chain}, acceptArgs...)...); err != nil { - return fmt.Errorf("Unable to allow intercontainer communication: %s", err.Error()) - } - } - } - } else { - // Remove any ICC rule. - if !iccEnable { - if iptable.Exists(table, chain, dropArgs...) { - iptable.Raw(append([]string{"-D", chain}, dropArgs...)...) - } - } else { - if iptable.Exists(table, chain, acceptArgs...) { - iptable.Raw(append([]string{"-D", chain}, acceptArgs...)...) - } - } - } - - return nil -} - -// Control Inter Network Communication. Install[Remove] only if it is [not] present. -func setINC(version iptables.IPVersion, iface string, enable bool) error { - iptable := iptables.GetIptable(version) - var ( - action = iptables.Insert - actionMsg = "add" - chains = []string{IsolationChain1, IsolationChain2} - rules = [][]string{ - {"-i", iface, "!", "-o", iface, "-j", IsolationChain2}, - {"-o", iface, "-j", "DROP"}, - } - ) - - if !enable { - action = iptables.Delete - actionMsg = "remove" - } - - for i, chain := range chains { - if err := iptable.ProgramRule(iptables.Filter, chain, action, rules[i]); err != nil { - msg := fmt.Sprintf("unable to %s inter-network communication rule: %v", actionMsg, err) - if enable { - if i == 1 { - // Rollback the rule installed on first chain - if err2 := iptable.ProgramRule(iptables.Filter, chains[0], iptables.Delete, rules[0]); err2 != nil { - logrus.Warnf("Failed to rollback iptables rule after failure (%v): %v", err, err2) - } - } - return fmt.Errorf(msg) - } - logrus.Warn(msg) - } - } - - return nil -} - -// Obsolete chain from previous docker versions -const oldIsolationChain = "DOCKER-ISOLATION" - -func removeIPChains(version iptables.IPVersion) { - ipt := iptables.IPTable{Version: version} - - // Remove obsolete rules from default chains - ipt.ProgramRule(iptables.Filter, "FORWARD", iptables.Delete, []string{"-j", oldIsolationChain}) - - // Remove chains - for _, chainInfo := range []iptables.ChainInfo{ - {Name: DockerChain, Table: iptables.Nat, IPTable: ipt}, - {Name: DockerChain, Table: iptables.Filter, IPTable: ipt}, - {Name: IsolationChain1, Table: iptables.Filter, IPTable: ipt}, - {Name: IsolationChain2, Table: iptables.Filter, IPTable: ipt}, - {Name: oldIsolationChain, Table: iptables.Filter, IPTable: ipt}, - } { - - if err := chainInfo.Remove(); err != nil { - logrus.Warnf("Failed to remove existing iptables entries in table %s chain %s : %v", chainInfo.Table, chainInfo.Name, err) - } - } -} - -func setupInternalNetworkRules(bridgeIface string, addr *net.IPNet, icc, insert bool) error { - var ( - inDropRule = iptRule{table: iptables.Filter, chain: IsolationChain1, args: []string{"-i", bridgeIface, "!", "-d", addr.String(), "-j", "DROP"}} - outDropRule = iptRule{table: iptables.Filter, chain: IsolationChain1, args: []string{"-o", bridgeIface, "!", "-s", addr.String(), "-j", "DROP"}} - ) - - version := iptables.IPv4 - - if addr.IP.To4() == nil { - version = iptables.IPv6 - } - - if err := programChainRule(version, inDropRule, "DROP INCOMING", insert); err != nil { - return err - } - if err := programChainRule(version, outDropRule, "DROP OUTGOING", insert); err != nil { - return err - } - // Set Inter Container Communication. - return setIcc(version, bridgeIface, icc, insert) -} - -func clearEndpointConnections(nlh *netlink.Handle, ep *bridgeEndpoint) { - var ipv4List []net.IP - var ipv6List []net.IP - if ep.addr != nil { - ipv4List = append(ipv4List, ep.addr.IP) - } - if ep.addrv6 != nil { - ipv6List = append(ipv6List, ep.addrv6.IP) - } - iptables.DeleteConntrackEntries(nlh, ipv4List, ipv6List) -} diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/setup_ipv4.go b/vendor/github.com/docker/libnetwork/drivers/bridge/setup_ipv4.go deleted file mode 100644 index e4e47a1af1..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/bridge/setup_ipv4.go +++ /dev/null @@ -1,82 +0,0 @@ -package bridge - -import ( - "errors" - "fmt" - "io/ioutil" - "net" - "path/filepath" - - "github.com/docker/libnetwork/types" - "github.com/sirupsen/logrus" - "github.com/vishvananda/netlink" -) - -func selectIPv4Address(addresses []netlink.Addr, selector *net.IPNet) (netlink.Addr, error) { - if len(addresses) == 0 { - return netlink.Addr{}, errors.New("unable to select an address as the address pool is empty") - } - if selector != nil { - for _, addr := range addresses { - if selector.Contains(addr.IP) { - return addr, nil - } - } - } - return addresses[0], nil -} - -func setupBridgeIPv4(config *networkConfiguration, i *bridgeInterface) error { - if !config.InhibitIPv4 { - addrv4List, _, err := i.addresses() - if err != nil { - return fmt.Errorf("failed to retrieve bridge interface addresses: %v", err) - } - - addrv4, _ := selectIPv4Address(addrv4List, config.AddressIPv4) - - if !types.CompareIPNet(addrv4.IPNet, config.AddressIPv4) { - if addrv4.IPNet != nil { - if err := i.nlh.AddrDel(i.Link, &addrv4); err != nil { - return fmt.Errorf("failed to remove current ip address from bridge: %v", err) - } - } - logrus.Debugf("Assigning address to bridge interface %s: %s", config.BridgeName, config.AddressIPv4) - if err := i.nlh.AddrAdd(i.Link, &netlink.Addr{IPNet: config.AddressIPv4}); err != nil { - return &IPv4AddrAddError{IP: config.AddressIPv4, Err: err} - } - } - } - - // Store bridge network and default gateway - i.bridgeIPv4 = config.AddressIPv4 - i.gatewayIPv4 = config.AddressIPv4.IP - - return nil -} - -func setupGatewayIPv4(config *networkConfiguration, i *bridgeInterface) error { - if !i.bridgeIPv4.Contains(config.DefaultGatewayIPv4) { - return &ErrInvalidGateway{} - } - - // Store requested default gateway - i.gatewayIPv4 = config.DefaultGatewayIPv4 - - return nil -} - -func setupLoopbackAddressesRouting(config *networkConfiguration, i *bridgeInterface) error { - sysPath := filepath.Join("/proc/sys/net/ipv4/conf", config.BridgeName, "route_localnet") - ipv4LoRoutingData, err := ioutil.ReadFile(sysPath) - if err != nil { - return fmt.Errorf("Cannot read IPv4 local routing setup: %v", err) - } - // Enable loopback addresses routing only if it isn't already enabled - if ipv4LoRoutingData[0] != '1' { - if err := ioutil.WriteFile(sysPath, []byte{'1', '\n'}, 0644); err != nil { - return fmt.Errorf("Unable to enable local routing for hairpin mode: %v", err) - } - } - return nil -} diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/setup_ipv6.go b/vendor/github.com/docker/libnetwork/drivers/bridge/setup_ipv6.go deleted file mode 100644 index 28fa824944..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/bridge/setup_ipv6.go +++ /dev/null @@ -1,119 +0,0 @@ -package bridge - -import ( - "fmt" - "io/ioutil" - "net" - "os" - - "github.com/docker/libnetwork/types" - "github.com/sirupsen/logrus" - "github.com/vishvananda/netlink" -) - -var bridgeIPv6 *net.IPNet - -const ( - bridgeIPv6Str = "fe80::1/64" - ipv6ForwardConfPerm = 0644 - ipv6ForwardConfDefault = "/proc/sys/net/ipv6/conf/default/forwarding" - ipv6ForwardConfAll = "/proc/sys/net/ipv6/conf/all/forwarding" -) - -func init() { - // We allow ourselves to panic in this special case because we indicate a - // failure to parse a compile-time define constant. - var err error - if bridgeIPv6, err = types.ParseCIDR(bridgeIPv6Str); err != nil { - panic(fmt.Sprintf("Cannot parse default bridge IPv6 address %q: %v", bridgeIPv6Str, err)) - } -} - -func setupBridgeIPv6(config *networkConfiguration, i *bridgeInterface) error { - procFile := "/proc/sys/net/ipv6/conf/" + config.BridgeName + "/disable_ipv6" - ipv6BridgeData, err := ioutil.ReadFile(procFile) - if err != nil { - return fmt.Errorf("Cannot read IPv6 setup for bridge %v: %v", config.BridgeName, err) - } - // Enable IPv6 on the bridge only if it isn't already enabled - if ipv6BridgeData[0] != '0' { - if err := ioutil.WriteFile(procFile, []byte{'0', '\n'}, ipv6ForwardConfPerm); err != nil { - return fmt.Errorf("Unable to enable IPv6 addresses on bridge: %v", err) - } - } - - // Store bridge network and default gateway - i.bridgeIPv6 = bridgeIPv6 - i.gatewayIPv6 = i.bridgeIPv6.IP - - if err := i.programIPv6Address(); err != nil { - return err - } - - if config.AddressIPv6 == nil { - return nil - } - - // Store the user specified bridge network and network gateway and program it - i.bridgeIPv6 = config.AddressIPv6 - i.gatewayIPv6 = config.AddressIPv6.IP - - if err := i.programIPv6Address(); err != nil { - return err - } - - // Setting route to global IPv6 subnet - logrus.Debugf("Adding route to IPv6 network %s via device %s", config.AddressIPv6.String(), config.BridgeName) - err = i.nlh.RouteAdd(&netlink.Route{ - Scope: netlink.SCOPE_UNIVERSE, - LinkIndex: i.Link.Attrs().Index, - Dst: config.AddressIPv6, - }) - if err != nil && !os.IsExist(err) { - logrus.Errorf("Could not add route to IPv6 network %s via device %s: %s", config.AddressIPv6.String(), config.BridgeName, err) - } - - return nil -} - -func setupGatewayIPv6(config *networkConfiguration, i *bridgeInterface) error { - if config.AddressIPv6 == nil { - return &ErrInvalidContainerSubnet{} - } - if !config.AddressIPv6.Contains(config.DefaultGatewayIPv6) { - return &ErrInvalidGateway{} - } - - // Store requested default gateway - i.gatewayIPv6 = config.DefaultGatewayIPv6 - - return nil -} - -func setupIPv6Forwarding(config *networkConfiguration, i *bridgeInterface) error { - // Get current IPv6 default forwarding setup - ipv6ForwardDataDefault, err := ioutil.ReadFile(ipv6ForwardConfDefault) - if err != nil { - return fmt.Errorf("Cannot read IPv6 default forwarding setup: %v", err) - } - // Enable IPv6 default forwarding only if it is not already enabled - if ipv6ForwardDataDefault[0] != '1' { - if err := ioutil.WriteFile(ipv6ForwardConfDefault, []byte{'1', '\n'}, ipv6ForwardConfPerm); err != nil { - logrus.Warnf("Unable to enable IPv6 default forwarding: %v", err) - } - } - - // Get current IPv6 all forwarding setup - ipv6ForwardDataAll, err := ioutil.ReadFile(ipv6ForwardConfAll) - if err != nil { - return fmt.Errorf("Cannot read IPv6 all forwarding setup: %v", err) - } - // Enable IPv6 all forwarding only if it is not already enabled - if ipv6ForwardDataAll[0] != '1' { - if err := ioutil.WriteFile(ipv6ForwardConfAll, []byte{'1', '\n'}, ipv6ForwardConfPerm); err != nil { - logrus.Warnf("Unable to enable IPv6 all forwarding: %v", err) - } - } - - return nil -} diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/setup_verify.go b/vendor/github.com/docker/libnetwork/drivers/bridge/setup_verify.go deleted file mode 100644 index de77c38a66..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/bridge/setup_verify.go +++ /dev/null @@ -1,73 +0,0 @@ -package bridge - -import ( - "fmt" - "strings" - - "github.com/docker/libnetwork/ns" - "github.com/docker/libnetwork/types" - "github.com/sirupsen/logrus" - "github.com/vishvananda/netlink" -) - -func setupVerifyAndReconcile(config *networkConfiguration, i *bridgeInterface) error { - // Fetch a slice of IPv4 addresses and a slice of IPv6 addresses from the bridge. - addrsv4, addrsv6, err := i.addresses() - if err != nil { - return fmt.Errorf("Failed to verify ip addresses: %v", err) - } - - addrv4, _ := selectIPv4Address(addrsv4, config.AddressIPv4) - - // Verify that the bridge does have an IPv4 address. - if addrv4.IPNet == nil { - return &ErrNoIPAddr{} - } - - // Verify that the bridge IPv4 address matches the requested configuration. - if config.AddressIPv4 != nil && !addrv4.IP.Equal(config.AddressIPv4.IP) { - return &IPv4AddrNoMatchError{IP: addrv4.IP, CfgIP: config.AddressIPv4.IP} - } - - // Verify that one of the bridge IPv6 addresses matches the requested - // configuration. - if config.EnableIPv6 && !findIPv6Address(netlink.Addr{IPNet: bridgeIPv6}, addrsv6) { - return (*IPv6AddrNoMatchError)(bridgeIPv6) - } - - // Release any residual IPv6 address that might be there because of older daemon instances - for _, addrv6 := range addrsv6 { - if addrv6.IP.IsGlobalUnicast() && !types.CompareIPNet(addrv6.IPNet, i.bridgeIPv6) { - if err := i.nlh.AddrDel(i.Link, &addrv6); err != nil { - logrus.Warnf("Failed to remove residual IPv6 address %s from bridge: %v", addrv6.IPNet, err) - } - } - } - - return nil -} - -func findIPv6Address(addr netlink.Addr, addresses []netlink.Addr) bool { - for _, addrv6 := range addresses { - if addrv6.String() == addr.String() { - return true - } - } - return false -} - -func bridgeInterfaceExists(name string) (bool, error) { - nlh := ns.NlHandle() - link, err := nlh.LinkByName(name) - if err != nil { - if strings.Contains(err.Error(), "Link not found") { - return false, nil - } - return false, fmt.Errorf("failed to check bridge interface existence: %v", err) - } - - if link.Type() == "bridge" { - return true, nil - } - return false, fmt.Errorf("existing interface %s is not a bridge", name) -} diff --git a/vendor/github.com/docker/libnetwork/drivers/host/host.go b/vendor/github.com/docker/libnetwork/drivers/host/host.go deleted file mode 100644 index a71d461380..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/host/host.go +++ /dev/null @@ -1,106 +0,0 @@ -package host - -import ( - "sync" - - "github.com/docker/libnetwork/datastore" - "github.com/docker/libnetwork/discoverapi" - "github.com/docker/libnetwork/driverapi" - "github.com/docker/libnetwork/types" -) - -const networkType = "host" - -type driver struct { - network string - sync.Mutex -} - -// Init registers a new instance of host driver -func Init(dc driverapi.DriverCallback, config map[string]interface{}) error { - c := driverapi.Capability{ - DataScope: datastore.LocalScope, - ConnectivityScope: datastore.LocalScope, - } - return dc.RegisterDriver(networkType, &driver{}, c) -} - -func (d *driver) NetworkAllocate(id string, option map[string]string, ipV4Data, ipV6Data []driverapi.IPAMData) (map[string]string, error) { - return nil, types.NotImplementedErrorf("not implemented") -} - -func (d *driver) NetworkFree(id string) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) EventNotify(etype driverapi.EventType, nid, tableName, key string, value []byte) { -} - -func (d *driver) DecodeTableEntry(tablename string, key string, value []byte) (string, map[string]string) { - return "", nil -} - -func (d *driver) CreateNetwork(id string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error { - d.Lock() - defer d.Unlock() - - if d.network != "" { - return types.ForbiddenErrorf("only one instance of \"%s\" network is allowed", networkType) - } - - d.network = id - - return nil -} - -func (d *driver) DeleteNetwork(nid string) error { - return types.ForbiddenErrorf("network of type \"%s\" cannot be deleted", networkType) -} - -func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo, epOptions map[string]interface{}) error { - return nil -} - -func (d *driver) DeleteEndpoint(nid, eid string) error { - return nil -} - -func (d *driver) EndpointOperInfo(nid, eid string) (map[string]interface{}, error) { - return make(map[string]interface{}, 0), nil -} - -// Join method is invoked when a Sandbox is attached to an endpoint. -func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error { - return nil -} - -// Leave method is invoked when a Sandbox detaches from an endpoint. -func (d *driver) Leave(nid, eid string) error { - return nil -} - -func (d *driver) ProgramExternalConnectivity(nid, eid string, options map[string]interface{}) error { - return nil -} - -func (d *driver) RevokeExternalConnectivity(nid, eid string) error { - return nil -} - -func (d *driver) Type() string { - return networkType -} - -func (d *driver) IsBuiltIn() bool { - return true -} - -// DiscoverNew is a notification for a new discovery event, such as a new node joining a cluster -func (d *driver) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error { - return nil -} - -// DiscoverDelete is a notification for a discovery delete event, such as a node leaving a cluster -func (d *driver) DiscoverDelete(dType discoverapi.DiscoveryType, data interface{}) error { - return nil -} diff --git a/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan.go b/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan.go deleted file mode 100644 index c64ad555a3..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan.go +++ /dev/null @@ -1,115 +0,0 @@ -package ipvlan - -import ( - "net" - "sync" - - "github.com/docker/libnetwork/datastore" - "github.com/docker/libnetwork/discoverapi" - "github.com/docker/libnetwork/driverapi" - "github.com/docker/libnetwork/osl" - "github.com/docker/libnetwork/types" -) - -const ( - vethLen = 7 - containerVethPrefix = "eth" - vethPrefix = "veth" - ipvlanType = "ipvlan" // driver type name - modeL2 = "l2" // ipvlan mode l2 is the default - modeL3 = "l3" // ipvlan L3 mode - parentOpt = "parent" // parent interface -o parent - modeOpt = "_mode" // ipvlan mode ux opt suffix -) - -var driverModeOpt = ipvlanType + modeOpt // mode -o ipvlan_mode - -type endpointTable map[string]*endpoint - -type networkTable map[string]*network - -type driver struct { - networks networkTable - sync.Once - sync.Mutex - store datastore.DataStore -} - -type endpoint struct { - id string - nid string - mac net.HardwareAddr - addr *net.IPNet - addrv6 *net.IPNet - srcName string - dbIndex uint64 - dbExists bool -} - -type network struct { - id string - sbox osl.Sandbox - endpoints endpointTable - driver *driver - config *configuration - sync.Mutex -} - -// 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) -} - -func (d *driver) NetworkAllocate(id string, option map[string]string, ipV4Data, ipV6Data []driverapi.IPAMData) (map[string]string, error) { - return nil, types.NotImplementedErrorf("not implemented") -} - -func (d *driver) NetworkFree(id string) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) EndpointOperInfo(nid, eid string) (map[string]interface{}, error) { - return make(map[string]interface{}, 0), nil -} - -func (d *driver) Type() string { - return ipvlanType -} - -func (d *driver) IsBuiltIn() bool { - return true -} - -func (d *driver) ProgramExternalConnectivity(nid, eid string, options map[string]interface{}) error { - return nil -} - -func (d *driver) RevokeExternalConnectivity(nid, eid string) error { - return nil -} - -// DiscoverNew is a notification for a new discovery event. -func (d *driver) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error { - return nil -} - -// DiscoverDelete is a notification for a discovery delete event. -func (d *driver) DiscoverDelete(dType discoverapi.DiscoveryType, data interface{}) error { - return nil -} - -func (d *driver) EventNotify(etype driverapi.EventType, nid, tableName, key string, value []byte) { -} - -func (d *driver) DecodeTableEntry(tablename string, key string, value []byte) (string, map[string]string) { - return "", nil -} diff --git a/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_endpoint.go b/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_endpoint.go deleted file mode 100644 index 336b681bab..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_endpoint.go +++ /dev/null @@ -1,89 +0,0 @@ -package ipvlan - -import ( - "fmt" - - "github.com/docker/libnetwork/driverapi" - "github.com/docker/libnetwork/netlabel" - "github.com/docker/libnetwork/ns" - "github.com/docker/libnetwork/osl" - "github.com/docker/libnetwork/types" - "github.com/sirupsen/logrus" -) - -// CreateEndpoint assigns the mac, ip and endpoint id for the new container -func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo, - epOptions map[string]interface{}) error { - defer osl.InitOSContext()() - - if err := validateID(nid, eid); err != nil { - return err - } - n, err := d.getNetwork(nid) - if err != nil { - return fmt.Errorf("network id %q not found", nid) - } - if ifInfo.MacAddress() != nil { - return fmt.Errorf("%s interfaces do not support custom mac address assignment", ipvlanType) - } - ep := &endpoint{ - id: eid, - nid: nid, - addr: ifInfo.Address(), - addrv6: ifInfo.AddressIPv6(), - } - if ep.addr == nil { - return fmt.Errorf("create endpoint was not passed an IP address") - } - // disallow port mapping -p - if opt, ok := epOptions[netlabel.PortMap]; ok { - if _, ok := opt.([]types.PortBinding); ok { - if len(opt.([]types.PortBinding)) > 0 { - logrus.Warnf("%s driver does not support port mappings", ipvlanType) - } - } - } - // disallow port exposure --expose - if opt, ok := epOptions[netlabel.ExposedPorts]; ok { - if _, ok := opt.([]types.TransportPort); ok { - if len(opt.([]types.TransportPort)) > 0 { - logrus.Warnf("%s driver does not support port exposures", ipvlanType) - } - } - } - - if err := d.storeUpdate(ep); err != nil { - return fmt.Errorf("failed to save ipvlan endpoint %.7s to store: %v", ep.id, err) - } - - n.addEndpoint(ep) - - return nil -} - -// DeleteEndpoint remove the endpoint and associated netlink interface -func (d *driver) DeleteEndpoint(nid, eid string) error { - defer osl.InitOSContext()() - if err := validateID(nid, eid); err != nil { - return err - } - n := d.network(nid) - if n == nil { - return fmt.Errorf("network id %q not found", nid) - } - ep := n.endpoint(eid) - if ep == nil { - return fmt.Errorf("endpoint id %q not found", eid) - } - if link, err := ns.NlHandle().LinkByName(ep.srcName); err == nil { - if err := ns.NlHandle().LinkDel(link); err != nil { - logrus.WithError(err).Warnf("Failed to delete interface (%s)'s link on endpoint (%s) delete", ep.srcName, ep.id) - } - } - - if err := d.storeDelete(ep); err != nil { - logrus.Warnf("Failed to remove ipvlan endpoint %.7s from store: %v", ep.id, err) - } - n.deleteEndpoint(ep.id) - return nil -} diff --git a/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_joinleave.go b/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_joinleave.go deleted file mode 100644 index 9474824105..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_joinleave.go +++ /dev/null @@ -1,210 +0,0 @@ -package ipvlan - -import ( - "fmt" - "net" - - "github.com/docker/libnetwork/driverapi" - "github.com/docker/libnetwork/netutils" - "github.com/docker/libnetwork/ns" - "github.com/docker/libnetwork/osl" - "github.com/docker/libnetwork/types" - "github.com/sirupsen/logrus" -) - -type staticRoute struct { - Destination *net.IPNet - RouteType int - NextHop net.IP -} - -const ( - defaultV4RouteCidr = "0.0.0.0/0" - defaultV6RouteCidr = "::/0" -) - -// Join method is invoked when a Sandbox is attached to an endpoint. -func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error { - defer osl.InitOSContext()() - n, err := d.getNetwork(nid) - if err != nil { - return err - } - endpoint := n.endpoint(eid) - if endpoint == nil { - return fmt.Errorf("could not find endpoint with id %s", eid) - } - // generate a name for the iface that will be renamed to eth0 in the sbox - containerIfName, err := netutils.GenerateIfaceName(ns.NlHandle(), vethPrefix, vethLen) - if err != nil { - return fmt.Errorf("error generating an interface name: %v", err) - } - // create the netlink ipvlan interface - vethName, err := createIPVlan(containerIfName, n.config.Parent, n.config.IpvlanMode) - if err != nil { - return err - } - // bind the generated iface name to the endpoint - endpoint.srcName = vethName - ep := n.endpoint(eid) - if ep == nil { - return fmt.Errorf("could not find endpoint with id %s", eid) - } - if !n.config.Internal { - if n.config.IpvlanMode == modeL3 { - // disable gateway services to add a default gw using dev eth0 only - jinfo.DisableGatewayService() - defaultRoute, err := ifaceGateway(defaultV4RouteCidr) - if err != nil { - return err - } - if err := jinfo.AddStaticRoute(defaultRoute.Destination, defaultRoute.RouteType, defaultRoute.NextHop); err != nil { - return fmt.Errorf("failed to set an ipvlan l3 mode ipv4 default gateway: %v", err) - } - logrus.Debugf("Ipvlan Endpoint Joined with IPv4_Addr: %s, Ipvlan_Mode: %s, Parent: %s", - ep.addr.IP.String(), n.config.IpvlanMode, n.config.Parent) - // If the endpoint has a v6 address, set a v6 default route - if ep.addrv6 != nil { - default6Route, err := ifaceGateway(defaultV6RouteCidr) - if err != nil { - return err - } - if err = jinfo.AddStaticRoute(default6Route.Destination, default6Route.RouteType, default6Route.NextHop); err != nil { - return fmt.Errorf("failed to set an ipvlan l3 mode ipv6 default gateway: %v", err) - } - logrus.Debugf("Ipvlan Endpoint Joined with IPv6_Addr: %s, Ipvlan_Mode: %s, Parent: %s", - ep.addrv6.IP.String(), n.config.IpvlanMode, n.config.Parent) - } - } - if n.config.IpvlanMode == modeL2 { - // parse and correlate the endpoint v4 address with the available v4 subnets - if len(n.config.Ipv4Subnets) > 0 { - s := n.getSubnetforIPv4(ep.addr) - if s == nil { - return fmt.Errorf("could not find a valid ipv4 subnet for endpoint %s", eid) - } - v4gw, _, err := net.ParseCIDR(s.GwIP) - if err != nil { - return fmt.Errorf("gateway %s is not a valid ipv4 address: %v", s.GwIP, err) - } - err = jinfo.SetGateway(v4gw) - if err != nil { - return err - } - logrus.Debugf("Ipvlan Endpoint Joined with IPv4_Addr: %s, Gateway: %s, Ipvlan_Mode: %s, Parent: %s", - ep.addr.IP.String(), v4gw.String(), n.config.IpvlanMode, n.config.Parent) - } - // parse and correlate the endpoint v6 address with the available v6 subnets - if len(n.config.Ipv6Subnets) > 0 { - s := n.getSubnetforIPv6(ep.addrv6) - if s == nil { - return fmt.Errorf("could not find a valid ipv6 subnet for endpoint %s", eid) - } - v6gw, _, err := net.ParseCIDR(s.GwIP) - if err != nil { - return fmt.Errorf("gateway %s is not a valid ipv6 address: %v", s.GwIP, err) - } - err = jinfo.SetGatewayIPv6(v6gw) - if err != nil { - return err - } - logrus.Debugf("Ipvlan Endpoint Joined with IPv6_Addr: %s, Gateway: %s, Ipvlan_Mode: %s, Parent: %s", - ep.addrv6.IP.String(), v6gw.String(), n.config.IpvlanMode, n.config.Parent) - } - } - } else { - if len(n.config.Ipv4Subnets) > 0 { - logrus.Debugf("Ipvlan Endpoint Joined with IPv4_Addr: %s, IpVlan_Mode: %s, Parent: %s", - ep.addr.IP.String(), n.config.IpvlanMode, n.config.Parent) - } - if len(n.config.Ipv6Subnets) > 0 { - logrus.Debugf("Ipvlan Endpoint Joined with IPv6_Addr: %s IpVlan_Mode: %s, Parent: %s", - ep.addrv6.IP.String(), n.config.IpvlanMode, n.config.Parent) - } - } - iNames := jinfo.InterfaceName() - err = iNames.SetNames(vethName, containerVethPrefix) - if err != nil { - return err - } - if err = d.storeUpdate(ep); err != nil { - return fmt.Errorf("failed to save ipvlan endpoint %.7s to store: %v", ep.id, err) - } - - return nil -} - -// Leave method is invoked when a Sandbox detaches from an endpoint. -func (d *driver) Leave(nid, eid string) error { - defer osl.InitOSContext()() - network, err := d.getNetwork(nid) - if err != nil { - return err - } - endpoint, err := network.getEndpoint(eid) - if err != nil { - return err - } - if endpoint == nil { - return fmt.Errorf("could not find endpoint with id %s", eid) - } - - return nil -} - -// ifaceGateway returns a static route for either v4/v6 to be set to the container eth0 -func ifaceGateway(dfNet string) (*staticRoute, error) { - nh, dst, err := net.ParseCIDR(dfNet) - if err != nil { - return nil, fmt.Errorf("unable to parse default route %v", err) - } - defaultRoute := &staticRoute{ - Destination: dst, - RouteType: types.CONNECTED, - NextHop: nh, - } - - return defaultRoute, nil -} - -// getSubnetforIPv4 returns the ipv4 subnet to which the given IP belongs -func (n *network) getSubnetforIPv4(ip *net.IPNet) *ipv4Subnet { - for _, s := range n.config.Ipv4Subnets { - _, snet, err := net.ParseCIDR(s.SubnetIP) - if err != nil { - return nil - } - // first check if the mask lengths are the same - i, _ := snet.Mask.Size() - j, _ := ip.Mask.Size() - if i != j { - continue - } - if snet.Contains(ip.IP) { - return s - } - } - - return nil -} - -// getSubnetforIPv6 returns the ipv6 subnet to which the given IP belongs -func (n *network) getSubnetforIPv6(ip *net.IPNet) *ipv6Subnet { - for _, s := range n.config.Ipv6Subnets { - _, snet, err := net.ParseCIDR(s.SubnetIP) - if err != nil { - return nil - } - // first check if the mask lengths are the same - i, _ := snet.Mask.Size() - j, _ := ip.Mask.Size() - if i != j { - continue - } - if snet.Contains(ip.IP) { - return s - } - } - - return nil -} diff --git a/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_network.go b/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_network.go deleted file mode 100644 index 09aff60c90..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_network.go +++ /dev/null @@ -1,260 +0,0 @@ -package ipvlan - -import ( - "fmt" - - "github.com/docker/docker/pkg/parsers/kernel" - "github.com/docker/docker/pkg/stringid" - "github.com/docker/libnetwork/driverapi" - "github.com/docker/libnetwork/netlabel" - "github.com/docker/libnetwork/ns" - "github.com/docker/libnetwork/options" - "github.com/docker/libnetwork/osl" - "github.com/docker/libnetwork/types" - "github.com/sirupsen/logrus" -) - -// CreateNetwork the network for the specified driver type -func (d *driver) CreateNetwork(nid string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error { - defer osl.InitOSContext()() - kv, err := kernel.GetKernelVersion() - if err != nil { - return fmt.Errorf("Failed to check kernel version for %s driver support: %v", ipvlanType, err) - } - // ensure Kernel version is >= v4.2 for ipvlan support - if kv.Kernel < ipvlanKernelVer || (kv.Kernel == ipvlanKernelVer && kv.Major < ipvlanMajorVer) { - return fmt.Errorf("kernel version failed to meet the minimum ipvlan kernel requirement of %d.%d, found %d.%d.%d", - ipvlanKernelVer, ipvlanMajorVer, kv.Kernel, kv.Major, kv.Minor) - } - // reject a null v4 network - if len(ipV4Data) == 0 || ipV4Data[0].Pool.String() == "0.0.0.0/0" { - return fmt.Errorf("ipv4 pool is empty") - } - // parse and validate the config and bind to networkConfiguration - config, err := parseNetworkOptions(nid, option) - if err != nil { - return err - } - config.ID = nid - err = config.processIPAM(nid, ipV4Data, ipV6Data) - if err != nil { - return err - } - // verify the ipvlan mode from -o ipvlan_mode option - switch config.IpvlanMode { - case "", modeL2: - // default to ipvlan L2 mode if -o ipvlan_mode is empty - config.IpvlanMode = modeL2 - case modeL3: - config.IpvlanMode = modeL3 - default: - return fmt.Errorf("requested ipvlan mode '%s' is not valid, 'l2' mode is the ipvlan driver default", config.IpvlanMode) - } - // loopback is not a valid parent link - if config.Parent == "lo" { - return fmt.Errorf("loopback interface is not a valid %s parent link", ipvlanType) - } - // if parent interface not specified, create a dummy type link to use named dummy+net_id - if config.Parent == "" { - config.Parent = getDummyName(stringid.TruncateID(config.ID)) - } - foundExisting, err := d.createNetwork(config) - if err != nil { - return err - } - - if foundExisting { - return types.InternalMaskableErrorf("restoring existing network %s", config.ID) - } - // update persistent db, rollback on fail - err = d.storeUpdate(config) - if err != nil { - d.deleteNetwork(config.ID) - logrus.Debugf("encountered an error rolling back a network create for %s : %v", config.ID, err) - return err - } - - return nil -} - -// createNetwork is used by new network callbacks and persistent network cache -func (d *driver) createNetwork(config *configuration) (bool, error) { - foundExisting := false - networkList := d.getNetworks() - for _, nw := range networkList { - if config.Parent == nw.config.Parent { - if config.ID != nw.config.ID { - return false, fmt.Errorf("network %s is already using parent interface %s", - getDummyName(stringid.TruncateID(nw.config.ID)), config.Parent) - } - logrus.Debugf("Create Network for the same ID %s\n", config.ID) - foundExisting = true - break - } - } - if !parentExists(config.Parent) { - // Create a dummy link if a dummy name is set for parent - if dummyName := getDummyName(stringid.TruncateID(config.ID)); dummyName == config.Parent { - err := createDummyLink(config.Parent, dummyName) - if err != nil { - return false, err - } - config.CreatedSlaveLink = true - - // notify the user in logs they have limited communications - logrus.Debugf("Empty -o parent= flags limit communications to other containers inside of network: %s", - config.Parent) - } else { - // if the subinterface parent_iface.vlan_id checks do not pass, return err. - // a valid example is 'eth0.10' for a parent iface 'eth0' with a vlan id '10' - err := createVlanLink(config.Parent) - if err != nil { - return false, err - } - // if driver created the networks slave link, record it for future deletion - config.CreatedSlaveLink = true - } - } - if !foundExisting { - n := &network{ - id: config.ID, - driver: d, - endpoints: endpointTable{}, - config: config, - } - // add the network - d.addNetwork(n) - } - - return foundExisting, nil -} - -// DeleteNetwork the network for the specified driver type -func (d *driver) DeleteNetwork(nid string) error { - defer osl.InitOSContext()() - n := d.network(nid) - if n == nil { - return fmt.Errorf("network id %s not found", nid) - } - // if the driver created the slave interface, delete it, otherwise leave it - if ok := n.config.CreatedSlaveLink; ok { - // if the interface exists, only delete if it matches iface.vlan or dummy.net_id naming - if ok := parentExists(n.config.Parent); ok { - // only delete the link if it is named the net_id - if n.config.Parent == getDummyName(stringid.TruncateID(nid)) { - err := delDummyLink(n.config.Parent) - if err != nil { - logrus.Debugf("link %s was not deleted, continuing the delete network operation: %v", - n.config.Parent, err) - } - } else { - // only delete the link if it matches iface.vlan naming - err := delVlanLink(n.config.Parent) - if err != nil { - logrus.Debugf("link %s was not deleted, continuing the delete network operation: %v", - n.config.Parent, err) - } - } - } - } - for _, ep := range n.endpoints { - if link, err := ns.NlHandle().LinkByName(ep.srcName); err == nil { - if err := ns.NlHandle().LinkDel(link); err != nil { - logrus.WithError(err).Warnf("Failed to delete interface (%s)'s link on endpoint (%s) delete", ep.srcName, ep.id) - } - } - - if err := d.storeDelete(ep); err != nil { - logrus.Warnf("Failed to remove ipvlan endpoint %.7s from store: %v", ep.id, err) - } - } - // delete the *network - d.deleteNetwork(nid) - // delete the network record from persistent cache - err := d.storeDelete(n.config) - if err != nil { - return fmt.Errorf("error deleting deleting id %s from datastore: %v", nid, err) - } - return nil -} - -// parseNetworkOptions parse docker network options -func parseNetworkOptions(id string, option options.Generic) (*configuration, error) { - var ( - err error - config = &configuration{} - ) - // parse generic labels first - if genData, ok := option[netlabel.GenericData]; ok && genData != nil { - if config, err = parseNetworkGenericOptions(genData); err != nil { - return nil, err - } - } - if val, ok := option[netlabel.Internal]; ok { - if internal, ok := val.(bool); ok && internal { - config.Internal = true - } - } - return config, nil -} - -// parseNetworkGenericOptions parse generic driver docker network options -func parseNetworkGenericOptions(data interface{}) (*configuration, error) { - var ( - err error - config *configuration - ) - switch opt := data.(type) { - case *configuration: - config = opt - case map[string]string: - config = &configuration{} - err = config.fromOptions(opt) - case options.Generic: - var opaqueConfig interface{} - if opaqueConfig, err = options.GenerateFromModel(opt, config); err == nil { - config = opaqueConfig.(*configuration) - } - default: - err = types.BadRequestErrorf("unrecognized network configuration format: %v", opt) - } - return config, err -} - -// fromOptions binds the generic options to networkConfiguration to cache -func (config *configuration) fromOptions(labels map[string]string) error { - for label, value := range labels { - switch label { - case parentOpt: - // parse driver option '-o parent' - config.Parent = value - case driverModeOpt: - // parse driver option '-o ipvlan_mode' - config.IpvlanMode = value - } - } - return nil -} - -// processIPAM parses v4 and v6 IP information and binds it to the network configuration -func (config *configuration) processIPAM(id string, ipamV4Data, ipamV6Data []driverapi.IPAMData) error { - if len(ipamV4Data) > 0 { - for _, ipd := range ipamV4Data { - s := &ipv4Subnet{ - SubnetIP: ipd.Pool.String(), - GwIP: ipd.Gateway.String(), - } - config.Ipv4Subnets = append(config.Ipv4Subnets, s) - } - } - if len(ipamV6Data) > 0 { - for _, ipd := range ipamV6Data { - s := &ipv6Subnet{ - SubnetIP: ipd.Pool.String(), - GwIP: ipd.Gateway.String(), - } - config.Ipv6Subnets = append(config.Ipv6Subnets, s) - } - } - return nil -} diff --git a/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_setup.go b/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_setup.go deleted file mode 100644 index da8d8faeb8..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_setup.go +++ /dev/null @@ -1,205 +0,0 @@ -package ipvlan - -import ( - "fmt" - "strconv" - "strings" - - "github.com/docker/libnetwork/ns" - "github.com/sirupsen/logrus" - "github.com/vishvananda/netlink" -) - -const ( - dummyPrefix = "di-" // ipvlan prefix for dummy parent interface - ipvlanKernelVer = 4 // minimum ipvlan kernel support - ipvlanMajorVer = 2 // minimum ipvlan major kernel support -) - -// createIPVlan Create the ipvlan slave specifying the source name -func createIPVlan(containerIfName, parent, ipvlanMode string) (string, error) { - // Set the ipvlan mode. Default is bridge mode - mode, err := setIPVlanMode(ipvlanMode) - if err != nil { - return "", fmt.Errorf("Unsupported %s ipvlan mode: %v", ipvlanMode, err) - } - // verify the Docker host interface acting as the macvlan parent iface exists - if !parentExists(parent) { - return "", fmt.Errorf("the requested parent interface %s was not found on the Docker host", parent) - } - // Get the link for the master index (Example: the docker host eth iface) - parentLink, err := ns.NlHandle().LinkByName(parent) - if err != nil { - return "", fmt.Errorf("error occurred looking up the %s parent iface %s error: %s", ipvlanType, parent, err) - } - // Create an ipvlan link - ipvlan := &netlink.IPVlan{ - LinkAttrs: netlink.LinkAttrs{ - Name: containerIfName, - ParentIndex: parentLink.Attrs().Index, - }, - Mode: mode, - } - if err := ns.NlHandle().LinkAdd(ipvlan); err != nil { - // If a user creates a macvlan and ipvlan on same parent, only one slave iface can be active at a time. - return "", fmt.Errorf("failed to create the %s port: %v", ipvlanType, err) - } - - return ipvlan.Attrs().Name, nil -} - -// setIPVlanMode setter for one of the two ipvlan port types -func setIPVlanMode(mode string) (netlink.IPVlanMode, error) { - switch mode { - case modeL2: - return netlink.IPVLAN_MODE_L2, nil - case modeL3: - return netlink.IPVLAN_MODE_L3, nil - default: - return 0, fmt.Errorf("Unknown ipvlan mode: %s", mode) - } -} - -// parentExists check if the specified interface exists in the default namespace -func parentExists(ifaceStr string) bool { - _, err := ns.NlHandle().LinkByName(ifaceStr) - if err != nil { - return false - } - - return true -} - -// createVlanLink parses sub-interfaces and vlan id for creation -func createVlanLink(parentName string) error { - if strings.Contains(parentName, ".") { - parent, vidInt, err := parseVlan(parentName) - if err != nil { - return err - } - // VLAN identifier or VID is a 12-bit field specifying the VLAN to which the frame belongs - if vidInt > 4094 || vidInt < 1 { - return fmt.Errorf("vlan id must be between 1-4094, received: %d", vidInt) - } - // get the parent link to attach a vlan subinterface - parentLink, err := ns.NlHandle().LinkByName(parent) - if err != nil { - return fmt.Errorf("failed to find master interface %s on the Docker host: %v", parent, err) - } - vlanLink := &netlink.Vlan{ - LinkAttrs: netlink.LinkAttrs{ - Name: parentName, - ParentIndex: parentLink.Attrs().Index, - }, - VlanId: vidInt, - } - // create the subinterface - if err := ns.NlHandle().LinkAdd(vlanLink); err != nil { - return fmt.Errorf("failed to create %s vlan link: %v", vlanLink.Name, err) - } - // Bring the new netlink iface up - if err := ns.NlHandle().LinkSetUp(vlanLink); err != nil { - return fmt.Errorf("failed to enable %s the ipvlan parent link %v", vlanLink.Name, err) - } - logrus.Debugf("Added a vlan tagged netlink subinterface: %s with a vlan id: %d", parentName, vidInt) - return nil - } - - return fmt.Errorf("invalid subinterface vlan name %s, example formatting is eth0.10", parentName) -} - -// delVlanLink verifies only sub-interfaces with a vlan id get deleted -func delVlanLink(linkName string) error { - if strings.Contains(linkName, ".") { - _, _, err := parseVlan(linkName) - if err != nil { - return err - } - // delete the vlan subinterface - vlanLink, err := ns.NlHandle().LinkByName(linkName) - if err != nil { - return fmt.Errorf("failed to find interface %s on the Docker host : %v", linkName, err) - } - // verify a parent interface isn't being deleted - if vlanLink.Attrs().ParentIndex == 0 { - return fmt.Errorf("interface %s does not appear to be a slave device: %v", linkName, err) - } - // delete the ipvlan slave device - if err := ns.NlHandle().LinkDel(vlanLink); err != nil { - return fmt.Errorf("failed to delete %s link: %v", linkName, err) - } - logrus.Debugf("Deleted a vlan tagged netlink subinterface: %s", linkName) - } - // if the subinterface doesn't parse to iface.vlan_id leave the interface in - // place since it could be a user specified name not created by the driver. - return nil -} - -// parseVlan parses and verifies a slave interface name: -o parent=eth0.10 -func parseVlan(linkName string) (string, int, error) { - // parse -o parent=eth0.10 - splitName := strings.Split(linkName, ".") - if len(splitName) != 2 { - return "", 0, fmt.Errorf("required interface name format is: name.vlan_id, ex. eth0.10 for vlan 10, instead received %s", linkName) - } - parent, vidStr := splitName[0], splitName[1] - // validate type and convert vlan id to int - vidInt, err := strconv.Atoi(vidStr) - if err != nil { - return "", 0, fmt.Errorf("unable to parse a valid vlan id from: %s (ex. eth0.10 for vlan 10)", vidStr) - } - // Check if the interface exists - if !parentExists(parent) { - return "", 0, fmt.Errorf("-o parent interface was not found on the host: %s", parent) - } - - return parent, vidInt, nil -} - -// createDummyLink creates a dummy0 parent link -func createDummyLink(dummyName, truncNetID string) error { - // create a parent interface since one was not specified - parent := &netlink.Dummy{ - LinkAttrs: netlink.LinkAttrs{ - Name: dummyName, - }, - } - if err := ns.NlHandle().LinkAdd(parent); err != nil { - return err - } - parentDummyLink, err := ns.NlHandle().LinkByName(dummyName) - if err != nil { - return fmt.Errorf("error occurred looking up the %s parent iface %s error: %s", ipvlanType, dummyName, err) - } - // bring the new netlink iface up - if err := ns.NlHandle().LinkSetUp(parentDummyLink); err != nil { - return fmt.Errorf("failed to enable %s the ipvlan parent link: %v", dummyName, err) - } - - return nil -} - -// delDummyLink deletes the link type dummy used when -o parent is not passed -func delDummyLink(linkName string) error { - // delete the vlan subinterface - dummyLink, err := ns.NlHandle().LinkByName(linkName) - if err != nil { - return fmt.Errorf("failed to find link %s on the Docker host : %v", linkName, err) - } - // verify a parent interface is being deleted - if dummyLink.Attrs().ParentIndex != 0 { - return fmt.Errorf("link %s is not a parent dummy interface", linkName) - } - // delete the ipvlan dummy device - if err := ns.NlHandle().LinkDel(dummyLink); err != nil { - return fmt.Errorf("failed to delete the dummy %s link: %v", linkName, err) - } - logrus.Debugf("Deleted a dummy parent link: %s", linkName) - - return nil -} - -// getDummyName returns the name of a dummy parent with truncated net ID and driver prefix -func getDummyName(netID string) string { - return dummyPrefix + netID -} diff --git a/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_state.go b/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_state.go deleted file mode 100644 index dc73b6893d..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_state.go +++ /dev/null @@ -1,115 +0,0 @@ -package ipvlan - -import ( - "fmt" - - "github.com/docker/libnetwork/osl" - "github.com/docker/libnetwork/types" - "github.com/sirupsen/logrus" -) - -func (d *driver) network(nid string) *network { - d.Lock() - n, ok := d.networks[nid] - d.Unlock() - if !ok { - logrus.Errorf("network id %s not found", nid) - } - - return n -} - -func (d *driver) addNetwork(n *network) { - d.Lock() - d.networks[n.id] = n - d.Unlock() -} - -func (d *driver) deleteNetwork(nid string) { - d.Lock() - delete(d.networks, nid) - d.Unlock() -} - -// getNetworks Safely returns a slice of existing networks -func (d *driver) getNetworks() []*network { - d.Lock() - defer d.Unlock() - - ls := make([]*network, 0, len(d.networks)) - for _, nw := range d.networks { - ls = append(ls, nw) - } - - return ls -} - -func (n *network) endpoint(eid string) *endpoint { - n.Lock() - defer n.Unlock() - - return n.endpoints[eid] -} - -func (n *network) addEndpoint(ep *endpoint) { - n.Lock() - n.endpoints[ep.id] = ep - n.Unlock() -} - -func (n *network) deleteEndpoint(eid string) { - n.Lock() - delete(n.endpoints, eid) - n.Unlock() -} - -func (n *network) getEndpoint(eid string) (*endpoint, error) { - n.Lock() - defer n.Unlock() - if eid == "" { - return nil, fmt.Errorf("endpoint id %s not found", eid) - } - if ep, ok := n.endpoints[eid]; ok { - return ep, nil - } - - return nil, nil -} - -func validateID(nid, eid string) error { - if nid == "" { - return fmt.Errorf("invalid network id") - } - if eid == "" { - return fmt.Errorf("invalid endpoint id") - } - - return nil -} - -func (n *network) sandbox() osl.Sandbox { - n.Lock() - defer n.Unlock() - - return n.sbox -} - -func (n *network) setSandbox(sbox osl.Sandbox) { - n.Lock() - n.sbox = sbox - n.Unlock() -} - -func (d *driver) getNetwork(id string) (*network, error) { - d.Lock() - defer d.Unlock() - if id == "" { - return nil, types.BadRequestErrorf("invalid network id: %s", id) - } - - if nw, ok := d.networks[id]; ok { - return nw, nil - } - - return nil, types.NotFoundErrorf("network not found: %s", id) -} diff --git a/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_store.go b/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_store.go deleted file mode 100644 index cf9d324292..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_store.go +++ /dev/null @@ -1,356 +0,0 @@ -package ipvlan - -import ( - "encoding/json" - "fmt" - "net" - - "github.com/docker/libnetwork/datastore" - "github.com/docker/libnetwork/discoverapi" - "github.com/docker/libnetwork/netlabel" - "github.com/docker/libnetwork/types" - "github.com/sirupsen/logrus" -) - -const ( - ipvlanPrefix = "ipvlan" - ipvlanNetworkPrefix = ipvlanPrefix + "/network" - ipvlanEndpointPrefix = ipvlanPrefix + "/endpoint" -) - -// networkConfiguration for this driver's network specific configuration -type configuration struct { - ID string - Mtu int - dbIndex uint64 - dbExists bool - Internal bool - Parent string - IpvlanMode string - CreatedSlaveLink bool - Ipv4Subnets []*ipv4Subnet - Ipv6Subnets []*ipv6Subnet -} - -type ipv4Subnet struct { - SubnetIP string - GwIP string -} - -type ipv6Subnet struct { - SubnetIP string - GwIP string -} - -// initStore drivers are responsible for caching their own persistent state -func (d *driver) initStore(option map[string]interface{}) error { - if data, ok := option[netlabel.LocalKVClient]; ok { - var err error - dsc, ok := data.(discoverapi.DatastoreConfigData) - if !ok { - return types.InternalErrorf("incorrect data in datastore configuration: %v", data) - } - d.store, err = datastore.NewDataStoreFromConfig(dsc) - if err != nil { - return types.InternalErrorf("ipvlan driver failed to initialize data store: %v", err) - } - - err = d.populateNetworks() - if err != nil { - return err - } - err = d.populateEndpoints() - if err != nil { - return err - } - } - - return nil -} - -// populateNetworks is invoked at driver init to recreate persistently stored networks -func (d *driver) populateNetworks() error { - kvol, err := d.store.List(datastore.Key(ipvlanNetworkPrefix), &configuration{}) - if err != nil && err != datastore.ErrKeyNotFound { - return fmt.Errorf("failed to get ipvlan network configurations from store: %v", err) - } - // If empty it simply means no ipvlan networks have been created yet - if err == datastore.ErrKeyNotFound { - return nil - } - for _, kvo := range kvol { - config := kvo.(*configuration) - if _, err = d.createNetwork(config); err != nil { - logrus.Warnf("could not create ipvlan network for id %s from persistent state", config.ID) - } - } - - return nil -} - -func (d *driver) populateEndpoints() error { - kvol, err := d.store.List(datastore.Key(ipvlanEndpointPrefix), &endpoint{}) - if err != nil && err != datastore.ErrKeyNotFound { - return fmt.Errorf("failed to get ipvlan endpoints from store: %v", err) - } - - if err == datastore.ErrKeyNotFound { - return nil - } - - for _, kvo := range kvol { - ep := kvo.(*endpoint) - n, ok := d.networks[ep.nid] - if !ok { - logrus.Debugf("Network (%.7s) not found for restored ipvlan endpoint (%.7s)", ep.nid, ep.id) - logrus.Debugf("Deleting stale ipvlan endpoint (%.7s) from store", ep.id) - if err := d.storeDelete(ep); err != nil { - logrus.Debugf("Failed to delete stale ipvlan endpoint (%.7s) from store", ep.id) - } - continue - } - n.endpoints[ep.id] = ep - logrus.Debugf("Endpoint (%.7s) restored to network (%.7s)", ep.id, ep.nid) - } - - return nil -} - -// storeUpdate used to update persistent ipvlan network records as they are created -func (d *driver) storeUpdate(kvObject datastore.KVObject) error { - if d.store == nil { - logrus.Warnf("ipvlan store not initialized. kv object %s is not added to the store", datastore.Key(kvObject.Key()...)) - return nil - } - if err := d.store.PutObjectAtomic(kvObject); err != nil { - return fmt.Errorf("failed to update ipvlan store for object type %T: %v", kvObject, err) - } - - return nil -} - -// storeDelete used to delete ipvlan network records from persistent cache as they are deleted -func (d *driver) storeDelete(kvObject datastore.KVObject) error { - if d.store == nil { - logrus.Debugf("ipvlan store not initialized. kv object %s is not deleted from store", datastore.Key(kvObject.Key()...)) - return nil - } -retry: - if err := d.store.DeleteObjectAtomic(kvObject); err != nil { - if err == datastore.ErrKeyModified { - if err := d.store.GetObject(datastore.Key(kvObject.Key()...), kvObject); err != nil { - return fmt.Errorf("could not update the kvobject to latest when trying to delete: %v", err) - } - goto retry - } - return err - } - - return nil -} - -func (config *configuration) MarshalJSON() ([]byte, error) { - nMap := make(map[string]interface{}) - nMap["ID"] = config.ID - nMap["Mtu"] = config.Mtu - nMap["Parent"] = config.Parent - nMap["IpvlanMode"] = config.IpvlanMode - nMap["Internal"] = config.Internal - nMap["CreatedSubIface"] = config.CreatedSlaveLink - if len(config.Ipv4Subnets) > 0 { - iis, err := json.Marshal(config.Ipv4Subnets) - if err != nil { - return nil, err - } - nMap["Ipv4Subnets"] = string(iis) - } - if len(config.Ipv6Subnets) > 0 { - iis, err := json.Marshal(config.Ipv6Subnets) - if err != nil { - return nil, err - } - nMap["Ipv6Subnets"] = string(iis) - } - - return json.Marshal(nMap) -} - -func (config *configuration) UnmarshalJSON(b []byte) error { - var ( - err error - nMap map[string]interface{} - ) - - if err = json.Unmarshal(b, &nMap); err != nil { - return err - } - config.ID = nMap["ID"].(string) - config.Mtu = int(nMap["Mtu"].(float64)) - config.Parent = nMap["Parent"].(string) - config.IpvlanMode = nMap["IpvlanMode"].(string) - config.Internal = nMap["Internal"].(bool) - config.CreatedSlaveLink = nMap["CreatedSubIface"].(bool) - if v, ok := nMap["Ipv4Subnets"]; ok { - if err := json.Unmarshal([]byte(v.(string)), &config.Ipv4Subnets); err != nil { - return err - } - } - if v, ok := nMap["Ipv6Subnets"]; ok { - if err := json.Unmarshal([]byte(v.(string)), &config.Ipv6Subnets); err != nil { - return err - } - } - - return nil -} - -func (config *configuration) Key() []string { - return []string{ipvlanNetworkPrefix, config.ID} -} - -func (config *configuration) KeyPrefix() []string { - return []string{ipvlanNetworkPrefix} -} - -func (config *configuration) Value() []byte { - b, err := json.Marshal(config) - if err != nil { - return nil - } - return b -} - -func (config *configuration) SetValue(value []byte) error { - return json.Unmarshal(value, config) -} - -func (config *configuration) Index() uint64 { - return config.dbIndex -} - -func (config *configuration) SetIndex(index uint64) { - config.dbIndex = index - config.dbExists = true -} - -func (config *configuration) Exists() bool { - return config.dbExists -} - -func (config *configuration) Skip() bool { - return false -} - -func (config *configuration) New() datastore.KVObject { - return &configuration{} -} - -func (config *configuration) CopyTo(o datastore.KVObject) error { - dstNcfg := o.(*configuration) - *dstNcfg = *config - return nil -} - -func (config *configuration) DataScope() string { - return datastore.LocalScope -} - -func (ep *endpoint) MarshalJSON() ([]byte, error) { - epMap := make(map[string]interface{}) - epMap["id"] = ep.id - epMap["nid"] = ep.nid - epMap["SrcName"] = ep.srcName - if len(ep.mac) != 0 { - epMap["MacAddress"] = ep.mac.String() - } - if ep.addr != nil { - epMap["Addr"] = ep.addr.String() - } - if ep.addrv6 != nil { - epMap["Addrv6"] = ep.addrv6.String() - } - return json.Marshal(epMap) -} - -func (ep *endpoint) UnmarshalJSON(b []byte) error { - var ( - err error - epMap map[string]interface{} - ) - - if err = json.Unmarshal(b, &epMap); err != nil { - return fmt.Errorf("Failed to unmarshal to ipvlan endpoint: %v", err) - } - - if v, ok := epMap["MacAddress"]; ok { - if ep.mac, err = net.ParseMAC(v.(string)); err != nil { - return types.InternalErrorf("failed to decode ipvlan endpoint MAC address (%s) after json unmarshal: %v", v.(string), err) - } - } - if v, ok := epMap["Addr"]; ok { - if ep.addr, err = types.ParseCIDR(v.(string)); err != nil { - return types.InternalErrorf("failed to decode ipvlan endpoint IPv4 address (%s) after json unmarshal: %v", v.(string), err) - } - } - if v, ok := epMap["Addrv6"]; ok { - if ep.addrv6, err = types.ParseCIDR(v.(string)); err != nil { - return types.InternalErrorf("failed to decode ipvlan endpoint IPv6 address (%s) after json unmarshal: %v", v.(string), err) - } - } - ep.id = epMap["id"].(string) - ep.nid = epMap["nid"].(string) - ep.srcName = epMap["SrcName"].(string) - - return nil -} - -func (ep *endpoint) Key() []string { - return []string{ipvlanEndpointPrefix, ep.id} -} - -func (ep *endpoint) KeyPrefix() []string { - return []string{ipvlanEndpointPrefix} -} - -func (ep *endpoint) Value() []byte { - b, err := json.Marshal(ep) - if err != nil { - return nil - } - return b -} - -func (ep *endpoint) SetValue(value []byte) error { - return json.Unmarshal(value, ep) -} - -func (ep *endpoint) Index() uint64 { - return ep.dbIndex -} - -func (ep *endpoint) SetIndex(index uint64) { - ep.dbIndex = index - ep.dbExists = true -} - -func (ep *endpoint) Exists() bool { - return ep.dbExists -} - -func (ep *endpoint) Skip() bool { - return false -} - -func (ep *endpoint) New() datastore.KVObject { - return &endpoint{} -} - -func (ep *endpoint) CopyTo(o datastore.KVObject) error { - dstEp := o.(*endpoint) - *dstEp = *ep - return nil -} - -func (ep *endpoint) DataScope() string { - return datastore.LocalScope -} diff --git a/vendor/github.com/docker/libnetwork/drivers/ipvlan/ivmanager/ivmanager.go b/vendor/github.com/docker/libnetwork/drivers/ipvlan/ivmanager/ivmanager.go deleted file mode 100644 index 519f1e8795..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/ipvlan/ivmanager/ivmanager.go +++ /dev/null @@ -1,88 +0,0 @@ -package ivmanager - -import ( - "github.com/docker/libnetwork/datastore" - "github.com/docker/libnetwork/discoverapi" - "github.com/docker/libnetwork/driverapi" - "github.com/docker/libnetwork/types" -) - -const networkType = "ipvlan" - -type driver struct{} - -// Init registers a new instance of ipvlan manager driver -func Init(dc driverapi.DriverCallback, config map[string]interface{}) error { - c := driverapi.Capability{ - DataScope: datastore.LocalScope, - ConnectivityScope: datastore.GlobalScope, - } - return dc.RegisterDriver(networkType, &driver{}, c) -} - -func (d *driver) NetworkAllocate(id string, option map[string]string, ipV4Data, ipV6Data []driverapi.IPAMData) (map[string]string, error) { - return nil, types.NotImplementedErrorf("not implemented") -} - -func (d *driver) NetworkFree(id string) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) CreateNetwork(id string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) EventNotify(etype driverapi.EventType, nid, tableName, key string, value []byte) { -} - -func (d *driver) DecodeTableEntry(tablename string, key string, value []byte) (string, map[string]string) { - return "", nil -} - -func (d *driver) DeleteNetwork(nid string) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo, epOptions map[string]interface{}) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) DeleteEndpoint(nid, eid string) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) EndpointOperInfo(nid, eid string) (map[string]interface{}, error) { - return nil, types.NotImplementedErrorf("not implemented") -} - -func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) Leave(nid, eid string) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) Type() string { - return networkType -} - -func (d *driver) IsBuiltIn() bool { - return true -} - -func (d *driver) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) DiscoverDelete(dType discoverapi.DiscoveryType, data interface{}) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) ProgramExternalConnectivity(nid, eid string, options map[string]interface{}) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) RevokeExternalConnectivity(nid, eid string) error { - return types.NotImplementedErrorf("not implemented") -} diff --git a/vendor/github.com/docker/libnetwork/drivers/macvlan/macvlan.go b/vendor/github.com/docker/libnetwork/drivers/macvlan/macvlan.go deleted file mode 100644 index 872e6f3ec1..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/macvlan/macvlan.go +++ /dev/null @@ -1,117 +0,0 @@ -package macvlan - -import ( - "net" - "sync" - - "github.com/docker/libnetwork/datastore" - "github.com/docker/libnetwork/discoverapi" - "github.com/docker/libnetwork/driverapi" - "github.com/docker/libnetwork/osl" - "github.com/docker/libnetwork/types" -) - -const ( - vethLen = 7 - containerVethPrefix = "eth" - vethPrefix = "veth" - macvlanType = "macvlan" // driver type name - modePrivate = "private" // macvlan mode private - modeVepa = "vepa" // macvlan mode vepa - modeBridge = "bridge" // macvlan mode bridge - modePassthru = "passthru" // macvlan mode passthrough - parentOpt = "parent" // parent interface -o parent - modeOpt = "_mode" // macvlan mode ux opt suffix -) - -var driverModeOpt = macvlanType + modeOpt // mode --option macvlan_mode - -type endpointTable map[string]*endpoint - -type networkTable map[string]*network - -type driver struct { - networks networkTable - sync.Once - sync.Mutex - store datastore.DataStore -} - -type endpoint struct { - id string - nid string - mac net.HardwareAddr - addr *net.IPNet - addrv6 *net.IPNet - srcName string - dbIndex uint64 - dbExists bool -} - -type network struct { - id string - sbox osl.Sandbox - endpoints endpointTable - driver *driver - config *configuration - sync.Mutex -} - -// Init initializes and registers the libnetwork macvlan 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(macvlanType, d, c) -} - -func (d *driver) NetworkAllocate(id string, option map[string]string, ipV4Data, ipV6Data []driverapi.IPAMData) (map[string]string, error) { - return nil, types.NotImplementedErrorf("not implemented") -} - -func (d *driver) NetworkFree(id string) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) EndpointOperInfo(nid, eid string) (map[string]interface{}, error) { - return make(map[string]interface{}, 0), nil -} - -func (d *driver) Type() string { - return macvlanType -} - -func (d *driver) IsBuiltIn() bool { - return true -} - -func (d *driver) ProgramExternalConnectivity(nid, eid string, options map[string]interface{}) error { - return nil -} - -func (d *driver) RevokeExternalConnectivity(nid, eid string) error { - return nil -} - -// DiscoverNew is a notification for a new discovery event -func (d *driver) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error { - return nil -} - -// DiscoverDelete is a notification for a discovery delete event -func (d *driver) DiscoverDelete(dType discoverapi.DiscoveryType, data interface{}) error { - return nil -} - -func (d *driver) EventNotify(etype driverapi.EventType, nid, tableName, key string, value []byte) { -} - -func (d *driver) DecodeTableEntry(tablename string, key string, value []byte) (string, map[string]string) { - return "", nil -} diff --git a/vendor/github.com/docker/libnetwork/drivers/macvlan/macvlan_endpoint.go b/vendor/github.com/docker/libnetwork/drivers/macvlan/macvlan_endpoint.go deleted file mode 100644 index dc3ce36543..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/macvlan/macvlan_endpoint.go +++ /dev/null @@ -1,96 +0,0 @@ -package macvlan - -import ( - "fmt" - - "github.com/docker/libnetwork/driverapi" - "github.com/docker/libnetwork/netlabel" - "github.com/docker/libnetwork/netutils" - "github.com/docker/libnetwork/ns" - "github.com/docker/libnetwork/osl" - "github.com/docker/libnetwork/types" - "github.com/sirupsen/logrus" -) - -// CreateEndpoint assigns the mac, ip and endpoint id for the new container -func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo, - epOptions map[string]interface{}) error { - defer osl.InitOSContext()() - - if err := validateID(nid, eid); err != nil { - return err - } - n, err := d.getNetwork(nid) - if err != nil { - return fmt.Errorf("network id %q not found", nid) - } - ep := &endpoint{ - id: eid, - nid: nid, - addr: ifInfo.Address(), - addrv6: ifInfo.AddressIPv6(), - mac: ifInfo.MacAddress(), - } - if ep.addr == nil { - return fmt.Errorf("create endpoint was not passed an IP address") - } - if ep.mac == nil { - ep.mac = netutils.GenerateMACFromIP(ep.addr.IP) - if err := ifInfo.SetMacAddress(ep.mac); err != nil { - return err - } - } - // disallow portmapping -p - if opt, ok := epOptions[netlabel.PortMap]; ok { - if _, ok := opt.([]types.PortBinding); ok { - if len(opt.([]types.PortBinding)) > 0 { - logrus.Warnf("%s driver does not support port mappings", macvlanType) - } - } - } - // disallow port exposure --expose - if opt, ok := epOptions[netlabel.ExposedPorts]; ok { - if _, ok := opt.([]types.TransportPort); ok { - if len(opt.([]types.TransportPort)) > 0 { - logrus.Warnf("%s driver does not support port exposures", macvlanType) - } - } - } - - if err := d.storeUpdate(ep); err != nil { - return fmt.Errorf("failed to save macvlan endpoint %.7s to store: %v", ep.id, err) - } - - n.addEndpoint(ep) - - return nil -} - -// DeleteEndpoint removes the endpoint and associated netlink interface -func (d *driver) DeleteEndpoint(nid, eid string) error { - defer osl.InitOSContext()() - if err := validateID(nid, eid); err != nil { - return err - } - n := d.network(nid) - if n == nil { - return fmt.Errorf("network id %q not found", nid) - } - ep := n.endpoint(eid) - if ep == nil { - return fmt.Errorf("endpoint id %q not found", eid) - } - if link, err := ns.NlHandle().LinkByName(ep.srcName); err == nil { - if err := ns.NlHandle().LinkDel(link); err != nil { - logrus.WithError(err).Warnf("Failed to delete interface (%s)'s link on endpoint (%s) delete", ep.srcName, ep.id) - } - } - - if err := d.storeDelete(ep); err != nil { - logrus.Warnf("Failed to remove macvlan endpoint %.7s from store: %v", ep.id, err) - } - - n.deleteEndpoint(ep.id) - - return nil -} diff --git a/vendor/github.com/docker/libnetwork/drivers/macvlan/macvlan_joinleave.go b/vendor/github.com/docker/libnetwork/drivers/macvlan/macvlan_joinleave.go deleted file mode 100644 index 0c67f5ac3f..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/macvlan/macvlan_joinleave.go +++ /dev/null @@ -1,155 +0,0 @@ -package macvlan - -import ( - "fmt" - "net" - - "github.com/docker/libnetwork/driverapi" - "github.com/docker/libnetwork/netutils" - "github.com/docker/libnetwork/ns" - "github.com/docker/libnetwork/osl" - "github.com/sirupsen/logrus" -) - -// Join method is invoked when a Sandbox is attached to an endpoint. -func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error { - defer osl.InitOSContext()() - n, err := d.getNetwork(nid) - if err != nil { - return err - } - endpoint := n.endpoint(eid) - if endpoint == nil { - return fmt.Errorf("could not find endpoint with id %s", eid) - } - // generate a name for the iface that will be renamed to eth0 in the sbox - containerIfName, err := netutils.GenerateIfaceName(ns.NlHandle(), vethPrefix, vethLen) - if err != nil { - return fmt.Errorf("error generating an interface name: %s", err) - } - // create the netlink macvlan interface - vethName, err := createMacVlan(containerIfName, n.config.Parent, n.config.MacvlanMode) - if err != nil { - return err - } - // bind the generated iface name to the endpoint - endpoint.srcName = vethName - ep := n.endpoint(eid) - if ep == nil { - return fmt.Errorf("could not find endpoint with id %s", eid) - } - // parse and match the endpoint address with the available v4 subnets - if !n.config.Internal { - if len(n.config.Ipv4Subnets) > 0 { - s := n.getSubnetforIPv4(ep.addr) - if s == nil { - return fmt.Errorf("could not find a valid ipv4 subnet for endpoint %s", eid) - } - v4gw, _, err := net.ParseCIDR(s.GwIP) - if err != nil { - return fmt.Errorf("gateway %s is not a valid ipv4 address: %v", s.GwIP, err) - } - err = jinfo.SetGateway(v4gw) - if err != nil { - return err - } - logrus.Debugf("Macvlan Endpoint Joined with IPv4_Addr: %s, Gateway: %s, MacVlan_Mode: %s, Parent: %s", - ep.addr.IP.String(), v4gw.String(), n.config.MacvlanMode, n.config.Parent) - } - // parse and match the endpoint address with the available v6 subnets - if len(n.config.Ipv6Subnets) > 0 { - s := n.getSubnetforIPv6(ep.addrv6) - if s == nil { - return fmt.Errorf("could not find a valid ipv6 subnet for endpoint %s", eid) - } - v6gw, _, err := net.ParseCIDR(s.GwIP) - if err != nil { - return fmt.Errorf("gateway %s is not a valid ipv6 address: %v", s.GwIP, err) - } - err = jinfo.SetGatewayIPv6(v6gw) - if err != nil { - return err - } - logrus.Debugf("Macvlan Endpoint Joined with IPv6_Addr: %s Gateway: %s MacVlan_Mode: %s, Parent: %s", - ep.addrv6.IP.String(), v6gw.String(), n.config.MacvlanMode, n.config.Parent) - } - } else { - if len(n.config.Ipv4Subnets) > 0 { - logrus.Debugf("Macvlan Endpoint Joined with IPv4_Addr: %s, MacVlan_Mode: %s, Parent: %s", - ep.addr.IP.String(), n.config.MacvlanMode, n.config.Parent) - } - if len(n.config.Ipv6Subnets) > 0 { - logrus.Debugf("Macvlan Endpoint Joined with IPv6_Addr: %s MacVlan_Mode: %s, Parent: %s", - ep.addrv6.IP.String(), n.config.MacvlanMode, n.config.Parent) - } - } - iNames := jinfo.InterfaceName() - err = iNames.SetNames(vethName, containerVethPrefix) - if err != nil { - return err - } - if err := d.storeUpdate(ep); err != nil { - return fmt.Errorf("failed to save macvlan endpoint %.7s to store: %v", ep.id, err) - } - return nil -} - -// Leave method is invoked when a Sandbox detaches from an endpoint. -func (d *driver) Leave(nid, eid string) error { - defer osl.InitOSContext()() - network, err := d.getNetwork(nid) - if err != nil { - return err - } - endpoint, err := network.getEndpoint(eid) - if err != nil { - return err - } - if endpoint == nil { - return fmt.Errorf("could not find endpoint with id %s", eid) - } - - return nil -} - -// getSubnetforIP returns the ipv4 subnet to which the given IP belongs -func (n *network) getSubnetforIPv4(ip *net.IPNet) *ipv4Subnet { - for _, s := range n.config.Ipv4Subnets { - _, snet, err := net.ParseCIDR(s.SubnetIP) - if err != nil { - return nil - } - // first check if the mask lengths are the same - i, _ := snet.Mask.Size() - j, _ := ip.Mask.Size() - if i != j { - continue - } - if snet.Contains(ip.IP) { - return s - } - } - - return nil -} - -// getSubnetforIPv6 returns the ipv6 subnet to which the given IP belongs -func (n *network) getSubnetforIPv6(ip *net.IPNet) *ipv6Subnet { - for _, s := range n.config.Ipv6Subnets { - _, snet, err := net.ParseCIDR(s.SubnetIP) - if err != nil { - return nil - } - // first check if the mask lengths are the same - i, _ := snet.Mask.Size() - j, _ := ip.Mask.Size() - if i != j { - continue - } - if snet.Contains(ip.IP) { - return s - } - } - - return nil -} diff --git a/vendor/github.com/docker/libnetwork/drivers/macvlan/macvlan_network.go b/vendor/github.com/docker/libnetwork/drivers/macvlan/macvlan_network.go deleted file mode 100644 index 350eb68402..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/macvlan/macvlan_network.go +++ /dev/null @@ -1,259 +0,0 @@ -package macvlan - -import ( - "fmt" - - "github.com/docker/docker/pkg/stringid" - "github.com/docker/libnetwork/driverapi" - "github.com/docker/libnetwork/netlabel" - "github.com/docker/libnetwork/ns" - "github.com/docker/libnetwork/options" - "github.com/docker/libnetwork/osl" - "github.com/docker/libnetwork/types" - "github.com/sirupsen/logrus" -) - -// CreateNetwork the network for the specified driver type -func (d *driver) CreateNetwork(nid string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error { - defer osl.InitOSContext()() - - // reject a null v4 network - if len(ipV4Data) == 0 || ipV4Data[0].Pool.String() == "0.0.0.0/0" { - return fmt.Errorf("ipv4 pool is empty") - } - // parse and validate the config and bind to networkConfiguration - config, err := parseNetworkOptions(nid, option) - if err != nil { - return err - } - config.ID = nid - err = config.processIPAM(nid, ipV4Data, ipV6Data) - if err != nil { - return err - } - // verify the macvlan mode from -o macvlan_mode option - switch config.MacvlanMode { - case "", modeBridge: - // default to macvlan bridge mode if -o macvlan_mode is empty - config.MacvlanMode = modeBridge - case modePrivate: - config.MacvlanMode = modePrivate - case modePassthru: - config.MacvlanMode = modePassthru - case modeVepa: - config.MacvlanMode = modeVepa - default: - return fmt.Errorf("requested macvlan mode '%s' is not valid, 'bridge' mode is the macvlan driver default", config.MacvlanMode) - } - // loopback is not a valid parent link - if config.Parent == "lo" { - return fmt.Errorf("loopback interface is not a valid %s parent link", macvlanType) - } - // if parent interface not specified, create a dummy type link to use named dummy+net_id - if config.Parent == "" { - config.Parent = getDummyName(stringid.TruncateID(config.ID)) - } - foundExisting, err := d.createNetwork(config) - if err != nil { - return err - } - - if foundExisting { - return types.InternalMaskableErrorf("restoring existing network %s", config.ID) - } - - // update persistent db, rollback on fail - err = d.storeUpdate(config) - if err != nil { - d.deleteNetwork(config.ID) - logrus.Debugf("encountered an error rolling back a network create for %s : %v", config.ID, err) - return err - } - - return nil -} - -// createNetwork is used by new network callbacks and persistent network cache -func (d *driver) createNetwork(config *configuration) (bool, error) { - foundExisting := false - networkList := d.getNetworks() - for _, nw := range networkList { - if config.Parent == nw.config.Parent { - if config.ID != nw.config.ID { - return false, fmt.Errorf("network %s is already using parent interface %s", - getDummyName(stringid.TruncateID(nw.config.ID)), config.Parent) - } - logrus.Debugf("Create Network for the same ID %s\n", config.ID) - foundExisting = true - break - } - } - if !parentExists(config.Parent) { - // Create a dummy link if a dummy name is set for parent - if dummyName := getDummyName(stringid.TruncateID(config.ID)); dummyName == config.Parent { - err := createDummyLink(config.Parent, dummyName) - if err != nil { - return false, err - } - config.CreatedSlaveLink = true - // notify the user in logs that they have limited communications - logrus.Debugf("Empty -o parent= limit communications to other containers inside of network: %s", - config.Parent) - } else { - // if the subinterface parent_iface.vlan_id checks do not pass, return err. - // a valid example is 'eth0.10' for a parent iface 'eth0' with a vlan id '10' - err := createVlanLink(config.Parent) - if err != nil { - return false, err - } - // if driver created the networks slave link, record it for future deletion - config.CreatedSlaveLink = true - } - } - if !foundExisting { - n := &network{ - id: config.ID, - driver: d, - endpoints: endpointTable{}, - config: config, - } - // add the network - d.addNetwork(n) - } - - return foundExisting, nil -} - -// DeleteNetwork deletes the network for the specified driver type -func (d *driver) DeleteNetwork(nid string) error { - defer osl.InitOSContext()() - n := d.network(nid) - if n == nil { - return fmt.Errorf("network id %s not found", nid) - } - // if the driver created the slave interface, delete it, otherwise leave it - if ok := n.config.CreatedSlaveLink; ok { - // if the interface exists, only delete if it matches iface.vlan or dummy.net_id naming - if ok := parentExists(n.config.Parent); ok { - // only delete the link if it is named the net_id - if n.config.Parent == getDummyName(stringid.TruncateID(nid)) { - err := delDummyLink(n.config.Parent) - if err != nil { - logrus.Debugf("link %s was not deleted, continuing the delete network operation: %v", - n.config.Parent, err) - } - } else { - // only delete the link if it matches iface.vlan naming - err := delVlanLink(n.config.Parent) - if err != nil { - logrus.Debugf("link %s was not deleted, continuing the delete network operation: %v", - n.config.Parent, err) - } - } - } - } - for _, ep := range n.endpoints { - if link, err := ns.NlHandle().LinkByName(ep.srcName); err == nil { - if err := ns.NlHandle().LinkDel(link); err != nil { - logrus.WithError(err).Warnf("Failed to delete interface (%s)'s link on endpoint (%s) delete", ep.srcName, ep.id) - } - } - - if err := d.storeDelete(ep); err != nil { - logrus.Warnf("Failed to remove macvlan endpoint %.7s from store: %v", ep.id, err) - } - } - // delete the *network - d.deleteNetwork(nid) - // delete the network record from persistent cache - err := d.storeDelete(n.config) - if err != nil { - return fmt.Errorf("error deleting deleting id %s from datastore: %v", nid, err) - } - return nil -} - -// parseNetworkOptions parses docker network options -func parseNetworkOptions(id string, option options.Generic) (*configuration, error) { - var ( - err error - config = &configuration{} - ) - // parse generic labels first - if genData, ok := option[netlabel.GenericData]; ok && genData != nil { - if config, err = parseNetworkGenericOptions(genData); err != nil { - return nil, err - } - } - if val, ok := option[netlabel.Internal]; ok { - if internal, ok := val.(bool); ok && internal { - config.Internal = true - } - } - - return config, nil -} - -// parseNetworkGenericOptions parses generic driver docker network options -func parseNetworkGenericOptions(data interface{}) (*configuration, error) { - var ( - err error - config *configuration - ) - switch opt := data.(type) { - case *configuration: - config = opt - case map[string]string: - config = &configuration{} - err = config.fromOptions(opt) - case options.Generic: - var opaqueConfig interface{} - if opaqueConfig, err = options.GenerateFromModel(opt, config); err == nil { - config = opaqueConfig.(*configuration) - } - default: - err = types.BadRequestErrorf("unrecognized network configuration format: %v", opt) - } - - return config, err -} - -// fromOptions binds the generic options to networkConfiguration to cache -func (config *configuration) fromOptions(labels map[string]string) error { - for label, value := range labels { - switch label { - case parentOpt: - // parse driver option '-o parent' - config.Parent = value - case driverModeOpt: - // parse driver option '-o macvlan_mode' - config.MacvlanMode = value - } - } - - return nil -} - -// processIPAM parses v4 and v6 IP information and binds it to the network configuration -func (config *configuration) processIPAM(id string, ipamV4Data, ipamV6Data []driverapi.IPAMData) error { - if len(ipamV4Data) > 0 { - for _, ipd := range ipamV4Data { - s := &ipv4Subnet{ - SubnetIP: ipd.Pool.String(), - GwIP: ipd.Gateway.String(), - } - config.Ipv4Subnets = append(config.Ipv4Subnets, s) - } - } - if len(ipamV6Data) > 0 { - for _, ipd := range ipamV6Data { - s := &ipv6Subnet{ - SubnetIP: ipd.Pool.String(), - GwIP: ipd.Gateway.String(), - } - config.Ipv6Subnets = append(config.Ipv6Subnets, s) - } - } - - return nil -} diff --git a/vendor/github.com/docker/libnetwork/drivers/macvlan/macvlan_setup.go b/vendor/github.com/docker/libnetwork/drivers/macvlan/macvlan_setup.go deleted file mode 100644 index 86bcca2f03..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/macvlan/macvlan_setup.go +++ /dev/null @@ -1,207 +0,0 @@ -package macvlan - -import ( - "fmt" - "strconv" - "strings" - - "github.com/docker/libnetwork/ns" - "github.com/sirupsen/logrus" - "github.com/vishvananda/netlink" -) - -const ( - dummyPrefix = "dm-" // macvlan prefix for dummy parent interface -) - -// Create the macvlan slave specifying the source name -func createMacVlan(containerIfName, parent, macvlanMode string) (string, error) { - // Set the macvlan mode. Default is bridge mode - mode, err := setMacVlanMode(macvlanMode) - if err != nil { - return "", fmt.Errorf("Unsupported %s macvlan mode: %v", macvlanMode, err) - } - // verify the Docker host interface acting as the macvlan parent iface exists - if !parentExists(parent) { - return "", fmt.Errorf("the requested parent interface %s was not found on the Docker host", parent) - } - // Get the link for the master index (Example: the docker host eth iface) - parentLink, err := ns.NlHandle().LinkByName(parent) - if err != nil { - return "", fmt.Errorf("error occurred looking up the %s parent iface %s error: %s", macvlanType, parent, err) - } - // Create a macvlan link - macvlan := &netlink.Macvlan{ - LinkAttrs: netlink.LinkAttrs{ - Name: containerIfName, - ParentIndex: parentLink.Attrs().Index, - }, - Mode: mode, - } - if err := ns.NlHandle().LinkAdd(macvlan); err != nil { - // If a user creates a macvlan and ipvlan on same parent, only one slave iface can be active at a time. - return "", fmt.Errorf("failed to create the %s port: %v", macvlanType, err) - } - - return macvlan.Attrs().Name, nil -} - -// setMacVlanMode setter for one of the four macvlan port types -func setMacVlanMode(mode string) (netlink.MacvlanMode, error) { - switch mode { - case modePrivate: - return netlink.MACVLAN_MODE_PRIVATE, nil - case modeVepa: - return netlink.MACVLAN_MODE_VEPA, nil - case modeBridge: - return netlink.MACVLAN_MODE_BRIDGE, nil - case modePassthru: - return netlink.MACVLAN_MODE_PASSTHRU, nil - default: - return 0, fmt.Errorf("unknown macvlan mode: %s", mode) - } -} - -// parentExists checks if the specified interface exists in the default namespace -func parentExists(ifaceStr string) bool { - _, err := ns.NlHandle().LinkByName(ifaceStr) - if err != nil { - return false - } - - return true -} - -// createVlanLink parses sub-interfaces and vlan id for creation -func createVlanLink(parentName string) error { - if strings.Contains(parentName, ".") { - parent, vidInt, err := parseVlan(parentName) - if err != nil { - return err - } - // VLAN identifier or VID is a 12-bit field specifying the VLAN to which the frame belongs - if vidInt > 4094 || vidInt < 1 { - return fmt.Errorf("vlan id must be between 1-4094, received: %d", vidInt) - } - // get the parent link to attach a vlan subinterface - parentLink, err := ns.NlHandle().LinkByName(parent) - if err != nil { - return fmt.Errorf("failed to find master interface %s on the Docker host: %v", parent, err) - } - vlanLink := &netlink.Vlan{ - LinkAttrs: netlink.LinkAttrs{ - Name: parentName, - ParentIndex: parentLink.Attrs().Index, - }, - VlanId: vidInt, - } - // create the subinterface - if err := ns.NlHandle().LinkAdd(vlanLink); err != nil { - return fmt.Errorf("failed to create %s vlan link: %v", vlanLink.Name, err) - } - // Bring the new netlink iface up - if err := ns.NlHandle().LinkSetUp(vlanLink); err != nil { - return fmt.Errorf("failed to enable %s the macvlan parent link %v", vlanLink.Name, err) - } - logrus.Debugf("Added a vlan tagged netlink subinterface: %s with a vlan id: %d", parentName, vidInt) - return nil - } - - return fmt.Errorf("invalid subinterface vlan name %s, example formatting is eth0.10", parentName) -} - -// delVlanLink verifies only sub-interfaces with a vlan id get deleted -func delVlanLink(linkName string) error { - if strings.Contains(linkName, ".") { - _, _, err := parseVlan(linkName) - if err != nil { - return err - } - // delete the vlan subinterface - vlanLink, err := ns.NlHandle().LinkByName(linkName) - if err != nil { - return fmt.Errorf("failed to find interface %s on the Docker host : %v", linkName, err) - } - // verify a parent interface isn't being deleted - if vlanLink.Attrs().ParentIndex == 0 { - return fmt.Errorf("interface %s does not appear to be a slave device: %v", linkName, err) - } - // delete the macvlan slave device - if err := ns.NlHandle().LinkDel(vlanLink); err != nil { - return fmt.Errorf("failed to delete %s link: %v", linkName, err) - } - logrus.Debugf("Deleted a vlan tagged netlink subinterface: %s", linkName) - } - // if the subinterface doesn't parse to iface.vlan_id leave the interface in - // place since it could be a user specified name not created by the driver. - return nil -} - -// parseVlan parses and verifies a slave interface name: -o parent=eth0.10 -func parseVlan(linkName string) (string, int, error) { - // parse -o parent=eth0.10 - splitName := strings.Split(linkName, ".") - if len(splitName) != 2 { - return "", 0, fmt.Errorf("required interface name format is: name.vlan_id, ex. eth0.10 for vlan 10, instead received %s", linkName) - } - parent, vidStr := splitName[0], splitName[1] - // validate type and convert vlan id to int - vidInt, err := strconv.Atoi(vidStr) - if err != nil { - return "", 0, fmt.Errorf("unable to parse a valid vlan id from: %s (ex. eth0.10 for vlan 10)", vidStr) - } - // Check if the interface exists - if !parentExists(parent) { - return "", 0, fmt.Errorf("-o parent interface does was not found on the host: %s", parent) - } - - return parent, vidInt, nil -} - -// createDummyLink creates a dummy0 parent link -func createDummyLink(dummyName, truncNetID string) error { - // create a parent interface since one was not specified - parent := &netlink.Dummy{ - LinkAttrs: netlink.LinkAttrs{ - Name: dummyName, - }, - } - if err := ns.NlHandle().LinkAdd(parent); err != nil { - return err - } - parentDummyLink, err := ns.NlHandle().LinkByName(dummyName) - if err != nil { - return fmt.Errorf("error occurred looking up the %s parent iface %s error: %s", macvlanType, dummyName, err) - } - // bring the new netlink iface up - if err := ns.NlHandle().LinkSetUp(parentDummyLink); err != nil { - return fmt.Errorf("failed to enable %s the macvlan parent link: %v", dummyName, err) - } - - return nil -} - -// delDummyLink deletes the link type dummy used when -o parent is not passed -func delDummyLink(linkName string) error { - // delete the vlan subinterface - dummyLink, err := ns.NlHandle().LinkByName(linkName) - if err != nil { - return fmt.Errorf("failed to find link %s on the Docker host : %v", linkName, err) - } - // verify a parent interface is being deleted - if dummyLink.Attrs().ParentIndex != 0 { - return fmt.Errorf("link %s is not a parent dummy interface", linkName) - } - // delete the macvlan dummy device - if err := ns.NlHandle().LinkDel(dummyLink); err != nil { - return fmt.Errorf("failed to delete the dummy %s link: %v", linkName, err) - } - logrus.Debugf("Deleted a dummy parent link: %s", linkName) - - return nil -} - -// getDummyName returns the name of a dummy parent with truncated net ID and driver prefix -func getDummyName(netID string) string { - return dummyPrefix + netID -} diff --git a/vendor/github.com/docker/libnetwork/drivers/macvlan/macvlan_state.go b/vendor/github.com/docker/libnetwork/drivers/macvlan/macvlan_state.go deleted file mode 100644 index 8fd1a9e4dc..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/macvlan/macvlan_state.go +++ /dev/null @@ -1,113 +0,0 @@ -package macvlan - -import ( - "fmt" - - "github.com/docker/libnetwork/osl" - "github.com/docker/libnetwork/types" - "github.com/sirupsen/logrus" -) - -func (d *driver) network(nid string) *network { - d.Lock() - n, ok := d.networks[nid] - d.Unlock() - if !ok { - logrus.Errorf("network id %s not found", nid) - } - - return n -} - -func (d *driver) addNetwork(n *network) { - d.Lock() - d.networks[n.id] = n - d.Unlock() -} - -func (d *driver) deleteNetwork(nid string) { - d.Lock() - delete(d.networks, nid) - d.Unlock() -} - -// getNetworks Safely returns a slice of existing networks -func (d *driver) getNetworks() []*network { - d.Lock() - defer d.Unlock() - - ls := make([]*network, 0, len(d.networks)) - for _, nw := range d.networks { - ls = append(ls, nw) - } - - return ls -} - -func (n *network) endpoint(eid string) *endpoint { - n.Lock() - defer n.Unlock() - - return n.endpoints[eid] -} - -func (n *network) addEndpoint(ep *endpoint) { - n.Lock() - n.endpoints[ep.id] = ep - n.Unlock() -} - -func (n *network) deleteEndpoint(eid string) { - n.Lock() - delete(n.endpoints, eid) - n.Unlock() -} - -func (n *network) getEndpoint(eid string) (*endpoint, error) { - n.Lock() - defer n.Unlock() - if eid == "" { - return nil, fmt.Errorf("endpoint id %s not found", eid) - } - if ep, ok := n.endpoints[eid]; ok { - return ep, nil - } - - return nil, nil -} - -func validateID(nid, eid string) error { - if nid == "" { - return fmt.Errorf("invalid network id") - } - if eid == "" { - return fmt.Errorf("invalid endpoint id") - } - return nil -} - -func (n *network) sandbox() osl.Sandbox { - n.Lock() - defer n.Unlock() - - return n.sbox -} - -func (n *network) setSandbox(sbox osl.Sandbox) { - n.Lock() - n.sbox = sbox - n.Unlock() -} - -func (d *driver) getNetwork(id string) (*network, error) { - d.Lock() - defer d.Unlock() - if id == "" { - return nil, types.BadRequestErrorf("invalid network id: %s", id) - } - if nw, ok := d.networks[id]; ok { - return nw, nil - } - - return nil, types.NotFoundErrorf("network not found: %s", id) -} diff --git a/vendor/github.com/docker/libnetwork/drivers/macvlan/macvlan_store.go b/vendor/github.com/docker/libnetwork/drivers/macvlan/macvlan_store.go deleted file mode 100644 index 184e3da957..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/macvlan/macvlan_store.go +++ /dev/null @@ -1,359 +0,0 @@ -package macvlan - -import ( - "encoding/json" - "fmt" - "net" - - "github.com/docker/libnetwork/datastore" - "github.com/docker/libnetwork/discoverapi" - "github.com/docker/libnetwork/netlabel" - "github.com/docker/libnetwork/types" - "github.com/sirupsen/logrus" -) - -const ( - macvlanPrefix = "macvlan" - macvlanNetworkPrefix = macvlanPrefix + "/network" - macvlanEndpointPrefix = macvlanPrefix + "/endpoint" -) - -// networkConfiguration for this driver's network specific configuration -type configuration struct { - ID string - Mtu int - dbIndex uint64 - dbExists bool - Internal bool - Parent string - MacvlanMode string - CreatedSlaveLink bool - Ipv4Subnets []*ipv4Subnet - Ipv6Subnets []*ipv6Subnet -} - -type ipv4Subnet struct { - SubnetIP string - GwIP string -} - -type ipv6Subnet struct { - SubnetIP string - GwIP string -} - -// initStore drivers are responsible for caching their own persistent state -func (d *driver) initStore(option map[string]interface{}) error { - if data, ok := option[netlabel.LocalKVClient]; ok { - var err error - dsc, ok := data.(discoverapi.DatastoreConfigData) - if !ok { - return types.InternalErrorf("incorrect data in datastore configuration: %v", data) - } - d.store, err = datastore.NewDataStoreFromConfig(dsc) - if err != nil { - return types.InternalErrorf("macvlan driver failed to initialize data store: %v", err) - } - - err = d.populateNetworks() - if err != nil { - return err - } - err = d.populateEndpoints() - if err != nil { - return err - } - - } - - return nil -} - -// populateNetworks is invoked at driver init to recreate persistently stored networks -func (d *driver) populateNetworks() error { - kvol, err := d.store.List(datastore.Key(macvlanPrefix), &configuration{}) - if err != nil && err != datastore.ErrKeyNotFound { - return fmt.Errorf("failed to get macvlan network configurations from store: %v", err) - } - // If empty it simply means no macvlan networks have been created yet - if err == datastore.ErrKeyNotFound { - return nil - } - for _, kvo := range kvol { - config := kvo.(*configuration) - if _, err = d.createNetwork(config); err != nil { - logrus.Warnf("Could not create macvlan network for id %s from persistent state", config.ID) - } - } - - return nil -} - -func (d *driver) populateEndpoints() error { - kvol, err := d.store.List(datastore.Key(macvlanEndpointPrefix), &endpoint{}) - if err != nil && err != datastore.ErrKeyNotFound { - return fmt.Errorf("failed to get macvlan endpoints from store: %v", err) - } - - if err == datastore.ErrKeyNotFound { - return nil - } - - for _, kvo := range kvol { - ep := kvo.(*endpoint) - n, ok := d.networks[ep.nid] - if !ok { - logrus.Debugf("Network (%.7s) not found for restored macvlan endpoint (%.7s)", ep.nid, ep.id) - logrus.Debugf("Deleting stale macvlan endpoint (%.7s) from store", ep.id) - if err := d.storeDelete(ep); err != nil { - logrus.Debugf("Failed to delete stale macvlan endpoint (%.7s) from store", ep.id) - } - continue - } - n.endpoints[ep.id] = ep - logrus.Debugf("Endpoint (%.7s) restored to network (%.7s)", ep.id, ep.nid) - } - - return nil -} - -// storeUpdate used to update persistent macvlan network records as they are created -func (d *driver) storeUpdate(kvObject datastore.KVObject) error { - if d.store == nil { - logrus.Warnf("macvlan store not initialized. kv object %s is not added to the store", datastore.Key(kvObject.Key()...)) - return nil - } - if err := d.store.PutObjectAtomic(kvObject); err != nil { - return fmt.Errorf("failed to update macvlan store for object type %T: %v", kvObject, err) - } - - return nil -} - -// storeDelete used to delete macvlan records from persistent cache as they are deleted -func (d *driver) storeDelete(kvObject datastore.KVObject) error { - if d.store == nil { - logrus.Debugf("macvlan store not initialized. kv object %s is not deleted from store", datastore.Key(kvObject.Key()...)) - return nil - } -retry: - if err := d.store.DeleteObjectAtomic(kvObject); err != nil { - if err == datastore.ErrKeyModified { - if err := d.store.GetObject(datastore.Key(kvObject.Key()...), kvObject); err != nil { - return fmt.Errorf("could not update the kvobject to latest when trying to delete: %v", err) - } - goto retry - } - return err - } - - return nil -} - -func (config *configuration) MarshalJSON() ([]byte, error) { - nMap := make(map[string]interface{}) - nMap["ID"] = config.ID - nMap["Mtu"] = config.Mtu - nMap["Parent"] = config.Parent - nMap["MacvlanMode"] = config.MacvlanMode - nMap["Internal"] = config.Internal - nMap["CreatedSubIface"] = config.CreatedSlaveLink - if len(config.Ipv4Subnets) > 0 { - iis, err := json.Marshal(config.Ipv4Subnets) - if err != nil { - return nil, err - } - nMap["Ipv4Subnets"] = string(iis) - } - if len(config.Ipv6Subnets) > 0 { - iis, err := json.Marshal(config.Ipv6Subnets) - if err != nil { - return nil, err - } - nMap["Ipv6Subnets"] = string(iis) - } - - return json.Marshal(nMap) -} - -func (config *configuration) UnmarshalJSON(b []byte) error { - var ( - err error - nMap map[string]interface{} - ) - - if err = json.Unmarshal(b, &nMap); err != nil { - return err - } - config.ID = nMap["ID"].(string) - config.Mtu = int(nMap["Mtu"].(float64)) - config.Parent = nMap["Parent"].(string) - config.MacvlanMode = nMap["MacvlanMode"].(string) - config.Internal = nMap["Internal"].(bool) - config.CreatedSlaveLink = nMap["CreatedSubIface"].(bool) - if v, ok := nMap["Ipv4Subnets"]; ok { - if err := json.Unmarshal([]byte(v.(string)), &config.Ipv4Subnets); err != nil { - return err - } - } - if v, ok := nMap["Ipv6Subnets"]; ok { - if err := json.Unmarshal([]byte(v.(string)), &config.Ipv6Subnets); err != nil { - return err - } - } - - return nil -} - -func (config *configuration) Key() []string { - return []string{macvlanNetworkPrefix, config.ID} -} - -func (config *configuration) KeyPrefix() []string { - return []string{macvlanNetworkPrefix} -} - -func (config *configuration) Value() []byte { - b, err := json.Marshal(config) - if err != nil { - return nil - } - - return b -} - -func (config *configuration) SetValue(value []byte) error { - return json.Unmarshal(value, config) -} - -func (config *configuration) Index() uint64 { - return config.dbIndex -} - -func (config *configuration) SetIndex(index uint64) { - config.dbIndex = index - config.dbExists = true -} - -func (config *configuration) Exists() bool { - return config.dbExists -} - -func (config *configuration) Skip() bool { - return false -} - -func (config *configuration) New() datastore.KVObject { - return &configuration{} -} - -func (config *configuration) CopyTo(o datastore.KVObject) error { - dstNcfg := o.(*configuration) - *dstNcfg = *config - - return nil -} - -func (config *configuration) DataScope() string { - return datastore.LocalScope -} - -func (ep *endpoint) MarshalJSON() ([]byte, error) { - epMap := make(map[string]interface{}) - epMap["id"] = ep.id - epMap["nid"] = ep.nid - epMap["SrcName"] = ep.srcName - if len(ep.mac) != 0 { - epMap["MacAddress"] = ep.mac.String() - } - if ep.addr != nil { - epMap["Addr"] = ep.addr.String() - } - if ep.addrv6 != nil { - epMap["Addrv6"] = ep.addrv6.String() - } - return json.Marshal(epMap) -} - -func (ep *endpoint) UnmarshalJSON(b []byte) error { - var ( - err error - epMap map[string]interface{} - ) - - if err = json.Unmarshal(b, &epMap); err != nil { - return fmt.Errorf("Failed to unmarshal to macvlan endpoint: %v", err) - } - - if v, ok := epMap["MacAddress"]; ok { - if ep.mac, err = net.ParseMAC(v.(string)); err != nil { - return types.InternalErrorf("failed to decode macvlan endpoint MAC address (%s) after json unmarshal: %v", v.(string), err) - } - } - if v, ok := epMap["Addr"]; ok { - if ep.addr, err = types.ParseCIDR(v.(string)); err != nil { - return types.InternalErrorf("failed to decode macvlan endpoint IPv4 address (%s) after json unmarshal: %v", v.(string), err) - } - } - if v, ok := epMap["Addrv6"]; ok { - if ep.addrv6, err = types.ParseCIDR(v.(string)); err != nil { - return types.InternalErrorf("failed to decode macvlan endpoint IPv6 address (%s) after json unmarshal: %v", v.(string), err) - } - } - ep.id = epMap["id"].(string) - ep.nid = epMap["nid"].(string) - ep.srcName = epMap["SrcName"].(string) - - return nil -} - -func (ep *endpoint) Key() []string { - return []string{macvlanEndpointPrefix, ep.id} -} - -func (ep *endpoint) KeyPrefix() []string { - return []string{macvlanEndpointPrefix} -} - -func (ep *endpoint) Value() []byte { - b, err := json.Marshal(ep) - if err != nil { - return nil - } - return b -} - -func (ep *endpoint) SetValue(value []byte) error { - return json.Unmarshal(value, ep) -} - -func (ep *endpoint) Index() uint64 { - return ep.dbIndex -} - -func (ep *endpoint) SetIndex(index uint64) { - ep.dbIndex = index - ep.dbExists = true -} - -func (ep *endpoint) Exists() bool { - return ep.dbExists -} - -func (ep *endpoint) Skip() bool { - return false -} - -func (ep *endpoint) New() datastore.KVObject { - return &endpoint{} -} - -func (ep *endpoint) CopyTo(o datastore.KVObject) error { - dstEp := o.(*endpoint) - *dstEp = *ep - return nil -} - -func (ep *endpoint) DataScope() string { - return datastore.LocalScope -} diff --git a/vendor/github.com/docker/libnetwork/drivers/macvlan/mvmanager/mvmanager.go b/vendor/github.com/docker/libnetwork/drivers/macvlan/mvmanager/mvmanager.go deleted file mode 100644 index 0f811ac36f..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/macvlan/mvmanager/mvmanager.go +++ /dev/null @@ -1,88 +0,0 @@ -package mvmanager - -import ( - "github.com/docker/libnetwork/datastore" - "github.com/docker/libnetwork/discoverapi" - "github.com/docker/libnetwork/driverapi" - "github.com/docker/libnetwork/types" -) - -const networkType = "macvlan" - -type driver struct{} - -// Init registers a new instance of macvlan manager driver -func Init(dc driverapi.DriverCallback, config map[string]interface{}) error { - c := driverapi.Capability{ - DataScope: datastore.LocalScope, - ConnectivityScope: datastore.GlobalScope, - } - return dc.RegisterDriver(networkType, &driver{}, c) -} - -func (d *driver) NetworkAllocate(id string, option map[string]string, ipV4Data, ipV6Data []driverapi.IPAMData) (map[string]string, error) { - return nil, types.NotImplementedErrorf("not implemented") -} - -func (d *driver) NetworkFree(id string) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) CreateNetwork(id string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) EventNotify(etype driverapi.EventType, nid, tableName, key string, value []byte) { -} - -func (d *driver) DecodeTableEntry(tablename string, key string, value []byte) (string, map[string]string) { - return "", nil -} - -func (d *driver) DeleteNetwork(nid string) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo, epOptions map[string]interface{}) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) DeleteEndpoint(nid, eid string) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) EndpointOperInfo(nid, eid string) (map[string]interface{}, error) { - return nil, types.NotImplementedErrorf("not implemented") -} - -func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) Leave(nid, eid string) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) Type() string { - return networkType -} - -func (d *driver) IsBuiltIn() bool { - return true -} - -func (d *driver) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) DiscoverDelete(dType discoverapi.DiscoveryType, data interface{}) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) ProgramExternalConnectivity(nid, eid string, options map[string]interface{}) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) RevokeExternalConnectivity(nid, eid string) error { - return types.NotImplementedErrorf("not implemented") -} diff --git a/vendor/github.com/docker/libnetwork/drivers/null/null.go b/vendor/github.com/docker/libnetwork/drivers/null/null.go deleted file mode 100644 index 7f2a5e32f7..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/null/null.go +++ /dev/null @@ -1,105 +0,0 @@ -package null - -import ( - "sync" - - "github.com/docker/libnetwork/datastore" - "github.com/docker/libnetwork/discoverapi" - "github.com/docker/libnetwork/driverapi" - "github.com/docker/libnetwork/types" -) - -const networkType = "null" - -type driver struct { - network string - sync.Mutex -} - -// Init registers a new instance of null driver -func Init(dc driverapi.DriverCallback, config map[string]interface{}) error { - c := driverapi.Capability{ - DataScope: datastore.LocalScope, - } - return dc.RegisterDriver(networkType, &driver{}, c) -} - -func (d *driver) NetworkAllocate(id string, option map[string]string, ipV4Data, ipV6Data []driverapi.IPAMData) (map[string]string, error) { - return nil, types.NotImplementedErrorf("not implemented") -} - -func (d *driver) NetworkFree(id string) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) EventNotify(etype driverapi.EventType, nid, tableName, key string, value []byte) { -} - -func (d *driver) DecodeTableEntry(tablename string, key string, value []byte) (string, map[string]string) { - return "", nil -} - -func (d *driver) CreateNetwork(id string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error { - d.Lock() - defer d.Unlock() - - if d.network != "" { - return types.ForbiddenErrorf("only one instance of \"%s\" network is allowed", networkType) - } - - d.network = id - - return nil -} - -func (d *driver) DeleteNetwork(nid string) error { - return types.ForbiddenErrorf("network of type \"%s\" cannot be deleted", networkType) -} - -func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo, epOptions map[string]interface{}) error { - return nil -} - -func (d *driver) DeleteEndpoint(nid, eid string) error { - return nil -} - -func (d *driver) EndpointOperInfo(nid, eid string) (map[string]interface{}, error) { - return make(map[string]interface{}, 0), nil -} - -// Join method is invoked when a Sandbox is attached to an endpoint. -func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error { - return nil -} - -// Leave method is invoked when a Sandbox detaches from an endpoint. -func (d *driver) Leave(nid, eid string) error { - return nil -} - -func (d *driver) ProgramExternalConnectivity(nid, eid string, options map[string]interface{}) error { - return nil -} - -func (d *driver) RevokeExternalConnectivity(nid, eid string) error { - return nil -} - -func (d *driver) Type() string { - return networkType -} - -func (d *driver) IsBuiltIn() bool { - return true -} - -// DiscoverNew is a notification for a new discovery event, such as a new node joining a cluster -func (d *driver) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error { - return nil -} - -// DiscoverDelete is a notification for a discovery delete event, such as a node leaving a cluster -func (d *driver) DiscoverDelete(dType discoverapi.DiscoveryType, data interface{}) error { - return nil -} diff --git a/vendor/github.com/docker/libnetwork/drivers/overlay/encryption.go b/vendor/github.com/docker/libnetwork/drivers/overlay/encryption.go deleted file mode 100644 index aafd9c0b5e..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/overlay/encryption.go +++ /dev/null @@ -1,646 +0,0 @@ -package overlay - -import ( - "bytes" - "encoding/binary" - "encoding/hex" - "fmt" - "hash/fnv" - "net" - "sync" - "syscall" - - "strconv" - - "github.com/docker/libnetwork/drivers/overlay/overlayutils" - "github.com/docker/libnetwork/iptables" - "github.com/docker/libnetwork/ns" - "github.com/docker/libnetwork/types" - "github.com/sirupsen/logrus" - "github.com/vishvananda/netlink" -) - -const ( - r = 0xD0C4E3 - pktExpansion = 26 // SPI(4) + SeqN(4) + IV(8) + PadLength(1) + NextHeader(1) + ICV(8) -) - -const ( - forward = iota + 1 - reverse - bidir -) - -var spMark = netlink.XfrmMark{Value: uint32(r), Mask: 0xffffffff} - -type key struct { - value []byte - tag uint32 -} - -func (k *key) String() string { - if k != nil { - return fmt.Sprintf("(key: %s, tag: 0x%x)", hex.EncodeToString(k.value)[0:5], k.tag) - } - return "" -} - -type spi struct { - forward int - reverse int -} - -func (s *spi) String() string { - return fmt.Sprintf("SPI(FWD: 0x%x, REV: 0x%x)", uint32(s.forward), uint32(s.reverse)) -} - -type encrMap struct { - nodes map[string][]*spi - sync.Mutex -} - -func (e *encrMap) String() string { - e.Lock() - defer e.Unlock() - b := new(bytes.Buffer) - for k, v := range e.nodes { - b.WriteString("\n") - b.WriteString(k) - b.WriteString(":") - b.WriteString("[") - for _, s := range v { - b.WriteString(s.String()) - b.WriteString(",") - } - b.WriteString("]") - - } - return b.String() -} - -func (d *driver) checkEncryption(nid string, rIP net.IP, vxlanID uint32, isLocal, add bool) error { - logrus.Debugf("checkEncryption(%.7s, %v, %d, %t)", nid, rIP, vxlanID, isLocal) - - n := d.network(nid) - if n == nil || !n.secure { - return nil - } - - if len(d.keys) == 0 { - return types.ForbiddenErrorf("encryption key is not present") - } - - lIP := net.ParseIP(d.bindAddress) - aIP := net.ParseIP(d.advertiseAddress) - nodes := map[string]net.IP{} - - switch { - case isLocal: - if err := d.peerDbNetworkWalk(nid, func(pKey *peerKey, pEntry *peerEntry) bool { - if !aIP.Equal(pEntry.vtep) { - nodes[pEntry.vtep.String()] = pEntry.vtep - } - return false - }); err != nil { - logrus.Warnf("Failed to retrieve list of participating nodes in overlay network %.5s: %v", nid, err) - } - default: - if len(d.network(nid).endpoints) > 0 { - nodes[rIP.String()] = rIP - } - } - - logrus.Debugf("List of nodes: %s", nodes) - - if add { - for _, rIP := range nodes { - if err := setupEncryption(lIP, aIP, rIP, vxlanID, d.secMap, d.keys); err != nil { - logrus.Warnf("Failed to program network encryption between %s and %s: %v", lIP, rIP, err) - } - } - } else { - if len(nodes) == 0 { - if err := removeEncryption(lIP, rIP, d.secMap); err != nil { - logrus.Warnf("Failed to remove network encryption between %s and %s: %v", lIP, rIP, err) - } - } - } - - return nil -} - -func setupEncryption(localIP, advIP, remoteIP net.IP, vni uint32, em *encrMap, keys []*key) error { - logrus.Debugf("Programming encryption for vxlan %d between %s and %s", vni, localIP, remoteIP) - rIPs := remoteIP.String() - - indices := make([]*spi, 0, len(keys)) - - err := programMangle(vni, true) - if err != nil { - logrus.Warn(err) - } - - err = programInput(vni, true) - if err != nil { - logrus.Warn(err) - } - - for i, k := range keys { - spis := &spi{buildSPI(advIP, remoteIP, k.tag), buildSPI(remoteIP, advIP, k.tag)} - dir := reverse - if i == 0 { - dir = bidir - } - fSA, rSA, err := programSA(localIP, remoteIP, spis, k, dir, true) - if err != nil { - logrus.Warn(err) - } - indices = append(indices, spis) - if i != 0 { - continue - } - err = programSP(fSA, rSA, true) - if err != nil { - logrus.Warn(err) - } - } - - em.Lock() - em.nodes[rIPs] = indices - em.Unlock() - - return nil -} - -func removeEncryption(localIP, remoteIP net.IP, em *encrMap) error { - em.Lock() - indices, ok := em.nodes[remoteIP.String()] - em.Unlock() - if !ok { - return nil - } - for i, idxs := range indices { - dir := reverse - if i == 0 { - dir = bidir - } - fSA, rSA, err := programSA(localIP, remoteIP, idxs, nil, dir, false) - if err != nil { - logrus.Warn(err) - } - if i != 0 { - continue - } - err = programSP(fSA, rSA, false) - if err != nil { - logrus.Warn(err) - } - } - return nil -} - -func programMangle(vni uint32, add bool) (err error) { - var ( - p = strconv.FormatUint(uint64(overlayutils.VXLANUDPPort()), 10) - c = fmt.Sprintf("0>>22&0x3C@12&0xFFFFFF00=%d", int(vni)<<8) - m = strconv.FormatUint(uint64(r), 10) - chain = "OUTPUT" - rule = []string{"-p", "udp", "--dport", p, "-m", "u32", "--u32", c, "-j", "MARK", "--set-mark", m} - a = "-A" - action = "install" - ) - - // TODO IPv6 support - iptable := iptables.GetIptable(iptables.IPv4) - - if add == iptable.Exists(iptables.Mangle, chain, rule...) { - return - } - - if !add { - a = "-D" - action = "remove" - } - - if err = iptable.RawCombinedOutput(append([]string{"-t", string(iptables.Mangle), a, chain}, rule...)...); err != nil { - logrus.Warnf("could not %s mangle rule: %v", action, err) - } - - return -} - -func programInput(vni uint32, add bool) (err error) { - var ( - port = strconv.FormatUint(uint64(overlayutils.VXLANUDPPort()), 10) - vniMatch = fmt.Sprintf("0>>22&0x3C@12&0xFFFFFF00=%d", int(vni)<<8) - plainVxlan = []string{"-p", "udp", "--dport", port, "-m", "u32", "--u32", vniMatch, "-j"} - ipsecVxlan = append([]string{"-m", "policy", "--dir", "in", "--pol", "ipsec"}, plainVxlan...) - block = append(plainVxlan, "DROP") - accept = append(ipsecVxlan, "ACCEPT") - chain = "INPUT" - action = iptables.Append - msg = "add" - ) - - // TODO IPv6 support - iptable := iptables.GetIptable(iptables.IPv4) - - if !add { - action = iptables.Delete - msg = "remove" - } - - if err := iptable.ProgramRule(iptables.Filter, chain, action, accept); err != nil { - logrus.Errorf("could not %s input rule: %v. Please do it manually.", msg, err) - } - - if err := iptable.ProgramRule(iptables.Filter, chain, action, block); err != nil { - logrus.Errorf("could not %s input rule: %v. Please do it manually.", msg, err) - } - - return -} - -func programSA(localIP, remoteIP net.IP, spi *spi, k *key, dir int, add bool) (fSA *netlink.XfrmState, rSA *netlink.XfrmState, err error) { - var ( - action = "Removing" - xfrmProgram = ns.NlHandle().XfrmStateDel - ) - - if add { - action = "Adding" - xfrmProgram = ns.NlHandle().XfrmStateAdd - } - - if dir&reverse > 0 { - rSA = &netlink.XfrmState{ - Src: remoteIP, - Dst: localIP, - Proto: netlink.XFRM_PROTO_ESP, - Spi: spi.reverse, - Mode: netlink.XFRM_MODE_TRANSPORT, - Reqid: r, - } - if add { - rSA.Aead = buildAeadAlgo(k, spi.reverse) - } - - exists, err := saExists(rSA) - if err != nil { - exists = !add - } - - if add != exists { - logrus.Debugf("%s: rSA{%s}", action, rSA) - if err := xfrmProgram(rSA); err != nil { - logrus.Warnf("Failed %s rSA{%s}: %v", action, rSA, err) - } - } - } - - if dir&forward > 0 { - fSA = &netlink.XfrmState{ - Src: localIP, - Dst: remoteIP, - Proto: netlink.XFRM_PROTO_ESP, - Spi: spi.forward, - Mode: netlink.XFRM_MODE_TRANSPORT, - Reqid: r, - } - if add { - fSA.Aead = buildAeadAlgo(k, spi.forward) - } - - exists, err := saExists(fSA) - if err != nil { - exists = !add - } - - if add != exists { - logrus.Debugf("%s fSA{%s}", action, fSA) - if err := xfrmProgram(fSA); err != nil { - logrus.Warnf("Failed %s fSA{%s}: %v.", action, fSA, err) - } - } - } - - return -} - -func programSP(fSA *netlink.XfrmState, rSA *netlink.XfrmState, add bool) error { - action := "Removing" - xfrmProgram := ns.NlHandle().XfrmPolicyDel - if add { - action = "Adding" - xfrmProgram = ns.NlHandle().XfrmPolicyAdd - } - - // Create a congruent cidr - s := types.GetMinimalIP(fSA.Src) - d := types.GetMinimalIP(fSA.Dst) - fullMask := net.CIDRMask(8*len(s), 8*len(s)) - - fPol := &netlink.XfrmPolicy{ - Src: &net.IPNet{IP: s, Mask: fullMask}, - Dst: &net.IPNet{IP: d, Mask: fullMask}, - Dir: netlink.XFRM_DIR_OUT, - Proto: 17, - DstPort: 4789, - Mark: &spMark, - Tmpls: []netlink.XfrmPolicyTmpl{ - { - Src: fSA.Src, - Dst: fSA.Dst, - Proto: netlink.XFRM_PROTO_ESP, - Mode: netlink.XFRM_MODE_TRANSPORT, - Spi: fSA.Spi, - Reqid: r, - }, - }, - } - - exists, err := spExists(fPol) - if err != nil { - exists = !add - } - - if add != exists { - logrus.Debugf("%s fSP{%s}", action, fPol) - if err := xfrmProgram(fPol); err != nil { - logrus.Warnf("%s fSP{%s}: %v", action, fPol, err) - } - } - - return nil -} - -func saExists(sa *netlink.XfrmState) (bool, error) { - _, err := ns.NlHandle().XfrmStateGet(sa) - switch err { - case nil: - return true, nil - case syscall.ESRCH: - return false, nil - default: - err = fmt.Errorf("Error while checking for SA existence: %v", err) - logrus.Warn(err) - return false, err - } -} - -func spExists(sp *netlink.XfrmPolicy) (bool, error) { - _, err := ns.NlHandle().XfrmPolicyGet(sp) - switch err { - case nil: - return true, nil - case syscall.ENOENT: - return false, nil - default: - err = fmt.Errorf("Error while checking for SP existence: %v", err) - logrus.Warn(err) - return false, err - } -} - -func buildSPI(src, dst net.IP, st uint32) int { - b := make([]byte, 4) - binary.BigEndian.PutUint32(b, st) - h := fnv.New32a() - h.Write(src) - h.Write(b) - h.Write(dst) - return int(binary.BigEndian.Uint32(h.Sum(nil))) -} - -func buildAeadAlgo(k *key, s int) *netlink.XfrmStateAlgo { - salt := make([]byte, 4) - binary.BigEndian.PutUint32(salt, uint32(s)) - return &netlink.XfrmStateAlgo{ - Name: "rfc4106(gcm(aes))", - Key: append(k.value, salt...), - ICVLen: 64, - } -} - -func (d *driver) secMapWalk(f func(string, []*spi) ([]*spi, bool)) error { - d.secMap.Lock() - for node, indices := range d.secMap.nodes { - idxs, stop := f(node, indices) - if idxs != nil { - d.secMap.nodes[node] = idxs - } - if stop { - break - } - } - d.secMap.Unlock() - return nil -} - -func (d *driver) setKeys(keys []*key) error { - // Remove any stale policy, state - clearEncryptionStates() - // Accept the encryption keys and clear any stale encryption map - d.Lock() - d.keys = keys - d.secMap = &encrMap{nodes: map[string][]*spi{}} - d.Unlock() - logrus.Debugf("Initial encryption keys: %v", keys) - return nil -} - -// updateKeys allows to add a new key and/or change the primary key and/or prune an existing key -// The primary key is the key used in transmission and will go in first position in the list. -func (d *driver) updateKeys(newKey, primary, pruneKey *key) error { - logrus.Debugf("Updating Keys. New: %v, Primary: %v, Pruned: %v", newKey, primary, pruneKey) - - logrus.Debugf("Current: %v", d.keys) - - var ( - newIdx = -1 - priIdx = -1 - delIdx = -1 - lIP = net.ParseIP(d.bindAddress) - aIP = net.ParseIP(d.advertiseAddress) - ) - - d.Lock() - defer d.Unlock() - - // add new - if newKey != nil { - d.keys = append(d.keys, newKey) - newIdx += len(d.keys) - } - for i, k := range d.keys { - if primary != nil && k.tag == primary.tag { - priIdx = i - } - if pruneKey != nil && k.tag == pruneKey.tag { - delIdx = i - } - } - - if (newKey != nil && newIdx == -1) || - (primary != nil && priIdx == -1) || - (pruneKey != nil && delIdx == -1) { - return types.BadRequestErrorf("cannot find proper key indices while processing key update:"+ - "(newIdx,priIdx,delIdx):(%d, %d, %d)", newIdx, priIdx, delIdx) - } - - if priIdx != -1 && priIdx == delIdx { - return types.BadRequestErrorf("attempting to both make a key (index %d) primary and delete it", priIdx) - } - - d.secMapWalk(func(rIPs string, spis []*spi) ([]*spi, bool) { - rIP := net.ParseIP(rIPs) - return updateNodeKey(lIP, aIP, rIP, spis, d.keys, newIdx, priIdx, delIdx), false - }) - - // swap primary - if priIdx != -1 { - d.keys[0], d.keys[priIdx] = d.keys[priIdx], d.keys[0] - } - // prune - if delIdx != -1 { - if delIdx == 0 { - delIdx = priIdx - } - d.keys = append(d.keys[:delIdx], d.keys[delIdx+1:]...) - } - - logrus.Debugf("Updated: %v", d.keys) - - return nil -} - -/******************************************************** - * Steady state: rSA0, rSA1, rSA2, fSA1, fSP1 - * Rotation --> -rSA0, +rSA3, +fSA2, +fSP2/-fSP1, -fSA1 - * Steady state: rSA1, rSA2, rSA3, fSA2, fSP2 - *********************************************************/ - -// Spis and keys are sorted in such away the one in position 0 is the primary -func updateNodeKey(lIP, aIP, rIP net.IP, idxs []*spi, curKeys []*key, newIdx, priIdx, delIdx int) []*spi { - logrus.Debugf("Updating keys for node: %s (%d,%d,%d)", rIP, newIdx, priIdx, delIdx) - - spis := idxs - logrus.Debugf("Current: %v", spis) - - // add new - if newIdx != -1 { - spis = append(spis, &spi{ - forward: buildSPI(aIP, rIP, curKeys[newIdx].tag), - reverse: buildSPI(rIP, aIP, curKeys[newIdx].tag), - }) - } - - if delIdx != -1 { - // -rSA0 - programSA(lIP, rIP, spis[delIdx], nil, reverse, false) - } - - if newIdx > -1 { - // +rSA2 - programSA(lIP, rIP, spis[newIdx], curKeys[newIdx], reverse, true) - } - - if priIdx > 0 { - // +fSA2 - fSA2, _, _ := programSA(lIP, rIP, spis[priIdx], curKeys[priIdx], forward, true) - - // +fSP2, -fSP1 - s := types.GetMinimalIP(fSA2.Src) - d := types.GetMinimalIP(fSA2.Dst) - fullMask := net.CIDRMask(8*len(s), 8*len(s)) - - fSP1 := &netlink.XfrmPolicy{ - Src: &net.IPNet{IP: s, Mask: fullMask}, - Dst: &net.IPNet{IP: d, Mask: fullMask}, - Dir: netlink.XFRM_DIR_OUT, - Proto: 17, - DstPort: 4789, - Mark: &spMark, - Tmpls: []netlink.XfrmPolicyTmpl{ - { - Src: fSA2.Src, - Dst: fSA2.Dst, - Proto: netlink.XFRM_PROTO_ESP, - Mode: netlink.XFRM_MODE_TRANSPORT, - Spi: fSA2.Spi, - Reqid: r, - }, - }, - } - logrus.Debugf("Updating fSP{%s}", fSP1) - if err := ns.NlHandle().XfrmPolicyUpdate(fSP1); err != nil { - logrus.Warnf("Failed to update fSP{%s}: %v", fSP1, err) - } - - // -fSA1 - programSA(lIP, rIP, spis[0], nil, forward, false) - } - - // swap - if priIdx > 0 { - swp := spis[0] - spis[0] = spis[priIdx] - spis[priIdx] = swp - } - // prune - if delIdx != -1 { - if delIdx == 0 { - delIdx = priIdx - } - spis = append(spis[:delIdx], spis[delIdx+1:]...) - } - - logrus.Debugf("Updated: %v", spis) - - return spis -} - -func (n *network) maxMTU() int { - mtu := 1500 - if n.mtu != 0 { - mtu = n.mtu - } - mtu -= vxlanEncap - if n.secure { - // In case of encryption account for the - // esp packet expansion and padding - mtu -= pktExpansion - mtu -= (mtu % 4) - } - return mtu -} - -func clearEncryptionStates() { - nlh := ns.NlHandle() - spList, err := nlh.XfrmPolicyList(netlink.FAMILY_ALL) - if err != nil { - logrus.Warnf("Failed to retrieve SP list for cleanup: %v", err) - } - saList, err := nlh.XfrmStateList(netlink.FAMILY_ALL) - if err != nil { - logrus.Warnf("Failed to retrieve SA list for cleanup: %v", err) - } - for _, sp := range spList { - if sp.Mark != nil && sp.Mark.Value == spMark.Value { - if err := nlh.XfrmPolicyDel(&sp); err != nil { - logrus.Warnf("Failed to delete stale SP %s: %v", sp, err) - continue - } - logrus.Debugf("Removed stale SP: %s", sp) - } - } - for _, sa := range saList { - if sa.Reqid == r { - if err := nlh.XfrmStateDel(&sa); err != nil { - logrus.Warnf("Failed to delete stale SA %s: %v", sa, err) - continue - } - logrus.Debugf("Removed stale SA: %s", sa) - } - } -} diff --git a/vendor/github.com/docker/libnetwork/drivers/overlay/filter.go b/vendor/github.com/docker/libnetwork/drivers/overlay/filter.go deleted file mode 100644 index 853afc6a80..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/overlay/filter.go +++ /dev/null @@ -1,150 +0,0 @@ -package overlay - -import ( - "fmt" - "sync" - - "github.com/docker/libnetwork/iptables" - "github.com/sirupsen/logrus" -) - -const globalChain = "DOCKER-OVERLAY" - -var filterOnce sync.Once - -var filterChan = make(chan struct{}, 1) - -func filterWait() func() { - filterChan <- struct{}{} - return func() { <-filterChan } -} - -func chainExists(cname string) bool { - // TODO IPv6 support - iptable := iptables.GetIptable(iptables.IPv4) - if _, err := iptable.Raw("-L", cname); err != nil { - return false - } - - return true -} - -func setupGlobalChain() { - // TODO IPv6 support - iptable := iptables.GetIptable(iptables.IPv4) - // Because of an ungraceful shutdown, chain could already be present - if !chainExists(globalChain) { - if err := iptable.RawCombinedOutput("-N", globalChain); err != nil { - logrus.Errorf("could not create global overlay chain: %v", err) - return - } - } - - if !iptable.Exists(iptables.Filter, globalChain, "-j", "RETURN") { - if err := iptable.RawCombinedOutput("-A", globalChain, "-j", "RETURN"); err != nil { - logrus.Errorf("could not install default return chain in the overlay global chain: %v", err) - } - } -} - -func setNetworkChain(cname string, remove bool) error { - // TODO IPv6 support - iptable := iptables.GetIptable(iptables.IPv4) - // Initialize the onetime global overlay chain - filterOnce.Do(setupGlobalChain) - - exists := chainExists(cname) - - opt := "-N" - // In case of remove, make sure to flush the rules in the chain - if remove && exists { - if err := iptable.RawCombinedOutput("-F", cname); err != nil { - return fmt.Errorf("failed to flush overlay network chain %s rules: %v", cname, err) - } - opt = "-X" - } - - if (!remove && !exists) || (remove && exists) { - if err := iptable.RawCombinedOutput(opt, cname); err != nil { - return fmt.Errorf("failed network chain operation %q for chain %s: %v", opt, cname, err) - } - } - - if !remove { - if !iptable.Exists(iptables.Filter, cname, "-j", "DROP") { - if err := iptable.RawCombinedOutput("-A", cname, "-j", "DROP"); err != nil { - return fmt.Errorf("failed adding default drop rule to overlay network chain %s: %v", cname, err) - } - } - } - - return nil -} - -func addNetworkChain(cname string) error { - defer filterWait()() - - return setNetworkChain(cname, false) -} - -func removeNetworkChain(cname string) error { - defer filterWait()() - - return setNetworkChain(cname, true) -} - -func setFilters(cname, brName string, remove bool) error { - opt := "-I" - if remove { - opt = "-D" - } - // TODO IPv6 support - iptable := iptables.GetIptable(iptables.IPv4) - - // Every time we set filters for a new subnet make sure to move the global overlay hook to the top of the both the OUTPUT and forward chains - if !remove { - for _, chain := range []string{"OUTPUT", "FORWARD"} { - exists := iptable.Exists(iptables.Filter, chain, "-j", globalChain) - if exists { - if err := iptable.RawCombinedOutput("-D", chain, "-j", globalChain); err != nil { - return fmt.Errorf("failed to delete overlay hook in chain %s while moving the hook: %v", chain, err) - } - } - - if err := iptable.RawCombinedOutput("-I", chain, "-j", globalChain); err != nil { - return fmt.Errorf("failed to insert overlay hook in chain %s: %v", chain, err) - } - } - } - - // Insert/Delete the rule to jump to per-bridge chain - exists := iptable.Exists(iptables.Filter, globalChain, "-o", brName, "-j", cname) - if (!remove && !exists) || (remove && exists) { - if err := iptable.RawCombinedOutput(opt, globalChain, "-o", brName, "-j", cname); err != nil { - return fmt.Errorf("failed to add per-bridge filter rule for bridge %s, network chain %s: %v", brName, cname, err) - } - } - - exists = iptable.Exists(iptables.Filter, cname, "-i", brName, "-j", "ACCEPT") - if (!remove && exists) || (remove && !exists) { - return nil - } - - if err := iptable.RawCombinedOutput(opt, cname, "-i", brName, "-j", "ACCEPT"); err != nil { - return fmt.Errorf("failed to add overlay filter rile for network chain %s, bridge %s: %v", cname, brName, err) - } - - return nil -} - -func addFilters(cname, brName string) error { - defer filterWait()() - - return setFilters(cname, brName, false) -} - -func removeFilters(cname, brName string) error { - defer filterWait()() - - return setFilters(cname, brName, true) -} diff --git a/vendor/github.com/docker/libnetwork/drivers/overlay/joinleave.go b/vendor/github.com/docker/libnetwork/drivers/overlay/joinleave.go deleted file mode 100644 index a51bcd8985..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/overlay/joinleave.go +++ /dev/null @@ -1,232 +0,0 @@ -package overlay - -import ( - "fmt" - "net" - "syscall" - - "github.com/docker/libnetwork/driverapi" - "github.com/docker/libnetwork/ns" - "github.com/docker/libnetwork/types" - "github.com/gogo/protobuf/proto" - "github.com/sirupsen/logrus" -) - -// Join method is invoked when a Sandbox is attached to an endpoint. -func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error { - if err := validateID(nid, eid); err != nil { - return err - } - - n := d.network(nid) - if n == nil { - return fmt.Errorf("could not find network with id %s", nid) - } - - ep := n.endpoint(eid) - if ep == nil { - return fmt.Errorf("could not find endpoint with id %s", eid) - } - - if n.secure && len(d.keys) == 0 { - return fmt.Errorf("cannot join secure network: encryption keys not present") - } - - nlh := ns.NlHandle() - - if n.secure && !nlh.SupportsNetlinkFamily(syscall.NETLINK_XFRM) { - return fmt.Errorf("cannot join secure network: required modules to install IPSEC rules are missing on host") - } - - s := n.getSubnetforIP(ep.addr) - if s == nil { - return fmt.Errorf("could not find subnet for endpoint %s", eid) - } - - if err := n.obtainVxlanID(s); err != nil { - return fmt.Errorf("couldn't get vxlan id for %q: %v", s.subnetIP.String(), err) - } - - if err := n.joinSandbox(s, false, true); err != nil { - return fmt.Errorf("network sandbox join failed: %v", err) - } - - sbox := n.sandbox() - - overlayIfName, containerIfName, err := createVethPair() - if err != nil { - return err - } - - ep.ifName = containerIfName - - if err = d.writeEndpointToStore(ep); err != nil { - return fmt.Errorf("failed to update overlay endpoint %.7s to local data store: %v", ep.id, err) - } - - // Set the container interface and its peer MTU to 1450 to allow - // for 50 bytes vxlan encap (inner eth header(14) + outer IP(20) + - // outer UDP(8) + vxlan header(8)) - mtu := n.maxMTU() - - veth, err := nlh.LinkByName(overlayIfName) - if err != nil { - return fmt.Errorf("cound not find link by name %s: %v", overlayIfName, err) - } - err = nlh.LinkSetMTU(veth, mtu) - if err != nil { - return err - } - - if err = sbox.AddInterface(overlayIfName, "veth", - sbox.InterfaceOptions().Master(s.brName)); err != nil { - return fmt.Errorf("could not add veth pair inside the network sandbox: %v", err) - } - - veth, err = nlh.LinkByName(containerIfName) - if err != nil { - return fmt.Errorf("could not find link by name %s: %v", containerIfName, err) - } - err = nlh.LinkSetMTU(veth, mtu) - if err != nil { - return err - } - - if err = nlh.LinkSetHardwareAddr(veth, ep.mac); err != nil { - return fmt.Errorf("could not set mac address (%v) to the container interface: %v", ep.mac, err) - } - - for _, sub := range n.subnets { - if sub == s { - continue - } - if err = jinfo.AddStaticRoute(sub.subnetIP, types.NEXTHOP, s.gwIP.IP); err != nil { - logrus.Errorf("Adding subnet %s static route in network %q failed\n", s.subnetIP, n.id) - } - } - - if iNames := jinfo.InterfaceName(); iNames != nil { - err = iNames.SetNames(containerIfName, "eth") - if err != nil { - return err - } - } - - d.peerAdd(nid, eid, ep.addr.IP, ep.addr.Mask, ep.mac, net.ParseIP(d.advertiseAddress), false, false, true) - - if err = d.checkEncryption(nid, nil, n.vxlanID(s), true, true); err != nil { - logrus.Warn(err) - } - - buf, err := proto.Marshal(&PeerRecord{ - EndpointIP: ep.addr.String(), - EndpointMAC: ep.mac.String(), - TunnelEndpointIP: d.advertiseAddress, - }) - if err != nil { - return err - } - - if err := jinfo.AddTableEntry(ovPeerTable, eid, buf); err != nil { - logrus.Errorf("overlay: Failed adding table entry to joininfo: %v", err) - } - - d.pushLocalEndpointEvent("join", nid, eid) - - return nil -} - -func (d *driver) DecodeTableEntry(tablename string, key string, value []byte) (string, map[string]string) { - if tablename != ovPeerTable { - logrus.Errorf("DecodeTableEntry: unexpected table name %s", tablename) - return "", nil - } - - var peer PeerRecord - if err := proto.Unmarshal(value, &peer); err != nil { - logrus.Errorf("DecodeTableEntry: failed to unmarshal peer record for key %s: %v", key, err) - return "", nil - } - - return key, map[string]string{ - "Host IP": peer.TunnelEndpointIP, - } -} - -func (d *driver) EventNotify(etype driverapi.EventType, nid, tableName, key string, value []byte) { - if tableName != ovPeerTable { - logrus.Errorf("Unexpected table notification for table %s received", tableName) - return - } - - eid := key - - var peer PeerRecord - if err := proto.Unmarshal(value, &peer); err != nil { - logrus.Errorf("Failed to unmarshal peer record: %v", err) - return - } - - // Ignore local peers. We already know about them and they - // should not be added to vxlan fdb. - if peer.TunnelEndpointIP == d.advertiseAddress { - return - } - - addr, err := types.ParseCIDR(peer.EndpointIP) - if err != nil { - logrus.Errorf("Invalid peer IP %s received in event notify", peer.EndpointIP) - return - } - - mac, err := net.ParseMAC(peer.EndpointMAC) - if err != nil { - logrus.Errorf("Invalid mac %s received in event notify", peer.EndpointMAC) - return - } - - vtep := net.ParseIP(peer.TunnelEndpointIP) - if vtep == nil { - logrus.Errorf("Invalid VTEP %s received in event notify", peer.TunnelEndpointIP) - return - } - - if etype == driverapi.Delete { - d.peerDelete(nid, eid, addr.IP, addr.Mask, mac, vtep, false) - return - } - - d.peerAdd(nid, eid, addr.IP, addr.Mask, mac, vtep, false, false, false) -} - -// Leave method is invoked when a Sandbox detaches from an endpoint. -func (d *driver) Leave(nid, eid string) error { - if err := validateID(nid, eid); err != nil { - return err - } - - n := d.network(nid) - if n == nil { - return fmt.Errorf("could not find network with id %s", nid) - } - - ep := n.endpoint(eid) - - if ep == nil { - return types.InternalMaskableErrorf("could not find endpoint with id %s", eid) - } - - if d.notifyCh != nil { - d.notifyCh <- ovNotify{ - action: "leave", - nw: n, - ep: ep, - } - } - - d.peerDelete(nid, eid, ep.addr.IP, ep.addr.Mask, ep.mac, net.ParseIP(d.advertiseAddress), true) - - n.leaveSandbox() - - return nil -} diff --git a/vendor/github.com/docker/libnetwork/drivers/overlay/ostweaks_linux.go b/vendor/github.com/docker/libnetwork/drivers/overlay/ostweaks_linux.go deleted file mode 100644 index fa0a470921..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/overlay/ostweaks_linux.go +++ /dev/null @@ -1,23 +0,0 @@ -package overlay - -import ( - "strconv" - - "github.com/docker/libnetwork/osl/kernel" -) - -var ovConfig = map[string]*kernel.OSValue{ - "net.ipv4.neigh.default.gc_thresh1": {Value: "8192", CheckFn: checkHigher}, - "net.ipv4.neigh.default.gc_thresh2": {Value: "49152", CheckFn: checkHigher}, - "net.ipv4.neigh.default.gc_thresh3": {Value: "65536", CheckFn: checkHigher}, -} - -func checkHigher(val1, val2 string) bool { - val1Int, _ := strconv.ParseInt(val1, 10, 32) - val2Int, _ := strconv.ParseInt(val2, 10, 32) - return val1Int < val2Int -} - -func applyOStweaks() { - kernel.ApplyOSTweaks(ovConfig) -} diff --git a/vendor/github.com/docker/libnetwork/drivers/overlay/ostweaks_unsupported.go b/vendor/github.com/docker/libnetwork/drivers/overlay/ostweaks_unsupported.go deleted file mode 100644 index a5e8d91083..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/overlay/ostweaks_unsupported.go +++ /dev/null @@ -1,5 +0,0 @@ -// +build !linux - -package overlay - -func applyOStweaks() {} diff --git a/vendor/github.com/docker/libnetwork/drivers/overlay/ov_endpoint.go b/vendor/github.com/docker/libnetwork/drivers/overlay/ov_endpoint.go deleted file mode 100644 index 0aaaac59d9..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/overlay/ov_endpoint.go +++ /dev/null @@ -1,252 +0,0 @@ -package overlay - -import ( - "encoding/json" - "fmt" - "net" - - "github.com/docker/libnetwork/datastore" - "github.com/docker/libnetwork/driverapi" - "github.com/docker/libnetwork/netutils" - "github.com/docker/libnetwork/ns" - "github.com/docker/libnetwork/types" - "github.com/sirupsen/logrus" -) - -type endpointTable map[string]*endpoint - -const overlayEndpointPrefix = "overlay/endpoint" - -type endpoint struct { - id string - nid string - ifName string - mac net.HardwareAddr - addr *net.IPNet - dbExists bool - dbIndex uint64 -} - -func (n *network) endpoint(eid string) *endpoint { - n.Lock() - defer n.Unlock() - - return n.endpoints[eid] -} - -func (n *network) addEndpoint(ep *endpoint) { - n.Lock() - n.endpoints[ep.id] = ep - n.Unlock() -} - -func (n *network) deleteEndpoint(eid string) { - n.Lock() - delete(n.endpoints, eid) - n.Unlock() -} - -func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo, - epOptions map[string]interface{}) error { - var err error - - if err = validateID(nid, eid); err != nil { - return err - } - - // Since we perform lazy configuration make sure we try - // configuring the driver when we enter CreateEndpoint since - // CreateNetwork may not be called in every node. - if err := d.configure(); err != nil { - return err - } - - n := d.network(nid) - if n == nil { - return fmt.Errorf("network id %q not found", nid) - } - - ep := &endpoint{ - id: eid, - nid: n.id, - addr: ifInfo.Address(), - mac: ifInfo.MacAddress(), - } - if ep.addr == nil { - return fmt.Errorf("create endpoint was not passed interface IP address") - } - - if s := n.getSubnetforIP(ep.addr); s == nil { - return fmt.Errorf("no matching subnet for IP %q in network %q", ep.addr, nid) - } - - if ep.mac == nil { - ep.mac = netutils.GenerateMACFromIP(ep.addr.IP) - if err := ifInfo.SetMacAddress(ep.mac); err != nil { - return err - } - } - - n.addEndpoint(ep) - - if err := d.writeEndpointToStore(ep); err != nil { - return fmt.Errorf("failed to update overlay endpoint %.7s to local store: %v", ep.id, err) - } - - return nil -} - -func (d *driver) DeleteEndpoint(nid, eid string) error { - nlh := ns.NlHandle() - - if err := validateID(nid, eid); err != nil { - return err - } - - n := d.network(nid) - if n == nil { - return fmt.Errorf("network id %q not found", nid) - } - - ep := n.endpoint(eid) - if ep == nil { - return fmt.Errorf("endpoint id %q not found", eid) - } - - n.deleteEndpoint(eid) - - if err := d.deleteEndpointFromStore(ep); err != nil { - logrus.Warnf("Failed to delete overlay endpoint %.7s from local store: %v", ep.id, err) - } - - if ep.ifName == "" { - return nil - } - - link, err := nlh.LinkByName(ep.ifName) - if err != nil { - logrus.Debugf("Failed to retrieve interface (%s)'s link on endpoint (%s) delete: %v", ep.ifName, ep.id, err) - return nil - } - if err := nlh.LinkDel(link); err != nil { - logrus.Debugf("Failed to delete interface (%s)'s link on endpoint (%s) delete: %v", ep.ifName, ep.id, err) - } - - return nil -} - -func (d *driver) EndpointOperInfo(nid, eid string) (map[string]interface{}, error) { - return make(map[string]interface{}, 0), nil -} - -func (d *driver) deleteEndpointFromStore(e *endpoint) error { - if d.localStore == nil { - return fmt.Errorf("overlay local store not initialized, ep not deleted") - } - - return d.localStore.DeleteObjectAtomic(e) -} - -func (d *driver) writeEndpointToStore(e *endpoint) error { - if d.localStore == nil { - return fmt.Errorf("overlay local store not initialized, ep not added") - } - - return d.localStore.PutObjectAtomic(e) -} - -func (ep *endpoint) DataScope() string { - return datastore.LocalScope -} - -func (ep *endpoint) New() datastore.KVObject { - return &endpoint{} -} - -func (ep *endpoint) CopyTo(o datastore.KVObject) error { - dstep := o.(*endpoint) - *dstep = *ep - return nil -} - -func (ep *endpoint) Key() []string { - return []string{overlayEndpointPrefix, ep.id} -} - -func (ep *endpoint) KeyPrefix() []string { - return []string{overlayEndpointPrefix} -} - -func (ep *endpoint) Index() uint64 { - return ep.dbIndex -} - -func (ep *endpoint) SetIndex(index uint64) { - ep.dbIndex = index - ep.dbExists = true -} - -func (ep *endpoint) Exists() bool { - return ep.dbExists -} - -func (ep *endpoint) Skip() bool { - return false -} - -func (ep *endpoint) Value() []byte { - b, err := json.Marshal(ep) - if err != nil { - return nil - } - return b -} - -func (ep *endpoint) SetValue(value []byte) error { - return json.Unmarshal(value, ep) -} - -func (ep *endpoint) MarshalJSON() ([]byte, error) { - epMap := make(map[string]interface{}) - - epMap["id"] = ep.id - epMap["nid"] = ep.nid - if ep.ifName != "" { - epMap["ifName"] = ep.ifName - } - if ep.addr != nil { - epMap["addr"] = ep.addr.String() - } - if len(ep.mac) != 0 { - epMap["mac"] = ep.mac.String() - } - - return json.Marshal(epMap) -} - -func (ep *endpoint) UnmarshalJSON(value []byte) error { - var ( - err error - epMap map[string]interface{} - ) - - json.Unmarshal(value, &epMap) - - ep.id = epMap["id"].(string) - ep.nid = epMap["nid"].(string) - if v, ok := epMap["mac"]; ok { - if ep.mac, err = net.ParseMAC(v.(string)); err != nil { - return types.InternalErrorf("failed to decode endpoint interface mac address after json unmarshal: %s", v.(string)) - } - } - if v, ok := epMap["addr"]; ok { - if ep.addr, err = types.ParseCIDR(v.(string)); err != nil { - return types.InternalErrorf("failed to decode endpoint interface ipv4 address after json unmarshal: %v", err) - } - } - if v, ok := epMap["ifName"]; ok { - ep.ifName = v.(string) - } - - return nil -} diff --git a/vendor/github.com/docker/libnetwork/drivers/overlay/ov_network.go b/vendor/github.com/docker/libnetwork/drivers/overlay/ov_network.go deleted file mode 100644 index 2aa24b9778..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/overlay/ov_network.go +++ /dev/null @@ -1,1155 +0,0 @@ -package overlay - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net" - "os" - "os/exec" - "path/filepath" - "runtime" - "strconv" - "strings" - "sync" - - "github.com/docker/docker/pkg/reexec" - "github.com/docker/libnetwork/datastore" - "github.com/docker/libnetwork/driverapi" - "github.com/docker/libnetwork/netlabel" - "github.com/docker/libnetwork/netutils" - "github.com/docker/libnetwork/ns" - "github.com/docker/libnetwork/osl" - "github.com/docker/libnetwork/resolvconf" - "github.com/docker/libnetwork/types" - "github.com/sirupsen/logrus" - "github.com/vishvananda/netlink" - "github.com/vishvananda/netlink/nl" - "github.com/vishvananda/netns" - "golang.org/x/sys/unix" -) - -var ( - hostMode bool - networkOnce sync.Once - networkMu sync.Mutex - vniTbl = make(map[uint32]string) -) - -type networkTable map[string]*network - -type subnet struct { - sboxInit bool - vxlanName string - brName string - vni uint32 - initErr error - subnetIP *net.IPNet - gwIP *net.IPNet -} - -type subnetJSON struct { - SubnetIP string - GwIP string - Vni uint32 -} - -type network struct { - id string - dbIndex uint64 - dbExists bool - sbox osl.Sandbox - nlSocket *nl.NetlinkSocket - endpoints endpointTable - driver *driver - joinCnt int - sboxInit bool - initEpoch int - initErr error - subnets []*subnet - secure bool - mtu int - sync.Mutex -} - -func init() { - reexec.Register("set-default-vlan", setDefaultVlan) -} - -func setDefaultVlan() { - if len(os.Args) < 3 { - logrus.Error("insufficient number of arguments") - os.Exit(1) - } - - runtime.LockOSThread() - defer runtime.UnlockOSThread() - - nsPath := os.Args[1] - ns, err := netns.GetFromPath(nsPath) - if err != nil { - logrus.Errorf("overlay namespace get failed, %v", err) - os.Exit(1) - } - if err = netns.Set(ns); err != nil { - logrus.Errorf("setting into overlay namespace failed, %v", err) - os.Exit(1) - } - - // make sure the sysfs mount doesn't propagate back - if err = unix.Unshare(unix.CLONE_NEWNS); err != nil { - logrus.Errorf("unshare failed, %v", err) - os.Exit(1) - } - - flag := unix.MS_PRIVATE | unix.MS_REC - if err = unix.Mount("", "/", "", uintptr(flag), ""); err != nil { - logrus.Errorf("root mount failed, %v", err) - os.Exit(1) - } - - if err = unix.Mount("sysfs", "/sys", "sysfs", 0, ""); err != nil { - logrus.Errorf("mounting sysfs failed, %v", err) - os.Exit(1) - } - - brName := os.Args[2] - path := filepath.Join("/sys/class/net", brName, "bridge/default_pvid") - data := []byte{'0', '\n'} - - if err = ioutil.WriteFile(path, data, 0644); err != nil { - logrus.Errorf("enabling default vlan on bridge %s failed %v", brName, err) - os.Exit(1) - } - os.Exit(0) -} - -func (d *driver) NetworkAllocate(id string, option map[string]string, ipV4Data, ipV6Data []driverapi.IPAMData) (map[string]string, error) { - return nil, types.NotImplementedErrorf("not implemented") -} - -func (d *driver) NetworkFree(id string) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) CreateNetwork(id string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error { - if id == "" { - return fmt.Errorf("invalid network id") - } - if len(ipV4Data) == 0 || ipV4Data[0].Pool.String() == "0.0.0.0/0" { - return types.BadRequestErrorf("ipv4 pool is empty") - } - - // Since we perform lazy configuration make sure we try - // configuring the driver when we enter CreateNetwork - if err := d.configure(); err != nil { - return err - } - - n := &network{ - id: id, - driver: d, - endpoints: endpointTable{}, - subnets: []*subnet{}, - } - - vnis := make([]uint32, 0, len(ipV4Data)) - if gval, ok := option[netlabel.GenericData]; ok { - optMap := gval.(map[string]string) - if val, ok := optMap[netlabel.OverlayVxlanIDList]; ok { - logrus.Debugf("overlay: Received vxlan IDs: %s", val) - vniStrings := strings.Split(val, ",") - for _, vniStr := range vniStrings { - vni, err := strconv.Atoi(vniStr) - if err != nil { - return fmt.Errorf("invalid vxlan id value %q passed", vniStr) - } - - vnis = append(vnis, uint32(vni)) - } - } - if _, ok := optMap[secureOption]; ok { - n.secure = true - } - if val, ok := optMap[netlabel.DriverMTU]; ok { - var err error - if n.mtu, err = strconv.Atoi(val); err != nil { - return fmt.Errorf("failed to parse %v: %v", val, err) - } - if n.mtu < 0 { - return fmt.Errorf("invalid MTU value: %v", n.mtu) - } - } - } - - // If we are getting vnis from libnetwork, either we get for - // all subnets or none. - if len(vnis) != 0 && len(vnis) < len(ipV4Data) { - return fmt.Errorf("insufficient vnis(%d) passed to overlay", len(vnis)) - } - - for i, ipd := range ipV4Data { - s := &subnet{ - subnetIP: ipd.Pool, - gwIP: ipd.Gateway, - } - - if len(vnis) != 0 { - s.vni = vnis[i] - } - - n.subnets = append(n.subnets, s) - } - - d.Lock() - defer d.Unlock() - if d.networks[n.id] != nil { - return fmt.Errorf("attempt to create overlay network %v that already exists", n.id) - } - - if err := n.writeToStore(); err != nil { - return fmt.Errorf("failed to update data store for network %v: %v", n.id, err) - } - - // Make sure no rule is on the way from any stale secure network - if !n.secure { - for _, vni := range vnis { - programMangle(vni, false) - programInput(vni, false) - } - } - - if nInfo != nil { - if err := nInfo.TableEventRegister(ovPeerTable, driverapi.EndpointObject); err != nil { - // XXX Undo writeToStore? No method to so. Why? - return err - } - } - - d.networks[id] = n - - return nil -} - -func (d *driver) DeleteNetwork(nid string) error { - if nid == "" { - return fmt.Errorf("invalid network id") - } - - // Make sure driver resources are initialized before proceeding - if err := d.configure(); err != nil { - return err - } - - d.Lock() - // Only perform a peer flush operation (if required) AFTER unlocking - // the driver lock to avoid deadlocking w/ the peerDB. - var doPeerFlush bool - defer func() { - d.Unlock() - if doPeerFlush { - d.peerFlush(nid) - } - }() - - // This is similar to d.network(), but we need to keep holding the lock - // until we are done removing this network. - n, ok := d.networks[nid] - if !ok { - n = d.restoreNetworkFromStore(nid) - } - if n == nil { - return fmt.Errorf("could not find network with id %s", nid) - } - - for _, ep := range n.endpoints { - if ep.ifName != "" { - if link, err := ns.NlHandle().LinkByName(ep.ifName); err == nil { - if err := ns.NlHandle().LinkDel(link); err != nil { - logrus.WithError(err).Warnf("Failed to delete interface (%s)'s link on endpoint (%s) delete", ep.ifName, ep.id) - } - } - } - - if err := d.deleteEndpointFromStore(ep); err != nil { - logrus.Warnf("Failed to delete overlay endpoint %.7s from local store: %v", ep.id, err) - } - } - - doPeerFlush = true - delete(d.networks, nid) - - vnis, err := n.releaseVxlanID() - if err != nil { - return err - } - - if n.secure { - for _, vni := range vnis { - programMangle(vni, false) - programInput(vni, false) - } - } - - return nil -} - -func (d *driver) ProgramExternalConnectivity(nid, eid string, options map[string]interface{}) error { - return nil -} - -func (d *driver) RevokeExternalConnectivity(nid, eid string) error { - return nil -} - -func (n *network) joinSandbox(s *subnet, restore bool, incJoinCount bool) error { - // If there is a race between two go routines here only one will win - // the other will wait. - networkOnce.Do(networkOnceInit) - - n.Lock() - // If non-restore initialization occurred and was successful then - // tell the peerDB to initialize the sandbox with all the peers - // previously received from networkdb. But only do this after - // unlocking the network. Otherwise we could deadlock with - // on the peerDB channel while peerDB is waiting for the network lock. - var doInitPeerDB bool - defer func() { - n.Unlock() - if doInitPeerDB { - n.driver.initSandboxPeerDB(n.id) - } - }() - - if !n.sboxInit { - n.initErr = n.initSandbox(restore) - doInitPeerDB = n.initErr == nil && !restore - // If there was an error, we cannot recover it - n.sboxInit = true - } - - if n.initErr != nil { - return fmt.Errorf("network sandbox join failed: %v", n.initErr) - } - - subnetErr := s.initErr - if !s.sboxInit { - subnetErr = n.initSubnetSandbox(s, restore) - // We can recover from these errors, but not on restore - if restore || subnetErr == nil { - s.initErr = subnetErr - s.sboxInit = true - } - } - if subnetErr != nil { - return fmt.Errorf("subnet sandbox join failed for %q: %v", s.subnetIP.String(), subnetErr) - } - - if incJoinCount { - n.joinCnt++ - } - - return nil -} - -func (n *network) leaveSandbox() { - n.Lock() - defer n.Unlock() - n.joinCnt-- - if n.joinCnt != 0 { - return - } - - n.destroySandbox() - - n.sboxInit = false - n.initErr = nil - for _, s := range n.subnets { - s.sboxInit = false - s.initErr = nil - } -} - -// to be called while holding network lock -func (n *network) destroySandbox() { - if n.sbox != nil { - for _, iface := range n.sbox.Info().Interfaces() { - if err := iface.Remove(); err != nil { - logrus.Debugf("Remove interface %s failed: %v", iface.SrcName(), err) - } - } - - for _, s := range n.subnets { - if hostMode { - if err := removeFilters(n.id[:12], s.brName); err != nil { - logrus.Warnf("Could not remove overlay filters: %v", err) - } - } - - if s.vxlanName != "" { - err := deleteInterface(s.vxlanName) - if err != nil { - logrus.Warnf("could not cleanup sandbox properly: %v", err) - } - } - } - - if hostMode { - if err := removeNetworkChain(n.id[:12]); err != nil { - logrus.Warnf("could not remove network chain: %v", err) - } - } - - // Close the netlink socket, this will also release the watchMiss goroutine that is using it - if n.nlSocket != nil { - n.nlSocket.Close() - n.nlSocket = nil - } - - n.sbox.Destroy() - n.sbox = nil - } -} - -func populateVNITbl() { - filepath.Walk(filepath.Dir(osl.GenerateKey("walk")), - func(path string, info os.FileInfo, err error) error { - _, fname := filepath.Split(path) - - if len(strings.Split(fname, "-")) <= 1 { - return nil - } - - ns, err := netns.GetFromPath(path) - if err != nil { - logrus.Errorf("Could not open namespace path %s during vni population: %v", path, err) - return nil - } - defer ns.Close() - - nlh, err := netlink.NewHandleAt(ns, unix.NETLINK_ROUTE) - if err != nil { - logrus.Errorf("Could not open netlink handle during vni population for ns %s: %v", path, err) - return nil - } - defer nlh.Delete() - - err = nlh.SetSocketTimeout(soTimeout) - if err != nil { - logrus.Warnf("Failed to set the timeout on the netlink handle sockets for vni table population: %v", err) - } - - links, err := nlh.LinkList() - if err != nil { - logrus.Errorf("Failed to list interfaces during vni population for ns %s: %v", path, err) - return nil - } - - for _, l := range links { - if l.Type() == "vxlan" { - vniTbl[uint32(l.(*netlink.Vxlan).VxlanId)] = path - } - } - - return nil - }) -} - -func networkOnceInit() { - populateVNITbl() - - if os.Getenv("_OVERLAY_HOST_MODE") != "" { - hostMode = true - return - } - - err := createVxlan("testvxlan", 1, 0) - if err != nil { - logrus.Errorf("Failed to create testvxlan interface: %v", err) - return - } - - defer deleteInterface("testvxlan") - - path := "/proc/self/ns/net" - hNs, err := netns.GetFromPath(path) - if err != nil { - logrus.Errorf("Failed to get network namespace from path %s while setting host mode: %v", path, err) - return - } - defer hNs.Close() - - nlh := ns.NlHandle() - - iface, err := nlh.LinkByName("testvxlan") - if err != nil { - logrus.Errorf("Failed to get link testvxlan while setting host mode: %v", err) - return - } - - // If we are not able to move the vxlan interface to a namespace - // then fallback to host mode - if err := nlh.LinkSetNsFd(iface, int(hNs)); err != nil { - hostMode = true - } -} - -func (n *network) generateVxlanName(s *subnet) string { - id := n.id - if len(n.id) > 5 { - id = n.id[:5] - } - - return fmt.Sprintf("vx-%06x-%v", s.vni, id) -} - -func (n *network) generateBridgeName(s *subnet) string { - id := n.id - if len(n.id) > 5 { - id = n.id[:5] - } - - return n.getBridgeNamePrefix(s) + "-" + id -} - -func (n *network) getBridgeNamePrefix(s *subnet) string { - return fmt.Sprintf("ov-%06x", s.vni) -} - -func checkOverlap(nw *net.IPNet) error { - var nameservers []string - - if rc, err := resolvconf.Get(); err == nil { - nameservers = resolvconf.GetNameserversAsCIDR(rc.Content) - } - - if err := netutils.CheckNameserverOverlaps(nameservers, nw); err != nil { - return fmt.Errorf("overlay subnet %s failed check with nameserver: %v: %v", nw.String(), nameservers, err) - } - - if err := netutils.CheckRouteOverlaps(nw); err != nil { - return fmt.Errorf("overlay subnet %s failed check with host route table: %v", nw.String(), err) - } - - return nil -} - -func (n *network) restoreSubnetSandbox(s *subnet, brName, vxlanName string) error { - sbox := n.sbox - - // restore overlay osl sandbox - Ifaces := make(map[string][]osl.IfaceOption) - brIfaceOption := make([]osl.IfaceOption, 2) - brIfaceOption = append(brIfaceOption, sbox.InterfaceOptions().Address(s.gwIP)) - brIfaceOption = append(brIfaceOption, sbox.InterfaceOptions().Bridge(true)) - Ifaces[brName+"+br"] = brIfaceOption - - err := sbox.Restore(Ifaces, nil, nil, nil) - if err != nil { - return err - } - - Ifaces = make(map[string][]osl.IfaceOption) - vxlanIfaceOption := make([]osl.IfaceOption, 1) - vxlanIfaceOption = append(vxlanIfaceOption, sbox.InterfaceOptions().Master(brName)) - Ifaces[vxlanName+"+vxlan"] = vxlanIfaceOption - return sbox.Restore(Ifaces, nil, nil, nil) -} - -func (n *network) setupSubnetSandbox(s *subnet, brName, vxlanName string) error { - - if hostMode { - // Try to delete stale bridge interface if it exists - if err := deleteInterface(brName); err != nil { - deleteInterfaceBySubnet(n.getBridgeNamePrefix(s), s) - } - // Try to delete the vxlan interface by vni if already present - deleteVxlanByVNI("", s.vni) - - if err := checkOverlap(s.subnetIP); err != nil { - return err - } - } - - if !hostMode { - // Try to find this subnet's vni is being used in some - // other namespace by looking at vniTbl that we just - // populated in the once init. If a hit is found then - // it must a stale namespace from previous - // life. Destroy it completely and reclaim resourced. - networkMu.Lock() - path, ok := vniTbl[s.vni] - networkMu.Unlock() - - if ok { - deleteVxlanByVNI(path, s.vni) - if err := unix.Unmount(path, unix.MNT_FORCE); err != nil { - logrus.Errorf("unmount of %s failed: %v", path, err) - } - os.Remove(path) - - networkMu.Lock() - delete(vniTbl, s.vni) - networkMu.Unlock() - } - } - - // create a bridge and vxlan device for this subnet and move it to the sandbox - sbox := n.sbox - - if err := sbox.AddInterface(brName, "br", - sbox.InterfaceOptions().Address(s.gwIP), - sbox.InterfaceOptions().Bridge(true)); err != nil { - return fmt.Errorf("bridge creation in sandbox failed for subnet %q: %v", s.subnetIP.String(), err) - } - - err := createVxlan(vxlanName, s.vni, n.maxMTU()) - if err != nil { - return err - } - - if err := sbox.AddInterface(vxlanName, "vxlan", - sbox.InterfaceOptions().Master(brName)); err != nil { - // If adding vxlan device to the overlay namespace fails, remove the bridge interface we - // already added to the namespace. This allows the caller to try the setup again. - for _, iface := range sbox.Info().Interfaces() { - if iface.SrcName() == brName { - if ierr := iface.Remove(); ierr != nil { - logrus.Errorf("removing bridge failed from ov ns %v failed, %v", n.sbox.Key(), ierr) - } - } - } - - // Also, delete the vxlan interface. Since a global vni id is associated - // with the vxlan interface, an orphaned vxlan interface will result in - // failure of vxlan device creation if the vni is assigned to some other - // network. - if deleteErr := deleteInterface(vxlanName); deleteErr != nil { - logrus.Warnf("could not delete vxlan interface, %s, error %v, after config error, %v", vxlanName, deleteErr, err) - } - return fmt.Errorf("vxlan interface creation failed for subnet %q: %v", s.subnetIP.String(), err) - } - - if !hostMode { - var name string - for _, i := range sbox.Info().Interfaces() { - if i.Bridge() { - name = i.DstName() - } - } - cmd := &exec.Cmd{ - Path: reexec.Self(), - Args: []string{"set-default-vlan", sbox.Key(), name}, - Stdout: os.Stdout, - Stderr: os.Stderr, - } - if err := cmd.Run(); err != nil { - // not a fatal error - logrus.Errorf("reexec to set bridge default vlan failed %v", err) - } - } - - if hostMode { - if err := addFilters(n.id[:12], brName); err != nil { - return err - } - } - - return nil -} - -// Must be called with the network lock -func (n *network) initSubnetSandbox(s *subnet, restore bool) error { - brName := n.generateBridgeName(s) - vxlanName := n.generateVxlanName(s) - - if restore { - if err := n.restoreSubnetSandbox(s, brName, vxlanName); err != nil { - return err - } - } else { - if err := n.setupSubnetSandbox(s, brName, vxlanName); err != nil { - return err - } - } - - s.vxlanName = vxlanName - s.brName = brName - - return nil -} - -func (n *network) cleanupStaleSandboxes() { - filepath.Walk(filepath.Dir(osl.GenerateKey("walk")), - func(path string, info os.FileInfo, err error) error { - _, fname := filepath.Split(path) - - pList := strings.Split(fname, "-") - if len(pList) <= 1 { - return nil - } - - pattern := pList[1] - if strings.Contains(n.id, pattern) { - // Delete all vnis - deleteVxlanByVNI(path, 0) - unix.Unmount(path, unix.MNT_DETACH) - os.Remove(path) - - // Now that we have destroyed this - // sandbox, remove all references to - // it in vniTbl so that we don't - // inadvertently destroy the sandbox - // created in this life. - networkMu.Lock() - for vni, tblPath := range vniTbl { - if tblPath == path { - delete(vniTbl, vni) - } - } - networkMu.Unlock() - } - - return nil - }) -} - -func (n *network) initSandbox(restore bool) error { - n.initEpoch++ - - if !restore { - if hostMode { - if err := addNetworkChain(n.id[:12]); err != nil { - return err - } - } - - // If there are any stale sandboxes related to this network - // from previous daemon life clean it up here - n.cleanupStaleSandboxes() - } - - // In the restore case network sandbox already exist; but we don't know - // what epoch number it was created with. It has to be retrieved by - // searching the net namespaces. - var key string - if restore { - key = osl.GenerateKey("-" + n.id) - } else { - key = osl.GenerateKey(fmt.Sprintf("%d-", n.initEpoch) + n.id) - } - - sbox, err := osl.NewSandbox(key, !hostMode, restore) - if err != nil { - return fmt.Errorf("could not get network sandbox (oper %t): %v", restore, err) - } - - // this is needed to let the peerAdd configure the sandbox - n.sbox = sbox - - // If we are in swarm mode, we don't need anymore the watchMiss routine. - // This will save 1 thread and 1 netlink socket per network - if !n.driver.isSerfAlive() { - return nil - } - - var nlSock *nl.NetlinkSocket - sbox.InvokeFunc(func() { - nlSock, err = nl.Subscribe(unix.NETLINK_ROUTE, unix.RTNLGRP_NEIGH) - if err != nil { - return - } - // set the receive timeout to not remain stuck on the RecvFrom if the fd gets closed - tv := unix.NsecToTimeval(soTimeout.Nanoseconds()) - err = nlSock.SetReceiveTimeout(&tv) - }) - n.nlSocket = nlSock - - if err == nil { - go n.watchMiss(nlSock, key) - } else { - logrus.Errorf("failed to subscribe to neighbor group netlink messages for overlay network %s in sbox %s: %v", - n.id, sbox.Key(), err) - } - - return nil -} - -func (n *network) watchMiss(nlSock *nl.NetlinkSocket, nsPath string) { - // With the new version of the netlink library the deserialize function makes - // requests about the interface of the netlink message. This can succeed only - // if this go routine is in the target namespace. For this reason following we - // lock the thread on that namespace - runtime.LockOSThread() - defer runtime.UnlockOSThread() - newNs, err := netns.GetFromPath(nsPath) - if err != nil { - logrus.WithError(err).Errorf("failed to get the namespace %s", nsPath) - return - } - defer newNs.Close() - if err = netns.Set(newNs); err != nil { - logrus.WithError(err).Errorf("failed to enter the namespace %s", nsPath) - return - } - for { - msgs, _, err := nlSock.Receive() - if err != nil { - n.Lock() - nlFd := nlSock.GetFd() - n.Unlock() - if nlFd == -1 { - // The netlink socket got closed, simply exit to not leak this goroutine - return - } - // When the receive timeout expires the receive will return EAGAIN - if err == unix.EAGAIN { - // we continue here to avoid spam for timeouts - continue - } - logrus.Errorf("Failed to receive from netlink: %v ", err) - continue - } - - for _, msg := range msgs { - if msg.Header.Type != unix.RTM_GETNEIGH && msg.Header.Type != unix.RTM_NEWNEIGH { - continue - } - - neigh, err := netlink.NeighDeserialize(msg.Data) - if err != nil { - logrus.Errorf("Failed to deserialize netlink ndmsg: %v", err) - continue - } - - var ( - ip net.IP - mac net.HardwareAddr - l2Miss, l3Miss bool - ) - if neigh.IP.To4() != nil { - ip = neigh.IP - l3Miss = true - } else if neigh.HardwareAddr != nil { - mac = []byte(neigh.HardwareAddr) - ip = net.IP(mac[2:]) - l2Miss = true - } else { - continue - } - - // Not any of the network's subnets. Ignore. - if !n.contains(ip) { - continue - } - - if neigh.State&(netlink.NUD_STALE|netlink.NUD_INCOMPLETE) == 0 { - continue - } - - logrus.Debugf("miss notification: dest IP %v, dest MAC %v", ip, mac) - mac, IPmask, vtep, err := n.driver.resolvePeer(n.id, ip) - if err != nil { - logrus.Errorf("could not resolve peer %q: %v", ip, err) - continue - } - n.driver.peerAdd(n.id, "dummy", ip, IPmask, mac, vtep, l2Miss, l3Miss, false) - } - } -} - -// Restore a network from the store to the driver if it is present. -// Must be called with the driver locked! -func (d *driver) restoreNetworkFromStore(nid string) *network { - n := d.getNetworkFromStore(nid) - if n != nil { - n.driver = d - n.endpoints = endpointTable{} - d.networks[nid] = n - } - return n -} - -func (d *driver) network(nid string) *network { - d.Lock() - n, ok := d.networks[nid] - if !ok { - n = d.restoreNetworkFromStore(nid) - } - d.Unlock() - - return n -} - -func (d *driver) getNetworkFromStore(nid string) *network { - if d.store == nil { - return nil - } - - n := &network{id: nid} - if err := d.store.GetObject(datastore.Key(n.Key()...), n); err != nil { - return nil - } - - return n -} - -func (n *network) sandbox() osl.Sandbox { - n.Lock() - defer n.Unlock() - return n.sbox -} - -func (n *network) vxlanID(s *subnet) uint32 { - n.Lock() - defer n.Unlock() - return s.vni -} - -func (n *network) setVxlanID(s *subnet, vni uint32) { - n.Lock() - s.vni = vni - n.Unlock() -} - -func (n *network) Key() []string { - return []string{"overlay", "network", n.id} -} - -func (n *network) KeyPrefix() []string { - return []string{"overlay", "network"} -} - -func (n *network) Value() []byte { - m := map[string]interface{}{} - - netJSON := []*subnetJSON{} - - for _, s := range n.subnets { - sj := &subnetJSON{ - SubnetIP: s.subnetIP.String(), - GwIP: s.gwIP.String(), - Vni: s.vni, - } - netJSON = append(netJSON, sj) - } - - m["secure"] = n.secure - m["subnets"] = netJSON - m["mtu"] = n.mtu - b, err := json.Marshal(m) - if err != nil { - return []byte{} - } - - return b -} - -func (n *network) Index() uint64 { - return n.dbIndex -} - -func (n *network) SetIndex(index uint64) { - n.dbIndex = index - n.dbExists = true -} - -func (n *network) Exists() bool { - return n.dbExists -} - -func (n *network) Skip() bool { - return false -} - -func (n *network) SetValue(value []byte) error { - var ( - m map[string]interface{} - newNet bool - isMap = true - netJSON = []*subnetJSON{} - ) - - if err := json.Unmarshal(value, &m); err != nil { - err := json.Unmarshal(value, &netJSON) - if err != nil { - return err - } - isMap = false - } - - if len(n.subnets) == 0 { - newNet = true - } - - if isMap { - if val, ok := m["secure"]; ok { - n.secure = val.(bool) - } - if val, ok := m["mtu"]; ok { - n.mtu = int(val.(float64)) - } - bytes, err := json.Marshal(m["subnets"]) - if err != nil { - return err - } - if err := json.Unmarshal(bytes, &netJSON); err != nil { - return err - } - } - - for _, sj := range netJSON { - subnetIPstr := sj.SubnetIP - gwIPstr := sj.GwIP - vni := sj.Vni - - subnetIP, _ := types.ParseCIDR(subnetIPstr) - gwIP, _ := types.ParseCIDR(gwIPstr) - - if newNet { - s := &subnet{ - subnetIP: subnetIP, - gwIP: gwIP, - vni: vni, - } - n.subnets = append(n.subnets, s) - } else { - sNet := n.getMatchingSubnet(subnetIP) - if sNet != nil { - sNet.vni = vni - } - } - } - return nil -} - -func (n *network) DataScope() string { - return datastore.GlobalScope -} - -func (n *network) writeToStore() error { - if n.driver.store == nil { - return nil - } - - return n.driver.store.PutObjectAtomic(n) -} - -func (n *network) releaseVxlanID() ([]uint32, error) { - n.Lock() - nSubnets := len(n.subnets) - n.Unlock() - if nSubnets == 0 { - return nil, nil - } - - if n.driver.store != nil { - if err := n.driver.store.DeleteObjectAtomic(n); err != nil { - if err == datastore.ErrKeyModified || err == datastore.ErrKeyNotFound { - // In both the above cases we can safely assume that the key has been removed by some other - // instance and so simply get out of here - return nil, nil - } - - return nil, fmt.Errorf("failed to delete network to vxlan id map: %v", err) - } - } - var vnis []uint32 - n.Lock() - for _, s := range n.subnets { - if n.driver.vxlanIdm != nil { - vnis = append(vnis, s.vni) - } - s.vni = 0 - } - n.Unlock() - - for _, vni := range vnis { - n.driver.vxlanIdm.Release(uint64(vni)) - } - - return vnis, nil -} - -func (n *network) obtainVxlanID(s *subnet) error { - //return if the subnet already has a vxlan id assigned - if n.vxlanID(s) != 0 { - return nil - } - - if n.driver.store == nil { - return fmt.Errorf("no valid vxlan id and no datastore configured, cannot obtain vxlan id") - } - - for { - if err := n.driver.store.GetObject(datastore.Key(n.Key()...), n); err != nil { - return fmt.Errorf("getting network %q from datastore failed %v", n.id, err) - } - - if n.vxlanID(s) == 0 { - vxlanID, err := n.driver.vxlanIdm.GetID(true) - if err != nil { - return fmt.Errorf("failed to allocate vxlan id: %v", err) - } - - n.setVxlanID(s, uint32(vxlanID)) - if err := n.writeToStore(); err != nil { - n.driver.vxlanIdm.Release(uint64(n.vxlanID(s))) - n.setVxlanID(s, 0) - if err == datastore.ErrKeyModified { - continue - } - return fmt.Errorf("network %q failed to update data store: %v", n.id, err) - } - return nil - } - return nil - } -} - -// contains return true if the passed ip belongs to one the network's -// subnets -func (n *network) contains(ip net.IP) bool { - for _, s := range n.subnets { - if s.subnetIP.Contains(ip) { - return true - } - } - - return false -} - -// getSubnetforIP returns the subnet to which the given IP belongs -func (n *network) getSubnetforIP(ip *net.IPNet) *subnet { - for _, s := range n.subnets { - // first check if the mask lengths are the same - i, _ := s.subnetIP.Mask.Size() - j, _ := ip.Mask.Size() - if i != j { - continue - } - if s.subnetIP.Contains(ip.IP) { - return s - } - } - return nil -} - -// getMatchingSubnet return the network's subnet that matches the input -func (n *network) getMatchingSubnet(ip *net.IPNet) *subnet { - if ip == nil { - return nil - } - for _, s := range n.subnets { - // first check if the mask lengths are the same - i, _ := s.subnetIP.Mask.Size() - j, _ := ip.Mask.Size() - if i != j { - continue - } - if s.subnetIP.IP.Equal(ip.IP) { - return s - } - } - return nil -} diff --git a/vendor/github.com/docker/libnetwork/drivers/overlay/ov_serf.go b/vendor/github.com/docker/libnetwork/drivers/overlay/ov_serf.go deleted file mode 100644 index f644799afd..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/overlay/ov_serf.go +++ /dev/null @@ -1,229 +0,0 @@ -package overlay - -import ( - "fmt" - "net" - "strings" - "time" - - "github.com/hashicorp/serf/serf" - "github.com/sirupsen/logrus" -) - -type ovNotify struct { - action string - ep *endpoint - nw *network -} - -type logWriter struct{} - -func (l *logWriter) Write(p []byte) (int, error) { - str := string(p) - - switch { - case strings.Contains(str, "[WARN]"): - logrus.Warn(str) - case strings.Contains(str, "[DEBUG]"): - logrus.Debug(str) - case strings.Contains(str, "[INFO]"): - logrus.Info(str) - case strings.Contains(str, "[ERR]"): - logrus.Error(str) - } - - return len(p), nil -} - -func (d *driver) serfInit() error { - var err error - - config := serf.DefaultConfig() - config.Init() - config.MemberlistConfig.BindAddr = d.advertiseAddress - - d.eventCh = make(chan serf.Event, 4) - config.EventCh = d.eventCh - config.UserCoalescePeriod = 1 * time.Second - config.UserQuiescentPeriod = 50 * time.Millisecond - - config.LogOutput = &logWriter{} - config.MemberlistConfig.LogOutput = config.LogOutput - - s, err := serf.Create(config) - if err != nil { - return fmt.Errorf("failed to create cluster node: %v", err) - } - defer func() { - if err != nil { - s.Shutdown() - } - }() - - d.serfInstance = s - - d.notifyCh = make(chan ovNotify) - d.exitCh = make(chan chan struct{}) - - go d.startSerfLoop(d.eventCh, d.notifyCh, d.exitCh) - return nil -} - -func (d *driver) serfJoin(neighIP string) error { - if neighIP == "" { - return fmt.Errorf("no neighbor to join") - } - if _, err := d.serfInstance.Join([]string{neighIP}, true); err != nil { - return fmt.Errorf("Failed to join the cluster at neigh IP %s: %v", - neighIP, err) - } - return nil -} - -func (d *driver) notifyEvent(event ovNotify) { - ep := event.ep - - ePayload := fmt.Sprintf("%s %s %s %s", event.action, ep.addr.IP.String(), - net.IP(ep.addr.Mask).String(), ep.mac.String()) - eName := fmt.Sprintf("jl %s %s %s", d.serfInstance.LocalMember().Addr.String(), - event.nw.id, ep.id) - - if err := d.serfInstance.UserEvent(eName, []byte(ePayload), true); err != nil { - logrus.Errorf("Sending user event failed: %v\n", err) - } -} - -func (d *driver) processEvent(u serf.UserEvent) { - logrus.Debugf("Received user event name:%s, payload:%s LTime:%d \n", u.Name, - string(u.Payload), uint64(u.LTime)) - - var dummy, action, vtepStr, nid, eid, ipStr, maskStr, macStr string - if _, err := fmt.Sscan(u.Name, &dummy, &vtepStr, &nid, &eid); err != nil { - fmt.Printf("Failed to scan name string: %v\n", err) - } - - if _, err := fmt.Sscan(string(u.Payload), &action, - &ipStr, &maskStr, &macStr); err != nil { - fmt.Printf("Failed to scan value string: %v\n", err) - } - - logrus.Debugf("Parsed data = %s/%s/%s/%s/%s/%s\n", nid, eid, vtepStr, ipStr, maskStr, macStr) - - mac, err := net.ParseMAC(macStr) - if err != nil { - logrus.Errorf("Failed to parse mac: %v\n", err) - } - - if d.serfInstance.LocalMember().Addr.String() == vtepStr { - return - } - - switch action { - case "join": - d.peerAdd(nid, eid, net.ParseIP(ipStr), net.IPMask(net.ParseIP(maskStr).To4()), mac, net.ParseIP(vtepStr), false, false, false) - case "leave": - d.peerDelete(nid, eid, net.ParseIP(ipStr), net.IPMask(net.ParseIP(maskStr).To4()), mac, net.ParseIP(vtepStr), false) - } -} - -func (d *driver) processQuery(q *serf.Query) { - logrus.Debugf("Received query name:%s, payload:%s\n", q.Name, - string(q.Payload)) - - var nid, ipStr string - if _, err := fmt.Sscan(string(q.Payload), &nid, &ipStr); err != nil { - fmt.Printf("Failed to scan query payload string: %v\n", err) - } - - pKey, pEntry, err := d.peerDbSearch(nid, net.ParseIP(ipStr)) - if err != nil { - return - } - - logrus.Debugf("Sending peer query resp mac %v, mask %s, vtep %s", pKey.peerMac, net.IP(pEntry.peerIPMask).String(), pEntry.vtep) - q.Respond([]byte(fmt.Sprintf("%s %s %s", pKey.peerMac.String(), net.IP(pEntry.peerIPMask).String(), pEntry.vtep.String()))) -} - -func (d *driver) resolvePeer(nid string, peerIP net.IP) (net.HardwareAddr, net.IPMask, net.IP, error) { - if d.serfInstance == nil { - return nil, nil, nil, fmt.Errorf("could not resolve peer: serf instance not initialized") - } - - qPayload := fmt.Sprintf("%s %s", string(nid), peerIP.String()) - resp, err := d.serfInstance.Query("peerlookup", []byte(qPayload), nil) - if err != nil { - return nil, nil, nil, fmt.Errorf("resolving peer by querying the cluster failed: %v", err) - } - - respCh := resp.ResponseCh() - select { - case r := <-respCh: - var macStr, maskStr, vtepStr string - if _, err := fmt.Sscan(string(r.Payload), &macStr, &maskStr, &vtepStr); err != nil { - return nil, nil, nil, fmt.Errorf("bad response %q for the resolve query: %v", string(r.Payload), err) - } - - mac, err := net.ParseMAC(macStr) - if err != nil { - return nil, nil, nil, fmt.Errorf("failed to parse mac: %v", err) - } - - logrus.Debugf("Received peer query response, mac %s, vtep %s, mask %s", macStr, vtepStr, maskStr) - return mac, net.IPMask(net.ParseIP(maskStr).To4()), net.ParseIP(vtepStr), nil - - case <-time.After(time.Second): - return nil, nil, nil, fmt.Errorf("timed out resolving peer by querying the cluster") - } -} - -func (d *driver) startSerfLoop(eventCh chan serf.Event, notifyCh chan ovNotify, - exitCh chan chan struct{}) { - - for { - select { - case notify, ok := <-notifyCh: - if !ok { - break - } - - d.notifyEvent(notify) - case ch, ok := <-exitCh: - if !ok { - break - } - - if err := d.serfInstance.Leave(); err != nil { - logrus.Errorf("failed leaving the cluster: %v\n", err) - } - - d.serfInstance.Shutdown() - close(ch) - return - case e, ok := <-eventCh: - if !ok { - break - } - - if e.EventType() == serf.EventQuery { - d.processQuery(e.(*serf.Query)) - break - } - - u, ok := e.(serf.UserEvent) - if !ok { - break - } - d.processEvent(u) - } - } -} - -func (d *driver) isSerfAlive() bool { - d.Lock() - serfInstance := d.serfInstance - d.Unlock() - if serfInstance == nil || serfInstance.State() != serf.SerfAlive { - return false - } - return true -} diff --git a/vendor/github.com/docker/libnetwork/drivers/overlay/ov_utils.go b/vendor/github.com/docker/libnetwork/drivers/overlay/ov_utils.go deleted file mode 100644 index 7338ea9e47..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/overlay/ov_utils.go +++ /dev/null @@ -1,162 +0,0 @@ -package overlay - -import ( - "fmt" - "strings" - "syscall" - - "github.com/docker/libnetwork/drivers/overlay/overlayutils" - "github.com/docker/libnetwork/netutils" - "github.com/docker/libnetwork/ns" - "github.com/docker/libnetwork/osl" - "github.com/sirupsen/logrus" - "github.com/vishvananda/netlink" - "github.com/vishvananda/netns" -) - -var soTimeout = ns.NetlinkSocketsTimeout - -func validateID(nid, eid string) error { - if nid == "" { - return fmt.Errorf("invalid network id") - } - - if eid == "" { - return fmt.Errorf("invalid endpoint id") - } - - return nil -} - -func createVethPair() (string, string, error) { - defer osl.InitOSContext()() - nlh := ns.NlHandle() - - // Generate a name for what will be the host side pipe interface - name1, err := netutils.GenerateIfaceName(nlh, vethPrefix, vethLen) - if err != nil { - return "", "", fmt.Errorf("error generating veth name1: %v", err) - } - - // Generate a name for what will be the sandbox side pipe interface - name2, err := netutils.GenerateIfaceName(nlh, vethPrefix, vethLen) - if err != nil { - return "", "", fmt.Errorf("error generating veth name2: %v", err) - } - - // Generate and add the interface pipe host <-> sandbox - veth := &netlink.Veth{ - LinkAttrs: netlink.LinkAttrs{Name: name1, TxQLen: 0}, - PeerName: name2} - if err := nlh.LinkAdd(veth); err != nil { - return "", "", fmt.Errorf("error creating veth pair: %v", err) - } - - return name1, name2, nil -} - -func createVxlan(name string, vni uint32, mtu int) error { - defer osl.InitOSContext()() - - vxlan := &netlink.Vxlan{ - LinkAttrs: netlink.LinkAttrs{Name: name, MTU: mtu}, - VxlanId: int(vni), - Learning: true, - Port: int(overlayutils.VXLANUDPPort()), - Proxy: true, - L3miss: true, - L2miss: true, - } - - if err := ns.NlHandle().LinkAdd(vxlan); err != nil { - return fmt.Errorf("error creating vxlan interface: %v", err) - } - - return nil -} - -func deleteInterfaceBySubnet(brPrefix string, s *subnet) error { - defer osl.InitOSContext()() - - nlh := ns.NlHandle() - links, err := nlh.LinkList() - if err != nil { - return fmt.Errorf("failed to list interfaces while deleting bridge interface by subnet: %v", err) - } - - for _, l := range links { - name := l.Attrs().Name - if _, ok := l.(*netlink.Bridge); ok && strings.HasPrefix(name, brPrefix) { - addrList, err := nlh.AddrList(l, netlink.FAMILY_V4) - if err != nil { - logrus.Errorf("error getting AddressList for bridge %s", name) - continue - } - for _, addr := range addrList { - if netutils.NetworkOverlaps(addr.IPNet, s.subnetIP) { - err = nlh.LinkDel(l) - if err != nil { - logrus.Errorf("error deleting bridge (%s) with subnet %v: %v", name, addr.IPNet, err) - } - } - } - } - } - return nil - -} - -func deleteInterface(name string) error { - defer osl.InitOSContext()() - - link, err := ns.NlHandle().LinkByName(name) - if err != nil { - return fmt.Errorf("failed to find interface with name %s: %v", name, err) - } - - if err := ns.NlHandle().LinkDel(link); err != nil { - return fmt.Errorf("error deleting interface with name %s: %v", name, err) - } - - return nil -} - -func deleteVxlanByVNI(path string, vni uint32) error { - defer osl.InitOSContext()() - - nlh := ns.NlHandle() - if path != "" { - ns, err := netns.GetFromPath(path) - if err != nil { - return fmt.Errorf("failed to get ns handle for %s: %v", path, err) - } - defer ns.Close() - - nlh, err = netlink.NewHandleAt(ns, syscall.NETLINK_ROUTE) - if err != nil { - return fmt.Errorf("failed to get netlink handle for ns %s: %v", path, err) - } - defer nlh.Delete() - err = nlh.SetSocketTimeout(soTimeout) - if err != nil { - logrus.Warnf("Failed to set the timeout on the netlink handle sockets for vxlan deletion: %v", err) - } - } - - links, err := nlh.LinkList() - if err != nil { - return fmt.Errorf("failed to list interfaces while deleting vxlan interface by vni: %v", err) - } - - for _, l := range links { - if l.Type() == "vxlan" && (vni == 0 || l.(*netlink.Vxlan).VxlanId == int(vni)) { - err = nlh.LinkDel(l) - if err != nil { - return fmt.Errorf("error deleting vxlan interface with id %d: %v", vni, err) - } - return nil - } - } - - return fmt.Errorf("could not find a vxlan interface to delete with id %d", vni) -} diff --git a/vendor/github.com/docker/libnetwork/drivers/overlay/overlay.go b/vendor/github.com/docker/libnetwork/drivers/overlay/overlay.go deleted file mode 100644 index 6f83e6de06..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/overlay/overlay.go +++ /dev/null @@ -1,391 +0,0 @@ -package overlay - -//go:generate protoc -I.:../../Godeps/_workspace/src/github.com/gogo/protobuf --gogo_out=import_path=github.com/docker/libnetwork/drivers/overlay,Mgogoproto/gogo.proto=github.com/gogo/protobuf/gogoproto:. overlay.proto - -import ( - "context" - "fmt" - "net" - "sync" - - "github.com/docker/libnetwork/datastore" - "github.com/docker/libnetwork/discoverapi" - "github.com/docker/libnetwork/driverapi" - "github.com/docker/libnetwork/idm" - "github.com/docker/libnetwork/netlabel" - "github.com/docker/libnetwork/osl" - "github.com/docker/libnetwork/types" - "github.com/hashicorp/serf/serf" - "github.com/sirupsen/logrus" -) - -const ( - networkType = "overlay" - vethPrefix = "veth" - vethLen = 7 - vxlanIDStart = 256 - vxlanIDEnd = (1 << 24) - 1 - vxlanEncap = 50 - secureOption = "encrypted" -) - -var initVxlanIdm = make(chan (bool), 1) - -type driver struct { - eventCh chan serf.Event - notifyCh chan ovNotify - exitCh chan chan struct{} - bindAddress string - advertiseAddress string - neighIP string - config map[string]interface{} - peerDb peerNetworkMap - secMap *encrMap - serfInstance *serf.Serf - networks networkTable - store datastore.DataStore - localStore datastore.DataStore - vxlanIdm *idm.Idm - initOS sync.Once - joinOnce sync.Once - localJoinOnce sync.Once - keys []*key - peerOpCh chan *peerOperation - peerOpCancel context.CancelFunc - sync.Mutex -} - -// Init registers a new instance of overlay driver -func Init(dc driverapi.DriverCallback, config map[string]interface{}) error { - c := driverapi.Capability{ - DataScope: datastore.GlobalScope, - ConnectivityScope: datastore.GlobalScope, - } - d := &driver{ - networks: networkTable{}, - peerDb: peerNetworkMap{ - mp: map[string]*peerMap{}, - }, - secMap: &encrMap{nodes: map[string][]*spi{}}, - config: config, - peerOpCh: make(chan *peerOperation), - } - - // Launch the go routine for processing peer operations - ctx, cancel := context.WithCancel(context.Background()) - d.peerOpCancel = cancel - go d.peerOpRoutine(ctx, d.peerOpCh) - - if data, ok := config[netlabel.GlobalKVClient]; ok { - var err error - dsc, ok := data.(discoverapi.DatastoreConfigData) - if !ok { - return types.InternalErrorf("incorrect data in datastore configuration: %v", data) - } - d.store, err = datastore.NewDataStoreFromConfig(dsc) - if err != nil { - return types.InternalErrorf("failed to initialize data store: %v", err) - } - } - - if data, ok := config[netlabel.LocalKVClient]; ok { - var err error - dsc, ok := data.(discoverapi.DatastoreConfigData) - if !ok { - return types.InternalErrorf("incorrect data in datastore configuration: %v", data) - } - d.localStore, err = datastore.NewDataStoreFromConfig(dsc) - if err != nil { - return types.InternalErrorf("failed to initialize local data store: %v", err) - } - } - - if err := d.restoreEndpoints(); err != nil { - logrus.Warnf("Failure during overlay endpoints restore: %v", err) - } - - return dc.RegisterDriver(networkType, d, c) -} - -// Endpoints are stored in the local store. Restore them and reconstruct the overlay sandbox -func (d *driver) restoreEndpoints() error { - if d.localStore == nil { - logrus.Warn("Cannot restore overlay endpoints because local datastore is missing") - return nil - } - kvol, err := d.localStore.List(datastore.Key(overlayEndpointPrefix), &endpoint{}) - if err != nil && err != datastore.ErrKeyNotFound { - return fmt.Errorf("failed to read overlay endpoint from store: %v", err) - } - - if err == datastore.ErrKeyNotFound { - return nil - } - for _, kvo := range kvol { - ep := kvo.(*endpoint) - n := d.network(ep.nid) - if n == nil { - logrus.Debugf("Network (%.7s) not found for restored endpoint (%.7s)", ep.nid, ep.id) - logrus.Debugf("Deleting stale overlay endpoint (%.7s) from store", ep.id) - if err := d.deleteEndpointFromStore(ep); err != nil { - logrus.Debugf("Failed to delete stale overlay endpoint (%.7s) from store", ep.id) - } - continue - } - n.addEndpoint(ep) - - s := n.getSubnetforIP(ep.addr) - if s == nil { - return fmt.Errorf("could not find subnet for endpoint %s", ep.id) - } - - if err := n.joinSandbox(s, true, true); err != nil { - return fmt.Errorf("restore network sandbox failed: %v", err) - } - - Ifaces := make(map[string][]osl.IfaceOption) - vethIfaceOption := make([]osl.IfaceOption, 1) - vethIfaceOption = append(vethIfaceOption, n.sbox.InterfaceOptions().Master(s.brName)) - Ifaces["veth+veth"] = vethIfaceOption - - err := n.sbox.Restore(Ifaces, nil, nil, nil) - if err != nil { - n.leaveSandbox() - return fmt.Errorf("failed to restore overlay sandbox: %v", err) - } - - d.peerAdd(ep.nid, ep.id, ep.addr.IP, ep.addr.Mask, ep.mac, net.ParseIP(d.advertiseAddress), false, false, true) - } - return nil -} - -// Fini cleans up the driver resources -func Fini(drv driverapi.Driver) { - d := drv.(*driver) - - // Notify the peer go routine to return - if d.peerOpCancel != nil { - d.peerOpCancel() - } - - if d.exitCh != nil { - waitCh := make(chan struct{}) - - d.exitCh <- waitCh - - <-waitCh - } -} - -func (d *driver) configure() error { - - // Apply OS specific kernel configs if needed - d.initOS.Do(applyOStweaks) - - if d.store == nil { - return nil - } - - if d.vxlanIdm == nil { - return d.initializeVxlanIdm() - } - - return nil -} - -func (d *driver) initializeVxlanIdm() error { - var err error - - initVxlanIdm <- true - defer func() { <-initVxlanIdm }() - - if d.vxlanIdm != nil { - return nil - } - - d.vxlanIdm, err = idm.New(d.store, "vxlan-id", vxlanIDStart, vxlanIDEnd) - if err != nil { - return fmt.Errorf("failed to initialize vxlan id manager: %v", err) - } - - return nil -} - -func (d *driver) Type() string { - return networkType -} - -func (d *driver) IsBuiltIn() bool { - return true -} - -func validateSelf(node string) error { - advIP := net.ParseIP(node) - if advIP == nil { - return fmt.Errorf("invalid self address (%s)", node) - } - - addrs, err := net.InterfaceAddrs() - if err != nil { - return fmt.Errorf("Unable to get interface addresses %v", err) - } - for _, addr := range addrs { - ip, _, err := net.ParseCIDR(addr.String()) - if err == nil && ip.Equal(advIP) { - return nil - } - } - return fmt.Errorf("Multi-Host overlay networking requires cluster-advertise(%s) to be configured with a local ip-address that is reachable within the cluster", advIP.String()) -} - -func (d *driver) nodeJoin(advertiseAddress, bindAddress string, self bool) { - if self && !d.isSerfAlive() { - d.Lock() - d.advertiseAddress = advertiseAddress - d.bindAddress = bindAddress - d.Unlock() - - // If containers are already running on this network update the - // advertise address in the peerDB - d.localJoinOnce.Do(func() { - d.peerDBUpdateSelf() - }) - - // If there is no cluster store there is no need to start serf. - if d.store != nil { - if err := validateSelf(advertiseAddress); err != nil { - logrus.Warn(err.Error()) - } - err := d.serfInit() - if err != nil { - logrus.Errorf("initializing serf instance failed: %v", err) - d.Lock() - d.advertiseAddress = "" - d.bindAddress = "" - d.Unlock() - return - } - } - } - - d.Lock() - if !self { - d.neighIP = advertiseAddress - } - neighIP := d.neighIP - d.Unlock() - - if d.serfInstance != nil && neighIP != "" { - var err error - d.joinOnce.Do(func() { - err = d.serfJoin(neighIP) - if err == nil { - d.pushLocalDb() - } - }) - if err != nil { - logrus.Errorf("joining serf neighbor %s failed: %v", advertiseAddress, err) - d.Lock() - d.joinOnce = sync.Once{} - d.Unlock() - return - } - } -} - -func (d *driver) pushLocalEndpointEvent(action, nid, eid string) { - n := d.network(nid) - if n == nil { - logrus.Debugf("Error pushing local endpoint event for network %s", nid) - return - } - ep := n.endpoint(eid) - if ep == nil { - logrus.Debugf("Error pushing local endpoint event for ep %s / %s", nid, eid) - return - } - - if !d.isSerfAlive() { - return - } - d.notifyCh <- ovNotify{ - action: "join", - nw: n, - ep: ep, - } -} - -// DiscoverNew is a notification for a new discovery event, such as a new node joining a cluster -func (d *driver) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error { - var err error - switch dType { - case discoverapi.NodeDiscovery: - nodeData, ok := data.(discoverapi.NodeDiscoveryData) - if !ok || nodeData.Address == "" { - return fmt.Errorf("invalid discovery data") - } - d.nodeJoin(nodeData.Address, nodeData.BindAddress, nodeData.Self) - case discoverapi.DatastoreConfig: - if d.store != nil { - return types.ForbiddenErrorf("cannot accept datastore configuration: Overlay driver has a datastore configured already") - } - dsc, ok := data.(discoverapi.DatastoreConfigData) - if !ok { - return types.InternalErrorf("incorrect data in datastore configuration: %v", data) - } - d.store, err = datastore.NewDataStoreFromConfig(dsc) - if err != nil { - return types.InternalErrorf("failed to initialize data store: %v", err) - } - case discoverapi.EncryptionKeysConfig: - encrData, ok := data.(discoverapi.DriverEncryptionConfig) - if !ok { - return fmt.Errorf("invalid encryption key notification data") - } - keys := make([]*key, 0, len(encrData.Keys)) - for i := 0; i < len(encrData.Keys); i++ { - k := &key{ - value: encrData.Keys[i], - tag: uint32(encrData.Tags[i]), - } - keys = append(keys, k) - } - if err := d.setKeys(keys); err != nil { - logrus.Warn(err) - } - case discoverapi.EncryptionKeysUpdate: - var newKey, delKey, priKey *key - encrData, ok := data.(discoverapi.DriverEncryptionUpdate) - if !ok { - return fmt.Errorf("invalid encryption key notification data") - } - if encrData.Key != nil { - newKey = &key{ - value: encrData.Key, - tag: uint32(encrData.Tag), - } - } - if encrData.Primary != nil { - priKey = &key{ - value: encrData.Primary, - tag: uint32(encrData.PrimaryTag), - } - } - if encrData.Prune != nil { - delKey = &key{ - value: encrData.Prune, - tag: uint32(encrData.PruneTag), - } - } - if err := d.updateKeys(newKey, priKey, delKey); err != nil { - return err - } - default: - } - return nil -} - -// DiscoverDelete is a notification for a discovery delete event, such as a node leaving a cluster -func (d *driver) DiscoverDelete(dType discoverapi.DiscoveryType, data interface{}) error { - return nil -} diff --git a/vendor/github.com/docker/libnetwork/drivers/overlay/overlay.pb.go b/vendor/github.com/docker/libnetwork/drivers/overlay/overlay.pb.go deleted file mode 100644 index 243c196541..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/overlay/overlay.pb.go +++ /dev/null @@ -1,455 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: drivers/overlay/overlay.proto - -/* - Package overlay is a generated protocol buffer package. - - It is generated from these files: - drivers/overlay/overlay.proto - - It has these top-level messages: - PeerRecord -*/ -package overlay - -import proto "github.com/gogo/protobuf/proto" -import fmt "fmt" -import math "math" -import _ "github.com/gogo/protobuf/gogoproto" - -import strings "strings" -import reflect "reflect" - -import io "io" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package - -// PeerRecord defines the information corresponding to a peer -// container in the overlay network. -type PeerRecord struct { - // Endpoint IP is the IP of the container attachment on the - // given overlay network. - EndpointIP string `protobuf:"bytes,1,opt,name=endpoint_ip,json=endpointIp,proto3" json:"endpoint_ip,omitempty"` - // Endpoint MAC is the mac address of the container attachment - // on the given overlay network. - EndpointMAC string `protobuf:"bytes,2,opt,name=endpoint_mac,json=endpointMac,proto3" json:"endpoint_mac,omitempty"` - // Tunnel Endpoint IP defines the host IP for the host in - // which this container is running and can be reached by - // building a tunnel to that host IP. - TunnelEndpointIP string `protobuf:"bytes,3,opt,name=tunnel_endpoint_ip,json=tunnelEndpointIp,proto3" json:"tunnel_endpoint_ip,omitempty"` -} - -func (m *PeerRecord) Reset() { *m = PeerRecord{} } -func (*PeerRecord) ProtoMessage() {} -func (*PeerRecord) Descriptor() ([]byte, []int) { return fileDescriptorOverlay, []int{0} } - -func (m *PeerRecord) GetEndpointIP() string { - if m != nil { - return m.EndpointIP - } - return "" -} - -func (m *PeerRecord) GetEndpointMAC() string { - if m != nil { - return m.EndpointMAC - } - return "" -} - -func (m *PeerRecord) GetTunnelEndpointIP() string { - if m != nil { - return m.TunnelEndpointIP - } - return "" -} - -func init() { - proto.RegisterType((*PeerRecord)(nil), "overlay.PeerRecord") -} -func (this *PeerRecord) GoString() string { - if this == nil { - return "nil" - } - s := make([]string, 0, 7) - s = append(s, "&overlay.PeerRecord{") - s = append(s, "EndpointIP: "+fmt.Sprintf("%#v", this.EndpointIP)+",\n") - s = append(s, "EndpointMAC: "+fmt.Sprintf("%#v", this.EndpointMAC)+",\n") - s = append(s, "TunnelEndpointIP: "+fmt.Sprintf("%#v", this.TunnelEndpointIP)+",\n") - s = append(s, "}") - return strings.Join(s, "") -} -func valueToGoStringOverlay(v interface{}, typ string) string { - rv := reflect.ValueOf(v) - if rv.IsNil() { - return "nil" - } - pv := reflect.Indirect(rv).Interface() - return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv) -} -func (m *PeerRecord) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalTo(dAtA) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *PeerRecord) MarshalTo(dAtA []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if len(m.EndpointIP) > 0 { - dAtA[i] = 0xa - i++ - i = encodeVarintOverlay(dAtA, i, uint64(len(m.EndpointIP))) - i += copy(dAtA[i:], m.EndpointIP) - } - if len(m.EndpointMAC) > 0 { - dAtA[i] = 0x12 - i++ - i = encodeVarintOverlay(dAtA, i, uint64(len(m.EndpointMAC))) - i += copy(dAtA[i:], m.EndpointMAC) - } - if len(m.TunnelEndpointIP) > 0 { - dAtA[i] = 0x1a - i++ - i = encodeVarintOverlay(dAtA, i, uint64(len(m.TunnelEndpointIP))) - i += copy(dAtA[i:], m.TunnelEndpointIP) - } - return i, nil -} - -func encodeVarintOverlay(dAtA []byte, offset int, v uint64) int { - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return offset + 1 -} -func (m *PeerRecord) Size() (n int) { - var l int - _ = l - l = len(m.EndpointIP) - if l > 0 { - n += 1 + l + sovOverlay(uint64(l)) - } - l = len(m.EndpointMAC) - if l > 0 { - n += 1 + l + sovOverlay(uint64(l)) - } - l = len(m.TunnelEndpointIP) - if l > 0 { - n += 1 + l + sovOverlay(uint64(l)) - } - return n -} - -func sovOverlay(x uint64) (n int) { - for { - n++ - x >>= 7 - if x == 0 { - break - } - } - return n -} -func sozOverlay(x uint64) (n int) { - return sovOverlay(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (this *PeerRecord) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&PeerRecord{`, - `EndpointIP:` + fmt.Sprintf("%v", this.EndpointIP) + `,`, - `EndpointMAC:` + fmt.Sprintf("%v", this.EndpointMAC) + `,`, - `TunnelEndpointIP:` + fmt.Sprintf("%v", this.TunnelEndpointIP) + `,`, - `}`, - }, "") - return s -} -func valueToStringOverlay(v interface{}) string { - rv := reflect.ValueOf(v) - if rv.IsNil() { - return "nil" - } - pv := reflect.Indirect(rv).Interface() - return fmt.Sprintf("*%v", pv) -} -func (m *PeerRecord) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowOverlay - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: PeerRecord: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: PeerRecord: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field EndpointIP", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowOverlay - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthOverlay - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.EndpointIP = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field EndpointMAC", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowOverlay - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthOverlay - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.EndpointMAC = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TunnelEndpointIP", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowOverlay - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthOverlay - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.TunnelEndpointIP = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipOverlay(dAtA[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthOverlay - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipOverlay(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowOverlay - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowOverlay - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - return iNdEx, nil - case 1: - iNdEx += 8 - return iNdEx, nil - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowOverlay - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - iNdEx += length - if length < 0 { - return 0, ErrInvalidLengthOverlay - } - return iNdEx, nil - case 3: - for { - var innerWire uint64 - var start int = iNdEx - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowOverlay - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - innerWire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - innerWireType := int(innerWire & 0x7) - if innerWireType == 4 { - break - } - next, err := skipOverlay(dAtA[start:]) - if err != nil { - return 0, err - } - iNdEx = start + next - } - return iNdEx, nil - case 4: - return iNdEx, nil - case 5: - iNdEx += 4 - return iNdEx, nil - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - } - panic("unreachable") -} - -var ( - ErrInvalidLengthOverlay = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowOverlay = fmt.Errorf("proto: integer overflow") -) - -func init() { proto.RegisterFile("drivers/overlay/overlay.proto", fileDescriptorOverlay) } - -var fileDescriptorOverlay = []byte{ - // 212 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4d, 0x29, 0xca, 0x2c, - 0x4b, 0x2d, 0x2a, 0xd6, 0xcf, 0x2f, 0x4b, 0x2d, 0xca, 0x49, 0xac, 0x84, 0xd1, 0x7a, 0x05, 0x45, - 0xf9, 0x25, 0xf9, 0x42, 0xec, 0x50, 0xae, 0x94, 0x48, 0x7a, 0x7e, 0x7a, 0x3e, 0x58, 0x4c, 0x1f, - 0xc4, 0x82, 0x48, 0x2b, 0x6d, 0x65, 0xe4, 0xe2, 0x0a, 0x48, 0x4d, 0x2d, 0x0a, 0x4a, 0x4d, 0xce, - 0x2f, 0x4a, 0x11, 0xd2, 0xe7, 0xe2, 0x4e, 0xcd, 0x4b, 0x29, 0xc8, 0xcf, 0xcc, 0x2b, 0x89, 0xcf, - 0x2c, 0x90, 0x60, 0x54, 0x60, 0xd4, 0xe0, 0x74, 0xe2, 0x7b, 0x74, 0x4f, 0x9e, 0xcb, 0x15, 0x2a, - 0xec, 0x19, 0x10, 0xc4, 0x05, 0x53, 0xe2, 0x59, 0x20, 0x64, 0xc4, 0xc5, 0x03, 0xd7, 0x90, 0x9b, - 0x98, 0x2c, 0xc1, 0x04, 0xd6, 0xc1, 0xff, 0xe8, 0x9e, 0x3c, 0x37, 0x4c, 0x87, 0xaf, 0xa3, 0x73, - 0x10, 0xdc, 0x54, 0xdf, 0xc4, 0x64, 0x21, 0x27, 0x2e, 0xa1, 0x92, 0xd2, 0xbc, 0xbc, 0xd4, 0x9c, - 0x78, 0x64, 0xbb, 0x98, 0xc1, 0x3a, 0x45, 0x1e, 0xdd, 0x93, 0x17, 0x08, 0x01, 0xcb, 0x22, 0xd9, - 0x28, 0x50, 0x82, 0x2a, 0x52, 0xe0, 0x24, 0x71, 0xe3, 0xa1, 0x1c, 0xc3, 0x87, 0x87, 0x72, 0x8c, - 0x0d, 0x8f, 0xe4, 0x18, 0x4f, 0x3c, 0x92, 0x63, 0xbc, 0xf0, 0x48, 0x8e, 0xf1, 0xc1, 0x23, 0x39, - 0xc6, 0x24, 0x36, 0xb0, 0xc7, 0x8c, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0x48, 0x07, 0xf6, 0xf3, - 0x18, 0x01, 0x00, 0x00, -} diff --git a/vendor/github.com/docker/libnetwork/drivers/overlay/overlay.proto b/vendor/github.com/docker/libnetwork/drivers/overlay/overlay.proto deleted file mode 100644 index 3133386e03..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/overlay/overlay.proto +++ /dev/null @@ -1,27 +0,0 @@ -syntax = "proto3"; - -import "gogoproto/gogo.proto"; - -package overlay; - -option (gogoproto.marshaler_all) = true; -option (gogoproto.unmarshaler_all) = true; -option (gogoproto.stringer_all) = true; -option (gogoproto.gostring_all) = true; -option (gogoproto.sizer_all) = true; -option (gogoproto.goproto_stringer_all) = false; - -// PeerRecord defines the information corresponding to a peer -// container in the overlay network. -message PeerRecord { - // Endpoint IP is the IP of the container attachment on the - // given overlay network. - string endpoint_ip = 1 [(gogoproto.customname) = "EndpointIP"]; - // Endpoint MAC is the mac address of the container attachment - // on the given overlay network. - string endpoint_mac = 2 [(gogoproto.customname) = "EndpointMAC"]; - // Tunnel Endpoint IP defines the host IP for the host in - // which this container is running and can be reached by - // building a tunnel to that host IP. - string tunnel_endpoint_ip = 3 [(gogoproto.customname) = "TunnelEndpointIP"]; -} diff --git a/vendor/github.com/docker/libnetwork/drivers/overlay/overlayutils/utils.go b/vendor/github.com/docker/libnetwork/drivers/overlay/overlayutils/utils.go deleted file mode 100644 index 73136e8e2a..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/overlay/overlayutils/utils.go +++ /dev/null @@ -1,46 +0,0 @@ -// Package overlayutils provides utility functions for overlay networks -package overlayutils - -import ( - "fmt" - "sync" -) - -var ( - mutex sync.RWMutex - vxlanUDPPort uint32 -) - -const defaultVXLANUDPPort = 4789 - -func init() { - vxlanUDPPort = defaultVXLANUDPPort -} - -// ConfigVXLANUDPPort configures the VXLAN UDP port (data path port) number. -// If no port is set, the default (4789) is returned. Valid port numbers are -// between 1024 and 49151. -func ConfigVXLANUDPPort(vxlanPort uint32) error { - if vxlanPort == 0 { - vxlanPort = defaultVXLANUDPPort - } - // IANA procedures for each range in detail - // The Well Known Ports, aka the System Ports, from 0-1023 - // The Registered Ports, aka the User Ports, from 1024-49151 - // The Dynamic Ports, aka the Private Ports, from 49152-65535 - // So we can allow range between 1024 to 49151 - if vxlanPort < 1024 || vxlanPort > 49151 { - return fmt.Errorf("VXLAN UDP port number is not in valid range (1024-49151): %d", vxlanPort) - } - mutex.Lock() - vxlanUDPPort = vxlanPort - mutex.Unlock() - return nil -} - -// VXLANUDPPort returns Vxlan UDP port number -func VXLANUDPPort() uint32 { - mutex.RLock() - defer mutex.RUnlock() - return vxlanUDPPort -} diff --git a/vendor/github.com/docker/libnetwork/drivers/overlay/ovmanager/ovmanager.go b/vendor/github.com/docker/libnetwork/drivers/overlay/ovmanager/ovmanager.go deleted file mode 100644 index 12deb22e44..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/overlay/ovmanager/ovmanager.go +++ /dev/null @@ -1,259 +0,0 @@ -package ovmanager - -import ( - "fmt" - "net" - "strconv" - "strings" - "sync" - - "github.com/docker/libnetwork/datastore" - "github.com/docker/libnetwork/discoverapi" - "github.com/docker/libnetwork/driverapi" - "github.com/docker/libnetwork/idm" - "github.com/docker/libnetwork/netlabel" - "github.com/docker/libnetwork/types" - "github.com/sirupsen/logrus" -) - -const ( - networkType = "overlay" - vxlanIDStart = 4096 - vxlanIDEnd = (1 << 24) - 1 -) - -type networkTable map[string]*network - -type driver struct { - config map[string]interface{} - networks networkTable - store datastore.DataStore - vxlanIdm *idm.Idm - sync.Mutex -} - -type subnet struct { - subnetIP *net.IPNet - gwIP *net.IPNet - vni uint32 -} - -type network struct { - id string - driver *driver - subnets []*subnet - sync.Mutex -} - -// Init registers a new instance of overlay driver -func Init(dc driverapi.DriverCallback, config map[string]interface{}) error { - var err error - c := driverapi.Capability{ - DataScope: datastore.GlobalScope, - ConnectivityScope: datastore.GlobalScope, - } - - d := &driver{ - networks: networkTable{}, - config: config, - } - - d.vxlanIdm, err = idm.New(nil, "vxlan-id", 0, vxlanIDEnd) - if err != nil { - return fmt.Errorf("failed to initialize vxlan id manager: %v", err) - } - - return dc.RegisterDriver(networkType, d, c) -} - -func (d *driver) NetworkAllocate(id string, option map[string]string, ipV4Data, ipV6Data []driverapi.IPAMData) (map[string]string, error) { - if id == "" { - return nil, fmt.Errorf("invalid network id for overlay network") - } - - if ipV4Data == nil { - return nil, fmt.Errorf("empty ipv4 data passed during overlay network creation") - } - - n := &network{ - id: id, - driver: d, - subnets: []*subnet{}, - } - - opts := make(map[string]string) - vxlanIDList := make([]uint32, 0, len(ipV4Data)) - for key, val := range option { - if key == netlabel.OverlayVxlanIDList { - logrus.Debugf("overlay network option: %s", val) - valStrList := strings.Split(val, ",") - for _, idStr := range valStrList { - vni, err := strconv.Atoi(idStr) - if err != nil { - return nil, fmt.Errorf("invalid vxlan id value %q passed", idStr) - } - - vxlanIDList = append(vxlanIDList, uint32(vni)) - } - } else { - opts[key] = val - } - } - - for i, ipd := range ipV4Data { - s := &subnet{ - subnetIP: ipd.Pool, - gwIP: ipd.Gateway, - } - - if len(vxlanIDList) > i { - s.vni = vxlanIDList[i] - } - - if err := n.obtainVxlanID(s); err != nil { - n.releaseVxlanID() - return nil, fmt.Errorf("could not obtain vxlan id for pool %s: %v", s.subnetIP, err) - } - - n.subnets = append(n.subnets, s) - } - - val := fmt.Sprintf("%d", n.subnets[0].vni) - for _, s := range n.subnets[1:] { - val = val + fmt.Sprintf(",%d", s.vni) - } - opts[netlabel.OverlayVxlanIDList] = val - - d.Lock() - defer d.Unlock() - if _, ok := d.networks[id]; ok { - n.releaseVxlanID() - return nil, fmt.Errorf("network %s already exists", id) - } - d.networks[id] = n - - return opts, nil -} - -func (d *driver) NetworkFree(id string) error { - if id == "" { - return fmt.Errorf("invalid network id passed while freeing overlay network") - } - - d.Lock() - defer d.Unlock() - n, ok := d.networks[id] - - if !ok { - return fmt.Errorf("overlay network with id %s not found", id) - } - - // Release all vxlan IDs in one shot. - n.releaseVxlanID() - - delete(d.networks, id) - - return nil -} - -func (n *network) obtainVxlanID(s *subnet) error { - var ( - err error - vni uint64 - ) - - n.Lock() - vni = uint64(s.vni) - n.Unlock() - - if vni == 0 { - vni, err = n.driver.vxlanIdm.GetIDInRange(vxlanIDStart, vxlanIDEnd, true) - if err != nil { - return err - } - - n.Lock() - s.vni = uint32(vni) - n.Unlock() - return nil - } - - return n.driver.vxlanIdm.GetSpecificID(vni) -} - -func (n *network) releaseVxlanID() { - n.Lock() - vnis := make([]uint32, 0, len(n.subnets)) - for _, s := range n.subnets { - vnis = append(vnis, s.vni) - s.vni = 0 - } - n.Unlock() - - for _, vni := range vnis { - n.driver.vxlanIdm.Release(uint64(vni)) - } -} - -func (d *driver) CreateNetwork(id string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) EventNotify(etype driverapi.EventType, nid, tableName, key string, value []byte) { -} - -func (d *driver) DecodeTableEntry(tablename string, key string, value []byte) (string, map[string]string) { - return "", nil -} - -func (d *driver) DeleteNetwork(nid string) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo, epOptions map[string]interface{}) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) DeleteEndpoint(nid, eid string) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) EndpointOperInfo(nid, eid string) (map[string]interface{}, error) { - return nil, types.NotImplementedErrorf("not implemented") -} - -// Join method is invoked when a Sandbox is attached to an endpoint. -func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error { - return types.NotImplementedErrorf("not implemented") -} - -// Leave method is invoked when a Sandbox detaches from an endpoint. -func (d *driver) Leave(nid, eid string) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) Type() string { - return networkType -} - -func (d *driver) IsBuiltIn() bool { - return true -} - -// DiscoverNew is a notification for a new discovery event, such as a new node joining a cluster -func (d *driver) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error { - return types.NotImplementedErrorf("not implemented") -} - -// DiscoverDelete is a notification for a discovery delete event, such as a node leaving a cluster -func (d *driver) DiscoverDelete(dType discoverapi.DiscoveryType, data interface{}) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) ProgramExternalConnectivity(nid, eid string, options map[string]interface{}) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) RevokeExternalConnectivity(nid, eid string) error { - return types.NotImplementedErrorf("not implemented") -} diff --git a/vendor/github.com/docker/libnetwork/drivers/overlay/peerdb.go b/vendor/github.com/docker/libnetwork/drivers/overlay/peerdb.go deleted file mode 100644 index 58d70d04d8..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/overlay/peerdb.go +++ /dev/null @@ -1,526 +0,0 @@ -package overlay - -import ( - "context" - "fmt" - "net" - "sync" - "syscall" - - "github.com/docker/libnetwork/internal/caller" - "github.com/docker/libnetwork/internal/setmatrix" - "github.com/docker/libnetwork/osl" - "github.com/sirupsen/logrus" -) - -const ovPeerTable = "overlay_peer_table" - -type peerKey struct { - peerIP net.IP - peerMac net.HardwareAddr -} - -type peerEntry struct { - eid string - vtep net.IP - peerIPMask net.IPMask - isLocal bool -} - -func (p *peerEntry) MarshalDB() peerEntryDB { - ones, bits := p.peerIPMask.Size() - return peerEntryDB{ - eid: p.eid, - vtep: p.vtep.String(), - peerIPMaskOnes: ones, - peerIPMaskBits: bits, - isLocal: p.isLocal, - } -} - -// This the structure saved into the set (SetMatrix), due to the implementation of it -// the value inserted in the set has to be Hashable so the []byte had to be converted into -// strings -type peerEntryDB struct { - eid string - vtep string - peerIPMaskOnes int - peerIPMaskBits int - isLocal bool -} - -func (p *peerEntryDB) UnMarshalDB() peerEntry { - return peerEntry{ - eid: p.eid, - vtep: net.ParseIP(p.vtep), - peerIPMask: net.CIDRMask(p.peerIPMaskOnes, p.peerIPMaskBits), - isLocal: p.isLocal, - } -} - -type peerMap struct { - // set of peerEntry, note they have to be objects and not pointers to maintain the proper equality checks - mp setmatrix.SetMatrix - sync.Mutex -} - -type peerNetworkMap struct { - // map with key peerKey - mp map[string]*peerMap - sync.Mutex -} - -func (pKey peerKey) String() string { - return fmt.Sprintf("%s %s", pKey.peerIP, pKey.peerMac) -} - -func (pKey *peerKey) Scan(state fmt.ScanState, verb rune) error { - ipB, err := state.Token(true, nil) - if err != nil { - return err - } - - pKey.peerIP = net.ParseIP(string(ipB)) - - macB, err := state.Token(true, nil) - if err != nil { - return err - } - - pKey.peerMac, err = net.ParseMAC(string(macB)) - return err -} - -func (d *driver) peerDbWalk(f func(string, *peerKey, *peerEntry) bool) error { - d.peerDb.Lock() - nids := []string{} - for nid := range d.peerDb.mp { - nids = append(nids, nid) - } - d.peerDb.Unlock() - - for _, nid := range nids { - d.peerDbNetworkWalk(nid, func(pKey *peerKey, pEntry *peerEntry) bool { - return f(nid, pKey, pEntry) - }) - } - return nil -} - -func (d *driver) peerDbNetworkWalk(nid string, f func(*peerKey, *peerEntry) bool) error { - d.peerDb.Lock() - pMap, ok := d.peerDb.mp[nid] - d.peerDb.Unlock() - - if !ok { - return nil - } - - mp := map[string]peerEntry{} - pMap.Lock() - for _, pKeyStr := range pMap.mp.Keys() { - entryDBList, ok := pMap.mp.Get(pKeyStr) - if ok { - peerEntryDB := entryDBList[0].(peerEntryDB) - mp[pKeyStr] = peerEntryDB.UnMarshalDB() - } - } - pMap.Unlock() - - for pKeyStr, pEntry := range mp { - var pKey peerKey - if _, err := fmt.Sscan(pKeyStr, &pKey); err != nil { - logrus.Warnf("Peer key scan on network %s failed: %v", nid, err) - } - if f(&pKey, &pEntry) { - return nil - } - } - - return nil -} - -func (d *driver) peerDbSearch(nid string, peerIP net.IP) (*peerKey, *peerEntry, error) { - var pKeyMatched *peerKey - var pEntryMatched *peerEntry - err := d.peerDbNetworkWalk(nid, func(pKey *peerKey, pEntry *peerEntry) bool { - if pKey.peerIP.Equal(peerIP) { - pKeyMatched = pKey - pEntryMatched = pEntry - return true - } - - return false - }) - - if err != nil { - return nil, nil, fmt.Errorf("peerdb search for peer ip %q failed: %v", peerIP, err) - } - - if pKeyMatched == nil || pEntryMatched == nil { - return nil, nil, fmt.Errorf("peer ip %q not found in peerdb", peerIP) - } - - return pKeyMatched, pEntryMatched, nil -} - -func (d *driver) peerDbAdd(nid, eid string, peerIP net.IP, peerIPMask net.IPMask, - peerMac net.HardwareAddr, vtep net.IP, isLocal bool) (bool, int) { - - d.peerDb.Lock() - pMap, ok := d.peerDb.mp[nid] - if !ok { - d.peerDb.mp[nid] = &peerMap{ - mp: setmatrix.NewSetMatrix(), - } - - pMap = d.peerDb.mp[nid] - } - d.peerDb.Unlock() - - pKey := peerKey{ - peerIP: peerIP, - peerMac: peerMac, - } - - pEntry := peerEntry{ - eid: eid, - vtep: vtep, - peerIPMask: peerIPMask, - isLocal: isLocal, - } - - pMap.Lock() - defer pMap.Unlock() - b, i := pMap.mp.Insert(pKey.String(), pEntry.MarshalDB()) - if i != 1 { - // Transient case, there is more than one endpoint that is using the same IP,MAC pair - s, _ := pMap.mp.String(pKey.String()) - logrus.Warnf("peerDbAdd transient condition - Key:%s cardinality:%d db state:%s", pKey.String(), i, s) - } - return b, i -} - -func (d *driver) peerDbDelete(nid, eid string, peerIP net.IP, peerIPMask net.IPMask, - peerMac net.HardwareAddr, vtep net.IP, isLocal bool) (bool, int) { - - d.peerDb.Lock() - pMap, ok := d.peerDb.mp[nid] - if !ok { - d.peerDb.Unlock() - return false, 0 - } - d.peerDb.Unlock() - - pKey := peerKey{ - peerIP: peerIP, - peerMac: peerMac, - } - - pEntry := peerEntry{ - eid: eid, - vtep: vtep, - peerIPMask: peerIPMask, - isLocal: isLocal, - } - - pMap.Lock() - defer pMap.Unlock() - b, i := pMap.mp.Remove(pKey.String(), pEntry.MarshalDB()) - if i != 0 { - // Transient case, there is more than one endpoint that is using the same IP,MAC pair - s, _ := pMap.mp.String(pKey.String()) - logrus.Warnf("peerDbDelete transient condition - Key:%s cardinality:%d db state:%s", pKey.String(), i, s) - } - return b, i -} - -// The overlay uses a lazy initialization approach, this means that when a network is created -// and the driver registered the overlay does not allocate resources till the moment that a -// sandbox is actually created. -// At the moment of this call, that happens when a sandbox is initialized, is possible that -// networkDB has already delivered some events of peers already available on remote nodes, -// these peers are saved into the peerDB and this function is used to properly configure -// the network sandbox with all those peers that got previously notified. -// Note also that this method sends a single message on the channel and the go routine on the -// other side, will atomically loop on the whole table of peers and will program their state -// in one single atomic operation. This is fundamental to guarantee consistency, and avoid that -// new peerAdd or peerDelete gets reordered during the sandbox init. -func (d *driver) initSandboxPeerDB(nid string) { - d.peerInit(nid) -} - -type peerOperationType int32 - -const ( - peerOperationINIT peerOperationType = iota - peerOperationADD - peerOperationDELETE - peerOperationFLUSH -) - -type peerOperation struct { - opType peerOperationType - networkID string - endpointID string - peerIP net.IP - peerIPMask net.IPMask - peerMac net.HardwareAddr - vtepIP net.IP - l2Miss bool - l3Miss bool - localPeer bool - callerName string -} - -func (d *driver) peerOpRoutine(ctx context.Context, ch chan *peerOperation) { - var err error - for { - select { - case <-ctx.Done(): - return - case op := <-ch: - switch op.opType { - case peerOperationINIT: - err = d.peerInitOp(op.networkID) - case peerOperationADD: - err = d.peerAddOp(op.networkID, op.endpointID, op.peerIP, op.peerIPMask, op.peerMac, op.vtepIP, op.l2Miss, op.l3Miss, true, op.localPeer) - case peerOperationDELETE: - err = d.peerDeleteOp(op.networkID, op.endpointID, op.peerIP, op.peerIPMask, op.peerMac, op.vtepIP, op.localPeer) - case peerOperationFLUSH: - err = d.peerFlushOp(op.networkID) - } - if err != nil { - logrus.Warnf("Peer operation failed:%s op:%v", err, op) - } - } - } -} - -func (d *driver) peerInit(nid string) { - callerName := caller.Name(1) - d.peerOpCh <- &peerOperation{ - opType: peerOperationINIT, - networkID: nid, - callerName: callerName, - } -} - -func (d *driver) peerInitOp(nid string) error { - return d.peerDbNetworkWalk(nid, func(pKey *peerKey, pEntry *peerEntry) bool { - // Local entries do not need to be added - if pEntry.isLocal { - return false - } - - d.peerAddOp(nid, pEntry.eid, pKey.peerIP, pEntry.peerIPMask, pKey.peerMac, pEntry.vtep, false, false, false, pEntry.isLocal) - // return false to loop on all entries - return false - }) -} - -func (d *driver) peerAdd(nid, eid string, peerIP net.IP, peerIPMask net.IPMask, - peerMac net.HardwareAddr, vtep net.IP, l2Miss, l3Miss, localPeer bool) { - d.peerOpCh <- &peerOperation{ - opType: peerOperationADD, - networkID: nid, - endpointID: eid, - peerIP: peerIP, - peerIPMask: peerIPMask, - peerMac: peerMac, - vtepIP: vtep, - l2Miss: l2Miss, - l3Miss: l3Miss, - localPeer: localPeer, - callerName: caller.Name(1), - } -} - -func (d *driver) peerAddOp(nid, eid string, peerIP net.IP, peerIPMask net.IPMask, - peerMac net.HardwareAddr, vtep net.IP, l2Miss, l3Miss, updateDB, localPeer bool) error { - - if err := validateID(nid, eid); err != nil { - return err - } - - var dbEntries int - var inserted bool - if updateDB { - inserted, dbEntries = d.peerDbAdd(nid, eid, peerIP, peerIPMask, peerMac, vtep, localPeer) - if !inserted { - logrus.Warnf("Entry already present in db: nid:%s eid:%s peerIP:%v peerMac:%v isLocal:%t vtep:%v", - nid, eid, peerIP, peerMac, localPeer, vtep) - } - } - - // Local peers do not need any further configuration - if localPeer { - return nil - } - - n := d.network(nid) - if n == nil { - return nil - } - - sbox := n.sandbox() - if sbox == nil { - // We are hitting this case for all the events that are arriving before that the sandbox - // is being created. The peer got already added into the database and the sanbox init will - // call the peerDbUpdateSandbox that will configure all these peers from the database - return nil - } - - IP := &net.IPNet{ - IP: peerIP, - Mask: peerIPMask, - } - - s := n.getSubnetforIP(IP) - if s == nil { - return fmt.Errorf("couldn't find the subnet %q in network %q", IP.String(), n.id) - } - - if err := n.obtainVxlanID(s); err != nil { - return fmt.Errorf("couldn't get vxlan id for %q: %v", s.subnetIP.String(), err) - } - - if err := n.joinSandbox(s, false, false); err != nil { - return fmt.Errorf("subnet sandbox join failed for %q: %v", s.subnetIP.String(), err) - } - - if err := d.checkEncryption(nid, vtep, n.vxlanID(s), false, true); err != nil { - logrus.Warn(err) - } - - // Add neighbor entry for the peer IP - if err := sbox.AddNeighbor(peerIP, peerMac, l3Miss, sbox.NeighborOptions().LinkName(s.vxlanName)); err != nil { - if _, ok := err.(osl.NeighborSearchError); ok && dbEntries > 1 { - // We are in the transient case so only the first configuration is programmed into the kernel - // Upon deletion if the active configuration is deleted the next one from the database will be restored - // Note we are skipping also the next configuration - return nil - } - return fmt.Errorf("could not add neighbor entry for nid:%s eid:%s into the sandbox:%v", nid, eid, err) - } - - // Add fdb entry to the bridge for the peer mac - if err := sbox.AddNeighbor(vtep, peerMac, l2Miss, sbox.NeighborOptions().LinkName(s.vxlanName), - sbox.NeighborOptions().Family(syscall.AF_BRIDGE)); err != nil { - return fmt.Errorf("could not add fdb entry for nid:%s eid:%s into the sandbox:%v", nid, eid, err) - } - - return nil -} - -func (d *driver) peerDelete(nid, eid string, peerIP net.IP, peerIPMask net.IPMask, - peerMac net.HardwareAddr, vtep net.IP, localPeer bool) { - d.peerOpCh <- &peerOperation{ - opType: peerOperationDELETE, - networkID: nid, - endpointID: eid, - peerIP: peerIP, - peerIPMask: peerIPMask, - peerMac: peerMac, - vtepIP: vtep, - callerName: caller.Name(1), - localPeer: localPeer, - } -} - -func (d *driver) peerDeleteOp(nid, eid string, peerIP net.IP, peerIPMask net.IPMask, - peerMac net.HardwareAddr, vtep net.IP, localPeer bool) error { - - if err := validateID(nid, eid); err != nil { - return err - } - - deleted, dbEntries := d.peerDbDelete(nid, eid, peerIP, peerIPMask, peerMac, vtep, localPeer) - if !deleted { - logrus.Warnf("Entry was not in db: nid:%s eid:%s peerIP:%v peerMac:%v isLocal:%t vtep:%v", - nid, eid, peerIP, peerMac, localPeer, vtep) - } - - n := d.network(nid) - if n == nil { - return nil - } - - sbox := n.sandbox() - if sbox == nil { - return nil - } - - if err := d.checkEncryption(nid, vtep, 0, localPeer, false); err != nil { - logrus.Warn(err) - } - - // Local peers do not have any local configuration to delete - if !localPeer { - // Remove fdb entry to the bridge for the peer mac - if err := sbox.DeleteNeighbor(vtep, peerMac, true); err != nil { - if _, ok := err.(osl.NeighborSearchError); ok && dbEntries > 0 { - // We fall in here if there is a transient state and if the neighbor that is being deleted - // was never been configured into the kernel (we allow only 1 configuration at the time per mapping) - return nil - } - return fmt.Errorf("could not delete fdb entry for nid:%s eid:%s into the sandbox:%v", nid, eid, err) - } - - // Delete neighbor entry for the peer IP - if err := sbox.DeleteNeighbor(peerIP, peerMac, true); err != nil { - return fmt.Errorf("could not delete neighbor entry for nid:%s eid:%s into the sandbox:%v", nid, eid, err) - } - } - - if dbEntries == 0 { - return nil - } - - // If there is still an entry into the database and the deletion went through without errors means that there is now no - // configuration active in the kernel. - // Restore one configuration for the directly from the database, note that is guaranteed that there is one - peerKey, peerEntry, err := d.peerDbSearch(nid, peerIP) - if err != nil { - logrus.Errorf("peerDeleteOp unable to restore a configuration for nid:%s ip:%v mac:%v err:%s", nid, peerIP, peerMac, err) - return err - } - return d.peerAddOp(nid, peerEntry.eid, peerIP, peerEntry.peerIPMask, peerKey.peerMac, peerEntry.vtep, false, false, false, peerEntry.isLocal) -} - -func (d *driver) peerFlush(nid string) { - d.peerOpCh <- &peerOperation{ - opType: peerOperationFLUSH, - networkID: nid, - callerName: caller.Name(1), - } -} - -func (d *driver) peerFlushOp(nid string) error { - d.peerDb.Lock() - defer d.peerDb.Unlock() - _, ok := d.peerDb.mp[nid] - if !ok { - return fmt.Errorf("Unable to find the peerDB for nid:%s", nid) - } - delete(d.peerDb.mp, nid) - return nil -} - -func (d *driver) pushLocalDb() { - d.peerDbWalk(func(nid string, pKey *peerKey, pEntry *peerEntry) bool { - if pEntry.isLocal { - d.pushLocalEndpointEvent("join", nid, pEntry.eid) - } - return false - }) -} - -func (d *driver) peerDBUpdateSelf() { - d.peerDbWalk(func(nid string, pkey *peerKey, pEntry *peerEntry) bool { - if pEntry.isLocal { - pEntry.vtep = net.ParseIP(d.advertiseAddress) - } - return false - }) -} diff --git a/vendor/github.com/docker/libnetwork/drivers/remote/api/api.go b/vendor/github.com/docker/libnetwork/drivers/remote/api/api.go deleted file mode 100644 index fb35da5928..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/remote/api/api.go +++ /dev/null @@ -1,221 +0,0 @@ -/* -Package api represents all requests and responses suitable for conversation -with a remote driver. -*/ -package api - -import ( - "net" - - "github.com/docker/libnetwork/discoverapi" - "github.com/docker/libnetwork/driverapi" -) - -// Response is the basic response structure used in all responses. -type Response struct { - Err string -} - -// GetError returns the error from the response, if any. -func (r *Response) GetError() string { - return r.Err -} - -// GetCapabilityResponse is the response of GetCapability request -type GetCapabilityResponse struct { - Response - Scope string - ConnectivityScope string -} - -// AllocateNetworkRequest requests allocation of new network by manager -type AllocateNetworkRequest struct { - // A network ID that remote plugins are expected to store for future - // reference. - NetworkID string - - // A free form map->object interface for communication of options. - Options map[string]string - - // IPAMData contains the address pool information for this network - IPv4Data, IPv6Data []driverapi.IPAMData -} - -// AllocateNetworkResponse is the response to the AllocateNetworkRequest. -type AllocateNetworkResponse struct { - Response - // A free form plugin specific string->string object to be sent in - // CreateNetworkRequest call in the libnetwork agents - Options map[string]string -} - -// FreeNetworkRequest is the request to free allocated network in the manager -type FreeNetworkRequest struct { - // The ID of the network to be freed. - NetworkID string -} - -// FreeNetworkResponse is the response to a request for freeing a network. -type FreeNetworkResponse struct { - Response -} - -// CreateNetworkRequest requests a new network. -type CreateNetworkRequest struct { - // A network ID that remote plugins are expected to store for future - // reference. - NetworkID string - - // A free form map->object interface for communication of options. - Options map[string]interface{} - - // IPAMData contains the address pool information for this network - IPv4Data, IPv6Data []driverapi.IPAMData -} - -// CreateNetworkResponse is the response to the CreateNetworkRequest. -type CreateNetworkResponse struct { - Response -} - -// DeleteNetworkRequest is the request to delete an existing network. -type DeleteNetworkRequest struct { - // The ID of the network to delete. - NetworkID string -} - -// DeleteNetworkResponse is the response to a request for deleting a network. -type DeleteNetworkResponse struct { - Response -} - -// CreateEndpointRequest is the request to create an endpoint within a network. -type CreateEndpointRequest struct { - // Provided at create time, this will be the network id referenced. - NetworkID string - // The ID of the endpoint for later reference. - EndpointID string - Interface *EndpointInterface - Options map[string]interface{} -} - -// EndpointInterface represents an interface endpoint. -type EndpointInterface struct { - Address string - AddressIPv6 string - MacAddress string -} - -// CreateEndpointResponse is the response to the CreateEndpoint action. -type CreateEndpointResponse struct { - Response - Interface *EndpointInterface -} - -// Interface is the representation of a linux interface. -type Interface struct { - Address *net.IPNet - AddressIPv6 *net.IPNet - MacAddress net.HardwareAddr -} - -// DeleteEndpointRequest describes the API for deleting an endpoint. -type DeleteEndpointRequest struct { - NetworkID string - EndpointID string -} - -// DeleteEndpointResponse is the response to the DeleteEndpoint action. -type DeleteEndpointResponse struct { - Response -} - -// EndpointInfoRequest retrieves information about the endpoint from the network driver. -type EndpointInfoRequest struct { - NetworkID string - EndpointID string -} - -// EndpointInfoResponse is the response to an EndpointInfoRequest. -type EndpointInfoResponse struct { - Response - Value map[string]interface{} -} - -// JoinRequest describes the API for joining an endpoint to a sandbox. -type JoinRequest struct { - NetworkID string - EndpointID string - SandboxKey string - Options map[string]interface{} -} - -// InterfaceName is the struct representation of a pair of devices with source -// and destination, for the purposes of putting an endpoint into a container. -type InterfaceName struct { - SrcName string - DstName string - DstPrefix string -} - -// StaticRoute is the plain JSON representation of a static route. -type StaticRoute struct { - Destination string - RouteType int - NextHop string -} - -// JoinResponse is the response to a JoinRequest. -type JoinResponse struct { - Response - InterfaceName *InterfaceName - Gateway string - GatewayIPv6 string - StaticRoutes []StaticRoute - DisableGatewayService bool -} - -// LeaveRequest describes the API for detaching an endpoint from a sandbox. -type LeaveRequest struct { - NetworkID string - EndpointID string -} - -// LeaveResponse is the answer to LeaveRequest. -type LeaveResponse struct { - Response -} - -// ProgramExternalConnectivityRequest describes the API for programming the external connectivity for the given endpoint. -type ProgramExternalConnectivityRequest struct { - NetworkID string - EndpointID string - Options map[string]interface{} -} - -// ProgramExternalConnectivityResponse is the answer to ProgramExternalConnectivityRequest. -type ProgramExternalConnectivityResponse struct { - Response -} - -// RevokeExternalConnectivityRequest describes the API for revoking the external connectivity for the given endpoint. -type RevokeExternalConnectivityRequest struct { - NetworkID string - EndpointID string -} - -// RevokeExternalConnectivityResponse is the answer to RevokeExternalConnectivityRequest. -type RevokeExternalConnectivityResponse struct { - Response -} - -// DiscoveryNotification represents a discovery notification -type DiscoveryNotification struct { - DiscoveryType discoverapi.DiscoveryType - DiscoveryData interface{} -} - -// DiscoveryResponse is used by libnetwork to log any plugin error processing the discovery notifications -type DiscoveryResponse struct { - Response -} diff --git a/vendor/github.com/docker/libnetwork/drivers/remote/driver.go b/vendor/github.com/docker/libnetwork/drivers/remote/driver.go deleted file mode 100644 index 9786d9e746..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/remote/driver.go +++ /dev/null @@ -1,436 +0,0 @@ -package remote - -import ( - "fmt" - "net" - - "github.com/docker/docker/pkg/plugingetter" - "github.com/docker/docker/pkg/plugins" - "github.com/docker/libnetwork/datastore" - "github.com/docker/libnetwork/discoverapi" - "github.com/docker/libnetwork/driverapi" - "github.com/docker/libnetwork/drivers/remote/api" - "github.com/docker/libnetwork/types" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" -) - -type driver struct { - endpoint *plugins.Client - networkType string -} - -type maybeError interface { - GetError() string -} - -func newDriver(name string, client *plugins.Client) driverapi.Driver { - return &driver{networkType: name, endpoint: client} -} - -// Init makes sure a remote driver is registered when a network driver -// plugin is activated. -func Init(dc driverapi.DriverCallback, config map[string]interface{}) error { - newPluginHandler := func(name string, client *plugins.Client) { - // negotiate driver capability with client - d := newDriver(name, client) - c, err := d.(*driver).getCapabilities() - if err != nil { - logrus.Errorf("error getting capability for %s due to %v", name, err) - return - } - if err = dc.RegisterDriver(name, d, *c); err != nil { - logrus.Errorf("error registering driver for %s due to %v", name, err) - } - } - - // Unit test code is unaware of a true PluginStore. So we fall back to v1 plugins. - handleFunc := plugins.Handle - if pg := dc.GetPluginGetter(); pg != nil { - handleFunc = pg.Handle - activePlugins := pg.GetAllManagedPluginsByCap(driverapi.NetworkPluginEndpointType) - for _, ap := range activePlugins { - client, err := getPluginClient(ap) - if err != nil { - return err - } - newPluginHandler(ap.Name(), client) - } - } - handleFunc(driverapi.NetworkPluginEndpointType, newPluginHandler) - - return nil -} - -func getPluginClient(p plugingetter.CompatPlugin) (*plugins.Client, error) { - if v1, ok := p.(plugingetter.PluginWithV1Client); ok { - return v1.Client(), nil - } - - pa, ok := p.(plugingetter.PluginAddr) - if !ok { - return nil, errors.Errorf("unknown plugin type %T", p) - } - - if pa.Protocol() != plugins.ProtocolSchemeHTTPV1 { - return nil, errors.Errorf("unsupported plugin protocol %s", pa.Protocol()) - } - - addr := pa.Addr() - client, err := plugins.NewClientWithTimeout(addr.Network()+"://"+addr.String(), nil, pa.Timeout()) - if err != nil { - return nil, errors.Wrap(err, "error creating plugin client") - } - return client, nil -} - -// Get capability from client -func (d *driver) getCapabilities() (*driverapi.Capability, error) { - var capResp api.GetCapabilityResponse - if err := d.call("GetCapabilities", nil, &capResp); err != nil { - return nil, err - } - - c := &driverapi.Capability{} - switch capResp.Scope { - case "global": - c.DataScope = datastore.GlobalScope - case "local": - c.DataScope = datastore.LocalScope - default: - return nil, fmt.Errorf("invalid capability: expecting 'local' or 'global', got %s", capResp.Scope) - } - - switch capResp.ConnectivityScope { - case "global": - c.ConnectivityScope = datastore.GlobalScope - case "local": - c.ConnectivityScope = datastore.LocalScope - case "": - c.ConnectivityScope = c.DataScope - default: - return nil, fmt.Errorf("invalid capability: expecting 'local' or 'global', got %s", capResp.Scope) - } - - return c, nil -} - -// Config is not implemented for remote drivers, since it is assumed -// to be supplied to the remote process out-of-band (e.g., as command -// line arguments). -func (d *driver) Config(option map[string]interface{}) error { - return &driverapi.ErrNotImplemented{} -} - -func (d *driver) call(methodName string, arg interface{}, retVal maybeError) error { - method := driverapi.NetworkPluginEndpointType + "." + methodName - err := d.endpoint.Call(method, arg, retVal) - if err != nil { - return err - } - if e := retVal.GetError(); e != "" { - return fmt.Errorf("remote: %s", e) - } - return nil -} - -func (d *driver) NetworkAllocate(id string, options map[string]string, ipV4Data, ipV6Data []driverapi.IPAMData) (map[string]string, error) { - create := &api.AllocateNetworkRequest{ - NetworkID: id, - Options: options, - IPv4Data: ipV4Data, - IPv6Data: ipV6Data, - } - retVal := api.AllocateNetworkResponse{} - err := d.call("AllocateNetwork", create, &retVal) - return retVal.Options, err -} - -func (d *driver) NetworkFree(id string) error { - fr := &api.FreeNetworkRequest{NetworkID: id} - return d.call("FreeNetwork", fr, &api.FreeNetworkResponse{}) -} - -func (d *driver) EventNotify(etype driverapi.EventType, nid, tableName, key string, value []byte) { -} - -func (d *driver) DecodeTableEntry(tablename string, key string, value []byte) (string, map[string]string) { - return "", nil -} - -func (d *driver) CreateNetwork(id string, options map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error { - create := &api.CreateNetworkRequest{ - NetworkID: id, - Options: options, - IPv4Data: ipV4Data, - IPv6Data: ipV6Data, - } - return d.call("CreateNetwork", create, &api.CreateNetworkResponse{}) -} - -func (d *driver) DeleteNetwork(nid string) error { - delete := &api.DeleteNetworkRequest{NetworkID: nid} - return d.call("DeleteNetwork", delete, &api.DeleteNetworkResponse{}) -} - -func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo, epOptions map[string]interface{}) error { - if ifInfo == nil { - return errors.New("must not be called with nil InterfaceInfo") - } - - reqIface := &api.EndpointInterface{} - if ifInfo.Address() != nil { - reqIface.Address = ifInfo.Address().String() - } - if ifInfo.AddressIPv6() != nil { - reqIface.AddressIPv6 = ifInfo.AddressIPv6().String() - } - if ifInfo.MacAddress() != nil { - reqIface.MacAddress = ifInfo.MacAddress().String() - } - - create := &api.CreateEndpointRequest{ - NetworkID: nid, - EndpointID: eid, - Interface: reqIface, - Options: epOptions, - } - var res api.CreateEndpointResponse - if err := d.call("CreateEndpoint", create, &res); err != nil { - return err - } - - inIface, err := parseInterface(res) - if err != nil { - return err - } - if inIface == nil { - // Remote driver did not set any field - return nil - } - - if inIface.MacAddress != nil { - if err := ifInfo.SetMacAddress(inIface.MacAddress); err != nil { - return errorWithRollback(fmt.Sprintf("driver modified interface MAC address: %v", err), d.DeleteEndpoint(nid, eid)) - } - } - if inIface.Address != nil { - if err := ifInfo.SetIPAddress(inIface.Address); err != nil { - return errorWithRollback(fmt.Sprintf("driver modified interface address: %v", err), d.DeleteEndpoint(nid, eid)) - } - } - if inIface.AddressIPv6 != nil { - if err := ifInfo.SetIPAddress(inIface.AddressIPv6); err != nil { - return errorWithRollback(fmt.Sprintf("driver modified interface address: %v", err), d.DeleteEndpoint(nid, eid)) - } - } - - return nil -} - -func errorWithRollback(msg string, err error) error { - rollback := "rolled back" - if err != nil { - rollback = "failed to roll back: " + err.Error() - } - return fmt.Errorf("%s; %s", msg, rollback) -} - -func (d *driver) DeleteEndpoint(nid, eid string) error { - delete := &api.DeleteEndpointRequest{ - NetworkID: nid, - EndpointID: eid, - } - return d.call("DeleteEndpoint", delete, &api.DeleteEndpointResponse{}) -} - -func (d *driver) EndpointOperInfo(nid, eid string) (map[string]interface{}, error) { - info := &api.EndpointInfoRequest{ - NetworkID: nid, - EndpointID: eid, - } - var res api.EndpointInfoResponse - if err := d.call("EndpointOperInfo", info, &res); err != nil { - return nil, err - } - return res.Value, nil -} - -// Join method is invoked when a Sandbox is attached to an endpoint. -func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error { - join := &api.JoinRequest{ - NetworkID: nid, - EndpointID: eid, - SandboxKey: sboxKey, - Options: options, - } - var ( - res api.JoinResponse - err error - ) - if err = d.call("Join", join, &res); err != nil { - return err - } - - ifaceName := res.InterfaceName - if iface := jinfo.InterfaceName(); iface != nil && ifaceName != nil { - if err := iface.SetNames(ifaceName.SrcName, ifaceName.DstPrefix); err != nil { - return errorWithRollback(fmt.Sprintf("failed to set interface name: %s", err), d.Leave(nid, eid)) - } - } - - var addr net.IP - if res.Gateway != "" { - if addr = net.ParseIP(res.Gateway); addr == nil { - return fmt.Errorf(`unable to parse Gateway "%s"`, res.Gateway) - } - if jinfo.SetGateway(addr) != nil { - return errorWithRollback(fmt.Sprintf("failed to set gateway: %v", addr), d.Leave(nid, eid)) - } - } - if res.GatewayIPv6 != "" { - if addr = net.ParseIP(res.GatewayIPv6); addr == nil { - return fmt.Errorf(`unable to parse GatewayIPv6 "%s"`, res.GatewayIPv6) - } - if jinfo.SetGatewayIPv6(addr) != nil { - return errorWithRollback(fmt.Sprintf("failed to set gateway IPv6: %v", addr), d.Leave(nid, eid)) - } - } - if len(res.StaticRoutes) > 0 { - routes, err := parseStaticRoutes(res) - if err != nil { - return err - } - for _, route := range routes { - if jinfo.AddStaticRoute(route.Destination, route.RouteType, route.NextHop) != nil { - return errorWithRollback(fmt.Sprintf("failed to set static route: %v", route), d.Leave(nid, eid)) - } - } - } - if res.DisableGatewayService { - jinfo.DisableGatewayService() - } - return nil -} - -// Leave method is invoked when a Sandbox detaches from an endpoint. -func (d *driver) Leave(nid, eid string) error { - leave := &api.LeaveRequest{ - NetworkID: nid, - EndpointID: eid, - } - return d.call("Leave", leave, &api.LeaveResponse{}) -} - -// ProgramExternalConnectivity is invoked to program the rules to allow external connectivity for the endpoint. -func (d *driver) ProgramExternalConnectivity(nid, eid string, options map[string]interface{}) error { - data := &api.ProgramExternalConnectivityRequest{ - NetworkID: nid, - EndpointID: eid, - Options: options, - } - err := d.call("ProgramExternalConnectivity", data, &api.ProgramExternalConnectivityResponse{}) - if err != nil && plugins.IsNotFound(err) { - // It is not mandatory yet to support this method - return nil - } - return err -} - -// RevokeExternalConnectivity method is invoked to remove any external connectivity programming related to the endpoint. -func (d *driver) RevokeExternalConnectivity(nid, eid string) error { - data := &api.RevokeExternalConnectivityRequest{ - NetworkID: nid, - EndpointID: eid, - } - err := d.call("RevokeExternalConnectivity", data, &api.RevokeExternalConnectivityResponse{}) - if err != nil && plugins.IsNotFound(err) { - // It is not mandatory yet to support this method - return nil - } - return err -} - -func (d *driver) Type() string { - return d.networkType -} - -func (d *driver) IsBuiltIn() bool { - return false -} - -// DiscoverNew is a notification for a new discovery event, such as a new node joining a cluster -func (d *driver) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error { - if dType != discoverapi.NodeDiscovery { - return nil - } - notif := &api.DiscoveryNotification{ - DiscoveryType: dType, - DiscoveryData: data, - } - return d.call("DiscoverNew", notif, &api.DiscoveryResponse{}) -} - -// DiscoverDelete is a notification for a discovery delete event, such as a node leaving a cluster -func (d *driver) DiscoverDelete(dType discoverapi.DiscoveryType, data interface{}) error { - if dType != discoverapi.NodeDiscovery { - return nil - } - notif := &api.DiscoveryNotification{ - DiscoveryType: dType, - DiscoveryData: data, - } - return d.call("DiscoverDelete", notif, &api.DiscoveryResponse{}) -} - -func parseStaticRoutes(r api.JoinResponse) ([]*types.StaticRoute, error) { - var routes = make([]*types.StaticRoute, len(r.StaticRoutes)) - for i, inRoute := range r.StaticRoutes { - var err error - outRoute := &types.StaticRoute{RouteType: inRoute.RouteType} - - if inRoute.Destination != "" { - if outRoute.Destination, err = types.ParseCIDR(inRoute.Destination); err != nil { - return nil, err - } - } - - if inRoute.NextHop != "" { - outRoute.NextHop = net.ParseIP(inRoute.NextHop) - if outRoute.NextHop == nil { - return nil, fmt.Errorf("failed to parse nexthop IP %s", inRoute.NextHop) - } - } - - routes[i] = outRoute - } - return routes, nil -} - -// parseInterfaces validates all the parameters of an Interface and returns them. -func parseInterface(r api.CreateEndpointResponse) (*api.Interface, error) { - var outIf *api.Interface - - inIf := r.Interface - if inIf != nil { - var err error - outIf = &api.Interface{} - if inIf.Address != "" { - if outIf.Address, err = types.ParseCIDR(inIf.Address); err != nil { - return nil, err - } - } - if inIf.AddressIPv6 != "" { - if outIf.AddressIPv6, err = types.ParseCIDR(inIf.AddressIPv6); err != nil { - return nil, err - } - } - if inIf.MacAddress != "" { - if outIf.MacAddress, err = net.ParseMAC(inIf.MacAddress); err != nil { - return nil, err - } - } - } - - return outIf, nil -} diff --git a/vendor/github.com/docker/libnetwork/drivers/windows/labels.go b/vendor/github.com/docker/libnetwork/drivers/windows/labels.go deleted file mode 100644 index a4b23c1a22..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/windows/labels.go +++ /dev/null @@ -1,51 +0,0 @@ -package windows - -const ( - // NetworkName label for bridge driver - NetworkName = "com.docker.network.windowsshim.networkname" - - // HNSID of the discovered network - HNSID = "com.docker.network.windowsshim.hnsid" - - // RoutingDomain of the network - RoutingDomain = "com.docker.network.windowsshim.routingdomain" - - // Interface of the network - Interface = "com.docker.network.windowsshim.interface" - - // QosPolicies of the endpoint - QosPolicies = "com.docker.endpoint.windowsshim.qospolicies" - - // VLAN of the network - VLAN = "com.docker.network.windowsshim.vlanid" - - // VSID of the network - VSID = "com.docker.network.windowsshim.vsid" - - // DNSSuffix of the network - DNSSuffix = "com.docker.network.windowsshim.dnssuffix" - - // DNSServers of the network - DNSServers = "com.docker.network.windowsshim.dnsservers" - - // MacPool of the network - MacPool = "com.docker.network.windowsshim.macpool" - - // SourceMac of the network - SourceMac = "com.docker.network.windowsshim.sourcemac" - - // DisableICC label - DisableICC = "com.docker.network.windowsshim.disableicc" - - // DisableDNS label - DisableDNS = "com.docker.network.windowsshim.disable_dns" - - // DisableGatewayDNS label - DisableGatewayDNS = "com.docker.network.windowsshim.disable_gatewaydns" - - // EnableOutboundNat label - EnableOutboundNat = "com.docker.network.windowsshim.enable_outboundnat" - - // OutboundNatExceptions label - OutboundNatExceptions = "com.docker.network.windowsshim.outboundnat_exceptions" -) diff --git a/vendor/github.com/docker/libnetwork/drivers/windows/overlay/joinleave_windows.go b/vendor/github.com/docker/libnetwork/drivers/windows/overlay/joinleave_windows.go deleted file mode 100644 index 65500852b4..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/windows/overlay/joinleave_windows.go +++ /dev/null @@ -1,115 +0,0 @@ -package overlay - -import ( - "fmt" - "net" - - "github.com/docker/libnetwork/driverapi" - "github.com/docker/libnetwork/types" - "github.com/gogo/protobuf/proto" - "github.com/sirupsen/logrus" -) - -// Join method is invoked when a Sandbox is attached to an endpoint. -func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error { - if err := validateID(nid, eid); err != nil { - return err - } - - n := d.network(nid) - if n == nil { - return fmt.Errorf("could not find network with id %s", nid) - } - - ep := n.endpoint(eid) - if ep == nil { - return fmt.Errorf("could not find endpoint with id %s", eid) - } - - buf, err := proto.Marshal(&PeerRecord{ - EndpointIP: ep.addr.String(), - EndpointMAC: ep.mac.String(), - TunnelEndpointIP: n.providerAddress, - }) - - if err != nil { - return err - } - - if err := jinfo.AddTableEntry(ovPeerTable, eid, buf); err != nil { - logrus.Errorf("overlay: Failed adding table entry to joininfo: %v", err) - } - - if ep.disablegateway { - jinfo.DisableGatewayService() - } - - return nil -} - -func (d *driver) EventNotify(etype driverapi.EventType, nid, tableName, key string, value []byte) { - if tableName != ovPeerTable { - logrus.Errorf("Unexpected table notification for table %s received", tableName) - return - } - - eid := key - - var peer PeerRecord - if err := proto.Unmarshal(value, &peer); err != nil { - logrus.Errorf("Failed to unmarshal peer record: %v", err) - return - } - - n := d.network(nid) - if n == nil { - return - } - - // Ignore local peers. We already know about them and they - // should not be added to vxlan fdb. - if peer.TunnelEndpointIP == n.providerAddress { - return - } - - addr, err := types.ParseCIDR(peer.EndpointIP) - if err != nil { - logrus.Errorf("Invalid peer IP %s received in event notify", peer.EndpointIP) - return - } - - mac, err := net.ParseMAC(peer.EndpointMAC) - if err != nil { - logrus.Errorf("Invalid mac %s received in event notify", peer.EndpointMAC) - return - } - - vtep := net.ParseIP(peer.TunnelEndpointIP) - if vtep == nil { - logrus.Errorf("Invalid VTEP %s received in event notify", peer.TunnelEndpointIP) - return - } - - if etype == driverapi.Delete { - d.peerDelete(nid, eid, addr.IP, addr.Mask, mac, vtep, true) - return - } - - err = d.peerAdd(nid, eid, addr.IP, addr.Mask, mac, vtep, true) - if err != nil { - logrus.Errorf("peerAdd failed (%v) for ip %s with mac %s", err, addr.IP.String(), mac.String()) - } -} - -func (d *driver) DecodeTableEntry(tablename string, key string, value []byte) (string, map[string]string) { - return "", nil -} - -// Leave method is invoked when a Sandbox detaches from an endpoint. -func (d *driver) Leave(nid, eid string) error { - if err := validateID(nid, eid); err != nil { - return err - } - - return nil -} diff --git a/vendor/github.com/docker/libnetwork/drivers/windows/overlay/ov_endpoint_windows.go b/vendor/github.com/docker/libnetwork/drivers/windows/overlay/ov_endpoint_windows.go deleted file mode 100644 index 94b4a2eae3..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/windows/overlay/ov_endpoint_windows.go +++ /dev/null @@ -1,296 +0,0 @@ -package overlay - -import ( - "encoding/json" - "fmt" - "net" - "sync" - - "github.com/Microsoft/hcsshim" - "github.com/Microsoft/hcsshim/osversion" - "github.com/docker/libnetwork/driverapi" - "github.com/docker/libnetwork/drivers/windows" - "github.com/docker/libnetwork/netlabel" - "github.com/docker/libnetwork/types" - "github.com/sirupsen/logrus" -) - -type endpointTable map[string]*endpoint - -const overlayEndpointPrefix = "overlay/endpoint" - -type endpoint struct { - id string - nid string - profileID string - remote bool - mac net.HardwareAddr - addr *net.IPNet - disablegateway bool - portMapping []types.PortBinding // Operation port bindings -} - -var ( - //Server 2016 (RS1) does not support concurrent add/delete of endpoints. Therefore, we need - //to use this mutex and serialize the add/delete of endpoints on RS1. - endpointMu sync.Mutex - windowsBuild = osversion.Build() -) - -func validateID(nid, eid string) error { - if nid == "" { - return fmt.Errorf("invalid network id") - } - - if eid == "" { - return fmt.Errorf("invalid endpoint id") - } - - return nil -} - -func (n *network) endpoint(eid string) *endpoint { - n.Lock() - defer n.Unlock() - - return n.endpoints[eid] -} - -func (n *network) addEndpoint(ep *endpoint) { - n.Lock() - n.endpoints[ep.id] = ep - n.Unlock() -} - -func (n *network) deleteEndpoint(eid string) { - n.Lock() - delete(n.endpoints, eid) - n.Unlock() -} - -func (n *network) removeEndpointWithAddress(addr *net.IPNet) { - var networkEndpoint *endpoint - n.Lock() - for _, ep := range n.endpoints { - if ep.addr.IP.Equal(addr.IP) { - networkEndpoint = ep - break - } - } - - if networkEndpoint != nil { - delete(n.endpoints, networkEndpoint.id) - } - n.Unlock() - - if networkEndpoint != nil { - logrus.Debugf("Removing stale endpoint from HNS") - _, err := endpointRequest("DELETE", networkEndpoint.profileID, "") - if err != nil { - logrus.Debugf("Failed to delete stale overlay endpoint (%.7s) from hns", networkEndpoint.id) - } - } -} - -func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo, - epOptions map[string]interface{}) error { - var err error - if err = validateID(nid, eid); err != nil { - return err - } - - n := d.network(nid) - if n == nil { - return fmt.Errorf("network id %q not found", nid) - } - - ep := n.endpoint(eid) - if ep != nil { - logrus.Debugf("Deleting stale endpoint %s", eid) - n.deleteEndpoint(eid) - _, err := endpointRequest("DELETE", ep.profileID, "") - if err != nil { - return err - } - } - - ep = &endpoint{ - id: eid, - nid: n.id, - addr: ifInfo.Address(), - mac: ifInfo.MacAddress(), - } - - if ep.addr == nil { - return fmt.Errorf("create endpoint was not passed interface IP address") - } - - s := n.getSubnetforIP(ep.addr) - if s == nil { - return fmt.Errorf("no matching subnet for IP %q in network %q", ep.addr, nid) - } - - // Todo: Add port bindings and qos policies here - - hnsEndpoint := &hcsshim.HNSEndpoint{ - Name: eid, - VirtualNetwork: n.hnsID, - IPAddress: ep.addr.IP, - EnableInternalDNS: true, - GatewayAddress: s.gwIP.String(), - } - - if ep.mac != nil { - hnsEndpoint.MacAddress = ep.mac.String() - } - - paPolicy, err := json.Marshal(hcsshim.PaPolicy{ - Type: "PA", - PA: n.providerAddress, - }) - - if err != nil { - return err - } - - hnsEndpoint.Policies = append(hnsEndpoint.Policies, paPolicy) - - if osversion.Build() > 16236 { - natPolicy, err := json.Marshal(hcsshim.PaPolicy{ - Type: "OutBoundNAT", - }) - - if err != nil { - return err - } - - hnsEndpoint.Policies = append(hnsEndpoint.Policies, natPolicy) - - epConnectivity, err := windows.ParseEndpointConnectivity(epOptions) - if err != nil { - return err - } - - ep.portMapping = epConnectivity.PortBindings - ep.portMapping, err = windows.AllocatePorts(n.portMapper, ep.portMapping, ep.addr.IP) - if err != nil { - return err - } - - defer func() { - if err != nil { - windows.ReleasePorts(n.portMapper, ep.portMapping) - } - }() - - pbPolicy, err := windows.ConvertPortBindings(ep.portMapping) - if err != nil { - return err - } - hnsEndpoint.Policies = append(hnsEndpoint.Policies, pbPolicy...) - - ep.disablegateway = true - } - - configurationb, err := json.Marshal(hnsEndpoint) - if err != nil { - return err - } - - hnsresponse, err := endpointRequest("POST", "", string(configurationb)) - if err != nil { - return err - } - - ep.profileID = hnsresponse.Id - - if ep.mac == nil { - ep.mac, err = net.ParseMAC(hnsresponse.MacAddress) - if err != nil { - return err - } - - if err := ifInfo.SetMacAddress(ep.mac); err != nil { - return err - } - } - - ep.portMapping, err = windows.ParsePortBindingPolicies(hnsresponse.Policies) - if err != nil { - endpointRequest("DELETE", hnsresponse.Id, "") - return err - } - - n.addEndpoint(ep) - - return nil -} - -func (d *driver) DeleteEndpoint(nid, eid string) error { - if err := validateID(nid, eid); err != nil { - return err - } - - n := d.network(nid) - if n == nil { - return fmt.Errorf("network id %q not found", nid) - } - - ep := n.endpoint(eid) - if ep == nil { - return fmt.Errorf("endpoint id %q not found", eid) - } - - windows.ReleasePorts(n.portMapper, ep.portMapping) - - n.deleteEndpoint(eid) - - _, err := endpointRequest("DELETE", ep.profileID, "") - if err != nil { - return err - } - - return nil -} - -func (d *driver) EndpointOperInfo(nid, eid string) (map[string]interface{}, error) { - if err := validateID(nid, eid); err != nil { - return nil, err - } - - n := d.network(nid) - if n == nil { - return nil, fmt.Errorf("network id %q not found", nid) - } - - ep := n.endpoint(eid) - if ep == nil { - return nil, fmt.Errorf("endpoint id %q not found", eid) - } - - data := make(map[string]interface{}, 1) - data["hnsid"] = ep.profileID - data["AllowUnqualifiedDNSQuery"] = true - - if ep.portMapping != nil { - // Return a copy of the operational data - pmc := make([]types.PortBinding, 0, len(ep.portMapping)) - for _, pm := range ep.portMapping { - pmc = append(pmc, pm.GetCopy()) - } - data[netlabel.PortMap] = pmc - } - - return data, nil -} - -func endpointRequest(method, path, request string) (*hcsshim.HNSEndpoint, error) { - if windowsBuild == 14393 { - endpointMu.Lock() - } - hnsresponse, err := hcsshim.HNSEndpointRequest(method, path, request) - if windowsBuild == 14393 { - endpointMu.Unlock() - } - return hnsresponse, err -} diff --git a/vendor/github.com/docker/libnetwork/drivers/windows/overlay/ov_network_windows.go b/vendor/github.com/docker/libnetwork/drivers/windows/overlay/ov_network_windows.go deleted file mode 100644 index 592cfc663b..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/windows/overlay/ov_network_windows.go +++ /dev/null @@ -1,384 +0,0 @@ -package overlay - -import ( - "encoding/json" - "fmt" - "net" - "strconv" - "strings" - "sync" - - "github.com/Microsoft/hcsshim" - "github.com/docker/libnetwork/driverapi" - "github.com/docker/libnetwork/netlabel" - "github.com/docker/libnetwork/portmapper" - "github.com/docker/libnetwork/types" - "github.com/sirupsen/logrus" -) - -var ( - hostMode bool - networkMu sync.Mutex -) - -type networkTable map[string]*network - -type subnet struct { - vni uint32 - subnetIP *net.IPNet - gwIP *net.IP -} - -type subnetJSON struct { - SubnetIP string - GwIP string - Vni uint32 -} - -type network struct { - id string - name string - hnsID string - providerAddress string - interfaceName string - endpoints endpointTable - driver *driver - initEpoch int - initErr error - subnets []*subnet - secure bool - portMapper *portmapper.PortMapper - sync.Mutex -} - -func (d *driver) NetworkAllocate(id string, option map[string]string, ipV4Data, ipV6Data []driverapi.IPAMData) (map[string]string, error) { - return nil, types.NotImplementedErrorf("not implemented") -} - -func (d *driver) NetworkFree(id string) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) CreateNetwork(id string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error { - var ( - networkName string - interfaceName string - staleNetworks []string - ) - - if id == "" { - return fmt.Errorf("invalid network id") - } - - if nInfo == nil { - return fmt.Errorf("invalid network info structure") - } - - if len(ipV4Data) == 0 || ipV4Data[0].Pool.String() == "0.0.0.0/0" { - return types.BadRequestErrorf("ipv4 pool is empty") - } - - staleNetworks = make([]string, 0) - vnis := make([]uint32, 0, len(ipV4Data)) - - existingNetwork := d.network(id) - if existingNetwork != nil { - logrus.Debugf("Network preexists. Deleting %s", id) - err := d.DeleteNetwork(id) - if err != nil { - logrus.Errorf("Error deleting stale network %s", err.Error()) - } - } - - n := &network{ - id: id, - driver: d, - endpoints: endpointTable{}, - subnets: []*subnet{}, - portMapper: portmapper.New(""), - } - - genData, ok := option[netlabel.GenericData].(map[string]string) - - if !ok { - return fmt.Errorf("Unknown generic data option") - } - - for label, value := range genData { - switch label { - case "com.docker.network.windowsshim.networkname": - networkName = value - case "com.docker.network.windowsshim.interface": - interfaceName = value - case "com.docker.network.windowsshim.hnsid": - n.hnsID = value - case netlabel.OverlayVxlanIDList: - vniStrings := strings.Split(value, ",") - for _, vniStr := range vniStrings { - vni, err := strconv.Atoi(vniStr) - if err != nil { - return fmt.Errorf("invalid vxlan id value %q passed", vniStr) - } - - vnis = append(vnis, uint32(vni)) - } - } - } - - // If we are getting vnis from libnetwork, either we get for - // all subnets or none. - if len(vnis) < len(ipV4Data) { - return fmt.Errorf("insufficient vnis(%d) passed to overlay. Windows driver requires VNIs to be prepopulated", len(vnis)) - } - - for i, ipd := range ipV4Data { - s := &subnet{ - subnetIP: ipd.Pool, - gwIP: &ipd.Gateway.IP, - } - - if len(vnis) != 0 { - s.vni = vnis[i] - } - - d.Lock() - for _, network := range d.networks { - found := false - for _, sub := range network.subnets { - if sub.vni == s.vni { - staleNetworks = append(staleNetworks, network.id) - found = true - break - } - } - if found { - break - } - } - d.Unlock() - - n.subnets = append(n.subnets, s) - } - - for _, staleNetwork := range staleNetworks { - d.DeleteNetwork(staleNetwork) - } - - n.name = networkName - if n.name == "" { - n.name = id - } - - n.interfaceName = interfaceName - - if nInfo != nil { - if err := nInfo.TableEventRegister(ovPeerTable, driverapi.EndpointObject); err != nil { - return err - } - } - - d.addNetwork(n) - - err := d.createHnsNetwork(n) - - if err != nil { - d.deleteNetwork(id) - } else { - genData["com.docker.network.windowsshim.hnsid"] = n.hnsID - } - - return err -} - -func (d *driver) DeleteNetwork(nid string) error { - if nid == "" { - return fmt.Errorf("invalid network id") - } - - n := d.network(nid) - if n == nil { - return types.ForbiddenErrorf("could not find network with id %s", nid) - } - - _, err := hcsshim.HNSNetworkRequest("DELETE", n.hnsID, "") - if err != nil { - return types.ForbiddenErrorf(err.Error()) - } - - d.deleteNetwork(nid) - - return nil -} - -func (d *driver) ProgramExternalConnectivity(nid, eid string, options map[string]interface{}) error { - return nil -} - -func (d *driver) RevokeExternalConnectivity(nid, eid string) error { - return nil -} - -func (d *driver) addNetwork(n *network) { - d.Lock() - d.networks[n.id] = n - d.Unlock() -} - -func (d *driver) deleteNetwork(nid string) { - d.Lock() - delete(d.networks, nid) - d.Unlock() -} - -func (d *driver) network(nid string) *network { - d.Lock() - defer d.Unlock() - return d.networks[nid] -} - -// func (n *network) restoreNetworkEndpoints() error { -// logrus.Infof("Restoring endpoints for overlay network: %s", n.id) - -// hnsresponse, err := hcsshim.HNSListEndpointRequest("GET", "", "") -// if err != nil { -// return err -// } - -// for _, endpoint := range hnsresponse { -// if endpoint.VirtualNetwork != n.hnsID { -// continue -// } - -// ep := n.convertToOverlayEndpoint(&endpoint) - -// if ep != nil { -// logrus.Debugf("Restored endpoint:%s Remote:%t", ep.id, ep.remote) -// n.addEndpoint(ep) -// } -// } - -// return nil -// } - -func (n *network) convertToOverlayEndpoint(v *hcsshim.HNSEndpoint) *endpoint { - ep := &endpoint{ - id: v.Name, - profileID: v.Id, - nid: n.id, - remote: v.IsRemoteEndpoint, - } - - mac, err := net.ParseMAC(v.MacAddress) - - if err != nil { - return nil - } - - ep.mac = mac - ep.addr = &net.IPNet{ - IP: v.IPAddress, - Mask: net.CIDRMask(32, 32), - } - - return ep -} - -func (d *driver) createHnsNetwork(n *network) error { - - subnets := []hcsshim.Subnet{} - - for _, s := range n.subnets { - subnet := hcsshim.Subnet{ - AddressPrefix: s.subnetIP.String(), - } - - if s.gwIP != nil { - subnet.GatewayAddress = s.gwIP.String() - } - - vsidPolicy, err := json.Marshal(hcsshim.VsidPolicy{ - Type: "VSID", - VSID: uint(s.vni), - }) - - if err != nil { - return err - } - - subnet.Policies = append(subnet.Policies, vsidPolicy) - subnets = append(subnets, subnet) - } - - network := &hcsshim.HNSNetwork{ - Name: n.name, - Type: d.Type(), - Subnets: subnets, - NetworkAdapterName: n.interfaceName, - AutomaticDNS: true, - } - - configurationb, err := json.Marshal(network) - if err != nil { - return err - } - - configuration := string(configurationb) - logrus.Infof("HNSNetwork Request =%v", configuration) - - hnsresponse, err := hcsshim.HNSNetworkRequest("POST", "", configuration) - if err != nil { - return err - } - - n.hnsID = hnsresponse.Id - n.providerAddress = hnsresponse.ManagementIP - - return nil -} - -// contains return true if the passed ip belongs to one the network's -// subnets -func (n *network) contains(ip net.IP) bool { - for _, s := range n.subnets { - if s.subnetIP.Contains(ip) { - return true - } - } - - return false -} - -// getSubnetforIP returns the subnet to which the given IP belongs -func (n *network) getSubnetforIP(ip *net.IPNet) *subnet { - for _, s := range n.subnets { - // first check if the mask lengths are the same - i, _ := s.subnetIP.Mask.Size() - j, _ := ip.Mask.Size() - if i != j { - continue - } - if s.subnetIP.Contains(ip.IP) { - return s - } - } - return nil -} - -// getMatchingSubnet return the network's subnet that matches the input -func (n *network) getMatchingSubnet(ip *net.IPNet) *subnet { - if ip == nil { - return nil - } - for _, s := range n.subnets { - // first check if the mask lengths are the same - i, _ := s.subnetIP.Mask.Size() - j, _ := ip.Mask.Size() - if i != j { - continue - } - if s.subnetIP.IP.Equal(ip.IP) { - return s - } - } - return nil -} diff --git a/vendor/github.com/docker/libnetwork/drivers/windows/overlay/overlay.pb.go b/vendor/github.com/docker/libnetwork/drivers/windows/overlay/overlay.pb.go deleted file mode 100644 index 9d0cf2663f..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/windows/overlay/overlay.pb.go +++ /dev/null @@ -1,455 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: drivers/windows/overlay/overlay.proto - -/* - Package overlay is a generated protocol buffer package. - - It is generated from these files: - drivers/windows/overlay/overlay.proto - - It has these top-level messages: - PeerRecord -*/ -package overlay - -import proto "github.com/gogo/protobuf/proto" -import fmt "fmt" -import math "math" -import _ "github.com/gogo/protobuf/gogoproto" - -import strings "strings" -import reflect "reflect" - -import io "io" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package - -// PeerRecord defines the information corresponding to a peer -// container in the overlay network. -type PeerRecord struct { - // Endpoint IP is the IP of the container attachment on the - // given overlay network. - EndpointIP string `protobuf:"bytes,1,opt,name=endpoint_ip,json=endpointIp,proto3" json:"endpoint_ip,omitempty"` - // Endpoint MAC is the mac address of the container attachment - // on the given overlay network. - EndpointMAC string `protobuf:"bytes,2,opt,name=endpoint_mac,json=endpointMac,proto3" json:"endpoint_mac,omitempty"` - // Tunnel Endpoint IP defines the host IP for the host in - // which this container is running and can be reached by - // building a tunnel to that host IP. - TunnelEndpointIP string `protobuf:"bytes,3,opt,name=tunnel_endpoint_ip,json=tunnelEndpointIp,proto3" json:"tunnel_endpoint_ip,omitempty"` -} - -func (m *PeerRecord) Reset() { *m = PeerRecord{} } -func (*PeerRecord) ProtoMessage() {} -func (*PeerRecord) Descriptor() ([]byte, []int) { return fileDescriptorOverlay, []int{0} } - -func (m *PeerRecord) GetEndpointIP() string { - if m != nil { - return m.EndpointIP - } - return "" -} - -func (m *PeerRecord) GetEndpointMAC() string { - if m != nil { - return m.EndpointMAC - } - return "" -} - -func (m *PeerRecord) GetTunnelEndpointIP() string { - if m != nil { - return m.TunnelEndpointIP - } - return "" -} - -func init() { - proto.RegisterType((*PeerRecord)(nil), "overlay.PeerRecord") -} -func (this *PeerRecord) GoString() string { - if this == nil { - return "nil" - } - s := make([]string, 0, 7) - s = append(s, "&overlay.PeerRecord{") - s = append(s, "EndpointIP: "+fmt.Sprintf("%#v", this.EndpointIP)+",\n") - s = append(s, "EndpointMAC: "+fmt.Sprintf("%#v", this.EndpointMAC)+",\n") - s = append(s, "TunnelEndpointIP: "+fmt.Sprintf("%#v", this.TunnelEndpointIP)+",\n") - s = append(s, "}") - return strings.Join(s, "") -} -func valueToGoStringOverlay(v interface{}, typ string) string { - rv := reflect.ValueOf(v) - if rv.IsNil() { - return "nil" - } - pv := reflect.Indirect(rv).Interface() - return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv) -} -func (m *PeerRecord) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalTo(dAtA) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *PeerRecord) MarshalTo(dAtA []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if len(m.EndpointIP) > 0 { - dAtA[i] = 0xa - i++ - i = encodeVarintOverlay(dAtA, i, uint64(len(m.EndpointIP))) - i += copy(dAtA[i:], m.EndpointIP) - } - if len(m.EndpointMAC) > 0 { - dAtA[i] = 0x12 - i++ - i = encodeVarintOverlay(dAtA, i, uint64(len(m.EndpointMAC))) - i += copy(dAtA[i:], m.EndpointMAC) - } - if len(m.TunnelEndpointIP) > 0 { - dAtA[i] = 0x1a - i++ - i = encodeVarintOverlay(dAtA, i, uint64(len(m.TunnelEndpointIP))) - i += copy(dAtA[i:], m.TunnelEndpointIP) - } - return i, nil -} - -func encodeVarintOverlay(dAtA []byte, offset int, v uint64) int { - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return offset + 1 -} -func (m *PeerRecord) Size() (n int) { - var l int - _ = l - l = len(m.EndpointIP) - if l > 0 { - n += 1 + l + sovOverlay(uint64(l)) - } - l = len(m.EndpointMAC) - if l > 0 { - n += 1 + l + sovOverlay(uint64(l)) - } - l = len(m.TunnelEndpointIP) - if l > 0 { - n += 1 + l + sovOverlay(uint64(l)) - } - return n -} - -func sovOverlay(x uint64) (n int) { - for { - n++ - x >>= 7 - if x == 0 { - break - } - } - return n -} -func sozOverlay(x uint64) (n int) { - return sovOverlay(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (this *PeerRecord) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&PeerRecord{`, - `EndpointIP:` + fmt.Sprintf("%v", this.EndpointIP) + `,`, - `EndpointMAC:` + fmt.Sprintf("%v", this.EndpointMAC) + `,`, - `TunnelEndpointIP:` + fmt.Sprintf("%v", this.TunnelEndpointIP) + `,`, - `}`, - }, "") - return s -} -func valueToStringOverlay(v interface{}) string { - rv := reflect.ValueOf(v) - if rv.IsNil() { - return "nil" - } - pv := reflect.Indirect(rv).Interface() - return fmt.Sprintf("*%v", pv) -} -func (m *PeerRecord) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowOverlay - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: PeerRecord: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: PeerRecord: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field EndpointIP", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowOverlay - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthOverlay - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.EndpointIP = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field EndpointMAC", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowOverlay - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthOverlay - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.EndpointMAC = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TunnelEndpointIP", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowOverlay - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthOverlay - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.TunnelEndpointIP = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipOverlay(dAtA[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthOverlay - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipOverlay(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowOverlay - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowOverlay - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - return iNdEx, nil - case 1: - iNdEx += 8 - return iNdEx, nil - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowOverlay - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - iNdEx += length - if length < 0 { - return 0, ErrInvalidLengthOverlay - } - return iNdEx, nil - case 3: - for { - var innerWire uint64 - var start int = iNdEx - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowOverlay - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - innerWire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - innerWireType := int(innerWire & 0x7) - if innerWireType == 4 { - break - } - next, err := skipOverlay(dAtA[start:]) - if err != nil { - return 0, err - } - iNdEx = start + next - } - return iNdEx, nil - case 4: - return iNdEx, nil - case 5: - iNdEx += 4 - return iNdEx, nil - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - } - panic("unreachable") -} - -var ( - ErrInvalidLengthOverlay = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowOverlay = fmt.Errorf("proto: integer overflow") -) - -func init() { proto.RegisterFile("drivers/windows/overlay/overlay.proto", fileDescriptorOverlay) } - -var fileDescriptorOverlay = []byte{ - // 220 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x4d, 0x29, 0xca, 0x2c, - 0x4b, 0x2d, 0x2a, 0xd6, 0x2f, 0xcf, 0xcc, 0x4b, 0xc9, 0x2f, 0x2f, 0xd6, 0xcf, 0x2f, 0x4b, 0x2d, - 0xca, 0x49, 0xac, 0x84, 0xd1, 0x7a, 0x05, 0x45, 0xf9, 0x25, 0xf9, 0x42, 0xec, 0x50, 0xae, 0x94, - 0x48, 0x7a, 0x7e, 0x7a, 0x3e, 0x58, 0x4c, 0x1f, 0xc4, 0x82, 0x48, 0x2b, 0x6d, 0x65, 0xe4, 0xe2, - 0x0a, 0x48, 0x4d, 0x2d, 0x0a, 0x4a, 0x4d, 0xce, 0x2f, 0x4a, 0x11, 0xd2, 0xe7, 0xe2, 0x4e, 0xcd, - 0x4b, 0x29, 0xc8, 0xcf, 0xcc, 0x2b, 0x89, 0xcf, 0x2c, 0x90, 0x60, 0x54, 0x60, 0xd4, 0xe0, 0x74, - 0xe2, 0x7b, 0x74, 0x4f, 0x9e, 0xcb, 0x15, 0x2a, 0xec, 0x19, 0x10, 0xc4, 0x05, 0x53, 0xe2, 0x59, - 0x20, 0x64, 0xc4, 0xc5, 0x03, 0xd7, 0x90, 0x9b, 0x98, 0x2c, 0xc1, 0x04, 0xd6, 0xc1, 0xff, 0xe8, - 0x9e, 0x3c, 0x37, 0x4c, 0x87, 0xaf, 0xa3, 0x73, 0x10, 0xdc, 0x54, 0xdf, 0xc4, 0x64, 0x21, 0x27, - 0x2e, 0xa1, 0x92, 0xd2, 0xbc, 0xbc, 0xd4, 0x9c, 0x78, 0x64, 0xbb, 0x98, 0xc1, 0x3a, 0x45, 0x1e, - 0xdd, 0x93, 0x17, 0x08, 0x01, 0xcb, 0x22, 0xd9, 0x28, 0x50, 0x82, 0x2a, 0x52, 0xe0, 0x24, 0x71, - 0xe3, 0xa1, 0x1c, 0xc3, 0x87, 0x87, 0x72, 0x8c, 0x0d, 0x8f, 0xe4, 0x18, 0x4f, 0x3c, 0x92, 0x63, - 0xbc, 0xf0, 0x48, 0x8e, 0xf1, 0xc1, 0x23, 0x39, 0xc6, 0x24, 0x36, 0xb0, 0xc7, 0x8c, 0x01, 0x01, - 0x00, 0x00, 0xff, 0xff, 0xc0, 0x48, 0xd1, 0xc0, 0x20, 0x01, 0x00, 0x00, -} diff --git a/vendor/github.com/docker/libnetwork/drivers/windows/overlay/overlay.proto b/vendor/github.com/docker/libnetwork/drivers/windows/overlay/overlay.proto deleted file mode 100644 index 45b8c9de7e..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/windows/overlay/overlay.proto +++ /dev/null @@ -1,27 +0,0 @@ -syntax = "proto3"; - -import "gogoproto/gogo.proto"; - -package overlay; - -option (gogoproto.marshaler_all) = true; -option (gogoproto.unmarshaler_all) = true; -option (gogoproto.stringer_all) = true; -option (gogoproto.gostring_all) = true; -option (gogoproto.sizer_all) = true; -option (gogoproto.goproto_stringer_all) = false; - -// PeerRecord defines the information corresponding to a peer -// container in the overlay network. -message PeerRecord { - // Endpoint IP is the IP of the container attachment on the - // given overlay network. - string endpoint_ip = 1 [(gogoproto.customname) = "EndpointIP"]; - // Endpoint MAC is the mac address of the container attachment - // on the given overlay network. - string endpoint_mac = 2 [(gogoproto.customname) = "EndpointMAC"]; - // Tunnel Endpoint IP defines the host IP for the host in - // which this container is running and can be reached by - // building a tunnel to that host IP. - string tunnel_endpoint_ip = 3 [(gogoproto.customname) = "TunnelEndpointIP"]; -} \ No newline at end of file diff --git a/vendor/github.com/docker/libnetwork/drivers/windows/overlay/overlay_windows.go b/vendor/github.com/docker/libnetwork/drivers/windows/overlay/overlay_windows.go deleted file mode 100644 index 65ad62ae0d..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/windows/overlay/overlay_windows.go +++ /dev/null @@ -1,159 +0,0 @@ -package overlay - -//go:generate protoc -I.:../../Godeps/_workspace/src/github.com/gogo/protobuf --gogo_out=import_path=github.com/docker/libnetwork/drivers/overlay,Mgogoproto/gogo.proto=github.com/gogo/protobuf/gogoproto:. overlay.proto - -import ( - "encoding/json" - "net" - "sync" - - "github.com/Microsoft/hcsshim" - "github.com/docker/libnetwork/datastore" - "github.com/docker/libnetwork/discoverapi" - "github.com/docker/libnetwork/driverapi" - "github.com/docker/libnetwork/netlabel" - "github.com/docker/libnetwork/types" - "github.com/sirupsen/logrus" -) - -const ( - networkType = "overlay" - vethPrefix = "veth" - vethLen = 7 - secureOption = "encrypted" -) - -type driver struct { - config map[string]interface{} - networks networkTable - store datastore.DataStore - localStore datastore.DataStore - once sync.Once - joinOnce sync.Once - sync.Mutex -} - -// Init registers a new instance of overlay driver -func Init(dc driverapi.DriverCallback, config map[string]interface{}) error { - c := driverapi.Capability{ - DataScope: datastore.GlobalScope, - ConnectivityScope: datastore.GlobalScope, - } - - d := &driver{ - networks: networkTable{}, - config: config, - } - - if data, ok := config[netlabel.GlobalKVClient]; ok { - var err error - dsc, ok := data.(discoverapi.DatastoreConfigData) - if !ok { - return types.InternalErrorf("incorrect data in datastore configuration: %v", data) - } - d.store, err = datastore.NewDataStoreFromConfig(dsc) - if err != nil { - return types.InternalErrorf("failed to initialize data store: %v", err) - } - } - - if data, ok := config[netlabel.LocalKVClient]; ok { - var err error - dsc, ok := data.(discoverapi.DatastoreConfigData) - if !ok { - return types.InternalErrorf("incorrect data in datastore configuration: %v", data) - } - d.localStore, err = datastore.NewDataStoreFromConfig(dsc) - if err != nil { - return types.InternalErrorf("failed to initialize local data store: %v", err) - } - } - - d.restoreHNSNetworks() - - return dc.RegisterDriver(networkType, d, c) -} - -func (d *driver) restoreHNSNetworks() error { - logrus.Infof("Restoring existing overlay networks from HNS into docker") - - hnsresponse, err := hcsshim.HNSListNetworkRequest("GET", "", "") - if err != nil { - return err - } - - for _, v := range hnsresponse { - if v.Type != networkType { - continue - } - - logrus.Infof("Restoring overlay network: %s", v.Name) - n := d.convertToOverlayNetwork(&v) - d.addNetwork(n) - - // - // We assume that any network will be recreated on daemon restart - // and therefore don't restore hns endpoints for now - // - //n.restoreNetworkEndpoints() - } - - return nil -} - -func (d *driver) convertToOverlayNetwork(v *hcsshim.HNSNetwork) *network { - n := &network{ - id: v.Name, - hnsID: v.Id, - driver: d, - endpoints: endpointTable{}, - subnets: []*subnet{}, - providerAddress: v.ManagementIP, - } - - for _, hnsSubnet := range v.Subnets { - vsidPolicy := &hcsshim.VsidPolicy{} - for _, policy := range hnsSubnet.Policies { - if err := json.Unmarshal([]byte(policy), &vsidPolicy); err == nil && vsidPolicy.Type == "VSID" { - break - } - } - - gwIP := net.ParseIP(hnsSubnet.GatewayAddress) - localsubnet := &subnet{ - vni: uint32(vsidPolicy.VSID), - gwIP: &gwIP, - } - - _, subnetIP, err := net.ParseCIDR(hnsSubnet.AddressPrefix) - - if err != nil { - logrus.Errorf("Error parsing subnet address %s ", hnsSubnet.AddressPrefix) - continue - } - - localsubnet.subnetIP = subnetIP - - n.subnets = append(n.subnets, localsubnet) - } - - return n -} - -func (d *driver) Type() string { - return networkType -} - -func (d *driver) IsBuiltIn() bool { - return true -} - -// DiscoverNew is a notification for a new discovery event, such as a new node joining a cluster -func (d *driver) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error { - return types.NotImplementedErrorf("not implemented") -} - -// DiscoverDelete is a notification for a discovery delete event, such as a node leaving a cluster -func (d *driver) DiscoverDelete(dType discoverapi.DiscoveryType, data interface{}) error { - return types.NotImplementedErrorf("not implemented") -} diff --git a/vendor/github.com/docker/libnetwork/drivers/windows/overlay/peerdb_windows.go b/vendor/github.com/docker/libnetwork/drivers/windows/overlay/peerdb_windows.go deleted file mode 100644 index 34f77cbfae..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/windows/overlay/peerdb_windows.go +++ /dev/null @@ -1,119 +0,0 @@ -package overlay - -import ( - "fmt" - "net" - - "encoding/json" - - "github.com/docker/libnetwork/types" - "github.com/sirupsen/logrus" - - "github.com/Microsoft/hcsshim" -) - -const ovPeerTable = "overlay_peer_table" - -func (d *driver) peerAdd(nid, eid string, peerIP net.IP, peerIPMask net.IPMask, - peerMac net.HardwareAddr, vtep net.IP, updateDb bool) error { - - logrus.Debugf("WINOVERLAY: Enter peerAdd for ca ip %s with ca mac %s", peerIP.String(), peerMac.String()) - - if err := validateID(nid, eid); err != nil { - return err - } - - n := d.network(nid) - if n == nil { - return nil - } - - if updateDb { - logrus.Info("WINOVERLAY: peerAdd: notifying HNS of the REMOTE endpoint") - - hnsEndpoint := &hcsshim.HNSEndpoint{ - Name: eid, - VirtualNetwork: n.hnsID, - MacAddress: peerMac.String(), - IPAddress: peerIP, - IsRemoteEndpoint: true, - } - - paPolicy, err := json.Marshal(hcsshim.PaPolicy{ - Type: "PA", - PA: vtep.String(), - }) - - if err != nil { - return err - } - - hnsEndpoint.Policies = append(hnsEndpoint.Policies, paPolicy) - - configurationb, err := json.Marshal(hnsEndpoint) - if err != nil { - return err - } - - // Temp: We have to create an endpoint object to keep track of the HNS ID for - // this endpoint so that we can retrieve it later when the endpoint is deleted. - // This seems unnecessary when we already have dockers EID. See if we can pass - // the global EID to HNS to use as it's ID, rather than having each HNS assign - // it's own local ID for the endpoint - - addr, err := types.ParseCIDR(peerIP.String() + "/32") - if err != nil { - return err - } - - n.removeEndpointWithAddress(addr) - hnsresponse, err := endpointRequest("POST", "", string(configurationb)) - if err != nil { - return err - } - - ep := &endpoint{ - id: eid, - nid: nid, - addr: addr, - mac: peerMac, - profileID: hnsresponse.Id, - remote: true, - } - - n.addEndpoint(ep) - } - - return nil -} - -func (d *driver) peerDelete(nid, eid string, peerIP net.IP, peerIPMask net.IPMask, - peerMac net.HardwareAddr, vtep net.IP, updateDb bool) error { - - logrus.Infof("WINOVERLAY: Enter peerDelete for endpoint %s and peer ip %s", eid, peerIP.String()) - - if err := validateID(nid, eid); err != nil { - return err - } - - n := d.network(nid) - if n == nil { - return nil - } - - ep := n.endpoint(eid) - if ep == nil { - return fmt.Errorf("could not find endpoint with id %s", eid) - } - - if updateDb { - _, err := endpointRequest("DELETE", ep.profileID, "") - if err != nil { - return err - } - - n.deleteEndpoint(eid) - } - - return nil -} diff --git a/vendor/github.com/docker/libnetwork/drivers/windows/port_mapping.go b/vendor/github.com/docker/libnetwork/drivers/windows/port_mapping.go deleted file mode 100644 index 4ad25c1e79..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/windows/port_mapping.go +++ /dev/null @@ -1,131 +0,0 @@ -// +build windows - -package windows - -import ( - "bytes" - "errors" - "fmt" - "net" - - "github.com/docker/libnetwork/portmapper" - "github.com/docker/libnetwork/types" - "github.com/ishidawataru/sctp" - "github.com/sirupsen/logrus" -) - -const ( - maxAllocatePortAttempts = 10 -) - -// ErrUnsupportedAddressType is returned when the specified address type is not supported. -type ErrUnsupportedAddressType string - -func (uat ErrUnsupportedAddressType) Error() string { - return fmt.Sprintf("unsupported address type: %s", string(uat)) -} - -// 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 -} - -func allocatePort(portMapper *portmapper.PortMapper, bnd *types.PortBinding, containerIP net.IP) error { - var ( - host net.Addr - err error - ) - - // Windows does not support a host ip for port bindings (this is validated in ConvertPortBindings()). - // If the HostIP is nil, force it to be 0.0.0.0 for use as the key in portMapper. - if bnd.HostIP == nil { - bnd.HostIP = net.IPv4zero - } - - // Store the container interface address in the operational binding - bnd.IP = containerIP - - // Adjust HostPortEnd if this is not a range. - if bnd.HostPortEnd == 0 { - bnd.HostPortEnd = bnd.HostPort - } - - // Construct the container side transport address - container, err := bnd.ContainerAddr() - if err != nil { - return err - } - - // Try up to maxAllocatePortAttempts times to get a port that's not already allocated. - for i := 0; i < maxAllocatePortAttempts; i++ { - if host, err = portMapper.MapRange(container, bnd.HostIP, int(bnd.HostPort), int(bnd.HostPortEnd), false); err == nil { - break - } - // There is no point in immediately retrying to map an explicitly chosen port. - if bnd.HostPort != 0 { - logrus.Warnf("Failed to allocate and map port %d-%d: %s", bnd.HostPort, bnd.HostPortEnd, err) - break - } - logrus.Warnf("Failed to allocate and map port: %s, retry: %d", err, i+1) - } - if err != nil { - return err - } - - // Save the host port (regardless it was or not specified in the binding) - switch netAddr := host.(type) { - case *net.TCPAddr: - bnd.HostPort = uint16(host.(*net.TCPAddr).Port) - break - case *net.UDPAddr: - bnd.HostPort = uint16(host.(*net.UDPAddr).Port) - break - case *sctp.SCTPAddr: - bnd.HostPort = uint16(host.(*sctp.SCTPAddr).Port) - break - default: - // For completeness - return ErrUnsupportedAddressType(fmt.Sprintf("%T", netAddr)) - } - //Windows does not support host port ranges. - bnd.HostPortEnd = bnd.HostPort - return nil -} - -// 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 -} - -func releasePort(portMapper *portmapper.PortMapper, bnd types.PortBinding) error { - // Construct the host side transport address - host, err := bnd.HostAddr() - if err != nil { - return err - } - return portMapper.Unmap(host) -} diff --git a/vendor/github.com/docker/libnetwork/drivers/windows/windows.go b/vendor/github.com/docker/libnetwork/drivers/windows/windows.go deleted file mode 100644 index 2dbd7c949e..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/windows/windows.go +++ /dev/null @@ -1,920 +0,0 @@ -// +build windows - -// Shim for the Host Network Service (HNS) to manage networking for -// Windows Server containers and Hyper-V containers. This module -// is a basic libnetwork driver that passes all the calls to HNS -// It implements the 4 networking modes supported by HNS L2Bridge, -// L2Tunnel, NAT and Transparent(DHCP) -// -// The network are stored in memory and docker daemon ensures discovering -// and loading these networks on startup - -package windows - -import ( - "encoding/json" - "fmt" - "net" - "strconv" - "strings" - "sync" - - "github.com/Microsoft/hcsshim" - "github.com/Microsoft/hcsshim/osversion" - "github.com/docker/libnetwork/datastore" - "github.com/docker/libnetwork/discoverapi" - "github.com/docker/libnetwork/driverapi" - "github.com/docker/libnetwork/netlabel" - "github.com/docker/libnetwork/portmapper" - "github.com/docker/libnetwork/types" - "github.com/sirupsen/logrus" -) - -// networkConfiguration for network specific configuration -type networkConfiguration struct { - ID string - Type string - Name string - HnsID string - RDID string - VLAN uint - VSID uint - DNSServers string - MacPools []hcsshim.MacPool - DNSSuffix string - SourceMac string - NetworkAdapterName string - dbIndex uint64 - dbExists bool - DisableGatewayDNS bool - EnableOutboundNat bool - OutboundNatExceptions []string -} - -// endpointConfiguration represents the user specified configuration for the sandbox endpoint -type endpointOption struct { - MacAddress net.HardwareAddr - QosPolicies []types.QosPolicy - DNSServers []string - DisableDNS bool - DisableICC bool -} - -// EndpointConnectivity stores the port bindings and exposed ports that the user has specified in epOptions. -type EndpointConnectivity struct { - PortBindings []types.PortBinding - ExposedPorts []types.TransportPort -} - -type hnsEndpoint struct { - id string - nid string - profileID string - Type string - //Note: Currently, the sandboxID is the same as the containerID since windows does - //not expose the sandboxID. - //In the future, windows will support a proper sandboxID that is different - //than the containerID. - //Therefore, we are using sandboxID now, so that we won't have to change this code - //when windows properly supports a sandboxID. - sandboxID string - macAddress net.HardwareAddr - epOption *endpointOption // User specified parameters - epConnectivity *EndpointConnectivity // User specified parameters - portMapping []types.PortBinding // Operation port bindings - addr *net.IPNet - gateway net.IP - dbIndex uint64 - dbExists bool -} - -type hnsNetwork struct { - id string - created bool - config *networkConfiguration - endpoints map[string]*hnsEndpoint // key: endpoint id - driver *driver // The network's driver - portMapper *portmapper.PortMapper - sync.Mutex -} - -type driver struct { - name string - networks map[string]*hnsNetwork - store datastore.DataStore - sync.Mutex -} - -const ( - errNotFound = "HNS failed with error : The object identifier does not represent a valid object. " -) - -// IsBuiltinLocalDriver validates if network-type is a builtin local-scoped driver -func IsBuiltinLocalDriver(networkType string) bool { - if "l2bridge" == networkType || "l2tunnel" == networkType || - "nat" == networkType || "ics" == networkType || - "transparent" == networkType || "internal" == networkType || - "private" == networkType { - return true - } - - return false -} - -// New constructs a new bridge driver -func newDriver(networkType string) *driver { - return &driver{name: networkType, networks: map[string]*hnsNetwork{}} -} - -// GetInit returns an initializer for the given network type -func GetInit(networkType string) func(dc driverapi.DriverCallback, config map[string]interface{}) error { - return func(dc driverapi.DriverCallback, config map[string]interface{}) error { - if !IsBuiltinLocalDriver(networkType) { - return types.BadRequestErrorf("Network type not supported: %s", networkType) - } - - d := newDriver(networkType) - - err := d.initStore(config) - if err != nil { - return err - } - - return dc.RegisterDriver(networkType, d, driverapi.Capability{ - DataScope: datastore.LocalScope, - ConnectivityScope: datastore.LocalScope, - }) - } -} - -func (d *driver) getNetwork(id string) (*hnsNetwork, error) { - d.Lock() - defer d.Unlock() - - if nw, ok := d.networks[id]; ok { - return nw, nil - } - - return nil, types.NotFoundErrorf("network not found: %s", id) -} - -func (n *hnsNetwork) getEndpoint(eid string) (*hnsEndpoint, error) { - n.Lock() - defer n.Unlock() - - if ep, ok := n.endpoints[eid]; ok { - return ep, nil - } - - return nil, types.NotFoundErrorf("Endpoint not found: %s", eid) -} - -func (d *driver) parseNetworkOptions(id string, genericOptions map[string]string) (*networkConfiguration, error) { - config := &networkConfiguration{Type: d.name} - - for label, value := range genericOptions { - switch label { - case NetworkName: - config.Name = value - case HNSID: - config.HnsID = value - case RoutingDomain: - config.RDID = value - case Interface: - config.NetworkAdapterName = value - case DNSSuffix: - config.DNSSuffix = value - case DNSServers: - config.DNSServers = value - case DisableGatewayDNS: - b, err := strconv.ParseBool(value) - if err != nil { - return nil, err - } - config.DisableGatewayDNS = b - case MacPool: - config.MacPools = make([]hcsshim.MacPool, 0) - s := strings.Split(value, ",") - if len(s)%2 != 0 { - return nil, types.BadRequestErrorf("Invalid mac pool. You must specify both a start range and an end range") - } - for i := 0; i < len(s)-1; i += 2 { - config.MacPools = append(config.MacPools, hcsshim.MacPool{ - StartMacAddress: s[i], - EndMacAddress: s[i+1], - }) - } - case VLAN: - vlan, err := strconv.ParseUint(value, 10, 32) - if err != nil { - return nil, err - } - config.VLAN = uint(vlan) - case VSID: - vsid, err := strconv.ParseUint(value, 10, 32) - if err != nil { - return nil, err - } - config.VSID = uint(vsid) - case EnableOutboundNat: - if osversion.Build() <= 16236 { - return nil, fmt.Errorf("Invalid network option. OutboundNat is not supported on this OS version") - } - b, err := strconv.ParseBool(value) - if err != nil { - return nil, err - } - config.EnableOutboundNat = b - case OutboundNatExceptions: - s := strings.Split(value, ",") - config.OutboundNatExceptions = s - } - } - - config.ID = id - config.Type = d.name - return config, nil -} - -func (c *networkConfiguration) processIPAM(id string, ipamV4Data, ipamV6Data []driverapi.IPAMData) error { - if len(ipamV6Data) > 0 { - return types.ForbiddenErrorf("windowsshim driver doesn't support v6 subnets") - } - - if len(ipamV4Data) == 0 { - return types.BadRequestErrorf("network %s requires ipv4 configuration", id) - } - - return nil -} - -func (d *driver) EventNotify(etype driverapi.EventType, nid, tableName, key string, value []byte) { -} - -func (d *driver) DecodeTableEntry(tablename string, key string, value []byte) (string, map[string]string) { - return "", nil -} - -func (d *driver) createNetwork(config *networkConfiguration) *hnsNetwork { - network := &hnsNetwork{ - id: config.ID, - endpoints: make(map[string]*hnsEndpoint), - config: config, - driver: d, - portMapper: portmapper.New(""), - } - - d.Lock() - d.networks[config.ID] = network - d.Unlock() - - return network -} - -// Create a new network -func (d *driver) CreateNetwork(id string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error { - if _, err := d.getNetwork(id); err == nil { - return types.ForbiddenErrorf("network %s exists", id) - } - - genData, ok := option[netlabel.GenericData].(map[string]string) - if !ok { - return fmt.Errorf("Unknown generic data option") - } - - // Parse and validate the config. It should not conflict with existing networks' config - config, err := d.parseNetworkOptions(id, genData) - if err != nil { - return err - } - - err = config.processIPAM(id, ipV4Data, ipV6Data) - if err != nil { - return err - } - - n := d.createNetwork(config) - - // A non blank hnsid indicates that the network was discovered - // from HNS. No need to call HNS if this network was discovered - // from HNS - if config.HnsID == "" { - subnets := []hcsshim.Subnet{} - - for _, ipData := range ipV4Data { - subnet := hcsshim.Subnet{ - AddressPrefix: ipData.Pool.String(), - } - - if ipData.Gateway != nil { - subnet.GatewayAddress = ipData.Gateway.IP.String() - } - - subnets = append(subnets, subnet) - } - - network := &hcsshim.HNSNetwork{ - Name: config.Name, - Type: d.name, - Subnets: subnets, - DNSServerList: config.DNSServers, - DNSSuffix: config.DNSSuffix, - MacPools: config.MacPools, - SourceMac: config.SourceMac, - NetworkAdapterName: config.NetworkAdapterName, - } - - if config.VLAN != 0 { - vlanPolicy, err := json.Marshal(hcsshim.VlanPolicy{ - Type: "VLAN", - VLAN: config.VLAN, - }) - - if err != nil { - return err - } - network.Policies = append(network.Policies, vlanPolicy) - } - - if config.VSID != 0 { - vsidPolicy, err := json.Marshal(hcsshim.VsidPolicy{ - Type: "VSID", - VSID: config.VSID, - }) - - if err != nil { - return err - } - network.Policies = append(network.Policies, vsidPolicy) - } - - if network.Name == "" { - network.Name = id - } - - configurationb, err := json.Marshal(network) - if err != nil { - return err - } - - configuration := string(configurationb) - logrus.Debugf("HNSNetwork Request =%v Address Space=%v", configuration, subnets) - - hnsresponse, err := hcsshim.HNSNetworkRequest("POST", "", configuration) - if err != nil { - return err - } - - config.HnsID = hnsresponse.Id - genData[HNSID] = config.HnsID - n.created = true - - defer func() { - if err != nil { - d.DeleteNetwork(n.id) - } - }() - - hnsIPv4Data := make([]driverapi.IPAMData, len(hnsresponse.Subnets)) - - for i, subnet := range hnsresponse.Subnets { - var gwIP, subnetIP *net.IPNet - - //The gateway returned from HNS is an IPAddress. - //We need to convert it to an IPNet to use as the Gateway of driverapi.IPAMData struct - gwCIDR := subnet.GatewayAddress + "/32" - _, gwIP, err = net.ParseCIDR(gwCIDR) - if err != nil { - return err - } - - hnsIPv4Data[i].Gateway = gwIP - _, subnetIP, err = net.ParseCIDR(subnet.AddressPrefix) - if err != nil { - return err - } - hnsIPv4Data[i].Pool = subnetIP - } - - nInfo.UpdateIpamConfig(hnsIPv4Data) - - } else { - // Delete any stale HNS endpoints for this network. - if endpoints, err := hcsshim.HNSListEndpointRequest(); err == nil { - for _, ep := range endpoints { - if ep.VirtualNetwork == config.HnsID { - logrus.Infof("Removing stale HNS endpoint %s", ep.Id) - _, err = hcsshim.HNSEndpointRequest("DELETE", ep.Id, "") - if err != nil { - logrus.Warnf("Error removing HNS endpoint %s", ep.Id) - } - } - } - } else { - logrus.Warnf("Error listing HNS endpoints for network %s", config.HnsID) - } - - n.created = true - } - - return d.storeUpdate(config) -} - -func (d *driver) DeleteNetwork(nid string) error { - n, err := d.getNetwork(nid) - if err != nil { - return types.InternalMaskableErrorf("%s", err) - } - - n.Lock() - config := n.config - n.Unlock() - - if n.created { - _, err = hcsshim.HNSNetworkRequest("DELETE", config.HnsID, "") - if err != nil && err.Error() != errNotFound { - return types.ForbiddenErrorf(err.Error()) - } - } - - d.Lock() - delete(d.networks, nid) - d.Unlock() - - // delele endpoints belong to this network - for _, ep := range n.endpoints { - if err := d.storeDelete(ep); err != nil { - logrus.Warnf("Failed to remove bridge endpoint %.7s from store: %v", ep.id, err) - } - } - - return d.storeDelete(config) -} - -func convertQosPolicies(qosPolicies []types.QosPolicy) ([]json.RawMessage, error) { - var qps []json.RawMessage - - // Enumerate through the qos policies specified by the user and convert - // them into the internal structure matching the JSON blob that can be - // understood by the HCS. - for _, elem := range qosPolicies { - encodedPolicy, err := json.Marshal(hcsshim.QosPolicy{ - Type: "QOS", - MaximumOutgoingBandwidthInBytes: elem.MaxEgressBandwidth, - }) - - if err != nil { - return nil, err - } - qps = append(qps, encodedPolicy) - } - return qps, nil -} - -// ConvertPortBindings converts PortBindings to JSON for HNS request -func ConvertPortBindings(portBindings []types.PortBinding) ([]json.RawMessage, error) { - var pbs []json.RawMessage - - // Enumerate through the port bindings specified by the user and convert - // them into the internal structure matching the JSON blob that can be - // understood by the HCS. - for _, elem := range portBindings { - proto := strings.ToUpper(elem.Proto.String()) - if proto != "TCP" && proto != "UDP" { - return nil, fmt.Errorf("invalid protocol %s", elem.Proto.String()) - } - - if elem.HostPort != elem.HostPortEnd { - return nil, fmt.Errorf("Windows does not support more than one host port in NAT settings") - } - - if len(elem.HostIP) != 0 && !elem.HostIP.IsUnspecified() { - return nil, fmt.Errorf("Windows does not support host IP addresses in NAT settings") - } - - encodedPolicy, err := json.Marshal(hcsshim.NatPolicy{ - Type: "NAT", - ExternalPort: elem.HostPort, - InternalPort: elem.Port, - Protocol: elem.Proto.String(), - }) - - if err != nil { - return nil, err - } - pbs = append(pbs, encodedPolicy) - } - return pbs, nil -} - -// ParsePortBindingPolicies parses HNS endpoint response message to PortBindings -func ParsePortBindingPolicies(policies []json.RawMessage) ([]types.PortBinding, error) { - var bindings []types.PortBinding - hcsPolicy := &hcsshim.NatPolicy{} - - for _, elem := range policies { - - if err := json.Unmarshal([]byte(elem), &hcsPolicy); err != nil || hcsPolicy.Type != "NAT" { - continue - } - - binding := types.PortBinding{ - HostPort: hcsPolicy.ExternalPort, - HostPortEnd: hcsPolicy.ExternalPort, - Port: hcsPolicy.InternalPort, - Proto: types.ParseProtocol(hcsPolicy.Protocol), - HostIP: net.IPv4(0, 0, 0, 0), - } - - bindings = append(bindings, binding) - } - - return bindings, nil -} - -func parseEndpointOptions(epOptions map[string]interface{}) (*endpointOption, error) { - if epOptions == nil { - return nil, nil - } - - ec := &endpointOption{} - - if opt, ok := epOptions[netlabel.MacAddress]; ok { - if mac, ok := opt.(net.HardwareAddr); ok { - ec.MacAddress = mac - } else { - return nil, fmt.Errorf("Invalid endpoint configuration") - } - } - - if opt, ok := epOptions[QosPolicies]; ok { - if policies, ok := opt.([]types.QosPolicy); ok { - ec.QosPolicies = policies - } else { - return nil, fmt.Errorf("Invalid endpoint configuration") - } - } - - if opt, ok := epOptions[netlabel.DNSServers]; ok { - if dns, ok := opt.([]string); ok { - ec.DNSServers = dns - } else { - return nil, fmt.Errorf("Invalid endpoint configuration") - } - } - - if opt, ok := epOptions[DisableICC]; ok { - if disableICC, ok := opt.(bool); ok { - ec.DisableICC = disableICC - } else { - return nil, fmt.Errorf("Invalid endpoint configuration") - } - } - - if opt, ok := epOptions[DisableDNS]; ok { - if disableDNS, ok := opt.(bool); ok { - ec.DisableDNS = disableDNS - } else { - return nil, fmt.Errorf("Invalid endpoint configuration") - } - } - - return ec, nil -} - -// ParseEndpointConnectivity parses options passed to CreateEndpoint, specifically port bindings, and store in a endpointConnectivity object. -func ParseEndpointConnectivity(epOptions map[string]interface{}) (*EndpointConnectivity, error) { - if epOptions == nil { - return nil, nil - } - - ec := &EndpointConnectivity{} - - if opt, ok := epOptions[netlabel.PortMap]; ok { - if bs, ok := opt.([]types.PortBinding); ok { - ec.PortBindings = bs - } else { - return nil, fmt.Errorf("Invalid endpoint configuration") - } - } - - if opt, ok := epOptions[netlabel.ExposedPorts]; ok { - if ports, ok := opt.([]types.TransportPort); ok { - ec.ExposedPorts = ports - } else { - return nil, fmt.Errorf("Invalid endpoint configuration") - } - } - return ec, nil -} - -func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo, epOptions map[string]interface{}) error { - n, err := d.getNetwork(nid) - if err != nil { - return err - } - - // Check if endpoint id is good and retrieve corresponding endpoint - ep, err := n.getEndpoint(eid) - if err == nil && ep != nil { - return driverapi.ErrEndpointExists(eid) - } - - endpointStruct := &hcsshim.HNSEndpoint{ - VirtualNetwork: n.config.HnsID, - } - - epOption, err := parseEndpointOptions(epOptions) - if err != nil { - return err - } - epConnectivity, err := ParseEndpointConnectivity(epOptions) - if err != nil { - return err - } - - macAddress := ifInfo.MacAddress() - // Use the macaddress if it was provided - if macAddress != nil { - endpointStruct.MacAddress = strings.Replace(macAddress.String(), ":", "-", -1) - } - - portMapping := epConnectivity.PortBindings - - if n.config.Type == "l2bridge" || n.config.Type == "l2tunnel" { - ip := net.IPv4(0, 0, 0, 0) - if ifInfo.Address() != nil { - ip = ifInfo.Address().IP - } - - portMapping, err = AllocatePorts(n.portMapper, portMapping, ip) - if err != nil { - return err - } - - defer func() { - if err != nil { - ReleasePorts(n.portMapper, portMapping) - } - }() - } - - endpointStruct.Policies, err = ConvertPortBindings(portMapping) - if err != nil { - return err - } - - qosPolicies, err := convertQosPolicies(epOption.QosPolicies) - if err != nil { - return err - } - endpointStruct.Policies = append(endpointStruct.Policies, qosPolicies...) - - if ifInfo.Address() != nil { - endpointStruct.IPAddress = ifInfo.Address().IP - } - - endpointStruct.DNSServerList = strings.Join(epOption.DNSServers, ",") - - // overwrite the ep DisableDNS option if DisableGatewayDNS was set to true during the network creation option - if n.config.DisableGatewayDNS { - logrus.Debugf("n.config.DisableGatewayDNS[%v] overwrites epOption.DisableDNS[%v]", n.config.DisableGatewayDNS, epOption.DisableDNS) - epOption.DisableDNS = n.config.DisableGatewayDNS - } - - if n.driver.name == "nat" && !epOption.DisableDNS { - logrus.Debugf("endpointStruct.EnableInternalDNS =[%v]", endpointStruct.EnableInternalDNS) - endpointStruct.EnableInternalDNS = true - } - - endpointStruct.DisableICC = epOption.DisableICC - - // Inherit OutboundNat policy from the network - if n.config.EnableOutboundNat { - outboundNatPolicy, err := json.Marshal(hcsshim.OutboundNatPolicy{ - Policy: hcsshim.Policy{Type: hcsshim.OutboundNat}, - Exceptions: n.config.OutboundNatExceptions, - }) - - if err != nil { - return err - } - endpointStruct.Policies = append(endpointStruct.Policies, outboundNatPolicy) - } - - configurationb, err := json.Marshal(endpointStruct) - if err != nil { - return err - } - - hnsresponse, err := hcsshim.HNSEndpointRequest("POST", "", string(configurationb)) - if err != nil { - return err - } - - mac, err := net.ParseMAC(hnsresponse.MacAddress) - if err != nil { - return err - } - - // TODO For now the ip mask is not in the info generated by HNS - endpoint := &hnsEndpoint{ - id: eid, - nid: n.id, - Type: d.name, - addr: &net.IPNet{IP: hnsresponse.IPAddress, Mask: hnsresponse.IPAddress.DefaultMask()}, - macAddress: mac, - } - - if hnsresponse.GatewayAddress != "" { - endpoint.gateway = net.ParseIP(hnsresponse.GatewayAddress) - } - - endpoint.profileID = hnsresponse.Id - endpoint.epConnectivity = epConnectivity - endpoint.epOption = epOption - endpoint.portMapping, err = ParsePortBindingPolicies(hnsresponse.Policies) - - if err != nil { - hcsshim.HNSEndpointRequest("DELETE", hnsresponse.Id, "") - return err - } - - n.Lock() - n.endpoints[eid] = endpoint - n.Unlock() - - if ifInfo.Address() == nil { - ifInfo.SetIPAddress(endpoint.addr) - } - - if macAddress == nil { - ifInfo.SetMacAddress(endpoint.macAddress) - } - - if err = d.storeUpdate(endpoint); err != nil { - logrus.Errorf("Failed to save endpoint %.7s to store: %v", endpoint.id, err) - } - - return nil -} - -func (d *driver) DeleteEndpoint(nid, eid string) error { - n, err := d.getNetwork(nid) - if err != nil { - return types.InternalMaskableErrorf("%s", err) - } - - ep, err := n.getEndpoint(eid) - if err != nil { - return err - } - - if n.config.Type == "l2bridge" || n.config.Type == "l2tunnel" { - ReleasePorts(n.portMapper, ep.portMapping) - } - - n.Lock() - delete(n.endpoints, eid) - n.Unlock() - - _, err = hcsshim.HNSEndpointRequest("DELETE", ep.profileID, "") - if err != nil && err.Error() != errNotFound { - return err - } - - if err := d.storeDelete(ep); err != nil { - logrus.Warnf("Failed to remove bridge endpoint %.7s from store: %v", ep.id, err) - } - return nil -} - -func (d *driver) EndpointOperInfo(nid, eid string) (map[string]interface{}, error) { - network, err := d.getNetwork(nid) - if err != nil { - return nil, err - } - - ep, err := network.getEndpoint(eid) - if err != nil { - return nil, err - } - - data := make(map[string]interface{}, 1) - if network.driver.name == "nat" { - data["AllowUnqualifiedDNSQuery"] = true - } - - data["hnsid"] = ep.profileID - if ep.epConnectivity.ExposedPorts != nil { - // Return a copy of the config data - epc := make([]types.TransportPort, 0, len(ep.epConnectivity.ExposedPorts)) - for _, tp := range ep.epConnectivity.ExposedPorts { - epc = append(epc, tp.GetCopy()) - } - data[netlabel.ExposedPorts] = epc - } - - if ep.portMapping != nil { - // Return a copy of the operational data - pmc := make([]types.PortBinding, 0, len(ep.portMapping)) - for _, pm := range ep.portMapping { - pmc = append(pmc, pm.GetCopy()) - } - data[netlabel.PortMap] = pmc - } - - if len(ep.macAddress) != 0 { - data[netlabel.MacAddress] = ep.macAddress - } - return data, nil -} - -// Join method is invoked when a Sandbox is attached to an endpoint. -func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error { - network, err := d.getNetwork(nid) - if err != nil { - return err - } - - // Ensure that the endpoint exists - endpoint, err := network.getEndpoint(eid) - if err != nil { - return err - } - - err = jinfo.SetGateway(endpoint.gateway) - if err != nil { - return err - } - - endpoint.sandboxID = sboxKey - - err = hcsshim.HotAttachEndpoint(endpoint.sandboxID, endpoint.profileID) - if err != nil { - // If container doesn't exists in hcs, do not throw error for hot add/remove - if err != hcsshim.ErrComputeSystemDoesNotExist { - return err - } - } - - jinfo.DisableGatewayService() - return nil -} - -// Leave method is invoked when a Sandbox detaches from an endpoint. -func (d *driver) Leave(nid, eid string) error { - network, err := d.getNetwork(nid) - if err != nil { - return types.InternalMaskableErrorf("%s", err) - } - - // Ensure that the endpoint exists - endpoint, err := network.getEndpoint(eid) - if err != nil { - return err - } - - err = hcsshim.HotDetachEndpoint(endpoint.sandboxID, endpoint.profileID) - if err != nil { - // If container doesn't exists in hcs, do not throw error for hot add/remove - if err != hcsshim.ErrComputeSystemDoesNotExist { - return err - } - } - return nil -} - -func (d *driver) ProgramExternalConnectivity(nid, eid string, options map[string]interface{}) error { - return nil -} - -func (d *driver) RevokeExternalConnectivity(nid, eid string) error { - return nil -} - -func (d *driver) NetworkAllocate(id string, option map[string]string, ipV4Data, ipV6Data []driverapi.IPAMData) (map[string]string, error) { - return nil, types.NotImplementedErrorf("not implemented") -} - -func (d *driver) NetworkFree(id string) error { - return types.NotImplementedErrorf("not implemented") -} - -func (d *driver) Type() string { - return d.name -} - -func (d *driver) IsBuiltIn() bool { - return true -} - -// DiscoverNew is a notification for a new discovery event, such as a new node joining a cluster -func (d *driver) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error { - return nil -} - -// DiscoverDelete is a notification for a discovery delete event, such as a node leaving a cluster -func (d *driver) DiscoverDelete(dType discoverapi.DiscoveryType, data interface{}) error { - return nil -} diff --git a/vendor/github.com/docker/libnetwork/drivers/windows/windows_store.go b/vendor/github.com/docker/libnetwork/drivers/windows/windows_store.go deleted file mode 100644 index 9ca8be27eb..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers/windows/windows_store.go +++ /dev/null @@ -1,337 +0,0 @@ -// +build windows - -package windows - -import ( - "encoding/json" - "fmt" - "net" - - "github.com/docker/libnetwork/datastore" - "github.com/docker/libnetwork/discoverapi" - "github.com/docker/libnetwork/netlabel" - "github.com/docker/libnetwork/types" - "github.com/sirupsen/logrus" -) - -const ( - windowsPrefix = "windows" - windowsEndpointPrefix = "windows-endpoint" -) - -func (d *driver) initStore(option map[string]interface{}) error { - if data, ok := option[netlabel.LocalKVClient]; ok { - var err error - dsc, ok := data.(discoverapi.DatastoreConfigData) - if !ok { - return types.InternalErrorf("incorrect data in datastore configuration: %v", data) - } - d.store, err = datastore.NewDataStoreFromConfig(dsc) - if err != nil { - return types.InternalErrorf("windows driver failed to initialize data store: %v", err) - } - - err = d.populateNetworks() - if err != nil { - return err - } - - err = d.populateEndpoints() - if err != nil { - return err - } - } - - return nil -} - -func (d *driver) populateNetworks() error { - kvol, err := d.store.List(datastore.Key(windowsPrefix), &networkConfiguration{Type: d.name}) - if err != nil && err != datastore.ErrKeyNotFound { - return fmt.Errorf("failed to get windows network configurations from store: %v", err) - } - - // It's normal for network configuration state to be empty. Just return. - if err == datastore.ErrKeyNotFound { - return nil - } - - for _, kvo := range kvol { - ncfg := kvo.(*networkConfiguration) - if ncfg.Type != d.name { - continue - } - d.createNetwork(ncfg) - logrus.Debugf("Network %v (%.7s) restored", d.name, ncfg.ID) - } - - return nil -} - -func (d *driver) populateEndpoints() error { - kvol, err := d.store.List(datastore.Key(windowsEndpointPrefix), &hnsEndpoint{Type: d.name}) - if err != nil && err != datastore.ErrKeyNotFound { - return fmt.Errorf("failed to get endpoints from store: %v", err) - } - - if err == datastore.ErrKeyNotFound { - return nil - } - - for _, kvo := range kvol { - ep := kvo.(*hnsEndpoint) - if ep.Type != d.name { - continue - } - n, ok := d.networks[ep.nid] - if !ok { - logrus.Debugf("Network (%.7s) not found for restored endpoint (%.7s)", ep.nid, ep.id) - logrus.Debugf("Deleting stale endpoint (%.7s) from store", ep.id) - if err := d.storeDelete(ep); err != nil { - logrus.Debugf("Failed to delete stale endpoint (%.7s) from store", ep.id) - } - continue - } - n.endpoints[ep.id] = ep - logrus.Debugf("Endpoint (%.7s) restored to network (%.7s)", ep.id, ep.nid) - } - - return nil -} - -func (d *driver) storeUpdate(kvObject datastore.KVObject) error { - if d.store == nil { - logrus.Warnf("store not initialized. kv object %s is not added to the store", datastore.Key(kvObject.Key()...)) - return nil - } - - if err := d.store.PutObjectAtomic(kvObject); err != nil { - return fmt.Errorf("failed to update store for object type %T: %v", kvObject, err) - } - - return nil -} - -func (d *driver) storeDelete(kvObject datastore.KVObject) error { - if d.store == nil { - logrus.Debugf("store not initialized. kv object %s is not deleted from store", datastore.Key(kvObject.Key()...)) - return nil - } - -retry: - if err := d.store.DeleteObjectAtomic(kvObject); err != nil { - if err == datastore.ErrKeyModified { - if err := d.store.GetObject(datastore.Key(kvObject.Key()...), kvObject); err != nil { - return fmt.Errorf("could not update the kvobject to latest when trying to delete: %v", err) - } - goto retry - } - return err - } - - return nil -} - -func (ncfg *networkConfiguration) MarshalJSON() ([]byte, error) { - nMap := make(map[string]interface{}) - - nMap["ID"] = ncfg.ID - nMap["Type"] = ncfg.Type - nMap["Name"] = ncfg.Name - nMap["HnsID"] = ncfg.HnsID - nMap["VLAN"] = ncfg.VLAN - nMap["VSID"] = ncfg.VSID - nMap["DNSServers"] = ncfg.DNSServers - nMap["DNSSuffix"] = ncfg.DNSSuffix - nMap["SourceMac"] = ncfg.SourceMac - nMap["NetworkAdapterName"] = ncfg.NetworkAdapterName - - return json.Marshal(nMap) -} - -func (ncfg *networkConfiguration) UnmarshalJSON(b []byte) error { - var ( - err error - nMap map[string]interface{} - ) - - if err = json.Unmarshal(b, &nMap); err != nil { - return err - } - - ncfg.ID = nMap["ID"].(string) - ncfg.Type = nMap["Type"].(string) - ncfg.Name = nMap["Name"].(string) - ncfg.HnsID = nMap["HnsID"].(string) - ncfg.VLAN = uint(nMap["VLAN"].(float64)) - ncfg.VSID = uint(nMap["VSID"].(float64)) - ncfg.DNSServers = nMap["DNSServers"].(string) - ncfg.DNSSuffix = nMap["DNSSuffix"].(string) - ncfg.SourceMac = nMap["SourceMac"].(string) - ncfg.NetworkAdapterName = nMap["NetworkAdapterName"].(string) - return nil -} - -func (ncfg *networkConfiguration) Key() []string { - return []string{windowsPrefix + ncfg.Type, ncfg.ID} -} - -func (ncfg *networkConfiguration) KeyPrefix() []string { - return []string{windowsPrefix + ncfg.Type} -} - -func (ncfg *networkConfiguration) Value() []byte { - b, err := json.Marshal(ncfg) - if err != nil { - return nil - } - return b -} - -func (ncfg *networkConfiguration) SetValue(value []byte) error { - return json.Unmarshal(value, ncfg) -} - -func (ncfg *networkConfiguration) Index() uint64 { - return ncfg.dbIndex -} - -func (ncfg *networkConfiguration) SetIndex(index uint64) { - ncfg.dbIndex = index - ncfg.dbExists = true -} - -func (ncfg *networkConfiguration) Exists() bool { - return ncfg.dbExists -} - -func (ncfg *networkConfiguration) Skip() bool { - return false -} - -func (ncfg *networkConfiguration) New() datastore.KVObject { - return &networkConfiguration{Type: ncfg.Type} -} - -func (ncfg *networkConfiguration) CopyTo(o datastore.KVObject) error { - dstNcfg := o.(*networkConfiguration) - *dstNcfg = *ncfg - return nil -} - -func (ncfg *networkConfiguration) DataScope() string { - return datastore.LocalScope -} - -func (ep *hnsEndpoint) MarshalJSON() ([]byte, error) { - epMap := make(map[string]interface{}) - epMap["id"] = ep.id - epMap["nid"] = ep.nid - epMap["Type"] = ep.Type - epMap["profileID"] = ep.profileID - epMap["MacAddress"] = ep.macAddress.String() - if ep.addr.IP != nil { - epMap["Addr"] = ep.addr.String() - } - if ep.gateway != nil { - epMap["gateway"] = ep.gateway.String() - } - epMap["epOption"] = ep.epOption - epMap["epConnectivity"] = ep.epConnectivity - epMap["PortMapping"] = ep.portMapping - - return json.Marshal(epMap) -} - -func (ep *hnsEndpoint) UnmarshalJSON(b []byte) error { - var ( - err error - epMap map[string]interface{} - ) - - if err = json.Unmarshal(b, &epMap); err != nil { - return fmt.Errorf("Failed to unmarshal to endpoint: %v", err) - } - if v, ok := epMap["MacAddress"]; ok { - if ep.macAddress, err = net.ParseMAC(v.(string)); err != nil { - return types.InternalErrorf("failed to decode endpoint MAC address (%s) after json unmarshal: %v", v.(string), err) - } - } - if v, ok := epMap["Addr"]; ok { - if ep.addr, err = types.ParseCIDR(v.(string)); err != nil { - logrus.Warnf("failed to decode endpoint IPv4 address (%s) after json unmarshal: %v", v.(string), err) - } - } - if v, ok := epMap["gateway"]; ok { - ep.gateway = net.ParseIP(v.(string)) - } - ep.id = epMap["id"].(string) - ep.Type = epMap["Type"].(string) - ep.nid = epMap["nid"].(string) - ep.profileID = epMap["profileID"].(string) - d, _ := json.Marshal(epMap["epOption"]) - if err := json.Unmarshal(d, &ep.epOption); err != nil { - logrus.Warnf("Failed to decode endpoint container config %v", err) - } - d, _ = json.Marshal(epMap["epConnectivity"]) - if err := json.Unmarshal(d, &ep.epConnectivity); err != nil { - logrus.Warnf("Failed to decode endpoint external connectivity configuration %v", err) - } - d, _ = json.Marshal(epMap["PortMapping"]) - if err := json.Unmarshal(d, &ep.portMapping); err != nil { - logrus.Warnf("Failed to decode endpoint port mapping %v", err) - } - - return nil -} - -func (ep *hnsEndpoint) Key() []string { - return []string{windowsEndpointPrefix + ep.Type, ep.id} -} - -func (ep *hnsEndpoint) KeyPrefix() []string { - return []string{windowsEndpointPrefix + ep.Type} -} - -func (ep *hnsEndpoint) Value() []byte { - b, err := json.Marshal(ep) - if err != nil { - return nil - } - return b -} - -func (ep *hnsEndpoint) SetValue(value []byte) error { - return json.Unmarshal(value, ep) -} - -func (ep *hnsEndpoint) Index() uint64 { - return ep.dbIndex -} - -func (ep *hnsEndpoint) SetIndex(index uint64) { - ep.dbIndex = index - ep.dbExists = true -} - -func (ep *hnsEndpoint) Exists() bool { - return ep.dbExists -} - -func (ep *hnsEndpoint) Skip() bool { - return false -} - -func (ep *hnsEndpoint) New() datastore.KVObject { - return &hnsEndpoint{Type: ep.Type} -} - -func (ep *hnsEndpoint) CopyTo(o datastore.KVObject) error { - dstEp := o.(*hnsEndpoint) - *dstEp = *ep - return nil -} - -func (ep *hnsEndpoint) DataScope() string { - return datastore.LocalScope -} diff --git a/vendor/github.com/docker/libnetwork/drivers_freebsd.go b/vendor/github.com/docker/libnetwork/drivers_freebsd.go deleted file mode 100644 index d117c25780..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers_freebsd.go +++ /dev/null @@ -1,13 +0,0 @@ -package libnetwork - -import ( - "github.com/docker/libnetwork/drivers/null" - "github.com/docker/libnetwork/drivers/remote" -) - -func getInitializers(experimental bool) []initializer { - return []initializer{ - {null.Init, "null"}, - {remote.Init, "remote"}, - } -} diff --git a/vendor/github.com/docker/libnetwork/drivers_ipam.go b/vendor/github.com/docker/libnetwork/drivers_ipam.go deleted file mode 100644 index f47c01c714..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers_ipam.go +++ /dev/null @@ -1,25 +0,0 @@ -package libnetwork - -import ( - "github.com/docker/libnetwork/drvregistry" - "github.com/docker/libnetwork/ipamapi" - builtinIpam "github.com/docker/libnetwork/ipams/builtin" - nullIpam "github.com/docker/libnetwork/ipams/null" - remoteIpam "github.com/docker/libnetwork/ipams/remote" - "github.com/docker/libnetwork/ipamutils" -) - -func initIPAMDrivers(r *drvregistry.DrvRegistry, lDs, gDs interface{}, addressPool []*ipamutils.NetworkToSplit) error { - builtinIpam.SetDefaultIPAddressPool(addressPool) - for _, fn := range [](func(ipamapi.Callback, interface{}, interface{}) error){ - builtinIpam.Init, - remoteIpam.Init, - nullIpam.Init, - } { - if err := fn(r, lDs, gDs); err != nil { - return err - } - } - - return nil -} diff --git a/vendor/github.com/docker/libnetwork/drivers_linux.go b/vendor/github.com/docker/libnetwork/drivers_linux.go deleted file mode 100644 index 452ffca052..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers_linux.go +++ /dev/null @@ -1,24 +0,0 @@ -package libnetwork - -import ( - "github.com/docker/libnetwork/drivers/bridge" - "github.com/docker/libnetwork/drivers/host" - "github.com/docker/libnetwork/drivers/ipvlan" - "github.com/docker/libnetwork/drivers/macvlan" - "github.com/docker/libnetwork/drivers/null" - "github.com/docker/libnetwork/drivers/overlay" - "github.com/docker/libnetwork/drivers/remote" -) - -func getInitializers(experimental bool) []initializer { - in := []initializer{ - {bridge.Init, "bridge"}, - {host.Init, "host"}, - {ipvlan.Init, "ipvlan"}, - {macvlan.Init, "macvlan"}, - {null.Init, "null"}, - {overlay.Init, "overlay"}, - {remote.Init, "remote"}, - } - return in -} diff --git a/vendor/github.com/docker/libnetwork/drivers_windows.go b/vendor/github.com/docker/libnetwork/drivers_windows.go deleted file mode 100644 index e82f5c3016..0000000000 --- a/vendor/github.com/docker/libnetwork/drivers_windows.go +++ /dev/null @@ -1,23 +0,0 @@ -package libnetwork - -import ( - "github.com/docker/libnetwork/drivers/null" - "github.com/docker/libnetwork/drivers/remote" - "github.com/docker/libnetwork/drivers/windows" - "github.com/docker/libnetwork/drivers/windows/overlay" -) - -func getInitializers(experimental bool) []initializer { - return []initializer{ - {null.Init, "null"}, - {overlay.Init, "overlay"}, - {remote.Init, "remote"}, - {windows.GetInit("transparent"), "transparent"}, - {windows.GetInit("l2bridge"), "l2bridge"}, - {windows.GetInit("l2tunnel"), "l2tunnel"}, - {windows.GetInit("nat"), "nat"}, - {windows.GetInit("internal"), "internal"}, - {windows.GetInit("private"), "private"}, - {windows.GetInit("ics"), "ics"}, - } -} diff --git a/vendor/github.com/docker/libnetwork/drvregistry/drvregistry.go b/vendor/github.com/docker/libnetwork/drvregistry/drvregistry.go deleted file mode 100644 index cc336fa5a8..0000000000 --- a/vendor/github.com/docker/libnetwork/drvregistry/drvregistry.go +++ /dev/null @@ -1,228 +0,0 @@ -package drvregistry - -import ( - "errors" - "fmt" - "strings" - "sync" - - "github.com/docker/docker/pkg/plugingetter" - "github.com/docker/libnetwork/driverapi" - "github.com/docker/libnetwork/ipamapi" - "github.com/docker/libnetwork/types" -) - -type driverData struct { - driver driverapi.Driver - capability driverapi.Capability -} - -type ipamData struct { - driver ipamapi.Ipam - capability *ipamapi.Capability - // default address spaces are provided by ipam driver at registration time - defaultLocalAddressSpace, defaultGlobalAddressSpace string -} - -type driverTable map[string]*driverData -type ipamTable map[string]*ipamData - -// DrvRegistry holds the registry of all network drivers and IPAM drivers that it knows about. -type DrvRegistry struct { - sync.Mutex - drivers driverTable - ipamDrivers ipamTable - dfn DriverNotifyFunc - ifn IPAMNotifyFunc - pluginGetter plugingetter.PluginGetter -} - -// Functors definition - -// InitFunc defines the driver initialization function signature. -type InitFunc func(driverapi.DriverCallback, map[string]interface{}) error - -// IPAMWalkFunc defines the IPAM driver table walker function signature. -type IPAMWalkFunc func(name string, driver ipamapi.Ipam, cap *ipamapi.Capability) bool - -// DriverWalkFunc defines the network driver table walker function signature. -type DriverWalkFunc func(name string, driver driverapi.Driver, capability driverapi.Capability) bool - -// IPAMNotifyFunc defines the notify function signature when a new IPAM driver gets registered. -type IPAMNotifyFunc func(name string, driver ipamapi.Ipam, cap *ipamapi.Capability) error - -// DriverNotifyFunc defines the notify function signature when a new network driver gets registered. -type DriverNotifyFunc func(name string, driver driverapi.Driver, capability driverapi.Capability) 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 -} - -// 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) -} - -// 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 - } - } -} - -// 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 - } - } -} - -// 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 -} - -// 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 -} - -// 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 -} - -// GetPluginGetter returns the plugingetter -func (r *DrvRegistry) GetPluginGetter() plugingetter.PluginGetter { - return r.pluginGetter -} - -// 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 -} - -func (r *DrvRegistry) registerIpamDriver(name string, driver ipamapi.Ipam, caps *ipamapi.Capability) error { - if strings.TrimSpace(name) == "" { - return errors.New("ipam driver name string cannot be empty") - } - - r.Lock() - dd, ok := r.ipamDrivers[name] - r.Unlock() - if ok && dd.driver.IsBuiltIn() { - return types.ForbiddenErrorf("ipam driver %q already registered", name) - } - - locAS, glbAS, err := driver.GetDefaultAddressSpaces() - if err != nil { - return types.InternalErrorf("ipam driver %q failed to return default address spaces: %v", name, err) - } - - if r.ifn != nil { - if err := r.ifn(name, driver, caps); err != nil { - return err - } - } - - r.Lock() - r.ipamDrivers[name] = &ipamData{driver: driver, defaultLocalAddressSpace: locAS, defaultGlobalAddressSpace: glbAS, capability: caps} - r.Unlock() - - return nil -} - -// 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{}) -} - -// 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) -} diff --git a/vendor/github.com/docker/libnetwork/endpoint.go b/vendor/github.com/docker/libnetwork/endpoint.go deleted file mode 100644 index d79bd33648..0000000000 --- a/vendor/github.com/docker/libnetwork/endpoint.go +++ /dev/null @@ -1,1232 +0,0 @@ -package libnetwork - -import ( - "encoding/json" - "fmt" - "net" - "strings" - "sync" - - "github.com/docker/libnetwork/datastore" - "github.com/docker/libnetwork/ipamapi" - "github.com/docker/libnetwork/netlabel" - "github.com/docker/libnetwork/options" - "github.com/docker/libnetwork/types" - "github.com/sirupsen/logrus" -) - -// Endpoint represents a logical connection between a network and a sandbox. -type Endpoint interface { - // A system generated id for this endpoint. - ID() string - - // Name returns the name of this endpoint. - Name() string - - // Network returns the name of the network to which this endpoint is attached. - Network() string - - // Join joins the sandbox to the endpoint and populates into the sandbox - // the network resources allocated for the endpoint. - Join(sandbox Sandbox, options ...EndpointOption) error - - // Leave detaches the network resources populated in the sandbox. - Leave(sandbox Sandbox, options ...EndpointOption) error - - // Return certain operational data belonging to this endpoint - Info() EndpointInfo - - // DriverInfo returns a collection of driver operational data related to this endpoint retrieved from the driver - DriverInfo() (map[string]interface{}, error) - - // Delete and detaches this endpoint from the network. - Delete(force bool) error -} - -// EndpointOption is an option setter function type used to pass various options to Network -// and Endpoint interfaces methods. The various setter functions of type EndpointOption are -// provided by libnetwork, they look like Option[...](...) -type EndpointOption func(ep *endpoint) - -type endpoint struct { - name string - id string - network *network - iface *endpointInterface - joinInfo *endpointJoinInfo - sandboxID string - locator string - exposedPorts []types.TransportPort - anonymous bool - disableResolution bool - generic map[string]interface{} - joinLeaveDone chan struct{} - prefAddress net.IP - prefAddressV6 net.IP - ipamOptions map[string]string - aliases map[string]string - myAliases []string - svcID string - svcName string - virtualIP net.IP - svcAliases []string - ingressPorts []*PortConfig - dbIndex uint64 - dbExists bool - serviceEnabled bool - loadBalancer bool - sync.Mutex -} - -func (ep *endpoint) MarshalJSON() ([]byte, error) { - ep.Lock() - defer ep.Unlock() - - epMap := make(map[string]interface{}) - epMap["name"] = ep.name - epMap["id"] = ep.id - epMap["ep_iface"] = ep.iface - epMap["joinInfo"] = ep.joinInfo - epMap["exposed_ports"] = ep.exposedPorts - if ep.generic != nil { - epMap["generic"] = ep.generic - } - epMap["sandbox"] = ep.sandboxID - epMap["locator"] = ep.locator - epMap["anonymous"] = ep.anonymous - epMap["disableResolution"] = ep.disableResolution - epMap["myAliases"] = ep.myAliases - epMap["svcName"] = ep.svcName - epMap["svcID"] = ep.svcID - epMap["virtualIP"] = ep.virtualIP.String() - epMap["ingressPorts"] = ep.ingressPorts - epMap["svcAliases"] = ep.svcAliases - epMap["loadBalancer"] = ep.loadBalancer - - return json.Marshal(epMap) -} - -func (ep *endpoint) UnmarshalJSON(b []byte) (err error) { - ep.Lock() - defer ep.Unlock() - - var epMap map[string]interface{} - if err := json.Unmarshal(b, &epMap); err != nil { - return err - } - ep.name = epMap["name"].(string) - ep.id = epMap["id"].(string) - - ib, _ := json.Marshal(epMap["ep_iface"]) - json.Unmarshal(ib, &ep.iface) - - jb, _ := json.Marshal(epMap["joinInfo"]) - json.Unmarshal(jb, &ep.joinInfo) - - tb, _ := json.Marshal(epMap["exposed_ports"]) - var tPorts []types.TransportPort - json.Unmarshal(tb, &tPorts) - ep.exposedPorts = tPorts - - cb, _ := json.Marshal(epMap["sandbox"]) - json.Unmarshal(cb, &ep.sandboxID) - - if v, ok := epMap["generic"]; ok { - ep.generic = v.(map[string]interface{}) - - if opt, ok := ep.generic[netlabel.PortMap]; ok { - pblist := []types.PortBinding{} - - for i := 0; i < len(opt.([]interface{})); i++ { - pb := types.PortBinding{} - tmp := opt.([]interface{})[i].(map[string]interface{}) - - bytes, err := json.Marshal(tmp) - if err != nil { - logrus.Error(err) - break - } - err = json.Unmarshal(bytes, &pb) - if err != nil { - logrus.Error(err) - break - } - pblist = append(pblist, pb) - } - ep.generic[netlabel.PortMap] = pblist - } - - if opt, ok := ep.generic[netlabel.ExposedPorts]; ok { - tplist := []types.TransportPort{} - - for i := 0; i < len(opt.([]interface{})); i++ { - tp := types.TransportPort{} - tmp := opt.([]interface{})[i].(map[string]interface{}) - - bytes, err := json.Marshal(tmp) - if err != nil { - logrus.Error(err) - break - } - err = json.Unmarshal(bytes, &tp) - if err != nil { - logrus.Error(err) - break - } - tplist = append(tplist, tp) - } - ep.generic[netlabel.ExposedPorts] = tplist - - } - } - - if v, ok := epMap["anonymous"]; ok { - ep.anonymous = v.(bool) - } - if v, ok := epMap["disableResolution"]; ok { - ep.disableResolution = v.(bool) - } - if l, ok := epMap["locator"]; ok { - ep.locator = l.(string) - } - - if sn, ok := epMap["svcName"]; ok { - ep.svcName = sn.(string) - } - - if si, ok := epMap["svcID"]; ok { - ep.svcID = si.(string) - } - - if vip, ok := epMap["virtualIP"]; ok { - ep.virtualIP = net.ParseIP(vip.(string)) - } - - if v, ok := epMap["loadBalancer"]; ok { - ep.loadBalancer = v.(bool) - } - - sal, _ := json.Marshal(epMap["svcAliases"]) - var svcAliases []string - json.Unmarshal(sal, &svcAliases) - ep.svcAliases = svcAliases - - pc, _ := json.Marshal(epMap["ingressPorts"]) - var ingressPorts []*PortConfig - json.Unmarshal(pc, &ingressPorts) - ep.ingressPorts = ingressPorts - - ma, _ := json.Marshal(epMap["myAliases"]) - var myAliases []string - json.Unmarshal(ma, &myAliases) - ep.myAliases = myAliases - return nil -} - -func (ep *endpoint) New() datastore.KVObject { - return &endpoint{network: ep.getNetwork()} -} - -func (ep *endpoint) CopyTo(o datastore.KVObject) error { - ep.Lock() - defer ep.Unlock() - - dstEp := o.(*endpoint) - dstEp.name = ep.name - dstEp.id = ep.id - dstEp.sandboxID = ep.sandboxID - dstEp.locator = ep.locator - dstEp.dbIndex = ep.dbIndex - dstEp.dbExists = ep.dbExists - dstEp.anonymous = ep.anonymous - dstEp.disableResolution = ep.disableResolution - dstEp.svcName = ep.svcName - dstEp.svcID = ep.svcID - dstEp.virtualIP = ep.virtualIP - dstEp.loadBalancer = ep.loadBalancer - - dstEp.svcAliases = make([]string, len(ep.svcAliases)) - copy(dstEp.svcAliases, ep.svcAliases) - - dstEp.ingressPorts = make([]*PortConfig, len(ep.ingressPorts)) - copy(dstEp.ingressPorts, ep.ingressPorts) - - if ep.iface != nil { - dstEp.iface = &endpointInterface{} - ep.iface.CopyTo(dstEp.iface) - } - - if ep.joinInfo != nil { - dstEp.joinInfo = &endpointJoinInfo{} - ep.joinInfo.CopyTo(dstEp.joinInfo) - } - - dstEp.exposedPorts = make([]types.TransportPort, len(ep.exposedPorts)) - copy(dstEp.exposedPorts, ep.exposedPorts) - - dstEp.myAliases = make([]string, len(ep.myAliases)) - copy(dstEp.myAliases, ep.myAliases) - - dstEp.generic = options.Generic{} - for k, v := range ep.generic { - dstEp.generic[k] = v - } - - return nil -} - -func (ep *endpoint) ID() string { - ep.Lock() - defer ep.Unlock() - - return ep.id -} - -func (ep *endpoint) Name() string { - ep.Lock() - defer ep.Unlock() - - return ep.name -} - -func (ep *endpoint) MyAliases() []string { - ep.Lock() - defer ep.Unlock() - - return ep.myAliases -} - -func (ep *endpoint) Network() string { - if ep.network == nil { - return "" - } - - return ep.network.name -} - -func (ep *endpoint) isAnonymous() bool { - ep.Lock() - defer ep.Unlock() - return ep.anonymous -} - -// isServiceEnabled check if service is enabled on the endpoint -func (ep *endpoint) isServiceEnabled() bool { - ep.Lock() - defer ep.Unlock() - return ep.serviceEnabled -} - -// enableService sets service enabled on the endpoint -func (ep *endpoint) enableService() { - ep.Lock() - defer ep.Unlock() - ep.serviceEnabled = true -} - -// disableService disables service on the endpoint -func (ep *endpoint) disableService() { - ep.Lock() - defer ep.Unlock() - ep.serviceEnabled = false -} - -func (ep *endpoint) needResolver() bool { - ep.Lock() - defer ep.Unlock() - return !ep.disableResolution -} - -// endpoint Key structure : endpoint/network-id/endpoint-id -func (ep *endpoint) Key() []string { - if ep.network == nil { - return nil - } - - return []string{datastore.EndpointKeyPrefix, ep.network.id, ep.id} -} - -func (ep *endpoint) KeyPrefix() []string { - if ep.network == nil { - return nil - } - - return []string{datastore.EndpointKeyPrefix, ep.network.id} -} - -func (ep *endpoint) networkIDFromKey(key string) (string, error) { - // endpoint Key structure : docker/libnetwork/endpoint/${network-id}/${endpoint-id} - // it's an invalid key if the key doesn't have all the 5 key elements above - keyElements := strings.Split(key, "/") - if !strings.HasPrefix(key, datastore.Key(datastore.EndpointKeyPrefix)) || len(keyElements) < 5 { - return "", fmt.Errorf("invalid endpoint key : %v", key) - } - // network-id is placed at index=3. pls refer to endpoint.Key() method - return strings.Split(key, "/")[3], nil -} - -func (ep *endpoint) Value() []byte { - b, err := json.Marshal(ep) - if err != nil { - return nil - } - return b -} - -func (ep *endpoint) SetValue(value []byte) error { - return json.Unmarshal(value, ep) -} - -func (ep *endpoint) Index() uint64 { - ep.Lock() - defer ep.Unlock() - return ep.dbIndex -} - -func (ep *endpoint) SetIndex(index uint64) { - ep.Lock() - defer ep.Unlock() - ep.dbIndex = index - ep.dbExists = true -} - -func (ep *endpoint) Exists() bool { - ep.Lock() - defer ep.Unlock() - return ep.dbExists -} - -func (ep *endpoint) Skip() bool { - return ep.getNetwork().Skip() -} - -func (ep *endpoint) processOptions(options ...EndpointOption) { - ep.Lock() - defer ep.Unlock() - - for _, opt := range options { - if opt != nil { - opt(ep) - } - } -} - -func (ep *endpoint) getNetwork() *network { - ep.Lock() - defer ep.Unlock() - - return ep.network -} - -func (ep *endpoint) getNetworkFromStore() (*network, error) { - if ep.network == nil { - return nil, fmt.Errorf("invalid network object in endpoint %s", ep.Name()) - } - - return ep.network.getController().getNetworkFromStore(ep.network.id) -} - -func (ep *endpoint) Join(sbox Sandbox, options ...EndpointOption) error { - if sbox == nil { - return types.BadRequestErrorf("endpoint cannot be joined by nil container") - } - - sb, ok := sbox.(*sandbox) - if !ok { - return types.BadRequestErrorf("not a valid Sandbox interface") - } - - sb.joinLeaveStart() - defer sb.joinLeaveEnd() - - return ep.sbJoin(sb, options...) -} - -func (ep *endpoint) sbJoin(sb *sandbox, options ...EndpointOption) (err error) { - n, err := ep.getNetworkFromStore() - if err != nil { - return fmt.Errorf("failed to get network from store during join: %v", err) - } - - ep, err = n.getEndpointFromStore(ep.ID()) - if err != nil { - return fmt.Errorf("failed to get endpoint from store during join: %v", err) - } - - ep.Lock() - if ep.sandboxID != "" { - ep.Unlock() - return types.ForbiddenErrorf("another container is attached to the same network endpoint") - } - ep.network = n - ep.sandboxID = sb.ID() - ep.joinInfo = &endpointJoinInfo{} - epid := ep.id - ep.Unlock() - defer func() { - if err != nil { - ep.Lock() - ep.sandboxID = "" - ep.Unlock() - } - }() - - nid := n.ID() - - ep.processOptions(options...) - - d, err := n.driver(true) - if err != nil { - return fmt.Errorf("failed to get driver during join: %v", err) - } - - err = d.Join(nid, epid, sb.Key(), ep, sb.Labels()) - if err != nil { - return err - } - defer func() { - if err != nil { - if e := d.Leave(nid, epid); e != nil { - logrus.Warnf("driver leave failed while rolling back join: %v", e) - } - } - }() - - // Watch for service records - if !n.getController().isAgent() { - n.getController().watchSvcRecord(ep) - } - - if doUpdateHostsFile(n, sb) { - var addresses []string - if ip := ep.getFirstInterfaceIPv4Address(); ip != nil { - addresses = append(addresses, ip.String()) - } - if ip := ep.getFirstInterfaceIPv6Address(); ip != nil { - addresses = append(addresses, ip.String()) - } - if err = sb.updateHostsFile(addresses); err != nil { - return err - } - } - if err = sb.updateDNS(n.enableIPv6); err != nil { - return err - } - - // Current endpoint providing external connectivity for the sandbox - extEp := sb.getGatewayEndpoint() - - sb.addEndpoint(ep) - defer func() { - if err != nil { - sb.removeEndpoint(ep) - } - }() - - if err = sb.populateNetworkResources(ep); err != nil { - return err - } - - if err = n.getController().updateToStore(ep); err != nil { - return err - } - - if err = ep.addDriverInfoToCluster(); err != nil { - return err - } - - defer func() { - if err != nil { - if e := ep.deleteDriverInfoFromCluster(); e != nil { - logrus.Errorf("Could not delete endpoint state for endpoint %s from cluster on join failure: %v", ep.Name(), e) - } - } - }() - - // Load balancing endpoints should never have a default gateway nor - // should they alter the status of a network's default gateway - if ep.loadBalancer && !sb.ingress { - return nil - } - - if sb.needDefaultGW() && sb.getEndpointInGWNetwork() == nil { - return sb.setupDefaultGW() - } - - moveExtConn := sb.getGatewayEndpoint() != extEp - - if moveExtConn { - if extEp != nil { - logrus.Debugf("Revoking external connectivity on endpoint %s (%s)", extEp.Name(), extEp.ID()) - extN, err := extEp.getNetworkFromStore() - if err != nil { - return fmt.Errorf("failed to get network from store for revoking external connectivity during join: %v", err) - } - extD, err := extN.driver(true) - if err != nil { - return fmt.Errorf("failed to get driver for revoking external connectivity during join: %v", err) - } - if err = extD.RevokeExternalConnectivity(extEp.network.ID(), extEp.ID()); err != nil { - return types.InternalErrorf( - "driver failed revoking external connectivity on endpoint %s (%s): %v", - extEp.Name(), extEp.ID(), err) - } - defer func() { - if err != nil { - if e := extD.ProgramExternalConnectivity(extEp.network.ID(), extEp.ID(), sb.Labels()); e != nil { - logrus.Warnf("Failed to roll-back external connectivity on endpoint %s (%s): %v", - extEp.Name(), extEp.ID(), e) - } - } - }() - } - if !n.internal { - logrus.Debugf("Programming external connectivity on endpoint %s (%s)", ep.Name(), ep.ID()) - if err = d.ProgramExternalConnectivity(n.ID(), ep.ID(), sb.Labels()); err != nil { - return types.InternalErrorf( - "driver failed programming external connectivity on endpoint %s (%s): %v", - ep.Name(), ep.ID(), err) - } - } - - } - - if !sb.needDefaultGW() { - if e := sb.clearDefaultGW(); e != nil { - logrus.Warnf("Failure while disconnecting sandbox %s (%s) from gateway network: %v", - sb.ID(), sb.ContainerID(), e) - } - } - - return nil -} - -func doUpdateHostsFile(n *network, sb *sandbox) bool { - return !n.ingress && n.Name() != libnGWNetwork -} - -func (ep *endpoint) rename(name string) error { - var ( - err error - netWatch *netWatch - ok bool - ) - - n := ep.getNetwork() - if n == nil { - return fmt.Errorf("network not connected for ep %q", ep.name) - } - - c := n.getController() - - sb, ok := ep.getSandbox() - if !ok { - logrus.Warnf("rename for %s aborted, sandbox %s is not anymore present", ep.ID(), ep.sandboxID) - return nil - } - - if c.isAgent() { - if err = ep.deleteServiceInfoFromCluster(sb, true, "rename"); err != nil { - return types.InternalErrorf("Could not delete service state for endpoint %s from cluster on rename: %v", ep.Name(), err) - } - } else { - c.Lock() - netWatch, ok = c.nmap[n.ID()] - c.Unlock() - if !ok { - return fmt.Errorf("watch null for network %q", n.Name()) - } - n.updateSvcRecord(ep, c.getLocalEps(netWatch), false) - } - - oldName := ep.name - oldAnonymous := ep.anonymous - ep.name = name - ep.anonymous = false - - if c.isAgent() { - if err = ep.addServiceInfoToCluster(sb); err != nil { - return types.InternalErrorf("Could not add service state for endpoint %s to cluster on rename: %v", ep.Name(), err) - } - defer func() { - if err != nil { - ep.deleteServiceInfoFromCluster(sb, true, "rename") - ep.name = oldName - ep.anonymous = oldAnonymous - ep.addServiceInfoToCluster(sb) - } - }() - } else { - n.updateSvcRecord(ep, c.getLocalEps(netWatch), true) - defer func() { - if err != nil { - n.updateSvcRecord(ep, c.getLocalEps(netWatch), false) - ep.name = oldName - ep.anonymous = oldAnonymous - n.updateSvcRecord(ep, c.getLocalEps(netWatch), true) - } - }() - } - - // Update the store with the updated name - if err = c.updateToStore(ep); err != nil { - return err - } - // After the name change do a dummy endpoint count update to - // trigger the service record update in the peer nodes - - // Ignore the error because updateStore fail for EpCnt is a - // benign error. Besides there is no meaningful recovery that - // we can do. When the cluster recovers subsequent EpCnt update - // will force the peers to get the correct EP name. - n.getEpCnt().updateStore() - - return err -} - -func (ep *endpoint) hasInterface(iName string) bool { - ep.Lock() - defer ep.Unlock() - - return ep.iface != nil && ep.iface.srcName == iName -} - -func (ep *endpoint) Leave(sbox Sandbox, options ...EndpointOption) error { - if sbox == nil || sbox.ID() == "" || sbox.Key() == "" { - return types.BadRequestErrorf("invalid Sandbox passed to endpoint leave: %v", sbox) - } - - sb, ok := sbox.(*sandbox) - if !ok { - return types.BadRequestErrorf("not a valid Sandbox interface") - } - - sb.joinLeaveStart() - defer sb.joinLeaveEnd() - - return ep.sbLeave(sb, false, options...) -} - -func (ep *endpoint) sbLeave(sb *sandbox, force bool, options ...EndpointOption) error { - n, err := ep.getNetworkFromStore() - if err != nil { - return fmt.Errorf("failed to get network from store during leave: %v", err) - } - - ep, err = n.getEndpointFromStore(ep.ID()) - if err != nil { - return fmt.Errorf("failed to get endpoint from store during leave: %v", err) - } - - ep.Lock() - sid := ep.sandboxID - ep.Unlock() - - if sid == "" { - return types.ForbiddenErrorf("cannot leave endpoint with no attached sandbox") - } - if sid != sb.ID() { - return types.ForbiddenErrorf("unexpected sandbox ID in leave request. Expected %s. Got %s", ep.sandboxID, sb.ID()) - } - - ep.processOptions(options...) - - d, err := n.driver(!force) - if err != nil { - return fmt.Errorf("failed to get driver during endpoint leave: %v", err) - } - - ep.Lock() - ep.sandboxID = "" - ep.network = n - ep.Unlock() - - // Current endpoint providing external connectivity to the sandbox - extEp := sb.getGatewayEndpoint() - moveExtConn := extEp != nil && (extEp.ID() == ep.ID()) - - if d != nil { - if moveExtConn { - logrus.Debugf("Revoking external connectivity on endpoint %s (%s)", ep.Name(), ep.ID()) - if err := d.RevokeExternalConnectivity(n.id, ep.id); err != nil { - logrus.Warnf("driver failed revoking external connectivity on endpoint %s (%s): %v", - ep.Name(), ep.ID(), err) - } - } - - if err := d.Leave(n.id, ep.id); err != nil { - if _, ok := err.(types.MaskableError); !ok { - logrus.Warnf("driver error disconnecting container %s : %v", ep.name, err) - } - } - } - - if err := ep.deleteServiceInfoFromCluster(sb, true, "sbLeave"); err != nil { - logrus.Warnf("Failed to clean up service info on container %s disconnect: %v", ep.name, err) - } - - if err := sb.clearNetworkResources(ep); err != nil { - logrus.Warnf("Failed to clean up network resources on container %s disconnect: %v", ep.name, err) - } - - // Update the store about the sandbox detach only after we - // have completed sb.clearNetworkresources above to avoid - // spurious logs when cleaning up the sandbox when the daemon - // ungracefully exits and restarts before completing sandbox - // detach but after store has been updated. - if err := n.getController().updateToStore(ep); err != nil { - return err - } - - if e := ep.deleteDriverInfoFromCluster(); e != nil { - logrus.Errorf("Failed to delete endpoint state for endpoint %s from cluster: %v", ep.Name(), e) - } - - sb.deleteHostsEntries(n.getSvcRecords(ep)) - if !sb.inDelete && sb.needDefaultGW() && sb.getEndpointInGWNetwork() == nil { - return sb.setupDefaultGW() - } - - // New endpoint providing external connectivity for the sandbox - extEp = sb.getGatewayEndpoint() - if moveExtConn && extEp != nil { - logrus.Debugf("Programming external connectivity on endpoint %s (%s)", extEp.Name(), extEp.ID()) - extN, err := extEp.getNetworkFromStore() - if err != nil { - return fmt.Errorf("failed to get network from store for programming external connectivity during leave: %v", err) - } - extD, err := extN.driver(true) - if err != nil { - return fmt.Errorf("failed to get driver for programming external connectivity during leave: %v", err) - } - if err := extD.ProgramExternalConnectivity(extEp.network.ID(), extEp.ID(), sb.Labels()); err != nil { - logrus.Warnf("driver failed programming external connectivity on endpoint %s: (%s) %v", - extEp.Name(), extEp.ID(), err) - } - } - - if !sb.needDefaultGW() { - if err := sb.clearDefaultGW(); err != nil { - logrus.Warnf("Failure while disconnecting sandbox %s (%s) from gateway network: %v", - sb.ID(), sb.ContainerID(), err) - } - } - - return nil -} - -func (ep *endpoint) Delete(force bool) error { - var err error - n, err := ep.getNetworkFromStore() - if err != nil { - return fmt.Errorf("failed to get network during Delete: %v", err) - } - - ep, err = n.getEndpointFromStore(ep.ID()) - if err != nil { - return fmt.Errorf("failed to get endpoint from store during Delete: %v", err) - } - - ep.Lock() - epid := ep.id - name := ep.name - sbid := ep.sandboxID - ep.Unlock() - - sb, _ := n.getController().SandboxByID(sbid) - if sb != nil && !force { - return &ActiveContainerError{name: name, id: epid} - } - - if sb != nil { - if e := ep.sbLeave(sb.(*sandbox), force); e != nil { - logrus.Warnf("failed to leave sandbox for endpoint %s : %v", name, e) - } - } - - if err = n.getController().deleteFromStore(ep); err != nil { - return err - } - - defer func() { - if err != nil && !force { - ep.dbExists = false - if e := n.getController().updateToStore(ep); e != nil { - logrus.Warnf("failed to recreate endpoint in store %s : %v", name, e) - } - } - }() - - // unwatch for service records - n.getController().unWatchSvcRecord(ep) - - if err = ep.deleteEndpoint(force); err != nil && !force { - return err - } - - ep.releaseAddress() - - if err := n.getEpCnt().DecEndpointCnt(); err != nil { - logrus.Warnf("failed to decrement endpoint count for ep %s: %v", ep.ID(), err) - } - - return nil -} - -func (ep *endpoint) deleteEndpoint(force bool) error { - ep.Lock() - n := ep.network - name := ep.name - epid := ep.id - ep.Unlock() - - driver, err := n.driver(!force) - if err != nil { - return fmt.Errorf("failed to delete endpoint: %v", err) - } - - if driver == nil { - return nil - } - - if err := driver.DeleteEndpoint(n.id, epid); err != nil { - if _, ok := err.(types.ForbiddenError); ok { - return err - } - - if _, ok := err.(types.MaskableError); !ok { - logrus.Warnf("driver error deleting endpoint %s : %v", name, err) - } - } - - return nil -} - -func (ep *endpoint) getSandbox() (*sandbox, bool) { - c := ep.network.getController() - ep.Lock() - sid := ep.sandboxID - ep.Unlock() - - c.Lock() - ps, ok := c.sandboxes[sid] - c.Unlock() - - return ps, ok -} - -func (ep *endpoint) getFirstInterfaceIPv4Address() net.IP { - ep.Lock() - defer ep.Unlock() - - if ep.iface.addr != nil { - return ep.iface.addr.IP - } - - return nil -} - -func (ep *endpoint) getFirstInterfaceIPv6Address() net.IP { - ep.Lock() - defer ep.Unlock() - - if ep.iface.addrv6 != nil { - return ep.iface.addrv6.IP - } - - return nil -} - -// EndpointOptionGeneric function returns an option setter for a Generic option defined -// in a Dictionary of Key-Value pair -func EndpointOptionGeneric(generic map[string]interface{}) EndpointOption { - return func(ep *endpoint) { - for k, v := range generic { - ep.generic[k] = v - } - } -} - -var ( - linkLocalMask = net.CIDRMask(16, 32) - linkLocalMaskIPv6 = net.CIDRMask(64, 128) -) - -// CreateOptionIpam function returns an option setter for the ipam configuration for this endpoint -func CreateOptionIpam(ipV4, ipV6 net.IP, llIPs []net.IP, ipamOptions map[string]string) EndpointOption { - return func(ep *endpoint) { - ep.prefAddress = ipV4 - ep.prefAddressV6 = ipV6 - if len(llIPs) != 0 { - for _, ip := range llIPs { - nw := &net.IPNet{IP: ip, Mask: linkLocalMask} - if ip.To4() == nil { - nw.Mask = linkLocalMaskIPv6 - } - ep.iface.llAddrs = append(ep.iface.llAddrs, nw) - } - } - ep.ipamOptions = ipamOptions - } -} - -// CreateOptionExposedPorts function returns an option setter for the container exposed -// ports option to be passed to network.CreateEndpoint() method. -func CreateOptionExposedPorts(exposedPorts []types.TransportPort) EndpointOption { - return func(ep *endpoint) { - // Defensive copy - eps := make([]types.TransportPort, len(exposedPorts)) - copy(eps, exposedPorts) - // Store endpoint label and in generic because driver needs it - ep.exposedPorts = eps - ep.generic[netlabel.ExposedPorts] = eps - } -} - -// CreateOptionPortMapping function returns an option setter for the mapping -// ports option to be passed to network.CreateEndpoint() method. -func CreateOptionPortMapping(portBindings []types.PortBinding) EndpointOption { - return func(ep *endpoint) { - // Store a copy of the bindings as generic data to pass to the driver - pbs := make([]types.PortBinding, len(portBindings)) - copy(pbs, portBindings) - ep.generic[netlabel.PortMap] = pbs - } -} - -// CreateOptionDNS function returns an option setter for dns entry option to -// be passed to container Create method. -func CreateOptionDNS(dns []string) EndpointOption { - return func(ep *endpoint) { - ep.generic[netlabel.DNSServers] = dns - } -} - -// CreateOptionAnonymous function returns an option setter for setting -// this endpoint as anonymous -func CreateOptionAnonymous() EndpointOption { - return func(ep *endpoint) { - ep.anonymous = true - } -} - -// CreateOptionDisableResolution function returns an option setter to indicate -// this endpoint doesn't want embedded DNS server functionality -func CreateOptionDisableResolution() EndpointOption { - return func(ep *endpoint) { - ep.disableResolution = true - } -} - -// CreateOptionAlias function returns an option setter for setting endpoint alias -func CreateOptionAlias(name string, alias string) EndpointOption { - return func(ep *endpoint) { - if ep.aliases == nil { - ep.aliases = make(map[string]string) - } - ep.aliases[alias] = name - } -} - -// CreateOptionService function returns an option setter for setting service binding configuration -func CreateOptionService(name, id string, vip net.IP, ingressPorts []*PortConfig, aliases []string) EndpointOption { - return func(ep *endpoint) { - ep.svcName = name - ep.svcID = id - ep.virtualIP = vip - ep.ingressPorts = ingressPorts - ep.svcAliases = aliases - } -} - -// CreateOptionMyAlias function returns an option setter for setting endpoint's self alias -func CreateOptionMyAlias(alias string) EndpointOption { - return func(ep *endpoint) { - ep.myAliases = append(ep.myAliases, alias) - } -} - -// CreateOptionLoadBalancer function returns an option setter for denoting the endpoint is a load balancer for a network -func CreateOptionLoadBalancer() EndpointOption { - return func(ep *endpoint) { - ep.loadBalancer = true - } -} - -// JoinOptionPriority function returns an option setter for priority option to -// be passed to the endpoint.Join() method. -func JoinOptionPriority(prio int) EndpointOption { - return func(ep *endpoint) { - // ep lock already acquired - c := ep.network.getController() - c.Lock() - sb, ok := c.sandboxes[ep.sandboxID] - c.Unlock() - if !ok { - logrus.Errorf("Could not set endpoint priority value during Join to endpoint %s: No sandbox id present in endpoint", ep.id) - return - } - sb.epPriority[ep.id] = prio - } -} - -func (ep *endpoint) DataScope() string { - return ep.getNetwork().DataScope() -} - -func (ep *endpoint) assignAddress(ipam ipamapi.Ipam, assignIPv4, assignIPv6 bool) error { - var err error - - n := ep.getNetwork() - if n.hasSpecialDriver() { - return nil - } - - logrus.Debugf("Assigning addresses for endpoint %s's interface on network %s", ep.Name(), n.Name()) - - if assignIPv4 { - if err = ep.assignAddressVersion(4, ipam); err != nil { - return err - } - } - - if assignIPv6 { - err = ep.assignAddressVersion(6, ipam) - } - - return err -} - -func (ep *endpoint) assignAddressVersion(ipVer int, ipam ipamapi.Ipam) error { - var ( - poolID *string - address **net.IPNet - prefAdd net.IP - progAdd net.IP - ) - - n := ep.getNetwork() - switch ipVer { - case 4: - poolID = &ep.iface.v4PoolID - address = &ep.iface.addr - prefAdd = ep.prefAddress - case 6: - poolID = &ep.iface.v6PoolID - address = &ep.iface.addrv6 - prefAdd = ep.prefAddressV6 - default: - return types.InternalErrorf("incorrect ip version number passed: %d", ipVer) - } - - ipInfo := n.getIPInfo(ipVer) - - // ipv6 address is not mandatory - if len(ipInfo) == 0 && ipVer == 6 { - return nil - } - - // The address to program may be chosen by the user or by the network driver in one specific - // case to support backward compatibility with `docker daemon --fixed-cidrv6` use case - if prefAdd != nil { - progAdd = prefAdd - } else if *address != nil { - progAdd = (*address).IP - } - - for _, d := range ipInfo { - if progAdd != nil && !d.Pool.Contains(progAdd) { - continue - } - addr, _, err := ipam.RequestAddress(d.PoolID, progAdd, ep.ipamOptions) - if err == nil { - ep.Lock() - *address = addr - *poolID = d.PoolID - ep.Unlock() - return nil - } - if err != ipamapi.ErrNoAvailableIPs || progAdd != nil { - return err - } - } - if progAdd != nil { - return types.BadRequestErrorf("Invalid address %s: It does not belong to any of this network's subnets", prefAdd) - } - return fmt.Errorf("no available IPv%d addresses on this network's address pools: %s (%s)", ipVer, n.Name(), n.ID()) -} - -func (ep *endpoint) releaseAddress() { - n := ep.getNetwork() - if n.hasSpecialDriver() { - return - } - - logrus.Debugf("Releasing addresses for endpoint %s's interface on network %s", ep.Name(), n.Name()) - - ipam, _, err := n.getController().getIPAMDriver(n.ipamType) - if err != nil { - logrus.Warnf("Failed to retrieve ipam driver to release interface address on delete of endpoint %s (%s): %v", ep.Name(), ep.ID(), err) - return - } - - if ep.iface.addr != nil { - if err := ipam.ReleaseAddress(ep.iface.v4PoolID, ep.iface.addr.IP); err != nil { - logrus.Warnf("Failed to release ip address %s on delete of endpoint %s (%s): %v", ep.iface.addr.IP, ep.Name(), ep.ID(), err) - } - } - - if ep.iface.addrv6 != nil && ep.iface.addrv6.IP.IsGlobalUnicast() { - if err := ipam.ReleaseAddress(ep.iface.v6PoolID, ep.iface.addrv6.IP); err != nil { - logrus.Warnf("Failed to release ip address %s on delete of endpoint %s (%s): %v", ep.iface.addrv6.IP, ep.Name(), ep.ID(), err) - } - } -} - -func (c *controller) cleanupLocalEndpoints() { - // Get used endpoints - eps := make(map[string]interface{}) - for _, sb := range c.sandboxes { - for _, ep := range sb.endpoints { - eps[ep.id] = true - } - } - nl, err := c.getNetworksForScope(datastore.LocalScope) - if err != nil { - logrus.Warnf("Could not get list of networks during endpoint cleanup: %v", err) - return - } - - for _, n := range nl { - if n.ConfigOnly() { - continue - } - epl, err := n.getEndpointsFromStore() - if err != nil { - logrus.Warnf("Could not get list of endpoints in network %s during endpoint cleanup: %v", n.name, err) - continue - } - - for _, ep := range epl { - if _, ok := eps[ep.id]; ok { - continue - } - logrus.Infof("Removing stale endpoint %s (%s)", ep.name, ep.id) - if err := ep.Delete(true); err != nil { - logrus.Warnf("Could not delete local endpoint %s during endpoint cleanup: %v", ep.name, err) - } - } - - epl, err = n.getEndpointsFromStore() - if err != nil { - logrus.Warnf("Could not get list of endpoints in network %s for count update: %v", n.name, err) - continue - } - - epCnt := n.getEpCnt().EndpointCnt() - if epCnt != uint64(len(epl)) { - logrus.Infof("Fixing inconsistent endpoint_cnt for network %s. Expected=%d, Actual=%d", n.name, len(epl), epCnt) - n.getEpCnt().setCnt(uint64(len(epl))) - } - } -} diff --git a/vendor/github.com/docker/libnetwork/endpoint_cnt.go b/vendor/github.com/docker/libnetwork/endpoint_cnt.go deleted file mode 100644 index 7b7527426d..0000000000 --- a/vendor/github.com/docker/libnetwork/endpoint_cnt.go +++ /dev/null @@ -1,182 +0,0 @@ -package libnetwork - -import ( - "encoding/json" - "fmt" - "sync" - - "github.com/docker/libnetwork/datastore" -) - -type endpointCnt struct { - n *network - Count uint64 - dbIndex uint64 - dbExists bool - sync.Mutex -} - -const epCntKeyPrefix = "endpoint_count" - -func (ec *endpointCnt) Key() []string { - ec.Lock() - defer ec.Unlock() - - return []string{epCntKeyPrefix, ec.n.id} -} - -func (ec *endpointCnt) KeyPrefix() []string { - ec.Lock() - defer ec.Unlock() - - return []string{epCntKeyPrefix, ec.n.id} -} - -func (ec *endpointCnt) Value() []byte { - ec.Lock() - defer ec.Unlock() - - b, err := json.Marshal(ec) - if err != nil { - return nil - } - return b -} - -func (ec *endpointCnt) SetValue(value []byte) error { - ec.Lock() - defer ec.Unlock() - - return json.Unmarshal(value, &ec) -} - -func (ec *endpointCnt) Index() uint64 { - ec.Lock() - defer ec.Unlock() - return ec.dbIndex -} - -func (ec *endpointCnt) SetIndex(index uint64) { - ec.Lock() - ec.dbIndex = index - ec.dbExists = true - ec.Unlock() -} - -func (ec *endpointCnt) Exists() bool { - ec.Lock() - defer ec.Unlock() - return ec.dbExists -} - -func (ec *endpointCnt) Skip() bool { - ec.Lock() - defer ec.Unlock() - return !ec.n.persist -} - -func (ec *endpointCnt) New() datastore.KVObject { - ec.Lock() - defer ec.Unlock() - - return &endpointCnt{ - n: ec.n, - } -} - -func (ec *endpointCnt) CopyTo(o datastore.KVObject) error { - ec.Lock() - defer ec.Unlock() - - dstEc := o.(*endpointCnt) - dstEc.n = ec.n - dstEc.Count = ec.Count - dstEc.dbExists = ec.dbExists - dstEc.dbIndex = ec.dbIndex - - return nil -} - -func (ec *endpointCnt) DataScope() string { - return ec.n.DataScope() -} - -func (ec *endpointCnt) EndpointCnt() uint64 { - ec.Lock() - defer ec.Unlock() - - return ec.Count -} - -func (ec *endpointCnt) updateStore() error { - store := ec.n.getController().getStore(ec.DataScope()) - if store == nil { - return fmt.Errorf("store not found for scope %s on endpoint count update", ec.DataScope()) - } - // make a copy of count and n to avoid being overwritten by store.GetObject - count := ec.EndpointCnt() - n := ec.n - for { - if err := ec.n.getController().updateToStore(ec); err == nil || err != datastore.ErrKeyModified { - return err - } - if err := store.GetObject(datastore.Key(ec.Key()...), ec); err != nil { - return fmt.Errorf("could not update the kvobject to latest on endpoint count update: %v", err) - } - ec.Lock() - ec.Count = count - ec.n = n - ec.Unlock() - } -} - -func (ec *endpointCnt) setCnt(cnt uint64) error { - ec.Lock() - ec.Count = cnt - ec.Unlock() - return ec.updateStore() -} - -func (ec *endpointCnt) atomicIncDecEpCnt(inc bool) error { - store := ec.n.getController().getStore(ec.DataScope()) - if store == nil { - return fmt.Errorf("store not found for scope %s", ec.DataScope()) - } - - tmp := &endpointCnt{n: ec.n} - if err := store.GetObject(datastore.Key(ec.Key()...), tmp); err != nil { - return err - } -retry: - ec.Lock() - if inc { - ec.Count++ - } else { - if ec.Count > 0 { - ec.Count-- - } - } - ec.Unlock() - - if err := ec.n.getController().updateToStore(ec); err != nil { - if err == datastore.ErrKeyModified { - if err := store.GetObject(datastore.Key(ec.Key()...), ec); err != nil { - return fmt.Errorf("could not update the kvobject to latest when trying to atomic add endpoint count: %v", err) - } - - goto retry - } - - return err - } - - return nil -} - -func (ec *endpointCnt) IncEndpointCnt() error { - return ec.atomicIncDecEpCnt(true) -} - -func (ec *endpointCnt) DecEndpointCnt() error { - return ec.atomicIncDecEpCnt(false) -} diff --git a/vendor/github.com/docker/libnetwork/endpoint_info.go b/vendor/github.com/docker/libnetwork/endpoint_info.go deleted file mode 100644 index 80b662defa..0000000000 --- a/vendor/github.com/docker/libnetwork/endpoint_info.go +++ /dev/null @@ -1,459 +0,0 @@ -package libnetwork - -import ( - "encoding/json" - "fmt" - "net" - - "github.com/docker/libnetwork/driverapi" - "github.com/docker/libnetwork/types" -) - -// EndpointInfo provides an interface to retrieve network resources bound to the endpoint. -type EndpointInfo interface { - // Iface returns InterfaceInfo, go interface that can be used - // to get more information on the interface which was assigned to - // the endpoint by the driver. This can be used after the - // endpoint has been created. - Iface() InterfaceInfo - - // Gateway returns the IPv4 gateway assigned by the driver. - // This will only return a valid value if a container has joined the endpoint. - Gateway() net.IP - - // GatewayIPv6 returns the IPv6 gateway assigned by the driver. - // This will only return a valid value if a container has joined the endpoint. - GatewayIPv6() net.IP - - // StaticRoutes returns the list of static routes configured by the network - // driver when the container joins a network - StaticRoutes() []*types.StaticRoute - - // Sandbox returns the attached sandbox if there, nil otherwise. - Sandbox() Sandbox - - // LoadBalancer returns whether the endpoint is the load balancer endpoint for the network. - LoadBalancer() bool -} - -// InterfaceInfo provides an interface to retrieve interface addresses bound to the endpoint. -type InterfaceInfo interface { - // MacAddress returns the MAC address assigned to the endpoint. - MacAddress() net.HardwareAddr - - // Address returns the IPv4 address assigned to the endpoint. - Address() *net.IPNet - - // AddressIPv6 returns the IPv6 address assigned to the endpoint. - AddressIPv6() *net.IPNet - - // LinkLocalAddresses returns the list of link-local (IPv4/IPv6) addresses assigned to the endpoint. - LinkLocalAddresses() []*net.IPNet - - // SrcName returns the name of the interface w/in the container - SrcName() string -} - -type endpointInterface struct { - mac net.HardwareAddr - addr *net.IPNet - addrv6 *net.IPNet - llAddrs []*net.IPNet - srcName string - dstPrefix string - routes []*net.IPNet - v4PoolID string - v6PoolID string -} - -func (epi *endpointInterface) MarshalJSON() ([]byte, error) { - epMap := make(map[string]interface{}) - if epi.mac != nil { - epMap["mac"] = epi.mac.String() - } - if epi.addr != nil { - epMap["addr"] = epi.addr.String() - } - if epi.addrv6 != nil { - epMap["addrv6"] = epi.addrv6.String() - } - if len(epi.llAddrs) != 0 { - list := make([]string, 0, len(epi.llAddrs)) - for _, ll := range epi.llAddrs { - list = append(list, ll.String()) - } - epMap["llAddrs"] = list - } - epMap["srcName"] = epi.srcName - epMap["dstPrefix"] = epi.dstPrefix - var routes []string - for _, route := range epi.routes { - routes = append(routes, route.String()) - } - epMap["routes"] = routes - epMap["v4PoolID"] = epi.v4PoolID - epMap["v6PoolID"] = epi.v6PoolID - return json.Marshal(epMap) -} - -func (epi *endpointInterface) UnmarshalJSON(b []byte) error { - var ( - err error - epMap map[string]interface{} - ) - if err = json.Unmarshal(b, &epMap); err != nil { - return err - } - if v, ok := epMap["mac"]; ok { - if epi.mac, err = net.ParseMAC(v.(string)); err != nil { - return types.InternalErrorf("failed to decode endpoint interface mac address after json unmarshal: %s", v.(string)) - } - } - if v, ok := epMap["addr"]; ok { - if epi.addr, err = types.ParseCIDR(v.(string)); err != nil { - return types.InternalErrorf("failed to decode endpoint interface ipv4 address after json unmarshal: %v", err) - } - } - if v, ok := epMap["addrv6"]; ok { - if epi.addrv6, err = types.ParseCIDR(v.(string)); err != nil { - return types.InternalErrorf("failed to decode endpoint interface ipv6 address after json unmarshal: %v", err) - } - } - if v, ok := epMap["llAddrs"]; ok { - list := v.([]interface{}) - epi.llAddrs = make([]*net.IPNet, 0, len(list)) - for _, llS := range list { - ll, err := types.ParseCIDR(llS.(string)) - if err != nil { - return types.InternalErrorf("failed to decode endpoint interface link-local address (%v) after json unmarshal: %v", llS, err) - } - epi.llAddrs = append(epi.llAddrs, ll) - } - } - epi.srcName = epMap["srcName"].(string) - epi.dstPrefix = epMap["dstPrefix"].(string) - - rb, _ := json.Marshal(epMap["routes"]) - var routes []string - json.Unmarshal(rb, &routes) - epi.routes = make([]*net.IPNet, 0) - for _, route := range routes { - ip, ipr, err := net.ParseCIDR(route) - if err == nil { - ipr.IP = ip - epi.routes = append(epi.routes, ipr) - } - } - epi.v4PoolID = epMap["v4PoolID"].(string) - epi.v6PoolID = epMap["v6PoolID"].(string) - - return nil -} - -func (epi *endpointInterface) CopyTo(dstEpi *endpointInterface) error { - dstEpi.mac = types.GetMacCopy(epi.mac) - dstEpi.addr = types.GetIPNetCopy(epi.addr) - dstEpi.addrv6 = types.GetIPNetCopy(epi.addrv6) - dstEpi.srcName = epi.srcName - dstEpi.dstPrefix = epi.dstPrefix - dstEpi.v4PoolID = epi.v4PoolID - dstEpi.v6PoolID = epi.v6PoolID - if len(epi.llAddrs) != 0 { - dstEpi.llAddrs = make([]*net.IPNet, 0, len(epi.llAddrs)) - dstEpi.llAddrs = append(dstEpi.llAddrs, epi.llAddrs...) - } - - for _, route := range epi.routes { - dstEpi.routes = append(dstEpi.routes, types.GetIPNetCopy(route)) - } - - return nil -} - -type endpointJoinInfo struct { - gw net.IP - gw6 net.IP - StaticRoutes []*types.StaticRoute - driverTableEntries []*tableEntry - disableGatewayService bool -} - -type tableEntry struct { - tableName string - key string - value []byte -} - -func (ep *endpoint) Info() EndpointInfo { - if ep.sandboxID != "" { - return ep - } - n, err := ep.getNetworkFromStore() - if err != nil { - return nil - } - - ep, err = n.getEndpointFromStore(ep.ID()) - if err != nil { - return nil - } - - sb, ok := ep.getSandbox() - if !ok { - // endpoint hasn't joined any sandbox. - // Just return the endpoint - return ep - } - - return sb.getEndpoint(ep.ID()) -} - -func (ep *endpoint) Iface() InterfaceInfo { - ep.Lock() - defer ep.Unlock() - - if ep.iface != nil { - return ep.iface - } - - return nil -} - -func (ep *endpoint) Interface() driverapi.InterfaceInfo { - ep.Lock() - defer ep.Unlock() - - if ep.iface != nil { - return ep.iface - } - - return nil -} - -func (epi *endpointInterface) SetMacAddress(mac net.HardwareAddr) error { - if epi.mac != nil { - return types.ForbiddenErrorf("endpoint interface MAC address present (%s). Cannot be modified with %s.", epi.mac, mac) - } - if mac == nil { - return types.BadRequestErrorf("tried to set nil MAC address to endpoint interface") - } - epi.mac = types.GetMacCopy(mac) - return nil -} - -func (epi *endpointInterface) SetIPAddress(address *net.IPNet) error { - if address.IP == nil { - return types.BadRequestErrorf("tried to set nil IP address to endpoint interface") - } - if address.IP.To4() == nil { - return setAddress(&epi.addrv6, address) - } - return setAddress(&epi.addr, address) -} - -func setAddress(ifaceAddr **net.IPNet, address *net.IPNet) error { - if *ifaceAddr != nil { - return types.ForbiddenErrorf("endpoint interface IP present (%s). Cannot be modified with (%s).", *ifaceAddr, address) - } - *ifaceAddr = types.GetIPNetCopy(address) - return nil -} - -func (epi *endpointInterface) MacAddress() net.HardwareAddr { - return types.GetMacCopy(epi.mac) -} - -func (epi *endpointInterface) Address() *net.IPNet { - return types.GetIPNetCopy(epi.addr) -} - -func (epi *endpointInterface) AddressIPv6() *net.IPNet { - return types.GetIPNetCopy(epi.addrv6) -} - -func (epi *endpointInterface) LinkLocalAddresses() []*net.IPNet { - return epi.llAddrs -} - -func (epi *endpointInterface) SrcName() string { - return epi.srcName -} - -func (epi *endpointInterface) SetNames(srcName string, dstPrefix string) error { - epi.srcName = srcName - epi.dstPrefix = dstPrefix - return nil -} - -func (ep *endpoint) InterfaceName() driverapi.InterfaceNameInfo { - ep.Lock() - defer ep.Unlock() - - if ep.iface != nil { - return ep.iface - } - - return nil -} - -func (ep *endpoint) AddStaticRoute(destination *net.IPNet, routeType int, nextHop net.IP) error { - ep.Lock() - defer ep.Unlock() - - r := types.StaticRoute{Destination: destination, RouteType: routeType, NextHop: nextHop} - - if routeType == types.NEXTHOP { - // If the route specifies a next-hop, then it's loosely routed (i.e. not bound to a particular interface). - ep.joinInfo.StaticRoutes = append(ep.joinInfo.StaticRoutes, &r) - } else { - // If the route doesn't specify a next-hop, it must be a connected route, bound to an interface. - ep.iface.routes = append(ep.iface.routes, r.Destination) - } - return nil -} - -func (ep *endpoint) AddTableEntry(tableName, key string, value []byte) error { - ep.Lock() - defer ep.Unlock() - - ep.joinInfo.driverTableEntries = append(ep.joinInfo.driverTableEntries, &tableEntry{ - tableName: tableName, - key: key, - value: value, - }) - - return nil -} - -func (ep *endpoint) Sandbox() Sandbox { - cnt, ok := ep.getSandbox() - if !ok { - return nil - } - return cnt -} - -func (ep *endpoint) LoadBalancer() bool { - ep.Lock() - defer ep.Unlock() - return ep.loadBalancer -} - -func (ep *endpoint) StaticRoutes() []*types.StaticRoute { - ep.Lock() - defer ep.Unlock() - - if ep.joinInfo == nil { - return nil - } - - return ep.joinInfo.StaticRoutes -} - -func (ep *endpoint) Gateway() net.IP { - ep.Lock() - defer ep.Unlock() - - if ep.joinInfo == nil { - return net.IP{} - } - - return types.GetIPCopy(ep.joinInfo.gw) -} - -func (ep *endpoint) GatewayIPv6() net.IP { - ep.Lock() - defer ep.Unlock() - - if ep.joinInfo == nil { - return net.IP{} - } - - return types.GetIPCopy(ep.joinInfo.gw6) -} - -func (ep *endpoint) SetGateway(gw net.IP) error { - ep.Lock() - defer ep.Unlock() - - ep.joinInfo.gw = types.GetIPCopy(gw) - return nil -} - -func (ep *endpoint) SetGatewayIPv6(gw6 net.IP) error { - ep.Lock() - defer ep.Unlock() - - ep.joinInfo.gw6 = types.GetIPCopy(gw6) - return nil -} - -func (ep *endpoint) retrieveFromStore() (*endpoint, error) { - n, err := ep.getNetworkFromStore() - if err != nil { - return nil, fmt.Errorf("could not find network in store to get latest endpoint %s: %v", ep.Name(), err) - } - return n.getEndpointFromStore(ep.ID()) -} - -func (ep *endpoint) DisableGatewayService() { - ep.Lock() - defer ep.Unlock() - - ep.joinInfo.disableGatewayService = true -} - -func (epj *endpointJoinInfo) MarshalJSON() ([]byte, error) { - epMap := make(map[string]interface{}) - if epj.gw != nil { - epMap["gw"] = epj.gw.String() - } - if epj.gw6 != nil { - epMap["gw6"] = epj.gw6.String() - } - epMap["disableGatewayService"] = epj.disableGatewayService - epMap["StaticRoutes"] = epj.StaticRoutes - return json.Marshal(epMap) -} - -func (epj *endpointJoinInfo) UnmarshalJSON(b []byte) error { - var ( - err error - epMap map[string]interface{} - ) - if err = json.Unmarshal(b, &epMap); err != nil { - return err - } - if v, ok := epMap["gw"]; ok { - epj.gw = net.ParseIP(v.(string)) - } - if v, ok := epMap["gw6"]; ok { - epj.gw6 = net.ParseIP(v.(string)) - } - epj.disableGatewayService = epMap["disableGatewayService"].(bool) - - var tStaticRoute []types.StaticRoute - if v, ok := epMap["StaticRoutes"]; ok { - tb, _ := json.Marshal(v) - var tStaticRoute []types.StaticRoute - json.Unmarshal(tb, &tStaticRoute) - } - var StaticRoutes []*types.StaticRoute - for _, r := range tStaticRoute { - StaticRoutes = append(StaticRoutes, &r) - } - epj.StaticRoutes = StaticRoutes - - return nil -} - -func (epj *endpointJoinInfo) CopyTo(dstEpj *endpointJoinInfo) error { - dstEpj.disableGatewayService = epj.disableGatewayService - dstEpj.StaticRoutes = make([]*types.StaticRoute, len(epj.StaticRoutes)) - copy(dstEpj.StaticRoutes, epj.StaticRoutes) - dstEpj.driverTableEntries = make([]*tableEntry, len(epj.driverTableEntries)) - copy(dstEpj.driverTableEntries, epj.driverTableEntries) - dstEpj.gw = types.GetIPCopy(epj.gw) - dstEpj.gw6 = types.GetIPCopy(epj.gw6) - return nil -} diff --git a/vendor/github.com/docker/libnetwork/endpoint_info_unix.go b/vendor/github.com/docker/libnetwork/endpoint_info_unix.go deleted file mode 100644 index f2534f4904..0000000000 --- a/vendor/github.com/docker/libnetwork/endpoint_info_unix.go +++ /dev/null @@ -1,30 +0,0 @@ -// +build !windows - -package libnetwork - -import "fmt" - -func (ep *endpoint) DriverInfo() (map[string]interface{}, error) { - ep, err := ep.retrieveFromStore() - if err != nil { - return nil, err - } - - if sb, ok := ep.getSandbox(); ok { - if gwep := sb.getEndpointInGWNetwork(); gwep != nil && gwep.ID() != ep.ID() { - return gwep.DriverInfo() - } - } - - n, err := ep.getNetworkFromStore() - if err != nil { - return nil, fmt.Errorf("could not find network in store for driver info: %v", err) - } - - driver, err := n.driver(true) - if err != nil { - return nil, fmt.Errorf("failed to get driver info: %v", err) - } - - return driver.EndpointOperInfo(n.ID(), ep.ID()) -} diff --git a/vendor/github.com/docker/libnetwork/endpoint_info_windows.go b/vendor/github.com/docker/libnetwork/endpoint_info_windows.go deleted file mode 100644 index 93ad8330e9..0000000000 --- a/vendor/github.com/docker/libnetwork/endpoint_info_windows.go +++ /dev/null @@ -1,45 +0,0 @@ -// +build windows - -package libnetwork - -import "fmt" - -func (ep *endpoint) DriverInfo() (map[string]interface{}, error) { - ep, err := ep.retrieveFromStore() - if err != nil { - return nil, err - } - - var gwDriverInfo map[string]interface{} - if sb, ok := ep.getSandbox(); ok { - if gwep := sb.getEndpointInGWNetwork(); gwep != nil && gwep.ID() != ep.ID() { - - gwDriverInfo, err = gwep.DriverInfo() - if err != nil { - return nil, err - } - } - } - - n, err := ep.getNetworkFromStore() - if err != nil { - return nil, fmt.Errorf("could not find network in store for driver info: %v", err) - } - - driver, err := n.driver(true) - if err != nil { - return nil, fmt.Errorf("failed to get driver info: %v", err) - } - - epInfo, err := driver.EndpointOperInfo(n.ID(), ep.ID()) - if err != nil { - return nil, err - } - - if epInfo != nil { - epInfo["GW_INFO"] = gwDriverInfo - return epInfo, nil - } - - return gwDriverInfo, nil -} diff --git a/vendor/github.com/docker/libnetwork/error.go b/vendor/github.com/docker/libnetwork/error.go deleted file mode 100644 index 5f00709ff9..0000000000 --- a/vendor/github.com/docker/libnetwork/error.go +++ /dev/null @@ -1,193 +0,0 @@ -package libnetwork - -import ( - "fmt" -) - -// ErrNoSuchNetwork is returned when a network query finds no result -type ErrNoSuchNetwork string - -func (nsn ErrNoSuchNetwork) Error() string { - return fmt.Sprintf("network %s not found", string(nsn)) -} - -// NotFound denotes the type of this error -func (nsn ErrNoSuchNetwork) NotFound() {} - -// ErrNoSuchEndpoint is returned when an endpoint query finds no result -type ErrNoSuchEndpoint string - -func (nse ErrNoSuchEndpoint) Error() string { - return fmt.Sprintf("endpoint %s not found", string(nse)) -} - -// NotFound denotes the type of this error -func (nse ErrNoSuchEndpoint) NotFound() {} - -// ErrInvalidNetworkDriver is returned if an invalid driver -// name is passed. -type ErrInvalidNetworkDriver string - -func (ind ErrInvalidNetworkDriver) Error() string { - return fmt.Sprintf("invalid driver bound to network: %s", string(ind)) -} - -// BadRequest denotes the type of this error -func (ind ErrInvalidNetworkDriver) BadRequest() {} - -// ErrInvalidJoin is returned if a join is attempted on an endpoint -// which already has a container joined. -type ErrInvalidJoin struct{} - -func (ij ErrInvalidJoin) Error() string { - return "a container has already joined the endpoint" -} - -// BadRequest denotes the type of this error -func (ij ErrInvalidJoin) BadRequest() {} - -// ErrNoContainer is returned when the endpoint has no container -// attached to it. -type ErrNoContainer struct{} - -func (nc ErrNoContainer) Error() string { - return "no container is attached to the endpoint" -} - -// Maskable denotes the type of this error -func (nc ErrNoContainer) Maskable() {} - -// ErrInvalidID is returned when a query-by-id method is being invoked -// with an empty id parameter -type ErrInvalidID string - -func (ii ErrInvalidID) Error() string { - return fmt.Sprintf("invalid id: %s", string(ii)) -} - -// BadRequest denotes the type of this error -func (ii ErrInvalidID) BadRequest() {} - -// ErrInvalidName is returned when a query-by-name or resource create method is -// invoked with an empty name parameter -type ErrInvalidName string - -func (in ErrInvalidName) Error() string { - return fmt.Sprintf("invalid name: %s", string(in)) -} - -// BadRequest denotes the type of this error -func (in ErrInvalidName) BadRequest() {} - -// ErrInvalidConfigFile type is returned when an invalid LibNetwork config file is detected -type ErrInvalidConfigFile string - -func (cf ErrInvalidConfigFile) Error() string { - return fmt.Sprintf("Invalid Config file %q", string(cf)) -} - -// NetworkTypeError type is returned when the network type string is not -// known to libnetwork. -type NetworkTypeError string - -func (nt NetworkTypeError) Error() string { - return fmt.Sprintf("unknown driver %q", string(nt)) -} - -// NotFound denotes the type of this error -func (nt NetworkTypeError) NotFound() {} - -// NetworkNameError is returned when a network with the same name already exists. -type NetworkNameError string - -func (nnr NetworkNameError) Error() string { - return fmt.Sprintf("network with name %s already exists", string(nnr)) -} - -// Forbidden denotes the type of this error -func (nnr NetworkNameError) Forbidden() {} - -// UnknownNetworkError is returned when libnetwork could not find in its database -// a network with the same name and id. -type UnknownNetworkError struct { - name string - id string -} - -func (une *UnknownNetworkError) Error() string { - return fmt.Sprintf("unknown network %s id %s", une.name, une.id) -} - -// NotFound denotes the type of this error -func (une *UnknownNetworkError) NotFound() {} - -// ActiveEndpointsError is returned when a network is deleted which has active -// endpoints in it. -type ActiveEndpointsError struct { - name string - id string -} - -func (aee *ActiveEndpointsError) Error() string { - return fmt.Sprintf("network %s id %s has active endpoints", aee.name, aee.id) -} - -// Forbidden denotes the type of this error -func (aee *ActiveEndpointsError) Forbidden() {} - -// UnknownEndpointError is returned when libnetwork could not find in its database -// an endpoint with the same name and id. -type UnknownEndpointError struct { - name string - id string -} - -func (uee *UnknownEndpointError) Error() string { - return fmt.Sprintf("unknown endpoint %s id %s", uee.name, uee.id) -} - -// NotFound denotes the type of this error -func (uee *UnknownEndpointError) NotFound() {} - -// ActiveContainerError is returned when an endpoint is deleted which has active -// containers attached to it. -type ActiveContainerError struct { - name string - id string -} - -func (ace *ActiveContainerError) Error() string { - return fmt.Sprintf("endpoint with name %s id %s has active containers", ace.name, ace.id) -} - -// Forbidden denotes the type of this error -func (ace *ActiveContainerError) Forbidden() {} - -// InvalidContainerIDError is returned when an invalid container id is passed -// in Join/Leave -type InvalidContainerIDError string - -func (id InvalidContainerIDError) Error() string { - return fmt.Sprintf("invalid container id %s", string(id)) -} - -// BadRequest denotes the type of this error -func (id InvalidContainerIDError) BadRequest() {} - -// ManagerRedirectError is returned when the request should be redirected to Manager -type ManagerRedirectError string - -func (mr ManagerRedirectError) Error() string { - return "Redirect the request to the manager" -} - -// Maskable denotes the type of this error -func (mr ManagerRedirectError) Maskable() {} - -// ErrDataStoreNotInitialized is returned if an invalid data scope is passed -// for getting data store -type ErrDataStoreNotInitialized string - -func (dsni ErrDataStoreNotInitialized) Error() string { - return fmt.Sprintf("datastore for scope %q is not initialized", string(dsni)) -} diff --git a/vendor/github.com/docker/libnetwork/etchosts/etchosts.go b/vendor/github.com/docker/libnetwork/etchosts/etchosts.go deleted file mode 100644 index d55298af45..0000000000 --- a/vendor/github.com/docker/libnetwork/etchosts/etchosts.go +++ /dev/null @@ -1,208 +0,0 @@ -package etchosts - -import ( - "bufio" - "bytes" - "fmt" - "io" - "io/ioutil" - "os" - "regexp" - "strings" - "sync" -) - -// Record Structure for a single host record -type Record struct { - Hosts string - IP string -} - -// WriteTo writes record to file and returns bytes written or error -func (r Record) WriteTo(w io.Writer) (int64, error) { - n, err := fmt.Fprintf(w, "%s\t%s\n", r.IP, r.Hosts) - return int64(n), err -} - -var ( - // Default hosts config records slice - defaultContent = []Record{ - {Hosts: "localhost", IP: "127.0.0.1"}, - {Hosts: "localhost ip6-localhost ip6-loopback", IP: "::1"}, - {Hosts: "ip6-localnet", IP: "fe00::0"}, - {Hosts: "ip6-mcastprefix", IP: "ff00::0"}, - {Hosts: "ip6-allnodes", IP: "ff02::1"}, - {Hosts: "ip6-allrouters", IP: "ff02::2"}, - } - - // A cache of path level locks for synchronizing /etc/hosts - // updates on a file level - pathMap = make(map[string]*sync.Mutex) - - // A package level mutex to synchronize the cache itself - pathMutex sync.Mutex -) - -func pathLock(path string) func() { - pathMutex.Lock() - defer pathMutex.Unlock() - - pl, ok := pathMap[path] - if !ok { - pl = &sync.Mutex{} - pathMap[path] = pl - } - - pl.Lock() - return func() { - pl.Unlock() - } -} - -// Drop drops the path string from the path cache -func Drop(path string) { - pathMutex.Lock() - defer pathMutex.Unlock() - - delete(pathMap, path) -} - -// Build function -// path is path to host file string required -// IP, hostname, and domainname set main record leave empty for no master record -// extraContent is an array of extra host records. -func Build(path, IP, hostname, domainname string, extraContent []Record) error { - defer pathLock(path)() - - content := bytes.NewBuffer(nil) - if IP != "" { - //set main record - var mainRec Record - mainRec.IP = IP - // User might have provided a FQDN in hostname or split it across hostname - // and domainname. We want the FQDN and the bare hostname. - fqdn := hostname - if domainname != "" { - fqdn = fmt.Sprintf("%s.%s", fqdn, domainname) - } - parts := strings.SplitN(fqdn, ".", 2) - if len(parts) == 2 { - mainRec.Hosts = fmt.Sprintf("%s %s", fqdn, parts[0]) - } else { - mainRec.Hosts = fqdn - } - if _, err := mainRec.WriteTo(content); err != nil { - return err - } - } - // Write defaultContent slice to buffer - for _, r := range defaultContent { - if _, err := r.WriteTo(content); err != nil { - return err - } - } - // Write extra content from function arguments - for _, r := range extraContent { - if _, err := r.WriteTo(content); err != nil { - return err - } - } - - return ioutil.WriteFile(path, content.Bytes(), 0644) -} - -// Add adds an arbitrary number of Records to an already existing /etc/hosts file -func Add(path string, recs []Record) error { - defer pathLock(path)() - - if len(recs) == 0 { - return nil - } - - b, err := mergeRecords(path, recs) - if err != nil { - return err - } - - return ioutil.WriteFile(path, b, 0644) -} - -func mergeRecords(path string, recs []Record) ([]byte, error) { - f, err := os.Open(path) - if err != nil { - return nil, err - } - defer f.Close() - - content := bytes.NewBuffer(nil) - - if _, err := content.ReadFrom(f); err != nil { - return nil, err - } - - for _, r := range recs { - if _, err := r.WriteTo(content); err != nil { - return nil, err - } - } - - return content.Bytes(), nil -} - -// Delete deletes an arbitrary number of Records already existing in /etc/hosts file -func Delete(path string, recs []Record) error { - defer pathLock(path)() - - if len(recs) == 0 { - return nil - } - old, err := os.Open(path) - if err != nil { - return err - } - - var buf bytes.Buffer - - s := bufio.NewScanner(old) - eol := []byte{'\n'} -loop: - for s.Scan() { - b := s.Bytes() - if len(b) == 0 { - continue - } - - if b[0] == '#' { - buf.Write(b) - buf.Write(eol) - continue - } - for _, r := range recs { - if bytes.HasSuffix(b, []byte("\t"+r.Hosts)) { - continue loop - } - } - buf.Write(b) - buf.Write(eol) - } - old.Close() - if err := s.Err(); err != nil { - return err - } - return ioutil.WriteFile(path, buf.Bytes(), 0644) -} - -// Update all IP addresses where hostname matches. -// path is path to host file -// IP is new IP address -// hostname is hostname to search for to replace IP -func Update(path, IP, hostname string) error { - defer pathLock(path)() - - old, err := ioutil.ReadFile(path) - if err != nil { - return err - } - var re = regexp.MustCompile(fmt.Sprintf("(\\S*)(\\t%s)(\\s|\\.)", regexp.QuoteMeta(hostname))) - return ioutil.WriteFile(path, re.ReplaceAll(old, []byte(IP+"$2"+"$3")), 0644) -} diff --git a/vendor/github.com/docker/libnetwork/firewall_linux.go b/vendor/github.com/docker/libnetwork/firewall_linux.go deleted file mode 100644 index ead12b5396..0000000000 --- a/vendor/github.com/docker/libnetwork/firewall_linux.go +++ /dev/null @@ -1,46 +0,0 @@ -package libnetwork - -import ( - "github.com/docker/libnetwork/iptables" - "github.com/sirupsen/logrus" -) - -const userChain = "DOCKER-USER" - -var ( - ctrl *controller = nil -) - -func setupArrangeUserFilterRule(c *controller) { - ctrl = c - iptables.OnReloaded(arrangeUserFilterRule) -} - -// This chain allow users to configure firewall policies in a way that persists -// docker operations/restarts. Docker will not delete or modify any pre-existing -// rules from the DOCKER-USER filter chain. -// Note once DOCKER-USER chain is created, docker engine does not remove it when -// IPTableForwarding is disabled, because it contains rules configured by user that -// are beyond docker engine's control. -func arrangeUserFilterRule() { - if ctrl == nil || !ctrl.iptablesEnabled() { - return - } - // TODO IPv6 support - iptable := iptables.GetIptable(iptables.IPv4) - _, err := iptable.NewChain(userChain, iptables.Filter, false) - if err != nil { - logrus.Warnf("Failed to create %s chain: %v", userChain, err) - return - } - - if err = iptable.AddReturnRule(userChain); err != nil { - logrus.Warnf("Failed to add the RETURN rule for %s: %v", userChain, err) - return - } - - err = iptable.EnsureJumpRule("FORWARD", userChain) - if err != nil { - logrus.Warnf("Failed to ensure the jump rule for %s: %v", userChain, err) - } -} diff --git a/vendor/github.com/docker/libnetwork/firewall_others.go b/vendor/github.com/docker/libnetwork/firewall_others.go deleted file mode 100644 index 4f72ae9df3..0000000000 --- a/vendor/github.com/docker/libnetwork/firewall_others.go +++ /dev/null @@ -1,6 +0,0 @@ -// +build !linux - -package libnetwork - -func setupArrangeUserFilterRule(c *controller) {} -func arrangeUserFilterRule() {} diff --git a/vendor/github.com/docker/libnetwork/hostdiscovery/hostdiscovery.go b/vendor/github.com/docker/libnetwork/hostdiscovery/hostdiscovery.go deleted file mode 100644 index 452b5628c1..0000000000 --- a/vendor/github.com/docker/libnetwork/hostdiscovery/hostdiscovery.go +++ /dev/null @@ -1,121 +0,0 @@ -package hostdiscovery - -import ( - "net" - "sync" - - "github.com/sirupsen/logrus" - - mapset "github.com/deckarep/golang-set" - "github.com/docker/docker/pkg/discovery" - // Including KV - _ "github.com/docker/docker/pkg/discovery/kv" - "github.com/docker/libkv/store/consul" - "github.com/docker/libkv/store/etcd" - "github.com/docker/libkv/store/zookeeper" - "github.com/docker/libnetwork/types" -) - -type hostDiscovery struct { - watcher discovery.Watcher - nodes mapset.Set - stopChan chan struct{} - sync.Mutex -} - -func init() { - consul.Register() - etcd.Register() - zookeeper.Register() -} - -// NewHostDiscovery function creates a host discovery object -func NewHostDiscovery(watcher discovery.Watcher) HostDiscovery { - return &hostDiscovery{watcher: watcher, nodes: mapset.NewSet(), stopChan: make(chan struct{})} -} - -func (h *hostDiscovery) Watch(activeCallback ActiveCallback, joinCallback JoinCallback, leaveCallback LeaveCallback) error { - h.Lock() - d := h.watcher - h.Unlock() - if d == nil { - return types.BadRequestErrorf("invalid discovery watcher") - } - discoveryCh, errCh := d.Watch(h.stopChan) - go h.monitorDiscovery(discoveryCh, errCh, activeCallback, joinCallback, leaveCallback) - return nil -} - -func (h *hostDiscovery) monitorDiscovery(ch <-chan discovery.Entries, errCh <-chan error, - activeCallback ActiveCallback, joinCallback JoinCallback, leaveCallback LeaveCallback) { - for { - select { - case entries := <-ch: - h.processCallback(entries, activeCallback, joinCallback, leaveCallback) - case err := <-errCh: - if err != nil { - logrus.Errorf("discovery error: %v", err) - } - case <-h.stopChan: - return - } - } -} - -func (h *hostDiscovery) StopDiscovery() error { - h.Lock() - stopChan := h.stopChan - h.watcher = nil - h.Unlock() - - close(stopChan) - return nil -} - -func (h *hostDiscovery) processCallback(entries discovery.Entries, - activeCallback ActiveCallback, joinCallback JoinCallback, leaveCallback LeaveCallback) { - updated := hosts(entries) - h.Lock() - existing := h.nodes - added, removed := diff(existing, updated) - h.nodes = updated - h.Unlock() - - activeCallback() - if len(added) > 0 { - joinCallback(added) - } - if len(removed) > 0 { - leaveCallback(removed) - } -} - -func diff(existing mapset.Set, updated mapset.Set) (added []net.IP, removed []net.IP) { - addSlice := updated.Difference(existing).ToSlice() - removeSlice := existing.Difference(updated).ToSlice() - for _, ip := range addSlice { - added = append(added, net.ParseIP(ip.(string))) - } - for _, ip := range removeSlice { - removed = append(removed, net.ParseIP(ip.(string))) - } - return -} - -func (h *hostDiscovery) Fetch() []net.IP { - h.Lock() - defer h.Unlock() - ips := []net.IP{} - for _, ipstr := range h.nodes.ToSlice() { - ips = append(ips, net.ParseIP(ipstr.(string))) - } - return ips -} - -func hosts(entries discovery.Entries) mapset.Set { - hosts := mapset.NewSet() - for _, entry := range entries { - hosts.Add(entry.Host) - } - return hosts -} diff --git a/vendor/github.com/docker/libnetwork/hostdiscovery/hostdiscovery_api.go b/vendor/github.com/docker/libnetwork/hostdiscovery/hostdiscovery_api.go deleted file mode 100644 index f0ca40e31f..0000000000 --- a/vendor/github.com/docker/libnetwork/hostdiscovery/hostdiscovery_api.go +++ /dev/null @@ -1,22 +0,0 @@ -package hostdiscovery - -import "net" - -// JoinCallback provides a callback event for new node joining the cluster -type JoinCallback func(entries []net.IP) - -// ActiveCallback provides a callback event for active discovery event -type ActiveCallback func() - -// LeaveCallback provides a callback event for node leaving the cluster -type LeaveCallback func(entries []net.IP) - -// HostDiscovery primary interface -type HostDiscovery interface { - //Watch Node join and leave cluster events - Watch(activeCallback ActiveCallback, joinCallback JoinCallback, leaveCallback LeaveCallback) error - // StopDiscovery stops the discovery process - StopDiscovery() error - // Fetch returns a list of host IPs that are currently discovered - Fetch() []net.IP -} diff --git a/vendor/github.com/docker/libnetwork/idm/idm.go b/vendor/github.com/docker/libnetwork/idm/idm.go deleted file mode 100644 index d5843d4a58..0000000000 --- a/vendor/github.com/docker/libnetwork/idm/idm.go +++ /dev/null @@ -1,76 +0,0 @@ -// Package idm manages reservation/release of numerical ids from a configured set of contiguous ids -package idm - -import ( - "errors" - "fmt" - - "github.com/docker/libnetwork/bitseq" - "github.com/docker/libnetwork/datastore" -) - -// Idm manages the reservation/release of numerical ids from a contiguous set -type Idm struct { - start uint64 - end uint64 - handle *bitseq.Handle -} - -// New returns an instance of id manager for a [start,end] set of numerical ids -func New(ds datastore.DataStore, id string, start, end uint64) (*Idm, error) { - if id == "" { - return nil, errors.New("Invalid id") - } - if end <= start { - return nil, fmt.Errorf("Invalid set range: [%d, %d]", start, end) - } - - h, err := bitseq.NewHandle("idm", ds, id, 1+end-start) - if err != nil { - return nil, fmt.Errorf("failed to initialize bit sequence handler: %s", err.Error()) - } - - return &Idm{start: start, end: end, handle: h}, nil -} - -// GetID returns the first available id in the set -func (i *Idm) GetID(serial bool) (uint64, error) { - if i.handle == nil { - return 0, errors.New("ID set is not initialized") - } - ordinal, err := i.handle.SetAny(serial) - return i.start + ordinal, err -} - -// GetSpecificID tries to reserve the specified id -func (i *Idm) GetSpecificID(id uint64) error { - if i.handle == nil { - return errors.New("ID set is not initialized") - } - - if id < i.start || id > i.end { - return errors.New("Requested id does not belong to the set") - } - - return i.handle.Set(id - i.start) -} - -// GetIDInRange returns the first available id in the set within a [start,end] range -func (i *Idm) GetIDInRange(start, end uint64, serial bool) (uint64, error) { - if i.handle == nil { - return 0, errors.New("ID set is not initialized") - } - - if start < i.start || end > i.end { - return 0, errors.New("Requested range does not belong to the set") - } - - ordinal, err := i.handle.SetAnyInRange(start-i.start, end-i.start, serial) - - return i.start + ordinal, err -} - -// Release releases the specified id -func (i *Idm) Release(id uint64) { - i.handle.Unset(id - i.start) -} diff --git a/vendor/github.com/docker/libnetwork/internal/caller/caller.go b/vendor/github.com/docker/libnetwork/internal/caller/caller.go deleted file mode 100644 index 1634ffc6b3..0000000000 --- a/vendor/github.com/docker/libnetwork/internal/caller/caller.go +++ /dev/null @@ -1,29 +0,0 @@ -package caller - -import ( - "runtime" - "strings" -) - -func callerInfo(i int) string { - ptr, _, _, ok := runtime.Caller(i) - fName := "unknown" - if ok { - f := runtime.FuncForPC(ptr) - if f != nil { - // f.Name() is like: github.com/docker/libnetwork/caller.MethodName - tmp := strings.Split(f.Name(), ".") - if len(tmp) > 0 { - fName = tmp[len(tmp)-1] - } - } - } - - return fName -} - -// Name returns the name of the function at the specified level -// level == 0 means current method name -func Name(level int) string { - return callerInfo(2 + level) -} diff --git a/vendor/github.com/docker/libnetwork/internal/setmatrix/setmatrix.go b/vendor/github.com/docker/libnetwork/internal/setmatrix/setmatrix.go deleted file mode 100644 index 4a57d841cf..0000000000 --- a/vendor/github.com/docker/libnetwork/internal/setmatrix/setmatrix.go +++ /dev/null @@ -1,135 +0,0 @@ -package setmatrix - -import ( - "sync" - - mapset "github.com/deckarep/golang-set" -) - -// SetMatrix is a map of Sets -type SetMatrix interface { - // Get returns the members of the set for a specific key as a slice. - Get(key string) ([]interface{}, bool) - // Contains is used to verify if an element is in a set for a specific key - // returns true if the element is in the set - // returns true if there is a set for the key - Contains(key string, value interface{}) (bool, bool) - // Insert inserts the value in the set of a key - // returns true if the value is inserted (was not already in the set), false otherwise - // returns also the length of the set for the key - Insert(key string, value interface{}) (bool, int) - // Remove removes the value in the set for a specific key - // returns true if the value is deleted, false otherwise - // returns also the length of the set for the key - Remove(key string, value interface{}) (bool, int) - // Cardinality returns the number of elements in the set for a key - // returns false if the set is not present - Cardinality(key string) (int, bool) - // String returns the string version of the set, empty otherwise - // returns false if the set is not present - String(key string) (string, bool) - // Returns all the keys in the map - Keys() []string -} - -type setMatrix struct { - matrix map[string]mapset.Set - - sync.Mutex -} - -// NewSetMatrix creates a new set matrix object -func NewSetMatrix() SetMatrix { - s := &setMatrix{} - s.init() - return s -} - -func (s *setMatrix) init() { - s.matrix = make(map[string]mapset.Set) -} - -func (s *setMatrix) Get(key string) ([]interface{}, bool) { - s.Lock() - defer s.Unlock() - set, ok := s.matrix[key] - if !ok { - return nil, ok - } - return set.ToSlice(), ok -} - -func (s *setMatrix) Contains(key string, value interface{}) (bool, bool) { - s.Lock() - defer s.Unlock() - set, ok := s.matrix[key] - if !ok { - return false, ok - } - return set.Contains(value), ok -} - -func (s *setMatrix) Insert(key string, value interface{}) (bool, int) { - s.Lock() - defer s.Unlock() - set, ok := s.matrix[key] - if !ok { - s.matrix[key] = mapset.NewSet() - s.matrix[key].Add(value) - return true, 1 - } - - return set.Add(value), set.Cardinality() -} - -func (s *setMatrix) Remove(key string, value interface{}) (bool, int) { - s.Lock() - defer s.Unlock() - set, ok := s.matrix[key] - if !ok { - return false, 0 - } - - var removed bool - if set.Contains(value) { - set.Remove(value) - removed = true - // If the set is empty remove it from the matrix - if set.Cardinality() == 0 { - delete(s.matrix, key) - } - } - - return removed, set.Cardinality() -} - -func (s *setMatrix) Cardinality(key string) (int, bool) { - s.Lock() - defer s.Unlock() - set, ok := s.matrix[key] - if !ok { - return 0, ok - } - - return set.Cardinality(), ok -} - -func (s *setMatrix) String(key string) (string, bool) { - s.Lock() - defer s.Unlock() - set, ok := s.matrix[key] - if !ok { - return "", ok - } - return set.String(), ok -} - -func (s *setMatrix) Keys() []string { - s.Lock() - defer s.Unlock() - keys := make([]string, 0, len(s.matrix)) - for k := range s.matrix { - keys = append(keys, k) - } - return keys -} diff --git a/vendor/github.com/docker/libnetwork/ipam/allocator.go b/vendor/github.com/docker/libnetwork/ipam/allocator.go deleted file mode 100644 index 73a682aba0..0000000000 --- a/vendor/github.com/docker/libnetwork/ipam/allocator.go +++ /dev/null @@ -1,642 +0,0 @@ -package ipam - -import ( - "fmt" - "net" - "sort" - "sync" - - "github.com/docker/libnetwork/bitseq" - "github.com/docker/libnetwork/datastore" - "github.com/docker/libnetwork/discoverapi" - "github.com/docker/libnetwork/ipamapi" - "github.com/docker/libnetwork/ipamutils" - "github.com/docker/libnetwork/types" - "github.com/sirupsen/logrus" -) - -const ( - localAddressSpace = "LocalDefault" - globalAddressSpace = "GlobalDefault" - // The biggest configurable host subnets - minNetSize = 8 - minNetSizeV6 = 64 - // datastore keyes for ipam objects - dsConfigKey = "ipam/" + ipamapi.DefaultIPAM + "/config" - dsDataKey = "ipam/" + ipamapi.DefaultIPAM + "/data" -) - -// Allocator provides per address space ipv4/ipv6 book keeping -type Allocator struct { - // Predefined pools for default address spaces - // Separate from the addrSpace because they should not be serialized - predefined map[string][]*net.IPNet - predefinedStartIndices map[string]int - // The (potentially serialized) address spaces - addrSpaces map[string]*addrSpace - // stores []datastore.Datastore - // Allocated addresses in each address space's subnet - addresses map[SubnetKey]*bitseq.Handle - sync.Mutex -} - -// NewAllocator returns an instance of libnetwork ipam -func NewAllocator(lcDs, glDs datastore.DataStore) (*Allocator, error) { - a := &Allocator{} - - // Load predefined subnet pools - - a.predefined = map[string][]*net.IPNet{ - localAddressSpace: ipamutils.GetLocalScopeDefaultNetworks(), - globalAddressSpace: ipamutils.GetGlobalScopeDefaultNetworks(), - } - - // Initialize asIndices map - a.predefinedStartIndices = make(map[string]int) - - // Initialize bitseq map - a.addresses = make(map[SubnetKey]*bitseq.Handle) - - // Initialize address spaces - a.addrSpaces = make(map[string]*addrSpace) - for _, aspc := range []struct { - as string - ds datastore.DataStore - }{ - {localAddressSpace, lcDs}, - {globalAddressSpace, glDs}, - } { - a.initializeAddressSpace(aspc.as, aspc.ds) - } - - return a, nil -} - -func (a *Allocator) refresh(as string) error { - aSpace, err := a.getAddressSpaceFromStore(as) - if err != nil { - return types.InternalErrorf("error getting pools config from store: %v", err) - } - - if aSpace == nil { - return nil - } - - a.Lock() - a.addrSpaces[as] = aSpace - a.Unlock() - - return nil -} - -func (a *Allocator) updateBitMasks(aSpace *addrSpace) error { - var inserterList []func() error - - aSpace.Lock() - for k, v := range aSpace.subnets { - if v.Range == nil { - kk := k - vv := v - inserterList = append(inserterList, func() error { return a.insertBitMask(kk, vv.Pool) }) - } - } - aSpace.Unlock() - - // Add the bitmasks (data could come from datastore) - if inserterList != nil { - for _, f := range inserterList { - if err := f(); err != nil { - return err - } - } - } - - return nil -} - -// Checks for and fixes damaged bitmask. -func (a *Allocator) checkConsistency(as string) { - var sKeyList []SubnetKey - - // Retrieve this address space's configuration and bitmasks from the datastore - a.refresh(as) - a.Lock() - aSpace, ok := a.addrSpaces[as] - a.Unlock() - if !ok { - return - } - a.updateBitMasks(aSpace) - - aSpace.Lock() - for sk, pd := range aSpace.subnets { - if pd.Range != nil { - continue - } - sKeyList = append(sKeyList, sk) - } - aSpace.Unlock() - - for _, sk := range sKeyList { - a.Lock() - bm := a.addresses[sk] - a.Unlock() - if err := bm.CheckConsistency(); err != nil { - logrus.Warnf("Error while running consistency check for %s: %v", sk, err) - } - } -} - -func (a *Allocator) initializeAddressSpace(as string, ds datastore.DataStore) error { - scope := "" - if ds != nil { - scope = ds.Scope() - } - - a.Lock() - if currAS, ok := a.addrSpaces[as]; ok { - if currAS.ds != nil { - a.Unlock() - return types.ForbiddenErrorf("a datastore is already configured for the address space %s", as) - } - } - a.addrSpaces[as] = &addrSpace{ - subnets: map[SubnetKey]*PoolData{}, - id: dsConfigKey + "/" + as, - scope: scope, - ds: ds, - alloc: a, - } - a.Unlock() - - a.checkConsistency(as) - - return nil -} - -// DiscoverNew informs the allocator about a new global scope datastore -func (a *Allocator) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error { - if dType != discoverapi.DatastoreConfig { - return nil - } - - dsc, ok := data.(discoverapi.DatastoreConfigData) - if !ok { - return types.InternalErrorf("incorrect data in datastore update notification: %v", data) - } - - ds, err := datastore.NewDataStoreFromConfig(dsc) - if err != nil { - return err - } - - return a.initializeAddressSpace(globalAddressSpace, ds) -} - -// DiscoverDelete is a notification of no interest for the allocator -func (a *Allocator) DiscoverDelete(dType discoverapi.DiscoveryType, data interface{}) error { - return nil -} - -// GetDefaultAddressSpaces returns the local and global default address spaces -func (a *Allocator) GetDefaultAddressSpaces() (string, string, error) { - return localAddressSpace, globalAddressSpace, nil -} - -// RequestPool returns an address pool along with its unique id. -// addressSpace must be a valid address space name and must not be the empty string. -// If pool is the empty string then the default predefined pool for addressSpace will be used, otherwise pool must be a valid IP address and length in CIDR notation. -// If subPool is not empty, it must be a valid IP address and length in CIDR notation which is a sub-range of pool. -// subPool must be empty if pool is empty. -func (a *Allocator) RequestPool(addressSpace, pool, subPool string, options map[string]string, v6 bool) (string, *net.IPNet, map[string]string, error) { - logrus.Debugf("RequestPool(%s, %s, %s, %v, %t)", addressSpace, pool, subPool, options, v6) - - k, nw, ipr, err := a.parsePoolRequest(addressSpace, pool, subPool, v6) - if err != nil { - return "", nil, nil, types.InternalErrorf("failed to parse pool request for address space %q pool %q subpool %q: %v", addressSpace, pool, subPool, err) - } - - pdf := k == nil - -retry: - if pdf { - if nw, err = a.getPredefinedPool(addressSpace, v6); err != nil { - return "", nil, nil, err - } - k = &SubnetKey{AddressSpace: addressSpace, Subnet: nw.String()} - } - - if err := a.refresh(addressSpace); err != nil { - return "", nil, nil, err - } - - aSpace, err := a.getAddrSpace(addressSpace) - if err != nil { - return "", nil, nil, err - } - - insert, err := aSpace.updatePoolDBOnAdd(*k, nw, ipr, pdf) - if err != nil { - if _, ok := err.(types.MaskableError); ok { - logrus.Debugf("Retrying predefined pool search: %v", err) - goto retry - } - return "", nil, nil, err - } - - if err := a.writeToStore(aSpace); err != nil { - if _, ok := err.(types.RetryError); !ok { - return "", nil, nil, types.InternalErrorf("pool configuration failed because of %s", err.Error()) - } - - goto retry - } - - return k.String(), nw, nil, insert() -} - -// ReleasePool releases the address pool identified by the passed id -func (a *Allocator) ReleasePool(poolID string) error { - logrus.Debugf("ReleasePool(%s)", poolID) - k := SubnetKey{} - if err := k.FromString(poolID); err != nil { - return types.BadRequestErrorf("invalid pool id: %s", poolID) - } - -retry: - if err := a.refresh(k.AddressSpace); err != nil { - return err - } - - aSpace, err := a.getAddrSpace(k.AddressSpace) - if err != nil { - return err - } - - remove, err := aSpace.updatePoolDBOnRemoval(k) - if err != nil { - return err - } - - if err = a.writeToStore(aSpace); err != nil { - if _, ok := err.(types.RetryError); !ok { - return types.InternalErrorf("pool (%s) removal failed because of %v", poolID, err) - } - goto retry - } - - return remove() -} - -// Given the address space, returns the local or global PoolConfig based on whether the -// address space is local or global. AddressSpace locality is registered with IPAM out of band. -func (a *Allocator) getAddrSpace(as string) (*addrSpace, error) { - a.Lock() - defer a.Unlock() - aSpace, ok := a.addrSpaces[as] - if !ok { - return nil, types.BadRequestErrorf("cannot find address space %s (most likely the backing datastore is not configured)", as) - } - return aSpace, nil -} - -// parsePoolRequest parses and validates a request to create a new pool under addressSpace and returns -// a SubnetKey, network and range describing the request. -func (a *Allocator) parsePoolRequest(addressSpace, pool, subPool string, v6 bool) (*SubnetKey, *net.IPNet, *AddressRange, error) { - var ( - nw *net.IPNet - ipr *AddressRange - err error - ) - - if addressSpace == "" { - return nil, nil, nil, ipamapi.ErrInvalidAddressSpace - } - - if pool == "" && subPool != "" { - return nil, nil, nil, ipamapi.ErrInvalidSubPool - } - - if pool == "" { - return nil, nil, nil, nil - } - - if _, nw, err = net.ParseCIDR(pool); err != nil { - return nil, nil, nil, ipamapi.ErrInvalidPool - } - - if subPool != "" { - if ipr, err = getAddressRange(subPool, nw); err != nil { - return nil, nil, nil, err - } - } - - return &SubnetKey{AddressSpace: addressSpace, Subnet: nw.String(), ChildSubnet: subPool}, nw, ipr, nil -} - -func (a *Allocator) insertBitMask(key SubnetKey, pool *net.IPNet) error { - //logrus.Debugf("Inserting bitmask (%s, %s)", key.String(), pool.String()) - - store := a.getStore(key.AddressSpace) - ipVer := getAddressVersion(pool.IP) - ones, bits := pool.Mask.Size() - numAddresses := uint64(1 << uint(bits-ones)) - - // Allow /64 subnet - if ipVer == v6 && numAddresses == 0 { - numAddresses-- - } - - // Generate the new address masks. AddressMask content may come from datastore - h, err := bitseq.NewHandle(dsDataKey, store, key.String(), numAddresses) - if err != nil { - return err - } - - // Do not let network identifier address be reserved - // Do the same for IPv6 so that bridge ip starts with XXXX...::1 - h.Set(0) - - // Do not let broadcast address be reserved - if ipVer == v4 { - h.Set(numAddresses - 1) - } - - a.Lock() - a.addresses[key] = h - a.Unlock() - return nil -} - -func (a *Allocator) retrieveBitmask(k SubnetKey, n *net.IPNet) (*bitseq.Handle, error) { - a.Lock() - bm, ok := a.addresses[k] - a.Unlock() - if !ok { - logrus.Debugf("Retrieving bitmask (%s, %s)", k.String(), n.String()) - if err := a.insertBitMask(k, n); err != nil { - return nil, types.InternalErrorf("could not find bitmask in datastore for %s", k.String()) - } - a.Lock() - bm = a.addresses[k] - a.Unlock() - } - return bm, nil -} - -func (a *Allocator) getPredefineds(as string) []*net.IPNet { - a.Lock() - defer a.Unlock() - - p := a.predefined[as] - i := a.predefinedStartIndices[as] - // defensive in case the list changed since last update - if i >= len(p) { - i = 0 - } - return append(p[i:], p[:i]...) -} - -func (a *Allocator) updateStartIndex(as string, amt int) { - a.Lock() - i := a.predefinedStartIndices[as] + amt - if i < 0 || i >= len(a.predefined[as]) { - i = 0 - } - a.predefinedStartIndices[as] = i - a.Unlock() -} - -func (a *Allocator) getPredefinedPool(as string, ipV6 bool) (*net.IPNet, error) { - var v ipVersion - v = v4 - if ipV6 { - v = v6 - } - - if as != localAddressSpace && as != globalAddressSpace { - return nil, types.NotImplementedErrorf("no default pool available for non-default address spaces") - } - - aSpace, err := a.getAddrSpace(as) - if err != nil { - return nil, err - } - - predefined := a.getPredefineds(as) - - aSpace.Lock() - for i, nw := range predefined { - if v != getAddressVersion(nw.IP) { - continue - } - // Checks whether pool has already been allocated - if _, ok := aSpace.subnets[SubnetKey{AddressSpace: as, Subnet: nw.String()}]; ok { - continue - } - // Shouldn't be necessary, but check prevents IP collisions should - // predefined pools overlap for any reason. - if !aSpace.contains(as, nw) { - aSpace.Unlock() - a.updateStartIndex(as, i+1) - return nw, nil - } - } - aSpace.Unlock() - - return nil, types.NotFoundErrorf("could not find an available, non-overlapping IPv%d address pool among the defaults to assign to the network", v) -} - -// RequestAddress returns an address from the specified pool ID -func (a *Allocator) RequestAddress(poolID string, prefAddress net.IP, opts map[string]string) (*net.IPNet, map[string]string, error) { - logrus.Debugf("RequestAddress(%s, %v, %v)", poolID, prefAddress, opts) - k := SubnetKey{} - if err := k.FromString(poolID); err != nil { - return nil, nil, types.BadRequestErrorf("invalid pool id: %s", poolID) - } - - if err := a.refresh(k.AddressSpace); err != nil { - return nil, nil, err - } - - aSpace, err := a.getAddrSpace(k.AddressSpace) - if err != nil { - return nil, nil, err - } - - aSpace.Lock() - p, ok := aSpace.subnets[k] - if !ok { - aSpace.Unlock() - return nil, nil, types.NotFoundErrorf("cannot find address pool for poolID:%s", poolID) - } - - if prefAddress != nil && !p.Pool.Contains(prefAddress) { - aSpace.Unlock() - return nil, nil, ipamapi.ErrIPOutOfRange - } - - c := p - for c.Range != nil { - k = c.ParentKey - c = aSpace.subnets[k] - } - aSpace.Unlock() - - bm, err := a.retrieveBitmask(k, c.Pool) - if err != nil { - return nil, nil, types.InternalErrorf("could not find bitmask in datastore for %s on address %v request from pool %s: %v", - k.String(), prefAddress, poolID, err) - } - // In order to request for a serial ip address allocation, callers can pass in the option to request - // IP allocation serially or first available IP in the subnet - var serial bool - if opts != nil { - if val, ok := opts[ipamapi.AllocSerialPrefix]; ok { - serial = (val == "true") - } - } - ip, err := a.getAddress(p.Pool, bm, prefAddress, p.Range, serial) - if err != nil { - return nil, nil, err - } - - return &net.IPNet{IP: ip, Mask: p.Pool.Mask}, nil, nil -} - -// ReleaseAddress releases the address from the specified pool ID -func (a *Allocator) ReleaseAddress(poolID string, address net.IP) error { - logrus.Debugf("ReleaseAddress(%s, %v)", poolID, address) - k := SubnetKey{} - if err := k.FromString(poolID); err != nil { - return types.BadRequestErrorf("invalid pool id: %s", poolID) - } - - if err := a.refresh(k.AddressSpace); err != nil { - return err - } - - aSpace, err := a.getAddrSpace(k.AddressSpace) - if err != nil { - return err - } - - aSpace.Lock() - p, ok := aSpace.subnets[k] - if !ok { - aSpace.Unlock() - return types.NotFoundErrorf("cannot find address pool for poolID:%s", poolID) - } - - if address == nil { - aSpace.Unlock() - return types.BadRequestErrorf("invalid address: nil") - } - - if !p.Pool.Contains(address) { - aSpace.Unlock() - return ipamapi.ErrIPOutOfRange - } - - c := p - for c.Range != nil { - k = c.ParentKey - c = aSpace.subnets[k] - } - aSpace.Unlock() - - mask := p.Pool.Mask - - h, err := types.GetHostPartIP(address, mask) - if err != nil { - return types.InternalErrorf("failed to release address %s: %v", address.String(), err) - } - - bm, err := a.retrieveBitmask(k, c.Pool) - if err != nil { - return types.InternalErrorf("could not find bitmask in datastore for %s on address %v release from pool %s: %v", - k.String(), address, poolID, err) - } - defer logrus.Debugf("Released address PoolID:%s, Address:%v Sequence:%s", poolID, address, bm.String()) - - return bm.Unset(ipToUint64(h)) -} - -func (a *Allocator) getAddress(nw *net.IPNet, bitmask *bitseq.Handle, prefAddress net.IP, ipr *AddressRange, serial bool) (net.IP, error) { - var ( - ordinal uint64 - err error - base *net.IPNet - ) - - logrus.Debugf("Request address PoolID:%v %s Serial:%v PrefAddress:%v ", nw, bitmask.String(), serial, prefAddress) - base = types.GetIPNetCopy(nw) - - if bitmask.Unselected() <= 0 { - return nil, ipamapi.ErrNoAvailableIPs - } - if ipr == nil && prefAddress == nil { - ordinal, err = bitmask.SetAny(serial) - } else if prefAddress != nil { - hostPart, e := types.GetHostPartIP(prefAddress, base.Mask) - if e != nil { - return nil, types.InternalErrorf("failed to allocate requested address %s: %v", prefAddress.String(), e) - } - ordinal = ipToUint64(types.GetMinimalIP(hostPart)) - err = bitmask.Set(ordinal) - } else { - ordinal, err = bitmask.SetAnyInRange(ipr.Start, ipr.End, serial) - } - - switch err { - case nil: - // Convert IP ordinal for this subnet into IP address - return generateAddress(ordinal, base), nil - case bitseq.ErrBitAllocated: - return nil, ipamapi.ErrIPAlreadyAllocated - case bitseq.ErrNoBitAvailable: - return nil, ipamapi.ErrNoAvailableIPs - default: - return nil, err - } -} - -// DumpDatabase dumps the internal info -func (a *Allocator) DumpDatabase() string { - a.Lock() - aspaces := make(map[string]*addrSpace, len(a.addrSpaces)) - orderedAS := make([]string, 0, len(a.addrSpaces)) - for as, aSpace := range a.addrSpaces { - orderedAS = append(orderedAS, as) - aspaces[as] = aSpace - } - a.Unlock() - - sort.Strings(orderedAS) - - var s string - for _, as := range orderedAS { - aSpace := aspaces[as] - s = fmt.Sprintf("\n\n%s Config", as) - aSpace.Lock() - for k, config := range aSpace.subnets { - s += fmt.Sprintf("\n%v: %v", k, config) - if config.Range == nil { - a.retrieveBitmask(k, config.Pool) - } - } - aSpace.Unlock() - } - - s = fmt.Sprintf("%s\n\nBitmasks", s) - for k, bm := range a.addresses { - s += fmt.Sprintf("\n%s: %s", k, bm) - } - - return s -} - -// IsBuiltIn returns true for builtin drivers -func (a *Allocator) IsBuiltIn() bool { - return true -} diff --git a/vendor/github.com/docker/libnetwork/ipam/store.go b/vendor/github.com/docker/libnetwork/ipam/store.go deleted file mode 100644 index 124d585518..0000000000 --- a/vendor/github.com/docker/libnetwork/ipam/store.go +++ /dev/null @@ -1,136 +0,0 @@ -package ipam - -import ( - "encoding/json" - - "github.com/docker/libnetwork/datastore" - "github.com/docker/libnetwork/types" - "github.com/sirupsen/logrus" -) - -// Key provides the Key to be used in KV Store -func (aSpace *addrSpace) Key() []string { - aSpace.Lock() - defer aSpace.Unlock() - return []string{aSpace.id} -} - -// KeyPrefix returns the immediate parent key that can be used for tree walk -func (aSpace *addrSpace) KeyPrefix() []string { - aSpace.Lock() - defer aSpace.Unlock() - return []string{dsConfigKey} -} - -// Value marshals the data to be stored in the KV store -func (aSpace *addrSpace) Value() []byte { - b, err := json.Marshal(aSpace) - if err != nil { - logrus.Warnf("Failed to marshal ipam configured pools: %v", err) - return nil - } - return b -} - -// SetValue unmarshalls the data from the KV store. -func (aSpace *addrSpace) SetValue(value []byte) error { - rc := &addrSpace{subnets: make(map[SubnetKey]*PoolData)} - if err := json.Unmarshal(value, rc); err != nil { - return err - } - aSpace.subnets = rc.subnets - return nil -} - -// Index returns the latest DB Index as seen by this object -func (aSpace *addrSpace) Index() uint64 { - aSpace.Lock() - defer aSpace.Unlock() - return aSpace.dbIndex -} - -// SetIndex method allows the datastore to store the latest DB Index into this object -func (aSpace *addrSpace) SetIndex(index uint64) { - aSpace.Lock() - aSpace.dbIndex = index - aSpace.dbExists = true - aSpace.Unlock() -} - -// Exists method is true if this object has been stored in the DB. -func (aSpace *addrSpace) Exists() bool { - aSpace.Lock() - defer aSpace.Unlock() - return aSpace.dbExists -} - -// Skip provides a way for a KV Object to avoid persisting it in the KV Store -func (aSpace *addrSpace) Skip() bool { - return false -} - -func (a *Allocator) getStore(as string) datastore.DataStore { - a.Lock() - defer a.Unlock() - - if aSpace, ok := a.addrSpaces[as]; ok { - return aSpace.ds - } - - return nil -} - -func (a *Allocator) getAddressSpaceFromStore(as string) (*addrSpace, error) { - store := a.getStore(as) - - // IPAM may not have a valid store. In such cases it is just in-memory state. - if store == nil { - return nil, nil - } - - pc := &addrSpace{id: dsConfigKey + "/" + as, ds: store, alloc: a} - if err := store.GetObject(datastore.Key(pc.Key()...), pc); err != nil { - if err == datastore.ErrKeyNotFound { - return nil, nil - } - - return nil, types.InternalErrorf("could not get pools config from store: %v", err) - } - - return pc, nil -} - -func (a *Allocator) writeToStore(aSpace *addrSpace) error { - store := aSpace.store() - - // IPAM may not have a valid store. In such cases it is just in-memory state. - if store == nil { - return nil - } - - err := store.PutObjectAtomic(aSpace) - if err == datastore.ErrKeyModified { - return types.RetryErrorf("failed to perform atomic write (%v). retry might fix the error", err) - } - - return err -} - -func (a *Allocator) deleteFromStore(aSpace *addrSpace) error { - store := aSpace.store() - - // IPAM may not have a valid store. In such cases it is just in-memory state. - if store == nil { - return nil - } - - return store.DeleteObjectAtomic(aSpace) -} - -// DataScope method returns the storage scope of the datastore -func (aSpace *addrSpace) DataScope() string { - aSpace.Lock() - defer aSpace.Unlock() - - return aSpace.scope -} diff --git a/vendor/github.com/docker/libnetwork/ipam/structures.go b/vendor/github.com/docker/libnetwork/ipam/structures.go deleted file mode 100644 index 2e6d75eaa4..0000000000 --- a/vendor/github.com/docker/libnetwork/ipam/structures.go +++ /dev/null @@ -1,364 +0,0 @@ -package ipam - -import ( - "encoding/json" - "fmt" - "net" - "strings" - "sync" - - "github.com/docker/libnetwork/datastore" - "github.com/docker/libnetwork/ipamapi" - "github.com/docker/libnetwork/types" -) - -// SubnetKey is the pointer to the configured pools in each address space -type SubnetKey struct { - AddressSpace string - Subnet string - ChildSubnet string -} - -// PoolData contains the configured pool data -type PoolData struct { - ParentKey SubnetKey - Pool *net.IPNet - Range *AddressRange `json:",omitempty"` - RefCount int -} - -// addrSpace contains the pool configurations for the address space -type addrSpace struct { - subnets map[SubnetKey]*PoolData - dbIndex uint64 - dbExists bool - id string - scope string - ds datastore.DataStore - alloc *Allocator - sync.Mutex -} - -// AddressRange specifies first and last ip ordinal which -// identifies a range in a pool of addresses -type AddressRange struct { - Sub *net.IPNet - Start, End uint64 -} - -// String returns the string form of the AddressRange object -func (r *AddressRange) String() string { - return fmt.Sprintf("Sub: %s, range [%d, %d]", r.Sub, r.Start, r.End) -} - -// MarshalJSON returns the JSON encoding of the Range object -func (r *AddressRange) MarshalJSON() ([]byte, error) { - m := map[string]interface{}{ - "Sub": r.Sub.String(), - "Start": r.Start, - "End": r.End, - } - return json.Marshal(m) -} - -// UnmarshalJSON decodes data into the Range object -func (r *AddressRange) UnmarshalJSON(data []byte) error { - m := map[string]interface{}{} - err := json.Unmarshal(data, &m) - if err != nil { - return err - } - if r.Sub, err = types.ParseCIDR(m["Sub"].(string)); err != nil { - return err - } - r.Start = uint64(m["Start"].(float64)) - r.End = uint64(m["End"].(float64)) - return nil -} - -// String returns the string form of the SubnetKey object -func (s *SubnetKey) String() string { - k := fmt.Sprintf("%s/%s", s.AddressSpace, s.Subnet) - if s.ChildSubnet != "" { - k = fmt.Sprintf("%s/%s", k, s.ChildSubnet) - } - return k -} - -// FromString populates the SubnetKey object reading it from string -func (s *SubnetKey) FromString(str string) error { - if str == "" || !strings.Contains(str, "/") { - return types.BadRequestErrorf("invalid string form for subnetkey: %s", str) - } - - p := strings.Split(str, "/") - if len(p) != 3 && len(p) != 5 { - return types.BadRequestErrorf("invalid string form for subnetkey: %s", str) - } - s.AddressSpace = p[0] - s.Subnet = fmt.Sprintf("%s/%s", p[1], p[2]) - if len(p) == 5 { - s.ChildSubnet = fmt.Sprintf("%s/%s", p[3], p[4]) - } - - return nil -} - -// String returns the string form of the PoolData object -func (p *PoolData) String() string { - return fmt.Sprintf("ParentKey: %s, Pool: %s, Range: %s, RefCount: %d", - p.ParentKey.String(), p.Pool.String(), p.Range, p.RefCount) -} - -// MarshalJSON returns the JSON encoding of the PoolData object -func (p *PoolData) MarshalJSON() ([]byte, error) { - m := map[string]interface{}{ - "ParentKey": p.ParentKey, - "RefCount": p.RefCount, - } - if p.Pool != nil { - m["Pool"] = p.Pool.String() - } - if p.Range != nil { - m["Range"] = p.Range - } - return json.Marshal(m) -} - -// UnmarshalJSON decodes data into the PoolData object -func (p *PoolData) UnmarshalJSON(data []byte) error { - var ( - err error - t struct { - ParentKey SubnetKey - Pool string - Range *AddressRange `json:",omitempty"` - RefCount int - } - ) - - if err = json.Unmarshal(data, &t); err != nil { - return err - } - - p.ParentKey = t.ParentKey - p.Range = t.Range - p.RefCount = t.RefCount - if t.Pool != "" { - if p.Pool, err = types.ParseCIDR(t.Pool); err != nil { - return err - } - } - - return nil -} - -// MarshalJSON returns the JSON encoding of the addrSpace object -func (aSpace *addrSpace) MarshalJSON() ([]byte, error) { - aSpace.Lock() - defer aSpace.Unlock() - - m := map[string]interface{}{ - "Scope": string(aSpace.scope), - } - - if aSpace.subnets != nil { - s := map[string]*PoolData{} - for k, v := range aSpace.subnets { - s[k.String()] = v - } - m["Subnets"] = s - } - - return json.Marshal(m) -} - -// UnmarshalJSON decodes data into the addrSpace object -func (aSpace *addrSpace) UnmarshalJSON(data []byte) error { - aSpace.Lock() - defer aSpace.Unlock() - - m := map[string]interface{}{} - err := json.Unmarshal(data, &m) - if err != nil { - return err - } - - aSpace.scope = datastore.LocalScope - s := m["Scope"].(string) - if s == string(datastore.GlobalScope) { - aSpace.scope = datastore.GlobalScope - } - - if v, ok := m["Subnets"]; ok { - sb, _ := json.Marshal(v) - var s map[string]*PoolData - err := json.Unmarshal(sb, &s) - if err != nil { - return err - } - for ks, v := range s { - k := SubnetKey{} - k.FromString(ks) - aSpace.subnets[k] = v - } - } - - return nil -} - -// CopyTo deep copies the pool data to the destination pooldata -func (p *PoolData) CopyTo(dstP *PoolData) error { - dstP.ParentKey = p.ParentKey - dstP.Pool = types.GetIPNetCopy(p.Pool) - - if p.Range != nil { - dstP.Range = &AddressRange{} - dstP.Range.Sub = types.GetIPNetCopy(p.Range.Sub) - dstP.Range.Start = p.Range.Start - dstP.Range.End = p.Range.End - } - - dstP.RefCount = p.RefCount - return nil -} - -func (aSpace *addrSpace) CopyTo(o datastore.KVObject) error { - aSpace.Lock() - defer aSpace.Unlock() - - dstAspace := o.(*addrSpace) - - dstAspace.id = aSpace.id - dstAspace.ds = aSpace.ds - dstAspace.alloc = aSpace.alloc - dstAspace.scope = aSpace.scope - dstAspace.dbIndex = aSpace.dbIndex - dstAspace.dbExists = aSpace.dbExists - - dstAspace.subnets = make(map[SubnetKey]*PoolData) - for k, v := range aSpace.subnets { - dstAspace.subnets[k] = &PoolData{} - v.CopyTo(dstAspace.subnets[k]) - } - - return nil -} - -func (aSpace *addrSpace) New() datastore.KVObject { - aSpace.Lock() - defer aSpace.Unlock() - - return &addrSpace{ - id: aSpace.id, - ds: aSpace.ds, - alloc: aSpace.alloc, - scope: aSpace.scope, - } -} - -// updatePoolDBOnAdd returns a closure which will add the subnet k to the address space when executed. -func (aSpace *addrSpace) updatePoolDBOnAdd(k SubnetKey, nw *net.IPNet, ipr *AddressRange, pdf bool) (func() error, error) { - aSpace.Lock() - defer aSpace.Unlock() - - // Check if already allocated - if _, ok := aSpace.subnets[k]; ok { - if pdf { - return nil, types.InternalMaskableErrorf("predefined pool %s is already reserved", nw) - } - // This means the same pool is already allocated. updatePoolDBOnAdd is called when there - // is request for a pool/subpool. It should ensure there is no overlap with existing pools - return nil, ipamapi.ErrPoolOverlap - } - - // If master pool, check for overlap - if ipr == nil { - if aSpace.contains(k.AddressSpace, nw) { - return nil, ipamapi.ErrPoolOverlap - } - // This is a new master pool, add it along with corresponding bitmask - aSpace.subnets[k] = &PoolData{Pool: nw, RefCount: 1} - return func() error { return aSpace.alloc.insertBitMask(k, nw) }, nil - } - - // This is a new non-master pool (subPool) - p := &PoolData{ - ParentKey: SubnetKey{AddressSpace: k.AddressSpace, Subnet: k.Subnet}, - Pool: nw, - Range: ipr, - RefCount: 1, - } - aSpace.subnets[k] = p - - // Look for parent pool - pp, ok := aSpace.subnets[p.ParentKey] - if ok { - aSpace.incRefCount(pp, 1) - return func() error { return nil }, nil - } - - // Parent pool does not exist, add it along with corresponding bitmask - aSpace.subnets[p.ParentKey] = &PoolData{Pool: nw, RefCount: 1} - return func() error { return aSpace.alloc.insertBitMask(p.ParentKey, nw) }, nil -} - -func (aSpace *addrSpace) updatePoolDBOnRemoval(k SubnetKey) (func() error, error) { - aSpace.Lock() - defer aSpace.Unlock() - - p, ok := aSpace.subnets[k] - if !ok { - return nil, ipamapi.ErrBadPool - } - - aSpace.incRefCount(p, -1) - - c := p - for ok { - if c.RefCount == 0 { - delete(aSpace.subnets, k) - if c.Range == nil { - return func() error { - bm, err := aSpace.alloc.retrieveBitmask(k, c.Pool) - if err != nil { - return types.InternalErrorf("could not find bitmask in datastore for pool %s removal: %v", k.String(), err) - } - return bm.Destroy() - }, nil - } - } - k = c.ParentKey - c, ok = aSpace.subnets[k] - } - - return func() error { return nil }, nil -} - -func (aSpace *addrSpace) incRefCount(p *PoolData, delta int) { - c := p - ok := true - for ok { - c.RefCount += delta - c, ok = aSpace.subnets[c.ParentKey] - } -} - -// Checks whether the passed subnet is a superset or subset of any of the subset in this config db -func (aSpace *addrSpace) contains(space string, nw *net.IPNet) bool { - for k, v := range aSpace.subnets { - if space == k.AddressSpace && k.ChildSubnet == "" { - if nw.Contains(v.Pool.IP) || v.Pool.Contains(nw.IP) { - return true - } - } - } - return false -} - -func (aSpace *addrSpace) store() datastore.DataStore { - aSpace.Lock() - defer aSpace.Unlock() - - return aSpace.ds -} diff --git a/vendor/github.com/docker/libnetwork/ipam/utils.go b/vendor/github.com/docker/libnetwork/ipam/utils.go deleted file mode 100644 index 5117c55cc7..0000000000 --- a/vendor/github.com/docker/libnetwork/ipam/utils.go +++ /dev/null @@ -1,81 +0,0 @@ -package ipam - -import ( - "fmt" - "net" - - "github.com/docker/libnetwork/ipamapi" - "github.com/docker/libnetwork/types" -) - -type ipVersion int - -const ( - v4 = 4 - v6 = 6 -) - -func getAddressRange(pool string, masterNw *net.IPNet) (*AddressRange, error) { - ip, nw, err := net.ParseCIDR(pool) - if err != nil { - return nil, ipamapi.ErrInvalidSubPool - } - lIP, e := types.GetHostPartIP(nw.IP, masterNw.Mask) - if e != nil { - return nil, fmt.Errorf("failed to compute range's lowest ip address: %v", e) - } - bIP, e := types.GetBroadcastIP(nw.IP, nw.Mask) - if e != nil { - return nil, fmt.Errorf("failed to compute range's broadcast ip address: %v", e) - } - hIP, e := types.GetHostPartIP(bIP, masterNw.Mask) - if e != nil { - return nil, fmt.Errorf("failed to compute range's highest ip address: %v", e) - } - nw.IP = ip - return &AddressRange{nw, ipToUint64(types.GetMinimalIP(lIP)), ipToUint64(types.GetMinimalIP(hIP))}, nil -} - -// It generates the ip address in the passed subnet specified by -// the passed host address ordinal -func generateAddress(ordinal uint64, network *net.IPNet) net.IP { - var address [16]byte - - // Get network portion of IP - if getAddressVersion(network.IP) == v4 { - copy(address[:], network.IP.To4()) - } else { - copy(address[:], network.IP) - } - - end := len(network.Mask) - addIntToIP(address[:end], ordinal) - - return net.IP(address[:end]) -} - -func getAddressVersion(ip net.IP) ipVersion { - if ip.To4() == nil { - return v6 - } - return v4 -} - -// Adds the ordinal IP to the current array -// 192.168.0.0 + 53 => 192.168.0.53 -func addIntToIP(array []byte, ordinal uint64) { - for i := len(array) - 1; i >= 0; i-- { - array[i] |= (byte)(ordinal & 0xff) - ordinal >>= 8 - } -} - -// Convert an ordinal to the respective IP address -func ipToUint64(ip []byte) (value uint64) { - cip := types.GetMinimalIP(ip) - for i := 0; i < len(cip); i++ { - j := len(cip) - 1 - i - value += uint64(cip[i]) << uint(j*8) - } - return value -} diff --git a/vendor/github.com/docker/libnetwork/ipamapi/contract.go b/vendor/github.com/docker/libnetwork/ipamapi/contract.go deleted file mode 100644 index 7f967863d8..0000000000 --- a/vendor/github.com/docker/libnetwork/ipamapi/contract.go +++ /dev/null @@ -1,96 +0,0 @@ -// Package ipamapi specifies the contract the IPAM service (built-in or remote) needs to satisfy. -package ipamapi - -import ( - "net" - - "github.com/docker/docker/pkg/plugingetter" - "github.com/docker/libnetwork/discoverapi" - "github.com/docker/libnetwork/types" -) - -/******************** - * IPAM plugin types - ********************/ - -const ( - // DefaultIPAM is the name of the built-in default ipam driver - DefaultIPAM = "default" - // NullIPAM is the name of the built-in null ipam driver - NullIPAM = "null" - // PluginEndpointType represents the Endpoint Type used by Plugin system - PluginEndpointType = "IpamDriver" - // RequestAddressType represents the Address Type used when requesting an address - RequestAddressType = "RequestAddressType" -) - -// Callback provides a Callback interface for registering an IPAM instance into LibNetwork -type Callback interface { - // GetPluginGetter returns the pluginv2 getter. - GetPluginGetter() plugingetter.PluginGetter - // RegisterIpamDriver provides a way for Remote drivers to dynamically register with libnetwork - RegisterIpamDriver(name string, driver Ipam) error - // RegisterIpamDriverWithCapabilities provides a way for Remote drivers to dynamically register with libnetwork and specify capabilities - RegisterIpamDriverWithCapabilities(name string, driver Ipam, capability *Capability) error -} - -/************** - * IPAM Errors - **************/ - -// Well-known errors returned by IPAM -var ( - ErrIpamInternalError = types.InternalErrorf("IPAM Internal Error") - ErrInvalidAddressSpace = types.BadRequestErrorf("Invalid Address Space") - ErrInvalidPool = types.BadRequestErrorf("Invalid Address Pool") - ErrInvalidSubPool = types.BadRequestErrorf("Invalid Address SubPool") - ErrInvalidRequest = types.BadRequestErrorf("Invalid Request") - ErrPoolNotFound = types.BadRequestErrorf("Address Pool not found") - ErrOverlapPool = types.ForbiddenErrorf("Address pool overlaps with existing pool on this address space") - ErrNoAvailablePool = types.NoServiceErrorf("No available pool") - ErrNoAvailableIPs = types.NoServiceErrorf("No available addresses on this pool") - ErrNoIPReturned = types.NoServiceErrorf("No address returned") - ErrIPAlreadyAllocated = types.ForbiddenErrorf("Address already in use") - ErrIPOutOfRange = types.BadRequestErrorf("Requested address is out of range") - ErrPoolOverlap = types.ForbiddenErrorf("Pool overlaps with other one on this address space") - ErrBadPool = types.BadRequestErrorf("Address space does not contain specified address pool") -) - -/******************************* - * IPAM Service Interface - *******************************/ - -// Ipam represents the interface the IPAM service plugins must implement -// in order to allow injection/modification of IPAM database. -type Ipam interface { - discoverapi.Discover - - // GetDefaultAddressSpaces returns the default local and global address spaces for this ipam - GetDefaultAddressSpaces() (string, string, error) - // RequestPool returns an address pool along with its unique id. Address space is a mandatory field - // which denotes a set of non-overlapping pools. pool describes the pool of addresses in CIDR notation. - // subpool indicates a smaller range of addresses from the pool, for now it is specified in CIDR notation. - // Both pool and subpool are non mandatory fields. When they are not specified, Ipam driver may choose to - // return a self chosen pool for this request. In such case the v6 flag needs to be set appropriately so - // that the driver would return the expected ip version pool. - RequestPool(addressSpace, pool, subPool string, options map[string]string, v6 bool) (string, *net.IPNet, map[string]string, error) - // ReleasePool releases the address pool identified by the passed id - ReleasePool(poolID string) error - // Request address from the specified pool ID. Input options or required IP can be passed. - RequestAddress(string, net.IP, map[string]string) (*net.IPNet, map[string]string, error) - // Release the address from the specified pool ID - ReleaseAddress(string, net.IP) error - - //IsBuiltIn returns true if it is a built-in driver. - IsBuiltIn() bool -} - -// Capability represents the requirements and capabilities of the IPAM driver -type Capability struct { - // Whether on address request, libnetwork must - // specify the endpoint MAC address - RequiresMACAddress bool - // Whether of daemon start, libnetwork must replay the pool - // request and the address request for current local networks - RequiresRequestReplay bool -} diff --git a/vendor/github.com/docker/libnetwork/ipamapi/labels.go b/vendor/github.com/docker/libnetwork/ipamapi/labels.go deleted file mode 100644 index e5c7d1cc7e..0000000000 --- a/vendor/github.com/docker/libnetwork/ipamapi/labels.go +++ /dev/null @@ -1,10 +0,0 @@ -package ipamapi - -const ( - // Prefix constant marks the reserved label space for libnetwork - Prefix = "com.docker.network" - - // AllocSerialPrefix constant marks the reserved label space for libnetwork ipam - // allocation ordering.(serial/first available) - AllocSerialPrefix = Prefix + ".ipam.serial" -) diff --git a/vendor/github.com/docker/libnetwork/ipams/builtin/builtin_unix.go b/vendor/github.com/docker/libnetwork/ipams/builtin/builtin_unix.go deleted file mode 100644 index 5ac3def770..0000000000 --- a/vendor/github.com/docker/libnetwork/ipams/builtin/builtin_unix.go +++ /dev/null @@ -1,61 +0,0 @@ -// +build linux freebsd darwin - -package builtin - -import ( - "errors" - - "github.com/docker/libnetwork/datastore" - "github.com/docker/libnetwork/ipam" - "github.com/docker/libnetwork/ipamapi" - "github.com/docker/libnetwork/ipamutils" -) - -var ( - // defaultAddressPool Stores user configured subnet list - defaultAddressPool []*ipamutils.NetworkToSplit -) - -// 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") - } - } - - err := ipamutils.ConfigLocalScopeDefaultNetworks(GetDefaultIPAddressPool()) - if err != nil { - return err - } - - a, err := ipam.NewAllocator(localDs, globalDs) - if err != nil { - return err - } - - cps := &ipamapi.Capability{RequiresRequestReplay: true} - - return ic.RegisterIpamDriverWithCapabilities(ipamapi.DefaultIPAM, a, cps) -} - -// SetDefaultIPAddressPool stores default address pool. -func SetDefaultIPAddressPool(addressPool []*ipamutils.NetworkToSplit) { - defaultAddressPool = addressPool -} - -// GetDefaultIPAddressPool returns default address pool. -func GetDefaultIPAddressPool() []*ipamutils.NetworkToSplit { - return defaultAddressPool -} diff --git a/vendor/github.com/docker/libnetwork/ipams/builtin/builtin_windows.go b/vendor/github.com/docker/libnetwork/ipams/builtin/builtin_windows.go deleted file mode 100644 index 7975981eec..0000000000 --- a/vendor/github.com/docker/libnetwork/ipams/builtin/builtin_windows.go +++ /dev/null @@ -1,72 +0,0 @@ -// +build windows - -package builtin - -import ( - "errors" - - "github.com/docker/libnetwork/datastore" - "github.com/docker/libnetwork/ipam" - "github.com/docker/libnetwork/ipamapi" - "github.com/docker/libnetwork/ipamutils" - - windowsipam "github.com/docker/libnetwork/ipams/windowsipam" -) - -var ( - // defaultAddressPool Stores user configured subnet list - defaultAddressPool []*ipamutils.NetworkToSplit -) - -// InitDockerDefault registers the built-in ipam service with libnetwork -func InitDockerDefault(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(nil) - - a, err := ipam.NewAllocator(localDs, globalDs) - if err != nil { - return err - } - - cps := &ipamapi.Capability{RequiresRequestReplay: true} - - return ic.RegisterIpamDriverWithCapabilities(ipamapi.DefaultIPAM, a, cps) -} - -// Init registers the built-in ipam service with libnetwork -func Init(ic ipamapi.Callback, l, g interface{}) error { - initFunc := windowsipam.GetInit(windowsipam.DefaultIPAM) - - err := InitDockerDefault(ic, l, g) - if err != nil { - return err - } - - return initFunc(ic, l, g) -} - -// SetDefaultIPAddressPool stores default address pool . -func SetDefaultIPAddressPool(addressPool []*ipamutils.NetworkToSplit) { - defaultAddressPool = addressPool -} - -// GetDefaultIPAddressPool returns default address pool . -func GetDefaultIPAddressPool() []*ipamutils.NetworkToSplit { - return defaultAddressPool -} diff --git a/vendor/github.com/docker/libnetwork/ipams/null/null.go b/vendor/github.com/docker/libnetwork/ipams/null/null.go deleted file mode 100644 index 339b5308d1..0000000000 --- a/vendor/github.com/docker/libnetwork/ipams/null/null.go +++ /dev/null @@ -1,75 +0,0 @@ -// Package null implements the null ipam driver. Null ipam driver satisfies ipamapi contract, -// but does not effectively reserve/allocate any address pool or address -package null - -import ( - "fmt" - "net" - - "github.com/docker/libnetwork/discoverapi" - "github.com/docker/libnetwork/ipamapi" - "github.com/docker/libnetwork/types" -) - -var ( - defaultAS = "null" - defaultPool, _ = types.ParseCIDR("0.0.0.0/0") - defaultPoolID = fmt.Sprintf("%s/%s", defaultAS, defaultPool.String()) -) - -type allocator struct{} - -func (a *allocator) GetDefaultAddressSpaces() (string, string, error) { - return defaultAS, defaultAS, nil -} - -func (a *allocator) RequestPool(addressSpace, pool, subPool string, options map[string]string, v6 bool) (string, *net.IPNet, map[string]string, error) { - if addressSpace != defaultAS { - return "", nil, nil, types.BadRequestErrorf("unknown address space: %s", addressSpace) - } - if pool != "" { - return "", nil, nil, types.BadRequestErrorf("null ipam driver does not handle specific address pool requests") - } - if subPool != "" { - return "", nil, nil, types.BadRequestErrorf("null ipam driver does not handle specific address subpool requests") - } - if v6 { - return "", nil, nil, types.BadRequestErrorf("null ipam driver does not handle IPv6 address pool pool requests") - } - return defaultPoolID, defaultPool, nil, nil -} - -func (a *allocator) ReleasePool(poolID string) error { - return nil -} - -func (a *allocator) RequestAddress(poolID string, ip net.IP, opts map[string]string) (*net.IPNet, map[string]string, error) { - if poolID != defaultPoolID { - return nil, nil, types.BadRequestErrorf("unknown pool id: %s", poolID) - } - return nil, nil, nil -} - -func (a *allocator) ReleaseAddress(poolID string, ip net.IP) error { - if poolID != defaultPoolID { - return types.BadRequestErrorf("unknown pool id: %s", poolID) - } - return nil -} - -func (a *allocator) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error { - return nil -} - -func (a *allocator) DiscoverDelete(dType discoverapi.DiscoveryType, data interface{}) error { - return nil -} - -func (a *allocator) IsBuiltIn() bool { - return true -} - -// Init registers a remote ipam when its plugin is activated -func Init(ic ipamapi.Callback, l, g interface{}) error { - return ic.RegisterIpamDriver(ipamapi.NullIPAM, &allocator{}) -} diff --git a/vendor/github.com/docker/libnetwork/ipams/remote/api/api.go b/vendor/github.com/docker/libnetwork/ipams/remote/api/api.go deleted file mode 100644 index 543c99bb00..0000000000 --- a/vendor/github.com/docker/libnetwork/ipams/remote/api/api.go +++ /dev/null @@ -1,94 +0,0 @@ -// Package api defines the data structure to be used in the request/response -// messages between libnetwork and the remote ipam plugin -package api - -import "github.com/docker/libnetwork/ipamapi" - -// Response is the basic response structure used in all responses -type Response struct { - Error string -} - -// IsSuccess returns whether the plugin response is successful -func (r *Response) IsSuccess() bool { - return r.Error == "" -} - -// GetError returns the error from the response, if any. -func (r *Response) GetError() string { - return r.Error -} - -// GetCapabilityResponse is the response of GetCapability request -type GetCapabilityResponse struct { - Response - RequiresMACAddress bool - RequiresRequestReplay bool -} - -// ToCapability converts the capability response into the internal ipam driver capability structure -func (capRes GetCapabilityResponse) ToCapability() *ipamapi.Capability { - return &ipamapi.Capability{ - RequiresMACAddress: capRes.RequiresMACAddress, - RequiresRequestReplay: capRes.RequiresRequestReplay, - } -} - -// GetAddressSpacesResponse is the response to the ``get default address spaces`` request message -type GetAddressSpacesResponse struct { - Response - LocalDefaultAddressSpace string - GlobalDefaultAddressSpace string -} - -// RequestPoolRequest represents the expected data in a ``request address pool`` request message -type RequestPoolRequest struct { - AddressSpace string - Pool string - SubPool string - Options map[string]string - V6 bool -} - -// RequestPoolResponse represents the response message to a ``request address pool`` request -type RequestPoolResponse struct { - Response - PoolID string - Pool string // CIDR format - Data map[string]string -} - -// ReleasePoolRequest represents the expected data in a ``release address pool`` request message -type ReleasePoolRequest struct { - PoolID string -} - -// ReleasePoolResponse represents the response message to a ``release address pool`` request -type ReleasePoolResponse struct { - Response -} - -// RequestAddressRequest represents the expected data in a ``request address`` request message -type RequestAddressRequest struct { - PoolID string - Address string - Options map[string]string -} - -// RequestAddressResponse represents the expected data in the response message to a ``request address`` request -type RequestAddressResponse struct { - Response - Address string // in CIDR format - Data map[string]string -} - -// ReleaseAddressRequest represents the expected data in a ``release address`` request message -type ReleaseAddressRequest struct { - PoolID string - Address string -} - -// ReleaseAddressResponse represents the response message to a ``release address`` request -type ReleaseAddressResponse struct { - Response -} diff --git a/vendor/github.com/docker/libnetwork/ipams/remote/remote.go b/vendor/github.com/docker/libnetwork/ipams/remote/remote.go deleted file mode 100644 index 6f2173f308..0000000000 --- a/vendor/github.com/docker/libnetwork/ipams/remote/remote.go +++ /dev/null @@ -1,183 +0,0 @@ -package remote - -import ( - "fmt" - "net" - - "github.com/docker/docker/pkg/plugingetter" - "github.com/docker/docker/pkg/plugins" - "github.com/docker/libnetwork/discoverapi" - "github.com/docker/libnetwork/ipamapi" - "github.com/docker/libnetwork/ipams/remote/api" - "github.com/docker/libnetwork/types" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" -) - -type allocator struct { - endpoint *plugins.Client - name string -} - -// PluginResponse is the interface for the plugin request responses -type PluginResponse interface { - IsSuccess() bool - GetError() string -} - -func newAllocator(name string, client *plugins.Client) ipamapi.Ipam { - a := &allocator{name: name, endpoint: client} - return a -} - -// Init registers a remote ipam when its plugin is activated -func Init(cb ipamapi.Callback, l, g interface{}) error { - - newPluginHandler := func(name string, client *plugins.Client) { - a := newAllocator(name, client) - if cps, err := a.(*allocator).getCapabilities(); err == nil { - if err := cb.RegisterIpamDriverWithCapabilities(name, a, cps); err != nil { - logrus.Errorf("error registering remote ipam driver %s due to %v", name, err) - } - } else { - logrus.Infof("remote ipam driver %s does not support capabilities", name) - logrus.Debug(err) - if err := cb.RegisterIpamDriver(name, a); err != nil { - logrus.Errorf("error registering remote ipam driver %s due to %v", name, err) - } - } - } - - // Unit test code is unaware of a true PluginStore. So we fall back to v1 plugins. - handleFunc := plugins.Handle - if pg := cb.GetPluginGetter(); pg != nil { - handleFunc = pg.Handle - activePlugins := pg.GetAllManagedPluginsByCap(ipamapi.PluginEndpointType) - for _, ap := range activePlugins { - client, err := getPluginClient(ap) - if err != nil { - return err - } - newPluginHandler(ap.Name(), client) - } - } - handleFunc(ipamapi.PluginEndpointType, newPluginHandler) - return nil -} - -func getPluginClient(p plugingetter.CompatPlugin) (*plugins.Client, error) { - if v1, ok := p.(plugingetter.PluginWithV1Client); ok { - return v1.Client(), nil - } - - pa, ok := p.(plugingetter.PluginAddr) - if !ok { - return nil, errors.Errorf("unknown plugin type %T", p) - } - - if pa.Protocol() != plugins.ProtocolSchemeHTTPV1 { - return nil, errors.Errorf("unsupported plugin protocol %s", pa.Protocol()) - } - - addr := pa.Addr() - client, err := plugins.NewClientWithTimeout(addr.Network()+"://"+addr.String(), nil, pa.Timeout()) - if err != nil { - return nil, errors.Wrap(err, "error creating plugin client") - } - return client, nil -} - -func (a *allocator) call(methodName string, arg interface{}, retVal PluginResponse) error { - method := ipamapi.PluginEndpointType + "." + methodName - err := a.endpoint.Call(method, arg, retVal) - if err != nil { - return err - } - if !retVal.IsSuccess() { - return fmt.Errorf("remote: %s", retVal.GetError()) - } - return nil -} - -func (a *allocator) getCapabilities() (*ipamapi.Capability, error) { - var res api.GetCapabilityResponse - if err := a.call("GetCapabilities", nil, &res); err != nil { - return nil, err - } - return res.ToCapability(), nil -} - -// GetDefaultAddressSpaces returns the local and global default address spaces -func (a *allocator) GetDefaultAddressSpaces() (string, string, error) { - res := &api.GetAddressSpacesResponse{} - if err := a.call("GetDefaultAddressSpaces", nil, res); err != nil { - return "", "", err - } - return res.LocalDefaultAddressSpace, res.GlobalDefaultAddressSpace, nil -} - -// RequestPool requests an address pool in the specified address space -func (a *allocator) RequestPool(addressSpace, pool, subPool string, options map[string]string, v6 bool) (string, *net.IPNet, map[string]string, error) { - req := &api.RequestPoolRequest{AddressSpace: addressSpace, Pool: pool, SubPool: subPool, Options: options, V6: v6} - res := &api.RequestPoolResponse{} - if err := a.call("RequestPool", req, res); err != nil { - return "", nil, nil, err - } - retPool, err := types.ParseCIDR(res.Pool) - return res.PoolID, retPool, res.Data, err -} - -// ReleasePool removes an address pool from the specified address space -func (a *allocator) ReleasePool(poolID string) error { - req := &api.ReleasePoolRequest{PoolID: poolID} - res := &api.ReleasePoolResponse{} - return a.call("ReleasePool", req, res) -} - -// RequestAddress requests an address from the address pool -func (a *allocator) RequestAddress(poolID string, address net.IP, options map[string]string) (*net.IPNet, map[string]string, error) { - var ( - prefAddress string - retAddress *net.IPNet - err error - ) - if address != nil { - prefAddress = address.String() - } - req := &api.RequestAddressRequest{PoolID: poolID, Address: prefAddress, Options: options} - res := &api.RequestAddressResponse{} - if err := a.call("RequestAddress", req, res); err != nil { - return nil, nil, err - } - if res.Address != "" { - retAddress, err = types.ParseCIDR(res.Address) - } else { - return nil, nil, ipamapi.ErrNoIPReturned - } - return retAddress, res.Data, err -} - -// ReleaseAddress releases the address from the specified address pool -func (a *allocator) ReleaseAddress(poolID string, address net.IP) error { - var relAddress string - if address != nil { - relAddress = address.String() - } - req := &api.ReleaseAddressRequest{PoolID: poolID, Address: relAddress} - res := &api.ReleaseAddressResponse{} - return a.call("ReleaseAddress", req, res) -} - -// DiscoverNew is a notification for a new discovery event, such as a new global datastore -func (a *allocator) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error { - return nil -} - -// DiscoverDelete is a notification for a discovery delete event, such as a node leaving a cluster -func (a *allocator) DiscoverDelete(dType discoverapi.DiscoveryType, data interface{}) error { - return nil -} - -func (a *allocator) IsBuiltIn() bool { - return false -} diff --git a/vendor/github.com/docker/libnetwork/ipams/windowsipam/windowsipam.go b/vendor/github.com/docker/libnetwork/ipams/windowsipam/windowsipam.go deleted file mode 100644 index 5c7b1f5411..0000000000 --- a/vendor/github.com/docker/libnetwork/ipams/windowsipam/windowsipam.go +++ /dev/null @@ -1,102 +0,0 @@ -package windowsipam - -import ( - "net" - - "github.com/docker/libnetwork/discoverapi" - "github.com/docker/libnetwork/ipamapi" - "github.com/docker/libnetwork/types" - "github.com/sirupsen/logrus" -) - -const ( - localAddressSpace = "LocalDefault" - globalAddressSpace = "GlobalDefault" -) - -// DefaultIPAM defines the default ipam-driver for local-scoped windows networks -const DefaultIPAM = "windows" - -var ( - defaultPool, _ = types.ParseCIDR("0.0.0.0/0") -) - -type allocator struct { -} - -// GetInit registers the built-in ipam service with libnetwork -func GetInit(ipamName string) func(ic ipamapi.Callback, l, g interface{}) error { - return func(ic ipamapi.Callback, l, g interface{}) error { - return ic.RegisterIpamDriver(ipamName, &allocator{}) - } -} - -func (a *allocator) GetDefaultAddressSpaces() (string, string, error) { - return localAddressSpace, globalAddressSpace, nil -} - -// RequestPool returns an address pool along with its unique id. This is a null ipam driver. It allocates the -// subnet user asked and does not validate anything. Doesn't support subpool allocation -func (a *allocator) RequestPool(addressSpace, pool, subPool string, options map[string]string, v6 bool) (string, *net.IPNet, map[string]string, error) { - logrus.Debugf("RequestPool(%s, %s, %s, %v, %t)", addressSpace, pool, subPool, options, v6) - if subPool != "" || v6 { - return "", nil, nil, types.InternalErrorf("This request is not supported by null ipam driver") - } - - var ipNet *net.IPNet - var err error - - if pool != "" { - _, ipNet, err = net.ParseCIDR(pool) - if err != nil { - return "", nil, nil, err - } - } else { - ipNet = defaultPool - } - - return ipNet.String(), ipNet, nil, nil -} - -// ReleasePool releases the address pool - always succeeds -func (a *allocator) ReleasePool(poolID string) error { - logrus.Debugf("ReleasePool(%s)", poolID) - return nil -} - -// RequestAddress returns an address from the specified pool ID. -// Always allocate the 0.0.0.0/32 ip if no preferred address was specified -func (a *allocator) RequestAddress(poolID string, prefAddress net.IP, opts map[string]string) (*net.IPNet, map[string]string, error) { - logrus.Debugf("RequestAddress(%s, %v, %v)", poolID, prefAddress, opts) - _, ipNet, err := net.ParseCIDR(poolID) - - if err != nil { - return nil, nil, err - } - - if prefAddress != nil { - return &net.IPNet{IP: prefAddress, Mask: ipNet.Mask}, nil, nil - } - - return nil, nil, nil -} - -// ReleaseAddress releases the address - always succeeds -func (a *allocator) ReleaseAddress(poolID string, address net.IP) error { - logrus.Debugf("ReleaseAddress(%s, %v)", poolID, address) - return nil -} - -// DiscoverNew informs the allocator about a new global scope datastore -func (a *allocator) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error { - return nil -} - -// DiscoverDelete is a notification of no interest for the allocator -func (a *allocator) DiscoverDelete(dType discoverapi.DiscoveryType, data interface{}) error { - return nil -} - -func (a *allocator) IsBuiltIn() bool { - return true -} diff --git a/vendor/github.com/docker/libnetwork/ipamutils/utils.go b/vendor/github.com/docker/libnetwork/ipamutils/utils.go deleted file mode 100644 index 3fd37cd884..0000000000 --- a/vendor/github.com/docker/libnetwork/ipamutils/utils.go +++ /dev/null @@ -1,135 +0,0 @@ -// Package ipamutils provides utility functions for ipam management -package ipamutils - -import ( - "fmt" - "net" - "sync" -) - -var ( - // PredefinedLocalScopeDefaultNetworks contains a list of 31 IPv4 private networks with host size 16 and 12 - // (172.17-31.x.x/16, 192.168.x.x/20) which do not overlap with the networks in `PredefinedGlobalScopeDefaultNetworks` - PredefinedLocalScopeDefaultNetworks []*net.IPNet - // PredefinedGlobalScopeDefaultNetworks contains a list of 64K IPv4 private networks with host size 8 - // (10.x.x.x/24) which do not overlap with the networks in `PredefinedLocalScopeDefaultNetworks` - PredefinedGlobalScopeDefaultNetworks []*net.IPNet - mutex sync.Mutex - localScopeDefaultNetworks = []*NetworkToSplit{{"172.17.0.0/16", 16}, {"172.18.0.0/16", 16}, {"172.19.0.0/16", 16}, - {"172.20.0.0/14", 16}, {"172.24.0.0/14", 16}, {"172.28.0.0/14", 16}, - {"192.168.0.0/16", 20}} - globalScopeDefaultNetworks = []*NetworkToSplit{{"10.0.0.0/8", 24}} -) - -// NetworkToSplit represent a network that has to be split in chunks with mask length Size. -// Each subnet in the set is derived from the Base pool. Base is to be passed -// in CIDR format. -// Example: a Base "10.10.0.0/16 with Size 24 will define the set of 256 -// 10.10.[0-255].0/24 address pools -type NetworkToSplit struct { - Base string `json:"base"` - Size int `json:"size"` -} - -func init() { - var err error - if PredefinedGlobalScopeDefaultNetworks, err = splitNetworks(globalScopeDefaultNetworks); err != nil { - //we are going to panic in case of error as we should never get into this state - panic("InitAddressPools failed to initialize the global scope default address pool") - } - - if PredefinedLocalScopeDefaultNetworks, err = splitNetworks(localScopeDefaultNetworks); err != nil { - //we are going to panic in case of error as we should never get into this state - panic("InitAddressPools failed to initialize the local scope default address pool") - } -} - -// configDefaultNetworks configures local as well global default pool based on input -func configDefaultNetworks(defaultAddressPool []*NetworkToSplit, result *[]*net.IPNet) error { - mutex.Lock() - defer mutex.Unlock() - defaultNetworks, err := splitNetworks(defaultAddressPool) - if err != nil { - return err - } - *result = defaultNetworks - return nil -} - -// GetGlobalScopeDefaultNetworks returns PredefinedGlobalScopeDefaultNetworks -func GetGlobalScopeDefaultNetworks() []*net.IPNet { - mutex.Lock() - defer mutex.Unlock() - return PredefinedGlobalScopeDefaultNetworks -} - -// GetLocalScopeDefaultNetworks returns PredefinedLocalScopeDefaultNetworks -func GetLocalScopeDefaultNetworks() []*net.IPNet { - mutex.Lock() - defer mutex.Unlock() - return PredefinedLocalScopeDefaultNetworks -} - -// ConfigGlobalScopeDefaultNetworks configures global default pool. -// Ideally this will be called from SwarmKit as part of swarm init -func ConfigGlobalScopeDefaultNetworks(defaultAddressPool []*NetworkToSplit) error { - if defaultAddressPool == nil { - defaultAddressPool = globalScopeDefaultNetworks - } - return configDefaultNetworks(defaultAddressPool, &PredefinedGlobalScopeDefaultNetworks) -} - -// ConfigLocalScopeDefaultNetworks configures local default pool. -// Ideally this will be called during libnetwork init -func ConfigLocalScopeDefaultNetworks(defaultAddressPool []*NetworkToSplit) error { - if defaultAddressPool == nil { - return nil - } - return configDefaultNetworks(defaultAddressPool, &PredefinedLocalScopeDefaultNetworks) -} - -// splitNetworks takes a slice of networks, split them accordingly and returns them -func splitNetworks(list []*NetworkToSplit) ([]*net.IPNet, error) { - localPools := make([]*net.IPNet, 0, len(list)) - - for _, p := range list { - _, b, err := net.ParseCIDR(p.Base) - if err != nil { - return nil, fmt.Errorf("invalid base pool %q: %v", p.Base, err) - } - ones, _ := b.Mask.Size() - if p.Size <= 0 || p.Size < ones { - return nil, fmt.Errorf("invalid pools size: %d", p.Size) - } - localPools = append(localPools, splitNetwork(p.Size, b)...) - } - return localPools, nil -} - -func splitNetwork(size int, base *net.IPNet) []*net.IPNet { - one, bits := base.Mask.Size() - mask := net.CIDRMask(size, bits) - n := 1 << uint(size-one) - s := uint(bits - size) - list := make([]*net.IPNet, 0, n) - - for i := 0; i < n; i++ { - ip := copyIP(base.IP) - addIntToIP(ip, uint(i<= 0; i-- { - array[i] |= (byte)(ordinal & 0xff) - ordinal >>= 8 - } -} diff --git a/vendor/github.com/docker/libnetwork/iptables/conntrack.go b/vendor/github.com/docker/libnetwork/iptables/conntrack.go deleted file mode 100644 index 08317c33ee..0000000000 --- a/vendor/github.com/docker/libnetwork/iptables/conntrack.go +++ /dev/null @@ -1,59 +0,0 @@ -package iptables - -import ( - "errors" - "net" - "syscall" - - "github.com/sirupsen/logrus" - "github.com/vishvananda/netlink" -) - -var ( - // ErrConntrackNotConfigurable means that conntrack module is not loaded or does not have the netlink module loaded - ErrConntrackNotConfigurable = errors.New("conntrack is not available") -) - -// IsConntrackProgrammable returns true if the handle supports the NETLINK_NETFILTER and the base modules are loaded -func IsConntrackProgrammable(nlh *netlink.Handle) bool { - return nlh.SupportsNetlinkFamily(syscall.NETLINK_NETFILTER) -} - -// DeleteConntrackEntries deletes all the conntrack connections on the host for the specified IP -// Returns the number of flows deleted for IPv4, IPv6 else error -func DeleteConntrackEntries(nlh *netlink.Handle, ipv4List []net.IP, ipv6List []net.IP) (uint, uint, error) { - if !IsConntrackProgrammable(nlh) { - return 0, 0, ErrConntrackNotConfigurable - } - - var totalIPv4FlowPurged uint - for _, ipAddress := range ipv4List { - flowPurged, err := purgeConntrackState(nlh, syscall.AF_INET, ipAddress) - if err != nil { - logrus.Warnf("Failed to delete conntrack state for %s: %v", ipAddress, err) - continue - } - totalIPv4FlowPurged += flowPurged - } - - var totalIPv6FlowPurged uint - for _, ipAddress := range ipv6List { - flowPurged, err := purgeConntrackState(nlh, syscall.AF_INET6, ipAddress) - if err != nil { - logrus.Warnf("Failed to delete conntrack state for %s: %v", ipAddress, err) - continue - } - totalIPv6FlowPurged += flowPurged - } - - logrus.Debugf("DeleteConntrackEntries purged ipv4:%d, ipv6:%d", totalIPv4FlowPurged, totalIPv6FlowPurged) - return totalIPv4FlowPurged, totalIPv6FlowPurged, nil -} - -func purgeConntrackState(nlh *netlink.Handle, family netlink.InetFamily, ipAddress net.IP) (uint, error) { - filter := &netlink.ConntrackFilter{} - // NOTE: doing the flush using the ipAddress is safe because today there cannot be multiple networks with the same subnet - // so it will not be possible to flush flows that are of other containers - filter.AddIP(netlink.ConntrackNatAnyIP, ipAddress) - return nlh.ConntrackDeleteFilter(netlink.ConntrackTable, family, filter) -} diff --git a/vendor/github.com/docker/libnetwork/iptables/firewalld.go b/vendor/github.com/docker/libnetwork/iptables/firewalld.go deleted file mode 100644 index 8746b220f5..0000000000 --- a/vendor/github.com/docker/libnetwork/iptables/firewalld.go +++ /dev/null @@ -1,303 +0,0 @@ -package iptables - -import ( - "fmt" - "strings" - - dbus "github.com/godbus/dbus/v5" - "github.com/sirupsen/logrus" -) - -// IPV defines the table string -type IPV string - -const ( - // Iptables point ipv4 table - Iptables IPV = "ipv4" - // IP6Tables point to ipv6 table - IP6Tables IPV = "ipv6" - // Ebtables point to bridge table - Ebtables IPV = "eb" -) - -const ( - dbusInterface = "org.fedoraproject.FirewallD1" - dbusPath = "/org/fedoraproject/FirewallD1" - dbusConfigPath = "/org/fedoraproject/FirewallD1/config" - dockerZone = "docker" -) - -// Conn is a connection to firewalld dbus endpoint. -type Conn struct { - sysconn *dbus.Conn - sysObj dbus.BusObject - sysConfObj dbus.BusObject - signal chan *dbus.Signal -} - -// ZoneSettings holds the firewalld zone settings, documented in -// https://firewalld.org/documentation/man-pages/firewalld.dbus.html -type ZoneSettings struct { - version string - name string - description string - unused bool - target string - services []string - ports [][]interface{} - icmpBlocks []string - masquerade bool - forwardPorts [][]interface{} - interfaces []string - sourceAddresses []string - richRules []string - protocols []string - sourcePorts [][]interface{} - icmpBlockInversion bool -} - -var ( - connection *Conn - - firewalldRunning bool // is Firewalld service running - onReloaded []*func() // callbacks when Firewalld has been reloaded -) - -// FirewalldInit initializes firewalld management code. -func FirewalldInit() error { - var err error - - if connection, err = newConnection(); err != nil { - return fmt.Errorf("Failed to connect to D-Bus system bus: %v", err) - } - firewalldRunning = checkRunning() - if !firewalldRunning { - connection.sysconn.Close() - connection = nil - } - if connection != nil { - go signalHandler() - if err := setupDockerZone(); err != nil { - return err - } - } - - return nil -} - -// New() establishes a connection to the system bus. -func newConnection() (*Conn, error) { - c := new(Conn) - if err := c.initConnection(); err != nil { - return nil, err - } - - return c, nil -} - -// Initialize D-Bus connection. -func (c *Conn) initConnection() error { - var err error - - c.sysconn, err = dbus.SystemBus() - if err != nil { - return err - } - - // This never fails, even if the service is not running atm. - c.sysObj = c.sysconn.Object(dbusInterface, dbus.ObjectPath(dbusPath)) - c.sysConfObj = c.sysconn.Object(dbusInterface, dbus.ObjectPath(dbusConfigPath)) - rule := fmt.Sprintf("type='signal',path='%s',interface='%s',sender='%s',member='Reloaded'", - dbusPath, dbusInterface, dbusInterface) - c.sysconn.BusObject().Call("org.freedesktop.DBus.AddMatch", 0, rule) - - rule = fmt.Sprintf("type='signal',interface='org.freedesktop.DBus',member='NameOwnerChanged',path='/org/freedesktop/DBus',sender='org.freedesktop.DBus',arg0='%s'", - dbusInterface) - c.sysconn.BusObject().Call("org.freedesktop.DBus.AddMatch", 0, rule) - - c.signal = make(chan *dbus.Signal, 10) - c.sysconn.Signal(c.signal) - - return nil -} - -func signalHandler() { - for signal := range connection.signal { - if strings.Contains(signal.Name, "NameOwnerChanged") { - firewalldRunning = checkRunning() - dbusConnectionChanged(signal.Body) - } else if strings.Contains(signal.Name, "Reloaded") { - reloaded() - } - } -} - -func dbusConnectionChanged(args []interface{}) { - name := args[0].(string) - oldOwner := args[1].(string) - newOwner := args[2].(string) - - if name != dbusInterface { - return - } - - if len(newOwner) > 0 { - connectionEstablished() - } else if len(oldOwner) > 0 { - connectionLost() - } -} - -func connectionEstablished() { - reloaded() -} - -func connectionLost() { - // Doesn't do anything for now. Libvirt also doesn't react to this. -} - -// call all callbacks -func reloaded() { - for _, pf := range onReloaded { - (*pf)() - } -} - -// OnReloaded add callback -func OnReloaded(callback func()) { - for _, pf := range onReloaded { - if pf == &callback { - return - } - } - onReloaded = append(onReloaded, &callback) -} - -// Call some remote method to see whether the service is actually running. -func checkRunning() bool { - var zone string - var err error - - if connection != nil { - err = connection.sysObj.Call(dbusInterface+".getDefaultZone", 0).Store(&zone) - return err == nil - } - return false -} - -// Passthrough method simply passes args through to iptables/ip6tables -func Passthrough(ipv IPV, args ...string) ([]byte, error) { - var output string - logrus.Debugf("Firewalld passthrough: %s, %s", ipv, args) - if err := connection.sysObj.Call(dbusInterface+".direct.passthrough", 0, ipv, args).Store(&output); err != nil { - return nil, err - } - return []byte(output), nil -} - -// getDockerZoneSettings converts the ZoneSettings struct into a interface slice -func getDockerZoneSettings() []interface{} { - settings := ZoneSettings{ - version: "1.0", - name: dockerZone, - description: "zone for docker bridge network interfaces", - target: "ACCEPT", - } - slice := []interface{}{ - settings.version, - settings.name, - settings.description, - settings.unused, - settings.target, - settings.services, - settings.ports, - settings.icmpBlocks, - settings.masquerade, - settings.forwardPorts, - settings.interfaces, - settings.sourceAddresses, - settings.richRules, - settings.protocols, - settings.sourcePorts, - settings.icmpBlockInversion, - } - return slice - -} - -// setupDockerZone creates a zone called docker in firewalld which includes docker interfaces to allow -// container networking -func setupDockerZone() error { - var zones []string - // Check if zone exists - if err := connection.sysObj.Call(dbusInterface+".zone.getZones", 0).Store(&zones); err != nil { - return err - } - if contains(zones, dockerZone) { - logrus.Infof("Firewalld: %s zone already exists, returning", dockerZone) - return nil - } - logrus.Debugf("Firewalld: creating %s zone", dockerZone) - - settings := getDockerZoneSettings() - // Permanent - if err := connection.sysConfObj.Call(dbusInterface+".config.addZone", 0, dockerZone, settings).Err; err != nil { - return err - } - // Reload for change to take effect - if err := connection.sysObj.Call(dbusInterface+".reload", 0).Err; err != nil { - return err - } - - return nil -} - -// AddInterfaceFirewalld adds the interface to the trusted zone -func AddInterfaceFirewalld(intf string) error { - var intfs []string - // Check if interface is already added to the zone - if err := connection.sysObj.Call(dbusInterface+".zone.getInterfaces", 0, dockerZone).Store(&intfs); err != nil { - return err - } - // Return if interface is already part of the zone - if contains(intfs, intf) { - logrus.Infof("Firewalld: interface %s already part of %s zone, returning", intf, dockerZone) - return nil - } - - logrus.Debugf("Firewalld: adding %s interface to %s zone", intf, dockerZone) - // Runtime - if err := connection.sysObj.Call(dbusInterface+".zone.addInterface", 0, dockerZone, intf).Err; err != nil { - return err - } - return nil -} - -// DelInterfaceFirewalld removes the interface from the trusted zone -func DelInterfaceFirewalld(intf string) error { - var intfs []string - // Check if interface is part of the zone - if err := connection.sysObj.Call(dbusInterface+".zone.getInterfaces", 0, dockerZone).Store(&intfs); err != nil { - return err - } - // Remove interface if it exists - if !contains(intfs, intf) { - return fmt.Errorf("Firewalld: unable to find interface %s in %s zone", intf, dockerZone) - } - - logrus.Debugf("Firewalld: removing %s interface from %s zone", intf, dockerZone) - // Runtime - if err := connection.sysObj.Call(dbusInterface+".zone.removeInterface", 0, dockerZone, intf).Err; err != nil { - return err - } - return nil -} - -func contains(list []string, val string) bool { - for _, v := range list { - if v == val { - return true - } - } - return false -} diff --git a/vendor/github.com/docker/libnetwork/iptables/iptables.go b/vendor/github.com/docker/libnetwork/iptables/iptables.go deleted file mode 100644 index 9bd100f1e8..0000000000 --- a/vendor/github.com/docker/libnetwork/iptables/iptables.go +++ /dev/null @@ -1,654 +0,0 @@ -package iptables - -import ( - "errors" - "fmt" - "net" - "os/exec" - "regexp" - "strconv" - "strings" - "sync" - "time" - - "github.com/sirupsen/logrus" -) - -// Action signifies the iptable action. -type Action string - -// Policy is the default iptable policies -type Policy string - -// Table refers to Nat, Filter or Mangle. -type Table string - -// IPVersion refers to IP version, v4 or v6 -type IPVersion string - -const ( - // Append appends the rule at the end of the chain. - Append Action = "-A" - // Delete deletes the rule from the chain. - Delete Action = "-D" - // Insert inserts the rule at the top of the chain. - Insert Action = "-I" - // Nat table is used for nat translation rules. - Nat Table = "nat" - // Filter table is used for filter rules. - Filter Table = "filter" - // Mangle table is used for mangling the packet. - Mangle Table = "mangle" - // Drop is the default iptables DROP policy - Drop Policy = "DROP" - // Accept is the default iptables ACCEPT policy - Accept Policy = "ACCEPT" - // IPv4 is version 4 - IPv4 IPVersion = "IPV4" - // IPv6 is version 6 - IPv6 IPVersion = "IPV6" -) - -var ( - iptablesPath string - ip6tablesPath string - supportsXlock = false - supportsCOpt = false - xLockWaitMsg = "Another app is currently holding the xtables lock" - // used to lock iptables commands if xtables lock is not supported - bestEffortLock sync.Mutex - // ErrIptablesNotFound is returned when the rule is not found. - ErrIptablesNotFound = errors.New("Iptables not found") - initOnce sync.Once -) - -// IPTable defines struct with IPVersion -type IPTable struct { - Version IPVersion -} - -// ChainInfo defines the iptables chain. -type ChainInfo struct { - Name string - Table Table - HairpinMode bool - IPTable IPTable -} - -// ChainError is returned to represent errors during ip table operation. -type ChainError struct { - Chain string - Output []byte -} - -func (e ChainError) Error() string { - return fmt.Sprintf("Error iptables %s: %s", e.Chain, string(e.Output)) -} - -func probe() { - path, err := exec.LookPath("iptables") - if err != nil { - logrus.Warnf("Failed to find iptables: %v", err) - return - } - if out, err := exec.Command(path, "--wait", "-t", "nat", "-L", "-n").CombinedOutput(); err != nil { - logrus.Warnf("Running iptables --wait -t nat -L -n failed with message: `%s`, error: %v", strings.TrimSpace(string(out)), err) - } - _, err = exec.LookPath("ip6tables") - if err != nil { - logrus.Warnf("Failed to find ip6tables: %v", err) - return - } -} - -func initFirewalld() { - if err := FirewalldInit(); err != nil { - logrus.Debugf("Fail to initialize firewalld: %v, using raw iptables instead", err) - } -} - -func detectIptables() { - path, err := exec.LookPath("iptables") - if err != nil { - return - } - iptablesPath = path - path, err = exec.LookPath("ip6tables") - if err != nil { - return - } - ip6tablesPath = path - supportsXlock = exec.Command(iptablesPath, "--wait", "-L", "-n").Run() == nil - mj, mn, mc, err := GetVersion() - if err != nil { - logrus.Warnf("Failed to read iptables version: %v", err) - return - } - supportsCOpt = supportsCOption(mj, mn, mc) -} - -func initDependencies() { - probe() - initFirewalld() - detectIptables() -} - -func initCheck() error { - initOnce.Do(initDependencies) - - if iptablesPath == "" { - return ErrIptablesNotFound - } - return nil -} - -// GetIptable returns an instance of IPTable with specified version -func GetIptable(version IPVersion) *IPTable { - return &IPTable{Version: version} -} - -// NewChain adds a new chain to ip table. -func (iptable IPTable) NewChain(name string, table Table, hairpinMode bool) (*ChainInfo, error) { - c := &ChainInfo{ - Name: name, - Table: table, - HairpinMode: hairpinMode, - IPTable: iptable, - } - if string(c.Table) == "" { - c.Table = Filter - } - - // Add chain if it doesn't exist - if _, err := iptable.Raw("-t", string(c.Table), "-n", "-L", c.Name); err != nil { - if output, err := iptable.Raw("-t", string(c.Table), "-N", c.Name); err != nil { - return nil, err - } else if len(output) != 0 { - return nil, fmt.Errorf("Could not create %s/%s chain: %s", c.Table, c.Name, output) - } - } - return c, nil -} - -// LoopbackByVersion returns loopback address by version -func (iptable IPTable) LoopbackByVersion() string { - if iptable.Version == IPv6 { - return "::1/128" - } - return "127.0.0.0/8" -} - -// ProgramChain is used to add rules to a chain -func (iptable IPTable) ProgramChain(c *ChainInfo, bridgeName string, hairpinMode, enable bool) error { - if c.Name == "" { - return errors.New("Could not program chain, missing chain name") - } - - // Either add or remove the interface from the firewalld zone - if firewalldRunning { - if enable { - if err := AddInterfaceFirewalld(bridgeName); err != nil { - return err - } - } else { - if err := DelInterfaceFirewalld(bridgeName); err != nil { - return err - } - } - } - - switch c.Table { - case Nat: - preroute := []string{ - "-m", "addrtype", - "--dst-type", "LOCAL", - "-j", c.Name} - if !iptable.Exists(Nat, "PREROUTING", preroute...) && enable { - if err := c.Prerouting(Append, preroute...); err != nil { - return fmt.Errorf("Failed to inject %s in PREROUTING chain: %s", c.Name, err) - } - } else if iptable.Exists(Nat, "PREROUTING", preroute...) && !enable { - if err := c.Prerouting(Delete, preroute...); err != nil { - return fmt.Errorf("Failed to remove %s in PREROUTING chain: %s", c.Name, err) - } - } - output := []string{ - "-m", "addrtype", - "--dst-type", "LOCAL", - "-j", c.Name} - if !hairpinMode { - output = append(output, "!", "--dst", iptable.LoopbackByVersion()) - } - if !iptable.Exists(Nat, "OUTPUT", output...) && enable { - if err := c.Output(Append, output...); err != nil { - return fmt.Errorf("Failed to inject %s in OUTPUT chain: %s", c.Name, err) - } - } else if iptable.Exists(Nat, "OUTPUT", output...) && !enable { - if err := c.Output(Delete, output...); err != nil { - return fmt.Errorf("Failed to inject %s in OUTPUT chain: %s", c.Name, err) - } - } - case Filter: - if bridgeName == "" { - return fmt.Errorf("Could not program chain %s/%s, missing bridge name", - c.Table, c.Name) - } - link := []string{ - "-o", bridgeName, - "-j", c.Name} - if !iptable.Exists(Filter, "FORWARD", link...) && enable { - insert := append([]string{string(Insert), "FORWARD"}, link...) - if output, err := iptable.Raw(insert...); err != nil { - return err - } else if len(output) != 0 { - return fmt.Errorf("Could not create linking rule to %s/%s: %s", c.Table, c.Name, output) - } - } else if iptable.Exists(Filter, "FORWARD", link...) && !enable { - del := append([]string{string(Delete), "FORWARD"}, link...) - if output, err := iptable.Raw(del...); err != nil { - return err - } else if len(output) != 0 { - return fmt.Errorf("Could not delete linking rule from %s/%s: %s", c.Table, c.Name, output) - } - - } - establish := []string{ - "-o", bridgeName, - "-m", "conntrack", - "--ctstate", "RELATED,ESTABLISHED", - "-j", "ACCEPT"} - if !iptable.Exists(Filter, "FORWARD", establish...) && enable { - insert := append([]string{string(Insert), "FORWARD"}, establish...) - if output, err := iptable.Raw(insert...); err != nil { - return err - } else if len(output) != 0 { - return fmt.Errorf("Could not create establish rule to %s: %s", c.Table, output) - } - } else if iptable.Exists(Filter, "FORWARD", establish...) && !enable { - del := append([]string{string(Delete), "FORWARD"}, establish...) - if output, err := iptable.Raw(del...); err != nil { - return err - } else if len(output) != 0 { - return fmt.Errorf("Could not delete establish rule from %s: %s", c.Table, output) - } - } - } - return nil -} - -// RemoveExistingChain removes existing chain from the table. -func (iptable IPTable) RemoveExistingChain(name string, table Table) error { - c := &ChainInfo{ - Name: name, - Table: table, - IPTable: iptable, - } - if string(c.Table) == "" { - c.Table = Filter - } - return c.Remove() -} - -// Forward adds forwarding rule to 'filter' table and corresponding nat rule to 'nat' table. -func (c *ChainInfo) Forward(action Action, ip net.IP, port int, proto, destAddr string, destPort int, bridgeName string) error { - - iptable := GetIptable(c.IPTable.Version) - daddr := ip.String() - if ip.IsUnspecified() { - // iptables interprets "0.0.0.0" as "0.0.0.0/32", whereas we - // want "0.0.0.0/0". "0/0" is correctly interpreted as "any - // value" by both iptables and ip6tables. - daddr = "0/0" - } - - args := []string{ - "-p", proto, - "-d", daddr, - "--dport", strconv.Itoa(port), - "-j", "DNAT", - "--to-destination", net.JoinHostPort(destAddr, strconv.Itoa(destPort))} - - if !c.HairpinMode { - args = append(args, "!", "-i", bridgeName) - } - if err := iptable.ProgramRule(Nat, c.Name, action, args); err != nil { - return err - } - - args = []string{ - "!", "-i", bridgeName, - "-o", bridgeName, - "-p", proto, - "-d", destAddr, - "--dport", strconv.Itoa(destPort), - "-j", "ACCEPT", - } - if err := iptable.ProgramRule(Filter, c.Name, action, args); err != nil { - return err - } - - args = []string{ - "-p", proto, - "-s", destAddr, - "-d", destAddr, - "--dport", strconv.Itoa(destPort), - "-j", "MASQUERADE", - } - - if err := iptable.ProgramRule(Nat, "POSTROUTING", action, args); err != nil { - return err - } - - if proto == "sctp" { - // Linux kernel v4.9 and below enables NETIF_F_SCTP_CRC for veth by - // the following commit. - // This introduces a problem when conbined with a physical NIC without - // NETIF_F_SCTP_CRC. As for a workaround, here we add an iptables entry - // to fill the checksum. - // - // https://github.com/torvalds/linux/commit/c80fafbbb59ef9924962f83aac85531039395b18 - args = []string{ - "-p", proto, - "--sport", strconv.Itoa(destPort), - "-j", "CHECKSUM", - "--checksum-fill", - } - if err := iptable.ProgramRule(Mangle, "POSTROUTING", action, args); err != nil { - return err - } - } - - return nil -} - -// Link adds reciprocal ACCEPT rule for two supplied IP addresses. -// Traffic is allowed from ip1 to ip2 and vice-versa -func (c *ChainInfo) Link(action Action, ip1, ip2 net.IP, port int, proto string, bridgeName string) error { - iptable := GetIptable(c.IPTable.Version) - // forward - args := []string{ - "-i", bridgeName, "-o", bridgeName, - "-p", proto, - "-s", ip1.String(), - "-d", ip2.String(), - "--dport", strconv.Itoa(port), - "-j", "ACCEPT", - } - - if err := iptable.ProgramRule(Filter, c.Name, action, args); err != nil { - return err - } - // reverse - args[7], args[9] = args[9], args[7] - args[10] = "--sport" - return iptable.ProgramRule(Filter, c.Name, action, args) -} - -// ProgramRule adds the rule specified by args only if the -// rule is not already present in the chain. Reciprocally, -// it removes the rule only if present. -func (iptable IPTable) ProgramRule(table Table, chain string, action Action, args []string) error { - if iptable.Exists(table, chain, args...) != (action == Delete) { - return nil - } - return iptable.RawCombinedOutput(append([]string{"-t", string(table), string(action), chain}, args...)...) -} - -// Prerouting adds linking rule to nat/PREROUTING chain. -func (c *ChainInfo) Prerouting(action Action, args ...string) error { - iptable := GetIptable(c.IPTable.Version) - a := []string{"-t", string(Nat), string(action), "PREROUTING"} - if len(args) > 0 { - a = append(a, args...) - } - if output, err := iptable.Raw(a...); err != nil { - return err - } else if len(output) != 0 { - return ChainError{Chain: "PREROUTING", Output: output} - } - return nil -} - -// Output adds linking rule to an OUTPUT chain. -func (c *ChainInfo) Output(action Action, args ...string) error { - iptable := GetIptable(c.IPTable.Version) - a := []string{"-t", string(c.Table), string(action), "OUTPUT"} - if len(args) > 0 { - a = append(a, args...) - } - if output, err := iptable.Raw(a...); err != nil { - return err - } else if len(output) != 0 { - return ChainError{Chain: "OUTPUT", Output: output} - } - return nil -} - -// Remove removes the chain. -func (c *ChainInfo) Remove() error { - iptable := GetIptable(c.IPTable.Version) - // Ignore errors - This could mean the chains were never set up - if c.Table == Nat { - c.Prerouting(Delete, "-m", "addrtype", "--dst-type", "LOCAL", "-j", c.Name) - c.Output(Delete, "-m", "addrtype", "--dst-type", "LOCAL", "!", "--dst", iptable.LoopbackByVersion(), "-j", c.Name) - c.Output(Delete, "-m", "addrtype", "--dst-type", "LOCAL", "-j", c.Name) // Created in versions <= 0.1.6 - - c.Prerouting(Delete) - c.Output(Delete) - } - iptable.Raw("-t", string(c.Table), "-F", c.Name) - iptable.Raw("-t", string(c.Table), "-X", c.Name) - return nil -} - -// Exists checks if a rule exists -func (iptable IPTable) Exists(table Table, chain string, rule ...string) bool { - return iptable.exists(false, table, chain, rule...) -} - -// ExistsNative behaves as Exists with the difference it -// will always invoke `iptables` binary. -func (iptable IPTable) ExistsNative(table Table, chain string, rule ...string) bool { - return iptable.exists(true, table, chain, rule...) -} - -func (iptable IPTable) exists(native bool, table Table, chain string, rule ...string) bool { - f := iptable.Raw - if native { - f = iptable.raw - } - - if string(table) == "" { - table = Filter - } - - if err := initCheck(); err != nil { - // The exists() signature does not allow us to return an error, but at least - // we can skip the (likely invalid) exec invocation. - return false - } - - if supportsCOpt { - // if exit status is 0 then return true, the rule exists - _, err := f(append([]string{"-t", string(table), "-C", chain}, rule...)...) - return err == nil - } - - // parse "iptables -S" for the rule (it checks rules in a specific chain - // in a specific table and it is very unreliable) - return iptable.existsRaw(table, chain, rule...) -} - -func (iptable IPTable) existsRaw(table Table, chain string, rule ...string) bool { - path := iptablesPath - if iptable.Version == IPv6 { - path = ip6tablesPath - } - ruleString := fmt.Sprintf("%s %s\n", chain, strings.Join(rule, " ")) - existingRules, _ := exec.Command(path, "-t", string(table), "-S", chain).Output() - - return strings.Contains(string(existingRules), ruleString) -} - -// Maximum duration that an iptables operation can take -// before flagging a warning. -const opWarnTime = 2 * time.Second - -func filterOutput(start time.Time, output []byte, args ...string) []byte { - // Flag operations that have taken a long time to complete - opTime := time.Since(start) - if opTime > opWarnTime { - logrus.Warnf("xtables contention detected while running [%s]: Waited for %.2f seconds and received %q", strings.Join(args, " "), float64(opTime)/float64(time.Second), string(output)) - } - // ignore iptables' message about xtables lock: - // it is a warning, not an error. - if strings.Contains(string(output), xLockWaitMsg) { - output = []byte("") - } - // Put further filters here if desired - return output -} - -// Raw calls 'iptables' system command, passing supplied arguments. -func (iptable IPTable) Raw(args ...string) ([]byte, error) { - if firewalldRunning { - // select correct IP version for firewalld - ipv := Iptables - if iptable.Version == IPv6 { - ipv = IP6Tables - } - - startTime := time.Now() - output, err := Passthrough(ipv, args...) - if err == nil || !strings.Contains(err.Error(), "was not provided by any .service files") { - return filterOutput(startTime, output, args...), err - } - } - return iptable.raw(args...) -} - -func (iptable IPTable) raw(args ...string) ([]byte, error) { - if err := initCheck(); err != nil { - return nil, err - } - if supportsXlock { - args = append([]string{"--wait"}, args...) - } else { - bestEffortLock.Lock() - defer bestEffortLock.Unlock() - } - - path := iptablesPath - commandName := "iptables" - if iptable.Version == IPv6 { - path = ip6tablesPath - commandName = "ip6tables" - } - - logrus.Debugf("%s, %v", path, args) - - startTime := time.Now() - output, err := exec.Command(path, args...).CombinedOutput() - if err != nil { - return nil, fmt.Errorf("iptables failed: %s %v: %s (%s)", commandName, strings.Join(args, " "), output, err) - } - - return filterOutput(startTime, output, args...), err -} - -// RawCombinedOutput internally calls the Raw function and returns a non nil -// error if Raw returned a non nil error or a non empty output -func (iptable IPTable) RawCombinedOutput(args ...string) error { - if output, err := iptable.Raw(args...); err != nil || len(output) != 0 { - return fmt.Errorf("%s (%v)", string(output), err) - } - return nil -} - -// RawCombinedOutputNative behave as RawCombinedOutput with the difference it -// will always invoke `iptables` binary -func (iptable IPTable) RawCombinedOutputNative(args ...string) error { - if output, err := iptable.raw(args...); err != nil || len(output) != 0 { - return fmt.Errorf("%s (%v)", string(output), err) - } - return nil -} - -// ExistChain checks if a chain exists -func (iptable IPTable) ExistChain(chain string, table Table) bool { - if _, err := iptable.Raw("-t", string(table), "-nL", chain); err == nil { - return true - } - return false -} - -// GetVersion reads the iptables version numbers during initialization -func GetVersion() (major, minor, micro int, err error) { - out, err := exec.Command(iptablesPath, "--version").CombinedOutput() - if err == nil { - major, minor, micro = parseVersionNumbers(string(out)) - } - return -} - -// SetDefaultPolicy sets the passed default policy for the table/chain -func (iptable IPTable) SetDefaultPolicy(table Table, chain string, policy Policy) error { - if err := iptable.RawCombinedOutput("-t", string(table), "-P", chain, string(policy)); err != nil { - return fmt.Errorf("setting default policy to %v in %v chain failed: %v", policy, chain, err) - } - return nil -} - -func parseVersionNumbers(input string) (major, minor, micro int) { - re := regexp.MustCompile(`v\d*.\d*.\d*`) - line := re.FindString(input) - fmt.Sscanf(line, "v%d.%d.%d", &major, &minor, µ) - return -} - -// iptables -C, --check option was added in v.1.4.11 -// http://ftp.netfilter.org/pub/iptables/changes-iptables-1.4.11.txt -func supportsCOption(mj, mn, mc int) bool { - return mj > 1 || (mj == 1 && (mn > 4 || (mn == 4 && mc >= 11))) -} - -// AddReturnRule adds a return rule for the chain in the filter table -func (iptable IPTable) AddReturnRule(chain string) error { - var ( - table = Filter - args = []string{"-j", "RETURN"} - ) - - if iptable.Exists(table, chain, args...) { - return nil - } - - err := iptable.RawCombinedOutput(append([]string{"-A", chain}, args...)...) - if err != nil { - return fmt.Errorf("unable to add return rule in %s chain: %s", chain, err.Error()) - } - - return nil -} - -// EnsureJumpRule ensures the jump rule is on top -func (iptable IPTable) EnsureJumpRule(fromChain, toChain string) error { - var ( - table = Filter - args = []string{"-j", toChain} - ) - - if iptable.Exists(table, fromChain, args...) { - err := iptable.RawCombinedOutput(append([]string{"-D", fromChain}, args...)...) - if err != nil { - return fmt.Errorf("unable to remove jump to %s rule in %s chain: %s", toChain, fromChain, err.Error()) - } - } - - err := iptable.RawCombinedOutput(append([]string{"-I", fromChain}, args...)...) - if err != nil { - return fmt.Errorf("unable to insert jump to %s rule in %s chain: %s", toChain, fromChain, err.Error()) - } - - return nil -} diff --git a/vendor/github.com/docker/libnetwork/netlabel/labels.go b/vendor/github.com/docker/libnetwork/netlabel/labels.go deleted file mode 100644 index f5075a6c34..0000000000 --- a/vendor/github.com/docker/libnetwork/netlabel/labels.go +++ /dev/null @@ -1,132 +0,0 @@ -package netlabel - -import ( - "strings" -) - -const ( - // Prefix constant marks the reserved label space for libnetwork - Prefix = "com.docker.network" - - // DriverPrefix constant marks the reserved label space for libnetwork drivers - DriverPrefix = Prefix + ".driver" - - // DriverPrivatePrefix constant marks the reserved label space - // for internal libnetwork drivers - DriverPrivatePrefix = DriverPrefix + ".private" - - // GenericData constant that helps to identify an option as a Generic constant - GenericData = Prefix + ".generic" - - // PortMap constant represents Port Mapping - PortMap = Prefix + ".portmap" - - // MacAddress constant represents Mac Address config of a Container - MacAddress = Prefix + ".endpoint.macaddress" - - // ExposedPorts constant represents the container's Exposed Ports - ExposedPorts = Prefix + ".endpoint.exposedports" - - // DNSServers A list of DNS servers associated with the endpoint - DNSServers = Prefix + ".endpoint.dnsservers" - - //EnableIPv6 constant represents enabling IPV6 at network level - EnableIPv6 = Prefix + ".enable_ipv6" - - // DriverMTU constant represents the MTU size for the network driver - DriverMTU = DriverPrefix + ".mtu" - - // OverlayBindInterface constant represents overlay driver bind interface - OverlayBindInterface = DriverPrefix + ".overlay.bind_interface" - - // OverlayNeighborIP constant represents overlay driver neighbor IP - OverlayNeighborIP = DriverPrefix + ".overlay.neighbor_ip" - - // OverlayVxlanIDList constant represents a list of VXLAN Ids as csv - OverlayVxlanIDList = DriverPrefix + ".overlay.vxlanid_list" - - // Gateway represents the gateway for the network - Gateway = Prefix + ".gateway" - - // Internal constant represents that the network is internal which disables default gateway service - Internal = Prefix + ".internal" - - // ContainerIfacePrefix can be used to override the interface prefix used inside the container - ContainerIfacePrefix = Prefix + ".container_iface_prefix" - - // HostIP is the Source-IP Address used to SNAT container traffic - HostIP = Prefix + ".host_ipv4" -) - -var ( - // GlobalKVProvider constant represents the KV provider backend - GlobalKVProvider = MakeKVProvider("global") - - // GlobalKVProviderURL constant represents the KV provider URL - GlobalKVProviderURL = MakeKVProviderURL("global") - - // GlobalKVProviderConfig constant represents the KV provider Config - GlobalKVProviderConfig = MakeKVProviderConfig("global") - - // GlobalKVClient constants represents the global kv store client - GlobalKVClient = MakeKVClient("global") - - // LocalKVProvider constant represents the KV provider backend - LocalKVProvider = MakeKVProvider("local") - - // LocalKVProviderURL constant represents the KV provider URL - LocalKVProviderURL = MakeKVProviderURL("local") - - // LocalKVProviderConfig constant represents the KV provider Config - LocalKVProviderConfig = MakeKVProviderConfig("local") - - // LocalKVClient constants represents the local kv store client - LocalKVClient = MakeKVClient("local") -) - -// MakeKVProvider returns the kvprovider label for the scope -func MakeKVProvider(scope string) string { - return DriverPrivatePrefix + scope + "kv_provider" -} - -// MakeKVProviderURL returns the kvprovider url label for the scope -func MakeKVProviderURL(scope string) string { - return DriverPrivatePrefix + scope + "kv_provider_url" -} - -// MakeKVProviderConfig returns the kvprovider config label for the scope -func MakeKVProviderConfig(scope string) string { - return DriverPrivatePrefix + scope + "kv_provider_config" -} - -// MakeKVClient returns the kv client label for the scope -func MakeKVClient(scope string) string { - return DriverPrivatePrefix + scope + "kv_client" -} - -// Key extracts the key portion of the label -func Key(label string) (key string) { - if kv := strings.SplitN(label, "=", 2); len(kv) > 0 { - key = kv[0] - } - return -} - -// Value extracts the value portion of the label -func Value(label string) (value string) { - if kv := strings.SplitN(label, "=", 2); len(kv) > 1 { - value = kv[1] - } - return -} - -// KeyValue decomposes the label in the (key,value) pair -func KeyValue(label string) (key string, value string) { - if kv := strings.SplitN(label, "=", 2); len(kv) > 0 { - key = kv[0] - if len(kv) > 1 { - value = kv[1] - } - } - return -} diff --git a/vendor/github.com/docker/libnetwork/netutils/utils.go b/vendor/github.com/docker/libnetwork/netutils/utils.go deleted file mode 100644 index 7de98f6b07..0000000000 --- a/vendor/github.com/docker/libnetwork/netutils/utils.go +++ /dev/null @@ -1,194 +0,0 @@ -// Network utility functions. - -package netutils - -import ( - "crypto/rand" - "encoding/hex" - "errors" - "fmt" - "io" - "net" - "strings" - - "github.com/docker/libnetwork/types" -) - -var ( - // ErrNetworkOverlapsWithNameservers preformatted error - ErrNetworkOverlapsWithNameservers = errors.New("requested network overlaps with nameserver") - // ErrNetworkOverlaps preformatted error - ErrNetworkOverlaps = errors.New("requested network overlaps with existing network") - // ErrNoDefaultRoute preformatted error - ErrNoDefaultRoute = errors.New("no default route") -) - -// CheckNameserverOverlaps checks whether the passed network overlaps with any of the nameservers -func CheckNameserverOverlaps(nameservers []string, toCheck *net.IPNet) error { - if len(nameservers) > 0 { - for _, ns := range nameservers { - _, nsNetwork, err := net.ParseCIDR(ns) - if err != nil { - return err - } - if NetworkOverlaps(toCheck, nsNetwork) { - return ErrNetworkOverlapsWithNameservers - } - } - } - return nil -} - -// NetworkOverlaps detects overlap between one IPNet and another -func NetworkOverlaps(netX *net.IPNet, netY *net.IPNet) bool { - return netX.Contains(netY.IP) || netY.Contains(netX.IP) -} - -// NetworkRange calculates the first and last IP addresses in an IPNet -func NetworkRange(network *net.IPNet) (net.IP, net.IP) { - if network == nil { - return nil, nil - } - - firstIP := network.IP.Mask(network.Mask) - lastIP := types.GetIPCopy(firstIP) - for i := 0; i < len(firstIP); i++ { - lastIP[i] = firstIP[i] | ^network.Mask[i] - } - - if network.IP.To4() != nil { - firstIP = firstIP.To4() - lastIP = lastIP.To4() - } - - return firstIP, lastIP -} - -// GetIfaceAddr returns the first IPv4 address and slice of IPv6 addresses for the specified network interface -func GetIfaceAddr(name string) (net.Addr, []net.Addr, error) { - iface, err := net.InterfaceByName(name) - if err != nil { - return nil, nil, err - } - addrs, err := iface.Addrs() - if err != nil { - return nil, nil, err - } - var addrs4 []net.Addr - var addrs6 []net.Addr - for _, addr := range addrs { - ip := (addr.(*net.IPNet)).IP - if ip4 := ip.To4(); ip4 != nil { - addrs4 = append(addrs4, addr) - } else if ip6 := ip.To16(); len(ip6) == net.IPv6len { - addrs6 = append(addrs6, addr) - } - } - switch { - case len(addrs4) == 0: - return nil, nil, fmt.Errorf("Interface %v has no IPv4 addresses", name) - case len(addrs4) > 1: - fmt.Printf("Interface %v has more than 1 IPv4 address. Defaulting to using %v\n", - name, (addrs4[0].(*net.IPNet)).IP) - } - return addrs4[0], addrs6, nil -} - -func genMAC(ip net.IP) net.HardwareAddr { - hw := make(net.HardwareAddr, 6) - // The first byte of the MAC address has to comply with these rules: - // 1. Unicast: Set the least-significant bit to 0. - // 2. Address is locally administered: Set the second-least-significant bit (U/L) to 1. - hw[0] = 0x02 - // The first 24 bits of the MAC represent the Organizationally Unique Identifier (OUI). - // Since this address is locally administered, we can do whatever we want as long as - // it doesn't conflict with other addresses. - hw[1] = 0x42 - // Fill the remaining 4 bytes based on the input - if ip == nil { - rand.Read(hw[2:]) - } else { - copy(hw[2:], ip.To4()) - } - return hw -} - -// GenerateRandomMAC returns a new 6-byte(48-bit) hardware address (MAC) -func GenerateRandomMAC() net.HardwareAddr { - return genMAC(nil) -} - -// GenerateMACFromIP returns a locally administered MAC address where the 4 least -// significant bytes are derived from the IPv4 address. -func GenerateMACFromIP(ip net.IP) net.HardwareAddr { - return genMAC(ip) -} - -// GenerateRandomName returns a new name joined with a prefix. This size -// specified is used to truncate the randomly generated value -func GenerateRandomName(prefix string, size int) (string, error) { - id := make([]byte, 32) - if _, err := io.ReadFull(rand.Reader, id); err != nil { - return "", err - } - return prefix + hex.EncodeToString(id)[:size], nil -} - -// ReverseIP accepts a V4 or V6 IP string in the canonical form and returns a reversed IP in -// the dotted decimal form . This is used to setup the IP to service name mapping in the optimal -// way for the DNS PTR queries. -func ReverseIP(IP string) string { - var reverseIP []string - - if net.ParseIP(IP).To4() != nil { - reverseIP = strings.Split(IP, ".") - l := len(reverseIP) - for i, j := 0, l-1; i < l/2; i, j = i+1, j-1 { - reverseIP[i], reverseIP[j] = reverseIP[j], reverseIP[i] - } - } else { - reverseIP = strings.Split(IP, ":") - - // Reversed IPv6 is represented in dotted decimal instead of the typical - // colon hex notation - for key := range reverseIP { - if len(reverseIP[key]) == 0 { // expand the compressed 0s - reverseIP[key] = strings.Repeat("0000", 8-strings.Count(IP, ":")) - } else if len(reverseIP[key]) < 4 { // 0-padding needed - reverseIP[key] = strings.Repeat("0", 4-len(reverseIP[key])) + reverseIP[key] - } - } - - reverseIP = strings.Split(strings.Join(reverseIP, ""), "") - - l := len(reverseIP) - for i, j := 0, l-1; i < l/2; i, j = i+1, j-1 { - reverseIP[i], reverseIP[j] = reverseIP[j], reverseIP[i] - } - } - - return strings.Join(reverseIP, ".") -} - -// ParseAlias parses and validates the specified string as an alias format (name:alias) -func ParseAlias(val string) (string, string, error) { - if val == "" { - return "", "", errors.New("empty string specified for alias") - } - arr := strings.Split(val, ":") - if len(arr) > 2 { - return "", "", fmt.Errorf("bad format for alias: %s", val) - } - if len(arr) == 1 { - return val, val, nil - } - return arr[0], arr[1], nil -} - -// ValidateAlias validates that the specified string has a valid alias format (containerName:alias). -func ValidateAlias(val string) (string, error) { - if _, _, err := ParseAlias(val); err != nil { - return val, err - } - return val, nil -} diff --git a/vendor/github.com/docker/libnetwork/netutils/utils_freebsd.go b/vendor/github.com/docker/libnetwork/netutils/utils_freebsd.go deleted file mode 100644 index 02bcd32aa8..0000000000 --- a/vendor/github.com/docker/libnetwork/netutils/utils_freebsd.go +++ /dev/null @@ -1,23 +0,0 @@ -package netutils - -import ( - "net" - - "github.com/docker/libnetwork/types" -) - -// ElectInterfaceAddresses looks for an interface on the OS with the specified name -// and returns returns all its IPv4 and IPv6 addresses in CIDR notation. -// If a failure in retrieving the addresses or no IPv4 address is found, an error is returned. -// If the interface does not exist, it chooses from a predefined -// list the first IPv4 address which does not conflict with other -// interfaces on the system. -func ElectInterfaceAddresses(name string) ([]*net.IPNet, []*net.IPNet, error) { - return nil, nil, types.NotImplementedErrorf("not supported on freebsd") -} - -// FindAvailableNetwork returns a network from the passed list which does not -// overlap with existing interfaces in the system -func FindAvailableNetwork(list []*net.IPNet) (*net.IPNet, error) { - return nil, types.NotImplementedErrorf("not supported on freebsd") -} diff --git a/vendor/github.com/docker/libnetwork/netutils/utils_linux.go b/vendor/github.com/docker/libnetwork/netutils/utils_linux.go deleted file mode 100644 index 4d2376437a..0000000000 --- a/vendor/github.com/docker/libnetwork/netutils/utils_linux.go +++ /dev/null @@ -1,128 +0,0 @@ -// +build linux -// Network utility functions. - -package netutils - -import ( - "fmt" - "net" - "strings" - - "github.com/docker/libnetwork/ipamutils" - "github.com/docker/libnetwork/ns" - "github.com/docker/libnetwork/osl" - "github.com/docker/libnetwork/resolvconf" - "github.com/docker/libnetwork/types" - "github.com/pkg/errors" - "github.com/vishvananda/netlink" -) - -var ( - networkGetRoutesFct func(netlink.Link, int) ([]netlink.Route, error) -) - -// CheckRouteOverlaps checks whether the passed network overlaps with any existing routes -func CheckRouteOverlaps(toCheck *net.IPNet) error { - if networkGetRoutesFct == nil { - networkGetRoutesFct = ns.NlHandle().RouteList - } - networks, err := networkGetRoutesFct(nil, netlink.FAMILY_V4) - if err != nil { - return err - } - for _, network := range networks { - if network.Dst != nil && NetworkOverlaps(toCheck, network.Dst) { - return ErrNetworkOverlaps - } - } - return nil -} - -// GenerateIfaceName returns an interface name using the passed in -// prefix and the length of random bytes. The api ensures that the -// there are is no interface which exists with that name. -func GenerateIfaceName(nlh *netlink.Handle, prefix string, len int) (string, error) { - linkByName := netlink.LinkByName - if nlh != nil { - linkByName = nlh.LinkByName - } - for i := 0; i < 3; i++ { - name, err := GenerateRandomName(prefix, len) - if err != nil { - continue - } - _, err = linkByName(name) - if err != nil { - if strings.Contains(err.Error(), "not found") { - return name, nil - } - return "", err - } - } - return "", types.InternalErrorf("could not generate interface name") -} - -// ElectInterfaceAddresses looks for an interface on the OS with the -// specified name and returns returns all its IPv4 and IPv6 addresses in CIDR notation. -// If a failure in retrieving the addresses or no IPv4 address is found, an error is returned. -// If the interface does not exist, it chooses from a predefined -// list the first IPv4 address which does not conflict with other -// interfaces on the system. -func ElectInterfaceAddresses(name string) ([]*net.IPNet, []*net.IPNet, error) { - var ( - v4Nets []*net.IPNet - v6Nets []*net.IPNet - ) - - defer osl.InitOSContext()() - - link, _ := ns.NlHandle().LinkByName(name) - if link != nil { - v4addr, err := ns.NlHandle().AddrList(link, netlink.FAMILY_V4) - if err != nil { - return nil, nil, err - } - v6addr, err := ns.NlHandle().AddrList(link, netlink.FAMILY_V6) - if err != nil { - return nil, nil, err - } - for _, nlAddr := range v4addr { - v4Nets = append(v4Nets, nlAddr.IPNet) - } - for _, nlAddr := range v6addr { - v6Nets = append(v6Nets, nlAddr.IPNet) - } - } - - if link == nil || len(v4Nets) == 0 { - // Choose from predefined local scope networks - v4Net, err := FindAvailableNetwork(ipamutils.PredefinedLocalScopeDefaultNetworks) - if err != nil { - return nil, nil, errors.Wrapf(err, "PredefinedLocalScopeDefaultNetworks List: %+v", - ipamutils.PredefinedLocalScopeDefaultNetworks) - } - v4Nets = append(v4Nets, v4Net) - } - - return v4Nets, v6Nets, nil -} - -// FindAvailableNetwork returns a network from the passed list which does not -// overlap with existing interfaces in the system -func FindAvailableNetwork(list []*net.IPNet) (*net.IPNet, error) { - // We don't check for an error here, because we don't really care if we - // can't read /etc/resolv.conf. So instead we skip the append if resolvConf - // is nil. It either doesn't exist, or we can't read it for some reason. - var nameservers []string - if rc, err := resolvconf.Get(); err == nil { - nameservers = resolvconf.GetNameserversAsCIDR(rc.Content) - } - for _, nw := range list { - if err := CheckNameserverOverlaps(nameservers, nw); err == nil { - if err := CheckRouteOverlaps(nw); err == nil { - return nw, nil - } - } - } - return nil, fmt.Errorf("no available network") -} diff --git a/vendor/github.com/docker/libnetwork/netutils/utils_windows.go b/vendor/github.com/docker/libnetwork/netutils/utils_windows.go deleted file mode 100644 index 73af44ec71..0000000000 --- a/vendor/github.com/docker/libnetwork/netutils/utils_windows.go +++ /dev/null @@ -1,25 +0,0 @@ -package netutils - -import ( - "net" - - "github.com/docker/libnetwork/types" -) - -// ElectInterfaceAddresses looks for an interface on the OS with the specified name -// and returns returns all its IPv4 and IPv6 addresses in CIDR notation. -// If a failure in retrieving the addresses or no IPv4 address is found, an error is returned. -// If the interface does not exist, it chooses from a predefined -// list the first IPv4 address which does not conflict with other -// interfaces on the system. -func ElectInterfaceAddresses(name string) ([]*net.IPNet, []*net.IPNet, error) { - return nil, nil, types.NotImplementedErrorf("not supported on windows") -} - -// FindAvailableNetwork returns a network from the passed list which does not -// overlap with existing interfaces in the system - -// TODO : Use appropriate windows APIs to identify non-overlapping subnets -func FindAvailableNetwork(list []*net.IPNet) (*net.IPNet, error) { - return nil, nil -} diff --git a/vendor/github.com/docker/libnetwork/network.go b/vendor/github.com/docker/libnetwork/network.go deleted file mode 100644 index 2514d6c4fc..0000000000 --- a/vendor/github.com/docker/libnetwork/network.go +++ /dev/null @@ -1,2249 +0,0 @@ -package libnetwork - -import ( - "encoding/json" - "fmt" - "net" - "strings" - "sync" - "time" - - "github.com/docker/docker/pkg/stringid" - "github.com/docker/libnetwork/config" - "github.com/docker/libnetwork/datastore" - "github.com/docker/libnetwork/driverapi" - "github.com/docker/libnetwork/etchosts" - "github.com/docker/libnetwork/internal/setmatrix" - "github.com/docker/libnetwork/ipamapi" - "github.com/docker/libnetwork/netlabel" - "github.com/docker/libnetwork/netutils" - "github.com/docker/libnetwork/networkdb" - "github.com/docker/libnetwork/options" - "github.com/docker/libnetwork/types" - "github.com/sirupsen/logrus" -) - -// A Network represents a logical connectivity zone that containers may -// join using the Link method. A Network is managed by a specific driver. -type Network interface { - // A user chosen name for this network. - Name() string - - // A system generated id for this network. - ID() string - - // The type of network, which corresponds to its managing driver. - Type() string - - // Create a new endpoint to this network symbolically identified by the - // specified unique name. The options parameter carries driver specific options. - CreateEndpoint(name string, options ...EndpointOption) (Endpoint, error) - - // Delete the network. - Delete(options ...NetworkDeleteOption) error - - // Endpoints returns the list of Endpoint(s) in this network. - Endpoints() []Endpoint - - // WalkEndpoints uses the provided function to walk the Endpoints - WalkEndpoints(walker EndpointWalker) - - // EndpointByName returns the Endpoint which has the passed name. If not found, the error ErrNoSuchEndpoint is returned. - EndpointByName(name string) (Endpoint, error) - - // EndpointByID returns the Endpoint which has the passed id. If not found, the error ErrNoSuchEndpoint is returned. - EndpointByID(id string) (Endpoint, error) - - // Return certain operational data belonging to this network - Info() NetworkInfo -} - -// NetworkInfo returns some configuration and operational information about the network -type NetworkInfo interface { - IpamConfig() (string, map[string]string, []*IpamConf, []*IpamConf) - IpamInfo() ([]*IpamInfo, []*IpamInfo) - DriverOptions() map[string]string - Scope() string - IPv6Enabled() bool - Internal() bool - Attachable() bool - Ingress() bool - ConfigFrom() string - ConfigOnly() bool - Labels() map[string]string - Dynamic() bool - Created() time.Time - // Peers returns a slice of PeerInfo structures which has the information about the peer - // nodes participating in the same overlay network. This is currently the per-network - // gossip cluster. For non-dynamic overlay networks and bridge networks it returns an - // empty slice - Peers() []networkdb.PeerInfo - //Services returns a map of services keyed by the service name with the details - //of all the tasks that belong to the service. Applicable only in swarm mode. - Services() map[string]ServiceInfo -} - -// EndpointWalker is a client provided function which will be used to walk the Endpoints. -// When the function returns true, the walk will stop. -type EndpointWalker func(ep Endpoint) bool - -// ipInfo is the reverse mapping from IP to service name to serve the PTR query. -// extResolver is set if an external server resolves a service name to this IP. -// Its an indication to defer PTR queries also to that external server. -type ipInfo struct { - name string - serviceID string - extResolver bool -} - -// svcMapEntry is the body of the element into the svcMap -// The ip is a string because the SetMatrix does not accept non hashable values -type svcMapEntry struct { - ip string - serviceID string -} - -type svcInfo struct { - svcMap setmatrix.SetMatrix - svcIPv6Map setmatrix.SetMatrix - ipMap setmatrix.SetMatrix - service map[string][]servicePorts -} - -// backing container or host's info -type serviceTarget struct { - name string - ip net.IP - port uint16 -} - -type servicePorts struct { - portName string - proto string - target []serviceTarget -} - -type networkDBTable struct { - name string - objType driverapi.ObjectType -} - -// IpamConf contains all the ipam related configurations for a network -type IpamConf struct { - // The master address pool for containers and network interfaces - PreferredPool string - // A subset of the master pool. If specified, - // this becomes the container pool - SubPool string - // Preferred Network Gateway address (optional) - Gateway string - // Auxiliary addresses for network driver. Must be within the master pool. - // libnetwork will reserve them if they fall into the container pool - AuxAddresses map[string]string -} - -// Validate checks whether the configuration is valid -func (c *IpamConf) Validate() error { - if c.Gateway != "" && nil == net.ParseIP(c.Gateway) { - return types.BadRequestErrorf("invalid gateway address %s in Ipam configuration", c.Gateway) - } - return nil -} - -// IpamInfo contains all the ipam related operational info for a network -type IpamInfo struct { - PoolID string - Meta map[string]string - driverapi.IPAMData -} - -// MarshalJSON encodes IpamInfo into json message -func (i *IpamInfo) MarshalJSON() ([]byte, error) { - m := map[string]interface{}{ - "PoolID": i.PoolID, - } - v, err := json.Marshal(&i.IPAMData) - if err != nil { - return nil, err - } - m["IPAMData"] = string(v) - - if i.Meta != nil { - m["Meta"] = i.Meta - } - return json.Marshal(m) -} - -// UnmarshalJSON decodes json message into PoolData -func (i *IpamInfo) UnmarshalJSON(data []byte) error { - var ( - m map[string]interface{} - err error - ) - if err = json.Unmarshal(data, &m); err != nil { - return err - } - i.PoolID = m["PoolID"].(string) - if v, ok := m["Meta"]; ok { - b, _ := json.Marshal(v) - if err = json.Unmarshal(b, &i.Meta); err != nil { - return err - } - } - if v, ok := m["IPAMData"]; ok { - if err = json.Unmarshal([]byte(v.(string)), &i.IPAMData); err != nil { - return err - } - } - return nil -} - -type network struct { - ctrlr *controller - name string - networkType string - id string - created time.Time - scope string // network data scope - labels map[string]string - ipamType string - ipamOptions map[string]string - addrSpace string - ipamV4Config []*IpamConf - ipamV6Config []*IpamConf - ipamV4Info []*IpamInfo - ipamV6Info []*IpamInfo - enableIPv6 bool - postIPv6 bool - epCnt *endpointCnt - generic options.Generic - dbIndex uint64 - dbExists bool - persist bool - stopWatchCh chan struct{} - drvOnce *sync.Once - resolverOnce sync.Once - resolver []Resolver - internal bool - attachable bool - inDelete bool - ingress bool - driverTables []networkDBTable - dynamic bool - configOnly bool - configFrom string - loadBalancerIP net.IP - loadBalancerMode string - sync.Mutex -} - -const ( - loadBalancerModeNAT = "NAT" - loadBalancerModeDSR = "DSR" - loadBalancerModeDefault = loadBalancerModeNAT -) - -func (n *network) Name() string { - n.Lock() - defer n.Unlock() - - return n.name -} - -func (n *network) ID() string { - n.Lock() - defer n.Unlock() - - return n.id -} - -func (n *network) Created() time.Time { - n.Lock() - defer n.Unlock() - - return n.created -} - -func (n *network) Type() string { - n.Lock() - defer n.Unlock() - - return n.networkType -} - -func (n *network) Key() []string { - n.Lock() - defer n.Unlock() - return []string{datastore.NetworkKeyPrefix, n.id} -} - -func (n *network) KeyPrefix() []string { - return []string{datastore.NetworkKeyPrefix} -} - -func (n *network) Value() []byte { - n.Lock() - defer n.Unlock() - b, err := json.Marshal(n) - if err != nil { - return nil - } - return b -} - -func (n *network) SetValue(value []byte) error { - return json.Unmarshal(value, n) -} - -func (n *network) Index() uint64 { - n.Lock() - defer n.Unlock() - return n.dbIndex -} - -func (n *network) SetIndex(index uint64) { - n.Lock() - n.dbIndex = index - n.dbExists = true - n.Unlock() -} - -func (n *network) Exists() bool { - n.Lock() - defer n.Unlock() - return n.dbExists -} - -func (n *network) Skip() bool { - n.Lock() - defer n.Unlock() - return !n.persist -} - -func (n *network) New() datastore.KVObject { - n.Lock() - defer n.Unlock() - - return &network{ - ctrlr: n.ctrlr, - drvOnce: &sync.Once{}, - scope: n.scope, - } -} - -// CopyTo deep copies to the destination IpamConfig -func (c *IpamConf) CopyTo(dstC *IpamConf) error { - dstC.PreferredPool = c.PreferredPool - dstC.SubPool = c.SubPool - dstC.Gateway = c.Gateway - if c.AuxAddresses != nil { - dstC.AuxAddresses = make(map[string]string, len(c.AuxAddresses)) - for k, v := range c.AuxAddresses { - dstC.AuxAddresses[k] = v - } - } - return nil -} - -// CopyTo deep copies to the destination IpamInfo -func (i *IpamInfo) CopyTo(dstI *IpamInfo) error { - dstI.PoolID = i.PoolID - if i.Meta != nil { - dstI.Meta = make(map[string]string) - for k, v := range i.Meta { - dstI.Meta[k] = v - } - } - - dstI.AddressSpace = i.AddressSpace - dstI.Pool = types.GetIPNetCopy(i.Pool) - dstI.Gateway = types.GetIPNetCopy(i.Gateway) - - if i.AuxAddresses != nil { - dstI.AuxAddresses = make(map[string]*net.IPNet) - for k, v := range i.AuxAddresses { - dstI.AuxAddresses[k] = types.GetIPNetCopy(v) - } - } - - return nil -} - -func (n *network) validateConfiguration() error { - if n.configOnly { - // Only supports network specific configurations. - // Network operator configurations are not supported. - if n.ingress || n.internal || n.attachable || n.scope != "" { - return types.ForbiddenErrorf("configuration network can only contain network " + - "specific fields. Network operator fields like " + - "[ ingress | internal | attachable | scope ] are not supported.") - } - } - if n.configFrom != "" { - if n.configOnly { - return types.ForbiddenErrorf("a configuration network cannot depend on another configuration network") - } - if n.ipamType != "" && - n.ipamType != defaultIpamForNetworkType(n.networkType) || - n.enableIPv6 || - len(n.labels) > 0 || len(n.ipamOptions) > 0 || - len(n.ipamV4Config) > 0 || len(n.ipamV6Config) > 0 { - return types.ForbiddenErrorf("user specified configurations are not supported if the network depends on a configuration network") - } - if len(n.generic) > 0 { - if data, ok := n.generic[netlabel.GenericData]; ok { - var ( - driverOptions map[string]string - opts interface{} - ) - switch t := data.(type) { - case map[string]interface{}, map[string]string: - opts = t - } - ba, err := json.Marshal(opts) - if err != nil { - return fmt.Errorf("failed to validate network configuration: %v", err) - } - if err := json.Unmarshal(ba, &driverOptions); err != nil { - return fmt.Errorf("failed to validate network configuration: %v", err) - } - if len(driverOptions) > 0 { - return types.ForbiddenErrorf("network driver options are not supported if the network depends on a configuration network") - } - } - } - } - return nil -} - -// Applies network specific configurations -func (n *network) applyConfigurationTo(to *network) error { - to.enableIPv6 = n.enableIPv6 - if len(n.labels) > 0 { - to.labels = make(map[string]string, len(n.labels)) - for k, v := range n.labels { - if _, ok := to.labels[k]; !ok { - to.labels[k] = v - } - } - } - if len(n.ipamType) != 0 { - to.ipamType = n.ipamType - } - if len(n.ipamOptions) > 0 { - to.ipamOptions = make(map[string]string, len(n.ipamOptions)) - for k, v := range n.ipamOptions { - if _, ok := to.ipamOptions[k]; !ok { - to.ipamOptions[k] = v - } - } - } - if len(n.ipamV4Config) > 0 { - to.ipamV4Config = make([]*IpamConf, 0, len(n.ipamV4Config)) - to.ipamV4Config = append(to.ipamV4Config, n.ipamV4Config...) - } - if len(n.ipamV6Config) > 0 { - to.ipamV6Config = make([]*IpamConf, 0, len(n.ipamV6Config)) - to.ipamV6Config = append(to.ipamV6Config, n.ipamV6Config...) - } - if len(n.generic) > 0 { - to.generic = options.Generic{} - for k, v := range n.generic { - to.generic[k] = v - } - } - return nil -} - -func (n *network) CopyTo(o datastore.KVObject) error { - n.Lock() - defer n.Unlock() - - dstN := o.(*network) - dstN.name = n.name - dstN.id = n.id - dstN.created = n.created - dstN.networkType = n.networkType - dstN.scope = n.scope - dstN.dynamic = n.dynamic - dstN.ipamType = n.ipamType - dstN.enableIPv6 = n.enableIPv6 - dstN.persist = n.persist - dstN.postIPv6 = n.postIPv6 - dstN.dbIndex = n.dbIndex - dstN.dbExists = n.dbExists - dstN.drvOnce = n.drvOnce - dstN.internal = n.internal - dstN.attachable = n.attachable - dstN.inDelete = n.inDelete - dstN.ingress = n.ingress - dstN.configOnly = n.configOnly - dstN.configFrom = n.configFrom - dstN.loadBalancerIP = n.loadBalancerIP - dstN.loadBalancerMode = n.loadBalancerMode - - // copy labels - if dstN.labels == nil { - dstN.labels = make(map[string]string, len(n.labels)) - } - for k, v := range n.labels { - dstN.labels[k] = v - } - - if n.ipamOptions != nil { - dstN.ipamOptions = make(map[string]string, len(n.ipamOptions)) - for k, v := range n.ipamOptions { - dstN.ipamOptions[k] = v - } - } - - for _, v4conf := range n.ipamV4Config { - dstV4Conf := &IpamConf{} - v4conf.CopyTo(dstV4Conf) - dstN.ipamV4Config = append(dstN.ipamV4Config, dstV4Conf) - } - - for _, v4info := range n.ipamV4Info { - dstV4Info := &IpamInfo{} - v4info.CopyTo(dstV4Info) - dstN.ipamV4Info = append(dstN.ipamV4Info, dstV4Info) - } - - for _, v6conf := range n.ipamV6Config { - dstV6Conf := &IpamConf{} - v6conf.CopyTo(dstV6Conf) - dstN.ipamV6Config = append(dstN.ipamV6Config, dstV6Conf) - } - - for _, v6info := range n.ipamV6Info { - dstV6Info := &IpamInfo{} - v6info.CopyTo(dstV6Info) - dstN.ipamV6Info = append(dstN.ipamV6Info, dstV6Info) - } - - dstN.generic = options.Generic{} - for k, v := range n.generic { - dstN.generic[k] = v - } - - return nil -} - -func (n *network) DataScope() string { - s := n.Scope() - // All swarm scope networks have local datascope - if s == datastore.SwarmScope { - s = datastore.LocalScope - } - return s -} - -func (n *network) getEpCnt() *endpointCnt { - n.Lock() - defer n.Unlock() - - return n.epCnt -} - -// TODO : Can be made much more generic with the help of reflection (but has some golang limitations) -func (n *network) MarshalJSON() ([]byte, error) { - netMap := make(map[string]interface{}) - netMap["name"] = n.name - netMap["id"] = n.id - netMap["created"] = n.created - netMap["networkType"] = n.networkType - netMap["scope"] = n.scope - netMap["labels"] = n.labels - netMap["ipamType"] = n.ipamType - netMap["ipamOptions"] = n.ipamOptions - netMap["addrSpace"] = n.addrSpace - netMap["enableIPv6"] = n.enableIPv6 - if n.generic != nil { - netMap["generic"] = n.generic - } - netMap["persist"] = n.persist - netMap["postIPv6"] = n.postIPv6 - if len(n.ipamV4Config) > 0 { - ics, err := json.Marshal(n.ipamV4Config) - if err != nil { - return nil, err - } - netMap["ipamV4Config"] = string(ics) - } - if len(n.ipamV4Info) > 0 { - iis, err := json.Marshal(n.ipamV4Info) - if err != nil { - return nil, err - } - netMap["ipamV4Info"] = string(iis) - } - if len(n.ipamV6Config) > 0 { - ics, err := json.Marshal(n.ipamV6Config) - if err != nil { - return nil, err - } - netMap["ipamV6Config"] = string(ics) - } - if len(n.ipamV6Info) > 0 { - iis, err := json.Marshal(n.ipamV6Info) - if err != nil { - return nil, err - } - netMap["ipamV6Info"] = string(iis) - } - netMap["internal"] = n.internal - netMap["attachable"] = n.attachable - netMap["inDelete"] = n.inDelete - netMap["ingress"] = n.ingress - netMap["configOnly"] = n.configOnly - netMap["configFrom"] = n.configFrom - netMap["loadBalancerIP"] = n.loadBalancerIP - netMap["loadBalancerMode"] = n.loadBalancerMode - return json.Marshal(netMap) -} - -// TODO : Can be made much more generic with the help of reflection (but has some golang limitations) -func (n *network) UnmarshalJSON(b []byte) (err error) { - var netMap map[string]interface{} - if err := json.Unmarshal(b, &netMap); err != nil { - return err - } - n.name = netMap["name"].(string) - n.id = netMap["id"].(string) - // "created" is not available in older versions - if v, ok := netMap["created"]; ok { - // n.created is time.Time but marshalled as string - if err = n.created.UnmarshalText([]byte(v.(string))); err != nil { - logrus.Warnf("failed to unmarshal creation time %v: %v", v, err) - n.created = time.Time{} - } - } - n.networkType = netMap["networkType"].(string) - n.enableIPv6 = netMap["enableIPv6"].(bool) - - // if we weren't unmarshaling to netMap we could simply set n.labels - // unfortunately, we can't because map[string]interface{} != map[string]string - if labels, ok := netMap["labels"].(map[string]interface{}); ok { - n.labels = make(map[string]string, len(labels)) - for label, value := range labels { - n.labels[label] = value.(string) - } - } - - if v, ok := netMap["ipamOptions"]; ok { - if iOpts, ok := v.(map[string]interface{}); ok { - n.ipamOptions = make(map[string]string, len(iOpts)) - for k, v := range iOpts { - n.ipamOptions[k] = v.(string) - } - } - } - - if v, ok := netMap["generic"]; ok { - n.generic = v.(map[string]interface{}) - // Restore opts in their map[string]string form - if v, ok := n.generic[netlabel.GenericData]; ok { - var lmap map[string]string - ba, err := json.Marshal(v) - if err != nil { - return err - } - if err := json.Unmarshal(ba, &lmap); err != nil { - return err - } - n.generic[netlabel.GenericData] = lmap - } - } - if v, ok := netMap["persist"]; ok { - n.persist = v.(bool) - } - if v, ok := netMap["postIPv6"]; ok { - n.postIPv6 = v.(bool) - } - if v, ok := netMap["ipamType"]; ok { - n.ipamType = v.(string) - } else { - n.ipamType = ipamapi.DefaultIPAM - } - if v, ok := netMap["addrSpace"]; ok { - n.addrSpace = v.(string) - } - if v, ok := netMap["ipamV4Config"]; ok { - if err := json.Unmarshal([]byte(v.(string)), &n.ipamV4Config); err != nil { - return err - } - } - if v, ok := netMap["ipamV4Info"]; ok { - if err := json.Unmarshal([]byte(v.(string)), &n.ipamV4Info); err != nil { - return err - } - } - if v, ok := netMap["ipamV6Config"]; ok { - if err := json.Unmarshal([]byte(v.(string)), &n.ipamV6Config); err != nil { - return err - } - } - if v, ok := netMap["ipamV6Info"]; ok { - if err := json.Unmarshal([]byte(v.(string)), &n.ipamV6Info); err != nil { - return err - } - } - if v, ok := netMap["internal"]; ok { - n.internal = v.(bool) - } - if v, ok := netMap["attachable"]; ok { - n.attachable = v.(bool) - } - if s, ok := netMap["scope"]; ok { - n.scope = s.(string) - } - if v, ok := netMap["inDelete"]; ok { - n.inDelete = v.(bool) - } - if v, ok := netMap["ingress"]; ok { - n.ingress = v.(bool) - } - if v, ok := netMap["configOnly"]; ok { - n.configOnly = v.(bool) - } - if v, ok := netMap["configFrom"]; ok { - n.configFrom = v.(string) - } - if v, ok := netMap["loadBalancerIP"]; ok { - n.loadBalancerIP = net.ParseIP(v.(string)) - } - n.loadBalancerMode = loadBalancerModeDefault - if v, ok := netMap["loadBalancerMode"]; ok { - n.loadBalancerMode = v.(string) - } - // Reconcile old networks with the recently added `--ipv6` flag - if !n.enableIPv6 { - n.enableIPv6 = len(n.ipamV6Info) > 0 - } - return nil -} - -// NetworkOption is an option setter function type used to pass various options to -// NewNetwork method. The various setter functions of type NetworkOption are -// provided by libnetwork, they look like NetworkOptionXXXX(...) -type NetworkOption func(n *network) - -// NetworkOptionGeneric function returns an option setter for a Generic option defined -// in a Dictionary of Key-Value pair -func NetworkOptionGeneric(generic map[string]interface{}) NetworkOption { - return func(n *network) { - if n.generic == nil { - n.generic = make(map[string]interface{}) - } - if val, ok := generic[netlabel.EnableIPv6]; ok { - n.enableIPv6 = val.(bool) - } - if val, ok := generic[netlabel.Internal]; ok { - n.internal = val.(bool) - } - for k, v := range generic { - n.generic[k] = v - } - } -} - -// NetworkOptionIngress returns an option setter to indicate if a network is -// an ingress network. -func NetworkOptionIngress(ingress bool) NetworkOption { - return func(n *network) { - n.ingress = ingress - } -} - -// NetworkOptionPersist returns an option setter to set persistence policy for a network -func NetworkOptionPersist(persist bool) NetworkOption { - return func(n *network) { - n.persist = persist - } -} - -// NetworkOptionEnableIPv6 returns an option setter to explicitly configure IPv6 -func NetworkOptionEnableIPv6(enableIPv6 bool) NetworkOption { - return func(n *network) { - if n.generic == nil { - n.generic = make(map[string]interface{}) - } - n.enableIPv6 = enableIPv6 - n.generic[netlabel.EnableIPv6] = enableIPv6 - } -} - -// NetworkOptionInternalNetwork returns an option setter to config the network -// to be internal which disables default gateway service -func NetworkOptionInternalNetwork() NetworkOption { - return func(n *network) { - if n.generic == nil { - n.generic = make(map[string]interface{}) - } - n.internal = true - n.generic[netlabel.Internal] = true - } -} - -// NetworkOptionAttachable returns an option setter to set attachable for a network -func NetworkOptionAttachable(attachable bool) NetworkOption { - return func(n *network) { - n.attachable = attachable - } -} - -// NetworkOptionScope returns an option setter to overwrite the network's scope. -// By default the network's scope is set to the network driver's datascope. -func NetworkOptionScope(scope string) NetworkOption { - return func(n *network) { - n.scope = scope - } -} - -// NetworkOptionIpam function returns an option setter for the ipam configuration for this network -func NetworkOptionIpam(ipamDriver string, addrSpace string, ipV4 []*IpamConf, ipV6 []*IpamConf, opts map[string]string) NetworkOption { - return func(n *network) { - if ipamDriver != "" { - n.ipamType = ipamDriver - if ipamDriver == ipamapi.DefaultIPAM { - n.ipamType = defaultIpamForNetworkType(n.Type()) - } - } - n.ipamOptions = opts - n.addrSpace = addrSpace - n.ipamV4Config = ipV4 - n.ipamV6Config = ipV6 - } -} - -// NetworkOptionLBEndpoint function returns an option setter for the configuration of the load balancer endpoint for this network -func NetworkOptionLBEndpoint(ip net.IP) NetworkOption { - return func(n *network) { - n.loadBalancerIP = ip - } -} - -// NetworkOptionDriverOpts function returns an option setter for any driver parameter described by a map -func NetworkOptionDriverOpts(opts map[string]string) NetworkOption { - return func(n *network) { - if n.generic == nil { - n.generic = make(map[string]interface{}) - } - if opts == nil { - opts = make(map[string]string) - } - // Store the options - n.generic[netlabel.GenericData] = opts - } -} - -// NetworkOptionLabels function returns an option setter for labels specific to a network -func NetworkOptionLabels(labels map[string]string) NetworkOption { - return func(n *network) { - n.labels = labels - } -} - -// NetworkOptionDynamic function returns an option setter for dynamic option for a network -func NetworkOptionDynamic() NetworkOption { - return func(n *network) { - n.dynamic = true - } -} - -// NetworkOptionDeferIPv6Alloc instructs the network to defer the IPV6 address allocation until after the endpoint has been created -// It is being provided to support the specific docker daemon flags where user can deterministically assign an IPv6 address -// to a container as combination of fixed-cidr-v6 + mac-address -// TODO: Remove this option setter once we support endpoint ipam options -func NetworkOptionDeferIPv6Alloc(enable bool) NetworkOption { - return func(n *network) { - n.postIPv6 = enable - } -} - -// NetworkOptionConfigOnly tells controller this network is -// a configuration only network. It serves as a configuration -// for other networks. -func NetworkOptionConfigOnly() NetworkOption { - return func(n *network) { - n.configOnly = true - } -} - -// NetworkOptionConfigFrom tells controller to pick the -// network configuration from a configuration only network -func NetworkOptionConfigFrom(name string) NetworkOption { - return func(n *network) { - n.configFrom = name - } -} - -func (n *network) processOptions(options ...NetworkOption) { - for _, opt := range options { - if opt != nil { - opt(n) - } - } -} - -type networkDeleteParams struct { - rmLBEndpoint bool -} - -// NetworkDeleteOption is a type for optional parameters to pass to the -// network.Delete() function. -type NetworkDeleteOption func(p *networkDeleteParams) - -// NetworkDeleteOptionRemoveLB informs a network.Delete() operation that should -// remove the load balancer endpoint for this network. Note that the Delete() -// method will automatically remove a load balancing endpoint for most networks -// when the network is otherwise empty. However, this does not occur for some -// networks. In particular, networks marked as ingress (which are supposed to -// be more permanent than other overlay networks) won't automatically remove -// the LB endpoint on Delete(). This method allows for explicit removal of -// such networks provided there are no other endpoints present in the network. -// If the network still has non-LB endpoints present, Delete() will not -// remove the LB endpoint and will return an error. -func NetworkDeleteOptionRemoveLB(p *networkDeleteParams) { - p.rmLBEndpoint = true -} - -func (n *network) resolveDriver(name string, load bool) (driverapi.Driver, *driverapi.Capability, error) { - c := n.getController() - - // Check if a driver for the specified network type is available - d, cap := c.drvRegistry.Driver(name) - if d == nil { - if load { - err := c.loadDriver(name) - if err != nil { - return nil, nil, err - } - - d, cap = c.drvRegistry.Driver(name) - if d == nil { - return nil, nil, fmt.Errorf("could not resolve driver %s in registry", name) - } - } else { - // don't fail if driver loading is not required - return nil, nil, nil - } - } - - return d, cap, nil -} - -func (n *network) driverScope() string { - _, cap, err := n.resolveDriver(n.networkType, true) - if err != nil { - // If driver could not be resolved simply return an empty string - return "" - } - - return cap.DataScope -} - -func (n *network) driverIsMultihost() bool { - _, cap, err := n.resolveDriver(n.networkType, true) - if err != nil { - return false - } - return cap.ConnectivityScope == datastore.GlobalScope -} - -func (n *network) driver(load bool) (driverapi.Driver, error) { - d, cap, err := n.resolveDriver(n.networkType, load) - if err != nil { - return nil, err - } - - n.Lock() - // If load is not required, driver, cap and err may all be nil - if n.scope == "" && cap != nil { - n.scope = cap.DataScope - } - if n.dynamic { - // If the network is dynamic, then it is swarm - // scoped regardless of the backing driver. - n.scope = datastore.SwarmScope - } - n.Unlock() - return d, nil -} - -func (n *network) Delete(options ...NetworkDeleteOption) error { - var params networkDeleteParams - for _, opt := range options { - opt(¶ms) - } - return n.delete(false, params.rmLBEndpoint) -} - -// This function gets called in 3 ways: -// * Delete() -- (false, false) -// remove if endpoint count == 0 or endpoint count == 1 and -// there is a load balancer IP -// * Delete(libnetwork.NetworkDeleteOptionRemoveLB) -- (false, true) -// remove load balancer and network if endpoint count == 1 -// * controller.networkCleanup() -- (true, true) -// remove the network no matter what -func (n *network) delete(force bool, rmLBEndpoint bool) error { - n.Lock() - c := n.ctrlr - name := n.name - id := n.id - n.Unlock() - - c.networkLocker.Lock(id) - defer c.networkLocker.Unlock(id) - - n, err := c.getNetworkFromStore(id) - if err != nil { - return &UnknownNetworkError{name: name, id: id} - } - - // Only remove ingress on force removal or explicit LB endpoint removal - if n.ingress && !force && !rmLBEndpoint { - return &ActiveEndpointsError{name: n.name, id: n.id} - } - - // Check that the network is empty - var emptyCount uint64 - if n.hasLoadBalancerEndpoint() { - emptyCount = 1 - } - if !force && n.getEpCnt().EndpointCnt() > emptyCount { - if n.configOnly { - return types.ForbiddenErrorf("configuration network %q is in use", n.Name()) - } - return &ActiveEndpointsError{name: n.name, id: n.id} - } - - if n.hasLoadBalancerEndpoint() { - // If we got to this point, then the following must hold: - // * force is true OR endpoint count == 1 - if err := n.deleteLoadBalancerSandbox(); err != nil { - if !force { - return err - } - // continue deletion when force is true even on error - logrus.Warnf("Error deleting load balancer sandbox: %v", err) - } - //Reload the network from the store to update the epcnt. - n, err = c.getNetworkFromStore(id) - if err != nil { - return &UnknownNetworkError{name: name, id: id} - } - } - - // Up to this point, errors that we returned were recoverable. - // From here on, any errors leave us in an inconsistent state. - // This is unfortunate, but there isn't a safe way to - // reconstitute a load-balancer endpoint after removing it. - - // Mark the network for deletion - n.inDelete = true - if err = c.updateToStore(n); err != nil { - return fmt.Errorf("error marking network %s (%s) for deletion: %v", n.Name(), n.ID(), err) - } - - if n.ConfigFrom() != "" { - if t, err := c.getConfigNetwork(n.ConfigFrom()); err == nil { - if err := t.getEpCnt().DecEndpointCnt(); err != nil { - logrus.Warnf("Failed to update reference count for configuration network %q on removal of network %q: %v", - t.Name(), n.Name(), err) - } - } else { - logrus.Warnf("Could not find configuration network %q during removal of network %q", n.configFrom, n.Name()) - } - } - - if n.configOnly { - goto removeFromStore - } - - if err = n.deleteNetwork(); err != nil { - if !force { - return err - } - logrus.Debugf("driver failed to delete stale network %s (%s): %v", n.Name(), n.ID(), err) - } - - n.ipamRelease() - if err = c.updateToStore(n); err != nil { - logrus.Warnf("Failed to update store after ipam release for network %s (%s): %v", n.Name(), n.ID(), err) - } - - // We are about to delete the network. Leave the gossip - // cluster for the network to stop all incoming network - // specific gossip updates before cleaning up all the service - // bindings for the network. But cleanup service binding - // before deleting the network from the store since service - // bindings cleanup requires the network in the store. - n.cancelDriverWatches() - if err = n.leaveCluster(); err != nil { - logrus.Errorf("Failed leaving network %s from the agent cluster: %v", n.Name(), err) - } - - // Cleanup the service discovery for this network - c.cleanupServiceDiscovery(n.ID()) - - // Cleanup the load balancer. On Windows this call is required - // to remove remote loadbalancers in VFP. - c.cleanupServiceBindings(n.ID()) - -removeFromStore: - // deleteFromStore performs an atomic delete operation and the - // network.epCnt will help prevent any possible - // race between endpoint join and network delete - if err = c.deleteFromStore(n.getEpCnt()); err != nil { - if !force { - return fmt.Errorf("error deleting network endpoint count from store: %v", err) - } - logrus.Debugf("Error deleting endpoint count from store for stale network %s (%s) for deletion: %v", n.Name(), n.ID(), err) - } - - if err = c.deleteFromStore(n); err != nil { - return fmt.Errorf("error deleting network from store: %v", err) - } - - return nil -} - -func (n *network) deleteNetwork() error { - d, err := n.driver(true) - if err != nil { - return fmt.Errorf("failed deleting network: %v", err) - } - - if err := d.DeleteNetwork(n.ID()); err != nil { - // Forbidden Errors should be honored - if _, ok := err.(types.ForbiddenError); ok { - return err - } - - if _, ok := err.(types.MaskableError); !ok { - logrus.Warnf("driver error deleting network %s : %v", n.name, err) - } - } - - for _, resolver := range n.resolver { - resolver.Stop() - } - return nil -} - -func (n *network) addEndpoint(ep *endpoint) error { - d, err := n.driver(true) - if err != nil { - return fmt.Errorf("failed to add endpoint: %v", err) - } - - err = d.CreateEndpoint(n.id, ep.id, ep.Interface(), ep.generic) - if err != nil { - return types.InternalErrorf("failed to create endpoint %s on network %s: %v", - ep.Name(), n.Name(), err) - } - - return nil -} - -func (n *network) CreateEndpoint(name string, options ...EndpointOption) (Endpoint, error) { - var err error - if !config.IsValidName(name) { - return nil, ErrInvalidName(name) - } - - if n.ConfigOnly() { - return nil, types.ForbiddenErrorf("cannot create endpoint on configuration-only network") - } - - if _, err = n.EndpointByName(name); err == nil { - return nil, types.ForbiddenErrorf("endpoint with name %s already exists in network %s", name, n.Name()) - } - - n.ctrlr.networkLocker.Lock(n.id) - defer n.ctrlr.networkLocker.Unlock(n.id) - - return n.createEndpoint(name, options...) - -} - -func (n *network) createEndpoint(name string, options ...EndpointOption) (Endpoint, error) { - var err error - - ep := &endpoint{name: name, generic: make(map[string]interface{}), iface: &endpointInterface{}} - ep.id = stringid.GenerateRandomID() - - // Initialize ep.network with a possibly stale copy of n. We need this to get network from - // store. But once we get it from store we will have the most uptodate copy possibly. - ep.network = n - ep.locator = n.getController().clusterHostID() - ep.network, err = ep.getNetworkFromStore() - if err != nil { - logrus.Errorf("failed to get network during CreateEndpoint: %v", err) - return nil, err - } - n = ep.network - - ep.processOptions(options...) - - for _, llIPNet := range ep.Iface().LinkLocalAddresses() { - if !llIPNet.IP.IsLinkLocalUnicast() { - return nil, types.BadRequestErrorf("invalid link local IP address: %v", llIPNet.IP) - } - } - - if opt, ok := ep.generic[netlabel.MacAddress]; ok { - if mac, ok := opt.(net.HardwareAddr); ok { - ep.iface.mac = mac - } - } - - ipam, cap, err := n.getController().getIPAMDriver(n.ipamType) - if err != nil { - return nil, err - } - - if cap.RequiresMACAddress { - if ep.iface.mac == nil { - ep.iface.mac = netutils.GenerateRandomMAC() - } - if ep.ipamOptions == nil { - ep.ipamOptions = make(map[string]string) - } - ep.ipamOptions[netlabel.MacAddress] = ep.iface.mac.String() - } - - if err = ep.assignAddress(ipam, true, n.enableIPv6 && !n.postIPv6); err != nil { - return nil, err - } - defer func() { - if err != nil { - ep.releaseAddress() - } - }() - - if err = n.addEndpoint(ep); err != nil { - return nil, err - } - defer func() { - if err != nil { - if e := ep.deleteEndpoint(false); e != nil { - logrus.Warnf("cleaning up endpoint failed %s : %v", name, e) - } - } - }() - - // We should perform updateToStore call right after addEndpoint - // in order to have iface properly configured - if err = n.getController().updateToStore(ep); err != nil { - return nil, err - } - defer func() { - if err != nil { - if e := n.getController().deleteFromStore(ep); e != nil { - logrus.Warnf("error rolling back endpoint %s from store: %v", name, e) - } - } - }() - - if err = ep.assignAddress(ipam, false, n.enableIPv6 && n.postIPv6); err != nil { - return nil, err - } - - // Watch for service records - n.getController().watchSvcRecord(ep) - defer func() { - if err != nil { - n.getController().unWatchSvcRecord(ep) - } - }() - - // Increment endpoint count to indicate completion of endpoint addition - if err = n.getEpCnt().IncEndpointCnt(); err != nil { - return nil, err - } - - return ep, nil -} - -func (n *network) Endpoints() []Endpoint { - var list []Endpoint - - endpoints, err := n.getEndpointsFromStore() - if err != nil { - logrus.Error(err) - } - - for _, ep := range endpoints { - list = append(list, ep) - } - - return list -} - -func (n *network) WalkEndpoints(walker EndpointWalker) { - for _, e := range n.Endpoints() { - if walker(e) { - return - } - } -} - -func (n *network) EndpointByName(name string) (Endpoint, error) { - if name == "" { - return nil, ErrInvalidName(name) - } - var e Endpoint - - s := func(current Endpoint) bool { - if current.Name() == name { - e = current - return true - } - return false - } - - n.WalkEndpoints(s) - - if e == nil { - return nil, ErrNoSuchEndpoint(name) - } - - return e, nil -} - -func (n *network) EndpointByID(id string) (Endpoint, error) { - if id == "" { - return nil, ErrInvalidID(id) - } - - ep, err := n.getEndpointFromStore(id) - if err != nil { - return nil, ErrNoSuchEndpoint(id) - } - - return ep, nil -} - -func (n *network) updateSvcRecord(ep *endpoint, localEps []*endpoint, isAdd bool) { - var ipv6 net.IP - epName := ep.Name() - if iface := ep.Iface(); iface != nil && iface.Address() != nil { - myAliases := ep.MyAliases() - if iface.AddressIPv6() != nil { - ipv6 = iface.AddressIPv6().IP - } - - serviceID := ep.svcID - if serviceID == "" { - serviceID = ep.ID() - } - if isAdd { - // If anonymous endpoint has an alias use the first alias - // for ip->name mapping. Not having the reverse mapping - // breaks some apps - if ep.isAnonymous() { - if len(myAliases) > 0 { - n.addSvcRecords(ep.ID(), myAliases[0], serviceID, iface.Address().IP, ipv6, true, "updateSvcRecord") - } - } else { - n.addSvcRecords(ep.ID(), epName, serviceID, iface.Address().IP, ipv6, true, "updateSvcRecord") - } - for _, alias := range myAliases { - n.addSvcRecords(ep.ID(), alias, serviceID, iface.Address().IP, ipv6, false, "updateSvcRecord") - } - } else { - if ep.isAnonymous() { - if len(myAliases) > 0 { - n.deleteSvcRecords(ep.ID(), myAliases[0], serviceID, iface.Address().IP, ipv6, true, "updateSvcRecord") - } - } else { - n.deleteSvcRecords(ep.ID(), epName, serviceID, iface.Address().IP, ipv6, true, "updateSvcRecord") - } - for _, alias := range myAliases { - n.deleteSvcRecords(ep.ID(), alias, serviceID, iface.Address().IP, ipv6, false, "updateSvcRecord") - } - } - } -} - -func addIPToName(ipMap setmatrix.SetMatrix, name, serviceID string, ip net.IP) { - reverseIP := netutils.ReverseIP(ip.String()) - ipMap.Insert(reverseIP, ipInfo{ - name: name, - serviceID: serviceID, - }) -} - -func delIPToName(ipMap setmatrix.SetMatrix, name, serviceID string, ip net.IP) { - reverseIP := netutils.ReverseIP(ip.String()) - ipMap.Remove(reverseIP, ipInfo{ - name: name, - serviceID: serviceID, - }) -} - -func addNameToIP(svcMap setmatrix.SetMatrix, name, serviceID string, epIP net.IP) { - // Since DNS name resolution is case-insensitive, Use the lower-case form - // of the name as the key into svcMap - lowerCaseName := strings.ToLower(name) - svcMap.Insert(lowerCaseName, svcMapEntry{ - ip: epIP.String(), - serviceID: serviceID, - }) -} - -func delNameToIP(svcMap setmatrix.SetMatrix, name, serviceID string, epIP net.IP) { - lowerCaseName := strings.ToLower(name) - svcMap.Remove(lowerCaseName, svcMapEntry{ - ip: epIP.String(), - serviceID: serviceID, - }) -} - -func (n *network) addSvcRecords(eID, name, serviceID string, epIP, epIPv6 net.IP, ipMapUpdate bool, method string) { - // Do not add service names for ingress network as this is a - // routing only network - if n.ingress { - return - } - networkID := n.ID() - logrus.Debugf("%s (%.7s).addSvcRecords(%s, %s, %s, %t) %s sid:%s", eID, networkID, name, epIP, epIPv6, ipMapUpdate, method, serviceID) - - c := n.getController() - c.Lock() - defer c.Unlock() - - sr, ok := c.svcRecords[networkID] - if !ok { - sr = svcInfo{ - svcMap: setmatrix.NewSetMatrix(), - svcIPv6Map: setmatrix.NewSetMatrix(), - ipMap: setmatrix.NewSetMatrix(), - } - c.svcRecords[networkID] = sr - } - - if ipMapUpdate { - addIPToName(sr.ipMap, name, serviceID, epIP) - if epIPv6 != nil { - addIPToName(sr.ipMap, name, serviceID, epIPv6) - } - } - - addNameToIP(sr.svcMap, name, serviceID, epIP) - if epIPv6 != nil { - addNameToIP(sr.svcIPv6Map, name, serviceID, epIPv6) - } -} - -func (n *network) deleteSvcRecords(eID, name, serviceID string, epIP net.IP, epIPv6 net.IP, ipMapUpdate bool, method string) { - // Do not delete service names from ingress network as this is a - // routing only network - if n.ingress { - return - } - networkID := n.ID() - logrus.Debugf("%s (%.7s).deleteSvcRecords(%s, %s, %s, %t) %s sid:%s ", eID, networkID, name, epIP, epIPv6, ipMapUpdate, method, serviceID) - - c := n.getController() - c.Lock() - defer c.Unlock() - - sr, ok := c.svcRecords[networkID] - if !ok { - return - } - - if ipMapUpdate { - delIPToName(sr.ipMap, name, serviceID, epIP) - - if epIPv6 != nil { - delIPToName(sr.ipMap, name, serviceID, epIPv6) - } - } - - delNameToIP(sr.svcMap, name, serviceID, epIP) - - if epIPv6 != nil { - delNameToIP(sr.svcIPv6Map, name, serviceID, epIPv6) - } -} - -func (n *network) getSvcRecords(ep *endpoint) []etchosts.Record { - n.Lock() - defer n.Unlock() - - if ep == nil { - return nil - } - - var recs []etchosts.Record - - epName := ep.Name() - - n.ctrlr.Lock() - defer n.ctrlr.Unlock() - sr, ok := n.ctrlr.svcRecords[n.id] - if !ok || sr.svcMap == nil { - return nil - } - - svcMapKeys := sr.svcMap.Keys() - // Loop on service names on this network - for _, k := range svcMapKeys { - if strings.Split(k, ".")[0] == epName { - continue - } - // Get all the IPs associated to this service - mapEntryList, ok := sr.svcMap.Get(k) - if !ok { - // The key got deleted - continue - } - if len(mapEntryList) == 0 { - logrus.Warnf("Found empty list of IP addresses for service %s on network %s (%s)", k, n.name, n.id) - continue - } - - recs = append(recs, etchosts.Record{ - Hosts: k, - IP: mapEntryList[0].(svcMapEntry).ip, - }) - } - - return recs -} - -func (n *network) getController() *controller { - n.Lock() - defer n.Unlock() - return n.ctrlr -} - -func (n *network) ipamAllocate() error { - if n.hasSpecialDriver() { - return nil - } - - ipam, _, err := n.getController().getIPAMDriver(n.ipamType) - if err != nil { - return err - } - - if n.addrSpace == "" { - if n.addrSpace, err = n.deriveAddressSpace(); err != nil { - return err - } - } - - err = n.ipamAllocateVersion(4, ipam) - if err != nil { - return err - } - - defer func() { - if err != nil { - n.ipamReleaseVersion(4, ipam) - } - }() - - if !n.enableIPv6 { - return nil - } - - err = n.ipamAllocateVersion(6, ipam) - return err -} - -func (n *network) requestPoolHelper(ipam ipamapi.Ipam, addressSpace, preferredPool, subPool string, options map[string]string, v6 bool) (string, *net.IPNet, map[string]string, error) { - for { - poolID, pool, meta, err := ipam.RequestPool(addressSpace, preferredPool, subPool, options, v6) - if err != nil { - return "", nil, nil, err - } - - // If the network belongs to global scope or the pool was - // explicitly chosen or it is invalid, do not perform the overlap check. - if n.Scope() == datastore.GlobalScope || preferredPool != "" || !types.IsIPNetValid(pool) { - return poolID, pool, meta, nil - } - - // Check for overlap and if none found, we have found the right pool. - if _, err := netutils.FindAvailableNetwork([]*net.IPNet{pool}); err == nil { - return poolID, pool, meta, nil - } - - // Pool obtained in this iteration is - // overlapping. Hold onto the pool and don't release - // it yet, because we don't want ipam to give us back - // the same pool over again. But make sure we still do - // a deferred release when we have either obtained a - // non-overlapping pool or ran out of pre-defined - // pools. - defer func() { - if err := ipam.ReleasePool(poolID); err != nil { - logrus.Warnf("Failed to release overlapping pool %s while returning from pool request helper for network %s", pool, n.Name()) - } - }() - - // If this is a preferred pool request and the network - // is local scope and there is an overlap, we fail the - // network creation right here. The pool will be - // released in the defer. - if preferredPool != "" { - return "", nil, nil, fmt.Errorf("requested subnet %s overlaps in the host", preferredPool) - } - } -} - -func (n *network) ipamAllocateVersion(ipVer int, ipam ipamapi.Ipam) error { - var ( - cfgList *[]*IpamConf - infoList *[]*IpamInfo - err error - ) - - switch ipVer { - case 4: - cfgList = &n.ipamV4Config - infoList = &n.ipamV4Info - case 6: - cfgList = &n.ipamV6Config - infoList = &n.ipamV6Info - default: - return types.InternalErrorf("incorrect ip version passed to ipam allocate: %d", ipVer) - } - - if len(*cfgList) == 0 { - *cfgList = []*IpamConf{{}} - } - - *infoList = make([]*IpamInfo, len(*cfgList)) - - logrus.Debugf("Allocating IPv%d pools for network %s (%s)", ipVer, n.Name(), n.ID()) - - for i, cfg := range *cfgList { - if err = cfg.Validate(); err != nil { - return err - } - d := &IpamInfo{} - (*infoList)[i] = d - - d.AddressSpace = n.addrSpace - d.PoolID, d.Pool, d.Meta, err = n.requestPoolHelper(ipam, n.addrSpace, cfg.PreferredPool, cfg.SubPool, n.ipamOptions, ipVer == 6) - if err != nil { - return err - } - - defer func() { - if err != nil { - if err := ipam.ReleasePool(d.PoolID); err != nil { - logrus.Warnf("Failed to release address pool %s after failure to create network %s (%s)", d.PoolID, n.Name(), n.ID()) - } - } - }() - - if gws, ok := d.Meta[netlabel.Gateway]; ok { - if d.Gateway, err = types.ParseCIDR(gws); err != nil { - return types.BadRequestErrorf("failed to parse gateway address (%v) returned by ipam driver: %v", gws, err) - } - } - - // If user requested a specific gateway, libnetwork will allocate it - // irrespective of whether ipam driver returned a gateway already. - // If none of the above is true, libnetwork will allocate one. - if cfg.Gateway != "" || d.Gateway == nil { - var gatewayOpts = map[string]string{ - ipamapi.RequestAddressType: netlabel.Gateway, - } - if d.Gateway, _, err = ipam.RequestAddress(d.PoolID, net.ParseIP(cfg.Gateway), gatewayOpts); err != nil { - return types.InternalErrorf("failed to allocate gateway (%v): %v", cfg.Gateway, err) - } - } - - // Auxiliary addresses must be part of the master address pool - // If they fall into the container addressable pool, libnetwork will reserve them - if cfg.AuxAddresses != nil { - var ip net.IP - d.IPAMData.AuxAddresses = make(map[string]*net.IPNet, len(cfg.AuxAddresses)) - for k, v := range cfg.AuxAddresses { - if ip = net.ParseIP(v); ip == nil { - return types.BadRequestErrorf("non parsable secondary ip address (%s:%s) passed for network %s", k, v, n.Name()) - } - if !d.Pool.Contains(ip) { - return types.ForbiddenErrorf("auxiliary address: (%s:%s) must belong to the master pool: %s", k, v, d.Pool) - } - // Attempt reservation in the container addressable pool, silent the error if address does not belong to that pool - if d.IPAMData.AuxAddresses[k], _, err = ipam.RequestAddress(d.PoolID, ip, nil); err != nil && err != ipamapi.ErrIPOutOfRange { - return types.InternalErrorf("failed to allocate secondary ip address (%s:%s): %v", k, v, err) - } - } - } - } - - return nil -} - -func (n *network) ipamRelease() { - if n.hasSpecialDriver() { - return - } - ipam, _, err := n.getController().getIPAMDriver(n.ipamType) - if err != nil { - logrus.Warnf("Failed to retrieve ipam driver to release address pool(s) on delete of network %s (%s): %v", n.Name(), n.ID(), err) - return - } - n.ipamReleaseVersion(4, ipam) - n.ipamReleaseVersion(6, ipam) -} - -func (n *network) ipamReleaseVersion(ipVer int, ipam ipamapi.Ipam) { - var infoList *[]*IpamInfo - - switch ipVer { - case 4: - infoList = &n.ipamV4Info - case 6: - infoList = &n.ipamV6Info - default: - logrus.Warnf("incorrect ip version passed to ipam release: %d", ipVer) - return - } - - if len(*infoList) == 0 { - return - } - - logrus.Debugf("releasing IPv%d pools from network %s (%s)", ipVer, n.Name(), n.ID()) - - for _, d := range *infoList { - if d.Gateway != nil { - if err := ipam.ReleaseAddress(d.PoolID, d.Gateway.IP); err != nil { - logrus.Warnf("Failed to release gateway ip address %s on delete of network %s (%s): %v", d.Gateway.IP, n.Name(), n.ID(), err) - } - } - if d.IPAMData.AuxAddresses != nil { - for k, nw := range d.IPAMData.AuxAddresses { - if d.Pool.Contains(nw.IP) { - if err := ipam.ReleaseAddress(d.PoolID, nw.IP); err != nil && err != ipamapi.ErrIPOutOfRange { - logrus.Warnf("Failed to release secondary ip address %s (%v) on delete of network %s (%s): %v", k, nw.IP, n.Name(), n.ID(), err) - } - } - } - } - if err := ipam.ReleasePool(d.PoolID); err != nil { - logrus.Warnf("Failed to release address pool %s on delete of network %s (%s): %v", d.PoolID, n.Name(), n.ID(), err) - } - } - - *infoList = nil -} - -func (n *network) getIPInfo(ipVer int) []*IpamInfo { - var info []*IpamInfo - switch ipVer { - case 4: - info = n.ipamV4Info - case 6: - info = n.ipamV6Info - default: - return nil - } - l := make([]*IpamInfo, 0, len(info)) - n.Lock() - l = append(l, info...) - n.Unlock() - return l -} - -func (n *network) getIPData(ipVer int) []driverapi.IPAMData { - var info []*IpamInfo - switch ipVer { - case 4: - info = n.ipamV4Info - case 6: - info = n.ipamV6Info - default: - return nil - } - l := make([]driverapi.IPAMData, 0, len(info)) - n.Lock() - for _, d := range info { - l = append(l, d.IPAMData) - } - n.Unlock() - return l -} - -func (n *network) deriveAddressSpace() (string, error) { - local, global, err := n.getController().drvRegistry.IPAMDefaultAddressSpaces(n.ipamType) - if err != nil { - return "", types.NotFoundErrorf("failed to get default address space: %v", err) - } - if n.DataScope() == datastore.GlobalScope { - return global, nil - } - return local, nil -} - -func (n *network) Info() NetworkInfo { - return n -} - -func (n *network) Peers() []networkdb.PeerInfo { - if !n.Dynamic() { - return []networkdb.PeerInfo{} - } - - agent := n.getController().getAgent() - if agent == nil { - return []networkdb.PeerInfo{} - } - - return agent.networkDB.Peers(n.ID()) -} - -func (n *network) DriverOptions() map[string]string { - n.Lock() - defer n.Unlock() - if n.generic != nil { - if m, ok := n.generic[netlabel.GenericData]; ok { - return m.(map[string]string) - } - } - return map[string]string{} -} - -func (n *network) Scope() string { - n.Lock() - defer n.Unlock() - return n.scope -} - -func (n *network) IpamConfig() (string, map[string]string, []*IpamConf, []*IpamConf) { - n.Lock() - defer n.Unlock() - - v4L := make([]*IpamConf, len(n.ipamV4Config)) - v6L := make([]*IpamConf, len(n.ipamV6Config)) - - for i, c := range n.ipamV4Config { - cc := &IpamConf{} - c.CopyTo(cc) - v4L[i] = cc - } - - for i, c := range n.ipamV6Config { - cc := &IpamConf{} - c.CopyTo(cc) - v6L[i] = cc - } - - return n.ipamType, n.ipamOptions, v4L, v6L -} - -func (n *network) IpamInfo() ([]*IpamInfo, []*IpamInfo) { - n.Lock() - defer n.Unlock() - - v4Info := make([]*IpamInfo, len(n.ipamV4Info)) - v6Info := make([]*IpamInfo, len(n.ipamV6Info)) - - for i, info := range n.ipamV4Info { - ic := &IpamInfo{} - info.CopyTo(ic) - v4Info[i] = ic - } - - for i, info := range n.ipamV6Info { - ic := &IpamInfo{} - info.CopyTo(ic) - v6Info[i] = ic - } - - return v4Info, v6Info -} - -func (n *network) Internal() bool { - n.Lock() - defer n.Unlock() - - return n.internal -} - -func (n *network) Attachable() bool { - n.Lock() - defer n.Unlock() - - return n.attachable -} - -func (n *network) Ingress() bool { - n.Lock() - defer n.Unlock() - - return n.ingress -} - -func (n *network) Dynamic() bool { - n.Lock() - defer n.Unlock() - - return n.dynamic -} - -func (n *network) IPv6Enabled() bool { - n.Lock() - defer n.Unlock() - - return n.enableIPv6 -} - -func (n *network) ConfigFrom() string { - n.Lock() - defer n.Unlock() - - return n.configFrom -} - -func (n *network) ConfigOnly() bool { - n.Lock() - defer n.Unlock() - - return n.configOnly -} - -func (n *network) Labels() map[string]string { - n.Lock() - defer n.Unlock() - - var lbls = make(map[string]string, len(n.labels)) - for k, v := range n.labels { - lbls[k] = v - } - - return lbls -} - -func (n *network) TableEventRegister(tableName string, objType driverapi.ObjectType) error { - if !driverapi.IsValidType(objType) { - return fmt.Errorf("invalid object type %v in registering table, %s", objType, tableName) - } - - t := networkDBTable{ - name: tableName, - objType: objType, - } - n.Lock() - defer n.Unlock() - n.driverTables = append(n.driverTables, t) - return nil -} - -func (n *network) UpdateIpamConfig(ipV4Data []driverapi.IPAMData) { - - ipamV4Config := make([]*IpamConf, len(ipV4Data)) - - for i, data := range ipV4Data { - ic := &IpamConf{} - ic.PreferredPool = data.Pool.String() - ic.Gateway = data.Gateway.IP.String() - ipamV4Config[i] = ic - } - - n.Lock() - defer n.Unlock() - n.ipamV4Config = ipamV4Config -} - -// Special drivers are ones which do not need to perform any network plumbing -func (n *network) hasSpecialDriver() bool { - return n.Type() == "host" || n.Type() == "null" -} - -func (n *network) hasLoadBalancerEndpoint() bool { - return len(n.loadBalancerIP) != 0 -} - -func (n *network) ResolveName(req string, ipType int) ([]net.IP, bool) { - var ipv6Miss bool - - c := n.getController() - networkID := n.ID() - c.Lock() - defer c.Unlock() - sr, ok := c.svcRecords[networkID] - - if !ok { - return nil, false - } - - req = strings.TrimSuffix(req, ".") - req = strings.ToLower(req) - ipSet, ok := sr.svcMap.Get(req) - - if ipType == types.IPv6 { - // If the name resolved to v4 address then its a valid name in - // the docker network domain. If the network is not v6 enabled - // set ipv6Miss to filter the DNS query from going to external - // resolvers. - if ok && !n.enableIPv6 { - ipv6Miss = true - } - ipSet, ok = sr.svcIPv6Map.Get(req) - } - - if ok && len(ipSet) > 0 { - // this map is to avoid IP duplicates, this can happen during a transition period where 2 services are using the same IP - noDup := make(map[string]bool) - var ipLocal []net.IP - for _, ip := range ipSet { - if _, dup := noDup[ip.(svcMapEntry).ip]; !dup { - noDup[ip.(svcMapEntry).ip] = true - ipLocal = append(ipLocal, net.ParseIP(ip.(svcMapEntry).ip)) - } - } - return ipLocal, ok - } - - return nil, ipv6Miss -} - -func (n *network) HandleQueryResp(name string, ip net.IP) { - networkID := n.ID() - c := n.getController() - c.Lock() - defer c.Unlock() - sr, ok := c.svcRecords[networkID] - - if !ok { - return - } - - ipStr := netutils.ReverseIP(ip.String()) - // If an object with extResolver == true is already in the set this call will fail - // but anyway it means that has already been inserted before - if ok, _ := sr.ipMap.Contains(ipStr, ipInfo{name: name}); ok { - sr.ipMap.Remove(ipStr, ipInfo{name: name}) - sr.ipMap.Insert(ipStr, ipInfo{name: name, extResolver: true}) - } -} - -func (n *network) ResolveIP(ip string) string { - networkID := n.ID() - c := n.getController() - c.Lock() - defer c.Unlock() - sr, ok := c.svcRecords[networkID] - - if !ok { - return "" - } - - nwName := n.Name() - - elemSet, ok := sr.ipMap.Get(ip) - if !ok || len(elemSet) == 0 { - return "" - } - // NOTE it is possible to have more than one element in the Set, this will happen - // because of interleave of different events from different sources (local container create vs - // network db notifications) - // In such cases the resolution will be based on the first element of the set, and can vary - // during the system stabilitation - elem, ok := elemSet[0].(ipInfo) - if !ok { - setStr, b := sr.ipMap.String(ip) - logrus.Errorf("expected set of ipInfo type for key %s set:%t %s", ip, b, setStr) - return "" - } - - if elem.extResolver { - return "" - } - - return elem.name + "." + nwName -} - -func (n *network) ResolveService(name string) ([]*net.SRV, []net.IP) { - c := n.getController() - - srv := []*net.SRV{} - ip := []net.IP{} - - logrus.Debugf("Service name To resolve: %v", name) - - // There are DNS implementations that allow SRV queries for names not in - // the format defined by RFC 2782. Hence specific validations checks are - // not done - parts := strings.Split(name, ".") - if len(parts) < 3 { - return nil, nil - } - - portName := parts[0] - proto := parts[1] - svcName := strings.Join(parts[2:], ".") - - networkID := n.ID() - c.Lock() - defer c.Unlock() - sr, ok := c.svcRecords[networkID] - - if !ok { - return nil, nil - } - - svcs, ok := sr.service[svcName] - if !ok { - return nil, nil - } - - for _, svc := range svcs { - if svc.portName != portName { - continue - } - if svc.proto != proto { - continue - } - for _, t := range svc.target { - srv = append(srv, - &net.SRV{ - Target: t.name, - Port: t.port, - }) - - ip = append(ip, t.ip) - } - } - - return srv, ip -} - -func (n *network) ExecFunc(f func()) error { - return types.NotImplementedErrorf("ExecFunc not supported by network") -} - -func (n *network) NdotsSet() bool { - return false -} - -// config-only network is looked up by name -func (c *controller) getConfigNetwork(name string) (*network, error) { - var n Network - - s := func(current Network) bool { - if current.Info().ConfigOnly() && current.Name() == name { - n = current - return true - } - return false - } - - c.WalkNetworks(s) - - if n == nil { - return nil, types.NotFoundErrorf("configuration network %q not found", name) - } - - return n.(*network), nil -} - -func (n *network) lbSandboxName() string { - name := "lb-" + n.name - if n.ingress { - name = n.name + "-sbox" - } - return name -} - -func (n *network) lbEndpointName() string { - return n.name + "-endpoint" -} - -func (n *network) createLoadBalancerSandbox() (retErr error) { - sandboxName := n.lbSandboxName() - // Mark the sandbox to be a load balancer - sbOptions := []SandboxOption{OptionLoadBalancer(n.id)} - if n.ingress { - sbOptions = append(sbOptions, OptionIngress()) - } - sb, err := n.ctrlr.NewSandbox(sandboxName, sbOptions...) - if err != nil { - return err - } - defer func() { - if retErr != nil { - if e := n.ctrlr.SandboxDestroy(sandboxName); e != nil { - logrus.Warnf("could not delete sandbox %s on failure on failure (%v): %v", sandboxName, retErr, e) - } - } - }() - - endpointName := n.lbEndpointName() - epOptions := []EndpointOption{ - CreateOptionIpam(n.loadBalancerIP, nil, nil, nil), - CreateOptionLoadBalancer(), - } - if n.hasLoadBalancerEndpoint() && !n.ingress { - // Mark LB endpoints as anonymous so they don't show up in DNS - epOptions = append(epOptions, CreateOptionAnonymous()) - } - ep, err := n.createEndpoint(endpointName, epOptions...) - if err != nil { - return err - } - defer func() { - if retErr != nil { - if e := ep.Delete(true); e != nil { - logrus.Warnf("could not delete endpoint %s on failure on failure (%v): %v", endpointName, retErr, e) - } - } - }() - - if err := ep.Join(sb, nil); err != nil { - return err - } - - return sb.EnableService() -} - -func (n *network) deleteLoadBalancerSandbox() error { - n.Lock() - c := n.ctrlr - name := n.name - n.Unlock() - - sandboxName := n.lbSandboxName() - endpointName := n.lbEndpointName() - - endpoint, err := n.EndpointByName(endpointName) - if err != nil { - logrus.Warnf("Failed to find load balancer endpoint %s on network %s: %v", endpointName, name, err) - } else { - - info := endpoint.Info() - if info != nil { - sb := info.Sandbox() - if sb != nil { - if err := sb.DisableService(); err != nil { - logrus.Warnf("Failed to disable service on sandbox %s: %v", sandboxName, err) - //Ignore error and attempt to delete the load balancer endpoint - } - } - } - - if err := endpoint.Delete(true); err != nil { - logrus.Warnf("Failed to delete endpoint %s (%s) in %s: %v", endpoint.Name(), endpoint.ID(), sandboxName, err) - //Ignore error and attempt to delete the sandbox. - } - } - - if err := c.SandboxDestroy(sandboxName); err != nil { - return fmt.Errorf("Failed to delete %s sandbox: %v", sandboxName, err) - } - return nil -} diff --git a/vendor/github.com/docker/libnetwork/network_unix.go b/vendor/github.com/docker/libnetwork/network_unix.go deleted file mode 100644 index 585261ece0..0000000000 --- a/vendor/github.com/docker/libnetwork/network_unix.go +++ /dev/null @@ -1,14 +0,0 @@ -// +build !windows - -package libnetwork - -import "github.com/docker/libnetwork/ipamapi" - -// Stub implementations for DNS related functions - -func (n *network) startResolver() { -} - -func defaultIpamForNetworkType(networkType string) string { - return ipamapi.DefaultIPAM -} diff --git a/vendor/github.com/docker/libnetwork/network_windows.go b/vendor/github.com/docker/libnetwork/network_windows.go deleted file mode 100644 index e7819e1c3e..0000000000 --- a/vendor/github.com/docker/libnetwork/network_windows.go +++ /dev/null @@ -1,75 +0,0 @@ -// +build windows - -package libnetwork - -import ( - "runtime" - "time" - - "github.com/Microsoft/hcsshim" - "github.com/docker/libnetwork/drivers/windows" - "github.com/docker/libnetwork/ipamapi" - "github.com/docker/libnetwork/ipams/windowsipam" - "github.com/sirupsen/logrus" -) - -func executeInCompartment(compartmentID uint32, x func()) { - runtime.LockOSThread() - - if err := hcsshim.SetCurrentThreadCompartmentId(compartmentID); err != nil { - logrus.Error(err) - } - defer func() { - hcsshim.SetCurrentThreadCompartmentId(0) - runtime.UnlockOSThread() - }() - - x() -} - -func (n *network) startResolver() { - if n.networkType == "ics" { - return - } - n.resolverOnce.Do(func() { - logrus.Debugf("Launching DNS server for network %q", n.Name()) - options := n.Info().DriverOptions() - hnsid := options[windows.HNSID] - - if hnsid == "" { - return - } - - hnsresponse, err := hcsshim.HNSNetworkRequest("GET", hnsid, "") - if err != nil { - logrus.Errorf("Resolver Setup/Start failed for container %s, %q", n.Name(), err) - return - } - - for _, subnet := range hnsresponse.Subnets { - if subnet.GatewayAddress != "" { - for i := 0; i < 3; i++ { - resolver := NewResolver(subnet.GatewayAddress, false, "", n) - logrus.Debugf("Binding a resolver on network %s gateway %s", n.Name(), subnet.GatewayAddress) - executeInCompartment(hnsresponse.DNSServerCompartment, resolver.SetupFunc(53)) - - if err = resolver.Start(); err != nil { - logrus.Errorf("Resolver Setup/Start failed for container %s, %q", n.Name(), err) - time.Sleep(1 * time.Second) - } else { - logrus.Debugf("Resolver bound successfully for network %s", n.Name()) - n.resolver = append(n.resolver, resolver) - break - } - } - } - } - }) -} - -func defaultIpamForNetworkType(networkType string) string { - if windows.IsBuiltinLocalDriver(networkType) { - return windowsipam.DefaultIPAM - } - return ipamapi.DefaultIPAM -} diff --git a/vendor/github.com/docker/libnetwork/networkdb/broadcast.go b/vendor/github.com/docker/libnetwork/networkdb/broadcast.go deleted file mode 100644 index efcfcc2426..0000000000 --- a/vendor/github.com/docker/libnetwork/networkdb/broadcast.go +++ /dev/null @@ -1,172 +0,0 @@ -package networkdb - -import ( - "errors" - "time" - - "github.com/hashicorp/memberlist" - "github.com/hashicorp/serf/serf" -) - -const broadcastTimeout = 5 * time.Second - -type networkEventMessage struct { - id string - node string - msg []byte -} - -func (m *networkEventMessage) Invalidates(other memberlist.Broadcast) bool { - otherm := other.(*networkEventMessage) - return m.id == otherm.id && m.node == otherm.node -} - -func (m *networkEventMessage) Message() []byte { - return m.msg -} - -func (m *networkEventMessage) Finished() { -} - -func (nDB *NetworkDB) sendNetworkEvent(nid string, event NetworkEvent_Type, ltime serf.LamportTime) error { - nEvent := NetworkEvent{ - Type: event, - LTime: ltime, - NodeName: nDB.config.NodeID, - NetworkID: nid, - } - - raw, err := encodeMessage(MessageTypeNetworkEvent, &nEvent) - if err != nil { - return err - } - - nDB.networkBroadcasts.QueueBroadcast(&networkEventMessage{ - msg: raw, - id: nid, - node: nDB.config.NodeID, - }) - return nil -} - -type nodeEventMessage struct { - msg []byte - notify chan<- struct{} -} - -func (m *nodeEventMessage) Invalidates(other memberlist.Broadcast) bool { - return false -} - -func (m *nodeEventMessage) Message() []byte { - return m.msg -} - -func (m *nodeEventMessage) Finished() { - if m.notify != nil { - close(m.notify) - } -} - -func (nDB *NetworkDB) sendNodeEvent(event NodeEvent_Type) error { - nEvent := NodeEvent{ - Type: event, - LTime: nDB.networkClock.Increment(), - NodeName: nDB.config.NodeID, - } - - raw, err := encodeMessage(MessageTypeNodeEvent, &nEvent) - if err != nil { - return err - } - - notifyCh := make(chan struct{}) - nDB.nodeBroadcasts.QueueBroadcast(&nodeEventMessage{ - msg: raw, - notify: notifyCh, - }) - - nDB.RLock() - noPeers := len(nDB.nodes) <= 1 - nDB.RUnlock() - - // Message enqueued, do not wait for a send if no peer is present - if noPeers { - return nil - } - - // Wait for the broadcast - select { - case <-notifyCh: - case <-time.After(broadcastTimeout): - return errors.New("timed out broadcasting node event") - } - - return nil -} - -type tableEventMessage struct { - id string - tname string - key string - msg []byte -} - -func (m *tableEventMessage) Invalidates(other memberlist.Broadcast) bool { - otherm := other.(*tableEventMessage) - return m.tname == otherm.tname && m.id == otherm.id && m.key == otherm.key -} - -func (m *tableEventMessage) Message() []byte { - return m.msg -} - -func (m *tableEventMessage) Finished() { -} - -func (nDB *NetworkDB) sendTableEvent(event TableEvent_Type, nid string, tname string, key string, entry *entry) error { - tEvent := TableEvent{ - Type: event, - LTime: entry.ltime, - NodeName: nDB.config.NodeID, - NetworkID: nid, - TableName: tname, - Key: key, - Value: entry.value, - // The duration in second is a float that below would be truncated - ResidualReapTime: int32(entry.reapTime.Seconds()), - } - - raw, err := encodeMessage(MessageTypeTableEvent, &tEvent) - if err != nil { - return err - } - - var broadcastQ *memberlist.TransmitLimitedQueue - nDB.RLock() - thisNodeNetworks, ok := nDB.networks[nDB.config.NodeID] - if ok { - // The network may have been removed - network, networkOk := thisNodeNetworks[nid] - if !networkOk { - nDB.RUnlock() - return nil - } - - broadcastQ = network.tableBroadcasts - } - nDB.RUnlock() - - // The network may have been removed - if broadcastQ == nil { - return nil - } - - broadcastQ.QueueBroadcast(&tableEventMessage{ - msg: raw, - id: nid, - tname: tname, - key: key, - }) - return nil -} diff --git a/vendor/github.com/docker/libnetwork/networkdb/cluster.go b/vendor/github.com/docker/libnetwork/networkdb/cluster.go deleted file mode 100644 index 92c0c41bca..0000000000 --- a/vendor/github.com/docker/libnetwork/networkdb/cluster.go +++ /dev/null @@ -1,761 +0,0 @@ -package networkdb - -import ( - "bytes" - "context" - "crypto/rand" - "encoding/hex" - "fmt" - "log" - "math/big" - rnd "math/rand" - "net" - "strings" - "time" - - "github.com/hashicorp/memberlist" - "github.com/sirupsen/logrus" -) - -const ( - reapPeriod = 5 * time.Second - rejoinClusterDuration = 10 * time.Second - rejoinInterval = 60 * time.Second - retryInterval = 1 * time.Second - nodeReapInterval = 24 * time.Hour - nodeReapPeriod = 2 * time.Hour - // considering a cluster with > 20 nodes and a drain speed of 100 msg/s - // the following is roughly 1 minute - maxQueueLenBroadcastOnSync = 500 -) - -type logWriter struct{} - -func (l *logWriter) Write(p []byte) (int, error) { - str := string(p) - str = strings.TrimSuffix(str, "\n") - - switch { - case strings.HasPrefix(str, "[WARN] "): - str = strings.TrimPrefix(str, "[WARN] ") - logrus.Warn(str) - case strings.HasPrefix(str, "[DEBUG] "): - str = strings.TrimPrefix(str, "[DEBUG] ") - logrus.Debug(str) - case strings.HasPrefix(str, "[INFO] "): - str = strings.TrimPrefix(str, "[INFO] ") - logrus.Info(str) - case strings.HasPrefix(str, "[ERR] "): - str = strings.TrimPrefix(str, "[ERR] ") - logrus.Warn(str) - } - - return len(p), nil -} - -// 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) - } -} - -// 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 - } - } -} - -// 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 - } - } -} - -func (nDB *NetworkDB) clusterInit() error { - nDB.lastStatsTimestamp = time.Now() - nDB.lastHealthTimestamp = nDB.lastStatsTimestamp - - config := memberlist.DefaultLANConfig() - config.Name = nDB.config.NodeID - config.BindAddr = nDB.config.BindAddr - config.AdvertiseAddr = nDB.config.AdvertiseAddr - config.UDPBufferSize = nDB.config.PacketBufferSize - - if nDB.config.BindPort != 0 { - config.BindPort = nDB.config.BindPort - } - - config.ProtocolVersion = memberlist.ProtocolVersion2Compatible - config.Delegate = &delegate{nDB: nDB} - config.Events = &eventDelegate{nDB: nDB} - // custom logger that does not add time or date, so they are not - // duplicated by logrus - config.Logger = log.New(&logWriter{}, "", 0) - - var err error - if len(nDB.config.Keys) > 0 { - for i, key := range nDB.config.Keys { - logrus.Debugf("Encryption key %d: %.5s", i+1, hex.EncodeToString(key)) - } - nDB.keyring, err = memberlist.NewKeyring(nDB.config.Keys, nDB.config.Keys[0]) - if err != nil { - return err - } - config.Keyring = nDB.keyring - } - - nDB.networkBroadcasts = &memberlist.TransmitLimitedQueue{ - NumNodes: func() int { - nDB.RLock() - num := len(nDB.nodes) - nDB.RUnlock() - return num - }, - RetransmitMult: config.RetransmitMult, - } - - nDB.nodeBroadcasts = &memberlist.TransmitLimitedQueue{ - NumNodes: func() int { - nDB.RLock() - num := len(nDB.nodes) - nDB.RUnlock() - return num - }, - RetransmitMult: config.RetransmitMult, - } - - mlist, err := memberlist.Create(config) - if err != nil { - return fmt.Errorf("failed to create memberlist: %v", err) - } - - nDB.ctx, nDB.cancelCtx = context.WithCancel(context.Background()) - nDB.memberlist = mlist - - for _, trigger := range []struct { - interval time.Duration - fn func() - }{ - {reapPeriod, nDB.reapState}, - {config.GossipInterval, nDB.gossip}, - {config.PushPullInterval, nDB.bulkSyncTables}, - {retryInterval, nDB.reconnectNode}, - {nodeReapPeriod, nDB.reapDeadNode}, - {rejoinInterval, nDB.rejoinClusterBootStrap}, - } { - t := time.NewTicker(trigger.interval) - go nDB.triggerFunc(trigger.interval, t.C, trigger.fn) - nDB.tickers = append(nDB.tickers, t) - } - - return nil -} - -func (nDB *NetworkDB) retryJoin(ctx context.Context, members []string) { - t := time.NewTicker(retryInterval) - defer t.Stop() - - for { - select { - case <-t.C: - if _, err := nDB.memberlist.Join(members); err != nil { - logrus.Errorf("Failed to join memberlist %s on retry: %v", members, err) - continue - } - if err := nDB.sendNodeEvent(NodeEventTypeJoin); err != nil { - logrus.Errorf("failed to send node join on retry: %v", err) - continue - } - return - case <-ctx.Done(): - return - } - } - -} - -func (nDB *NetworkDB) clusterJoin(members []string) error { - mlist := nDB.memberlist - - if _, err := mlist.Join(members); err != nil { - // In case of failure, we no longer need to explicitly call retryJoin. - // rejoinClusterBootStrap, which runs every minute, will retryJoin for 10sec - return fmt.Errorf("could not join node to memberlist: %v", err) - } - - if err := nDB.sendNodeEvent(NodeEventTypeJoin); err != nil { - return fmt.Errorf("failed to send node join: %v", err) - } - - return nil -} - -func (nDB *NetworkDB) clusterLeave() error { - mlist := nDB.memberlist - - if err := nDB.sendNodeEvent(NodeEventTypeLeave); err != nil { - logrus.Errorf("failed to send node leave: %v", err) - } - - if err := mlist.Leave(time.Second); err != nil { - return err - } - - // cancel the context - nDB.cancelCtx() - - for _, t := range nDB.tickers { - t.Stop() - } - - return mlist.Shutdown() -} - -func (nDB *NetworkDB) triggerFunc(stagger time.Duration, C <-chan time.Time, f func()) { - // Use a random stagger to avoid synchronizing - randStagger := time.Duration(uint64(rnd.Int63()) % uint64(stagger)) - select { - case <-time.After(randStagger): - case <-nDB.ctx.Done(): - return - } - for { - select { - case <-C: - f() - case <-nDB.ctx.Done(): - return - } - } -} - -func (nDB *NetworkDB) reapDeadNode() { - nDB.Lock() - defer nDB.Unlock() - for _, nodeMap := range []map[string]*node{ - nDB.failedNodes, - nDB.leftNodes, - } { - for id, n := range nodeMap { - if n.reapTime > nodeReapPeriod { - n.reapTime -= nodeReapPeriod - continue - } - logrus.Debugf("Garbage collect node %v", n.Name) - delete(nodeMap, id) - } - } -} - -// 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) -} - -func (nDB *NetworkDB) reconnectNode() { - nDB.RLock() - if len(nDB.failedNodes) == 0 { - nDB.RUnlock() - return - } - - nodes := make([]*node, 0, len(nDB.failedNodes)) - for _, n := range nDB.failedNodes { - nodes = append(nodes, n) - } - nDB.RUnlock() - - node := nodes[randomOffset(len(nodes))] - addr := net.UDPAddr{IP: node.Addr, Port: int(node.Port)} - - if _, err := nDB.memberlist.Join([]string{addr.String()}); err != nil { - return - } - - if err := nDB.sendNodeEvent(NodeEventTypeJoin); err != nil { - return - } - - logrus.Debugf("Initiating bulk sync with node %s after reconnect", node.Name) - nDB.bulkSync([]string{node.Name}, true) -} - -// For timing the entry deletion in the reaper APIs that doesn't use monotonic clock -// source (time.Now, Sub etc.) should be avoided. Hence we use reapTime in every -// entry which is set initially to reapInterval and decremented by reapPeriod every time -// the reaper runs. NOTE nDB.reapTableEntries updates the reapTime with a readlock. This -// is safe as long as no other concurrent path touches the reapTime field. -func (nDB *NetworkDB) reapState() { - // The reapTableEntries leverage the presence of the network so garbage collect entries first - nDB.reapTableEntries() - nDB.reapNetworks() -} - -func (nDB *NetworkDB) reapNetworks() { - nDB.Lock() - for _, nn := range nDB.networks { - for id, n := range nn { - if n.leaving { - if n.reapTime <= 0 { - delete(nn, id) - continue - } - n.reapTime -= reapPeriod - } - } - } - nDB.Unlock() -} - -func (nDB *NetworkDB) reapTableEntries() { - var nodeNetworks []string - // This is best effort, if the list of network changes will be picked up in the next cycle - nDB.RLock() - for nid := range nDB.networks[nDB.config.NodeID] { - nodeNetworks = append(nodeNetworks, nid) - } - nDB.RUnlock() - - cycleStart := time.Now() - // In order to avoid blocking the database for a long time, apply the garbage collection logic by network - // The lock is taken at the beginning of the cycle and the deletion is inline - for _, nid := range nodeNetworks { - nDB.Lock() - nDB.indexes[byNetwork].WalkPrefix(fmt.Sprintf("/%s", nid), func(path string, v interface{}) bool { - // timeCompensation compensate in case the lock took some time to be released - timeCompensation := time.Since(cycleStart) - entry, ok := v.(*entry) - if !ok || !entry.deleting { - return false - } - - // In this check we are adding an extra 1 second to guarantee that when the number is truncated to int32 to fit the packet - // for the tableEvent the number is always strictly > 1 and never 0 - if entry.reapTime > reapPeriod+timeCompensation+time.Second { - entry.reapTime -= reapPeriod + timeCompensation - return false - } - - params := strings.Split(path[1:], "/") - nid := params[0] - tname := params[1] - key := params[2] - - okTable, okNetwork := nDB.deleteEntry(nid, tname, key) - if !okTable { - logrus.Errorf("Table tree delete failed, entry with key:%s does not exists in the table:%s network:%s", key, tname, nid) - } - if !okNetwork { - logrus.Errorf("Network tree delete failed, entry with key:%s does not exists in the network:%s table:%s", key, nid, tname) - } - - return false - }) - nDB.Unlock() - } -} - -func (nDB *NetworkDB) gossip() { - networkNodes := make(map[string][]string) - nDB.RLock() - thisNodeNetworks := nDB.networks[nDB.config.NodeID] - for nid := range thisNodeNetworks { - networkNodes[nid] = nDB.networkNodes[nid] - } - printStats := time.Since(nDB.lastStatsTimestamp) >= nDB.config.StatsPrintPeriod - printHealth := time.Since(nDB.lastHealthTimestamp) >= nDB.config.HealthPrintPeriod - nDB.RUnlock() - - if printHealth { - healthScore := nDB.memberlist.GetHealthScore() - if healthScore != 0 { - logrus.Warnf("NetworkDB stats %v(%v) - healthscore:%d (connectivity issues)", nDB.config.Hostname, nDB.config.NodeID, healthScore) - } - nDB.lastHealthTimestamp = time.Now() - } - - for nid, nodes := range networkNodes { - mNodes := nDB.mRandomNodes(3, nodes) - bytesAvail := nDB.config.PacketBufferSize - compoundHeaderOverhead - - nDB.RLock() - network, ok := thisNodeNetworks[nid] - nDB.RUnlock() - if !ok || network == nil { - // It is normal for the network to be removed - // between the time we collect the network - // attachments of this node and processing - // them here. - continue - } - - broadcastQ := network.tableBroadcasts - - if broadcastQ == nil { - logrus.Errorf("Invalid broadcastQ encountered while gossiping for network %s", nid) - continue - } - - msgs := broadcastQ.GetBroadcasts(compoundOverhead, bytesAvail) - // Collect stats and print the queue info, note this code is here also to have a view of the queues empty - network.qMessagesSent += len(msgs) - if printStats { - logrus.Infof("NetworkDB stats %v(%v) - netID:%s leaving:%t netPeers:%d entries:%d Queue qLen:%d netMsg/s:%d", - nDB.config.Hostname, nDB.config.NodeID, - nid, network.leaving, broadcastQ.NumNodes(), network.entriesNumber, broadcastQ.NumQueued(), - network.qMessagesSent/int((nDB.config.StatsPrintPeriod/time.Second))) - network.qMessagesSent = 0 - } - - if len(msgs) == 0 { - continue - } - - // Create a compound message - compound := makeCompoundMessage(msgs) - - for _, node := range mNodes { - nDB.RLock() - mnode := nDB.nodes[node] - nDB.RUnlock() - - if mnode == nil { - break - } - - // Send the compound message - if err := nDB.memberlist.SendBestEffort(&mnode.Node, compound); err != nil { - logrus.Errorf("Failed to send gossip to %s: %s", mnode.Addr, err) - } - } - } - // Reset the stats - if printStats { - nDB.lastStatsTimestamp = time.Now() - } -} - -func (nDB *NetworkDB) bulkSyncTables() { - var networks []string - nDB.RLock() - for nid, network := range nDB.networks[nDB.config.NodeID] { - if network.leaving { - continue - } - networks = append(networks, nid) - } - nDB.RUnlock() - - for { - if len(networks) == 0 { - break - } - - nid := networks[0] - networks = networks[1:] - - nDB.RLock() - nodes := nDB.networkNodes[nid] - nDB.RUnlock() - - // No peer nodes on this network. Move on. - if len(nodes) == 0 { - continue - } - - completed, err := nDB.bulkSync(nodes, false) - if err != nil { - logrus.Errorf("periodic bulk sync failure for network %s: %v", nid, err) - continue - } - - // Remove all the networks for which we have - // successfully completed bulk sync in this iteration. - updatedNetworks := make([]string, 0, len(networks)) - for _, nid := range networks { - var found bool - for _, completedNid := range completed { - if nid == completedNid { - found = true - break - } - } - - if !found { - updatedNetworks = append(updatedNetworks, nid) - } - } - - networks = updatedNetworks - } -} - -func (nDB *NetworkDB) bulkSync(nodes []string, all bool) ([]string, error) { - if !all { - // Get 2 random nodes. 2nd node will be tried if the bulk sync to - // 1st node fails. - nodes = nDB.mRandomNodes(2, nodes) - } - - if len(nodes) == 0 { - return nil, nil - } - - var err error - var networks []string - var success bool - for _, node := range nodes { - if node == nDB.config.NodeID { - continue - } - logrus.Debugf("%v(%v): Initiating bulk sync with node %v", nDB.config.Hostname, nDB.config.NodeID, node) - networks = nDB.findCommonNetworks(node) - err = nDB.bulkSyncNode(networks, node, true) - if err != nil { - err = fmt.Errorf("bulk sync to node %s failed: %v", node, err) - logrus.Warn(err.Error()) - } else { - // bulk sync succeeded - success = true - // if its periodic bulksync stop after the first successful sync - if !all { - break - } - } - } - - if success { - // if at least one node sync succeeded - return networks, nil - } - - return nil, err -} - -// 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 -} - -// 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()) -} - -// 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 -} diff --git a/vendor/github.com/docker/libnetwork/networkdb/delegate.go b/vendor/github.com/docker/libnetwork/networkdb/delegate.go deleted file mode 100644 index 14e19bbdd7..0000000000 --- a/vendor/github.com/docker/libnetwork/networkdb/delegate.go +++ /dev/null @@ -1,494 +0,0 @@ -package networkdb - -import ( - "net" - "time" - - "github.com/gogo/protobuf/proto" - "github.com/sirupsen/logrus" -) - -type delegate struct { - nDB *NetworkDB -} - -func (d *delegate) NodeMeta(limit int) []byte { - return []byte{} -} - -func (nDB *NetworkDB) handleNodeEvent(nEvent *NodeEvent) bool { - // Update our local clock if the received messages has newer - // time. - nDB.networkClock.Witness(nEvent.LTime) - - nDB.Lock() - defer nDB.Unlock() - - // check if the node exists - n, _, _ := nDB.findNode(nEvent.NodeName) - if n == nil { - return false - } - - // check if the event is fresh - if n.ltime >= nEvent.LTime { - return false - } - - // If we are here means that the event is fresher and the node is known. Update the laport time - n.ltime = nEvent.LTime - - // If the node is not known from memberlist we cannot process save any state of it else if it actually - // dies we won't receive any notification and we will remain stuck with it - if _, ok := nDB.nodes[nEvent.NodeName]; !ok { - logrus.Errorf("node: %s is unknown to memberlist", nEvent.NodeName) - return false - } - - switch nEvent.Type { - case NodeEventTypeJoin: - moved, err := nDB.changeNodeState(n.Name, nodeActiveState) - if err != nil { - logrus.WithError(err).Error("unable to find the node to move") - return false - } - if moved { - logrus.Infof("%v(%v): Node join event for %s/%s", nDB.config.Hostname, nDB.config.NodeID, n.Name, n.Addr) - } - return moved - case NodeEventTypeLeave: - moved, err := nDB.changeNodeState(n.Name, nodeLeftState) - if err != nil { - logrus.WithError(err).Error("unable to find the node to move") - return false - } - if moved { - logrus.Infof("%v(%v): Node leave event for %s/%s", nDB.config.Hostname, nDB.config.NodeID, n.Name, n.Addr) - } - return moved - } - - return false -} - -func (nDB *NetworkDB) handleNetworkEvent(nEvent *NetworkEvent) bool { - // Update our local clock if the received messages has newer - // time. - nDB.networkClock.Witness(nEvent.LTime) - - nDB.Lock() - defer nDB.Unlock() - - if nEvent.NodeName == nDB.config.NodeID { - return false - } - - nodeNetworks, ok := nDB.networks[nEvent.NodeName] - if !ok { - // We haven't heard about this node at all. Ignore the leave - if nEvent.Type == NetworkEventTypeLeave { - return false - } - - nodeNetworks = make(map[string]*network) - nDB.networks[nEvent.NodeName] = nodeNetworks - } - - if n, ok := nodeNetworks[nEvent.NetworkID]; ok { - // We have the latest state. Ignore the event - // since it is stale. - if n.ltime >= nEvent.LTime { - return false - } - - n.ltime = nEvent.LTime - n.leaving = nEvent.Type == NetworkEventTypeLeave - if n.leaving { - n.reapTime = nDB.config.reapNetworkInterval - - // The remote node is leaving the network, but not the gossip cluster. - // Mark all its entries in deleted state, this will guarantee that - // if some node bulk sync with us, the deleted state of - // these entries will be propagated. - nDB.deleteNodeNetworkEntries(nEvent.NetworkID, nEvent.NodeName) - } - - if nEvent.Type == NetworkEventTypeLeave { - nDB.deleteNetworkNode(nEvent.NetworkID, nEvent.NodeName) - } else { - nDB.addNetworkNode(nEvent.NetworkID, nEvent.NodeName) - } - - return true - } - - if nEvent.Type == NetworkEventTypeLeave { - return false - } - - // If the node is not known from memberlist we cannot process save any state of it else if it actually - // dies we won't receive any notification and we will remain stuck with it - if _, ok := nDB.nodes[nEvent.NodeName]; !ok { - return false - } - - // This remote network join is being seen the first time. - nodeNetworks[nEvent.NetworkID] = &network{ - id: nEvent.NetworkID, - ltime: nEvent.LTime, - } - - nDB.addNetworkNode(nEvent.NetworkID, nEvent.NodeName) - return true -} - -func (nDB *NetworkDB) handleTableEvent(tEvent *TableEvent, isBulkSync bool) bool { - // Update our local clock if the received messages has newer time. - nDB.tableClock.Witness(tEvent.LTime) - - // Ignore the table events for networks that are in the process of going away - nDB.RLock() - networks := nDB.networks[nDB.config.NodeID] - network, ok := networks[tEvent.NetworkID] - // Check if the owner of the event is still part of the network - nodes := nDB.networkNodes[tEvent.NetworkID] - var nodePresent bool - for _, node := range nodes { - if node == tEvent.NodeName { - nodePresent = true - break - } - } - nDB.RUnlock() - - if !ok || network.leaving || !nodePresent { - // I'm out of the network OR the event owner is not anymore part of the network so do not propagate - return false - } - - nDB.Lock() - e, err := nDB.getEntry(tEvent.TableName, tEvent.NetworkID, tEvent.Key) - if err == nil { - // We have the latest state. Ignore the event - // since it is stale. - if e.ltime >= tEvent.LTime { - nDB.Unlock() - return false - } - } else if tEvent.Type == TableEventTypeDelete && !isBulkSync { - nDB.Unlock() - // We don't know the entry, the entry is being deleted and the message is an async message - // In this case the safest approach is to ignore it, it is possible that the queue grew so much to - // exceed the garbage collection time (the residual reap time that is in the message is not being - // updated, to avoid inserting too many messages in the queue). - // Instead the messages coming from TCP bulk sync are safe with the latest value for the garbage collection time - return false - } - - e = &entry{ - ltime: tEvent.LTime, - node: tEvent.NodeName, - value: tEvent.Value, - deleting: tEvent.Type == TableEventTypeDelete, - reapTime: time.Duration(tEvent.ResidualReapTime) * time.Second, - } - - // All the entries marked for deletion should have a reapTime set greater than 0 - // This case can happen if the cluster is running different versions of the engine where the old version does not have the - // field. If that is not the case, this can be a BUG - if e.deleting && e.reapTime == 0 { - logrus.Warnf("%v(%v) handleTableEvent object %+v has a 0 reapTime, is the cluster running the same docker engine version?", - nDB.config.Hostname, nDB.config.NodeID, tEvent) - e.reapTime = nDB.config.reapEntryInterval - } - nDB.createOrUpdateEntry(tEvent.NetworkID, tEvent.TableName, tEvent.Key, e) - nDB.Unlock() - - if err != nil && tEvent.Type == TableEventTypeDelete { - // Again we don't know the entry but this is coming from a TCP sync so the message body is up to date. - // We had saved the state so to speed up convergence and be able to avoid accepting create events. - // Now we will rebroadcast the message if 2 conditions are met: - // 1) we had already synced this network (during the network join) - // 2) the residual reapTime is higher than 1/6 of the total reapTime. - // If the residual reapTime is lower or equal to 1/6 of the total reapTime don't bother broadcasting it around - // most likely the cluster is already aware of it - // This also reduce the possibility that deletion of entries close to their garbage collection ends up circuling around - // forever - //logrus.Infof("exiting on delete not knowing the obj with rebroadcast:%t", network.inSync) - return network.inSync && e.reapTime > nDB.config.reapEntryInterval/6 - } - - var op opType - switch tEvent.Type { - case TableEventTypeCreate: - op = opCreate - case TableEventTypeUpdate: - op = opUpdate - case TableEventTypeDelete: - op = opDelete - } - - nDB.broadcaster.Write(makeEvent(op, tEvent.TableName, tEvent.NetworkID, tEvent.Key, tEvent.Value)) - return network.inSync -} - -func (nDB *NetworkDB) handleCompound(buf []byte, isBulkSync bool) { - // Decode the parts - parts, err := decodeCompoundMessage(buf) - if err != nil { - logrus.Errorf("Failed to decode compound request: %v", err) - return - } - - // Handle each message - for _, part := range parts { - nDB.handleMessage(part, isBulkSync) - } -} - -func (nDB *NetworkDB) handleTableMessage(buf []byte, isBulkSync bool) { - var tEvent TableEvent - if err := proto.Unmarshal(buf, &tEvent); err != nil { - logrus.Errorf("Error decoding table event message: %v", err) - return - } - - // Ignore messages that this node generated. - if tEvent.NodeName == nDB.config.NodeID { - return - } - - if rebroadcast := nDB.handleTableEvent(&tEvent, isBulkSync); rebroadcast { - var err error - buf, err = encodeRawMessage(MessageTypeTableEvent, buf) - if err != nil { - logrus.Errorf("Error marshalling gossip message for network event rebroadcast: %v", err) - return - } - - nDB.RLock() - n, ok := nDB.networks[nDB.config.NodeID][tEvent.NetworkID] - nDB.RUnlock() - - // if the network is not there anymore, OR we are leaving the network OR the broadcast queue is not present - if !ok || n.leaving || n.tableBroadcasts == nil { - return - } - - // if the queue is over the threshold, avoid distributing information coming from TCP sync - if isBulkSync && n.tableBroadcasts.NumQueued() > maxQueueLenBroadcastOnSync { - return - } - - n.tableBroadcasts.QueueBroadcast(&tableEventMessage{ - msg: buf, - id: tEvent.NetworkID, - tname: tEvent.TableName, - key: tEvent.Key, - }) - } -} - -func (nDB *NetworkDB) handleNodeMessage(buf []byte) { - var nEvent NodeEvent - if err := proto.Unmarshal(buf, &nEvent); err != nil { - logrus.Errorf("Error decoding node event message: %v", err) - return - } - - if rebroadcast := nDB.handleNodeEvent(&nEvent); rebroadcast { - var err error - buf, err = encodeRawMessage(MessageTypeNodeEvent, buf) - if err != nil { - logrus.Errorf("Error marshalling gossip message for node event rebroadcast: %v", err) - return - } - - nDB.nodeBroadcasts.QueueBroadcast(&nodeEventMessage{ - msg: buf, - }) - } -} - -func (nDB *NetworkDB) handleNetworkMessage(buf []byte) { - var nEvent NetworkEvent - if err := proto.Unmarshal(buf, &nEvent); err != nil { - logrus.Errorf("Error decoding network event message: %v", err) - return - } - - if rebroadcast := nDB.handleNetworkEvent(&nEvent); rebroadcast { - var err error - buf, err = encodeRawMessage(MessageTypeNetworkEvent, buf) - if err != nil { - logrus.Errorf("Error marshalling gossip message for network event rebroadcast: %v", err) - return - } - - nDB.networkBroadcasts.QueueBroadcast(&networkEventMessage{ - msg: buf, - id: nEvent.NetworkID, - node: nEvent.NodeName, - }) - } -} - -func (nDB *NetworkDB) handleBulkSync(buf []byte) { - var bsm BulkSyncMessage - if err := proto.Unmarshal(buf, &bsm); err != nil { - logrus.Errorf("Error decoding bulk sync message: %v", err) - return - } - - if bsm.LTime > 0 { - nDB.tableClock.Witness(bsm.LTime) - } - - nDB.handleMessage(bsm.Payload, true) - - // Don't respond to a bulk sync which was not unsolicited - if !bsm.Unsolicited { - nDB.Lock() - ch, ok := nDB.bulkSyncAckTbl[bsm.NodeName] - if ok { - close(ch) - delete(nDB.bulkSyncAckTbl, bsm.NodeName) - } - nDB.Unlock() - - return - } - - var nodeAddr net.IP - nDB.RLock() - if node, ok := nDB.nodes[bsm.NodeName]; ok { - nodeAddr = node.Addr - } - nDB.RUnlock() - - if err := nDB.bulkSyncNode(bsm.Networks, bsm.NodeName, false); err != nil { - logrus.Errorf("Error in responding to bulk sync from node %s: %v", nodeAddr, err) - } -} - -func (nDB *NetworkDB) handleMessage(buf []byte, isBulkSync bool) { - mType, data, err := decodeMessage(buf) - if err != nil { - logrus.Errorf("Error decoding gossip message to get message type: %v", err) - return - } - - switch mType { - case MessageTypeNodeEvent: - nDB.handleNodeMessage(data) - case MessageTypeNetworkEvent: - nDB.handleNetworkMessage(data) - case MessageTypeTableEvent: - nDB.handleTableMessage(data, isBulkSync) - case MessageTypeBulkSync: - nDB.handleBulkSync(data) - case MessageTypeCompound: - nDB.handleCompound(data, isBulkSync) - default: - logrus.Errorf("%v(%v): unknown message type %d", nDB.config.Hostname, nDB.config.NodeID, mType) - } -} - -func (d *delegate) NotifyMsg(buf []byte) { - if len(buf) == 0 { - return - } - - d.nDB.handleMessage(buf, false) -} - -func (d *delegate) GetBroadcasts(overhead, limit int) [][]byte { - msgs := d.nDB.networkBroadcasts.GetBroadcasts(overhead, limit) - msgs = append(msgs, d.nDB.nodeBroadcasts.GetBroadcasts(overhead, limit)...) - return msgs -} - -func (d *delegate) LocalState(join bool) []byte { - if join { - // Update all the local node/network state to a new time to - // force update on the node we are trying to rejoin, just in - // case that node has these in leaving state still. This is - // facilitate fast convergence after recovering from a gossip - // failure. - d.nDB.updateLocalNetworkTime() - } - - d.nDB.RLock() - defer d.nDB.RUnlock() - - pp := NetworkPushPull{ - LTime: d.nDB.networkClock.Time(), - NodeName: d.nDB.config.NodeID, - } - - for name, nn := range d.nDB.networks { - for _, n := range nn { - pp.Networks = append(pp.Networks, &NetworkEntry{ - LTime: n.ltime, - NetworkID: n.id, - NodeName: name, - Leaving: n.leaving, - }) - } - } - - buf, err := encodeMessage(MessageTypePushPull, &pp) - if err != nil { - logrus.Errorf("Failed to encode local network state: %v", err) - return nil - } - - return buf -} - -func (d *delegate) MergeRemoteState(buf []byte, isJoin bool) { - if len(buf) == 0 { - logrus.Error("zero byte remote network state received") - return - } - - var gMsg GossipMessage - err := proto.Unmarshal(buf, &gMsg) - if err != nil { - logrus.Errorf("Error unmarshalling push pull message: %v", err) - return - } - - if gMsg.Type != MessageTypePushPull { - logrus.Errorf("Invalid message type %v received from remote", buf[0]) - } - - pp := NetworkPushPull{} - if err := proto.Unmarshal(gMsg.Data, &pp); err != nil { - logrus.Errorf("Failed to decode remote network state: %v", err) - return - } - - nodeEvent := &NodeEvent{ - LTime: pp.LTime, - NodeName: pp.NodeName, - Type: NodeEventTypeJoin, - } - d.nDB.handleNodeEvent(nodeEvent) - - for _, n := range pp.Networks { - nEvent := &NetworkEvent{ - LTime: n.LTime, - NodeName: n.NodeName, - NetworkID: n.NetworkID, - Type: NetworkEventTypeJoin, - } - - if n.Leaving { - nEvent.Type = NetworkEventTypeLeave - } - - d.nDB.handleNetworkEvent(nEvent) - } - -} diff --git a/vendor/github.com/docker/libnetwork/networkdb/event_delegate.go b/vendor/github.com/docker/libnetwork/networkdb/event_delegate.go deleted file mode 100644 index 78ebe0fd9e..0000000000 --- a/vendor/github.com/docker/libnetwork/networkdb/event_delegate.go +++ /dev/null @@ -1,72 +0,0 @@ -package networkdb - -import ( - "encoding/json" - "net" - - "github.com/hashicorp/memberlist" - "github.com/sirupsen/logrus" -) - -type eventDelegate struct { - nDB *NetworkDB -} - -func (e *eventDelegate) broadcastNodeEvent(addr net.IP, op opType) { - value, err := json.Marshal(&NodeAddr{addr}) - if err == nil { - e.nDB.broadcaster.Write(makeEvent(op, NodeTable, "", "", value)) - } else { - logrus.Errorf("Error marshalling node broadcast event %s", addr.String()) - } -} - -func (e *eventDelegate) NotifyJoin(mn *memberlist.Node) { - logrus.Infof("Node %s/%s, joined gossip cluster", mn.Name, mn.Addr) - e.broadcastNodeEvent(mn.Addr, opCreate) - e.nDB.Lock() - defer e.nDB.Unlock() - - // In case the node is rejoining after a failure or leave, - // just add the node back to active - if moved, _ := e.nDB.changeNodeState(mn.Name, nodeActiveState); moved { - return - } - - // Every node has a unique ID - // Check on the base of the IP address if the new node that joined is actually a new incarnation of a previous - // failed or shutdown one - e.nDB.purgeReincarnation(mn) - - e.nDB.nodes[mn.Name] = &node{Node: *mn} - logrus.Infof("Node %s/%s, added to nodes list", mn.Name, mn.Addr) -} - -func (e *eventDelegate) NotifyLeave(mn *memberlist.Node) { - logrus.Infof("Node %s/%s, left gossip cluster", mn.Name, mn.Addr) - e.broadcastNodeEvent(mn.Addr, opDelete) - - e.nDB.Lock() - defer e.nDB.Unlock() - - n, currState, _ := e.nDB.findNode(mn.Name) - if n == nil { - logrus.Errorf("Node %s/%s not found in the node lists", mn.Name, mn.Addr) - return - } - // if the node was active means that did not send the leave cluster message, so it's probable that - // failed. Else would be already in the left list so nothing else has to be done - if currState == nodeActiveState { - moved, err := e.nDB.changeNodeState(mn.Name, nodeFailedState) - if err != nil { - logrus.WithError(err).Errorf("impossible condition, node %s/%s not present in the list", mn.Name, mn.Addr) - return - } - if moved { - logrus.Infof("Node %s/%s, added to failed nodes list", mn.Name, mn.Addr) - } - } -} - -func (e *eventDelegate) NotifyUpdate(n *memberlist.Node) { -} diff --git a/vendor/github.com/docker/libnetwork/networkdb/message.go b/vendor/github.com/docker/libnetwork/networkdb/message.go deleted file mode 100644 index 81a6d832a6..0000000000 --- a/vendor/github.com/docker/libnetwork/networkdb/message.go +++ /dev/null @@ -1,98 +0,0 @@ -package networkdb - -import "github.com/gogo/protobuf/proto" - -const ( - // Compound message header overhead 1 byte(message type) + 4 - // bytes (num messages) - compoundHeaderOverhead = 5 - - // Overhead for each embedded message in a compound message 4 - // bytes (len of embedded message) - compoundOverhead = 4 -) - -func encodeRawMessage(t MessageType, raw []byte) ([]byte, error) { - gMsg := GossipMessage{ - Type: t, - Data: raw, - } - - buf, err := proto.Marshal(&gMsg) - if err != nil { - return nil, err - } - - return buf, nil -} - -func encodeMessage(t MessageType, msg interface{}) ([]byte, error) { - buf, err := proto.Marshal(msg.(proto.Message)) - if err != nil { - return nil, err - } - - buf, err = encodeRawMessage(t, buf) - if err != nil { - return nil, err - } - - return buf, nil -} - -func decodeMessage(buf []byte) (MessageType, []byte, error) { - var gMsg GossipMessage - - err := proto.Unmarshal(buf, &gMsg) - if err != nil { - return MessageTypeInvalid, nil, err - } - - return gMsg.Type, gMsg.Data, nil -} - -// 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 -} - -// 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 -} diff --git a/vendor/github.com/docker/libnetwork/networkdb/networkdb.go b/vendor/github.com/docker/libnetwork/networkdb/networkdb.go deleted file mode 100644 index d8c3107baa..0000000000 --- a/vendor/github.com/docker/libnetwork/networkdb/networkdb.go +++ /dev/null @@ -1,769 +0,0 @@ -package networkdb - -//go:generate protoc -I.:../vendor/github.com/gogo/protobuf --gogo_out=import_path=github.com/docker/libnetwork/networkdb,Mgogoproto/gogo.proto=github.com/gogo/protobuf/gogoproto:. networkdb.proto - -import ( - "context" - "fmt" - "os" - "strings" - "sync" - "time" - - "github.com/armon/go-radix" - "github.com/docker/docker/pkg/stringid" - "github.com/docker/go-events" - "github.com/docker/libnetwork/types" - "github.com/hashicorp/memberlist" - "github.com/hashicorp/serf/serf" - "github.com/sirupsen/logrus" -) - -const ( - byTable int = 1 + iota - byNetwork -) - -// NetworkDB instance drives the networkdb cluster and acts the broker -// for cluster-scoped and network-scoped gossip and watches. -type NetworkDB struct { - // The clocks MUST be the first things - // in this struct due to Golang issue #599. - - // Global lamport clock for node network attach events. - networkClock serf.LamportClock - - // Global lamport clock for table events. - tableClock serf.LamportClock - - sync.RWMutex - - // NetworkDB configuration. - config *Config - - // All the tree index (byTable, byNetwork) that we maintain - // the db. - indexes map[int]*radix.Tree - - // Memberlist we use to drive the cluster. - memberlist *memberlist.Memberlist - - // List of all peer nodes in the cluster not-limited to any - // network. - nodes map[string]*node - - // List of all peer nodes which have failed - failedNodes map[string]*node - - // List of all peer nodes which have left - leftNodes map[string]*node - - // A multi-dimensional map of network/node attachments. The - // first key is a node name and the second key is a network ID - // for the network that node is participating in. - networks map[string]map[string]*network - - // A map of nodes which are participating in a given - // network. The key is a network ID. - networkNodes map[string][]string - - // A table of ack channels for every node from which we are - // waiting for an ack. - bulkSyncAckTbl map[string]chan struct{} - - // Broadcast queue for network event gossip. - networkBroadcasts *memberlist.TransmitLimitedQueue - - // Broadcast queue for node event gossip. - nodeBroadcasts *memberlist.TransmitLimitedQueue - - // A central context to stop all go routines running on - // behalf of the NetworkDB instance. - ctx context.Context - cancelCtx context.CancelFunc - - // A central broadcaster for all local watchers watching table - // events. - broadcaster *events.Broadcaster - - // List of all tickers which needed to be stopped when - // cleaning up. - tickers []*time.Ticker - - // Reference to the memberlist's keyring to add & remove keys - keyring *memberlist.Keyring - - // bootStrapIP is the list of IPs that can be used to bootstrap - // the gossip. - bootStrapIP []string - - // lastStatsTimestamp is the last timestamp when the stats got printed - lastStatsTimestamp time.Time - - // lastHealthTimestamp is the last timestamp when the health score got printed - lastHealthTimestamp time.Time -} - -// PeerInfo represents the peer (gossip cluster) nodes of a network -type PeerInfo struct { - Name string - IP string -} - -// PeerClusterInfo represents the peer (gossip cluster) nodes -type PeerClusterInfo struct { - PeerInfo -} - -type node struct { - memberlist.Node - ltime serf.LamportTime - // Number of hours left before the reaper removes the node - reapTime time.Duration -} - -// network describes the node/network attachment. -type network struct { - // Network ID - id string - - // Lamport time for the latest state of the entry. - ltime serf.LamportTime - - // Gets set to true after the first bulk sync happens - inSync bool - - // Node leave is in progress. - leaving bool - - // Number of seconds still left before a deleted network entry gets - // removed from networkDB - reapTime time.Duration - - // The broadcast queue for table event gossip. This is only - // initialized for this node's network attachment entries. - tableBroadcasts *memberlist.TransmitLimitedQueue - - // Number of gossip messages sent related to this network during the last stats collection period - qMessagesSent int - - // Number of entries on the network. This value is the sum of all the entries of all the tables of a specific network. - // Its use is for statistics purposes. It keep tracks of database size and is printed per network every StatsPrintPeriod - // interval - entriesNumber int -} - -// Config represents the configuration of the networkdb instance and -// can be passed by the caller. -type Config struct { - // NodeID is the node unique identifier of the node when is part of the cluster - NodeID string - - // Hostname is the node hostname. - Hostname string - - // BindAddr is the IP on which networkdb listens. It can be - // 0.0.0.0 to listen on all addresses on the host. - BindAddr string - - // AdvertiseAddr is the node's IP address that we advertise for - // cluster communication. - AdvertiseAddr string - - // BindPort is the local node's port to which we bind to for - // cluster communication. - BindPort int - - // Keys to be added to the Keyring of the memberlist. Key at index - // 0 is the primary key - Keys [][]byte - - // PacketBufferSize is the maximum number of bytes that memberlist will - // put in a packet (this will be for UDP packets by default with a NetTransport). - // A safe value for this is typically 1400 bytes (which is the default). However, - // depending on your network's MTU (Maximum Transmission Unit) you may - // be able to increase this to get more content into each gossip packet. - PacketBufferSize int - - // reapEntryInterval duration of a deleted entry before being garbage collected - reapEntryInterval time.Duration - - // reapNetworkInterval duration of a delted network before being garbage collected - // NOTE this MUST always be higher than reapEntryInterval - reapNetworkInterval time.Duration - - // StatsPrintPeriod the period to use to print queue stats - // Default is 5min - StatsPrintPeriod time.Duration - - // HealthPrintPeriod the period to use to print the health score - // Default is 1min - HealthPrintPeriod time.Duration -} - -// entry defines a table entry -type entry struct { - // node from which this entry was learned. - node string - - // Lamport time for the most recent update to the entry - ltime serf.LamportTime - - // Opaque value store in the entry - value []byte - - // Deleting the entry is in progress. All entries linger in - // the cluster for certain amount of time after deletion. - deleting bool - - // Number of seconds still left before a deleted table entry gets - // removed from networkDB - reapTime time.Duration -} - -// 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, - } -} - -// 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 -} - -// 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) -} - -// 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() -} - -// 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 -} - -// 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 -} - -// 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 -} - -func (nDB *NetworkDB) getEntry(tname, nid, key string) (*entry, error) { - e, ok := nDB.indexes[byTable].Get(fmt.Sprintf("/%s/%s/%s", tname, nid, key)) - if !ok { - return nil, types.NotFoundErrorf("could not get entry in table %s with network id %s and key %s", tname, nid, key) - } - - return e.(*entry), nil -} - -// 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 -} - -// 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 -} - -// TableElem elem -type TableElem struct { - Value []byte - owner string -} - -// 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 -} - -// 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 -} - -func (nDB *NetworkDB) deleteNodeFromNetworks(deletedNode string) { - for nid, nodes := range nDB.networkNodes { - updatedNodes := make([]string, 0, len(nodes)) - for _, node := range nodes { - if node == deletedNode { - continue - } - - updatedNodes = append(updatedNodes, node) - } - - nDB.networkNodes[nid] = updatedNodes - } - - delete(nDB.networks, deletedNode) -} - -// 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 - }) -} - -func (nDB *NetworkDB) deleteNodeTableEntries(node string) { - nDB.indexes[byTable].Walk(func(path string, v interface{}) bool { - oldEntry := v.(*entry) - if oldEntry.node != node { - return false - } - - params := strings.Split(path[1:], "/") - tname := params[0] - nid := params[1] - key := params[2] - - nDB.deleteEntry(nid, tname, key) - - if !oldEntry.deleting { - nDB.broadcaster.Write(makeEvent(opDelete, tname, nid, key, oldEntry.value)) - } - return false - }) -} - -// 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 -} - -// 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 -} - -// 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 -} - -// 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) -} - -// 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 -} - -// 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 -} - -func (nDB *NetworkDB) updateLocalNetworkTime() { - nDB.Lock() - defer nDB.Unlock() - - ltime := nDB.networkClock.Increment() - for _, n := range nDB.networks[nDB.config.NodeID] { - n.ltime = ltime - } -} - -// 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 -} - -// deleteEntry this function handles the deletion 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) deleteEntry(nid, tname, key string) (bool, bool) { - _, okTable := nDB.indexes[byTable].Delete(fmt.Sprintf("/%s/%s/%s", tname, nid, key)) - _, okNetwork := nDB.indexes[byNetwork].Delete(fmt.Sprintf("/%s/%s/%s", nid, tname, key)) - if okNetwork { - // Remove only if the delete is successful - n, ok := nDB.networks[nDB.config.NodeID][nid] - if ok { - n.entriesNumber-- - } - } - return okTable, okNetwork -} diff --git a/vendor/github.com/docker/libnetwork/networkdb/networkdb.pb.go b/vendor/github.com/docker/libnetwork/networkdb/networkdb.pb.go deleted file mode 100644 index aa6fe21410..0000000000 --- a/vendor/github.com/docker/libnetwork/networkdb/networkdb.pb.go +++ /dev/null @@ -1,2715 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: networkdb/networkdb.proto - -/* - Package networkdb is a generated protocol buffer package. - - It is generated from these files: - networkdb/networkdb.proto - - It has these top-level messages: - GossipMessage - NodeEvent - NetworkEvent - NetworkEntry - NetworkPushPull - TableEvent - BulkSyncMessage - CompoundMessage -*/ -package networkdb - -import proto "github.com/gogo/protobuf/proto" -import fmt "fmt" -import math "math" -import _ "github.com/gogo/protobuf/gogoproto" - -import github_com_hashicorp_serf_serf "github.com/hashicorp/serf/serf" - -import strings "strings" -import reflect "reflect" - -import io "io" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package - -// MessageType enum defines all the core message types that networkdb -// uses to communicate to peers. -type MessageType int32 - -const ( - MessageTypeInvalid MessageType = 0 - // NetworkEvent message type is used to communicate network - // attachments on the node. - MessageTypeNetworkEvent MessageType = 1 - // TableEvent message type is used to communicate any table - // CRUD event that happened on the node. - MessageTypeTableEvent MessageType = 2 - // PushPull message type is used to syncup all network - // attachments on a peer node either during startup of this - // node or with a random peer node periodically thereafter. - MessageTypePushPull MessageType = 3 - // BulkSync message is used to bulksync the whole networkdb - // state with a peer node during startup of this node or with - // a random peer node periodically thereafter. - MessageTypeBulkSync MessageType = 4 - // Compound message type is used to form a compound message - // which is a pack of many message of above types, packed into - // a single compound message. - MessageTypeCompound MessageType = 5 - // NodeEvent message type is used to communicate node - // join/leave events in the cluster - MessageTypeNodeEvent MessageType = 6 -) - -var MessageType_name = map[int32]string{ - 0: "INVALID", - 1: "NETWORK_EVENT", - 2: "TABLE_EVENT", - 3: "PUSH_PULL", - 4: "BULK_SYNC", - 5: "COMPOUND", - 6: "NODE_EVENT", -} -var MessageType_value = map[string]int32{ - "INVALID": 0, - "NETWORK_EVENT": 1, - "TABLE_EVENT": 2, - "PUSH_PULL": 3, - "BULK_SYNC": 4, - "COMPOUND": 5, - "NODE_EVENT": 6, -} - -func (x MessageType) String() string { - return proto.EnumName(MessageType_name, int32(x)) -} -func (MessageType) EnumDescriptor() ([]byte, []int) { return fileDescriptorNetworkdb, []int{0} } - -type NodeEvent_Type int32 - -const ( - NodeEventTypeInvalid NodeEvent_Type = 0 - // Join event is generated when this node joins the cluster. - NodeEventTypeJoin NodeEvent_Type = 1 - // Leave event is generated when this node leaves the cluster. - NodeEventTypeLeave NodeEvent_Type = 2 -) - -var NodeEvent_Type_name = map[int32]string{ - 0: "INVALID", - 1: "JOIN", - 2: "LEAVE", -} -var NodeEvent_Type_value = map[string]int32{ - "INVALID": 0, - "JOIN": 1, - "LEAVE": 2, -} - -func (x NodeEvent_Type) String() string { - return proto.EnumName(NodeEvent_Type_name, int32(x)) -} -func (NodeEvent_Type) EnumDescriptor() ([]byte, []int) { return fileDescriptorNetworkdb, []int{1, 0} } - -type NetworkEvent_Type int32 - -const ( - NetworkEventTypeInvalid NetworkEvent_Type = 0 - // Join event is generated when this node joins a network. - NetworkEventTypeJoin NetworkEvent_Type = 1 - // Leave event is generated when this node leaves a network. - NetworkEventTypeLeave NetworkEvent_Type = 2 -) - -var NetworkEvent_Type_name = map[int32]string{ - 0: "INVALID", - 1: "JOIN", - 2: "LEAVE", -} -var NetworkEvent_Type_value = map[string]int32{ - "INVALID": 0, - "JOIN": 1, - "LEAVE": 2, -} - -func (x NetworkEvent_Type) String() string { - return proto.EnumName(NetworkEvent_Type_name, int32(x)) -} -func (NetworkEvent_Type) EnumDescriptor() ([]byte, []int) { return fileDescriptorNetworkdb, []int{2, 0} } - -type TableEvent_Type int32 - -const ( - TableEventTypeInvalid TableEvent_Type = 0 - // Create signifies that this table entry was just - // created. - TableEventTypeCreate TableEvent_Type = 1 - // Update signifies that this table entry was just - // updated. - TableEventTypeUpdate TableEvent_Type = 2 - // Delete signifies that this table entry was just - // updated. - TableEventTypeDelete TableEvent_Type = 3 -) - -var TableEvent_Type_name = map[int32]string{ - 0: "INVALID", - 1: "CREATE", - 2: "UPDATE", - 3: "DELETE", -} -var TableEvent_Type_value = map[string]int32{ - "INVALID": 0, - "CREATE": 1, - "UPDATE": 2, - "DELETE": 3, -} - -func (x TableEvent_Type) String() string { - return proto.EnumName(TableEvent_Type_name, int32(x)) -} -func (TableEvent_Type) EnumDescriptor() ([]byte, []int) { return fileDescriptorNetworkdb, []int{5, 0} } - -// GossipMessage is a basic message header used by all messages types. -type GossipMessage struct { - Type MessageType `protobuf:"varint,1,opt,name=type,proto3,enum=networkdb.MessageType" json:"type,omitempty"` - Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"` -} - -func (m *GossipMessage) Reset() { *m = GossipMessage{} } -func (*GossipMessage) ProtoMessage() {} -func (*GossipMessage) Descriptor() ([]byte, []int) { return fileDescriptorNetworkdb, []int{0} } - -func (m *GossipMessage) GetType() MessageType { - if m != nil { - return m.Type - } - return MessageTypeInvalid -} - -func (m *GossipMessage) GetData() []byte { - if m != nil { - return m.Data - } - return nil -} - -// NodeEvent message payload definition. -type NodeEvent struct { - Type NodeEvent_Type `protobuf:"varint,1,opt,name=type,proto3,enum=networkdb.NodeEvent_Type" json:"type,omitempty"` - // Lamport time using a network lamport clock indicating the - // time this event was generated on the node where it was - // generated. - LTime github_com_hashicorp_serf_serf.LamportTime `protobuf:"varint,2,opt,name=l_time,json=lTime,proto3,customtype=github.com/hashicorp/serf/serf.LamportTime" json:"l_time"` - // Source node name. - NodeName string `protobuf:"bytes,3,opt,name=node_name,json=nodeName,proto3" json:"node_name,omitempty"` -} - -func (m *NodeEvent) Reset() { *m = NodeEvent{} } -func (*NodeEvent) ProtoMessage() {} -func (*NodeEvent) Descriptor() ([]byte, []int) { return fileDescriptorNetworkdb, []int{1} } - -func (m *NodeEvent) GetType() NodeEvent_Type { - if m != nil { - return m.Type - } - return NodeEventTypeInvalid -} - -func (m *NodeEvent) GetNodeName() string { - if m != nil { - return m.NodeName - } - return "" -} - -// NetworkEvent message payload definition. -type NetworkEvent struct { - Type NetworkEvent_Type `protobuf:"varint,1,opt,name=type,proto3,enum=networkdb.NetworkEvent_Type" json:"type,omitempty"` - // Lamport time using a network lamport clock indicating the - // time this event was generated on the node where it was - // generated. - LTime github_com_hashicorp_serf_serf.LamportTime `protobuf:"varint,2,opt,name=l_time,json=lTime,proto3,customtype=github.com/hashicorp/serf/serf.LamportTime" json:"l_time"` - // Source node name. - NodeName string `protobuf:"bytes,3,opt,name=node_name,json=nodeName,proto3" json:"node_name,omitempty"` - // ID of the network for which the event is generated. - NetworkID string `protobuf:"bytes,4,opt,name=network_id,json=networkId,proto3" json:"network_id,omitempty"` -} - -func (m *NetworkEvent) Reset() { *m = NetworkEvent{} } -func (*NetworkEvent) ProtoMessage() {} -func (*NetworkEvent) Descriptor() ([]byte, []int) { return fileDescriptorNetworkdb, []int{2} } - -func (m *NetworkEvent) GetType() NetworkEvent_Type { - if m != nil { - return m.Type - } - return NetworkEventTypeInvalid -} - -func (m *NetworkEvent) GetNodeName() string { - if m != nil { - return m.NodeName - } - return "" -} - -func (m *NetworkEvent) GetNetworkID() string { - if m != nil { - return m.NetworkID - } - return "" -} - -// NetworkEntry for push pull of networks. -type NetworkEntry struct { - // ID of the network - NetworkID string `protobuf:"bytes,1,opt,name=network_id,json=networkId,proto3" json:"network_id,omitempty"` - // Latest lamport time of the network attachment when this - // network event was recorded. - LTime github_com_hashicorp_serf_serf.LamportTime `protobuf:"varint,2,opt,name=l_time,json=lTime,proto3,customtype=github.com/hashicorp/serf/serf.LamportTime" json:"l_time"` - // Source node name where this network attachment happened. - NodeName string `protobuf:"bytes,3,opt,name=node_name,json=nodeName,proto3" json:"node_name,omitempty"` - // Indicates if a leave from this network is in progress. - Leaving bool `protobuf:"varint,4,opt,name=leaving,proto3" json:"leaving,omitempty"` -} - -func (m *NetworkEntry) Reset() { *m = NetworkEntry{} } -func (*NetworkEntry) ProtoMessage() {} -func (*NetworkEntry) Descriptor() ([]byte, []int) { return fileDescriptorNetworkdb, []int{3} } - -func (m *NetworkEntry) GetNetworkID() string { - if m != nil { - return m.NetworkID - } - return "" -} - -func (m *NetworkEntry) GetNodeName() string { - if m != nil { - return m.NodeName - } - return "" -} - -func (m *NetworkEntry) GetLeaving() bool { - if m != nil { - return m.Leaving - } - return false -} - -// NetworkPushpull message payload definition. -type NetworkPushPull struct { - // Lamport time when this push pull was initiated. - LTime github_com_hashicorp_serf_serf.LamportTime `protobuf:"varint,1,opt,name=l_time,json=lTime,proto3,customtype=github.com/hashicorp/serf/serf.LamportTime" json:"l_time"` - Networks []*NetworkEntry `protobuf:"bytes,2,rep,name=networks" json:"networks,omitempty"` - // Name of the node sending this push pull payload. - NodeName string `protobuf:"bytes,3,opt,name=node_name,json=nodeName,proto3" json:"node_name,omitempty"` -} - -func (m *NetworkPushPull) Reset() { *m = NetworkPushPull{} } -func (*NetworkPushPull) ProtoMessage() {} -func (*NetworkPushPull) Descriptor() ([]byte, []int) { return fileDescriptorNetworkdb, []int{4} } - -func (m *NetworkPushPull) GetNetworks() []*NetworkEntry { - if m != nil { - return m.Networks - } - return nil -} - -func (m *NetworkPushPull) GetNodeName() string { - if m != nil { - return m.NodeName - } - return "" -} - -// TableEvent message payload definition. -type TableEvent struct { - Type TableEvent_Type `protobuf:"varint,1,opt,name=type,proto3,enum=networkdb.TableEvent_Type" json:"type,omitempty"` - // Lamport time when this event was generated. - LTime github_com_hashicorp_serf_serf.LamportTime `protobuf:"varint,2,opt,name=l_time,json=lTime,proto3,customtype=github.com/hashicorp/serf/serf.LamportTime" json:"l_time"` - // Node name where this event originated. - NodeName string `protobuf:"bytes,3,opt,name=node_name,json=nodeName,proto3" json:"node_name,omitempty"` - // ID of the network to which this table entry belongs. - NetworkID string `protobuf:"bytes,4,opt,name=network_id,json=networkId,proto3" json:"network_id,omitempty"` - // Name of the table to which this table entry belongs. - TableName string `protobuf:"bytes,5,opt,name=table_name,json=tableName,proto3" json:"table_name,omitempty"` - // Entry key. - Key string `protobuf:"bytes,6,opt,name=key,proto3" json:"key,omitempty"` - // Entry value. - Value []byte `protobuf:"bytes,7,opt,name=value,proto3" json:"value,omitempty"` - // Residual reap time for the entry before getting deleted in seconds - ResidualReapTime int32 `protobuf:"varint,8,opt,name=residual_reap_time,json=residualReapTime,proto3" json:"residual_reap_time,omitempty"` -} - -func (m *TableEvent) Reset() { *m = TableEvent{} } -func (*TableEvent) ProtoMessage() {} -func (*TableEvent) Descriptor() ([]byte, []int) { return fileDescriptorNetworkdb, []int{5} } - -func (m *TableEvent) GetType() TableEvent_Type { - if m != nil { - return m.Type - } - return TableEventTypeInvalid -} - -func (m *TableEvent) GetNodeName() string { - if m != nil { - return m.NodeName - } - return "" -} - -func (m *TableEvent) GetNetworkID() string { - if m != nil { - return m.NetworkID - } - return "" -} - -func (m *TableEvent) GetTableName() string { - if m != nil { - return m.TableName - } - return "" -} - -func (m *TableEvent) GetKey() string { - if m != nil { - return m.Key - } - return "" -} - -func (m *TableEvent) GetValue() []byte { - if m != nil { - return m.Value - } - return nil -} - -func (m *TableEvent) GetResidualReapTime() int32 { - if m != nil { - return m.ResidualReapTime - } - return 0 -} - -// BulkSync message payload definition. -type BulkSyncMessage struct { - // Lamport time when this bulk sync was initiated. - LTime github_com_hashicorp_serf_serf.LamportTime `protobuf:"varint,1,opt,name=l_time,json=lTime,proto3,customtype=github.com/hashicorp/serf/serf.LamportTime" json:"l_time"` - // Indicates if this bulksync is a response to a bulk sync - // request from a peer node. - Unsolicited bool `protobuf:"varint,2,opt,name=unsolicited,proto3" json:"unsolicited,omitempty"` - // Name of the node which is producing this bulk sync message. - NodeName string `protobuf:"bytes,3,opt,name=node_name,json=nodeName,proto3" json:"node_name,omitempty"` - // List of network names whose table entries are getting - // bulksynced as part of the bulksync. - Networks []string `protobuf:"bytes,4,rep,name=networks" json:"networks,omitempty"` - // Bulksync payload - Payload []byte `protobuf:"bytes,5,opt,name=payload,proto3" json:"payload,omitempty"` -} - -func (m *BulkSyncMessage) Reset() { *m = BulkSyncMessage{} } -func (*BulkSyncMessage) ProtoMessage() {} -func (*BulkSyncMessage) Descriptor() ([]byte, []int) { return fileDescriptorNetworkdb, []int{6} } - -func (m *BulkSyncMessage) GetUnsolicited() bool { - if m != nil { - return m.Unsolicited - } - return false -} - -func (m *BulkSyncMessage) GetNodeName() string { - if m != nil { - return m.NodeName - } - return "" -} - -func (m *BulkSyncMessage) GetNetworks() []string { - if m != nil { - return m.Networks - } - return nil -} - -func (m *BulkSyncMessage) GetPayload() []byte { - if m != nil { - return m.Payload - } - return nil -} - -// Compound message payload definition. -type CompoundMessage struct { - // A list of simple messages. - Messages []*CompoundMessage_SimpleMessage `protobuf:"bytes,1,rep,name=messages" json:"messages,omitempty"` -} - -func (m *CompoundMessage) Reset() { *m = CompoundMessage{} } -func (*CompoundMessage) ProtoMessage() {} -func (*CompoundMessage) Descriptor() ([]byte, []int) { return fileDescriptorNetworkdb, []int{7} } - -func (m *CompoundMessage) GetMessages() []*CompoundMessage_SimpleMessage { - if m != nil { - return m.Messages - } - return nil -} - -type CompoundMessage_SimpleMessage struct { - // Bytestring payload of a message constructed using - // other message type definitions. - Payload []byte `protobuf:"bytes,1,opt,name=Payload,proto3" json:"Payload,omitempty"` -} - -func (m *CompoundMessage_SimpleMessage) Reset() { *m = CompoundMessage_SimpleMessage{} } -func (*CompoundMessage_SimpleMessage) ProtoMessage() {} -func (*CompoundMessage_SimpleMessage) Descriptor() ([]byte, []int) { - return fileDescriptorNetworkdb, []int{7, 0} -} - -func (m *CompoundMessage_SimpleMessage) GetPayload() []byte { - if m != nil { - return m.Payload - } - return nil -} - -func init() { - proto.RegisterType((*GossipMessage)(nil), "networkdb.GossipMessage") - proto.RegisterType((*NodeEvent)(nil), "networkdb.NodeEvent") - proto.RegisterType((*NetworkEvent)(nil), "networkdb.NetworkEvent") - proto.RegisterType((*NetworkEntry)(nil), "networkdb.NetworkEntry") - proto.RegisterType((*NetworkPushPull)(nil), "networkdb.NetworkPushPull") - proto.RegisterType((*TableEvent)(nil), "networkdb.TableEvent") - proto.RegisterType((*BulkSyncMessage)(nil), "networkdb.BulkSyncMessage") - proto.RegisterType((*CompoundMessage)(nil), "networkdb.CompoundMessage") - proto.RegisterType((*CompoundMessage_SimpleMessage)(nil), "networkdb.CompoundMessage.SimpleMessage") - proto.RegisterEnum("networkdb.MessageType", MessageType_name, MessageType_value) - proto.RegisterEnum("networkdb.NodeEvent_Type", NodeEvent_Type_name, NodeEvent_Type_value) - proto.RegisterEnum("networkdb.NetworkEvent_Type", NetworkEvent_Type_name, NetworkEvent_Type_value) - proto.RegisterEnum("networkdb.TableEvent_Type", TableEvent_Type_name, TableEvent_Type_value) -} -func (this *GossipMessage) GoString() string { - if this == nil { - return "nil" - } - s := make([]string, 0, 6) - s = append(s, "&networkdb.GossipMessage{") - s = append(s, "Type: "+fmt.Sprintf("%#v", this.Type)+",\n") - s = append(s, "Data: "+fmt.Sprintf("%#v", this.Data)+",\n") - s = append(s, "}") - return strings.Join(s, "") -} -func (this *NodeEvent) GoString() string { - if this == nil { - return "nil" - } - s := make([]string, 0, 7) - s = append(s, "&networkdb.NodeEvent{") - s = append(s, "Type: "+fmt.Sprintf("%#v", this.Type)+",\n") - s = append(s, "LTime: "+fmt.Sprintf("%#v", this.LTime)+",\n") - s = append(s, "NodeName: "+fmt.Sprintf("%#v", this.NodeName)+",\n") - s = append(s, "}") - return strings.Join(s, "") -} -func (this *NetworkEvent) GoString() string { - if this == nil { - return "nil" - } - s := make([]string, 0, 8) - s = append(s, "&networkdb.NetworkEvent{") - s = append(s, "Type: "+fmt.Sprintf("%#v", this.Type)+",\n") - s = append(s, "LTime: "+fmt.Sprintf("%#v", this.LTime)+",\n") - s = append(s, "NodeName: "+fmt.Sprintf("%#v", this.NodeName)+",\n") - s = append(s, "NetworkID: "+fmt.Sprintf("%#v", this.NetworkID)+",\n") - s = append(s, "}") - return strings.Join(s, "") -} -func (this *NetworkEntry) GoString() string { - if this == nil { - return "nil" - } - s := make([]string, 0, 8) - s = append(s, "&networkdb.NetworkEntry{") - s = append(s, "NetworkID: "+fmt.Sprintf("%#v", this.NetworkID)+",\n") - s = append(s, "LTime: "+fmt.Sprintf("%#v", this.LTime)+",\n") - s = append(s, "NodeName: "+fmt.Sprintf("%#v", this.NodeName)+",\n") - s = append(s, "Leaving: "+fmt.Sprintf("%#v", this.Leaving)+",\n") - s = append(s, "}") - return strings.Join(s, "") -} -func (this *NetworkPushPull) GoString() string { - if this == nil { - return "nil" - } - s := make([]string, 0, 7) - s = append(s, "&networkdb.NetworkPushPull{") - s = append(s, "LTime: "+fmt.Sprintf("%#v", this.LTime)+",\n") - if this.Networks != nil { - s = append(s, "Networks: "+fmt.Sprintf("%#v", this.Networks)+",\n") - } - s = append(s, "NodeName: "+fmt.Sprintf("%#v", this.NodeName)+",\n") - s = append(s, "}") - return strings.Join(s, "") -} -func (this *TableEvent) GoString() string { - if this == nil { - return "nil" - } - s := make([]string, 0, 12) - s = append(s, "&networkdb.TableEvent{") - s = append(s, "Type: "+fmt.Sprintf("%#v", this.Type)+",\n") - s = append(s, "LTime: "+fmt.Sprintf("%#v", this.LTime)+",\n") - s = append(s, "NodeName: "+fmt.Sprintf("%#v", this.NodeName)+",\n") - s = append(s, "NetworkID: "+fmt.Sprintf("%#v", this.NetworkID)+",\n") - s = append(s, "TableName: "+fmt.Sprintf("%#v", this.TableName)+",\n") - s = append(s, "Key: "+fmt.Sprintf("%#v", this.Key)+",\n") - s = append(s, "Value: "+fmt.Sprintf("%#v", this.Value)+",\n") - s = append(s, "ResidualReapTime: "+fmt.Sprintf("%#v", this.ResidualReapTime)+",\n") - s = append(s, "}") - return strings.Join(s, "") -} -func (this *BulkSyncMessage) GoString() string { - if this == nil { - return "nil" - } - s := make([]string, 0, 9) - s = append(s, "&networkdb.BulkSyncMessage{") - s = append(s, "LTime: "+fmt.Sprintf("%#v", this.LTime)+",\n") - s = append(s, "Unsolicited: "+fmt.Sprintf("%#v", this.Unsolicited)+",\n") - s = append(s, "NodeName: "+fmt.Sprintf("%#v", this.NodeName)+",\n") - s = append(s, "Networks: "+fmt.Sprintf("%#v", this.Networks)+",\n") - s = append(s, "Payload: "+fmt.Sprintf("%#v", this.Payload)+",\n") - s = append(s, "}") - return strings.Join(s, "") -} -func (this *CompoundMessage) GoString() string { - if this == nil { - return "nil" - } - s := make([]string, 0, 5) - s = append(s, "&networkdb.CompoundMessage{") - if this.Messages != nil { - s = append(s, "Messages: "+fmt.Sprintf("%#v", this.Messages)+",\n") - } - s = append(s, "}") - return strings.Join(s, "") -} -func (this *CompoundMessage_SimpleMessage) GoString() string { - if this == nil { - return "nil" - } - s := make([]string, 0, 5) - s = append(s, "&networkdb.CompoundMessage_SimpleMessage{") - s = append(s, "Payload: "+fmt.Sprintf("%#v", this.Payload)+",\n") - s = append(s, "}") - return strings.Join(s, "") -} -func valueToGoStringNetworkdb(v interface{}, typ string) string { - rv := reflect.ValueOf(v) - if rv.IsNil() { - return "nil" - } - pv := reflect.Indirect(rv).Interface() - return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv) -} -func (m *GossipMessage) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalTo(dAtA) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *GossipMessage) MarshalTo(dAtA []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if m.Type != 0 { - dAtA[i] = 0x8 - i++ - i = encodeVarintNetworkdb(dAtA, i, uint64(m.Type)) - } - if len(m.Data) > 0 { - dAtA[i] = 0x12 - i++ - i = encodeVarintNetworkdb(dAtA, i, uint64(len(m.Data))) - i += copy(dAtA[i:], m.Data) - } - return i, nil -} - -func (m *NodeEvent) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalTo(dAtA) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *NodeEvent) MarshalTo(dAtA []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if m.Type != 0 { - dAtA[i] = 0x8 - i++ - i = encodeVarintNetworkdb(dAtA, i, uint64(m.Type)) - } - if m.LTime != 0 { - dAtA[i] = 0x10 - i++ - i = encodeVarintNetworkdb(dAtA, i, uint64(m.LTime)) - } - if len(m.NodeName) > 0 { - dAtA[i] = 0x1a - i++ - i = encodeVarintNetworkdb(dAtA, i, uint64(len(m.NodeName))) - i += copy(dAtA[i:], m.NodeName) - } - return i, nil -} - -func (m *NetworkEvent) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalTo(dAtA) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *NetworkEvent) MarshalTo(dAtA []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if m.Type != 0 { - dAtA[i] = 0x8 - i++ - i = encodeVarintNetworkdb(dAtA, i, uint64(m.Type)) - } - if m.LTime != 0 { - dAtA[i] = 0x10 - i++ - i = encodeVarintNetworkdb(dAtA, i, uint64(m.LTime)) - } - if len(m.NodeName) > 0 { - dAtA[i] = 0x1a - i++ - i = encodeVarintNetworkdb(dAtA, i, uint64(len(m.NodeName))) - i += copy(dAtA[i:], m.NodeName) - } - if len(m.NetworkID) > 0 { - dAtA[i] = 0x22 - i++ - i = encodeVarintNetworkdb(dAtA, i, uint64(len(m.NetworkID))) - i += copy(dAtA[i:], m.NetworkID) - } - return i, nil -} - -func (m *NetworkEntry) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalTo(dAtA) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *NetworkEntry) MarshalTo(dAtA []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if len(m.NetworkID) > 0 { - dAtA[i] = 0xa - i++ - i = encodeVarintNetworkdb(dAtA, i, uint64(len(m.NetworkID))) - i += copy(dAtA[i:], m.NetworkID) - } - if m.LTime != 0 { - dAtA[i] = 0x10 - i++ - i = encodeVarintNetworkdb(dAtA, i, uint64(m.LTime)) - } - if len(m.NodeName) > 0 { - dAtA[i] = 0x1a - i++ - i = encodeVarintNetworkdb(dAtA, i, uint64(len(m.NodeName))) - i += copy(dAtA[i:], m.NodeName) - } - if m.Leaving { - dAtA[i] = 0x20 - i++ - if m.Leaving { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i++ - } - return i, nil -} - -func (m *NetworkPushPull) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalTo(dAtA) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *NetworkPushPull) MarshalTo(dAtA []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if m.LTime != 0 { - dAtA[i] = 0x8 - i++ - i = encodeVarintNetworkdb(dAtA, i, uint64(m.LTime)) - } - if len(m.Networks) > 0 { - for _, msg := range m.Networks { - dAtA[i] = 0x12 - i++ - i = encodeVarintNetworkdb(dAtA, i, uint64(msg.Size())) - n, err := msg.MarshalTo(dAtA[i:]) - if err != nil { - return 0, err - } - i += n - } - } - if len(m.NodeName) > 0 { - dAtA[i] = 0x1a - i++ - i = encodeVarintNetworkdb(dAtA, i, uint64(len(m.NodeName))) - i += copy(dAtA[i:], m.NodeName) - } - return i, nil -} - -func (m *TableEvent) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalTo(dAtA) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *TableEvent) MarshalTo(dAtA []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if m.Type != 0 { - dAtA[i] = 0x8 - i++ - i = encodeVarintNetworkdb(dAtA, i, uint64(m.Type)) - } - if m.LTime != 0 { - dAtA[i] = 0x10 - i++ - i = encodeVarintNetworkdb(dAtA, i, uint64(m.LTime)) - } - if len(m.NodeName) > 0 { - dAtA[i] = 0x1a - i++ - i = encodeVarintNetworkdb(dAtA, i, uint64(len(m.NodeName))) - i += copy(dAtA[i:], m.NodeName) - } - if len(m.NetworkID) > 0 { - dAtA[i] = 0x22 - i++ - i = encodeVarintNetworkdb(dAtA, i, uint64(len(m.NetworkID))) - i += copy(dAtA[i:], m.NetworkID) - } - if len(m.TableName) > 0 { - dAtA[i] = 0x2a - i++ - i = encodeVarintNetworkdb(dAtA, i, uint64(len(m.TableName))) - i += copy(dAtA[i:], m.TableName) - } - if len(m.Key) > 0 { - dAtA[i] = 0x32 - i++ - i = encodeVarintNetworkdb(dAtA, i, uint64(len(m.Key))) - i += copy(dAtA[i:], m.Key) - } - if len(m.Value) > 0 { - dAtA[i] = 0x3a - i++ - i = encodeVarintNetworkdb(dAtA, i, uint64(len(m.Value))) - i += copy(dAtA[i:], m.Value) - } - if m.ResidualReapTime != 0 { - dAtA[i] = 0x40 - i++ - i = encodeVarintNetworkdb(dAtA, i, uint64(m.ResidualReapTime)) - } - return i, nil -} - -func (m *BulkSyncMessage) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalTo(dAtA) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *BulkSyncMessage) MarshalTo(dAtA []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if m.LTime != 0 { - dAtA[i] = 0x8 - i++ - i = encodeVarintNetworkdb(dAtA, i, uint64(m.LTime)) - } - if m.Unsolicited { - dAtA[i] = 0x10 - i++ - if m.Unsolicited { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i++ - } - if len(m.NodeName) > 0 { - dAtA[i] = 0x1a - i++ - i = encodeVarintNetworkdb(dAtA, i, uint64(len(m.NodeName))) - i += copy(dAtA[i:], m.NodeName) - } - if len(m.Networks) > 0 { - for _, s := range m.Networks { - dAtA[i] = 0x22 - i++ - l = len(s) - for l >= 1<<7 { - dAtA[i] = uint8(uint64(l)&0x7f | 0x80) - l >>= 7 - i++ - } - dAtA[i] = uint8(l) - i++ - i += copy(dAtA[i:], s) - } - } - if len(m.Payload) > 0 { - dAtA[i] = 0x2a - i++ - i = encodeVarintNetworkdb(dAtA, i, uint64(len(m.Payload))) - i += copy(dAtA[i:], m.Payload) - } - return i, nil -} - -func (m *CompoundMessage) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalTo(dAtA) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *CompoundMessage) MarshalTo(dAtA []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if len(m.Messages) > 0 { - for _, msg := range m.Messages { - dAtA[i] = 0xa - i++ - i = encodeVarintNetworkdb(dAtA, i, uint64(msg.Size())) - n, err := msg.MarshalTo(dAtA[i:]) - if err != nil { - return 0, err - } - i += n - } - } - return i, nil -} - -func (m *CompoundMessage_SimpleMessage) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalTo(dAtA) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *CompoundMessage_SimpleMessage) MarshalTo(dAtA []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if len(m.Payload) > 0 { - dAtA[i] = 0xa - i++ - i = encodeVarintNetworkdb(dAtA, i, uint64(len(m.Payload))) - i += copy(dAtA[i:], m.Payload) - } - return i, nil -} - -func encodeVarintNetworkdb(dAtA []byte, offset int, v uint64) int { - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return offset + 1 -} -func (m *GossipMessage) Size() (n int) { - var l int - _ = l - if m.Type != 0 { - n += 1 + sovNetworkdb(uint64(m.Type)) - } - l = len(m.Data) - if l > 0 { - n += 1 + l + sovNetworkdb(uint64(l)) - } - return n -} - -func (m *NodeEvent) Size() (n int) { - var l int - _ = l - if m.Type != 0 { - n += 1 + sovNetworkdb(uint64(m.Type)) - } - if m.LTime != 0 { - n += 1 + sovNetworkdb(uint64(m.LTime)) - } - l = len(m.NodeName) - if l > 0 { - n += 1 + l + sovNetworkdb(uint64(l)) - } - return n -} - -func (m *NetworkEvent) Size() (n int) { - var l int - _ = l - if m.Type != 0 { - n += 1 + sovNetworkdb(uint64(m.Type)) - } - if m.LTime != 0 { - n += 1 + sovNetworkdb(uint64(m.LTime)) - } - l = len(m.NodeName) - if l > 0 { - n += 1 + l + sovNetworkdb(uint64(l)) - } - l = len(m.NetworkID) - if l > 0 { - n += 1 + l + sovNetworkdb(uint64(l)) - } - return n -} - -func (m *NetworkEntry) Size() (n int) { - var l int - _ = l - l = len(m.NetworkID) - if l > 0 { - n += 1 + l + sovNetworkdb(uint64(l)) - } - if m.LTime != 0 { - n += 1 + sovNetworkdb(uint64(m.LTime)) - } - l = len(m.NodeName) - if l > 0 { - n += 1 + l + sovNetworkdb(uint64(l)) - } - if m.Leaving { - n += 2 - } - return n -} - -func (m *NetworkPushPull) Size() (n int) { - var l int - _ = l - if m.LTime != 0 { - n += 1 + sovNetworkdb(uint64(m.LTime)) - } - if len(m.Networks) > 0 { - for _, e := range m.Networks { - l = e.Size() - n += 1 + l + sovNetworkdb(uint64(l)) - } - } - l = len(m.NodeName) - if l > 0 { - n += 1 + l + sovNetworkdb(uint64(l)) - } - return n -} - -func (m *TableEvent) Size() (n int) { - var l int - _ = l - if m.Type != 0 { - n += 1 + sovNetworkdb(uint64(m.Type)) - } - if m.LTime != 0 { - n += 1 + sovNetworkdb(uint64(m.LTime)) - } - l = len(m.NodeName) - if l > 0 { - n += 1 + l + sovNetworkdb(uint64(l)) - } - l = len(m.NetworkID) - if l > 0 { - n += 1 + l + sovNetworkdb(uint64(l)) - } - l = len(m.TableName) - if l > 0 { - n += 1 + l + sovNetworkdb(uint64(l)) - } - l = len(m.Key) - if l > 0 { - n += 1 + l + sovNetworkdb(uint64(l)) - } - l = len(m.Value) - if l > 0 { - n += 1 + l + sovNetworkdb(uint64(l)) - } - if m.ResidualReapTime != 0 { - n += 1 + sovNetworkdb(uint64(m.ResidualReapTime)) - } - return n -} - -func (m *BulkSyncMessage) Size() (n int) { - var l int - _ = l - if m.LTime != 0 { - n += 1 + sovNetworkdb(uint64(m.LTime)) - } - if m.Unsolicited { - n += 2 - } - l = len(m.NodeName) - if l > 0 { - n += 1 + l + sovNetworkdb(uint64(l)) - } - if len(m.Networks) > 0 { - for _, s := range m.Networks { - l = len(s) - n += 1 + l + sovNetworkdb(uint64(l)) - } - } - l = len(m.Payload) - if l > 0 { - n += 1 + l + sovNetworkdb(uint64(l)) - } - return n -} - -func (m *CompoundMessage) Size() (n int) { - var l int - _ = l - if len(m.Messages) > 0 { - for _, e := range m.Messages { - l = e.Size() - n += 1 + l + sovNetworkdb(uint64(l)) - } - } - return n -} - -func (m *CompoundMessage_SimpleMessage) Size() (n int) { - var l int - _ = l - l = len(m.Payload) - if l > 0 { - n += 1 + l + sovNetworkdb(uint64(l)) - } - return n -} - -func sovNetworkdb(x uint64) (n int) { - for { - n++ - x >>= 7 - if x == 0 { - break - } - } - return n -} -func sozNetworkdb(x uint64) (n int) { - return sovNetworkdb(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (this *GossipMessage) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&GossipMessage{`, - `Type:` + fmt.Sprintf("%v", this.Type) + `,`, - `Data:` + fmt.Sprintf("%v", this.Data) + `,`, - `}`, - }, "") - return s -} -func (this *NodeEvent) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&NodeEvent{`, - `Type:` + fmt.Sprintf("%v", this.Type) + `,`, - `LTime:` + fmt.Sprintf("%v", this.LTime) + `,`, - `NodeName:` + fmt.Sprintf("%v", this.NodeName) + `,`, - `}`, - }, "") - return s -} -func (this *NetworkEvent) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&NetworkEvent{`, - `Type:` + fmt.Sprintf("%v", this.Type) + `,`, - `LTime:` + fmt.Sprintf("%v", this.LTime) + `,`, - `NodeName:` + fmt.Sprintf("%v", this.NodeName) + `,`, - `NetworkID:` + fmt.Sprintf("%v", this.NetworkID) + `,`, - `}`, - }, "") - return s -} -func (this *NetworkEntry) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&NetworkEntry{`, - `NetworkID:` + fmt.Sprintf("%v", this.NetworkID) + `,`, - `LTime:` + fmt.Sprintf("%v", this.LTime) + `,`, - `NodeName:` + fmt.Sprintf("%v", this.NodeName) + `,`, - `Leaving:` + fmt.Sprintf("%v", this.Leaving) + `,`, - `}`, - }, "") - return s -} -func (this *NetworkPushPull) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&NetworkPushPull{`, - `LTime:` + fmt.Sprintf("%v", this.LTime) + `,`, - `Networks:` + strings.Replace(fmt.Sprintf("%v", this.Networks), "NetworkEntry", "NetworkEntry", 1) + `,`, - `NodeName:` + fmt.Sprintf("%v", this.NodeName) + `,`, - `}`, - }, "") - return s -} -func (this *TableEvent) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&TableEvent{`, - `Type:` + fmt.Sprintf("%v", this.Type) + `,`, - `LTime:` + fmt.Sprintf("%v", this.LTime) + `,`, - `NodeName:` + fmt.Sprintf("%v", this.NodeName) + `,`, - `NetworkID:` + fmt.Sprintf("%v", this.NetworkID) + `,`, - `TableName:` + fmt.Sprintf("%v", this.TableName) + `,`, - `Key:` + fmt.Sprintf("%v", this.Key) + `,`, - `Value:` + fmt.Sprintf("%v", this.Value) + `,`, - `ResidualReapTime:` + fmt.Sprintf("%v", this.ResidualReapTime) + `,`, - `}`, - }, "") - return s -} -func (this *BulkSyncMessage) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&BulkSyncMessage{`, - `LTime:` + fmt.Sprintf("%v", this.LTime) + `,`, - `Unsolicited:` + fmt.Sprintf("%v", this.Unsolicited) + `,`, - `NodeName:` + fmt.Sprintf("%v", this.NodeName) + `,`, - `Networks:` + fmt.Sprintf("%v", this.Networks) + `,`, - `Payload:` + fmt.Sprintf("%v", this.Payload) + `,`, - `}`, - }, "") - return s -} -func (this *CompoundMessage) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&CompoundMessage{`, - `Messages:` + strings.Replace(fmt.Sprintf("%v", this.Messages), "CompoundMessage_SimpleMessage", "CompoundMessage_SimpleMessage", 1) + `,`, - `}`, - }, "") - return s -} -func (this *CompoundMessage_SimpleMessage) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&CompoundMessage_SimpleMessage{`, - `Payload:` + fmt.Sprintf("%v", this.Payload) + `,`, - `}`, - }, "") - return s -} -func valueToStringNetworkdb(v interface{}) string { - rv := reflect.ValueOf(v) - if rv.IsNil() { - return "nil" - } - pv := reflect.Indirect(rv).Interface() - return fmt.Sprintf("*%v", pv) -} -func (m *GossipMessage) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: GossipMessage: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: GossipMessage: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) - } - m.Type = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Type |= (MessageType(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthNetworkdb - } - postIndex := iNdEx + byteLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...) - if m.Data == nil { - m.Data = []byte{} - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipNetworkdb(dAtA[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthNetworkdb - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *NodeEvent) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: NodeEvent: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: NodeEvent: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) - } - m.Type = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Type |= (NodeEvent_Type(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field LTime", wireType) - } - m.LTime = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.LTime |= (github_com_hashicorp_serf_serf.LamportTime(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field NodeName", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthNetworkdb - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.NodeName = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipNetworkdb(dAtA[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthNetworkdb - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *NetworkEvent) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: NetworkEvent: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: NetworkEvent: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) - } - m.Type = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Type |= (NetworkEvent_Type(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field LTime", wireType) - } - m.LTime = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.LTime |= (github_com_hashicorp_serf_serf.LamportTime(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field NodeName", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthNetworkdb - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.NodeName = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field NetworkID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthNetworkdb - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.NetworkID = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipNetworkdb(dAtA[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthNetworkdb - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *NetworkEntry) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: NetworkEntry: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: NetworkEntry: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field NetworkID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthNetworkdb - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.NetworkID = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field LTime", wireType) - } - m.LTime = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.LTime |= (github_com_hashicorp_serf_serf.LamportTime(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field NodeName", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthNetworkdb - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.NodeName = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Leaving", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - m.Leaving = bool(v != 0) - default: - iNdEx = preIndex - skippy, err := skipNetworkdb(dAtA[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthNetworkdb - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *NetworkPushPull) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: NetworkPushPull: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: NetworkPushPull: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field LTime", wireType) - } - m.LTime = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.LTime |= (github_com_hashicorp_serf_serf.LamportTime(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Networks", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthNetworkdb - } - postIndex := iNdEx + msglen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Networks = append(m.Networks, &NetworkEntry{}) - if err := m.Networks[len(m.Networks)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field NodeName", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthNetworkdb - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.NodeName = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipNetworkdb(dAtA[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthNetworkdb - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *TableEvent) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: TableEvent: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: TableEvent: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) - } - m.Type = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Type |= (TableEvent_Type(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field LTime", wireType) - } - m.LTime = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.LTime |= (github_com_hashicorp_serf_serf.LamportTime(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field NodeName", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthNetworkdb - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.NodeName = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field NetworkID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthNetworkdb - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.NetworkID = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TableName", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthNetworkdb - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.TableName = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthNetworkdb - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Key = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthNetworkdb - } - postIndex := iNdEx + byteLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Value = append(m.Value[:0], dAtA[iNdEx:postIndex]...) - if m.Value == nil { - m.Value = []byte{} - } - iNdEx = postIndex - case 8: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ResidualReapTime", wireType) - } - m.ResidualReapTime = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.ResidualReapTime |= (int32(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipNetworkdb(dAtA[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthNetworkdb - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *BulkSyncMessage) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: BulkSyncMessage: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: BulkSyncMessage: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field LTime", wireType) - } - m.LTime = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.LTime |= (github_com_hashicorp_serf_serf.LamportTime(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Unsolicited", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - m.Unsolicited = bool(v != 0) - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field NodeName", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthNetworkdb - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.NodeName = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Networks", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthNetworkdb - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Networks = append(m.Networks, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Payload", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthNetworkdb - } - postIndex := iNdEx + byteLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Payload = append(m.Payload[:0], dAtA[iNdEx:postIndex]...) - if m.Payload == nil { - m.Payload = []byte{} - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipNetworkdb(dAtA[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthNetworkdb - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CompoundMessage) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: CompoundMessage: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CompoundMessage: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Messages", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthNetworkdb - } - postIndex := iNdEx + msglen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Messages = append(m.Messages, &CompoundMessage_SimpleMessage{}) - if err := m.Messages[len(m.Messages)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipNetworkdb(dAtA[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthNetworkdb - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CompoundMessage_SimpleMessage) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: SimpleMessage: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: SimpleMessage: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Payload", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthNetworkdb - } - postIndex := iNdEx + byteLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Payload = append(m.Payload[:0], dAtA[iNdEx:postIndex]...) - if m.Payload == nil { - m.Payload = []byte{} - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipNetworkdb(dAtA[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthNetworkdb - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipNetworkdb(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - return iNdEx, nil - case 1: - iNdEx += 8 - return iNdEx, nil - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - iNdEx += length - if length < 0 { - return 0, ErrInvalidLengthNetworkdb - } - return iNdEx, nil - case 3: - for { - var innerWire uint64 - var start int = iNdEx - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowNetworkdb - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - innerWire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - innerWireType := int(innerWire & 0x7) - if innerWireType == 4 { - break - } - next, err := skipNetworkdb(dAtA[start:]) - if err != nil { - return 0, err - } - iNdEx = start + next - } - return iNdEx, nil - case 4: - return iNdEx, nil - case 5: - iNdEx += 4 - return iNdEx, nil - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - } - panic("unreachable") -} - -var ( - ErrInvalidLengthNetworkdb = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowNetworkdb = fmt.Errorf("proto: integer overflow") -) - -func init() { proto.RegisterFile("networkdb/networkdb.proto", fileDescriptorNetworkdb) } - -var fileDescriptorNetworkdb = []byte{ - // 956 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x96, 0xcd, 0x6e, 0xe3, 0x54, - 0x14, 0xc7, 0x7b, 0xf3, 0xd1, 0x26, 0xa7, 0x29, 0x35, 0x77, 0x3a, 0x53, 0xd7, 0x03, 0x89, 0x31, - 0x33, 0x55, 0xa6, 0x82, 0x14, 0x75, 0x9e, 0xa0, 0x49, 0x2c, 0xc8, 0x4c, 0xc6, 0x89, 0xdc, 0xa4, - 0x88, 0x55, 0x74, 0x5b, 0x5f, 0x52, 0xab, 0x8e, 0x6d, 0xd9, 0x4e, 0x50, 0x56, 0x20, 0x56, 0xa3, - 0x2c, 0x78, 0x83, 0xac, 0x86, 0x35, 0x0f, 0x80, 0x58, 0xb2, 0x98, 0x05, 0x0b, 0xd8, 0x21, 0x16, - 0x11, 0xcd, 0x13, 0xf0, 0x08, 0xc8, 0xd7, 0x76, 0x72, 0x93, 0x56, 0x23, 0x21, 0x46, 0x82, 0x4d, - 0x72, 0x3f, 0x7e, 0x39, 0x3e, 0xe7, 0xef, 0xff, 0xb9, 0x37, 0x70, 0x60, 0xd3, 0xe0, 0x2b, 0xc7, - 0xbb, 0x36, 0x2e, 0x8e, 0x17, 0xa3, 0x8a, 0xeb, 0x39, 0x81, 0x83, 0xf3, 0x8b, 0x05, 0x69, 0xaf, - 0xef, 0xf4, 0x1d, 0xb6, 0x7a, 0x1c, 0x8e, 0x22, 0x40, 0x69, 0xc1, 0xce, 0xa7, 0x8e, 0xef, 0x9b, - 0xee, 0x0b, 0xea, 0xfb, 0xa4, 0x4f, 0xf1, 0x11, 0x64, 0x82, 0xb1, 0x4b, 0x45, 0x24, 0xa3, 0xf2, - 0x3b, 0x27, 0x0f, 0x2a, 0xcb, 0x88, 0x31, 0xd1, 0x19, 0xbb, 0x54, 0x67, 0x0c, 0xc6, 0x90, 0x31, - 0x48, 0x40, 0xc4, 0x94, 0x8c, 0xca, 0x05, 0x9d, 0x8d, 0x95, 0x57, 0x29, 0xc8, 0x6b, 0x8e, 0x41, - 0xd5, 0x11, 0xb5, 0x03, 0xfc, 0xf1, 0x4a, 0xb4, 0x03, 0x2e, 0xda, 0x82, 0xa9, 0x70, 0x01, 0x1b, - 0xb0, 0x69, 0xf5, 0x02, 0x73, 0x40, 0x59, 0xc8, 0x4c, 0xf5, 0xe4, 0xf5, 0xac, 0xb4, 0xf1, 0xc7, - 0xac, 0x74, 0xd4, 0x37, 0x83, 0xab, 0xe1, 0x45, 0xe5, 0xd2, 0x19, 0x1c, 0x5f, 0x11, 0xff, 0xca, - 0xbc, 0x74, 0x3c, 0xf7, 0xd8, 0xa7, 0xde, 0x97, 0xec, 0xa3, 0xd2, 0x24, 0x03, 0xd7, 0xf1, 0x82, - 0x8e, 0x39, 0xa0, 0x7a, 0xd6, 0x0a, 0xbf, 0xf0, 0x43, 0xc8, 0xdb, 0x8e, 0x41, 0x7b, 0x36, 0x19, - 0x50, 0x31, 0x2d, 0xa3, 0x72, 0x5e, 0xcf, 0x85, 0x0b, 0x1a, 0x19, 0x50, 0xe5, 0x6b, 0xc8, 0x84, - 0x4f, 0xc5, 0x8f, 0x61, 0xab, 0xa1, 0x9d, 0x9f, 0x36, 0x1b, 0x75, 0x61, 0x43, 0x12, 0x27, 0x53, - 0x79, 0x6f, 0x91, 0x56, 0xb8, 0xdf, 0xb0, 0x47, 0xc4, 0x32, 0x0d, 0x5c, 0x82, 0xcc, 0xb3, 0x56, - 0x43, 0x13, 0x90, 0x74, 0x7f, 0x32, 0x95, 0xdf, 0x5d, 0x61, 0x9e, 0x39, 0xa6, 0x8d, 0x3f, 0x80, - 0x6c, 0x53, 0x3d, 0x3d, 0x57, 0x85, 0x94, 0xf4, 0x60, 0x32, 0x95, 0xf1, 0x0a, 0xd1, 0xa4, 0x64, - 0x44, 0xa5, 0xc2, 0xcb, 0x57, 0xc5, 0x8d, 0x1f, 0xbf, 0x2f, 0xb2, 0x07, 0x2b, 0x37, 0x29, 0x28, - 0x68, 0x91, 0x16, 0x91, 0x50, 0x9f, 0xac, 0x08, 0xf5, 0x1e, 0x2f, 0x14, 0x87, 0xfd, 0x07, 0x5a, - 0xe1, 0x8f, 0x00, 0xe2, 0x64, 0x7a, 0xa6, 0x21, 0x66, 0xc2, 0xdd, 0xea, 0xce, 0x7c, 0x56, 0xca, - 0xc7, 0x89, 0x35, 0xea, 0x7a, 0xe2, 0xb2, 0x86, 0xa1, 0xbc, 0x44, 0xb1, 0xb4, 0x65, 0x5e, 0xda, - 0x87, 0x93, 0xa9, 0xbc, 0xcf, 0x17, 0xc2, 0xab, 0xab, 0x2c, 0xd4, 0x8d, 0xde, 0xc0, 0x1a, 0xc6, - 0x04, 0x7e, 0xb4, 0x14, 0xf8, 0x60, 0x32, 0x95, 0xef, 0xaf, 0x43, 0x77, 0x69, 0xfc, 0x0b, 0x5a, - 0x6a, 0x6c, 0x07, 0xde, 0x78, 0xad, 0x12, 0xf4, 0xe6, 0x4a, 0xde, 0xa6, 0xbe, 0x4f, 0x6e, 0xe9, - 0x5b, 0x2d, 0xcc, 0x67, 0xa5, 0x9c, 0x16, 0x6b, 0xcc, 0xa9, 0x2d, 0xc2, 0x96, 0x45, 0xc9, 0xc8, - 0xb4, 0xfb, 0x4c, 0xea, 0x9c, 0x9e, 0x4c, 0x95, 0x9f, 0x10, 0xec, 0xc6, 0x89, 0xb6, 0x87, 0xfe, - 0x55, 0x7b, 0x68, 0x59, 0x5c, 0x8e, 0xe8, 0xdf, 0xe6, 0xf8, 0x14, 0x72, 0x71, 0xed, 0xbe, 0x98, - 0x92, 0xd3, 0xe5, 0xed, 0x93, 0xfd, 0x3b, 0x4c, 0x18, 0xea, 0xa8, 0x2f, 0xc0, 0x7f, 0x50, 0x98, - 0xf2, 0x5d, 0x06, 0xa0, 0x43, 0x2e, 0xac, 0xf8, 0x60, 0xa8, 0xac, 0xf8, 0x5d, 0xe2, 0x1e, 0xb5, - 0x84, 0xfe, 0xf7, 0x6e, 0xc7, 0xef, 0x03, 0x04, 0x61, 0xba, 0x51, 0xac, 0x2c, 0x8b, 0x95, 0x67, - 0x2b, 0x2c, 0x98, 0x00, 0xe9, 0x6b, 0x3a, 0x16, 0x37, 0xd9, 0x7a, 0x38, 0xc4, 0x7b, 0x90, 0x1d, - 0x11, 0x6b, 0x48, 0xc5, 0x2d, 0x76, 0x64, 0x46, 0x13, 0x5c, 0x05, 0xec, 0x51, 0xdf, 0x34, 0x86, - 0xc4, 0xea, 0x79, 0x94, 0xb8, 0x51, 0xa1, 0x39, 0x19, 0x95, 0xb3, 0xd5, 0xbd, 0xf9, 0xac, 0x24, - 0xe8, 0xf1, 0xae, 0x4e, 0x89, 0xcb, 0x4a, 0x11, 0xbc, 0xb5, 0x15, 0xe5, 0x87, 0xa4, 0xf1, 0x0e, - 0xf9, 0xc6, 0x63, 0xcd, 0xb2, 0x54, 0x94, 0x6f, 0xbb, 0x47, 0xb0, 0x59, 0xd3, 0xd5, 0xd3, 0x8e, - 0x9a, 0x34, 0xde, 0x2a, 0x56, 0xf3, 0x28, 0x09, 0x68, 0x48, 0x75, 0xdb, 0xf5, 0x90, 0x4a, 0xdd, - 0x45, 0x75, 0x5d, 0x23, 0xa6, 0xea, 0x6a, 0x53, 0xed, 0xa8, 0x42, 0xfa, 0x2e, 0xaa, 0x4e, 0x2d, - 0x1a, 0xac, 0xb7, 0xe7, 0x6f, 0x08, 0x76, 0xab, 0x43, 0xeb, 0xfa, 0x6c, 0x6c, 0x5f, 0x26, 0x97, - 0xcf, 0x5b, 0xf4, 0xb3, 0x0c, 0xdb, 0x43, 0xdb, 0x77, 0x2c, 0xf3, 0xd2, 0x0c, 0xa8, 0xc1, 0x5c, - 0x93, 0xd3, 0xf9, 0xa5, 0x37, 0xfb, 0x40, 0xe2, 0xda, 0x21, 0x23, 0xa7, 0xd9, 0x5e, 0xe2, 0x7a, - 0x11, 0xb6, 0x5c, 0x32, 0xb6, 0x1c, 0x62, 0xb0, 0x57, 0x5e, 0xd0, 0x93, 0xa9, 0xf2, 0x2d, 0x82, - 0xdd, 0x9a, 0x33, 0x70, 0x9d, 0xa1, 0x6d, 0x24, 0x35, 0xd5, 0x21, 0x37, 0x88, 0x86, 0xbe, 0x88, - 0x58, 0x63, 0x95, 0x39, 0xb7, 0xaf, 0xd1, 0x95, 0x33, 0x73, 0xe0, 0x5a, 0x34, 0x9e, 0xe9, 0x8b, - 0x5f, 0x4a, 0x4f, 0x60, 0x67, 0x65, 0x2b, 0x4c, 0xa2, 0x1d, 0x27, 0x81, 0xa2, 0x24, 0xe2, 0xe9, - 0xd1, 0xcf, 0x29, 0xd8, 0xe6, 0xee, 0x6a, 0xfc, 0x21, 0x6f, 0x08, 0x76, 0x3d, 0x71, 0xbb, 0x89, - 0x1b, 0x2a, 0xb0, 0xa3, 0xa9, 0x9d, 0xcf, 0x5b, 0xfa, 0xf3, 0x9e, 0x7a, 0xae, 0x6a, 0x1d, 0x01, - 0x45, 0x87, 0x36, 0x87, 0xae, 0xdc, 0x57, 0x47, 0xb0, 0xdd, 0x39, 0xad, 0x36, 0xd5, 0x98, 0x8e, - 0x8f, 0x65, 0x8e, 0xe6, 0x7a, 0xfd, 0x10, 0xf2, 0xed, 0xee, 0xd9, 0x67, 0xbd, 0x76, 0xb7, 0xd9, - 0x14, 0xd2, 0xd2, 0xfe, 0x64, 0x2a, 0xdf, 0xe3, 0xc8, 0xc5, 0x69, 0x76, 0x08, 0xf9, 0x6a, 0xb7, - 0xf9, 0xbc, 0x77, 0xf6, 0x85, 0x56, 0x13, 0x32, 0xb7, 0xb8, 0xc4, 0x2c, 0xf8, 0x31, 0xe4, 0x6a, - 0xad, 0x17, 0xed, 0x56, 0x57, 0xab, 0x0b, 0xd9, 0x5b, 0x58, 0xa2, 0x28, 0x2e, 0x03, 0x68, 0xad, - 0x7a, 0x92, 0xe1, 0x66, 0x64, 0x4c, 0xbe, 0x9e, 0xe4, 0x92, 0x96, 0xee, 0xc5, 0xc6, 0xe4, 0x65, - 0xab, 0x8a, 0xbf, 0xdf, 0x14, 0x37, 0xfe, 0xba, 0x29, 0xa2, 0x6f, 0xe6, 0x45, 0xf4, 0x7a, 0x5e, - 0x44, 0xbf, 0xce, 0x8b, 0xe8, 0xcf, 0x79, 0x11, 0x5d, 0x6c, 0xb2, 0xbf, 0x4e, 0x4f, 0xff, 0x0e, - 0x00, 0x00, 0xff, 0xff, 0x0b, 0x8d, 0x70, 0xa7, 0x78, 0x09, 0x00, 0x00, -} diff --git a/vendor/github.com/docker/libnetwork/networkdb/networkdb.proto b/vendor/github.com/docker/libnetwork/networkdb/networkdb.proto deleted file mode 100644 index 4e1272eb89..0000000000 --- a/vendor/github.com/docker/libnetwork/networkdb/networkdb.proto +++ /dev/null @@ -1,187 +0,0 @@ -syntax = "proto3"; - -import "gogoproto/gogo.proto"; - -package networkdb; - -option (gogoproto.marshaler_all) = true; -option (gogoproto.unmarshaler_all) = true; -option (gogoproto.stringer_all) = true; -option (gogoproto.gostring_all) = true; -option (gogoproto.sizer_all) = true; -option (gogoproto.goproto_stringer_all) = false; - -// MessageType enum defines all the core message types that networkdb -// uses to communicate to peers. -enum MessageType { - option (gogoproto.goproto_enum_prefix) = false; - option (gogoproto.enum_customname) = "MessageType"; - - INVALID = 0 [(gogoproto.enumvalue_customname) = "MessageTypeInvalid"]; - - // NetworkEvent message type is used to communicate network - // attachments on the node. - NETWORK_EVENT = 1 [(gogoproto.enumvalue_customname) = "MessageTypeNetworkEvent"]; - - // TableEvent message type is used to communicate any table - // CRUD event that happened on the node. - TABLE_EVENT = 2 [(gogoproto.enumvalue_customname) = "MessageTypeTableEvent"]; - - // PushPull message type is used to syncup all network - // attachments on a peer node either during startup of this - // node or with a random peer node periodically thereafter. - PUSH_PULL = 3 [(gogoproto.enumvalue_customname) = "MessageTypePushPull"]; - - // BulkSync message is used to bulksync the whole networkdb - // state with a peer node during startup of this node or with - // a random peer node periodically thereafter. - BULK_SYNC = 4 [(gogoproto.enumvalue_customname) = "MessageTypeBulkSync"]; - - // Compound message type is used to form a compound message - // which is a pack of many message of above types, packed into - // a single compound message. - COMPOUND = 5 [(gogoproto.enumvalue_customname) = "MessageTypeCompound"]; - - // NodeEvent message type is used to communicate node - // join/leave events in the cluster - NODE_EVENT = 6 [(gogoproto.enumvalue_customname) = "MessageTypeNodeEvent"]; -} - -// GossipMessage is a basic message header used by all messages types. -message GossipMessage { - MessageType type = 1; // type defines one of the message types defined above. - bytes data = 2; // Payload of the message of any type defined here. -} - -// NodeEvent message payload definition. -message NodeEvent { - enum Type { - option (gogoproto.goproto_enum_prefix) = false; - option (gogoproto.enum_customname) = "Type"; - - INVALID = 0 [(gogoproto.enumvalue_customname) = "NodeEventTypeInvalid"]; - // Join event is generated when this node joins the cluster. - JOIN = 1 [(gogoproto.enumvalue_customname) = "NodeEventTypeJoin"];; - // Leave event is generated when this node leaves the cluster. - LEAVE = 2 [(gogoproto.enumvalue_customname) = "NodeEventTypeLeave"];; - } - - Type type = 1; - - // Lamport time using a network lamport clock indicating the - // time this event was generated on the node where it was - // generated. - uint64 l_time = 2 [(gogoproto.customtype) = "github.com/hashicorp/serf/serf.LamportTime", (gogoproto.nullable) = false]; - // Source node name. - string node_name = 3; -} - -// NetworkEvent message payload definition. -message NetworkEvent { - enum Type { - option (gogoproto.goproto_enum_prefix) = false; - option (gogoproto.enum_customname) = "Type"; - - INVALID = 0 [(gogoproto.enumvalue_customname) = "NetworkEventTypeInvalid"]; - // Join event is generated when this node joins a network. - JOIN = 1 [(gogoproto.enumvalue_customname) = "NetworkEventTypeJoin"];; - // Leave event is generated when this node leaves a network. - LEAVE = 2 [(gogoproto.enumvalue_customname) = "NetworkEventTypeLeave"];; - } - - Type type = 1; - - // Lamport time using a network lamport clock indicating the - // time this event was generated on the node where it was - // generated. - uint64 l_time = 2 [(gogoproto.customtype) = "github.com/hashicorp/serf/serf.LamportTime", (gogoproto.nullable) = false]; - // Source node name. - string node_name = 3; - // ID of the network for which the event is generated. - string network_id = 4 [(gogoproto.customname) = "NetworkID"]; -} - -// NetworkEntry for push pull of networks. -message NetworkEntry { - // ID of the network - string network_id = 1 [(gogoproto.customname) = "NetworkID"]; - // Latest lamport time of the network attachment when this - // network event was recorded. - uint64 l_time = 2 [(gogoproto.customtype) = "github.com/hashicorp/serf/serf.LamportTime", (gogoproto.nullable) = false]; - // Source node name where this network attachment happened. - string node_name = 3 [(gogoproto.customname) = "NodeName"]; - // Indicates if a leave from this network is in progress. - bool leaving = 4; -} - -// NetworkPushpull message payload definition. -message NetworkPushPull { - // Lamport time when this push pull was initiated. - uint64 l_time = 1 [(gogoproto.customtype) = "github.com/hashicorp/serf/serf.LamportTime", (gogoproto.nullable) = false]; - repeated NetworkEntry networks = 2; - // Name of the node sending this push pull payload. - string node_name = 3 [(gogoproto.customname) = "NodeName"]; -} - -// TableEvent message payload definition. -message TableEvent { - enum Type { - option (gogoproto.goproto_enum_prefix) = false; - option (gogoproto.enum_customname) = "Type"; - - INVALID = 0 [(gogoproto.enumvalue_customname) = "TableEventTypeInvalid"]; - // Create signifies that this table entry was just - // created. - CREATE = 1 [(gogoproto.enumvalue_customname) = "TableEventTypeCreate"]; - // Update signifies that this table entry was just - // updated. - UPDATE = 2 [(gogoproto.enumvalue_customname) = "TableEventTypeUpdate"]; - // Delete signifies that this table entry was just - // updated. - DELETE = 3 [(gogoproto.enumvalue_customname) = "TableEventTypeDelete"]; - } - - Type type = 1; - // Lamport time when this event was generated. - uint64 l_time = 2 [(gogoproto.customtype) = "github.com/hashicorp/serf/serf.LamportTime", (gogoproto.nullable) = false]; - // Node name where this event originated. - string node_name = 3; - // ID of the network to which this table entry belongs. - string network_id = 4 [(gogoproto.customname) = "NetworkID"]; - // Name of the table to which this table entry belongs. - string table_name = 5; - // Entry key. - string key = 6; - // Entry value. - bytes value = 7; - // Residual reap time for the entry before getting deleted in seconds - int32 residual_reap_time = 8 [(gogoproto.customname) = "ResidualReapTime"];; -} - -// BulkSync message payload definition. -message BulkSyncMessage { - // Lamport time when this bulk sync was initiated. - uint64 l_time = 1 [(gogoproto.customtype) = "github.com/hashicorp/serf/serf.LamportTime", (gogoproto.nullable) = false]; - // Indicates if this bulksync is a response to a bulk sync - // request from a peer node. - bool unsolicited = 2; - // Name of the node which is producing this bulk sync message. - string node_name = 3; - // List of network names whose table entries are getting - // bulksynced as part of the bulksync. - repeated string networks = 4; - // Bulksync payload - bytes payload = 5; -} - -// Compound message payload definition. -message CompoundMessage { - message SimpleMessage { - // Bytestring payload of a message constructed using - // other message type definitions. - bytes Payload = 1; - } - - // A list of simple messages. - repeated SimpleMessage messages = 1; -} diff --git a/vendor/github.com/docker/libnetwork/networkdb/networkdbdiagnostic.go b/vendor/github.com/docker/libnetwork/networkdb/networkdbdiagnostic.go deleted file mode 100644 index ea90c5a0e8..0000000000 --- a/vendor/github.com/docker/libnetwork/networkdb/networkdbdiagnostic.go +++ /dev/null @@ -1,452 +0,0 @@ -package networkdb - -import ( - "encoding/base64" - "fmt" - "net/http" - "strings" - - "github.com/docker/libnetwork/diagnostic" - "github.com/docker/libnetwork/internal/caller" - "github.com/sirupsen/logrus" -) - -const ( - missingParameter = "missing parameter" - dbNotAvailable = "database not available" -) - -// NetDbPaths2Func TODO -var NetDbPaths2Func = map[string]diagnostic.HTTPHandlerFunc{ - "/join": dbJoin, - "/networkpeers": dbPeers, - "/clusterpeers": dbClusterPeers, - "/joinnetwork": dbJoinNetwork, - "/leavenetwork": dbLeaveNetwork, - "/createentry": dbCreateEntry, - "/updateentry": dbUpdateEntry, - "/deleteentry": dbDeleteEntry, - "/getentry": dbGetEntry, - "/gettable": dbGetTable, - "/networkstats": dbNetworkStats, -} - -func dbJoin(ctx interface{}, w http.ResponseWriter, r *http.Request) { - r.ParseForm() - diagnostic.DebugHTTPForm(r) - _, json := diagnostic.ParseHTTPFormOptions(r) - - // audit logs - log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) - log.Info("join cluster") - - if len(r.Form["members"]) < 1 { - rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?members=ip1,ip2,...", r.URL.Path)) - log.Error("join cluster failed, wrong input") - diagnostic.HTTPReply(w, rsp, json) - return - } - - nDB, ok := ctx.(*NetworkDB) - if ok { - err := nDB.Join(strings.Split(r.Form["members"][0], ",")) - if err != nil { - rsp := diagnostic.FailCommand(fmt.Errorf("%s error in the DB join %s", r.URL.Path, err)) - log.WithError(err).Error("join cluster failed") - diagnostic.HTTPReply(w, rsp, json) - return - } - - log.Info("join cluster done") - diagnostic.HTTPReply(w, diagnostic.CommandSucceed(nil), json) - return - } - diagnostic.HTTPReply(w, diagnostic.FailCommand(fmt.Errorf("%s", dbNotAvailable)), json) -} - -func dbPeers(ctx interface{}, w http.ResponseWriter, r *http.Request) { - r.ParseForm() - diagnostic.DebugHTTPForm(r) - _, json := diagnostic.ParseHTTPFormOptions(r) - - // audit logs - log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) - log.Info("network peers") - - if len(r.Form["nid"]) < 1 { - rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?nid=test", r.URL.Path)) - log.Error("network peers failed, wrong input") - diagnostic.HTTPReply(w, rsp, json) - return - } - - nDB, ok := ctx.(*NetworkDB) - if ok { - peers := nDB.Peers(r.Form["nid"][0]) - rsp := &diagnostic.TableObj{Length: len(peers)} - for i, peerInfo := range peers { - if peerInfo.IP == "unknown" { - rsp.Elements = append(rsp.Elements, &diagnostic.PeerEntryObj{Index: i, Name: "orphan-" + peerInfo.Name, IP: peerInfo.IP}) - } else { - rsp.Elements = append(rsp.Elements, &diagnostic.PeerEntryObj{Index: i, Name: peerInfo.Name, IP: peerInfo.IP}) - } - } - log.WithField("response", fmt.Sprintf("%+v", rsp)).Info("network peers done") - diagnostic.HTTPReply(w, diagnostic.CommandSucceed(rsp), json) - return - } - diagnostic.HTTPReply(w, diagnostic.FailCommand(fmt.Errorf("%s", dbNotAvailable)), json) -} - -func dbClusterPeers(ctx interface{}, w http.ResponseWriter, r *http.Request) { - r.ParseForm() - diagnostic.DebugHTTPForm(r) - _, json := diagnostic.ParseHTTPFormOptions(r) - - // audit logs - log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) - log.Info("cluster peers") - - nDB, ok := ctx.(*NetworkDB) - if ok { - peers := nDB.ClusterPeers() - rsp := &diagnostic.TableObj{Length: len(peers)} - for i, peerInfo := range peers { - rsp.Elements = append(rsp.Elements, &diagnostic.PeerEntryObj{Index: i, Name: peerInfo.Name, IP: peerInfo.IP}) - } - log.WithField("response", fmt.Sprintf("%+v", rsp)).Info("cluster peers done") - diagnostic.HTTPReply(w, diagnostic.CommandSucceed(rsp), json) - return - } - diagnostic.HTTPReply(w, diagnostic.FailCommand(fmt.Errorf("%s", dbNotAvailable)), json) -} - -func dbCreateEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) { - r.ParseForm() - diagnostic.DebugHTTPForm(r) - unsafe, json := diagnostic.ParseHTTPFormOptions(r) - - // audit logs - log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) - log.Info("create entry") - - if len(r.Form["tname"]) < 1 || - len(r.Form["nid"]) < 1 || - len(r.Form["key"]) < 1 || - len(r.Form["value"]) < 1 { - rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?tname=table_name&nid=network_id&key=k&value=v", r.URL.Path)) - log.Error("create entry failed, wrong input") - diagnostic.HTTPReply(w, rsp, json) - return - } - - tname := r.Form["tname"][0] - nid := r.Form["nid"][0] - key := r.Form["key"][0] - value := r.Form["value"][0] - decodedValue := []byte(value) - if !unsafe { - var err error - decodedValue, err = base64.StdEncoding.DecodeString(value) - if err != nil { - log.WithError(err).Error("create entry failed") - diagnostic.HTTPReply(w, diagnostic.FailCommand(err), json) - return - } - } - - nDB, ok := ctx.(*NetworkDB) - if ok { - if err := nDB.CreateEntry(tname, nid, key, decodedValue); err != nil { - rsp := diagnostic.FailCommand(err) - diagnostic.HTTPReply(w, rsp, json) - log.WithError(err).Error("create entry failed") - return - } - log.Info("create entry done") - diagnostic.HTTPReply(w, diagnostic.CommandSucceed(nil), json) - return - } - diagnostic.HTTPReply(w, diagnostic.FailCommand(fmt.Errorf("%s", dbNotAvailable)), json) -} - -func dbUpdateEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) { - r.ParseForm() - diagnostic.DebugHTTPForm(r) - unsafe, json := diagnostic.ParseHTTPFormOptions(r) - - // audit logs - log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) - log.Info("update entry") - - if len(r.Form["tname"]) < 1 || - len(r.Form["nid"]) < 1 || - len(r.Form["key"]) < 1 || - len(r.Form["value"]) < 1 { - rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?tname=table_name&nid=network_id&key=k&value=v", r.URL.Path)) - log.Error("update entry failed, wrong input") - diagnostic.HTTPReply(w, rsp, json) - return - } - - tname := r.Form["tname"][0] - nid := r.Form["nid"][0] - key := r.Form["key"][0] - value := r.Form["value"][0] - decodedValue := []byte(value) - if !unsafe { - var err error - decodedValue, err = base64.StdEncoding.DecodeString(value) - if err != nil { - log.WithError(err).Error("update entry failed") - diagnostic.HTTPReply(w, diagnostic.FailCommand(err), json) - return - } - } - - nDB, ok := ctx.(*NetworkDB) - if ok { - if err := nDB.UpdateEntry(tname, nid, key, decodedValue); err != nil { - log.WithError(err).Error("update entry failed") - diagnostic.HTTPReply(w, diagnostic.FailCommand(err), json) - return - } - log.Info("update entry done") - diagnostic.HTTPReply(w, diagnostic.CommandSucceed(nil), json) - return - } - diagnostic.HTTPReply(w, diagnostic.FailCommand(fmt.Errorf("%s", dbNotAvailable)), json) -} - -func dbDeleteEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) { - r.ParseForm() - diagnostic.DebugHTTPForm(r) - _, json := diagnostic.ParseHTTPFormOptions(r) - - // audit logs - log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) - log.Info("delete entry") - - if len(r.Form["tname"]) < 1 || - len(r.Form["nid"]) < 1 || - len(r.Form["key"]) < 1 { - rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?tname=table_name&nid=network_id&key=k", r.URL.Path)) - log.Error("delete entry failed, wrong input") - diagnostic.HTTPReply(w, rsp, json) - return - } - - tname := r.Form["tname"][0] - nid := r.Form["nid"][0] - key := r.Form["key"][0] - - nDB, ok := ctx.(*NetworkDB) - if ok { - err := nDB.DeleteEntry(tname, nid, key) - if err != nil { - log.WithError(err).Error("delete entry failed") - diagnostic.HTTPReply(w, diagnostic.FailCommand(err), json) - return - } - log.Info("delete entry done") - diagnostic.HTTPReply(w, diagnostic.CommandSucceed(nil), json) - return - } - diagnostic.HTTPReply(w, diagnostic.FailCommand(fmt.Errorf("%s", dbNotAvailable)), json) -} - -func dbGetEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) { - r.ParseForm() - diagnostic.DebugHTTPForm(r) - unsafe, json := diagnostic.ParseHTTPFormOptions(r) - - // audit logs - log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) - log.Info("get entry") - - if len(r.Form["tname"]) < 1 || - len(r.Form["nid"]) < 1 || - len(r.Form["key"]) < 1 { - rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?tname=table_name&nid=network_id&key=k", r.URL.Path)) - log.Error("get entry failed, wrong input") - diagnostic.HTTPReply(w, rsp, json) - return - } - - tname := r.Form["tname"][0] - nid := r.Form["nid"][0] - key := r.Form["key"][0] - - nDB, ok := ctx.(*NetworkDB) - if ok { - value, err := nDB.GetEntry(tname, nid, key) - if err != nil { - log.WithError(err).Error("get entry failed") - diagnostic.HTTPReply(w, diagnostic.FailCommand(err), json) - return - } - - var encodedValue string - if unsafe { - encodedValue = string(value) - } else { - encodedValue = base64.StdEncoding.EncodeToString(value) - } - - rsp := &diagnostic.TableEntryObj{Key: key, Value: encodedValue} - log.WithField("response", fmt.Sprintf("%+v", rsp)).Info("get entry done") - diagnostic.HTTPReply(w, diagnostic.CommandSucceed(rsp), json) - return - } - diagnostic.HTTPReply(w, diagnostic.FailCommand(fmt.Errorf("%s", dbNotAvailable)), json) -} - -func dbJoinNetwork(ctx interface{}, w http.ResponseWriter, r *http.Request) { - r.ParseForm() - diagnostic.DebugHTTPForm(r) - _, json := diagnostic.ParseHTTPFormOptions(r) - - // audit logs - log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) - log.Info("join network") - - if len(r.Form["nid"]) < 1 { - rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?nid=network_id", r.URL.Path)) - log.Error("join network failed, wrong input") - diagnostic.HTTPReply(w, rsp, json) - return - } - - nid := r.Form["nid"][0] - - nDB, ok := ctx.(*NetworkDB) - if ok { - if err := nDB.JoinNetwork(nid); err != nil { - log.WithError(err).Error("join network failed") - diagnostic.HTTPReply(w, diagnostic.FailCommand(err), json) - return - } - log.Info("join network done") - diagnostic.HTTPReply(w, diagnostic.CommandSucceed(nil), json) - return - } - diagnostic.HTTPReply(w, diagnostic.FailCommand(fmt.Errorf("%s", dbNotAvailable)), json) -} - -func dbLeaveNetwork(ctx interface{}, w http.ResponseWriter, r *http.Request) { - r.ParseForm() - diagnostic.DebugHTTPForm(r) - _, json := diagnostic.ParseHTTPFormOptions(r) - - // audit logs - log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) - log.Info("leave network") - - if len(r.Form["nid"]) < 1 { - rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?nid=network_id", r.URL.Path)) - log.Error("leave network failed, wrong input") - diagnostic.HTTPReply(w, rsp, json) - return - } - - nid := r.Form["nid"][0] - - nDB, ok := ctx.(*NetworkDB) - if ok { - if err := nDB.LeaveNetwork(nid); err != nil { - log.WithError(err).Error("leave network failed") - diagnostic.HTTPReply(w, diagnostic.FailCommand(err), json) - return - } - log.Info("leave network done") - diagnostic.HTTPReply(w, diagnostic.CommandSucceed(nil), json) - return - } - diagnostic.HTTPReply(w, diagnostic.FailCommand(fmt.Errorf("%s", dbNotAvailable)), json) -} - -func dbGetTable(ctx interface{}, w http.ResponseWriter, r *http.Request) { - r.ParseForm() - diagnostic.DebugHTTPForm(r) - unsafe, json := diagnostic.ParseHTTPFormOptions(r) - - // audit logs - log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) - log.Info("get table") - - if len(r.Form["tname"]) < 1 || - len(r.Form["nid"]) < 1 { - rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?tname=table_name&nid=network_id", r.URL.Path)) - log.Error("get table failed, wrong input") - diagnostic.HTTPReply(w, rsp, json) - return - } - - tname := r.Form["tname"][0] - nid := r.Form["nid"][0] - - nDB, ok := ctx.(*NetworkDB) - if ok { - table := nDB.GetTableByNetwork(tname, nid) - rsp := &diagnostic.TableObj{Length: len(table)} - var i = 0 - for k, v := range table { - var encodedValue string - if unsafe { - encodedValue = string(v.Value) - } else { - encodedValue = base64.StdEncoding.EncodeToString(v.Value) - } - rsp.Elements = append(rsp.Elements, - &diagnostic.TableEntryObj{ - Index: i, - Key: k, - Value: encodedValue, - Owner: v.owner, - }) - i++ - } - log.WithField("response", fmt.Sprintf("%+v", rsp)).Info("get table done") - diagnostic.HTTPReply(w, diagnostic.CommandSucceed(rsp), json) - return - } - diagnostic.HTTPReply(w, diagnostic.FailCommand(fmt.Errorf("%s", dbNotAvailable)), json) -} - -func dbNetworkStats(ctx interface{}, w http.ResponseWriter, r *http.Request) { - r.ParseForm() - diagnostic.DebugHTTPForm(r) - _, json := diagnostic.ParseHTTPFormOptions(r) - - // audit logs - log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) - log.Info("network stats") - - if len(r.Form["nid"]) < 1 { - rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?nid=test", r.URL.Path)) - log.Error("network stats failed, wrong input") - diagnostic.HTTPReply(w, rsp, json) - return - } - - nDB, ok := ctx.(*NetworkDB) - if ok { - nDB.RLock() - networks := nDB.networks[nDB.config.NodeID] - network, ok := networks[r.Form["nid"][0]] - - entries := -1 - qLen := -1 - if ok { - entries = network.entriesNumber - qLen = network.tableBroadcasts.NumQueued() - } - nDB.RUnlock() - - rsp := diagnostic.CommandSucceed(&diagnostic.NetworkStatsResult{Entries: entries, QueueLen: qLen}) - log.WithField("response", fmt.Sprintf("%+v", rsp)).Info("network stats done") - diagnostic.HTTPReply(w, rsp, json) - return - } - diagnostic.HTTPReply(w, diagnostic.FailCommand(fmt.Errorf("%s", dbNotAvailable)), json) -} diff --git a/vendor/github.com/docker/libnetwork/networkdb/nodemgmt.go b/vendor/github.com/docker/libnetwork/networkdb/nodemgmt.go deleted file mode 100644 index f5a7498522..0000000000 --- a/vendor/github.com/docker/libnetwork/networkdb/nodemgmt.go +++ /dev/null @@ -1,120 +0,0 @@ -package networkdb - -import ( - "fmt" - - "github.com/hashicorp/memberlist" - "github.com/sirupsen/logrus" -) - -type nodeState int - -const ( - nodeNotFound nodeState = -1 - nodeActiveState nodeState = 0 - nodeLeftState nodeState = 1 - nodeFailedState nodeState = 2 -) - -var nodeStateName = map[nodeState]string{ - -1: "NodeNotFound", - 0: "NodeActive", - 1: "NodeLeft", - 2: "NodeFailed", -} - -// 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 -} - -// 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 -} - -func (nDB *NetworkDB) purgeReincarnation(mn *memberlist.Node) bool { - for name, node := range nDB.nodes { - if node.Addr.Equal(mn.Addr) && node.Port == mn.Port && mn.Name != name { - logrus.Infof("Node %s/%s, is the new incarnation of the active node %s/%s", mn.Name, mn.Addr, name, node.Addr) - nDB.changeNodeState(name, nodeLeftState) - return true - } - } - - for name, node := range nDB.failedNodes { - if node.Addr.Equal(mn.Addr) && node.Port == mn.Port && mn.Name != name { - logrus.Infof("Node %s/%s, is the new incarnation of the failed node %s/%s", mn.Name, mn.Addr, name, node.Addr) - nDB.changeNodeState(name, nodeLeftState) - return true - } - } - - for name, node := range nDB.leftNodes { - if node.Addr.Equal(mn.Addr) && node.Port == mn.Port && mn.Name != name { - logrus.Infof("Node %s/%s, is the new incarnation of the shutdown node %s/%s", mn.Name, mn.Addr, name, node.Addr) - nDB.changeNodeState(name, nodeLeftState) - return true - } - } - - return false -} diff --git a/vendor/github.com/docker/libnetwork/networkdb/watch.go b/vendor/github.com/docker/libnetwork/networkdb/watch.go deleted file mode 100644 index 2ef30422a8..0000000000 --- a/vendor/github.com/docker/libnetwork/networkdb/watch.go +++ /dev/null @@ -1,110 +0,0 @@ -package networkdb - -import ( - "net" - - "github.com/docker/go-events" -) - -type opType uint8 - -const ( - opCreate opType = 1 + iota - opUpdate - opDelete -) - -type event struct { - Table string - NetworkID string - Key string - Value []byte -} - -// NodeTable represents table event for node join and leave -const NodeTable = "NodeTable" - -// NodeAddr represents the value carried for node event in NodeTable -type NodeAddr struct { - Addr net.IP -} - -// CreateEvent generates a table entry create event to the watchers -type CreateEvent event - -// UpdateEvent generates a table entry update event to the watchers -type UpdateEvent event - -// DeleteEvent generates a table entry delete event to the watchers -type DeleteEvent event - -// Watch creates a watcher with filters for a particular table or -// network or key or any combination of the tuple. If any of the -// filter is an empty string it acts as a wildcard for that -// field. Watch returns a channel of events, where the events will be -// sent. -func (nDB *NetworkDB) Watch(tname, nid, key string) (*events.Channel, func()) { - var matcher events.Matcher - - if tname != "" || nid != "" || key != "" { - matcher = events.MatcherFunc(func(ev events.Event) bool { - var evt event - switch ev := ev.(type) { - case CreateEvent: - evt = event(ev) - case UpdateEvent: - evt = event(ev) - case DeleteEvent: - evt = event(ev) - } - - if tname != "" && evt.Table != tname { - return false - } - - if nid != "" && evt.NetworkID != nid { - return false - } - - if key != "" && evt.Key != key { - return false - } - - return true - }) - } - - ch := events.NewChannel(0) - sink := events.Sink(events.NewQueue(ch)) - - if matcher != nil { - sink = events.NewFilter(sink, matcher) - } - - nDB.broadcaster.Add(sink) - return ch, func() { - nDB.broadcaster.Remove(sink) - ch.Close() - sink.Close() - } -} - -func makeEvent(op opType, tname, nid, key string, value []byte) events.Event { - ev := event{ - Table: tname, - NetworkID: nid, - Key: key, - Value: value, - } - - switch op { - case opCreate: - return CreateEvent(ev) - case opUpdate: - return UpdateEvent(ev) - case opDelete: - return DeleteEvent(ev) - } - - return nil -} diff --git a/vendor/github.com/docker/libnetwork/ns/init_linux.go b/vendor/github.com/docker/libnetwork/ns/init_linux.go deleted file mode 100644 index 1d08a02f52..0000000000 --- a/vendor/github.com/docker/libnetwork/ns/init_linux.go +++ /dev/null @@ -1,126 +0,0 @@ -package ns - -import ( - "fmt" - "os" - "os/exec" - "strings" - "sync" - "syscall" - "time" - - "github.com/sirupsen/logrus" - "github.com/vishvananda/netlink" - "github.com/vishvananda/netns" -) - -var ( - initNs netns.NsHandle - initNl *netlink.Handle - initOnce sync.Once - // NetlinkSocketsTimeout represents the default timeout duration for the sockets - NetlinkSocketsTimeout = 3 * time.Second -) - -// 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) - } -} - -// 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 -} - -// ParseHandlerInt transforms the namespace handler into an integer -func ParseHandlerInt() int { - return int(getHandler()) -} - -// GetHandler returns the namespace handler -func getHandler() netns.NsHandle { - initOnce.Do(Init) - return initNs -} - -func getLink() (string, error) { - return os.Readlink(fmt.Sprintf("/proc/%d/task/%d/ns/net", os.Getpid(), syscall.Gettid())) -} - -// NlHandle returns the netlink handler -func NlHandle() *netlink.Handle { - initOnce.Do(Init) - return initNl -} - -func getSupportedNlFamilies() []int { - fams := []int{syscall.NETLINK_ROUTE} - // NETLINK_XFRM test - if err := checkXfrmSocket(); err != nil { - logrus.Warnf("Could not load necessary modules for IPSEC rules: %v", err) - } else { - fams = append(fams, syscall.NETLINK_XFRM) - } - // NETLINK_NETFILTER test - if err := loadNfConntrackModules(); err != nil { - if checkNfSocket() != nil { - logrus.Warnf("Could not load necessary modules for Conntrack: %v", err) - } else { - fams = append(fams, syscall.NETLINK_NETFILTER) - } - } else { - fams = append(fams, syscall.NETLINK_NETFILTER) - } - - return fams -} - -// 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 -} - -func loadNfConntrackModules() error { - if out, err := exec.Command("modprobe", "-va", "nf_conntrack").CombinedOutput(); err != nil { - return fmt.Errorf("Running modprobe nf_conntrack failed with message: `%s`, error: %v", strings.TrimSpace(string(out)), err) - } - if out, err := exec.Command("modprobe", "-va", "nf_conntrack_netlink").CombinedOutput(); err != nil { - return fmt.Errorf("Running modprobe nf_conntrack_netlink failed with message: `%s`, error: %v", strings.TrimSpace(string(out)), err) - } - return nil -} - -// 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 -} diff --git a/vendor/github.com/docker/libnetwork/ns/init_windows.go b/vendor/github.com/docker/libnetwork/ns/init_windows.go deleted file mode 100644 index f5838f81dd..0000000000 --- a/vendor/github.com/docker/libnetwork/ns/init_windows.go +++ /dev/null @@ -1,3 +0,0 @@ -package ns - -// File is present so that go build ./... is closer to working on Windows from repo root. diff --git a/vendor/github.com/docker/libnetwork/options/options.go b/vendor/github.com/docker/libnetwork/options/options.go deleted file mode 100644 index 06d8ae5902..0000000000 --- a/vendor/github.com/docker/libnetwork/options/options.go +++ /dev/null @@ -1,88 +0,0 @@ -// Package options provides a way to pass unstructured sets of options to a -// component expecting a strongly-typed configuration structure. -package options - -import ( - "fmt" - "reflect" -) - -// NoSuchFieldError is the error returned when the generic parameters hold a -// value for a field absent from the destination structure. -type NoSuchFieldError struct { - Field string - Type string -} - -func (e NoSuchFieldError) Error() string { - return fmt.Sprintf("no field %q in type %q", e.Field, e.Type) -} - -// CannotSetFieldError is the error returned when the generic parameters hold a -// value for a field that cannot be set in the destination structure. -type CannotSetFieldError struct { - Field string - Type string -} - -func (e CannotSetFieldError) Error() string { - return fmt.Sprintf("cannot set field %q of type %q", e.Field, e.Type) -} - -// TypeMismatchError is the error returned when the type of the generic value -// for a field mismatches the type of the destination structure. -type TypeMismatchError struct { - Field string - ExpectType string - ActualType string -} - -func (e TypeMismatchError) Error() string { - return fmt.Sprintf("type mismatch, field %s require type %v, actual type %v", e.Field, e.ExpectType, e.ActualType) -} - -// Generic is a basic type to store arbitrary settings. -type Generic map[string]interface{} - -// NewGeneric returns a new Generic instance. -func NewGeneric() Generic { - return make(Generic) -} - -// GenerateFromModel takes the generic options, and tries to build a new -// instance of the model's type by matching keys from the generic options to -// fields in the model. -// -// The return value is of the same type than the model (including a potential -// pointer qualifier). -func GenerateFromModel(options Generic, model interface{}) (interface{}, error) { - modType := reflect.TypeOf(model) - - // If the model is of pointer type, we need to dereference for New. - resType := reflect.TypeOf(model) - if modType.Kind() == reflect.Ptr { - resType = resType.Elem() - } - - // Populate the result structure with the generic layout content. - res := reflect.New(resType) - for name, value := range options { - field := res.Elem().FieldByName(name) - if !field.IsValid() { - return nil, NoSuchFieldError{name, resType.String()} - } - if !field.CanSet() { - return nil, CannotSetFieldError{name, resType.String()} - } - if reflect.TypeOf(value) != field.Type() { - return nil, TypeMismatchError{name, field.Type().String(), reflect.TypeOf(value).String()} - } - field.Set(reflect.ValueOf(value)) - } - - // If the model is not of pointer type, return content of the result. - if modType.Kind() == reflect.Ptr { - return res.Interface(), nil - } - return res.Elem().Interface(), nil -} diff --git a/vendor/github.com/docker/libnetwork/osl/interface_freebsd.go b/vendor/github.com/docker/libnetwork/osl/interface_freebsd.go deleted file mode 100644 index 9c0141fd9b..0000000000 --- a/vendor/github.com/docker/libnetwork/osl/interface_freebsd.go +++ /dev/null @@ -1,4 +0,0 @@ -package osl - -// IfaceOption is a function option type to set interface options -type IfaceOption func() diff --git a/vendor/github.com/docker/libnetwork/osl/interface_linux.go b/vendor/github.com/docker/libnetwork/osl/interface_linux.go deleted file mode 100644 index 4f8ff3d639..0000000000 --- a/vendor/github.com/docker/libnetwork/osl/interface_linux.go +++ /dev/null @@ -1,460 +0,0 @@ -package osl - -import ( - "fmt" - "net" - "regexp" - "sync" - "syscall" - "time" - - "github.com/docker/libnetwork/ns" - "github.com/docker/libnetwork/types" - "github.com/sirupsen/logrus" - "github.com/vishvananda/netlink" - "github.com/vishvananda/netns" -) - -// IfaceOption is a function option type to set interface options -type IfaceOption func(i *nwIface) - -type nwIface struct { - srcName string - dstName string - master string - dstMaster string - mac net.HardwareAddr - address *net.IPNet - addressIPv6 *net.IPNet - llAddrs []*net.IPNet - routes []*net.IPNet - bridge bool - ns *networkNamespace - sync.Mutex -} - -func (i *nwIface) SrcName() string { - i.Lock() - defer i.Unlock() - - return i.srcName -} - -func (i *nwIface) DstName() string { - i.Lock() - defer i.Unlock() - - return i.dstName -} - -func (i *nwIface) DstMaster() string { - i.Lock() - defer i.Unlock() - - return i.dstMaster -} - -func (i *nwIface) Bridge() bool { - i.Lock() - defer i.Unlock() - - return i.bridge -} - -func (i *nwIface) Master() string { - i.Lock() - defer i.Unlock() - - return i.master -} - -func (i *nwIface) MacAddress() net.HardwareAddr { - i.Lock() - defer i.Unlock() - - return types.GetMacCopy(i.mac) -} - -func (i *nwIface) Address() *net.IPNet { - i.Lock() - defer i.Unlock() - - return types.GetIPNetCopy(i.address) -} - -func (i *nwIface) AddressIPv6() *net.IPNet { - i.Lock() - defer i.Unlock() - - return types.GetIPNetCopy(i.addressIPv6) -} - -func (i *nwIface) LinkLocalAddresses() []*net.IPNet { - i.Lock() - defer i.Unlock() - - return i.llAddrs -} - -func (i *nwIface) Routes() []*net.IPNet { - i.Lock() - defer i.Unlock() - - routes := make([]*net.IPNet, len(i.routes)) - for index, route := range i.routes { - r := types.GetIPNetCopy(route) - routes[index] = r - } - - return routes -} - -func (n *networkNamespace) Interfaces() []Interface { - n.Lock() - defer n.Unlock() - - ifaces := make([]Interface, len(n.iFaces)) - - for i, iface := range n.iFaces { - ifaces[i] = iface - } - - return ifaces -} - -func (i *nwIface) Remove() error { - i.Lock() - n := i.ns - i.Unlock() - - n.Lock() - isDefault := n.isDefault - nlh := n.nlHandle - n.Unlock() - - // Find the network interface identified by the DstName attribute. - iface, err := nlh.LinkByName(i.DstName()) - if err != nil { - return err - } - - // Down the interface before configuring - if err := nlh.LinkSetDown(iface); err != nil { - return err - } - - err = nlh.LinkSetName(iface, i.SrcName()) - if err != nil { - logrus.Debugf("LinkSetName failed for interface %s: %v", i.SrcName(), err) - return err - } - - // if it is a bridge just delete it. - if i.Bridge() { - if err := nlh.LinkDel(iface); err != nil { - return fmt.Errorf("failed deleting bridge %q: %v", i.SrcName(), err) - } - } else if !isDefault { - // Move the network interface to caller namespace. - if err := nlh.LinkSetNsFd(iface, ns.ParseHandlerInt()); err != nil { - logrus.Debugf("LinkSetNsPid failed for interface %s: %v", i.SrcName(), err) - return err - } - } - - n.Lock() - for index, intf := range n.iFaces { - if intf == i { - n.iFaces = append(n.iFaces[:index], n.iFaces[index+1:]...) - break - } - } - n.Unlock() - - n.checkLoV6() - - return nil -} - -// Returns the sandbox's side veth interface statistics -func (i *nwIface) Statistics() (*types.InterfaceStatistics, error) { - i.Lock() - n := i.ns - i.Unlock() - - l, err := n.nlHandle.LinkByName(i.DstName()) - if err != nil { - return nil, fmt.Errorf("failed to retrieve the statistics for %s in netns %s: %v", i.DstName(), n.path, err) - } - - stats := l.Attrs().Statistics - if stats == nil { - return nil, fmt.Errorf("no statistics were returned") - } - - return &types.InterfaceStatistics{ - RxBytes: uint64(stats.RxBytes), - TxBytes: uint64(stats.TxBytes), - RxPackets: uint64(stats.RxPackets), - TxPackets: uint64(stats.TxPackets), - RxDropped: uint64(stats.RxDropped), - TxDropped: uint64(stats.TxDropped), - }, nil -} - -func (n *networkNamespace) findDst(srcName string, isBridge bool) string { - n.Lock() - defer n.Unlock() - - for _, i := range n.iFaces { - // The master should match the srcname of the interface and the - // master interface should be of type bridge, if searching for a bridge type - if i.SrcName() == srcName && (!isBridge || i.Bridge()) { - return i.DstName() - } - } - - return "" -} - -func (n *networkNamespace) AddInterface(srcName, dstPrefix string, options ...IfaceOption) error { - i := &nwIface{srcName: srcName, dstName: dstPrefix, ns: n} - i.processInterfaceOptions(options...) - - if i.master != "" { - i.dstMaster = n.findDst(i.master, true) - if i.dstMaster == "" { - return fmt.Errorf("could not find an appropriate master %q for %q", - i.master, i.srcName) - } - } - - n.Lock() - if n.isDefault { - i.dstName = i.srcName - } else { - i.dstName = fmt.Sprintf("%s%d", dstPrefix, n.nextIfIndex[dstPrefix]) - n.nextIfIndex[dstPrefix]++ - } - - path := n.path - isDefault := n.isDefault - nlh := n.nlHandle - nlhHost := ns.NlHandle() - n.Unlock() - - // If it is a bridge interface we have to create the bridge inside - // the namespace so don't try to lookup the interface using srcName - if i.bridge { - link := &netlink.Bridge{ - LinkAttrs: netlink.LinkAttrs{ - Name: i.srcName, - }, - } - if err := nlh.LinkAdd(link); err != nil { - return fmt.Errorf("failed to create bridge %q: %v", i.srcName, err) - } - } else { - // Find the network interface identified by the SrcName attribute. - iface, err := nlhHost.LinkByName(i.srcName) - if err != nil { - return fmt.Errorf("failed to get link by name %q: %v", i.srcName, err) - } - - // Move the network interface to the destination - // namespace only if the namespace is not a default - // type - if !isDefault { - newNs, err := netns.GetFromPath(path) - if err != nil { - return fmt.Errorf("failed get network namespace %q: %v", path, err) - } - defer newNs.Close() - if err := nlhHost.LinkSetNsFd(iface, int(newNs)); err != nil { - return fmt.Errorf("failed to set namespace on link %q: %v", i.srcName, err) - } - } - } - - // Find the network interface identified by the SrcName attribute. - iface, err := nlh.LinkByName(i.srcName) - if err != nil { - return fmt.Errorf("failed to get link by name %q: %v", i.srcName, err) - } - - // Down the interface before configuring - if err := nlh.LinkSetDown(iface); err != nil { - return fmt.Errorf("failed to set link down: %v", err) - } - - // Configure the interface now this is moved in the proper namespace. - if err := configureInterface(nlh, iface, i); err != nil { - // If configuring the device fails move it back to the host namespace - // and change the name back to the source name. This allows the caller - // to properly cleanup the interface. Its important especially for - // interfaces with global attributes, ex: vni id for vxlan interfaces. - if nerr := nlh.LinkSetName(iface, i.SrcName()); nerr != nil { - logrus.Errorf("renaming interface (%s->%s) failed, %v after config error %v", i.DstName(), i.SrcName(), nerr, err) - } - if nerr := nlh.LinkSetNsFd(iface, ns.ParseHandlerInt()); nerr != nil { - logrus.Errorf("moving interface %s to host ns failed, %v, after config error %v", i.SrcName(), nerr, err) - } - return err - } - - // Up the interface. - cnt := 0 - for err = nlh.LinkSetUp(iface); err != nil && cnt < 3; cnt++ { - logrus.Debugf("retrying link setup because of: %v", err) - time.Sleep(10 * time.Millisecond) - err = nlh.LinkSetUp(iface) - } - if err != nil { - return fmt.Errorf("failed to set link up: %v", err) - } - - // Set the routes on the interface. This can only be done when the interface is up. - if err := setInterfaceRoutes(nlh, iface, i); err != nil { - return fmt.Errorf("error setting interface %q routes to %q: %v", iface.Attrs().Name, i.Routes(), err) - } - - n.Lock() - n.iFaces = append(n.iFaces, i) - n.Unlock() - - n.checkLoV6() - - return nil -} - -func configureInterface(nlh *netlink.Handle, iface netlink.Link, i *nwIface) error { - ifaceName := iface.Attrs().Name - ifaceConfigurators := []struct { - Fn func(*netlink.Handle, netlink.Link, *nwIface) error - ErrMessage string - }{ - {setInterfaceName, fmt.Sprintf("error renaming interface %q to %q", ifaceName, i.DstName())}, - {setInterfaceMAC, fmt.Sprintf("error setting interface %q MAC to %q", ifaceName, i.MacAddress())}, - {setInterfaceIP, fmt.Sprintf("error setting interface %q IP to %v", ifaceName, i.Address())}, - {setInterfaceIPv6, fmt.Sprintf("error setting interface %q IPv6 to %v", ifaceName, i.AddressIPv6())}, - {setInterfaceMaster, fmt.Sprintf("error setting interface %q master to %q", ifaceName, i.DstMaster())}, - {setInterfaceLinkLocalIPs, fmt.Sprintf("error setting interface %q link local IPs to %v", ifaceName, i.LinkLocalAddresses())}, - } - - for _, config := range ifaceConfigurators { - if err := config.Fn(nlh, iface, i); err != nil { - return fmt.Errorf("%s: %v", config.ErrMessage, err) - } - } - return nil -} - -func setInterfaceMaster(nlh *netlink.Handle, iface netlink.Link, i *nwIface) error { - if i.DstMaster() == "" { - return nil - } - - return nlh.LinkSetMaster(iface, &netlink.Bridge{ - LinkAttrs: netlink.LinkAttrs{Name: i.DstMaster()}}) -} - -func setInterfaceMAC(nlh *netlink.Handle, iface netlink.Link, i *nwIface) error { - if i.MacAddress() == nil { - return nil - } - return nlh.LinkSetHardwareAddr(iface, i.MacAddress()) -} - -func setInterfaceIP(nlh *netlink.Handle, iface netlink.Link, i *nwIface) error { - if i.Address() == nil { - return nil - } - if err := checkRouteConflict(nlh, i.Address(), netlink.FAMILY_V4); err != nil { - return err - } - ipAddr := &netlink.Addr{IPNet: i.Address(), Label: ""} - return nlh.AddrAdd(iface, ipAddr) -} - -func setInterfaceIPv6(nlh *netlink.Handle, iface netlink.Link, i *nwIface) error { - if i.AddressIPv6() == nil { - return nil - } - if err := checkRouteConflict(nlh, i.AddressIPv6(), netlink.FAMILY_V6); err != nil { - return err - } - if err := setIPv6(i.ns.path, i.DstName(), true); err != nil { - return fmt.Errorf("failed to enable ipv6: %v", err) - } - ipAddr := &netlink.Addr{IPNet: i.AddressIPv6(), Label: "", Flags: syscall.IFA_F_NODAD} - return nlh.AddrAdd(iface, ipAddr) -} - -func setInterfaceLinkLocalIPs(nlh *netlink.Handle, iface netlink.Link, i *nwIface) error { - for _, llIP := range i.LinkLocalAddresses() { - ipAddr := &netlink.Addr{IPNet: llIP} - if err := nlh.AddrAdd(iface, ipAddr); err != nil { - return err - } - } - return nil -} - -func setInterfaceName(nlh *netlink.Handle, iface netlink.Link, i *nwIface) error { - return nlh.LinkSetName(iface, i.DstName()) -} - -func setInterfaceRoutes(nlh *netlink.Handle, iface netlink.Link, i *nwIface) error { - for _, route := range i.Routes() { - err := nlh.RouteAdd(&netlink.Route{ - Scope: netlink.SCOPE_LINK, - LinkIndex: iface.Attrs().Index, - Dst: route, - }) - if err != nil { - return err - } - } - return nil -} - -// In older kernels (like the one in Centos 6.6 distro) sysctl does not have netns support. Therefore -// we cannot gather the statistics from /sys/class/net//statistics/ files. Per-netns stats -// are naturally found in /proc/net/dev in kernels which support netns (ifconfig relies on that). -const ( - netStatsFile = "/proc/net/dev" - base = "[ ]*%s:([ ]+[0-9]+){16}" -) - -func scanInterfaceStats(data, ifName string, i *types.InterfaceStatistics) error { - var ( - bktStr string - bkt uint64 - ) - - regex := fmt.Sprintf(base, ifName) - re := regexp.MustCompile(regex) - line := re.FindString(data) - - _, err := fmt.Sscanf(line, "%s %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d", - &bktStr, &i.RxBytes, &i.RxPackets, &i.RxErrors, &i.RxDropped, &bkt, &bkt, &bkt, - &bkt, &i.TxBytes, &i.TxPackets, &i.TxErrors, &i.TxDropped, &bkt, &bkt, &bkt, &bkt) - - return err -} - -func checkRouteConflict(nlh *netlink.Handle, address *net.IPNet, family int) error { - routes, err := nlh.RouteList(nil, family) - if err != nil { - return err - } - for _, route := range routes { - if route.Dst != nil { - if route.Dst.Contains(address.IP) || address.Contains(route.Dst.IP) { - return fmt.Errorf("cannot program address %v in sandbox interface because it conflicts with existing route %s", - address, route) - } - } - } - return nil -} diff --git a/vendor/github.com/docker/libnetwork/osl/interface_windows.go b/vendor/github.com/docker/libnetwork/osl/interface_windows.go deleted file mode 100644 index 9c0141fd9b..0000000000 --- a/vendor/github.com/docker/libnetwork/osl/interface_windows.go +++ /dev/null @@ -1,4 +0,0 @@ -package osl - -// IfaceOption is a function option type to set interface options -type IfaceOption func() diff --git a/vendor/github.com/docker/libnetwork/osl/kernel/knobs.go b/vendor/github.com/docker/libnetwork/osl/kernel/knobs.go deleted file mode 100644 index a7cd7dbb72..0000000000 --- a/vendor/github.com/docker/libnetwork/osl/kernel/knobs.go +++ /dev/null @@ -1,16 +0,0 @@ -package kernel - -type conditionalCheck func(val1, val2 string) bool - -// OSValue represents a tuple, value defined, check function when to apply the value -type OSValue struct { - Value string - CheckFn conditionalCheck -} - -func propertyIsValid(val1, val2 string, check conditionalCheck) bool { - if check == nil || check(val1, val2) { - return true - } - return false -} diff --git a/vendor/github.com/docker/libnetwork/osl/kernel/knobs_linux.go b/vendor/github.com/docker/libnetwork/osl/kernel/knobs_linux.go deleted file mode 100644 index 964280650c..0000000000 --- a/vendor/github.com/docker/libnetwork/osl/kernel/knobs_linux.go +++ /dev/null @@ -1,47 +0,0 @@ -package kernel - -import ( - "io/ioutil" - "path" - "strings" - - "github.com/sirupsen/logrus" -) - -// writeSystemProperty writes the value to a path under /proc/sys as determined from the key. -// For e.g. net.ipv4.ip_forward translated to /proc/sys/net/ipv4/ip_forward. -func writeSystemProperty(key, value string) error { - keyPath := strings.Replace(key, ".", "/", -1) - return ioutil.WriteFile(path.Join("/proc/sys", keyPath), []byte(value), 0644) -} - -// readSystemProperty reads the value from the path under /proc/sys and returns it -func readSystemProperty(key string) (string, error) { - keyPath := strings.Replace(key, ".", "/", -1) - value, err := ioutil.ReadFile(path.Join("/proc/sys", keyPath)) - if err != nil { - return "", err - } - return strings.TrimSpace(string(value)), nil -} - -// ApplyOSTweaks applies the configuration values passed as arguments -func ApplyOSTweaks(osConfig map[string]*OSValue) { - for k, v := range osConfig { - // read the existing property from disk - oldv, err := readSystemProperty(k) - if err != nil { - logrus.WithError(err).Errorf("error reading the kernel parameter %s", k) - continue - } - - if propertyIsValid(oldv, v.Value, v.CheckFn) { - // write new prop value to disk - if err := writeSystemProperty(k, v.Value); err != nil { - logrus.WithError(err).Errorf("error setting the kernel parameter %s = %s, (leaving as %s)", k, v.Value, oldv) - continue - } - logrus.Debugf("updated kernel parameter %s = %s (was %s)", k, v.Value, oldv) - } - } -} diff --git a/vendor/github.com/docker/libnetwork/osl/kernel/knobs_unsupported.go b/vendor/github.com/docker/libnetwork/osl/kernel/knobs_unsupported.go deleted file mode 100644 index 32f258f416..0000000000 --- a/vendor/github.com/docker/libnetwork/osl/kernel/knobs_unsupported.go +++ /dev/null @@ -1,7 +0,0 @@ -// +build !linux - -package kernel - -// ApplyOSTweaks applies the configuration values passed as arguments -func ApplyOSTweaks(osConfig map[string]*OSValue) { -} diff --git a/vendor/github.com/docker/libnetwork/osl/namespace_linux.go b/vendor/github.com/docker/libnetwork/osl/namespace_linux.go deleted file mode 100644 index 89cf96454b..0000000000 --- a/vendor/github.com/docker/libnetwork/osl/namespace_linux.go +++ /dev/null @@ -1,693 +0,0 @@ -package osl - -import ( - "fmt" - "io/ioutil" - "net" - "os" - "os/exec" - "path/filepath" - "runtime" - "strconv" - "strings" - "sync" - "syscall" - "time" - - "github.com/docker/docker/pkg/reexec" - "github.com/docker/libnetwork/ns" - "github.com/docker/libnetwork/osl/kernel" - "github.com/docker/libnetwork/types" - "github.com/sirupsen/logrus" - "github.com/vishvananda/netlink" - "github.com/vishvananda/netns" -) - -const defaultPrefix = "/var/run/docker" - -func init() { - reexec.Register("set-ipv6", reexecSetIPv6) -} - -var ( - once sync.Once - garbagePathMap = make(map[string]bool) - gpmLock sync.Mutex - gpmWg sync.WaitGroup - gpmCleanupPeriod = 60 * time.Second - gpmChan = make(chan chan struct{}) - prefix = defaultPrefix - loadBalancerConfig = map[string]*kernel.OSValue{ - // disables any special handling on port reuse of existing IPVS connection table entries - // more info: https://github.com/torvalds/linux/blob/master/Documentation/networking/ipvs-sysctl.txt#L25:1 - "net.ipv4.vs.conn_reuse_mode": {Value: "0", CheckFn: nil}, - // expires connection from the IPVS connection table when the backend is not available - // more info: https://github.com/torvalds/linux/blob/master/Documentation/networking/ipvs-sysctl.txt#L126:1 - "net.ipv4.vs.expire_nodest_conn": {Value: "1", CheckFn: nil}, - // expires persistent connections to destination servers with weights set to 0 - // more info: https://github.com/torvalds/linux/blob/master/Documentation/networking/ipvs-sysctl.txt#L144:1 - "net.ipv4.vs.expire_quiescent_template": {Value: "1", CheckFn: nil}, - } -) - -// The networkNamespace type is the linux implementation of the Sandbox -// interface. It represents a linux network namespace, and moves an interface -// into it when called on method AddInterface or sets the gateway etc. -type networkNamespace struct { - path string - iFaces []*nwIface - gw net.IP - gwv6 net.IP - staticRoutes []*types.StaticRoute - neighbors []*neigh - nextIfIndex map[string]int - isDefault bool - nlHandle *netlink.Handle - loV6Enabled bool - sync.Mutex -} - -// SetBasePath sets the base url prefix for the ns path -func SetBasePath(path string) { - prefix = path -} - -func init() { - reexec.Register("netns-create", reexecCreateNamespace) -} - -func basePath() string { - return filepath.Join(prefix, "netns") -} - -func createBasePath() { - err := os.MkdirAll(basePath(), 0755) - if err != nil { - panic("Could not create net namespace path directory") - } - - // Start the garbage collection go routine - go removeUnusedPaths() -} - -func removeUnusedPaths() { - gpmLock.Lock() - period := gpmCleanupPeriod - gpmLock.Unlock() - - ticker := time.NewTicker(period) - for { - var ( - gc chan struct{} - gcOk bool - ) - - select { - case <-ticker.C: - case gc, gcOk = <-gpmChan: - } - - gpmLock.Lock() - pathList := make([]string, 0, len(garbagePathMap)) - for path := range garbagePathMap { - pathList = append(pathList, path) - } - garbagePathMap = make(map[string]bool) - gpmWg.Add(1) - gpmLock.Unlock() - - for _, path := range pathList { - os.Remove(path) - } - - gpmWg.Done() - if gcOk { - close(gc) - } - } -} - -func addToGarbagePaths(path string) { - gpmLock.Lock() - garbagePathMap[path] = true - gpmLock.Unlock() -} - -func removeFromGarbagePaths(path string) { - gpmLock.Lock() - delete(garbagePathMap, path) - gpmLock.Unlock() -} - -// GC triggers garbage collection of namespace path right away -// and waits for it. -func GC() { - gpmLock.Lock() - if len(garbagePathMap) == 0 { - // No need for GC if map is empty - gpmLock.Unlock() - return - } - gpmLock.Unlock() - - // if content exists in the garbage paths - // we can trigger GC to run, providing a - // channel to be notified on completion - waitGC := make(chan struct{}) - gpmChan <- waitGC - // wait for GC completion - <-waitGC -} - -// GenerateKey generates a sandbox key based on the passed -// container id. -func GenerateKey(containerID string) string { - maxLen := 12 - // Read sandbox key from host for overlay - if strings.HasPrefix(containerID, "-") { - var ( - index int - indexStr string - tmpkey string - ) - dir, err := ioutil.ReadDir(basePath()) - if err != nil { - return "" - } - - for _, v := range dir { - id := v.Name() - if strings.HasSuffix(id, containerID[:maxLen-1]) { - indexStr = strings.TrimSuffix(id, containerID[:maxLen-1]) - tmpindex, err := strconv.Atoi(indexStr) - if err != nil { - return "" - } - if tmpindex > index { - index = tmpindex - tmpkey = id - } - - } - } - containerID = tmpkey - if containerID == "" { - return "" - } - } - - if len(containerID) < maxLen { - maxLen = len(containerID) - } - - return basePath() + "/" + containerID[:maxLen] -} - -// NewSandbox provides a new sandbox instance created in an os specific way -// provided a key which uniquely identifies the sandbox -func NewSandbox(key string, osCreate, isRestore bool) (Sandbox, error) { - if !isRestore { - err := createNetworkNamespace(key, osCreate) - if err != nil { - return nil, err - } - } else { - once.Do(createBasePath) - } - - n := &networkNamespace{path: key, isDefault: !osCreate, nextIfIndex: make(map[string]int)} - - sboxNs, err := netns.GetFromPath(n.path) - if err != nil { - return nil, fmt.Errorf("failed get network namespace %q: %v", n.path, err) - } - defer sboxNs.Close() - - n.nlHandle, err = netlink.NewHandleAt(sboxNs, syscall.NETLINK_ROUTE) - if err != nil { - return nil, fmt.Errorf("failed to create a netlink handle: %v", err) - } - - err = n.nlHandle.SetSocketTimeout(ns.NetlinkSocketsTimeout) - if err != nil { - logrus.Warnf("Failed to set the timeout on the sandbox netlink handle sockets: %v", err) - } - // In live-restore mode, IPV6 entries are getting cleaned up due to below code - // We should retain IPV6 configurations in live-restore mode when Docker Daemon - // comes back. It should work as it is on other cases - // As starting point, disable IPv6 on all interfaces - if !isRestore && !n.isDefault { - err = setIPv6(n.path, "all", false) - if err != nil { - logrus.Warnf("Failed to disable IPv6 on all interfaces on network namespace %q: %v", n.path, err) - } - } - - if err = n.loopbackUp(); err != nil { - n.nlHandle.Delete() - return nil, err - } - - return n, nil -} - -func (n *networkNamespace) InterfaceOptions() IfaceOptionSetter { - return n -} - -func (n *networkNamespace) NeighborOptions() NeighborOptionSetter { - return n -} - -func mountNetworkNamespace(basePath string, lnPath string) error { - return syscall.Mount(basePath, lnPath, "bind", syscall.MS_BIND, "") -} - -// GetSandboxForExternalKey returns sandbox object for the supplied path -func GetSandboxForExternalKey(basePath string, key string) (Sandbox, error) { - if err := createNamespaceFile(key); err != nil { - return nil, err - } - - if err := mountNetworkNamespace(basePath, key); err != nil { - return nil, err - } - n := &networkNamespace{path: key, nextIfIndex: make(map[string]int)} - - sboxNs, err := netns.GetFromPath(n.path) - if err != nil { - return nil, fmt.Errorf("failed get network namespace %q: %v", n.path, err) - } - defer sboxNs.Close() - - n.nlHandle, err = netlink.NewHandleAt(sboxNs, syscall.NETLINK_ROUTE) - if err != nil { - return nil, fmt.Errorf("failed to create a netlink handle: %v", err) - } - - err = n.nlHandle.SetSocketTimeout(ns.NetlinkSocketsTimeout) - if err != nil { - logrus.Warnf("Failed to set the timeout on the sandbox netlink handle sockets: %v", err) - } - - // As starting point, disable IPv6 on all interfaces - err = setIPv6(n.path, "all", false) - if err != nil { - logrus.Warnf("Failed to disable IPv6 on all interfaces on network namespace %q: %v", n.path, err) - } - - if err = n.loopbackUp(); err != nil { - n.nlHandle.Delete() - return nil, err - } - - return n, nil -} - -func reexecCreateNamespace() { - if len(os.Args) < 2 { - logrus.Fatal("no namespace path provided") - } - if err := mountNetworkNamespace("/proc/self/ns/net", os.Args[1]); err != nil { - logrus.Fatal(err) - } -} - -func createNetworkNamespace(path string, osCreate bool) error { - if err := createNamespaceFile(path); err != nil { - return err - } - - cmd := &exec.Cmd{ - Path: reexec.Self(), - Args: append([]string{"netns-create"}, path), - Stdout: os.Stdout, - Stderr: os.Stderr, - } - if osCreate { - cmd.SysProcAttr = &syscall.SysProcAttr{} - cmd.SysProcAttr.Cloneflags = syscall.CLONE_NEWNET - } - if err := cmd.Run(); err != nil { - return fmt.Errorf("namespace creation reexec command failed: %v", err) - } - - return nil -} - -func unmountNamespaceFile(path string) { - if _, err := os.Stat(path); err == nil { - syscall.Unmount(path, syscall.MNT_DETACH) - } -} - -func createNamespaceFile(path string) (err error) { - var f *os.File - - once.Do(createBasePath) - // Remove it from garbage collection list if present - removeFromGarbagePaths(path) - - // If the path is there unmount it first - unmountNamespaceFile(path) - - // wait for garbage collection to complete if it is in progress - // before trying to create the file. - gpmWg.Wait() - - if f, err = os.Create(path); err == nil { - f.Close() - } - - return err -} - -func (n *networkNamespace) loopbackUp() error { - iface, err := n.nlHandle.LinkByName("lo") - if err != nil { - return err - } - return n.nlHandle.LinkSetUp(iface) -} - -func (n *networkNamespace) GetLoopbackIfaceName() string { - return "lo" -} - -func (n *networkNamespace) AddAliasIP(ifName string, ip *net.IPNet) error { - iface, err := n.nlHandle.LinkByName(ifName) - if err != nil { - return err - } - return n.nlHandle.AddrAdd(iface, &netlink.Addr{IPNet: ip}) -} - -func (n *networkNamespace) RemoveAliasIP(ifName string, ip *net.IPNet) error { - iface, err := n.nlHandle.LinkByName(ifName) - if err != nil { - return err - } - return n.nlHandle.AddrDel(iface, &netlink.Addr{IPNet: ip}) -} - -func (n *networkNamespace) DisableARPForVIP(srcName string) (Err error) { - dstName := "" - for _, i := range n.Interfaces() { - if i.SrcName() == srcName { - dstName = i.DstName() - break - } - } - if dstName == "" { - return fmt.Errorf("failed to find interface %s in sandbox", srcName) - } - - err := n.InvokeFunc(func() { - path := filepath.Join("/proc/sys/net/ipv4/conf", dstName, "arp_ignore") - if err := ioutil.WriteFile(path, []byte{'1', '\n'}, 0644); err != nil { - Err = fmt.Errorf("Failed to set %s to 1: %v", path, err) - return - } - path = filepath.Join("/proc/sys/net/ipv4/conf", dstName, "arp_announce") - if err := ioutil.WriteFile(path, []byte{'2', '\n'}, 0644); err != nil { - Err = fmt.Errorf("Failed to set %s to 2: %v", path, err) - return - } - }) - if err != nil { - return err - } - return -} - -func (n *networkNamespace) InvokeFunc(f func()) error { - return nsInvoke(n.nsPath(), func(nsFD int) error { return nil }, func(callerFD int) error { - f() - return nil - }) -} - -// InitOSContext initializes OS context while configuring network resources -func InitOSContext() func() { - runtime.LockOSThread() - if err := ns.SetNamespace(); err != nil { - logrus.Error(err) - } - return runtime.UnlockOSThread -} - -func nsInvoke(path string, prefunc func(nsFD int) error, postfunc func(callerFD int) error) error { - defer InitOSContext()() - - newNs, err := netns.GetFromPath(path) - if err != nil { - return fmt.Errorf("failed get network namespace %q: %v", path, err) - } - defer newNs.Close() - - // Invoked before the namespace switch happens but after the namespace file - // handle is obtained. - if err := prefunc(int(newNs)); err != nil { - return fmt.Errorf("failed in prefunc: %v", err) - } - - if err = netns.Set(newNs); err != nil { - return err - } - defer ns.SetNamespace() - - // Invoked after the namespace switch. - return postfunc(ns.ParseHandlerInt()) -} - -func (n *networkNamespace) nsPath() string { - n.Lock() - defer n.Unlock() - - return n.path -} - -func (n *networkNamespace) Info() Info { - return n -} - -func (n *networkNamespace) Key() string { - return n.path -} - -func (n *networkNamespace) Destroy() error { - if n.nlHandle != nil { - n.nlHandle.Delete() - } - // Assuming no running process is executing in this network namespace, - // unmounting is sufficient to destroy it. - if err := syscall.Unmount(n.path, syscall.MNT_DETACH); err != nil { - return err - } - - // Stash it into the garbage collection list - addToGarbagePaths(n.path) - return nil -} - -// Restore restore the network namespace -func (n *networkNamespace) Restore(ifsopt map[string][]IfaceOption, routes []*types.StaticRoute, gw net.IP, gw6 net.IP) error { - // restore interfaces - for name, opts := range ifsopt { - if !strings.Contains(name, "+") { - return fmt.Errorf("wrong iface name in restore osl sandbox interface: %s", name) - } - seps := strings.Split(name, "+") - srcName := seps[0] - dstPrefix := seps[1] - i := &nwIface{srcName: srcName, dstName: dstPrefix, ns: n} - i.processInterfaceOptions(opts...) - if i.master != "" { - i.dstMaster = n.findDst(i.master, true) - if i.dstMaster == "" { - return fmt.Errorf("could not find an appropriate master %q for %q", - i.master, i.srcName) - } - } - if n.isDefault { - i.dstName = i.srcName - } else { - links, err := n.nlHandle.LinkList() - if err != nil { - return fmt.Errorf("failed to retrieve list of links in network namespace %q during restore", n.path) - } - // due to the docker network connect/disconnect, so the dstName should - // restore from the namespace - for _, link := range links { - addrs, err := n.nlHandle.AddrList(link, netlink.FAMILY_V4) - if err != nil { - return err - } - ifaceName := link.Attrs().Name - if strings.HasPrefix(ifaceName, "vxlan") { - if i.dstName == "vxlan" { - i.dstName = ifaceName - break - } - } - // find the interface name by ip - if i.address != nil { - for _, addr := range addrs { - if addr.IPNet.String() == i.address.String() { - i.dstName = ifaceName - break - } - continue - } - if i.dstName == ifaceName { - break - } - } - // This is to find the interface name of the pair in overlay sandbox - if strings.HasPrefix(ifaceName, "veth") { - if i.master != "" && i.dstName == "veth" { - i.dstName = ifaceName - } - } - } - - var index int - indexStr := strings.TrimPrefix(i.dstName, dstPrefix) - if indexStr != "" { - index, err = strconv.Atoi(indexStr) - if err != nil { - return err - } - } - index++ - n.Lock() - if index > n.nextIfIndex[dstPrefix] { - n.nextIfIndex[dstPrefix] = index - } - n.iFaces = append(n.iFaces, i) - n.Unlock() - } - } - - // restore routes - for _, r := range routes { - n.Lock() - n.staticRoutes = append(n.staticRoutes, r) - n.Unlock() - } - - // restore gateway - if len(gw) > 0 { - n.Lock() - n.gw = gw - n.Unlock() - } - - if len(gw6) > 0 { - n.Lock() - n.gwv6 = gw6 - n.Unlock() - } - - return nil -} - -// Checks whether IPv6 needs to be enabled/disabled on the loopback interface -func (n *networkNamespace) checkLoV6() { - var ( - enable = false - action = "disable" - ) - - n.Lock() - for _, iface := range n.iFaces { - if iface.AddressIPv6() != nil { - enable = true - action = "enable" - break - } - } - n.Unlock() - - if n.loV6Enabled == enable { - return - } - - if err := setIPv6(n.path, "lo", enable); err != nil { - logrus.Warnf("Failed to %s IPv6 on loopback interface on network namespace %q: %v", action, n.path, err) - } - - n.loV6Enabled = enable -} - -func reexecSetIPv6() { - runtime.LockOSThread() - defer runtime.UnlockOSThread() - - if len(os.Args) < 3 { - logrus.Errorf("invalid number of arguments for %s", os.Args[0]) - os.Exit(1) - } - - ns, err := netns.GetFromPath(os.Args[1]) - if err != nil { - logrus.Errorf("failed get network namespace %q: %v", os.Args[1], err) - os.Exit(2) - } - defer ns.Close() - - if err = netns.Set(ns); err != nil { - logrus.Errorf("setting into container netns %q failed: %v", os.Args[1], err) - os.Exit(3) - } - - var ( - action = "disable" - value = byte('1') - path = fmt.Sprintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", os.Args[2]) - ) - - if os.Args[3] == "true" { - action = "enable" - value = byte('0') - } - - if _, err := os.Stat(path); err != nil { - if os.IsNotExist(err) { - logrus.Warnf("file does not exist: %s : %v Has IPv6 been disabled in this node's kernel?", path, err) - os.Exit(0) - } - logrus.Errorf("failed to stat %s : %v", path, err) - os.Exit(5) - } - - if err = ioutil.WriteFile(path, []byte{value, '\n'}, 0644); err != nil { - logrus.Errorf("failed to %s IPv6 forwarding for container's interface %s: %v", action, os.Args[2], err) - os.Exit(4) - } - - os.Exit(0) -} - -func setIPv6(path, iface string, enable bool) error { - cmd := &exec.Cmd{ - Path: reexec.Self(), - Args: append([]string{"set-ipv6"}, path, iface, strconv.FormatBool(enable)), - Stdout: os.Stdout, - Stderr: os.Stderr, - } - if err := cmd.Run(); err != nil { - return fmt.Errorf("reexec to set IPv6 failed: %v", err) - } - return nil -} - -// ApplyOSTweaks applies linux configs on the sandbox -func (n *networkNamespace) ApplyOSTweaks(types []SandboxType) { - for _, t := range types { - switch t { - case SandboxTypeLoadBalancer: - kernel.ApplyOSTweaks(loadBalancerConfig) - } - } -} diff --git a/vendor/github.com/docker/libnetwork/osl/namespace_unsupported.go b/vendor/github.com/docker/libnetwork/osl/namespace_unsupported.go deleted file mode 100644 index 74372e2492..0000000000 --- a/vendor/github.com/docker/libnetwork/osl/namespace_unsupported.go +++ /dev/null @@ -1,17 +0,0 @@ -// +build !linux,!windows,!freebsd - -package osl - -// GC triggers garbage collection of namespace path right away -// and waits for it. -func GC() { -} - -// GetSandboxForExternalKey returns sandbox object for the supplied path -func GetSandboxForExternalKey(path string, key string) (Sandbox, error) { - return nil, nil -} - -// SetBasePath sets the base url prefix for the ns path -func SetBasePath(path string) { -} diff --git a/vendor/github.com/docker/libnetwork/osl/namespace_windows.go b/vendor/github.com/docker/libnetwork/osl/namespace_windows.go deleted file mode 100644 index 49503c00ff..0000000000 --- a/vendor/github.com/docker/libnetwork/osl/namespace_windows.go +++ /dev/null @@ -1,38 +0,0 @@ -package osl - -import "testing" - -// GenerateKey generates a sandbox key based on the passed -// container id. -func GenerateKey(containerID string) string { - return containerID -} - -// NewSandbox provides a new sandbox instance created in an os specific way -// provided a key which uniquely identifies the sandbox -func NewSandbox(key string, osCreate, isRestore bool) (Sandbox, error) { - return nil, nil -} - -func GetSandboxForExternalKey(path string, key string) (Sandbox, error) { - return nil, nil -} - -// GC triggers garbage collection of namespace path right away -// and waits for it. -func GC() { -} - -// InitOSContext initializes OS context while configuring network resources -func InitOSContext() func() { - return func() {} -} - -// SetupTestOSContext sets up a separate test OS context in which tests will be executed. -func SetupTestOSContext(t *testing.T) func() { - return func() {} -} - -// SetBasePath sets the base url prefix for the ns path -func SetBasePath(path string) { -} diff --git a/vendor/github.com/docker/libnetwork/osl/neigh_freebsd.go b/vendor/github.com/docker/libnetwork/osl/neigh_freebsd.go deleted file mode 100644 index 280f006396..0000000000 --- a/vendor/github.com/docker/libnetwork/osl/neigh_freebsd.go +++ /dev/null @@ -1,4 +0,0 @@ -package osl - -// NeighOption is a function option type to set neighbor options -type NeighOption func() diff --git a/vendor/github.com/docker/libnetwork/osl/neigh_linux.go b/vendor/github.com/docker/libnetwork/osl/neigh_linux.go deleted file mode 100644 index 6bf1c16dc5..0000000000 --- a/vendor/github.com/docker/libnetwork/osl/neigh_linux.go +++ /dev/null @@ -1,194 +0,0 @@ -package osl - -import ( - "bytes" - "fmt" - "net" - - "github.com/sirupsen/logrus" - "github.com/vishvananda/netlink" -) - -// NeighborSearchError indicates that the neighbor is already present -type NeighborSearchError struct { - ip net.IP - mac net.HardwareAddr - present bool -} - -func (n NeighborSearchError) Error() string { - return fmt.Sprintf("Search neighbor failed for IP %v, mac %v, present in db:%t", n.ip, n.mac, n.present) -} - -// NeighOption is a function option type to set interface options -type NeighOption func(nh *neigh) - -type neigh struct { - dstIP net.IP - dstMac net.HardwareAddr - linkName string - linkDst string - family int -} - -func (n *networkNamespace) findNeighbor(dstIP net.IP, dstMac net.HardwareAddr) *neigh { - n.Lock() - defer n.Unlock() - - for _, nh := range n.neighbors { - if nh.dstIP.Equal(dstIP) && bytes.Equal(nh.dstMac, dstMac) { - return nh - } - } - - return nil -} - -func (n *networkNamespace) DeleteNeighbor(dstIP net.IP, dstMac net.HardwareAddr, osDelete bool) error { - var ( - iface netlink.Link - err error - ) - - nh := n.findNeighbor(dstIP, dstMac) - if nh == nil { - return NeighborSearchError{dstIP, dstMac, false} - } - - if osDelete { - n.Lock() - nlh := n.nlHandle - n.Unlock() - - if nh.linkDst != "" { - iface, err = nlh.LinkByName(nh.linkDst) - if err != nil { - return fmt.Errorf("could not find interface with destination name %s: %v", - nh.linkDst, err) - } - } - - nlnh := &netlink.Neigh{ - IP: dstIP, - State: netlink.NUD_PERMANENT, - Family: nh.family, - } - - if nlnh.Family > 0 { - nlnh.HardwareAddr = dstMac - nlnh.Flags = netlink.NTF_SELF - } - - if nh.linkDst != "" { - nlnh.LinkIndex = iface.Attrs().Index - } - - // If the kernel deletion fails for the neighbor entry still remote it - // from the namespace cache. Otherwise if the neighbor moves back to the - // same host again, kernel update can fail. - if err := nlh.NeighDel(nlnh); err != nil { - logrus.Warnf("Deleting neighbor IP %s, mac %s failed, %v", dstIP, dstMac, err) - } - - // Delete the dynamic entry in the bridge - if nlnh.Family > 0 { - nlnh := &netlink.Neigh{ - IP: dstIP, - Family: nh.family, - } - - nlnh.HardwareAddr = dstMac - nlnh.Flags = netlink.NTF_MASTER - if nh.linkDst != "" { - nlnh.LinkIndex = iface.Attrs().Index - } - nlh.NeighDel(nlnh) - } - } - - n.Lock() - for i, nh := range n.neighbors { - if nh.dstIP.Equal(dstIP) && bytes.Equal(nh.dstMac, dstMac) { - n.neighbors = append(n.neighbors[:i], n.neighbors[i+1:]...) - break - } - } - n.Unlock() - logrus.Debugf("Neighbor entry deleted for IP %v, mac %v osDelete:%t", dstIP, dstMac, osDelete) - - return nil -} - -func (n *networkNamespace) AddNeighbor(dstIP net.IP, dstMac net.HardwareAddr, force bool, options ...NeighOption) error { - var ( - iface netlink.Link - err error - neighborAlreadyPresent bool - ) - - // If the namespace already has the neighbor entry but the AddNeighbor is called - // because of a miss notification (force flag) program the kernel anyway. - nh := n.findNeighbor(dstIP, dstMac) - if nh != nil { - neighborAlreadyPresent = true - logrus.Warnf("Neighbor entry already present for IP %v, mac %v neighbor:%+v forceUpdate:%t", dstIP, dstMac, nh, force) - if !force { - return NeighborSearchError{dstIP, dstMac, true} - } - } - - nh = &neigh{ - dstIP: dstIP, - dstMac: dstMac, - } - - nh.processNeighOptions(options...) - - if nh.linkName != "" { - nh.linkDst = n.findDst(nh.linkName, false) - if nh.linkDst == "" { - return fmt.Errorf("could not find the interface with name %s", nh.linkName) - } - } - - n.Lock() - nlh := n.nlHandle - n.Unlock() - - if nh.linkDst != "" { - iface, err = nlh.LinkByName(nh.linkDst) - if err != nil { - return fmt.Errorf("could not find interface with destination name %s: %v", nh.linkDst, err) - } - } - - nlnh := &netlink.Neigh{ - IP: dstIP, - HardwareAddr: dstMac, - State: netlink.NUD_PERMANENT, - Family: nh.family, - } - - if nlnh.Family > 0 { - nlnh.Flags = netlink.NTF_SELF - } - - if nh.linkDst != "" { - nlnh.LinkIndex = iface.Attrs().Index - } - - if err := nlh.NeighSet(nlnh); err != nil { - return fmt.Errorf("could not add neighbor entry:%+v error:%v", nlnh, err) - } - - if neighborAlreadyPresent { - return nil - } - - n.Lock() - n.neighbors = append(n.neighbors, nh) - n.Unlock() - logrus.Debugf("Neighbor entry added for IP:%v, mac:%v on ifc:%s", dstIP, dstMac, nh.linkName) - - return nil -} diff --git a/vendor/github.com/docker/libnetwork/osl/neigh_windows.go b/vendor/github.com/docker/libnetwork/osl/neigh_windows.go deleted file mode 100644 index 280f006396..0000000000 --- a/vendor/github.com/docker/libnetwork/osl/neigh_windows.go +++ /dev/null @@ -1,4 +0,0 @@ -package osl - -// NeighOption is a function option type to set neighbor options -type NeighOption func() diff --git a/vendor/github.com/docker/libnetwork/osl/options_linux.go b/vendor/github.com/docker/libnetwork/osl/options_linux.go deleted file mode 100644 index 818669647f..0000000000 --- a/vendor/github.com/docker/libnetwork/osl/options_linux.go +++ /dev/null @@ -1,73 +0,0 @@ -package osl - -import "net" - -func (nh *neigh) processNeighOptions(options ...NeighOption) { - for _, opt := range options { - if opt != nil { - opt(nh) - } - } -} - -func (n *networkNamespace) LinkName(name string) NeighOption { - return func(nh *neigh) { - nh.linkName = name - } -} - -func (n *networkNamespace) Family(family int) NeighOption { - return func(nh *neigh) { - nh.family = family - } -} - -func (i *nwIface) processInterfaceOptions(options ...IfaceOption) { - for _, opt := range options { - if opt != nil { - opt(i) - } - } -} - -func (n *networkNamespace) Bridge(isBridge bool) IfaceOption { - return func(i *nwIface) { - i.bridge = isBridge - } -} - -func (n *networkNamespace) Master(name string) IfaceOption { - return func(i *nwIface) { - i.master = name - } -} - -func (n *networkNamespace) MacAddress(mac net.HardwareAddr) IfaceOption { - return func(i *nwIface) { - i.mac = mac - } -} - -func (n *networkNamespace) Address(addr *net.IPNet) IfaceOption { - return func(i *nwIface) { - i.address = addr - } -} - -func (n *networkNamespace) AddressIPv6(addr *net.IPNet) IfaceOption { - return func(i *nwIface) { - i.addressIPv6 = addr - } -} - -func (n *networkNamespace) LinkLocalAddresses(list []*net.IPNet) IfaceOption { - return func(i *nwIface) { - i.llAddrs = list - } -} - -func (n *networkNamespace) Routes(routes []*net.IPNet) IfaceOption { - return func(i *nwIface) { - i.routes = routes - } -} diff --git a/vendor/github.com/docker/libnetwork/osl/route_linux.go b/vendor/github.com/docker/libnetwork/osl/route_linux.go deleted file mode 100644 index a9ff191b37..0000000000 --- a/vendor/github.com/docker/libnetwork/osl/route_linux.go +++ /dev/null @@ -1,203 +0,0 @@ -package osl - -import ( - "fmt" - "net" - - "github.com/docker/libnetwork/types" - "github.com/vishvananda/netlink" -) - -func (n *networkNamespace) Gateway() net.IP { - n.Lock() - defer n.Unlock() - - return n.gw -} - -func (n *networkNamespace) GatewayIPv6() net.IP { - n.Lock() - defer n.Unlock() - - return n.gwv6 -} - -func (n *networkNamespace) StaticRoutes() []*types.StaticRoute { - n.Lock() - defer n.Unlock() - - routes := make([]*types.StaticRoute, len(n.staticRoutes)) - for i, route := range n.staticRoutes { - r := route.GetCopy() - routes[i] = r - } - - return routes -} - -func (n *networkNamespace) setGateway(gw net.IP) { - n.Lock() - n.gw = gw - n.Unlock() -} - -func (n *networkNamespace) setGatewayIPv6(gwv6 net.IP) { - n.Lock() - n.gwv6 = gwv6 - n.Unlock() -} - -func (n *networkNamespace) SetGateway(gw net.IP) error { - // Silently return if the gateway is empty - if len(gw) == 0 { - return nil - } - - err := n.programGateway(gw, true) - if err == nil { - n.setGateway(gw) - } - - return err -} - -func (n *networkNamespace) UnsetGateway() error { - gw := n.Gateway() - - // Silently return if the gateway is empty - if len(gw) == 0 { - return nil - } - - err := n.programGateway(gw, false) - if err == nil { - n.setGateway(net.IP{}) - } - - return err -} - -func (n *networkNamespace) programGateway(gw net.IP, isAdd bool) error { - gwRoutes, err := n.nlHandle.RouteGet(gw) - if err != nil { - return fmt.Errorf("route for the gateway %s could not be found: %v", gw, err) - } - - var linkIndex int - for _, gwRoute := range gwRoutes { - if gwRoute.Gw == nil { - linkIndex = gwRoute.LinkIndex - break - } - } - - if linkIndex == 0 { - return fmt.Errorf("Direct route for the gateway %s could not be found", gw) - } - - if isAdd { - return n.nlHandle.RouteAdd(&netlink.Route{ - Scope: netlink.SCOPE_UNIVERSE, - LinkIndex: linkIndex, - Gw: gw, - }) - } - - return n.nlHandle.RouteDel(&netlink.Route{ - Scope: netlink.SCOPE_UNIVERSE, - LinkIndex: linkIndex, - Gw: gw, - }) -} - -// 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, - }) -} - -// Delete a route from the namespace routing table. -func (n *networkNamespace) removeRoute(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 could not be found: %v", err) - } - - return n.nlHandle.RouteDel(&netlink.Route{ - Scope: netlink.SCOPE_UNIVERSE, - LinkIndex: gwRoutes[0].LinkIndex, - Gw: nh, - Dst: dest, - }) -} - -func (n *networkNamespace) SetGatewayIPv6(gwv6 net.IP) error { - // Silently return if the gateway is empty - if len(gwv6) == 0 { - return nil - } - - err := n.programGateway(gwv6, true) - if err == nil { - n.setGatewayIPv6(gwv6) - } - - return err -} - -func (n *networkNamespace) UnsetGatewayIPv6() error { - gwv6 := n.GatewayIPv6() - - // Silently return if the gateway is empty - if len(gwv6) == 0 { - return nil - } - - err := n.programGateway(gwv6, false) - if err == nil { - n.Lock() - n.gwv6 = net.IP{} - n.Unlock() - } - - return err -} - -func (n *networkNamespace) AddStaticRoute(r *types.StaticRoute) error { - err := n.programRoute(n.nsPath(), r.Destination, r.NextHop) - if err == nil { - n.Lock() - n.staticRoutes = append(n.staticRoutes, r) - n.Unlock() - } - return err -} - -func (n *networkNamespace) RemoveStaticRoute(r *types.StaticRoute) error { - - err := n.removeRoute(n.nsPath(), r.Destination, r.NextHop) - if err == nil { - n.Lock() - lastIndex := len(n.staticRoutes) - 1 - for i, v := range n.staticRoutes { - if v == r { - // Overwrite the route we're removing with the last element - n.staticRoutes[i] = n.staticRoutes[lastIndex] - // Shorten the slice to trim the extra element - n.staticRoutes = n.staticRoutes[:lastIndex] - break - } - } - n.Unlock() - } - return err -} diff --git a/vendor/github.com/docker/libnetwork/osl/sandbox.go b/vendor/github.com/docker/libnetwork/osl/sandbox.go deleted file mode 100644 index 198cf641a1..0000000000 --- a/vendor/github.com/docker/libnetwork/osl/sandbox.go +++ /dev/null @@ -1,191 +0,0 @@ -// Package osl describes structures and interfaces which abstract os entities -package osl - -import ( - "net" - - "github.com/docker/libnetwork/types" -) - -// SandboxType specify the time of the sandbox, this can be used to apply special configs -type SandboxType int - -const ( - // SandboxTypeIngress indicates that the sandbox is for the ingress - SandboxTypeIngress = iota - // SandboxTypeLoadBalancer indicates that the sandbox is a load balancer - SandboxTypeLoadBalancer = iota -) - -// Sandbox represents a network sandbox, identified by a specific key. It -// holds a list of Interfaces, routes etc, and more can be added dynamically. -type Sandbox interface { - // The path where the network namespace is mounted. - Key() string - - // Add an existing Interface to this sandbox. The operation will rename - // from the Interface SrcName to DstName as it moves, and reconfigure the - // interface according to the specified settings. The caller is expected - // to only provide a prefix for DstName. The AddInterface api will auto-generate - // an appropriate suffix for the DstName to disambiguate. - AddInterface(SrcName string, DstPrefix string, options ...IfaceOption) error - - // Set default IPv4 gateway for the sandbox - SetGateway(gw net.IP) error - - // Set default IPv6 gateway for the sandbox - SetGatewayIPv6(gw net.IP) error - - // Unset the previously set default IPv4 gateway in the sandbox - UnsetGateway() error - - // Unset the previously set default IPv6 gateway in the sandbox - UnsetGatewayIPv6() error - - // GetLoopbackIfaceName returns the name of the loopback interface - GetLoopbackIfaceName() string - - // AddAliasIP adds the passed IP address to the named interface - AddAliasIP(ifName string, ip *net.IPNet) error - - // RemoveAliasIP removes the passed IP address from the named interface - RemoveAliasIP(ifName string, ip *net.IPNet) error - - // DisableARPForVIP disables ARP replies and requests for VIP addresses - // on a particular interface - DisableARPForVIP(ifName string) error - - // Add a static route to the sandbox. - AddStaticRoute(*types.StaticRoute) error - - // Remove a static route from the sandbox. - RemoveStaticRoute(*types.StaticRoute) error - - // AddNeighbor adds a neighbor entry into the sandbox. - AddNeighbor(dstIP net.IP, dstMac net.HardwareAddr, force bool, option ...NeighOption) error - - // DeleteNeighbor deletes neighbor entry from the sandbox. - DeleteNeighbor(dstIP net.IP, dstMac net.HardwareAddr, osDelete bool) error - - // Returns an interface with methods to set neighbor options. - NeighborOptions() NeighborOptionSetter - - // Returns an interface with methods to set interface options. - InterfaceOptions() IfaceOptionSetter - - //Invoke - InvokeFunc(func()) error - - // Returns an interface with methods to get sandbox state. - Info() Info - - // Destroy the sandbox - Destroy() error - - // restore sandbox - Restore(ifsopt map[string][]IfaceOption, routes []*types.StaticRoute, gw net.IP, gw6 net.IP) error - - // ApplyOSTweaks applies operating system specific knobs on the sandbox - ApplyOSTweaks([]SandboxType) -} - -// NeighborOptionSetter interface defines the option setter methods for interface options -type NeighborOptionSetter interface { - // LinkName returns an option setter to set the srcName of the link that should - // be used in the neighbor entry - LinkName(string) NeighOption - - // Family returns an option setter to set the address family for the neighbor - // entry. eg. AF_BRIDGE - Family(int) NeighOption -} - -// IfaceOptionSetter interface defines the option setter methods for interface options. -type IfaceOptionSetter interface { - // Bridge returns an option setter to set if the interface is a bridge. - Bridge(bool) IfaceOption - - // MacAddress returns an option setter to set the MAC address. - MacAddress(net.HardwareAddr) IfaceOption - - // Address returns an option setter to set IPv4 address. - Address(*net.IPNet) IfaceOption - - // Address returns an option setter to set IPv6 address. - AddressIPv6(*net.IPNet) IfaceOption - - // LinkLocalAddresses returns an option setter to set the link-local IP addresses. - LinkLocalAddresses([]*net.IPNet) IfaceOption - - // Master returns an option setter to set the master interface if any for this - // interface. The master interface name should refer to the srcname of a - // previously added interface of type bridge. - Master(string) IfaceOption - - // Address returns an option setter to set interface routes. - Routes([]*net.IPNet) IfaceOption -} - -// Info represents all possible information that -// the driver wants to place in the sandbox which includes -// interfaces, routes and gateway -type Info interface { - // The collection of Interface previously added with the AddInterface - // method. Note that this doesn't include network interfaces added in any - // other way (such as the default loopback interface which is automatically - // created on creation of a sandbox). - Interfaces() []Interface - - // IPv4 gateway for the sandbox. - Gateway() net.IP - - // IPv6 gateway for the sandbox. - GatewayIPv6() net.IP - - // Additional static routes for the sandbox. (Note that directly - // connected routes are stored on the particular interface they refer to.) - StaticRoutes() []*types.StaticRoute - - // TODO: Add ip tables etc. -} - -// Interface represents the settings and identity of a network device. It is -// used as a return type for Network.Link, and it is common practice for the -// caller to use this information when moving interface SrcName from host -// namespace to DstName in a different net namespace with the appropriate -// network settings. -type Interface interface { - // The name of the interface in the origin network namespace. - SrcName() string - - // The name that will be assigned to the interface once moves inside a - // network namespace. When the caller passes in a DstName, it is only - // expected to pass a prefix. The name will modified with an appropriately - // auto-generated suffix. - DstName() string - - // IPv4 address for the interface. - Address() *net.IPNet - - // IPv6 address for the interface. - AddressIPv6() *net.IPNet - - // LinkLocalAddresses returns the link-local IP addresses assigned to the interface. - LinkLocalAddresses() []*net.IPNet - - // IP routes for the interface. - Routes() []*net.IPNet - - // Bridge returns true if the interface is a bridge - Bridge() bool - - // Master returns the srcname of the master interface for this interface. - Master() string - - // Remove an interface from the sandbox by renaming to original name - // and moving it out of the sandbox. - Remove() error - - // Statistics returns the statistics for this interface - Statistics() (*types.InterfaceStatistics, error) -} diff --git a/vendor/github.com/docker/libnetwork/osl/sandbox_freebsd.go b/vendor/github.com/docker/libnetwork/osl/sandbox_freebsd.go deleted file mode 100644 index e5bc6278ee..0000000000 --- a/vendor/github.com/docker/libnetwork/osl/sandbox_freebsd.go +++ /dev/null @@ -1,44 +0,0 @@ -package osl - -import "testing" - -// GenerateKey generates a sandbox key based on the passed -// container id. -func GenerateKey(containerID string) string { - maxLen := 12 - if len(containerID) < maxLen { - maxLen = len(containerID) - } - - return containerID[:maxLen] -} - -// NewSandbox provides a new sandbox instance created in an os specific way -// provided a key which uniquely identifies the sandbox -func NewSandbox(key string, osCreate, isRestore bool) (Sandbox, error) { - return nil, nil -} - -// GetSandboxForExternalKey returns sandbox object for the supplied path -func GetSandboxForExternalKey(path string, key string) (Sandbox, error) { - return nil, nil -} - -// GC triggers garbage collection of namespace path right away -// and waits for it. -func GC() { -} - -// InitOSContext initializes OS context while configuring network resources -func InitOSContext() func() { - return func() {} -} - -// SetupTestOSContext sets up a separate test OS context in which tests will be executed. -func SetupTestOSContext(t *testing.T) func() { - return func() {} -} - -// SetBasePath sets the base url prefix for the ns path -func SetBasePath(path string) { -} diff --git a/vendor/github.com/docker/libnetwork/osl/sandbox_unsupported.go b/vendor/github.com/docker/libnetwork/osl/sandbox_unsupported.go deleted file mode 100644 index 51a656c806..0000000000 --- a/vendor/github.com/docker/libnetwork/osl/sandbox_unsupported.go +++ /dev/null @@ -1,22 +0,0 @@ -// +build !linux,!windows,!freebsd - -package osl - -import "errors" - -var ( - // ErrNotImplemented is for platforms which don't implement sandbox - ErrNotImplemented = errors.New("not implemented") -) - -// NewSandbox provides a new sandbox instance created in an os specific way -// provided a key which uniquely identifies the sandbox -func NewSandbox(key string, osCreate, isRestore bool) (Sandbox, error) { - return nil, ErrNotImplemented -} - -// GenerateKey generates a sandbox key based on the passed -// container id. -func GenerateKey(containerID string) string { - return "" -} diff --git a/vendor/github.com/docker/libnetwork/portallocator/portallocator.go b/vendor/github.com/docker/libnetwork/portallocator/portallocator.go deleted file mode 100644 index c87478c0cd..0000000000 --- a/vendor/github.com/docker/libnetwork/portallocator/portallocator.go +++ /dev/null @@ -1,305 +0,0 @@ -package portallocator - -import ( - "errors" - "fmt" - "github.com/sirupsen/logrus" - "net" - "sync" -) - -var ( - // defaultPortRangeStart indicates the first port in port range - defaultPortRangeStart = 49153 - // defaultPortRangeEnd indicates the last port in port range - // consistent with default /proc/sys/net/ipv4/ip_local_port_range - // upper bound on linux - defaultPortRangeEnd = 60999 -) - -func sanitizePortRange(start int, end int) (newStart, newEnd int, err error) { - if start > defaultPortRangeEnd || end < defaultPortRangeStart || start > end { - return 0, 0, fmt.Errorf("Request out allowed range [%v, %v]", - defaultPortRangeStart, defaultPortRangeEnd) - } - err = nil - newStart, newEnd = start, end - if start < defaultPortRangeStart { - newStart = defaultPortRangeStart - } - if end > defaultPortRangeEnd { - newEnd = defaultPortRangeEnd - } - return -} - -type ipMapping map[string]protoMap - -var ( - // ErrAllPortsAllocated is returned when no more ports are available - ErrAllPortsAllocated = errors.New("all ports are allocated") - // ErrUnknownProtocol is returned when an unknown protocol was specified - ErrUnknownProtocol = errors.New("unknown protocol") - defaultIP = net.ParseIP("0.0.0.0") - once sync.Once - instance *PortAllocator - createInstance = func() { instance = newInstance() } -) - -// ErrPortAlreadyAllocated is the returned error information when a requested port is already being used -type ErrPortAlreadyAllocated struct { - ip string - port int -} - -func newErrPortAlreadyAllocated(ip string, port int) ErrPortAlreadyAllocated { - return ErrPortAlreadyAllocated{ - ip: ip, - port: port, - } -} - -// IP returns the address to which the used port is associated -func (e ErrPortAlreadyAllocated) IP() string { - return e.ip -} - -// Port returns the value of the already used port -func (e ErrPortAlreadyAllocated) Port() int { - return e.port -} - -// IPPort returns the address and the port in the form ip:port -func (e ErrPortAlreadyAllocated) IPPort() string { - return fmt.Sprintf("%s:%d", e.ip, e.port) -} - -// Error is the implementation of error.Error interface -func (e ErrPortAlreadyAllocated) Error() string { - return fmt.Sprintf("Bind for %s:%d failed: port is already allocated", e.ip, e.port) -} - -type ( - // PortAllocator manages the transport ports database - PortAllocator struct { - mutex sync.Mutex - ipMap ipMapping - Begin int - End int - } - portRange struct { - begin int - end int - last int - } - portMap struct { - p map[int]struct{} - defaultRange string - portRanges map[string]*portRange - } - protoMap map[string]*portMap -) - -// Get returns the default instance of PortAllocator -func Get() *PortAllocator { - // Port Allocator is a singleton - // Note: Long term solution will be each PortAllocator will have access to - // the OS so that it can have up to date view of the OS port allocation. - // When this happens singleton behavior will be removed. Clients do not - // need to worry about this, they will not see a change in behavior. - once.Do(createInstance) - return instance -} - -func getDefaultPortRange() (int, int) { - start, end, err := getDynamicPortRange() - if err == nil { - start, end, err = sanitizePortRange(start, end) - } - if err != nil { - start, end = defaultPortRangeStart, defaultPortRangeEnd - } - return start, end -} - -func newInstance() *PortAllocator { - start, end := getDefaultPortRange() - return &PortAllocator{ - ipMap: ipMapping{}, - Begin: start, - End: end, - } -} - -// RequestPort requests new port from global ports pool for specified ip and proto. -// If port is 0 it returns first free port. Otherwise it checks port availability -// in proto's pool and returns that port or error if port is already busy. -func (p *PortAllocator) RequestPort(ip net.IP, proto string, port int) (int, error) { - return p.RequestPortInRange(ip, proto, port, port) -} - -// RequestPortInRange requests new port from global ports pool for specified ip and proto. -// If portStart and portEnd are 0 it returns the first free port in the default ephemeral range. -// If portStart != portEnd it returns the first free port in the requested range. -// Otherwise (portStart == portEnd) it checks port availability in the requested proto's port-pool -// and returns that port or error if port is already busy. -func (p *PortAllocator) RequestPortInRange(ip net.IP, proto string, portStart, portEnd int) (int, error) { - p.mutex.Lock() - defer p.mutex.Unlock() - - if proto != "tcp" && proto != "udp" && proto != "sctp" { - return 0, ErrUnknownProtocol - } - - if ip == nil { - ip = defaultIP - } - ipstr := ip.String() - protomap, ok := p.ipMap[ipstr] - if !ok { - protomap = protoMap{ - "tcp": p.newPortMap(), - "udp": p.newPortMap(), - "sctp": p.newPortMap(), - } - - p.ipMap[ipstr] = protomap - } - mapping := protomap[proto] - if portStart > 0 && portStart == portEnd { - if _, ok := mapping.p[portStart]; !ok { - mapping.p[portStart] = struct{}{} - return portStart, nil - } - return 0, newErrPortAlreadyAllocated(ipstr, portStart) - } - - port, err := mapping.findPort(portStart, portEnd) - if err != nil { - return 0, err - } - return port, nil -} - -// ReleasePort releases port from global ports pool for specified ip and proto. -func (p *PortAllocator) ReleasePort(ip net.IP, proto string, port int) error { - p.mutex.Lock() - defer p.mutex.Unlock() - - if ip == nil { - ip = defaultIP - } - protomap, ok := p.ipMap[ip.String()] - if !ok { - return nil - } - delete(protomap[proto].p, port) - return nil -} - -// SetPortRange sets dynamic port allocation range. -// if both portBegin and portEnd are 0, the port range reverts to default -// value. Otherwise they are sanitized against the default values to -// ensure their validity. -func (p *PortAllocator) SetPortRange(portBegin, portEnd int) error { - // if begin and end is zero, revert to default values - var begin, end int - var err error - if portBegin == 0 && portEnd == 0 { - begin, end = getDefaultPortRange() - - } else { - begin, end, err = sanitizePortRange(portBegin, portEnd) - if err != nil { - return err - } - } - logrus.Debugf("Setting up port allocator to range %v-%v, current %v-%v", - begin, end, p.Begin, p.End) - p.mutex.Lock() - defer p.mutex.Unlock() - if p.Begin == begin && p.End == end { - return nil - } - p.ipMap = ipMapping{} - p.Begin, p.End = begin, end - return nil -} - -func (p *PortAllocator) newPortMap() *portMap { - defaultKey := getRangeKey(p.Begin, p.End) - pm := &portMap{ - p: map[int]struct{}{}, - defaultRange: defaultKey, - portRanges: map[string]*portRange{ - defaultKey: newPortRange(p.Begin, p.End), - }, - } - return pm -} - -// ReleaseAll releases all ports for all ips. -func (p *PortAllocator) ReleaseAll() error { - p.mutex.Lock() - p.ipMap = ipMapping{} - p.mutex.Unlock() - return nil -} - -func getRangeKey(portStart, portEnd int) string { - return fmt.Sprintf("%d-%d", portStart, portEnd) -} - -func newPortRange(portStart, portEnd int) *portRange { - return &portRange{ - begin: portStart, - end: portEnd, - last: portEnd, - } -} - -func (pm *portMap) getPortRange(portStart, portEnd int) (*portRange, error) { - var key string - if portStart == 0 && portEnd == 0 { - key = pm.defaultRange - } else { - key = getRangeKey(portStart, portEnd) - if portStart == portEnd || - portStart == 0 || portEnd == 0 || - portEnd < portStart { - return nil, fmt.Errorf("invalid port range: %s", key) - } - } - - // Return existing port range, if already known. - if pr, exists := pm.portRanges[key]; exists { - return pr, nil - } - - // Otherwise create a new port range. - pr := newPortRange(portStart, portEnd) - pm.portRanges[key] = pr - return pr, nil -} - -func (pm *portMap) findPort(portStart, portEnd int) (int, error) { - pr, err := pm.getPortRange(portStart, portEnd) - if err != nil { - return 0, err - } - port := pr.last - - for i := 0; i <= pr.end-pr.begin; i++ { - port++ - if port > pr.end { - port = pr.begin - } - - if _, ok := pm.p[port]; !ok { - pm.p[port] = struct{}{} - pr.last = port - return port, nil - } - } - return 0, ErrAllPortsAllocated -} diff --git a/vendor/github.com/docker/libnetwork/portallocator/portallocator_freebsd.go b/vendor/github.com/docker/libnetwork/portallocator/portallocator_freebsd.go deleted file mode 100644 index d71038ed54..0000000000 --- a/vendor/github.com/docker/libnetwork/portallocator/portallocator_freebsd.go +++ /dev/null @@ -1,42 +0,0 @@ -package portallocator - -import ( - "bytes" - "fmt" - "os/exec" -) - -func getDynamicPortRange() (start int, end int, err error) { - portRangeKernelSysctl := []string{"net.inet.ip.portrange.hifirst", "net.ip.portrange.hilast"} - portRangeFallback := fmt.Sprintf("using fallback port range %d-%d", defaultPortRangeStart, defaultPortRangeEnd) - portRangeLowCmd := exec.Command("/sbin/sysctl", portRangeKernelSysctl[0]) - var portRangeLowOut bytes.Buffer - portRangeLowCmd.Stdout = &portRangeLowOut - cmdErr := portRangeLowCmd.Run() - if cmdErr != nil { - return 0, 0, fmt.Errorf("port allocator - sysctl net.inet.ip.portrange.hifirst failed - %s: %v", portRangeFallback, err) - } - n, err := fmt.Sscanf(portRangeLowOut.String(), "%d", &start) - if n != 1 || err != nil { - if err == nil { - err = fmt.Errorf("unexpected count of parsed numbers (%d)", n) - } - return 0, 0, fmt.Errorf("port allocator - failed to parse system ephemeral port range start from %s - %s: %v", portRangeLowOut.String(), portRangeFallback, err) - } - - portRangeHighCmd := exec.Command("/sbin/sysctl", portRangeKernelSysctl[1]) - var portRangeHighOut bytes.Buffer - portRangeHighCmd.Stdout = &portRangeHighOut - cmdErr = portRangeHighCmd.Run() - if cmdErr != nil { - return 0, 0, fmt.Errorf("port allocator - sysctl net.inet.ip.portrange.hilast failed - %s: %v", portRangeFallback, err) - } - n, err = fmt.Sscanf(portRangeHighOut.String(), "%d", &end) - if n != 1 || err != nil { - if err == nil { - err = fmt.Errorf("unexpected count of parsed numbers (%d)", n) - } - return 0, 0, fmt.Errorf("port allocator - failed to parse system ephemeral port range end from %s - %s: %v", portRangeHighOut.String(), portRangeFallback, err) - } - return start, end, nil -} diff --git a/vendor/github.com/docker/libnetwork/portallocator/portallocator_linux.go b/vendor/github.com/docker/libnetwork/portallocator/portallocator_linux.go deleted file mode 100644 index 8ce696273e..0000000000 --- a/vendor/github.com/docker/libnetwork/portallocator/portallocator_linux.go +++ /dev/null @@ -1,27 +0,0 @@ -package portallocator - -import ( - "bufio" - "fmt" - "os" -) - -func getDynamicPortRange() (start int, end int, err error) { - const portRangeKernelParam = "/proc/sys/net/ipv4/ip_local_port_range" - portRangeFallback := fmt.Sprintf("using fallback port range %d-%d", defaultPortRangeStart, defaultPortRangeEnd) - file, err := os.Open(portRangeKernelParam) - if err != nil { - return 0, 0, fmt.Errorf("port allocator - %s due to error: %v", portRangeFallback, err) - } - - defer file.Close() - - n, err := fmt.Fscanf(bufio.NewReader(file), "%d\t%d", &start, &end) - if n != 2 || err != nil { - if err == nil { - err = fmt.Errorf("unexpected count of parsed numbers (%d)", n) - } - return 0, 0, fmt.Errorf("port allocator - failed to parse system ephemeral port range from %s - %s: %v", portRangeKernelParam, portRangeFallback, err) - } - return start, end, nil -} diff --git a/vendor/github.com/docker/libnetwork/portallocator/portallocator_windows.go b/vendor/github.com/docker/libnetwork/portallocator/portallocator_windows.go deleted file mode 100644 index 7d0d5c8037..0000000000 --- a/vendor/github.com/docker/libnetwork/portallocator/portallocator_windows.go +++ /dev/null @@ -1,10 +0,0 @@ -package portallocator - -func init() { - defaultPortRangeStart = 60000 - defaultPortRangeEnd = 65000 -} - -func getDynamicPortRange() (start int, end int, err error) { - return defaultPortRangeStart, defaultPortRangeEnd, nil -} diff --git a/vendor/github.com/docker/libnetwork/portmapper/mapper.go b/vendor/github.com/docker/libnetwork/portmapper/mapper.go deleted file mode 100644 index 33f4ec98cc..0000000000 --- a/vendor/github.com/docker/libnetwork/portmapper/mapper.go +++ /dev/null @@ -1,261 +0,0 @@ -package portmapper - -import ( - "errors" - "fmt" - "net" - - "github.com/docker/libnetwork/portallocator" - "github.com/ishidawataru/sctp" - "github.com/sirupsen/logrus" -) - -type mapping struct { - proto string - userlandProxy userlandProxy - host net.Addr - container net.Addr -} - -var newProxy = newProxyCommand - -var ( - // ErrUnknownBackendAddressType refers to an unknown container or unsupported address type - ErrUnknownBackendAddressType = errors.New("unknown container address type not supported") - // ErrPortMappedForIP refers to a port already mapped to an ip address - ErrPortMappedForIP = errors.New("port is already mapped to ip") - // ErrPortNotMapped refers to an unmapped port - ErrPortNotMapped = errors.New("port is not mapped") - // ErrSCTPAddrNoIP refers to a SCTP address without IP address. - ErrSCTPAddrNoIP = errors.New("sctp address does not contain any IP address") -) - -// New returns a new instance of PortMapper -func New(proxyPath string) *PortMapper { - return NewWithPortAllocator(portallocator.Get(), proxyPath) -} - -// NewWithPortAllocator returns a new instance of PortMapper which will use the specified PortAllocator -func NewWithPortAllocator(allocator *portallocator.PortAllocator, proxyPath string) *PortMapper { - return &PortMapper{ - currentMappings: make(map[string]*mapping), - Allocator: allocator, - proxyPath: proxyPath, - } -} - -// Map maps the specified container transport address to the host's network address and transport port -func (pm *PortMapper) Map(container net.Addr, hostIP net.IP, hostPort int, useProxy bool) (host net.Addr, err error) { - return pm.MapRange(container, hostIP, hostPort, hostPort, useProxy) -} - -// MapRange maps the specified container transport address to the host's network address and transport port range -func (pm *PortMapper) MapRange(container net.Addr, hostIP net.IP, hostPortStart, hostPortEnd int, useProxy bool) (host net.Addr, err error) { - pm.lock.Lock() - defer pm.lock.Unlock() - - var ( - m *mapping - proto string - allocatedHostPort int - ) - - switch container.(type) { - case *net.TCPAddr: - proto = "tcp" - if allocatedHostPort, err = pm.Allocator.RequestPortInRange(hostIP, proto, hostPortStart, hostPortEnd); err != nil { - return nil, err - } - - m = &mapping{ - proto: proto, - host: &net.TCPAddr{IP: hostIP, Port: allocatedHostPort}, - container: container, - } - - if useProxy { - m.userlandProxy, err = newProxy(proto, hostIP, allocatedHostPort, container.(*net.TCPAddr).IP, container.(*net.TCPAddr).Port, pm.proxyPath) - if err != nil { - return nil, err - } - } else { - m.userlandProxy, err = newDummyProxy(proto, hostIP, allocatedHostPort) - if err != nil { - return nil, err - } - } - case *net.UDPAddr: - proto = "udp" - if allocatedHostPort, err = pm.Allocator.RequestPortInRange(hostIP, proto, hostPortStart, hostPortEnd); err != nil { - return nil, err - } - - m = &mapping{ - proto: proto, - host: &net.UDPAddr{IP: hostIP, Port: allocatedHostPort}, - container: container, - } - - if useProxy { - m.userlandProxy, err = newProxy(proto, hostIP, allocatedHostPort, container.(*net.UDPAddr).IP, container.(*net.UDPAddr).Port, pm.proxyPath) - if err != nil { - return nil, err - } - } else { - m.userlandProxy, err = newDummyProxy(proto, hostIP, allocatedHostPort) - if err != nil { - return nil, err - } - } - case *sctp.SCTPAddr: - proto = "sctp" - if allocatedHostPort, err = pm.Allocator.RequestPortInRange(hostIP, proto, hostPortStart, hostPortEnd); err != nil { - return nil, err - } - - m = &mapping{ - proto: proto, - host: &sctp.SCTPAddr{IPAddrs: []net.IPAddr{{IP: hostIP}}, Port: allocatedHostPort}, - container: container, - } - - if useProxy { - sctpAddr := container.(*sctp.SCTPAddr) - if len(sctpAddr.IPAddrs) == 0 { - return nil, ErrSCTPAddrNoIP - } - m.userlandProxy, err = newProxy(proto, hostIP, allocatedHostPort, sctpAddr.IPAddrs[0].IP, sctpAddr.Port, pm.proxyPath) - if err != nil { - return nil, err - } - } else { - m.userlandProxy, err = newDummyProxy(proto, hostIP, allocatedHostPort) - if err != nil { - return nil, err - } - } - default: - return nil, ErrUnknownBackendAddressType - } - - // release the allocated port on any further error during return. - defer func() { - if err != nil { - pm.Allocator.ReleasePort(hostIP, proto, allocatedHostPort) - } - }() - - key := getKey(m.host) - if _, exists := pm.currentMappings[key]; exists { - return nil, ErrPortMappedForIP - } - - containerIP, containerPort := getIPAndPort(m.container) - if err := pm.AppendForwardingTableEntry(m.proto, hostIP, allocatedHostPort, containerIP.String(), containerPort); err != nil { - return nil, err - } - - cleanup := func() error { - // need to undo the iptables rules before we return - m.userlandProxy.Stop() - pm.DeleteForwardingTableEntry(m.proto, hostIP, allocatedHostPort, containerIP.String(), containerPort) - if err := pm.Allocator.ReleasePort(hostIP, m.proto, allocatedHostPort); err != nil { - return err - } - - return nil - } - - if err := m.userlandProxy.Start(); err != nil { - if err := cleanup(); err != nil { - return nil, fmt.Errorf("Error during port allocation cleanup: %v", err) - } - return nil, err - } - - pm.currentMappings[key] = m - return m.host, nil -} - -// Unmap removes stored mapping for the specified host transport address -func (pm *PortMapper) Unmap(host net.Addr) error { - pm.lock.Lock() - defer pm.lock.Unlock() - - key := getKey(host) - data, exists := pm.currentMappings[key] - if !exists { - return ErrPortNotMapped - } - - if data.userlandProxy != nil { - data.userlandProxy.Stop() - } - - delete(pm.currentMappings, key) - - containerIP, containerPort := getIPAndPort(data.container) - hostIP, hostPort := getIPAndPort(data.host) - if err := pm.DeleteForwardingTableEntry(data.proto, hostIP, hostPort, containerIP.String(), containerPort); err != nil { - logrus.Errorf("Error on iptables delete: %s", err) - } - - switch a := host.(type) { - case *net.TCPAddr: - return pm.Allocator.ReleasePort(a.IP, "tcp", a.Port) - case *net.UDPAddr: - return pm.Allocator.ReleasePort(a.IP, "udp", a.Port) - case *sctp.SCTPAddr: - if len(a.IPAddrs) == 0 { - return ErrSCTPAddrNoIP - } - return pm.Allocator.ReleasePort(a.IPAddrs[0].IP, "sctp", a.Port) - } - return ErrUnknownBackendAddressType -} - -//ReMapAll will re-apply all port mappings -func (pm *PortMapper) ReMapAll() { - pm.lock.Lock() - defer pm.lock.Unlock() - logrus.Debugln("Re-applying all port mappings.") - for _, data := range pm.currentMappings { - containerIP, containerPort := getIPAndPort(data.container) - hostIP, hostPort := getIPAndPort(data.host) - if err := pm.AppendForwardingTableEntry(data.proto, hostIP, hostPort, containerIP.String(), containerPort); err != nil { - logrus.Errorf("Error on iptables add: %s", err) - } - } -} - -func getKey(a net.Addr) string { - switch t := a.(type) { - case *net.TCPAddr: - return fmt.Sprintf("%s:%d/%s", t.IP.String(), t.Port, "tcp") - case *net.UDPAddr: - return fmt.Sprintf("%s:%d/%s", t.IP.String(), t.Port, "udp") - case *sctp.SCTPAddr: - if len(t.IPAddrs) == 0 { - logrus.Error(ErrSCTPAddrNoIP) - return "" - } - return fmt.Sprintf("%s:%d/%s", t.IPAddrs[0].IP.String(), t.Port, "sctp") - } - return "" -} - -func getIPAndPort(a net.Addr) (net.IP, int) { - switch t := a.(type) { - case *net.TCPAddr: - return t.IP, t.Port - case *net.UDPAddr: - return t.IP, t.Port - case *sctp.SCTPAddr: - if len(t.IPAddrs) == 0 { - logrus.Error(ErrSCTPAddrNoIP) - return nil, 0 - } - return t.IPAddrs[0].IP, t.Port - } - return nil, 0 -} diff --git a/vendor/github.com/docker/libnetwork/portmapper/mapper_linux.go b/vendor/github.com/docker/libnetwork/portmapper/mapper_linux.go deleted file mode 100644 index 0e76c546c5..0000000000 --- a/vendor/github.com/docker/libnetwork/portmapper/mapper_linux.go +++ /dev/null @@ -1,46 +0,0 @@ -package portmapper - -import ( - "net" - "sync" - - "github.com/docker/libnetwork/iptables" - "github.com/docker/libnetwork/portallocator" -) - -// PortMapper manages the network address translation -type PortMapper struct { - bridgeName string - - // udp:ip:port - currentMappings map[string]*mapping - lock sync.Mutex - - proxyPath string - - Allocator *portallocator.PortAllocator - chain *iptables.ChainInfo -} - -// SetIptablesChain sets the specified chain into portmapper -func (pm *PortMapper) SetIptablesChain(c *iptables.ChainInfo, bridgeName string) { - pm.chain = c - pm.bridgeName = bridgeName -} - -// AppendForwardingTableEntry adds a port mapping to the forwarding table -func (pm *PortMapper) AppendForwardingTableEntry(proto string, sourceIP net.IP, sourcePort int, containerIP string, containerPort int) error { - return pm.forward(iptables.Append, proto, sourceIP, sourcePort, containerIP, containerPort) -} - -// DeleteForwardingTableEntry removes a port mapping from the forwarding table -func (pm *PortMapper) DeleteForwardingTableEntry(proto string, sourceIP net.IP, sourcePort int, containerIP string, containerPort int) error { - return pm.forward(iptables.Delete, proto, sourceIP, sourcePort, containerIP, containerPort) -} - -func (pm *PortMapper) forward(action iptables.Action, proto string, sourceIP net.IP, sourcePort int, containerIP string, containerPort int) error { - if pm.chain == nil { - return nil - } - return pm.chain.Forward(action, sourceIP, sourcePort, proto, containerIP, containerPort, pm.bridgeName) -} diff --git a/vendor/github.com/docker/libnetwork/portmapper/mapper_windows.go b/vendor/github.com/docker/libnetwork/portmapper/mapper_windows.go deleted file mode 100644 index d1f703f3c9..0000000000 --- a/vendor/github.com/docker/libnetwork/portmapper/mapper_windows.go +++ /dev/null @@ -1,37 +0,0 @@ -package portmapper - -import ( - "net" - "sync" - - "github.com/docker/libnetwork/portallocator" -) - -// PortMapper manages the network address translation -type PortMapper struct { - bridgeName string - - // udp:ip:port - currentMappings map[string]*mapping - lock sync.Mutex - - proxyPath string - - Allocator *portallocator.PortAllocator -} - -// AppendForwardingTableEntry adds a port mapping to the forwarding table -func (pm *PortMapper) AppendForwardingTableEntry(proto string, sourceIP net.IP, sourcePort int, containerIP string, containerPort int) error { - return nil -} - -// DeleteForwardingTableEntry removes a port mapping from the forwarding table -func (pm *PortMapper) DeleteForwardingTableEntry(proto string, sourceIP net.IP, sourcePort int, containerIP string, containerPort int) error { - return nil -} - -// checkIP checks if IP is valid and matching to chain version -func (pm *PortMapper) checkIP(ip net.IP) bool { - // no IPv6 for port mapper on windows -> only IPv4 valid - return ip.To4() != nil -} diff --git a/vendor/github.com/docker/libnetwork/portmapper/mock_proxy.go b/vendor/github.com/docker/libnetwork/portmapper/mock_proxy.go deleted file mode 100644 index ceb7b02926..0000000000 --- a/vendor/github.com/docker/libnetwork/portmapper/mock_proxy.go +++ /dev/null @@ -1,18 +0,0 @@ -package portmapper - -import "net" - -func newMockProxyCommand(proto string, hostIP net.IP, hostPort int, containerIP net.IP, containerPort int, userlandProxyPath string) (userlandProxy, error) { - return &mockProxyCommand{}, nil -} - -type mockProxyCommand struct { -} - -func (p *mockProxyCommand) Start() error { - return nil -} - -func (p *mockProxyCommand) Stop() error { - return nil -} diff --git a/vendor/github.com/docker/libnetwork/portmapper/proxy.go b/vendor/github.com/docker/libnetwork/portmapper/proxy.go deleted file mode 100644 index f945851d54..0000000000 --- a/vendor/github.com/docker/libnetwork/portmapper/proxy.go +++ /dev/null @@ -1,147 +0,0 @@ -package portmapper - -import ( - "fmt" - "io" - "io/ioutil" - "net" - "os" - "os/exec" - "time" - - "github.com/ishidawataru/sctp" -) - -var userlandProxyCommandName = "docker-proxy" - -type userlandProxy interface { - Start() error - Stop() error -} - -// ipVersion refers to IP version - v4 or v6 -type ipVersion string - -const ( - // IPv4 is version 4 - ipv4 ipVersion = "4" - // IPv4 is version 6 - ipv6 ipVersion = "6" -) - -// proxyCommand wraps an exec.Cmd to run the userland TCP and UDP -// proxies as separate processes. -type proxyCommand struct { - cmd *exec.Cmd -} - -func (p *proxyCommand) Start() error { - r, w, err := os.Pipe() - if err != nil { - return fmt.Errorf("proxy unable to open os.Pipe %s", err) - } - defer r.Close() - p.cmd.ExtraFiles = []*os.File{w} - if err := p.cmd.Start(); err != nil { - return err - } - w.Close() - - errchan := make(chan error, 1) - go func() { - buf := make([]byte, 2) - r.Read(buf) - - if string(buf) != "0\n" { - errStr, err := ioutil.ReadAll(r) - if err != nil { - errchan <- fmt.Errorf("Error reading exit status from userland proxy: %v", err) - return - } - - errchan <- fmt.Errorf("Error starting userland proxy: %s", errStr) - return - } - errchan <- nil - }() - - select { - case err := <-errchan: - return err - case <-time.After(16 * time.Second): - return fmt.Errorf("Timed out proxy starting the userland proxy") - } -} - -func (p *proxyCommand) Stop() error { - if p.cmd.Process != nil { - if err := p.cmd.Process.Signal(os.Interrupt); err != nil { - return err - } - return p.cmd.Wait() - } - return nil -} - -// dummyProxy just listen on some port, it is needed to prevent accidental -// port allocations on bound port, because without userland proxy we using -// iptables rules and not net.Listen -type dummyProxy struct { - listener io.Closer - addr net.Addr - ipVersion ipVersion -} - -func newDummyProxy(proto string, hostIP net.IP, hostPort int) (userlandProxy, error) { - // detect version of hostIP to bind only to correct version - version := ipv4 - if hostIP.To4() == nil { - version = ipv6 - } - switch proto { - case "tcp": - addr := &net.TCPAddr{IP: hostIP, Port: hostPort} - return &dummyProxy{addr: addr, ipVersion: version}, nil - case "udp": - addr := &net.UDPAddr{IP: hostIP, Port: hostPort} - return &dummyProxy{addr: addr, ipVersion: version}, nil - case "sctp": - addr := &sctp.SCTPAddr{IPAddrs: []net.IPAddr{{IP: hostIP}}, Port: hostPort} - return &dummyProxy{addr: addr, ipVersion: version}, nil - default: - return nil, fmt.Errorf("Unknown addr type: %s", proto) - } -} - -func (p *dummyProxy) Start() error { - switch addr := p.addr.(type) { - case *net.TCPAddr: - l, err := net.ListenTCP("tcp"+string(p.ipVersion), addr) - if err != nil { - return err - } - p.listener = l - case *net.UDPAddr: - l, err := net.ListenUDP("udp"+string(p.ipVersion), addr) - if err != nil { - return err - } - p.listener = l - case *sctp.SCTPAddr: - l, err := sctp.ListenSCTP("sctp"+string(p.ipVersion), addr) - if err != nil { - return err - } - p.listener = l - default: - return fmt.Errorf("Unknown addr type: %T", p.addr) - } - return nil -} - -func (p *dummyProxy) Stop() error { - if p.listener != nil { - return p.listener.Close() - } - return nil -} diff --git a/vendor/github.com/docker/libnetwork/portmapper/proxy_linux.go b/vendor/github.com/docker/libnetwork/portmapper/proxy_linux.go deleted file mode 100644 index 947cd0ba4b..0000000000 --- a/vendor/github.com/docker/libnetwork/portmapper/proxy_linux.go +++ /dev/null @@ -1,38 +0,0 @@ -package portmapper - -import ( - "net" - "os/exec" - "strconv" - "syscall" -) - -func newProxyCommand(proto string, hostIP net.IP, hostPort int, containerIP net.IP, containerPort int, proxyPath string) (userlandProxy, error) { - path := proxyPath - if proxyPath == "" { - cmd, err := exec.LookPath(userlandProxyCommandName) - if err != nil { - return nil, err - } - path = cmd - } - - args := []string{ - path, - "-proto", proto, - "-host-ip", hostIP.String(), - "-host-port", strconv.Itoa(hostPort), - "-container-ip", containerIP.String(), - "-container-port", strconv.Itoa(containerPort), - } - - return &proxyCommand{ - cmd: &exec.Cmd{ - Path: path, - Args: args, - SysProcAttr: &syscall.SysProcAttr{ - Pdeathsig: syscall.SIGTERM, // send a sigterm to the proxy if the daemon process dies - }, - }, - }, nil -} diff --git a/vendor/github.com/docker/libnetwork/portmapper/proxy_windows.go b/vendor/github.com/docker/libnetwork/portmapper/proxy_windows.go deleted file mode 100644 index 06a9e2462c..0000000000 --- a/vendor/github.com/docker/libnetwork/portmapper/proxy_windows.go +++ /dev/null @@ -1,10 +0,0 @@ -package portmapper - -import ( - "errors" - "net" -) - -func newProxyCommand(proto string, hostIP net.IP, hostPort int, containerIP net.IP, containerPort int, proxyPath string) (userlandProxy, error) { - return nil, errors.New("proxy is unsupported on windows") -} diff --git a/vendor/github.com/docker/libnetwork/resolver.go b/vendor/github.com/docker/libnetwork/resolver.go deleted file mode 100644 index bc8b964cdf..0000000000 --- a/vendor/github.com/docker/libnetwork/resolver.go +++ /dev/null @@ -1,578 +0,0 @@ -package libnetwork - -import ( - "fmt" - "math/rand" - "net" - "strings" - "sync" - "time" - - "github.com/docker/libnetwork/types" - "github.com/miekg/dns" - "github.com/sirupsen/logrus" -) - -// Resolver represents the embedded DNS server in Docker. It operates -// by listening on container's loopback interface for DNS queries. -type Resolver interface { - // Start starts the name server for the container - Start() error - // Stop stops the name server for the container. Stopped resolver - // can be reused after running the SetupFunc again. - Stop() - // SetupFunc() provides the setup function that should be run - // in the container's network namespace. - SetupFunc(int) func() - // NameServer() returns the IP of the DNS resolver for the - // containers. - NameServer() string - // SetExtServers configures the external nameservers the resolver - // should use to forward queries - SetExtServers([]extDNSEntry) - // ResolverOptions returns resolv.conf options that should be set - ResolverOptions() []string -} - -// DNSBackend represents a backend DNS resolver used for DNS name -// resolution. All the queries to the resolver are forwarded to the -// backend resolver. -type DNSBackend interface { - // ResolveName resolves a service name to an IPv4 or IPv6 address by searching - // the networks the sandbox is connected to. For IPv6 queries, second return - // value will be true if the name exists in docker domain but doesn't have an - // IPv6 address. Such queries shouldn't be forwarded to external nameservers. - ResolveName(name string, iplen int) ([]net.IP, bool) - // ResolveIP returns the service name for the passed in IP. IP is in reverse dotted - // notation; the format used for DNS PTR records - ResolveIP(name string) string - // ResolveService returns all the backend details about the containers or hosts - // backing a service. Its purpose is to satisfy an SRV query - ResolveService(name string) ([]*net.SRV, []net.IP) - // ExecFunc allows a function to be executed in the context of the backend - // on behalf of the resolver. - ExecFunc(f func()) error - //NdotsSet queries the backends ndots dns option settings - NdotsSet() bool - // HandleQueryResp passes the name & IP from a response to the backend. backend - // can use it to maintain any required state about the resolution - HandleQueryResp(name string, ip net.IP) -} - -const ( - dnsPort = "53" - ptrIPv4domain = ".in-addr.arpa." - ptrIPv6domain = ".ip6.arpa." - respTTL = 600 - maxExtDNS = 3 //max number of external servers to try - extIOTimeout = 4 * time.Second - defaultRespSize = 512 - maxConcurrent = 1024 - logInterval = 2 * time.Second -) - -type extDNSEntry struct { - IPStr string - HostLoopback bool -} - -// resolver implements the Resolver interface -type resolver struct { - backend DNSBackend - extDNSList [maxExtDNS]extDNSEntry - server *dns.Server - conn *net.UDPConn - tcpServer *dns.Server - tcpListen *net.TCPListener - err error - count int32 - tStamp time.Time - queryLock sync.Mutex - listenAddress string - proxyDNS bool - resolverKey string - startCh chan struct{} -} - -func init() { - rand.Seed(time.Now().Unix()) -} - -// NewResolver creates a new instance of the Resolver -func NewResolver(address string, proxyDNS bool, resolverKey string, backend DNSBackend) Resolver { - return &resolver{ - backend: backend, - proxyDNS: proxyDNS, - listenAddress: address, - resolverKey: resolverKey, - err: fmt.Errorf("setup not done yet"), - startCh: make(chan struct{}, 1), - } -} - -func (r *resolver) SetupFunc(port int) func() { - return func() { - var err error - - // DNS operates primarily on UDP - addr := &net.UDPAddr{ - IP: net.ParseIP(r.listenAddress), - Port: port, - } - - r.conn, err = net.ListenUDP("udp", addr) - if err != nil { - r.err = fmt.Errorf("error in opening name server socket %v", err) - return - } - - // Listen on a TCP as well - tcpaddr := &net.TCPAddr{ - IP: net.ParseIP(r.listenAddress), - Port: port, - } - - r.tcpListen, err = net.ListenTCP("tcp", tcpaddr) - if err != nil { - r.err = fmt.Errorf("error in opening name TCP server socket %v", err) - return - } - r.err = nil - } -} - -func (r *resolver) Start() error { - r.startCh <- struct{}{} - defer func() { <-r.startCh }() - - // make sure the resolver has been setup before starting - if r.err != nil { - return r.err - } - - if err := r.setupIPTable(); err != nil { - return fmt.Errorf("setting up IP table rules failed: %v", err) - } - - s := &dns.Server{Handler: r, PacketConn: r.conn} - r.server = s - go func() { - s.ActivateAndServe() - }() - - tcpServer := &dns.Server{Handler: r, Listener: r.tcpListen} - r.tcpServer = tcpServer - go func() { - tcpServer.ActivateAndServe() - }() - return nil -} - -func (r *resolver) Stop() { - r.startCh <- struct{}{} - defer func() { <-r.startCh }() - - if r.server != nil { - r.server.Shutdown() - } - if r.tcpServer != nil { - r.tcpServer.Shutdown() - } - r.conn = nil - r.tcpServer = nil - r.err = fmt.Errorf("setup not done yet") - r.tStamp = time.Time{} - r.count = 0 - r.queryLock = sync.Mutex{} -} - -func (r *resolver) SetExtServers(extDNS []extDNSEntry) { - l := len(extDNS) - if l > maxExtDNS { - l = maxExtDNS - } - for i := 0; i < l; i++ { - r.extDNSList[i] = extDNS[i] - } -} - -func (r *resolver) NameServer() string { - return r.listenAddress -} - -func (r *resolver) ResolverOptions() []string { - return []string{"ndots:0"} -} - -func setCommonFlags(msg *dns.Msg) { - msg.RecursionAvailable = true -} - -func shuffleAddr(addr []net.IP) []net.IP { - for i := len(addr) - 1; i > 0; i-- { - r := rand.Intn(i + 1) - addr[i], addr[r] = addr[r], addr[i] - } - return addr -} - -func createRespMsg(query *dns.Msg) *dns.Msg { - resp := new(dns.Msg) - resp.SetReply(query) - setCommonFlags(resp) - - return resp -} - -func (r *resolver) handleMXQuery(name string, query *dns.Msg) (*dns.Msg, error) { - addrv4, _ := r.backend.ResolveName(name, types.IPv4) - addrv6, _ := r.backend.ResolveName(name, types.IPv6) - - if addrv4 == nil && addrv6 == nil { - return nil, nil - } - - // We were able to resolve the name. Respond with an empty list with - // RcodeSuccess/NOERROR so that email clients can treat it as "implicit MX" - // [RFC 5321 Section-5.1] and issue a Type A/AAAA query for the name. - - resp := createRespMsg(query) - return resp, nil -} - -func (r *resolver) handleIPQuery(name string, query *dns.Msg, ipType int) (*dns.Msg, error) { - var addr []net.IP - var ipv6Miss bool - addr, ipv6Miss = r.backend.ResolveName(name, ipType) - - if addr == nil && ipv6Miss { - // Send a reply without any Answer sections - logrus.Debugf("[resolver] lookup name %s present without IPv6 address", name) - resp := createRespMsg(query) - return resp, nil - } - if addr == nil { - return nil, nil - } - - logrus.Debugf("[resolver] lookup for %s: IP %v", name, addr) - - resp := createRespMsg(query) - if len(addr) > 1 { - addr = shuffleAddr(addr) - } - if ipType == types.IPv4 { - for _, ip := range addr { - rr := new(dns.A) - rr.Hdr = dns.RR_Header{Name: name, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: respTTL} - rr.A = ip - resp.Answer = append(resp.Answer, rr) - } - } else { - for _, ip := range addr { - rr := new(dns.AAAA) - rr.Hdr = dns.RR_Header{Name: name, Rrtype: dns.TypeAAAA, Class: dns.ClassINET, Ttl: respTTL} - rr.AAAA = ip - resp.Answer = append(resp.Answer, rr) - } - } - return resp, nil -} - -func (r *resolver) handlePTRQuery(ptr string, query *dns.Msg) (*dns.Msg, error) { - var parts []string - - if strings.HasSuffix(ptr, ptrIPv4domain) { - parts = strings.Split(ptr, ptrIPv4domain) - } else if strings.HasSuffix(ptr, ptrIPv6domain) { - parts = strings.Split(ptr, ptrIPv6domain) - } else { - return nil, fmt.Errorf("invalid PTR query, %v", ptr) - } - - host := r.backend.ResolveIP(parts[0]) - - if len(host) == 0 { - return nil, nil - } - - logrus.Debugf("[resolver] lookup for IP %s: name %s", parts[0], host) - fqdn := dns.Fqdn(host) - - resp := new(dns.Msg) - resp.SetReply(query) - setCommonFlags(resp) - - rr := new(dns.PTR) - rr.Hdr = dns.RR_Header{Name: ptr, Rrtype: dns.TypePTR, Class: dns.ClassINET, Ttl: respTTL} - rr.Ptr = fqdn - resp.Answer = append(resp.Answer, rr) - return resp, nil -} - -func (r *resolver) handleSRVQuery(svc string, query *dns.Msg) (*dns.Msg, error) { - - srv, ip := r.backend.ResolveService(svc) - - if len(srv) == 0 { - return nil, nil - } - if len(srv) != len(ip) { - return nil, fmt.Errorf("invalid reply for SRV query %s", svc) - } - - resp := createRespMsg(query) - - for i, r := range srv { - rr := new(dns.SRV) - rr.Hdr = dns.RR_Header{Name: svc, Rrtype: dns.TypePTR, Class: dns.ClassINET, Ttl: respTTL} - rr.Port = r.Port - rr.Target = r.Target - resp.Answer = append(resp.Answer, rr) - - rr1 := new(dns.A) - rr1.Hdr = dns.RR_Header{Name: r.Target, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: respTTL} - rr1.A = ip[i] - resp.Extra = append(resp.Extra, rr1) - } - return resp, nil - -} - -func truncateResp(resp *dns.Msg, maxSize int, isTCP bool) { - if !isTCP { - resp.Truncated = true - } - - srv := resp.Question[0].Qtype == dns.TypeSRV - // trim the Answer RRs one by one till the whole message fits - // within the reply size - for resp.Len() > maxSize { - resp.Answer = resp.Answer[:len(resp.Answer)-1] - - if srv && len(resp.Extra) > 0 { - resp.Extra = resp.Extra[:len(resp.Extra)-1] - } - } -} - -func (r *resolver) ServeDNS(w dns.ResponseWriter, query *dns.Msg) { - var ( - extConn net.Conn - resp *dns.Msg - err error - ) - - if query == nil || len(query.Question) == 0 { - return - } - - name := query.Question[0].Name - switch query.Question[0].Qtype { - case dns.TypeA: - resp, err = r.handleIPQuery(name, query, types.IPv4) - case dns.TypeAAAA: - resp, err = r.handleIPQuery(name, query, types.IPv6) - case dns.TypeMX: - resp, err = r.handleMXQuery(name, query) - case dns.TypePTR: - resp, err = r.handlePTRQuery(name, query) - case dns.TypeSRV: - resp, err = r.handleSRVQuery(name, query) - } - - if err != nil { - logrus.Error(err) - return - } - - if resp == nil { - // If the backend doesn't support proxying dns request - // fail the response - if !r.proxyDNS { - resp = new(dns.Msg) - resp.SetRcode(query, dns.RcodeServerFailure) - w.WriteMsg(resp) - return - } - - // If the user sets ndots > 0 explicitly and the query is - // in the root domain don't forward it out. We will return - // failure and let the client retry with the search domain - // attached - switch query.Question[0].Qtype { - case dns.TypeA: - fallthrough - case dns.TypeAAAA: - if r.backend.NdotsSet() && !strings.Contains(strings.TrimSuffix(name, "."), ".") { - resp = createRespMsg(query) - } - } - } - - proto := w.LocalAddr().Network() - maxSize := 0 - if proto == "tcp" { - maxSize = dns.MaxMsgSize - 1 - } else if proto == "udp" { - optRR := query.IsEdns0() - if optRR != nil { - maxSize = int(optRR.UDPSize()) - } - if maxSize < defaultRespSize { - maxSize = defaultRespSize - } - } - - if resp != nil { - if resp.Len() > maxSize { - truncateResp(resp, maxSize, proto == "tcp") - } - } else { - for i := 0; i < maxExtDNS; i++ { - extDNS := &r.extDNSList[i] - if extDNS.IPStr == "" { - break - } - extConnect := func() { - addr := fmt.Sprintf("%s:%d", extDNS.IPStr, 53) - extConn, err = net.DialTimeout(proto, addr, extIOTimeout) - } - - if extDNS.HostLoopback { - extConnect() - } else { - execErr := r.backend.ExecFunc(extConnect) - if execErr != nil { - logrus.Warn(execErr) - continue - } - } - if err != nil { - logrus.Warnf("[resolver] connect failed: %s", err) - continue - } - queryType := dns.TypeToString[query.Question[0].Qtype] - logrus.Debugf("[resolver] query %s (%s) from %s, forwarding to %s:%s", name, queryType, - extConn.LocalAddr().String(), proto, extDNS.IPStr) - - // Timeout has to be set for every IO operation. - extConn.SetDeadline(time.Now().Add(extIOTimeout)) - co := &dns.Conn{ - Conn: extConn, - UDPSize: uint16(maxSize), - } - defer co.Close() - - // limits the number of outstanding concurrent queries. - if !r.forwardQueryStart() { - old := r.tStamp - r.tStamp = time.Now() - if r.tStamp.Sub(old) > logInterval { - logrus.Errorf("[resolver] more than %v concurrent queries from %s", maxConcurrent, extConn.LocalAddr().String()) - } - continue - } - - err = co.WriteMsg(query) - if err != nil { - r.forwardQueryEnd() - logrus.Debugf("[resolver] send to DNS server failed, %s", err) - continue - } - - resp, err = co.ReadMsg() - // Truncated DNS replies should be sent to the client so that the - // client can retry over TCP - if err != nil && (resp == nil || !resp.Truncated) { - r.forwardQueryEnd() - logrus.Debugf("[resolver] read from DNS server failed, %s", err) - continue - } - r.forwardQueryEnd() - - if resp == nil { - logrus.Debugf("[resolver] external DNS %s:%s returned empty response for %q", proto, extDNS.IPStr, name) - break - } - switch resp.Rcode { - case dns.RcodeServerFailure, dns.RcodeRefused: - // Server returned FAILURE: continue with the next external DNS server - // Server returned REFUSED: this can be a transitional status, so continue with the next external DNS server - logrus.Debugf("[resolver] external DNS %s:%s responded with %s for %q", proto, extDNS.IPStr, statusString(resp.Rcode), name) - continue - case dns.RcodeNameError: - // Server returned NXDOMAIN. Stop resolution if it's an authoritative answer (see RFC 8020: https://tools.ietf.org/html/rfc8020#section-2) - logrus.Debugf("[resolver] external DNS %s:%s responded with %s for %q", proto, extDNS.IPStr, statusString(resp.Rcode), name) - if resp.Authoritative { - break - } - continue - case dns.RcodeSuccess: - // All is well - default: - // Server gave some error. Log the error, and continue with the next external DNS server - logrus.Debugf("[resolver] external DNS %s:%s responded with %s (code %d) for %q", proto, extDNS.IPStr, statusString(resp.Rcode), resp.Rcode, name) - continue - } - answers := 0 - for _, rr := range resp.Answer { - h := rr.Header() - switch h.Rrtype { - case dns.TypeA: - answers++ - ip := rr.(*dns.A).A - logrus.Debugf("[resolver] received A record %q for %q from %s:%s", ip, h.Name, proto, extDNS.IPStr) - r.backend.HandleQueryResp(h.Name, ip) - case dns.TypeAAAA: - answers++ - ip := rr.(*dns.AAAA).AAAA - logrus.Debugf("[resolver] received AAAA record %q for %q from %s:%s", ip, h.Name, proto, extDNS.IPStr) - r.backend.HandleQueryResp(h.Name, ip) - } - } - if resp.Answer == nil || answers == 0 { - logrus.Debugf("[resolver] external DNS %s:%s did not return any %s records for %q", proto, extDNS.IPStr, queryType, name) - } - resp.Compress = true - break - } - if resp == nil { - return - } - } - - if err = w.WriteMsg(resp); err != nil { - logrus.Errorf("[resolver] error writing resolver resp, %s", err) - } -} - -func statusString(responseCode int) string { - if s, ok := dns.RcodeToString[responseCode]; ok { - return s - } - return "UNKNOWN" -} - -func (r *resolver) forwardQueryStart() bool { - r.queryLock.Lock() - defer r.queryLock.Unlock() - - if r.count == maxConcurrent { - return false - } - r.count++ - - return true -} - -func (r *resolver) forwardQueryEnd() { - r.queryLock.Lock() - defer r.queryLock.Unlock() - - if r.count == 0 { - logrus.Error("[resolver] invalid concurrent query count") - } else { - r.count-- - } -} diff --git a/vendor/github.com/docker/libnetwork/resolver_unix.go b/vendor/github.com/docker/libnetwork/resolver_unix.go deleted file mode 100644 index 28b8c4277c..0000000000 --- a/vendor/github.com/docker/libnetwork/resolver_unix.go +++ /dev/null @@ -1,104 +0,0 @@ -// +build !windows - -package libnetwork - -import ( - "fmt" - "net" - "os" - "os/exec" - "runtime" - - "github.com/docker/docker/pkg/reexec" - "github.com/docker/libnetwork/iptables" - "github.com/sirupsen/logrus" - "github.com/vishvananda/netns" -) - -func init() { - reexec.Register("setup-resolver", reexecSetupResolver) -} - -const ( - // outputChain used for docker embed dns - outputChain = "DOCKER_OUTPUT" - //postroutingchain used for docker embed dns - postroutingchain = "DOCKER_POSTROUTING" -) - -func reexecSetupResolver() { - runtime.LockOSThread() - defer runtime.UnlockOSThread() - - if len(os.Args) < 4 { - logrus.Error("invalid number of arguments..") - os.Exit(1) - } - - resolverIP, ipPort, _ := net.SplitHostPort(os.Args[2]) - _, tcpPort, _ := net.SplitHostPort(os.Args[3]) - rules := [][]string{ - {"-t", "nat", "-I", outputChain, "-d", resolverIP, "-p", "udp", "--dport", dnsPort, "-j", "DNAT", "--to-destination", os.Args[2]}, - {"-t", "nat", "-I", postroutingchain, "-s", resolverIP, "-p", "udp", "--sport", ipPort, "-j", "SNAT", "--to-source", ":" + dnsPort}, - {"-t", "nat", "-I", outputChain, "-d", resolverIP, "-p", "tcp", "--dport", dnsPort, "-j", "DNAT", "--to-destination", os.Args[3]}, - {"-t", "nat", "-I", postroutingchain, "-s", resolverIP, "-p", "tcp", "--sport", tcpPort, "-j", "SNAT", "--to-source", ":" + dnsPort}, - } - - f, err := os.OpenFile(os.Args[1], os.O_RDONLY, 0) - if err != nil { - logrus.Errorf("failed get network namespace %q: %v", os.Args[1], err) - os.Exit(2) - } - defer f.Close() - - nsFD := f.Fd() - if err = netns.Set(netns.NsHandle(nsFD)); err != nil { - logrus.Errorf("setting into container net ns %v failed, %v", os.Args[1], err) - os.Exit(3) - } - - // TODO IPv6 support - iptable := iptables.GetIptable(iptables.IPv4) - - // insert outputChain and postroutingchain - err = iptable.RawCombinedOutputNative("-t", "nat", "-C", "OUTPUT", "-d", resolverIP, "-j", outputChain) - if err == nil { - iptable.RawCombinedOutputNative("-t", "nat", "-F", outputChain) - } else { - iptable.RawCombinedOutputNative("-t", "nat", "-N", outputChain) - iptable.RawCombinedOutputNative("-t", "nat", "-I", "OUTPUT", "-d", resolverIP, "-j", outputChain) - } - - err = iptable.RawCombinedOutputNative("-t", "nat", "-C", "POSTROUTING", "-d", resolverIP, "-j", postroutingchain) - if err == nil { - iptable.RawCombinedOutputNative("-t", "nat", "-F", postroutingchain) - } else { - iptable.RawCombinedOutputNative("-t", "nat", "-N", postroutingchain) - iptable.RawCombinedOutputNative("-t", "nat", "-I", "POSTROUTING", "-d", resolverIP, "-j", postroutingchain) - } - - for _, rule := range rules { - if iptable.RawCombinedOutputNative(rule...) != nil { - logrus.Errorf("set up rule failed, %v", rule) - } - } -} - -func (r *resolver) setupIPTable() error { - if r.err != nil { - return r.err - } - laddr := r.conn.LocalAddr().String() - ltcpaddr := r.tcpListen.Addr().String() - - cmd := &exec.Cmd{ - Path: reexec.Self(), - Args: append([]string{"setup-resolver"}, r.resolverKey, laddr, ltcpaddr), - Stdout: os.Stdout, - Stderr: os.Stderr, - } - if err := cmd.Run(); err != nil { - return fmt.Errorf("reexec failed: %v", err) - } - return nil -} diff --git a/vendor/github.com/docker/libnetwork/resolver_windows.go b/vendor/github.com/docker/libnetwork/resolver_windows.go deleted file mode 100644 index aa33b1a2ec..0000000000 --- a/vendor/github.com/docker/libnetwork/resolver_windows.go +++ /dev/null @@ -1,7 +0,0 @@ -// +build windows - -package libnetwork - -func (r *resolver) setupIPTable() error { - return nil -} diff --git a/vendor/github.com/docker/libnetwork/sandbox.go b/vendor/github.com/docker/libnetwork/sandbox.go deleted file mode 100644 index 03c9215786..0000000000 --- a/vendor/github.com/docker/libnetwork/sandbox.go +++ /dev/null @@ -1,1269 +0,0 @@ -package libnetwork - -import ( - "encoding/json" - "fmt" - "net" - "sort" - "strings" - "sync" - "time" - - "github.com/docker/libnetwork/etchosts" - "github.com/docker/libnetwork/netlabel" - "github.com/docker/libnetwork/osl" - "github.com/docker/libnetwork/types" - "github.com/sirupsen/logrus" -) - -// Sandbox provides the control over the network container entity. It is a one to one mapping with the container. -type Sandbox interface { - // ID returns the ID of the sandbox - ID() string - // Key returns the sandbox's key - Key() string - // ContainerID returns the container id associated to this sandbox - ContainerID() string - // Labels returns the sandbox's labels - Labels() map[string]interface{} - // Statistics retrieves the interfaces' statistics for the sandbox - Statistics() (map[string]*types.InterfaceStatistics, error) - // Refresh leaves all the endpoints, resets and re-applies the options, - // re-joins all the endpoints without destroying the osl sandbox - Refresh(options ...SandboxOption) error - // SetKey updates the Sandbox Key - SetKey(key string) error - // Rename changes the name of all attached Endpoints - Rename(name string) error - // Delete destroys this container after detaching it from all connected endpoints. - Delete() error - // Endpoints returns all the endpoints connected to the sandbox - Endpoints() []Endpoint - // ResolveService returns all the backend details about the containers or hosts - // backing a service. Its purpose is to satisfy an SRV query - ResolveService(name string) ([]*net.SRV, []net.IP) - // EnableService makes a managed container's service available by adding the - // endpoint to the service load balancer and service discovery - EnableService() error - // DisableService removes a managed container's endpoints from the load balancer - // and service discovery - DisableService() error -} - -// SandboxOption is an option setter function type used to pass various options to -// NewNetContainer method. The various setter functions of type SandboxOption are -// provided by libnetwork, they look like ContainerOptionXXXX(...) -type SandboxOption func(sb *sandbox) - -func (sb *sandbox) processOptions(options ...SandboxOption) { - for _, opt := range options { - if opt != nil { - opt(sb) - } - } -} - -type sandbox struct { - id string - containerID string - config containerConfig - extDNS []extDNSEntry - osSbox osl.Sandbox - controller *controller - resolver Resolver - resolverOnce sync.Once - refCnt int - endpoints []*endpoint - epPriority map[string]int - populatedEndpoints map[string]struct{} - joinLeaveDone chan struct{} - dbIndex uint64 - dbExists bool - isStub bool - inDelete bool - ingress bool - ndotsSet bool - oslTypes []osl.SandboxType // slice of properties of this sandbox - loadBalancerNID string // NID that this SB is a load balancer for - sync.Mutex - // This mutex is used to serialize service related operation for an endpoint - // The lock is here because the endpoint is saved into the store so is not unique - Service sync.Mutex -} - -// These are the container configs used to customize container /etc/hosts file. -type hostsPathConfig struct { - hostName string - domainName string - hostsPath string - originHostsPath string - extraHosts []extraHost - parentUpdates []parentUpdate -} - -type parentUpdate struct { - cid string - name string - ip string -} - -type extraHost struct { - name string - IP string -} - -// These are the container configs used to customize container /etc/resolv.conf file. -type resolvConfPathConfig struct { - resolvConfPath string - originResolvConfPath string - resolvConfHashFile string - dnsList []string - dnsSearchList []string - dnsOptionsList []string -} - -type containerConfig struct { - hostsPathConfig - resolvConfPathConfig - generic map[string]interface{} - useDefaultSandBox bool - useExternalKey bool - prio int // higher the value, more the priority - exposedPorts []types.TransportPort -} - -const ( - resolverIPSandbox = "127.0.0.11" -) - -func (sb *sandbox) ID() string { - return sb.id -} - -func (sb *sandbox) ContainerID() string { - return sb.containerID -} - -func (sb *sandbox) Key() string { - if sb.config.useDefaultSandBox { - return osl.GenerateKey("default") - } - return osl.GenerateKey(sb.id) -} - -func (sb *sandbox) Labels() map[string]interface{} { - sb.Lock() - defer sb.Unlock() - opts := make(map[string]interface{}, len(sb.config.generic)) - for k, v := range sb.config.generic { - opts[k] = v - } - return opts -} - -func (sb *sandbox) Statistics() (map[string]*types.InterfaceStatistics, error) { - m := make(map[string]*types.InterfaceStatistics) - - sb.Lock() - osb := sb.osSbox - sb.Unlock() - if osb == nil { - return m, nil - } - - var err error - for _, i := range osb.Info().Interfaces() { - if m[i.DstName()], err = i.Statistics(); err != nil { - return m, err - } - } - - return m, nil -} - -func (sb *sandbox) Delete() error { - return sb.delete(false) -} - -func (sb *sandbox) delete(force bool) error { - sb.Lock() - if sb.inDelete { - sb.Unlock() - return types.ForbiddenErrorf("another sandbox delete in progress") - } - // Set the inDelete flag. This will ensure that we don't - // update the store until we have completed all the endpoint - // leaves and deletes. And when endpoint leaves and deletes - // are completed then we can finally delete the sandbox object - // altogether from the data store. If the daemon exits - // ungracefully in the middle of a sandbox delete this way we - // will have all the references to the endpoints in the - // sandbox so that we can clean them up when we restart - sb.inDelete = true - sb.Unlock() - - c := sb.controller - - // Detach from all endpoints - retain := false - for _, ep := range sb.getConnectedEndpoints() { - // gw network endpoint detach and removal are automatic - if ep.endpointInGWNetwork() && !force { - continue - } - // Retain the sanbdox if we can't obtain the network from store. - if _, err := c.getNetworkFromStore(ep.getNetwork().ID()); err != nil { - if c.isDistributedControl() { - retain = true - } - logrus.Warnf("Failed getting network for ep %s during sandbox %s delete: %v", ep.ID(), sb.ID(), err) - continue - } - - if !force { - if err := ep.Leave(sb); err != nil { - logrus.Warnf("Failed detaching sandbox %s from endpoint %s: %v\n", sb.ID(), ep.ID(), err) - } - } - - if err := ep.Delete(force); err != nil { - logrus.Warnf("Failed deleting endpoint %s: %v\n", ep.ID(), err) - } - } - - if retain { - sb.Lock() - sb.inDelete = false - sb.Unlock() - return fmt.Errorf("could not cleanup all the endpoints in container %s / sandbox %s", sb.containerID, sb.id) - } - // Container is going away. Path cache in etchosts is most - // likely not required any more. Drop it. - etchosts.Drop(sb.config.hostsPath) - - if sb.resolver != nil { - sb.resolver.Stop() - } - - if sb.osSbox != nil && !sb.config.useDefaultSandBox { - sb.osSbox.Destroy() - } - - if err := sb.storeDelete(); err != nil { - logrus.Warnf("Failed to delete sandbox %s from store: %v", sb.ID(), err) - } - - c.Lock() - if sb.ingress { - c.ingressSandbox = nil - } - delete(c.sandboxes, sb.ID()) - c.Unlock() - - return nil -} - -func (sb *sandbox) Rename(name string) error { - var err error - - for _, ep := range sb.getConnectedEndpoints() { - if ep.endpointInGWNetwork() { - continue - } - - oldName := ep.Name() - lEp := ep - if err = ep.rename(name); err != nil { - break - } - - defer func() { - if err != nil { - lEp.rename(oldName) - } - }() - } - - return err -} - -func (sb *sandbox) Refresh(options ...SandboxOption) error { - // Store connected endpoints - epList := sb.getConnectedEndpoints() - - // Detach from all endpoints - for _, ep := range epList { - if err := ep.Leave(sb); err != nil { - logrus.Warnf("Failed detaching sandbox %s from endpoint %s: %v\n", sb.ID(), ep.ID(), err) - } - } - - // Re-apply options - sb.config = containerConfig{} - sb.processOptions(options...) - - // Setup discovery files - if err := sb.setupResolutionFiles(); err != nil { - return err - } - - // Re-connect to all endpoints - for _, ep := range epList { - if err := ep.Join(sb); err != nil { - logrus.Warnf("Failed attach sandbox %s to endpoint %s: %v\n", sb.ID(), ep.ID(), err) - } - } - - return nil -} - -func (sb *sandbox) MarshalJSON() ([]byte, error) { - sb.Lock() - defer sb.Unlock() - - // We are just interested in the container ID. This can be expanded to include all of containerInfo if there is a need - return json.Marshal(sb.id) -} - -func (sb *sandbox) UnmarshalJSON(b []byte) (err error) { - sb.Lock() - defer sb.Unlock() - - var id string - if err := json.Unmarshal(b, &id); err != nil { - return err - } - sb.id = id - return nil -} - -func (sb *sandbox) Endpoints() []Endpoint { - sb.Lock() - defer sb.Unlock() - - endpoints := make([]Endpoint, len(sb.endpoints)) - for i, ep := range sb.endpoints { - endpoints[i] = ep - } - return endpoints -} - -func (sb *sandbox) getConnectedEndpoints() []*endpoint { - sb.Lock() - defer sb.Unlock() - - eps := make([]*endpoint, len(sb.endpoints)) - copy(eps, sb.endpoints) - - return eps -} - -func (sb *sandbox) addEndpoint(ep *endpoint) { - sb.Lock() - defer sb.Unlock() - - l := len(sb.endpoints) - i := sort.Search(l, func(j int) bool { - return ep.Less(sb.endpoints[j]) - }) - - sb.endpoints = append(sb.endpoints, nil) - copy(sb.endpoints[i+1:], sb.endpoints[i:]) - sb.endpoints[i] = ep -} - -func (sb *sandbox) removeEndpoint(ep *endpoint) { - sb.Lock() - defer sb.Unlock() - - sb.removeEndpointRaw(ep) -} - -func (sb *sandbox) removeEndpointRaw(ep *endpoint) { - for i, e := range sb.endpoints { - if e == ep { - sb.endpoints = append(sb.endpoints[:i], sb.endpoints[i+1:]...) - return - } - } -} - -func (sb *sandbox) getEndpoint(id string) *endpoint { - sb.Lock() - defer sb.Unlock() - - for _, ep := range sb.endpoints { - if ep.id == id { - return ep - } - } - - return nil -} - -func (sb *sandbox) updateGateway(ep *endpoint) error { - sb.Lock() - osSbox := sb.osSbox - sb.Unlock() - if osSbox == nil { - return nil - } - osSbox.UnsetGateway() - osSbox.UnsetGatewayIPv6() - - if ep == nil { - return nil - } - - ep.Lock() - joinInfo := ep.joinInfo - ep.Unlock() - - if err := osSbox.SetGateway(joinInfo.gw); err != nil { - return fmt.Errorf("failed to set gateway while updating gateway: %v", err) - } - - if err := osSbox.SetGatewayIPv6(joinInfo.gw6); err != nil { - return fmt.Errorf("failed to set IPv6 gateway while updating gateway: %v", err) - } - - return nil -} - -func (sb *sandbox) HandleQueryResp(name string, ip net.IP) { - for _, ep := range sb.getConnectedEndpoints() { - n := ep.getNetwork() - n.HandleQueryResp(name, ip) - } -} - -func (sb *sandbox) ResolveIP(ip string) string { - var svc string - logrus.Debugf("IP To resolve %v", ip) - - for _, ep := range sb.getConnectedEndpoints() { - n := ep.getNetwork() - svc = n.ResolveIP(ip) - if len(svc) != 0 { - return svc - } - } - - return svc -} - -func (sb *sandbox) ExecFunc(f func()) error { - sb.Lock() - osSbox := sb.osSbox - sb.Unlock() - if osSbox != nil { - return osSbox.InvokeFunc(f) - } - return fmt.Errorf("osl sandbox unavailable in ExecFunc for %v", sb.ContainerID()) -} - -func (sb *sandbox) ResolveService(name string) ([]*net.SRV, []net.IP) { - srv := []*net.SRV{} - ip := []net.IP{} - - logrus.Debugf("Service name To resolve: %v", name) - - // There are DNS implementations that allow SRV queries for names not in - // the format defined by RFC 2782. Hence specific validations checks are - // not done - parts := strings.Split(name, ".") - if len(parts) < 3 { - return nil, nil - } - - for _, ep := range sb.getConnectedEndpoints() { - n := ep.getNetwork() - - srv, ip = n.ResolveService(name) - if len(srv) > 0 { - break - } - } - return srv, ip -} - -func getDynamicNwEndpoints(epList []*endpoint) []*endpoint { - eps := []*endpoint{} - for _, ep := range epList { - n := ep.getNetwork() - if n.dynamic && !n.ingress { - eps = append(eps, ep) - } - } - return eps -} - -func getIngressNwEndpoint(epList []*endpoint) *endpoint { - for _, ep := range epList { - n := ep.getNetwork() - if n.ingress { - return ep - } - } - return nil -} - -func getLocalNwEndpoints(epList []*endpoint) []*endpoint { - eps := []*endpoint{} - for _, ep := range epList { - n := ep.getNetwork() - if !n.dynamic && !n.ingress { - eps = append(eps, ep) - } - } - return eps -} - -func (sb *sandbox) ResolveName(name string, ipType int) ([]net.IP, bool) { - // Embedded server owns the docker network domain. Resolution should work - // for both container_name and container_name.network_name - // We allow '.' in service name and network name. For a name a.b.c.d the - // following have to tried; - // {a.b.c.d in the networks container is connected to} - // {a.b.c in network d}, - // {a.b in network c.d}, - // {a in network b.c.d}, - - logrus.Debugf("Name To resolve: %v", name) - name = strings.TrimSuffix(name, ".") - reqName := []string{name} - networkName := []string{""} - - if strings.Contains(name, ".") { - var i int - dup := name - for { - if i = strings.LastIndex(dup, "."); i == -1 { - break - } - networkName = append(networkName, name[i+1:]) - reqName = append(reqName, name[:i]) - - dup = dup[:i] - } - } - - epList := sb.getConnectedEndpoints() - - // In swarm mode services with exposed ports are connected to user overlay - // network, ingress network and docker_gwbridge network. Name resolution - // should prioritize returning the VIP/IPs on user overlay network. - newList := []*endpoint{} - if !sb.controller.isDistributedControl() { - newList = append(newList, getDynamicNwEndpoints(epList)...) - ingressEP := getIngressNwEndpoint(epList) - if ingressEP != nil { - newList = append(newList, ingressEP) - } - newList = append(newList, getLocalNwEndpoints(epList)...) - epList = newList - } - - for i := 0; i < len(reqName); i++ { - - // First check for local container alias - ip, ipv6Miss := sb.resolveName(reqName[i], networkName[i], epList, true, ipType) - if ip != nil { - return ip, false - } - if ipv6Miss { - return ip, ipv6Miss - } - - // Resolve the actual container name - ip, ipv6Miss = sb.resolveName(reqName[i], networkName[i], epList, false, ipType) - if ip != nil { - return ip, false - } - if ipv6Miss { - return ip, ipv6Miss - } - } - return nil, false -} - -func (sb *sandbox) resolveName(req string, networkName string, epList []*endpoint, alias bool, ipType int) ([]net.IP, bool) { - var ipv6Miss bool - - for _, ep := range epList { - name := req - n := ep.getNetwork() - - if networkName != "" && networkName != n.Name() { - continue - } - - if alias { - if ep.aliases == nil { - continue - } - - var ok bool - ep.Lock() - name, ok = ep.aliases[req] - ep.Unlock() - if !ok { - continue - } - } else { - // If it is a regular lookup and if the requested name is an alias - // don't perform a svc lookup for this endpoint. - ep.Lock() - if _, ok := ep.aliases[req]; ok { - ep.Unlock() - continue - } - ep.Unlock() - } - - ip, miss := n.ResolveName(name, ipType) - - if ip != nil { - return ip, false - } - - if miss { - ipv6Miss = miss - } - } - return nil, ipv6Miss -} - -func (sb *sandbox) SetKey(basePath string) error { - start := time.Now() - defer func() { - logrus.Debugf("sandbox set key processing took %s for container %s", time.Since(start), sb.ContainerID()) - }() - - if basePath == "" { - return types.BadRequestErrorf("invalid sandbox key") - } - - sb.Lock() - if sb.inDelete { - sb.Unlock() - return types.ForbiddenErrorf("failed to SetKey: sandbox %q delete in progress", sb.id) - } - oldosSbox := sb.osSbox - sb.Unlock() - - if oldosSbox != nil { - // If we already have an OS sandbox, release the network resources from that - // and destroy the OS snab. We are moving into a new home further down. Note that none - // of the network resources gets destroyed during the move. - sb.releaseOSSbox() - } - - osSbox, err := osl.GetSandboxForExternalKey(basePath, sb.Key()) - if err != nil { - return err - } - - sb.Lock() - sb.osSbox = osSbox - sb.Unlock() - - // If the resolver was setup before stop it and set it up in the - // new osl sandbox. - if oldosSbox != nil && sb.resolver != nil { - sb.resolver.Stop() - - if err := sb.osSbox.InvokeFunc(sb.resolver.SetupFunc(0)); err == nil { - if err := sb.resolver.Start(); err != nil { - logrus.Errorf("Resolver Start failed for container %s, %q", sb.ContainerID(), err) - } - } else { - logrus.Errorf("Resolver Setup Function failed for container %s, %q", sb.ContainerID(), err) - } - } - - for _, ep := range sb.getConnectedEndpoints() { - if err = sb.populateNetworkResources(ep); err != nil { - return err - } - } - return nil -} - -func (sb *sandbox) EnableService() (err error) { - logrus.Debugf("EnableService %s START", sb.containerID) - defer func() { - if err != nil { - sb.DisableService() - } - }() - for _, ep := range sb.getConnectedEndpoints() { - if !ep.isServiceEnabled() { - if err := ep.addServiceInfoToCluster(sb); err != nil { - return fmt.Errorf("could not update state for endpoint %s into cluster: %v", ep.Name(), err) - } - ep.enableService() - } - } - logrus.Debugf("EnableService %s DONE", sb.containerID) - return nil -} - -func (sb *sandbox) DisableService() (err error) { - logrus.Debugf("DisableService %s START", sb.containerID) - failedEps := []string{} - defer func() { - if len(failedEps) > 0 { - err = fmt.Errorf("failed to disable service on sandbox:%s, for endpoints %s", sb.ID(), strings.Join(failedEps, ",")) - } - }() - for _, ep := range sb.getConnectedEndpoints() { - if ep.isServiceEnabled() { - if err := ep.deleteServiceInfoFromCluster(sb, false, "DisableService"); err != nil { - failedEps = append(failedEps, ep.Name()) - logrus.Warnf("failed update state for endpoint %s into cluster: %v", ep.Name(), err) - } - ep.disableService() - } - } - logrus.Debugf("DisableService %s DONE", sb.containerID) - return nil -} - -func releaseOSSboxResources(osSbox osl.Sandbox, ep *endpoint) { - for _, i := range osSbox.Info().Interfaces() { - // Only remove the interfaces owned by this endpoint from the sandbox. - if ep.hasInterface(i.SrcName()) { - if err := i.Remove(); err != nil { - logrus.Debugf("Remove interface %s failed: %v", i.SrcName(), err) - } - } - } - - ep.Lock() - joinInfo := ep.joinInfo - vip := ep.virtualIP - lbModeIsDSR := ep.network.loadBalancerMode == loadBalancerModeDSR - ep.Unlock() - - if len(vip) > 0 && lbModeIsDSR { - ipNet := &net.IPNet{IP: vip, Mask: net.CIDRMask(32, 32)} - if err := osSbox.RemoveAliasIP(osSbox.GetLoopbackIfaceName(), ipNet); err != nil { - logrus.WithError(err).Debugf("failed to remove virtual ip %v to loopback", ipNet) - } - } - - if joinInfo == nil { - return - } - - // Remove non-interface routes. - for _, r := range joinInfo.StaticRoutes { - if err := osSbox.RemoveStaticRoute(r); err != nil { - logrus.Debugf("Remove route failed: %v", err) - } - } -} - -func (sb *sandbox) releaseOSSbox() { - sb.Lock() - osSbox := sb.osSbox - sb.osSbox = nil - sb.Unlock() - - if osSbox == nil { - return - } - - for _, ep := range sb.getConnectedEndpoints() { - releaseOSSboxResources(osSbox, ep) - } - - osSbox.Destroy() -} - -func (sb *sandbox) restoreOslSandbox() error { - var routes []*types.StaticRoute - - // restore osl sandbox - Ifaces := make(map[string][]osl.IfaceOption) - for _, ep := range sb.endpoints { - var ifaceOptions []osl.IfaceOption - ep.Lock() - joinInfo := ep.joinInfo - i := ep.iface - ep.Unlock() - - if i == nil { - logrus.Errorf("error restoring endpoint %s for container %s", ep.Name(), sb.ContainerID()) - continue - } - - ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().Address(i.addr), sb.osSbox.InterfaceOptions().Routes(i.routes)) - if i.addrv6 != nil && i.addrv6.IP.To16() != nil { - ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().AddressIPv6(i.addrv6)) - } - if i.mac != nil { - ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().MacAddress(i.mac)) - } - if len(i.llAddrs) != 0 { - ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().LinkLocalAddresses(i.llAddrs)) - } - Ifaces[fmt.Sprintf("%s+%s", i.srcName, i.dstPrefix)] = ifaceOptions - if joinInfo != nil { - routes = append(routes, joinInfo.StaticRoutes...) - } - if ep.needResolver() { - sb.startResolver(true) - } - } - - gwep := sb.getGatewayEndpoint() - if gwep == nil { - return nil - } - - // restore osl sandbox - err := sb.osSbox.Restore(Ifaces, routes, gwep.joinInfo.gw, gwep.joinInfo.gw6) - return err -} - -func (sb *sandbox) populateNetworkResources(ep *endpoint) error { - sb.Lock() - if sb.osSbox == nil { - sb.Unlock() - return nil - } - inDelete := sb.inDelete - sb.Unlock() - - ep.Lock() - joinInfo := ep.joinInfo - i := ep.iface - lbModeIsDSR := ep.network.loadBalancerMode == loadBalancerModeDSR - ep.Unlock() - - if ep.needResolver() { - sb.startResolver(false) - } - - if i != nil && i.srcName != "" { - var ifaceOptions []osl.IfaceOption - - ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().Address(i.addr), sb.osSbox.InterfaceOptions().Routes(i.routes)) - if i.addrv6 != nil && i.addrv6.IP.To16() != nil { - ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().AddressIPv6(i.addrv6)) - } - if len(i.llAddrs) != 0 { - ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().LinkLocalAddresses(i.llAddrs)) - } - if i.mac != nil { - ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().MacAddress(i.mac)) - } - - if err := sb.osSbox.AddInterface(i.srcName, i.dstPrefix, ifaceOptions...); err != nil { - return fmt.Errorf("failed to add interface %s to sandbox: %v", i.srcName, err) - } - - if len(ep.virtualIP) > 0 && lbModeIsDSR { - if sb.loadBalancerNID == "" { - if err := sb.osSbox.DisableARPForVIP(i.srcName); err != nil { - return fmt.Errorf("failed disable ARP for VIP: %v", err) - } - } - ipNet := &net.IPNet{IP: ep.virtualIP, Mask: net.CIDRMask(32, 32)} - if err := sb.osSbox.AddAliasIP(sb.osSbox.GetLoopbackIfaceName(), ipNet); err != nil { - return fmt.Errorf("failed to add virtual ip %v to loopback: %v", ipNet, err) - } - } - } - - if joinInfo != nil { - // Set up non-interface routes. - for _, r := range joinInfo.StaticRoutes { - if err := sb.osSbox.AddStaticRoute(r); err != nil { - return fmt.Errorf("failed to add static route %s: %v", r.Destination.String(), err) - } - } - } - - if ep == sb.getGatewayEndpoint() { - if err := sb.updateGateway(ep); err != nil { - return err - } - } - - // Make sure to add the endpoint to the populated endpoint set - // before populating loadbalancers. - sb.Lock() - sb.populatedEndpoints[ep.ID()] = struct{}{} - sb.Unlock() - - // Populate load balancer only after updating all the other - // information including gateway and other routes so that - // loadbalancers are populated all the network state is in - // place in the sandbox. - sb.populateLoadBalancers(ep) - - // Only update the store if we did not come here as part of - // sandbox delete. If we came here as part of delete then do - // not bother updating the store. The sandbox object will be - // deleted anyway - if !inDelete { - return sb.storeUpdate() - } - - return nil -} - -func (sb *sandbox) clearNetworkResources(origEp *endpoint) error { - ep := sb.getEndpoint(origEp.id) - if ep == nil { - return fmt.Errorf("could not find the sandbox endpoint data for endpoint %s", - origEp.id) - } - - sb.Lock() - osSbox := sb.osSbox - inDelete := sb.inDelete - sb.Unlock() - if osSbox != nil { - releaseOSSboxResources(osSbox, ep) - } - - sb.Lock() - delete(sb.populatedEndpoints, ep.ID()) - - if len(sb.endpoints) == 0 { - // sb.endpoints should never be empty and this is unexpected error condition - // We log an error message to note this down for debugging purposes. - logrus.Errorf("No endpoints in sandbox while trying to remove endpoint %s", ep.Name()) - sb.Unlock() - return nil - } - - var ( - gwepBefore, gwepAfter *endpoint - index = -1 - ) - for i, e := range sb.endpoints { - if e == ep { - index = i - } - if len(e.Gateway()) > 0 && gwepBefore == nil { - gwepBefore = e - } - if index != -1 && gwepBefore != nil { - break - } - } - - if index == -1 { - logrus.Warnf("Endpoint %s has already been deleted", ep.Name()) - sb.Unlock() - return nil - } - - sb.removeEndpointRaw(ep) - for _, e := range sb.endpoints { - if len(e.Gateway()) > 0 { - gwepAfter = e - break - } - } - delete(sb.epPriority, ep.ID()) - sb.Unlock() - - if gwepAfter != nil && gwepBefore != gwepAfter { - sb.updateGateway(gwepAfter) - } - - // Only update the store if we did not come here as part of - // sandbox delete. If we came here as part of delete then do - // not bother updating the store. The sandbox object will be - // deleted anyway - if !inDelete { - return sb.storeUpdate() - } - - return nil -} - -func (sb *sandbox) isEndpointPopulated(ep *endpoint) bool { - sb.Lock() - _, ok := sb.populatedEndpoints[ep.ID()] - sb.Unlock() - return ok -} - -// 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{}) -} - -// 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 - } -} - -func (sb *sandbox) hasPortConfigs() bool { - opts := sb.Labels() - _, hasExpPorts := opts[netlabel.ExposedPorts] - _, hasPortMaps := opts[netlabel.PortMap] - return hasExpPorts || hasPortMaps -} - -// 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 - } -} - -// 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 - } -} - -// 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 - } -} - -// 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 - } -} - -// 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}) - } -} - -// 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}) - } -} - -// 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 - } -} - -// 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 - } -} - -// 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) - } -} - -// 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) - } -} - -// 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) - } -} - -// OptionUseDefaultSandbox function returns an option setter for using default sandbox -// (host namespace) to be passed to container Create method. -func OptionUseDefaultSandbox() SandboxOption { - return func(sb *sandbox) { - sb.config.useDefaultSandBox = true - } -} - -// OptionUseExternalKey function returns an option setter for using provided namespace -// instead of creating one. -func OptionUseExternalKey() SandboxOption { - return func(sb *sandbox) { - sb.config.useExternalKey = true - } -} - -// 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 - } - } -} - -// 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 - } -} - -// 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 - } -} - -// 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) - } -} - -// 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) - } -} - -// <=> 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() -} - -func (sb *sandbox) NdotsSet() bool { - return sb.ndotsSet -} diff --git a/vendor/github.com/docker/libnetwork/sandbox_dns_unix.go b/vendor/github.com/docker/libnetwork/sandbox_dns_unix.go deleted file mode 100644 index 08bf017326..0000000000 --- a/vendor/github.com/docker/libnetwork/sandbox_dns_unix.go +++ /dev/null @@ -1,437 +0,0 @@ -// +build !windows - -package libnetwork - -import ( - "fmt" - "io/ioutil" - "os" - "path" - "path/filepath" - "strconv" - "strings" - - "github.com/docker/libnetwork/etchosts" - "github.com/docker/libnetwork/resolvconf" - "github.com/docker/libnetwork/resolvconf/dns" - "github.com/docker/libnetwork/types" - "github.com/sirupsen/logrus" -) - -const ( - defaultPrefix = "/var/lib/docker/network/files" - dirPerm = 0755 - filePerm = 0644 -) - -func (sb *sandbox) startResolver(restore bool) { - sb.resolverOnce.Do(func() { - var err error - sb.resolver = NewResolver(resolverIPSandbox, true, sb.Key(), sb) - defer func() { - if err != nil { - sb.resolver = nil - } - }() - - // In the case of live restore container is already running with - // right resolv.conf contents created before. Just update the - // external DNS servers from the restored sandbox for embedded - // server to use. - if !restore { - err = sb.rebuildDNS() - if err != nil { - logrus.Errorf("Updating resolv.conf failed for container %s, %q", sb.ContainerID(), err) - return - } - } - sb.resolver.SetExtServers(sb.extDNS) - - if err = sb.osSbox.InvokeFunc(sb.resolver.SetupFunc(0)); err != nil { - logrus.Errorf("Resolver Setup function failed for container %s, %q", sb.ContainerID(), err) - return - } - - if err = sb.resolver.Start(); err != nil { - logrus.Errorf("Resolver Start failed for container %s, %q", sb.ContainerID(), err) - } - }) -} - -func (sb *sandbox) setupResolutionFiles() error { - if err := sb.buildHostsFile(); err != nil { - return err - } - - if err := sb.updateParentHosts(); err != nil { - return err - } - - return sb.setupDNS() -} - -func (sb *sandbox) buildHostsFile() error { - if sb.config.hostsPath == "" { - sb.config.hostsPath = defaultPrefix + "/" + sb.id + "/hosts" - } - - dir, _ := filepath.Split(sb.config.hostsPath) - if err := createBasePath(dir); err != nil { - return err - } - - // This is for the host mode networking - if sb.config.useDefaultSandBox && len(sb.config.extraHosts) == 0 { - // We are working under the assumption that the origin file option had been properly expressed by the upper layer - // if not here we are going to error out - if err := copyFile(sb.config.originHostsPath, sb.config.hostsPath); err != nil && !os.IsNotExist(err) { - return types.InternalErrorf("could not copy source hosts file %s to %s: %v", sb.config.originHostsPath, sb.config.hostsPath, err) - } - return nil - } - - extraContent := make([]etchosts.Record, 0, len(sb.config.extraHosts)) - for _, extraHost := range sb.config.extraHosts { - extraContent = append(extraContent, etchosts.Record{Hosts: extraHost.name, IP: extraHost.IP}) - } - - return etchosts.Build(sb.config.hostsPath, "", sb.config.hostName, sb.config.domainName, extraContent) -} - -func (sb *sandbox) updateHostsFile(ifaceIPs []string) error { - if ifaceIPs == nil || len(ifaceIPs) == 0 { - return nil - } - - if sb.config.originHostsPath != "" { - return nil - } - - // User might have provided a FQDN in hostname or split it across hostname - // and domainname. We want the FQDN and the bare hostname. - fqdn := sb.config.hostName - mhost := sb.config.hostName - if sb.config.domainName != "" { - fqdn = fmt.Sprintf("%s.%s", fqdn, sb.config.domainName) - } - - parts := strings.SplitN(fqdn, ".", 2) - if len(parts) == 2 { - mhost = fmt.Sprintf("%s %s", fqdn, parts[0]) - } - - var extraContent []etchosts.Record - for _, ip := range ifaceIPs { - extraContent = append(extraContent, etchosts.Record{Hosts: mhost, IP: ip}) - } - - sb.addHostsEntries(extraContent) - return nil -} - -func (sb *sandbox) addHostsEntries(recs []etchosts.Record) { - if err := etchosts.Add(sb.config.hostsPath, recs); err != nil { - logrus.Warnf("Failed adding service host entries to the running container: %v", err) - } -} - -func (sb *sandbox) deleteHostsEntries(recs []etchosts.Record) { - if err := etchosts.Delete(sb.config.hostsPath, recs); err != nil { - logrus.Warnf("Failed deleting service host entries to the running container: %v", err) - } -} - -func (sb *sandbox) updateParentHosts() error { - var pSb Sandbox - - for _, update := range sb.config.parentUpdates { - sb.controller.WalkSandboxes(SandboxContainerWalker(&pSb, update.cid)) - if pSb == nil { - continue - } - if err := etchosts.Update(pSb.(*sandbox).config.hostsPath, update.ip, update.name); err != nil { - return err - } - } - - return nil -} - -func (sb *sandbox) restorePath() { - if sb.config.resolvConfPath == "" { - sb.config.resolvConfPath = defaultPrefix + "/" + sb.id + "/resolv.conf" - } - sb.config.resolvConfHashFile = sb.config.resolvConfPath + ".hash" - if sb.config.hostsPath == "" { - sb.config.hostsPath = defaultPrefix + "/" + sb.id + "/hosts" - } -} - -func (sb *sandbox) setExternalResolvers(content []byte, addrType int, checkLoopback bool) { - servers := resolvconf.GetNameservers(content, addrType) - for _, ip := range servers { - hostLoopback := false - if checkLoopback { - hostLoopback = dns.IsIPv4Localhost(ip) - } - sb.extDNS = append(sb.extDNS, extDNSEntry{ - IPStr: ip, - HostLoopback: hostLoopback, - }) - } -} - -func (sb *sandbox) setupDNS() error { - var newRC *resolvconf.File - - if sb.config.resolvConfPath == "" { - sb.config.resolvConfPath = defaultPrefix + "/" + sb.id + "/resolv.conf" - } - - sb.config.resolvConfHashFile = sb.config.resolvConfPath + ".hash" - - dir, _ := filepath.Split(sb.config.resolvConfPath) - if err := createBasePath(dir); err != nil { - return err - } - - // When the user specify a conainter in the host namespace and do no have any dns option specified - // we just copy the host resolv.conf from the host itself - if sb.config.useDefaultSandBox && - len(sb.config.dnsList) == 0 && len(sb.config.dnsSearchList) == 0 && len(sb.config.dnsOptionsList) == 0 { - - // We are working under the assumption that the origin file option had been properly expressed by the upper layer - // if not here we are going to error out - if err := copyFile(sb.config.originResolvConfPath, sb.config.resolvConfPath); err != nil { - if !os.IsNotExist(err) { - return fmt.Errorf("could not copy source resolv.conf file %s to %s: %v", sb.config.originResolvConfPath, sb.config.resolvConfPath, err) - } - logrus.Infof("%s does not exist, we create an empty resolv.conf for container", sb.config.originResolvConfPath) - if err := createFile(sb.config.resolvConfPath); err != nil { - return err - } - } - return nil - } - - originResolvConfPath := sb.config.originResolvConfPath - if originResolvConfPath == "" { - // fallback if not specified - originResolvConfPath = resolvconf.Path() - } - currRC, err := resolvconf.GetSpecific(originResolvConfPath) - if err != nil { - if !os.IsNotExist(err) { - return err - } - // it's ok to continue if /etc/resolv.conf doesn't exist, default resolvers (Google's Public DNS) - // will be used - currRC = &resolvconf.File{} - logrus.Infof("/etc/resolv.conf does not exist") - } - - if len(sb.config.dnsList) > 0 || len(sb.config.dnsSearchList) > 0 || len(sb.config.dnsOptionsList) > 0 { - var ( - err error - dnsList = resolvconf.GetNameservers(currRC.Content, types.IP) - dnsSearchList = resolvconf.GetSearchDomains(currRC.Content) - dnsOptionsList = resolvconf.GetOptions(currRC.Content) - ) - if len(sb.config.dnsList) > 0 { - dnsList = sb.config.dnsList - } - if len(sb.config.dnsSearchList) > 0 { - dnsSearchList = sb.config.dnsSearchList - } - if len(sb.config.dnsOptionsList) > 0 { - dnsOptionsList = sb.config.dnsOptionsList - } - newRC, err = resolvconf.Build(sb.config.resolvConfPath, dnsList, dnsSearchList, dnsOptionsList) - if err != nil { - return err - } - // After building the resolv.conf from the user config save the - // external resolvers in the sandbox. Note that --dns 127.0.0.x - // config refers to the loopback in the container namespace - sb.setExternalResolvers(newRC.Content, types.IPv4, false) - } else { - // If the host resolv.conf file has 127.0.0.x container should - // use the host resolver for queries. This is supported by the - // docker embedded DNS server. Hence save the external resolvers - // before filtering it out. - sb.setExternalResolvers(currRC.Content, types.IPv4, true) - - // Replace any localhost/127.* (at this point we have no info about ipv6, pass it as true) - if newRC, err = resolvconf.FilterResolvDNS(currRC.Content, true); err != nil { - return err - } - // No contention on container resolv.conf file at sandbox creation - if err := ioutil.WriteFile(sb.config.resolvConfPath, newRC.Content, filePerm); err != nil { - return types.InternalErrorf("failed to write unhaltered resolv.conf file content when setting up dns for sandbox %s: %v", sb.ID(), err) - } - } - - // Write hash - if err := ioutil.WriteFile(sb.config.resolvConfHashFile, []byte(newRC.Hash), filePerm); err != nil { - return types.InternalErrorf("failed to write resolv.conf hash file when setting up dns for sandbox %s: %v", sb.ID(), err) - } - - return nil -} - -func (sb *sandbox) updateDNS(ipv6Enabled bool) error { - var ( - currHash string - hashFile = sb.config.resolvConfHashFile - ) - - // This is for the host mode networking - if sb.config.useDefaultSandBox { - return nil - } - - if len(sb.config.dnsList) > 0 || len(sb.config.dnsSearchList) > 0 || len(sb.config.dnsOptionsList) > 0 { - return nil - } - - currRC, err := resolvconf.GetSpecific(sb.config.resolvConfPath) - if err != nil { - if !os.IsNotExist(err) { - return err - } - } else { - h, err := ioutil.ReadFile(hashFile) - if err != nil { - if !os.IsNotExist(err) { - return err - } - } else { - currHash = string(h) - } - } - - if currHash != "" && currHash != currRC.Hash { - // Seems the user has changed the container resolv.conf since the last time - // we checked so return without doing anything. - //logrus.Infof("Skipping update of resolv.conf file with ipv6Enabled: %t because file was touched by user", ipv6Enabled) - return nil - } - - // replace any localhost/127.* and remove IPv6 nameservers if IPv6 disabled. - newRC, err := resolvconf.FilterResolvDNS(currRC.Content, ipv6Enabled) - if err != nil { - return err - } - err = ioutil.WriteFile(sb.config.resolvConfPath, newRC.Content, 0644) - if err != nil { - return err - } - - // write the new hash in a temp file and rename it to make the update atomic - dir := path.Dir(sb.config.resolvConfPath) - tmpHashFile, err := ioutil.TempFile(dir, "hash") - if err != nil { - return err - } - if err = tmpHashFile.Chmod(filePerm); err != nil { - tmpHashFile.Close() - return err - } - _, err = tmpHashFile.Write([]byte(newRC.Hash)) - if err1 := tmpHashFile.Close(); err == nil { - err = err1 - } - if err != nil { - return err - } - return os.Rename(tmpHashFile.Name(), hashFile) -} - -// Embedded DNS server has to be enabled for this sandbox. Rebuild the container's -// resolv.conf by doing the following -// - Add only the embedded server's IP to container's resolv.conf -// - If the embedded server needs any resolv.conf options add it to the current list -func (sb *sandbox) rebuildDNS() error { - currRC, err := resolvconf.GetSpecific(sb.config.resolvConfPath) - if err != nil { - return err - } - - if len(sb.extDNS) == 0 { - sb.setExternalResolvers(currRC.Content, types.IPv4, false) - } - var ( - dnsList = []string{sb.resolver.NameServer()} - dnsOptionsList = resolvconf.GetOptions(currRC.Content) - dnsSearchList = resolvconf.GetSearchDomains(currRC.Content) - ) - - // external v6 DNS servers has to be listed in resolv.conf - dnsList = append(dnsList, resolvconf.GetNameservers(currRC.Content, types.IPv6)...) - - // If the user config and embedded DNS server both have ndots option set, - // remember the user's config so that unqualified names not in the docker - // domain can be dropped. - resOptions := sb.resolver.ResolverOptions() - -dnsOpt: - for _, resOpt := range resOptions { - if strings.Contains(resOpt, "ndots") { - for _, option := range dnsOptionsList { - if strings.Contains(option, "ndots") { - parts := strings.Split(option, ":") - if len(parts) != 2 { - return fmt.Errorf("invalid ndots option %v", option) - } - if num, err := strconv.Atoi(parts[1]); err != nil { - return fmt.Errorf("invalid number for ndots option: %v", parts[1]) - } else if num >= 0 { - // if the user sets ndots, use the user setting - sb.ndotsSet = true - break dnsOpt - } else { - return fmt.Errorf("invalid number for ndots option: %v", num) - } - } - } - } - } - - if !sb.ndotsSet { - // if the user did not set the ndots, set it to 0 to prioritize the service name resolution - // Ref: https://linux.die.net/man/5/resolv.conf - dnsOptionsList = append(dnsOptionsList, resOptions...) - } - - _, err = resolvconf.Build(sb.config.resolvConfPath, dnsList, dnsSearchList, dnsOptionsList) - return err -} - -func createBasePath(dir string) error { - return os.MkdirAll(dir, dirPerm) -} - -func createFile(path string) error { - var f *os.File - - dir, _ := filepath.Split(path) - err := createBasePath(dir) - if err != nil { - return err - } - - f, err = os.Create(path) - if err == nil { - f.Close() - } - - return err -} - -func copyFile(src, dst string) error { - sBytes, err := ioutil.ReadFile(src) - if err != nil { - return err - } - return ioutil.WriteFile(dst, sBytes, filePerm) -} diff --git a/vendor/github.com/docker/libnetwork/sandbox_dns_windows.go b/vendor/github.com/docker/libnetwork/sandbox_dns_windows.go deleted file mode 100644 index d30bc7eabc..0000000000 --- a/vendor/github.com/docker/libnetwork/sandbox_dns_windows.go +++ /dev/null @@ -1,35 +0,0 @@ -// +build windows - -package libnetwork - -import ( - "github.com/docker/libnetwork/etchosts" -) - -// Stub implementations for DNS related functions - -func (sb *sandbox) startResolver(bool) { -} - -func (sb *sandbox) setupResolutionFiles() error { - return nil -} - -func (sb *sandbox) restorePath() { -} - -func (sb *sandbox) updateHostsFile(ifaceIP []string) error { - return nil -} - -func (sb *sandbox) addHostsEntries(recs []etchosts.Record) { - -} - -func (sb *sandbox) deleteHostsEntries(recs []etchosts.Record) { - -} - -func (sb *sandbox) updateDNS(ipv6Enabled bool) error { - return nil -} diff --git a/vendor/github.com/docker/libnetwork/sandbox_externalkey.go b/vendor/github.com/docker/libnetwork/sandbox_externalkey.go deleted file mode 100644 index 3c362f30d6..0000000000 --- a/vendor/github.com/docker/libnetwork/sandbox_externalkey.go +++ /dev/null @@ -1,12 +0,0 @@ -package libnetwork - -import "github.com/docker/docker/pkg/reexec" - -type setKeyData struct { - ContainerID string - Key string -} - -func init() { - reexec.Register("libnetwork-setkey", processSetKeyReexec) -} diff --git a/vendor/github.com/docker/libnetwork/sandbox_externalkey_unix.go b/vendor/github.com/docker/libnetwork/sandbox_externalkey_unix.go deleted file mode 100644 index d0f60deda7..0000000000 --- a/vendor/github.com/docker/libnetwork/sandbox_externalkey_unix.go +++ /dev/null @@ -1,193 +0,0 @@ -// +build linux freebsd - -package libnetwork - -import ( - "encoding/json" - "flag" - "fmt" - "io" - "io/ioutil" - "net" - "os" - "path/filepath" - - "github.com/docker/docker/pkg/stringid" - "github.com/docker/libnetwork/types" - "github.com/opencontainers/runtime-spec/specs-go" - "github.com/sirupsen/logrus" -) - -const ( - execSubdir = "libnetwork" - defaultExecRoot = "/run/docker" - success = "success" -) - -// processSetKeyReexec is a private function that must be called only on an reexec path -// It expects 3 args { [0] = "libnetwork-setkey", [1] = , [2] = } -// It also expects specs.State as a json string in -// 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]=, [2]= } - // (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, shortCtlrID := args[0], args[1] - - // We expect specs.State as a json string in - 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(shortCtlrID, containerID, fmt.Sprintf("/proc/%d/ns/net", state.Pid), *execRoot) -} - -// SetExternalKey provides a convenient way to set an External key to a sandbox -func SetExternalKey(shortCtlrID string, containerID string, key string, execRoot string) error { - keyData := setKeyData{ - ContainerID: containerID, - Key: key} - - uds := filepath.Join(execRoot, execSubdir, shortCtlrID+".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) -} - -func sendKey(c net.Conn, data setKeyData) error { - var err error - defer func() { - if err != nil { - c.Close() - } - }() - - var b []byte - if b, err = json.Marshal(data); err != nil { - return err - } - - _, err = c.Write(b) - return err -} - -func processReturn(r io.Reader) error { - buf := make([]byte, 1024) - n, err := r.Read(buf[:]) - if err != nil { - return fmt.Errorf("failed to read buf in processReturn : %v", err) - } - if string(buf[0:n]) != success { - return fmt.Errorf(string(buf[0:n])) - } - return nil -} - -func (c *controller) startExternalKeyListener() error { - execRoot := defaultExecRoot - if v := c.Config().Daemon.ExecRoot; v != "" { - execRoot = v - } - udsBase := filepath.Join(execRoot, execSubdir) - if err := os.MkdirAll(udsBase, 0600); err != nil { - return err - } - shortCtlrID := stringid.TruncateID(c.id) - uds := filepath.Join(udsBase, shortCtlrID+".sock") - l, err := net.Listen("unix", uds) - if err != nil { - return err - } - if err := os.Chmod(uds, 0600); err != nil { - l.Close() - return err - } - c.Lock() - c.extKeyListener = l - c.Unlock() - - go c.acceptClientConnections(uds, l) - return nil -} - -func (c *controller) acceptClientConnections(sock string, l net.Listener) { - for { - conn, err := l.Accept() - if err != nil { - if _, err1 := os.Stat(sock); os.IsNotExist(err1) { - logrus.Debugf("Unix socket %s doesn't exist. cannot accept client connections", sock) - return - } - logrus.Errorf("Error accepting connection %v", err) - continue - } - go func() { - defer conn.Close() - - err := c.processExternalKey(conn) - ret := success - if err != nil { - ret = err.Error() - } - - _, err = conn.Write([]byte(ret)) - if err != nil { - logrus.Errorf("Error returning to the client %v", err) - } - }() - } -} - -func (c *controller) processExternalKey(conn net.Conn) error { - buf := make([]byte, 1280) - nr, err := conn.Read(buf) - if err != nil { - return err - } - var s setKeyData - if err = json.Unmarshal(buf[0:nr], &s); err != nil { - return err - } - - var sandbox Sandbox - search := SandboxContainerWalker(&sandbox, s.ContainerID) - c.WalkSandboxes(search) - if sandbox == nil { - return types.BadRequestErrorf("no sandbox present for %s", s.ContainerID) - } - - return sandbox.SetKey(s.Key) -} - -func (c *controller) stopExternalKeyListener() { - c.extKeyListener.Close() -} diff --git a/vendor/github.com/docker/libnetwork/sandbox_externalkey_windows.go b/vendor/github.com/docker/libnetwork/sandbox_externalkey_windows.go deleted file mode 100644 index 340cd1735f..0000000000 --- a/vendor/github.com/docker/libnetwork/sandbox_externalkey_windows.go +++ /dev/null @@ -1,45 +0,0 @@ -// +build windows - -package libnetwork - -import ( - "io" - "net" - - "github.com/docker/libnetwork/types" -) - -// processSetKeyReexec is a private function that must be called only on an reexec path -// It expects 3 args { [0] = "libnetwork-setkey", [1] = , [2] = } -// It also expects configs.HookState as a json string in -// Refer to https://github.com/opencontainers/runc/pull/160/ for more information -func processSetKeyReexec() { -} - -// SetExternalKey provides a convenient way to set an External key to a sandbox -func SetExternalKey(controllerID string, containerID string, key string) error { - return types.NotImplementedErrorf("SetExternalKey isn't supported on non linux systems") -} - -func sendKey(c net.Conn, data setKeyData) error { - return types.NotImplementedErrorf("sendKey isn't supported on non linux systems") -} - -func processReturn(r io.Reader) error { - return types.NotImplementedErrorf("processReturn isn't supported on non linux systems") -} - -// no-op on non linux systems -func (c *controller) startExternalKeyListener() error { - return nil -} - -func (c *controller) acceptClientConnections(sock string, l net.Listener) { -} - -func (c *controller) processExternalKey(conn net.Conn) error { - return types.NotImplementedErrorf("processExternalKey isn't supported on non linux systems") -} - -func (c *controller) stopExternalKeyListener() { -} diff --git a/vendor/github.com/docker/libnetwork/sandbox_store.go b/vendor/github.com/docker/libnetwork/sandbox_store.go deleted file mode 100644 index 1e53815aee..0000000000 --- a/vendor/github.com/docker/libnetwork/sandbox_store.go +++ /dev/null @@ -1,303 +0,0 @@ -package libnetwork - -import ( - "encoding/json" - "sync" - - "github.com/docker/libnetwork/datastore" - "github.com/docker/libnetwork/osl" - "github.com/sirupsen/logrus" -) - -const ( - sandboxPrefix = "sandbox" -) - -type epState struct { - Eid string - Nid string -} - -type sbState struct { - ID string - Cid string - c *controller - dbIndex uint64 - dbExists bool - Eps []epState - EpPriority map[string]int - // external servers have to be persisted so that on restart of a live-restore - // enabled daemon we get the external servers for the running containers. - // We have two versions of ExtDNS to support upgrade & downgrade of the daemon - // between >=1.14 and <1.14 versions. - ExtDNS []string - ExtDNS2 []extDNSEntry -} - -func (sbs *sbState) Key() []string { - return []string{sandboxPrefix, sbs.ID} -} - -func (sbs *sbState) KeyPrefix() []string { - return []string{sandboxPrefix} -} - -func (sbs *sbState) Value() []byte { - b, err := json.Marshal(sbs) - if err != nil { - return nil - } - return b -} - -func (sbs *sbState) SetValue(value []byte) error { - return json.Unmarshal(value, sbs) -} - -func (sbs *sbState) Index() uint64 { - sbi, err := sbs.c.SandboxByID(sbs.ID) - if err != nil { - return sbs.dbIndex - } - - sb := sbi.(*sandbox) - maxIndex := sb.dbIndex - if sbs.dbIndex > maxIndex { - maxIndex = sbs.dbIndex - } - - return maxIndex -} - -func (sbs *sbState) SetIndex(index uint64) { - sbs.dbIndex = index - sbs.dbExists = true - - sbi, err := sbs.c.SandboxByID(sbs.ID) - if err != nil { - return - } - - sb := sbi.(*sandbox) - sb.dbIndex = index - sb.dbExists = true -} - -func (sbs *sbState) Exists() bool { - if sbs.dbExists { - return sbs.dbExists - } - - sbi, err := sbs.c.SandboxByID(sbs.ID) - if err != nil { - return false - } - - sb := sbi.(*sandbox) - return sb.dbExists -} - -func (sbs *sbState) Skip() bool { - return false -} - -func (sbs *sbState) New() datastore.KVObject { - return &sbState{c: sbs.c} -} - -func (sbs *sbState) CopyTo(o datastore.KVObject) error { - dstSbs := o.(*sbState) - dstSbs.c = sbs.c - dstSbs.ID = sbs.ID - dstSbs.Cid = sbs.Cid - dstSbs.dbIndex = sbs.dbIndex - dstSbs.dbExists = sbs.dbExists - dstSbs.EpPriority = sbs.EpPriority - - dstSbs.Eps = append(dstSbs.Eps, sbs.Eps...) - - if len(sbs.ExtDNS2) > 0 { - for _, dns := range sbs.ExtDNS2 { - dstSbs.ExtDNS2 = append(dstSbs.ExtDNS2, dns) - dstSbs.ExtDNS = append(dstSbs.ExtDNS, dns.IPStr) - } - return nil - } - for _, dns := range sbs.ExtDNS { - dstSbs.ExtDNS = append(dstSbs.ExtDNS, dns) - dstSbs.ExtDNS2 = append(dstSbs.ExtDNS2, extDNSEntry{IPStr: dns}) - } - - return nil -} - -func (sbs *sbState) DataScope() string { - return datastore.LocalScope -} - -func (sb *sandbox) storeUpdate() error { - sbs := &sbState{ - c: sb.controller, - ID: sb.id, - Cid: sb.containerID, - EpPriority: sb.epPriority, - ExtDNS2: sb.extDNS, - } - - for _, ext := range sb.extDNS { - sbs.ExtDNS = append(sbs.ExtDNS, ext.IPStr) - } - -retry: - sbs.Eps = nil - for _, ep := range sb.getConnectedEndpoints() { - // If the endpoint is not persisted then do not add it to - // the sandbox checkpoint - if ep.Skip() { - continue - } - - eps := epState{ - Nid: ep.getNetwork().ID(), - Eid: ep.ID(), - } - - sbs.Eps = append(sbs.Eps, eps) - } - - err := sb.controller.updateToStore(sbs) - if err == datastore.ErrKeyModified { - // When we get ErrKeyModified it is sufficient to just - // go back and retry. No need to get the object from - // the store because we always regenerate the store - // state from in memory sandbox state - goto retry - } - - return err -} - -func (sb *sandbox) storeDelete() error { - sbs := &sbState{ - c: sb.controller, - ID: sb.id, - Cid: sb.containerID, - dbIndex: sb.dbIndex, - dbExists: sb.dbExists, - } - - return sb.controller.deleteFromStore(sbs) -} - -func (c *controller) sandboxCleanup(activeSandboxes map[string]interface{}) { - store := c.getStore(datastore.LocalScope) - if store == nil { - logrus.Error("Could not find local scope store while trying to cleanup sandboxes") - return - } - - kvol, err := store.List(datastore.Key(sandboxPrefix), &sbState{c: c}) - if err != nil && err != datastore.ErrKeyNotFound { - logrus.Errorf("failed to get sandboxes for scope %s: %v", store.Scope(), err) - return - } - - // It's normal for no sandboxes to be found. Just bail out. - if err == datastore.ErrKeyNotFound { - return - } - - for _, kvo := range kvol { - sbs := kvo.(*sbState) - - sb := &sandbox{ - id: sbs.ID, - controller: sbs.c, - containerID: sbs.Cid, - endpoints: []*endpoint{}, - populatedEndpoints: map[string]struct{}{}, - dbIndex: sbs.dbIndex, - isStub: true, - dbExists: true, - } - // If we are restoring from a older version extDNSEntry won't have the - // HostLoopback field - if len(sbs.ExtDNS2) > 0 { - sb.extDNS = sbs.ExtDNS2 - } else { - for _, dns := range sbs.ExtDNS { - sb.extDNS = append(sb.extDNS, extDNSEntry{IPStr: dns}) - } - } - - msg := " for cleanup" - create := true - isRestore := false - if val, ok := activeSandboxes[sb.ID()]; ok { - msg = "" - sb.isStub = false - isRestore = true - opts := val.([]SandboxOption) - sb.processOptions(opts...) - sb.restorePath() - create = !sb.config.useDefaultSandBox - } - sb.osSbox, err = osl.NewSandbox(sb.Key(), create, isRestore) - if err != nil { - logrus.Errorf("failed to create osl sandbox while trying to restore sandbox %.7s%s: %v", sb.ID(), msg, err) - continue - } - - c.Lock() - c.sandboxes[sb.id] = sb - c.Unlock() - - for _, eps := range sbs.Eps { - n, err := c.getNetworkFromStore(eps.Nid) - var ep *endpoint - if err != nil { - logrus.Errorf("getNetworkFromStore for nid %s failed while trying to build sandbox for cleanup: %v", eps.Nid, err) - n = &network{id: eps.Nid, ctrlr: c, drvOnce: &sync.Once{}, persist: true} - ep = &endpoint{id: eps.Eid, network: n, sandboxID: sbs.ID} - } else { - ep, err = n.getEndpointFromStore(eps.Eid) - if err != nil { - logrus.Errorf("getEndpointFromStore for eid %s failed while trying to build sandbox for cleanup: %v", eps.Eid, err) - ep = &endpoint{id: eps.Eid, network: n, sandboxID: sbs.ID} - } - } - if _, ok := activeSandboxes[sb.ID()]; ok && err != nil { - logrus.Errorf("failed to restore endpoint %s in %s for container %s due to %v", eps.Eid, eps.Nid, sb.ContainerID(), err) - continue - } - sb.addEndpoint(ep) - } - - if _, ok := activeSandboxes[sb.ID()]; !ok { - logrus.Infof("Removing stale sandbox %s (%s)", sb.id, sb.containerID) - if err := sb.delete(true); err != nil { - logrus.Errorf("Failed to delete sandbox %s while trying to cleanup: %v", sb.id, err) - } - continue - } - - // reconstruct osl sandbox field - if !sb.config.useDefaultSandBox { - if err := sb.restoreOslSandbox(); err != nil { - logrus.Errorf("failed to populate fields for osl sandbox %s", sb.ID()) - continue - } - } else { - c.sboxOnce.Do(func() { - c.defOsSbox = sb.osSbox - }) - } - - for _, ep := range sb.endpoints { - // Watch for service records - if !c.isAgent() { - c.watchSvcRecord(ep) - } - } - } -} diff --git a/vendor/github.com/docker/libnetwork/service.go b/vendor/github.com/docker/libnetwork/service.go deleted file mode 100644 index 5ed11959a1..0000000000 --- a/vendor/github.com/docker/libnetwork/service.go +++ /dev/null @@ -1,98 +0,0 @@ -package libnetwork - -import ( - "fmt" - "net" - "sync" - - "github.com/docker/libnetwork/internal/setmatrix" -) - -var ( - // A global monotonic counter to assign firewall marks to - // services. - fwMarkCtr uint32 = 256 - fwMarkCtrMu sync.Mutex -) - -type portConfigs []*PortConfig - -func (p portConfigs) String() string { - if len(p) == 0 { - return "" - } - - pc := p[0] - str := fmt.Sprintf("%d:%d/%s", pc.PublishedPort, pc.TargetPort, PortConfig_Protocol_name[int32(pc.Protocol)]) - for _, pc := range p[1:] { - str = str + fmt.Sprintf(",%d:%d/%s", pc.PublishedPort, pc.TargetPort, PortConfig_Protocol_name[int32(pc.Protocol)]) - } - - return str -} - -type serviceKey struct { - id string - ports string -} - -type service struct { - name string // Service Name - id string // Service ID - - // Map of loadbalancers for the service one-per attached - // network. It is keyed with network ID. - loadBalancers map[string]*loadBalancer - - // List of ingress ports exposed by the service - ingressPorts portConfigs - - // Service aliases - aliases []string - - // This maps tracks for each IP address the list of endpoints ID - // associated with it. At stable state the endpoint ID expected is 1 - // but during transition and service change it is possible to have - // temporary more than 1 - ipToEndpoint setmatrix.SetMatrix - - deleted bool - - sync.Mutex -} - -// assignIPToEndpoint inserts the mapping between the IP and the endpoint identifier -// returns true if the mapping was not present, false otherwise -// returns also the number of endpoints associated to the IP -func (s *service) assignIPToEndpoint(ip, eID string) (bool, int) { - return s.ipToEndpoint.Insert(ip, eID) -} - -// removeIPToEndpoint removes the mapping between the IP and the endpoint identifier -// returns true if the mapping was deleted, false otherwise -// returns also the number of endpoints associated to the IP -func (s *service) removeIPToEndpoint(ip, eID string) (bool, int) { - return s.ipToEndpoint.Remove(ip, eID) -} - -func (s *service) printIPToEndpoint(ip string) (string, bool) { - return s.ipToEndpoint.String(ip) -} - -type lbBackend struct { - ip net.IP - disabled bool -} - -type loadBalancer struct { - vip net.IP - fwMark uint32 - - // Map of backend IPs backing this loadbalancer on this - // network. It is keyed with endpoint ID. - backEnds map[string]*lbBackend - - // Back pointer to service to which the loadbalancer belongs. - service *service - sync.Mutex -} diff --git a/vendor/github.com/docker/libnetwork/service_common.go b/vendor/github.com/docker/libnetwork/service_common.go deleted file mode 100644 index b6d79cce35..0000000000 --- a/vendor/github.com/docker/libnetwork/service_common.go +++ /dev/null @@ -1,403 +0,0 @@ -// +build linux windows - -package libnetwork - -import ( - "net" - - "github.com/docker/libnetwork/internal/setmatrix" - "github.com/sirupsen/logrus" -) - -const maxSetStringLen = 350 - -func (c *controller) addEndpointNameResolution(svcName, svcID, nID, eID, containerName string, vip net.IP, serviceAliases, taskAliases []string, ip net.IP, addService bool, method string) error { - n, err := c.NetworkByID(nID) - if err != nil { - return err - } - - logrus.Debugf("addEndpointNameResolution %s %s add_service:%t sAliases:%v tAliases:%v", eID, svcName, addService, serviceAliases, taskAliases) - - // Add container resolution mappings - c.addContainerNameResolution(nID, eID, containerName, taskAliases, ip, method) - - serviceID := svcID - if serviceID == "" { - // This is the case of a normal container not part of a service - serviceID = eID - } - - // Add endpoint IP to special "tasks.svc_name" so that the applications have access to DNS RR. - n.(*network).addSvcRecords(eID, "tasks."+svcName, serviceID, ip, nil, false, method) - for _, alias := range serviceAliases { - n.(*network).addSvcRecords(eID, "tasks."+alias, serviceID, ip, nil, false, method) - } - - // Add service name to vip in DNS, if vip is valid. Otherwise resort to DNS RR - if len(vip) == 0 { - n.(*network).addSvcRecords(eID, svcName, serviceID, ip, nil, false, method) - for _, alias := range serviceAliases { - n.(*network).addSvcRecords(eID, alias, serviceID, ip, nil, false, method) - } - } - - if addService && len(vip) != 0 { - n.(*network).addSvcRecords(eID, svcName, serviceID, vip, nil, false, method) - for _, alias := range serviceAliases { - n.(*network).addSvcRecords(eID, alias, serviceID, vip, nil, false, method) - } - } - - return nil -} - -func (c *controller) addContainerNameResolution(nID, eID, containerName string, taskAliases []string, ip net.IP, method string) error { - n, err := c.NetworkByID(nID) - if err != nil { - return err - } - logrus.Debugf("addContainerNameResolution %s %s", eID, containerName) - - // Add resolution for container name - n.(*network).addSvcRecords(eID, containerName, eID, ip, nil, true, method) - - // Add resolution for taskaliases - for _, alias := range taskAliases { - n.(*network).addSvcRecords(eID, alias, eID, ip, nil, false, method) - } - - return nil -} - -func (c *controller) deleteEndpointNameResolution(svcName, svcID, nID, eID, containerName string, vip net.IP, serviceAliases, taskAliases []string, ip net.IP, rmService, multipleEntries bool, method string) error { - n, err := c.NetworkByID(nID) - if err != nil { - return err - } - - logrus.Debugf("deleteEndpointNameResolution %s %s rm_service:%t suppress:%t sAliases:%v tAliases:%v", eID, svcName, rmService, multipleEntries, serviceAliases, taskAliases) - - // Delete container resolution mappings - c.delContainerNameResolution(nID, eID, containerName, taskAliases, ip, method) - - serviceID := svcID - if serviceID == "" { - // This is the case of a normal container not part of a service - serviceID = eID - } - - // Delete the special "tasks.svc_name" backend record. - if !multipleEntries { - n.(*network).deleteSvcRecords(eID, "tasks."+svcName, serviceID, ip, nil, false, method) - for _, alias := range serviceAliases { - n.(*network).deleteSvcRecords(eID, "tasks."+alias, serviceID, ip, nil, false, method) - } - } - - // If we are doing DNS RR delete the endpoint IP from DNS record right away. - if !multipleEntries && len(vip) == 0 { - n.(*network).deleteSvcRecords(eID, svcName, serviceID, ip, nil, false, method) - for _, alias := range serviceAliases { - n.(*network).deleteSvcRecords(eID, alias, serviceID, ip, nil, false, method) - } - } - - // Remove the DNS record for VIP only if we are removing the service - if rmService && len(vip) != 0 && !multipleEntries { - n.(*network).deleteSvcRecords(eID, svcName, serviceID, vip, nil, false, method) - for _, alias := range serviceAliases { - n.(*network).deleteSvcRecords(eID, alias, serviceID, vip, nil, false, method) - } - } - - return nil -} - -func (c *controller) delContainerNameResolution(nID, eID, containerName string, taskAliases []string, ip net.IP, method string) error { - n, err := c.NetworkByID(nID) - if err != nil { - return err - } - logrus.Debugf("delContainerNameResolution %s %s", eID, containerName) - - // Delete resolution for container name - n.(*network).deleteSvcRecords(eID, containerName, eID, ip, nil, true, method) - - // Delete resolution for taskaliases - for _, alias := range taskAliases { - n.(*network).deleteSvcRecords(eID, alias, eID, ip, nil, true, method) - } - - return nil -} - -func newService(name string, id string, ingressPorts []*PortConfig, serviceAliases []string) *service { - return &service{ - name: name, - id: id, - ingressPorts: ingressPorts, - loadBalancers: make(map[string]*loadBalancer), - aliases: serviceAliases, - ipToEndpoint: setmatrix.NewSetMatrix(), - } -} - -func (c *controller) getLBIndex(sid, nid string, ingressPorts []*PortConfig) int { - skey := serviceKey{ - id: sid, - ports: portConfigs(ingressPorts).String(), - } - c.Lock() - s, ok := c.serviceBindings[skey] - c.Unlock() - - if !ok { - return 0 - } - - s.Lock() - lb := s.loadBalancers[nid] - s.Unlock() - - return int(lb.fwMark) -} - -// cleanupServiceDiscovery when the network is being deleted, erase all the associated service discovery records -func (c *controller) cleanupServiceDiscovery(cleanupNID string) { - c.Lock() - defer c.Unlock() - if cleanupNID == "" { - logrus.Debugf("cleanupServiceDiscovery for all networks") - c.svcRecords = make(map[string]svcInfo) - return - } - logrus.Debugf("cleanupServiceDiscovery for network:%s", cleanupNID) - delete(c.svcRecords, cleanupNID) -} - -func (c *controller) cleanupServiceBindings(cleanupNID string) { - var cleanupFuncs []func() - - logrus.Debugf("cleanupServiceBindings for %s", cleanupNID) - c.Lock() - services := make([]*service, 0, len(c.serviceBindings)) - for _, s := range c.serviceBindings { - services = append(services, s) - } - c.Unlock() - - for _, s := range services { - s.Lock() - // Skip the serviceBindings that got deleted - if s.deleted { - s.Unlock() - continue - } - for nid, lb := range s.loadBalancers { - if cleanupNID != "" && nid != cleanupNID { - continue - } - for eid, be := range lb.backEnds { - cleanupFuncs = append(cleanupFuncs, makeServiceCleanupFunc(c, s, nid, eid, lb.vip, be.ip)) - } - } - s.Unlock() - } - - for _, f := range cleanupFuncs { - f() - } - -} - -func makeServiceCleanupFunc(c *controller, s *service, nID, eID string, vip net.IP, ip net.IP) func() { - // ContainerName and taskAliases are not available here, this is still fine because the Service discovery - // cleanup already happened before. The only thing that rmServiceBinding is still doing here a part from the Load - // Balancer bookeeping, is to keep consistent the mapping of endpoint to IP. - return func() { - if err := c.rmServiceBinding(s.name, s.id, nID, eID, "", vip, s.ingressPorts, s.aliases, []string{}, ip, "cleanupServiceBindings", false, true); err != nil { - logrus.Errorf("Failed to remove service bindings for service %s network %s endpoint %s while cleanup: %v", s.id, nID, eID, err) - } - } -} - -func (c *controller) addServiceBinding(svcName, svcID, nID, eID, containerName string, vip net.IP, ingressPorts []*PortConfig, serviceAliases, taskAliases []string, ip net.IP, method string) error { - var addService bool - - // Failure to lock the network ID on add can result in racing - // racing against network deletion resulting in inconsistent - // state in the c.serviceBindings map and it's sub-maps. Also, - // always lock network ID before services to avoid deadlock. - c.networkLocker.Lock(nID) - defer c.networkLocker.Unlock(nID) - - n, err := c.NetworkByID(nID) - if err != nil { - return err - } - - skey := serviceKey{ - id: svcID, - ports: portConfigs(ingressPorts).String(), - } - - var s *service - for { - c.Lock() - var ok bool - s, ok = c.serviceBindings[skey] - if !ok { - // Create a new service if we are seeing this service - // for the first time. - s = newService(svcName, svcID, ingressPorts, serviceAliases) - c.serviceBindings[skey] = s - } - c.Unlock() - s.Lock() - if !s.deleted { - // ok the object is good to be used - break - } - s.Unlock() - } - logrus.Debugf("addServiceBinding from %s START for %s %s p:%p nid:%s skey:%v", method, svcName, eID, s, nID, skey) - defer s.Unlock() - - lb, ok := s.loadBalancers[nID] - if !ok { - // Create a new load balancer if we are seeing this - // network attachment on the service for the first - // time. - fwMarkCtrMu.Lock() - - lb = &loadBalancer{ - vip: vip, - fwMark: fwMarkCtr, - backEnds: make(map[string]*lbBackend), - service: s, - } - - fwMarkCtr++ - fwMarkCtrMu.Unlock() - - s.loadBalancers[nID] = lb - addService = true - } - - lb.backEnds[eID] = &lbBackend{ip, false} - - ok, entries := s.assignIPToEndpoint(ip.String(), eID) - if !ok || entries > 1 { - setStr, b := s.printIPToEndpoint(ip.String()) - if len(setStr) > maxSetStringLen { - setStr = setStr[:maxSetStringLen] - } - logrus.Warnf("addServiceBinding %s possible transient state ok:%t entries:%d set:%t %s", eID, ok, entries, b, setStr) - } - - // Add loadbalancer service and backend to the network - n.(*network).addLBBackend(ip, lb) - - // Add the appropriate name resolutions - c.addEndpointNameResolution(svcName, svcID, nID, eID, containerName, vip, serviceAliases, taskAliases, ip, addService, "addServiceBinding") - - logrus.Debugf("addServiceBinding from %s END for %s %s", method, svcName, eID) - - return nil -} - -func (c *controller) rmServiceBinding(svcName, svcID, nID, eID, containerName string, vip net.IP, ingressPorts []*PortConfig, serviceAliases []string, taskAliases []string, ip net.IP, method string, deleteSvcRecords bool, fullRemove bool) error { - - var rmService bool - - skey := serviceKey{ - id: svcID, - ports: portConfigs(ingressPorts).String(), - } - - c.Lock() - s, ok := c.serviceBindings[skey] - c.Unlock() - if !ok { - logrus.Warnf("rmServiceBinding %s %s %s aborted c.serviceBindings[skey] !ok", method, svcName, eID) - return nil - } - - s.Lock() - defer s.Unlock() - logrus.Debugf("rmServiceBinding from %s START for %s %s p:%p nid:%s sKey:%v deleteSvc:%t", method, svcName, eID, s, nID, skey, deleteSvcRecords) - lb, ok := s.loadBalancers[nID] - if !ok { - logrus.Warnf("rmServiceBinding %s %s %s aborted s.loadBalancers[nid] !ok", method, svcName, eID) - return nil - } - - be, ok := lb.backEnds[eID] - if !ok { - logrus.Warnf("rmServiceBinding %s %s %s aborted lb.backEnds[eid] && lb.disabled[eid] !ok", method, svcName, eID) - return nil - } - - if fullRemove { - // delete regardless - delete(lb.backEnds, eID) - } else { - be.disabled = true - } - - if len(lb.backEnds) == 0 { - // All the backends for this service have been - // removed. Time to remove the load balancer and also - // remove the service entry in IPVS. - rmService = true - - delete(s.loadBalancers, nID) - logrus.Debugf("rmServiceBinding %s delete %s, p:%p in loadbalancers len:%d", eID, nID, lb, len(s.loadBalancers)) - } - - ok, entries := s.removeIPToEndpoint(ip.String(), eID) - if !ok || entries > 0 { - setStr, b := s.printIPToEndpoint(ip.String()) - if len(setStr) > maxSetStringLen { - setStr = setStr[:maxSetStringLen] - } - logrus.Warnf("rmServiceBinding %s possible transient state ok:%t entries:%d set:%t %s", eID, ok, entries, b, setStr) - } - - // Remove loadbalancer service(if needed) and backend in all - // sandboxes in the network only if the vip is valid. - if entries == 0 { - // The network may well have been deleted before the last - // of the service bindings. That's ok on Linux because - // removing the network sandbox implicitly removes the - // backend service bindings. Windows VFP cleanup requires - // calling cleanupServiceBindings on the network prior to - // deleting the network, performed by network.delete. - n, err := c.NetworkByID(nID) - if err == nil { - n.(*network).rmLBBackend(ip, lb, rmService, fullRemove) - } - } - - // Delete the name resolutions - if deleteSvcRecords { - c.deleteEndpointNameResolution(svcName, svcID, nID, eID, containerName, vip, serviceAliases, taskAliases, ip, rmService, entries > 0, "rmServiceBinding") - } - - if len(s.loadBalancers) == 0 { - // All loadbalancers for the service removed. Time to - // remove the service itself. - c.Lock() - - // Mark the object as deleted so that the add won't use it wrongly - s.deleted = true - // NOTE The delete from the serviceBindings map has to be the last operation else we are allowing a race between this service - // that is getting deleted and a new service that will be created if the entry is not anymore there - delete(c.serviceBindings, skey) - c.Unlock() - } - - logrus.Debugf("rmServiceBinding from %s END for %s %s", method, svcName, eID) - return nil -} diff --git a/vendor/github.com/docker/libnetwork/service_linux.go b/vendor/github.com/docker/libnetwork/service_linux.go deleted file mode 100644 index 514c65a753..0000000000 --- a/vendor/github.com/docker/libnetwork/service_linux.go +++ /dev/null @@ -1,806 +0,0 @@ -package libnetwork - -import ( - "fmt" - "io" - "io/ioutil" - "net" - "os" - "os/exec" - "path/filepath" - "runtime" - "strconv" - "strings" - "sync" - "syscall" - - "github.com/docker/docker/pkg/reexec" - "github.com/docker/libnetwork/iptables" - "github.com/docker/libnetwork/ns" - "github.com/gogo/protobuf/proto" - "github.com/ishidawataru/sctp" - "github.com/moby/ipvs" - "github.com/sirupsen/logrus" - "github.com/vishvananda/netlink/nl" - "github.com/vishvananda/netns" -) - -func init() { - reexec.Register("fwmarker", fwMarker) - reexec.Register("redirector", redirector) -} - -// Populate all loadbalancers on the network that the passed endpoint -// belongs to, into this sandbox. -func (sb *sandbox) populateLoadBalancers(ep *endpoint) { - // This is an interface less endpoint. Nothing to do. - if ep.Iface() == nil { - return - } - - n := ep.getNetwork() - eIP := ep.Iface().Address() - - if n.ingress { - if err := addRedirectRules(sb.Key(), eIP, ep.ingressPorts); err != nil { - logrus.Errorf("Failed to add redirect rules for ep %s (%.7s): %v", ep.Name(), ep.ID(), err) - } - } -} - -func (n *network) findLBEndpointSandbox() (*endpoint, *sandbox, error) { - // TODO: get endpoint from store? See EndpointInfo() - var ep *endpoint - // Find this node's LB sandbox endpoint: there should be exactly one - for _, e := range n.Endpoints() { - epi := e.Info() - if epi != nil && epi.LoadBalancer() { - ep = e.(*endpoint) - break - } - } - if ep == nil { - return nil, nil, fmt.Errorf("Unable to find load balancing endpoint for network %s", n.ID()) - } - // Get the load balancer sandbox itself as well - sb, ok := ep.getSandbox() - if !ok { - return nil, nil, fmt.Errorf("Unable to get sandbox for %s(%s) in for %s", ep.Name(), ep.ID(), n.ID()) - } - var sep *endpoint - sep = sb.getEndpoint(ep.ID()) - if sep == nil { - return nil, nil, fmt.Errorf("Load balancing endpoint %s(%s) removed from %s", ep.Name(), ep.ID(), n.ID()) - } - return sep, sb, nil -} - -// Searches the OS sandbox for the name of the endpoint interface -// within the sandbox. This is required for adding/removing IP -// aliases to the interface. -func findIfaceDstName(sb *sandbox, ep *endpoint) string { - srcName := ep.Iface().SrcName() - for _, i := range sb.osSbox.Info().Interfaces() { - if i.SrcName() == srcName { - return i.DstName() - } - } - return "" -} - -// Add loadbalancer backend to the loadbalncer sandbox for the network. -// If needed add the service as well. -func (n *network) addLBBackend(ip net.IP, lb *loadBalancer) { - if len(lb.vip) == 0 { - return - } - ep, sb, err := n.findLBEndpointSandbox() - if err != nil { - logrus.Errorf("addLBBackend %s/%s: %v", n.ID(), n.Name(), err) - return - } - if sb.osSbox == nil { - return - } - - eIP := ep.Iface().Address() - - i, err := ipvs.New(sb.Key()) - if err != nil { - logrus.Errorf("Failed to create an ipvs handle for sbox %.7s (%.7s,%s) for lb addition: %v", sb.ID(), sb.ContainerID(), sb.Key(), err) - return - } - defer i.Close() - - s := &ipvs.Service{ - AddressFamily: nl.FAMILY_V4, - FWMark: lb.fwMark, - SchedName: ipvs.RoundRobin, - } - - if !i.IsServicePresent(s) { - // Add IP alias for the VIP to the endpoint - ifName := findIfaceDstName(sb, ep) - if ifName == "" { - logrus.Errorf("Failed find interface name for endpoint %s(%s) to create LB alias", ep.ID(), ep.Name()) - return - } - err := sb.osSbox.AddAliasIP(ifName, &net.IPNet{IP: lb.vip, Mask: net.CIDRMask(32, 32)}) - if err != nil { - logrus.Errorf("Failed add IP alias %s to network %s LB endpoint interface %s: %v", lb.vip, n.ID(), ifName, err) - return - } - - if sb.ingress { - var gwIP net.IP - if ep := sb.getGatewayEndpoint(); ep != nil { - gwIP = ep.Iface().Address().IP - } - if err := programIngress(gwIP, lb.service.ingressPorts, false); err != nil { - logrus.Errorf("Failed to add ingress: %v", err) - return - } - } - - logrus.Debugf("Creating service for vip %s fwMark %d ingressPorts %#v in sbox %.7s (%.7s)", lb.vip, lb.fwMark, lb.service.ingressPorts, sb.ID(), sb.ContainerID()) - if err := invokeFWMarker(sb.Key(), lb.vip, lb.fwMark, lb.service.ingressPorts, eIP, false, n.loadBalancerMode); err != nil { - logrus.Errorf("Failed to add firewall mark rule in sbox %.7s (%.7s): %v", sb.ID(), sb.ContainerID(), err) - return - } - - if err := i.NewService(s); err != nil && err != syscall.EEXIST { - logrus.Errorf("Failed to create a new service for vip %s fwmark %d in sbox %.7s (%.7s): %v", lb.vip, lb.fwMark, sb.ID(), sb.ContainerID(), err) - return - } - } - - d := &ipvs.Destination{ - AddressFamily: nl.FAMILY_V4, - Address: ip, - Weight: 1, - } - if n.loadBalancerMode == loadBalancerModeDSR { - d.ConnectionFlags = ipvs.ConnFwdDirectRoute - } - - // Remove the sched name before using the service to add - // destination. - s.SchedName = "" - if err := i.NewDestination(s, d); err != nil && err != syscall.EEXIST { - logrus.Errorf("Failed to create real server %s for vip %s fwmark %d in sbox %.7s (%.7s): %v", ip, lb.vip, lb.fwMark, sb.ID(), sb.ContainerID(), err) - } -} - -// Remove loadbalancer backend the load balancing endpoint for this -// network. If 'rmService' is true, then remove the service entry as well. -// If 'fullRemove' is true then completely remove the entry, otherwise -// just deweight it for now. -func (n *network) rmLBBackend(ip net.IP, lb *loadBalancer, rmService bool, fullRemove bool) { - if len(lb.vip) == 0 { - return - } - ep, sb, err := n.findLBEndpointSandbox() - if err != nil { - logrus.Debugf("rmLBBackend for %s/%s: %v -- probably transient state", n.ID(), n.Name(), err) - return - } - if sb.osSbox == nil { - return - } - - eIP := ep.Iface().Address() - - i, err := ipvs.New(sb.Key()) - if err != nil { - logrus.Errorf("Failed to create an ipvs handle for sbox %.7s (%.7s,%s) for lb removal: %v", sb.ID(), sb.ContainerID(), sb.Key(), err) - return - } - defer i.Close() - - s := &ipvs.Service{ - AddressFamily: nl.FAMILY_V4, - FWMark: lb.fwMark, - } - - d := &ipvs.Destination{ - AddressFamily: nl.FAMILY_V4, - Address: ip, - Weight: 1, - } - if n.loadBalancerMode == loadBalancerModeDSR { - d.ConnectionFlags = ipvs.ConnFwdDirectRoute - } - - if fullRemove { - if err := i.DelDestination(s, d); err != nil && err != syscall.ENOENT { - logrus.Errorf("Failed to delete real server %s for vip %s fwmark %d in sbox %.7s (%.7s): %v", ip, lb.vip, lb.fwMark, sb.ID(), sb.ContainerID(), err) - } - } else { - d.Weight = 0 - if err := i.UpdateDestination(s, d); err != nil && err != syscall.ENOENT { - logrus.Errorf("Failed to set LB weight of real server %s to 0 for vip %s fwmark %d in sbox %.7s (%.7s): %v", ip, lb.vip, lb.fwMark, sb.ID(), sb.ContainerID(), err) - } - } - - if rmService { - s.SchedName = ipvs.RoundRobin - if err := i.DelService(s); err != nil && err != syscall.ENOENT { - logrus.Errorf("Failed to delete service for vip %s fwmark %d in sbox %.7s (%.7s): %v", lb.vip, lb.fwMark, sb.ID(), sb.ContainerID(), err) - } - - if sb.ingress { - var gwIP net.IP - if ep := sb.getGatewayEndpoint(); ep != nil { - gwIP = ep.Iface().Address().IP - } - if err := programIngress(gwIP, lb.service.ingressPorts, true); err != nil { - logrus.Errorf("Failed to delete ingress: %v", err) - } - } - - if err := invokeFWMarker(sb.Key(), lb.vip, lb.fwMark, lb.service.ingressPorts, eIP, true, n.loadBalancerMode); err != nil { - logrus.Errorf("Failed to delete firewall mark rule in sbox %.7s (%.7s): %v", sb.ID(), sb.ContainerID(), err) - } - - // Remove IP alias from the VIP to the endpoint - ifName := findIfaceDstName(sb, ep) - if ifName == "" { - logrus.Errorf("Failed find interface name for endpoint %s(%s) to create LB alias", ep.ID(), ep.Name()) - return - } - err := sb.osSbox.RemoveAliasIP(ifName, &net.IPNet{IP: lb.vip, Mask: net.CIDRMask(32, 32)}) - if err != nil { - logrus.Errorf("Failed add IP alias %s to network %s LB endpoint interface %s: %v", lb.vip, n.ID(), ifName, err) - } - } -} - -const ingressChain = "DOCKER-INGRESS" - -var ( - ingressOnce sync.Once - ingressMu sync.Mutex // lock for operations on ingress - ingressProxyTbl = make(map[string]io.Closer) - portConfigMu sync.Mutex - portConfigTbl = make(map[PortConfig]int) -) - -func filterPortConfigs(ingressPorts []*PortConfig, isDelete bool) []*PortConfig { - portConfigMu.Lock() - iPorts := make([]*PortConfig, 0, len(ingressPorts)) - for _, pc := range ingressPorts { - if isDelete { - if cnt, ok := portConfigTbl[*pc]; ok { - // This is the last reference to this - // port config. Delete the port config - // and add it to filtered list to be - // plumbed. - if cnt == 1 { - delete(portConfigTbl, *pc) - iPorts = append(iPorts, pc) - continue - } - - portConfigTbl[*pc] = cnt - 1 - } - - continue - } - - if cnt, ok := portConfigTbl[*pc]; ok { - portConfigTbl[*pc] = cnt + 1 - continue - } - - // We are adding it for the first time. Add it to the - // filter list to be plumbed. - portConfigTbl[*pc] = 1 - iPorts = append(iPorts, pc) - } - portConfigMu.Unlock() - - return iPorts -} - -func programIngress(gwIP net.IP, ingressPorts []*PortConfig, isDelete bool) error { - // TODO IPv6 support - iptable := iptables.GetIptable(iptables.IPv4) - - addDelOpt := "-I" - rollbackAddDelOpt := "-D" - if isDelete { - addDelOpt = "-D" - rollbackAddDelOpt = "-I" - } - - ingressMu.Lock() - defer ingressMu.Unlock() - - chainExists := iptable.ExistChain(ingressChain, iptables.Nat) - filterChainExists := iptable.ExistChain(ingressChain, iptables.Filter) - - ingressOnce.Do(func() { - // Flush nat table and filter table ingress chain rules during init if it - // exists. It might contain stale rules from previous life. - if chainExists { - if err := iptable.RawCombinedOutput("-t", "nat", "-F", ingressChain); err != nil { - logrus.Errorf("Could not flush nat table ingress chain rules during init: %v", err) - } - } - if filterChainExists { - if err := iptable.RawCombinedOutput("-F", ingressChain); err != nil { - logrus.Errorf("Could not flush filter table ingress chain rules during init: %v", err) - } - } - }) - - if !isDelete { - if !chainExists { - if err := iptable.RawCombinedOutput("-t", "nat", "-N", ingressChain); err != nil { - return fmt.Errorf("failed to create ingress chain: %v", err) - } - } - if !filterChainExists { - if err := iptable.RawCombinedOutput("-N", ingressChain); err != nil { - return fmt.Errorf("failed to create filter table ingress chain: %v", err) - } - } - - if !iptable.Exists(iptables.Nat, ingressChain, "-j", "RETURN") { - if err := iptable.RawCombinedOutput("-t", "nat", "-A", ingressChain, "-j", "RETURN"); err != nil { - return fmt.Errorf("failed to add return rule in nat table ingress chain: %v", err) - } - } - - if !iptable.Exists(iptables.Filter, ingressChain, "-j", "RETURN") { - if err := iptable.RawCombinedOutput("-A", ingressChain, "-j", "RETURN"); err != nil { - return fmt.Errorf("failed to add return rule to filter table ingress chain: %v", err) - } - } - - for _, chain := range []string{"OUTPUT", "PREROUTING"} { - if !iptable.Exists(iptables.Nat, chain, "-m", "addrtype", "--dst-type", "LOCAL", "-j", ingressChain) { - if err := iptable.RawCombinedOutput("-t", "nat", "-I", chain, "-m", "addrtype", "--dst-type", "LOCAL", "-j", ingressChain); err != nil { - return fmt.Errorf("failed to add jump rule in %s to ingress chain: %v", chain, err) - } - } - } - - if !iptable.Exists(iptables.Filter, "FORWARD", "-j", ingressChain) { - if err := iptable.RawCombinedOutput("-I", "FORWARD", "-j", ingressChain); err != nil { - return fmt.Errorf("failed to add jump rule to %s in filter table forward chain: %v", ingressChain, err) - } - arrangeUserFilterRule() - } - - oifName, err := findOIFName(gwIP) - if err != nil { - return fmt.Errorf("failed to find gateway bridge interface name for %s: %v", gwIP, err) - } - - path := filepath.Join("/proc/sys/net/ipv4/conf", oifName, "route_localnet") - if err := ioutil.WriteFile(path, []byte{'1', '\n'}, 0644); err != nil { - return fmt.Errorf("could not write to %s: %v", path, err) - } - - ruleArgs := strings.Fields(fmt.Sprintf("-m addrtype --src-type LOCAL -o %s -j MASQUERADE", oifName)) - if !iptable.Exists(iptables.Nat, "POSTROUTING", ruleArgs...) { - if err := iptable.RawCombinedOutput(append([]string{"-t", "nat", "-I", "POSTROUTING"}, ruleArgs...)...); err != nil { - return fmt.Errorf("failed to add ingress localhost POSTROUTING rule for %s: %v", oifName, err) - } - } - } - - //Filter the ingress ports until port rules start to be added/deleted - filteredPorts := filterPortConfigs(ingressPorts, isDelete) - rollbackRules := make([][]string, 0, len(filteredPorts)*3) - var portErr error - defer func() { - if portErr != nil && !isDelete { - filterPortConfigs(filteredPorts, !isDelete) - for _, rule := range rollbackRules { - if err := iptable.RawCombinedOutput(rule...); err != nil { - logrus.Warnf("roll back rule failed, %v: %v", rule, err) - } - } - } - }() - - for _, iPort := range filteredPorts { - if iptable.ExistChain(ingressChain, iptables.Nat) { - rule := strings.Fields(fmt.Sprintf("-t nat %s %s -p %s --dport %d -j DNAT --to-destination %s:%d", - addDelOpt, ingressChain, strings.ToLower(PortConfig_Protocol_name[int32(iPort.Protocol)]), iPort.PublishedPort, gwIP, iPort.PublishedPort)) - if portErr = iptable.RawCombinedOutput(rule...); portErr != nil { - errStr := fmt.Sprintf("set up rule failed, %v: %v", rule, portErr) - if !isDelete { - return fmt.Errorf("%s", errStr) - } - logrus.Infof("%s", errStr) - } - rollbackRule := strings.Fields(fmt.Sprintf("-t nat %s %s -p %s --dport %d -j DNAT --to-destination %s:%d", rollbackAddDelOpt, - ingressChain, strings.ToLower(PortConfig_Protocol_name[int32(iPort.Protocol)]), iPort.PublishedPort, gwIP, iPort.PublishedPort)) - rollbackRules = append(rollbackRules, rollbackRule) - } - - // Filter table rules to allow a published service to be accessible in the local node from.. - // 1) service tasks attached to other networks - // 2) unmanaged containers on bridge networks - rule := strings.Fields(fmt.Sprintf("%s %s -m state -p %s --sport %d --state ESTABLISHED,RELATED -j ACCEPT", - addDelOpt, ingressChain, strings.ToLower(PortConfig_Protocol_name[int32(iPort.Protocol)]), iPort.PublishedPort)) - if portErr = iptable.RawCombinedOutput(rule...); portErr != nil { - errStr := fmt.Sprintf("set up rule failed, %v: %v", rule, portErr) - if !isDelete { - return fmt.Errorf("%s", errStr) - } - logrus.Warnf("%s", errStr) - } - rollbackRule := strings.Fields(fmt.Sprintf("%s %s -m state -p %s --sport %d --state ESTABLISHED,RELATED -j ACCEPT", rollbackAddDelOpt, - ingressChain, strings.ToLower(PortConfig_Protocol_name[int32(iPort.Protocol)]), iPort.PublishedPort)) - rollbackRules = append(rollbackRules, rollbackRule) - - rule = strings.Fields(fmt.Sprintf("%s %s -p %s --dport %d -j ACCEPT", - addDelOpt, ingressChain, strings.ToLower(PortConfig_Protocol_name[int32(iPort.Protocol)]), iPort.PublishedPort)) - if portErr = iptable.RawCombinedOutput(rule...); portErr != nil { - errStr := fmt.Sprintf("set up rule failed, %v: %v", rule, portErr) - if !isDelete { - return fmt.Errorf("%s", errStr) - } - logrus.Warnf("%s", errStr) - } - rollbackRule = strings.Fields(fmt.Sprintf("%s %s -p %s --dport %d -j ACCEPT", rollbackAddDelOpt, - ingressChain, strings.ToLower(PortConfig_Protocol_name[int32(iPort.Protocol)]), iPort.PublishedPort)) - rollbackRules = append(rollbackRules, rollbackRule) - - if err := plumbProxy(iPort, isDelete); err != nil { - logrus.Warnf("failed to create proxy for port %d: %v", iPort.PublishedPort, err) - } - } - - return nil -} - -// In the filter table FORWARD chain the first rule should be to jump to -// DOCKER-USER so the user is able to filter packet first. -// The second rule should be jump to INGRESS-CHAIN. -// This chain has the rules to allow access to the published ports for swarm tasks -// from local bridge networks and docker_gwbridge (ie:taks on other swarm networks) -func arrangeIngressFilterRule() { - // TODO IPv6 support - iptable := iptables.GetIptable(iptables.IPv4) - if iptable.ExistChain(ingressChain, iptables.Filter) { - if iptable.Exists(iptables.Filter, "FORWARD", "-j", ingressChain) { - if err := iptable.RawCombinedOutput("-D", "FORWARD", "-j", ingressChain); err != nil { - logrus.Warnf("failed to delete jump rule to ingressChain in filter table: %v", err) - } - } - if err := iptable.RawCombinedOutput("-I", "FORWARD", "-j", ingressChain); err != nil { - logrus.Warnf("failed to add jump rule to ingressChain in filter table: %v", err) - } - } -} - -func findOIFName(ip net.IP) (string, error) { - nlh := ns.NlHandle() - - routes, err := nlh.RouteGet(ip) - if err != nil { - return "", err - } - - if len(routes) == 0 { - return "", fmt.Errorf("no route to %s", ip) - } - - // Pick the first route(typically there is only one route). We - // don't support multipath. - link, err := nlh.LinkByIndex(routes[0].LinkIndex) - if err != nil { - return "", err - } - - return link.Attrs().Name, nil -} - -func plumbProxy(iPort *PortConfig, isDelete bool) error { - var ( - err error - l io.Closer - ) - - portSpec := fmt.Sprintf("%d/%s", iPort.PublishedPort, strings.ToLower(PortConfig_Protocol_name[int32(iPort.Protocol)])) - if isDelete { - if listener, ok := ingressProxyTbl[portSpec]; ok { - if listener != nil { - listener.Close() - } - } - - return nil - } - - switch iPort.Protocol { - case ProtocolTCP: - l, err = net.ListenTCP("tcp", &net.TCPAddr{Port: int(iPort.PublishedPort)}) - case ProtocolUDP: - l, err = net.ListenUDP("udp", &net.UDPAddr{Port: int(iPort.PublishedPort)}) - case ProtocolSCTP: - l, err = sctp.ListenSCTP("sctp", &sctp.SCTPAddr{Port: int(iPort.PublishedPort)}) - default: - err = fmt.Errorf("unknown protocol %v", iPort.Protocol) - } - - if err != nil { - return err - } - - ingressProxyTbl[portSpec] = l - - return nil -} - -func writePortsToFile(ports []*PortConfig) (string, error) { - f, err := ioutil.TempFile("", "port_configs") - if err != nil { - return "", err - } - defer f.Close() - - buf, _ := proto.Marshal(&EndpointRecord{ - IngressPorts: ports, - }) - - n, err := f.Write(buf) - if err != nil { - return "", err - } - - if n < len(buf) { - return "", io.ErrShortWrite - } - - return f.Name(), nil -} - -func readPortsFromFile(fileName string) ([]*PortConfig, error) { - buf, err := ioutil.ReadFile(fileName) - if err != nil { - return nil, err - } - - var epRec EndpointRecord - err = proto.Unmarshal(buf, &epRec) - if err != nil { - return nil, err - } - - return epRec.IngressPorts, nil -} - -// Invoke fwmarker reexec routine to mark vip destined packets with -// the passed firewall mark. -func invokeFWMarker(path string, vip net.IP, fwMark uint32, ingressPorts []*PortConfig, eIP *net.IPNet, isDelete bool, lbMode string) error { - var ingressPortsFile string - - if len(ingressPorts) != 0 { - var err error - ingressPortsFile, err = writePortsToFile(ingressPorts) - if err != nil { - return err - } - - defer os.Remove(ingressPortsFile) - } - - addDelOpt := "-A" - if isDelete { - addDelOpt = "-D" - } - - cmd := &exec.Cmd{ - Path: reexec.Self(), - Args: append([]string{"fwmarker"}, path, vip.String(), fmt.Sprintf("%d", fwMark), addDelOpt, ingressPortsFile, eIP.String(), lbMode), - Stdout: os.Stdout, - Stderr: os.Stderr, - } - - if err := cmd.Run(); err != nil { - return fmt.Errorf("reexec failed: %v", err) - } - - return nil -} - -// Firewall marker reexec function. -func fwMarker() { - // TODO IPv6 support - iptable := iptables.GetIptable(iptables.IPv4) - runtime.LockOSThread() - defer runtime.UnlockOSThread() - - if len(os.Args) < 8 { - logrus.Error("invalid number of arguments..") - os.Exit(1) - } - - var ingressPorts []*PortConfig - if os.Args[5] != "" { - var err error - ingressPorts, err = readPortsFromFile(os.Args[5]) - if err != nil { - logrus.Errorf("Failed reading ingress ports file: %v", err) - os.Exit(2) - } - } - - vip := os.Args[2] - fwMark, err := strconv.ParseUint(os.Args[3], 10, 32) - if err != nil { - logrus.Errorf("bad fwmark value(%s) passed: %v", os.Args[3], err) - os.Exit(3) - } - addDelOpt := os.Args[4] - - rules := [][]string{} - for _, iPort := range ingressPorts { - rule := strings.Fields(fmt.Sprintf("-t mangle %s PREROUTING -p %s --dport %d -j MARK --set-mark %d", - addDelOpt, strings.ToLower(PortConfig_Protocol_name[int32(iPort.Protocol)]), iPort.PublishedPort, fwMark)) - rules = append(rules, rule) - } - - ns, err := netns.GetFromPath(os.Args[1]) - if err != nil { - logrus.Errorf("failed get network namespace %q: %v", os.Args[1], err) - os.Exit(4) - } - defer ns.Close() - - if err := netns.Set(ns); err != nil { - logrus.Errorf("setting into container net ns %v failed, %v", os.Args[1], err) - os.Exit(5) - } - - lbMode := os.Args[7] - if addDelOpt == "-A" && lbMode == loadBalancerModeNAT { - eIP, subnet, err := net.ParseCIDR(os.Args[6]) - if err != nil { - logrus.Errorf("Failed to parse endpoint IP %s: %v", os.Args[6], err) - os.Exit(6) - } - - ruleParams := strings.Fields(fmt.Sprintf("-m ipvs --ipvs -d %s -j SNAT --to-source %s", subnet, eIP)) - if !iptable.Exists("nat", "POSTROUTING", ruleParams...) { - rule := append(strings.Fields("-t nat -A POSTROUTING"), ruleParams...) - rules = append(rules, rule) - - err := ioutil.WriteFile("/proc/sys/net/ipv4/vs/conntrack", []byte{'1', '\n'}, 0644) - if err != nil { - logrus.Errorf("Failed to write to /proc/sys/net/ipv4/vs/conntrack: %v", err) - os.Exit(7) - } - } - } - - rule := strings.Fields(fmt.Sprintf("-t mangle %s INPUT -d %s/32 -j MARK --set-mark %d", addDelOpt, vip, fwMark)) - rules = append(rules, rule) - - for _, rule := range rules { - if err := iptable.RawCombinedOutputNative(rule...); err != nil { - logrus.Errorf("set up rule failed, %v: %v", rule, err) - os.Exit(8) - } - } -} - -func addRedirectRules(path string, eIP *net.IPNet, ingressPorts []*PortConfig) error { - var ingressPortsFile string - - if len(ingressPorts) != 0 { - var err error - ingressPortsFile, err = writePortsToFile(ingressPorts) - if err != nil { - return err - } - defer os.Remove(ingressPortsFile) - } - - cmd := &exec.Cmd{ - Path: reexec.Self(), - Args: append([]string{"redirector"}, path, eIP.String(), ingressPortsFile), - Stdout: os.Stdout, - Stderr: os.Stderr, - } - - if err := cmd.Run(); err != nil { - return fmt.Errorf("reexec failed: %v", err) - } - - return nil -} - -// Redirector reexec function. -func redirector() { - // TODO IPv6 support - iptable := iptables.GetIptable(iptables.IPv4) - runtime.LockOSThread() - defer runtime.UnlockOSThread() - - if len(os.Args) < 4 { - logrus.Error("invalid number of arguments..") - os.Exit(1) - } - - var ingressPorts []*PortConfig - if os.Args[3] != "" { - var err error - ingressPorts, err = readPortsFromFile(os.Args[3]) - if err != nil { - logrus.Errorf("Failed reading ingress ports file: %v", err) - os.Exit(2) - } - } - - eIP, _, err := net.ParseCIDR(os.Args[2]) - if err != nil { - logrus.Errorf("Failed to parse endpoint IP %s: %v", os.Args[2], err) - os.Exit(3) - } - - rules := [][]string{} - for _, iPort := range ingressPorts { - rule := strings.Fields(fmt.Sprintf("-t nat -A PREROUTING -d %s -p %s --dport %d -j REDIRECT --to-port %d", - eIP.String(), strings.ToLower(PortConfig_Protocol_name[int32(iPort.Protocol)]), iPort.PublishedPort, iPort.TargetPort)) - rules = append(rules, rule) - // Allow only incoming connections to exposed ports - iRule := strings.Fields(fmt.Sprintf("-I INPUT -d %s -p %s --dport %d -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT", - eIP.String(), strings.ToLower(PortConfig_Protocol_name[int32(iPort.Protocol)]), iPort.TargetPort)) - rules = append(rules, iRule) - // Allow only outgoing connections from exposed ports - oRule := strings.Fields(fmt.Sprintf("-I OUTPUT -s %s -p %s --sport %d -m conntrack --ctstate ESTABLISHED -j ACCEPT", - eIP.String(), strings.ToLower(PortConfig_Protocol_name[int32(iPort.Protocol)]), iPort.TargetPort)) - rules = append(rules, oRule) - } - - ns, err := netns.GetFromPath(os.Args[1]) - if err != nil { - logrus.Errorf("failed get network namespace %q: %v", os.Args[1], err) - os.Exit(4) - } - defer ns.Close() - - if err := netns.Set(ns); err != nil { - logrus.Errorf("setting into container net ns %v failed, %v", os.Args[1], err) - os.Exit(5) - } - - for _, rule := range rules { - if err := iptable.RawCombinedOutputNative(rule...); err != nil { - logrus.Errorf("set up rule failed, %v: %v", rule, err) - os.Exit(6) - } - } - - if len(ingressPorts) == 0 { - return - } - - // Ensure blocking rules for anything else in/to ingress network - for _, rule := range [][]string{ - {"-d", eIP.String(), "-p", "sctp", "-j", "DROP"}, - {"-d", eIP.String(), "-p", "udp", "-j", "DROP"}, - {"-d", eIP.String(), "-p", "tcp", "-j", "DROP"}, - } { - if !iptable.ExistsNative(iptables.Filter, "INPUT", rule...) { - if err := iptable.RawCombinedOutputNative(append([]string{"-A", "INPUT"}, rule...)...); err != nil { - logrus.Errorf("set up rule failed, %v: %v", rule, err) - os.Exit(7) - } - } - rule[0] = "-s" - if !iptable.ExistsNative(iptables.Filter, "OUTPUT", rule...) { - if err := iptable.RawCombinedOutputNative(append([]string{"-A", "OUTPUT"}, rule...)...); err != nil { - logrus.Errorf("set up rule failed, %v: %v", rule, err) - os.Exit(8) - } - } - } -} diff --git a/vendor/github.com/docker/libnetwork/service_unsupported.go b/vendor/github.com/docker/libnetwork/service_unsupported.go deleted file mode 100644 index ee9750600c..0000000000 --- a/vendor/github.com/docker/libnetwork/service_unsupported.go +++ /dev/null @@ -1,25 +0,0 @@ -// +build !linux,!windows - -package libnetwork - -import ( - "fmt" - "net" -) - -func (c *controller) cleanupServiceBindings(nid string) { -} - -func (c *controller) addServiceBinding(name, sid, nid, eid string, vip net.IP, ingressPorts []*PortConfig, aliases []string, ip net.IP) error { - return fmt.Errorf("not supported") -} - -func (c *controller) rmServiceBinding(name, sid, nid, eid string, vip net.IP, ingressPorts []*PortConfig, aliases []string, ip net.IP) error { - return fmt.Errorf("not supported") -} - -func (sb *sandbox) populateLoadBalancers(ep *endpoint) { -} - -func arrangeIngressFilterRule() { -} diff --git a/vendor/github.com/docker/libnetwork/service_windows.go b/vendor/github.com/docker/libnetwork/service_windows.go deleted file mode 100644 index 7f8eb5366a..0000000000 --- a/vendor/github.com/docker/libnetwork/service_windows.go +++ /dev/null @@ -1,173 +0,0 @@ -package libnetwork - -import ( - "net" - - "github.com/Microsoft/hcsshim" - "github.com/Microsoft/hcsshim/osversion" - "github.com/sirupsen/logrus" -) - -type policyLists struct { - ilb *hcsshim.PolicyList - elb *hcsshim.PolicyList -} - -var lbPolicylistMap map[*loadBalancer]*policyLists - -func init() { - lbPolicylistMap = make(map[*loadBalancer]*policyLists) -} - -func (n *network) addLBBackend(ip net.IP, lb *loadBalancer) { - if len(lb.vip) == 0 { - return - } - - vip := lb.vip - ingressPorts := lb.service.ingressPorts - - if osversion.Build() > 16236 { - lb.Lock() - defer lb.Unlock() - //find the load balancer IP for the network. - var sourceVIP string - for _, e := range n.Endpoints() { - epInfo := e.Info() - if epInfo == nil { - continue - } - if epInfo.LoadBalancer() { - sourceVIP = epInfo.Iface().Address().IP.String() - break - } - } - - if sourceVIP == "" { - logrus.Errorf("Failed to find load balancer IP for network %s", n.Name()) - return - } - - var endpoints []hcsshim.HNSEndpoint - - for eid, be := range lb.backEnds { - if be.disabled { - continue - } - //Call HNS to get back ID (GUID) corresponding to the endpoint. - hnsEndpoint, err := hcsshim.GetHNSEndpointByName(eid) - if err != nil { - logrus.Errorf("Failed to find HNS ID for endpoint %v: %v", eid, err) - return - } - - endpoints = append(endpoints, *hnsEndpoint) - } - - if policies, ok := lbPolicylistMap[lb]; ok { - - if policies.ilb != nil { - policies.ilb.Delete() - policies.ilb = nil - } - - if policies.elb != nil { - policies.elb.Delete() - policies.elb = nil - } - delete(lbPolicylistMap, lb) - } - - ilbPolicy, err := hcsshim.AddLoadBalancer(endpoints, true, sourceVIP, vip.String(), 0, 0, 0) - if err != nil { - logrus.Errorf("Failed to add ILB policy for service %s (%s) with endpoints %v using load balancer IP %s on network %s: %v", - lb.service.name, vip.String(), endpoints, sourceVIP, n.Name(), err) - return - } - - lbPolicylistMap[lb] = &policyLists{ - ilb: ilbPolicy, - } - - publishedPorts := make(map[uint32]uint32) - - for i, port := range ingressPorts { - protocol := uint16(6) - - // Skip already published port - if publishedPorts[port.PublishedPort] == port.TargetPort { - continue - } - - if port.Protocol == ProtocolUDP { - protocol = 17 - } - - // check if already has udp matching to add wild card publishing - for j := i + 1; j < len(ingressPorts); j++ { - if ingressPorts[j].TargetPort == port.TargetPort && - ingressPorts[j].PublishedPort == port.PublishedPort { - protocol = 0 - } - } - - publishedPorts[port.PublishedPort] = port.TargetPort - - lbPolicylistMap[lb].elb, err = hcsshim.AddLoadBalancer(endpoints, false, sourceVIP, "", protocol, uint16(port.TargetPort), uint16(port.PublishedPort)) - if err != nil { - logrus.Errorf("Failed to add ELB policy for service %s (ip:%s target port:%v published port:%v) with endpoints %v using load balancer IP %s on network %s: %v", - lb.service.name, vip.String(), uint16(port.TargetPort), uint16(port.PublishedPort), endpoints, sourceVIP, n.Name(), err) - return - } - } - } -} - -func (n *network) rmLBBackend(ip net.IP, lb *loadBalancer, rmService bool, fullRemove bool) { - if len(lb.vip) == 0 { - return - } - - if osversion.Build() > 16236 { - if numEnabledBackends(lb) > 0 { - //Reprogram HNS (actually VFP) with the existing backends. - n.addLBBackend(ip, lb) - } else { - lb.Lock() - defer lb.Unlock() - logrus.Debugf("No more backends for service %s (ip:%s). Removing all policies", lb.service.name, lb.vip.String()) - - if policyLists, ok := lbPolicylistMap[lb]; ok { - if policyLists.ilb != nil { - policyLists.ilb.Delete() - policyLists.ilb = nil - } - - if policyLists.elb != nil { - policyLists.elb.Delete() - policyLists.elb = nil - } - delete(lbPolicylistMap, lb) - - } else { - logrus.Errorf("Failed to find policies for service %s (%s)", lb.service.name, lb.vip.String()) - } - } - } -} - -func numEnabledBackends(lb *loadBalancer) int { - nEnabled := 0 - for _, be := range lb.backEnds { - if !be.disabled { - nEnabled++ - } - } - return nEnabled -} - -func (sb *sandbox) populateLoadBalancers(ep *endpoint) { -} - -func arrangeIngressFilterRule() { -} diff --git a/vendor/github.com/docker/libnetwork/store.go b/vendor/github.com/docker/libnetwork/store.go deleted file mode 100644 index 1b850104e9..0000000000 --- a/vendor/github.com/docker/libnetwork/store.go +++ /dev/null @@ -1,468 +0,0 @@ -package libnetwork - -import ( - "fmt" - "strings" - - "github.com/docker/libkv/store/boltdb" - "github.com/docker/libkv/store/consul" - "github.com/docker/libkv/store/etcd" - "github.com/docker/libkv/store/zookeeper" - "github.com/docker/libnetwork/datastore" - "github.com/sirupsen/logrus" -) - -func registerKVStores() { - consul.Register() - zookeeper.Register() - etcd.Register() - boltdb.Register() -} - -func (c *controller) initScopedStore(scope string, scfg *datastore.ScopeCfg) error { - store, err := datastore.NewDataStore(scope, scfg) - if err != nil { - return err - } - c.Lock() - c.stores = append(c.stores, store) - c.Unlock() - - return nil -} - -func (c *controller) initStores() error { - registerKVStores() - - c.Lock() - if c.cfg == nil { - c.Unlock() - return nil - } - scopeConfigs := c.cfg.Scopes - c.stores = nil - c.Unlock() - - for scope, scfg := range scopeConfigs { - if err := c.initScopedStore(scope, scfg); err != nil { - return err - } - } - - c.startWatch() - return nil -} - -func (c *controller) closeStores() { - for _, store := range c.getStores() { - store.Close() - } -} - -func (c *controller) getStore(scope string) datastore.DataStore { - c.Lock() - defer c.Unlock() - - for _, store := range c.stores { - if store.Scope() == scope { - return store - } - } - - return nil -} - -func (c *controller) getStores() []datastore.DataStore { - c.Lock() - defer c.Unlock() - - return c.stores -} - -func (c *controller) getNetworkFromStore(nid string) (*network, error) { - for _, n := range c.getNetworksFromStore() { - if n.id == nid { - return n, nil - } - } - return nil, ErrNoSuchNetwork(nid) -} - -func (c *controller) getNetworksForScope(scope string) ([]*network, error) { - var nl []*network - - store := c.getStore(scope) - if store == nil { - return nil, nil - } - - kvol, err := store.List(datastore.Key(datastore.NetworkKeyPrefix), - &network{ctrlr: c}) - if err != nil && err != datastore.ErrKeyNotFound { - return nil, fmt.Errorf("failed to get networks for scope %s: %v", - scope, err) - } - - for _, kvo := range kvol { - n := kvo.(*network) - n.ctrlr = c - - ec := &endpointCnt{n: n} - err = store.GetObject(datastore.Key(ec.Key()...), ec) - if err != nil && !n.inDelete { - logrus.Warnf("Could not find endpoint count key %s for network %s while listing: %v", datastore.Key(ec.Key()...), n.Name(), err) - continue - } - - n.epCnt = ec - if n.scope == "" { - n.scope = scope - } - nl = append(nl, n) - } - - return nl, nil -} - -func (c *controller) getNetworksFromStore() []*network { - var nl []*network - - for _, store := range c.getStores() { - kvol, err := store.List(datastore.Key(datastore.NetworkKeyPrefix), &network{ctrlr: c}) - // Continue searching in the next store if no keys found in this store - if err != nil { - if err != datastore.ErrKeyNotFound { - logrus.Debugf("failed to get networks for scope %s: %v", store.Scope(), err) - } - continue - } - - kvep, err := store.Map(datastore.Key(epCntKeyPrefix), &endpointCnt{}) - if err != nil && err != datastore.ErrKeyNotFound { - logrus.Warnf("failed to get endpoint_count map for scope %s: %v", store.Scope(), err) - } - - for _, kvo := range kvol { - n := kvo.(*network) - n.Lock() - n.ctrlr = c - ec := &endpointCnt{n: n} - // Trim the leading & trailing "/" to make it consistent across all stores - if val, ok := kvep[strings.Trim(datastore.Key(ec.Key()...), "/")]; ok { - ec = val.(*endpointCnt) - ec.n = n - n.epCnt = ec - } - if n.scope == "" { - n.scope = store.Scope() - } - n.Unlock() - nl = append(nl, n) - } - } - - return nl -} - -func (n *network) getEndpointFromStore(eid string) (*endpoint, error) { - var errors []string - for _, store := range n.ctrlr.getStores() { - ep := &endpoint{id: eid, network: n} - err := store.GetObject(datastore.Key(ep.Key()...), ep) - // Continue searching in the next store if the key is not found in this store - if err != nil { - if err != datastore.ErrKeyNotFound { - errors = append(errors, fmt.Sprintf("{%s:%v}, ", store.Scope(), err)) - logrus.Debugf("could not find endpoint %s in %s: %v", eid, store.Scope(), err) - } - continue - } - return ep, nil - } - return nil, fmt.Errorf("could not find endpoint %s: %v", eid, errors) -} - -func (n *network) getEndpointsFromStore() ([]*endpoint, error) { - var epl []*endpoint - - tmp := endpoint{network: n} - for _, store := range n.getController().getStores() { - kvol, err := store.List(datastore.Key(tmp.KeyPrefix()...), &endpoint{network: n}) - // Continue searching in the next store if no keys found in this store - if err != nil { - if err != datastore.ErrKeyNotFound { - logrus.Debugf("failed to get endpoints for network %s scope %s: %v", - n.Name(), store.Scope(), err) - } - continue - } - - for _, kvo := range kvol { - ep := kvo.(*endpoint) - epl = append(epl, ep) - } - } - - return epl, nil -} - -func (c *controller) updateToStore(kvObject datastore.KVObject) error { - cs := c.getStore(kvObject.DataScope()) - if cs == nil { - return ErrDataStoreNotInitialized(kvObject.DataScope()) - } - - if err := cs.PutObjectAtomic(kvObject); err != nil { - if err == datastore.ErrKeyModified { - return err - } - return fmt.Errorf("failed to update store for object type %T: %v", kvObject, err) - } - - return nil -} - -func (c *controller) deleteFromStore(kvObject datastore.KVObject) error { - cs := c.getStore(kvObject.DataScope()) - if cs == nil { - return ErrDataStoreNotInitialized(kvObject.DataScope()) - } - -retry: - if err := cs.DeleteObjectAtomic(kvObject); err != nil { - if err == datastore.ErrKeyModified { - if err := cs.GetObject(datastore.Key(kvObject.Key()...), kvObject); err != nil { - return fmt.Errorf("could not update the kvobject to latest when trying to delete: %v", err) - } - logrus.Warnf("Error (%v) deleting object %v, retrying....", err, kvObject.Key()) - goto retry - } - return err - } - - return nil -} - -type netWatch struct { - localEps map[string]*endpoint - remoteEps map[string]*endpoint - stopCh chan struct{} -} - -func (c *controller) getLocalEps(nw *netWatch) []*endpoint { - c.Lock() - defer c.Unlock() - - var epl []*endpoint - for _, ep := range nw.localEps { - epl = append(epl, ep) - } - - return epl -} - -func (c *controller) watchSvcRecord(ep *endpoint) { - c.watchCh <- ep -} - -func (c *controller) unWatchSvcRecord(ep *endpoint) { - c.unWatchCh <- ep -} - -func (c *controller) networkWatchLoop(nw *netWatch, ep *endpoint, ecCh <-chan datastore.KVObject) { - for { - select { - case <-nw.stopCh: - return - case o := <-ecCh: - ec := o.(*endpointCnt) - - epl, err := ec.n.getEndpointsFromStore() - if err != nil { - break - } - - c.Lock() - var addEp []*endpoint - - delEpMap := make(map[string]*endpoint) - renameEpMap := make(map[string]bool) - for k, v := range nw.remoteEps { - delEpMap[k] = v - } - - for _, lEp := range epl { - if _, ok := nw.localEps[lEp.ID()]; ok { - continue - } - - if ep, ok := nw.remoteEps[lEp.ID()]; ok { - // On a container rename EP ID will remain - // the same but the name will change. service - // records should reflect the change. - // Keep old EP entry in the delEpMap and add - // EP from the store (which has the new name) - // into the new list - if lEp.name == ep.name { - delete(delEpMap, lEp.ID()) - continue - } - renameEpMap[lEp.ID()] = true - } - nw.remoteEps[lEp.ID()] = lEp - addEp = append(addEp, lEp) - } - - // EPs whose name are to be deleted from the svc records - // should also be removed from nw's remote EP list, except - // the ones that are getting renamed. - for _, lEp := range delEpMap { - if !renameEpMap[lEp.ID()] { - delete(nw.remoteEps, lEp.ID()) - } - } - c.Unlock() - - for _, lEp := range delEpMap { - ep.getNetwork().updateSvcRecord(lEp, c.getLocalEps(nw), false) - - } - for _, lEp := range addEp { - ep.getNetwork().updateSvcRecord(lEp, c.getLocalEps(nw), true) - } - } - } -} - -func (c *controller) processEndpointCreate(nmap map[string]*netWatch, ep *endpoint) { - n := ep.getNetwork() - if !c.isDistributedControl() && n.Scope() == datastore.SwarmScope && n.driverIsMultihost() { - return - } - - c.Lock() - nw, ok := nmap[n.ID()] - c.Unlock() - - if ok { - // Update the svc db for the local endpoint join right away - n.updateSvcRecord(ep, c.getLocalEps(nw), true) - - c.Lock() - nw.localEps[ep.ID()] = ep - - // If we had learned that from the kv store remove it - // from remote ep list now that we know that this is - // indeed a local endpoint - delete(nw.remoteEps, ep.ID()) - c.Unlock() - return - } - - nw = &netWatch{ - localEps: make(map[string]*endpoint), - remoteEps: make(map[string]*endpoint), - } - - // Update the svc db for the local endpoint join right away - // Do this before adding this ep to localEps so that we don't - // try to update this ep's container's svc records - n.updateSvcRecord(ep, c.getLocalEps(nw), true) - - c.Lock() - nw.localEps[ep.ID()] = ep - nmap[n.ID()] = nw - nw.stopCh = make(chan struct{}) - c.Unlock() - - store := c.getStore(n.DataScope()) - if store == nil { - return - } - - if !store.Watchable() { - return - } - - ch, err := store.Watch(n.getEpCnt(), nw.stopCh) - if err != nil { - logrus.Warnf("Error creating watch for network: %v", err) - return - } - - go c.networkWatchLoop(nw, ep, ch) -} - -func (c *controller) processEndpointDelete(nmap map[string]*netWatch, ep *endpoint) { - n := ep.getNetwork() - if !c.isDistributedControl() && n.Scope() == datastore.SwarmScope && n.driverIsMultihost() { - return - } - - c.Lock() - nw, ok := nmap[n.ID()] - - if ok { - delete(nw.localEps, ep.ID()) - c.Unlock() - - // Update the svc db about local endpoint leave right away - // Do this after we remove this ep from localEps so that we - // don't try to remove this svc record from this ep's container. - n.updateSvcRecord(ep, c.getLocalEps(nw), false) - - c.Lock() - if len(nw.localEps) == 0 { - close(nw.stopCh) - - // This is the last container going away for the network. Destroy - // this network's svc db entry - delete(c.svcRecords, n.ID()) - - delete(nmap, n.ID()) - } - } - c.Unlock() -} - -func (c *controller) watchLoop() { - for { - select { - case ep := <-c.watchCh: - c.processEndpointCreate(c.nmap, ep) - case ep := <-c.unWatchCh: - c.processEndpointDelete(c.nmap, ep) - } - } -} - -func (c *controller) startWatch() { - if c.watchCh != nil { - return - } - c.watchCh = make(chan *endpoint) - c.unWatchCh = make(chan *endpoint) - c.nmap = make(map[string]*netWatch) - - go c.watchLoop() -} - -func (c *controller) networkCleanup() { - for _, n := range c.getNetworksFromStore() { - if n.inDelete { - logrus.Infof("Removing stale network %s (%s)", n.Name(), n.ID()) - if err := n.delete(true, true); err != nil { - logrus.Debugf("Error while removing stale network: %v", err) - } - } - } -} - -var populateSpecial NetworkWalker = func(nw Network) bool { - if n := nw.(*network); n.hasSpecialDriver() && !n.ConfigOnly() { - if err := n.getController().addNetwork(n); err != nil { - logrus.Warnf("Failed to populate network %q with driver %q", nw.Name(), nw.Type()) - } - } - return false -} diff --git a/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/drivers_darwin.go b/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/drivers_darwin.go index 8cbedbd6b8..1767ee0f1c 100644 --- a/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/drivers_darwin.go +++ b/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/drivers_darwin.go @@ -1,8 +1,8 @@ package cnmallocator import ( - "github.com/docker/libnetwork/drivers/overlay/ovmanager" - "github.com/docker/libnetwork/drivers/remote" + "github.com/docker/docker/libnetwork/drivers/overlay/ovmanager" + "github.com/docker/docker/libnetwork/drivers/remote" "github.com/docker/swarmkit/manager/allocator/networkallocator" ) diff --git a/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/drivers_ipam.go b/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/drivers_ipam.go index 8307dd3497..1b9617d31e 100644 --- a/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/drivers_ipam.go +++ b/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/drivers_ipam.go @@ -4,12 +4,12 @@ import ( "strconv" "strings" - "github.com/docker/libnetwork/drvregistry" - "github.com/docker/libnetwork/ipamapi" - builtinIpam "github.com/docker/libnetwork/ipams/builtin" - nullIpam "github.com/docker/libnetwork/ipams/null" - remoteIpam "github.com/docker/libnetwork/ipams/remote" - "github.com/docker/libnetwork/ipamutils" + "github.com/docker/docker/libnetwork/drvregistry" + "github.com/docker/docker/libnetwork/ipamapi" + builtinIpam "github.com/docker/docker/libnetwork/ipams/builtin" + nullIpam "github.com/docker/docker/libnetwork/ipams/null" + remoteIpam "github.com/docker/docker/libnetwork/ipams/remote" + "github.com/docker/docker/libnetwork/ipamutils" "github.com/sirupsen/logrus" ) diff --git a/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/drivers_network_linux.go b/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/drivers_network_linux.go index 5d6a0e74bf..9d3b0e51cb 100644 --- a/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/drivers_network_linux.go +++ b/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/drivers_network_linux.go @@ -1,12 +1,12 @@ package cnmallocator import ( - "github.com/docker/libnetwork/drivers/bridge/brmanager" - "github.com/docker/libnetwork/drivers/host" - "github.com/docker/libnetwork/drivers/ipvlan/ivmanager" - "github.com/docker/libnetwork/drivers/macvlan/mvmanager" - "github.com/docker/libnetwork/drivers/overlay/ovmanager" - "github.com/docker/libnetwork/drivers/remote" + "github.com/docker/docker/libnetwork/drivers/bridge/brmanager" + "github.com/docker/docker/libnetwork/drivers/host" + "github.com/docker/docker/libnetwork/drivers/ipvlan/ivmanager" + "github.com/docker/docker/libnetwork/drivers/macvlan/mvmanager" + "github.com/docker/docker/libnetwork/drivers/overlay/ovmanager" + "github.com/docker/docker/libnetwork/drivers/remote" "github.com/docker/swarmkit/manager/allocator/networkallocator" ) diff --git a/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/drivers_network_windows.go b/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/drivers_network_windows.go index 8cbedbd6b8..1767ee0f1c 100644 --- a/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/drivers_network_windows.go +++ b/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/drivers_network_windows.go @@ -1,8 +1,8 @@ package cnmallocator import ( - "github.com/docker/libnetwork/drivers/overlay/ovmanager" - "github.com/docker/libnetwork/drivers/remote" + "github.com/docker/docker/libnetwork/drivers/overlay/ovmanager" + "github.com/docker/docker/libnetwork/drivers/remote" "github.com/docker/swarmkit/manager/allocator/networkallocator" ) diff --git a/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/networkallocator.go b/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/networkallocator.go index 4df84d974a..c8ee94c8f1 100644 --- a/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/networkallocator.go +++ b/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/networkallocator.go @@ -7,11 +7,11 @@ import ( "strings" "github.com/docker/docker/pkg/plugingetter" - "github.com/docker/libnetwork/datastore" - "github.com/docker/libnetwork/driverapi" - "github.com/docker/libnetwork/drvregistry" - "github.com/docker/libnetwork/ipamapi" - "github.com/docker/libnetwork/netlabel" + "github.com/docker/docker/libnetwork/datastore" + "github.com/docker/docker/libnetwork/driverapi" + "github.com/docker/docker/libnetwork/drvregistry" + "github.com/docker/docker/libnetwork/ipamapi" + "github.com/docker/docker/libnetwork/netlabel" "github.com/docker/swarmkit/api" "github.com/docker/swarmkit/log" "github.com/docker/swarmkit/manager/allocator/networkallocator" diff --git a/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/portallocator.go b/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/portallocator.go index 81447cbdb4..f5e4b60bd1 100644 --- a/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/portallocator.go +++ b/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/portallocator.go @@ -3,7 +3,7 @@ package cnmallocator import ( "fmt" - "github.com/docker/libnetwork/idm" + "github.com/docker/docker/libnetwork/idm" "github.com/docker/swarmkit/api" ) diff --git a/vendor/github.com/docker/swarmkit/manager/controlapi/common.go b/vendor/github.com/docker/swarmkit/manager/controlapi/common.go index 9e52179464..b410e6b544 100644 --- a/vendor/github.com/docker/swarmkit/manager/controlapi/common.go +++ b/vendor/github.com/docker/swarmkit/manager/controlapi/common.go @@ -5,8 +5,8 @@ import ( "strings" "github.com/docker/docker/pkg/plugingetter" - "github.com/docker/libnetwork/driverapi" - "github.com/docker/libnetwork/ipamapi" + "github.com/docker/docker/libnetwork/driverapi" + "github.com/docker/docker/libnetwork/ipamapi" "github.com/docker/swarmkit/api" "github.com/docker/swarmkit/manager/allocator" "github.com/docker/swarmkit/manager/state/store" diff --git a/vendor/github.com/docker/swarmkit/manager/controlapi/network.go b/vendor/github.com/docker/swarmkit/manager/controlapi/network.go index d3047fec72..09dc63b126 100644 --- a/vendor/github.com/docker/swarmkit/manager/controlapi/network.go +++ b/vendor/github.com/docker/swarmkit/manager/controlapi/network.go @@ -5,8 +5,8 @@ import ( "net" "github.com/docker/docker/pkg/plugingetter" - "github.com/docker/libnetwork/driverapi" - "github.com/docker/libnetwork/ipamapi" + "github.com/docker/docker/libnetwork/driverapi" + "github.com/docker/docker/libnetwork/ipamapi" "github.com/docker/swarmkit/api" "github.com/docker/swarmkit/identity" "github.com/docker/swarmkit/manager/allocator" diff --git a/vendor/github.com/docker/swarmkit/node/node.go b/vendor/github.com/docker/swarmkit/node/node.go index 7235da66f4..4c4f84e3c6 100644 --- a/vendor/github.com/docker/swarmkit/node/node.go +++ b/vendor/github.com/docker/swarmkit/node/node.go @@ -21,7 +21,7 @@ import ( "github.com/docker/docker/pkg/plugingetter" "github.com/docker/go-metrics" - "github.com/docker/libnetwork/drivers/overlay/overlayutils" + "github.com/docker/docker/libnetwork/drivers/overlay/overlayutils" "github.com/docker/swarmkit/agent" "github.com/docker/swarmkit/agent/exec" "github.com/docker/swarmkit/api" diff --git a/vendor/github.com/docker/swarmkit/vendor.conf b/vendor/github.com/docker/swarmkit/vendor.conf index d663ebf145..d53d4ce3fb 100644 --- a/vendor/github.com/docker/swarmkit/vendor.conf +++ b/vendor/github.com/docker/swarmkit/vendor.conf @@ -28,12 +28,12 @@ github.com/prometheus/common 7600349dcfe1abd18d72d3a1770870d9800a7801 github.com/prometheus/procfs 7d6f385de8bea29190f15ba9931442a0eaef9af7 github.com/docker/distribution 0d3efadf0154c2b8a4e7b6621fff9809655cc580 -github.com/docker/docker 827cb09f87964ed38b46502f22a585f2ed4a78e1 +github.com/docker/docker 5616f4544aefce5f0372d92c9ed2a022e9b734d5 git://github.com/cpuguy83/docker.git +github.com/containerd/containerd 0edc412565dcc6e3d6125ff9e4b009ad4b89c638 github.com/docker/go-connections 7395e3f8aa162843a74ed6d48e79627d9792ac55 # v0.4.0 github.com/docker/go-events 9461782956ad83b30282bf90e31fa6a70c255ba9 github.com/docker/go-units 519db1ee28dcc9fd2474ae59fca29a810482bfb1 # v0.4.0 github.com/docker/libkv 458977154600b9f23984d9f4b82e79570b5ae12b -github.com/docker/libnetwork 09cdcc8c0eab3946c2d70e8f6225b05baf1e90d1 github.com/opencontainers/runc 425e105d5a03fabd737a126ad93d62a9eeede87f # v1.0.0-rc8 github.com/opencontainers/go-digest v1.0.0-rc1 github.com/opencontainers/image-spec v1.0.1 @@ -53,7 +53,7 @@ github.com/hashicorp/golang-lru 7087cb70de9f7a8bc0a10c375cb0d2280a8edf9c # v0.5. github.com/inconshreveable/mousetrap 76626ae9c91c4f2a10f34cad8ce83ea42c93bb75 github.com/phayes/permbits f7e3ac5e859d0b919c5068d581cc4c5d4f4f9bc5 code.cloudfoundry.org/clock 02e53af36e6c978af692887ed449b74026d76fec -github.com/pkg/errors ba968bfe8b2f7e042a574c888954fccecfa385b4 # v0.8.1 +github.com/pkg/errors 614d223910a179a466c1767a985424175c39b465 # v0.9.1 github.com/pmezard/go-difflib 792786c7400a136282c1664665ae0a8db921c6c2 # v1.0.0 github.com/rcrowley/go-metrics 51425a2415d21afadfd55cd93432c0bc69e9598d github.com/spf13/cobra 8e91712f174ced10270cf66615e0a9127e7c4de5