container_operations.go 31 KB

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