zfs.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. // +build linux freebsd
  2. package 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 used to clean up any remaining mounts
  154. func (d *Driver) Cleanup() error {
  155. return mount.RecursiveUnmount(d.options.mountPath)
  156. }
  157. // Status returns information about the ZFS filesystem. It returns a two dimensional array of information
  158. // such as pool name, dataset name, disk usage, parent quota and compression used.
  159. // Currently it return 'Zpool', 'Zpool Health', 'Parent Dataset', 'Space Used By Parent',
  160. // 'Space Available', 'Parent Quota' and 'Compression'.
  161. func (d *Driver) Status() [][2]string {
  162. parts := strings.Split(d.dataset.Name, "/")
  163. pool, err := zfs.GetZpool(parts[0])
  164. var poolName, poolHealth string
  165. if err == nil {
  166. poolName = pool.Name
  167. poolHealth = pool.Health
  168. } else {
  169. poolName = fmt.Sprintf("error while getting pool information %v", err)
  170. poolHealth = "not available"
  171. }
  172. quota := "no"
  173. if d.dataset.Quota != 0 {
  174. quota = strconv.FormatUint(d.dataset.Quota, 10)
  175. }
  176. return [][2]string{
  177. {"Zpool", poolName},
  178. {"Zpool Health", poolHealth},
  179. {"Parent Dataset", d.dataset.Name},
  180. {"Space Used By Parent", strconv.FormatUint(d.dataset.Used, 10)},
  181. {"Space Available", strconv.FormatUint(d.dataset.Avail, 10)},
  182. {"Parent Quota", quota},
  183. {"Compression", d.dataset.Compression},
  184. }
  185. }
  186. // GetMetadata returns image/container metadata related to graph driver
  187. func (d *Driver) GetMetadata(id string) (map[string]string, error) {
  188. return map[string]string{
  189. "Mountpoint": d.mountPath(id),
  190. "Dataset": d.zfsPath(id),
  191. }, nil
  192. }
  193. func (d *Driver) cloneFilesystem(name, parentName string) error {
  194. snapshotName := fmt.Sprintf("%d", time.Now().Nanosecond())
  195. parentDataset := zfs.Dataset{Name: parentName}
  196. snapshot, err := parentDataset.Snapshot(snapshotName /*recursive */, false)
  197. if err != nil {
  198. return err
  199. }
  200. _, err = snapshot.Clone(name, map[string]string{"mountpoint": "legacy"})
  201. if err == nil {
  202. d.Lock()
  203. d.filesystemsCache[name] = true
  204. d.Unlock()
  205. }
  206. if err != nil {
  207. snapshot.Destroy(zfs.DestroyDeferDeletion)
  208. return err
  209. }
  210. return snapshot.Destroy(zfs.DestroyDeferDeletion)
  211. }
  212. func (d *Driver) zfsPath(id string) string {
  213. return d.options.fsName + "/" + id
  214. }
  215. func (d *Driver) mountPath(id string) string {
  216. return path.Join(d.options.mountPath, "graph", getMountpoint(id))
  217. }
  218. // CreateReadWrite creates a layer that is writable for use as a container
  219. // file system.
  220. func (d *Driver) CreateReadWrite(id, parent string, opts *graphdriver.CreateOpts) error {
  221. return d.Create(id, parent, opts)
  222. }
  223. // Create prepares the dataset and filesystem for the ZFS driver for the given id under the parent.
  224. func (d *Driver) Create(id, parent string, opts *graphdriver.CreateOpts) error {
  225. var storageOpt map[string]string
  226. if opts != nil {
  227. storageOpt = opts.StorageOpt
  228. }
  229. err := d.create(id, parent, storageOpt)
  230. if err == nil {
  231. return nil
  232. }
  233. if zfsError, ok := err.(*zfs.Error); ok {
  234. if !strings.HasSuffix(zfsError.Stderr, "dataset already exists\n") {
  235. return err
  236. }
  237. // aborted build -> cleanup
  238. } else {
  239. return err
  240. }
  241. dataset := zfs.Dataset{Name: d.zfsPath(id)}
  242. if err := dataset.Destroy(zfs.DestroyRecursiveClones); err != nil {
  243. return err
  244. }
  245. // retry
  246. return d.create(id, parent, storageOpt)
  247. }
  248. func (d *Driver) create(id, parent string, storageOpt map[string]string) error {
  249. name := d.zfsPath(id)
  250. quota, err := parseStorageOpt(storageOpt)
  251. if err != nil {
  252. return err
  253. }
  254. if parent == "" {
  255. mountoptions := map[string]string{"mountpoint": "legacy"}
  256. fs, err := zfs.CreateFilesystem(name, mountoptions)
  257. if err == nil {
  258. err = setQuota(name, quota)
  259. if err == nil {
  260. d.Lock()
  261. d.filesystemsCache[fs.Name] = true
  262. d.Unlock()
  263. }
  264. }
  265. return err
  266. }
  267. err = d.cloneFilesystem(name, d.zfsPath(parent))
  268. if err == nil {
  269. err = setQuota(name, quota)
  270. }
  271. return err
  272. }
  273. func parseStorageOpt(storageOpt map[string]string) (string, error) {
  274. // Read size to change the disk quota per container
  275. for k, v := range storageOpt {
  276. key := strings.ToLower(k)
  277. switch key {
  278. case "size":
  279. return v, nil
  280. default:
  281. return "0", fmt.Errorf("Unknown option %s", key)
  282. }
  283. }
  284. return "0", nil
  285. }
  286. func setQuota(name string, quota string) error {
  287. if quota == "0" {
  288. return nil
  289. }
  290. fs, err := zfs.GetDataset(name)
  291. if err != nil {
  292. return err
  293. }
  294. return fs.SetProperty("quota", quota)
  295. }
  296. // Remove deletes the dataset, filesystem and the cache for the given id.
  297. func (d *Driver) Remove(id string) error {
  298. name := d.zfsPath(id)
  299. dataset := zfs.Dataset{Name: name}
  300. err := dataset.Destroy(zfs.DestroyRecursive)
  301. if err == nil {
  302. d.Lock()
  303. delete(d.filesystemsCache, name)
  304. d.Unlock()
  305. }
  306. return err
  307. }
  308. // Get returns the mountpoint for the given id after creating the target directories if necessary.
  309. func (d *Driver) Get(id, mountLabel string) (_ containerfs.ContainerFS, retErr error) {
  310. mountpoint := d.mountPath(id)
  311. if count := d.ctr.Increment(mountpoint); count > 1 {
  312. return containerfs.NewLocalContainerFS(mountpoint), nil
  313. }
  314. defer func() {
  315. if retErr != nil {
  316. if c := d.ctr.Decrement(mountpoint); c <= 0 {
  317. if mntErr := unix.Unmount(mountpoint, 0); mntErr != nil {
  318. logrus.Errorf("Error unmounting %v: %v", mountpoint, mntErr)
  319. }
  320. if rmErr := unix.Rmdir(mountpoint); rmErr != nil && !os.IsNotExist(rmErr) {
  321. logrus.Debugf("Failed to remove %s: %v", id, rmErr)
  322. }
  323. }
  324. }
  325. }()
  326. filesystem := d.zfsPath(id)
  327. options := label.FormatMountLabel("", mountLabel)
  328. logrus.Debugf(`[zfs] mount("%s", "%s", "%s")`, filesystem, mountpoint, options)
  329. rootUID, rootGID, err := idtools.GetRootUIDGID(d.uidMaps, d.gidMaps)
  330. if err != nil {
  331. return nil, err
  332. }
  333. // Create the target directories if they don't exist
  334. if err := idtools.MkdirAllAndChown(mountpoint, 0755, idtools.IDPair{rootUID, rootGID}); err != nil {
  335. return nil, err
  336. }
  337. if err := mount.Mount(filesystem, mountpoint, "zfs", options); err != nil {
  338. return nil, fmt.Errorf("error creating zfs mount of %s to %s: %v", filesystem, mountpoint, err)
  339. }
  340. // this could be our first mount after creation of the filesystem, and the root dir may still have root
  341. // permissions instead of the remapped root uid:gid (if user namespaces are enabled):
  342. if err := os.Chown(mountpoint, rootUID, rootGID); err != nil {
  343. return nil, fmt.Errorf("error modifying zfs mountpoint (%s) directory ownership: %v", mountpoint, err)
  344. }
  345. return containerfs.NewLocalContainerFS(mountpoint), nil
  346. }
  347. // Put removes the existing mountpoint for the given id if it exists.
  348. func (d *Driver) Put(id string) error {
  349. mountpoint := d.mountPath(id)
  350. if count := d.ctr.Decrement(mountpoint); count > 0 {
  351. return nil
  352. }
  353. logrus.Debugf(`[zfs] unmount("%s")`, mountpoint)
  354. if err := unix.Unmount(mountpoint, unix.MNT_DETACH); err != nil {
  355. logrus.Warnf("Failed to unmount %s mount %s: %v", id, mountpoint, err)
  356. }
  357. if err := unix.Rmdir(mountpoint); err != nil && !os.IsNotExist(err) {
  358. logrus.Debugf("Failed to remove %s mount point %s: %v", id, mountpoint, err)
  359. }
  360. return nil
  361. }
  362. // Exists checks to see if the cache entry exists for the given id.
  363. func (d *Driver) Exists(id string) bool {
  364. d.Lock()
  365. defer d.Unlock()
  366. return d.filesystemsCache[d.zfsPath(id)]
  367. }