container_operations_unix.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. // +build linux freebsd
  2. package daemon
  3. import (
  4. "fmt"
  5. "io/ioutil"
  6. "os"
  7. "path/filepath"
  8. "strconv"
  9. "strings"
  10. "syscall"
  11. "time"
  12. "github.com/Sirupsen/logrus"
  13. "github.com/cloudflare/cfssl/log"
  14. containertypes "github.com/docker/docker/api/types/container"
  15. "github.com/docker/docker/container"
  16. "github.com/docker/docker/daemon/links"
  17. "github.com/docker/docker/pkg/idtools"
  18. "github.com/docker/docker/pkg/mount"
  19. "github.com/docker/docker/pkg/stringid"
  20. "github.com/docker/docker/runconfig"
  21. "github.com/docker/libnetwork"
  22. "github.com/opencontainers/runc/libcontainer/configs"
  23. "github.com/opencontainers/runc/libcontainer/devices"
  24. "github.com/opencontainers/runc/libcontainer/label"
  25. "github.com/opencontainers/runtime-spec/specs-go"
  26. "github.com/pkg/errors"
  27. )
  28. func u32Ptr(i int64) *uint32 { u := uint32(i); return &u }
  29. func fmPtr(i int64) *os.FileMode { fm := os.FileMode(i); return &fm }
  30. func (daemon *Daemon) setupLinkedContainers(container *container.Container) ([]string, error) {
  31. var env []string
  32. children := daemon.children(container)
  33. bridgeSettings := container.NetworkSettings.Networks[runconfig.DefaultDaemonNetworkMode().NetworkName()]
  34. if bridgeSettings == nil || bridgeSettings.EndpointSettings == nil {
  35. return nil, nil
  36. }
  37. for linkAlias, child := range children {
  38. if !child.IsRunning() {
  39. return nil, fmt.Errorf("Cannot link to a non running container: %s AS %s", child.Name, linkAlias)
  40. }
  41. childBridgeSettings := child.NetworkSettings.Networks[runconfig.DefaultDaemonNetworkMode().NetworkName()]
  42. if childBridgeSettings == nil || childBridgeSettings.EndpointSettings == nil {
  43. return nil, fmt.Errorf("container %s not attached to default bridge network", child.ID)
  44. }
  45. link := links.NewLink(
  46. bridgeSettings.IPAddress,
  47. childBridgeSettings.IPAddress,
  48. linkAlias,
  49. child.Config.Env,
  50. child.Config.ExposedPorts,
  51. )
  52. env = append(env, link.ToEnv()...)
  53. }
  54. return env, nil
  55. }
  56. func (daemon *Daemon) getIpcContainer(container *container.Container) (*container.Container, error) {
  57. containerID := container.HostConfig.IpcMode.Container()
  58. c, err := daemon.GetContainer(containerID)
  59. if err != nil {
  60. return nil, err
  61. }
  62. if !c.IsRunning() {
  63. return nil, fmt.Errorf("cannot join IPC of a non running container: %s", containerID)
  64. }
  65. if c.IsRestarting() {
  66. return nil, errContainerIsRestarting(container.ID)
  67. }
  68. return c, nil
  69. }
  70. func (daemon *Daemon) getPidContainer(container *container.Container) (*container.Container, error) {
  71. containerID := container.HostConfig.PidMode.Container()
  72. c, err := daemon.GetContainer(containerID)
  73. if err != nil {
  74. return nil, err
  75. }
  76. if !c.IsRunning() {
  77. return nil, fmt.Errorf("cannot join PID of a non running container: %s", containerID)
  78. }
  79. if c.IsRestarting() {
  80. return nil, errContainerIsRestarting(container.ID)
  81. }
  82. return c, nil
  83. }
  84. func (daemon *Daemon) setupIpcDirs(c *container.Container) error {
  85. var err error
  86. c.ShmPath, err = c.ShmResourcePath()
  87. if err != nil {
  88. return err
  89. }
  90. if c.HostConfig.IpcMode.IsContainer() {
  91. ic, err := daemon.getIpcContainer(c)
  92. if err != nil {
  93. return err
  94. }
  95. c.ShmPath = ic.ShmPath
  96. } else if c.HostConfig.IpcMode.IsHost() {
  97. if _, err := os.Stat("/dev/shm"); err != nil {
  98. return fmt.Errorf("/dev/shm is not mounted, but must be for --ipc=host")
  99. }
  100. c.ShmPath = "/dev/shm"
  101. } else {
  102. rootUID, rootGID := daemon.GetRemappedUIDGID()
  103. if !c.HasMountFor("/dev/shm") {
  104. shmPath, err := c.ShmResourcePath()
  105. if err != nil {
  106. return err
  107. }
  108. if err := idtools.MkdirAllAs(shmPath, 0700, rootUID, rootGID); err != nil {
  109. return err
  110. }
  111. shmSize := container.DefaultSHMSize
  112. if c.HostConfig.ShmSize != 0 {
  113. shmSize = c.HostConfig.ShmSize
  114. }
  115. shmproperty := "mode=1777,size=" + strconv.FormatInt(shmSize, 10)
  116. if err := syscall.Mount("shm", shmPath, "tmpfs", uintptr(syscall.MS_NOEXEC|syscall.MS_NOSUID|syscall.MS_NODEV), label.FormatMountLabel(shmproperty, c.GetMountLabel())); err != nil {
  117. return fmt.Errorf("mounting shm tmpfs: %s", err)
  118. }
  119. if err := os.Chown(shmPath, rootUID, rootGID); err != nil {
  120. return err
  121. }
  122. }
  123. }
  124. return nil
  125. }
  126. func (daemon *Daemon) setupSecretDir(c *container.Container) (setupErr error) {
  127. if len(c.Secrets) == 0 {
  128. return nil
  129. }
  130. localMountPath := c.SecretMountPath()
  131. logrus.Debugf("secrets: setting up secret dir: %s", localMountPath)
  132. defer func() {
  133. if setupErr != nil {
  134. // cleanup
  135. _ = detachMounted(localMountPath)
  136. if err := os.RemoveAll(localMountPath); err != nil {
  137. log.Errorf("error cleaning up secret mount: %s", err)
  138. }
  139. }
  140. }()
  141. // retrieve possible remapped range start for root UID, GID
  142. rootUID, rootGID := daemon.GetRemappedUIDGID()
  143. // create tmpfs
  144. if err := idtools.MkdirAllAs(localMountPath, 0700, rootUID, rootGID); err != nil {
  145. return errors.Wrap(err, "error creating secret local mount path")
  146. }
  147. tmpfsOwnership := fmt.Sprintf("uid=%d,gid=%d", rootUID, rootGID)
  148. if err := mount.Mount("tmpfs", localMountPath, "tmpfs", "nodev,nosuid,noexec,"+tmpfsOwnership); err != nil {
  149. return errors.Wrap(err, "unable to setup secret mount")
  150. }
  151. for _, s := range c.Secrets {
  152. targetPath := filepath.Clean(s.Target)
  153. // ensure that the target is a filename only; no paths allowed
  154. if targetPath != filepath.Base(targetPath) {
  155. return fmt.Errorf("error creating secret: secret must not be a path")
  156. }
  157. fPath := filepath.Join(localMountPath, targetPath)
  158. if err := idtools.MkdirAllAs(filepath.Dir(fPath), 0700, rootUID, rootGID); err != nil {
  159. return errors.Wrap(err, "error creating secret mount path")
  160. }
  161. logrus.WithFields(logrus.Fields{
  162. "name": s.Name,
  163. "path": fPath,
  164. }).Debug("injecting secret")
  165. if err := ioutil.WriteFile(fPath, s.Data, s.Mode); err != nil {
  166. return errors.Wrap(err, "error injecting secret")
  167. }
  168. uid, err := strconv.Atoi(s.UID)
  169. if err != nil {
  170. return err
  171. }
  172. gid, err := strconv.Atoi(s.GID)
  173. if err != nil {
  174. return err
  175. }
  176. if err := os.Chown(fPath, rootUID+uid, rootGID+gid); err != nil {
  177. return errors.Wrap(err, "error setting ownership for secret")
  178. }
  179. }
  180. // remount secrets ro
  181. if err := mount.Mount("tmpfs", localMountPath, "tmpfs", "remount,ro,"+tmpfsOwnership); err != nil {
  182. return errors.Wrap(err, "unable to remount secret dir as readonly")
  183. }
  184. return nil
  185. }
  186. func killProcessDirectly(container *container.Container) error {
  187. if _, err := container.WaitStop(10 * time.Second); err != nil {
  188. // Ensure that we don't kill ourselves
  189. if pid := container.GetPID(); pid != 0 {
  190. logrus.Infof("Container %s failed to exit within 10 seconds of kill - trying direct SIGKILL", stringid.TruncateID(container.ID))
  191. if err := syscall.Kill(pid, 9); err != nil {
  192. if err != syscall.ESRCH {
  193. return err
  194. }
  195. e := errNoSuchProcess{pid, 9}
  196. logrus.Debug(e)
  197. return e
  198. }
  199. }
  200. }
  201. return nil
  202. }
  203. func specDevice(d *configs.Device) specs.Device {
  204. return specs.Device{
  205. Type: string(d.Type),
  206. Path: d.Path,
  207. Major: d.Major,
  208. Minor: d.Minor,
  209. FileMode: fmPtr(int64(d.FileMode)),
  210. UID: u32Ptr(int64(d.Uid)),
  211. GID: u32Ptr(int64(d.Gid)),
  212. }
  213. }
  214. func specDeviceCgroup(d *configs.Device) specs.DeviceCgroup {
  215. t := string(d.Type)
  216. return specs.DeviceCgroup{
  217. Allow: true,
  218. Type: &t,
  219. Major: &d.Major,
  220. Minor: &d.Minor,
  221. Access: &d.Permissions,
  222. }
  223. }
  224. func getDevicesFromPath(deviceMapping containertypes.DeviceMapping) (devs []specs.Device, devPermissions []specs.DeviceCgroup, err error) {
  225. resolvedPathOnHost := deviceMapping.PathOnHost
  226. // check if it is a symbolic link
  227. if src, e := os.Lstat(deviceMapping.PathOnHost); e == nil && src.Mode()&os.ModeSymlink == os.ModeSymlink {
  228. if linkedPathOnHost, e := filepath.EvalSymlinks(deviceMapping.PathOnHost); e == nil {
  229. resolvedPathOnHost = linkedPathOnHost
  230. }
  231. }
  232. device, err := devices.DeviceFromPath(resolvedPathOnHost, deviceMapping.CgroupPermissions)
  233. // if there was no error, return the device
  234. if err == nil {
  235. device.Path = deviceMapping.PathInContainer
  236. return append(devs, specDevice(device)), append(devPermissions, specDeviceCgroup(device)), nil
  237. }
  238. // if the device is not a device node
  239. // try to see if it's a directory holding many devices
  240. if err == devices.ErrNotADevice {
  241. // check if it is a directory
  242. if src, e := os.Stat(resolvedPathOnHost); e == nil && src.IsDir() {
  243. // mount the internal devices recursively
  244. filepath.Walk(resolvedPathOnHost, func(dpath string, f os.FileInfo, e error) error {
  245. childDevice, e := devices.DeviceFromPath(dpath, deviceMapping.CgroupPermissions)
  246. if e != nil {
  247. // ignore the device
  248. return nil
  249. }
  250. // add the device to userSpecified devices
  251. childDevice.Path = strings.Replace(dpath, resolvedPathOnHost, deviceMapping.PathInContainer, 1)
  252. devs = append(devs, specDevice(childDevice))
  253. devPermissions = append(devPermissions, specDeviceCgroup(childDevice))
  254. return nil
  255. })
  256. }
  257. }
  258. if len(devs) > 0 {
  259. return devs, devPermissions, nil
  260. }
  261. return devs, devPermissions, fmt.Errorf("error gathering device information while adding custom device %q: %s", deviceMapping.PathOnHost, err)
  262. }
  263. func detachMounted(path string) error {
  264. return syscall.Unmount(path, syscall.MNT_DETACH)
  265. }
  266. func isLinkable(child *container.Container) bool {
  267. // A container is linkable only if it belongs to the default network
  268. _, ok := child.NetworkSettings.Networks[runconfig.DefaultDaemonNetworkMode().NetworkName()]
  269. return ok
  270. }
  271. func enableIPOnPredefinedNetwork() bool {
  272. return false
  273. }
  274. func (daemon *Daemon) isNetworkHotPluggable() bool {
  275. return true
  276. }
  277. func setupPathsAndSandboxOptions(container *container.Container, sboxOptions *[]libnetwork.SandboxOption) error {
  278. var err error
  279. container.HostsPath, err = container.GetRootResourcePath("hosts")
  280. if err != nil {
  281. return err
  282. }
  283. *sboxOptions = append(*sboxOptions, libnetwork.OptionHostsPath(container.HostsPath))
  284. container.ResolvConfPath, err = container.GetRootResourcePath("resolv.conf")
  285. if err != nil {
  286. return err
  287. }
  288. *sboxOptions = append(*sboxOptions, libnetwork.OptionResolvConfPath(container.ResolvConfPath))
  289. return nil
  290. }
  291. func initializeNetworkingPaths(container *container.Container, nc *container.Container) {
  292. container.HostnamePath = nc.HostnamePath
  293. container.HostsPath = nc.HostsPath
  294. container.ResolvConfPath = nc.ResolvConfPath
  295. }