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