container_operations_unix.go 15 KB

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