container_operations.go 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150
  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. if container.Name != container.Config.Hostname {
  582. addHostname := true
  583. for _, alias := range endpointConfig.Aliases {
  584. if alias == container.Config.Hostname {
  585. addHostname = false
  586. break
  587. }
  588. }
  589. if addHostname {
  590. endpointConfig.Aliases = append(endpointConfig.Aliases, container.Config.Hostname)
  591. }
  592. }
  593. }
  594. if err := validateNetworkingConfig(n, endpointConfig); err != nil {
  595. return err
  596. }
  597. if updateSettings {
  598. if err := daemon.updateNetworkSettings(container, n, endpointConfig); err != nil {
  599. return err
  600. }
  601. }
  602. return nil
  603. }
  604. func (daemon *Daemon) connectToNetwork(container *container.Container, idOrName string, endpointConfig *networktypes.EndpointSettings, updateSettings bool) (err error) {
  605. start := time.Now()
  606. if container.HostConfig.NetworkMode.IsContainer() {
  607. return runconfig.ErrConflictSharedNetwork
  608. }
  609. if containertypes.NetworkMode(idOrName).IsBridge() &&
  610. daemon.configStore.DisableBridge {
  611. container.Config.NetworkDisabled = true
  612. return nil
  613. }
  614. if endpointConfig == nil {
  615. endpointConfig = &networktypes.EndpointSettings{}
  616. }
  617. n, config, err := daemon.findAndAttachNetwork(container, idOrName, endpointConfig)
  618. if err != nil {
  619. return err
  620. }
  621. if n == nil {
  622. return nil
  623. }
  624. var operIPAM bool
  625. if config != nil {
  626. if epConfig, ok := config.EndpointsConfig[n.Name()]; ok {
  627. if endpointConfig.IPAMConfig == nil ||
  628. (endpointConfig.IPAMConfig.IPv4Address == "" &&
  629. endpointConfig.IPAMConfig.IPv6Address == "" &&
  630. len(endpointConfig.IPAMConfig.LinkLocalIPs) == 0) {
  631. operIPAM = true
  632. }
  633. // copy IPAMConfig and NetworkID from epConfig via AttachNetwork
  634. endpointConfig.IPAMConfig = epConfig.IPAMConfig
  635. endpointConfig.NetworkID = epConfig.NetworkID
  636. }
  637. }
  638. if err := daemon.updateNetworkConfig(container, n, endpointConfig, updateSettings); err != nil {
  639. return err
  640. }
  641. controller := daemon.netController
  642. sb := daemon.getNetworkSandbox(container)
  643. createOptions, err := buildCreateEndpointOptions(container, n, endpointConfig, sb, daemon.configStore.DNS)
  644. if err != nil {
  645. return err
  646. }
  647. endpointName := strings.TrimPrefix(container.Name, "/")
  648. ep, err := n.CreateEndpoint(endpointName, createOptions...)
  649. if err != nil {
  650. return err
  651. }
  652. defer func() {
  653. if err != nil {
  654. if e := ep.Delete(false); e != nil {
  655. logrus.Warnf("Could not rollback container connection to network %s", idOrName)
  656. }
  657. }
  658. }()
  659. container.NetworkSettings.Networks[n.Name()] = &network.EndpointSettings{
  660. EndpointSettings: endpointConfig,
  661. IPAMOperational: operIPAM,
  662. }
  663. if _, ok := container.NetworkSettings.Networks[n.ID()]; ok {
  664. delete(container.NetworkSettings.Networks, n.ID())
  665. }
  666. if err := daemon.updateEndpointNetworkSettings(container, n, ep); err != nil {
  667. return err
  668. }
  669. if sb == nil {
  670. options, err := daemon.buildSandboxOptions(container)
  671. if err != nil {
  672. return err
  673. }
  674. sb, err = controller.NewSandbox(container.ID, options...)
  675. if err != nil {
  676. return err
  677. }
  678. updateSandboxNetworkSettings(container, sb)
  679. }
  680. joinOptions, err := buildJoinOptions(container.NetworkSettings, n)
  681. if err != nil {
  682. return err
  683. }
  684. if err := ep.Join(sb, joinOptions...); err != nil {
  685. return err
  686. }
  687. if !container.Managed {
  688. // add container name/alias to DNS
  689. if err := daemon.ActivateContainerServiceBinding(container.Name); err != nil {
  690. return fmt.Errorf("Activate container service binding for %s failed: %v", container.Name, err)
  691. }
  692. }
  693. if err := updateJoinInfo(container.NetworkSettings, n, ep); err != nil {
  694. return fmt.Errorf("Updating join info failed: %v", err)
  695. }
  696. container.NetworkSettings.Ports = getPortMapInfo(sb)
  697. daemon.LogNetworkEventWithAttributes(n, "connect", map[string]string{"container": container.ID})
  698. networkActions.WithValues("connect").UpdateSince(start)
  699. return nil
  700. }
  701. func updateJoinInfo(networkSettings *network.Settings, n libnetwork.Network, ep libnetwork.Endpoint) error {
  702. if ep == nil {
  703. return errors.New("invalid enppoint whhile building portmap info")
  704. }
  705. if networkSettings == nil {
  706. return errors.New("invalid network settings while building port map info")
  707. }
  708. if len(networkSettings.Ports) == 0 {
  709. pm, err := getEndpointPortMapInfo(ep)
  710. if err != nil {
  711. return err
  712. }
  713. networkSettings.Ports = pm
  714. }
  715. epInfo := ep.Info()
  716. if epInfo == nil {
  717. // It is not an error to get an empty endpoint info
  718. return nil
  719. }
  720. if epInfo.Gateway() != nil {
  721. networkSettings.Networks[n.Name()].Gateway = epInfo.Gateway().String()
  722. }
  723. if epInfo.GatewayIPv6().To16() != nil {
  724. networkSettings.Networks[n.Name()].IPv6Gateway = epInfo.GatewayIPv6().String()
  725. }
  726. return nil
  727. }
  728. // ForceEndpointDelete deletes an endpoint from a network forcefully
  729. func (daemon *Daemon) ForceEndpointDelete(name string, networkName string) error {
  730. n, err := daemon.FindNetwork(networkName)
  731. if err != nil {
  732. return err
  733. }
  734. ep, err := n.EndpointByName(name)
  735. if err != nil {
  736. return err
  737. }
  738. return ep.Delete(true)
  739. }
  740. func (daemon *Daemon) disconnectFromNetwork(container *container.Container, n libnetwork.Network, force bool) error {
  741. var (
  742. ep libnetwork.Endpoint
  743. sbox libnetwork.Sandbox
  744. )
  745. s := func(current libnetwork.Endpoint) bool {
  746. epInfo := current.Info()
  747. if epInfo == nil {
  748. return false
  749. }
  750. if sb := epInfo.Sandbox(); sb != nil {
  751. if sb.ContainerID() == container.ID {
  752. ep = current
  753. sbox = sb
  754. return true
  755. }
  756. }
  757. return false
  758. }
  759. n.WalkEndpoints(s)
  760. if ep == nil && force {
  761. epName := strings.TrimPrefix(container.Name, "/")
  762. ep, err := n.EndpointByName(epName)
  763. if err != nil {
  764. return err
  765. }
  766. return ep.Delete(force)
  767. }
  768. if ep == nil {
  769. return fmt.Errorf("container %s is not connected to network %s", container.ID, n.Name())
  770. }
  771. if err := ep.Leave(sbox); err != nil {
  772. return fmt.Errorf("container %s failed to leave network %s: %v", container.ID, n.Name(), err)
  773. }
  774. container.NetworkSettings.Ports = getPortMapInfo(sbox)
  775. if err := ep.Delete(false); err != nil {
  776. return fmt.Errorf("endpoint delete failed for container %s on network %s: %v", container.ID, n.Name(), err)
  777. }
  778. delete(container.NetworkSettings.Networks, n.Name())
  779. daemon.tryDetachContainerFromClusterNetwork(n, container)
  780. return nil
  781. }
  782. func (daemon *Daemon) tryDetachContainerFromClusterNetwork(network libnetwork.Network, container *container.Container) {
  783. if daemon.clusterProvider != nil && network.Info().Dynamic() && !container.Managed {
  784. if err := daemon.clusterProvider.DetachNetwork(network.Name(), container.ID); err != nil {
  785. logrus.Warnf("error detaching from network %s: %v", network.Name(), err)
  786. if err := daemon.clusterProvider.DetachNetwork(network.ID(), container.ID); err != nil {
  787. logrus.Warnf("error detaching from network %s: %v", network.ID(), err)
  788. }
  789. }
  790. }
  791. attributes := map[string]string{
  792. "container": container.ID,
  793. }
  794. daemon.LogNetworkEventWithAttributes(network, "disconnect", attributes)
  795. }
  796. func (daemon *Daemon) initializeNetworking(container *container.Container) error {
  797. var err error
  798. if container.HostConfig.NetworkMode.IsContainer() {
  799. // we need to get the hosts files from the container to join
  800. nc, err := daemon.getNetworkedContainer(container.ID, container.HostConfig.NetworkMode.ConnectedContainer())
  801. if err != nil {
  802. return err
  803. }
  804. err = daemon.initializeNetworkingPaths(container, nc)
  805. if err != nil {
  806. return err
  807. }
  808. container.Config.Hostname = nc.Config.Hostname
  809. container.Config.Domainname = nc.Config.Domainname
  810. return nil
  811. }
  812. if container.HostConfig.NetworkMode.IsHost() {
  813. if container.Config.Hostname == "" {
  814. container.Config.Hostname, err = os.Hostname()
  815. if err != nil {
  816. return err
  817. }
  818. }
  819. }
  820. if err := daemon.allocateNetwork(container); err != nil {
  821. return err
  822. }
  823. return container.BuildHostnameFile()
  824. }
  825. func (daemon *Daemon) getNetworkedContainer(containerID, connectedContainerID string) (*container.Container, error) {
  826. nc, err := daemon.GetContainer(connectedContainerID)
  827. if err != nil {
  828. return nil, err
  829. }
  830. if containerID == nc.ID {
  831. return nil, fmt.Errorf("cannot join own network")
  832. }
  833. if !nc.IsRunning() {
  834. err := fmt.Errorf("cannot join network of a non running container: %s", connectedContainerID)
  835. return nil, errdefs.Conflict(err)
  836. }
  837. if nc.IsRestarting() {
  838. return nil, errContainerIsRestarting(connectedContainerID)
  839. }
  840. return nc, nil
  841. }
  842. func (daemon *Daemon) releaseNetwork(container *container.Container) {
  843. start := time.Now()
  844. if daemon.netController == nil {
  845. return
  846. }
  847. if container.HostConfig.NetworkMode.IsContainer() || container.Config.NetworkDisabled {
  848. return
  849. }
  850. sid := container.NetworkSettings.SandboxID
  851. settings := container.NetworkSettings.Networks
  852. container.NetworkSettings.Ports = nil
  853. if sid == "" {
  854. return
  855. }
  856. var networks []libnetwork.Network
  857. for n, epSettings := range settings {
  858. if nw, err := daemon.FindNetwork(getNetworkID(n, epSettings.EndpointSettings)); err == nil {
  859. networks = append(networks, nw)
  860. }
  861. if epSettings.EndpointSettings == nil {
  862. continue
  863. }
  864. cleanOperationalData(epSettings)
  865. }
  866. sb, err := daemon.netController.SandboxByID(sid)
  867. if err != nil {
  868. logrus.Warnf("error locating sandbox id %s: %v", sid, err)
  869. return
  870. }
  871. if err := sb.Delete(); err != nil {
  872. logrus.Errorf("Error deleting sandbox id %s for container %s: %v", sid, container.ID, err)
  873. }
  874. for _, nw := range networks {
  875. daemon.tryDetachContainerFromClusterNetwork(nw, container)
  876. }
  877. networkActions.WithValues("release").UpdateSince(start)
  878. }
  879. func errRemovalContainer(containerID string) error {
  880. return fmt.Errorf("Container %s is marked for removal and cannot be connected or disconnected to the network", containerID)
  881. }
  882. // ConnectToNetwork connects a container to a network
  883. func (daemon *Daemon) ConnectToNetwork(container *container.Container, idOrName string, endpointConfig *networktypes.EndpointSettings) error {
  884. if endpointConfig == nil {
  885. endpointConfig = &networktypes.EndpointSettings{}
  886. }
  887. container.Lock()
  888. defer container.Unlock()
  889. if !container.Running {
  890. if container.RemovalInProgress || container.Dead {
  891. return errRemovalContainer(container.ID)
  892. }
  893. n, err := daemon.FindNetwork(idOrName)
  894. if err == nil && n != nil {
  895. if err := daemon.updateNetworkConfig(container, n, endpointConfig, true); err != nil {
  896. return err
  897. }
  898. } else {
  899. container.NetworkSettings.Networks[idOrName] = &network.EndpointSettings{
  900. EndpointSettings: endpointConfig,
  901. }
  902. }
  903. } else {
  904. if err := daemon.connectToNetwork(container, idOrName, endpointConfig, true); err != nil {
  905. return err
  906. }
  907. }
  908. return container.CheckpointTo(daemon.containersReplica)
  909. }
  910. // DisconnectFromNetwork disconnects container from network n.
  911. func (daemon *Daemon) DisconnectFromNetwork(container *container.Container, networkName string, force bool) error {
  912. n, err := daemon.FindNetwork(networkName)
  913. container.Lock()
  914. defer container.Unlock()
  915. if !container.Running || (err != nil && force) {
  916. if container.RemovalInProgress || container.Dead {
  917. return errRemovalContainer(container.ID)
  918. }
  919. // In case networkName is resolved we will use n.Name()
  920. // this will cover the case where network id is passed.
  921. if n != nil {
  922. networkName = n.Name()
  923. }
  924. if _, ok := container.NetworkSettings.Networks[networkName]; !ok {
  925. return fmt.Errorf("container %s is not connected to the network %s", container.ID, networkName)
  926. }
  927. delete(container.NetworkSettings.Networks, networkName)
  928. } else if err == nil {
  929. if container.HostConfig.NetworkMode.IsHost() && containertypes.NetworkMode(n.Type()).IsHost() {
  930. return runconfig.ErrConflictHostNetwork
  931. }
  932. if err := daemon.disconnectFromNetwork(container, n, false); err != nil {
  933. return err
  934. }
  935. } else {
  936. return err
  937. }
  938. if err := container.CheckpointTo(daemon.containersReplica); err != nil {
  939. return err
  940. }
  941. if n != nil {
  942. daemon.LogNetworkEventWithAttributes(n, "disconnect", map[string]string{
  943. "container": container.ID,
  944. })
  945. }
  946. return nil
  947. }
  948. // ActivateContainerServiceBinding puts this container into load balancer active rotation and DNS response
  949. func (daemon *Daemon) ActivateContainerServiceBinding(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. return fmt.Errorf("network sandbox does not exist for container %s", containerName)
  957. }
  958. return sb.EnableService()
  959. }
  960. // DeactivateContainerServiceBinding removes this container from load balancer active rotation, and DNS response
  961. func (daemon *Daemon) DeactivateContainerServiceBinding(containerName string) error {
  962. container, err := daemon.GetContainer(containerName)
  963. if err != nil {
  964. return err
  965. }
  966. sb := daemon.getNetworkSandbox(container)
  967. if sb == nil {
  968. // If the network sandbox is not found, then there is nothing to deactivate
  969. logrus.Debugf("Could not find network sandbox for container %s on service binding deactivation request", containerName)
  970. return nil
  971. }
  972. return sb.DisableService()
  973. }
  974. func getNetworkID(name string, endpointSettings *networktypes.EndpointSettings) string {
  975. // We only want to prefer NetworkID for user defined networks.
  976. // For systems like bridge, none, etc. the name is preferred (otherwise restart may cause issues)
  977. if containertypes.NetworkMode(name).IsUserDefined() && endpointSettings != nil && endpointSettings.NetworkID != "" {
  978. return endpointSettings.NetworkID
  979. }
  980. return name
  981. }
  982. // updateSandboxNetworkSettings updates the sandbox ID and Key.
  983. func updateSandboxNetworkSettings(c *container.Container, sb libnetwork.Sandbox) error {
  984. c.NetworkSettings.SandboxID = sb.ID()
  985. c.NetworkSettings.SandboxKey = sb.Key()
  986. return nil
  987. }