container_operations.go 33 KB

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