zfs.go 12 KB

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