volumes.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. package daemon
  2. import (
  3. "fmt"
  4. "io"
  5. "io/ioutil"
  6. "os"
  7. "path/filepath"
  8. "sort"
  9. "strings"
  10. "syscall"
  11. log "github.com/Sirupsen/logrus"
  12. "github.com/docker/docker/daemon/execdriver"
  13. "github.com/docker/docker/pkg/chrootarchive"
  14. "github.com/docker/docker/pkg/symlink"
  15. "github.com/docker/docker/volumes"
  16. "github.com/docker/libcontainer/label"
  17. )
  18. type Mount struct {
  19. MountToPath string
  20. container *Container
  21. volume *volumes.Volume
  22. Writable bool
  23. copyData bool
  24. from *Container
  25. }
  26. func (mnt *Mount) Export(resource string) (io.ReadCloser, error) {
  27. var name string
  28. if resource == mnt.MountToPath[1:] {
  29. name = filepath.Base(resource)
  30. }
  31. path, err := filepath.Rel(mnt.MountToPath[1:], resource)
  32. if err != nil {
  33. return nil, err
  34. }
  35. return mnt.volume.Export(path, name)
  36. }
  37. func (container *Container) prepareVolumes() error {
  38. if container.Volumes == nil || len(container.Volumes) == 0 {
  39. container.Volumes = make(map[string]string)
  40. container.VolumesRW = make(map[string]bool)
  41. }
  42. return container.createVolumes()
  43. }
  44. // sortedVolumeMounts returns the list of container volume mount points sorted in lexicographic order
  45. func (container *Container) sortedVolumeMounts() []string {
  46. var mountPaths []string
  47. for path := range container.Volumes {
  48. mountPaths = append(mountPaths, path)
  49. }
  50. sort.Strings(mountPaths)
  51. return mountPaths
  52. }
  53. func (container *Container) createVolumes() error {
  54. mounts, err := container.parseVolumeMountConfig()
  55. if err != nil {
  56. return err
  57. }
  58. for _, mnt := range mounts {
  59. if err := mnt.initialize(); err != nil {
  60. return err
  61. }
  62. }
  63. // On every start, this will apply any new `VolumesFrom` entries passed in via HostConfig, which may override volumes set in `create`
  64. return container.applyVolumesFrom()
  65. }
  66. func (m *Mount) initialize() error {
  67. // No need to initialize anything since it's already been initialized
  68. if hostPath, exists := m.container.Volumes[m.MountToPath]; exists {
  69. // If this is a bind-mount/volumes-from, maybe it was passed in at start instead of create
  70. // We need to make sure bind-mounts/volumes-from passed on start can override existing ones.
  71. if !m.volume.IsBindMount && m.from == nil {
  72. return nil
  73. }
  74. if m.volume.Path == hostPath {
  75. return nil
  76. }
  77. // Make sure we remove these old volumes we don't actually want now.
  78. // Ignore any errors here since this is just cleanup, maybe someone volumes-from'd this volume
  79. v := m.container.daemon.volumes.Get(hostPath)
  80. v.RemoveContainer(m.container.ID)
  81. m.container.daemon.volumes.Delete(v.Path)
  82. }
  83. // This is the full path to container fs + mntToPath
  84. containerMntPath, err := symlink.FollowSymlinkInScope(filepath.Join(m.container.basefs, m.MountToPath), m.container.basefs)
  85. if err != nil {
  86. return err
  87. }
  88. m.container.VolumesRW[m.MountToPath] = m.Writable
  89. m.container.Volumes[m.MountToPath] = m.volume.Path
  90. m.volume.AddContainer(m.container.ID)
  91. if m.Writable && m.copyData {
  92. // Copy whatever is in the container at the mntToPath to the volume
  93. copyExistingContents(containerMntPath, m.volume.Path)
  94. }
  95. return nil
  96. }
  97. func (container *Container) VolumePaths() map[string]struct{} {
  98. var paths = make(map[string]struct{})
  99. for _, path := range container.Volumes {
  100. paths[path] = struct{}{}
  101. }
  102. return paths
  103. }
  104. func (container *Container) registerVolumes() {
  105. for _, mnt := range container.VolumeMounts() {
  106. mnt.volume.AddContainer(container.ID)
  107. }
  108. }
  109. func (container *Container) derefVolumes() {
  110. for path := range container.VolumePaths() {
  111. vol := container.daemon.volumes.Get(path)
  112. if vol == nil {
  113. log.Debugf("Volume %s was not found and could not be dereferenced", path)
  114. continue
  115. }
  116. vol.RemoveContainer(container.ID)
  117. }
  118. }
  119. func (container *Container) parseVolumeMountConfig() (map[string]*Mount, error) {
  120. var mounts = make(map[string]*Mount)
  121. // Get all the bind mounts
  122. for _, spec := range container.hostConfig.Binds {
  123. path, mountToPath, writable, err := parseBindMountSpec(spec)
  124. if err != nil {
  125. return nil, err
  126. }
  127. // Check if a volume already exists for this and use it
  128. vol, err := container.daemon.volumes.FindOrCreateVolume(path, writable)
  129. if err != nil {
  130. return nil, err
  131. }
  132. mounts[mountToPath] = &Mount{
  133. container: container,
  134. volume: vol,
  135. MountToPath: mountToPath,
  136. Writable: writable,
  137. }
  138. }
  139. // Get the rest of the volumes
  140. for path := range container.Config.Volumes {
  141. // Check if this is already added as a bind-mount
  142. path = filepath.Clean(path)
  143. if _, exists := mounts[path]; exists {
  144. continue
  145. }
  146. // Check if this has already been created
  147. if _, exists := container.Volumes[path]; exists {
  148. continue
  149. }
  150. vol, err := container.daemon.volumes.FindOrCreateVolume("", true)
  151. if err != nil {
  152. return nil, err
  153. }
  154. mounts[path] = &Mount{
  155. container: container,
  156. MountToPath: path,
  157. volume: vol,
  158. Writable: true,
  159. copyData: true,
  160. }
  161. }
  162. return mounts, nil
  163. }
  164. func parseBindMountSpec(spec string) (string, string, bool, error) {
  165. var (
  166. path, mountToPath string
  167. writable bool
  168. arr = strings.Split(spec, ":")
  169. )
  170. switch len(arr) {
  171. case 2:
  172. path = arr[0]
  173. mountToPath = arr[1]
  174. writable = true
  175. case 3:
  176. path = arr[0]
  177. mountToPath = arr[1]
  178. writable = validMountMode(arr[2]) && arr[2] == "rw"
  179. default:
  180. return "", "", false, fmt.Errorf("Invalid volume specification: %s", spec)
  181. }
  182. if !filepath.IsAbs(path) {
  183. return "", "", false, fmt.Errorf("cannot bind mount volume: %s volume paths must be absolute.", path)
  184. }
  185. path = filepath.Clean(path)
  186. mountToPath = filepath.Clean(mountToPath)
  187. return path, mountToPath, writable, nil
  188. }
  189. func (container *Container) applyVolumesFrom() error {
  190. volumesFrom := container.hostConfig.VolumesFrom
  191. mountGroups := make([]map[string]*Mount, 0, len(volumesFrom))
  192. for _, spec := range volumesFrom {
  193. mountGroup, err := parseVolumesFromSpec(container.daemon, spec)
  194. if err != nil {
  195. return err
  196. }
  197. mountGroups = append(mountGroups, mountGroup)
  198. }
  199. for _, mounts := range mountGroups {
  200. for _, mnt := range mounts {
  201. mnt.from = mnt.container
  202. mnt.container = container
  203. if err := mnt.initialize(); err != nil {
  204. return err
  205. }
  206. }
  207. }
  208. return nil
  209. }
  210. func validMountMode(mode string) bool {
  211. validModes := map[string]bool{
  212. "rw": true,
  213. "ro": true,
  214. }
  215. return validModes[mode]
  216. }
  217. func (container *Container) setupMounts() error {
  218. mounts := []execdriver.Mount{
  219. {Source: container.ResolvConfPath, Destination: "/etc/resolv.conf", Writable: true, Private: true},
  220. }
  221. if container.HostnamePath != "" {
  222. mounts = append(mounts, execdriver.Mount{Source: container.HostnamePath, Destination: "/etc/hostname", Writable: true, Private: true})
  223. }
  224. if container.HostsPath != "" {
  225. mounts = append(mounts, execdriver.Mount{Source: container.HostsPath, Destination: "/etc/hosts", Writable: true, Private: true})
  226. }
  227. for _, m := range mounts {
  228. if err := label.SetFileLabel(m.Source, container.MountLabel); err != nil {
  229. return err
  230. }
  231. }
  232. // Mount user specified volumes
  233. // Note, these are not private because you may want propagation of (un)mounts from host
  234. // volumes. For instance if you use -v /usr:/usr and the host later mounts /usr/share you
  235. // want this new mount in the container
  236. // These mounts must be ordered based on the length of the path that it is being mounted to (lexicographic)
  237. for _, path := range container.sortedVolumeMounts() {
  238. mounts = append(mounts, execdriver.Mount{
  239. Source: container.Volumes[path],
  240. Destination: path,
  241. Writable: container.VolumesRW[path],
  242. })
  243. }
  244. container.command.Mounts = mounts
  245. return nil
  246. }
  247. func parseVolumesFromSpec(daemon *Daemon, spec string) (map[string]*Mount, error) {
  248. specParts := strings.SplitN(spec, ":", 2)
  249. if len(specParts) == 0 {
  250. return nil, fmt.Errorf("Malformed volumes-from specification: %s", spec)
  251. }
  252. c := daemon.Get(specParts[0])
  253. if c == nil {
  254. return nil, fmt.Errorf("Container %s not found. Impossible to mount its volumes", specParts[0])
  255. }
  256. mounts := c.VolumeMounts()
  257. if len(specParts) == 2 {
  258. mode := specParts[1]
  259. if !validMountMode(mode) {
  260. return nil, fmt.Errorf("Invalid mode for volumes-from: %s", mode)
  261. }
  262. // Set the mode for the inheritted volume
  263. for _, mnt := range mounts {
  264. // Ensure that if the inherited volume is not writable, that we don't make
  265. // it writable here
  266. mnt.Writable = mnt.Writable && (mode == "rw")
  267. }
  268. }
  269. return mounts, nil
  270. }
  271. func (container *Container) VolumeMounts() map[string]*Mount {
  272. mounts := make(map[string]*Mount)
  273. for mountToPath, path := range container.Volumes {
  274. if v := container.daemon.volumes.Get(path); v != nil {
  275. mounts[mountToPath] = &Mount{volume: v, container: container, MountToPath: mountToPath, Writable: container.VolumesRW[mountToPath]}
  276. }
  277. }
  278. return mounts
  279. }
  280. func copyExistingContents(source, destination string) error {
  281. volList, err := ioutil.ReadDir(source)
  282. if err != nil {
  283. return err
  284. }
  285. if len(volList) > 0 {
  286. srcList, err := ioutil.ReadDir(destination)
  287. if err != nil {
  288. return err
  289. }
  290. if len(srcList) == 0 {
  291. // If the source volume is empty copy files from the root into the volume
  292. if err := chrootarchive.CopyWithTar(source, destination); err != nil {
  293. return err
  294. }
  295. }
  296. }
  297. return copyOwnership(source, destination)
  298. }
  299. // copyOwnership copies the permissions and uid:gid of the source file
  300. // into the destination file
  301. func copyOwnership(source, destination string) error {
  302. var stat syscall.Stat_t
  303. if err := syscall.Stat(source, &stat); err != nil {
  304. return err
  305. }
  306. if err := os.Chown(destination, int(stat.Uid), int(stat.Gid)); err != nil {
  307. return err
  308. }
  309. return os.Chmod(destination, os.FileMode(stat.Mode))
  310. }