container_operations_unix.go 27 KB

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