container_operations.go 34 KB

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