container_operations_unix.go 15 KB

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