github.com/ssdev-go/moby@v17.12.1-ce-rc2+incompatible/volume/local/local.go (about)

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