container_operations.go 32 KB

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