github.com/opsramp/moby@v1.13.1/daemon/container_operations.go (about)

     1  package daemon
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"net"
     7  	"os"
     8  	"path"
     9  	"runtime"
    10  	"strings"
    11  	"time"
    12  
    13  	"github.com/Sirupsen/logrus"
    14  	derr "github.com/docker/docker/api/errors"
    15  	containertypes "github.com/docker/docker/api/types/container"
    16  	networktypes "github.com/docker/docker/api/types/network"
    17  	"github.com/docker/docker/container"
    18  	"github.com/docker/docker/daemon/network"
    19  	"github.com/docker/docker/pkg/stringid"
    20  	"github.com/docker/docker/runconfig"
    21  	"github.com/docker/go-connections/nat"
    22  	"github.com/docker/libnetwork"
    23  	"github.com/docker/libnetwork/netlabel"
    24  	"github.com/docker/libnetwork/options"
    25  	"github.com/docker/libnetwork/types"
    26  )
    27  
    28  var (
    29  	// ErrRootFSReadOnly is returned when a container
    30  	// rootfs is marked readonly.
    31  	ErrRootFSReadOnly = errors.New("container rootfs is marked read-only")
    32  	getPortMapInfo    = container.GetSandboxPortMapInfo
    33  )
    34  
    35  func (daemon *Daemon) buildSandboxOptions(container *container.Container) ([]libnetwork.SandboxOption, error) {
    36  	var (
    37  		sboxOptions []libnetwork.SandboxOption
    38  		err         error
    39  		dns         []string
    40  		dnsSearch   []string
    41  		dnsOptions  []string
    42  		bindings    = make(nat.PortMap)
    43  		pbList      []types.PortBinding
    44  		exposeList  []types.TransportPort
    45  	)
    46  
    47  	defaultNetName := runconfig.DefaultDaemonNetworkMode().NetworkName()
    48  	sboxOptions = append(sboxOptions, libnetwork.OptionHostname(container.Config.Hostname),
    49  		libnetwork.OptionDomainname(container.Config.Domainname))
    50  
    51  	if container.HostConfig.NetworkMode.IsHost() {
    52  		sboxOptions = append(sboxOptions, libnetwork.OptionUseDefaultSandbox())
    53  		if len(container.HostConfig.ExtraHosts) == 0 {
    54  			sboxOptions = append(sboxOptions, libnetwork.OptionOriginHostsPath("/etc/hosts"))
    55  		}
    56  		if len(container.HostConfig.DNS) == 0 && len(daemon.configStore.DNS) == 0 &&
    57  			len(container.HostConfig.DNSSearch) == 0 && len(daemon.configStore.DNSSearch) == 0 &&
    58  			len(container.HostConfig.DNSOptions) == 0 && len(daemon.configStore.DNSOptions) == 0 {
    59  			sboxOptions = append(sboxOptions, libnetwork.OptionOriginResolvConfPath("/etc/resolv.conf"))
    60  		}
    61  	} else {
    62  		// OptionUseExternalKey is mandatory for userns support.
    63  		// But optional for non-userns support
    64  		sboxOptions = append(sboxOptions, libnetwork.OptionUseExternalKey())
    65  	}
    66  
    67  	if err = setupPathsAndSandboxOptions(container, &sboxOptions); err != nil {
    68  		return nil, err
    69  	}
    70  
    71  	if len(container.HostConfig.DNS) > 0 {
    72  		dns = container.HostConfig.DNS
    73  	} else if len(daemon.configStore.DNS) > 0 {
    74  		dns = daemon.configStore.DNS
    75  	}
    76  
    77  	for _, d := range dns {
    78  		sboxOptions = append(sboxOptions, libnetwork.OptionDNS(d))
    79  	}
    80  
    81  	if len(container.HostConfig.DNSSearch) > 0 {
    82  		dnsSearch = container.HostConfig.DNSSearch
    83  	} else if len(daemon.configStore.DNSSearch) > 0 {
    84  		dnsSearch = daemon.configStore.DNSSearch
    85  	}
    86  
    87  	for _, ds := range dnsSearch {
    88  		sboxOptions = append(sboxOptions, libnetwork.OptionDNSSearch(ds))
    89  	}
    90  
    91  	if len(container.HostConfig.DNSOptions) > 0 {
    92  		dnsOptions = container.HostConfig.DNSOptions
    93  	} else if len(daemon.configStore.DNSOptions) > 0 {
    94  		dnsOptions = daemon.configStore.DNSOptions
    95  	}
    96  
    97  	for _, ds := range dnsOptions {
    98  		sboxOptions = append(sboxOptions, libnetwork.OptionDNSOptions(ds))
    99  	}
   100  
   101  	if container.NetworkSettings.SecondaryIPAddresses != nil {
   102  		name := container.Config.Hostname
   103  		if container.Config.Domainname != "" {
   104  			name = name + "." + container.Config.Domainname
   105  		}
   106  
   107  		for _, a := range container.NetworkSettings.SecondaryIPAddresses {
   108  			sboxOptions = append(sboxOptions, libnetwork.OptionExtraHost(name, a.Addr))
   109  		}
   110  	}
   111  
   112  	for _, extraHost := range container.HostConfig.ExtraHosts {
   113  		// allow IPv6 addresses in extra hosts; only split on first ":"
   114  		parts := strings.SplitN(extraHost, ":", 2)
   115  		sboxOptions = append(sboxOptions, libnetwork.OptionExtraHost(parts[0], parts[1]))
   116  	}
   117  
   118  	if container.HostConfig.PortBindings != nil {
   119  		for p, b := range container.HostConfig.PortBindings {
   120  			bindings[p] = []nat.PortBinding{}
   121  			for _, bb := range b {
   122  				bindings[p] = append(bindings[p], nat.PortBinding{
   123  					HostIP:   bb.HostIP,
   124  					HostPort: bb.HostPort,
   125  				})
   126  			}
   127  		}
   128  	}
   129  
   130  	portSpecs := container.Config.ExposedPorts
   131  	ports := make([]nat.Port, len(portSpecs))
   132  	var i int
   133  	for p := range portSpecs {
   134  		ports[i] = p
   135  		i++
   136  	}
   137  	nat.SortPortMap(ports, bindings)
   138  	for _, port := range ports {
   139  		expose := types.TransportPort{}
   140  		expose.Proto = types.ParseProtocol(port.Proto())
   141  		expose.Port = uint16(port.Int())
   142  		exposeList = append(exposeList, expose)
   143  
   144  		pb := types.PortBinding{Port: expose.Port, Proto: expose.Proto}
   145  		binding := bindings[port]
   146  		for i := 0; i < len(binding); i++ {
   147  			pbCopy := pb.GetCopy()
   148  			newP, err := nat.NewPort(nat.SplitProtoPort(binding[i].HostPort))
   149  			var portStart, portEnd int
   150  			if err == nil {
   151  				portStart, portEnd, err = newP.Range()
   152  			}
   153  			if err != nil {
   154  				return nil, fmt.Errorf("Error parsing HostPort value(%s):%v", binding[i].HostPort, err)
   155  			}
   156  			pbCopy.HostPort = uint16(portStart)
   157  			pbCopy.HostPortEnd = uint16(portEnd)
   158  			pbCopy.HostIP = net.ParseIP(binding[i].HostIP)
   159  			pbList = append(pbList, pbCopy)
   160  		}
   161  
   162  		if container.HostConfig.PublishAllPorts && len(binding) == 0 {
   163  			pbList = append(pbList, pb)
   164  		}
   165  	}
   166  
   167  	sboxOptions = append(sboxOptions,
   168  		libnetwork.OptionPortMapping(pbList),
   169  		libnetwork.OptionExposedPorts(exposeList))
   170  
   171  	// Legacy Link feature is supported only for the default bridge network.
   172  	// return if this call to build join options is not for default bridge network
   173  	// Legacy Link is only supported by docker run --link
   174  	bridgeSettings, ok := container.NetworkSettings.Networks[defaultNetName]
   175  	if !ok || bridgeSettings.EndpointSettings == nil {
   176  		return sboxOptions, nil
   177  	}
   178  
   179  	if bridgeSettings.EndpointID == "" {
   180  		return sboxOptions, nil
   181  	}
   182  
   183  	var (
   184  		childEndpoints, parentEndpoints []string
   185  		cEndpointID                     string
   186  	)
   187  
   188  	children := daemon.children(container)
   189  	for linkAlias, child := range children {
   190  		if !isLinkable(child) {
   191  			return nil, fmt.Errorf("Cannot link to %s, as it does not belong to the default network", child.Name)
   192  		}
   193  		_, alias := path.Split(linkAlias)
   194  		// allow access to the linked container via the alias, real name, and container hostname
   195  		aliasList := alias + " " + child.Config.Hostname
   196  		// only add the name if alias isn't equal to the name
   197  		if alias != child.Name[1:] {
   198  			aliasList = aliasList + " " + child.Name[1:]
   199  		}
   200  		sboxOptions = append(sboxOptions, libnetwork.OptionExtraHost(aliasList, child.NetworkSettings.Networks[defaultNetName].IPAddress))
   201  		cEndpointID = child.NetworkSettings.Networks[defaultNetName].EndpointID
   202  		if cEndpointID != "" {
   203  			childEndpoints = append(childEndpoints, cEndpointID)
   204  		}
   205  	}
   206  
   207  	for alias, parent := range daemon.parents(container) {
   208  		if daemon.configStore.DisableBridge || !container.HostConfig.NetworkMode.IsPrivate() {
   209  			continue
   210  		}
   211  
   212  		_, alias = path.Split(alias)
   213  		logrus.Debugf("Update /etc/hosts of %s for alias %s with ip %s", parent.ID, alias, bridgeSettings.IPAddress)
   214  		sboxOptions = append(sboxOptions, libnetwork.OptionParentUpdate(
   215  			parent.ID,
   216  			alias,
   217  			bridgeSettings.IPAddress,
   218  		))
   219  		if cEndpointID != "" {
   220  			parentEndpoints = append(parentEndpoints, cEndpointID)
   221  		}
   222  	}
   223  
   224  	linkOptions := options.Generic{
   225  		netlabel.GenericData: options.Generic{
   226  			"ParentEndpoints": parentEndpoints,
   227  			"ChildEndpoints":  childEndpoints,
   228  		},
   229  	}
   230  
   231  	sboxOptions = append(sboxOptions, libnetwork.OptionGeneric(linkOptions))
   232  	return sboxOptions, nil
   233  }
   234  
   235  func (daemon *Daemon) updateNetworkSettings(container *container.Container, n libnetwork.Network, endpointConfig *networktypes.EndpointSettings) error {
   236  	if container.NetworkSettings == nil {
   237  		container.NetworkSettings = &network.Settings{Networks: make(map[string]*network.EndpointSettings)}
   238  	}
   239  
   240  	if !container.HostConfig.NetworkMode.IsHost() && containertypes.NetworkMode(n.Type()).IsHost() {
   241  		return runconfig.ErrConflictHostNetwork
   242  	}
   243  
   244  	for s := range container.NetworkSettings.Networks {
   245  		sn, err := daemon.FindNetwork(s)
   246  		if err != nil {
   247  			continue
   248  		}
   249  
   250  		if sn.Name() == n.Name() {
   251  			// Avoid duplicate config
   252  			return nil
   253  		}
   254  		if !containertypes.NetworkMode(sn.Type()).IsPrivate() ||
   255  			!containertypes.NetworkMode(n.Type()).IsPrivate() {
   256  			return runconfig.ErrConflictSharedNetwork
   257  		}
   258  		if containertypes.NetworkMode(sn.Name()).IsNone() ||
   259  			containertypes.NetworkMode(n.Name()).IsNone() {
   260  			return runconfig.ErrConflictNoNetwork
   261  		}
   262  	}
   263  
   264  	if _, ok := container.NetworkSettings.Networks[n.Name()]; !ok {
   265  		container.NetworkSettings.Networks[n.Name()] = &network.EndpointSettings{
   266  			EndpointSettings: endpointConfig,
   267  		}
   268  	}
   269  
   270  	return nil
   271  }
   272  
   273  func (daemon *Daemon) updateEndpointNetworkSettings(container *container.Container, n libnetwork.Network, ep libnetwork.Endpoint) error {
   274  	if err := container.BuildEndpointInfo(n, ep); err != nil {
   275  		return err
   276  	}
   277  
   278  	if container.HostConfig.NetworkMode == runconfig.DefaultDaemonNetworkMode() {
   279  		container.NetworkSettings.Bridge = daemon.configStore.bridgeConfig.Iface
   280  	}
   281  
   282  	return nil
   283  }
   284  
   285  // UpdateNetwork is used to update the container's network (e.g. when linked containers
   286  // get removed/unlinked).
   287  func (daemon *Daemon) updateNetwork(container *container.Container) error {
   288  	var (
   289  		start = time.Now()
   290  		ctrl  = daemon.netController
   291  		sid   = container.NetworkSettings.SandboxID
   292  	)
   293  
   294  	sb, err := ctrl.SandboxByID(sid)
   295  	if err != nil {
   296  		return fmt.Errorf("error locating sandbox id %s: %v", sid, err)
   297  	}
   298  
   299  	// Find if container is connected to the default bridge network
   300  	var n libnetwork.Network
   301  	for name := range container.NetworkSettings.Networks {
   302  		sn, err := daemon.FindNetwork(name)
   303  		if err != nil {
   304  			continue
   305  		}
   306  		if sn.Name() == runconfig.DefaultDaemonNetworkMode().NetworkName() {
   307  			n = sn
   308  			break
   309  		}
   310  	}
   311  
   312  	if n == nil {
   313  		// Not connected to the default bridge network; Nothing to do
   314  		return nil
   315  	}
   316  
   317  	options, err := daemon.buildSandboxOptions(container)
   318  	if err != nil {
   319  		return fmt.Errorf("Update network failed: %v", err)
   320  	}
   321  
   322  	if err := sb.Refresh(options...); err != nil {
   323  		return fmt.Errorf("Update network failed: Failure in refresh sandbox %s: %v", sid, err)
   324  	}
   325  
   326  	networkActions.WithValues("update").UpdateSince(start)
   327  
   328  	return nil
   329  }
   330  
   331  func (daemon *Daemon) findAndAttachNetwork(container *container.Container, idOrName string, epConfig *networktypes.EndpointSettings) (libnetwork.Network, *networktypes.NetworkingConfig, error) {
   332  	n, err := daemon.FindNetwork(idOrName)
   333  	if err != nil {
   334  		// We should always be able to find the network for a
   335  		// managed container.
   336  		if container.Managed {
   337  			return nil, nil, err
   338  		}
   339  	}
   340  
   341  	// If we found a network and if it is not dynamically created
   342  	// we should never attempt to attach to that network here.
   343  	if n != nil {
   344  		if container.Managed || !n.Info().Dynamic() {
   345  			return n, nil, nil
   346  		}
   347  	}
   348  
   349  	var addresses []string
   350  	if epConfig != nil && epConfig.IPAMConfig != nil {
   351  		if epConfig.IPAMConfig.IPv4Address != "" {
   352  			addresses = append(addresses, epConfig.IPAMConfig.IPv4Address)
   353  		}
   354  
   355  		if epConfig.IPAMConfig.IPv6Address != "" {
   356  			addresses = append(addresses, epConfig.IPAMConfig.IPv6Address)
   357  		}
   358  	}
   359  
   360  	var (
   361  		config     *networktypes.NetworkingConfig
   362  		retryCount int
   363  	)
   364  
   365  	for {
   366  		// In all other cases, attempt to attach to the network to
   367  		// trigger attachment in the swarm cluster manager.
   368  		if daemon.clusterProvider != nil {
   369  			var err error
   370  			config, err = daemon.clusterProvider.AttachNetwork(idOrName, container.ID, addresses)
   371  			if err != nil {
   372  				return nil, nil, err
   373  			}
   374  		}
   375  
   376  		n, err = daemon.FindNetwork(idOrName)
   377  		if err != nil {
   378  			if daemon.clusterProvider != nil {
   379  				if err := daemon.clusterProvider.DetachNetwork(idOrName, container.ID); err != nil {
   380  					logrus.Warnf("Could not rollback attachment for container %s to network %s: %v", container.ID, idOrName, err)
   381  				}
   382  			}
   383  
   384  			// Retry network attach again if we failed to
   385  			// find the network after successfull
   386  			// attachment because the only reason that
   387  			// would happen is if some other container
   388  			// attached to the swarm scope network went down
   389  			// and removed the network while we were in
   390  			// the process of attaching.
   391  			if config != nil {
   392  				if _, ok := err.(libnetwork.ErrNoSuchNetwork); ok {
   393  					if retryCount >= 5 {
   394  						return nil, nil, fmt.Errorf("could not find network %s after successful attachment", idOrName)
   395  					}
   396  					retryCount++
   397  					continue
   398  				}
   399  			}
   400  
   401  			return nil, nil, err
   402  		}
   403  
   404  		break
   405  	}
   406  
   407  	// This container has attachment to a swarm scope
   408  	// network. Update the container network settings accordingly.
   409  	container.NetworkSettings.HasSwarmEndpoint = true
   410  	return n, config, nil
   411  }
   412  
   413  // updateContainerNetworkSettings update the network settings
   414  func (daemon *Daemon) updateContainerNetworkSettings(container *container.Container, endpointsConfig map[string]*networktypes.EndpointSettings) {
   415  	var n libnetwork.Network
   416  
   417  	mode := container.HostConfig.NetworkMode
   418  	if container.Config.NetworkDisabled || mode.IsContainer() {
   419  		return
   420  	}
   421  
   422  	networkName := mode.NetworkName()
   423  	if mode.IsDefault() {
   424  		networkName = daemon.netController.Config().Daemon.DefaultNetwork
   425  	}
   426  
   427  	if mode.IsUserDefined() {
   428  		var err error
   429  
   430  		n, err = daemon.FindNetwork(networkName)
   431  		if err == nil {
   432  			networkName = n.Name()
   433  		}
   434  	}
   435  
   436  	if container.NetworkSettings == nil {
   437  		container.NetworkSettings = &network.Settings{}
   438  	}
   439  
   440  	if len(endpointsConfig) > 0 {
   441  		if container.NetworkSettings.Networks == nil {
   442  			container.NetworkSettings.Networks = make(map[string]*network.EndpointSettings)
   443  		}
   444  
   445  		for name, epConfig := range endpointsConfig {
   446  			container.NetworkSettings.Networks[name] = &network.EndpointSettings{
   447  				EndpointSettings: epConfig,
   448  			}
   449  		}
   450  	}
   451  
   452  	if container.NetworkSettings.Networks == nil {
   453  		container.NetworkSettings.Networks = make(map[string]*network.EndpointSettings)
   454  		container.NetworkSettings.Networks[networkName] = &network.EndpointSettings{
   455  			EndpointSettings: &networktypes.EndpointSettings{},
   456  		}
   457  	}
   458  
   459  	// Convert any settings added by client in default name to
   460  	// engine's default network name key
   461  	if mode.IsDefault() {
   462  		if nConf, ok := container.NetworkSettings.Networks[mode.NetworkName()]; ok {
   463  			container.NetworkSettings.Networks[networkName] = nConf
   464  			delete(container.NetworkSettings.Networks, mode.NetworkName())
   465  		}
   466  	}
   467  
   468  	if !mode.IsUserDefined() {
   469  		return
   470  	}
   471  	// Make sure to internally store the per network endpoint config by network name
   472  	if _, ok := container.NetworkSettings.Networks[networkName]; ok {
   473  		return
   474  	}
   475  
   476  	if n != nil {
   477  		if nwConfig, ok := container.NetworkSettings.Networks[n.ID()]; ok {
   478  			container.NetworkSettings.Networks[networkName] = nwConfig
   479  			delete(container.NetworkSettings.Networks, n.ID())
   480  			return
   481  		}
   482  	}
   483  }
   484  
   485  func (daemon *Daemon) allocateNetwork(container *container.Container) error {
   486  	start := time.Now()
   487  	controller := daemon.netController
   488  
   489  	if daemon.netController == nil {
   490  		return nil
   491  	}
   492  
   493  	// Cleanup any stale sandbox left over due to ungraceful daemon shutdown
   494  	if err := controller.SandboxDestroy(container.ID); err != nil {
   495  		logrus.Errorf("failed to cleanup up stale network sandbox for container %s", container.ID)
   496  	}
   497  
   498  	updateSettings := false
   499  	if len(container.NetworkSettings.Networks) == 0 {
   500  		if container.Config.NetworkDisabled || container.HostConfig.NetworkMode.IsContainer() {
   501  			return nil
   502  		}
   503  
   504  		daemon.updateContainerNetworkSettings(container, nil)
   505  		updateSettings = true
   506  	}
   507  
   508  	// always connect default network first since only default
   509  	// network mode support link and we need do some setting
   510  	// on sandbox initialize for link, but the sandbox only be initialized
   511  	// on first network connecting.
   512  	defaultNetName := runconfig.DefaultDaemonNetworkMode().NetworkName()
   513  	if nConf, ok := container.NetworkSettings.Networks[defaultNetName]; ok {
   514  		cleanOperationalData(nConf)
   515  		if err := daemon.connectToNetwork(container, defaultNetName, nConf.EndpointSettings, updateSettings); err != nil {
   516  			return err
   517  		}
   518  
   519  	}
   520  
   521  	// the intermediate map is necessary because "connectToNetwork" modifies "container.NetworkSettings.Networks"
   522  	networks := make(map[string]*network.EndpointSettings)
   523  	for n, epConf := range container.NetworkSettings.Networks {
   524  		if n == defaultNetName {
   525  			continue
   526  		}
   527  
   528  		networks[n] = epConf
   529  	}
   530  
   531  	for netName, epConf := range networks {
   532  		cleanOperationalData(epConf)
   533  		if err := daemon.connectToNetwork(container, netName, epConf.EndpointSettings, updateSettings); err != nil {
   534  			return err
   535  		}
   536  	}
   537  
   538  	if err := container.WriteHostConfig(); err != nil {
   539  		return err
   540  	}
   541  	networkActions.WithValues("allocate").UpdateSince(start)
   542  	return nil
   543  }
   544  
   545  func (daemon *Daemon) getNetworkSandbox(container *container.Container) libnetwork.Sandbox {
   546  	var sb libnetwork.Sandbox
   547  	daemon.netController.WalkSandboxes(func(s libnetwork.Sandbox) bool {
   548  		if s.ContainerID() == container.ID {
   549  			sb = s
   550  			return true
   551  		}
   552  		return false
   553  	})
   554  	return sb
   555  }
   556  
   557  // hasUserDefinedIPAddress returns whether the passed endpoint configuration contains IP address configuration
   558  func hasUserDefinedIPAddress(epConfig *networktypes.EndpointSettings) bool {
   559  	return epConfig != nil && epConfig.IPAMConfig != nil && (len(epConfig.IPAMConfig.IPv4Address) > 0 || len(epConfig.IPAMConfig.IPv6Address) > 0)
   560  }
   561  
   562  // User specified ip address is acceptable only for networks with user specified subnets.
   563  func validateNetworkingConfig(n libnetwork.Network, epConfig *networktypes.EndpointSettings) error {
   564  	if n == nil || epConfig == nil {
   565  		return nil
   566  	}
   567  	if !hasUserDefinedIPAddress(epConfig) {
   568  		return nil
   569  	}
   570  	_, _, nwIPv4Configs, nwIPv6Configs := n.Info().IpamConfig()
   571  	for _, s := range []struct {
   572  		ipConfigured  bool
   573  		subnetConfigs []*libnetwork.IpamConf
   574  	}{
   575  		{
   576  			ipConfigured:  len(epConfig.IPAMConfig.IPv4Address) > 0,
   577  			subnetConfigs: nwIPv4Configs,
   578  		},
   579  		{
   580  			ipConfigured:  len(epConfig.IPAMConfig.IPv6Address) > 0,
   581  			subnetConfigs: nwIPv6Configs,
   582  		},
   583  	} {
   584  		if s.ipConfigured {
   585  			foundSubnet := false
   586  			for _, cfg := range s.subnetConfigs {
   587  				if len(cfg.PreferredPool) > 0 {
   588  					foundSubnet = true
   589  					break
   590  				}
   591  			}
   592  			if !foundSubnet {
   593  				return runconfig.ErrUnsupportedNetworkNoSubnetAndIP
   594  			}
   595  		}
   596  	}
   597  
   598  	return nil
   599  }
   600  
   601  // cleanOperationalData resets the operational data from the passed endpoint settings
   602  func cleanOperationalData(es *network.EndpointSettings) {
   603  	es.EndpointID = ""
   604  	es.Gateway = ""
   605  	es.IPAddress = ""
   606  	es.IPPrefixLen = 0
   607  	es.IPv6Gateway = ""
   608  	es.GlobalIPv6Address = ""
   609  	es.GlobalIPv6PrefixLen = 0
   610  	es.MacAddress = ""
   611  	if es.IPAMOperational {
   612  		es.IPAMConfig = nil
   613  	}
   614  }
   615  
   616  func (daemon *Daemon) updateNetworkConfig(container *container.Container, n libnetwork.Network, endpointConfig *networktypes.EndpointSettings, updateSettings bool) error {
   617  
   618  	if !containertypes.NetworkMode(n.Name()).IsUserDefined() {
   619  		if hasUserDefinedIPAddress(endpointConfig) && !enableIPOnPredefinedNetwork() {
   620  			return runconfig.ErrUnsupportedNetworkAndIP
   621  		}
   622  		if endpointConfig != nil && len(endpointConfig.Aliases) > 0 && !container.EnableServiceDiscoveryOnDefaultNetwork() {
   623  			return runconfig.ErrUnsupportedNetworkAndAlias
   624  		}
   625  	} else {
   626  		addShortID := true
   627  		shortID := stringid.TruncateID(container.ID)
   628  		for _, alias := range endpointConfig.Aliases {
   629  			if alias == shortID {
   630  				addShortID = false
   631  				break
   632  			}
   633  		}
   634  		if addShortID {
   635  			endpointConfig.Aliases = append(endpointConfig.Aliases, shortID)
   636  		}
   637  	}
   638  
   639  	if err := validateNetworkingConfig(n, endpointConfig); err != nil {
   640  		return err
   641  	}
   642  
   643  	if updateSettings {
   644  		if err := daemon.updateNetworkSettings(container, n, endpointConfig); err != nil {
   645  			return err
   646  		}
   647  	}
   648  	return nil
   649  }
   650  
   651  func (daemon *Daemon) connectToNetwork(container *container.Container, idOrName string, endpointConfig *networktypes.EndpointSettings, updateSettings bool) (err error) {
   652  	start := time.Now()
   653  	if container.HostConfig.NetworkMode.IsContainer() {
   654  		return runconfig.ErrConflictSharedNetwork
   655  	}
   656  	if containertypes.NetworkMode(idOrName).IsBridge() &&
   657  		daemon.configStore.DisableBridge {
   658  		container.Config.NetworkDisabled = true
   659  		return nil
   660  	}
   661  	if endpointConfig == nil {
   662  		endpointConfig = &networktypes.EndpointSettings{}
   663  	}
   664  
   665  	n, config, err := daemon.findAndAttachNetwork(container, idOrName, endpointConfig)
   666  	if err != nil {
   667  		return err
   668  	}
   669  	if n == nil {
   670  		return nil
   671  	}
   672  
   673  	var operIPAM bool
   674  	if config != nil {
   675  		if epConfig, ok := config.EndpointsConfig[n.Name()]; ok {
   676  			if endpointConfig.IPAMConfig == nil ||
   677  				(endpointConfig.IPAMConfig.IPv4Address == "" &&
   678  					endpointConfig.IPAMConfig.IPv6Address == "" &&
   679  					len(endpointConfig.IPAMConfig.LinkLocalIPs) == 0) {
   680  				operIPAM = true
   681  			}
   682  
   683  			// copy IPAMConfig and NetworkID from epConfig via AttachNetwork
   684  			endpointConfig.IPAMConfig = epConfig.IPAMConfig
   685  			endpointConfig.NetworkID = epConfig.NetworkID
   686  		}
   687  	}
   688  
   689  	err = daemon.updateNetworkConfig(container, n, endpointConfig, updateSettings)
   690  	if err != nil {
   691  		return err
   692  	}
   693  
   694  	controller := daemon.netController
   695  	sb := daemon.getNetworkSandbox(container)
   696  	createOptions, err := container.BuildCreateEndpointOptions(n, endpointConfig, sb, daemon.configStore.DNS)
   697  	if err != nil {
   698  		return err
   699  	}
   700  
   701  	endpointName := strings.TrimPrefix(container.Name, "/")
   702  	ep, err := n.CreateEndpoint(endpointName, createOptions...)
   703  	if err != nil {
   704  		return err
   705  	}
   706  	defer func() {
   707  		if err != nil {
   708  			if e := ep.Delete(false); e != nil {
   709  				logrus.Warnf("Could not rollback container connection to network %s", idOrName)
   710  			}
   711  		}
   712  	}()
   713  	container.NetworkSettings.Networks[n.Name()] = &network.EndpointSettings{
   714  		EndpointSettings: endpointConfig,
   715  		IPAMOperational:  operIPAM,
   716  	}
   717  	if _, ok := container.NetworkSettings.Networks[n.ID()]; ok {
   718  		delete(container.NetworkSettings.Networks, n.ID())
   719  	}
   720  
   721  	if err := daemon.updateEndpointNetworkSettings(container, n, ep); err != nil {
   722  		return err
   723  	}
   724  
   725  	if sb == nil {
   726  		options, err := daemon.buildSandboxOptions(container)
   727  		if err != nil {
   728  			return err
   729  		}
   730  		sb, err = controller.NewSandbox(container.ID, options...)
   731  		if err != nil {
   732  			return err
   733  		}
   734  
   735  		container.UpdateSandboxNetworkSettings(sb)
   736  	}
   737  
   738  	joinOptions, err := container.BuildJoinOptions(n)
   739  	if err != nil {
   740  		return err
   741  	}
   742  
   743  	if err := ep.Join(sb, joinOptions...); err != nil {
   744  		return err
   745  	}
   746  
   747  	if !container.Managed {
   748  		// add container name/alias to DNS
   749  		if err := daemon.ActivateContainerServiceBinding(container.Name); err != nil {
   750  			return fmt.Errorf("Activate container service binding for %s failed: %v", container.Name, err)
   751  		}
   752  	}
   753  
   754  	if err := container.UpdateJoinInfo(n, ep); err != nil {
   755  		return fmt.Errorf("Updating join info failed: %v", err)
   756  	}
   757  
   758  	container.NetworkSettings.Ports = getPortMapInfo(sb)
   759  
   760  	daemon.LogNetworkEventWithAttributes(n, "connect", map[string]string{"container": container.ID})
   761  	networkActions.WithValues("connect").UpdateSince(start)
   762  	return nil
   763  }
   764  
   765  // ForceEndpointDelete deletes an endpoint from a network forcefully
   766  func (daemon *Daemon) ForceEndpointDelete(name string, networkName string) error {
   767  	n, err := daemon.FindNetwork(networkName)
   768  	if err != nil {
   769  		return err
   770  	}
   771  
   772  	ep, err := n.EndpointByName(name)
   773  	if err != nil {
   774  		return err
   775  	}
   776  	return ep.Delete(true)
   777  }
   778  
   779  func (daemon *Daemon) disconnectFromNetwork(container *container.Container, n libnetwork.Network, force bool) error {
   780  	var (
   781  		ep   libnetwork.Endpoint
   782  		sbox libnetwork.Sandbox
   783  	)
   784  
   785  	s := func(current libnetwork.Endpoint) bool {
   786  		epInfo := current.Info()
   787  		if epInfo == nil {
   788  			return false
   789  		}
   790  		if sb := epInfo.Sandbox(); sb != nil {
   791  			if sb.ContainerID() == container.ID {
   792  				ep = current
   793  				sbox = sb
   794  				return true
   795  			}
   796  		}
   797  		return false
   798  	}
   799  	n.WalkEndpoints(s)
   800  
   801  	if ep == nil && force {
   802  		epName := strings.TrimPrefix(container.Name, "/")
   803  		ep, err := n.EndpointByName(epName)
   804  		if err != nil {
   805  			return err
   806  		}
   807  		return ep.Delete(force)
   808  	}
   809  
   810  	if ep == nil {
   811  		return fmt.Errorf("container %s is not connected to the network", container.ID)
   812  	}
   813  
   814  	if err := ep.Leave(sbox); err != nil {
   815  		return fmt.Errorf("container %s failed to leave network %s: %v", container.ID, n.Name(), err)
   816  	}
   817  
   818  	container.NetworkSettings.Ports = getPortMapInfo(sbox)
   819  
   820  	if err := ep.Delete(false); err != nil {
   821  		return fmt.Errorf("endpoint delete failed for container %s on network %s: %v", container.ID, n.Name(), err)
   822  	}
   823  
   824  	delete(container.NetworkSettings.Networks, n.Name())
   825  
   826  	if daemon.clusterProvider != nil && n.Info().Dynamic() && !container.Managed {
   827  		if err := daemon.clusterProvider.DetachNetwork(n.Name(), container.ID); err != nil {
   828  			logrus.Warnf("error detaching from network %s: %v", n.Name(), err)
   829  			if err := daemon.clusterProvider.DetachNetwork(n.ID(), container.ID); err != nil {
   830  				logrus.Warnf("error detaching from network %s: %v", n.ID(), err)
   831  			}
   832  		}
   833  	}
   834  
   835  	return nil
   836  }
   837  
   838  func (daemon *Daemon) initializeNetworking(container *container.Container) error {
   839  	var err error
   840  
   841  	if container.HostConfig.NetworkMode.IsContainer() {
   842  		// we need to get the hosts files from the container to join
   843  		nc, err := daemon.getNetworkedContainer(container.ID, container.HostConfig.NetworkMode.ConnectedContainer())
   844  		if err != nil {
   845  			return err
   846  		}
   847  		initializeNetworkingPaths(container, nc)
   848  		container.Config.Hostname = nc.Config.Hostname
   849  		container.Config.Domainname = nc.Config.Domainname
   850  		return nil
   851  	}
   852  
   853  	if container.HostConfig.NetworkMode.IsHost() {
   854  		if container.Config.Hostname == "" {
   855  			container.Config.Hostname, err = os.Hostname()
   856  			if err != nil {
   857  				return err
   858  			}
   859  		}
   860  	}
   861  
   862  	if err := daemon.allocateNetwork(container); err != nil {
   863  		return err
   864  	}
   865  
   866  	return container.BuildHostnameFile()
   867  }
   868  
   869  func (daemon *Daemon) getNetworkedContainer(containerID, connectedContainerID string) (*container.Container, error) {
   870  	nc, err := daemon.GetContainer(connectedContainerID)
   871  	if err != nil {
   872  		return nil, err
   873  	}
   874  	if containerID == nc.ID {
   875  		return nil, fmt.Errorf("cannot join own network")
   876  	}
   877  	if !nc.IsRunning() {
   878  		err := fmt.Errorf("cannot join network of a non running container: %s", connectedContainerID)
   879  		return nil, derr.NewRequestConflictError(err)
   880  	}
   881  	if nc.IsRestarting() {
   882  		return nil, errContainerIsRestarting(connectedContainerID)
   883  	}
   884  	return nc, nil
   885  }
   886  
   887  func (daemon *Daemon) releaseNetwork(container *container.Container) {
   888  	start := time.Now()
   889  	if daemon.netController == nil {
   890  		return
   891  	}
   892  	if container.HostConfig.NetworkMode.IsContainer() || container.Config.NetworkDisabled {
   893  		return
   894  	}
   895  
   896  	sid := container.NetworkSettings.SandboxID
   897  	settings := container.NetworkSettings.Networks
   898  	container.NetworkSettings.Ports = nil
   899  
   900  	if sid == "" || len(settings) == 0 {
   901  		return
   902  	}
   903  
   904  	var networks []libnetwork.Network
   905  	for n, epSettings := range settings {
   906  		if nw, err := daemon.FindNetwork(n); err == nil {
   907  			networks = append(networks, nw)
   908  		}
   909  
   910  		if epSettings.EndpointSettings == nil {
   911  			continue
   912  		}
   913  
   914  		cleanOperationalData(epSettings)
   915  	}
   916  
   917  	sb, err := daemon.netController.SandboxByID(sid)
   918  	if err != nil {
   919  		logrus.Warnf("error locating sandbox id %s: %v", sid, err)
   920  		return
   921  	}
   922  
   923  	if err := sb.Delete(); err != nil {
   924  		logrus.Errorf("Error deleting sandbox id %s for container %s: %v", sid, container.ID, err)
   925  	}
   926  
   927  	for _, nw := range networks {
   928  		if daemon.clusterProvider != nil && nw.Info().Dynamic() && !container.Managed {
   929  			if err := daemon.clusterProvider.DetachNetwork(nw.Name(), container.ID); err != nil {
   930  				logrus.Warnf("error detaching from network %s: %v", nw.Name(), err)
   931  				if err := daemon.clusterProvider.DetachNetwork(nw.ID(), container.ID); err != nil {
   932  					logrus.Warnf("error detaching from network %s: %v", nw.ID(), err)
   933  				}
   934  			}
   935  		}
   936  
   937  		attributes := map[string]string{
   938  			"container": container.ID,
   939  		}
   940  		daemon.LogNetworkEventWithAttributes(nw, "disconnect", attributes)
   941  	}
   942  	networkActions.WithValues("release").UpdateSince(start)
   943  }
   944  
   945  func errRemovalContainer(containerID string) error {
   946  	return fmt.Errorf("Container %s is marked for removal and cannot be connected or disconnected to the network", containerID)
   947  }
   948  
   949  // ConnectToNetwork connects a container to a network
   950  func (daemon *Daemon) ConnectToNetwork(container *container.Container, idOrName string, endpointConfig *networktypes.EndpointSettings) error {
   951  	if endpointConfig == nil {
   952  		endpointConfig = &networktypes.EndpointSettings{}
   953  	}
   954  	if !container.Running {
   955  		if container.RemovalInProgress || container.Dead {
   956  			return errRemovalContainer(container.ID)
   957  		}
   958  
   959  		n, err := daemon.FindNetwork(idOrName)
   960  		if err == nil && n != nil {
   961  			if err := daemon.updateNetworkConfig(container, n, endpointConfig, true); err != nil {
   962  				return err
   963  			}
   964  		} else {
   965  			container.NetworkSettings.Networks[idOrName] = &network.EndpointSettings{
   966  				EndpointSettings: endpointConfig,
   967  			}
   968  		}
   969  	} else if !daemon.isNetworkHotPluggable() {
   970  		return fmt.Errorf(runtime.GOOS + " does not support connecting a running container to a network")
   971  	} else {
   972  		if err := daemon.connectToNetwork(container, idOrName, endpointConfig, true); err != nil {
   973  			return err
   974  		}
   975  	}
   976  	if err := container.ToDiskLocking(); err != nil {
   977  		return fmt.Errorf("Error saving container to disk: %v", err)
   978  	}
   979  	return nil
   980  }
   981  
   982  // DisconnectFromNetwork disconnects container from network n.
   983  func (daemon *Daemon) DisconnectFromNetwork(container *container.Container, networkName string, force bool) error {
   984  	n, err := daemon.FindNetwork(networkName)
   985  	if !container.Running || (err != nil && force) {
   986  		if container.RemovalInProgress || container.Dead {
   987  			return errRemovalContainer(container.ID)
   988  		}
   989  		// In case networkName is resolved we will use n.Name()
   990  		// this will cover the case where network id is passed.
   991  		if n != nil {
   992  			networkName = n.Name()
   993  		}
   994  		if _, ok := container.NetworkSettings.Networks[networkName]; !ok {
   995  			return fmt.Errorf("container %s is not connected to the network %s", container.ID, networkName)
   996  		}
   997  		delete(container.NetworkSettings.Networks, networkName)
   998  	} else if err == nil && !daemon.isNetworkHotPluggable() {
   999  		return fmt.Errorf(runtime.GOOS + " does not support connecting a running container to a network")
  1000  	} else if err == nil {
  1001  		if container.HostConfig.NetworkMode.IsHost() && containertypes.NetworkMode(n.Type()).IsHost() {
  1002  			return runconfig.ErrConflictHostNetwork
  1003  		}
  1004  
  1005  		if err := daemon.disconnectFromNetwork(container, n, false); err != nil {
  1006  			return err
  1007  		}
  1008  	} else {
  1009  		return err
  1010  	}
  1011  
  1012  	if err := container.ToDiskLocking(); err != nil {
  1013  		return fmt.Errorf("Error saving container to disk: %v", err)
  1014  	}
  1015  
  1016  	if n != nil {
  1017  		attributes := map[string]string{
  1018  			"container": container.ID,
  1019  		}
  1020  		daemon.LogNetworkEventWithAttributes(n, "disconnect", attributes)
  1021  	}
  1022  	return nil
  1023  }
  1024  
  1025  // ActivateContainerServiceBinding puts this container into load balancer active rotation and DNS response
  1026  func (daemon *Daemon) ActivateContainerServiceBinding(containerName string) error {
  1027  	container, err := daemon.GetContainer(containerName)
  1028  	if err != nil {
  1029  		return err
  1030  	}
  1031  	sb := daemon.getNetworkSandbox(container)
  1032  	if sb == nil {
  1033  		return fmt.Errorf("network sandbox does not exist for container %s", containerName)
  1034  	}
  1035  	return sb.EnableService()
  1036  }
  1037  
  1038  // DeactivateContainerServiceBinding remove this container fromload balancer active rotation, and DNS response
  1039  func (daemon *Daemon) DeactivateContainerServiceBinding(containerName string) error {
  1040  	container, err := daemon.GetContainer(containerName)
  1041  	if err != nil {
  1042  		return err
  1043  	}
  1044  	sb := daemon.getNetworkSandbox(container)
  1045  	if sb == nil {
  1046  		return fmt.Errorf("network sandbox does not exist for container %s", containerName)
  1047  	}
  1048  	return sb.DisableService()
  1049  }