container_operations_unix.go 29 KB

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