zfs.go 12 KB

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