container_operations.go 31 KB

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