volumes_unix.go 10 KB

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