container_operations_unix.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. // +build linux freebsd
  2. package 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/mount"
  16. "github.com/docker/docker/pkg/stringid"
  17. "github.com/docker/docker/runconfig"
  18. "github.com/docker/libnetwork"
  19. "github.com/opencontainers/selinux/go-selinux/label"
  20. "github.com/pkg/errors"
  21. "github.com/sirupsen/logrus"
  22. "golang.org/x/sys/unix"
  23. )
  24. func (daemon *Daemon) setupLinkedContainers(container *container.Container) ([]string, error) {
  25. var env []string
  26. children := daemon.children(container)
  27. bridgeSettings := container.NetworkSettings.Networks[runconfig.DefaultDaemonNetworkMode().NetworkName()]
  28. if bridgeSettings == nil || bridgeSettings.EndpointSettings == nil {
  29. return nil, nil
  30. }
  31. for linkAlias, child := range children {
  32. if !child.IsRunning() {
  33. return nil, fmt.Errorf("Cannot link to a non running container: %s AS %s", child.Name, linkAlias)
  34. }
  35. childBridgeSettings := child.NetworkSettings.Networks[runconfig.DefaultDaemonNetworkMode().NetworkName()]
  36. if childBridgeSettings == nil || childBridgeSettings.EndpointSettings == nil {
  37. return nil, fmt.Errorf("container %s not attached to default bridge network", child.ID)
  38. }
  39. link := links.NewLink(
  40. bridgeSettings.IPAddress,
  41. childBridgeSettings.IPAddress,
  42. linkAlias,
  43. child.Config.Env,
  44. child.Config.ExposedPorts,
  45. )
  46. env = append(env, link.ToEnv()...)
  47. }
  48. return env, nil
  49. }
  50. func (daemon *Daemon) getIpcContainer(id string) (*container.Container, error) {
  51. errMsg := "can't join IPC of container " + id
  52. // Check the container exists
  53. container, err := daemon.GetContainer(id)
  54. if err != nil {
  55. return nil, errors.Wrap(err, errMsg)
  56. }
  57. // Check the container is running and not restarting
  58. if err := daemon.checkContainer(container, containerIsRunning, containerIsNotRestarting); err != nil {
  59. return nil, errors.Wrap(err, errMsg)
  60. }
  61. // Check the container ipc is shareable
  62. if st, err := os.Stat(container.ShmPath); err != nil || !st.IsDir() {
  63. if err == nil || os.IsNotExist(err) {
  64. return nil, errors.New(errMsg + ": non-shareable IPC")
  65. }
  66. // stat() failed?
  67. return nil, errors.Wrap(err, errMsg+": unexpected error from stat "+container.ShmPath)
  68. }
  69. return container, nil
  70. }
  71. func (daemon *Daemon) getPidContainer(container *container.Container) (*container.Container, error) {
  72. containerID := container.HostConfig.PidMode.Container()
  73. container, err := daemon.GetContainer(containerID)
  74. if err != nil {
  75. return nil, errors.Wrapf(err, "cannot join PID of a non running container: %s", containerID)
  76. }
  77. return container, daemon.checkContainer(container, containerIsRunning, containerIsNotRestarting)
  78. }
  79. func containerIsRunning(c *container.Container) error {
  80. if !c.IsRunning() {
  81. return errdefs.Conflict(errors.Errorf("container %s is not running", c.ID))
  82. }
  83. return nil
  84. }
  85. func containerIsNotRestarting(c *container.Container) error {
  86. if c.IsRestarting() {
  87. return errContainerIsRestarting(c.ID)
  88. }
  89. return nil
  90. }
  91. func (daemon *Daemon) setupIpcDirs(c *container.Container) error {
  92. ipcMode := c.HostConfig.IpcMode
  93. switch {
  94. case ipcMode.IsContainer():
  95. ic, err := daemon.getIpcContainer(ipcMode.Container())
  96. if err != nil {
  97. return err
  98. }
  99. c.ShmPath = ic.ShmPath
  100. case ipcMode.IsHost():
  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. c.ShmPath = "/dev/shm"
  105. case ipcMode.IsPrivate(), ipcMode.IsNone():
  106. // c.ShmPath will/should not be used, so make it empty.
  107. // Container's /dev/shm mount comes from OCI spec.
  108. c.ShmPath = ""
  109. case ipcMode.IsEmpty():
  110. // A container was created by an older version of the daemon.
  111. // The default behavior used to be what is now called "shareable".
  112. fallthrough
  113. case ipcMode.IsShareable():
  114. rootIDs := daemon.idMappings.RootPair()
  115. if !c.HasMountFor("/dev/shm") {
  116. shmPath, err := c.ShmResourcePath()
  117. if err != nil {
  118. return err
  119. }
  120. if err := idtools.MkdirAllAndChown(shmPath, 0700, rootIDs); err != nil {
  121. return err
  122. }
  123. shmproperty := "mode=1777,size=" + strconv.FormatInt(c.HostConfig.ShmSize, 10)
  124. if err := unix.Mount("shm", shmPath, "tmpfs", uintptr(unix.MS_NOEXEC|unix.MS_NOSUID|unix.MS_NODEV), label.FormatMountLabel(shmproperty, c.GetMountLabel())); err != nil {
  125. return fmt.Errorf("mounting shm tmpfs: %s", err)
  126. }
  127. if err := os.Chown(shmPath, rootIDs.UID, rootIDs.GID); err != nil {
  128. return err
  129. }
  130. c.ShmPath = shmPath
  131. }
  132. default:
  133. return fmt.Errorf("invalid IPC mode: %v", ipcMode)
  134. }
  135. return nil
  136. }
  137. func (daemon *Daemon) setupSecretDir(c *container.Container) (setupErr error) {
  138. if len(c.SecretReferences) == 0 {
  139. return nil
  140. }
  141. localMountPath, err := c.SecretMountPath()
  142. if err != nil {
  143. return errors.Wrap(err, "error getting secrets mount dir")
  144. }
  145. logrus.Debugf("secrets: setting up secret dir: %s", localMountPath)
  146. // retrieve possible remapped range start for root UID, GID
  147. rootIDs := daemon.idMappings.RootPair()
  148. // create tmpfs
  149. if err := idtools.MkdirAllAndChown(localMountPath, 0700, rootIDs); err != nil {
  150. return errors.Wrap(err, "error creating secret local mount path")
  151. }
  152. defer func() {
  153. if setupErr != nil {
  154. // cleanup
  155. _ = detachMounted(localMountPath)
  156. if err := os.RemoveAll(localMountPath); err != nil {
  157. logrus.Errorf("error cleaning up secret mount: %s", err)
  158. }
  159. }
  160. }()
  161. tmpfsOwnership := fmt.Sprintf("uid=%d,gid=%d", rootIDs.UID, rootIDs.GID)
  162. if err := mount.Mount("tmpfs", localMountPath, "tmpfs", "nodev,nosuid,noexec,"+tmpfsOwnership); err != nil {
  163. return errors.Wrap(err, "unable to setup secret mount")
  164. }
  165. if c.DependencyStore == nil {
  166. return fmt.Errorf("secret store is not initialized")
  167. }
  168. for _, s := range c.SecretReferences {
  169. // TODO (ehazlett): use type switch when more are supported
  170. if s.File == nil {
  171. logrus.Error("secret target type is not a file target")
  172. continue
  173. }
  174. // secrets are created in the SecretMountPath on the host, at a
  175. // single level
  176. fPath, err := c.SecretFilePath(*s)
  177. if err != nil {
  178. return errors.Wrap(err, "error getting secret file path")
  179. }
  180. if err := idtools.MkdirAllAndChown(filepath.Dir(fPath), 0700, rootIDs); err != nil {
  181. return errors.Wrap(err, "error creating secret mount path")
  182. }
  183. logrus.WithFields(logrus.Fields{
  184. "name": s.File.Name,
  185. "path": fPath,
  186. }).Debug("injecting secret")
  187. secret, err := c.DependencyStore.Secrets().Get(s.SecretID)
  188. if err != nil {
  189. return errors.Wrap(err, "unable to get secret from secret store")
  190. }
  191. if err := ioutil.WriteFile(fPath, secret.Spec.Data, s.File.Mode); err != nil {
  192. return errors.Wrap(err, "error injecting secret")
  193. }
  194. uid, err := strconv.Atoi(s.File.UID)
  195. if err != nil {
  196. return err
  197. }
  198. gid, err := strconv.Atoi(s.File.GID)
  199. if err != nil {
  200. return err
  201. }
  202. if err := os.Chown(fPath, rootIDs.UID+uid, rootIDs.GID+gid); err != nil {
  203. return errors.Wrap(err, "error setting ownership for secret")
  204. }
  205. if err := os.Chmod(fPath, s.File.Mode); err != nil {
  206. return errors.Wrap(err, "error setting file mode for secret")
  207. }
  208. }
  209. label.Relabel(localMountPath, c.MountLabel, false)
  210. // remount secrets ro
  211. if err := mount.Mount("tmpfs", localMountPath, "tmpfs", "remount,ro,"+tmpfsOwnership); err != nil {
  212. return errors.Wrap(err, "unable to remount secret dir as readonly")
  213. }
  214. return nil
  215. }
  216. func (daemon *Daemon) setupConfigDir(c *container.Container) (setupErr error) {
  217. if len(c.ConfigReferences) == 0 {
  218. return nil
  219. }
  220. localPath, err := c.ConfigsDirPath()
  221. if err != nil {
  222. return err
  223. }
  224. logrus.Debugf("configs: setting up config dir: %s", localPath)
  225. // retrieve possible remapped range start for root UID, GID
  226. rootIDs := daemon.idMappings.RootPair()
  227. // create tmpfs
  228. if err := idtools.MkdirAllAndChown(localPath, 0700, rootIDs); err != nil {
  229. return errors.Wrap(err, "error creating config dir")
  230. }
  231. defer func() {
  232. if setupErr != nil {
  233. if err := os.RemoveAll(localPath); err != nil {
  234. logrus.Errorf("error cleaning up config dir: %s", err)
  235. }
  236. }
  237. }()
  238. if c.DependencyStore == nil {
  239. return fmt.Errorf("config store is not initialized")
  240. }
  241. for _, configRef := range c.ConfigReferences {
  242. // TODO (ehazlett): use type switch when more are supported
  243. if configRef.File == nil {
  244. logrus.Error("config target type is not a file target")
  245. continue
  246. }
  247. fPath, err := c.ConfigFilePath(*configRef)
  248. if err != nil {
  249. return err
  250. }
  251. log := logrus.WithFields(logrus.Fields{"name": configRef.File.Name, "path": fPath})
  252. if err := idtools.MkdirAllAndChown(filepath.Dir(fPath), 0700, rootIDs); err != nil {
  253. return errors.Wrap(err, "error creating config path")
  254. }
  255. log.Debug("injecting config")
  256. config, err := c.DependencyStore.Configs().Get(configRef.ConfigID)
  257. if err != nil {
  258. return errors.Wrap(err, "unable to get config from config store")
  259. }
  260. if err := ioutil.WriteFile(fPath, config.Spec.Data, configRef.File.Mode); err != nil {
  261. return errors.Wrap(err, "error injecting config")
  262. }
  263. uid, err := strconv.Atoi(configRef.File.UID)
  264. if err != nil {
  265. return err
  266. }
  267. gid, err := strconv.Atoi(configRef.File.GID)
  268. if err != nil {
  269. return err
  270. }
  271. if err := os.Chown(fPath, rootIDs.UID+uid, rootIDs.GID+gid); err != nil {
  272. return errors.Wrap(err, "error setting ownership for config")
  273. }
  274. if err := os.Chmod(fPath, configRef.File.Mode); err != nil {
  275. return errors.Wrap(err, "error setting file mode for config")
  276. }
  277. label.Relabel(fPath, c.MountLabel, false)
  278. }
  279. return nil
  280. }
  281. func killProcessDirectly(cntr *container.Container) error {
  282. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  283. defer cancel()
  284. // Block until the container to stops or timeout.
  285. status := <-cntr.Wait(ctx, container.WaitConditionNotRunning)
  286. if status.Err() != nil {
  287. // Ensure that we don't kill ourselves
  288. if pid := cntr.GetPID(); pid != 0 {
  289. logrus.Infof("Container %s failed to exit within 10 seconds of kill - trying direct SIGKILL", stringid.TruncateID(cntr.ID))
  290. if err := unix.Kill(pid, 9); err != nil {
  291. if err != unix.ESRCH {
  292. return err
  293. }
  294. e := errNoSuchProcess{pid, 9}
  295. logrus.Debug(e)
  296. return e
  297. }
  298. }
  299. }
  300. return nil
  301. }
  302. func detachMounted(path string) error {
  303. return unix.Unmount(path, unix.MNT_DETACH)
  304. }
  305. func isLinkable(child *container.Container) bool {
  306. // A container is linkable only if it belongs to the default network
  307. _, ok := child.NetworkSettings.Networks[runconfig.DefaultDaemonNetworkMode().NetworkName()]
  308. return ok
  309. }
  310. func enableIPOnPredefinedNetwork() bool {
  311. return false
  312. }
  313. func (daemon *Daemon) isNetworkHotPluggable() bool {
  314. return true
  315. }
  316. func setupPathsAndSandboxOptions(container *container.Container, sboxOptions *[]libnetwork.SandboxOption) error {
  317. var err error
  318. container.HostsPath, err = container.GetRootResourcePath("hosts")
  319. if err != nil {
  320. return err
  321. }
  322. *sboxOptions = append(*sboxOptions, libnetwork.OptionHostsPath(container.HostsPath))
  323. container.ResolvConfPath, err = container.GetRootResourcePath("resolv.conf")
  324. if err != nil {
  325. return err
  326. }
  327. *sboxOptions = append(*sboxOptions, libnetwork.OptionResolvConfPath(container.ResolvConfPath))
  328. return nil
  329. }
  330. func (daemon *Daemon) initializeNetworkingPaths(container *container.Container, nc *container.Container) error {
  331. container.HostnamePath = nc.HostnamePath
  332. container.HostsPath = nc.HostsPath
  333. container.ResolvConfPath = nc.ResolvConfPath
  334. return nil
  335. }
  336. func (daemon *Daemon) setupContainerMountsRoot(c *container.Container) error {
  337. // get the root mount path so we can make it unbindable
  338. p, err := c.MountsResourcePath("")
  339. if err != nil {
  340. return err
  341. }
  342. if err := idtools.MkdirAllAndChown(p, 0700, daemon.idMappings.RootPair()); err != nil {
  343. return err
  344. }
  345. if err := mount.MakeUnbindable(p); err != nil {
  346. // Setting unbindable is a precaution and is not neccessary for correct operation.
  347. // Do not error out if this fails.
  348. logrus.WithError(err).WithField("resource", p).WithField("container", c.ID).Warn("Error setting container resource mounts to unbindable, this may cause mount leakages, preventing removal of this container.")
  349. }
  350. return nil
  351. }