container_operations_unix.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197
  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. ep, err := container.GetEndpointInNetwork(n)
  670. if err == nil {
  671. return fmt.Errorf("Conflict. A container with name %q is already connected to network %s.", strings.TrimPrefix(container.Name, "/"), idOrName)
  672. }
  673. if _, ok := err.(libnetwork.ErrNoSuchEndpoint); !ok {
  674. return err
  675. }
  676. createOptions, err := container.BuildCreateEndpointOptions(n)
  677. if err != nil {
  678. return err
  679. }
  680. endpointName := strings.TrimPrefix(container.Name, "/")
  681. ep, err = n.CreateEndpoint(endpointName, createOptions...)
  682. if err != nil {
  683. return err
  684. }
  685. defer func() {
  686. if err != nil {
  687. if e := ep.Delete(false); e != nil {
  688. logrus.Warnf("Could not rollback container connection to network %s", idOrName)
  689. }
  690. }
  691. }()
  692. if err := daemon.updateEndpointNetworkSettings(container, n, ep); err != nil {
  693. return err
  694. }
  695. sb := daemon.getNetworkSandbox(container)
  696. if sb == nil {
  697. options, err := daemon.buildSandboxOptions(container, n)
  698. if err != nil {
  699. return err
  700. }
  701. sb, err = controller.NewSandbox(container.ID, options...)
  702. if err != nil {
  703. return err
  704. }
  705. container.UpdateSandboxNetworkSettings(sb)
  706. }
  707. joinOptions, err := container.BuildJoinOptions(n)
  708. if err != nil {
  709. return err
  710. }
  711. if err := ep.Join(sb, joinOptions...); err != nil {
  712. return err
  713. }
  714. if err := container.UpdateJoinInfo(n, ep); err != nil {
  715. return derr.ErrorCodeJoinInfo.WithArgs(err)
  716. }
  717. daemon.LogNetworkEventWithAttributes(n, "connect", map[string]string{"container": container.ID})
  718. return nil
  719. }
  720. // ForceEndpointDelete deletes an endpoing from a network forcefully
  721. func (daemon *Daemon) ForceEndpointDelete(name string, n libnetwork.Network) error {
  722. ep, err := n.EndpointByName(name)
  723. if err != nil {
  724. return err
  725. }
  726. return ep.Delete(true)
  727. }
  728. // DisconnectFromNetwork disconnects container from network n.
  729. func (daemon *Daemon) DisconnectFromNetwork(container *container.Container, n libnetwork.Network, force bool) error {
  730. if container.HostConfig.NetworkMode.IsHost() && containertypes.NetworkMode(n.Type()).IsHost() {
  731. return runconfig.ErrConflictHostNetwork
  732. }
  733. if !container.Running {
  734. if container.RemovalInProgress || container.Dead {
  735. return derr.ErrorCodeRemovalContainer.WithArgs(container.ID)
  736. }
  737. if _, ok := container.NetworkSettings.Networks[n.Name()]; ok {
  738. delete(container.NetworkSettings.Networks, n.Name())
  739. } else {
  740. return fmt.Errorf("container %s is not connected to the network %s", container.ID, n.Name())
  741. }
  742. } else {
  743. if err := disconnectFromNetwork(container, n, false); err != nil {
  744. return err
  745. }
  746. }
  747. if err := container.ToDiskLocking(); err != nil {
  748. return fmt.Errorf("Error saving container to disk: %v", err)
  749. }
  750. attributes := map[string]string{
  751. "container": container.ID,
  752. }
  753. daemon.LogNetworkEventWithAttributes(n, "disconnect", attributes)
  754. return nil
  755. }
  756. func disconnectFromNetwork(container *container.Container, n libnetwork.Network, force bool) error {
  757. var (
  758. ep libnetwork.Endpoint
  759. sbox libnetwork.Sandbox
  760. )
  761. s := func(current libnetwork.Endpoint) bool {
  762. epInfo := current.Info()
  763. if epInfo == nil {
  764. return false
  765. }
  766. if sb := epInfo.Sandbox(); sb != nil {
  767. if sb.ContainerID() == container.ID {
  768. ep = current
  769. sbox = sb
  770. return true
  771. }
  772. }
  773. return false
  774. }
  775. n.WalkEndpoints(s)
  776. if ep == nil && force {
  777. epName := strings.TrimPrefix(container.Name, "/")
  778. ep, err := n.EndpointByName(epName)
  779. if err != nil {
  780. return err
  781. }
  782. return ep.Delete(force)
  783. }
  784. if ep == nil {
  785. return fmt.Errorf("container %s is not connected to the network", container.ID)
  786. }
  787. if err := ep.Leave(sbox); err != nil {
  788. return fmt.Errorf("container %s failed to leave network %s: %v", container.ID, n.Name(), err)
  789. }
  790. if err := ep.Delete(false); err != nil {
  791. return fmt.Errorf("endpoint delete failed for container %s on network %s: %v", container.ID, n.Name(), err)
  792. }
  793. delete(container.NetworkSettings.Networks, n.Name())
  794. return nil
  795. }
  796. func (daemon *Daemon) initializeNetworking(container *container.Container) error {
  797. var err error
  798. if container.HostConfig.NetworkMode.IsContainer() {
  799. // we need to get the hosts files from the container to join
  800. nc, err := daemon.getNetworkedContainer(container.ID, container.HostConfig.NetworkMode.ConnectedContainer())
  801. if err != nil {
  802. return err
  803. }
  804. container.HostnamePath = nc.HostnamePath
  805. container.HostsPath = nc.HostsPath
  806. container.ResolvConfPath = nc.ResolvConfPath
  807. container.Config.Hostname = nc.Config.Hostname
  808. container.Config.Domainname = nc.Config.Domainname
  809. return nil
  810. }
  811. if container.HostConfig.NetworkMode.IsHost() {
  812. container.Config.Hostname, err = os.Hostname()
  813. if err != nil {
  814. return err
  815. }
  816. parts := strings.SplitN(container.Config.Hostname, ".", 2)
  817. if len(parts) > 1 {
  818. container.Config.Hostname = parts[0]
  819. container.Config.Domainname = parts[1]
  820. }
  821. }
  822. if err := daemon.allocateNetwork(container); err != nil {
  823. return err
  824. }
  825. return container.BuildHostnameFile()
  826. }
  827. // called from the libcontainer pre-start hook to set the network
  828. // namespace configuration linkage to the libnetwork "sandbox" entity
  829. func (daemon *Daemon) setNetworkNamespaceKey(containerID string, pid int) error {
  830. path := fmt.Sprintf("/proc/%d/ns/net", pid)
  831. var sandbox libnetwork.Sandbox
  832. search := libnetwork.SandboxContainerWalker(&sandbox, containerID)
  833. daemon.netController.WalkSandboxes(search)
  834. if sandbox == nil {
  835. return derr.ErrorCodeNoSandbox.WithArgs(containerID, "no sandbox found")
  836. }
  837. return sandbox.SetKey(path)
  838. }
  839. func (daemon *Daemon) getIpcContainer(container *container.Container) (*container.Container, error) {
  840. containerID := container.HostConfig.IpcMode.Container()
  841. c, err := daemon.GetContainer(containerID)
  842. if err != nil {
  843. return nil, err
  844. }
  845. if !c.IsRunning() {
  846. return nil, derr.ErrorCodeIPCRunning.WithArgs(containerID)
  847. }
  848. return c, nil
  849. }
  850. func (daemon *Daemon) getNetworkedContainer(containerID, connectedContainerID string) (*container.Container, error) {
  851. nc, err := daemon.GetContainer(connectedContainerID)
  852. if err != nil {
  853. return nil, err
  854. }
  855. if containerID == nc.ID {
  856. return nil, derr.ErrorCodeJoinSelf
  857. }
  858. if !nc.IsRunning() {
  859. return nil, derr.ErrorCodeJoinRunning.WithArgs(connectedContainerID)
  860. }
  861. return nc, nil
  862. }
  863. func (daemon *Daemon) releaseNetwork(container *container.Container) {
  864. if container.HostConfig.NetworkMode.IsContainer() || container.Config.NetworkDisabled {
  865. return
  866. }
  867. sid := container.NetworkSettings.SandboxID
  868. settings := container.NetworkSettings.Networks
  869. if sid == "" || len(settings) == 0 {
  870. return
  871. }
  872. var networks []libnetwork.Network
  873. for n, epSettings := range settings {
  874. if nw, err := daemon.FindNetwork(n); err == nil {
  875. networks = append(networks, nw)
  876. }
  877. cleanOperationalData(epSettings)
  878. }
  879. sb, err := daemon.netController.SandboxByID(sid)
  880. if err != nil {
  881. logrus.Errorf("error locating sandbox id %s: %v", sid, err)
  882. return
  883. }
  884. if err := sb.Delete(); err != nil {
  885. logrus.Errorf("Error deleting sandbox id %s for container %s: %v", sid, container.ID, err)
  886. }
  887. attributes := map[string]string{
  888. "container": container.ID,
  889. }
  890. for _, nw := range networks {
  891. daemon.LogNetworkEventWithAttributes(nw, "disconnect", attributes)
  892. }
  893. }
  894. func (daemon *Daemon) setupIpcDirs(c *container.Container) error {
  895. rootUID, rootGID := daemon.GetRemappedUIDGID()
  896. if !c.HasMountFor("/dev/shm") {
  897. shmPath, err := c.ShmResourcePath()
  898. if err != nil {
  899. return err
  900. }
  901. if err := idtools.MkdirAllAs(shmPath, 0700, rootUID, rootGID); err != nil {
  902. return err
  903. }
  904. shmSize := container.DefaultSHMSize
  905. if c.HostConfig.ShmSize != 0 {
  906. shmSize = c.HostConfig.ShmSize
  907. }
  908. shmproperty := "mode=1777,size=" + strconv.FormatInt(shmSize, 10)
  909. if err := syscall.Mount("shm", shmPath, "tmpfs", uintptr(syscall.MS_NOEXEC|syscall.MS_NOSUID|syscall.MS_NODEV), label.FormatMountLabel(shmproperty, c.GetMountLabel())); err != nil {
  910. return fmt.Errorf("mounting shm tmpfs: %s", err)
  911. }
  912. if err := os.Chown(shmPath, rootUID, rootGID); err != nil {
  913. return err
  914. }
  915. }
  916. if !c.HasMountFor("/dev/mqueue") {
  917. mqueuePath, err := c.MqueueResourcePath()
  918. if err != nil {
  919. return err
  920. }
  921. if err := idtools.MkdirAllAs(mqueuePath, 0700, rootUID, rootGID); err != nil {
  922. return err
  923. }
  924. if err := syscall.Mount("mqueue", mqueuePath, "mqueue", uintptr(syscall.MS_NOEXEC|syscall.MS_NOSUID|syscall.MS_NODEV), ""); err != nil {
  925. return fmt.Errorf("mounting mqueue mqueue : %s", err)
  926. }
  927. }
  928. return nil
  929. }
  930. func (daemon *Daemon) mountVolumes(container *container.Container) error {
  931. mounts, err := daemon.setupMounts(container)
  932. if err != nil {
  933. return err
  934. }
  935. for _, m := range mounts {
  936. dest, err := container.GetResourcePath(m.Destination)
  937. if err != nil {
  938. return err
  939. }
  940. var stat os.FileInfo
  941. stat, err = os.Stat(m.Source)
  942. if err != nil {
  943. return err
  944. }
  945. if err = fileutils.CreateIfNotExists(dest, stat.IsDir()); err != nil {
  946. return err
  947. }
  948. opts := "rbind,ro"
  949. if m.Writable {
  950. opts = "rbind,rw"
  951. }
  952. if err := mount.Mount(m.Source, dest, "bind", opts); err != nil {
  953. return err
  954. }
  955. }
  956. return nil
  957. }
  958. func killProcessDirectly(container *container.Container) error {
  959. if _, err := container.WaitStop(10 * time.Second); err != nil {
  960. // Ensure that we don't kill ourselves
  961. if pid := container.GetPID(); pid != 0 {
  962. logrus.Infof("Container %s failed to exit within 10 seconds of kill - trying direct SIGKILL", stringid.TruncateID(container.ID))
  963. if err := syscall.Kill(pid, 9); err != nil {
  964. if err != syscall.ESRCH {
  965. return err
  966. }
  967. logrus.Debugf("Cannot kill process (pid=%d) with signal 9: no such process.", pid)
  968. }
  969. }
  970. }
  971. return nil
  972. }
  973. func getDevicesFromPath(deviceMapping containertypes.DeviceMapping) (devs []*configs.Device, err error) {
  974. device, err := devices.DeviceFromPath(deviceMapping.PathOnHost, deviceMapping.CgroupPermissions)
  975. // if there was no error, return the device
  976. if err == nil {
  977. device.Path = deviceMapping.PathInContainer
  978. return append(devs, device), nil
  979. }
  980. // if the device is not a device node
  981. // try to see if it's a directory holding many devices
  982. if err == devices.ErrNotADevice {
  983. // check if it is a directory
  984. if src, e := os.Stat(deviceMapping.PathOnHost); e == nil && src.IsDir() {
  985. // mount the internal devices recursively
  986. filepath.Walk(deviceMapping.PathOnHost, func(dpath string, f os.FileInfo, e error) error {
  987. childDevice, e := devices.DeviceFromPath(dpath, deviceMapping.CgroupPermissions)
  988. if e != nil {
  989. // ignore the device
  990. return nil
  991. }
  992. // add the device to userSpecified devices
  993. childDevice.Path = strings.Replace(dpath, deviceMapping.PathOnHost, deviceMapping.PathInContainer, 1)
  994. devs = append(devs, childDevice)
  995. return nil
  996. })
  997. }
  998. }
  999. if len(devs) > 0 {
  1000. return devs, nil
  1001. }
  1002. return devs, derr.ErrorCodeDeviceInfo.WithArgs(deviceMapping.PathOnHost, err)
  1003. }
  1004. func mergeDevices(defaultDevices, userDevices []*configs.Device) []*configs.Device {
  1005. if len(userDevices) == 0 {
  1006. return defaultDevices
  1007. }
  1008. paths := map[string]*configs.Device{}
  1009. for _, d := range userDevices {
  1010. paths[d.Path] = d
  1011. }
  1012. var devs []*configs.Device
  1013. for _, d := range defaultDevices {
  1014. if _, defined := paths[d.Path]; !defined {
  1015. devs = append(devs, d)
  1016. }
  1017. }
  1018. return append(devs, userDevices...)
  1019. }
  1020. func detachMounted(path string) error {
  1021. return syscall.Unmount(path, syscall.MNT_DETACH)
  1022. }
  1023. func isLinkable(child *container.Container) bool {
  1024. // A container is linkable only if it belongs to the default network
  1025. _, ok := child.NetworkSettings.Networks["bridge"]
  1026. return ok
  1027. }