zfs.go 9.8 KB

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