github.com/docker/engine@v22.0.0-20211208180946-d456264580cf+incompatible/libnetwork/network.go (about)

     1  package libnetwork
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"net"
     7  	"strings"
     8  	"sync"
     9  	"time"
    10  
    11  	"github.com/docker/docker/libnetwork/config"
    12  	"github.com/docker/docker/libnetwork/datastore"
    13  	"github.com/docker/docker/libnetwork/driverapi"
    14  	"github.com/docker/docker/libnetwork/etchosts"
    15  	"github.com/docker/docker/libnetwork/internal/setmatrix"
    16  	"github.com/docker/docker/libnetwork/ipamapi"
    17  	"github.com/docker/docker/libnetwork/netlabel"
    18  	"github.com/docker/docker/libnetwork/netutils"
    19  	"github.com/docker/docker/libnetwork/networkdb"
    20  	"github.com/docker/docker/libnetwork/options"
    21  	"github.com/docker/docker/libnetwork/types"
    22  	"github.com/docker/docker/pkg/stringid"
    23  	"github.com/sirupsen/logrus"
    24  )
    25  
    26  // A Network represents a logical connectivity zone that containers may
    27  // join using the Link method. A Network is managed by a specific driver.
    28  type Network interface {
    29  	// Name returns a user chosen name for this network.
    30  	Name() string
    31  
    32  	// ID returns a system generated id for this network.
    33  	ID() string
    34  
    35  	// Type returns the type of network, which corresponds to its managing driver.
    36  	Type() string
    37  
    38  	// CreateEndpoint creates a new endpoint to this network symbolically identified by the
    39  	// specified unique name. The options parameter carries driver specific options.
    40  	CreateEndpoint(name string, options ...EndpointOption) (Endpoint, error)
    41  
    42  	// Delete the network.
    43  	Delete(options ...NetworkDeleteOption) error
    44  
    45  	// Endpoints returns the list of Endpoint(s) in this network.
    46  	Endpoints() []Endpoint
    47  
    48  	// WalkEndpoints uses the provided function to walk the Endpoints.
    49  	WalkEndpoints(walker EndpointWalker)
    50  
    51  	// EndpointByName returns the Endpoint which has the passed name. If not found, the error ErrNoSuchEndpoint is returned.
    52  	EndpointByName(name string) (Endpoint, error)
    53  
    54  	// EndpointByID returns the Endpoint which has the passed id. If not found, the error ErrNoSuchEndpoint is returned.
    55  	EndpointByID(id string) (Endpoint, error)
    56  
    57  	// Info returns certain operational data belonging to this network.
    58  	Info() NetworkInfo
    59  }
    60  
    61  // NetworkInfo returns some configuration and operational information about the network
    62  type NetworkInfo interface {
    63  	IpamConfig() (string, map[string]string, []*IpamConf, []*IpamConf)
    64  	IpamInfo() ([]*IpamInfo, []*IpamInfo)
    65  	DriverOptions() map[string]string
    66  	Scope() string
    67  	IPv6Enabled() bool
    68  	Internal() bool
    69  	Attachable() bool
    70  	Ingress() bool
    71  	ConfigFrom() string
    72  	ConfigOnly() bool
    73  	Labels() map[string]string
    74  	Dynamic() bool
    75  	Created() time.Time
    76  	// Peers returns a slice of PeerInfo structures which has the information about the peer
    77  	// nodes participating in the same overlay network. This is currently the per-network
    78  	// gossip cluster. For non-dynamic overlay networks and bridge networks it returns an
    79  	// empty slice
    80  	Peers() []networkdb.PeerInfo
    81  	// Services returns a map of services keyed by the service name with the details
    82  	// of all the tasks that belong to the service. Applicable only in swarm mode.
    83  	Services() map[string]ServiceInfo
    84  }
    85  
    86  // EndpointWalker is a client provided function which will be used to walk the Endpoints.
    87  // When the function returns true, the walk will stop.
    88  type EndpointWalker func(ep Endpoint) bool
    89  
    90  // ipInfo is the reverse mapping from IP to service name to serve the PTR query.
    91  // extResolver is set if an external server resolves a service name to this IP.
    92  // It's an indication to defer PTR queries also to that external server.
    93  type ipInfo struct {
    94  	name        string
    95  	serviceID   string
    96  	extResolver bool
    97  }
    98  
    99  // svcMapEntry is the body of the element into the svcMap
   100  // The ip is a string because the SetMatrix does not accept non hashable values
   101  type svcMapEntry struct {
   102  	ip        string
   103  	serviceID string
   104  }
   105  
   106  type svcInfo struct {
   107  	svcMap     setmatrix.SetMatrix
   108  	svcIPv6Map setmatrix.SetMatrix
   109  	ipMap      setmatrix.SetMatrix
   110  	service    map[string][]servicePorts
   111  }
   112  
   113  // backing container or host's info
   114  type serviceTarget struct {
   115  	name string
   116  	ip   net.IP
   117  	port uint16
   118  }
   119  
   120  type servicePorts struct {
   121  	portName string
   122  	proto    string
   123  	target   []serviceTarget
   124  }
   125  
   126  type networkDBTable struct {
   127  	name    string
   128  	objType driverapi.ObjectType
   129  }
   130  
   131  // IpamConf contains all the ipam related configurations for a network
   132  type IpamConf struct {
   133  	// PreferredPool is the master address pool for containers and network interfaces.
   134  	PreferredPool string
   135  	// SubPool is a subset of the master pool. If specified,
   136  	// this becomes the container pool.
   137  	SubPool string
   138  	// Gateway is the preferred Network Gateway address (optional).
   139  	Gateway string
   140  	// AuxAddresses contains auxiliary addresses for network driver. Must be within the master pool.
   141  	// libnetwork will reserve them if they fall into the container pool.
   142  	AuxAddresses map[string]string
   143  }
   144  
   145  // Validate checks whether the configuration is valid
   146  func (c *IpamConf) Validate() error {
   147  	if c.Gateway != "" && nil == net.ParseIP(c.Gateway) {
   148  		return types.BadRequestErrorf("invalid gateway address %s in Ipam configuration", c.Gateway)
   149  	}
   150  	return nil
   151  }
   152  
   153  // IpamInfo contains all the ipam related operational info for a network
   154  type IpamInfo struct {
   155  	PoolID string
   156  	Meta   map[string]string
   157  	driverapi.IPAMData
   158  }
   159  
   160  // MarshalJSON encodes IpamInfo into json message
   161  func (i *IpamInfo) MarshalJSON() ([]byte, error) {
   162  	m := map[string]interface{}{
   163  		"PoolID": i.PoolID,
   164  	}
   165  	v, err := json.Marshal(&i.IPAMData)
   166  	if err != nil {
   167  		return nil, err
   168  	}
   169  	m["IPAMData"] = string(v)
   170  
   171  	if i.Meta != nil {
   172  		m["Meta"] = i.Meta
   173  	}
   174  	return json.Marshal(m)
   175  }
   176  
   177  // UnmarshalJSON decodes json message into PoolData
   178  func (i *IpamInfo) UnmarshalJSON(data []byte) error {
   179  	var (
   180  		m   map[string]interface{}
   181  		err error
   182  	)
   183  	if err = json.Unmarshal(data, &m); err != nil {
   184  		return err
   185  	}
   186  	i.PoolID = m["PoolID"].(string)
   187  	if v, ok := m["Meta"]; ok {
   188  		b, _ := json.Marshal(v)
   189  		if err = json.Unmarshal(b, &i.Meta); err != nil {
   190  			return err
   191  		}
   192  	}
   193  	if v, ok := m["IPAMData"]; ok {
   194  		if err = json.Unmarshal([]byte(v.(string)), &i.IPAMData); err != nil {
   195  			return err
   196  		}
   197  	}
   198  	return nil
   199  }
   200  
   201  type network struct {
   202  	ctrlr            *controller
   203  	name             string
   204  	networkType      string
   205  	id               string
   206  	created          time.Time
   207  	scope            string // network data scope
   208  	labels           map[string]string
   209  	ipamType         string
   210  	ipamOptions      map[string]string
   211  	addrSpace        string
   212  	ipamV4Config     []*IpamConf
   213  	ipamV6Config     []*IpamConf
   214  	ipamV4Info       []*IpamInfo
   215  	ipamV6Info       []*IpamInfo
   216  	enableIPv6       bool
   217  	postIPv6         bool
   218  	epCnt            *endpointCnt
   219  	generic          options.Generic
   220  	dbIndex          uint64
   221  	dbExists         bool
   222  	persist          bool
   223  	drvOnce          *sync.Once
   224  	resolverOnce     sync.Once
   225  	resolver         []Resolver
   226  	internal         bool
   227  	attachable       bool
   228  	inDelete         bool
   229  	ingress          bool
   230  	driverTables     []networkDBTable
   231  	dynamic          bool
   232  	configOnly       bool
   233  	configFrom       string
   234  	loadBalancerIP   net.IP
   235  	loadBalancerMode string
   236  	sync.Mutex
   237  }
   238  
   239  const (
   240  	loadBalancerModeNAT     = "NAT"
   241  	loadBalancerModeDSR     = "DSR"
   242  	loadBalancerModeDefault = loadBalancerModeNAT
   243  )
   244  
   245  func (n *network) Name() string {
   246  	n.Lock()
   247  	defer n.Unlock()
   248  
   249  	return n.name
   250  }
   251  
   252  func (n *network) ID() string {
   253  	n.Lock()
   254  	defer n.Unlock()
   255  
   256  	return n.id
   257  }
   258  
   259  func (n *network) Created() time.Time {
   260  	n.Lock()
   261  	defer n.Unlock()
   262  
   263  	return n.created
   264  }
   265  
   266  func (n *network) Type() string {
   267  	n.Lock()
   268  	defer n.Unlock()
   269  
   270  	return n.networkType
   271  }
   272  
   273  func (n *network) Key() []string {
   274  	n.Lock()
   275  	defer n.Unlock()
   276  	return []string{datastore.NetworkKeyPrefix, n.id}
   277  }
   278  
   279  func (n *network) KeyPrefix() []string {
   280  	return []string{datastore.NetworkKeyPrefix}
   281  }
   282  
   283  func (n *network) Value() []byte {
   284  	n.Lock()
   285  	defer n.Unlock()
   286  	b, err := json.Marshal(n)
   287  	if err != nil {
   288  		return nil
   289  	}
   290  	return b
   291  }
   292  
   293  func (n *network) SetValue(value []byte) error {
   294  	return json.Unmarshal(value, n)
   295  }
   296  
   297  func (n *network) Index() uint64 {
   298  	n.Lock()
   299  	defer n.Unlock()
   300  	return n.dbIndex
   301  }
   302  
   303  func (n *network) SetIndex(index uint64) {
   304  	n.Lock()
   305  	n.dbIndex = index
   306  	n.dbExists = true
   307  	n.Unlock()
   308  }
   309  
   310  func (n *network) Exists() bool {
   311  	n.Lock()
   312  	defer n.Unlock()
   313  	return n.dbExists
   314  }
   315  
   316  func (n *network) Skip() bool {
   317  	n.Lock()
   318  	defer n.Unlock()
   319  	return !n.persist
   320  }
   321  
   322  func (n *network) New() datastore.KVObject {
   323  	n.Lock()
   324  	defer n.Unlock()
   325  
   326  	return &network{
   327  		ctrlr:   n.ctrlr,
   328  		drvOnce: &sync.Once{},
   329  		scope:   n.scope,
   330  	}
   331  }
   332  
   333  // CopyTo deep copies to the destination IpamConfig
   334  func (c *IpamConf) CopyTo(dstC *IpamConf) error {
   335  	dstC.PreferredPool = c.PreferredPool
   336  	dstC.SubPool = c.SubPool
   337  	dstC.Gateway = c.Gateway
   338  	if c.AuxAddresses != nil {
   339  		dstC.AuxAddresses = make(map[string]string, len(c.AuxAddresses))
   340  		for k, v := range c.AuxAddresses {
   341  			dstC.AuxAddresses[k] = v
   342  		}
   343  	}
   344  	return nil
   345  }
   346  
   347  // CopyTo deep copies to the destination IpamInfo
   348  func (i *IpamInfo) CopyTo(dstI *IpamInfo) error {
   349  	dstI.PoolID = i.PoolID
   350  	if i.Meta != nil {
   351  		dstI.Meta = make(map[string]string)
   352  		for k, v := range i.Meta {
   353  			dstI.Meta[k] = v
   354  		}
   355  	}
   356  
   357  	dstI.AddressSpace = i.AddressSpace
   358  	dstI.Pool = types.GetIPNetCopy(i.Pool)
   359  	dstI.Gateway = types.GetIPNetCopy(i.Gateway)
   360  
   361  	if i.AuxAddresses != nil {
   362  		dstI.AuxAddresses = make(map[string]*net.IPNet)
   363  		for k, v := range i.AuxAddresses {
   364  			dstI.AuxAddresses[k] = types.GetIPNetCopy(v)
   365  		}
   366  	}
   367  
   368  	return nil
   369  }
   370  
   371  func (n *network) validateConfiguration() error {
   372  	if n.configOnly {
   373  		// Only supports network specific configurations.
   374  		// Network operator configurations are not supported.
   375  		if n.ingress || n.internal || n.attachable || n.scope != "" {
   376  			return types.ForbiddenErrorf("configuration network can only contain network " +
   377  				"specific fields. Network operator fields like " +
   378  				"[ ingress | internal | attachable | scope ] are not supported.")
   379  		}
   380  	}
   381  	if n.configFrom != "" {
   382  		if n.configOnly {
   383  			return types.ForbiddenErrorf("a configuration network cannot depend on another configuration network")
   384  		}
   385  		if n.ipamType != "" &&
   386  			n.ipamType != defaultIpamForNetworkType(n.networkType) ||
   387  			n.enableIPv6 ||
   388  			len(n.labels) > 0 || len(n.ipamOptions) > 0 ||
   389  			len(n.ipamV4Config) > 0 || len(n.ipamV6Config) > 0 {
   390  			return types.ForbiddenErrorf("user specified configurations are not supported if the network depends on a configuration network")
   391  		}
   392  		if len(n.generic) > 0 {
   393  			if data, ok := n.generic[netlabel.GenericData]; ok {
   394  				var (
   395  					driverOptions map[string]string
   396  					opts          interface{}
   397  				)
   398  				switch t := data.(type) {
   399  				case map[string]interface{}, map[string]string:
   400  					opts = t
   401  				}
   402  				ba, err := json.Marshal(opts)
   403  				if err != nil {
   404  					return fmt.Errorf("failed to validate network configuration: %v", err)
   405  				}
   406  				if err := json.Unmarshal(ba, &driverOptions); err != nil {
   407  					return fmt.Errorf("failed to validate network configuration: %v", err)
   408  				}
   409  				if len(driverOptions) > 0 {
   410  					return types.ForbiddenErrorf("network driver options are not supported if the network depends on a configuration network")
   411  				}
   412  			}
   413  		}
   414  	}
   415  	return nil
   416  }
   417  
   418  // applyConfigurationTo applies network specific configurations.
   419  func (n *network) applyConfigurationTo(to *network) error {
   420  	to.enableIPv6 = n.enableIPv6
   421  	if len(n.labels) > 0 {
   422  		to.labels = make(map[string]string, len(n.labels))
   423  		for k, v := range n.labels {
   424  			if _, ok := to.labels[k]; !ok {
   425  				to.labels[k] = v
   426  			}
   427  		}
   428  	}
   429  	if len(n.ipamType) != 0 {
   430  		to.ipamType = n.ipamType
   431  	}
   432  	if len(n.ipamOptions) > 0 {
   433  		to.ipamOptions = make(map[string]string, len(n.ipamOptions))
   434  		for k, v := range n.ipamOptions {
   435  			if _, ok := to.ipamOptions[k]; !ok {
   436  				to.ipamOptions[k] = v
   437  			}
   438  		}
   439  	}
   440  	if len(n.ipamV4Config) > 0 {
   441  		to.ipamV4Config = make([]*IpamConf, 0, len(n.ipamV4Config))
   442  		to.ipamV4Config = append(to.ipamV4Config, n.ipamV4Config...)
   443  	}
   444  	if len(n.ipamV6Config) > 0 {
   445  		to.ipamV6Config = make([]*IpamConf, 0, len(n.ipamV6Config))
   446  		to.ipamV6Config = append(to.ipamV6Config, n.ipamV6Config...)
   447  	}
   448  	if len(n.generic) > 0 {
   449  		to.generic = options.Generic{}
   450  		for k, v := range n.generic {
   451  			to.generic[k] = v
   452  		}
   453  	}
   454  	return nil
   455  }
   456  
   457  func (n *network) CopyTo(o datastore.KVObject) error {
   458  	n.Lock()
   459  	defer n.Unlock()
   460  
   461  	dstN := o.(*network)
   462  	dstN.name = n.name
   463  	dstN.id = n.id
   464  	dstN.created = n.created
   465  	dstN.networkType = n.networkType
   466  	dstN.scope = n.scope
   467  	dstN.dynamic = n.dynamic
   468  	dstN.ipamType = n.ipamType
   469  	dstN.enableIPv6 = n.enableIPv6
   470  	dstN.persist = n.persist
   471  	dstN.postIPv6 = n.postIPv6
   472  	dstN.dbIndex = n.dbIndex
   473  	dstN.dbExists = n.dbExists
   474  	dstN.drvOnce = n.drvOnce
   475  	dstN.internal = n.internal
   476  	dstN.attachable = n.attachable
   477  	dstN.inDelete = n.inDelete
   478  	dstN.ingress = n.ingress
   479  	dstN.configOnly = n.configOnly
   480  	dstN.configFrom = n.configFrom
   481  	dstN.loadBalancerIP = n.loadBalancerIP
   482  	dstN.loadBalancerMode = n.loadBalancerMode
   483  
   484  	// copy labels
   485  	if dstN.labels == nil {
   486  		dstN.labels = make(map[string]string, len(n.labels))
   487  	}
   488  	for k, v := range n.labels {
   489  		dstN.labels[k] = v
   490  	}
   491  
   492  	if n.ipamOptions != nil {
   493  		dstN.ipamOptions = make(map[string]string, len(n.ipamOptions))
   494  		for k, v := range n.ipamOptions {
   495  			dstN.ipamOptions[k] = v
   496  		}
   497  	}
   498  
   499  	for _, v4conf := range n.ipamV4Config {
   500  		dstV4Conf := &IpamConf{}
   501  		if err := v4conf.CopyTo(dstV4Conf); err != nil {
   502  			return err
   503  		}
   504  		dstN.ipamV4Config = append(dstN.ipamV4Config, dstV4Conf)
   505  	}
   506  
   507  	for _, v4info := range n.ipamV4Info {
   508  		dstV4Info := &IpamInfo{}
   509  		if err := v4info.CopyTo(dstV4Info); err != nil {
   510  			return err
   511  		}
   512  		dstN.ipamV4Info = append(dstN.ipamV4Info, dstV4Info)
   513  	}
   514  
   515  	for _, v6conf := range n.ipamV6Config {
   516  		dstV6Conf := &IpamConf{}
   517  		if err := v6conf.CopyTo(dstV6Conf); err != nil {
   518  			return err
   519  		}
   520  		dstN.ipamV6Config = append(dstN.ipamV6Config, dstV6Conf)
   521  	}
   522  
   523  	for _, v6info := range n.ipamV6Info {
   524  		dstV6Info := &IpamInfo{}
   525  		if err := v6info.CopyTo(dstV6Info); err != nil {
   526  			return err
   527  		}
   528  		dstN.ipamV6Info = append(dstN.ipamV6Info, dstV6Info)
   529  	}
   530  
   531  	dstN.generic = options.Generic{}
   532  	for k, v := range n.generic {
   533  		dstN.generic[k] = v
   534  	}
   535  
   536  	return nil
   537  }
   538  
   539  func (n *network) DataScope() string {
   540  	s := n.Scope()
   541  	// All swarm scope networks have local datascope
   542  	if s == datastore.SwarmScope {
   543  		s = datastore.LocalScope
   544  	}
   545  	return s
   546  }
   547  
   548  func (n *network) getEpCnt() *endpointCnt {
   549  	n.Lock()
   550  	defer n.Unlock()
   551  
   552  	return n.epCnt
   553  }
   554  
   555  // TODO : Can be made much more generic with the help of reflection (but has some golang limitations)
   556  func (n *network) MarshalJSON() ([]byte, error) {
   557  	netMap := make(map[string]interface{})
   558  	netMap["name"] = n.name
   559  	netMap["id"] = n.id
   560  	netMap["created"] = n.created
   561  	netMap["networkType"] = n.networkType
   562  	netMap["scope"] = n.scope
   563  	netMap["labels"] = n.labels
   564  	netMap["ipamType"] = n.ipamType
   565  	netMap["ipamOptions"] = n.ipamOptions
   566  	netMap["addrSpace"] = n.addrSpace
   567  	netMap["enableIPv6"] = n.enableIPv6
   568  	if n.generic != nil {
   569  		netMap["generic"] = n.generic
   570  	}
   571  	netMap["persist"] = n.persist
   572  	netMap["postIPv6"] = n.postIPv6
   573  	if len(n.ipamV4Config) > 0 {
   574  		ics, err := json.Marshal(n.ipamV4Config)
   575  		if err != nil {
   576  			return nil, err
   577  		}
   578  		netMap["ipamV4Config"] = string(ics)
   579  	}
   580  	if len(n.ipamV4Info) > 0 {
   581  		iis, err := json.Marshal(n.ipamV4Info)
   582  		if err != nil {
   583  			return nil, err
   584  		}
   585  		netMap["ipamV4Info"] = string(iis)
   586  	}
   587  	if len(n.ipamV6Config) > 0 {
   588  		ics, err := json.Marshal(n.ipamV6Config)
   589  		if err != nil {
   590  			return nil, err
   591  		}
   592  		netMap["ipamV6Config"] = string(ics)
   593  	}
   594  	if len(n.ipamV6Info) > 0 {
   595  		iis, err := json.Marshal(n.ipamV6Info)
   596  		if err != nil {
   597  			return nil, err
   598  		}
   599  		netMap["ipamV6Info"] = string(iis)
   600  	}
   601  	netMap["internal"] = n.internal
   602  	netMap["attachable"] = n.attachable
   603  	netMap["inDelete"] = n.inDelete
   604  	netMap["ingress"] = n.ingress
   605  	netMap["configOnly"] = n.configOnly
   606  	netMap["configFrom"] = n.configFrom
   607  	netMap["loadBalancerIP"] = n.loadBalancerIP
   608  	netMap["loadBalancerMode"] = n.loadBalancerMode
   609  	return json.Marshal(netMap)
   610  }
   611  
   612  // TODO : Can be made much more generic with the help of reflection (but has some golang limitations)
   613  func (n *network) UnmarshalJSON(b []byte) (err error) {
   614  	var netMap map[string]interface{}
   615  	if err := json.Unmarshal(b, &netMap); err != nil {
   616  		return err
   617  	}
   618  	n.name = netMap["name"].(string)
   619  	n.id = netMap["id"].(string)
   620  	// "created" is not available in older versions
   621  	if v, ok := netMap["created"]; ok {
   622  		// n.created is time.Time but marshalled as string
   623  		if err = n.created.UnmarshalText([]byte(v.(string))); err != nil {
   624  			logrus.Warnf("failed to unmarshal creation time %v: %v", v, err)
   625  			n.created = time.Time{}
   626  		}
   627  	}
   628  	n.networkType = netMap["networkType"].(string)
   629  	n.enableIPv6 = netMap["enableIPv6"].(bool)
   630  
   631  	// if we weren't unmarshaling to netMap we could simply set n.labels
   632  	// unfortunately, we can't because map[string]interface{} != map[string]string
   633  	if labels, ok := netMap["labels"].(map[string]interface{}); ok {
   634  		n.labels = make(map[string]string, len(labels))
   635  		for label, value := range labels {
   636  			n.labels[label] = value.(string)
   637  		}
   638  	}
   639  
   640  	if v, ok := netMap["ipamOptions"]; ok {
   641  		if iOpts, ok := v.(map[string]interface{}); ok {
   642  			n.ipamOptions = make(map[string]string, len(iOpts))
   643  			for k, v := range iOpts {
   644  				n.ipamOptions[k] = v.(string)
   645  			}
   646  		}
   647  	}
   648  
   649  	if v, ok := netMap["generic"]; ok {
   650  		n.generic = v.(map[string]interface{})
   651  		// Restore opts in their map[string]string form
   652  		if v, ok := n.generic[netlabel.GenericData]; ok {
   653  			var lmap map[string]string
   654  			ba, err := json.Marshal(v)
   655  			if err != nil {
   656  				return err
   657  			}
   658  			if err := json.Unmarshal(ba, &lmap); err != nil {
   659  				return err
   660  			}
   661  			n.generic[netlabel.GenericData] = lmap
   662  		}
   663  	}
   664  	if v, ok := netMap["persist"]; ok {
   665  		n.persist = v.(bool)
   666  	}
   667  	if v, ok := netMap["postIPv6"]; ok {
   668  		n.postIPv6 = v.(bool)
   669  	}
   670  	if v, ok := netMap["ipamType"]; ok {
   671  		n.ipamType = v.(string)
   672  	} else {
   673  		n.ipamType = ipamapi.DefaultIPAM
   674  	}
   675  	if v, ok := netMap["addrSpace"]; ok {
   676  		n.addrSpace = v.(string)
   677  	}
   678  	if v, ok := netMap["ipamV4Config"]; ok {
   679  		if err := json.Unmarshal([]byte(v.(string)), &n.ipamV4Config); err != nil {
   680  			return err
   681  		}
   682  	}
   683  	if v, ok := netMap["ipamV4Info"]; ok {
   684  		if err := json.Unmarshal([]byte(v.(string)), &n.ipamV4Info); err != nil {
   685  			return err
   686  		}
   687  	}
   688  	if v, ok := netMap["ipamV6Config"]; ok {
   689  		if err := json.Unmarshal([]byte(v.(string)), &n.ipamV6Config); err != nil {
   690  			return err
   691  		}
   692  	}
   693  	if v, ok := netMap["ipamV6Info"]; ok {
   694  		if err := json.Unmarshal([]byte(v.(string)), &n.ipamV6Info); err != nil {
   695  			return err
   696  		}
   697  	}
   698  	if v, ok := netMap["internal"]; ok {
   699  		n.internal = v.(bool)
   700  	}
   701  	if v, ok := netMap["attachable"]; ok {
   702  		n.attachable = v.(bool)
   703  	}
   704  	if s, ok := netMap["scope"]; ok {
   705  		n.scope = s.(string)
   706  	}
   707  	if v, ok := netMap["inDelete"]; ok {
   708  		n.inDelete = v.(bool)
   709  	}
   710  	if v, ok := netMap["ingress"]; ok {
   711  		n.ingress = v.(bool)
   712  	}
   713  	if v, ok := netMap["configOnly"]; ok {
   714  		n.configOnly = v.(bool)
   715  	}
   716  	if v, ok := netMap["configFrom"]; ok {
   717  		n.configFrom = v.(string)
   718  	}
   719  	if v, ok := netMap["loadBalancerIP"]; ok {
   720  		n.loadBalancerIP = net.ParseIP(v.(string))
   721  	}
   722  	n.loadBalancerMode = loadBalancerModeDefault
   723  	if v, ok := netMap["loadBalancerMode"]; ok {
   724  		n.loadBalancerMode = v.(string)
   725  	}
   726  	// Reconcile old networks with the recently added `--ipv6` flag
   727  	if !n.enableIPv6 {
   728  		n.enableIPv6 = len(n.ipamV6Info) > 0
   729  	}
   730  	return nil
   731  }
   732  
   733  // NetworkOption is an option setter function type used to pass various options to
   734  // NewNetwork method. The various setter functions of type NetworkOption are
   735  // provided by libnetwork, they look like NetworkOptionXXXX(...)
   736  type NetworkOption func(n *network)
   737  
   738  // NetworkOptionGeneric function returns an option setter for a Generic option defined
   739  // in a Dictionary of Key-Value pair
   740  func NetworkOptionGeneric(generic map[string]interface{}) NetworkOption {
   741  	return func(n *network) {
   742  		if n.generic == nil {
   743  			n.generic = make(map[string]interface{})
   744  		}
   745  		if val, ok := generic[netlabel.EnableIPv6]; ok {
   746  			n.enableIPv6 = val.(bool)
   747  		}
   748  		if val, ok := generic[netlabel.Internal]; ok {
   749  			n.internal = val.(bool)
   750  		}
   751  		for k, v := range generic {
   752  			n.generic[k] = v
   753  		}
   754  	}
   755  }
   756  
   757  // NetworkOptionIngress returns an option setter to indicate if a network is
   758  // an ingress network.
   759  func NetworkOptionIngress(ingress bool) NetworkOption {
   760  	return func(n *network) {
   761  		n.ingress = ingress
   762  	}
   763  }
   764  
   765  // NetworkOptionPersist returns an option setter to set persistence policy for a network
   766  func NetworkOptionPersist(persist bool) NetworkOption {
   767  	return func(n *network) {
   768  		n.persist = persist
   769  	}
   770  }
   771  
   772  // NetworkOptionEnableIPv6 returns an option setter to explicitly configure IPv6
   773  func NetworkOptionEnableIPv6(enableIPv6 bool) NetworkOption {
   774  	return func(n *network) {
   775  		if n.generic == nil {
   776  			n.generic = make(map[string]interface{})
   777  		}
   778  		n.enableIPv6 = enableIPv6
   779  		n.generic[netlabel.EnableIPv6] = enableIPv6
   780  	}
   781  }
   782  
   783  // NetworkOptionInternalNetwork returns an option setter to config the network
   784  // to be internal which disables default gateway service
   785  func NetworkOptionInternalNetwork() NetworkOption {
   786  	return func(n *network) {
   787  		if n.generic == nil {
   788  			n.generic = make(map[string]interface{})
   789  		}
   790  		n.internal = true
   791  		n.generic[netlabel.Internal] = true
   792  	}
   793  }
   794  
   795  // NetworkOptionAttachable returns an option setter to set attachable for a network
   796  func NetworkOptionAttachable(attachable bool) NetworkOption {
   797  	return func(n *network) {
   798  		n.attachable = attachable
   799  	}
   800  }
   801  
   802  // NetworkOptionScope returns an option setter to overwrite the network's scope.
   803  // By default the network's scope is set to the network driver's datascope.
   804  func NetworkOptionScope(scope string) NetworkOption {
   805  	return func(n *network) {
   806  		n.scope = scope
   807  	}
   808  }
   809  
   810  // NetworkOptionIpam function returns an option setter for the ipam configuration for this network
   811  func NetworkOptionIpam(ipamDriver string, addrSpace string, ipV4 []*IpamConf, ipV6 []*IpamConf, opts map[string]string) NetworkOption {
   812  	return func(n *network) {
   813  		if ipamDriver != "" {
   814  			n.ipamType = ipamDriver
   815  			if ipamDriver == ipamapi.DefaultIPAM {
   816  				n.ipamType = defaultIpamForNetworkType(n.Type())
   817  			}
   818  		}
   819  		n.ipamOptions = opts
   820  		n.addrSpace = addrSpace
   821  		n.ipamV4Config = ipV4
   822  		n.ipamV6Config = ipV6
   823  	}
   824  }
   825  
   826  // NetworkOptionLBEndpoint function returns an option setter for the configuration of the load balancer endpoint for this network
   827  func NetworkOptionLBEndpoint(ip net.IP) NetworkOption {
   828  	return func(n *network) {
   829  		n.loadBalancerIP = ip
   830  	}
   831  }
   832  
   833  // NetworkOptionDriverOpts function returns an option setter for any driver parameter described by a map
   834  func NetworkOptionDriverOpts(opts map[string]string) NetworkOption {
   835  	return func(n *network) {
   836  		if n.generic == nil {
   837  			n.generic = make(map[string]interface{})
   838  		}
   839  		if opts == nil {
   840  			opts = make(map[string]string)
   841  		}
   842  		// Store the options
   843  		n.generic[netlabel.GenericData] = opts
   844  	}
   845  }
   846  
   847  // NetworkOptionLabels function returns an option setter for labels specific to a network
   848  func NetworkOptionLabels(labels map[string]string) NetworkOption {
   849  	return func(n *network) {
   850  		n.labels = labels
   851  	}
   852  }
   853  
   854  // NetworkOptionDynamic function returns an option setter for dynamic option for a network
   855  func NetworkOptionDynamic() NetworkOption {
   856  	return func(n *network) {
   857  		n.dynamic = true
   858  	}
   859  }
   860  
   861  // NetworkOptionDeferIPv6Alloc instructs the network to defer the IPV6 address allocation until after the endpoint has been created
   862  // It is being provided to support the specific docker daemon flags where user can deterministically assign an IPv6 address
   863  // to a container as combination of fixed-cidr-v6 + mac-address
   864  // TODO: Remove this option setter once we support endpoint ipam options
   865  func NetworkOptionDeferIPv6Alloc(enable bool) NetworkOption {
   866  	return func(n *network) {
   867  		n.postIPv6 = enable
   868  	}
   869  }
   870  
   871  // NetworkOptionConfigOnly tells controller this network is
   872  // a configuration only network. It serves as a configuration
   873  // for other networks.
   874  func NetworkOptionConfigOnly() NetworkOption {
   875  	return func(n *network) {
   876  		n.configOnly = true
   877  	}
   878  }
   879  
   880  // NetworkOptionConfigFrom tells controller to pick the
   881  // network configuration from a configuration only network
   882  func NetworkOptionConfigFrom(name string) NetworkOption {
   883  	return func(n *network) {
   884  		n.configFrom = name
   885  	}
   886  }
   887  
   888  func (n *network) processOptions(options ...NetworkOption) {
   889  	for _, opt := range options {
   890  		if opt != nil {
   891  			opt(n)
   892  		}
   893  	}
   894  }
   895  
   896  type networkDeleteParams struct {
   897  	rmLBEndpoint bool
   898  }
   899  
   900  // NetworkDeleteOption is a type for optional parameters to pass to the
   901  // network.Delete() function.
   902  type NetworkDeleteOption func(p *networkDeleteParams)
   903  
   904  // NetworkDeleteOptionRemoveLB informs a network.Delete() operation that should
   905  // remove the load balancer endpoint for this network.  Note that the Delete()
   906  // method will automatically remove a load balancing endpoint for most networks
   907  // when the network is otherwise empty.  However, this does not occur for some
   908  // networks.  In particular, networks marked as ingress (which are supposed to
   909  // be more permanent than other overlay networks) won't automatically remove
   910  // the LB endpoint on Delete().  This method allows for explicit removal of
   911  // such networks provided there are no other endpoints present in the network.
   912  // If the network still has non-LB endpoints present, Delete() will not
   913  // remove the LB endpoint and will return an error.
   914  func NetworkDeleteOptionRemoveLB(p *networkDeleteParams) {
   915  	p.rmLBEndpoint = true
   916  }
   917  
   918  func (n *network) resolveDriver(name string, load bool) (driverapi.Driver, *driverapi.Capability, error) {
   919  	c := n.getController()
   920  
   921  	// Check if a driver for the specified network type is available
   922  	d, cap := c.drvRegistry.Driver(name)
   923  	if d == nil {
   924  		if load {
   925  			err := c.loadDriver(name)
   926  			if err != nil {
   927  				return nil, nil, err
   928  			}
   929  
   930  			d, cap = c.drvRegistry.Driver(name)
   931  			if d == nil {
   932  				return nil, nil, fmt.Errorf("could not resolve driver %s in registry", name)
   933  			}
   934  		} else {
   935  			// don't fail if driver loading is not required
   936  			return nil, nil, nil
   937  		}
   938  	}
   939  
   940  	return d, cap, nil
   941  }
   942  
   943  func (n *network) driverIsMultihost() bool {
   944  	_, cap, err := n.resolveDriver(n.networkType, true)
   945  	if err != nil {
   946  		return false
   947  	}
   948  	return cap.ConnectivityScope == datastore.GlobalScope
   949  }
   950  
   951  func (n *network) driver(load bool) (driverapi.Driver, error) {
   952  	d, cap, err := n.resolveDriver(n.networkType, load)
   953  	if err != nil {
   954  		return nil, err
   955  	}
   956  
   957  	n.Lock()
   958  	// If load is not required, driver, cap and err may all be nil
   959  	if n.scope == "" && cap != nil {
   960  		n.scope = cap.DataScope
   961  	}
   962  	if n.dynamic {
   963  		// If the network is dynamic, then it is swarm
   964  		// scoped regardless of the backing driver.
   965  		n.scope = datastore.SwarmScope
   966  	}
   967  	n.Unlock()
   968  	return d, nil
   969  }
   970  
   971  func (n *network) Delete(options ...NetworkDeleteOption) error {
   972  	var params networkDeleteParams
   973  	for _, opt := range options {
   974  		opt(&params)
   975  	}
   976  	return n.delete(false, params.rmLBEndpoint)
   977  }
   978  
   979  // This function gets called in 3 ways:
   980  //  * Delete() -- (false, false)
   981  //      remove if endpoint count == 0 or endpoint count == 1 and
   982  //      there is a load balancer IP
   983  //  * Delete(libnetwork.NetworkDeleteOptionRemoveLB) -- (false, true)
   984  //      remove load balancer and network if endpoint count == 1
   985  //  * controller.networkCleanup() -- (true, true)
   986  //      remove the network no matter what
   987  func (n *network) delete(force bool, rmLBEndpoint bool) error {
   988  	n.Lock()
   989  	c := n.ctrlr
   990  	name := n.name
   991  	id := n.id
   992  	n.Unlock()
   993  
   994  	c.networkLocker.Lock(id)
   995  	defer c.networkLocker.Unlock(id) // nolint:errcheck
   996  
   997  	n, err := c.getNetworkFromStore(id)
   998  	if err != nil {
   999  		return &UnknownNetworkError{name: name, id: id}
  1000  	}
  1001  
  1002  	// Only remove ingress on force removal or explicit LB endpoint removal
  1003  	if n.ingress && !force && !rmLBEndpoint {
  1004  		return &ActiveEndpointsError{name: n.name, id: n.id}
  1005  	}
  1006  
  1007  	// Check that the network is empty
  1008  	var emptyCount uint64
  1009  	if n.hasLoadBalancerEndpoint() {
  1010  		emptyCount = 1
  1011  	}
  1012  	if !force && n.getEpCnt().EndpointCnt() > emptyCount {
  1013  		if n.configOnly {
  1014  			return types.ForbiddenErrorf("configuration network %q is in use", n.Name())
  1015  		}
  1016  		return &ActiveEndpointsError{name: n.name, id: n.id}
  1017  	}
  1018  
  1019  	if n.hasLoadBalancerEndpoint() {
  1020  		// If we got to this point, then the following must hold:
  1021  		//  * force is true OR endpoint count == 1
  1022  		if err := n.deleteLoadBalancerSandbox(); err != nil {
  1023  			if !force {
  1024  				return err
  1025  			}
  1026  			// continue deletion when force is true even on error
  1027  			logrus.Warnf("Error deleting load balancer sandbox: %v", err)
  1028  		}
  1029  		//Reload the network from the store to update the epcnt.
  1030  		n, err = c.getNetworkFromStore(id)
  1031  		if err != nil {
  1032  			return &UnknownNetworkError{name: name, id: id}
  1033  		}
  1034  	}
  1035  
  1036  	// Up to this point, errors that we returned were recoverable.
  1037  	// From here on, any errors leave us in an inconsistent state.
  1038  	// This is unfortunate, but there isn't a safe way to
  1039  	// reconstitute a load-balancer endpoint after removing it.
  1040  
  1041  	// Mark the network for deletion
  1042  	n.inDelete = true
  1043  	if err = c.updateToStore(n); err != nil {
  1044  		return fmt.Errorf("error marking network %s (%s) for deletion: %v", n.Name(), n.ID(), err)
  1045  	}
  1046  
  1047  	if n.ConfigFrom() != "" {
  1048  		if t, err := c.getConfigNetwork(n.ConfigFrom()); err == nil {
  1049  			if err := t.getEpCnt().DecEndpointCnt(); err != nil {
  1050  				logrus.Warnf("Failed to update reference count for configuration network %q on removal of network %q: %v",
  1051  					t.Name(), n.Name(), err)
  1052  			}
  1053  		} else {
  1054  			logrus.Warnf("Could not find configuration network %q during removal of network %q", n.configFrom, n.Name())
  1055  		}
  1056  	}
  1057  
  1058  	if n.configOnly {
  1059  		goto removeFromStore
  1060  	}
  1061  
  1062  	if err = n.deleteNetwork(); err != nil {
  1063  		if !force {
  1064  			return err
  1065  		}
  1066  		logrus.Debugf("driver failed to delete stale network %s (%s): %v", n.Name(), n.ID(), err)
  1067  	}
  1068  
  1069  	n.ipamRelease()
  1070  	if err = c.updateToStore(n); err != nil {
  1071  		logrus.Warnf("Failed to update store after ipam release for network %s (%s): %v", n.Name(), n.ID(), err)
  1072  	}
  1073  
  1074  	// We are about to delete the network. Leave the gossip
  1075  	// cluster for the network to stop all incoming network
  1076  	// specific gossip updates before cleaning up all the service
  1077  	// bindings for the network. But cleanup service binding
  1078  	// before deleting the network from the store since service
  1079  	// bindings cleanup requires the network in the store.
  1080  	n.cancelDriverWatches()
  1081  	if err = n.leaveCluster(); err != nil {
  1082  		logrus.Errorf("Failed leaving network %s from the agent cluster: %v", n.Name(), err)
  1083  	}
  1084  
  1085  	// Cleanup the service discovery for this network
  1086  	c.cleanupServiceDiscovery(n.ID())
  1087  
  1088  	// Cleanup the load balancer. On Windows this call is required
  1089  	// to remove remote loadbalancers in VFP.
  1090  	c.cleanupServiceBindings(n.ID())
  1091  
  1092  removeFromStore:
  1093  	// deleteFromStore performs an atomic delete operation and the
  1094  	// network.epCnt will help prevent any possible
  1095  	// race between endpoint join and network delete
  1096  	if err = c.deleteFromStore(n.getEpCnt()); err != nil {
  1097  		if !force {
  1098  			return fmt.Errorf("error deleting network endpoint count from store: %v", err)
  1099  		}
  1100  		logrus.Debugf("Error deleting endpoint count from store for stale network %s (%s) for deletion: %v", n.Name(), n.ID(), err)
  1101  	}
  1102  
  1103  	if err = c.deleteFromStore(n); err != nil {
  1104  		return fmt.Errorf("error deleting network from store: %v", err)
  1105  	}
  1106  
  1107  	return nil
  1108  }
  1109  
  1110  func (n *network) deleteNetwork() error {
  1111  	d, err := n.driver(true)
  1112  	if err != nil {
  1113  		return fmt.Errorf("failed deleting network: %v", err)
  1114  	}
  1115  
  1116  	if err := d.DeleteNetwork(n.ID()); err != nil {
  1117  		// Forbidden Errors should be honored
  1118  		if _, ok := err.(types.ForbiddenError); ok {
  1119  			return err
  1120  		}
  1121  
  1122  		if _, ok := err.(types.MaskableError); !ok {
  1123  			logrus.Warnf("driver error deleting network %s : %v", n.name, err)
  1124  		}
  1125  	}
  1126  
  1127  	for _, resolver := range n.resolver {
  1128  		resolver.Stop()
  1129  	}
  1130  	return nil
  1131  }
  1132  
  1133  func (n *network) addEndpoint(ep *endpoint) error {
  1134  	d, err := n.driver(true)
  1135  	if err != nil {
  1136  		return fmt.Errorf("failed to add endpoint: %v", err)
  1137  	}
  1138  
  1139  	err = d.CreateEndpoint(n.id, ep.id, ep.Interface(), ep.generic)
  1140  	if err != nil {
  1141  		return types.InternalErrorf("failed to create endpoint %s on network %s: %v",
  1142  			ep.Name(), n.Name(), err)
  1143  	}
  1144  
  1145  	return nil
  1146  }
  1147  
  1148  func (n *network) CreateEndpoint(name string, options ...EndpointOption) (Endpoint, error) {
  1149  	var err error
  1150  	if !config.IsValidName(name) {
  1151  		return nil, ErrInvalidName(name)
  1152  	}
  1153  
  1154  	if n.ConfigOnly() {
  1155  		return nil, types.ForbiddenErrorf("cannot create endpoint on configuration-only network")
  1156  	}
  1157  
  1158  	if _, err = n.EndpointByName(name); err == nil {
  1159  		return nil, types.ForbiddenErrorf("endpoint with name %s already exists in network %s", name, n.Name())
  1160  	}
  1161  
  1162  	n.ctrlr.networkLocker.Lock(n.id)
  1163  	defer n.ctrlr.networkLocker.Unlock(n.id) // nolint:errcheck
  1164  
  1165  	return n.createEndpoint(name, options...)
  1166  
  1167  }
  1168  
  1169  func (n *network) createEndpoint(name string, options ...EndpointOption) (Endpoint, error) {
  1170  	var err error
  1171  
  1172  	ep := &endpoint{name: name, generic: make(map[string]interface{}), iface: &endpointInterface{}}
  1173  	ep.id = stringid.GenerateRandomID()
  1174  
  1175  	// Initialize ep.network with a possibly stale copy of n. We need this to get network from
  1176  	// store. But once we get it from store we will have the most uptodate copy possibly.
  1177  	ep.network = n
  1178  	ep.locator = n.getController().clusterHostID()
  1179  	ep.network, err = ep.getNetworkFromStore()
  1180  	if err != nil {
  1181  		logrus.Errorf("failed to get network during CreateEndpoint: %v", err)
  1182  		return nil, err
  1183  	}
  1184  	n = ep.network
  1185  
  1186  	ep.processOptions(options...)
  1187  
  1188  	for _, llIPNet := range ep.Iface().LinkLocalAddresses() {
  1189  		if !llIPNet.IP.IsLinkLocalUnicast() {
  1190  			return nil, types.BadRequestErrorf("invalid link local IP address: %v", llIPNet.IP)
  1191  		}
  1192  	}
  1193  
  1194  	if opt, ok := ep.generic[netlabel.MacAddress]; ok {
  1195  		if mac, ok := opt.(net.HardwareAddr); ok {
  1196  			ep.iface.mac = mac
  1197  		}
  1198  	}
  1199  
  1200  	ipam, capability, err := n.getController().getIPAMDriver(n.ipamType)
  1201  	if err != nil {
  1202  		return nil, err
  1203  	}
  1204  
  1205  	if capability.RequiresMACAddress {
  1206  		if ep.iface.mac == nil {
  1207  			ep.iface.mac = netutils.GenerateRandomMAC()
  1208  		}
  1209  		if ep.ipamOptions == nil {
  1210  			ep.ipamOptions = make(map[string]string)
  1211  		}
  1212  		ep.ipamOptions[netlabel.MacAddress] = ep.iface.mac.String()
  1213  	}
  1214  
  1215  	if err = ep.assignAddress(ipam, true, n.enableIPv6 && !n.postIPv6); err != nil {
  1216  		return nil, err
  1217  	}
  1218  	defer func() {
  1219  		if err != nil {
  1220  			ep.releaseAddress()
  1221  		}
  1222  	}()
  1223  
  1224  	if err = n.addEndpoint(ep); err != nil {
  1225  		return nil, err
  1226  	}
  1227  	defer func() {
  1228  		if err != nil {
  1229  			if e := ep.deleteEndpoint(false); e != nil {
  1230  				logrus.Warnf("cleaning up endpoint failed %s : %v", name, e)
  1231  			}
  1232  		}
  1233  	}()
  1234  
  1235  	// We should perform updateToStore call right after addEndpoint
  1236  	// in order to have iface properly configured
  1237  	if err = n.getController().updateToStore(ep); err != nil {
  1238  		return nil, err
  1239  	}
  1240  	defer func() {
  1241  		if err != nil {
  1242  			if e := n.getController().deleteFromStore(ep); e != nil {
  1243  				logrus.Warnf("error rolling back endpoint %s from store: %v", name, e)
  1244  			}
  1245  		}
  1246  	}()
  1247  
  1248  	if err = ep.assignAddress(ipam, false, n.enableIPv6 && n.postIPv6); err != nil {
  1249  		return nil, err
  1250  	}
  1251  
  1252  	// Watch for service records
  1253  	n.getController().watchSvcRecord(ep)
  1254  	defer func() {
  1255  		if err != nil {
  1256  			n.getController().unWatchSvcRecord(ep)
  1257  		}
  1258  	}()
  1259  
  1260  	// Increment endpoint count to indicate completion of endpoint addition
  1261  	if err = n.getEpCnt().IncEndpointCnt(); err != nil {
  1262  		return nil, err
  1263  	}
  1264  
  1265  	return ep, nil
  1266  }
  1267  
  1268  func (n *network) Endpoints() []Endpoint {
  1269  	var list []Endpoint
  1270  
  1271  	endpoints, err := n.getEndpointsFromStore()
  1272  	if err != nil {
  1273  		logrus.Error(err)
  1274  	}
  1275  
  1276  	for _, ep := range endpoints {
  1277  		list = append(list, ep)
  1278  	}
  1279  
  1280  	return list
  1281  }
  1282  
  1283  func (n *network) WalkEndpoints(walker EndpointWalker) {
  1284  	for _, e := range n.Endpoints() {
  1285  		if walker(e) {
  1286  			return
  1287  		}
  1288  	}
  1289  }
  1290  
  1291  func (n *network) EndpointByName(name string) (Endpoint, error) {
  1292  	if name == "" {
  1293  		return nil, ErrInvalidName(name)
  1294  	}
  1295  	var e Endpoint
  1296  
  1297  	s := func(current Endpoint) bool {
  1298  		if current.Name() == name {
  1299  			e = current
  1300  			return true
  1301  		}
  1302  		return false
  1303  	}
  1304  
  1305  	n.WalkEndpoints(s)
  1306  
  1307  	if e == nil {
  1308  		return nil, ErrNoSuchEndpoint(name)
  1309  	}
  1310  
  1311  	return e, nil
  1312  }
  1313  
  1314  func (n *network) EndpointByID(id string) (Endpoint, error) {
  1315  	if id == "" {
  1316  		return nil, ErrInvalidID(id)
  1317  	}
  1318  
  1319  	ep, err := n.getEndpointFromStore(id)
  1320  	if err != nil {
  1321  		return nil, ErrNoSuchEndpoint(id)
  1322  	}
  1323  
  1324  	return ep, nil
  1325  }
  1326  
  1327  func (n *network) updateSvcRecord(ep *endpoint, localEps []*endpoint, isAdd bool) {
  1328  	var ipv6 net.IP
  1329  	epName := ep.Name()
  1330  	if iface := ep.Iface(); iface != nil && iface.Address() != nil {
  1331  		myAliases := ep.MyAliases()
  1332  		if iface.AddressIPv6() != nil {
  1333  			ipv6 = iface.AddressIPv6().IP
  1334  		}
  1335  
  1336  		serviceID := ep.svcID
  1337  		if serviceID == "" {
  1338  			serviceID = ep.ID()
  1339  		}
  1340  		if isAdd {
  1341  			// If anonymous endpoint has an alias use the first alias
  1342  			// for ip->name mapping. Not having the reverse mapping
  1343  			// breaks some apps
  1344  			if ep.isAnonymous() {
  1345  				if len(myAliases) > 0 {
  1346  					n.addSvcRecords(ep.ID(), myAliases[0], serviceID, iface.Address().IP, ipv6, true, "updateSvcRecord")
  1347  				}
  1348  			} else {
  1349  				n.addSvcRecords(ep.ID(), epName, serviceID, iface.Address().IP, ipv6, true, "updateSvcRecord")
  1350  			}
  1351  			for _, alias := range myAliases {
  1352  				n.addSvcRecords(ep.ID(), alias, serviceID, iface.Address().IP, ipv6, false, "updateSvcRecord")
  1353  			}
  1354  		} else {
  1355  			if ep.isAnonymous() {
  1356  				if len(myAliases) > 0 {
  1357  					n.deleteSvcRecords(ep.ID(), myAliases[0], serviceID, iface.Address().IP, ipv6, true, "updateSvcRecord")
  1358  				}
  1359  			} else {
  1360  				n.deleteSvcRecords(ep.ID(), epName, serviceID, iface.Address().IP, ipv6, true, "updateSvcRecord")
  1361  			}
  1362  			for _, alias := range myAliases {
  1363  				n.deleteSvcRecords(ep.ID(), alias, serviceID, iface.Address().IP, ipv6, false, "updateSvcRecord")
  1364  			}
  1365  		}
  1366  	}
  1367  }
  1368  
  1369  func addIPToName(ipMap setmatrix.SetMatrix, name, serviceID string, ip net.IP) {
  1370  	reverseIP := netutils.ReverseIP(ip.String())
  1371  	ipMap.Insert(reverseIP, ipInfo{
  1372  		name:      name,
  1373  		serviceID: serviceID,
  1374  	})
  1375  }
  1376  
  1377  func delIPToName(ipMap setmatrix.SetMatrix, name, serviceID string, ip net.IP) {
  1378  	reverseIP := netutils.ReverseIP(ip.String())
  1379  	ipMap.Remove(reverseIP, ipInfo{
  1380  		name:      name,
  1381  		serviceID: serviceID,
  1382  	})
  1383  }
  1384  
  1385  func addNameToIP(svcMap setmatrix.SetMatrix, name, serviceID string, epIP net.IP) {
  1386  	// Since DNS name resolution is case-insensitive, Use the lower-case form
  1387  	// of the name as the key into svcMap
  1388  	lowerCaseName := strings.ToLower(name)
  1389  	svcMap.Insert(lowerCaseName, svcMapEntry{
  1390  		ip:        epIP.String(),
  1391  		serviceID: serviceID,
  1392  	})
  1393  }
  1394  
  1395  func delNameToIP(svcMap setmatrix.SetMatrix, name, serviceID string, epIP net.IP) {
  1396  	lowerCaseName := strings.ToLower(name)
  1397  	svcMap.Remove(lowerCaseName, svcMapEntry{
  1398  		ip:        epIP.String(),
  1399  		serviceID: serviceID,
  1400  	})
  1401  }
  1402  
  1403  func (n *network) addSvcRecords(eID, name, serviceID string, epIP, epIPv6 net.IP, ipMapUpdate bool, method string) {
  1404  	// Do not add service names for ingress network as this is a
  1405  	// routing only network
  1406  	if n.ingress {
  1407  		return
  1408  	}
  1409  	networkID := n.ID()
  1410  	logrus.Debugf("%s (%.7s).addSvcRecords(%s, %s, %s, %t) %s sid:%s", eID, networkID, name, epIP, epIPv6, ipMapUpdate, method, serviceID)
  1411  
  1412  	c := n.getController()
  1413  	c.Lock()
  1414  	defer c.Unlock()
  1415  
  1416  	sr, ok := c.svcRecords[networkID]
  1417  	if !ok {
  1418  		sr = svcInfo{
  1419  			svcMap:     setmatrix.NewSetMatrix(),
  1420  			svcIPv6Map: setmatrix.NewSetMatrix(),
  1421  			ipMap:      setmatrix.NewSetMatrix(),
  1422  		}
  1423  		c.svcRecords[networkID] = sr
  1424  	}
  1425  
  1426  	if ipMapUpdate {
  1427  		addIPToName(sr.ipMap, name, serviceID, epIP)
  1428  		if epIPv6 != nil {
  1429  			addIPToName(sr.ipMap, name, serviceID, epIPv6)
  1430  		}
  1431  	}
  1432  
  1433  	addNameToIP(sr.svcMap, name, serviceID, epIP)
  1434  	if epIPv6 != nil {
  1435  		addNameToIP(sr.svcIPv6Map, name, serviceID, epIPv6)
  1436  	}
  1437  }
  1438  
  1439  func (n *network) deleteSvcRecords(eID, name, serviceID string, epIP net.IP, epIPv6 net.IP, ipMapUpdate bool, method string) {
  1440  	// Do not delete service names from ingress network as this is a
  1441  	// routing only network
  1442  	if n.ingress {
  1443  		return
  1444  	}
  1445  	networkID := n.ID()
  1446  	logrus.Debugf("%s (%.7s).deleteSvcRecords(%s, %s, %s, %t) %s sid:%s ", eID, networkID, name, epIP, epIPv6, ipMapUpdate, method, serviceID)
  1447  
  1448  	c := n.getController()
  1449  	c.Lock()
  1450  	defer c.Unlock()
  1451  
  1452  	sr, ok := c.svcRecords[networkID]
  1453  	if !ok {
  1454  		return
  1455  	}
  1456  
  1457  	if ipMapUpdate {
  1458  		delIPToName(sr.ipMap, name, serviceID, epIP)
  1459  
  1460  		if epIPv6 != nil {
  1461  			delIPToName(sr.ipMap, name, serviceID, epIPv6)
  1462  		}
  1463  	}
  1464  
  1465  	delNameToIP(sr.svcMap, name, serviceID, epIP)
  1466  
  1467  	if epIPv6 != nil {
  1468  		delNameToIP(sr.svcIPv6Map, name, serviceID, epIPv6)
  1469  	}
  1470  }
  1471  
  1472  func (n *network) getSvcRecords(ep *endpoint) []etchosts.Record {
  1473  	n.Lock()
  1474  	defer n.Unlock()
  1475  
  1476  	if ep == nil {
  1477  		return nil
  1478  	}
  1479  
  1480  	var recs []etchosts.Record
  1481  
  1482  	epName := ep.Name()
  1483  
  1484  	n.ctrlr.Lock()
  1485  	defer n.ctrlr.Unlock()
  1486  	sr, ok := n.ctrlr.svcRecords[n.id]
  1487  	if !ok || sr.svcMap == nil {
  1488  		return nil
  1489  	}
  1490  
  1491  	svcMapKeys := sr.svcMap.Keys()
  1492  	// Loop on service names on this network
  1493  	for _, k := range svcMapKeys {
  1494  		if strings.Split(k, ".")[0] == epName {
  1495  			continue
  1496  		}
  1497  		// Get all the IPs associated to this service
  1498  		mapEntryList, ok := sr.svcMap.Get(k)
  1499  		if !ok {
  1500  			// The key got deleted
  1501  			continue
  1502  		}
  1503  		if len(mapEntryList) == 0 {
  1504  			logrus.Warnf("Found empty list of IP addresses for service %s on network %s (%s)", k, n.name, n.id)
  1505  			continue
  1506  		}
  1507  
  1508  		recs = append(recs, etchosts.Record{
  1509  			Hosts: k,
  1510  			IP:    mapEntryList[0].(svcMapEntry).ip,
  1511  		})
  1512  	}
  1513  
  1514  	return recs
  1515  }
  1516  
  1517  func (n *network) getController() *controller {
  1518  	n.Lock()
  1519  	defer n.Unlock()
  1520  	return n.ctrlr
  1521  }
  1522  
  1523  func (n *network) ipamAllocate() error {
  1524  	if n.hasSpecialDriver() {
  1525  		return nil
  1526  	}
  1527  
  1528  	ipam, _, err := n.getController().getIPAMDriver(n.ipamType)
  1529  	if err != nil {
  1530  		return err
  1531  	}
  1532  
  1533  	if n.addrSpace == "" {
  1534  		if n.addrSpace, err = n.deriveAddressSpace(); err != nil {
  1535  			return err
  1536  		}
  1537  	}
  1538  
  1539  	err = n.ipamAllocateVersion(4, ipam)
  1540  	if err != nil {
  1541  		return err
  1542  	}
  1543  
  1544  	defer func() {
  1545  		if err != nil {
  1546  			n.ipamReleaseVersion(4, ipam)
  1547  		}
  1548  	}()
  1549  
  1550  	if !n.enableIPv6 {
  1551  		return nil
  1552  	}
  1553  
  1554  	err = n.ipamAllocateVersion(6, ipam)
  1555  	return err
  1556  }
  1557  
  1558  func (n *network) requestPoolHelper(ipam ipamapi.Ipam, addressSpace, preferredPool, subPool string, options map[string]string, v6 bool) (string, *net.IPNet, map[string]string, error) {
  1559  	for {
  1560  		poolID, pool, meta, err := ipam.RequestPool(addressSpace, preferredPool, subPool, options, v6)
  1561  		if err != nil {
  1562  			return "", nil, nil, err
  1563  		}
  1564  
  1565  		// If the network belongs to global scope or the pool was
  1566  		// explicitly chosen or it is invalid, do not perform the overlap check.
  1567  		if n.Scope() == datastore.GlobalScope || preferredPool != "" || !types.IsIPNetValid(pool) {
  1568  			return poolID, pool, meta, nil
  1569  		}
  1570  
  1571  		// Check for overlap and if none found, we have found the right pool.
  1572  		if _, err := netutils.FindAvailableNetwork([]*net.IPNet{pool}); err == nil {
  1573  			return poolID, pool, meta, nil
  1574  		}
  1575  
  1576  		// Pool obtained in this iteration is
  1577  		// overlapping. Hold onto the pool and don't release
  1578  		// it yet, because we don't want ipam to give us back
  1579  		// the same pool over again. But make sure we still do
  1580  		// a deferred release when we have either obtained a
  1581  		// non-overlapping pool or ran out of pre-defined
  1582  		// pools.
  1583  		defer func() {
  1584  			if err := ipam.ReleasePool(poolID); err != nil {
  1585  				logrus.Warnf("Failed to release overlapping pool %s while returning from pool request helper for network %s", pool, n.Name())
  1586  			}
  1587  		}()
  1588  
  1589  		// If this is a preferred pool request and the network
  1590  		// is local scope and there is an overlap, we fail the
  1591  		// network creation right here. The pool will be
  1592  		// released in the defer.
  1593  		if preferredPool != "" {
  1594  			return "", nil, nil, fmt.Errorf("requested subnet %s overlaps in the host", preferredPool)
  1595  		}
  1596  	}
  1597  }
  1598  
  1599  func (n *network) ipamAllocateVersion(ipVer int, ipam ipamapi.Ipam) error {
  1600  	var (
  1601  		cfgList  *[]*IpamConf
  1602  		infoList *[]*IpamInfo
  1603  		err      error
  1604  	)
  1605  
  1606  	switch ipVer {
  1607  	case 4:
  1608  		cfgList = &n.ipamV4Config
  1609  		infoList = &n.ipamV4Info
  1610  	case 6:
  1611  		cfgList = &n.ipamV6Config
  1612  		infoList = &n.ipamV6Info
  1613  	default:
  1614  		return types.InternalErrorf("incorrect ip version passed to ipam allocate: %d", ipVer)
  1615  	}
  1616  
  1617  	if len(*cfgList) == 0 {
  1618  		*cfgList = []*IpamConf{{}}
  1619  	}
  1620  
  1621  	*infoList = make([]*IpamInfo, len(*cfgList))
  1622  
  1623  	logrus.Debugf("Allocating IPv%d pools for network %s (%s)", ipVer, n.Name(), n.ID())
  1624  
  1625  	for i, cfg := range *cfgList {
  1626  		if err = cfg.Validate(); err != nil {
  1627  			return err
  1628  		}
  1629  		d := &IpamInfo{}
  1630  		(*infoList)[i] = d
  1631  
  1632  		d.AddressSpace = n.addrSpace
  1633  		d.PoolID, d.Pool, d.Meta, err = n.requestPoolHelper(ipam, n.addrSpace, cfg.PreferredPool, cfg.SubPool, n.ipamOptions, ipVer == 6)
  1634  		if err != nil {
  1635  			return err
  1636  		}
  1637  
  1638  		defer func() {
  1639  			if err != nil {
  1640  				if err := ipam.ReleasePool(d.PoolID); err != nil {
  1641  					logrus.Warnf("Failed to release address pool %s after failure to create network %s (%s)", d.PoolID, n.Name(), n.ID())
  1642  				}
  1643  			}
  1644  		}()
  1645  
  1646  		if gws, ok := d.Meta[netlabel.Gateway]; ok {
  1647  			if d.Gateway, err = types.ParseCIDR(gws); err != nil {
  1648  				return types.BadRequestErrorf("failed to parse gateway address (%v) returned by ipam driver: %v", gws, err)
  1649  			}
  1650  		}
  1651  
  1652  		// If user requested a specific gateway, libnetwork will allocate it
  1653  		// irrespective of whether ipam driver returned a gateway already.
  1654  		// If none of the above is true, libnetwork will allocate one.
  1655  		if cfg.Gateway != "" || d.Gateway == nil {
  1656  			var gatewayOpts = map[string]string{
  1657  				ipamapi.RequestAddressType: netlabel.Gateway,
  1658  			}
  1659  			if d.Gateway, _, err = ipam.RequestAddress(d.PoolID, net.ParseIP(cfg.Gateway), gatewayOpts); err != nil {
  1660  				return types.InternalErrorf("failed to allocate gateway (%v): %v", cfg.Gateway, err)
  1661  			}
  1662  		}
  1663  
  1664  		// Auxiliary addresses must be part of the master address pool
  1665  		// If they fall into the container addressable pool, libnetwork will reserve them
  1666  		if cfg.AuxAddresses != nil {
  1667  			var ip net.IP
  1668  			d.IPAMData.AuxAddresses = make(map[string]*net.IPNet, len(cfg.AuxAddresses))
  1669  			for k, v := range cfg.AuxAddresses {
  1670  				if ip = net.ParseIP(v); ip == nil {
  1671  					return types.BadRequestErrorf("non parsable secondary ip address (%s:%s) passed for network %s", k, v, n.Name())
  1672  				}
  1673  				if !d.Pool.Contains(ip) {
  1674  					return types.ForbiddenErrorf("auxiliary address: (%s:%s) must belong to the master pool: %s", k, v, d.Pool)
  1675  				}
  1676  				// Attempt reservation in the container addressable pool, silent the error if address does not belong to that pool
  1677  				if d.IPAMData.AuxAddresses[k], _, err = ipam.RequestAddress(d.PoolID, ip, nil); err != nil && err != ipamapi.ErrIPOutOfRange {
  1678  					return types.InternalErrorf("failed to allocate secondary ip address (%s:%s): %v", k, v, err)
  1679  				}
  1680  			}
  1681  		}
  1682  	}
  1683  
  1684  	return nil
  1685  }
  1686  
  1687  func (n *network) ipamRelease() {
  1688  	if n.hasSpecialDriver() {
  1689  		return
  1690  	}
  1691  	ipam, _, err := n.getController().getIPAMDriver(n.ipamType)
  1692  	if err != nil {
  1693  		logrus.Warnf("Failed to retrieve ipam driver to release address pool(s) on delete of network %s (%s): %v", n.Name(), n.ID(), err)
  1694  		return
  1695  	}
  1696  	n.ipamReleaseVersion(4, ipam)
  1697  	n.ipamReleaseVersion(6, ipam)
  1698  }
  1699  
  1700  func (n *network) ipamReleaseVersion(ipVer int, ipam ipamapi.Ipam) {
  1701  	var infoList *[]*IpamInfo
  1702  
  1703  	switch ipVer {
  1704  	case 4:
  1705  		infoList = &n.ipamV4Info
  1706  	case 6:
  1707  		infoList = &n.ipamV6Info
  1708  	default:
  1709  		logrus.Warnf("incorrect ip version passed to ipam release: %d", ipVer)
  1710  		return
  1711  	}
  1712  
  1713  	if len(*infoList) == 0 {
  1714  		return
  1715  	}
  1716  
  1717  	logrus.Debugf("releasing IPv%d pools from network %s (%s)", ipVer, n.Name(), n.ID())
  1718  
  1719  	for _, d := range *infoList {
  1720  		if d.Gateway != nil {
  1721  			if err := ipam.ReleaseAddress(d.PoolID, d.Gateway.IP); err != nil {
  1722  				logrus.Warnf("Failed to release gateway ip address %s on delete of network %s (%s): %v", d.Gateway.IP, n.Name(), n.ID(), err)
  1723  			}
  1724  		}
  1725  		if d.IPAMData.AuxAddresses != nil {
  1726  			for k, nw := range d.IPAMData.AuxAddresses {
  1727  				if d.Pool.Contains(nw.IP) {
  1728  					if err := ipam.ReleaseAddress(d.PoolID, nw.IP); err != nil && err != ipamapi.ErrIPOutOfRange {
  1729  						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)
  1730  					}
  1731  				}
  1732  			}
  1733  		}
  1734  		if err := ipam.ReleasePool(d.PoolID); err != nil {
  1735  			logrus.Warnf("Failed to release address pool %s on delete of network %s (%s): %v", d.PoolID, n.Name(), n.ID(), err)
  1736  		}
  1737  	}
  1738  
  1739  	*infoList = nil
  1740  }
  1741  
  1742  func (n *network) getIPInfo(ipVer int) []*IpamInfo {
  1743  	var info []*IpamInfo
  1744  	switch ipVer {
  1745  	case 4:
  1746  		info = n.ipamV4Info
  1747  	case 6:
  1748  		info = n.ipamV6Info
  1749  	default:
  1750  		return nil
  1751  	}
  1752  	l := make([]*IpamInfo, 0, len(info))
  1753  	n.Lock()
  1754  	l = append(l, info...)
  1755  	n.Unlock()
  1756  	return l
  1757  }
  1758  
  1759  func (n *network) getIPData(ipVer int) []driverapi.IPAMData {
  1760  	var info []*IpamInfo
  1761  	switch ipVer {
  1762  	case 4:
  1763  		info = n.ipamV4Info
  1764  	case 6:
  1765  		info = n.ipamV6Info
  1766  	default:
  1767  		return nil
  1768  	}
  1769  	l := make([]driverapi.IPAMData, 0, len(info))
  1770  	n.Lock()
  1771  	for _, d := range info {
  1772  		l = append(l, d.IPAMData)
  1773  	}
  1774  	n.Unlock()
  1775  	return l
  1776  }
  1777  
  1778  func (n *network) deriveAddressSpace() (string, error) {
  1779  	local, global, err := n.getController().drvRegistry.IPAMDefaultAddressSpaces(n.ipamType)
  1780  	if err != nil {
  1781  		return "", types.NotFoundErrorf("failed to get default address space: %v", err)
  1782  	}
  1783  	if n.DataScope() == datastore.GlobalScope {
  1784  		return global, nil
  1785  	}
  1786  	return local, nil
  1787  }
  1788  
  1789  func (n *network) Info() NetworkInfo {
  1790  	return n
  1791  }
  1792  
  1793  func (n *network) Peers() []networkdb.PeerInfo {
  1794  	if !n.Dynamic() {
  1795  		return []networkdb.PeerInfo{}
  1796  	}
  1797  
  1798  	agent := n.getController().getAgent()
  1799  	if agent == nil {
  1800  		return []networkdb.PeerInfo{}
  1801  	}
  1802  
  1803  	return agent.networkDB.Peers(n.ID())
  1804  }
  1805  
  1806  func (n *network) DriverOptions() map[string]string {
  1807  	n.Lock()
  1808  	defer n.Unlock()
  1809  	if n.generic != nil {
  1810  		if m, ok := n.generic[netlabel.GenericData]; ok {
  1811  			return m.(map[string]string)
  1812  		}
  1813  	}
  1814  	return map[string]string{}
  1815  }
  1816  
  1817  func (n *network) Scope() string {
  1818  	n.Lock()
  1819  	defer n.Unlock()
  1820  	return n.scope
  1821  }
  1822  
  1823  func (n *network) IpamConfig() (string, map[string]string, []*IpamConf, []*IpamConf) {
  1824  	n.Lock()
  1825  	defer n.Unlock()
  1826  
  1827  	v4L := make([]*IpamConf, len(n.ipamV4Config))
  1828  	v6L := make([]*IpamConf, len(n.ipamV6Config))
  1829  
  1830  	for i, c := range n.ipamV4Config {
  1831  		cc := &IpamConf{}
  1832  		if err := c.CopyTo(cc); err != nil {
  1833  			logrus.WithError(err).Error("Error copying ipam ipv4 config")
  1834  		}
  1835  		v4L[i] = cc
  1836  	}
  1837  
  1838  	for i, c := range n.ipamV6Config {
  1839  		cc := &IpamConf{}
  1840  		if err := c.CopyTo(cc); err != nil {
  1841  			logrus.WithError(err).Debug("Error copying ipam ipv6 config")
  1842  		}
  1843  		v6L[i] = cc
  1844  	}
  1845  
  1846  	return n.ipamType, n.ipamOptions, v4L, v6L
  1847  }
  1848  
  1849  func (n *network) IpamInfo() ([]*IpamInfo, []*IpamInfo) {
  1850  	n.Lock()
  1851  	defer n.Unlock()
  1852  
  1853  	v4Info := make([]*IpamInfo, len(n.ipamV4Info))
  1854  	v6Info := make([]*IpamInfo, len(n.ipamV6Info))
  1855  
  1856  	for i, info := range n.ipamV4Info {
  1857  		ic := &IpamInfo{}
  1858  		if err := info.CopyTo(ic); err != nil {
  1859  			logrus.WithError(err).Error("Error copying ipv4 ipam config")
  1860  		}
  1861  		v4Info[i] = ic
  1862  	}
  1863  
  1864  	for i, info := range n.ipamV6Info {
  1865  		ic := &IpamInfo{}
  1866  		if err := info.CopyTo(ic); err != nil {
  1867  			logrus.WithError(err).Error("Error copying ipv6 ipam config")
  1868  		}
  1869  		v6Info[i] = ic
  1870  	}
  1871  
  1872  	return v4Info, v6Info
  1873  }
  1874  
  1875  func (n *network) Internal() bool {
  1876  	n.Lock()
  1877  	defer n.Unlock()
  1878  
  1879  	return n.internal
  1880  }
  1881  
  1882  func (n *network) Attachable() bool {
  1883  	n.Lock()
  1884  	defer n.Unlock()
  1885  
  1886  	return n.attachable
  1887  }
  1888  
  1889  func (n *network) Ingress() bool {
  1890  	n.Lock()
  1891  	defer n.Unlock()
  1892  
  1893  	return n.ingress
  1894  }
  1895  
  1896  func (n *network) Dynamic() bool {
  1897  	n.Lock()
  1898  	defer n.Unlock()
  1899  
  1900  	return n.dynamic
  1901  }
  1902  
  1903  func (n *network) IPv6Enabled() bool {
  1904  	n.Lock()
  1905  	defer n.Unlock()
  1906  
  1907  	return n.enableIPv6
  1908  }
  1909  
  1910  func (n *network) ConfigFrom() string {
  1911  	n.Lock()
  1912  	defer n.Unlock()
  1913  
  1914  	return n.configFrom
  1915  }
  1916  
  1917  func (n *network) ConfigOnly() bool {
  1918  	n.Lock()
  1919  	defer n.Unlock()
  1920  
  1921  	return n.configOnly
  1922  }
  1923  
  1924  func (n *network) Labels() map[string]string {
  1925  	n.Lock()
  1926  	defer n.Unlock()
  1927  
  1928  	var lbls = make(map[string]string, len(n.labels))
  1929  	for k, v := range n.labels {
  1930  		lbls[k] = v
  1931  	}
  1932  
  1933  	return lbls
  1934  }
  1935  
  1936  func (n *network) TableEventRegister(tableName string, objType driverapi.ObjectType) error {
  1937  	if !driverapi.IsValidType(objType) {
  1938  		return fmt.Errorf("invalid object type %v in registering table, %s", objType, tableName)
  1939  	}
  1940  
  1941  	t := networkDBTable{
  1942  		name:    tableName,
  1943  		objType: objType,
  1944  	}
  1945  	n.Lock()
  1946  	defer n.Unlock()
  1947  	n.driverTables = append(n.driverTables, t)
  1948  	return nil
  1949  }
  1950  
  1951  func (n *network) UpdateIpamConfig(ipV4Data []driverapi.IPAMData) {
  1952  
  1953  	ipamV4Config := make([]*IpamConf, len(ipV4Data))
  1954  
  1955  	for i, data := range ipV4Data {
  1956  		ic := &IpamConf{}
  1957  		ic.PreferredPool = data.Pool.String()
  1958  		ic.Gateway = data.Gateway.IP.String()
  1959  		ipamV4Config[i] = ic
  1960  	}
  1961  
  1962  	n.Lock()
  1963  	defer n.Unlock()
  1964  	n.ipamV4Config = ipamV4Config
  1965  }
  1966  
  1967  // Special drivers are ones which do not need to perform any network plumbing
  1968  func (n *network) hasSpecialDriver() bool {
  1969  	return n.Type() == "host" || n.Type() == "null"
  1970  }
  1971  
  1972  func (n *network) hasLoadBalancerEndpoint() bool {
  1973  	return len(n.loadBalancerIP) != 0
  1974  }
  1975  
  1976  func (n *network) ResolveName(req string, ipType int) ([]net.IP, bool) {
  1977  	var ipv6Miss bool
  1978  
  1979  	c := n.getController()
  1980  	networkID := n.ID()
  1981  	c.Lock()
  1982  	defer c.Unlock()
  1983  	sr, ok := c.svcRecords[networkID]
  1984  
  1985  	if !ok {
  1986  		return nil, false
  1987  	}
  1988  
  1989  	req = strings.TrimSuffix(req, ".")
  1990  	req = strings.ToLower(req)
  1991  	ipSet, ok := sr.svcMap.Get(req)
  1992  
  1993  	if ipType == types.IPv6 {
  1994  		// If the name resolved to v4 address then its a valid name in
  1995  		// the docker network domain. If the network is not v6 enabled
  1996  		// set ipv6Miss to filter the DNS query from going to external
  1997  		// resolvers.
  1998  		if ok && !n.enableIPv6 {
  1999  			ipv6Miss = true
  2000  		}
  2001  		ipSet, ok = sr.svcIPv6Map.Get(req)
  2002  	}
  2003  
  2004  	if ok && len(ipSet) > 0 {
  2005  		// this map is to avoid IP duplicates, this can happen during a transition period where 2 services are using the same IP
  2006  		noDup := make(map[string]bool)
  2007  		var ipLocal []net.IP
  2008  		for _, ip := range ipSet {
  2009  			if _, dup := noDup[ip.(svcMapEntry).ip]; !dup {
  2010  				noDup[ip.(svcMapEntry).ip] = true
  2011  				ipLocal = append(ipLocal, net.ParseIP(ip.(svcMapEntry).ip))
  2012  			}
  2013  		}
  2014  		return ipLocal, ok
  2015  	}
  2016  
  2017  	return nil, ipv6Miss
  2018  }
  2019  
  2020  func (n *network) HandleQueryResp(name string, ip net.IP) {
  2021  	networkID := n.ID()
  2022  	c := n.getController()
  2023  	c.Lock()
  2024  	defer c.Unlock()
  2025  	sr, ok := c.svcRecords[networkID]
  2026  
  2027  	if !ok {
  2028  		return
  2029  	}
  2030  
  2031  	ipStr := netutils.ReverseIP(ip.String())
  2032  	// If an object with extResolver == true is already in the set this call will fail
  2033  	// but anyway it means that has already been inserted before
  2034  	if ok, _ := sr.ipMap.Contains(ipStr, ipInfo{name: name}); ok {
  2035  		sr.ipMap.Remove(ipStr, ipInfo{name: name})
  2036  		sr.ipMap.Insert(ipStr, ipInfo{name: name, extResolver: true})
  2037  	}
  2038  }
  2039  
  2040  func (n *network) ResolveIP(ip string) string {
  2041  	networkID := n.ID()
  2042  	c := n.getController()
  2043  	c.Lock()
  2044  	defer c.Unlock()
  2045  	sr, ok := c.svcRecords[networkID]
  2046  
  2047  	if !ok {
  2048  		return ""
  2049  	}
  2050  
  2051  	nwName := n.Name()
  2052  
  2053  	elemSet, ok := sr.ipMap.Get(ip)
  2054  	if !ok || len(elemSet) == 0 {
  2055  		return ""
  2056  	}
  2057  	// NOTE it is possible to have more than one element in the Set, this will happen
  2058  	// because of interleave of different events from different sources (local container create vs
  2059  	// network db notifications)
  2060  	// In such cases the resolution will be based on the first element of the set, and can vary
  2061  	// during the system stabilitation
  2062  	elem, ok := elemSet[0].(ipInfo)
  2063  	if !ok {
  2064  		setStr, b := sr.ipMap.String(ip)
  2065  		logrus.Errorf("expected set of ipInfo type for key %s set:%t %s", ip, b, setStr)
  2066  		return ""
  2067  	}
  2068  
  2069  	if elem.extResolver {
  2070  		return ""
  2071  	}
  2072  
  2073  	return elem.name + "." + nwName
  2074  }
  2075  
  2076  func (n *network) ResolveService(name string) ([]*net.SRV, []net.IP) {
  2077  	c := n.getController()
  2078  
  2079  	srv := []*net.SRV{}
  2080  	ip := []net.IP{}
  2081  
  2082  	logrus.Debugf("Service name To resolve: %v", name)
  2083  
  2084  	// There are DNS implementations that allow SRV queries for names not in
  2085  	// the format defined by RFC 2782. Hence specific validations checks are
  2086  	// not done
  2087  	parts := strings.Split(name, ".")
  2088  	if len(parts) < 3 {
  2089  		return nil, nil
  2090  	}
  2091  
  2092  	portName := parts[0]
  2093  	proto := parts[1]
  2094  	svcName := strings.Join(parts[2:], ".")
  2095  
  2096  	networkID := n.ID()
  2097  	c.Lock()
  2098  	defer c.Unlock()
  2099  	sr, ok := c.svcRecords[networkID]
  2100  
  2101  	if !ok {
  2102  		return nil, nil
  2103  	}
  2104  
  2105  	svcs, ok := sr.service[svcName]
  2106  	if !ok {
  2107  		return nil, nil
  2108  	}
  2109  
  2110  	for _, svc := range svcs {
  2111  		if svc.portName != portName {
  2112  			continue
  2113  		}
  2114  		if svc.proto != proto {
  2115  			continue
  2116  		}
  2117  		for _, t := range svc.target {
  2118  			srv = append(srv,
  2119  				&net.SRV{
  2120  					Target: t.name,
  2121  					Port:   t.port,
  2122  				})
  2123  
  2124  			ip = append(ip, t.ip)
  2125  		}
  2126  	}
  2127  
  2128  	return srv, ip
  2129  }
  2130  
  2131  func (n *network) ExecFunc(f func()) error {
  2132  	return types.NotImplementedErrorf("ExecFunc not supported by network")
  2133  }
  2134  
  2135  func (n *network) NdotsSet() bool {
  2136  	return false
  2137  }
  2138  
  2139  // config-only network is looked up by name
  2140  func (c *controller) getConfigNetwork(name string) (*network, error) {
  2141  	var n Network
  2142  
  2143  	s := func(current Network) bool {
  2144  		if current.Info().ConfigOnly() && current.Name() == name {
  2145  			n = current
  2146  			return true
  2147  		}
  2148  		return false
  2149  	}
  2150  
  2151  	c.WalkNetworks(s)
  2152  
  2153  	if n == nil {
  2154  		return nil, types.NotFoundErrorf("configuration network %q not found", name)
  2155  	}
  2156  
  2157  	return n.(*network), nil
  2158  }
  2159  
  2160  func (n *network) lbSandboxName() string {
  2161  	name := "lb-" + n.name
  2162  	if n.ingress {
  2163  		name = n.name + "-sbox"
  2164  	}
  2165  	return name
  2166  }
  2167  
  2168  func (n *network) lbEndpointName() string {
  2169  	return n.name + "-endpoint"
  2170  }
  2171  
  2172  func (n *network) createLoadBalancerSandbox() (retErr error) {
  2173  	sandboxName := n.lbSandboxName()
  2174  	// Mark the sandbox to be a load balancer
  2175  	sbOptions := []SandboxOption{OptionLoadBalancer(n.id)}
  2176  	if n.ingress {
  2177  		sbOptions = append(sbOptions, OptionIngress())
  2178  	}
  2179  	sb, err := n.ctrlr.NewSandbox(sandboxName, sbOptions...)
  2180  	if err != nil {
  2181  		return err
  2182  	}
  2183  	defer func() {
  2184  		if retErr != nil {
  2185  			if e := n.ctrlr.SandboxDestroy(sandboxName); e != nil {
  2186  				logrus.Warnf("could not delete sandbox %s on failure on failure (%v): %v", sandboxName, retErr, e)
  2187  			}
  2188  		}
  2189  	}()
  2190  
  2191  	endpointName := n.lbEndpointName()
  2192  	epOptions := []EndpointOption{
  2193  		CreateOptionIpam(n.loadBalancerIP, nil, nil, nil),
  2194  		CreateOptionLoadBalancer(),
  2195  	}
  2196  	if n.hasLoadBalancerEndpoint() && !n.ingress {
  2197  		// Mark LB endpoints as anonymous so they don't show up in DNS
  2198  		epOptions = append(epOptions, CreateOptionAnonymous())
  2199  	}
  2200  	ep, err := n.createEndpoint(endpointName, epOptions...)
  2201  	if err != nil {
  2202  		return err
  2203  	}
  2204  	defer func() {
  2205  		if retErr != nil {
  2206  			if e := ep.Delete(true); e != nil {
  2207  				logrus.Warnf("could not delete endpoint %s on failure on failure (%v): %v", endpointName, retErr, e)
  2208  			}
  2209  		}
  2210  	}()
  2211  
  2212  	if err := ep.Join(sb, nil); err != nil {
  2213  		return err
  2214  	}
  2215  
  2216  	return sb.EnableService()
  2217  }
  2218  
  2219  func (n *network) deleteLoadBalancerSandbox() error {
  2220  	n.Lock()
  2221  	c := n.ctrlr
  2222  	name := n.name
  2223  	n.Unlock()
  2224  
  2225  	sandboxName := n.lbSandboxName()
  2226  	endpointName := n.lbEndpointName()
  2227  
  2228  	endpoint, err := n.EndpointByName(endpointName)
  2229  	if err != nil {
  2230  		logrus.Warnf("Failed to find load balancer endpoint %s on network %s: %v", endpointName, name, err)
  2231  	} else {
  2232  
  2233  		info := endpoint.Info()
  2234  		if info != nil {
  2235  			sb := info.Sandbox()
  2236  			if sb != nil {
  2237  				if err := sb.DisableService(); err != nil {
  2238  					logrus.Warnf("Failed to disable service on sandbox %s: %v", sandboxName, err)
  2239  					// Ignore error and attempt to delete the load balancer endpoint
  2240  				}
  2241  			}
  2242  		}
  2243  
  2244  		if err := endpoint.Delete(true); err != nil {
  2245  			logrus.Warnf("Failed to delete endpoint %s (%s) in %s: %v", endpoint.Name(), endpoint.ID(), sandboxName, err)
  2246  			// Ignore error and attempt to delete the sandbox.
  2247  		}
  2248  	}
  2249  
  2250  	if err := c.SandboxDestroy(sandboxName); err != nil {
  2251  		return fmt.Errorf("Failed to delete %s sandbox: %v", sandboxName, err)
  2252  	}
  2253  	return nil
  2254  }