volumes_unix.go 11 KB

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