driver.go 11 KB

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