container_operations_unix.go 28 KB

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