zfs.go 11 KB

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