zfs.go 12 KB

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