container_operations_unix.go 33 KB

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