container_operations_unix.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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. // called from the libcontainer pre-start hook to set the network
  137. // namespace configuration linkage to the libnetwork "sandbox" entity
  138. func (daemon *Daemon) setNetworkNamespaceKey(containerID string, pid int) error {
  139. path := fmt.Sprintf("/proc/%d/ns/net", pid)
  140. var sandbox libnetwork.Sandbox
  141. search := libnetwork.SandboxContainerWalker(&sandbox, containerID)
  142. daemon.netController.WalkSandboxes(search)
  143. if sandbox == nil {
  144. return fmt.Errorf("error locating sandbox id %s: no sandbox found", containerID)
  145. }
  146. return sandbox.SetKey(path)
  147. }
  148. func (daemon *Daemon) getIpcContainer(container *container.Container) (*container.Container, error) {
  149. containerID := container.HostConfig.IpcMode.Container()
  150. c, err := daemon.GetContainer(containerID)
  151. if err != nil {
  152. return nil, err
  153. }
  154. if !c.IsRunning() {
  155. return nil, fmt.Errorf("cannot join IPC of a non running container: %s", containerID)
  156. }
  157. if c.IsRestarting() {
  158. return nil, errContainerIsRestarting(container.ID)
  159. }
  160. return c, nil
  161. }
  162. func (daemon *Daemon) setupIpcDirs(c *container.Container) error {
  163. var err error
  164. c.ShmPath, err = c.ShmResourcePath()
  165. if err != nil {
  166. return err
  167. }
  168. if c.HostConfig.IpcMode.IsContainer() {
  169. ic, err := daemon.getIpcContainer(c)
  170. if err != nil {
  171. return err
  172. }
  173. c.ShmPath = ic.ShmPath
  174. } else if c.HostConfig.IpcMode.IsHost() {
  175. if _, err := os.Stat("/dev/shm"); err != nil {
  176. return fmt.Errorf("/dev/shm is not mounted, but must be for --ipc=host")
  177. }
  178. c.ShmPath = "/dev/shm"
  179. } else {
  180. rootUID, rootGID := daemon.GetRemappedUIDGID()
  181. if !c.HasMountFor("/dev/shm") {
  182. shmPath, err := c.ShmResourcePath()
  183. if err != nil {
  184. return err
  185. }
  186. if err := idtools.MkdirAllAs(shmPath, 0700, rootUID, rootGID); err != nil {
  187. return err
  188. }
  189. shmSize := container.DefaultSHMSize
  190. if c.HostConfig.ShmSize != 0 {
  191. shmSize = c.HostConfig.ShmSize
  192. }
  193. shmproperty := "mode=1777,size=" + strconv.FormatInt(shmSize, 10)
  194. if err := syscall.Mount("shm", shmPath, "tmpfs", uintptr(syscall.MS_NOEXEC|syscall.MS_NOSUID|syscall.MS_NODEV), label.FormatMountLabel(shmproperty, c.GetMountLabel())); err != nil {
  195. return fmt.Errorf("mounting shm tmpfs: %s", err)
  196. }
  197. if err := os.Chown(shmPath, rootUID, rootGID); err != nil {
  198. return err
  199. }
  200. }
  201. }
  202. return nil
  203. }
  204. func (daemon *Daemon) mountVolumes(container *container.Container) error {
  205. mounts, err := daemon.setupMounts(container)
  206. if err != nil {
  207. return err
  208. }
  209. for _, m := range mounts {
  210. dest, err := container.GetResourcePath(m.Destination)
  211. if err != nil {
  212. return err
  213. }
  214. var stat os.FileInfo
  215. stat, err = os.Stat(m.Source)
  216. if err != nil {
  217. return err
  218. }
  219. if err = fileutils.CreateIfNotExists(dest, stat.IsDir()); err != nil {
  220. return err
  221. }
  222. opts := "rbind,ro"
  223. if m.Writable {
  224. opts = "rbind,rw"
  225. }
  226. if err := mount.Mount(m.Source, dest, "bind", opts); err != nil {
  227. return err
  228. }
  229. }
  230. return nil
  231. }
  232. func killProcessDirectly(container *container.Container) error {
  233. if _, err := container.WaitStop(10 * time.Second); err != nil {
  234. // Ensure that we don't kill ourselves
  235. if pid := container.GetPID(); pid != 0 {
  236. logrus.Infof("Container %s failed to exit within 10 seconds of kill - trying direct SIGKILL", stringid.TruncateID(container.ID))
  237. if err := syscall.Kill(pid, 9); err != nil {
  238. if err != syscall.ESRCH {
  239. return err
  240. }
  241. e := errNoSuchProcess{pid, 9}
  242. logrus.Debug(e)
  243. return e
  244. }
  245. }
  246. }
  247. return nil
  248. }
  249. func specDevice(d *configs.Device) specs.Device {
  250. return specs.Device{
  251. Type: string(d.Type),
  252. Path: d.Path,
  253. Major: d.Major,
  254. Minor: d.Minor,
  255. FileMode: fmPtr(int64(d.FileMode)),
  256. UID: u32Ptr(int64(d.Uid)),
  257. GID: u32Ptr(int64(d.Gid)),
  258. }
  259. }
  260. func getDevicesFromPath(deviceMapping containertypes.DeviceMapping) (devs []specs.Device, err error) {
  261. resolvedPathOnHost := deviceMapping.PathOnHost
  262. // check if it is a symbolic link
  263. if src, e := os.Lstat(deviceMapping.PathOnHost); e == nil && src.Mode()&os.ModeSymlink == os.ModeSymlink {
  264. if linkedPathOnHost, e := os.Readlink(deviceMapping.PathOnHost); e == nil {
  265. resolvedPathOnHost = linkedPathOnHost
  266. }
  267. }
  268. device, err := devices.DeviceFromPath(resolvedPathOnHost, deviceMapping.CgroupPermissions)
  269. // if there was no error, return the device
  270. if err == nil {
  271. device.Path = deviceMapping.PathInContainer
  272. return append(devs, specDevice(device)), nil
  273. }
  274. // if the device is not a device node
  275. // try to see if it's a directory holding many devices
  276. if err == devices.ErrNotADevice {
  277. // check if it is a directory
  278. if src, e := os.Stat(resolvedPathOnHost); e == nil && src.IsDir() {
  279. // mount the internal devices recursively
  280. filepath.Walk(resolvedPathOnHost, func(dpath string, f os.FileInfo, e error) error {
  281. childDevice, e := devices.DeviceFromPath(dpath, deviceMapping.CgroupPermissions)
  282. if e != nil {
  283. // ignore the device
  284. return nil
  285. }
  286. // add the device to userSpecified devices
  287. childDevice.Path = strings.Replace(dpath, resolvedPathOnHost, deviceMapping.PathInContainer, 1)
  288. devs = append(devs, specDevice(childDevice))
  289. return nil
  290. })
  291. }
  292. }
  293. if len(devs) > 0 {
  294. return devs, nil
  295. }
  296. return devs, fmt.Errorf("error gathering device information while adding custom device %q: %s", deviceMapping.PathOnHost, err)
  297. }
  298. func mergeDevices(defaultDevices, userDevices []*configs.Device) []*configs.Device {
  299. if len(userDevices) == 0 {
  300. return defaultDevices
  301. }
  302. paths := map[string]*configs.Device{}
  303. for _, d := range userDevices {
  304. paths[d.Path] = d
  305. }
  306. var devs []*configs.Device
  307. for _, d := range defaultDevices {
  308. if _, defined := paths[d.Path]; !defined {
  309. devs = append(devs, d)
  310. }
  311. }
  312. return append(devs, userDevices...)
  313. }
  314. func detachMounted(path string) error {
  315. return syscall.Unmount(path, syscall.MNT_DETACH)
  316. }
  317. func isLinkable(child *container.Container) bool {
  318. // A container is linkable only if it belongs to the default network
  319. _, ok := child.NetworkSettings.Networks[runconfig.DefaultDaemonNetworkMode().NetworkName()]
  320. return ok
  321. }
  322. func errRemovalContainer(containerID string) error {
  323. return fmt.Errorf("Container %s is marked for removal and cannot be connected or disconnected to the network", containerID)
  324. }