local.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. // Package local provides the default implementation for volumes. It
  2. // is used to mount data volume containers and directories local to
  3. // the host server.
  4. package local
  5. import (
  6. "encoding/json"
  7. "fmt"
  8. "io/ioutil"
  9. "os"
  10. "path/filepath"
  11. "reflect"
  12. "strings"
  13. "sync"
  14. "github.com/pkg/errors"
  15. "github.com/Sirupsen/logrus"
  16. "github.com/docker/docker/api"
  17. "github.com/docker/docker/pkg/idtools"
  18. "github.com/docker/docker/pkg/mount"
  19. "github.com/docker/docker/volume"
  20. )
  21. // VolumeDataPathName is the name of the directory where the volume data is stored.
  22. // It uses a very distinctive name to avoid collisions migrating data between
  23. // Docker versions.
  24. const (
  25. VolumeDataPathName = "_data"
  26. volumesPathName = "volumes"
  27. )
  28. var (
  29. // ErrNotFound is the typed error returned when the requested volume name can't be found
  30. ErrNotFound = fmt.Errorf("volume not found")
  31. // volumeNameRegex ensures the name assigned for the volume is valid.
  32. // This name is used to create the bind directory, so we need to avoid characters that
  33. // would make the path to escape the root directory.
  34. volumeNameRegex = api.RestrictedNamePattern
  35. )
  36. type validationError struct {
  37. error
  38. }
  39. func (validationError) IsValidationError() bool {
  40. return true
  41. }
  42. type activeMount struct {
  43. count uint64
  44. mounted bool
  45. }
  46. // New instantiates a new Root instance with the provided scope. Scope
  47. // is the base path that the Root instance uses to store its
  48. // volumes. The base path is created here if it does not exist.
  49. func New(scope string, rootUID, rootGID int) (*Root, error) {
  50. rootDirectory := filepath.Join(scope, volumesPathName)
  51. if err := idtools.MkdirAllAs(rootDirectory, 0700, rootUID, rootGID); err != nil {
  52. return nil, err
  53. }
  54. r := &Root{
  55. scope: scope,
  56. path: rootDirectory,
  57. volumes: make(map[string]*localVolume),
  58. rootUID: rootUID,
  59. rootGID: rootGID,
  60. }
  61. dirs, err := ioutil.ReadDir(rootDirectory)
  62. if err != nil {
  63. return nil, err
  64. }
  65. mountInfos, err := mount.GetMounts()
  66. if err != nil {
  67. logrus.Debugf("error looking up mounts for local volume cleanup: %v", err)
  68. }
  69. for _, d := range dirs {
  70. if !d.IsDir() {
  71. continue
  72. }
  73. name := filepath.Base(d.Name())
  74. v := &localVolume{
  75. driverName: r.Name(),
  76. name: name,
  77. path: r.DataPath(name),
  78. }
  79. r.volumes[name] = v
  80. optsFilePath := filepath.Join(rootDirectory, name, "opts.json")
  81. if b, err := ioutil.ReadFile(optsFilePath); err == nil {
  82. opts := optsConfig{}
  83. if err := json.Unmarshal(b, &opts); err != nil {
  84. return nil, errors.Wrapf(err, "error while unmarshaling volume options for volume: %s", name)
  85. }
  86. // Make sure this isn't an empty optsConfig.
  87. // This could be empty due to buggy behavior in older versions of Docker.
  88. if !reflect.DeepEqual(opts, optsConfig{}) {
  89. v.opts = &opts
  90. }
  91. // unmount anything that may still be mounted (for example, from an unclean shutdown)
  92. for _, info := range mountInfos {
  93. if info.Mountpoint == v.path {
  94. mount.Unmount(v.path)
  95. break
  96. }
  97. }
  98. }
  99. }
  100. return r, nil
  101. }
  102. // Root implements the Driver interface for the volume package and
  103. // manages the creation/removal of volumes. It uses only standard vfs
  104. // commands to create/remove dirs within its provided scope.
  105. type Root struct {
  106. m sync.Mutex
  107. scope string
  108. path string
  109. volumes map[string]*localVolume
  110. rootUID int
  111. rootGID int
  112. }
  113. // List lists all the volumes
  114. func (r *Root) List() ([]volume.Volume, error) {
  115. var ls []volume.Volume
  116. r.m.Lock()
  117. for _, v := range r.volumes {
  118. ls = append(ls, v)
  119. }
  120. r.m.Unlock()
  121. return ls, nil
  122. }
  123. // DataPath returns the constructed path of this volume.
  124. func (r *Root) DataPath(volumeName string) string {
  125. return filepath.Join(r.path, volumeName, VolumeDataPathName)
  126. }
  127. // Name returns the name of Root, defined in the volume package in the DefaultDriverName constant.
  128. func (r *Root) Name() string {
  129. return volume.DefaultDriverName
  130. }
  131. // Create creates a new volume.Volume with the provided name, creating
  132. // the underlying directory tree required for this volume in the
  133. // process.
  134. func (r *Root) Create(name string, opts map[string]string) (volume.Volume, error) {
  135. if err := r.validateName(name); err != nil {
  136. return nil, err
  137. }
  138. r.m.Lock()
  139. defer r.m.Unlock()
  140. v, exists := r.volumes[name]
  141. if exists {
  142. return v, nil
  143. }
  144. path := r.DataPath(name)
  145. if err := idtools.MkdirAllAs(path, 0755, r.rootUID, r.rootGID); err != nil {
  146. if os.IsExist(err) {
  147. return nil, fmt.Errorf("volume already exists under %s", filepath.Dir(path))
  148. }
  149. return nil, errors.Wrapf(err, "error while creating volume path '%s'", path)
  150. }
  151. var err error
  152. defer func() {
  153. if err != nil {
  154. os.RemoveAll(filepath.Dir(path))
  155. }
  156. }()
  157. v = &localVolume{
  158. driverName: r.Name(),
  159. name: name,
  160. path: path,
  161. }
  162. if len(opts) != 0 {
  163. if err = setOpts(v, opts); err != nil {
  164. return nil, err
  165. }
  166. var b []byte
  167. b, err = json.Marshal(v.opts)
  168. if err != nil {
  169. return nil, err
  170. }
  171. if err = ioutil.WriteFile(filepath.Join(filepath.Dir(path), "opts.json"), b, 600); err != nil {
  172. return nil, errors.Wrap(err, "error while persisting volume options")
  173. }
  174. }
  175. r.volumes[name] = v
  176. return v, nil
  177. }
  178. // Remove removes the specified volume and all underlying data. If the
  179. // given volume does not belong to this driver and an error is
  180. // returned. The volume is reference counted, if all references are
  181. // not released then the volume is not removed.
  182. func (r *Root) Remove(v volume.Volume) error {
  183. r.m.Lock()
  184. defer r.m.Unlock()
  185. lv, ok := v.(*localVolume)
  186. if !ok {
  187. return fmt.Errorf("unknown volume type %T", v)
  188. }
  189. if lv.active.count > 0 {
  190. return fmt.Errorf("volume has active mounts")
  191. }
  192. if err := lv.unmount(); err != nil {
  193. return err
  194. }
  195. realPath, err := filepath.EvalSymlinks(lv.path)
  196. if err != nil {
  197. if !os.IsNotExist(err) {
  198. return err
  199. }
  200. realPath = filepath.Dir(lv.path)
  201. }
  202. if !r.scopedPath(realPath) {
  203. return fmt.Errorf("Unable to remove a directory of out the Docker root %s: %s", r.scope, realPath)
  204. }
  205. if err := removePath(realPath); err != nil {
  206. return err
  207. }
  208. delete(r.volumes, lv.name)
  209. return removePath(filepath.Dir(lv.path))
  210. }
  211. func removePath(path string) error {
  212. if err := os.RemoveAll(path); err != nil {
  213. if os.IsNotExist(err) {
  214. return nil
  215. }
  216. return errors.Wrapf(err, "error removing volume path '%s'", path)
  217. }
  218. return nil
  219. }
  220. // Get looks up the volume for the given name and returns it if found
  221. func (r *Root) Get(name string) (volume.Volume, error) {
  222. r.m.Lock()
  223. v, exists := r.volumes[name]
  224. r.m.Unlock()
  225. if !exists {
  226. return nil, ErrNotFound
  227. }
  228. return v, nil
  229. }
  230. // Scope returns the local volume scope
  231. func (r *Root) Scope() string {
  232. return volume.LocalScope
  233. }
  234. func (r *Root) validateName(name string) error {
  235. if len(name) == 1 {
  236. return validationError{fmt.Errorf("volume name is too short, names should be at least two alphanumeric characters")}
  237. }
  238. if !volumeNameRegex.MatchString(name) {
  239. return validationError{fmt.Errorf("%q includes invalid characters for a local volume name, only %q are allowed. If you intended to pass a host directory, use absolute path", name, api.RestrictedNameChars)}
  240. }
  241. return nil
  242. }
  243. // localVolume implements the Volume interface from the volume package and
  244. // represents the volumes created by Root.
  245. type localVolume struct {
  246. m sync.Mutex
  247. // unique name of the volume
  248. name string
  249. // path is the path on the host where the data lives
  250. path string
  251. // driverName is the name of the driver that created the volume.
  252. driverName string
  253. // opts is the parsed list of options used to create the volume
  254. opts *optsConfig
  255. // active refcounts the active mounts
  256. active activeMount
  257. }
  258. // Name returns the name of the given Volume.
  259. func (v *localVolume) Name() string {
  260. return v.name
  261. }
  262. // DriverName returns the driver that created the given Volume.
  263. func (v *localVolume) DriverName() string {
  264. return v.driverName
  265. }
  266. // Path returns the data location.
  267. func (v *localVolume) Path() string {
  268. return v.path
  269. }
  270. // Mount implements the localVolume interface, returning the data location.
  271. // If there are any provided mount options, the resources will be mounted at this point
  272. func (v *localVolume) Mount(id string) (string, error) {
  273. v.m.Lock()
  274. defer v.m.Unlock()
  275. if v.opts != nil {
  276. if !v.active.mounted {
  277. if err := v.mount(); err != nil {
  278. return "", err
  279. }
  280. v.active.mounted = true
  281. }
  282. v.active.count++
  283. }
  284. return v.path, nil
  285. }
  286. // Unmount dereferences the id, and if it is the last reference will unmount any resources
  287. // that were previously mounted.
  288. func (v *localVolume) Unmount(id string) error {
  289. v.m.Lock()
  290. defer v.m.Unlock()
  291. // Always decrement the count, even if the unmount fails
  292. // Essentially docker doesn't care if this fails, it will send an error, but
  293. // ultimately there's nothing that can be done. If we don't decrement the count
  294. // this volume can never be removed until a daemon restart occurs.
  295. if v.opts != nil {
  296. v.active.count--
  297. }
  298. if v.active.count > 0 {
  299. return nil
  300. }
  301. return v.unmount()
  302. }
  303. func (v *localVolume) unmount() error {
  304. if v.opts != nil {
  305. if err := mount.Unmount(v.path); err != nil {
  306. if mounted, mErr := mount.Mounted(v.path); mounted || mErr != nil {
  307. return errors.Wrapf(err, "error while unmounting volume path '%s'", v.path)
  308. }
  309. }
  310. v.active.mounted = false
  311. }
  312. return nil
  313. }
  314. func validateOpts(opts map[string]string) error {
  315. for opt := range opts {
  316. if !validOpts[opt] {
  317. return validationError{fmt.Errorf("invalid option key: %q", opt)}
  318. }
  319. }
  320. return nil
  321. }
  322. func (v *localVolume) Status() map[string]interface{} {
  323. return nil
  324. }
  325. // getAddress finds out address/hostname from options
  326. func getAddress(opts string) string {
  327. optsList := strings.Split(opts, ",")
  328. for i := 0; i < len(optsList); i++ {
  329. if strings.HasPrefix(optsList[i], "addr=") {
  330. addr := (strings.SplitN(optsList[i], "=", 2)[1])
  331. return addr
  332. }
  333. }
  334. return ""
  335. }