1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
25 "git.arvados.org/arvados.git/sdk/go/arvados"
26 "github.com/prometheus/client_golang/prometheus"
27 "github.com/sirupsen/logrus"
31 driver["Directory"] = newDirectoryVolume
34 func newDirectoryVolume(cluster *arvados.Cluster, volume arvados.Volume, logger logrus.FieldLogger, metrics *volumeMetricsVecs) (Volume, error) {
35 v := &UnixVolume{cluster: cluster, volume: volume, logger: logger, metrics: metrics}
36 err := json.Unmarshal(volume.DriverParameters, &v)
40 v.logger = v.logger.WithField("Volume", v.String())
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 v.logger.Infof(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)
139 uuids, err := d.Readdirnames(0)
141 return giveup("reading %q: %s", udir, err)
143 for _, uuid := range uuids {
144 link := filepath.Join(udir, uuid)
145 fi, err = os.Stat(link)
147 v.logger.WithError(err).Errorf("stat(%q) failed", link)
150 if fi.Sys().(*syscall.Stat_t).Ino == ino {
154 return giveup("could not find entry in %q matching %q", udir, dev)
157 // Touch sets the timestamp for the given locator to the current time
158 func (v *UnixVolume) Touch(loc string) error {
159 if v.volume.ReadOnly {
160 return MethodDisabledError
162 p := v.blockPath(loc)
163 f, err := v.os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
168 if err := v.lock(context.TODO()); err != nil {
172 if e := v.lockfile(f); e != nil {
175 defer v.unlockfile(f)
177 v.os.stats.TickOps("utimes")
178 v.os.stats.Tick(&v.os.stats.UtimesOps)
179 err = os.Chtimes(p, ts, ts)
180 v.os.stats.TickErr(err)
184 // Mtime returns the stored timestamp for the given locator.
185 func (v *UnixVolume) Mtime(loc string) (time.Time, error) {
186 p := v.blockPath(loc)
187 fi, err := v.os.Stat(p)
189 return time.Time{}, err
191 return fi.ModTime(), nil
194 // Lock the locker (if one is in use), open the file for reading, and
195 // call the given function if and when the file is ready to read.
196 func (v *UnixVolume) getFunc(ctx context.Context, path string, fn func(io.Reader) error) error {
197 if err := v.lock(ctx); err != nil {
201 f, err := v.os.Open(path)
206 return fn(NewCountingReader(ioutil.NopCloser(f), v.os.stats.TickInBytes))
209 // stat is os.Stat() with some extra sanity checks.
210 func (v *UnixVolume) stat(path string) (os.FileInfo, error) {
211 stat, err := v.os.Stat(path)
215 } else if stat.Size() > BlockSize {
222 // Get retrieves a block, copies it to the given slice, and returns
223 // the number of bytes copied.
224 func (v *UnixVolume) Get(ctx context.Context, loc string, buf []byte) (int, error) {
225 return getWithPipe(ctx, loc, buf, v)
228 // ReadBlock implements BlockReader.
229 func (v *UnixVolume) ReadBlock(ctx context.Context, loc string, w io.Writer) error {
230 path := v.blockPath(loc)
231 stat, err := v.stat(path)
233 return v.translateError(err)
235 return v.getFunc(ctx, path, func(rdr io.Reader) error {
236 n, err := io.Copy(w, rdr)
237 if err == nil && n != stat.Size() {
238 err = io.ErrUnexpectedEOF
244 // Compare returns nil if Get(loc) would return the same content as
245 // expect. It is functionally equivalent to Get() followed by
246 // bytes.Compare(), but uses less memory.
247 func (v *UnixVolume) Compare(ctx context.Context, loc string, expect []byte) error {
248 path := v.blockPath(loc)
249 if _, err := v.stat(path); err != nil {
250 return v.translateError(err)
252 return v.getFunc(ctx, path, func(rdr io.Reader) error {
253 return compareReaderWithBuf(ctx, rdr, expect, loc[:32])
257 // Put stores a block of data identified by the locator string
258 // "loc". It returns nil on success. If the volume is full, it
259 // returns a FullError. If the write fails due to some other error,
260 // that error is returned.
261 func (v *UnixVolume) Put(ctx context.Context, loc string, block []byte) error {
262 return putWithPipe(ctx, loc, block, v)
265 // WriteBlock implements BlockWriter.
266 func (v *UnixVolume) WriteBlock(ctx context.Context, loc string, rdr io.Reader) error {
267 if v.volume.ReadOnly {
268 return MethodDisabledError
273 bdir := v.blockDir(loc)
274 if err := os.MkdirAll(bdir, 0755); err != nil {
275 return fmt.Errorf("error creating directory %s: %s", bdir, err)
278 bpath := v.blockPath(loc)
279 tmpfile, err := v.os.TempFile(bdir, "tmp"+loc)
281 return fmt.Errorf("TempFile(%s, tmp%s) failed: %s", bdir, loc, err)
283 defer v.os.Remove(tmpfile.Name())
284 defer tmpfile.Close()
286 if err = v.lock(ctx); err != nil {
290 n, err := io.Copy(tmpfile, rdr)
291 v.os.stats.TickOutBytes(uint64(n))
293 return fmt.Errorf("error writing %s: %s", bpath, err)
295 if err = tmpfile.Close(); err != nil {
296 return fmt.Errorf("error closing %s: %s", tmpfile.Name(), err)
298 // ext4 uses a low-precision clock and effectively backdates
299 // files by up to 10 ms, sometimes across a 1-second boundary,
300 // which produces confusing results in logs and tests. We
301 // avoid this by setting the output file's timestamps
302 // explicitly, using a higher resolution clock.
304 v.os.stats.TickOps("utimes")
305 v.os.stats.Tick(&v.os.stats.UtimesOps)
306 if err = os.Chtimes(tmpfile.Name(), ts, ts); err != nil {
307 return fmt.Errorf("error setting timestamps on %s: %s", tmpfile.Name(), err)
309 if err = v.os.Rename(tmpfile.Name(), bpath); err != nil {
310 return fmt.Errorf("error renaming %s to %s: %s", tmpfile.Name(), bpath, err)
315 // Status returns a VolumeStatus struct describing the volume's
316 // current state, or nil if an error occurs.
317 func (v *UnixVolume) Status() *VolumeStatus {
318 fi, err := v.os.Stat(v.Root)
320 v.logger.WithError(err).Error("stat failed")
323 // uint64() cast here supports GOOS=darwin where Dev is
324 // int32. If the device number is negative, the unsigned
325 // devnum won't be the real device number any more, but that's
326 // fine -- all we care about is getting the same number each
328 devnum := uint64(fi.Sys().(*syscall.Stat_t).Dev)
330 var fs syscall.Statfs_t
331 if err := syscall.Statfs(v.Root, &fs); err != nil {
332 v.logger.WithError(err).Error("statfs failed")
335 // These calculations match the way df calculates disk usage:
336 // "free" space is measured by fs.Bavail, but "used" space
337 // uses fs.Blocks - fs.Bfree.
338 free := fs.Bavail * uint64(fs.Bsize)
339 used := (fs.Blocks - fs.Bfree) * uint64(fs.Bsize)
340 return &VolumeStatus{
348 var blockDirRe = regexp.MustCompile(`^[0-9a-f]+$`)
349 var blockFileRe = regexp.MustCompile(`^[0-9a-f]{32}$`)
351 // IndexTo writes (to the given Writer) a list of blocks found on this
352 // volume which begin with the specified prefix. If the prefix is an
353 // empty string, IndexTo writes a complete list of blocks.
355 // Each block is given in the format
357 // locator+size modification-time {newline}
361 // e4df392f86be161ca6ed3773a962b8f3+67108864 1388894303
362 // e4d41e6fd68460e0e3fc18cc746959d2+67108864 1377796043
363 // e4de7a2810f5554cd39b36d8ddb132ff+67108864 1388701136
364 func (v *UnixVolume) IndexTo(prefix string, w io.Writer) error {
365 rootdir, err := v.os.Open(v.Root)
369 v.os.stats.TickOps("readdir")
370 v.os.stats.Tick(&v.os.stats.ReaddirOps)
371 subdirs, err := rootdir.Readdirnames(-1)
376 for _, subdir := range subdirs {
377 if !strings.HasPrefix(subdir, prefix) && !strings.HasPrefix(prefix, subdir) {
378 // prefix excludes all blocks stored in this dir
381 if !blockDirRe.MatchString(subdir) {
384 blockdirpath := filepath.Join(v.Root, subdir)
386 var dirents []os.DirEntry
387 for attempt := 0; ; attempt++ {
388 v.os.stats.TickOps("readdir")
389 v.os.stats.Tick(&v.os.stats.ReaddirOps)
390 dirents, err = os.ReadDir(blockdirpath)
393 } else if attempt < 5 && strings.Contains(err.Error(), "errno 523") {
394 // EBADCOOKIE (NFS stopped accepting
395 // our readdirent cookie) -- retry a
396 // few times before giving up
397 v.logger.WithError(err).Printf("retry after error reading %s", blockdirpath)
404 for _, dirent := range dirents {
405 fileInfo, err := dirent.Info()
406 if os.IsNotExist(err) {
407 // File disappeared between ReadDir() and now
409 } else if err != nil {
410 v.logger.WithError(err).Errorf("error getting FileInfo for %q in %q", dirent.Name(), blockdirpath)
413 name := fileInfo.Name()
414 if !strings.HasPrefix(name, prefix) {
417 if !blockFileRe.MatchString(name) {
420 _, err = fmt.Fprint(w,
422 "+", fileInfo.Size(),
423 " ", fileInfo.ModTime().UnixNano(),
426 return fmt.Errorf("error writing: %s", err)
433 // Trash trashes the block data from the unix storage
434 // If BlobTrashLifetime == 0, the block is deleted
435 // Else, the block is renamed as path/{loc}.trash.{deadline},
436 // where deadline = now + BlobTrashLifetime
437 func (v *UnixVolume) Trash(loc string) error {
438 // Touch() must be called before calling Write() on a block. Touch()
439 // also uses lockfile(). This avoids a race condition between Write()
440 // and Trash() because either (a) the file will be trashed and Touch()
441 // will signal to the caller that the file is not present (and needs to
442 // be re-written), or (b) Touch() will update the file's timestamp and
443 // Trash() will read the correct up-to-date timestamp and choose not to
445 if v.volume.ReadOnly && !v.volume.AllowTrashWhenReadOnly {
446 return MethodDisabledError
448 if err := v.lock(context.TODO()); err != nil {
452 p := v.blockPath(loc)
453 f, err := v.os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
458 if e := v.lockfile(f); e != nil {
461 defer v.unlockfile(f)
463 // If the block has been PUT in the last blobSignatureTTL
464 // seconds, return success without removing the block. This
465 // protects data from garbage collection until it is no longer
466 // possible for clients to retrieve the unreferenced blocks
467 // anyway (because the permission signatures have expired).
468 if fi, err := v.os.Stat(p); err != nil {
470 } else if time.Since(fi.ModTime()) < v.cluster.Collections.BlobSigningTTL.Duration() {
474 if v.cluster.Collections.BlobTrashLifetime == 0 {
475 return v.os.Remove(p)
477 return v.os.Rename(p, fmt.Sprintf("%v.trash.%d", p, time.Now().Add(v.cluster.Collections.BlobTrashLifetime.Duration()).Unix()))
480 // Untrash moves block from trash back into store
481 // Look for path/{loc}.trash.{deadline} in storage,
482 // and rename the first such file as path/{loc}
483 func (v *UnixVolume) Untrash(loc string) (err error) {
484 if v.volume.ReadOnly {
485 return MethodDisabledError
488 v.os.stats.TickOps("readdir")
489 v.os.stats.Tick(&v.os.stats.ReaddirOps)
490 files, err := ioutil.ReadDir(v.blockDir(loc))
496 return os.ErrNotExist
500 prefix := fmt.Sprintf("%v.trash.", loc)
501 for _, f := range files {
502 if strings.HasPrefix(f.Name(), prefix) {
504 err = v.os.Rename(v.blockPath(f.Name()), v.blockPath(loc))
511 if foundTrash == false {
512 return os.ErrNotExist
518 // blockDir returns the fully qualified directory name for the directory
519 // where loc is (or would be) stored on this volume.
520 func (v *UnixVolume) blockDir(loc string) string {
521 return filepath.Join(v.Root, loc[0:3])
524 // blockPath returns the fully qualified pathname for the path to loc
526 func (v *UnixVolume) blockPath(loc string) string {
527 return filepath.Join(v.blockDir(loc), loc)
530 // IsFull returns true if the free space on the volume is less than
532 func (v *UnixVolume) IsFull() (isFull bool) {
533 fullSymlink := v.Root + "/full"
535 // Check if the volume has been marked as full in the last hour.
536 if link, err := os.Readlink(fullSymlink); err == nil {
537 if ts, err := strconv.Atoi(link); err == nil {
538 fulltime := time.Unix(int64(ts), 0)
539 if time.Since(fulltime).Hours() < 1.0 {
545 if avail, err := v.FreeDiskSpace(); err == nil {
546 isFull = avail < MinFreeKilobytes
548 v.logger.WithError(err).Errorf("%s: FreeDiskSpace failed", v)
552 // If the volume is full, timestamp it.
554 now := fmt.Sprintf("%d", time.Now().Unix())
555 os.Symlink(now, fullSymlink)
560 // FreeDiskSpace returns the number of unused 1k blocks available on
562 func (v *UnixVolume) FreeDiskSpace() (free uint64, err error) {
563 var fs syscall.Statfs_t
564 err = syscall.Statfs(v.Root, &fs)
566 // Statfs output is not guaranteed to measure free
567 // space in terms of 1K blocks.
568 free = fs.Bavail * uint64(fs.Bsize) / 1024
573 func (v *UnixVolume) String() string {
574 return fmt.Sprintf("[UnixVolume %s]", v.Root)
577 // InternalStats returns I/O and filesystem ops counters.
578 func (v *UnixVolume) InternalStats() interface{} {
582 // lock acquires the serialize lock, if one is in use. If ctx is done
583 // before the lock is acquired, lock returns ctx.Err() instead of
584 // acquiring the lock.
585 func (v *UnixVolume) lock(ctx context.Context) error {
590 locked := make(chan struct{})
597 v.logger.Infof("client hung up while waiting for Serialize lock (%s)", time.Since(t0))
608 // unlock releases the serialize lock, if one is in use.
609 func (v *UnixVolume) unlock() {
616 // lockfile and unlockfile use flock(2) to manage kernel file locks.
617 func (v *UnixVolume) lockfile(f *os.File) error {
618 v.os.stats.TickOps("flock")
619 v.os.stats.Tick(&v.os.stats.FlockOps)
620 err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
621 v.os.stats.TickErr(err)
625 func (v *UnixVolume) unlockfile(f *os.File) error {
626 err := syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
627 v.os.stats.TickErr(err)
631 // Where appropriate, translate a more specific filesystem error to an
632 // error recognized by handlers, like os.ErrNotExist.
633 func (v *UnixVolume) translateError(err error) error {
636 // stat() returns a PathError if the parent directory
637 // (not just the file itself) is missing
638 return os.ErrNotExist
644 var unixTrashLocRegexp = regexp.MustCompile(`/([0-9a-f]{32})\.trash\.(\d+)$`)
646 // EmptyTrash walks hierarchy looking for {hash}.trash.*
647 // and deletes those with deadline < now.
648 func (v *UnixVolume) EmptyTrash() {
649 var bytesDeleted, bytesInTrash int64
650 var blocksDeleted, blocksInTrash int64
652 doFile := func(path string, info os.FileInfo) {
653 if info.Mode().IsDir() {
656 matches := unixTrashLocRegexp.FindStringSubmatch(path)
657 if len(matches) != 3 {
660 deadline, err := strconv.ParseInt(matches[2], 10, 64)
662 v.logger.WithError(err).Errorf("EmptyTrash: %v: ParseInt(%q) failed", path, matches[2])
665 atomic.AddInt64(&bytesInTrash, info.Size())
666 atomic.AddInt64(&blocksInTrash, 1)
667 if deadline > time.Now().Unix() {
670 err = v.os.Remove(path)
672 v.logger.WithError(err).Errorf("EmptyTrash: Remove(%q) failed", path)
675 atomic.AddInt64(&bytesDeleted, info.Size())
676 atomic.AddInt64(&blocksDeleted, 1)
683 var wg sync.WaitGroup
684 todo := make(chan dirent, v.cluster.Collections.BlobDeleteConcurrency)
685 for i := 0; i < v.cluster.Collections.BlobDeleteConcurrency; i++ {
689 for e := range todo {
690 doFile(e.path, e.info)
695 err := filepath.Walk(v.Root, func(path string, info os.FileInfo, err error) error {
697 v.logger.WithError(err).Errorf("EmptyTrash: filepath.Walk(%q) failed", path)
698 // Don't give up -- keep walking other
701 } else if !info.Mode().IsDir() {
702 todo <- dirent{path, info}
704 } else if path == v.Root || blockDirRe.MatchString(info.Name()) {
705 // Descend into a directory that we might have
709 // Don't descend into other dirs.
710 return filepath.SkipDir
717 v.logger.WithError(err).Error("EmptyTrash failed")
720 v.logger.Infof("EmptyTrash stats: Deleted %v bytes in %v blocks. Remaining in trash: %v bytes in %v blocks.", bytesDeleted, blocksDeleted, bytesInTrash-bytesDeleted, blocksInTrash-blocksDeleted)
723 type unixStats struct {
735 func (s *unixStats) TickErr(err error) {
739 s.statsTicker.TickErr(err, fmt.Sprintf("%T", err))
742 type osWithStats struct {
746 func (o *osWithStats) Open(name string) (*os.File, error) {
747 o.stats.TickOps("open")
748 o.stats.Tick(&o.stats.OpenOps)
749 f, err := os.Open(name)
754 func (o *osWithStats) OpenFile(name string, flag int, perm os.FileMode) (*os.File, error) {
755 o.stats.TickOps("open")
756 o.stats.Tick(&o.stats.OpenOps)
757 f, err := os.OpenFile(name, flag, perm)
762 func (o *osWithStats) Remove(path string) error {
763 o.stats.TickOps("unlink")
764 o.stats.Tick(&o.stats.UnlinkOps)
765 err := os.Remove(path)
770 func (o *osWithStats) Rename(a, b string) error {
771 o.stats.TickOps("rename")
772 o.stats.Tick(&o.stats.RenameOps)
773 err := os.Rename(a, b)
778 func (o *osWithStats) Stat(path string) (os.FileInfo, error) {
779 o.stats.TickOps("stat")
780 o.stats.Tick(&o.stats.StatOps)
781 fi, err := os.Stat(path)
786 func (o *osWithStats) TempFile(dir, base string) (*os.File, error) {
787 o.stats.TickOps("create")
788 o.stats.Tick(&o.stats.CreateOps)
789 f, err := ioutil.TempFile(dir, base)