container_operations_unix.go 9.9 KB

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