container_operations_unix.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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/pkg/idtools"
  14. "github.com/docker/docker/pkg/mount"
  15. "github.com/docker/docker/pkg/stringid"
  16. "github.com/docker/docker/runconfig"
  17. "github.com/docker/libnetwork"
  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. container, 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(container, 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(container.ShmPath); err != nil || !st.IsDir() {
  62. if err == nil || os.IsNotExist(err) {
  63. return nil, errors.New(errMsg + ": non-shareable IPC")
  64. }
  65. // stat() failed?
  66. return nil, errors.Wrap(err, errMsg+": unexpected error from stat "+container.ShmPath)
  67. }
  68. return container, nil
  69. }
  70. func (daemon *Daemon) getPidContainer(container *container.Container) (*container.Container, error) {
  71. containerID := container.HostConfig.PidMode.Container()
  72. container, err := daemon.GetContainer(containerID)
  73. if err != nil {
  74. return nil, errors.Wrapf(err, "cannot join PID of a non running container: %s", container.ID)
  75. }
  76. return container, daemon.checkContainer(container, containerIsRunning, containerIsNotRestarting)
  77. }
  78. func containerIsRunning(c *container.Container) error {
  79. if !c.IsRunning() {
  80. return stateConflictError{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.idMappings.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 {
  138. return nil
  139. }
  140. localMountPath := c.SecretMountPath()
  141. logrus.Debugf("secrets: setting up secret dir: %s", localMountPath)
  142. // retrieve possible remapped range start for root UID, GID
  143. rootIDs := daemon.idMappings.RootPair()
  144. // create tmpfs
  145. if err := idtools.MkdirAllAndChown(localMountPath, 0700, rootIDs); err != nil {
  146. return errors.Wrap(err, "error creating secret local mount path")
  147. }
  148. defer func() {
  149. if setupErr != nil {
  150. // cleanup
  151. _ = detachMounted(localMountPath)
  152. if err := os.RemoveAll(localMountPath); err != nil {
  153. logrus.Errorf("error cleaning up secret mount: %s", err)
  154. }
  155. }
  156. }()
  157. tmpfsOwnership := fmt.Sprintf("uid=%d,gid=%d", rootIDs.UID, rootIDs.GID)
  158. if err := mount.Mount("tmpfs", localMountPath, "tmpfs", "nodev,nosuid,noexec,"+tmpfsOwnership); err != nil {
  159. return errors.Wrap(err, "unable to setup secret mount")
  160. }
  161. if c.DependencyStore == nil {
  162. return fmt.Errorf("secret store is not initialized")
  163. }
  164. for _, s := range c.SecretReferences {
  165. // TODO (ehazlett): use type switch when more are supported
  166. if s.File == nil {
  167. logrus.Error("secret target type is not a file target")
  168. continue
  169. }
  170. // secrets are created in the SecretMountPath on the host, at a
  171. // single level
  172. fPath := c.SecretFilePath(*s)
  173. if err := idtools.MkdirAllAndChown(filepath.Dir(fPath), 0700, rootIDs); err != nil {
  174. return errors.Wrap(err, "error creating secret mount path")
  175. }
  176. logrus.WithFields(logrus.Fields{
  177. "name": s.File.Name,
  178. "path": fPath,
  179. }).Debug("injecting secret")
  180. secret, err := c.DependencyStore.Secrets().Get(s.SecretID)
  181. if err != nil {
  182. return errors.Wrap(err, "unable to get secret from secret store")
  183. }
  184. if err := ioutil.WriteFile(fPath, secret.Spec.Data, s.File.Mode); err != nil {
  185. return errors.Wrap(err, "error injecting secret")
  186. }
  187. uid, err := strconv.Atoi(s.File.UID)
  188. if err != nil {
  189. return err
  190. }
  191. gid, err := strconv.Atoi(s.File.GID)
  192. if err != nil {
  193. return err
  194. }
  195. if err := os.Chown(fPath, rootIDs.UID+uid, rootIDs.GID+gid); err != nil {
  196. return errors.Wrap(err, "error setting ownership for secret")
  197. }
  198. }
  199. label.Relabel(localMountPath, c.MountLabel, false)
  200. // remount secrets ro
  201. if err := mount.Mount("tmpfs", localMountPath, "tmpfs", "remount,ro,"+tmpfsOwnership); err != nil {
  202. return errors.Wrap(err, "unable to remount secret dir as readonly")
  203. }
  204. return nil
  205. }
  206. func (daemon *Daemon) setupConfigDir(c *container.Container) (setupErr error) {
  207. if len(c.ConfigReferences) == 0 {
  208. return nil
  209. }
  210. localPath := c.ConfigsDirPath()
  211. logrus.Debugf("configs: setting up config dir: %s", localPath)
  212. // retrieve possible remapped range start for root UID, GID
  213. rootIDs := daemon.idMappings.RootPair()
  214. // create tmpfs
  215. if err := idtools.MkdirAllAndChown(localPath, 0700, rootIDs); err != nil {
  216. return errors.Wrap(err, "error creating config dir")
  217. }
  218. defer func() {
  219. if setupErr != nil {
  220. if err := os.RemoveAll(localPath); err != nil {
  221. logrus.Errorf("error cleaning up config dir: %s", err)
  222. }
  223. }
  224. }()
  225. if c.DependencyStore == nil {
  226. return fmt.Errorf("config store is not initialized")
  227. }
  228. for _, configRef := range c.ConfigReferences {
  229. // TODO (ehazlett): use type switch when more are supported
  230. if configRef.File == nil {
  231. logrus.Error("config target type is not a file target")
  232. continue
  233. }
  234. fPath := c.ConfigFilePath(*configRef)
  235. log := logrus.WithFields(logrus.Fields{"name": configRef.File.Name, "path": fPath})
  236. if err := idtools.MkdirAllAndChown(filepath.Dir(fPath), 0700, rootIDs); err != nil {
  237. return errors.Wrap(err, "error creating config path")
  238. }
  239. log.Debug("injecting config")
  240. config, err := c.DependencyStore.Configs().Get(configRef.ConfigID)
  241. if err != nil {
  242. return errors.Wrap(err, "unable to get config from config store")
  243. }
  244. if err := ioutil.WriteFile(fPath, config.Spec.Data, configRef.File.Mode); err != nil {
  245. return errors.Wrap(err, "error injecting config")
  246. }
  247. uid, err := strconv.Atoi(configRef.File.UID)
  248. if err != nil {
  249. return err
  250. }
  251. gid, err := strconv.Atoi(configRef.File.GID)
  252. if err != nil {
  253. return err
  254. }
  255. if err := os.Chown(fPath, rootIDs.UID+uid, rootIDs.GID+gid); err != nil {
  256. return errors.Wrap(err, "error setting ownership for config")
  257. }
  258. label.Relabel(fPath, c.MountLabel, false)
  259. }
  260. return nil
  261. }
  262. func killProcessDirectly(cntr *container.Container) error {
  263. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  264. defer cancel()
  265. // Block until the container to stops or timeout.
  266. status := <-cntr.Wait(ctx, container.WaitConditionNotRunning)
  267. if status.Err() != nil {
  268. // Ensure that we don't kill ourselves
  269. if pid := cntr.GetPID(); pid != 0 {
  270. logrus.Infof("Container %s failed to exit within 10 seconds of kill - trying direct SIGKILL", stringid.TruncateID(cntr.ID))
  271. if err := unix.Kill(pid, 9); err != nil {
  272. if err != unix.ESRCH {
  273. return err
  274. }
  275. e := errNoSuchProcess{pid, 9}
  276. logrus.Debug(e)
  277. return e
  278. }
  279. }
  280. }
  281. return nil
  282. }
  283. func detachMounted(path string) error {
  284. return unix.Unmount(path, unix.MNT_DETACH)
  285. }
  286. func isLinkable(child *container.Container) bool {
  287. // A container is linkable only if it belongs to the default network
  288. _, ok := child.NetworkSettings.Networks[runconfig.DefaultDaemonNetworkMode().NetworkName()]
  289. return ok
  290. }
  291. func enableIPOnPredefinedNetwork() bool {
  292. return false
  293. }
  294. func (daemon *Daemon) isNetworkHotPluggable() bool {
  295. return true
  296. }
  297. func setupPathsAndSandboxOptions(container *container.Container, sboxOptions *[]libnetwork.SandboxOption) error {
  298. var err error
  299. container.HostsPath, err = container.GetRootResourcePath("hosts")
  300. if err != nil {
  301. return err
  302. }
  303. *sboxOptions = append(*sboxOptions, libnetwork.OptionHostsPath(container.HostsPath))
  304. container.ResolvConfPath, err = container.GetRootResourcePath("resolv.conf")
  305. if err != nil {
  306. return err
  307. }
  308. *sboxOptions = append(*sboxOptions, libnetwork.OptionResolvConfPath(container.ResolvConfPath))
  309. return nil
  310. }
  311. func (daemon *Daemon) initializeNetworkingPaths(container *container.Container, nc *container.Container) error {
  312. container.HostnamePath = nc.HostnamePath
  313. container.HostsPath = nc.HostsPath
  314. container.ResolvConfPath = nc.ResolvConfPath
  315. return nil
  316. }