volumes_unix.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. // +build !windows
  2. package daemon
  3. import (
  4. "fmt"
  5. "io/ioutil"
  6. "os"
  7. "path/filepath"
  8. "sort"
  9. "strings"
  10. "github.com/Sirupsen/logrus"
  11. "github.com/docker/docker/daemon/execdriver"
  12. "github.com/docker/docker/pkg/system"
  13. "github.com/docker/docker/runconfig"
  14. "github.com/docker/docker/volume"
  15. volumedrivers "github.com/docker/docker/volume/drivers"
  16. "github.com/docker/docker/volume/local"
  17. "github.com/opencontainers/runc/libcontainer/label"
  18. )
  19. // copyOwnership copies the permissions and uid:gid of the source file
  20. // to the destination file
  21. func copyOwnership(source, destination string) error {
  22. stat, err := system.Stat(source)
  23. if err != nil {
  24. return err
  25. }
  26. if err := os.Chown(destination, int(stat.UID()), int(stat.Gid())); err != nil {
  27. return err
  28. }
  29. return os.Chmod(destination, os.FileMode(stat.Mode()))
  30. }
  31. // setupMounts iterates through each of the mount points for a container and
  32. // calls Setup() on each. It also looks to see if is a network mount such as
  33. // /etc/resolv.conf, and if it is not, appends it to the array of mounts.
  34. func (container *Container) setupMounts() ([]execdriver.Mount, error) {
  35. var mounts []execdriver.Mount
  36. for _, m := range container.MountPoints {
  37. path, err := m.Setup()
  38. if err != nil {
  39. return nil, err
  40. }
  41. if !container.trySetNetworkMount(m.Destination, path) {
  42. mounts = append(mounts, execdriver.Mount{
  43. Source: path,
  44. Destination: m.Destination,
  45. Writable: m.RW,
  46. })
  47. }
  48. }
  49. mounts = sortMounts(mounts)
  50. return append(mounts, container.networkMounts()...), nil
  51. }
  52. // parseBindMount validates the configuration of mount information in runconfig is valid.
  53. func parseBindMount(spec string, mountLabel string, config *runconfig.Config) (*mountPoint, error) {
  54. bind := &mountPoint{
  55. RW: true,
  56. }
  57. arr := strings.Split(spec, ":")
  58. switch len(arr) {
  59. case 2:
  60. bind.Destination = arr[1]
  61. case 3:
  62. bind.Destination = arr[1]
  63. mode := arr[2]
  64. if !volume.ValidMountMode(mode) {
  65. return nil, fmt.Errorf("invalid mode for volumes-from: %s", mode)
  66. }
  67. bind.RW = volume.ReadWrite(mode)
  68. // Mode field is used by SELinux to decide whether to apply label
  69. bind.Mode = mode
  70. default:
  71. return nil, fmt.Errorf("Invalid volume specification: %s", spec)
  72. }
  73. name, source, err := parseVolumeSource(arr[0])
  74. if err != nil {
  75. return nil, err
  76. }
  77. if len(source) == 0 {
  78. bind.Driver = config.VolumeDriver
  79. if len(bind.Driver) == 0 {
  80. bind.Driver = volume.DefaultDriverName
  81. }
  82. } else {
  83. bind.Source = filepath.Clean(source)
  84. }
  85. bind.Name = name
  86. bind.Destination = filepath.Clean(bind.Destination)
  87. return bind, nil
  88. }
  89. // sortMounts sorts an array of mounts in lexicographic order. This ensure that
  90. // when mounting, the mounts don't shadow other mounts. For example, if mounting
  91. // /etc and /etc/resolv.conf, /etc/resolv.conf must not be mounted first.
  92. func sortMounts(m []execdriver.Mount) []execdriver.Mount {
  93. sort.Sort(mounts(m))
  94. return m
  95. }
  96. type mounts []execdriver.Mount
  97. // Len returns the number of mounts
  98. func (m mounts) Len() int {
  99. return len(m)
  100. }
  101. // Less returns true if the number of parts (a/b/c would be 3 parts) in the
  102. // mount indexed by parameter 1 is less than that of the mount indexed by
  103. // parameter 2.
  104. func (m mounts) Less(i, j int) bool {
  105. return m.parts(i) < m.parts(j)
  106. }
  107. // Swap swaps two items in an array of mounts.
  108. func (m mounts) Swap(i, j int) {
  109. m[i], m[j] = m[j], m[i]
  110. }
  111. // parts returns the number of parts in the destination of a mount.
  112. func (m mounts) parts(i int) int {
  113. return len(strings.Split(filepath.Clean(m[i].Destination), string(os.PathSeparator)))
  114. }
  115. // migrateVolume links the contents of a volume created pre Docker 1.7
  116. // into the location expected by the local driver.
  117. // It creates a symlink from DOCKER_ROOT/vfs/dir/VOLUME_ID to DOCKER_ROOT/volumes/VOLUME_ID/_container_data.
  118. // It preserves the volume json configuration generated pre Docker 1.7 to be able to
  119. // downgrade from Docker 1.7 to Docker 1.6 without losing volume compatibility.
  120. func migrateVolume(id, vfs string) error {
  121. l, err := volumedrivers.Lookup(volume.DefaultDriverName)
  122. if err != nil {
  123. return err
  124. }
  125. newDataPath := l.(*local.Root).DataPath(id)
  126. fi, err := os.Stat(newDataPath)
  127. if err != nil && !os.IsNotExist(err) {
  128. return err
  129. }
  130. if fi != nil && fi.IsDir() {
  131. return nil
  132. }
  133. return os.Symlink(vfs, newDataPath)
  134. }
  135. // validVolumeLayout checks whether the volume directory layout
  136. // is valid to work with Docker post 1.7 or not.
  137. func validVolumeLayout(files []os.FileInfo) bool {
  138. if len(files) == 1 && files[0].Name() == local.VolumeDataPathName && files[0].IsDir() {
  139. return true
  140. }
  141. if len(files) != 2 {
  142. return false
  143. }
  144. for _, f := range files {
  145. if f.Name() == "config.json" ||
  146. (f.Name() == local.VolumeDataPathName && f.Mode()&os.ModeSymlink == os.ModeSymlink) {
  147. // Old volume configuration, we ignore it
  148. continue
  149. }
  150. return false
  151. }
  152. return true
  153. }
  154. // verifyVolumesInfo ports volumes configured for the containers pre docker 1.7.
  155. // It reads the container configuration and creates valid mount points for the old volumes.
  156. func (daemon *Daemon) verifyVolumesInfo(container *Container) error {
  157. // Inspect old structures only when we're upgrading from old versions
  158. // to versions >= 1.7 and the MountPoints has not been populated with volumes data.
  159. if len(container.MountPoints) == 0 && len(container.Volumes) > 0 {
  160. for destination, hostPath := range container.Volumes {
  161. vfsPath := filepath.Join(daemon.root, "vfs", "dir")
  162. rw := container.VolumesRW != nil && container.VolumesRW[destination]
  163. if strings.HasPrefix(hostPath, vfsPath) {
  164. id := filepath.Base(hostPath)
  165. if err := migrateVolume(id, hostPath); err != nil {
  166. return err
  167. }
  168. container.addLocalMountPoint(id, destination, rw)
  169. } else { // Bind mount
  170. id, source, err := parseVolumeSource(hostPath)
  171. // We should not find an error here coming
  172. // from the old configuration, but who knows.
  173. if err != nil {
  174. return err
  175. }
  176. container.addBindMountPoint(id, source, destination, rw)
  177. }
  178. }
  179. } else if len(container.MountPoints) > 0 {
  180. // Volumes created with a Docker version >= 1.7. We verify integrity in case of data created
  181. // with Docker 1.7 RC versions that put the information in
  182. // DOCKER_ROOT/volumes/VOLUME_ID rather than DOCKER_ROOT/volumes/VOLUME_ID/_container_data.
  183. l, err := volumedrivers.Lookup(volume.DefaultDriverName)
  184. if err != nil {
  185. return err
  186. }
  187. for _, m := range container.MountPoints {
  188. if m.Driver != volume.DefaultDriverName {
  189. continue
  190. }
  191. dataPath := l.(*local.Root).DataPath(m.Name)
  192. volumePath := filepath.Dir(dataPath)
  193. d, err := ioutil.ReadDir(volumePath)
  194. if err != nil {
  195. // If the volume directory doesn't exist yet it will be recreated,
  196. // so we only return the error when there is a different issue.
  197. if !os.IsNotExist(err) {
  198. return err
  199. }
  200. // Do not check when the volume directory does not exist.
  201. continue
  202. }
  203. if validVolumeLayout(d) {
  204. continue
  205. }
  206. if err := os.Mkdir(dataPath, 0755); err != nil {
  207. return err
  208. }
  209. // Move data inside the data directory
  210. for _, f := range d {
  211. oldp := filepath.Join(volumePath, f.Name())
  212. newp := filepath.Join(dataPath, f.Name())
  213. if err := os.Rename(oldp, newp); err != nil {
  214. logrus.Errorf("Unable to move %s to %s\n", oldp, newp)
  215. }
  216. }
  217. }
  218. return container.ToDisk()
  219. }
  220. return nil
  221. }
  222. // parseVolumesFrom ensure that the supplied volumes-from is valid.
  223. func parseVolumesFrom(spec string) (string, string, error) {
  224. if len(spec) == 0 {
  225. return "", "", fmt.Errorf("malformed volumes-from specification: %s", spec)
  226. }
  227. specParts := strings.SplitN(spec, ":", 2)
  228. id := specParts[0]
  229. mode := "rw"
  230. if len(specParts) == 2 {
  231. mode = specParts[1]
  232. if !volume.ValidMountMode(mode) {
  233. return "", "", fmt.Errorf("invalid mode for volumes-from: %s", mode)
  234. }
  235. }
  236. return id, mode, nil
  237. }
  238. // registerMountPoints initializes the container mount points with the configured volumes and bind mounts.
  239. // It follows the next sequence to decide what to mount in each final destination:
  240. //
  241. // 1. Select the previously configured mount points for the containers, if any.
  242. // 2. Select the volumes mounted from another containers. Overrides previously configured mount point destination.
  243. // 3. Select the bind mounts set by the client. Overrides previously configured mount point destinations.
  244. func (daemon *Daemon) registerMountPoints(container *Container, hostConfig *runconfig.HostConfig) error {
  245. binds := map[string]bool{}
  246. mountPoints := map[string]*mountPoint{}
  247. // 1. Read already configured mount points.
  248. for name, point := range container.MountPoints {
  249. mountPoints[name] = point
  250. }
  251. // 2. Read volumes from other containers.
  252. for _, v := range hostConfig.VolumesFrom {
  253. containerID, mode, err := parseVolumesFrom(v)
  254. if err != nil {
  255. return err
  256. }
  257. c, err := daemon.Get(containerID)
  258. if err != nil {
  259. return err
  260. }
  261. for _, m := range c.MountPoints {
  262. cp := &mountPoint{
  263. Name: m.Name,
  264. Source: m.Source,
  265. RW: m.RW && volume.ReadWrite(mode),
  266. Driver: m.Driver,
  267. Destination: m.Destination,
  268. }
  269. if len(cp.Source) == 0 {
  270. v, err := daemon.createVolume(cp.Name, cp.Driver, nil)
  271. if err != nil {
  272. return err
  273. }
  274. cp.Volume = v
  275. }
  276. mountPoints[cp.Destination] = cp
  277. }
  278. }
  279. // 3. Read bind mounts
  280. for _, b := range hostConfig.Binds {
  281. // #10618
  282. bind, err := parseBindMount(b, container.MountLabel, container.Config)
  283. if err != nil {
  284. return err
  285. }
  286. if binds[bind.Destination] {
  287. return fmt.Errorf("Duplicate bind mount %s", bind.Destination)
  288. }
  289. if len(bind.Name) > 0 && len(bind.Driver) > 0 {
  290. // create the volume
  291. v, err := daemon.createVolume(bind.Name, bind.Driver, nil)
  292. if err != nil {
  293. return err
  294. }
  295. bind.Volume = v
  296. bind.Source = v.Path()
  297. // Since this is just a named volume and not a typical bind, set to shared mode `z`
  298. if bind.Mode == "" {
  299. bind.Mode = "z"
  300. }
  301. }
  302. if err := label.Relabel(bind.Source, container.MountLabel, bind.Mode); err != nil {
  303. return err
  304. }
  305. binds[bind.Destination] = true
  306. mountPoints[bind.Destination] = bind
  307. }
  308. // Keep backwards compatible structures
  309. bcVolumes := map[string]string{}
  310. bcVolumesRW := map[string]bool{}
  311. for _, m := range mountPoints {
  312. if m.BackwardsCompatible() {
  313. bcVolumes[m.Destination] = m.Path()
  314. bcVolumesRW[m.Destination] = m.RW
  315. // This mountpoint is replacing an existing one, so the count needs to be decremented
  316. if mp, exists := container.MountPoints[m.Destination]; exists && mp.Volume != nil {
  317. daemon.volumes.Decrement(mp.Volume)
  318. }
  319. }
  320. }
  321. container.Lock()
  322. container.MountPoints = mountPoints
  323. container.Volumes = bcVolumes
  324. container.VolumesRW = bcVolumesRW
  325. container.Unlock()
  326. return nil
  327. }
  328. // createVolume creates a volume.
  329. func (daemon *Daemon) createVolume(name, driverName string, opts map[string]string) (volume.Volume, error) {
  330. v, err := daemon.volumes.Create(name, driverName, opts)
  331. if err != nil {
  332. return nil, err
  333. }
  334. daemon.volumes.Increment(v)
  335. return v, nil
  336. }
  337. // parseVolumeSource parses the origin sources that's mounted into the container.
  338. func parseVolumeSource(spec string) (string, string, error) {
  339. if !filepath.IsAbs(spec) {
  340. return spec, "", nil
  341. }
  342. return "", spec, nil
  343. }
  344. // BackwardsCompatible decides whether this mount point can be
  345. // used in old versions of Docker or not.
  346. // Only bind mounts and local volumes can be used in old versions of Docker.
  347. func (m *mountPoint) BackwardsCompatible() bool {
  348. return len(m.Source) > 0 || m.Driver == volume.DefaultDriverName
  349. }