container_operations_unix.go 28 KB

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