container_operations_unix.go 34 KB

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