container_operations_unix.go 10 KB

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