1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
26 "git.curoverse.com/arvados.git/sdk/go/arvados"
27 "github.com/prometheus/client_golang/prometheus"
28 "github.com/sirupsen/logrus"
32 driver["Directory"] = newDirectoryVolume
35 func newDirectoryVolume(cluster *arvados.Cluster, volume arvados.Volume, logger logrus.FieldLogger, metrics *volumeMetricsVecs) (Volume, error) {
36 v := &UnixVolume{cluster: cluster, volume: volume, logger: logger, metrics: metrics}
37 err := json.Unmarshal(volume.DriverParameters, &v)
44 func (v *UnixVolume) check() error {
46 return errors.New("DriverParameters.Root was not provided")
49 v.locker = &sync.Mutex{}
51 if !strings.HasPrefix(v.Root, "/") {
52 return fmt.Errorf("DriverParameters.Root %q does not start with '/'", v.Root)
55 // Set up prometheus metrics
56 lbls := prometheus.Labels{"device_id": v.GetDeviceID()}
57 v.os.stats.opsCounters, v.os.stats.errCounters, v.os.stats.ioBytes = v.metrics.getCounterVecsFor(lbls)
59 _, err := v.os.Stat(v.Root)
63 // A UnixVolume stores and retrieves blocks in a local directory.
64 type UnixVolume struct {
65 Root string // path to the volume's root directory
68 cluster *arvados.Cluster
70 logger logrus.FieldLogger
71 metrics *volumeMetricsVecs
73 // something to lock during IO, typically a sync.Mutex (or nil
80 // GetDeviceID returns a globally unique ID for the volume's root
81 // directory, consisting of the filesystem's UUID and the path from
82 // filesystem root to storage directory, joined by "/". For example,
83 // the device ID for a local directory "/mnt/xvda1/keep" might be
84 // "fa0b6166-3b55-4994-bd3f-92f4e00a1bb0/keep".
85 func (v *UnixVolume) GetDeviceID() string {
86 giveup := func(f string, args ...interface{}) string {
87 log.Printf(f+"; using blank DeviceID for volume %s", append(args, v)...)
90 buf, err := exec.Command("findmnt", "--noheadings", "--target", v.Root).CombinedOutput()
92 return giveup("findmnt: %s (%q)", err, buf)
94 findmnt := strings.Fields(string(buf))
96 return giveup("could not parse findmnt output: %q", buf)
98 fsRoot, dev := findmnt[0], findmnt[1]
100 absRoot, err := filepath.Abs(v.Root)
102 return giveup("resolving relative path %q: %s", v.Root, err)
104 realRoot, err := filepath.EvalSymlinks(absRoot)
106 return giveup("resolving symlinks in %q: %s", absRoot, err)
109 // Find path from filesystem root to realRoot
111 if strings.HasPrefix(realRoot, fsRoot+"/") {
112 fsPath = realRoot[len(fsRoot):]
113 } else if fsRoot == "/" {
115 } else if fsRoot == realRoot {
118 return giveup("findmnt reports mount point %q which is not a prefix of volume root %q", fsRoot, realRoot)
121 if !strings.HasPrefix(dev, "/") {
122 return giveup("mount %q device %q is not a path", fsRoot, dev)
125 fi, err := os.Stat(dev)
127 return giveup("stat %q: %s", dev, err)
129 ino := fi.Sys().(*syscall.Stat_t).Ino
131 // Find a symlink in /dev/disk/by-uuid/ whose target is (i.e.,
132 // has the same inode as) the mounted device
133 udir := "/dev/disk/by-uuid"
134 d, err := os.Open(udir)
136 return giveup("opening %q: %s", udir, err)
138 uuids, err := d.Readdirnames(0)
140 return giveup("reading %q: %s", udir, err)
142 for _, uuid := range uuids {
143 link := filepath.Join(udir, uuid)
144 fi, err = os.Stat(link)
146 log.Printf("error: stat %q: %s", link, err)
149 if fi.Sys().(*syscall.Stat_t).Ino == ino {
153 return giveup("could not find entry in %q matching %q", udir, dev)
156 // Touch sets the timestamp for the given locator to the current time
157 func (v *UnixVolume) Touch(loc string) error {
158 if v.volume.ReadOnly {
159 return MethodDisabledError
161 p := v.blockPath(loc)
162 f, err := v.os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
167 if err := v.lock(context.TODO()); err != nil {
171 if e := v.lockfile(f); e != nil {
174 defer v.unlockfile(f)
175 ts := syscall.NsecToTimespec(time.Now().UnixNano())
176 v.os.stats.TickOps("utimes")
177 v.os.stats.Tick(&v.os.stats.UtimesOps)
178 err = syscall.UtimesNano(p, []syscall.Timespec{ts, ts})
179 v.os.stats.TickErr(err)
183 // Mtime returns the stored timestamp for the given locator.
184 func (v *UnixVolume) Mtime(loc string) (time.Time, error) {
185 p := v.blockPath(loc)
186 fi, err := v.os.Stat(p)
188 return time.Time{}, err
190 return fi.ModTime(), nil
193 // Lock the locker (if one is in use), open the file for reading, and
194 // call the given function if and when the file is ready to read.
195 func (v *UnixVolume) getFunc(ctx context.Context, path string, fn func(io.Reader) error) error {
196 if err := v.lock(ctx); err != nil {
200 f, err := v.os.Open(path)
205 return fn(NewCountingReader(ioutil.NopCloser(f), v.os.stats.TickInBytes))
208 // stat is os.Stat() with some extra sanity checks.
209 func (v *UnixVolume) stat(path string) (os.FileInfo, error) {
210 stat, err := v.os.Stat(path)
214 } else if stat.Size() > BlockSize {
221 // Get retrieves a block, copies it to the given slice, and returns
222 // the number of bytes copied.
223 func (v *UnixVolume) Get(ctx context.Context, loc string, buf []byte) (int, error) {
224 return getWithPipe(ctx, loc, buf, v)
227 // ReadBlock implements BlockReader.
228 func (v *UnixVolume) ReadBlock(ctx context.Context, loc string, w io.Writer) error {
229 path := v.blockPath(loc)
230 stat, err := v.stat(path)
232 return v.translateError(err)
234 return v.getFunc(ctx, path, func(rdr io.Reader) error {
235 n, err := io.Copy(w, rdr)
236 if err == nil && n != stat.Size() {
237 err = io.ErrUnexpectedEOF
243 // Compare returns nil if Get(loc) would return the same content as
244 // expect. It is functionally equivalent to Get() followed by
245 // bytes.Compare(), but uses less memory.
246 func (v *UnixVolume) Compare(ctx context.Context, loc string, expect []byte) error {
247 path := v.blockPath(loc)
248 if _, err := v.stat(path); err != nil {
249 return v.translateError(err)
251 return v.getFunc(ctx, path, func(rdr io.Reader) error {
252 return compareReaderWithBuf(ctx, rdr, expect, loc[:32])
256 // Put stores a block of data identified by the locator string
257 // "loc". It returns nil on success. If the volume is full, it
258 // returns a FullError. If the write fails due to some other error,
259 // that error is returned.
260 func (v *UnixVolume) Put(ctx context.Context, loc string, block []byte) error {
261 return putWithPipe(ctx, loc, block, v)
264 // WriteBlock implements BlockWriter.
265 func (v *UnixVolume) WriteBlock(ctx context.Context, loc string, rdr io.Reader) error {
266 if v.volume.ReadOnly {
267 return MethodDisabledError
272 bdir := v.blockDir(loc)
273 if err := os.MkdirAll(bdir, 0755); err != nil {
274 log.Printf("%s: could not create directory %s: %s",
279 tmpfile, tmperr := v.os.TempFile(bdir, "tmp"+loc)
281 log.Printf("ioutil.TempFile(%s, tmp%s): %s", bdir, loc, tmperr)
285 bpath := v.blockPath(loc)
287 if err := v.lock(ctx); err != nil {
291 n, err := io.Copy(tmpfile, rdr)
292 v.os.stats.TickOutBytes(uint64(n))
294 log.Printf("%s: writing to %s: %s", v, bpath, err)
296 v.os.Remove(tmpfile.Name())
299 if err := tmpfile.Close(); err != nil {
300 log.Printf("closing %s: %s", tmpfile.Name(), err)
301 v.os.Remove(tmpfile.Name())
304 if err := v.os.Rename(tmpfile.Name(), bpath); err != nil {
305 log.Printf("rename %s %s: %s", tmpfile.Name(), bpath, err)
306 return v.os.Remove(tmpfile.Name())
311 // Status returns a VolumeStatus struct describing the volume's
312 // current state, or nil if an error occurs.
314 func (v *UnixVolume) Status() *VolumeStatus {
315 fi, err := v.os.Stat(v.Root)
317 log.Printf("%s: os.Stat: %s", v, err)
320 devnum := fi.Sys().(*syscall.Stat_t).Dev
322 var fs syscall.Statfs_t
323 if err := syscall.Statfs(v.Root, &fs); err != nil {
324 log.Printf("%s: statfs: %s", v, err)
327 // These calculations match the way df calculates disk usage:
328 // "free" space is measured by fs.Bavail, but "used" space
329 // uses fs.Blocks - fs.Bfree.
330 free := fs.Bavail * uint64(fs.Bsize)
331 used := (fs.Blocks - fs.Bfree) * uint64(fs.Bsize)
332 return &VolumeStatus{
340 var blockDirRe = regexp.MustCompile(`^[0-9a-f]+$`)
341 var blockFileRe = regexp.MustCompile(`^[0-9a-f]{32}$`)
343 // IndexTo writes (to the given Writer) a list of blocks found on this
344 // volume which begin with the specified prefix. If the prefix is an
345 // empty string, IndexTo writes a complete list of blocks.
347 // Each block is given in the format
349 // locator+size modification-time {newline}
353 // e4df392f86be161ca6ed3773a962b8f3+67108864 1388894303
354 // e4d41e6fd68460e0e3fc18cc746959d2+67108864 1377796043
355 // e4de7a2810f5554cd39b36d8ddb132ff+67108864 1388701136
357 func (v *UnixVolume) IndexTo(prefix string, w io.Writer) error {
359 rootdir, err := v.os.Open(v.Root)
363 defer rootdir.Close()
364 v.os.stats.TickOps("readdir")
365 v.os.stats.Tick(&v.os.stats.ReaddirOps)
367 names, err := rootdir.Readdirnames(1)
370 } else if err != nil {
373 if !strings.HasPrefix(names[0], prefix) && !strings.HasPrefix(prefix, names[0]) {
374 // prefix excludes all blocks stored in this dir
377 if !blockDirRe.MatchString(names[0]) {
380 blockdirpath := filepath.Join(v.Root, names[0])
381 blockdir, err := v.os.Open(blockdirpath)
383 log.Print("Error reading ", blockdirpath, ": ", err)
387 v.os.stats.TickOps("readdir")
388 v.os.stats.Tick(&v.os.stats.ReaddirOps)
390 fileInfo, err := blockdir.Readdir(1)
393 } else if err != nil {
394 log.Print("Error reading ", blockdirpath, ": ", err)
398 name := fileInfo[0].Name()
399 if !strings.HasPrefix(name, prefix) {
402 if !blockFileRe.MatchString(name) {
405 _, err = fmt.Fprint(w,
407 "+", fileInfo[0].Size(),
408 " ", fileInfo[0].ModTime().UnixNano(),
411 log.Print("Error writing : ", err)
420 // Trash trashes the block data from the unix storage
421 // If TrashLifetime == 0, the block is deleted
422 // Else, the block is renamed as path/{loc}.trash.{deadline},
423 // where deadline = now + TrashLifetime
424 func (v *UnixVolume) Trash(loc string) error {
425 // Touch() must be called before calling Write() on a block. Touch()
426 // also uses lockfile(). This avoids a race condition between Write()
427 // and Trash() because either (a) the file will be trashed and Touch()
428 // will signal to the caller that the file is not present (and needs to
429 // be re-written), or (b) Touch() will update the file's timestamp and
430 // Trash() will read the correct up-to-date timestamp and choose not to
433 if v.volume.ReadOnly || !v.cluster.Collections.BlobTrash {
434 return MethodDisabledError
436 if err := v.lock(context.TODO()); err != nil {
440 p := v.blockPath(loc)
441 f, err := v.os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
446 if e := v.lockfile(f); e != nil {
449 defer v.unlockfile(f)
451 // If the block has been PUT in the last blobSignatureTTL
452 // seconds, return success without removing the block. This
453 // protects data from garbage collection until it is no longer
454 // possible for clients to retrieve the unreferenced blocks
455 // anyway (because the permission signatures have expired).
456 if fi, err := v.os.Stat(p); err != nil {
458 } else if time.Since(fi.ModTime()) < v.cluster.Collections.BlobSigningTTL.Duration() {
462 if v.cluster.Collections.BlobTrashLifetime == 0 {
463 return v.os.Remove(p)
465 return v.os.Rename(p, fmt.Sprintf("%v.trash.%d", p, time.Now().Add(v.cluster.Collections.BlobTrashLifetime.Duration()).Unix()))
468 // Untrash moves block from trash back into store
469 // Look for path/{loc}.trash.{deadline} in storage,
470 // and rename the first such file as path/{loc}
471 func (v *UnixVolume) Untrash(loc string) (err error) {
472 if v.volume.ReadOnly {
473 return MethodDisabledError
476 v.os.stats.TickOps("readdir")
477 v.os.stats.Tick(&v.os.stats.ReaddirOps)
478 files, err := ioutil.ReadDir(v.blockDir(loc))
484 return os.ErrNotExist
488 prefix := fmt.Sprintf("%v.trash.", loc)
489 for _, f := range files {
490 if strings.HasPrefix(f.Name(), prefix) {
492 err = v.os.Rename(v.blockPath(f.Name()), v.blockPath(loc))
499 if foundTrash == false {
500 return os.ErrNotExist
506 // blockDir returns the fully qualified directory name for the directory
507 // where loc is (or would be) stored on this volume.
508 func (v *UnixVolume) blockDir(loc string) string {
509 return filepath.Join(v.Root, loc[0:3])
512 // blockPath returns the fully qualified pathname for the path to loc
514 func (v *UnixVolume) blockPath(loc string) string {
515 return filepath.Join(v.blockDir(loc), loc)
518 // IsFull returns true if the free space on the volume is less than
521 func (v *UnixVolume) IsFull() (isFull bool) {
522 fullSymlink := v.Root + "/full"
524 // Check if the volume has been marked as full in the last hour.
525 if link, err := os.Readlink(fullSymlink); err == nil {
526 if ts, err := strconv.Atoi(link); err == nil {
527 fulltime := time.Unix(int64(ts), 0)
528 if time.Since(fulltime).Hours() < 1.0 {
534 if avail, err := v.FreeDiskSpace(); err == nil {
535 isFull = avail < MinFreeKilobytes
537 log.Printf("%s: FreeDiskSpace: %s", v, err)
541 // If the volume is full, timestamp it.
543 now := fmt.Sprintf("%d", time.Now().Unix())
544 os.Symlink(now, fullSymlink)
549 // FreeDiskSpace returns the number of unused 1k blocks available on
552 func (v *UnixVolume) FreeDiskSpace() (free uint64, err error) {
553 var fs syscall.Statfs_t
554 err = syscall.Statfs(v.Root, &fs)
556 // Statfs output is not guaranteed to measure free
557 // space in terms of 1K blocks.
558 free = fs.Bavail * uint64(fs.Bsize) / 1024
563 func (v *UnixVolume) String() string {
564 return fmt.Sprintf("[UnixVolume %s]", v.Root)
567 // InternalStats returns I/O and filesystem ops counters.
568 func (v *UnixVolume) InternalStats() interface{} {
572 // lock acquires the serialize lock, if one is in use. If ctx is done
573 // before the lock is acquired, lock returns ctx.Err() instead of
574 // acquiring the lock.
575 func (v *UnixVolume) lock(ctx context.Context) error {
580 locked := make(chan struct{})
587 log.Printf("%s: client hung up while waiting for Serialize lock (%s)", v, time.Since(t0))
598 // unlock releases the serialize lock, if one is in use.
599 func (v *UnixVolume) unlock() {
606 // lockfile and unlockfile use flock(2) to manage kernel file locks.
607 func (v *UnixVolume) lockfile(f *os.File) error {
608 v.os.stats.TickOps("flock")
609 v.os.stats.Tick(&v.os.stats.FlockOps)
610 err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
611 v.os.stats.TickErr(err)
615 func (v *UnixVolume) unlockfile(f *os.File) error {
616 err := syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
617 v.os.stats.TickErr(err)
621 // Where appropriate, translate a more specific filesystem error to an
622 // error recognized by handlers, like os.ErrNotExist.
623 func (v *UnixVolume) translateError(err error) error {
626 // stat() returns a PathError if the parent directory
627 // (not just the file itself) is missing
628 return os.ErrNotExist
634 var unixTrashLocRegexp = regexp.MustCompile(`/([0-9a-f]{32})\.trash\.(\d+)$`)
636 // EmptyTrash walks hierarchy looking for {hash}.trash.*
637 // and deletes those with deadline < now.
638 func (v *UnixVolume) EmptyTrash() {
639 if v.cluster.Collections.BlobDeleteConcurrency < 1 {
643 var bytesDeleted, bytesInTrash int64
644 var blocksDeleted, blocksInTrash int64
646 doFile := func(path string, info os.FileInfo) {
647 if info.Mode().IsDir() {
650 matches := unixTrashLocRegexp.FindStringSubmatch(path)
651 if len(matches) != 3 {
654 deadline, err := strconv.ParseInt(matches[2], 10, 64)
656 log.Printf("EmptyTrash: %v: ParseInt(%v): %v", path, matches[2], err)
659 atomic.AddInt64(&bytesInTrash, info.Size())
660 atomic.AddInt64(&blocksInTrash, 1)
661 if deadline > time.Now().Unix() {
664 err = v.os.Remove(path)
666 log.Printf("EmptyTrash: Remove %v: %v", path, err)
669 atomic.AddInt64(&bytesDeleted, info.Size())
670 atomic.AddInt64(&blocksDeleted, 1)
677 var wg sync.WaitGroup
678 todo := make(chan dirent, v.cluster.Collections.BlobDeleteConcurrency)
679 for i := 0; i < v.cluster.Collections.BlobDeleteConcurrency; i++ {
683 for e := range todo {
684 doFile(e.path, e.info)
689 err := filepath.Walk(v.Root, func(path string, info os.FileInfo, err error) error {
691 log.Printf("EmptyTrash: filepath.Walk: %v: %v", path, err)
694 todo <- dirent{path, info}
701 log.Printf("EmptyTrash error for %v: %v", v.String(), err)
704 log.Printf("EmptyTrash stats for %v: Deleted %v bytes in %v blocks. Remaining in trash: %v bytes in %v blocks.", v.String(), bytesDeleted, blocksDeleted, bytesInTrash-bytesDeleted, blocksInTrash-blocksDeleted)
707 type unixStats struct {
719 func (s *unixStats) TickErr(err error) {
723 s.statsTicker.TickErr(err, fmt.Sprintf("%T", err))
726 type osWithStats struct {
730 func (o *osWithStats) Open(name string) (*os.File, error) {
731 o.stats.TickOps("open")
732 o.stats.Tick(&o.stats.OpenOps)
733 f, err := os.Open(name)
738 func (o *osWithStats) OpenFile(name string, flag int, perm os.FileMode) (*os.File, error) {
739 o.stats.TickOps("open")
740 o.stats.Tick(&o.stats.OpenOps)
741 f, err := os.OpenFile(name, flag, perm)
746 func (o *osWithStats) Remove(path string) error {
747 o.stats.TickOps("unlink")
748 o.stats.Tick(&o.stats.UnlinkOps)
749 err := os.Remove(path)
754 func (o *osWithStats) Rename(a, b string) error {
755 o.stats.TickOps("rename")
756 o.stats.Tick(&o.stats.RenameOps)
757 err := os.Rename(a, b)
762 func (o *osWithStats) Stat(path string) (os.FileInfo, error) {
763 o.stats.TickOps("stat")
764 o.stats.Tick(&o.stats.StatOps)
765 fi, err := os.Stat(path)
770 func (o *osWithStats) TempFile(dir, base string) (*os.File, error) {
771 o.stats.TickOps("create")
772 o.stats.Tick(&o.stats.CreateOps)
773 f, err := ioutil.TempFile(dir, base)