container_operations_unix.go 29 KB

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