zfs.go 12 KB

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