container_operations_unix.go 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048
  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: daemon.configStore.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. if c.HostConfig.CgroupParent != "" {
  240. c.Command.CgroupParent = c.HostConfig.CgroupParent
  241. }
  242. return nil
  243. }
  244. // getSize returns the real size & virtual size of the container.
  245. func (daemon *Daemon) getSize(container *container.Container) (int64, int64) {
  246. var (
  247. sizeRw, sizeRootfs int64
  248. err error
  249. )
  250. if err := daemon.Mount(container); err != nil {
  251. logrus.Errorf("Failed to compute size of container rootfs %s: %s", container.ID, err)
  252. return sizeRw, sizeRootfs
  253. }
  254. defer daemon.Unmount(container)
  255. sizeRw, err = container.RWLayer.Size()
  256. if err != nil {
  257. logrus.Errorf("Driver %s couldn't return diff size of container %s: %s",
  258. daemon.GraphDriverName(), container.ID, err)
  259. // FIXME: GetSize should return an error. Not changing it now in case
  260. // there is a side-effect.
  261. sizeRw = -1
  262. }
  263. if parent := container.RWLayer.Parent(); parent != nil {
  264. sizeRootfs, err = parent.Size()
  265. if err != nil {
  266. sizeRootfs = -1
  267. } else if sizeRw != -1 {
  268. sizeRootfs += sizeRw
  269. }
  270. }
  271. return sizeRw, sizeRootfs
  272. }
  273. func (daemon *Daemon) buildSandboxOptions(container *container.Container, n libnetwork.Network) ([]libnetwork.SandboxOption, error) {
  274. var (
  275. sboxOptions []libnetwork.SandboxOption
  276. err error
  277. dns []string
  278. dnsSearch []string
  279. dnsOptions []string
  280. )
  281. sboxOptions = append(sboxOptions, libnetwork.OptionHostname(container.Config.Hostname),
  282. libnetwork.OptionDomainname(container.Config.Domainname))
  283. if container.HostConfig.NetworkMode.IsHost() {
  284. sboxOptions = append(sboxOptions, libnetwork.OptionUseDefaultSandbox())
  285. sboxOptions = append(sboxOptions, libnetwork.OptionOriginHostsPath("/etc/hosts"))
  286. sboxOptions = append(sboxOptions, libnetwork.OptionOriginResolvConfPath("/etc/resolv.conf"))
  287. } else if daemon.execDriver.SupportsHooks() {
  288. // OptionUseExternalKey is mandatory for userns support.
  289. // But optional for non-userns support
  290. sboxOptions = append(sboxOptions, libnetwork.OptionUseExternalKey())
  291. }
  292. container.HostsPath, err = container.GetRootResourcePath("hosts")
  293. if err != nil {
  294. return nil, err
  295. }
  296. sboxOptions = append(sboxOptions, libnetwork.OptionHostsPath(container.HostsPath))
  297. container.ResolvConfPath, err = container.GetRootResourcePath("resolv.conf")
  298. if err != nil {
  299. return nil, err
  300. }
  301. sboxOptions = append(sboxOptions, libnetwork.OptionResolvConfPath(container.ResolvConfPath))
  302. if len(container.HostConfig.DNS) > 0 {
  303. dns = container.HostConfig.DNS
  304. } else if len(daemon.configStore.DNS) > 0 {
  305. dns = daemon.configStore.DNS
  306. }
  307. for _, d := range dns {
  308. sboxOptions = append(sboxOptions, libnetwork.OptionDNS(d))
  309. }
  310. if len(container.HostConfig.DNSSearch) > 0 {
  311. dnsSearch = container.HostConfig.DNSSearch
  312. } else if len(daemon.configStore.DNSSearch) > 0 {
  313. dnsSearch = daemon.configStore.DNSSearch
  314. }
  315. for _, ds := range dnsSearch {
  316. sboxOptions = append(sboxOptions, libnetwork.OptionDNSSearch(ds))
  317. }
  318. if len(container.HostConfig.DNSOptions) > 0 {
  319. dnsOptions = container.HostConfig.DNSOptions
  320. } else if len(daemon.configStore.DNSOptions) > 0 {
  321. dnsOptions = daemon.configStore.DNSOptions
  322. }
  323. for _, ds := range dnsOptions {
  324. sboxOptions = append(sboxOptions, libnetwork.OptionDNSOptions(ds))
  325. }
  326. if container.NetworkSettings.SecondaryIPAddresses != nil {
  327. name := container.Config.Hostname
  328. if container.Config.Domainname != "" {
  329. name = name + "." + container.Config.Domainname
  330. }
  331. for _, a := range container.NetworkSettings.SecondaryIPAddresses {
  332. sboxOptions = append(sboxOptions, libnetwork.OptionExtraHost(name, a.Addr))
  333. }
  334. }
  335. for _, extraHost := range container.HostConfig.ExtraHosts {
  336. // allow IPv6 addresses in extra hosts; only split on first ":"
  337. parts := strings.SplitN(extraHost, ":", 2)
  338. sboxOptions = append(sboxOptions, libnetwork.OptionExtraHost(parts[0], parts[1]))
  339. }
  340. // Link feature is supported only for the default bridge network.
  341. // return if this call to build join options is not for default bridge network
  342. if n.Name() != "bridge" {
  343. return sboxOptions, nil
  344. }
  345. ep, _ := container.GetEndpointInNetwork(n)
  346. if ep == nil {
  347. return sboxOptions, nil
  348. }
  349. var childEndpoints, parentEndpoints []string
  350. children, err := daemon.children(container.Name)
  351. if err != nil {
  352. return nil, err
  353. }
  354. for linkAlias, child := range children {
  355. if !isLinkable(child) {
  356. return nil, fmt.Errorf("Cannot link to %s, as it does not belong to the default network", child.Name)
  357. }
  358. _, alias := path.Split(linkAlias)
  359. // allow access to the linked container via the alias, real name, and container hostname
  360. aliasList := alias + " " + child.Config.Hostname
  361. // only add the name if alias isn't equal to the name
  362. if alias != child.Name[1:] {
  363. aliasList = aliasList + " " + child.Name[1:]
  364. }
  365. sboxOptions = append(sboxOptions, libnetwork.OptionExtraHost(aliasList, child.NetworkSettings.Networks["bridge"].IPAddress))
  366. cEndpoint, _ := child.GetEndpointInNetwork(n)
  367. if cEndpoint != nil && cEndpoint.ID() != "" {
  368. childEndpoints = append(childEndpoints, cEndpoint.ID())
  369. }
  370. }
  371. bridgeSettings := container.NetworkSettings.Networks["bridge"]
  372. refs := daemon.containerGraph().RefPaths(container.ID)
  373. for _, ref := range refs {
  374. if ref.ParentID == "0" {
  375. continue
  376. }
  377. c, err := daemon.GetContainer(ref.ParentID)
  378. if err != nil {
  379. logrus.Error(err)
  380. }
  381. if c != nil && !daemon.configStore.DisableBridge && container.HostConfig.NetworkMode.IsPrivate() {
  382. logrus.Debugf("Update /etc/hosts of %s for alias %s with ip %s", c.ID, ref.Name, bridgeSettings.IPAddress)
  383. sboxOptions = append(sboxOptions, libnetwork.OptionParentUpdate(c.ID, ref.Name, bridgeSettings.IPAddress))
  384. if ep.ID() != "" {
  385. parentEndpoints = append(parentEndpoints, ep.ID())
  386. }
  387. }
  388. }
  389. linkOptions := options.Generic{
  390. netlabel.GenericData: options.Generic{
  391. "ParentEndpoints": parentEndpoints,
  392. "ChildEndpoints": childEndpoints,
  393. },
  394. }
  395. sboxOptions = append(sboxOptions, libnetwork.OptionGeneric(linkOptions))
  396. return sboxOptions, nil
  397. }
  398. func (daemon *Daemon) updateNetworkSettings(container *container.Container, n libnetwork.Network) error {
  399. if container.NetworkSettings == nil {
  400. container.NetworkSettings = &network.Settings{Networks: make(map[string]*networktypes.EndpointSettings)}
  401. }
  402. if !container.HostConfig.NetworkMode.IsHost() && containertypes.NetworkMode(n.Type()).IsHost() {
  403. return runconfig.ErrConflictHostNetwork
  404. }
  405. for s := range container.NetworkSettings.Networks {
  406. sn, err := daemon.FindNetwork(s)
  407. if err != nil {
  408. continue
  409. }
  410. if sn.Name() == n.Name() {
  411. // Avoid duplicate config
  412. return nil
  413. }
  414. if !containertypes.NetworkMode(sn.Type()).IsPrivate() ||
  415. !containertypes.NetworkMode(n.Type()).IsPrivate() {
  416. return runconfig.ErrConflictSharedNetwork
  417. }
  418. if containertypes.NetworkMode(sn.Name()).IsNone() ||
  419. containertypes.NetworkMode(n.Name()).IsNone() {
  420. return runconfig.ErrConflictNoNetwork
  421. }
  422. }
  423. container.NetworkSettings.Networks[n.Name()] = new(networktypes.EndpointSettings)
  424. return nil
  425. }
  426. func (daemon *Daemon) updateEndpointNetworkSettings(container *container.Container, n libnetwork.Network, ep libnetwork.Endpoint) error {
  427. if err := container.BuildEndpointInfo(n, ep); err != nil {
  428. return err
  429. }
  430. if container.HostConfig.NetworkMode == containertypes.NetworkMode("bridge") {
  431. container.NetworkSettings.Bridge = daemon.configStore.Bridge.Iface
  432. }
  433. return nil
  434. }
  435. // UpdateNetwork is used to update the container's network (e.g. when linked containers
  436. // get removed/unlinked).
  437. func (daemon *Daemon) updateNetwork(container *container.Container) error {
  438. ctrl := daemon.netController
  439. sid := container.NetworkSettings.SandboxID
  440. sb, err := ctrl.SandboxByID(sid)
  441. if err != nil {
  442. return derr.ErrorCodeNoSandbox.WithArgs(sid, err)
  443. }
  444. // Find if container is connected to the default bridge network
  445. var n libnetwork.Network
  446. for name := range container.NetworkSettings.Networks {
  447. sn, err := daemon.FindNetwork(name)
  448. if err != nil {
  449. continue
  450. }
  451. if sn.Name() == "bridge" {
  452. n = sn
  453. break
  454. }
  455. }
  456. if n == nil {
  457. // Not connected to the default bridge network; Nothing to do
  458. return nil
  459. }
  460. options, err := daemon.buildSandboxOptions(container, n)
  461. if err != nil {
  462. return derr.ErrorCodeNetworkUpdate.WithArgs(err)
  463. }
  464. if err := sb.Refresh(options...); err != nil {
  465. return derr.ErrorCodeNetworkRefresh.WithArgs(sid, err)
  466. }
  467. return nil
  468. }
  469. // updateContainerNetworkSettings update the network settings
  470. func (daemon *Daemon) updateContainerNetworkSettings(container *container.Container) error {
  471. mode := container.HostConfig.NetworkMode
  472. if container.Config.NetworkDisabled || mode.IsContainer() {
  473. return nil
  474. }
  475. networkName := mode.NetworkName()
  476. if mode.IsDefault() {
  477. networkName = daemon.netController.Config().Daemon.DefaultNetwork
  478. }
  479. if mode.IsUserDefined() {
  480. n, err := daemon.FindNetwork(networkName)
  481. if err != nil {
  482. return err
  483. }
  484. networkName = n.Name()
  485. }
  486. container.NetworkSettings.Networks = make(map[string]*networktypes.EndpointSettings)
  487. container.NetworkSettings.Networks[networkName] = new(networktypes.EndpointSettings)
  488. return nil
  489. }
  490. func (daemon *Daemon) allocateNetwork(container *container.Container) error {
  491. controller := daemon.netController
  492. // Cleanup any stale sandbox left over due to ungraceful daemon shutdown
  493. if err := controller.SandboxDestroy(container.ID); err != nil {
  494. logrus.Errorf("failed to cleanup up stale network sandbox for container %s", container.ID)
  495. }
  496. updateSettings := false
  497. if len(container.NetworkSettings.Networks) == 0 {
  498. if container.Config.NetworkDisabled || container.HostConfig.NetworkMode.IsContainer() {
  499. return nil
  500. }
  501. err := daemon.updateContainerNetworkSettings(container)
  502. if err != nil {
  503. return err
  504. }
  505. updateSettings = true
  506. }
  507. for n := range container.NetworkSettings.Networks {
  508. if err := daemon.connectToNetwork(container, n, updateSettings); err != nil {
  509. return err
  510. }
  511. }
  512. return container.WriteHostConfig()
  513. }
  514. func (daemon *Daemon) getNetworkSandbox(container *container.Container) libnetwork.Sandbox {
  515. var sb libnetwork.Sandbox
  516. daemon.netController.WalkSandboxes(func(s libnetwork.Sandbox) bool {
  517. if s.ContainerID() == container.ID {
  518. sb = s
  519. return true
  520. }
  521. return false
  522. })
  523. return sb
  524. }
  525. // ConnectToNetwork connects a container to a network
  526. func (daemon *Daemon) ConnectToNetwork(container *container.Container, idOrName string) error {
  527. if !container.Running {
  528. return derr.ErrorCodeNotRunning.WithArgs(container.ID)
  529. }
  530. if err := daemon.connectToNetwork(container, idOrName, true); err != nil {
  531. return err
  532. }
  533. if err := container.ToDiskLocking(); err != nil {
  534. return fmt.Errorf("Error saving container to disk: %v", err)
  535. }
  536. return nil
  537. }
  538. func (daemon *Daemon) connectToNetwork(container *container.Container, idOrName string, updateSettings bool) (err error) {
  539. if container.HostConfig.NetworkMode.IsContainer() {
  540. return runconfig.ErrConflictSharedNetwork
  541. }
  542. if containertypes.NetworkMode(idOrName).IsBridge() &&
  543. daemon.configStore.DisableBridge {
  544. container.Config.NetworkDisabled = true
  545. return nil
  546. }
  547. controller := daemon.netController
  548. n, err := daemon.FindNetwork(idOrName)
  549. if err != nil {
  550. return err
  551. }
  552. if updateSettings {
  553. if err := daemon.updateNetworkSettings(container, n); err != nil {
  554. return err
  555. }
  556. }
  557. ep, err := container.GetEndpointInNetwork(n)
  558. if err == nil {
  559. return fmt.Errorf("Conflict. A container with name %q is already connected to network %s.", strings.TrimPrefix(container.Name, "/"), idOrName)
  560. }
  561. if _, ok := err.(libnetwork.ErrNoSuchEndpoint); !ok {
  562. return err
  563. }
  564. createOptions, err := container.BuildCreateEndpointOptions(n)
  565. if err != nil {
  566. return err
  567. }
  568. endpointName := strings.TrimPrefix(container.Name, "/")
  569. ep, err = n.CreateEndpoint(endpointName, createOptions...)
  570. if err != nil {
  571. return err
  572. }
  573. defer func() {
  574. if err != nil {
  575. if e := ep.Delete(); e != nil {
  576. logrus.Warnf("Could not rollback container connection to network %s", idOrName)
  577. }
  578. }
  579. }()
  580. if err := daemon.updateEndpointNetworkSettings(container, n, ep); err != nil {
  581. return err
  582. }
  583. sb := daemon.getNetworkSandbox(container)
  584. if sb == nil {
  585. options, err := daemon.buildSandboxOptions(container, n)
  586. if err != nil {
  587. return err
  588. }
  589. sb, err = controller.NewSandbox(container.ID, options...)
  590. if err != nil {
  591. return err
  592. }
  593. container.UpdateSandboxNetworkSettings(sb)
  594. }
  595. if err := ep.Join(sb); err != nil {
  596. return err
  597. }
  598. if err := container.UpdateJoinInfo(n, ep); err != nil {
  599. return derr.ErrorCodeJoinInfo.WithArgs(err)
  600. }
  601. daemon.LogNetworkEventWithAttributes(n, "connect", map[string]string{"container": container.ID})
  602. return nil
  603. }
  604. // DisconnectFromNetwork disconnects container from network n.
  605. func (daemon *Daemon) DisconnectFromNetwork(container *container.Container, n libnetwork.Network) error {
  606. if !container.Running {
  607. return derr.ErrorCodeNotRunning.WithArgs(container.ID)
  608. }
  609. if container.HostConfig.NetworkMode.IsHost() && containertypes.NetworkMode(n.Type()).IsHost() {
  610. return runconfig.ErrConflictHostNetwork
  611. }
  612. if err := disconnectFromNetwork(container, n); err != nil {
  613. return err
  614. }
  615. if err := container.ToDiskLocking(); err != nil {
  616. return fmt.Errorf("Error saving container to disk: %v", err)
  617. }
  618. attributes := map[string]string{
  619. "container": container.ID,
  620. }
  621. daemon.LogNetworkEventWithAttributes(n, "disconnect", attributes)
  622. return nil
  623. }
  624. func disconnectFromNetwork(container *container.Container, n libnetwork.Network) error {
  625. var (
  626. ep libnetwork.Endpoint
  627. sbox libnetwork.Sandbox
  628. )
  629. s := func(current libnetwork.Endpoint) bool {
  630. epInfo := current.Info()
  631. if epInfo == nil {
  632. return false
  633. }
  634. if sb := epInfo.Sandbox(); sb != nil {
  635. if sb.ContainerID() == container.ID {
  636. ep = current
  637. sbox = sb
  638. return true
  639. }
  640. }
  641. return false
  642. }
  643. n.WalkEndpoints(s)
  644. if ep == nil {
  645. return fmt.Errorf("container %s is not connected to the network", container.ID)
  646. }
  647. if err := ep.Leave(sbox); err != nil {
  648. return fmt.Errorf("container %s failed to leave network %s: %v", container.ID, n.Name(), err)
  649. }
  650. if err := ep.Delete(); err != nil {
  651. return fmt.Errorf("endpoint delete failed for container %s on network %s: %v", container.ID, n.Name(), err)
  652. }
  653. delete(container.NetworkSettings.Networks, n.Name())
  654. return nil
  655. }
  656. func (daemon *Daemon) initializeNetworking(container *container.Container) error {
  657. var err error
  658. if container.HostConfig.NetworkMode.IsContainer() {
  659. // we need to get the hosts files from the container to join
  660. nc, err := daemon.getNetworkedContainer(container.ID, container.HostConfig.NetworkMode.ConnectedContainer())
  661. if err != nil {
  662. return err
  663. }
  664. container.HostnamePath = nc.HostnamePath
  665. container.HostsPath = nc.HostsPath
  666. container.ResolvConfPath = nc.ResolvConfPath
  667. container.Config.Hostname = nc.Config.Hostname
  668. container.Config.Domainname = nc.Config.Domainname
  669. return nil
  670. }
  671. if container.HostConfig.NetworkMode.IsHost() {
  672. container.Config.Hostname, err = os.Hostname()
  673. if err != nil {
  674. return err
  675. }
  676. parts := strings.SplitN(container.Config.Hostname, ".", 2)
  677. if len(parts) > 1 {
  678. container.Config.Hostname = parts[0]
  679. container.Config.Domainname = parts[1]
  680. }
  681. }
  682. if err := daemon.allocateNetwork(container); err != nil {
  683. return err
  684. }
  685. return container.BuildHostnameFile()
  686. }
  687. // called from the libcontainer pre-start hook to set the network
  688. // namespace configuration linkage to the libnetwork "sandbox" entity
  689. func (daemon *Daemon) setNetworkNamespaceKey(containerID string, pid int) error {
  690. path := fmt.Sprintf("/proc/%d/ns/net", pid)
  691. var sandbox libnetwork.Sandbox
  692. search := libnetwork.SandboxContainerWalker(&sandbox, containerID)
  693. daemon.netController.WalkSandboxes(search)
  694. if sandbox == nil {
  695. return derr.ErrorCodeNoSandbox.WithArgs(containerID, "no sandbox found")
  696. }
  697. return sandbox.SetKey(path)
  698. }
  699. func (daemon *Daemon) getIpcContainer(container *container.Container) (*container.Container, error) {
  700. containerID := container.HostConfig.IpcMode.Container()
  701. c, err := daemon.GetContainer(containerID)
  702. if err != nil {
  703. return nil, err
  704. }
  705. if !c.IsRunning() {
  706. return nil, derr.ErrorCodeIPCRunning
  707. }
  708. return c, nil
  709. }
  710. func (daemon *Daemon) getNetworkedContainer(containerID, connectedContainerID string) (*container.Container, error) {
  711. nc, err := daemon.GetContainer(connectedContainerID)
  712. if err != nil {
  713. return nil, err
  714. }
  715. if containerID == nc.ID {
  716. return nil, derr.ErrorCodeJoinSelf
  717. }
  718. if !nc.IsRunning() {
  719. return nil, derr.ErrorCodeJoinRunning.WithArgs(connectedContainerID)
  720. }
  721. return nc, nil
  722. }
  723. func (daemon *Daemon) releaseNetwork(container *container.Container) {
  724. if container.HostConfig.NetworkMode.IsContainer() || container.Config.NetworkDisabled {
  725. return
  726. }
  727. sid := container.NetworkSettings.SandboxID
  728. settings := container.NetworkSettings.Networks
  729. var networks []libnetwork.Network
  730. for n := range settings {
  731. if nw, err := daemon.FindNetwork(n); err == nil {
  732. networks = append(networks, nw)
  733. }
  734. settings[n] = &networktypes.EndpointSettings{}
  735. }
  736. container.NetworkSettings = &network.Settings{Networks: settings}
  737. if sid == "" || len(settings) == 0 {
  738. return
  739. }
  740. sb, err := daemon.netController.SandboxByID(sid)
  741. if err != nil {
  742. logrus.Errorf("error locating sandbox id %s: %v", sid, err)
  743. return
  744. }
  745. if err := sb.Delete(); err != nil {
  746. logrus.Errorf("Error deleting sandbox id %s for container %s: %v", sid, container.ID, err)
  747. }
  748. attributes := map[string]string{
  749. "container": container.ID,
  750. }
  751. for _, nw := range networks {
  752. daemon.LogNetworkEventWithAttributes(nw, "disconnect", attributes)
  753. }
  754. }
  755. func (daemon *Daemon) setupIpcDirs(c *container.Container) error {
  756. rootUID, rootGID := daemon.GetRemappedUIDGID()
  757. if !c.HasMountFor("/dev/shm") {
  758. shmPath, err := c.ShmResourcePath()
  759. if err != nil {
  760. return err
  761. }
  762. if err := idtools.MkdirAllAs(shmPath, 0700, rootUID, rootGID); err != nil {
  763. return err
  764. }
  765. shmSize := container.DefaultSHMSize
  766. if c.HostConfig.ShmSize != nil {
  767. shmSize = *c.HostConfig.ShmSize
  768. }
  769. shmproperty := "mode=1777,size=" + strconv.FormatInt(shmSize, 10)
  770. if err := syscall.Mount("shm", shmPath, "tmpfs", uintptr(syscall.MS_NOEXEC|syscall.MS_NOSUID|syscall.MS_NODEV), label.FormatMountLabel(shmproperty, c.GetMountLabel())); err != nil {
  771. return fmt.Errorf("mounting shm tmpfs: %s", err)
  772. }
  773. if err := os.Chown(shmPath, rootUID, rootGID); err != nil {
  774. return err
  775. }
  776. }
  777. if !c.HasMountFor("/dev/mqueue") {
  778. mqueuePath, err := c.MqueueResourcePath()
  779. if err != nil {
  780. return err
  781. }
  782. if err := idtools.MkdirAllAs(mqueuePath, 0700, rootUID, rootGID); err != nil {
  783. return err
  784. }
  785. if err := syscall.Mount("mqueue", mqueuePath, "mqueue", uintptr(syscall.MS_NOEXEC|syscall.MS_NOSUID|syscall.MS_NODEV), ""); err != nil {
  786. return fmt.Errorf("mounting mqueue mqueue : %s", err)
  787. }
  788. }
  789. return nil
  790. }
  791. func (daemon *Daemon) mountVolumes(container *container.Container) error {
  792. mounts, err := daemon.setupMounts(container)
  793. if err != nil {
  794. return err
  795. }
  796. for _, m := range mounts {
  797. dest, err := container.GetResourcePath(m.Destination)
  798. if err != nil {
  799. return err
  800. }
  801. var stat os.FileInfo
  802. stat, err = os.Stat(m.Source)
  803. if err != nil {
  804. return err
  805. }
  806. if err = fileutils.CreateIfNotExists(dest, stat.IsDir()); err != nil {
  807. return err
  808. }
  809. opts := "rbind,ro"
  810. if m.Writable {
  811. opts = "rbind,rw"
  812. }
  813. if err := mount.Mount(m.Source, dest, "bind", opts); err != nil {
  814. return err
  815. }
  816. }
  817. return nil
  818. }
  819. func killProcessDirectly(container *container.Container) error {
  820. if _, err := container.WaitStop(10 * time.Second); err != nil {
  821. // Ensure that we don't kill ourselves
  822. if pid := container.GetPID(); pid != 0 {
  823. logrus.Infof("Container %s failed to exit within 10 seconds of kill - trying direct SIGKILL", stringid.TruncateID(container.ID))
  824. if err := syscall.Kill(pid, 9); err != nil {
  825. if err != syscall.ESRCH {
  826. return err
  827. }
  828. logrus.Debugf("Cannot kill process (pid=%d) with signal 9: no such process.", pid)
  829. }
  830. }
  831. }
  832. return nil
  833. }
  834. func getDevicesFromPath(deviceMapping containertypes.DeviceMapping) (devs []*configs.Device, err error) {
  835. device, err := devices.DeviceFromPath(deviceMapping.PathOnHost, deviceMapping.CgroupPermissions)
  836. // if there was no error, return the device
  837. if err == nil {
  838. device.Path = deviceMapping.PathInContainer
  839. return append(devs, device), nil
  840. }
  841. // if the device is not a device node
  842. // try to see if it's a directory holding many devices
  843. if err == devices.ErrNotADevice {
  844. // check if it is a directory
  845. if src, e := os.Stat(deviceMapping.PathOnHost); e == nil && src.IsDir() {
  846. // mount the internal devices recursively
  847. filepath.Walk(deviceMapping.PathOnHost, func(dpath string, f os.FileInfo, e error) error {
  848. childDevice, e := devices.DeviceFromPath(dpath, deviceMapping.CgroupPermissions)
  849. if e != nil {
  850. // ignore the device
  851. return nil
  852. }
  853. // add the device to userSpecified devices
  854. childDevice.Path = strings.Replace(dpath, deviceMapping.PathOnHost, deviceMapping.PathInContainer, 1)
  855. devs = append(devs, childDevice)
  856. return nil
  857. })
  858. }
  859. }
  860. if len(devs) > 0 {
  861. return devs, nil
  862. }
  863. return devs, derr.ErrorCodeDeviceInfo.WithArgs(deviceMapping.PathOnHost, err)
  864. }
  865. func mergeDevices(defaultDevices, userDevices []*configs.Device) []*configs.Device {
  866. if len(userDevices) == 0 {
  867. return defaultDevices
  868. }
  869. paths := map[string]*configs.Device{}
  870. for _, d := range userDevices {
  871. paths[d.Path] = d
  872. }
  873. var devs []*configs.Device
  874. for _, d := range defaultDevices {
  875. if _, defined := paths[d.Path]; !defined {
  876. devs = append(devs, d)
  877. }
  878. }
  879. return append(devs, userDevices...)
  880. }
  881. func detachMounted(path string) error {
  882. return syscall.Unmount(path, syscall.MNT_DETACH)
  883. }
  884. func isLinkable(child *container.Container) bool {
  885. // A container is linkable only if it belongs to the default network
  886. _, ok := child.NetworkSettings.Networks["bridge"]
  887. return ok
  888. }