container_operations_unix.go 11 KB

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