volumes_unix.go 12 KB

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