container_operations.go 33 KB

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