zfs.go 12 KB

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