github.com/vieux/docker@v0.6.3-0.20161004191708-e097c2a938c7/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  	"sync"
    14  
    15  	"github.com/pkg/errors"
    16  
    17  	"github.com/Sirupsen/logrus"
    18  	"github.com/docker/docker/pkg/idtools"
    19  	"github.com/docker/docker/pkg/mount"
    20  	"github.com/docker/docker/utils"
    21  	"github.com/docker/docker/volume"
    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 = utils.RestrictedVolumeNamePattern
    39  )
    40  
    41  type validationError struct {
    42  	error
    43  }
    44  
    45  func (validationError) IsValidationError() bool {
    46  	return true
    47  }
    48  
    49  type activeMount struct {
    50  	count   uint64
    51  	mounted bool
    52  }
    53  
    54  // New instantiates a new Root instance with the provided scope. Scope
    55  // is the base path that the Root instance uses to store its
    56  // volumes. The base path is created here if it does not exist.
    57  func New(scope string, rootUID, rootGID int) (*Root, error) {
    58  	rootDirectory := filepath.Join(scope, volumesPathName)
    59  
    60  	if err := idtools.MkdirAllAs(rootDirectory, 0700, rootUID, rootGID); err != nil {
    61  		return nil, err
    62  	}
    63  
    64  	r := &Root{
    65  		scope:   scope,
    66  		path:    rootDirectory,
    67  		volumes: make(map[string]*localVolume),
    68  		rootUID: rootUID,
    69  		rootGID: rootGID,
    70  	}
    71  
    72  	dirs, err := ioutil.ReadDir(rootDirectory)
    73  	if err != nil {
    74  		return nil, err
    75  	}
    76  
    77  	mountInfos, err := mount.GetMounts()
    78  	if err != nil {
    79  		logrus.Debugf("error looking up mounts for local volume cleanup: %v", err)
    80  	}
    81  
    82  	for _, d := range dirs {
    83  		if !d.IsDir() {
    84  			continue
    85  		}
    86  
    87  		name := filepath.Base(d.Name())
    88  		v := &localVolume{
    89  			driverName: r.Name(),
    90  			name:       name,
    91  			path:       r.DataPath(name),
    92  		}
    93  		r.volumes[name] = v
    94  		optsFilePath := filepath.Join(rootDirectory, name, "opts.json")
    95  		if b, err := ioutil.ReadFile(optsFilePath); err == nil {
    96  			opts := optsConfig{}
    97  			if err := json.Unmarshal(b, &opts); err != nil {
    98  				return nil, errors.Wrapf(err, "error while unmarshaling volume options for volume: %s", name)
    99  			}
   100  			// Make sure this isn't an empty optsConfig.
   101  			// This could be empty due to buggy behavior in older versions of Docker.
   102  			if !reflect.DeepEqual(opts, optsConfig{}) {
   103  				v.opts = &opts
   104  			}
   105  
   106  			// unmount anything that may still be mounted (for example, from an unclean shutdown)
   107  			for _, info := range mountInfos {
   108  				if info.Mountpoint == v.path {
   109  					mount.Unmount(v.path)
   110  					break
   111  				}
   112  			}
   113  		}
   114  	}
   115  
   116  	return r, nil
   117  }
   118  
   119  // Root implements the Driver interface for the volume package and
   120  // manages the creation/removal of volumes. It uses only standard vfs
   121  // commands to create/remove dirs within its provided scope.
   122  type Root struct {
   123  	m       sync.Mutex
   124  	scope   string
   125  	path    string
   126  	volumes map[string]*localVolume
   127  	rootUID int
   128  	rootGID int
   129  }
   130  
   131  // List lists all the volumes
   132  func (r *Root) List() ([]volume.Volume, error) {
   133  	var ls []volume.Volume
   134  	r.m.Lock()
   135  	for _, v := range r.volumes {
   136  		ls = append(ls, v)
   137  	}
   138  	r.m.Unlock()
   139  	return ls, nil
   140  }
   141  
   142  // DataPath returns the constructed path of this volume.
   143  func (r *Root) DataPath(volumeName string) string {
   144  	return filepath.Join(r.path, volumeName, VolumeDataPathName)
   145  }
   146  
   147  // Name returns the name of Root, defined in the volume package in the DefaultDriverName constant.
   148  func (r *Root) Name() string {
   149  	return volume.DefaultDriverName
   150  }
   151  
   152  // Create creates a new volume.Volume with the provided name, creating
   153  // the underlying directory tree required for this volume in the
   154  // process.
   155  func (r *Root) Create(name string, opts map[string]string) (volume.Volume, error) {
   156  	if err := r.validateName(name); err != nil {
   157  		return nil, err
   158  	}
   159  
   160  	r.m.Lock()
   161  	defer r.m.Unlock()
   162  
   163  	v, exists := r.volumes[name]
   164  	if exists {
   165  		return v, nil
   166  	}
   167  
   168  	path := r.DataPath(name)
   169  	if err := idtools.MkdirAllAs(path, 0755, r.rootUID, r.rootGID); err != nil {
   170  		if os.IsExist(err) {
   171  			return nil, fmt.Errorf("volume already exists under %s", filepath.Dir(path))
   172  		}
   173  		return nil, errors.Wrapf(err, "error while creating volume path '%s'", path)
   174  	}
   175  
   176  	var err error
   177  	defer func() {
   178  		if err != nil {
   179  			os.RemoveAll(filepath.Dir(path))
   180  		}
   181  	}()
   182  
   183  	v = &localVolume{
   184  		driverName: r.Name(),
   185  		name:       name,
   186  		path:       path,
   187  	}
   188  
   189  	if len(opts) != 0 {
   190  		if err = setOpts(v, opts); err != nil {
   191  			return nil, err
   192  		}
   193  		var b []byte
   194  		b, err = json.Marshal(v.opts)
   195  		if err != nil {
   196  			return nil, err
   197  		}
   198  		if err = ioutil.WriteFile(filepath.Join(filepath.Dir(path), "opts.json"), b, 600); err != nil {
   199  			return nil, errors.Wrap(err, "error while persisting volume options")
   200  		}
   201  	}
   202  
   203  	r.volumes[name] = v
   204  	return v, nil
   205  }
   206  
   207  // Remove removes the specified volume and all underlying data. If the
   208  // given volume does not belong to this driver and an error is
   209  // returned. The volume is reference counted, if all references are
   210  // not released then the volume is not removed.
   211  func (r *Root) Remove(v volume.Volume) error {
   212  	r.m.Lock()
   213  	defer r.m.Unlock()
   214  
   215  	lv, ok := v.(*localVolume)
   216  	if !ok {
   217  		return fmt.Errorf("unknown volume type %T", v)
   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 fmt.Errorf("Unable to remove a directory of out the Docker 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  
   240  func removePath(path string) error {
   241  	if err := os.RemoveAll(path); err != nil {
   242  		if os.IsNotExist(err) {
   243  			return nil
   244  		}
   245  		return 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
   251  func (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
   262  func (r *Root) Scope() string {
   263  	return volume.LocalScope
   264  }
   265  
   266  func (r *Root) validateName(name string) error {
   267  	if len(name) == 1 {
   268  		return validationError{fmt.Errorf("volume name is too short, names should be at least two alphanumeric characters")}
   269  	}
   270  	if !volumeNameRegex.MatchString(name) {
   271  		return validationError{fmt.Errorf("%q includes invalid characters for a local volume name, only %q are allowed", name, utils.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.
   278  type 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  }
   291  
   292  // Name returns the name of the given Volume.
   293  func (v *localVolume) Name() string {
   294  	return v.name
   295  }
   296  
   297  // DriverName returns the driver that created the given Volume.
   298  func (v *localVolume) DriverName() string {
   299  	return v.driverName
   300  }
   301  
   302  // Path returns the data location.
   303  func (v *localVolume) Path() string {
   304  	return v.path
   305  }
   306  
   307  // Mount implements the localVolume interface, returning the data location.
   308  func (v *localVolume) Mount(id string) (string, error) {
   309  	v.m.Lock()
   310  	defer v.m.Unlock()
   311  	if v.opts != nil {
   312  		if !v.active.mounted {
   313  			if err := v.mount(); err != nil {
   314  				return "", err
   315  			}
   316  			v.active.mounted = true
   317  		}
   318  		v.active.count++
   319  	}
   320  	return v.path, nil
   321  }
   322  
   323  // Umount is for satisfying the localVolume interface and does not do anything in this driver.
   324  func (v *localVolume) Unmount(id string) error {
   325  	v.m.Lock()
   326  	defer v.m.Unlock()
   327  	if v.opts != nil {
   328  		v.active.count--
   329  		if v.active.count == 0 {
   330  			if err := mount.Unmount(v.path); err != nil {
   331  				v.active.count++
   332  				return errors.Wrapf(err, "error while unmounting volume path '%s'", v.path)
   333  			}
   334  			v.active.mounted = false
   335  		}
   336  	}
   337  	return nil
   338  }
   339  
   340  func validateOpts(opts map[string]string) error {
   341  	for opt := range opts {
   342  		if !validOpts[opt] {
   343  			return validationError{fmt.Errorf("invalid option key: %q", opt)}
   344  		}
   345  	}
   346  	return nil
   347  }
   348  
   349  func (v *localVolume) Status() map[string]interface{} {
   350  	return nil
   351  }