zfs.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. //go:build linux || freebsd
  2. // +build linux freebsd
  3. package zfs // import "github.com/docker/docker/daemon/graphdriver/zfs"
  4. import (
  5. "fmt"
  6. "os"
  7. "os/exec"
  8. "path"
  9. "strconv"
  10. "strings"
  11. "sync"
  12. "time"
  13. "github.com/docker/docker/daemon/graphdriver"
  14. "github.com/docker/docker/pkg/containerfs"
  15. "github.com/docker/docker/pkg/idtools"
  16. "github.com/docker/docker/pkg/parsers"
  17. zfs "github.com/mistifyio/go-zfs"
  18. "github.com/moby/locker"
  19. "github.com/moby/sys/mount"
  20. "github.com/moby/sys/mountinfo"
  21. "github.com/opencontainers/selinux/go-selinux/label"
  22. "github.com/pkg/errors"
  23. "github.com/sirupsen/logrus"
  24. "golang.org/x/sys/unix"
  25. )
  26. type zfsOptions struct {
  27. fsName string
  28. mountPath string
  29. }
  30. func init() {
  31. graphdriver.Register("zfs", Init)
  32. }
  33. // Logger returns a zfs logger implementation.
  34. type Logger struct{}
  35. // Log wraps log message from ZFS driver with a prefix '[zfs]'.
  36. func (*Logger) Log(cmd []string) {
  37. logrus.WithField("storage-driver", "zfs").Debugf("[zfs] %s", strings.Join(cmd, " "))
  38. }
  39. // Init returns a new ZFS driver.
  40. // It takes base mount path and an array of options which are represented as key value pairs.
  41. // Each option is in the for key=value. 'zfs.fsname' is expected to be a valid key in the options.
  42. func Init(base string, opt []string, idMap idtools.IdentityMapping) (graphdriver.Driver, error) {
  43. var err error
  44. logger := logrus.WithField("storage-driver", "zfs")
  45. if _, err := exec.LookPath("zfs"); err != nil {
  46. logger.Debugf("zfs command is not available: %v", err)
  47. return nil, graphdriver.ErrPrerequisites
  48. }
  49. file, err := os.OpenFile("/dev/zfs", os.O_RDWR, 0600)
  50. if err != nil {
  51. logger.Debugf("cannot open /dev/zfs: %v", err)
  52. return nil, graphdriver.ErrPrerequisites
  53. }
  54. defer file.Close()
  55. options, err := parseOptions(opt)
  56. if err != nil {
  57. return nil, err
  58. }
  59. options.mountPath = base
  60. rootdir := path.Dir(base)
  61. if options.fsName == "" {
  62. err = checkRootdirFs(rootdir)
  63. if err != nil {
  64. return nil, err
  65. }
  66. }
  67. if options.fsName == "" {
  68. options.fsName, err = lookupZfsDataset(rootdir)
  69. if err != nil {
  70. return nil, err
  71. }
  72. }
  73. zfs.SetLogger(new(Logger))
  74. filesystems, err := zfs.Filesystems(options.fsName)
  75. if err != nil {
  76. return nil, fmt.Errorf("Cannot find root filesystem %s: %v", options.fsName, err)
  77. }
  78. filesystemsCache := make(map[string]bool, len(filesystems))
  79. var rootDataset *zfs.Dataset
  80. for _, fs := range filesystems {
  81. if fs.Name == options.fsName {
  82. rootDataset = fs
  83. }
  84. filesystemsCache[fs.Name] = true
  85. }
  86. if rootDataset == nil {
  87. return nil, fmt.Errorf("BUG: zfs get all -t filesystem -rHp '%s' should contain '%s'", options.fsName, options.fsName)
  88. }
  89. dirID := idtools.Identity{
  90. UID: idtools.CurrentIdentity().UID,
  91. GID: idMap.RootPair().GID,
  92. }
  93. if err := idtools.MkdirAllAndChown(base, 0710, dirID); err != nil {
  94. return nil, fmt.Errorf("Failed to create '%s': %v", base, err)
  95. }
  96. d := &Driver{
  97. dataset: rootDataset,
  98. options: options,
  99. filesystemsCache: filesystemsCache,
  100. idMap: idMap,
  101. ctr: graphdriver.NewRefCounter(graphdriver.NewDefaultChecker()),
  102. locker: locker.New(),
  103. }
  104. return graphdriver.NewNaiveDiffDriver(d, idMap), nil
  105. }
  106. func parseOptions(opt []string) (zfsOptions, error) {
  107. var options zfsOptions
  108. options.fsName = ""
  109. for _, option := range opt {
  110. key, val, err := parsers.ParseKeyValueOpt(option)
  111. if err != nil {
  112. return options, err
  113. }
  114. key = strings.ToLower(key)
  115. switch key {
  116. case "zfs.fsname":
  117. options.fsName = val
  118. default:
  119. return options, fmt.Errorf("Unknown option %s", key)
  120. }
  121. }
  122. return options, nil
  123. }
  124. func lookupZfsDataset(rootdir string) (string, error) {
  125. var stat unix.Stat_t
  126. if err := unix.Stat(rootdir, &stat); err != nil {
  127. return "", fmt.Errorf("Failed to access '%s': %s", rootdir, err)
  128. }
  129. wantedDev := stat.Dev
  130. mounts, err := mountinfo.GetMounts(nil)
  131. if err != nil {
  132. return "", err
  133. }
  134. for _, m := range mounts {
  135. if err := unix.Stat(m.Mountpoint, &stat); err != nil {
  136. logrus.WithField("storage-driver", "zfs").Debugf("failed to stat '%s' while scanning for zfs mount: %v", m.Mountpoint, err)
  137. continue // may fail on fuse file systems
  138. }
  139. if stat.Dev == wantedDev && m.FSType == "zfs" {
  140. return m.Source, nil
  141. }
  142. }
  143. return "", fmt.Errorf("Failed to find zfs dataset mounted on '%s' in /proc/mounts", rootdir)
  144. }
  145. // Driver holds information about the driver, such as zfs dataset, options and cache.
  146. type Driver struct {
  147. dataset *zfs.Dataset
  148. options zfsOptions
  149. sync.Mutex // protects filesystem cache against concurrent access
  150. filesystemsCache map[string]bool
  151. idMap idtools.IdentityMapping
  152. ctr *graphdriver.RefCounter
  153. locker *locker.Locker
  154. }
  155. func (d *Driver) String() string {
  156. return "zfs"
  157. }
  158. // Cleanup is called on daemon shutdown, it is a no-op for ZFS.
  159. // TODO(@cpuguy83): Walk layer tree and check mounts?
  160. func (d *Driver) Cleanup() error {
  161. return nil
  162. }
  163. // Status returns information about the ZFS filesystem. It returns a two dimensional array of information
  164. // such as pool name, dataset name, disk usage, parent quota and compression used.
  165. // Currently it return 'Zpool', 'Zpool Health', 'Parent Dataset', 'Space Used By Parent',
  166. // 'Space Available', 'Parent Quota' and 'Compression'.
  167. func (d *Driver) Status() [][2]string {
  168. parts := strings.Split(d.dataset.Name, "/")
  169. pool, err := zfs.GetZpool(parts[0])
  170. var poolName, poolHealth string
  171. if err == nil {
  172. poolName = pool.Name
  173. poolHealth = pool.Health
  174. } else {
  175. poolName = fmt.Sprintf("error while getting pool information %v", err)
  176. poolHealth = "not available"
  177. }
  178. quota := "no"
  179. if d.dataset.Quota != 0 {
  180. quota = strconv.FormatUint(d.dataset.Quota, 10)
  181. }
  182. return [][2]string{
  183. {"Zpool", poolName},
  184. {"Zpool Health", poolHealth},
  185. {"Parent Dataset", d.dataset.Name},
  186. {"Space Used By Parent", strconv.FormatUint(d.dataset.Used, 10)},
  187. {"Space Available", strconv.FormatUint(d.dataset.Avail, 10)},
  188. {"Parent Quota", quota},
  189. {"Compression", d.dataset.Compression},
  190. }
  191. }
  192. // GetMetadata returns image/container metadata related to graph driver
  193. func (d *Driver) GetMetadata(id string) (map[string]string, error) {
  194. return map[string]string{
  195. "Mountpoint": d.mountPath(id),
  196. "Dataset": d.zfsPath(id),
  197. }, nil
  198. }
  199. func (d *Driver) cloneFilesystem(name, parentName string) error {
  200. snapshotName := fmt.Sprintf("%d", time.Now().Nanosecond())
  201. parentDataset := zfs.Dataset{Name: parentName}
  202. snapshot, err := parentDataset.Snapshot(snapshotName /*recursive */, false)
  203. if err != nil {
  204. return err
  205. }
  206. _, err = snapshot.Clone(name, map[string]string{"mountpoint": "legacy"})
  207. if err == nil {
  208. d.Lock()
  209. d.filesystemsCache[name] = true
  210. d.Unlock()
  211. }
  212. if err != nil {
  213. snapshot.Destroy(zfs.DestroyDeferDeletion)
  214. return err
  215. }
  216. return snapshot.Destroy(zfs.DestroyDeferDeletion)
  217. }
  218. func (d *Driver) zfsPath(id string) string {
  219. return d.options.fsName + "/" + id
  220. }
  221. func (d *Driver) mountPath(id string) string {
  222. return path.Join(d.options.mountPath, "graph", getMountpoint(id))
  223. }
  224. // CreateReadWrite creates a layer that is writable for use as a container
  225. // file system.
  226. func (d *Driver) CreateReadWrite(id, parent string, opts *graphdriver.CreateOpts) error {
  227. return d.Create(id, parent, opts)
  228. }
  229. // Create prepares the dataset and filesystem for the ZFS driver for the given id under the parent.
  230. func (d *Driver) Create(id, parent string, opts *graphdriver.CreateOpts) error {
  231. var storageOpt map[string]string
  232. if opts != nil {
  233. storageOpt = opts.StorageOpt
  234. }
  235. err := d.create(id, parent, storageOpt)
  236. if err == nil {
  237. return nil
  238. }
  239. if zfsError, ok := err.(*zfs.Error); ok {
  240. if !strings.HasSuffix(zfsError.Stderr, "dataset already exists\n") {
  241. return err
  242. }
  243. // aborted build -> cleanup
  244. } else {
  245. return err
  246. }
  247. dataset := zfs.Dataset{Name: d.zfsPath(id)}
  248. if err := dataset.Destroy(zfs.DestroyRecursiveClones); err != nil {
  249. return err
  250. }
  251. // retry
  252. return d.create(id, parent, storageOpt)
  253. }
  254. func (d *Driver) create(id, parent string, storageOpt map[string]string) error {
  255. name := d.zfsPath(id)
  256. quota, err := parseStorageOpt(storageOpt)
  257. if err != nil {
  258. return err
  259. }
  260. if parent == "" {
  261. mountoptions := map[string]string{"mountpoint": "legacy"}
  262. fs, err := zfs.CreateFilesystem(name, mountoptions)
  263. if err == nil {
  264. err = setQuota(name, quota)
  265. if err == nil {
  266. d.Lock()
  267. d.filesystemsCache[fs.Name] = true
  268. d.Unlock()
  269. }
  270. }
  271. return err
  272. }
  273. err = d.cloneFilesystem(name, d.zfsPath(parent))
  274. if err == nil {
  275. err = setQuota(name, quota)
  276. }
  277. return err
  278. }
  279. func parseStorageOpt(storageOpt map[string]string) (string, error) {
  280. // Read size to change the disk quota per container
  281. for k, v := range storageOpt {
  282. key := strings.ToLower(k)
  283. switch key {
  284. case "size":
  285. return v, nil
  286. default:
  287. return "0", fmt.Errorf("Unknown option %s", key)
  288. }
  289. }
  290. return "0", nil
  291. }
  292. func setQuota(name string, quota string) error {
  293. if quota == "0" {
  294. return nil
  295. }
  296. fs, err := zfs.GetDataset(name)
  297. if err != nil {
  298. return err
  299. }
  300. return fs.SetProperty("quota", quota)
  301. }
  302. // Remove deletes the dataset, filesystem and the cache for the given id.
  303. func (d *Driver) Remove(id string) error {
  304. d.locker.Lock(id)
  305. defer d.locker.Unlock(id)
  306. name := d.zfsPath(id)
  307. dataset := zfs.Dataset{Name: name}
  308. err := dataset.Destroy(zfs.DestroyRecursive)
  309. if err == nil {
  310. d.Lock()
  311. delete(d.filesystemsCache, name)
  312. d.Unlock()
  313. }
  314. return err
  315. }
  316. // Get returns the mountpoint for the given id after creating the target directories if necessary.
  317. func (d *Driver) Get(id, mountLabel string) (_ containerfs.ContainerFS, retErr error) {
  318. d.locker.Lock(id)
  319. defer d.locker.Unlock(id)
  320. mountpoint := d.mountPath(id)
  321. if count := d.ctr.Increment(mountpoint); count > 1 {
  322. return containerfs.NewLocalContainerFS(mountpoint), nil
  323. }
  324. defer func() {
  325. if retErr != nil {
  326. if c := d.ctr.Decrement(mountpoint); c <= 0 {
  327. if mntErr := unix.Unmount(mountpoint, 0); mntErr != nil {
  328. logrus.WithField("storage-driver", "zfs").Errorf("Error unmounting %v: %v", mountpoint, mntErr)
  329. }
  330. if rmErr := unix.Rmdir(mountpoint); rmErr != nil && !os.IsNotExist(rmErr) {
  331. logrus.WithField("storage-driver", "zfs").Debugf("Failed to remove %s: %v", id, rmErr)
  332. }
  333. }
  334. }
  335. }()
  336. filesystem := d.zfsPath(id)
  337. options := label.FormatMountLabel("", mountLabel)
  338. logrus.WithField("storage-driver", "zfs").Debugf(`mount("%s", "%s", "%s")`, filesystem, mountpoint, options)
  339. root := d.idMap.RootPair()
  340. // Create the target directories if they don't exist
  341. if err := idtools.MkdirAllAndChown(mountpoint, 0755, root); err != nil {
  342. return nil, err
  343. }
  344. if err := mount.Mount(filesystem, mountpoint, "zfs", options); err != nil {
  345. return nil, errors.Wrap(err, "error creating zfs mount")
  346. }
  347. // this could be our first mount after creation of the filesystem, and the root dir may still have root
  348. // permissions instead of the remapped root uid:gid (if user namespaces are enabled):
  349. if err := root.Chown(mountpoint); err != nil {
  350. return nil, fmt.Errorf("error modifying zfs mountpoint (%s) directory ownership: %v", mountpoint, err)
  351. }
  352. return containerfs.NewLocalContainerFS(mountpoint), nil
  353. }
  354. // Put removes the existing mountpoint for the given id if it exists.
  355. func (d *Driver) Put(id string) error {
  356. d.locker.Lock(id)
  357. defer d.locker.Unlock(id)
  358. mountpoint := d.mountPath(id)
  359. if count := d.ctr.Decrement(mountpoint); count > 0 {
  360. return nil
  361. }
  362. logger := logrus.WithField("storage-driver", "zfs")
  363. logger.Debugf(`unmount("%s")`, mountpoint)
  364. if err := unix.Unmount(mountpoint, unix.MNT_DETACH); err != nil {
  365. logger.Warnf("Failed to unmount %s mount %s: %v", id, mountpoint, err)
  366. }
  367. if err := unix.Rmdir(mountpoint); err != nil && !os.IsNotExist(err) {
  368. logger.Debugf("Failed to remove %s mount point %s: %v", id, mountpoint, err)
  369. }
  370. return nil
  371. }
  372. // Exists checks to see if the cache entry exists for the given id.
  373. func (d *Driver) Exists(id string) bool {
  374. d.Lock()
  375. defer d.Unlock()
  376. return d.filesystemsCache[d.zfsPath(id)]
  377. }