container_operations.go 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159
  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. // Throw an error if the container is already attached to the network
  306. if container.NetworkSettings.Networks != nil {
  307. networkName := n.Name()
  308. containerName := strings.TrimPrefix(container.Name, "/")
  309. if network, ok := container.NetworkSettings.Networks[networkName]; ok && network.EndpointID != "" {
  310. err := fmt.Errorf("%s is already attached to network %s", containerName, networkName)
  311. return n, nil, errdefs.Conflict(err)
  312. }
  313. }
  314. }
  315. var addresses []string
  316. if epConfig != nil && epConfig.IPAMConfig != nil {
  317. if epConfig.IPAMConfig.IPv4Address != "" {
  318. addresses = append(addresses, epConfig.IPAMConfig.IPv4Address)
  319. }
  320. if epConfig.IPAMConfig.IPv6Address != "" {
  321. addresses = append(addresses, epConfig.IPAMConfig.IPv6Address)
  322. }
  323. }
  324. var (
  325. config *networktypes.NetworkingConfig
  326. retryCount int
  327. )
  328. if n == nil && daemon.attachableNetworkLock != nil {
  329. daemon.attachableNetworkLock.Lock(id)
  330. defer daemon.attachableNetworkLock.Unlock(id)
  331. }
  332. for {
  333. // In all other cases, attempt to attach to the network to
  334. // trigger attachment in the swarm cluster manager.
  335. if daemon.clusterProvider != nil {
  336. var err error
  337. config, err = daemon.clusterProvider.AttachNetwork(id, container.ID, addresses)
  338. if err != nil {
  339. return nil, nil, err
  340. }
  341. }
  342. n, err = daemon.FindNetwork(id)
  343. if err != nil {
  344. if daemon.clusterProvider != nil {
  345. if err := daemon.clusterProvider.DetachNetwork(id, container.ID); err != nil {
  346. logrus.Warnf("Could not rollback attachment for container %s to network %s: %v", container.ID, idOrName, err)
  347. }
  348. }
  349. // Retry network attach again if we failed to
  350. // find the network after successful
  351. // attachment because the only reason that
  352. // would happen is if some other container
  353. // attached to the swarm scope network went down
  354. // and removed the network while we were in
  355. // the process of attaching.
  356. if config != nil {
  357. if _, ok := err.(libnetwork.ErrNoSuchNetwork); ok {
  358. if retryCount >= 5 {
  359. return nil, nil, fmt.Errorf("could not find network %s after successful attachment", idOrName)
  360. }
  361. retryCount++
  362. continue
  363. }
  364. }
  365. return nil, nil, err
  366. }
  367. break
  368. }
  369. // This container has attachment to a swarm scope
  370. // network. Update the container network settings accordingly.
  371. container.NetworkSettings.HasSwarmEndpoint = true
  372. return n, config, nil
  373. }
  374. // updateContainerNetworkSettings updates the network settings
  375. func (daemon *Daemon) updateContainerNetworkSettings(container *container.Container, endpointsConfig map[string]*networktypes.EndpointSettings) {
  376. var n libnetwork.Network
  377. mode := container.HostConfig.NetworkMode
  378. if container.Config.NetworkDisabled || mode.IsContainer() {
  379. return
  380. }
  381. networkName := mode.NetworkName()
  382. if mode.IsDefault() {
  383. networkName = daemon.netController.Config().Daemon.DefaultNetwork
  384. }
  385. if mode.IsUserDefined() {
  386. var err error
  387. n, err = daemon.FindNetwork(networkName)
  388. if err == nil {
  389. networkName = n.Name()
  390. }
  391. }
  392. if container.NetworkSettings == nil {
  393. container.NetworkSettings = &network.Settings{}
  394. }
  395. if len(endpointsConfig) > 0 {
  396. if container.NetworkSettings.Networks == nil {
  397. container.NetworkSettings.Networks = make(map[string]*network.EndpointSettings)
  398. }
  399. for name, epConfig := range endpointsConfig {
  400. container.NetworkSettings.Networks[name] = &network.EndpointSettings{
  401. EndpointSettings: epConfig,
  402. }
  403. }
  404. }
  405. if container.NetworkSettings.Networks == nil {
  406. container.NetworkSettings.Networks = make(map[string]*network.EndpointSettings)
  407. container.NetworkSettings.Networks[networkName] = &network.EndpointSettings{
  408. EndpointSettings: &networktypes.EndpointSettings{},
  409. }
  410. }
  411. // Convert any settings added by client in default name to
  412. // engine's default network name key
  413. if mode.IsDefault() {
  414. if nConf, ok := container.NetworkSettings.Networks[mode.NetworkName()]; ok {
  415. container.NetworkSettings.Networks[networkName] = nConf
  416. delete(container.NetworkSettings.Networks, mode.NetworkName())
  417. }
  418. }
  419. if !mode.IsUserDefined() {
  420. return
  421. }
  422. // Make sure to internally store the per network endpoint config by network name
  423. if _, ok := container.NetworkSettings.Networks[networkName]; ok {
  424. return
  425. }
  426. if n != nil {
  427. if nwConfig, ok := container.NetworkSettings.Networks[n.ID()]; ok {
  428. container.NetworkSettings.Networks[networkName] = nwConfig
  429. delete(container.NetworkSettings.Networks, n.ID())
  430. return
  431. }
  432. }
  433. }
  434. func (daemon *Daemon) allocateNetwork(container *container.Container) error {
  435. start := time.Now()
  436. controller := daemon.netController
  437. if daemon.netController == nil {
  438. return nil
  439. }
  440. // Cleanup any stale sandbox left over due to ungraceful daemon shutdown
  441. if err := controller.SandboxDestroy(container.ID); err != nil {
  442. logrus.Errorf("failed to cleanup up stale network sandbox for container %s", container.ID)
  443. }
  444. if container.Config.NetworkDisabled || container.HostConfig.NetworkMode.IsContainer() {
  445. return nil
  446. }
  447. updateSettings := false
  448. if len(container.NetworkSettings.Networks) == 0 {
  449. daemon.updateContainerNetworkSettings(container, nil)
  450. updateSettings = true
  451. }
  452. // always connect default network first since only default
  453. // network mode support link and we need do some setting
  454. // on sandbox initialize for link, but the sandbox only be initialized
  455. // on first network connecting.
  456. defaultNetName := runconfig.DefaultDaemonNetworkMode().NetworkName()
  457. if nConf, ok := container.NetworkSettings.Networks[defaultNetName]; ok {
  458. cleanOperationalData(nConf)
  459. if err := daemon.connectToNetwork(container, defaultNetName, nConf.EndpointSettings, updateSettings); err != nil {
  460. return err
  461. }
  462. }
  463. // the intermediate map is necessary because "connectToNetwork" modifies "container.NetworkSettings.Networks"
  464. networks := make(map[string]*network.EndpointSettings)
  465. for n, epConf := range container.NetworkSettings.Networks {
  466. if n == defaultNetName {
  467. continue
  468. }
  469. networks[n] = epConf
  470. }
  471. for netName, epConf := range networks {
  472. cleanOperationalData(epConf)
  473. if err := daemon.connectToNetwork(container, netName, epConf.EndpointSettings, updateSettings); err != nil {
  474. return err
  475. }
  476. }
  477. // If the container is not to be connected to any network,
  478. // create its network sandbox now if not present
  479. if len(networks) == 0 {
  480. if nil == daemon.getNetworkSandbox(container) {
  481. options, err := daemon.buildSandboxOptions(container)
  482. if err != nil {
  483. return err
  484. }
  485. sb, err := daemon.netController.NewSandbox(container.ID, options...)
  486. if err != nil {
  487. return err
  488. }
  489. updateSandboxNetworkSettings(container, sb)
  490. defer func() {
  491. if err != nil {
  492. sb.Delete()
  493. }
  494. }()
  495. }
  496. }
  497. if _, err := container.WriteHostConfig(); err != nil {
  498. return err
  499. }
  500. networkActions.WithValues("allocate").UpdateSince(start)
  501. return nil
  502. }
  503. func (daemon *Daemon) getNetworkSandbox(container *container.Container) libnetwork.Sandbox {
  504. var sb libnetwork.Sandbox
  505. daemon.netController.WalkSandboxes(func(s libnetwork.Sandbox) bool {
  506. if s.ContainerID() == container.ID {
  507. sb = s
  508. return true
  509. }
  510. return false
  511. })
  512. return sb
  513. }
  514. // hasUserDefinedIPAddress returns whether the passed IPAM configuration contains IP address configuration
  515. func hasUserDefinedIPAddress(ipamConfig *networktypes.EndpointIPAMConfig) bool {
  516. return ipamConfig != nil && (len(ipamConfig.IPv4Address) > 0 || len(ipamConfig.IPv6Address) > 0)
  517. }
  518. // User specified ip address is acceptable only for networks with user specified subnets.
  519. func validateNetworkingConfig(n libnetwork.Network, epConfig *networktypes.EndpointSettings) error {
  520. if n == nil || epConfig == nil {
  521. return nil
  522. }
  523. if !containertypes.NetworkMode(n.Name()).IsUserDefined() {
  524. if hasUserDefinedIPAddress(epConfig.IPAMConfig) && !enableIPOnPredefinedNetwork() {
  525. return runconfig.ErrUnsupportedNetworkAndIP
  526. }
  527. if len(epConfig.Aliases) > 0 && !serviceDiscoveryOnDefaultNetwork() {
  528. return runconfig.ErrUnsupportedNetworkAndAlias
  529. }
  530. }
  531. if !hasUserDefinedIPAddress(epConfig.IPAMConfig) {
  532. return nil
  533. }
  534. _, _, nwIPv4Configs, nwIPv6Configs := n.Info().IpamConfig()
  535. for _, s := range []struct {
  536. ipConfigured bool
  537. subnetConfigs []*libnetwork.IpamConf
  538. }{
  539. {
  540. ipConfigured: len(epConfig.IPAMConfig.IPv4Address) > 0,
  541. subnetConfigs: nwIPv4Configs,
  542. },
  543. {
  544. ipConfigured: len(epConfig.IPAMConfig.IPv6Address) > 0,
  545. subnetConfigs: nwIPv6Configs,
  546. },
  547. } {
  548. if s.ipConfigured {
  549. foundSubnet := false
  550. for _, cfg := range s.subnetConfigs {
  551. if len(cfg.PreferredPool) > 0 {
  552. foundSubnet = true
  553. break
  554. }
  555. }
  556. if !foundSubnet {
  557. return runconfig.ErrUnsupportedNetworkNoSubnetAndIP
  558. }
  559. }
  560. }
  561. return nil
  562. }
  563. // cleanOperationalData resets the operational data from the passed endpoint settings
  564. func cleanOperationalData(es *network.EndpointSettings) {
  565. es.EndpointID = ""
  566. es.Gateway = ""
  567. es.IPAddress = ""
  568. es.IPPrefixLen = 0
  569. es.IPv6Gateway = ""
  570. es.GlobalIPv6Address = ""
  571. es.GlobalIPv6PrefixLen = 0
  572. es.MacAddress = ""
  573. if es.IPAMOperational {
  574. es.IPAMConfig = nil
  575. }
  576. }
  577. func (daemon *Daemon) updateNetworkConfig(container *container.Container, n libnetwork.Network, endpointConfig *networktypes.EndpointSettings, updateSettings bool) error {
  578. if containertypes.NetworkMode(n.Name()).IsUserDefined() {
  579. addShortID := true
  580. shortID := stringid.TruncateID(container.ID)
  581. for _, alias := range endpointConfig.Aliases {
  582. if alias == shortID {
  583. addShortID = false
  584. break
  585. }
  586. }
  587. if addShortID {
  588. endpointConfig.Aliases = append(endpointConfig.Aliases, shortID)
  589. }
  590. if container.Name != container.Config.Hostname {
  591. addHostname := true
  592. for _, alias := range endpointConfig.Aliases {
  593. if alias == container.Config.Hostname {
  594. addHostname = false
  595. break
  596. }
  597. }
  598. if addHostname {
  599. endpointConfig.Aliases = append(endpointConfig.Aliases, container.Config.Hostname)
  600. }
  601. }
  602. }
  603. if err := validateNetworkingConfig(n, endpointConfig); err != nil {
  604. return err
  605. }
  606. if updateSettings {
  607. if err := daemon.updateNetworkSettings(container, n, endpointConfig); err != nil {
  608. return err
  609. }
  610. }
  611. return nil
  612. }
  613. func (daemon *Daemon) connectToNetwork(container *container.Container, idOrName string, endpointConfig *networktypes.EndpointSettings, updateSettings bool) (err error) {
  614. start := time.Now()
  615. if container.HostConfig.NetworkMode.IsContainer() {
  616. return runconfig.ErrConflictSharedNetwork
  617. }
  618. if containertypes.NetworkMode(idOrName).IsBridge() &&
  619. daemon.configStore.DisableBridge {
  620. container.Config.NetworkDisabled = true
  621. return nil
  622. }
  623. if endpointConfig == nil {
  624. endpointConfig = &networktypes.EndpointSettings{}
  625. }
  626. n, config, err := daemon.findAndAttachNetwork(container, idOrName, endpointConfig)
  627. if err != nil {
  628. return err
  629. }
  630. if n == nil {
  631. return nil
  632. }
  633. var operIPAM bool
  634. if config != nil {
  635. if epConfig, ok := config.EndpointsConfig[n.Name()]; ok {
  636. if endpointConfig.IPAMConfig == nil ||
  637. (endpointConfig.IPAMConfig.IPv4Address == "" &&
  638. endpointConfig.IPAMConfig.IPv6Address == "" &&
  639. len(endpointConfig.IPAMConfig.LinkLocalIPs) == 0) {
  640. operIPAM = true
  641. }
  642. // copy IPAMConfig and NetworkID from epConfig via AttachNetwork
  643. endpointConfig.IPAMConfig = epConfig.IPAMConfig
  644. endpointConfig.NetworkID = epConfig.NetworkID
  645. }
  646. }
  647. if err := daemon.updateNetworkConfig(container, n, endpointConfig, updateSettings); err != nil {
  648. return err
  649. }
  650. controller := daemon.netController
  651. sb := daemon.getNetworkSandbox(container)
  652. createOptions, err := buildCreateEndpointOptions(container, n, endpointConfig, sb, daemon.configStore.DNS)
  653. if err != nil {
  654. return err
  655. }
  656. endpointName := strings.TrimPrefix(container.Name, "/")
  657. ep, err := n.CreateEndpoint(endpointName, createOptions...)
  658. if err != nil {
  659. return err
  660. }
  661. defer func() {
  662. if err != nil {
  663. if e := ep.Delete(false); e != nil {
  664. logrus.Warnf("Could not rollback container connection to network %s", idOrName)
  665. }
  666. }
  667. }()
  668. container.NetworkSettings.Networks[n.Name()] = &network.EndpointSettings{
  669. EndpointSettings: endpointConfig,
  670. IPAMOperational: operIPAM,
  671. }
  672. if _, ok := container.NetworkSettings.Networks[n.ID()]; ok {
  673. delete(container.NetworkSettings.Networks, n.ID())
  674. }
  675. if err := daemon.updateEndpointNetworkSettings(container, n, ep); err != nil {
  676. return err
  677. }
  678. if sb == nil {
  679. options, err := daemon.buildSandboxOptions(container)
  680. if err != nil {
  681. return err
  682. }
  683. sb, err = controller.NewSandbox(container.ID, options...)
  684. if err != nil {
  685. return err
  686. }
  687. updateSandboxNetworkSettings(container, sb)
  688. }
  689. joinOptions, err := buildJoinOptions(container.NetworkSettings, n)
  690. if err != nil {
  691. return err
  692. }
  693. if err := ep.Join(sb, joinOptions...); err != nil {
  694. return err
  695. }
  696. if !container.Managed {
  697. // add container name/alias to DNS
  698. if err := daemon.ActivateContainerServiceBinding(container.Name); err != nil {
  699. return fmt.Errorf("Activate container service binding for %s failed: %v", container.Name, err)
  700. }
  701. }
  702. if err := updateJoinInfo(container.NetworkSettings, n, ep); err != nil {
  703. return fmt.Errorf("Updating join info failed: %v", err)
  704. }
  705. container.NetworkSettings.Ports = getPortMapInfo(sb)
  706. daemon.LogNetworkEventWithAttributes(n, "connect", map[string]string{"container": container.ID})
  707. networkActions.WithValues("connect").UpdateSince(start)
  708. return nil
  709. }
  710. func updateJoinInfo(networkSettings *network.Settings, n libnetwork.Network, ep libnetwork.Endpoint) error {
  711. if ep == nil {
  712. return errors.New("invalid enppoint whhile building portmap info")
  713. }
  714. if networkSettings == nil {
  715. return errors.New("invalid network settings while building port map info")
  716. }
  717. if len(networkSettings.Ports) == 0 {
  718. pm, err := getEndpointPortMapInfo(ep)
  719. if err != nil {
  720. return err
  721. }
  722. networkSettings.Ports = pm
  723. }
  724. epInfo := ep.Info()
  725. if epInfo == nil {
  726. // It is not an error to get an empty endpoint info
  727. return nil
  728. }
  729. if epInfo.Gateway() != nil {
  730. networkSettings.Networks[n.Name()].Gateway = epInfo.Gateway().String()
  731. }
  732. if epInfo.GatewayIPv6().To16() != nil {
  733. networkSettings.Networks[n.Name()].IPv6Gateway = epInfo.GatewayIPv6().String()
  734. }
  735. return nil
  736. }
  737. // ForceEndpointDelete deletes an endpoint from a network forcefully
  738. func (daemon *Daemon) ForceEndpointDelete(name string, networkName string) error {
  739. n, err := daemon.FindNetwork(networkName)
  740. if err != nil {
  741. return err
  742. }
  743. ep, err := n.EndpointByName(name)
  744. if err != nil {
  745. return err
  746. }
  747. return ep.Delete(true)
  748. }
  749. func (daemon *Daemon) disconnectFromNetwork(container *container.Container, n libnetwork.Network, force bool) error {
  750. var (
  751. ep libnetwork.Endpoint
  752. sbox libnetwork.Sandbox
  753. )
  754. s := func(current libnetwork.Endpoint) bool {
  755. epInfo := current.Info()
  756. if epInfo == nil {
  757. return false
  758. }
  759. if sb := epInfo.Sandbox(); sb != nil {
  760. if sb.ContainerID() == container.ID {
  761. ep = current
  762. sbox = sb
  763. return true
  764. }
  765. }
  766. return false
  767. }
  768. n.WalkEndpoints(s)
  769. if ep == nil && force {
  770. epName := strings.TrimPrefix(container.Name, "/")
  771. ep, err := n.EndpointByName(epName)
  772. if err != nil {
  773. return err
  774. }
  775. return ep.Delete(force)
  776. }
  777. if ep == nil {
  778. return fmt.Errorf("container %s is not connected to network %s", container.ID, n.Name())
  779. }
  780. if err := ep.Leave(sbox); err != nil {
  781. return fmt.Errorf("container %s failed to leave network %s: %v", container.ID, n.Name(), err)
  782. }
  783. container.NetworkSettings.Ports = getPortMapInfo(sbox)
  784. if err := ep.Delete(false); err != nil {
  785. return fmt.Errorf("endpoint delete failed for container %s on network %s: %v", container.ID, n.Name(), err)
  786. }
  787. delete(container.NetworkSettings.Networks, n.Name())
  788. daemon.tryDetachContainerFromClusterNetwork(n, container)
  789. return nil
  790. }
  791. func (daemon *Daemon) tryDetachContainerFromClusterNetwork(network libnetwork.Network, container *container.Container) {
  792. if daemon.clusterProvider != nil && network.Info().Dynamic() && !container.Managed {
  793. if err := daemon.clusterProvider.DetachNetwork(network.Name(), container.ID); err != nil {
  794. logrus.Warnf("error detaching from network %s: %v", network.Name(), err)
  795. if err := daemon.clusterProvider.DetachNetwork(network.ID(), container.ID); err != nil {
  796. logrus.Warnf("error detaching from network %s: %v", network.ID(), err)
  797. }
  798. }
  799. }
  800. attributes := map[string]string{
  801. "container": container.ID,
  802. }
  803. daemon.LogNetworkEventWithAttributes(network, "disconnect", attributes)
  804. }
  805. func (daemon *Daemon) initializeNetworking(container *container.Container) error {
  806. var err error
  807. if container.HostConfig.NetworkMode.IsContainer() {
  808. // we need to get the hosts files from the container to join
  809. nc, err := daemon.getNetworkedContainer(container.ID, container.HostConfig.NetworkMode.ConnectedContainer())
  810. if err != nil {
  811. return err
  812. }
  813. err = daemon.initializeNetworkingPaths(container, nc)
  814. if err != nil {
  815. return err
  816. }
  817. container.Config.Hostname = nc.Config.Hostname
  818. container.Config.Domainname = nc.Config.Domainname
  819. return nil
  820. }
  821. if container.HostConfig.NetworkMode.IsHost() {
  822. if container.Config.Hostname == "" {
  823. container.Config.Hostname, err = os.Hostname()
  824. if err != nil {
  825. return err
  826. }
  827. }
  828. }
  829. if err := daemon.allocateNetwork(container); err != nil {
  830. return err
  831. }
  832. return container.BuildHostnameFile()
  833. }
  834. func (daemon *Daemon) getNetworkedContainer(containerID, connectedContainerID string) (*container.Container, error) {
  835. nc, err := daemon.GetContainer(connectedContainerID)
  836. if err != nil {
  837. return nil, err
  838. }
  839. if containerID == nc.ID {
  840. return nil, fmt.Errorf("cannot join own network")
  841. }
  842. if !nc.IsRunning() {
  843. err := fmt.Errorf("cannot join network of a non running container: %s", connectedContainerID)
  844. return nil, errdefs.Conflict(err)
  845. }
  846. if nc.IsRestarting() {
  847. return nil, errContainerIsRestarting(connectedContainerID)
  848. }
  849. return nc, nil
  850. }
  851. func (daemon *Daemon) releaseNetwork(container *container.Container) {
  852. start := time.Now()
  853. if daemon.netController == nil {
  854. return
  855. }
  856. if container.HostConfig.NetworkMode.IsContainer() || container.Config.NetworkDisabled {
  857. return
  858. }
  859. sid := container.NetworkSettings.SandboxID
  860. settings := container.NetworkSettings.Networks
  861. container.NetworkSettings.Ports = nil
  862. if sid == "" {
  863. return
  864. }
  865. var networks []libnetwork.Network
  866. for n, epSettings := range settings {
  867. if nw, err := daemon.FindNetwork(getNetworkID(n, epSettings.EndpointSettings)); err == nil {
  868. networks = append(networks, nw)
  869. }
  870. if epSettings.EndpointSettings == nil {
  871. continue
  872. }
  873. cleanOperationalData(epSettings)
  874. }
  875. sb, err := daemon.netController.SandboxByID(sid)
  876. if err != nil {
  877. logrus.Warnf("error locating sandbox id %s: %v", sid, err)
  878. return
  879. }
  880. if err := sb.Delete(); err != nil {
  881. logrus.Errorf("Error deleting sandbox id %s for container %s: %v", sid, container.ID, err)
  882. }
  883. for _, nw := range networks {
  884. daemon.tryDetachContainerFromClusterNetwork(nw, container)
  885. }
  886. networkActions.WithValues("release").UpdateSince(start)
  887. }
  888. func errRemovalContainer(containerID string) error {
  889. return fmt.Errorf("Container %s is marked for removal and cannot be connected or disconnected to the network", containerID)
  890. }
  891. // ConnectToNetwork connects a container to a network
  892. func (daemon *Daemon) ConnectToNetwork(container *container.Container, idOrName string, endpointConfig *networktypes.EndpointSettings) error {
  893. if endpointConfig == nil {
  894. endpointConfig = &networktypes.EndpointSettings{}
  895. }
  896. container.Lock()
  897. defer container.Unlock()
  898. if !container.Running {
  899. if container.RemovalInProgress || container.Dead {
  900. return errRemovalContainer(container.ID)
  901. }
  902. n, err := daemon.FindNetwork(idOrName)
  903. if err == nil && n != nil {
  904. if err := daemon.updateNetworkConfig(container, n, endpointConfig, true); err != nil {
  905. return err
  906. }
  907. } else {
  908. container.NetworkSettings.Networks[idOrName] = &network.EndpointSettings{
  909. EndpointSettings: endpointConfig,
  910. }
  911. }
  912. } else {
  913. if err := daemon.connectToNetwork(container, idOrName, endpointConfig, true); err != nil {
  914. return err
  915. }
  916. }
  917. return container.CheckpointTo(daemon.containersReplica)
  918. }
  919. // DisconnectFromNetwork disconnects container from network n.
  920. func (daemon *Daemon) DisconnectFromNetwork(container *container.Container, networkName string, force bool) error {
  921. n, err := daemon.FindNetwork(networkName)
  922. container.Lock()
  923. defer container.Unlock()
  924. if !container.Running || (err != nil && force) {
  925. if container.RemovalInProgress || container.Dead {
  926. return errRemovalContainer(container.ID)
  927. }
  928. // In case networkName is resolved we will use n.Name()
  929. // this will cover the case where network id is passed.
  930. if n != nil {
  931. networkName = n.Name()
  932. }
  933. if _, ok := container.NetworkSettings.Networks[networkName]; !ok {
  934. return fmt.Errorf("container %s is not connected to the network %s", container.ID, networkName)
  935. }
  936. delete(container.NetworkSettings.Networks, networkName)
  937. } else if err == nil {
  938. if container.HostConfig.NetworkMode.IsHost() && containertypes.NetworkMode(n.Type()).IsHost() {
  939. return runconfig.ErrConflictHostNetwork
  940. }
  941. if err := daemon.disconnectFromNetwork(container, n, false); err != nil {
  942. return err
  943. }
  944. } else {
  945. return err
  946. }
  947. if err := container.CheckpointTo(daemon.containersReplica); err != nil {
  948. return err
  949. }
  950. if n != nil {
  951. daemon.LogNetworkEventWithAttributes(n, "disconnect", map[string]string{
  952. "container": container.ID,
  953. })
  954. }
  955. return nil
  956. }
  957. // ActivateContainerServiceBinding puts this container into load balancer active rotation and DNS response
  958. func (daemon *Daemon) ActivateContainerServiceBinding(containerName string) error {
  959. container, err := daemon.GetContainer(containerName)
  960. if err != nil {
  961. return err
  962. }
  963. sb := daemon.getNetworkSandbox(container)
  964. if sb == nil {
  965. return fmt.Errorf("network sandbox does not exist for container %s", containerName)
  966. }
  967. return sb.EnableService()
  968. }
  969. // DeactivateContainerServiceBinding removes this container from load balancer active rotation, and DNS response
  970. func (daemon *Daemon) DeactivateContainerServiceBinding(containerName string) error {
  971. container, err := daemon.GetContainer(containerName)
  972. if err != nil {
  973. return err
  974. }
  975. sb := daemon.getNetworkSandbox(container)
  976. if sb == nil {
  977. // If the network sandbox is not found, then there is nothing to deactivate
  978. logrus.Debugf("Could not find network sandbox for container %s on service binding deactivation request", containerName)
  979. return nil
  980. }
  981. return sb.DisableService()
  982. }
  983. func getNetworkID(name string, endpointSettings *networktypes.EndpointSettings) string {
  984. // We only want to prefer NetworkID for user defined networks.
  985. // For systems like bridge, none, etc. the name is preferred (otherwise restart may cause issues)
  986. if containertypes.NetworkMode(name).IsUserDefined() && endpointSettings != nil && endpointSettings.NetworkID != "" {
  987. return endpointSettings.NetworkID
  988. }
  989. return name
  990. }
  991. // updateSandboxNetworkSettings updates the sandbox ID and Key.
  992. func updateSandboxNetworkSettings(c *container.Container, sb libnetwork.Sandbox) error {
  993. c.NetworkSettings.SandboxID = sb.ID()
  994. c.NetworkSettings.SandboxKey = sb.Key()
  995. return nil
  996. }