container_operations_unix.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. // +build linux freebsd
  2. package daemon
  3. import (
  4. "context"
  5. "fmt"
  6. "io/ioutil"
  7. "os"
  8. "path/filepath"
  9. "strconv"
  10. "syscall"
  11. "time"
  12. "github.com/Sirupsen/logrus"
  13. "github.com/docker/docker/container"
  14. "github.com/docker/docker/daemon/links"
  15. "github.com/docker/docker/pkg/idtools"
  16. "github.com/docker/docker/pkg/mount"
  17. "github.com/docker/docker/pkg/stringid"
  18. "github.com/docker/docker/runconfig"
  19. "github.com/docker/libnetwork"
  20. "github.com/opencontainers/selinux/go-selinux/label"
  21. "github.com/pkg/errors"
  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(container *container.Container) (*container.Container, error) {
  50. containerID := container.HostConfig.IpcMode.Container()
  51. container, err := daemon.GetContainer(containerID)
  52. if err != nil {
  53. return nil, errors.Wrapf(err, "cannot join IPC of a non running container: %s", container.ID)
  54. }
  55. return container, daemon.checkContainer(container, containerIsRunning, containerIsNotRestarting)
  56. }
  57. func (daemon *Daemon) getPidContainer(container *container.Container) (*container.Container, error) {
  58. containerID := container.HostConfig.PidMode.Container()
  59. container, err := daemon.GetContainer(containerID)
  60. if err != nil {
  61. return nil, errors.Wrapf(err, "cannot join PID of a non running container: %s", container.ID)
  62. }
  63. return container, daemon.checkContainer(container, containerIsRunning, containerIsNotRestarting)
  64. }
  65. func containerIsRunning(c *container.Container) error {
  66. if !c.IsRunning() {
  67. return errors.Errorf("container %s is not running", c.ID)
  68. }
  69. return nil
  70. }
  71. func containerIsNotRestarting(c *container.Container) error {
  72. if c.IsRestarting() {
  73. return errContainerIsRestarting(c.ID)
  74. }
  75. return nil
  76. }
  77. func (daemon *Daemon) setupIpcDirs(c *container.Container) error {
  78. var err error
  79. c.ShmPath, err = c.ShmResourcePath()
  80. if err != nil {
  81. return err
  82. }
  83. if c.HostConfig.IpcMode.IsContainer() {
  84. ic, err := daemon.getIpcContainer(c)
  85. if err != nil {
  86. return err
  87. }
  88. c.ShmPath = ic.ShmPath
  89. } else if c.HostConfig.IpcMode.IsHost() {
  90. if _, err := os.Stat("/dev/shm"); err != nil {
  91. return fmt.Errorf("/dev/shm is not mounted, but must be for --ipc=host")
  92. }
  93. c.ShmPath = "/dev/shm"
  94. } else {
  95. rootUID, rootGID := daemon.GetRemappedUIDGID()
  96. if !c.HasMountFor("/dev/shm") {
  97. shmPath, err := c.ShmResourcePath()
  98. if err != nil {
  99. return err
  100. }
  101. if err := idtools.MkdirAllAs(shmPath, 0700, rootUID, rootGID); err != nil {
  102. return err
  103. }
  104. shmSize := int64(daemon.configStore.ShmSize)
  105. if c.HostConfig.ShmSize != 0 {
  106. shmSize = c.HostConfig.ShmSize
  107. }
  108. shmproperty := "mode=1777,size=" + strconv.FormatInt(shmSize, 10)
  109. if err := syscall.Mount("shm", shmPath, "tmpfs", uintptr(syscall.MS_NOEXEC|syscall.MS_NOSUID|syscall.MS_NODEV), label.FormatMountLabel(shmproperty, c.GetMountLabel())); err != nil {
  110. return fmt.Errorf("mounting shm tmpfs: %s", err)
  111. }
  112. if err := os.Chown(shmPath, rootUID, rootGID); err != nil {
  113. return err
  114. }
  115. }
  116. }
  117. return nil
  118. }
  119. func (daemon *Daemon) setupSecretDir(c *container.Container) (setupErr error) {
  120. if len(c.SecretReferences) == 0 {
  121. return nil
  122. }
  123. localMountPath := c.SecretMountPath()
  124. logrus.Debugf("secrets: setting up secret dir: %s", localMountPath)
  125. // retrieve possible remapped range start for root UID, GID
  126. rootUID, rootGID := daemon.GetRemappedUIDGID()
  127. // create tmpfs
  128. if err := idtools.MkdirAllAs(localMountPath, 0700, rootUID, rootGID); err != nil {
  129. return errors.Wrap(err, "error creating secret local mount path")
  130. }
  131. defer func() {
  132. if setupErr != nil {
  133. // cleanup
  134. _ = detachMounted(localMountPath)
  135. if err := os.RemoveAll(localMountPath); err != nil {
  136. logrus.Errorf("error cleaning up secret mount: %s", err)
  137. }
  138. }
  139. }()
  140. tmpfsOwnership := fmt.Sprintf("uid=%d,gid=%d", rootUID, rootGID)
  141. if err := mount.Mount("tmpfs", localMountPath, "tmpfs", "nodev,nosuid,noexec,"+tmpfsOwnership); err != nil {
  142. return errors.Wrap(err, "unable to setup secret mount")
  143. }
  144. if c.DependencyStore == nil {
  145. return fmt.Errorf("secret store is not initialized")
  146. }
  147. for _, s := range c.SecretReferences {
  148. // TODO (ehazlett): use type switch when more are supported
  149. if s.File == nil {
  150. logrus.Error("secret target type is not a file target")
  151. continue
  152. }
  153. // secrets are created in the SecretMountPath on the host, at a
  154. // single level
  155. fPath := c.SecretFilePath(*s)
  156. if err := idtools.MkdirAllAs(filepath.Dir(fPath), 0700, rootUID, rootGID); err != nil {
  157. return errors.Wrap(err, "error creating secret mount path")
  158. }
  159. logrus.WithFields(logrus.Fields{
  160. "name": s.File.Name,
  161. "path": fPath,
  162. }).Debug("injecting secret")
  163. secret := c.DependencyStore.Secrets().Get(s.SecretID)
  164. if secret == nil {
  165. return fmt.Errorf("unable to get secret from secret store")
  166. }
  167. if err := ioutil.WriteFile(fPath, secret.Spec.Data, s.File.Mode); err != nil {
  168. return errors.Wrap(err, "error injecting secret")
  169. }
  170. uid, err := strconv.Atoi(s.File.UID)
  171. if err != nil {
  172. return err
  173. }
  174. gid, err := strconv.Atoi(s.File.GID)
  175. if err != nil {
  176. return err
  177. }
  178. if err := os.Chown(fPath, rootUID+uid, rootGID+gid); err != nil {
  179. return errors.Wrap(err, "error setting ownership for secret")
  180. }
  181. }
  182. label.Relabel(localMountPath, c.MountLabel, false)
  183. // remount secrets ro
  184. if err := mount.Mount("tmpfs", localMountPath, "tmpfs", "remount,ro,"+tmpfsOwnership); err != nil {
  185. return errors.Wrap(err, "unable to remount secret dir as readonly")
  186. }
  187. return nil
  188. }
  189. func (daemon *Daemon) setupConfigDir(c *container.Container) (setupErr error) {
  190. if len(c.ConfigReferences) == 0 {
  191. return nil
  192. }
  193. localPath := c.ConfigsDirPath()
  194. logrus.Debugf("configs: setting up config dir: %s", localPath)
  195. // retrieve possible remapped range start for root UID, GID
  196. rootUID, rootGID := daemon.GetRemappedUIDGID()
  197. // create tmpfs
  198. if err := idtools.MkdirAllAs(localPath, 0700, rootUID, rootGID); err != nil {
  199. return errors.Wrap(err, "error creating config dir")
  200. }
  201. defer func() {
  202. if setupErr != nil {
  203. if err := os.RemoveAll(localPath); err != nil {
  204. logrus.Errorf("error cleaning up config dir: %s", err)
  205. }
  206. }
  207. }()
  208. if c.DependencyStore == nil {
  209. return fmt.Errorf("config store is not initialized")
  210. }
  211. for _, configRef := range c.ConfigReferences {
  212. // TODO (ehazlett): use type switch when more are supported
  213. if configRef.File == nil {
  214. logrus.Error("config target type is not a file target")
  215. continue
  216. }
  217. fPath := c.ConfigFilePath(*configRef)
  218. log := logrus.WithFields(logrus.Fields{"name": configRef.File.Name, "path": fPath})
  219. if err := idtools.MkdirAllAs(filepath.Dir(fPath), 0700, rootUID, rootGID); err != nil {
  220. return errors.Wrap(err, "error creating config path")
  221. }
  222. log.Debug("injecting config")
  223. config := c.DependencyStore.Configs().Get(configRef.ConfigID)
  224. if config == nil {
  225. return fmt.Errorf("unable to get config from config store")
  226. }
  227. if err := ioutil.WriteFile(fPath, config.Spec.Data, configRef.File.Mode); err != nil {
  228. return errors.Wrap(err, "error injecting config")
  229. }
  230. uid, err := strconv.Atoi(configRef.File.UID)
  231. if err != nil {
  232. return err
  233. }
  234. gid, err := strconv.Atoi(configRef.File.GID)
  235. if err != nil {
  236. return err
  237. }
  238. if err := os.Chown(fPath, rootUID+uid, rootGID+gid); err != nil {
  239. return errors.Wrap(err, "error setting ownership for config")
  240. }
  241. }
  242. return nil
  243. }
  244. func killProcessDirectly(container *container.Container) error {
  245. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  246. defer cancel()
  247. // Block until the container to stops or timeout.
  248. status := <-container.Wait(ctx, false)
  249. if status.Err() != nil {
  250. // Ensure that we don't kill ourselves
  251. if pid := container.GetPID(); pid != 0 {
  252. logrus.Infof("Container %s failed to exit within 10 seconds of kill - trying direct SIGKILL", stringid.TruncateID(container.ID))
  253. if err := syscall.Kill(pid, 9); err != nil {
  254. if err != syscall.ESRCH {
  255. return err
  256. }
  257. e := errNoSuchProcess{pid, 9}
  258. logrus.Debug(e)
  259. return e
  260. }
  261. }
  262. }
  263. return nil
  264. }
  265. func detachMounted(path string) error {
  266. return syscall.Unmount(path, syscall.MNT_DETACH)
  267. }
  268. func isLinkable(child *container.Container) bool {
  269. // A container is linkable only if it belongs to the default network
  270. _, ok := child.NetworkSettings.Networks[runconfig.DefaultDaemonNetworkMode().NetworkName()]
  271. return ok
  272. }
  273. func enableIPOnPredefinedNetwork() bool {
  274. return false
  275. }
  276. func (daemon *Daemon) isNetworkHotPluggable() bool {
  277. return true
  278. }
  279. func setupPathsAndSandboxOptions(container *container.Container, sboxOptions *[]libnetwork.SandboxOption) error {
  280. var err error
  281. container.HostsPath, err = container.GetRootResourcePath("hosts")
  282. if err != nil {
  283. return err
  284. }
  285. *sboxOptions = append(*sboxOptions, libnetwork.OptionHostsPath(container.HostsPath))
  286. container.ResolvConfPath, err = container.GetRootResourcePath("resolv.conf")
  287. if err != nil {
  288. return err
  289. }
  290. *sboxOptions = append(*sboxOptions, libnetwork.OptionResolvConfPath(container.ResolvConfPath))
  291. return nil
  292. }
  293. func initializeNetworkingPaths(container *container.Container, nc *container.Container) {
  294. container.HostnamePath = nc.HostnamePath
  295. container.HostsPath = nc.HostsPath
  296. container.ResolvConfPath = nc.ResolvConfPath
  297. }