volume.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. package volume
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "strings"
  7. "syscall"
  8. "time"
  9. mounttypes "github.com/docker/docker/api/types/mount"
  10. "github.com/docker/docker/pkg/idtools"
  11. "github.com/docker/docker/pkg/stringid"
  12. "github.com/opencontainers/selinux/go-selinux/label"
  13. "github.com/pkg/errors"
  14. )
  15. // DefaultDriverName is the driver name used for the driver
  16. // implemented in the local package.
  17. const DefaultDriverName = "local"
  18. // Scopes define if a volume has is cluster-wide (global) or local only.
  19. // Scopes are returned by the volume driver when it is queried for capabilities and then set on a volume
  20. const (
  21. LocalScope = "local"
  22. GlobalScope = "global"
  23. )
  24. // Driver is for creating and removing volumes.
  25. type Driver interface {
  26. // Name returns the name of the volume driver.
  27. Name() string
  28. // Create makes a new volume with the given name.
  29. Create(name string, opts map[string]string) (Volume, error)
  30. // Remove deletes the volume.
  31. Remove(vol Volume) (err error)
  32. // List lists all the volumes the driver has
  33. List() ([]Volume, error)
  34. // Get retrieves the volume with the requested name
  35. Get(name string) (Volume, error)
  36. // Scope returns the scope of the driver (e.g. `global` or `local`).
  37. // Scope determines how the driver is handled at a cluster level
  38. Scope() string
  39. }
  40. // Capability defines a set of capabilities that a driver is able to handle.
  41. type Capability struct {
  42. // Scope is the scope of the driver, `global` or `local`
  43. // A `global` scope indicates that the driver manages volumes across the cluster
  44. // A `local` scope indicates that the driver only manages volumes resources local to the host
  45. // Scope is declared by the driver
  46. Scope string
  47. }
  48. // Volume is a place to store data. It is backed by a specific driver, and can be mounted.
  49. type Volume interface {
  50. // Name returns the name of the volume
  51. Name() string
  52. // DriverName returns the name of the driver which owns this volume.
  53. DriverName() string
  54. // Path returns the absolute path to the volume.
  55. Path() string
  56. // Mount mounts the volume and returns the absolute path to
  57. // where it can be consumed.
  58. Mount(id string) (string, error)
  59. // Unmount unmounts the volume when it is no longer in use.
  60. Unmount(id string) error
  61. // CreatedAt returns Volume Creation time
  62. CreatedAt() (time.Time, error)
  63. // Status returns low-level status information about a volume
  64. Status() map[string]interface{}
  65. }
  66. // DetailedVolume wraps a Volume with user-defined labels, options, and cluster scope (e.g., `local` or `global`)
  67. type DetailedVolume interface {
  68. Labels() map[string]string
  69. Options() map[string]string
  70. Scope() string
  71. Volume
  72. }
  73. // MountPoint is the intersection point between a volume and a container. It
  74. // specifies which volume is to be used and where inside a container it should
  75. // be mounted.
  76. type MountPoint struct {
  77. // Source is the source path of the mount.
  78. // E.g. `mount --bind /foo /bar`, `/foo` is the `Source`.
  79. Source string
  80. // Destination is the path relative to the container root (`/`) to the mount point
  81. // It is where the `Source` is mounted to
  82. Destination string
  83. // RW is set to true when the mountpoint should be mounted as read-write
  84. RW bool
  85. // Name is the name reference to the underlying data defined by `Source`
  86. // e.g., the volume name
  87. Name string
  88. // Driver is the volume driver used to create the volume (if it is a volume)
  89. Driver string
  90. // Type of mount to use, see `Type<foo>` definitions in github.com/docker/docker/api/types/mount
  91. Type mounttypes.Type `json:",omitempty"`
  92. // Volume is the volume providing data to this mountpoint.
  93. // This is nil unless `Type` is set to `TypeVolume`
  94. Volume Volume `json:"-"`
  95. // Mode is the comma separated list of options supplied by the user when creating
  96. // the bind/volume mount.
  97. // Note Mode is not used on Windows
  98. Mode string `json:"Relabel,omitempty"` // Originally field was `Relabel`"
  99. // Propagation describes how the mounts are propagated from the host into the
  100. // mount point, and vice-versa.
  101. // See https://www.kernel.org/doc/Documentation/filesystems/sharedsubtree.txt
  102. // Note Propagation is not used on Windows
  103. Propagation mounttypes.Propagation `json:",omitempty"` // Mount propagation string
  104. // Specifies if data should be copied from the container before the first mount
  105. // Use a pointer here so we can tell if the user set this value explicitly
  106. // This allows us to error out when the user explicitly enabled copy but we can't copy due to the volume being populated
  107. CopyData bool `json:"-"`
  108. // ID is the opaque ID used to pass to the volume driver.
  109. // This should be set by calls to `Mount` and unset by calls to `Unmount`
  110. ID string `json:",omitempty"`
  111. // Sepc is a copy of the API request that created this mount.
  112. Spec mounttypes.Mount
  113. // Track usage of this mountpoint
  114. // Specicially needed for containers which are running and calls to `docker cp`
  115. // because both these actions require mounting the volumes.
  116. active int
  117. }
  118. // Cleanup frees resources used by the mountpoint
  119. func (m *MountPoint) Cleanup() error {
  120. if m.Volume == nil || m.ID == "" {
  121. return nil
  122. }
  123. if err := m.Volume.Unmount(m.ID); err != nil {
  124. return errors.Wrapf(err, "error unmounting volume %s", m.Volume.Name())
  125. }
  126. m.active--
  127. if m.active == 0 {
  128. m.ID = ""
  129. }
  130. return nil
  131. }
  132. // Setup sets up a mount point by either mounting the volume if it is
  133. // configured, or creating the source directory if supplied.
  134. func (m *MountPoint) Setup(mountLabel string, rootUID, rootGID int) (path string, err error) {
  135. defer func() {
  136. if err == nil {
  137. if label.RelabelNeeded(m.Mode) {
  138. if err = label.Relabel(m.Source, mountLabel, label.IsShared(m.Mode)); err != nil {
  139. path = ""
  140. err = errors.Wrapf(err, "error setting label on mount source '%s'", m.Source)
  141. return
  142. }
  143. }
  144. }
  145. return
  146. }()
  147. if m.Volume != nil {
  148. id := m.ID
  149. if id == "" {
  150. id = stringid.GenerateNonCryptoID()
  151. }
  152. path, err := m.Volume.Mount(id)
  153. if err != nil {
  154. return "", errors.Wrapf(err, "error while mounting volume '%s'", m.Source)
  155. }
  156. m.ID = id
  157. m.active++
  158. return path, nil
  159. }
  160. if len(m.Source) == 0 {
  161. return "", fmt.Errorf("Unable to setup mount point, neither source nor volume defined")
  162. }
  163. // system.MkdirAll() produces an error if m.Source exists and is a file (not a directory),
  164. if m.Type == mounttypes.TypeBind {
  165. // idtools.MkdirAllNewAs() produces an error if m.Source exists and is a file (not a directory)
  166. // also, makes sure that if the directory is created, the correct remapped rootUID/rootGID will own it
  167. if err := idtools.MkdirAllNewAs(m.Source, 0755, rootUID, rootGID); err != nil {
  168. if perr, ok := err.(*os.PathError); ok {
  169. if perr.Err != syscall.ENOTDIR {
  170. return "", errors.Wrapf(err, "error while creating mount source path '%s'", m.Source)
  171. }
  172. }
  173. }
  174. }
  175. return m.Source, nil
  176. }
  177. // Path returns the path of a volume in a mount point.
  178. func (m *MountPoint) Path() string {
  179. if m.Volume != nil {
  180. return m.Volume.Path()
  181. }
  182. return m.Source
  183. }
  184. // ParseVolumesFrom ensures that the supplied volumes-from is valid.
  185. func ParseVolumesFrom(spec string) (string, string, error) {
  186. if len(spec) == 0 {
  187. return "", "", fmt.Errorf("volumes-from specification cannot be an empty string")
  188. }
  189. specParts := strings.SplitN(spec, ":", 2)
  190. id := specParts[0]
  191. mode := "rw"
  192. if len(specParts) == 2 {
  193. mode = specParts[1]
  194. if !ValidMountMode(mode) {
  195. return "", "", errInvalidMode(mode)
  196. }
  197. // For now don't allow propagation properties while importing
  198. // volumes from data container. These volumes will inherit
  199. // the same propagation property as of the original volume
  200. // in data container. This probably can be relaxed in future.
  201. if HasPropagation(mode) {
  202. return "", "", errInvalidMode(mode)
  203. }
  204. // Do not allow copy modes on volumes-from
  205. if _, isSet := getCopyMode(mode); isSet {
  206. return "", "", errInvalidMode(mode)
  207. }
  208. }
  209. return id, mode, nil
  210. }
  211. // ParseMountRaw parses a raw volume spec (e.g. `-v /foo:/bar:shared`) into a
  212. // structured spec. Once the raw spec is parsed it relies on `ParseMountSpec` to
  213. // validate the spec and create a MountPoint
  214. func ParseMountRaw(raw, volumeDriver string) (*MountPoint, error) {
  215. arr, err := splitRawSpec(convertSlash(raw))
  216. if err != nil {
  217. return nil, err
  218. }
  219. var spec mounttypes.Mount
  220. var mode string
  221. switch len(arr) {
  222. case 1:
  223. // Just a destination path in the container
  224. spec.Target = arr[0]
  225. case 2:
  226. if ValidMountMode(arr[1]) {
  227. // Destination + Mode is not a valid volume - volumes
  228. // cannot include a mode. e.g. /foo:rw
  229. return nil, errInvalidSpec(raw)
  230. }
  231. // Host Source Path or Name + Destination
  232. spec.Source = arr[0]
  233. spec.Target = arr[1]
  234. case 3:
  235. // HostSourcePath+DestinationPath+Mode
  236. spec.Source = arr[0]
  237. spec.Target = arr[1]
  238. mode = arr[2]
  239. default:
  240. return nil, errInvalidSpec(raw)
  241. }
  242. if !ValidMountMode(mode) {
  243. return nil, errInvalidMode(mode)
  244. }
  245. if filepath.IsAbs(spec.Source) {
  246. spec.Type = mounttypes.TypeBind
  247. } else {
  248. spec.Type = mounttypes.TypeVolume
  249. }
  250. spec.ReadOnly = !ReadWrite(mode)
  251. // cannot assume that if a volume driver is passed in that we should set it
  252. if volumeDriver != "" && spec.Type == mounttypes.TypeVolume {
  253. spec.VolumeOptions = &mounttypes.VolumeOptions{
  254. DriverConfig: &mounttypes.Driver{Name: volumeDriver},
  255. }
  256. }
  257. if copyData, isSet := getCopyMode(mode); isSet {
  258. if spec.VolumeOptions == nil {
  259. spec.VolumeOptions = &mounttypes.VolumeOptions{}
  260. }
  261. spec.VolumeOptions.NoCopy = !copyData
  262. }
  263. if HasPropagation(mode) {
  264. spec.BindOptions = &mounttypes.BindOptions{
  265. Propagation: GetPropagation(mode),
  266. }
  267. }
  268. mp, err := ParseMountSpec(spec, platformRawValidationOpts...)
  269. if mp != nil {
  270. mp.Mode = mode
  271. }
  272. if err != nil {
  273. err = fmt.Errorf("%v: %v", errInvalidSpec(raw), err)
  274. }
  275. return mp, err
  276. }
  277. // ParseMountSpec reads a mount config, validates it, and configures a mountpoint from it.
  278. func ParseMountSpec(cfg mounttypes.Mount, options ...func(*validateOpts)) (*MountPoint, error) {
  279. if err := validateMountConfig(&cfg, options...); err != nil {
  280. return nil, err
  281. }
  282. mp := &MountPoint{
  283. RW: !cfg.ReadOnly,
  284. Destination: clean(convertSlash(cfg.Target)),
  285. Type: cfg.Type,
  286. Spec: cfg,
  287. }
  288. switch cfg.Type {
  289. case mounttypes.TypeVolume:
  290. if cfg.Source == "" {
  291. mp.Name = stringid.GenerateNonCryptoID()
  292. } else {
  293. mp.Name = cfg.Source
  294. }
  295. mp.CopyData = DefaultCopyMode
  296. if cfg.VolumeOptions != nil {
  297. if cfg.VolumeOptions.DriverConfig != nil {
  298. mp.Driver = cfg.VolumeOptions.DriverConfig.Name
  299. }
  300. if cfg.VolumeOptions.NoCopy {
  301. mp.CopyData = false
  302. }
  303. }
  304. case mounttypes.TypeBind:
  305. mp.Source = clean(convertSlash(cfg.Source))
  306. if cfg.BindOptions != nil && len(cfg.BindOptions.Propagation) > 0 {
  307. mp.Propagation = cfg.BindOptions.Propagation
  308. } else {
  309. // If user did not specify a propagation mode, get
  310. // default propagation mode.
  311. mp.Propagation = DefaultPropagationMode
  312. }
  313. case mounttypes.TypeTmpfs:
  314. // NOP
  315. }
  316. return mp, nil
  317. }
  318. func errInvalidMode(mode string) error {
  319. return fmt.Errorf("invalid mode: %v", mode)
  320. }
  321. func errInvalidSpec(spec string) error {
  322. return fmt.Errorf("invalid volume specification: '%s'", spec)
  323. }