zfs.go 12 KB

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