container_operations_unix.go 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015
  1. // +build linux freebsd
  2. package daemon
  3. import (
  4. "fmt"
  5. "os"
  6. "path"
  7. "path/filepath"
  8. "strconv"
  9. "strings"
  10. "syscall"
  11. "time"
  12. "github.com/Sirupsen/logrus"
  13. networktypes "github.com/docker/docker/api/types/network"
  14. "github.com/docker/docker/container"
  15. "github.com/docker/docker/daemon/execdriver"
  16. "github.com/docker/docker/daemon/links"
  17. "github.com/docker/docker/daemon/network"
  18. derr "github.com/docker/docker/errors"
  19. "github.com/docker/docker/pkg/fileutils"
  20. "github.com/docker/docker/pkg/idtools"
  21. "github.com/docker/docker/pkg/mount"
  22. "github.com/docker/docker/pkg/stringid"
  23. "github.com/docker/docker/pkg/ulimit"
  24. "github.com/docker/docker/runconfig"
  25. "github.com/docker/libnetwork"
  26. "github.com/docker/libnetwork/netlabel"
  27. "github.com/docker/libnetwork/options"
  28. "github.com/opencontainers/runc/libcontainer/configs"
  29. "github.com/opencontainers/runc/libcontainer/devices"
  30. "github.com/opencontainers/runc/libcontainer/label"
  31. )
  32. func (daemon *Daemon) setupLinkedContainers(container *container.Container) ([]string, error) {
  33. var env []string
  34. children, err := daemon.children(container.Name)
  35. if err != nil {
  36. return nil, err
  37. }
  38. bridgeSettings := container.NetworkSettings.Networks["bridge"]
  39. if bridgeSettings == nil {
  40. return nil, nil
  41. }
  42. if len(children) > 0 {
  43. for linkAlias, child := range children {
  44. if !child.IsRunning() {
  45. return nil, derr.ErrorCodeLinkNotRunning.WithArgs(child.Name, linkAlias)
  46. }
  47. childBridgeSettings := child.NetworkSettings.Networks["bridge"]
  48. if childBridgeSettings == nil {
  49. return nil, fmt.Errorf("container %s not attached to default bridge network", child.ID)
  50. }
  51. link := links.NewLink(
  52. bridgeSettings.IPAddress,
  53. childBridgeSettings.IPAddress,
  54. linkAlias,
  55. child.Config.Env,
  56. child.Config.ExposedPorts,
  57. )
  58. for _, envVar := range link.ToEnv() {
  59. env = append(env, envVar)
  60. }
  61. }
  62. }
  63. return env, nil
  64. }
  65. func (daemon *Daemon) populateCommand(c *container.Container, env []string) error {
  66. var en *execdriver.Network
  67. if !c.Config.NetworkDisabled {
  68. en = &execdriver.Network{}
  69. if !daemon.execDriver.SupportsHooks() || c.HostConfig.NetworkMode.IsHost() {
  70. en.NamespacePath = c.NetworkSettings.SandboxKey
  71. }
  72. if c.HostConfig.NetworkMode.IsContainer() {
  73. nc, err := daemon.getNetworkedContainer(c.ID, c.HostConfig.NetworkMode.ConnectedContainer())
  74. if err != nil {
  75. return err
  76. }
  77. en.ContainerID = nc.ID
  78. }
  79. }
  80. ipc := &execdriver.Ipc{}
  81. var err error
  82. c.ShmPath, err = c.ShmResourcePath()
  83. if err != nil {
  84. return err
  85. }
  86. c.MqueuePath, err = c.MqueueResourcePath()
  87. if err != nil {
  88. return err
  89. }
  90. if c.HostConfig.IpcMode.IsContainer() {
  91. ic, err := daemon.getIpcContainer(c)
  92. if err != nil {
  93. return err
  94. }
  95. ipc.ContainerID = ic.ID
  96. c.ShmPath = ic.ShmPath
  97. c.MqueuePath = ic.MqueuePath
  98. } else {
  99. ipc.HostIpc = c.HostConfig.IpcMode.IsHost()
  100. if ipc.HostIpc {
  101. if _, err := os.Stat("/dev/shm"); err != nil {
  102. return fmt.Errorf("/dev/shm is not mounted, but must be for --ipc=host")
  103. }
  104. if _, err := os.Stat("/dev/mqueue"); err != nil {
  105. return fmt.Errorf("/dev/mqueue is not mounted, but must be for --ipc=host")
  106. }
  107. c.ShmPath = "/dev/shm"
  108. c.MqueuePath = "/dev/mqueue"
  109. }
  110. }
  111. pid := &execdriver.Pid{}
  112. pid.HostPid = c.HostConfig.PidMode.IsHost()
  113. uts := &execdriver.UTS{
  114. HostUTS: c.HostConfig.UTSMode.IsHost(),
  115. }
  116. // Build lists of devices allowed and created within the container.
  117. var userSpecifiedDevices []*configs.Device
  118. for _, deviceMapping := range c.HostConfig.Devices {
  119. devs, err := getDevicesFromPath(deviceMapping)
  120. if err != nil {
  121. return err
  122. }
  123. userSpecifiedDevices = append(userSpecifiedDevices, devs...)
  124. }
  125. allowedDevices := mergeDevices(configs.DefaultAllowedDevices, userSpecifiedDevices)
  126. autoCreatedDevices := mergeDevices(configs.DefaultAutoCreatedDevices, userSpecifiedDevices)
  127. var rlimits []*ulimit.Rlimit
  128. ulimits := c.HostConfig.Ulimits
  129. // Merge ulimits with daemon defaults
  130. ulIdx := make(map[string]*ulimit.Ulimit)
  131. for _, ul := range ulimits {
  132. ulIdx[ul.Name] = ul
  133. }
  134. for name, ul := range daemon.configStore.Ulimits {
  135. if _, exists := ulIdx[name]; !exists {
  136. ulimits = append(ulimits, ul)
  137. }
  138. }
  139. weightDevices, err := getBlkioWeightDevices(c.HostConfig)
  140. if err != nil {
  141. return err
  142. }
  143. readBpsDevice, err := getBlkioReadBpsDevices(c.HostConfig)
  144. if err != nil {
  145. return err
  146. }
  147. writeBpsDevice, err := getBlkioWriteBpsDevices(c.HostConfig)
  148. if err != nil {
  149. return err
  150. }
  151. for _, limit := range ulimits {
  152. rl, err := limit.GetRlimit()
  153. if err != nil {
  154. return err
  155. }
  156. rlimits = append(rlimits, rl)
  157. }
  158. resources := &execdriver.Resources{
  159. CommonResources: execdriver.CommonResources{
  160. Memory: c.HostConfig.Memory,
  161. MemoryReservation: c.HostConfig.MemoryReservation,
  162. CPUShares: c.HostConfig.CPUShares,
  163. BlkioWeight: c.HostConfig.BlkioWeight,
  164. },
  165. MemorySwap: c.HostConfig.MemorySwap,
  166. KernelMemory: c.HostConfig.KernelMemory,
  167. CpusetCpus: c.HostConfig.CpusetCpus,
  168. CpusetMems: c.HostConfig.CpusetMems,
  169. CPUPeriod: c.HostConfig.CPUPeriod,
  170. CPUQuota: c.HostConfig.CPUQuota,
  171. Rlimits: rlimits,
  172. BlkioWeightDevice: weightDevices,
  173. BlkioThrottleReadBpsDevice: readBpsDevice,
  174. BlkioThrottleWriteBpsDevice: writeBpsDevice,
  175. OomKillDisable: c.HostConfig.OomKillDisable,
  176. MemorySwappiness: -1,
  177. }
  178. if c.HostConfig.MemorySwappiness != nil {
  179. resources.MemorySwappiness = *c.HostConfig.MemorySwappiness
  180. }
  181. processConfig := execdriver.ProcessConfig{
  182. CommonProcessConfig: execdriver.CommonProcessConfig{
  183. Entrypoint: c.Path,
  184. Arguments: c.Args,
  185. Tty: c.Config.Tty,
  186. },
  187. Privileged: c.HostConfig.Privileged,
  188. User: c.Config.User,
  189. }
  190. processConfig.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
  191. processConfig.Env = env
  192. remappedRoot := &execdriver.User{}
  193. rootUID, rootGID := daemon.GetRemappedUIDGID()
  194. if rootUID != 0 {
  195. remappedRoot.UID = rootUID
  196. remappedRoot.GID = rootGID
  197. }
  198. uidMap, gidMap := daemon.GetUIDGIDMaps()
  199. c.Command = &execdriver.Command{
  200. CommonCommand: execdriver.CommonCommand{
  201. ID: c.ID,
  202. InitPath: "/.dockerinit",
  203. MountLabel: c.GetMountLabel(),
  204. Network: en,
  205. ProcessConfig: processConfig,
  206. ProcessLabel: c.GetProcessLabel(),
  207. Rootfs: c.BaseFS,
  208. Resources: resources,
  209. WorkingDir: c.Config.WorkingDir,
  210. },
  211. AllowedDevices: allowedDevices,
  212. AppArmorProfile: c.AppArmorProfile,
  213. AutoCreatedDevices: autoCreatedDevices,
  214. CapAdd: c.HostConfig.CapAdd.Slice(),
  215. CapDrop: c.HostConfig.CapDrop.Slice(),
  216. CgroupParent: c.HostConfig.CgroupParent,
  217. GIDMapping: gidMap,
  218. GroupAdd: c.HostConfig.GroupAdd,
  219. Ipc: ipc,
  220. OomScoreAdj: c.HostConfig.OomScoreAdj,
  221. Pid: pid,
  222. ReadonlyRootfs: c.HostConfig.ReadonlyRootfs,
  223. RemappedRoot: remappedRoot,
  224. SeccompProfile: c.SeccompProfile,
  225. UIDMapping: uidMap,
  226. UTS: uts,
  227. }
  228. return nil
  229. }
  230. // getSize returns the real size & virtual size of the container.
  231. func (daemon *Daemon) getSize(container *container.Container) (int64, int64) {
  232. var (
  233. sizeRw, sizeRootfs int64
  234. err error
  235. )
  236. if err := daemon.Mount(container); err != nil {
  237. logrus.Errorf("Failed to compute size of container rootfs %s: %s", container.ID, err)
  238. return sizeRw, sizeRootfs
  239. }
  240. defer daemon.Unmount(container)
  241. sizeRw, err = container.RWLayer.Size()
  242. if err != nil {
  243. logrus.Errorf("Driver %s couldn't return diff size of container %s: %s", daemon.driver, container.ID, err)
  244. // FIXME: GetSize should return an error. Not changing it now in case
  245. // there is a side-effect.
  246. sizeRw = -1
  247. }
  248. if parent := container.RWLayer.Parent(); parent != nil {
  249. sizeRootfs, err = parent.Size()
  250. if err != nil {
  251. sizeRootfs = -1
  252. } else if sizeRw != -1 {
  253. sizeRootfs += sizeRw
  254. }
  255. }
  256. return sizeRw, sizeRootfs
  257. }
  258. func (daemon *Daemon) buildSandboxOptions(container *container.Container, n libnetwork.Network) ([]libnetwork.SandboxOption, error) {
  259. var (
  260. sboxOptions []libnetwork.SandboxOption
  261. err error
  262. dns []string
  263. dnsSearch []string
  264. dnsOptions []string
  265. )
  266. sboxOptions = append(sboxOptions, libnetwork.OptionHostname(container.Config.Hostname),
  267. libnetwork.OptionDomainname(container.Config.Domainname))
  268. if container.HostConfig.NetworkMode.IsHost() {
  269. sboxOptions = append(sboxOptions, libnetwork.OptionUseDefaultSandbox())
  270. sboxOptions = append(sboxOptions, libnetwork.OptionOriginHostsPath("/etc/hosts"))
  271. sboxOptions = append(sboxOptions, libnetwork.OptionOriginResolvConfPath("/etc/resolv.conf"))
  272. } else if daemon.execDriver.SupportsHooks() {
  273. // OptionUseExternalKey is mandatory for userns support.
  274. // But optional for non-userns support
  275. sboxOptions = append(sboxOptions, libnetwork.OptionUseExternalKey())
  276. }
  277. container.HostsPath, err = container.GetRootResourcePath("hosts")
  278. if err != nil {
  279. return nil, err
  280. }
  281. sboxOptions = append(sboxOptions, libnetwork.OptionHostsPath(container.HostsPath))
  282. container.ResolvConfPath, err = container.GetRootResourcePath("resolv.conf")
  283. if err != nil {
  284. return nil, err
  285. }
  286. sboxOptions = append(sboxOptions, libnetwork.OptionResolvConfPath(container.ResolvConfPath))
  287. if len(container.HostConfig.DNS) > 0 {
  288. dns = container.HostConfig.DNS
  289. } else if len(daemon.configStore.DNS) > 0 {
  290. dns = daemon.configStore.DNS
  291. }
  292. for _, d := range dns {
  293. sboxOptions = append(sboxOptions, libnetwork.OptionDNS(d))
  294. }
  295. if len(container.HostConfig.DNSSearch) > 0 {
  296. dnsSearch = container.HostConfig.DNSSearch
  297. } else if len(daemon.configStore.DNSSearch) > 0 {
  298. dnsSearch = daemon.configStore.DNSSearch
  299. }
  300. for _, ds := range dnsSearch {
  301. sboxOptions = append(sboxOptions, libnetwork.OptionDNSSearch(ds))
  302. }
  303. if len(container.HostConfig.DNSOptions) > 0 {
  304. dnsOptions = container.HostConfig.DNSOptions
  305. } else if len(daemon.configStore.DNSOptions) > 0 {
  306. dnsOptions = daemon.configStore.DNSOptions
  307. }
  308. for _, ds := range dnsOptions {
  309. sboxOptions = append(sboxOptions, libnetwork.OptionDNSOptions(ds))
  310. }
  311. if container.NetworkSettings.SecondaryIPAddresses != nil {
  312. name := container.Config.Hostname
  313. if container.Config.Domainname != "" {
  314. name = name + "." + container.Config.Domainname
  315. }
  316. for _, a := range container.NetworkSettings.SecondaryIPAddresses {
  317. sboxOptions = append(sboxOptions, libnetwork.OptionExtraHost(name, a.Addr))
  318. }
  319. }
  320. for _, extraHost := range container.HostConfig.ExtraHosts {
  321. // allow IPv6 addresses in extra hosts; only split on first ":"
  322. parts := strings.SplitN(extraHost, ":", 2)
  323. sboxOptions = append(sboxOptions, libnetwork.OptionExtraHost(parts[0], parts[1]))
  324. }
  325. // Link feature is supported only for the default bridge network.
  326. // return if this call to build join options is not for default bridge network
  327. if n.Name() != "bridge" {
  328. return sboxOptions, nil
  329. }
  330. ep, _ := container.GetEndpointInNetwork(n)
  331. if ep == nil {
  332. return sboxOptions, nil
  333. }
  334. var childEndpoints, parentEndpoints []string
  335. children, err := daemon.children(container.Name)
  336. if err != nil {
  337. return nil, err
  338. }
  339. for linkAlias, child := range children {
  340. if !isLinkable(child) {
  341. return nil, fmt.Errorf("Cannot link to %s, as it does not belong to the default network", child.Name)
  342. }
  343. _, alias := path.Split(linkAlias)
  344. // allow access to the linked container via the alias, real name, and container hostname
  345. aliasList := alias + " " + child.Config.Hostname
  346. // only add the name if alias isn't equal to the name
  347. if alias != child.Name[1:] {
  348. aliasList = aliasList + " " + child.Name[1:]
  349. }
  350. sboxOptions = append(sboxOptions, libnetwork.OptionExtraHost(aliasList, child.NetworkSettings.Networks["bridge"].IPAddress))
  351. cEndpoint, _ := child.GetEndpointInNetwork(n)
  352. if cEndpoint != nil && cEndpoint.ID() != "" {
  353. childEndpoints = append(childEndpoints, cEndpoint.ID())
  354. }
  355. }
  356. bridgeSettings := container.NetworkSettings.Networks["bridge"]
  357. refs := daemon.containerGraph().RefPaths(container.ID)
  358. for _, ref := range refs {
  359. if ref.ParentID == "0" {
  360. continue
  361. }
  362. c, err := daemon.GetContainer(ref.ParentID)
  363. if err != nil {
  364. logrus.Error(err)
  365. }
  366. if c != nil && !daemon.configStore.DisableBridge && container.HostConfig.NetworkMode.IsPrivate() {
  367. logrus.Debugf("Update /etc/hosts of %s for alias %s with ip %s", c.ID, ref.Name, bridgeSettings.IPAddress)
  368. sboxOptions = append(sboxOptions, libnetwork.OptionParentUpdate(c.ID, ref.Name, bridgeSettings.IPAddress))
  369. if ep.ID() != "" {
  370. parentEndpoints = append(parentEndpoints, ep.ID())
  371. }
  372. }
  373. }
  374. linkOptions := options.Generic{
  375. netlabel.GenericData: options.Generic{
  376. "ParentEndpoints": parentEndpoints,
  377. "ChildEndpoints": childEndpoints,
  378. },
  379. }
  380. sboxOptions = append(sboxOptions, libnetwork.OptionGeneric(linkOptions))
  381. return sboxOptions, nil
  382. }
  383. func (daemon *Daemon) updateNetworkSettings(container *container.Container, n libnetwork.Network) error {
  384. if container.NetworkSettings == nil {
  385. container.NetworkSettings = &network.Settings{Networks: make(map[string]*networktypes.EndpointSettings)}
  386. }
  387. if !container.HostConfig.NetworkMode.IsHost() && runconfig.NetworkMode(n.Type()).IsHost() {
  388. return runconfig.ErrConflictHostNetwork
  389. }
  390. for s := range container.NetworkSettings.Networks {
  391. sn, err := daemon.FindNetwork(s)
  392. if err != nil {
  393. continue
  394. }
  395. if sn.Name() == n.Name() {
  396. // Avoid duplicate config
  397. return nil
  398. }
  399. if !runconfig.NetworkMode(sn.Type()).IsPrivate() ||
  400. !runconfig.NetworkMode(n.Type()).IsPrivate() {
  401. return runconfig.ErrConflictSharedNetwork
  402. }
  403. if runconfig.NetworkMode(sn.Name()).IsNone() ||
  404. runconfig.NetworkMode(n.Name()).IsNone() {
  405. return runconfig.ErrConflictNoNetwork
  406. }
  407. }
  408. container.NetworkSettings.Networks[n.Name()] = new(networktypes.EndpointSettings)
  409. return nil
  410. }
  411. func (daemon *Daemon) updateEndpointNetworkSettings(container *container.Container, n libnetwork.Network, ep libnetwork.Endpoint) error {
  412. if err := container.BuildEndpointInfo(n, ep); err != nil {
  413. return err
  414. }
  415. if container.HostConfig.NetworkMode == runconfig.NetworkMode("bridge") {
  416. container.NetworkSettings.Bridge = daemon.configStore.Bridge.Iface
  417. }
  418. return nil
  419. }
  420. // UpdateNetwork is used to update the container's network (e.g. when linked containers
  421. // get removed/unlinked).
  422. func (daemon *Daemon) updateNetwork(container *container.Container) error {
  423. ctrl := daemon.netController
  424. sid := container.NetworkSettings.SandboxID
  425. sb, err := ctrl.SandboxByID(sid)
  426. if err != nil {
  427. return derr.ErrorCodeNoSandbox.WithArgs(sid, err)
  428. }
  429. // Find if container is connected to the default bridge network
  430. var n libnetwork.Network
  431. for name := range container.NetworkSettings.Networks {
  432. sn, err := daemon.FindNetwork(name)
  433. if err != nil {
  434. continue
  435. }
  436. if sn.Name() == "bridge" {
  437. n = sn
  438. break
  439. }
  440. }
  441. if n == nil {
  442. // Not connected to the default bridge network; Nothing to do
  443. return nil
  444. }
  445. options, err := daemon.buildSandboxOptions(container, n)
  446. if err != nil {
  447. return derr.ErrorCodeNetworkUpdate.WithArgs(err)
  448. }
  449. if err := sb.Refresh(options...); err != nil {
  450. return derr.ErrorCodeNetworkRefresh.WithArgs(sid, err)
  451. }
  452. return nil
  453. }
  454. // updateContainerNetworkSettings update the network settings
  455. func (daemon *Daemon) updateContainerNetworkSettings(container *container.Container) error {
  456. mode := container.HostConfig.NetworkMode
  457. if container.Config.NetworkDisabled || mode.IsContainer() {
  458. return nil
  459. }
  460. networkName := mode.NetworkName()
  461. if mode.IsDefault() {
  462. networkName = daemon.netController.Config().Daemon.DefaultNetwork
  463. }
  464. if mode.IsUserDefined() {
  465. n, err := daemon.FindNetwork(networkName)
  466. if err != nil {
  467. return err
  468. }
  469. networkName = n.Name()
  470. }
  471. container.NetworkSettings.Networks = make(map[string]*networktypes.EndpointSettings)
  472. container.NetworkSettings.Networks[networkName] = new(networktypes.EndpointSettings)
  473. return nil
  474. }
  475. func (daemon *Daemon) allocateNetwork(container *container.Container) error {
  476. controller := daemon.netController
  477. // Cleanup any stale sandbox left over due to ungraceful daemon shutdown
  478. if err := controller.SandboxDestroy(container.ID); err != nil {
  479. logrus.Errorf("failed to cleanup up stale network sandbox for container %s", container.ID)
  480. }
  481. updateSettings := false
  482. if len(container.NetworkSettings.Networks) == 0 {
  483. if container.Config.NetworkDisabled || container.HostConfig.NetworkMode.IsContainer() {
  484. return nil
  485. }
  486. err := daemon.updateContainerNetworkSettings(container)
  487. if err != nil {
  488. return err
  489. }
  490. updateSettings = true
  491. }
  492. for n := range container.NetworkSettings.Networks {
  493. if err := daemon.connectToNetwork(container, n, updateSettings); err != nil {
  494. return err
  495. }
  496. }
  497. return container.WriteHostConfig()
  498. }
  499. func (daemon *Daemon) getNetworkSandbox(container *container.Container) libnetwork.Sandbox {
  500. var sb libnetwork.Sandbox
  501. daemon.netController.WalkSandboxes(func(s libnetwork.Sandbox) bool {
  502. if s.ContainerID() == container.ID {
  503. sb = s
  504. return true
  505. }
  506. return false
  507. })
  508. return sb
  509. }
  510. // ConnectToNetwork connects a container to a network
  511. func (daemon *Daemon) ConnectToNetwork(container *container.Container, idOrName string) error {
  512. if !container.Running {
  513. return derr.ErrorCodeNotRunning.WithArgs(container.ID)
  514. }
  515. if err := daemon.connectToNetwork(container, idOrName, true); err != nil {
  516. return err
  517. }
  518. if err := container.ToDiskLocking(); err != nil {
  519. return fmt.Errorf("Error saving container to disk: %v", err)
  520. }
  521. return nil
  522. }
  523. func (daemon *Daemon) connectToNetwork(container *container.Container, idOrName string, updateSettings bool) (err error) {
  524. if container.HostConfig.NetworkMode.IsContainer() {
  525. return runconfig.ErrConflictSharedNetwork
  526. }
  527. if runconfig.NetworkMode(idOrName).IsBridge() &&
  528. daemon.configStore.DisableBridge {
  529. container.Config.NetworkDisabled = true
  530. return nil
  531. }
  532. controller := daemon.netController
  533. n, err := daemon.FindNetwork(idOrName)
  534. if err != nil {
  535. return err
  536. }
  537. if updateSettings {
  538. if err := daemon.updateNetworkSettings(container, n); err != nil {
  539. return err
  540. }
  541. }
  542. ep, err := container.GetEndpointInNetwork(n)
  543. if err == nil {
  544. return fmt.Errorf("Conflict. A container with name %q is already connected to network %s.", strings.TrimPrefix(container.Name, "/"), idOrName)
  545. }
  546. if _, ok := err.(libnetwork.ErrNoSuchEndpoint); !ok {
  547. return err
  548. }
  549. createOptions, err := container.BuildCreateEndpointOptions(n)
  550. if err != nil {
  551. return err
  552. }
  553. endpointName := strings.TrimPrefix(container.Name, "/")
  554. ep, err = n.CreateEndpoint(endpointName, createOptions...)
  555. if err != nil {
  556. return err
  557. }
  558. defer func() {
  559. if err != nil {
  560. if e := ep.Delete(); e != nil {
  561. logrus.Warnf("Could not rollback container connection to network %s", idOrName)
  562. }
  563. }
  564. }()
  565. if err := daemon.updateEndpointNetworkSettings(container, n, ep); err != nil {
  566. return err
  567. }
  568. sb := daemon.getNetworkSandbox(container)
  569. if sb == nil {
  570. options, err := daemon.buildSandboxOptions(container, n)
  571. if err != nil {
  572. return err
  573. }
  574. sb, err = controller.NewSandbox(container.ID, options...)
  575. if err != nil {
  576. return err
  577. }
  578. container.UpdateSandboxNetworkSettings(sb)
  579. }
  580. if err := ep.Join(sb); err != nil {
  581. return err
  582. }
  583. if err := container.UpdateJoinInfo(n, ep); err != nil {
  584. return derr.ErrorCodeJoinInfo.WithArgs(err)
  585. }
  586. return nil
  587. }
  588. // DisconnectFromNetwork disconnects container from network n.
  589. func (daemon *Daemon) DisconnectFromNetwork(container *container.Container, n libnetwork.Network) error {
  590. if !container.Running {
  591. return derr.ErrorCodeNotRunning.WithArgs(container.ID)
  592. }
  593. if container.HostConfig.NetworkMode.IsHost() && runconfig.NetworkMode(n.Type()).IsHost() {
  594. return runconfig.ErrConflictHostNetwork
  595. }
  596. return disconnectFromNetwork(container, n)
  597. }
  598. func disconnectFromNetwork(container *container.Container, n libnetwork.Network) error {
  599. if err := container.ToDiskLocking(); err != nil {
  600. return fmt.Errorf("Error saving container to disk: %v", err)
  601. }
  602. var (
  603. ep libnetwork.Endpoint
  604. sbox libnetwork.Sandbox
  605. )
  606. s := func(current libnetwork.Endpoint) bool {
  607. epInfo := current.Info()
  608. if epInfo == nil {
  609. return false
  610. }
  611. if sb := epInfo.Sandbox(); sb != nil {
  612. if sb.ContainerID() == container.ID {
  613. ep = current
  614. sbox = sb
  615. return true
  616. }
  617. }
  618. return false
  619. }
  620. n.WalkEndpoints(s)
  621. if ep == nil {
  622. return fmt.Errorf("container %s is not connected to the network", container.ID)
  623. }
  624. if err := ep.Leave(sbox); err != nil {
  625. return fmt.Errorf("container %s failed to leave network %s: %v", container.ID, n.Name(), err)
  626. }
  627. if err := ep.Delete(); err != nil {
  628. return fmt.Errorf("endpoint delete failed for container %s on network %s: %v", container.ID, n.Name(), err)
  629. }
  630. delete(container.NetworkSettings.Networks, n.Name())
  631. return nil
  632. }
  633. func (daemon *Daemon) initializeNetworking(container *container.Container) error {
  634. var err error
  635. if container.HostConfig.NetworkMode.IsContainer() {
  636. // we need to get the hosts files from the container to join
  637. nc, err := daemon.getNetworkedContainer(container.ID, container.HostConfig.NetworkMode.ConnectedContainer())
  638. if err != nil {
  639. return err
  640. }
  641. container.HostnamePath = nc.HostnamePath
  642. container.HostsPath = nc.HostsPath
  643. container.ResolvConfPath = nc.ResolvConfPath
  644. container.Config.Hostname = nc.Config.Hostname
  645. container.Config.Domainname = nc.Config.Domainname
  646. return nil
  647. }
  648. if container.HostConfig.NetworkMode.IsHost() {
  649. container.Config.Hostname, err = os.Hostname()
  650. if err != nil {
  651. return err
  652. }
  653. parts := strings.SplitN(container.Config.Hostname, ".", 2)
  654. if len(parts) > 1 {
  655. container.Config.Hostname = parts[0]
  656. container.Config.Domainname = parts[1]
  657. }
  658. }
  659. if err := daemon.allocateNetwork(container); err != nil {
  660. return err
  661. }
  662. return container.BuildHostnameFile()
  663. }
  664. // called from the libcontainer pre-start hook to set the network
  665. // namespace configuration linkage to the libnetwork "sandbox" entity
  666. func (daemon *Daemon) setNetworkNamespaceKey(containerID string, pid int) error {
  667. path := fmt.Sprintf("/proc/%d/ns/net", pid)
  668. var sandbox libnetwork.Sandbox
  669. search := libnetwork.SandboxContainerWalker(&sandbox, containerID)
  670. daemon.netController.WalkSandboxes(search)
  671. if sandbox == nil {
  672. return derr.ErrorCodeNoSandbox.WithArgs(containerID, "no sandbox found")
  673. }
  674. return sandbox.SetKey(path)
  675. }
  676. func (daemon *Daemon) getIpcContainer(container *container.Container) (*container.Container, error) {
  677. containerID := container.HostConfig.IpcMode.Container()
  678. c, err := daemon.GetContainer(containerID)
  679. if err != nil {
  680. return nil, err
  681. }
  682. if !c.IsRunning() {
  683. return nil, derr.ErrorCodeIPCRunning
  684. }
  685. return c, nil
  686. }
  687. func (daemon *Daemon) getNetworkedContainer(containerID, connectedContainerID string) (*container.Container, error) {
  688. nc, err := daemon.GetContainer(connectedContainerID)
  689. if err != nil {
  690. return nil, err
  691. }
  692. if containerID == nc.ID {
  693. return nil, derr.ErrorCodeJoinSelf
  694. }
  695. if !nc.IsRunning() {
  696. return nil, derr.ErrorCodeJoinRunning.WithArgs(connectedContainerID)
  697. }
  698. return nc, nil
  699. }
  700. func (daemon *Daemon) releaseNetwork(container *container.Container) {
  701. if container.HostConfig.NetworkMode.IsContainer() || container.Config.NetworkDisabled {
  702. return
  703. }
  704. sid := container.NetworkSettings.SandboxID
  705. networks := container.NetworkSettings.Networks
  706. for n := range networks {
  707. networks[n] = &networktypes.EndpointSettings{}
  708. }
  709. container.NetworkSettings = &network.Settings{Networks: networks}
  710. if sid == "" || len(networks) == 0 {
  711. return
  712. }
  713. sb, err := daemon.netController.SandboxByID(sid)
  714. if err != nil {
  715. logrus.Errorf("error locating sandbox id %s: %v", sid, err)
  716. return
  717. }
  718. if err := sb.Delete(); err != nil {
  719. logrus.Errorf("Error deleting sandbox id %s for container %s: %v", sid, container.ID, err)
  720. }
  721. }
  722. func (daemon *Daemon) setupIpcDirs(c *container.Container) error {
  723. rootUID, rootGID := daemon.GetRemappedUIDGID()
  724. if !c.HasMountFor("/dev/shm") {
  725. shmPath, err := c.ShmResourcePath()
  726. if err != nil {
  727. return err
  728. }
  729. if err := idtools.MkdirAllAs(shmPath, 0700, rootUID, rootGID); err != nil {
  730. return err
  731. }
  732. shmSize := container.DefaultSHMSize
  733. if c.HostConfig.ShmSize != nil {
  734. shmSize = *c.HostConfig.ShmSize
  735. }
  736. shmproperty := "mode=1777,size=" + strconv.FormatInt(shmSize, 10)
  737. if err := syscall.Mount("shm", shmPath, "tmpfs", uintptr(syscall.MS_NOEXEC|syscall.MS_NOSUID|syscall.MS_NODEV), label.FormatMountLabel(shmproperty, c.GetMountLabel())); err != nil {
  738. return fmt.Errorf("mounting shm tmpfs: %s", err)
  739. }
  740. if err := os.Chown(shmPath, rootUID, rootGID); err != nil {
  741. return err
  742. }
  743. }
  744. if !c.HasMountFor("/dev/mqueue") {
  745. mqueuePath, err := c.MqueueResourcePath()
  746. if err != nil {
  747. return err
  748. }
  749. if err := idtools.MkdirAllAs(mqueuePath, 0700, rootUID, rootGID); err != nil {
  750. return err
  751. }
  752. if err := syscall.Mount("mqueue", mqueuePath, "mqueue", uintptr(syscall.MS_NOEXEC|syscall.MS_NOSUID|syscall.MS_NODEV), ""); err != nil {
  753. return fmt.Errorf("mounting mqueue mqueue : %s", err)
  754. }
  755. if err := os.Chown(mqueuePath, rootUID, rootGID); err != nil {
  756. return err
  757. }
  758. }
  759. return nil
  760. }
  761. func (daemon *Daemon) mountVolumes(container *container.Container) error {
  762. mounts, err := daemon.setupMounts(container)
  763. if err != nil {
  764. return err
  765. }
  766. for _, m := range mounts {
  767. dest, err := container.GetResourcePath(m.Destination)
  768. if err != nil {
  769. return err
  770. }
  771. var stat os.FileInfo
  772. stat, err = os.Stat(m.Source)
  773. if err != nil {
  774. return err
  775. }
  776. if err = fileutils.CreateIfNotExists(dest, stat.IsDir()); err != nil {
  777. return err
  778. }
  779. opts := "rbind,ro"
  780. if m.Writable {
  781. opts = "rbind,rw"
  782. }
  783. if err := mount.Mount(m.Source, dest, "bind", opts); err != nil {
  784. return err
  785. }
  786. }
  787. return nil
  788. }
  789. func killProcessDirectly(container *container.Container) error {
  790. if _, err := container.WaitStop(10 * time.Second); err != nil {
  791. // Ensure that we don't kill ourselves
  792. if pid := container.GetPID(); pid != 0 {
  793. logrus.Infof("Container %s failed to exit within 10 seconds of kill - trying direct SIGKILL", stringid.TruncateID(container.ID))
  794. if err := syscall.Kill(pid, 9); err != nil {
  795. if err != syscall.ESRCH {
  796. return err
  797. }
  798. logrus.Debugf("Cannot kill process (pid=%d) with signal 9: no such process.", pid)
  799. }
  800. }
  801. }
  802. return nil
  803. }
  804. func getDevicesFromPath(deviceMapping runconfig.DeviceMapping) (devs []*configs.Device, err error) {
  805. device, err := devices.DeviceFromPath(deviceMapping.PathOnHost, deviceMapping.CgroupPermissions)
  806. // if there was no error, return the device
  807. if err == nil {
  808. device.Path = deviceMapping.PathInContainer
  809. return append(devs, device), nil
  810. }
  811. // if the device is not a device node
  812. // try to see if it's a directory holding many devices
  813. if err == devices.ErrNotADevice {
  814. // check if it is a directory
  815. if src, e := os.Stat(deviceMapping.PathOnHost); e == nil && src.IsDir() {
  816. // mount the internal devices recursively
  817. filepath.Walk(deviceMapping.PathOnHost, func(dpath string, f os.FileInfo, e error) error {
  818. childDevice, e := devices.DeviceFromPath(dpath, deviceMapping.CgroupPermissions)
  819. if e != nil {
  820. // ignore the device
  821. return nil
  822. }
  823. // add the device to userSpecified devices
  824. childDevice.Path = strings.Replace(dpath, deviceMapping.PathOnHost, deviceMapping.PathInContainer, 1)
  825. devs = append(devs, childDevice)
  826. return nil
  827. })
  828. }
  829. }
  830. if len(devs) > 0 {
  831. return devs, nil
  832. }
  833. return devs, derr.ErrorCodeDeviceInfo.WithArgs(deviceMapping.PathOnHost, err)
  834. }
  835. func mergeDevices(defaultDevices, userDevices []*configs.Device) []*configs.Device {
  836. if len(userDevices) == 0 {
  837. return defaultDevices
  838. }
  839. paths := map[string]*configs.Device{}
  840. for _, d := range userDevices {
  841. paths[d.Path] = d
  842. }
  843. var devs []*configs.Device
  844. for _, d := range defaultDevices {
  845. if _, defined := paths[d.Path]; !defined {
  846. devs = append(devs, d)
  847. }
  848. }
  849. return append(devs, userDevices...)
  850. }
  851. func detachMounted(path string) error {
  852. return syscall.Unmount(path, syscall.MNT_DETACH)
  853. }
  854. func isLinkable(child *container.Container) bool {
  855. // A container is linkable only if it belongs to the default network
  856. _, ok := child.NetworkSettings.Networks["bridge"]
  857. return ok
  858. }