driver.go 10 KB

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