container_operations_unix.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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) getPidContainer(container *container.Container) (*container.Container, error) {
  152. containerID := container.HostConfig.PidMode.Container()
  153. c, err := daemon.GetContainer(containerID)
  154. if err != nil {
  155. return nil, err
  156. }
  157. if !c.IsRunning() {
  158. return nil, fmt.Errorf("cannot join PID of a non running container: %s", containerID)
  159. }
  160. if c.IsRestarting() {
  161. return nil, errContainerIsRestarting(container.ID)
  162. }
  163. return c, nil
  164. }
  165. func (daemon *Daemon) setupIpcDirs(c *container.Container) error {
  166. var err error
  167. c.ShmPath, err = c.ShmResourcePath()
  168. if err != nil {
  169. return err
  170. }
  171. if c.HostConfig.IpcMode.IsContainer() {
  172. ic, err := daemon.getIpcContainer(c)
  173. if err != nil {
  174. return err
  175. }
  176. c.ShmPath = ic.ShmPath
  177. } else if c.HostConfig.IpcMode.IsHost() {
  178. if _, err := os.Stat("/dev/shm"); err != nil {
  179. return fmt.Errorf("/dev/shm is not mounted, but must be for --ipc=host")
  180. }
  181. c.ShmPath = "/dev/shm"
  182. } else {
  183. rootUID, rootGID := daemon.GetRemappedUIDGID()
  184. if !c.HasMountFor("/dev/shm") {
  185. shmPath, err := c.ShmResourcePath()
  186. if err != nil {
  187. return err
  188. }
  189. if err := idtools.MkdirAllAs(shmPath, 0700, rootUID, rootGID); err != nil {
  190. return err
  191. }
  192. shmSize := container.DefaultSHMSize
  193. if c.HostConfig.ShmSize != 0 {
  194. shmSize = c.HostConfig.ShmSize
  195. }
  196. shmproperty := "mode=1777,size=" + strconv.FormatInt(shmSize, 10)
  197. if err := syscall.Mount("shm", shmPath, "tmpfs", uintptr(syscall.MS_NOEXEC|syscall.MS_NOSUID|syscall.MS_NODEV), label.FormatMountLabel(shmproperty, c.GetMountLabel())); err != nil {
  198. return fmt.Errorf("mounting shm tmpfs: %s", err)
  199. }
  200. if err := os.Chown(shmPath, rootUID, rootGID); err != nil {
  201. return err
  202. }
  203. }
  204. }
  205. return nil
  206. }
  207. func (daemon *Daemon) mountVolumes(container *container.Container) error {
  208. mounts, err := daemon.setupMounts(container)
  209. if err != nil {
  210. return err
  211. }
  212. for _, m := range mounts {
  213. dest, err := container.GetResourcePath(m.Destination)
  214. if err != nil {
  215. return err
  216. }
  217. var stat os.FileInfo
  218. stat, err = os.Stat(m.Source)
  219. if err != nil {
  220. return err
  221. }
  222. if err = fileutils.CreateIfNotExists(dest, stat.IsDir()); err != nil {
  223. return err
  224. }
  225. opts := "rbind,ro"
  226. if m.Writable {
  227. opts = "rbind,rw"
  228. }
  229. if err := mount.Mount(m.Source, dest, "bind", opts); err != nil {
  230. return err
  231. }
  232. // mountVolumes() seems to be called for temporary mounts
  233. // outside the container. Soon these will be unmounted with
  234. // lazy unmount option and given we have mounted the rbind,
  235. // all the submounts will propagate if these are shared. If
  236. // daemon is running in host namespace and has / as shared
  237. // then these unmounts will propagate and unmount original
  238. // mount as well. So make all these mounts rprivate.
  239. // Do not use propagation property of volume as that should
  240. // apply only when mounting happen inside the container.
  241. if err := mount.MakeRPrivate(dest); err != nil {
  242. return err
  243. }
  244. }
  245. return nil
  246. }
  247. func killProcessDirectly(container *container.Container) error {
  248. if _, err := container.WaitStop(10 * time.Second); err != nil {
  249. // Ensure that we don't kill ourselves
  250. if pid := container.GetPID(); pid != 0 {
  251. logrus.Infof("Container %s failed to exit within 10 seconds of kill - trying direct SIGKILL", stringid.TruncateID(container.ID))
  252. if err := syscall.Kill(pid, 9); err != nil {
  253. if err != syscall.ESRCH {
  254. return err
  255. }
  256. e := errNoSuchProcess{pid, 9}
  257. logrus.Debug(e)
  258. return e
  259. }
  260. }
  261. }
  262. return nil
  263. }
  264. func specDevice(d *configs.Device) specs.Device {
  265. return specs.Device{
  266. Type: string(d.Type),
  267. Path: d.Path,
  268. Major: d.Major,
  269. Minor: d.Minor,
  270. FileMode: fmPtr(int64(d.FileMode)),
  271. UID: u32Ptr(int64(d.Uid)),
  272. GID: u32Ptr(int64(d.Gid)),
  273. }
  274. }
  275. func specDeviceCgroup(d *configs.Device) specs.DeviceCgroup {
  276. t := string(d.Type)
  277. return specs.DeviceCgroup{
  278. Allow: true,
  279. Type: &t,
  280. Major: &d.Major,
  281. Minor: &d.Minor,
  282. Access: &d.Permissions,
  283. }
  284. }
  285. func getDevicesFromPath(deviceMapping containertypes.DeviceMapping) (devs []specs.Device, devPermissions []specs.DeviceCgroup, err error) {
  286. resolvedPathOnHost := deviceMapping.PathOnHost
  287. // check if it is a symbolic link
  288. if src, e := os.Lstat(deviceMapping.PathOnHost); e == nil && src.Mode()&os.ModeSymlink == os.ModeSymlink {
  289. if linkedPathOnHost, e := filepath.EvalSymlinks(deviceMapping.PathOnHost); e == nil {
  290. resolvedPathOnHost = linkedPathOnHost
  291. }
  292. }
  293. device, err := devices.DeviceFromPath(resolvedPathOnHost, deviceMapping.CgroupPermissions)
  294. // if there was no error, return the device
  295. if err == nil {
  296. device.Path = deviceMapping.PathInContainer
  297. return append(devs, specDevice(device)), append(devPermissions, specDeviceCgroup(device)), nil
  298. }
  299. // if the device is not a device node
  300. // try to see if it's a directory holding many devices
  301. if err == devices.ErrNotADevice {
  302. // check if it is a directory
  303. if src, e := os.Stat(resolvedPathOnHost); e == nil && src.IsDir() {
  304. // mount the internal devices recursively
  305. filepath.Walk(resolvedPathOnHost, func(dpath string, f os.FileInfo, e error) error {
  306. childDevice, e := devices.DeviceFromPath(dpath, deviceMapping.CgroupPermissions)
  307. if e != nil {
  308. // ignore the device
  309. return nil
  310. }
  311. // add the device to userSpecified devices
  312. childDevice.Path = strings.Replace(dpath, resolvedPathOnHost, deviceMapping.PathInContainer, 1)
  313. devs = append(devs, specDevice(childDevice))
  314. devPermissions = append(devPermissions, specDeviceCgroup(childDevice))
  315. return nil
  316. })
  317. }
  318. }
  319. if len(devs) > 0 {
  320. return devs, devPermissions, nil
  321. }
  322. return devs, devPermissions, fmt.Errorf("error gathering device information while adding custom device %q: %s", deviceMapping.PathOnHost, err)
  323. }
  324. func detachMounted(path string) error {
  325. return syscall.Unmount(path, syscall.MNT_DETACH)
  326. }
  327. func isLinkable(child *container.Container) bool {
  328. // A container is linkable only if it belongs to the default network
  329. _, ok := child.NetworkSettings.Networks[runconfig.DefaultDaemonNetworkMode().NetworkName()]
  330. return ok
  331. }
  332. func errRemovalContainer(containerID string) error {
  333. return fmt.Errorf("Container %s is marked for removal and cannot be connected or disconnected to the network", containerID)
  334. }