github.com/rumpl/bof@v23.0.0-rc.2+incompatible/daemon/graphdriver/driver.go (about)

     1  package graphdriver // import "github.com/docker/docker/daemon/graphdriver"
     2  
     3  import (
     4  	"io"
     5  	"os"
     6  	"path/filepath"
     7  	"strings"
     8  
     9  	"github.com/docker/docker/pkg/archive"
    10  	"github.com/docker/docker/pkg/containerfs"
    11  	"github.com/docker/docker/pkg/idtools"
    12  	"github.com/docker/docker/pkg/plugingetter"
    13  	"github.com/pkg/errors"
    14  	"github.com/sirupsen/logrus"
    15  	"github.com/vbatts/tar-split/tar/storage"
    16  )
    17  
    18  // FsMagic unsigned id of the filesystem in use.
    19  type FsMagic uint32
    20  
    21  const (
    22  	// FsMagicUnsupported is a predefined constant value other than a valid filesystem id.
    23  	FsMagicUnsupported = FsMagic(0x00000000)
    24  )
    25  
    26  var (
    27  	// All registered drivers
    28  	drivers map[string]InitFunc
    29  )
    30  
    31  // CreateOpts contains optional arguments for Create() and CreateReadWrite()
    32  // methods.
    33  type CreateOpts struct {
    34  	MountLabel string
    35  	StorageOpt map[string]string
    36  }
    37  
    38  // InitFunc initializes the storage driver.
    39  type InitFunc func(root string, options []string, idMap idtools.IdentityMapping) (Driver, error)
    40  
    41  // ProtoDriver defines the basic capabilities of a driver.
    42  // This interface exists solely to be a minimum set of methods
    43  // for client code which choose not to implement the entire Driver
    44  // interface and use the NaiveDiffDriver wrapper constructor.
    45  //
    46  // Use of ProtoDriver directly by client code is not recommended.
    47  type ProtoDriver interface {
    48  	// String returns a string representation of this driver.
    49  	String() string
    50  	// CreateReadWrite creates a new, empty filesystem layer that is ready
    51  	// to be used as the storage for a container. Additional options can
    52  	// be passed in opts. parent may be "" and opts may be nil.
    53  	CreateReadWrite(id, parent string, opts *CreateOpts) error
    54  	// Create creates a new, empty, filesystem layer with the
    55  	// specified id and parent and options passed in opts. Parent
    56  	// may be "" and opts may be nil.
    57  	Create(id, parent string, opts *CreateOpts) error
    58  	// Remove attempts to remove the filesystem layer with this id.
    59  	Remove(id string) error
    60  	// Get returns the mountpoint for the layered filesystem referred
    61  	// to by this id. You can optionally specify a mountLabel or "".
    62  	// Returns the absolute path to the mounted layered filesystem.
    63  	Get(id, mountLabel string) (fs containerfs.ContainerFS, err error)
    64  	// Put releases the system resources for the specified id,
    65  	// e.g, unmounting layered filesystem.
    66  	Put(id string) error
    67  	// Exists returns whether a filesystem layer with the specified
    68  	// ID exists on this driver.
    69  	Exists(id string) bool
    70  	// Status returns a set of key-value pairs which give low
    71  	// level diagnostic status about this driver.
    72  	Status() [][2]string
    73  	// Returns a set of key-value pairs which give low level information
    74  	// about the image/container driver is managing.
    75  	GetMetadata(id string) (map[string]string, error)
    76  	// Cleanup performs necessary tasks to release resources
    77  	// held by the driver, e.g., unmounting all layered filesystems
    78  	// known to this driver.
    79  	Cleanup() error
    80  }
    81  
    82  // DiffDriver is the interface to use to implement graph diffs
    83  type DiffDriver interface {
    84  	// Diff produces an archive of the changes between the specified
    85  	// layer and its parent layer which may be "".
    86  	Diff(id, parent string) (io.ReadCloser, error)
    87  	// Changes produces a list of changes between the specified layer
    88  	// and its parent layer. If parent is "", then all changes will be ADD changes.
    89  	Changes(id, parent string) ([]archive.Change, error)
    90  	// ApplyDiff extracts the changeset from the given diff into the
    91  	// layer with the specified id and parent, returning the size of the
    92  	// new layer in bytes.
    93  	// The archive.Reader must be an uncompressed stream.
    94  	ApplyDiff(id, parent string, diff io.Reader) (size int64, err error)
    95  	// DiffSize calculates the changes between the specified id
    96  	// and its parent and returns the size in bytes of the changes
    97  	// relative to its base filesystem directory.
    98  	DiffSize(id, parent string) (size int64, err error)
    99  }
   100  
   101  // Driver is the interface for layered/snapshot file system drivers.
   102  type Driver interface {
   103  	ProtoDriver
   104  	DiffDriver
   105  }
   106  
   107  // Capabilities defines a list of capabilities a driver may implement.
   108  // These capabilities are not required; however, they do determine how a
   109  // graphdriver can be used.
   110  type Capabilities struct {
   111  	// Flags that this driver is capable of reproducing exactly equivalent
   112  	// diffs for read-only layers. If set, clients can rely on the driver
   113  	// for consistent tar streams, and avoid extra processing to account
   114  	// for potential differences (eg: the layer store's use of tar-split).
   115  	ReproducesExactDiffs bool
   116  }
   117  
   118  // CapabilityDriver is the interface for layered file system drivers that
   119  // can report on their Capabilities.
   120  type CapabilityDriver interface {
   121  	Capabilities() Capabilities
   122  }
   123  
   124  // DiffGetterDriver is the interface for layered file system drivers that
   125  // provide a specialized function for getting file contents for tar-split.
   126  type DiffGetterDriver interface {
   127  	Driver
   128  	// DiffGetter returns an interface to efficiently retrieve the contents
   129  	// of files in a layer.
   130  	DiffGetter(id string) (FileGetCloser, error)
   131  }
   132  
   133  // FileGetCloser extends the storage.FileGetter interface with a Close method
   134  // for cleaning up.
   135  type FileGetCloser interface {
   136  	storage.FileGetter
   137  	// Close cleans up any resources associated with the FileGetCloser.
   138  	Close() error
   139  }
   140  
   141  // Checker makes checks on specified filesystems.
   142  type Checker interface {
   143  	// IsMounted returns true if the provided path is mounted for the specific checker
   144  	IsMounted(path string) bool
   145  }
   146  
   147  func init() {
   148  	drivers = make(map[string]InitFunc)
   149  }
   150  
   151  // Register registers an InitFunc for the driver.
   152  func Register(name string, initFunc InitFunc) error {
   153  	if _, exists := drivers[name]; exists {
   154  		return errors.Errorf("name already registered %s", name)
   155  	}
   156  	drivers[name] = initFunc
   157  
   158  	return nil
   159  }
   160  
   161  // GetDriver initializes and returns the registered driver
   162  func GetDriver(name string, pg plugingetter.PluginGetter, config Options) (Driver, error) {
   163  	if initFunc, exists := drivers[name]; exists {
   164  		return initFunc(filepath.Join(config.Root, name), config.DriverOptions, config.IDMap)
   165  	}
   166  
   167  	pluginDriver, err := lookupPlugin(name, pg, config)
   168  	if err == nil {
   169  		return pluginDriver, nil
   170  	}
   171  	logrus.WithError(err).WithField("driver", name).WithField("home-dir", config.Root).Error("Failed to GetDriver graph")
   172  	return nil, ErrNotSupported
   173  }
   174  
   175  // getBuiltinDriver initializes and returns the registered driver, but does not try to load from plugins
   176  func getBuiltinDriver(name, home string, options []string, idMap idtools.IdentityMapping) (Driver, error) {
   177  	if initFunc, exists := drivers[name]; exists {
   178  		return initFunc(filepath.Join(home, name), options, idMap)
   179  	}
   180  	logrus.Errorf("Failed to built-in GetDriver graph %s %s", name, home)
   181  	return nil, ErrNotSupported
   182  }
   183  
   184  // Options is used to initialize a graphdriver
   185  type Options struct {
   186  	Root                string
   187  	DriverOptions       []string
   188  	IDMap               idtools.IdentityMapping
   189  	ExperimentalEnabled bool
   190  }
   191  
   192  // New creates the driver and initializes it at the specified root.
   193  func New(name string, pg plugingetter.PluginGetter, config Options) (Driver, error) {
   194  	if name != "" {
   195  		logrus.Infof("[graphdriver] trying configured driver: %s", name)
   196  		if isDeprecated(name) {
   197  			logrus.Warnf("[graphdriver] WARNING: the %s storage-driver is deprecated and will be removed in a future release; visit https://docs.docker.com/go/storage-driver/ for more information", name)
   198  		}
   199  		return GetDriver(name, pg, config)
   200  	}
   201  
   202  	// Guess for prior driver
   203  	driversMap := scanPriorDrivers(config.Root)
   204  	priorityList := strings.Split(priority, ",")
   205  	logrus.Debugf("[graphdriver] priority list: %v", priorityList)
   206  	for _, name := range priorityList {
   207  		if _, prior := driversMap[name]; prior {
   208  			// of the state found from prior drivers, check in order of our priority
   209  			// which we would prefer
   210  			driver, err := getBuiltinDriver(name, config.Root, config.DriverOptions, config.IDMap)
   211  			if err != nil {
   212  				// unlike below, we will return error here, because there is prior
   213  				// state, and now it is no longer supported/prereq/compatible, so
   214  				// something changed and needs attention. Otherwise the daemon's
   215  				// images would just "disappear".
   216  				logrus.Errorf("[graphdriver] prior storage driver %s failed: %s", name, err)
   217  				return nil, err
   218  			}
   219  			if isDeprecated(name) {
   220  				err = errors.Errorf("prior storage driver %s is deprecated and will be removed in a future release; update the the daemon configuration and explicitly choose this storage driver to continue using it; visit https://docs.docker.com/go/storage-driver/ for more information", name)
   221  				logrus.Errorf("[graphdriver] %v", err)
   222  				return nil, err
   223  			}
   224  
   225  			// abort starting when there are other prior configured drivers
   226  			// to ensure the user explicitly selects the driver to load
   227  			if len(driversMap) > 1 {
   228  				var driversSlice []string
   229  				for name := range driversMap {
   230  					driversSlice = append(driversSlice, name)
   231  				}
   232  
   233  				err = errors.Errorf("%s contains several valid graphdrivers: %s; cleanup or explicitly choose storage driver (-s <DRIVER>)", config.Root, strings.Join(driversSlice, ", "))
   234  				logrus.Errorf("[graphdriver] %v", err)
   235  				return nil, err
   236  			}
   237  
   238  			logrus.Infof("[graphdriver] using prior storage driver: %s", name)
   239  			return driver, nil
   240  		}
   241  	}
   242  
   243  	// If no prior state was found, continue with automatic selection, and pick
   244  	// the first supported, non-deprecated, storage driver (in order of priorityList).
   245  	for _, name := range priorityList {
   246  		if isDeprecated(name) {
   247  			// Deprecated storage-drivers are skipped in automatic selection, but
   248  			// can be selected through configuration.
   249  			continue
   250  		}
   251  		driver, err := getBuiltinDriver(name, config.Root, config.DriverOptions, config.IDMap)
   252  		if err != nil {
   253  			if IsDriverNotSupported(err) {
   254  				continue
   255  			}
   256  			return nil, err
   257  		}
   258  		return driver, nil
   259  	}
   260  
   261  	// Check all registered drivers if no priority driver is found
   262  	for name, initFunc := range drivers {
   263  		if isDeprecated(name) {
   264  			// Deprecated storage-drivers are skipped in automatic selection, but
   265  			// can be selected through configuration.
   266  			continue
   267  		}
   268  		driver, err := initFunc(filepath.Join(config.Root, name), config.DriverOptions, config.IDMap)
   269  		if err != nil {
   270  			if IsDriverNotSupported(err) {
   271  				continue
   272  			}
   273  			return nil, err
   274  		}
   275  		return driver, nil
   276  	}
   277  
   278  	return nil, errors.Errorf("no supported storage driver found")
   279  }
   280  
   281  // scanPriorDrivers returns an un-ordered scan of directories of prior storage
   282  // drivers. The 'vfs' storage driver is not taken into account, and ignored.
   283  func scanPriorDrivers(root string) map[string]bool {
   284  	driversMap := make(map[string]bool)
   285  
   286  	for driver := range drivers {
   287  		p := filepath.Join(root, driver)
   288  		if _, err := os.Stat(p); err == nil && driver != "vfs" {
   289  			if !isEmptyDir(p) {
   290  				driversMap[driver] = true
   291  			}
   292  		}
   293  	}
   294  	return driversMap
   295  }
   296  
   297  // isEmptyDir checks if a directory is empty. It is used to check if prior
   298  // storage-driver directories exist. If an error occurs, it also assumes the
   299  // directory is not empty (which preserves the behavior _before_ this check
   300  // was added)
   301  func isEmptyDir(name string) bool {
   302  	f, err := os.Open(name)
   303  	if err != nil {
   304  		return false
   305  	}
   306  	defer f.Close()
   307  
   308  	if _, err = f.Readdirnames(1); err == io.EOF {
   309  		return true
   310  	}
   311  	return false
   312  }
   313  
   314  // isDeprecated checks if a storage-driver is marked "deprecated"
   315  func isDeprecated(name string) bool {
   316  	switch name {
   317  	// NOTE: when deprecating a driver, update daemon.fillDriverInfo() accordingly
   318  	case "aufs", "devicemapper", "overlay":
   319  		return true
   320  	}
   321  	return false
   322  }