container_operations_unix.go 12 KB

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