container_operations_unix.go 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174
  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. "github.com/docker/docker/container"
  14. "github.com/docker/docker/daemon/execdriver"
  15. "github.com/docker/docker/daemon/links"
  16. "github.com/docker/docker/daemon/network"
  17. derr "github.com/docker/docker/errors"
  18. "github.com/docker/docker/pkg/fileutils"
  19. "github.com/docker/docker/pkg/idtools"
  20. "github.com/docker/docker/pkg/mount"
  21. "github.com/docker/docker/pkg/stringid"
  22. "github.com/docker/docker/runconfig"
  23. containertypes "github.com/docker/engine-api/types/container"
  24. networktypes "github.com/docker/engine-api/types/network"
  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 := daemon.children(container)
  36. bridgeSettings := container.NetworkSettings.Networks["bridge"]
  37. if bridgeSettings == nil {
  38. return nil, nil
  39. }
  40. for linkAlias, child := range children {
  41. if !child.IsRunning() {
  42. return nil, derr.ErrorCodeLinkNotRunning.WithArgs(child.Name, linkAlias)
  43. }
  44. childBridgeSettings := child.NetworkSettings.Networks["bridge"]
  45. if childBridgeSettings == nil {
  46. return nil, fmt.Errorf("container %s not attached to default bridge network", child.ID)
  47. }
  48. link := links.NewLink(
  49. bridgeSettings.IPAddress,
  50. childBridgeSettings.IPAddress,
  51. linkAlias,
  52. child.Config.Env,
  53. child.Config.ExposedPorts,
  54. )
  55. for _, envVar := range link.ToEnv() {
  56. env = append(env, envVar)
  57. }
  58. }
  59. return env, nil
  60. }
  61. func (daemon *Daemon) populateCommand(c *container.Container, env []string) error {
  62. var en *execdriver.Network
  63. if !c.Config.NetworkDisabled {
  64. en = &execdriver.Network{}
  65. if !daemon.execDriver.SupportsHooks() || c.HostConfig.NetworkMode.IsHost() {
  66. en.NamespacePath = c.NetworkSettings.SandboxKey
  67. }
  68. if c.HostConfig.NetworkMode.IsContainer() {
  69. nc, err := daemon.getNetworkedContainer(c.ID, c.HostConfig.NetworkMode.ConnectedContainer())
  70. if err != nil {
  71. return err
  72. }
  73. en.ContainerID = nc.ID
  74. }
  75. }
  76. ipc := &execdriver.Ipc{}
  77. var err error
  78. c.ShmPath, err = c.ShmResourcePath()
  79. if err != nil {
  80. return err
  81. }
  82. if c.HostConfig.IpcMode.IsContainer() {
  83. ic, err := daemon.getIpcContainer(c)
  84. if err != nil {
  85. return err
  86. }
  87. ipc.ContainerID = ic.ID
  88. c.ShmPath = ic.ShmPath
  89. } else {
  90. ipc.HostIpc = c.HostConfig.IpcMode.IsHost()
  91. if ipc.HostIpc {
  92. if _, err := os.Stat("/dev/shm"); err != nil {
  93. return fmt.Errorf("/dev/shm is not mounted, but must be for --ipc=host")
  94. }
  95. c.ShmPath = "/dev/shm"
  96. }
  97. }
  98. pid := &execdriver.Pid{}
  99. pid.HostPid = c.HostConfig.PidMode.IsHost()
  100. uts := &execdriver.UTS{
  101. HostUTS: c.HostConfig.UTSMode.IsHost(),
  102. }
  103. // Build lists of devices allowed and created within the container.
  104. var userSpecifiedDevices []*configs.Device
  105. for _, deviceMapping := range c.HostConfig.Devices {
  106. devs, err := getDevicesFromPath(deviceMapping)
  107. if err != nil {
  108. return err
  109. }
  110. userSpecifiedDevices = append(userSpecifiedDevices, devs...)
  111. }
  112. allowedDevices := mergeDevices(configs.DefaultAllowedDevices, userSpecifiedDevices)
  113. autoCreatedDevices := mergeDevices(configs.DefaultAutoCreatedDevices, userSpecifiedDevices)
  114. var rlimits []*units.Rlimit
  115. ulimits := c.HostConfig.Ulimits
  116. // Merge ulimits with daemon defaults
  117. ulIdx := make(map[string]*units.Ulimit)
  118. for _, ul := range ulimits {
  119. ulIdx[ul.Name] = ul
  120. }
  121. for name, ul := range daemon.configStore.Ulimits {
  122. if _, exists := ulIdx[name]; !exists {
  123. ulimits = append(ulimits, ul)
  124. }
  125. }
  126. weightDevices, err := getBlkioWeightDevices(c.HostConfig)
  127. if err != nil {
  128. return err
  129. }
  130. readBpsDevice, err := getBlkioReadBpsDevices(c.HostConfig)
  131. if err != nil {
  132. return err
  133. }
  134. writeBpsDevice, err := getBlkioWriteBpsDevices(c.HostConfig)
  135. if err != nil {
  136. return err
  137. }
  138. readIOpsDevice, err := getBlkioReadIOpsDevices(c.HostConfig)
  139. if err != nil {
  140. return err
  141. }
  142. writeIOpsDevice, err := getBlkioWriteIOpsDevices(c.HostConfig)
  143. if err != nil {
  144. return err
  145. }
  146. for _, limit := range ulimits {
  147. rl, err := limit.GetRlimit()
  148. if err != nil {
  149. return err
  150. }
  151. rlimits = append(rlimits, rl)
  152. }
  153. resources := &execdriver.Resources{
  154. CommonResources: execdriver.CommonResources{
  155. Memory: c.HostConfig.Memory,
  156. MemoryReservation: c.HostConfig.MemoryReservation,
  157. CPUShares: c.HostConfig.CPUShares,
  158. BlkioWeight: c.HostConfig.BlkioWeight,
  159. },
  160. MemorySwap: c.HostConfig.MemorySwap,
  161. KernelMemory: c.HostConfig.KernelMemory,
  162. CpusetCpus: c.HostConfig.CpusetCpus,
  163. CpusetMems: c.HostConfig.CpusetMems,
  164. CPUPeriod: c.HostConfig.CPUPeriod,
  165. CPUQuota: c.HostConfig.CPUQuota,
  166. Rlimits: rlimits,
  167. BlkioWeightDevice: weightDevices,
  168. BlkioThrottleReadBpsDevice: readBpsDevice,
  169. BlkioThrottleWriteBpsDevice: writeBpsDevice,
  170. BlkioThrottleReadIOpsDevice: readIOpsDevice,
  171. BlkioThrottleWriteIOpsDevice: writeIOpsDevice,
  172. MemorySwappiness: -1,
  173. }
  174. if c.HostConfig.OomKillDisable != nil {
  175. resources.OomKillDisable = *c.HostConfig.OomKillDisable
  176. }
  177. if c.HostConfig.MemorySwappiness != nil {
  178. resources.MemorySwappiness = *c.HostConfig.MemorySwappiness
  179. }
  180. processConfig := execdriver.ProcessConfig{
  181. CommonProcessConfig: execdriver.CommonProcessConfig{
  182. Entrypoint: c.Path,
  183. Arguments: c.Args,
  184. Tty: c.Config.Tty,
  185. },
  186. Privileged: c.HostConfig.Privileged,
  187. User: c.Config.User,
  188. }
  189. processConfig.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
  190. processConfig.Env = env
  191. remappedRoot := &execdriver.User{}
  192. rootUID, rootGID := daemon.GetRemappedUIDGID()
  193. if rootUID != 0 {
  194. remappedRoot.UID = rootUID
  195. remappedRoot.GID = rootGID
  196. }
  197. uidMap, gidMap := daemon.GetUIDGIDMaps()
  198. if !daemon.seccompEnabled {
  199. if c.SeccompProfile != "" && c.SeccompProfile != "unconfined" {
  200. return fmt.Errorf("Seccomp is not enabled in your kernel, cannot run a custom seccomp profile.")
  201. }
  202. logrus.Warn("Seccomp is not enabled in your kernel, running container without default profile.")
  203. c.SeccompProfile = "unconfined"
  204. }
  205. defaultCgroupParent := "/docker"
  206. if daemon.configStore.CgroupParent != "" {
  207. defaultCgroupParent = daemon.configStore.CgroupParent
  208. } else if daemon.usingSystemd() {
  209. defaultCgroupParent = "system.slice"
  210. }
  211. c.Command = &execdriver.Command{
  212. CommonCommand: execdriver.CommonCommand{
  213. ID: c.ID,
  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: defaultCgroupParent,
  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 := daemon.children(container)
  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. for alias, parent := range daemon.parents(container) {
  370. if daemon.configStore.DisableBridge || !container.HostConfig.NetworkMode.IsPrivate() {
  371. continue
  372. }
  373. _, alias = path.Split(alias)
  374. logrus.Debugf("Update /etc/hosts of %s for alias %s with ip %s", parent.ID, alias, bridgeSettings.IPAddress)
  375. sboxOptions = append(sboxOptions, libnetwork.OptionParentUpdate(
  376. parent.ID,
  377. alias,
  378. bridgeSettings.IPAddress,
  379. ))
  380. if ep.ID() != "" {
  381. parentEndpoints = append(parentEndpoints, ep.ID())
  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() && containertypes.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 !containertypes.NetworkMode(sn.Type()).IsPrivate() ||
  410. !containertypes.NetworkMode(n.Type()).IsPrivate() {
  411. return runconfig.ErrConflictSharedNetwork
  412. }
  413. if containertypes.NetworkMode(sn.Name()).IsNone() ||
  414. containertypes.NetworkMode(n.Name()).IsNone() {
  415. return runconfig.ErrConflictNoNetwork
  416. }
  417. }
  418. if _, ok := container.NetworkSettings.Networks[n.Name()]; !ok {
  419. container.NetworkSettings.Networks[n.Name()] = new(networktypes.EndpointSettings)
  420. }
  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.bridgeConfig.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, endpointsConfig map[string]*networktypes.EndpointSettings) error {
  468. var (
  469. n libnetwork.Network
  470. err error
  471. )
  472. mode := container.HostConfig.NetworkMode
  473. if container.Config.NetworkDisabled || mode.IsContainer() {
  474. return nil
  475. }
  476. networkName := mode.NetworkName()
  477. if mode.IsDefault() {
  478. networkName = daemon.netController.Config().Daemon.DefaultNetwork
  479. }
  480. if mode.IsUserDefined() {
  481. n, err = daemon.FindNetwork(networkName)
  482. if err != nil {
  483. return err
  484. }
  485. networkName = n.Name()
  486. }
  487. if container.NetworkSettings == nil {
  488. container.NetworkSettings = &network.Settings{}
  489. }
  490. if len(endpointsConfig) > 0 {
  491. container.NetworkSettings.Networks = endpointsConfig
  492. }
  493. if container.NetworkSettings.Networks == nil {
  494. container.NetworkSettings.Networks = make(map[string]*networktypes.EndpointSettings)
  495. container.NetworkSettings.Networks[networkName] = new(networktypes.EndpointSettings)
  496. }
  497. if !mode.IsUserDefined() {
  498. return nil
  499. }
  500. // Make sure to internally store the per network endpoint config by network name
  501. if _, ok := container.NetworkSettings.Networks[networkName]; ok {
  502. return nil
  503. }
  504. if nwConfig, ok := container.NetworkSettings.Networks[n.ID()]; ok {
  505. container.NetworkSettings.Networks[networkName] = nwConfig
  506. delete(container.NetworkSettings.Networks, n.ID())
  507. return nil
  508. }
  509. return nil
  510. }
  511. func (daemon *Daemon) allocateNetwork(container *container.Container) error {
  512. controller := daemon.netController
  513. // Cleanup any stale sandbox left over due to ungraceful daemon shutdown
  514. if err := controller.SandboxDestroy(container.ID); err != nil {
  515. logrus.Errorf("failed to cleanup up stale network sandbox for container %s", container.ID)
  516. }
  517. updateSettings := false
  518. if len(container.NetworkSettings.Networks) == 0 {
  519. if container.Config.NetworkDisabled || container.HostConfig.NetworkMode.IsContainer() {
  520. return nil
  521. }
  522. err := daemon.updateContainerNetworkSettings(container, nil)
  523. if err != nil {
  524. return err
  525. }
  526. updateSettings = true
  527. }
  528. for n, nConf := range container.NetworkSettings.Networks {
  529. if err := daemon.connectToNetwork(container, n, nConf, updateSettings); err != nil {
  530. return err
  531. }
  532. }
  533. return container.WriteHostConfig()
  534. }
  535. func (daemon *Daemon) getNetworkSandbox(container *container.Container) libnetwork.Sandbox {
  536. var sb libnetwork.Sandbox
  537. daemon.netController.WalkSandboxes(func(s libnetwork.Sandbox) bool {
  538. if s.ContainerID() == container.ID {
  539. sb = s
  540. return true
  541. }
  542. return false
  543. })
  544. return sb
  545. }
  546. // hasUserDefinedIPAddress returns whether the passed endpoint configuration contains IP address configuration
  547. func hasUserDefinedIPAddress(epConfig *networktypes.EndpointSettings) bool {
  548. return epConfig != nil && epConfig.IPAMConfig != nil && (len(epConfig.IPAMConfig.IPv4Address) > 0 || len(epConfig.IPAMConfig.IPv6Address) > 0)
  549. }
  550. // User specified ip address is acceptable only for networks with user specified subnets.
  551. func validateNetworkingConfig(n libnetwork.Network, epConfig *networktypes.EndpointSettings) error {
  552. if n == nil || epConfig == nil {
  553. return nil
  554. }
  555. if !hasUserDefinedIPAddress(epConfig) {
  556. return nil
  557. }
  558. _, _, nwIPv4Configs, nwIPv6Configs := n.Info().IpamConfig()
  559. for _, s := range []struct {
  560. ipConfigured bool
  561. subnetConfigs []*libnetwork.IpamConf
  562. }{
  563. {
  564. ipConfigured: len(epConfig.IPAMConfig.IPv4Address) > 0,
  565. subnetConfigs: nwIPv4Configs,
  566. },
  567. {
  568. ipConfigured: len(epConfig.IPAMConfig.IPv6Address) > 0,
  569. subnetConfigs: nwIPv6Configs,
  570. },
  571. } {
  572. if s.ipConfigured {
  573. foundSubnet := false
  574. for _, cfg := range s.subnetConfigs {
  575. if len(cfg.PreferredPool) > 0 {
  576. foundSubnet = true
  577. break
  578. }
  579. }
  580. if !foundSubnet {
  581. return runconfig.ErrUnsupportedNetworkNoSubnetAndIP
  582. }
  583. }
  584. }
  585. return nil
  586. }
  587. // cleanOperationalData resets the operational data from the passed endpoint settings
  588. func cleanOperationalData(es *networktypes.EndpointSettings) {
  589. es.EndpointID = ""
  590. es.Gateway = ""
  591. es.IPAddress = ""
  592. es.IPPrefixLen = 0
  593. es.IPv6Gateway = ""
  594. es.GlobalIPv6Address = ""
  595. es.GlobalIPv6PrefixLen = 0
  596. es.MacAddress = ""
  597. }
  598. func (daemon *Daemon) updateNetworkConfig(container *container.Container, idOrName string, endpointConfig *networktypes.EndpointSettings, updateSettings bool) (libnetwork.Network, error) {
  599. if container.HostConfig.NetworkMode.IsContainer() {
  600. return nil, runconfig.ErrConflictSharedNetwork
  601. }
  602. if containertypes.NetworkMode(idOrName).IsBridge() &&
  603. daemon.configStore.DisableBridge {
  604. container.Config.NetworkDisabled = true
  605. return nil, nil
  606. }
  607. if !containertypes.NetworkMode(idOrName).IsUserDefined() {
  608. if hasUserDefinedIPAddress(endpointConfig) {
  609. return nil, runconfig.ErrUnsupportedNetworkAndIP
  610. }
  611. if endpointConfig != nil && len(endpointConfig.Aliases) > 0 {
  612. return nil, runconfig.ErrUnsupportedNetworkAndAlias
  613. }
  614. }
  615. n, err := daemon.FindNetwork(idOrName)
  616. if err != nil {
  617. return nil, err
  618. }
  619. if err := validateNetworkingConfig(n, endpointConfig); err != nil {
  620. return nil, err
  621. }
  622. if updateSettings {
  623. if err := daemon.updateNetworkSettings(container, n); err != nil {
  624. return nil, err
  625. }
  626. }
  627. return n, nil
  628. }
  629. // ConnectToNetwork connects a container to a network
  630. func (daemon *Daemon) ConnectToNetwork(container *container.Container, idOrName string, endpointConfig *networktypes.EndpointSettings) error {
  631. if !container.Running {
  632. if container.RemovalInProgress || container.Dead {
  633. return derr.ErrorCodeRemovalContainer.WithArgs(container.ID)
  634. }
  635. if _, err := daemon.updateNetworkConfig(container, idOrName, endpointConfig, true); err != nil {
  636. return err
  637. }
  638. if endpointConfig != nil {
  639. container.NetworkSettings.Networks[idOrName] = endpointConfig
  640. }
  641. } else {
  642. if err := daemon.connectToNetwork(container, idOrName, endpointConfig, true); err != nil {
  643. return err
  644. }
  645. }
  646. if err := container.ToDiskLocking(); err != nil {
  647. return fmt.Errorf("Error saving container to disk: %v", err)
  648. }
  649. return nil
  650. }
  651. func (daemon *Daemon) connectToNetwork(container *container.Container, idOrName string, endpointConfig *networktypes.EndpointSettings, updateSettings bool) (err error) {
  652. n, err := daemon.updateNetworkConfig(container, idOrName, endpointConfig, updateSettings)
  653. if err != nil {
  654. return err
  655. }
  656. if n == nil {
  657. return nil
  658. }
  659. controller := daemon.netController
  660. sb := daemon.getNetworkSandbox(container)
  661. createOptions, err := container.BuildCreateEndpointOptions(n, endpointConfig, sb)
  662. if err != nil {
  663. return err
  664. }
  665. endpointName := strings.TrimPrefix(container.Name, "/")
  666. ep, err := n.CreateEndpoint(endpointName, createOptions...)
  667. if err != nil {
  668. return err
  669. }
  670. defer func() {
  671. if err != nil {
  672. if e := ep.Delete(false); e != nil {
  673. logrus.Warnf("Could not rollback container connection to network %s", idOrName)
  674. }
  675. }
  676. }()
  677. if endpointConfig != nil {
  678. container.NetworkSettings.Networks[n.Name()] = endpointConfig
  679. }
  680. if err := daemon.updateEndpointNetworkSettings(container, n, ep); err != nil {
  681. return err
  682. }
  683. if sb == nil {
  684. options, err := daemon.buildSandboxOptions(container, n)
  685. if err != nil {
  686. return err
  687. }
  688. sb, err = controller.NewSandbox(container.ID, options...)
  689. if err != nil {
  690. return err
  691. }
  692. container.UpdateSandboxNetworkSettings(sb)
  693. }
  694. joinOptions, err := container.BuildJoinOptions(n)
  695. if err != nil {
  696. return err
  697. }
  698. if err := ep.Join(sb, joinOptions...); err != nil {
  699. return err
  700. }
  701. if err := container.UpdateJoinInfo(n, ep); err != nil {
  702. return derr.ErrorCodeJoinInfo.WithArgs(err)
  703. }
  704. daemon.LogNetworkEventWithAttributes(n, "connect", map[string]string{"container": container.ID})
  705. return nil
  706. }
  707. // ForceEndpointDelete deletes an endpoing from a network forcefully
  708. func (daemon *Daemon) ForceEndpointDelete(name string, n libnetwork.Network) error {
  709. ep, err := n.EndpointByName(name)
  710. if err != nil {
  711. return err
  712. }
  713. return ep.Delete(true)
  714. }
  715. // DisconnectFromNetwork disconnects container from network n.
  716. func (daemon *Daemon) DisconnectFromNetwork(container *container.Container, n libnetwork.Network, force bool) error {
  717. if container.HostConfig.NetworkMode.IsHost() && containertypes.NetworkMode(n.Type()).IsHost() {
  718. return runconfig.ErrConflictHostNetwork
  719. }
  720. if !container.Running {
  721. if container.RemovalInProgress || container.Dead {
  722. return derr.ErrorCodeRemovalContainer.WithArgs(container.ID)
  723. }
  724. if _, ok := container.NetworkSettings.Networks[n.Name()]; ok {
  725. delete(container.NetworkSettings.Networks, n.Name())
  726. } else {
  727. return fmt.Errorf("container %s is not connected to the network %s", container.ID, n.Name())
  728. }
  729. } else {
  730. if err := disconnectFromNetwork(container, n, false); err != nil {
  731. return err
  732. }
  733. }
  734. if err := container.ToDiskLocking(); err != nil {
  735. return fmt.Errorf("Error saving container to disk: %v", err)
  736. }
  737. attributes := map[string]string{
  738. "container": container.ID,
  739. }
  740. daemon.LogNetworkEventWithAttributes(n, "disconnect", attributes)
  741. return nil
  742. }
  743. func disconnectFromNetwork(container *container.Container, n libnetwork.Network, force bool) error {
  744. var (
  745. ep libnetwork.Endpoint
  746. sbox libnetwork.Sandbox
  747. )
  748. s := func(current libnetwork.Endpoint) bool {
  749. epInfo := current.Info()
  750. if epInfo == nil {
  751. return false
  752. }
  753. if sb := epInfo.Sandbox(); sb != nil {
  754. if sb.ContainerID() == container.ID {
  755. ep = current
  756. sbox = sb
  757. return true
  758. }
  759. }
  760. return false
  761. }
  762. n.WalkEndpoints(s)
  763. if ep == nil && force {
  764. epName := strings.TrimPrefix(container.Name, "/")
  765. ep, err := n.EndpointByName(epName)
  766. if err != nil {
  767. return err
  768. }
  769. return ep.Delete(force)
  770. }
  771. if ep == nil {
  772. return fmt.Errorf("container %s is not connected to the network", container.ID)
  773. }
  774. if err := ep.Leave(sbox); err != nil {
  775. return fmt.Errorf("container %s failed to leave network %s: %v", container.ID, n.Name(), err)
  776. }
  777. if err := ep.Delete(false); err != nil {
  778. return fmt.Errorf("endpoint delete failed for container %s on network %s: %v", container.ID, n.Name(), err)
  779. }
  780. delete(container.NetworkSettings.Networks, n.Name())
  781. return nil
  782. }
  783. func (daemon *Daemon) initializeNetworking(container *container.Container) error {
  784. var err error
  785. if container.HostConfig.NetworkMode.IsContainer() {
  786. // we need to get the hosts files from the container to join
  787. nc, err := daemon.getNetworkedContainer(container.ID, container.HostConfig.NetworkMode.ConnectedContainer())
  788. if err != nil {
  789. return err
  790. }
  791. container.HostnamePath = nc.HostnamePath
  792. container.HostsPath = nc.HostsPath
  793. container.ResolvConfPath = nc.ResolvConfPath
  794. container.Config.Hostname = nc.Config.Hostname
  795. container.Config.Domainname = nc.Config.Domainname
  796. return nil
  797. }
  798. if container.HostConfig.NetworkMode.IsHost() {
  799. container.Config.Hostname, err = os.Hostname()
  800. if err != nil {
  801. return err
  802. }
  803. parts := strings.SplitN(container.Config.Hostname, ".", 2)
  804. if len(parts) > 1 {
  805. container.Config.Hostname = parts[0]
  806. container.Config.Domainname = parts[1]
  807. }
  808. }
  809. if err := daemon.allocateNetwork(container); err != nil {
  810. return err
  811. }
  812. return container.BuildHostnameFile()
  813. }
  814. // called from the libcontainer pre-start hook to set the network
  815. // namespace configuration linkage to the libnetwork "sandbox" entity
  816. func (daemon *Daemon) setNetworkNamespaceKey(containerID string, pid int) error {
  817. path := fmt.Sprintf("/proc/%d/ns/net", pid)
  818. var sandbox libnetwork.Sandbox
  819. search := libnetwork.SandboxContainerWalker(&sandbox, containerID)
  820. daemon.netController.WalkSandboxes(search)
  821. if sandbox == nil {
  822. return derr.ErrorCodeNoSandbox.WithArgs(containerID, "no sandbox found")
  823. }
  824. return sandbox.SetKey(path)
  825. }
  826. func (daemon *Daemon) getIpcContainer(container *container.Container) (*container.Container, error) {
  827. containerID := container.HostConfig.IpcMode.Container()
  828. c, err := daemon.GetContainer(containerID)
  829. if err != nil {
  830. return nil, err
  831. }
  832. if !c.IsRunning() {
  833. return nil, derr.ErrorCodeIPCRunning.WithArgs(containerID)
  834. }
  835. if c.IsRestarting() {
  836. return nil, derr.ErrorCodeContainerRestarting.WithArgs(containerID)
  837. }
  838. return c, nil
  839. }
  840. func (daemon *Daemon) getNetworkedContainer(containerID, connectedContainerID string) (*container.Container, error) {
  841. nc, err := daemon.GetContainer(connectedContainerID)
  842. if err != nil {
  843. return nil, err
  844. }
  845. if containerID == nc.ID {
  846. return nil, derr.ErrorCodeJoinSelf
  847. }
  848. if !nc.IsRunning() {
  849. return nil, derr.ErrorCodeJoinRunning.WithArgs(connectedContainerID)
  850. }
  851. if nc.IsRestarting() {
  852. return nil, derr.ErrorCodeContainerRestarting.WithArgs(connectedContainerID)
  853. }
  854. return nc, nil
  855. }
  856. func (daemon *Daemon) releaseNetwork(container *container.Container) {
  857. if container.HostConfig.NetworkMode.IsContainer() || container.Config.NetworkDisabled {
  858. return
  859. }
  860. sid := container.NetworkSettings.SandboxID
  861. settings := container.NetworkSettings.Networks
  862. container.NetworkSettings.Ports = nil
  863. if sid == "" || len(settings) == 0 {
  864. return
  865. }
  866. var networks []libnetwork.Network
  867. for n, epSettings := range settings {
  868. if nw, err := daemon.FindNetwork(n); err == nil {
  869. networks = append(networks, nw)
  870. }
  871. cleanOperationalData(epSettings)
  872. }
  873. sb, err := daemon.netController.SandboxByID(sid)
  874. if err != nil {
  875. logrus.Errorf("error locating sandbox id %s: %v", sid, err)
  876. return
  877. }
  878. if err := sb.Delete(); err != nil {
  879. logrus.Errorf("Error deleting sandbox id %s for container %s: %v", sid, container.ID, err)
  880. }
  881. attributes := map[string]string{
  882. "container": container.ID,
  883. }
  884. for _, nw := range networks {
  885. daemon.LogNetworkEventWithAttributes(nw, "disconnect", attributes)
  886. }
  887. }
  888. func (daemon *Daemon) setupIpcDirs(c *container.Container) error {
  889. rootUID, rootGID := daemon.GetRemappedUIDGID()
  890. if !c.HasMountFor("/dev/shm") {
  891. shmPath, err := c.ShmResourcePath()
  892. if err != nil {
  893. return err
  894. }
  895. if err := idtools.MkdirAllAs(shmPath, 0700, rootUID, rootGID); err != nil {
  896. return err
  897. }
  898. shmSize := container.DefaultSHMSize
  899. if c.HostConfig.ShmSize != 0 {
  900. shmSize = c.HostConfig.ShmSize
  901. }
  902. shmproperty := "mode=1777,size=" + strconv.FormatInt(shmSize, 10)
  903. if err := syscall.Mount("shm", shmPath, "tmpfs", uintptr(syscall.MS_NOEXEC|syscall.MS_NOSUID|syscall.MS_NODEV), label.FormatMountLabel(shmproperty, c.GetMountLabel())); err != nil {
  904. return fmt.Errorf("mounting shm tmpfs: %s", err)
  905. }
  906. if err := os.Chown(shmPath, rootUID, rootGID); err != nil {
  907. return err
  908. }
  909. }
  910. return nil
  911. }
  912. func (daemon *Daemon) mountVolumes(container *container.Container) error {
  913. mounts, err := daemon.setupMounts(container)
  914. if err != nil {
  915. return err
  916. }
  917. for _, m := range mounts {
  918. dest, err := container.GetResourcePath(m.Destination)
  919. if err != nil {
  920. return err
  921. }
  922. var stat os.FileInfo
  923. stat, err = os.Stat(m.Source)
  924. if err != nil {
  925. return err
  926. }
  927. if err = fileutils.CreateIfNotExists(dest, stat.IsDir()); err != nil {
  928. return err
  929. }
  930. opts := "rbind,ro"
  931. if m.Writable {
  932. opts = "rbind,rw"
  933. }
  934. if err := mount.Mount(m.Source, dest, "bind", opts); err != nil {
  935. return err
  936. }
  937. }
  938. return nil
  939. }
  940. func killProcessDirectly(container *container.Container) error {
  941. if _, err := container.WaitStop(10 * time.Second); err != nil {
  942. // Ensure that we don't kill ourselves
  943. if pid := container.GetPID(); pid != 0 {
  944. logrus.Infof("Container %s failed to exit within 10 seconds of kill - trying direct SIGKILL", stringid.TruncateID(container.ID))
  945. if err := syscall.Kill(pid, 9); err != nil {
  946. if err != syscall.ESRCH {
  947. return err
  948. }
  949. logrus.Debugf("Cannot kill process (pid=%d) with signal 9: no such process.", pid)
  950. }
  951. }
  952. }
  953. return nil
  954. }
  955. func getDevicesFromPath(deviceMapping containertypes.DeviceMapping) (devs []*configs.Device, err error) {
  956. device, err := devices.DeviceFromPath(deviceMapping.PathOnHost, deviceMapping.CgroupPermissions)
  957. // if there was no error, return the device
  958. if err == nil {
  959. device.Path = deviceMapping.PathInContainer
  960. return append(devs, device), nil
  961. }
  962. // if the device is not a device node
  963. // try to see if it's a directory holding many devices
  964. if err == devices.ErrNotADevice {
  965. // check if it is a directory
  966. if src, e := os.Stat(deviceMapping.PathOnHost); e == nil && src.IsDir() {
  967. // mount the internal devices recursively
  968. filepath.Walk(deviceMapping.PathOnHost, func(dpath string, f os.FileInfo, e error) error {
  969. childDevice, e := devices.DeviceFromPath(dpath, deviceMapping.CgroupPermissions)
  970. if e != nil {
  971. // ignore the device
  972. return nil
  973. }
  974. // add the device to userSpecified devices
  975. childDevice.Path = strings.Replace(dpath, deviceMapping.PathOnHost, deviceMapping.PathInContainer, 1)
  976. devs = append(devs, childDevice)
  977. return nil
  978. })
  979. }
  980. }
  981. if len(devs) > 0 {
  982. return devs, nil
  983. }
  984. return devs, derr.ErrorCodeDeviceInfo.WithArgs(deviceMapping.PathOnHost, err)
  985. }
  986. func mergeDevices(defaultDevices, userDevices []*configs.Device) []*configs.Device {
  987. if len(userDevices) == 0 {
  988. return defaultDevices
  989. }
  990. paths := map[string]*configs.Device{}
  991. for _, d := range userDevices {
  992. paths[d.Path] = d
  993. }
  994. var devs []*configs.Device
  995. for _, d := range defaultDevices {
  996. if _, defined := paths[d.Path]; !defined {
  997. devs = append(devs, d)
  998. }
  999. }
  1000. return append(devs, userDevices...)
  1001. }
  1002. func detachMounted(path string) error {
  1003. return syscall.Unmount(path, syscall.MNT_DETACH)
  1004. }
  1005. func isLinkable(child *container.Container) bool {
  1006. // A container is linkable only if it belongs to the default network
  1007. _, ok := child.NetworkSettings.Networks["bridge"]
  1008. return ok
  1009. }