container_operations_unix.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. // +build linux freebsd
  2. package daemon // import "github.com/docker/docker/daemon"
  3. import (
  4. "context"
  5. "fmt"
  6. "io/ioutil"
  7. "os"
  8. "path/filepath"
  9. "strconv"
  10. "time"
  11. "github.com/docker/docker/container"
  12. "github.com/docker/docker/daemon/links"
  13. "github.com/docker/docker/errdefs"
  14. "github.com/docker/docker/pkg/idtools"
  15. "github.com/docker/docker/pkg/stringid"
  16. "github.com/docker/docker/pkg/system"
  17. "github.com/docker/docker/runconfig"
  18. "github.com/docker/libnetwork"
  19. "github.com/moby/sys/mount"
  20. "github.com/opencontainers/selinux/go-selinux/label"
  21. "github.com/pkg/errors"
  22. "github.com/sirupsen/logrus"
  23. "golang.org/x/sys/unix"
  24. )
  25. func (daemon *Daemon) setupLinkedContainers(container *container.Container) ([]string, error) {
  26. var env []string
  27. children := daemon.children(container)
  28. bridgeSettings := container.NetworkSettings.Networks[runconfig.DefaultDaemonNetworkMode().NetworkName()]
  29. if bridgeSettings == nil || bridgeSettings.EndpointSettings == nil {
  30. return nil, nil
  31. }
  32. for linkAlias, child := range children {
  33. if !child.IsRunning() {
  34. return nil, fmt.Errorf("Cannot link to a non running container: %s AS %s", child.Name, linkAlias)
  35. }
  36. childBridgeSettings := child.NetworkSettings.Networks[runconfig.DefaultDaemonNetworkMode().NetworkName()]
  37. if childBridgeSettings == nil || childBridgeSettings.EndpointSettings == nil {
  38. return nil, fmt.Errorf("container %s not attached to default bridge network", child.ID)
  39. }
  40. link := links.NewLink(
  41. bridgeSettings.IPAddress,
  42. childBridgeSettings.IPAddress,
  43. linkAlias,
  44. child.Config.Env,
  45. child.Config.ExposedPorts,
  46. )
  47. env = append(env, link.ToEnv()...)
  48. }
  49. return env, nil
  50. }
  51. func (daemon *Daemon) getIpcContainer(id string) (*container.Container, error) {
  52. errMsg := "can't join IPC of container " + id
  53. // Check the container exists
  54. ctr, err := daemon.GetContainer(id)
  55. if err != nil {
  56. return nil, errors.Wrap(err, errMsg)
  57. }
  58. // Check the container is running and not restarting
  59. if err := daemon.checkContainer(ctr, containerIsRunning, containerIsNotRestarting); err != nil {
  60. return nil, errors.Wrap(err, errMsg)
  61. }
  62. // Check the container ipc is shareable
  63. if st, err := os.Stat(ctr.ShmPath); err != nil || !st.IsDir() {
  64. if err == nil || os.IsNotExist(err) {
  65. return nil, errors.New(errMsg + ": non-shareable IPC (hint: use IpcMode:shareable for the donor container)")
  66. }
  67. // stat() failed?
  68. return nil, errors.Wrap(err, errMsg+": unexpected error from stat "+ctr.ShmPath)
  69. }
  70. return ctr, nil
  71. }
  72. func (daemon *Daemon) getPidContainer(ctr *container.Container) (*container.Container, error) {
  73. containerID := ctr.HostConfig.PidMode.Container()
  74. ctr, err := daemon.GetContainer(containerID)
  75. if err != nil {
  76. return nil, errors.Wrapf(err, "cannot join PID of a non running container: %s", containerID)
  77. }
  78. return ctr, daemon.checkContainer(ctr, containerIsRunning, containerIsNotRestarting)
  79. }
  80. func containerIsRunning(c *container.Container) error {
  81. if !c.IsRunning() {
  82. return errdefs.Conflict(errors.Errorf("container %s is not running", c.ID))
  83. }
  84. return nil
  85. }
  86. func containerIsNotRestarting(c *container.Container) error {
  87. if c.IsRestarting() {
  88. return errContainerIsRestarting(c.ID)
  89. }
  90. return nil
  91. }
  92. func (daemon *Daemon) setupIpcDirs(c *container.Container) error {
  93. ipcMode := c.HostConfig.IpcMode
  94. switch {
  95. case ipcMode.IsContainer():
  96. ic, err := daemon.getIpcContainer(ipcMode.Container())
  97. if err != nil {
  98. return err
  99. }
  100. c.ShmPath = ic.ShmPath
  101. case ipcMode.IsHost():
  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. c.ShmPath = "/dev/shm"
  106. case ipcMode.IsPrivate(), ipcMode.IsNone():
  107. // c.ShmPath will/should not be used, so make it empty.
  108. // Container's /dev/shm mount comes from OCI spec.
  109. c.ShmPath = ""
  110. case ipcMode.IsEmpty():
  111. // A container was created by an older version of the daemon.
  112. // The default behavior used to be what is now called "shareable".
  113. fallthrough
  114. case ipcMode.IsShareable():
  115. rootIDs := daemon.idMapping.RootPair()
  116. if !c.HasMountFor("/dev/shm") {
  117. shmPath, err := c.ShmResourcePath()
  118. if err != nil {
  119. return err
  120. }
  121. if err := idtools.MkdirAllAndChown(shmPath, 0700, rootIDs); err != nil {
  122. return err
  123. }
  124. shmproperty := "mode=1777,size=" + strconv.FormatInt(c.HostConfig.ShmSize, 10)
  125. if err := unix.Mount("shm", shmPath, "tmpfs", uintptr(unix.MS_NOEXEC|unix.MS_NOSUID|unix.MS_NODEV), label.FormatMountLabel(shmproperty, c.GetMountLabel())); err != nil {
  126. return fmt.Errorf("mounting shm tmpfs: %s", err)
  127. }
  128. if err := os.Chown(shmPath, rootIDs.UID, rootIDs.GID); err != nil {
  129. return err
  130. }
  131. c.ShmPath = shmPath
  132. }
  133. default:
  134. return fmt.Errorf("invalid IPC mode: %v", ipcMode)
  135. }
  136. return nil
  137. }
  138. func (daemon *Daemon) setupSecretDir(c *container.Container) (setupErr error) {
  139. if len(c.SecretReferences) == 0 && len(c.ConfigReferences) == 0 {
  140. return nil
  141. }
  142. if err := daemon.createSecretsDir(c); err != nil {
  143. return err
  144. }
  145. defer func() {
  146. if setupErr != nil {
  147. daemon.cleanupSecretDir(c)
  148. }
  149. }()
  150. if c.DependencyStore == nil {
  151. return fmt.Errorf("secret store is not initialized")
  152. }
  153. // retrieve possible remapped range start for root UID, GID
  154. rootIDs := daemon.idMapping.RootPair()
  155. for _, s := range c.SecretReferences {
  156. // TODO (ehazlett): use type switch when more are supported
  157. if s.File == nil {
  158. logrus.Error("secret target type is not a file target")
  159. continue
  160. }
  161. // secrets are created in the SecretMountPath on the host, at a
  162. // single level
  163. fPath, err := c.SecretFilePath(*s)
  164. if err != nil {
  165. return errors.Wrap(err, "error getting secret file path")
  166. }
  167. if err := idtools.MkdirAllAndChown(filepath.Dir(fPath), 0700, rootIDs); err != nil {
  168. return errors.Wrap(err, "error creating secret mount path")
  169. }
  170. logrus.WithFields(logrus.Fields{
  171. "name": s.File.Name,
  172. "path": fPath,
  173. }).Debug("injecting secret")
  174. secret, err := c.DependencyStore.Secrets().Get(s.SecretID)
  175. if err != nil {
  176. return errors.Wrap(err, "unable to get secret from secret store")
  177. }
  178. if err := ioutil.WriteFile(fPath, secret.Spec.Data, s.File.Mode); err != nil {
  179. return errors.Wrap(err, "error injecting secret")
  180. }
  181. uid, err := strconv.Atoi(s.File.UID)
  182. if err != nil {
  183. return err
  184. }
  185. gid, err := strconv.Atoi(s.File.GID)
  186. if err != nil {
  187. return err
  188. }
  189. if err := os.Chown(fPath, rootIDs.UID+uid, rootIDs.GID+gid); err != nil {
  190. return errors.Wrap(err, "error setting ownership for secret")
  191. }
  192. if err := os.Chmod(fPath, s.File.Mode); err != nil {
  193. return errors.Wrap(err, "error setting file mode for secret")
  194. }
  195. }
  196. for _, configRef := range c.ConfigReferences {
  197. // TODO (ehazlett): use type switch when more are supported
  198. if configRef.File == nil {
  199. // Runtime configs are not mounted into the container, but they're
  200. // a valid type of config so we should not error when we encounter
  201. // one.
  202. if configRef.Runtime == nil {
  203. logrus.Error("config target type is not a file or runtime target")
  204. }
  205. // However, in any case, this isn't a file config, so we have no
  206. // further work to do
  207. continue
  208. }
  209. fPath, err := c.ConfigFilePath(*configRef)
  210. if err != nil {
  211. return errors.Wrap(err, "error getting config file path for container")
  212. }
  213. if err := idtools.MkdirAllAndChown(filepath.Dir(fPath), 0700, rootIDs); err != nil {
  214. return errors.Wrap(err, "error creating config mount path")
  215. }
  216. logrus.WithFields(logrus.Fields{
  217. "name": configRef.File.Name,
  218. "path": fPath,
  219. }).Debug("injecting config")
  220. config, err := c.DependencyStore.Configs().Get(configRef.ConfigID)
  221. if err != nil {
  222. return errors.Wrap(err, "unable to get config from config store")
  223. }
  224. if err := ioutil.WriteFile(fPath, config.Spec.Data, configRef.File.Mode); err != nil {
  225. return errors.Wrap(err, "error injecting config")
  226. }
  227. uid, err := strconv.Atoi(configRef.File.UID)
  228. if err != nil {
  229. return err
  230. }
  231. gid, err := strconv.Atoi(configRef.File.GID)
  232. if err != nil {
  233. return err
  234. }
  235. if err := os.Chown(fPath, rootIDs.UID+uid, rootIDs.GID+gid); err != nil {
  236. return errors.Wrap(err, "error setting ownership for config")
  237. }
  238. if err := os.Chmod(fPath, configRef.File.Mode); err != nil {
  239. return errors.Wrap(err, "error setting file mode for config")
  240. }
  241. }
  242. return daemon.remountSecretDir(c)
  243. }
  244. // createSecretsDir is used to create a dir suitable for storing container secrets.
  245. // In practice this is using a tmpfs mount and is used for both "configs" and "secrets"
  246. func (daemon *Daemon) createSecretsDir(c *container.Container) error {
  247. // retrieve possible remapped range start for root UID, GID
  248. rootIDs := daemon.idMapping.RootPair()
  249. dir, err := c.SecretMountPath()
  250. if err != nil {
  251. return errors.Wrap(err, "error getting container secrets dir")
  252. }
  253. // create tmpfs
  254. if err := idtools.MkdirAllAndChown(dir, 0700, rootIDs); err != nil {
  255. return errors.Wrap(err, "error creating secret local mount path")
  256. }
  257. tmpfsOwnership := fmt.Sprintf("uid=%d,gid=%d", rootIDs.UID, rootIDs.GID)
  258. if err := mount.Mount("tmpfs", dir, "tmpfs", "nodev,nosuid,noexec,"+tmpfsOwnership); err != nil {
  259. return errors.Wrap(err, "unable to setup secret mount")
  260. }
  261. return nil
  262. }
  263. func (daemon *Daemon) remountSecretDir(c *container.Container) error {
  264. dir, err := c.SecretMountPath()
  265. if err != nil {
  266. return errors.Wrap(err, "error getting container secrets path")
  267. }
  268. if err := label.Relabel(dir, c.MountLabel, false); err != nil {
  269. logrus.WithError(err).WithField("dir", dir).Warn("Error while attempting to set selinux label")
  270. }
  271. rootIDs := daemon.idMapping.RootPair()
  272. tmpfsOwnership := fmt.Sprintf("uid=%d,gid=%d", rootIDs.UID, rootIDs.GID)
  273. // remount secrets ro
  274. if err := mount.Mount("tmpfs", dir, "tmpfs", "remount,ro,"+tmpfsOwnership); err != nil {
  275. return errors.Wrap(err, "unable to remount dir as readonly")
  276. }
  277. return nil
  278. }
  279. func (daemon *Daemon) cleanupSecretDir(c *container.Container) {
  280. dir, err := c.SecretMountPath()
  281. if err != nil {
  282. logrus.WithError(err).WithField("container", c.ID).Warn("error getting secrets mount path for container")
  283. }
  284. if err := mount.RecursiveUnmount(dir); err != nil {
  285. logrus.WithField("dir", dir).WithError(err).Warn("Error while attempting to unmount dir, this may prevent removal of container.")
  286. }
  287. if err := os.RemoveAll(dir); err != nil && !os.IsNotExist(err) {
  288. logrus.WithField("dir", dir).WithError(err).Error("Error removing dir.")
  289. }
  290. }
  291. func killProcessDirectly(cntr *container.Container) error {
  292. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  293. defer cancel()
  294. // Block until the container to stops or timeout.
  295. status := <-cntr.Wait(ctx, container.WaitConditionNotRunning)
  296. if status.Err() != nil {
  297. // Ensure that we don't kill ourselves
  298. if pid := cntr.GetPID(); pid != 0 {
  299. logrus.Infof("Container %s failed to exit within 10 seconds of kill - trying direct SIGKILL", stringid.TruncateID(cntr.ID))
  300. if err := unix.Kill(pid, 9); err != nil {
  301. if err != unix.ESRCH {
  302. return err
  303. }
  304. e := errNoSuchProcess{pid, 9}
  305. logrus.Debug(e)
  306. return e
  307. }
  308. // In case there were some exceptions(e.g., state of zombie and D)
  309. if system.IsProcessAlive(pid) {
  310. // Since we can not kill a zombie pid, add zombie check here
  311. isZombie, err := system.IsProcessZombie(pid)
  312. if err != nil {
  313. logrus.Warnf("Container %s state is invalid", stringid.TruncateID(cntr.ID))
  314. return err
  315. }
  316. if isZombie {
  317. return errdefs.System(errors.Errorf("container %s PID %d is zombie and can not be killed. Use the --init option when creating containers to run an init inside the container that forwards signals and reaps processes", stringid.TruncateID(cntr.ID), pid))
  318. }
  319. }
  320. }
  321. }
  322. return nil
  323. }
  324. func isLinkable(child *container.Container) bool {
  325. // A container is linkable only if it belongs to the default network
  326. _, ok := child.NetworkSettings.Networks[runconfig.DefaultDaemonNetworkMode().NetworkName()]
  327. return ok
  328. }
  329. func enableIPOnPredefinedNetwork() bool {
  330. return false
  331. }
  332. // serviceDiscoveryOnDefaultNetwork indicates if service discovery is supported on the default network
  333. func serviceDiscoveryOnDefaultNetwork() bool {
  334. return false
  335. }
  336. func (daemon *Daemon) setupPathsAndSandboxOptions(container *container.Container, sboxOptions *[]libnetwork.SandboxOption) error {
  337. var err error
  338. // Set the correct paths for /etc/hosts and /etc/resolv.conf, based on the
  339. // networking-mode of the container. Note that containers with "container"
  340. // networking are already handled in "initializeNetworking()" before we reach
  341. // this function, so do not have to be accounted for here.
  342. switch {
  343. case container.HostConfig.NetworkMode.IsHost():
  344. // In host-mode networking, the container does not have its own networking
  345. // namespace, so both `/etc/hosts` and `/etc/resolv.conf` should be the same
  346. // as on the host itself. The container gets a copy of these files.
  347. *sboxOptions = append(
  348. *sboxOptions,
  349. libnetwork.OptionOriginHostsPath("/etc/hosts"),
  350. libnetwork.OptionOriginResolvConfPath("/etc/resolv.conf"),
  351. )
  352. case container.HostConfig.NetworkMode.IsUserDefined():
  353. // The container uses a user-defined network. We use the embedded DNS
  354. // server for container name resolution and to act as a DNS forwarder
  355. // for external DNS resolution.
  356. // We parse the DNS server(s) that are defined in /etc/resolv.conf on
  357. // the host, which may be a local DNS server (for example, if DNSMasq or
  358. // systemd-resolvd are in use). The embedded DNS server forwards DNS
  359. // resolution to the DNS server configured on the host, which in itself
  360. // may act as a forwarder for external DNS servers.
  361. // If systemd-resolvd is used, the "upstream" DNS servers can be found in
  362. // /run/systemd/resolve/resolv.conf. We do not query those DNS servers
  363. // directly, as they can be dynamically reconfigured.
  364. *sboxOptions = append(
  365. *sboxOptions,
  366. libnetwork.OptionOriginResolvConfPath("/etc/resolv.conf"),
  367. )
  368. default:
  369. // For other situations, such as the default bridge network, container
  370. // discovery / name resolution is handled through /etc/hosts, and no
  371. // embedded DNS server is available. Without the embedded DNS, we
  372. // cannot use local DNS servers on the host (for example, if DNSMasq or
  373. // systemd-resolvd is used). If systemd-resolvd is used, we try to
  374. // determine the external DNS servers that are used on the host.
  375. // This situation is not ideal, because DNS servers configured in the
  376. // container are not updated after the container is created, but the
  377. // DNS servers on the host can be dynamically updated.
  378. //
  379. // Copy the host's resolv.conf for the container (/run/systemd/resolve/resolv.conf or /etc/resolv.conf)
  380. *sboxOptions = append(
  381. *sboxOptions,
  382. libnetwork.OptionOriginResolvConfPath(daemon.configStore.GetResolvConf()),
  383. )
  384. }
  385. container.HostsPath, err = container.GetRootResourcePath("hosts")
  386. if err != nil {
  387. return err
  388. }
  389. *sboxOptions = append(*sboxOptions, libnetwork.OptionHostsPath(container.HostsPath))
  390. container.ResolvConfPath, err = container.GetRootResourcePath("resolv.conf")
  391. if err != nil {
  392. return err
  393. }
  394. *sboxOptions = append(*sboxOptions, libnetwork.OptionResolvConfPath(container.ResolvConfPath))
  395. return nil
  396. }
  397. func (daemon *Daemon) initializeNetworkingPaths(container *container.Container, nc *container.Container) error {
  398. container.HostnamePath = nc.HostnamePath
  399. container.HostsPath = nc.HostsPath
  400. container.ResolvConfPath = nc.ResolvConfPath
  401. return nil
  402. }
  403. func (daemon *Daemon) setupContainerMountsRoot(c *container.Container) error {
  404. // get the root mount path so we can make it unbindable
  405. p, err := c.MountsResourcePath("")
  406. if err != nil {
  407. return err
  408. }
  409. return idtools.MkdirAllAndChown(p, 0700, daemon.idMapping.RootPair())
  410. }