volumes_unix.go 12 KB

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