container_operations.go 36 KB

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