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"] = newUnixVolume
34 func newUnixVolume(params newVolumeParams) (volume, error) {
37 cluster: params.Cluster,
38 volume: params.ConfigVolume,
39 logger: params.Logger,
40 metrics: params.MetricsVecs,
41 bufferPool: params.BufferPool,
43 err := json.Unmarshal(params.ConfigVolume.DriverParameters, &v)
47 v.logger = v.logger.WithField("Volume", v.DeviceID())
51 func (v *unixVolume) check() error {
53 return errors.New("DriverParameters.Root was not provided")
56 v.locker = &sync.Mutex{}
58 if !strings.HasPrefix(v.Root, "/") {
59 return fmt.Errorf("DriverParameters.Root %q does not start with '/'", v.Root)
62 // Set up prometheus metrics
63 lbls := prometheus.Labels{"device_id": v.DeviceID()}
64 v.os.stats.opsCounters, v.os.stats.errCounters, v.os.stats.ioBytes = v.metrics.getCounterVecsFor(lbls)
66 _, err := v.os.Stat(v.Root)
70 // A unixVolume stores and retrieves blocks in a local directory.
71 type unixVolume struct {
72 Root string // path to the volume's root directory
76 cluster *arvados.Cluster
78 logger logrus.FieldLogger
79 metrics *volumeMetricsVecs
80 bufferPool *bufferPool
82 // something to lock during IO, typically a sync.Mutex (or nil
89 // DeviceID returns a globally unique ID for the volume's root
90 // directory, consisting of the filesystem's UUID and the path from
91 // filesystem root to storage directory, joined by "/". For example,
92 // the device ID for a local directory "/mnt/xvda1/keep" might be
93 // "fa0b6166-3b55-4994-bd3f-92f4e00a1bb0/keep".
94 func (v *unixVolume) DeviceID() string {
95 giveup := func(f string, args ...interface{}) string {
96 v.logger.Infof(f+"; using hostname:path for volume %s", append(args, v.uuid)...)
97 host, _ := os.Hostname()
98 return host + ":" + v.Root
100 buf, err := exec.Command("findmnt", "--noheadings", "--target", v.Root).CombinedOutput()
102 return giveup("findmnt: %s (%q)", err, buf)
104 findmnt := strings.Fields(string(buf))
105 if len(findmnt) < 2 {
106 return giveup("could not parse findmnt output: %q", buf)
108 fsRoot, dev := findmnt[0], findmnt[1]
110 absRoot, err := filepath.Abs(v.Root)
112 return giveup("resolving relative path %q: %s", v.Root, err)
114 realRoot, err := filepath.EvalSymlinks(absRoot)
116 return giveup("resolving symlinks in %q: %s", absRoot, err)
119 // Find path from filesystem root to realRoot
121 if strings.HasPrefix(realRoot, fsRoot+"/") {
122 fsPath = realRoot[len(fsRoot):]
123 } else if fsRoot == "/" {
125 } else if fsRoot == realRoot {
128 return giveup("findmnt reports mount point %q which is not a prefix of volume root %q", fsRoot, realRoot)
131 if !strings.HasPrefix(dev, "/") {
132 return giveup("mount %q device %q is not a path", fsRoot, dev)
135 fi, err := os.Stat(dev)
137 return giveup("stat %q: %s", dev, err)
139 ino := fi.Sys().(*syscall.Stat_t).Ino
141 // Find a symlink in /dev/disk/by-uuid/ whose target is (i.e.,
142 // has the same inode as) the mounted device
143 udir := "/dev/disk/by-uuid"
144 d, err := os.Open(udir)
146 return giveup("opening %q: %s", udir, err)
149 uuids, err := d.Readdirnames(0)
151 return giveup("reading %q: %s", udir, err)
153 for _, uuid := range uuids {
154 link := filepath.Join(udir, uuid)
155 fi, err = os.Stat(link)
157 v.logger.WithError(err).Errorf("stat(%q) failed", link)
160 if fi.Sys().(*syscall.Stat_t).Ino == ino {
164 return giveup("could not find entry in %q matching %q", udir, dev)
167 // BlockTouch sets the timestamp for the given locator to the current time
168 func (v *unixVolume) BlockTouch(hash string) error {
169 p := v.blockPath(hash)
170 f, err := v.os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
175 if err := v.lock(context.TODO()); err != nil {
179 if e := v.lockfile(f); e != nil {
182 defer v.unlockfile(f)
184 v.os.stats.TickOps("utimes")
185 v.os.stats.Tick(&v.os.stats.UtimesOps)
186 err = os.Chtimes(p, ts, ts)
187 v.os.stats.TickErr(err)
191 // Mtime returns the stored timestamp for the given locator.
192 func (v *unixVolume) Mtime(loc string) (time.Time, error) {
193 p := v.blockPath(loc)
194 fi, err := v.os.Stat(p)
196 return time.Time{}, err
198 return fi.ModTime(), nil
201 // stat is os.Stat() with some extra sanity checks.
202 func (v *unixVolume) stat(path string) (os.FileInfo, error) {
203 stat, err := v.os.Stat(path)
207 } else if stat.Size() > BlockSize {
214 // BlockRead reads a block from the volume.
215 func (v *unixVolume) BlockRead(ctx context.Context, hash string, w io.WriterAt) error {
216 path := v.blockPath(hash)
217 stat, err := v.stat(path)
219 return v.translateError(err)
221 if err := v.lock(ctx); err != nil {
225 f, err := v.os.Open(path)
230 src := newCountingReader(ioutil.NopCloser(f), v.os.stats.TickInBytes)
231 dst := io.NewOffsetWriter(w, 0)
232 n, err := io.Copy(dst, src)
233 if err == nil && n != stat.Size() {
234 err = io.ErrUnexpectedEOF
239 // BlockWrite stores a block on the volume. If it already exists, its
240 // timestamp is updated.
241 func (v *unixVolume) BlockWrite(ctx context.Context, hash string, data []byte) error {
245 bdir := v.blockDir(hash)
246 if err := os.MkdirAll(bdir, 0755); err != nil {
247 return fmt.Errorf("error creating directory %s: %s", bdir, err)
250 bpath := v.blockPath(hash)
251 tmpfile, err := v.os.TempFile(bdir, "tmp"+hash)
253 return fmt.Errorf("TempFile(%s, tmp%s) failed: %s", bdir, hash, err)
255 defer v.os.Remove(tmpfile.Name())
256 defer tmpfile.Close()
258 if err = v.lock(ctx); err != nil {
262 n, err := tmpfile.Write(data)
263 v.os.stats.TickOutBytes(uint64(n))
265 return fmt.Errorf("error writing %s: %s", bpath, err)
267 if err = tmpfile.Close(); err != nil {
268 return fmt.Errorf("error closing %s: %s", tmpfile.Name(), err)
270 // ext4 uses a low-precision clock and effectively backdates
271 // files by up to 10 ms, sometimes across a 1-second boundary,
272 // which produces confusing results in logs and tests. We
273 // avoid this by setting the output file's timestamps
274 // explicitly, using a higher resolution clock.
276 v.os.stats.TickOps("utimes")
277 v.os.stats.Tick(&v.os.stats.UtimesOps)
278 if err = os.Chtimes(tmpfile.Name(), ts, ts); err != nil {
279 return fmt.Errorf("error setting timestamps on %s: %s", tmpfile.Name(), err)
281 if err = v.os.Rename(tmpfile.Name(), bpath); err != nil {
282 return fmt.Errorf("error renaming %s to %s: %s", tmpfile.Name(), bpath, err)
287 var blockDirRe = regexp.MustCompile(`^[0-9a-f]+$`)
288 var blockFileRe = regexp.MustCompile(`^[0-9a-f]{32}$`)
290 func (v *unixVolume) Index(ctx context.Context, prefix string, w io.Writer) error {
291 rootdir, err := v.os.Open(v.Root)
295 v.os.stats.TickOps("readdir")
296 v.os.stats.Tick(&v.os.stats.ReaddirOps)
297 subdirs, err := rootdir.Readdirnames(-1)
302 for _, subdir := range subdirs {
303 if ctx.Err() != nil {
306 if !strings.HasPrefix(subdir, prefix) && !strings.HasPrefix(prefix, subdir) {
307 // prefix excludes all blocks stored in this dir
310 if !blockDirRe.MatchString(subdir) {
313 blockdirpath := filepath.Join(v.Root, subdir)
315 var dirents []os.DirEntry
316 for attempt := 0; ; attempt++ {
317 v.os.stats.TickOps("readdir")
318 v.os.stats.Tick(&v.os.stats.ReaddirOps)
319 dirents, err = os.ReadDir(blockdirpath)
320 if ctx.Err() != nil {
322 } else if err == nil {
324 } else if attempt < 5 && strings.Contains(err.Error(), "errno 523") {
325 // EBADCOOKIE (NFS stopped accepting
326 // our readdirent cookie) -- retry a
327 // few times before giving up
328 v.logger.WithError(err).Printf("retry after error reading %s", blockdirpath)
335 for _, dirent := range dirents {
336 if ctx.Err() != nil {
339 fileInfo, err := dirent.Info()
340 if os.IsNotExist(err) {
341 // File disappeared between ReadDir() and now
343 } else if err != nil {
344 v.logger.WithError(err).Errorf("error getting FileInfo for %q in %q", dirent.Name(), blockdirpath)
347 name := fileInfo.Name()
348 if !strings.HasPrefix(name, prefix) {
351 if !blockFileRe.MatchString(name) {
354 _, err = fmt.Fprint(w,
356 "+", fileInfo.Size(),
357 " ", fileInfo.ModTime().UnixNano(),
360 return fmt.Errorf("error writing: %s", err)
367 // BlockTrash trashes the block data from the unix storage. If
368 // BlobTrashLifetime == 0, the block is deleted; otherwise, the block
369 // is renamed as path/{loc}.trash.{deadline}, where deadline = now +
370 // BlobTrashLifetime.
371 func (v *unixVolume) BlockTrash(loc string) error {
372 // Touch() must be called before calling Write() on a block. Touch()
373 // also uses lockfile(). This avoids a race condition between Write()
374 // and Trash() because either (a) the file will be trashed and Touch()
375 // will signal to the caller that the file is not present (and needs to
376 // be re-written), or (b) Touch() will update the file's timestamp and
377 // Trash() will read the correct up-to-date timestamp and choose not to
379 if err := v.lock(context.TODO()); err != nil {
383 p := v.blockPath(loc)
384 f, err := v.os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
389 if e := v.lockfile(f); e != nil {
392 defer v.unlockfile(f)
394 // If the block has been PUT in the last blobSignatureTTL
395 // seconds, return success without removing the block. This
396 // protects data from garbage collection until it is no longer
397 // possible for clients to retrieve the unreferenced blocks
398 // anyway (because the permission signatures have expired).
399 if fi, err := v.os.Stat(p); err != nil {
401 } else if time.Since(fi.ModTime()) < v.cluster.Collections.BlobSigningTTL.Duration() {
405 if v.cluster.Collections.BlobTrashLifetime == 0 {
406 return v.os.Remove(p)
408 return v.os.Rename(p, fmt.Sprintf("%v.trash.%d", p, time.Now().Add(v.cluster.Collections.BlobTrashLifetime.Duration()).Unix()))
411 // BlockUntrash moves block from trash back into store
412 // Look for path/{loc}.trash.{deadline} in storage,
413 // and rename the first such file as path/{loc}
414 func (v *unixVolume) BlockUntrash(hash string) error {
415 v.os.stats.TickOps("readdir")
416 v.os.stats.Tick(&v.os.stats.ReaddirOps)
417 files, err := ioutil.ReadDir(v.blockDir(hash))
423 return os.ErrNotExist
427 prefix := fmt.Sprintf("%v.trash.", hash)
428 for _, f := range files {
429 if strings.HasPrefix(f.Name(), prefix) {
431 err = v.os.Rename(v.blockPath(f.Name()), v.blockPath(hash))
438 if foundTrash == false {
439 return os.ErrNotExist
445 // blockDir returns the fully qualified directory name for the directory
446 // where loc is (or would be) stored on this volume.
447 func (v *unixVolume) blockDir(loc string) string {
448 return filepath.Join(v.Root, loc[0:3])
451 // blockPath returns the fully qualified pathname for the path to loc
453 func (v *unixVolume) blockPath(loc string) string {
454 return filepath.Join(v.blockDir(loc), loc)
457 // isFull returns true if the free space on the volume is less than
459 func (v *unixVolume) isFull() (isFull bool) {
460 fullSymlink := v.Root + "/full"
462 // Check if the volume has been marked as full in the last hour.
463 if link, err := os.Readlink(fullSymlink); err == nil {
464 if ts, err := strconv.Atoi(link); err == nil {
465 fulltime := time.Unix(int64(ts), 0)
466 if time.Since(fulltime).Hours() < 1.0 {
472 if avail, err := v.FreeDiskSpace(); err == nil {
473 isFull = avail < BlockSize
475 v.logger.WithError(err).Errorf("%s: FreeDiskSpace failed", v.DeviceID())
479 // If the volume is full, timestamp it.
481 now := fmt.Sprintf("%d", time.Now().Unix())
482 os.Symlink(now, fullSymlink)
487 // FreeDiskSpace returns the number of unused 1k blocks available on
489 func (v *unixVolume) FreeDiskSpace() (free uint64, err error) {
490 var fs syscall.Statfs_t
491 err = syscall.Statfs(v.Root, &fs)
493 // Statfs output is not guaranteed to measure free
494 // space in terms of 1K blocks.
495 free = fs.Bavail * uint64(fs.Bsize)
500 // InternalStats returns I/O and filesystem ops counters.
501 func (v *unixVolume) InternalStats() interface{} {
505 // lock acquires the serialize lock, if one is in use. If ctx is done
506 // before the lock is acquired, lock returns ctx.Err() instead of
507 // acquiring the lock.
508 func (v *unixVolume) lock(ctx context.Context) error {
513 locked := make(chan struct{})
520 v.logger.Infof("client hung up while waiting for Serialize lock (%s)", time.Since(t0))
531 // unlock releases the serialize lock, if one is in use.
532 func (v *unixVolume) unlock() {
539 // lockfile and unlockfile use flock(2) to manage kernel file locks.
540 func (v *unixVolume) lockfile(f *os.File) error {
541 v.os.stats.TickOps("flock")
542 v.os.stats.Tick(&v.os.stats.FlockOps)
543 err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
544 v.os.stats.TickErr(err)
548 func (v *unixVolume) unlockfile(f *os.File) error {
549 err := syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
550 v.os.stats.TickErr(err)
554 // Where appropriate, translate a more specific filesystem error to an
555 // error recognized by handlers, like os.ErrNotExist.
556 func (v *unixVolume) translateError(err error) error {
559 // stat() returns a PathError if the parent directory
560 // (not just the file itself) is missing
561 return os.ErrNotExist
567 var unixTrashLocRegexp = regexp.MustCompile(`/([0-9a-f]{32})\.trash\.(\d+)$`)
569 // EmptyTrash walks hierarchy looking for {hash}.trash.*
570 // and deletes those with deadline < now.
571 func (v *unixVolume) EmptyTrash() {
572 var bytesDeleted, bytesInTrash int64
573 var blocksDeleted, blocksInTrash int64
575 doFile := func(path string, info os.FileInfo) {
576 if info.Mode().IsDir() {
579 matches := unixTrashLocRegexp.FindStringSubmatch(path)
580 if len(matches) != 3 {
583 deadline, err := strconv.ParseInt(matches[2], 10, 64)
585 v.logger.WithError(err).Errorf("EmptyTrash: %v: ParseInt(%q) failed", path, matches[2])
588 atomic.AddInt64(&bytesInTrash, info.Size())
589 atomic.AddInt64(&blocksInTrash, 1)
590 if deadline > time.Now().Unix() {
593 err = v.os.Remove(path)
595 v.logger.WithError(err).Errorf("EmptyTrash: Remove(%q) failed", path)
598 atomic.AddInt64(&bytesDeleted, info.Size())
599 atomic.AddInt64(&blocksDeleted, 1)
606 var wg sync.WaitGroup
607 todo := make(chan dirent, v.cluster.Collections.BlobDeleteConcurrency)
608 for i := 0; i < v.cluster.Collections.BlobDeleteConcurrency; i++ {
612 for e := range todo {
613 doFile(e.path, e.info)
618 err := filepath.Walk(v.Root, func(path string, info os.FileInfo, err error) error {
620 v.logger.WithError(err).Errorf("EmptyTrash: filepath.Walk(%q) failed", path)
621 // Don't give up -- keep walking other
624 } else if !info.Mode().IsDir() {
625 todo <- dirent{path, info}
627 } else if path == v.Root || blockDirRe.MatchString(info.Name()) {
628 // Descend into a directory that we might have
632 // Don't descend into other dirs.
633 return filepath.SkipDir
640 v.logger.WithError(err).Error("EmptyTrash failed")
643 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)
646 type unixStats struct {
658 func (s *unixStats) TickErr(err error) {
662 s.statsTicker.TickErr(err, fmt.Sprintf("%T", err))
665 type osWithStats struct {
669 func (o *osWithStats) Open(name string) (*os.File, error) {
670 o.stats.TickOps("open")
671 o.stats.Tick(&o.stats.OpenOps)
672 f, err := os.Open(name)
677 func (o *osWithStats) OpenFile(name string, flag int, perm os.FileMode) (*os.File, error) {
678 o.stats.TickOps("open")
679 o.stats.Tick(&o.stats.OpenOps)
680 f, err := os.OpenFile(name, flag, perm)
685 func (o *osWithStats) Remove(path string) error {
686 o.stats.TickOps("unlink")
687 o.stats.Tick(&o.stats.UnlinkOps)
688 err := os.Remove(path)
693 func (o *osWithStats) Rename(a, b string) error {
694 o.stats.TickOps("rename")
695 o.stats.Tick(&o.stats.RenameOps)
696 err := os.Rename(a, b)
701 func (o *osWithStats) Stat(path string) (os.FileInfo, error) {
702 o.stats.TickOps("stat")
703 o.stats.Tick(&o.stats.StatOps)
704 fi, err := os.Stat(path)
709 func (o *osWithStats) TempFile(dir, base string) (*os.File, error) {
710 o.stats.TickOps("create")
711 o.stats.Tick(&o.stats.CreateOps)
712 f, err := ioutil.TempFile(dir, base)