container_operations_unix.go 33 KB

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