container_operations_unix.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. // +build linux freebsd
  2. package daemon
  3. import (
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "strconv"
  8. "strings"
  9. "syscall"
  10. "time"
  11. "github.com/Sirupsen/logrus"
  12. containertypes "github.com/docker/docker/api/types/container"
  13. "github.com/docker/docker/container"
  14. "github.com/docker/docker/daemon/links"
  15. "github.com/docker/docker/pkg/fileutils"
  16. "github.com/docker/docker/pkg/idtools"
  17. "github.com/docker/docker/pkg/mount"
  18. "github.com/docker/docker/pkg/stringid"
  19. "github.com/docker/docker/runconfig"
  20. "github.com/opencontainers/runc/libcontainer/configs"
  21. "github.com/opencontainers/runc/libcontainer/devices"
  22. "github.com/opencontainers/runc/libcontainer/label"
  23. "github.com/opencontainers/runtime-spec/specs-go"
  24. )
  25. func u32Ptr(i int64) *uint32 { u := uint32(i); return &u }
  26. func fmPtr(i int64) *os.FileMode { fm := os.FileMode(i); return &fm }
  27. func (daemon *Daemon) setupLinkedContainers(container *container.Container) ([]string, error) {
  28. var env []string
  29. children := daemon.children(container)
  30. bridgeSettings := container.NetworkSettings.Networks[runconfig.DefaultDaemonNetworkMode().NetworkName()]
  31. if bridgeSettings == nil || bridgeSettings.EndpointSettings == nil {
  32. return nil, nil
  33. }
  34. for linkAlias, child := range children {
  35. if !child.IsRunning() {
  36. return nil, fmt.Errorf("Cannot link to a non running container: %s AS %s", child.Name, linkAlias)
  37. }
  38. childBridgeSettings := child.NetworkSettings.Networks[runconfig.DefaultDaemonNetworkMode().NetworkName()]
  39. if childBridgeSettings == nil || childBridgeSettings.EndpointSettings == nil {
  40. return nil, fmt.Errorf("container %s not attached to default bridge network", child.ID)
  41. }
  42. link := links.NewLink(
  43. bridgeSettings.IPAddress,
  44. childBridgeSettings.IPAddress,
  45. linkAlias,
  46. child.Config.Env,
  47. child.Config.ExposedPorts,
  48. )
  49. env = append(env, link.ToEnv()...)
  50. }
  51. return env, nil
  52. }
  53. // getSize returns the real size & virtual size of the container.
  54. func (daemon *Daemon) getSize(container *container.Container) (int64, int64) {
  55. var (
  56. sizeRw, sizeRootfs int64
  57. err error
  58. )
  59. if err := daemon.Mount(container); err != nil {
  60. logrus.Errorf("Failed to compute size of container rootfs %s: %s", container.ID, err)
  61. return sizeRw, sizeRootfs
  62. }
  63. defer daemon.Unmount(container)
  64. sizeRw, err = container.RWLayer.Size()
  65. if err != nil {
  66. logrus.Errorf("Driver %s couldn't return diff size of container %s: %s",
  67. daemon.GraphDriverName(), container.ID, err)
  68. // FIXME: GetSize should return an error. Not changing it now in case
  69. // there is a side-effect.
  70. sizeRw = -1
  71. }
  72. if parent := container.RWLayer.Parent(); parent != nil {
  73. sizeRootfs, err = parent.Size()
  74. if err != nil {
  75. sizeRootfs = -1
  76. } else if sizeRw != -1 {
  77. sizeRootfs += sizeRw
  78. }
  79. }
  80. return sizeRw, sizeRootfs
  81. }
  82. func (daemon *Daemon) getIpcContainer(container *container.Container) (*container.Container, error) {
  83. containerID := container.HostConfig.IpcMode.Container()
  84. c, err := daemon.GetContainer(containerID)
  85. if err != nil {
  86. return nil, err
  87. }
  88. if !c.IsRunning() {
  89. return nil, fmt.Errorf("cannot join IPC of a non running container: %s", containerID)
  90. }
  91. if c.IsRestarting() {
  92. return nil, errContainerIsRestarting(container.ID)
  93. }
  94. return c, nil
  95. }
  96. func (daemon *Daemon) getPidContainer(container *container.Container) (*container.Container, error) {
  97. containerID := container.HostConfig.PidMode.Container()
  98. c, err := daemon.GetContainer(containerID)
  99. if err != nil {
  100. return nil, err
  101. }
  102. if !c.IsRunning() {
  103. return nil, fmt.Errorf("cannot join PID of a non running container: %s", containerID)
  104. }
  105. if c.IsRestarting() {
  106. return nil, errContainerIsRestarting(container.ID)
  107. }
  108. return c, nil
  109. }
  110. func (daemon *Daemon) setupIpcDirs(c *container.Container) error {
  111. var err error
  112. c.ShmPath, err = c.ShmResourcePath()
  113. if err != nil {
  114. return err
  115. }
  116. if c.HostConfig.IpcMode.IsContainer() {
  117. ic, err := daemon.getIpcContainer(c)
  118. if err != nil {
  119. return err
  120. }
  121. c.ShmPath = ic.ShmPath
  122. } else if c.HostConfig.IpcMode.IsHost() {
  123. if _, err := os.Stat("/dev/shm"); err != nil {
  124. return fmt.Errorf("/dev/shm is not mounted, but must be for --ipc=host")
  125. }
  126. c.ShmPath = "/dev/shm"
  127. } else {
  128. rootUID, rootGID := daemon.GetRemappedUIDGID()
  129. if !c.HasMountFor("/dev/shm") {
  130. shmPath, err := c.ShmResourcePath()
  131. if err != nil {
  132. return err
  133. }
  134. if err := idtools.MkdirAllAs(shmPath, 0700, rootUID, rootGID); err != nil {
  135. return err
  136. }
  137. shmSize := container.DefaultSHMSize
  138. if c.HostConfig.ShmSize != 0 {
  139. shmSize = c.HostConfig.ShmSize
  140. }
  141. shmproperty := "mode=1777,size=" + strconv.FormatInt(shmSize, 10)
  142. if err := syscall.Mount("shm", shmPath, "tmpfs", uintptr(syscall.MS_NOEXEC|syscall.MS_NOSUID|syscall.MS_NODEV), label.FormatMountLabel(shmproperty, c.GetMountLabel())); err != nil {
  143. return fmt.Errorf("mounting shm tmpfs: %s", err)
  144. }
  145. if err := os.Chown(shmPath, rootUID, rootGID); err != nil {
  146. return err
  147. }
  148. }
  149. }
  150. return nil
  151. }
  152. func (daemon *Daemon) mountVolumes(container *container.Container) error {
  153. mounts, err := daemon.setupMounts(container)
  154. if err != nil {
  155. return err
  156. }
  157. for _, m := range mounts {
  158. dest, err := container.GetResourcePath(m.Destination)
  159. if err != nil {
  160. return err
  161. }
  162. var stat os.FileInfo
  163. stat, err = os.Stat(m.Source)
  164. if err != nil {
  165. return err
  166. }
  167. if err = fileutils.CreateIfNotExists(dest, stat.IsDir()); err != nil {
  168. return err
  169. }
  170. opts := "rbind,ro"
  171. if m.Writable {
  172. opts = "rbind,rw"
  173. }
  174. if err := mount.Mount(m.Source, dest, "bind", opts); err != nil {
  175. return err
  176. }
  177. // mountVolumes() seems to be called for temporary mounts
  178. // outside the container. Soon these will be unmounted with
  179. // lazy unmount option and given we have mounted the rbind,
  180. // all the submounts will propagate if these are shared. If
  181. // daemon is running in host namespace and has / as shared
  182. // then these unmounts will propagate and unmount original
  183. // mount as well. So make all these mounts rprivate.
  184. // Do not use propagation property of volume as that should
  185. // apply only when mounting happen inside the container.
  186. if err := mount.MakeRPrivate(dest); err != nil {
  187. return err
  188. }
  189. }
  190. return nil
  191. }
  192. func killProcessDirectly(container *container.Container) error {
  193. if _, err := container.WaitStop(10 * time.Second); err != nil {
  194. // Ensure that we don't kill ourselves
  195. if pid := container.GetPID(); pid != 0 {
  196. logrus.Infof("Container %s failed to exit within 10 seconds of kill - trying direct SIGKILL", stringid.TruncateID(container.ID))
  197. if err := syscall.Kill(pid, 9); err != nil {
  198. if err != syscall.ESRCH {
  199. return err
  200. }
  201. e := errNoSuchProcess{pid, 9}
  202. logrus.Debug(e)
  203. return e
  204. }
  205. }
  206. }
  207. return nil
  208. }
  209. func specDevice(d *configs.Device) specs.Device {
  210. return specs.Device{
  211. Type: string(d.Type),
  212. Path: d.Path,
  213. Major: d.Major,
  214. Minor: d.Minor,
  215. FileMode: fmPtr(int64(d.FileMode)),
  216. UID: u32Ptr(int64(d.Uid)),
  217. GID: u32Ptr(int64(d.Gid)),
  218. }
  219. }
  220. func specDeviceCgroup(d *configs.Device) specs.DeviceCgroup {
  221. t := string(d.Type)
  222. return specs.DeviceCgroup{
  223. Allow: true,
  224. Type: &t,
  225. Major: &d.Major,
  226. Minor: &d.Minor,
  227. Access: &d.Permissions,
  228. }
  229. }
  230. func getDevicesFromPath(deviceMapping containertypes.DeviceMapping) (devs []specs.Device, devPermissions []specs.DeviceCgroup, err error) {
  231. resolvedPathOnHost := deviceMapping.PathOnHost
  232. // check if it is a symbolic link
  233. if src, e := os.Lstat(deviceMapping.PathOnHost); e == nil && src.Mode()&os.ModeSymlink == os.ModeSymlink {
  234. if linkedPathOnHost, e := filepath.EvalSymlinks(deviceMapping.PathOnHost); e == nil {
  235. resolvedPathOnHost = linkedPathOnHost
  236. }
  237. }
  238. device, err := devices.DeviceFromPath(resolvedPathOnHost, deviceMapping.CgroupPermissions)
  239. // if there was no error, return the device
  240. if err == nil {
  241. device.Path = deviceMapping.PathInContainer
  242. return append(devs, specDevice(device)), append(devPermissions, specDeviceCgroup(device)), nil
  243. }
  244. // if the device is not a device node
  245. // try to see if it's a directory holding many devices
  246. if err == devices.ErrNotADevice {
  247. // check if it is a directory
  248. if src, e := os.Stat(resolvedPathOnHost); e == nil && src.IsDir() {
  249. // mount the internal devices recursively
  250. filepath.Walk(resolvedPathOnHost, func(dpath string, f os.FileInfo, e error) error {
  251. childDevice, e := devices.DeviceFromPath(dpath, deviceMapping.CgroupPermissions)
  252. if e != nil {
  253. // ignore the device
  254. return nil
  255. }
  256. // add the device to userSpecified devices
  257. childDevice.Path = strings.Replace(dpath, resolvedPathOnHost, deviceMapping.PathInContainer, 1)
  258. devs = append(devs, specDevice(childDevice))
  259. devPermissions = append(devPermissions, specDeviceCgroup(childDevice))
  260. return nil
  261. })
  262. }
  263. }
  264. if len(devs) > 0 {
  265. return devs, devPermissions, nil
  266. }
  267. return devs, devPermissions, fmt.Errorf("error gathering device information while adding custom device %q: %s", deviceMapping.PathOnHost, err)
  268. }
  269. func detachMounted(path string) error {
  270. return syscall.Unmount(path, syscall.MNT_DETACH)
  271. }
  272. func isLinkable(child *container.Container) bool {
  273. // A container is linkable only if it belongs to the default network
  274. _, ok := child.NetworkSettings.Networks[runconfig.DefaultDaemonNetworkMode().NetworkName()]
  275. return ok
  276. }
  277. func enableIPOnPredefinedNetwork() bool {
  278. return false
  279. }
  280. func (daemon *Daemon) isNetworkHotPluggable() bool {
  281. return true
  282. }