container_operations.go 31 KB

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