container_operations_unix.go 33 KB

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