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