zfs.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. // +build linux freebsd solaris
  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.MkdirAllAs(base, 0700, 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 used to implement graphdriver.ProtoDriver. There is no cleanup required for this driver.
  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, error) {
  313. mountpoint := d.mountPath(id)
  314. if count := d.ctr.Increment(mountpoint); count > 1 {
  315. return containerfs.NewLocalContainerFS(mountpoint), nil
  316. }
  317. filesystem := d.zfsPath(id)
  318. options := label.FormatMountLabel("", mountLabel)
  319. logrus.Debugf(`[zfs] mount("%s", "%s", "%s")`, filesystem, mountpoint, options)
  320. rootUID, rootGID, err := idtools.GetRootUIDGID(d.uidMaps, d.gidMaps)
  321. if err != nil {
  322. d.ctr.Decrement(mountpoint)
  323. return nil, err
  324. }
  325. // Create the target directories if they don't exist
  326. if err := idtools.MkdirAllAs(mountpoint, 0755, rootUID, rootGID); err != nil {
  327. d.ctr.Decrement(mountpoint)
  328. return nil, err
  329. }
  330. if err := mount.Mount(filesystem, mountpoint, "zfs", options); err != nil {
  331. d.ctr.Decrement(mountpoint)
  332. return nil, fmt.Errorf("error creating zfs mount of %s to %s: %v", filesystem, mountpoint, err)
  333. }
  334. // this could be our first mount after creation of the filesystem, and the root dir may still have root
  335. // permissions instead of the remapped root uid:gid (if user namespaces are enabled):
  336. if err := os.Chown(mountpoint, rootUID, rootGID); err != nil {
  337. mount.Unmount(mountpoint)
  338. d.ctr.Decrement(mountpoint)
  339. return nil, fmt.Errorf("error modifying zfs mountpoint (%s) directory ownership: %v", mountpoint, err)
  340. }
  341. return containerfs.NewLocalContainerFS(mountpoint), nil
  342. }
  343. // Put removes the existing mountpoint for the given id if it exists.
  344. func (d *Driver) Put(id string) error {
  345. mountpoint := d.mountPath(id)
  346. if count := d.ctr.Decrement(mountpoint); count > 0 {
  347. return nil
  348. }
  349. mounted, err := graphdriver.Mounted(graphdriver.FsMagicZfs, mountpoint)
  350. if err != nil || !mounted {
  351. return err
  352. }
  353. logrus.Debugf(`[zfs] unmount("%s")`, mountpoint)
  354. if err := mount.Unmount(mountpoint); err != nil {
  355. return fmt.Errorf("error unmounting to %s: %v", mountpoint, err)
  356. }
  357. return nil
  358. }
  359. // Exists checks to see if the cache entry exists for the given id.
  360. func (d *Driver) Exists(id string) bool {
  361. d.Lock()
  362. defer d.Unlock()
  363. return d.filesystemsCache[d.zfsPath(id)]
  364. }