container_operations_unix.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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/stringid"
  19. "github.com/docker/docker/runconfig"
  20. "github.com/docker/engine-api/types/mount"
  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. localMountPath := c.SecretMountPath()
  128. logrus.Debugf("secrets: setting up secret dir: %s", localMountPath)
  129. defer func(err error) {
  130. if err != nil {
  131. // cleanup
  132. _ = detachMounted(localMountPath)
  133. if err := os.RemoveAll(localMountPath); err != nil {
  134. log.Errorf("error cleaning up secret mount: %s", err)
  135. }
  136. }
  137. }(setupErr)
  138. // create tmpfs
  139. if err := os.MkdirAll(localMountPath, 0700); err != nil {
  140. return errors.Wrap(err, "error creating secret local mount path")
  141. }
  142. if err := mount.Mount("tmpfs", localMountPath, "tmpfs", "nodev"); err != nil {
  143. return errors.Wrap(err, "unable to setup secret mount")
  144. }
  145. for _, s := range c.Secrets {
  146. // ensure that the target is a filename only; no paths allowed
  147. tDir, tPath := filepath.Split(s.Target)
  148. if tDir != "" {
  149. return fmt.Errorf("error creating secret: secret must not have a path")
  150. }
  151. fPath := filepath.Join(localMountPath, tPath)
  152. if err := os.MkdirAll(filepath.Dir(fPath), 0700); err != nil {
  153. return errors.Wrap(err, "error creating secret mount path")
  154. }
  155. logrus.WithFields(logrus.Fields{
  156. "name": s.Name,
  157. "path": fPath,
  158. }).Debug("injecting secret")
  159. if err := ioutil.WriteFile(fPath, s.Data, s.Mode); err != nil {
  160. return errors.Wrap(err, "error injecting secret")
  161. }
  162. if err := os.Chown(fPath, s.Uid, s.Gid); err != nil {
  163. return errors.Wrap(err, "error setting ownership for secret")
  164. }
  165. }
  166. // remount secrets ro
  167. if err := mount.Mount("tmpfs", localMountPath, "tmpfs", "remount,ro"); err != nil {
  168. return errors.Wrap(err, "unable to remount secret dir as readonly")
  169. }
  170. return nil
  171. }
  172. func killProcessDirectly(container *container.Container) error {
  173. if _, err := container.WaitStop(10 * time.Second); err != nil {
  174. // Ensure that we don't kill ourselves
  175. if pid := container.GetPID(); pid != 0 {
  176. logrus.Infof("Container %s failed to exit within 10 seconds of kill - trying direct SIGKILL", stringid.TruncateID(container.ID))
  177. if err := syscall.Kill(pid, 9); err != nil {
  178. if err != syscall.ESRCH {
  179. return err
  180. }
  181. e := errNoSuchProcess{pid, 9}
  182. logrus.Debug(e)
  183. return e
  184. }
  185. }
  186. }
  187. return nil
  188. }
  189. func specDevice(d *configs.Device) specs.Device {
  190. return specs.Device{
  191. Type: string(d.Type),
  192. Path: d.Path,
  193. Major: d.Major,
  194. Minor: d.Minor,
  195. FileMode: fmPtr(int64(d.FileMode)),
  196. UID: u32Ptr(int64(d.Uid)),
  197. GID: u32Ptr(int64(d.Gid)),
  198. }
  199. }
  200. func specDeviceCgroup(d *configs.Device) specs.DeviceCgroup {
  201. t := string(d.Type)
  202. return specs.DeviceCgroup{
  203. Allow: true,
  204. Type: &t,
  205. Major: &d.Major,
  206. Minor: &d.Minor,
  207. Access: &d.Permissions,
  208. }
  209. }
  210. func getDevicesFromPath(deviceMapping containertypes.DeviceMapping) (devs []specs.Device, devPermissions []specs.DeviceCgroup, err error) {
  211. resolvedPathOnHost := deviceMapping.PathOnHost
  212. // check if it is a symbolic link
  213. if src, e := os.Lstat(deviceMapping.PathOnHost); e == nil && src.Mode()&os.ModeSymlink == os.ModeSymlink {
  214. if linkedPathOnHost, e := filepath.EvalSymlinks(deviceMapping.PathOnHost); e == nil {
  215. resolvedPathOnHost = linkedPathOnHost
  216. }
  217. }
  218. device, err := devices.DeviceFromPath(resolvedPathOnHost, deviceMapping.CgroupPermissions)
  219. // if there was no error, return the device
  220. if err == nil {
  221. device.Path = deviceMapping.PathInContainer
  222. return append(devs, specDevice(device)), append(devPermissions, specDeviceCgroup(device)), nil
  223. }
  224. // if the device is not a device node
  225. // try to see if it's a directory holding many devices
  226. if err == devices.ErrNotADevice {
  227. // check if it is a directory
  228. if src, e := os.Stat(resolvedPathOnHost); e == nil && src.IsDir() {
  229. // mount the internal devices recursively
  230. filepath.Walk(resolvedPathOnHost, func(dpath string, f os.FileInfo, e error) error {
  231. childDevice, e := devices.DeviceFromPath(dpath, deviceMapping.CgroupPermissions)
  232. if e != nil {
  233. // ignore the device
  234. return nil
  235. }
  236. // add the device to userSpecified devices
  237. childDevice.Path = strings.Replace(dpath, resolvedPathOnHost, deviceMapping.PathInContainer, 1)
  238. devs = append(devs, specDevice(childDevice))
  239. devPermissions = append(devPermissions, specDeviceCgroup(childDevice))
  240. return nil
  241. })
  242. }
  243. }
  244. if len(devs) > 0 {
  245. return devs, devPermissions, nil
  246. }
  247. return devs, devPermissions, fmt.Errorf("error gathering device information while adding custom device %q: %s", deviceMapping.PathOnHost, err)
  248. }
  249. func detachMounted(path string) error {
  250. return syscall.Unmount(path, syscall.MNT_DETACH)
  251. }
  252. func isLinkable(child *container.Container) bool {
  253. // A container is linkable only if it belongs to the default network
  254. _, ok := child.NetworkSettings.Networks[runconfig.DefaultDaemonNetworkMode().NetworkName()]
  255. return ok
  256. }
  257. func enableIPOnPredefinedNetwork() bool {
  258. return false
  259. }
  260. func (daemon *Daemon) isNetworkHotPluggable() bool {
  261. return true
  262. }
  263. func setupPathsAndSandboxOptions(container *container.Container, sboxOptions *[]libnetwork.SandboxOption) error {
  264. var err error
  265. container.HostsPath, err = container.GetRootResourcePath("hosts")
  266. if err != nil {
  267. return err
  268. }
  269. *sboxOptions = append(*sboxOptions, libnetwork.OptionHostsPath(container.HostsPath))
  270. container.ResolvConfPath, err = container.GetRootResourcePath("resolv.conf")
  271. if err != nil {
  272. return err
  273. }
  274. *sboxOptions = append(*sboxOptions, libnetwork.OptionResolvConfPath(container.ResolvConfPath))
  275. return nil
  276. }
  277. func initializeNetworkingPaths(container *container.Container, nc *container.Container) {
  278. container.HostnamePath = nc.HostnamePath
  279. container.HostsPath = nc.HostsPath
  280. container.ResolvConfPath = nc.ResolvConfPath
  281. }