container_operations_unix.go 28 KB

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