container_operations.go 34 KB

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