container_operations_unix.go 10 KB

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