zfs.go 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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. d := &Driver{
  84. dataset: rootDataset,
  85. options: options,
  86. filesystemsCache: filesystemsCache,
  87. uidMaps: uidMaps,
  88. gidMaps: gidMaps,
  89. ctr: graphdriver.NewRefCounter(graphdriver.NewDefaultChecker()),
  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. if len(storageOpt) != 0 {
  215. return fmt.Errorf("--storage-opt is not supported for zfs")
  216. }
  217. err := d.create(id, parent)
  218. if err == nil {
  219. return nil
  220. }
  221. if zfsError, ok := err.(*zfs.Error); ok {
  222. if !strings.HasSuffix(zfsError.Stderr, "dataset already exists\n") {
  223. return err
  224. }
  225. // aborted build -> cleanup
  226. } else {
  227. return err
  228. }
  229. dataset := zfs.Dataset{Name: d.zfsPath(id)}
  230. if err := dataset.Destroy(zfs.DestroyRecursiveClones); err != nil {
  231. return err
  232. }
  233. // retry
  234. return d.create(id, parent)
  235. }
  236. func (d *Driver) create(id, parent string) error {
  237. name := d.zfsPath(id)
  238. if parent == "" {
  239. mountoptions := map[string]string{"mountpoint": "legacy"}
  240. fs, err := zfs.CreateFilesystem(name, mountoptions)
  241. if err == nil {
  242. d.Lock()
  243. d.filesystemsCache[fs.Name] = true
  244. d.Unlock()
  245. }
  246. return err
  247. }
  248. return d.cloneFilesystem(name, d.zfsPath(parent))
  249. }
  250. // Remove deletes the dataset, filesystem and the cache for the given id.
  251. func (d *Driver) Remove(id string) error {
  252. name := d.zfsPath(id)
  253. dataset := zfs.Dataset{Name: name}
  254. err := dataset.Destroy(zfs.DestroyRecursive)
  255. if err == nil {
  256. d.Lock()
  257. delete(d.filesystemsCache, name)
  258. d.Unlock()
  259. }
  260. return err
  261. }
  262. // Get returns the mountpoint for the given id after creating the target directories if necessary.
  263. func (d *Driver) Get(id, mountLabel string) (string, error) {
  264. mountpoint := d.mountPath(id)
  265. if count := d.ctr.Increment(mountpoint); count > 1 {
  266. return mountpoint, nil
  267. }
  268. filesystem := d.zfsPath(id)
  269. options := label.FormatMountLabel("", mountLabel)
  270. logrus.Debugf(`[zfs] mount("%s", "%s", "%s")`, filesystem, mountpoint, options)
  271. rootUID, rootGID, err := idtools.GetRootUIDGID(d.uidMaps, d.gidMaps)
  272. if err != nil {
  273. d.ctr.Decrement(mountpoint)
  274. return "", err
  275. }
  276. // Create the target directories if they don't exist
  277. if err := idtools.MkdirAllAs(mountpoint, 0755, rootUID, rootGID); err != nil {
  278. d.ctr.Decrement(mountpoint)
  279. return "", err
  280. }
  281. if err := mount.Mount(filesystem, mountpoint, "zfs", options); err != nil {
  282. d.ctr.Decrement(mountpoint)
  283. return "", fmt.Errorf("error creating zfs mount of %s to %s: %v", filesystem, mountpoint, err)
  284. }
  285. // this could be our first mount after creation of the filesystem, and the root dir may still have root
  286. // permissions instead of the remapped root uid:gid (if user namespaces are enabled):
  287. if err := os.Chown(mountpoint, rootUID, rootGID); err != nil {
  288. mount.Unmount(mountpoint)
  289. d.ctr.Decrement(mountpoint)
  290. return "", fmt.Errorf("error modifying zfs mountpoint (%s) directory ownership: %v", mountpoint, err)
  291. }
  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. mountpoint := d.mountPath(id)
  297. if count := d.ctr.Decrement(mountpoint); count > 0 {
  298. return nil
  299. }
  300. mounted, err := graphdriver.Mounted(graphdriver.FsMagicZfs, mountpoint)
  301. if err != nil || !mounted {
  302. return err
  303. }
  304. logrus.Debugf(`[zfs] unmount("%s")`, mountpoint)
  305. if err := mount.Unmount(mountpoint); err != nil {
  306. return fmt.Errorf("error unmounting to %s: %v", mountpoint, err)
  307. }
  308. return nil
  309. }
  310. // Exists checks to see if the cache entry exists for the given id.
  311. func (d *Driver) Exists(id string) bool {
  312. d.Lock()
  313. defer d.Unlock()
  314. return d.filesystemsCache[d.zfsPath(id)] == true
  315. }