container_operations.go 34 KB

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