container_operations_unix.go 9.3 KB

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