container_operations_unix.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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. 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. // create tmpfs
  142. if err := os.MkdirAll(localMountPath, 0700); err != nil {
  143. return errors.Wrap(err, "error creating secret local mount path")
  144. }
  145. if err := mount.Mount("tmpfs", localMountPath, "tmpfs", "nodev,nosuid,noexec"); err != nil {
  146. return errors.Wrap(err, "unable to setup secret mount")
  147. }
  148. for _, s := range c.Secrets {
  149. targetPath := filepath.Clean(s.Target)
  150. // ensure that the target is a filename only; no paths allowed
  151. if targetPath != filepath.Base(targetPath) {
  152. return fmt.Errorf("error creating secret: secret must not be a path")
  153. }
  154. fPath := filepath.Join(localMountPath, targetPath)
  155. if err := os.MkdirAll(filepath.Dir(fPath), 0700); err != nil {
  156. return errors.Wrap(err, "error creating secret mount path")
  157. }
  158. logrus.WithFields(logrus.Fields{
  159. "name": s.Name,
  160. "path": fPath,
  161. }).Debug("injecting secret")
  162. if err := ioutil.WriteFile(fPath, s.Data, s.Mode); err != nil {
  163. return errors.Wrap(err, "error injecting secret")
  164. }
  165. uid, err := strconv.Atoi(s.UID)
  166. if err != nil {
  167. return err
  168. }
  169. gid, err := strconv.Atoi(s.GID)
  170. if err != nil {
  171. return err
  172. }
  173. if err := os.Chown(fPath, uid, gid); err != nil {
  174. return errors.Wrap(err, "error setting ownership for secret")
  175. }
  176. }
  177. // remount secrets ro
  178. if err := mount.Mount("tmpfs", localMountPath, "tmpfs", "remount,ro"); err != nil {
  179. return errors.Wrap(err, "unable to remount secret dir as readonly")
  180. }
  181. return nil
  182. }
  183. func killProcessDirectly(container *container.Container) error {
  184. if _, err := container.WaitStop(10 * time.Second); err != nil {
  185. // Ensure that we don't kill ourselves
  186. if pid := container.GetPID(); pid != 0 {
  187. logrus.Infof("Container %s failed to exit within 10 seconds of kill - trying direct SIGKILL", stringid.TruncateID(container.ID))
  188. if err := syscall.Kill(pid, 9); err != nil {
  189. if err != syscall.ESRCH {
  190. return err
  191. }
  192. e := errNoSuchProcess{pid, 9}
  193. logrus.Debug(e)
  194. return e
  195. }
  196. }
  197. }
  198. return nil
  199. }
  200. func specDevice(d *configs.Device) specs.Device {
  201. return specs.Device{
  202. Type: string(d.Type),
  203. Path: d.Path,
  204. Major: d.Major,
  205. Minor: d.Minor,
  206. FileMode: fmPtr(int64(d.FileMode)),
  207. UID: u32Ptr(int64(d.Uid)),
  208. GID: u32Ptr(int64(d.Gid)),
  209. }
  210. }
  211. func specDeviceCgroup(d *configs.Device) specs.DeviceCgroup {
  212. t := string(d.Type)
  213. return specs.DeviceCgroup{
  214. Allow: true,
  215. Type: &t,
  216. Major: &d.Major,
  217. Minor: &d.Minor,
  218. Access: &d.Permissions,
  219. }
  220. }
  221. func getDevicesFromPath(deviceMapping containertypes.DeviceMapping) (devs []specs.Device, devPermissions []specs.DeviceCgroup, err error) {
  222. resolvedPathOnHost := deviceMapping.PathOnHost
  223. // check if it is a symbolic link
  224. if src, e := os.Lstat(deviceMapping.PathOnHost); e == nil && src.Mode()&os.ModeSymlink == os.ModeSymlink {
  225. if linkedPathOnHost, e := filepath.EvalSymlinks(deviceMapping.PathOnHost); e == nil {
  226. resolvedPathOnHost = linkedPathOnHost
  227. }
  228. }
  229. device, err := devices.DeviceFromPath(resolvedPathOnHost, deviceMapping.CgroupPermissions)
  230. // if there was no error, return the device
  231. if err == nil {
  232. device.Path = deviceMapping.PathInContainer
  233. return append(devs, specDevice(device)), append(devPermissions, specDeviceCgroup(device)), nil
  234. }
  235. // if the device is not a device node
  236. // try to see if it's a directory holding many devices
  237. if err == devices.ErrNotADevice {
  238. // check if it is a directory
  239. if src, e := os.Stat(resolvedPathOnHost); e == nil && src.IsDir() {
  240. // mount the internal devices recursively
  241. filepath.Walk(resolvedPathOnHost, func(dpath string, f os.FileInfo, e error) error {
  242. childDevice, e := devices.DeviceFromPath(dpath, deviceMapping.CgroupPermissions)
  243. if e != nil {
  244. // ignore the device
  245. return nil
  246. }
  247. // add the device to userSpecified devices
  248. childDevice.Path = strings.Replace(dpath, resolvedPathOnHost, deviceMapping.PathInContainer, 1)
  249. devs = append(devs, specDevice(childDevice))
  250. devPermissions = append(devPermissions, specDeviceCgroup(childDevice))
  251. return nil
  252. })
  253. }
  254. }
  255. if len(devs) > 0 {
  256. return devs, devPermissions, nil
  257. }
  258. return devs, devPermissions, fmt.Errorf("error gathering device information while adding custom device %q: %s", deviceMapping.PathOnHost, err)
  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. }