container_operations.go 34 KB

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