container_operations_unix.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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 !container.Running {
  89. if container.RemovalInProgress || container.Dead {
  90. return errRemovalContainer(container.ID)
  91. }
  92. if _, err := daemon.updateNetworkConfig(container, idOrName, endpointConfig, true); err != nil {
  93. return err
  94. }
  95. if endpointConfig != nil {
  96. container.NetworkSettings.Networks[idOrName] = endpointConfig
  97. }
  98. } else {
  99. if err := daemon.connectToNetwork(container, idOrName, endpointConfig, true); err != nil {
  100. return err
  101. }
  102. }
  103. if err := container.ToDiskLocking(); err != nil {
  104. return fmt.Errorf("Error saving container to disk: %v", err)
  105. }
  106. return nil
  107. }
  108. // DisconnectFromNetwork disconnects container from network n.
  109. func (daemon *Daemon) DisconnectFromNetwork(container *container.Container, n libnetwork.Network, force bool) error {
  110. if container.HostConfig.NetworkMode.IsHost() && containertypes.NetworkMode(n.Type()).IsHost() {
  111. return runconfig.ErrConflictHostNetwork
  112. }
  113. if !container.Running {
  114. if container.RemovalInProgress || container.Dead {
  115. return errRemovalContainer(container.ID)
  116. }
  117. if _, ok := container.NetworkSettings.Networks[n.Name()]; ok {
  118. delete(container.NetworkSettings.Networks, n.Name())
  119. } else {
  120. return fmt.Errorf("container %s is not connected to the network %s", container.ID, n.Name())
  121. }
  122. } else {
  123. if err := disconnectFromNetwork(container, n, false); err != nil {
  124. return err
  125. }
  126. }
  127. if err := container.ToDiskLocking(); err != nil {
  128. return fmt.Errorf("Error saving container to disk: %v", err)
  129. }
  130. attributes := map[string]string{
  131. "container": container.ID,
  132. }
  133. daemon.LogNetworkEventWithAttributes(n, "disconnect", attributes)
  134. return nil
  135. }
  136. func (daemon *Daemon) getIpcContainer(container *container.Container) (*container.Container, error) {
  137. containerID := container.HostConfig.IpcMode.Container()
  138. c, err := daemon.GetContainer(containerID)
  139. if err != nil {
  140. return nil, err
  141. }
  142. if !c.IsRunning() {
  143. return nil, fmt.Errorf("cannot join IPC of a non running container: %s", containerID)
  144. }
  145. if c.IsRestarting() {
  146. return nil, errContainerIsRestarting(container.ID)
  147. }
  148. return c, nil
  149. }
  150. func (daemon *Daemon) setupIpcDirs(c *container.Container) error {
  151. var err error
  152. c.ShmPath, err = c.ShmResourcePath()
  153. if err != nil {
  154. return err
  155. }
  156. if c.HostConfig.IpcMode.IsContainer() {
  157. ic, err := daemon.getIpcContainer(c)
  158. if err != nil {
  159. return err
  160. }
  161. c.ShmPath = ic.ShmPath
  162. } else if c.HostConfig.IpcMode.IsHost() {
  163. if _, err := os.Stat("/dev/shm"); err != nil {
  164. return fmt.Errorf("/dev/shm is not mounted, but must be for --ipc=host")
  165. }
  166. c.ShmPath = "/dev/shm"
  167. } else {
  168. rootUID, rootGID := daemon.GetRemappedUIDGID()
  169. if !c.HasMountFor("/dev/shm") {
  170. shmPath, err := c.ShmResourcePath()
  171. if err != nil {
  172. return err
  173. }
  174. if err := idtools.MkdirAllAs(shmPath, 0700, rootUID, rootGID); err != nil {
  175. return err
  176. }
  177. shmSize := container.DefaultSHMSize
  178. if c.HostConfig.ShmSize != 0 {
  179. shmSize = c.HostConfig.ShmSize
  180. }
  181. shmproperty := "mode=1777,size=" + strconv.FormatInt(shmSize, 10)
  182. if err := syscall.Mount("shm", shmPath, "tmpfs", uintptr(syscall.MS_NOEXEC|syscall.MS_NOSUID|syscall.MS_NODEV), label.FormatMountLabel(shmproperty, c.GetMountLabel())); err != nil {
  183. return fmt.Errorf("mounting shm tmpfs: %s", err)
  184. }
  185. if err := os.Chown(shmPath, rootUID, rootGID); err != nil {
  186. return err
  187. }
  188. }
  189. }
  190. return nil
  191. }
  192. func (daemon *Daemon) mountVolumes(container *container.Container) error {
  193. mounts, err := daemon.setupMounts(container)
  194. if err != nil {
  195. return err
  196. }
  197. for _, m := range mounts {
  198. dest, err := container.GetResourcePath(m.Destination)
  199. if err != nil {
  200. return err
  201. }
  202. var stat os.FileInfo
  203. stat, err = os.Stat(m.Source)
  204. if err != nil {
  205. return err
  206. }
  207. if err = fileutils.CreateIfNotExists(dest, stat.IsDir()); err != nil {
  208. return err
  209. }
  210. opts := "rbind,ro"
  211. if m.Writable {
  212. opts = "rbind,rw"
  213. }
  214. if err := mount.Mount(m.Source, dest, "bind", opts); err != nil {
  215. return err
  216. }
  217. }
  218. return nil
  219. }
  220. func killProcessDirectly(container *container.Container) error {
  221. if _, err := container.WaitStop(10 * time.Second); err != nil {
  222. // Ensure that we don't kill ourselves
  223. if pid := container.GetPID(); pid != 0 {
  224. logrus.Infof("Container %s failed to exit within 10 seconds of kill - trying direct SIGKILL", stringid.TruncateID(container.ID))
  225. if err := syscall.Kill(pid, 9); err != nil {
  226. if err != syscall.ESRCH {
  227. return err
  228. }
  229. e := errNoSuchProcess{pid, 9}
  230. logrus.Debug(e)
  231. return e
  232. }
  233. }
  234. }
  235. return nil
  236. }
  237. func specDevice(d *configs.Device) specs.Device {
  238. return specs.Device{
  239. Type: string(d.Type),
  240. Path: d.Path,
  241. Major: d.Major,
  242. Minor: d.Minor,
  243. FileMode: fmPtr(int64(d.FileMode)),
  244. UID: u32Ptr(int64(d.Uid)),
  245. GID: u32Ptr(int64(d.Gid)),
  246. }
  247. }
  248. func specDeviceCgroup(d *configs.Device) specs.DeviceCgroup {
  249. t := string(d.Type)
  250. return specs.DeviceCgroup{
  251. Allow: true,
  252. Type: &t,
  253. Major: &d.Major,
  254. Minor: &d.Minor,
  255. Access: &d.Permissions,
  256. }
  257. }
  258. func getDevicesFromPath(deviceMapping containertypes.DeviceMapping) (devs []specs.Device, devPermissions []specs.DeviceCgroup, err error) {
  259. resolvedPathOnHost := deviceMapping.PathOnHost
  260. // check if it is a symbolic link
  261. if src, e := os.Lstat(deviceMapping.PathOnHost); e == nil && src.Mode()&os.ModeSymlink == os.ModeSymlink {
  262. if linkedPathOnHost, e := os.Readlink(deviceMapping.PathOnHost); e == nil {
  263. resolvedPathOnHost = linkedPathOnHost
  264. }
  265. }
  266. device, err := devices.DeviceFromPath(resolvedPathOnHost, deviceMapping.CgroupPermissions)
  267. // if there was no error, return the device
  268. if err == nil {
  269. device.Path = deviceMapping.PathInContainer
  270. return append(devs, specDevice(device)), append(devPermissions, specDeviceCgroup(device)), nil
  271. }
  272. // if the device is not a device node
  273. // try to see if it's a directory holding many devices
  274. if err == devices.ErrNotADevice {
  275. // check if it is a directory
  276. if src, e := os.Stat(resolvedPathOnHost); e == nil && src.IsDir() {
  277. // mount the internal devices recursively
  278. filepath.Walk(resolvedPathOnHost, func(dpath string, f os.FileInfo, e error) error {
  279. childDevice, e := devices.DeviceFromPath(dpath, deviceMapping.CgroupPermissions)
  280. if e != nil {
  281. // ignore the device
  282. return nil
  283. }
  284. // add the device to userSpecified devices
  285. childDevice.Path = strings.Replace(dpath, resolvedPathOnHost, deviceMapping.PathInContainer, 1)
  286. devs = append(devs, specDevice(childDevice))
  287. devPermissions = append(devPermissions, specDeviceCgroup(childDevice))
  288. return nil
  289. })
  290. }
  291. }
  292. if len(devs) > 0 {
  293. return devs, devPermissions, nil
  294. }
  295. return devs, devPermissions, fmt.Errorf("error gathering device information while adding custom device %q: %s", deviceMapping.PathOnHost, err)
  296. }
  297. func detachMounted(path string) error {
  298. return syscall.Unmount(path, syscall.MNT_DETACH)
  299. }
  300. func isLinkable(child *container.Container) bool {
  301. // A container is linkable only if it belongs to the default network
  302. _, ok := child.NetworkSettings.Networks[runconfig.DefaultDaemonNetworkMode().NetworkName()]
  303. return ok
  304. }
  305. func errRemovalContainer(containerID string) error {
  306. return fmt.Errorf("Container %s is marked for removal and cannot be connected or disconnected to the network", containerID)
  307. }