zfs.go 11 KB

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