Merge branch '18336-httplib2-pysdk-issues' into main. Closes #18336
[arvados.git] / services / keepstore / unix_volume.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package keepstore
6
7 import (
8         "context"
9         "encoding/json"
10         "errors"
11         "fmt"
12         "io"
13         "io/ioutil"
14         "os"
15         "os/exec"
16         "path/filepath"
17         "regexp"
18         "strconv"
19         "strings"
20         "sync"
21         "sync/atomic"
22         "syscall"
23         "time"
24
25         "git.arvados.org/arvados.git/sdk/go/arvados"
26         "github.com/prometheus/client_golang/prometheus"
27         "github.com/sirupsen/logrus"
28 )
29
30 func init() {
31         driver["Directory"] = newDirectoryVolume
32 }
33
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)
37         if err != nil {
38                 return nil, err
39         }
40         v.logger = v.logger.WithField("Volume", v.String())
41         return v, v.check()
42 }
43
44 func (v *UnixVolume) check() error {
45         if v.Root == "" {
46                 return errors.New("DriverParameters.Root was not provided")
47         }
48         if v.Serialize {
49                 v.locker = &sync.Mutex{}
50         }
51         if !strings.HasPrefix(v.Root, "/") {
52                 return fmt.Errorf("DriverParameters.Root %q does not start with '/'", v.Root)
53         }
54
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)
58
59         _, err := v.os.Stat(v.Root)
60         return err
61 }
62
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
66         Serialize bool
67
68         cluster *arvados.Cluster
69         volume  arvados.Volume
70         logger  logrus.FieldLogger
71         metrics *volumeMetricsVecs
72
73         // something to lock during IO, typically a sync.Mutex (or nil
74         // to skip locking)
75         locker sync.Locker
76
77         os osWithStats
78 }
79
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)...)
88                 return ""
89         }
90         buf, err := exec.Command("findmnt", "--noheadings", "--target", v.Root).CombinedOutput()
91         if err != nil {
92                 return giveup("findmnt: %s (%q)", err, buf)
93         }
94         findmnt := strings.Fields(string(buf))
95         if len(findmnt) < 2 {
96                 return giveup("could not parse findmnt output: %q", buf)
97         }
98         fsRoot, dev := findmnt[0], findmnt[1]
99
100         absRoot, err := filepath.Abs(v.Root)
101         if err != nil {
102                 return giveup("resolving relative path %q: %s", v.Root, err)
103         }
104         realRoot, err := filepath.EvalSymlinks(absRoot)
105         if err != nil {
106                 return giveup("resolving symlinks in %q: %s", absRoot, err)
107         }
108
109         // Find path from filesystem root to realRoot
110         var fsPath string
111         if strings.HasPrefix(realRoot, fsRoot+"/") {
112                 fsPath = realRoot[len(fsRoot):]
113         } else if fsRoot == "/" {
114                 fsPath = realRoot
115         } else if fsRoot == realRoot {
116                 fsPath = ""
117         } else {
118                 return giveup("findmnt reports mount point %q which is not a prefix of volume root %q", fsRoot, realRoot)
119         }
120
121         if !strings.HasPrefix(dev, "/") {
122                 return giveup("mount %q device %q is not a path", fsRoot, dev)
123         }
124
125         fi, err := os.Stat(dev)
126         if err != nil {
127                 return giveup("stat %q: %s", dev, err)
128         }
129         ino := fi.Sys().(*syscall.Stat_t).Ino
130
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)
135         if err != nil {
136                 return giveup("opening %q: %s", udir, err)
137         }
138         defer d.Close()
139         uuids, err := d.Readdirnames(0)
140         if err != nil {
141                 return giveup("reading %q: %s", udir, err)
142         }
143         for _, uuid := range uuids {
144                 link := filepath.Join(udir, uuid)
145                 fi, err = os.Stat(link)
146                 if err != nil {
147                         v.logger.WithError(err).Errorf("stat(%q) failed", link)
148                         continue
149                 }
150                 if fi.Sys().(*syscall.Stat_t).Ino == ino {
151                         return uuid + fsPath
152                 }
153         }
154         return giveup("could not find entry in %q matching %q", udir, dev)
155 }
156
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
161         }
162         p := v.blockPath(loc)
163         f, err := v.os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
164         if err != nil {
165                 return err
166         }
167         defer f.Close()
168         if err := v.lock(context.TODO()); err != nil {
169                 return err
170         }
171         defer v.unlock()
172         if e := v.lockfile(f); e != nil {
173                 return e
174         }
175         defer v.unlockfile(f)
176         ts := time.Now()
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)
181         return err
182 }
183
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)
188         if err != nil {
189                 return time.Time{}, err
190         }
191         return fi.ModTime(), nil
192 }
193
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 {
198                 return err
199         }
200         defer v.unlock()
201         f, err := v.os.Open(path)
202         if err != nil {
203                 return err
204         }
205         defer f.Close()
206         return fn(NewCountingReader(ioutil.NopCloser(f), v.os.stats.TickInBytes))
207 }
208
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)
212         if err == nil {
213                 if stat.Size() < 0 {
214                         err = os.ErrInvalid
215                 } else if stat.Size() > BlockSize {
216                         err = TooLongError
217                 }
218         }
219         return stat, err
220 }
221
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)
226 }
227
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)
232         if err != nil {
233                 return v.translateError(err)
234         }
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
239                 }
240                 return err
241         })
242 }
243
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)
251         }
252         return v.getFunc(ctx, path, func(rdr io.Reader) error {
253                 return compareReaderWithBuf(ctx, rdr, expect, loc[:32])
254         })
255 }
256
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)
263 }
264
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
269         }
270         if v.IsFull() {
271                 return FullError
272         }
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)
276         }
277
278         bpath := v.blockPath(loc)
279         tmpfile, err := v.os.TempFile(bdir, "tmp"+loc)
280         if err != nil {
281                 return fmt.Errorf("TempFile(%s, tmp%s) failed: %s", bdir, loc, err)
282         }
283         defer v.os.Remove(tmpfile.Name())
284         defer tmpfile.Close()
285
286         if err = v.lock(ctx); err != nil {
287                 return err
288         }
289         defer v.unlock()
290         n, err := io.Copy(tmpfile, rdr)
291         v.os.stats.TickOutBytes(uint64(n))
292         if err != nil {
293                 return fmt.Errorf("error writing %s: %s", bpath, err)
294         }
295         if err = tmpfile.Close(); err != nil {
296                 return fmt.Errorf("error closing %s: %s", tmpfile.Name(), err)
297         }
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.
303         ts := time.Now()
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)
308         }
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)
311         }
312         return nil
313 }
314
315 // Status returns a VolumeStatus struct describing the volume's
316 // current state, or nil if an error occurs.
317 //
318 func (v *UnixVolume) Status() *VolumeStatus {
319         fi, err := v.os.Stat(v.Root)
320         if err != nil {
321                 v.logger.WithError(err).Error("stat failed")
322                 return nil
323         }
324         devnum := fi.Sys().(*syscall.Stat_t).Dev
325
326         var fs syscall.Statfs_t
327         if err := syscall.Statfs(v.Root, &fs); err != nil {
328                 v.logger.WithError(err).Error("statfs failed")
329                 return nil
330         }
331         // These calculations match the way df calculates disk usage:
332         // "free" space is measured by fs.Bavail, but "used" space
333         // uses fs.Blocks - fs.Bfree.
334         free := fs.Bavail * uint64(fs.Bsize)
335         used := (fs.Blocks - fs.Bfree) * uint64(fs.Bsize)
336         return &VolumeStatus{
337                 MountPoint: v.Root,
338                 DeviceNum:  devnum,
339                 BytesFree:  free,
340                 BytesUsed:  used,
341         }
342 }
343
344 var blockDirRe = regexp.MustCompile(`^[0-9a-f]+$`)
345 var blockFileRe = regexp.MustCompile(`^[0-9a-f]{32}$`)
346
347 // IndexTo writes (to the given Writer) a list of blocks found on this
348 // volume which begin with the specified prefix. If the prefix is an
349 // empty string, IndexTo writes a complete list of blocks.
350 //
351 // Each block is given in the format
352 //
353 //     locator+size modification-time {newline}
354 //
355 // e.g.:
356 //
357 //     e4df392f86be161ca6ed3773a962b8f3+67108864 1388894303
358 //     e4d41e6fd68460e0e3fc18cc746959d2+67108864 1377796043
359 //     e4de7a2810f5554cd39b36d8ddb132ff+67108864 1388701136
360 //
361 func (v *UnixVolume) IndexTo(prefix string, w io.Writer) error {
362         rootdir, err := v.os.Open(v.Root)
363         if err != nil {
364                 return err
365         }
366         v.os.stats.TickOps("readdir")
367         v.os.stats.Tick(&v.os.stats.ReaddirOps)
368         subdirs, err := rootdir.Readdirnames(-1)
369         rootdir.Close()
370         if err != nil {
371                 return err
372         }
373         for _, subdir := range subdirs {
374                 if !strings.HasPrefix(subdir, prefix) && !strings.HasPrefix(prefix, subdir) {
375                         // prefix excludes all blocks stored in this dir
376                         continue
377                 }
378                 if !blockDirRe.MatchString(subdir) {
379                         continue
380                 }
381                 blockdirpath := filepath.Join(v.Root, subdir)
382                 blockdir, err := v.os.Open(blockdirpath)
383                 if err != nil {
384                         v.logger.WithError(err).Errorf("error reading %q", blockdirpath)
385                         return fmt.Errorf("error reading %q: %s", blockdirpath, err)
386                 }
387                 v.os.stats.TickOps("readdir")
388                 v.os.stats.Tick(&v.os.stats.ReaddirOps)
389                 // ReadDir() (compared to Readdir(), which returns
390                 // FileInfo structs) helps complete the sequence of
391                 // readdirent calls as quickly as possible, reducing
392                 // the likelihood of NFS EBADCOOKIE (523) errors.
393                 dirents, err := blockdir.ReadDir(-1)
394                 blockdir.Close()
395                 if err != nil {
396                         v.logger.WithError(err).Errorf("error reading %q", blockdirpath)
397                         return fmt.Errorf("error reading %q: %s", blockdirpath, err)
398                 }
399                 for _, dirent := range dirents {
400                         fileInfo, err := dirent.Info()
401                         if os.IsNotExist(err) {
402                                 // File disappeared between ReadDir() and now
403                                 continue
404                         } else if err != nil {
405                                 v.logger.WithError(err).Errorf("error getting FileInfo for %q in %q", dirent.Name(), blockdirpath)
406                                 return err
407                         }
408                         name := fileInfo.Name()
409                         if !strings.HasPrefix(name, prefix) {
410                                 continue
411                         }
412                         if !blockFileRe.MatchString(name) {
413                                 continue
414                         }
415                         _, err = fmt.Fprint(w,
416                                 name,
417                                 "+", fileInfo.Size(),
418                                 " ", fileInfo.ModTime().UnixNano(),
419                                 "\n")
420                         if err != nil {
421                                 return fmt.Errorf("error writing: %s", err)
422                         }
423                 }
424         }
425         return nil
426 }
427
428 // Trash trashes the block data from the unix storage
429 // If BlobTrashLifetime == 0, the block is deleted
430 // Else, the block is renamed as path/{loc}.trash.{deadline},
431 // where deadline = now + BlobTrashLifetime
432 func (v *UnixVolume) Trash(loc string) error {
433         // Touch() must be called before calling Write() on a block.  Touch()
434         // also uses lockfile().  This avoids a race condition between Write()
435         // and Trash() because either (a) the file will be trashed and Touch()
436         // will signal to the caller that the file is not present (and needs to
437         // be re-written), or (b) Touch() will update the file's timestamp and
438         // Trash() will read the correct up-to-date timestamp and choose not to
439         // trash the file.
440
441         if v.volume.ReadOnly || !v.cluster.Collections.BlobTrash {
442                 return MethodDisabledError
443         }
444         if err := v.lock(context.TODO()); err != nil {
445                 return err
446         }
447         defer v.unlock()
448         p := v.blockPath(loc)
449         f, err := v.os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
450         if err != nil {
451                 return err
452         }
453         defer f.Close()
454         if e := v.lockfile(f); e != nil {
455                 return e
456         }
457         defer v.unlockfile(f)
458
459         // If the block has been PUT in the last blobSignatureTTL
460         // seconds, return success without removing the block. This
461         // protects data from garbage collection until it is no longer
462         // possible for clients to retrieve the unreferenced blocks
463         // anyway (because the permission signatures have expired).
464         if fi, err := v.os.Stat(p); err != nil {
465                 return err
466         } else if time.Since(fi.ModTime()) < v.cluster.Collections.BlobSigningTTL.Duration() {
467                 return nil
468         }
469
470         if v.cluster.Collections.BlobTrashLifetime == 0 {
471                 return v.os.Remove(p)
472         }
473         return v.os.Rename(p, fmt.Sprintf("%v.trash.%d", p, time.Now().Add(v.cluster.Collections.BlobTrashLifetime.Duration()).Unix()))
474 }
475
476 // Untrash moves block from trash back into store
477 // Look for path/{loc}.trash.{deadline} in storage,
478 // and rename the first such file as path/{loc}
479 func (v *UnixVolume) Untrash(loc string) (err error) {
480         if v.volume.ReadOnly {
481                 return MethodDisabledError
482         }
483
484         v.os.stats.TickOps("readdir")
485         v.os.stats.Tick(&v.os.stats.ReaddirOps)
486         files, err := ioutil.ReadDir(v.blockDir(loc))
487         if err != nil {
488                 return err
489         }
490
491         if len(files) == 0 {
492                 return os.ErrNotExist
493         }
494
495         foundTrash := false
496         prefix := fmt.Sprintf("%v.trash.", loc)
497         for _, f := range files {
498                 if strings.HasPrefix(f.Name(), prefix) {
499                         foundTrash = true
500                         err = v.os.Rename(v.blockPath(f.Name()), v.blockPath(loc))
501                         if err == nil {
502                                 break
503                         }
504                 }
505         }
506
507         if foundTrash == false {
508                 return os.ErrNotExist
509         }
510
511         return
512 }
513
514 // blockDir returns the fully qualified directory name for the directory
515 // where loc is (or would be) stored on this volume.
516 func (v *UnixVolume) blockDir(loc string) string {
517         return filepath.Join(v.Root, loc[0:3])
518 }
519
520 // blockPath returns the fully qualified pathname for the path to loc
521 // on this volume.
522 func (v *UnixVolume) blockPath(loc string) string {
523         return filepath.Join(v.blockDir(loc), loc)
524 }
525
526 // IsFull returns true if the free space on the volume is less than
527 // MinFreeKilobytes.
528 //
529 func (v *UnixVolume) IsFull() (isFull bool) {
530         fullSymlink := v.Root + "/full"
531
532         // Check if the volume has been marked as full in the last hour.
533         if link, err := os.Readlink(fullSymlink); err == nil {
534                 if ts, err := strconv.Atoi(link); err == nil {
535                         fulltime := time.Unix(int64(ts), 0)
536                         if time.Since(fulltime).Hours() < 1.0 {
537                                 return true
538                         }
539                 }
540         }
541
542         if avail, err := v.FreeDiskSpace(); err == nil {
543                 isFull = avail < MinFreeKilobytes
544         } else {
545                 v.logger.WithError(err).Errorf("%s: FreeDiskSpace failed", v)
546                 isFull = false
547         }
548
549         // If the volume is full, timestamp it.
550         if isFull {
551                 now := fmt.Sprintf("%d", time.Now().Unix())
552                 os.Symlink(now, fullSymlink)
553         }
554         return
555 }
556
557 // FreeDiskSpace returns the number of unused 1k blocks available on
558 // the volume.
559 //
560 func (v *UnixVolume) FreeDiskSpace() (free uint64, err error) {
561         var fs syscall.Statfs_t
562         err = syscall.Statfs(v.Root, &fs)
563         if err == nil {
564                 // Statfs output is not guaranteed to measure free
565                 // space in terms of 1K blocks.
566                 free = fs.Bavail * uint64(fs.Bsize) / 1024
567         }
568         return
569 }
570
571 func (v *UnixVolume) String() string {
572         return fmt.Sprintf("[UnixVolume %s]", v.Root)
573 }
574
575 // InternalStats returns I/O and filesystem ops counters.
576 func (v *UnixVolume) InternalStats() interface{} {
577         return &v.os.stats
578 }
579
580 // lock acquires the serialize lock, if one is in use. If ctx is done
581 // before the lock is acquired, lock returns ctx.Err() instead of
582 // acquiring the lock.
583 func (v *UnixVolume) lock(ctx context.Context) error {
584         if v.locker == nil {
585                 return nil
586         }
587         t0 := time.Now()
588         locked := make(chan struct{})
589         go func() {
590                 v.locker.Lock()
591                 close(locked)
592         }()
593         select {
594         case <-ctx.Done():
595                 v.logger.Infof("client hung up while waiting for Serialize lock (%s)", time.Since(t0))
596                 go func() {
597                         <-locked
598                         v.locker.Unlock()
599                 }()
600                 return ctx.Err()
601         case <-locked:
602                 return nil
603         }
604 }
605
606 // unlock releases the serialize lock, if one is in use.
607 func (v *UnixVolume) unlock() {
608         if v.locker == nil {
609                 return
610         }
611         v.locker.Unlock()
612 }
613
614 // lockfile and unlockfile use flock(2) to manage kernel file locks.
615 func (v *UnixVolume) lockfile(f *os.File) error {
616         v.os.stats.TickOps("flock")
617         v.os.stats.Tick(&v.os.stats.FlockOps)
618         err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
619         v.os.stats.TickErr(err)
620         return err
621 }
622
623 func (v *UnixVolume) unlockfile(f *os.File) error {
624         err := syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
625         v.os.stats.TickErr(err)
626         return err
627 }
628
629 // Where appropriate, translate a more specific filesystem error to an
630 // error recognized by handlers, like os.ErrNotExist.
631 func (v *UnixVolume) translateError(err error) error {
632         switch err.(type) {
633         case *os.PathError:
634                 // stat() returns a PathError if the parent directory
635                 // (not just the file itself) is missing
636                 return os.ErrNotExist
637         default:
638                 return err
639         }
640 }
641
642 var unixTrashLocRegexp = regexp.MustCompile(`/([0-9a-f]{32})\.trash\.(\d+)$`)
643
644 // EmptyTrash walks hierarchy looking for {hash}.trash.*
645 // and deletes those with deadline < now.
646 func (v *UnixVolume) EmptyTrash() {
647         if v.cluster.Collections.BlobDeleteConcurrency < 1 {
648                 return
649         }
650
651         var bytesDeleted, bytesInTrash int64
652         var blocksDeleted, blocksInTrash int64
653
654         doFile := func(path string, info os.FileInfo) {
655                 if info.Mode().IsDir() {
656                         return
657                 }
658                 matches := unixTrashLocRegexp.FindStringSubmatch(path)
659                 if len(matches) != 3 {
660                         return
661                 }
662                 deadline, err := strconv.ParseInt(matches[2], 10, 64)
663                 if err != nil {
664                         v.logger.WithError(err).Errorf("EmptyTrash: %v: ParseInt(%q) failed", path, matches[2])
665                         return
666                 }
667                 atomic.AddInt64(&bytesInTrash, info.Size())
668                 atomic.AddInt64(&blocksInTrash, 1)
669                 if deadline > time.Now().Unix() {
670                         return
671                 }
672                 err = v.os.Remove(path)
673                 if err != nil {
674                         v.logger.WithError(err).Errorf("EmptyTrash: Remove(%q) failed", path)
675                         return
676                 }
677                 atomic.AddInt64(&bytesDeleted, info.Size())
678                 atomic.AddInt64(&blocksDeleted, 1)
679         }
680
681         type dirent struct {
682                 path string
683                 info os.FileInfo
684         }
685         var wg sync.WaitGroup
686         todo := make(chan dirent, v.cluster.Collections.BlobDeleteConcurrency)
687         for i := 0; i < v.cluster.Collections.BlobDeleteConcurrency; i++ {
688                 wg.Add(1)
689                 go func() {
690                         defer wg.Done()
691                         for e := range todo {
692                                 doFile(e.path, e.info)
693                         }
694                 }()
695         }
696
697         err := filepath.Walk(v.Root, func(path string, info os.FileInfo, err error) error {
698                 if err != nil {
699                         v.logger.WithError(err).Errorf("EmptyTrash: filepath.Walk(%q) failed", path)
700                         // Don't give up -- keep walking other
701                         // files/dirs
702                         return nil
703                 } else if !info.Mode().IsDir() {
704                         todo <- dirent{path, info}
705                         return nil
706                 } else if path == v.Root || blockDirRe.MatchString(info.Name()) {
707                         // Descend into a directory that we might have
708                         // put trash in.
709                         return nil
710                 } else {
711                         // Don't descend into other dirs.
712                         return filepath.SkipDir
713                 }
714         })
715         close(todo)
716         wg.Wait()
717
718         if err != nil {
719                 v.logger.WithError(err).Error("EmptyTrash failed")
720         }
721
722         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 }
724
725 type unixStats struct {
726         statsTicker
727         OpenOps    uint64
728         StatOps    uint64
729         FlockOps   uint64
730         UtimesOps  uint64
731         CreateOps  uint64
732         RenameOps  uint64
733         UnlinkOps  uint64
734         ReaddirOps uint64
735 }
736
737 func (s *unixStats) TickErr(err error) {
738         if err == nil {
739                 return
740         }
741         s.statsTicker.TickErr(err, fmt.Sprintf("%T", err))
742 }
743
744 type osWithStats struct {
745         stats unixStats
746 }
747
748 func (o *osWithStats) Open(name string) (*os.File, error) {
749         o.stats.TickOps("open")
750         o.stats.Tick(&o.stats.OpenOps)
751         f, err := os.Open(name)
752         o.stats.TickErr(err)
753         return f, err
754 }
755
756 func (o *osWithStats) OpenFile(name string, flag int, perm os.FileMode) (*os.File, error) {
757         o.stats.TickOps("open")
758         o.stats.Tick(&o.stats.OpenOps)
759         f, err := os.OpenFile(name, flag, perm)
760         o.stats.TickErr(err)
761         return f, err
762 }
763
764 func (o *osWithStats) Remove(path string) error {
765         o.stats.TickOps("unlink")
766         o.stats.Tick(&o.stats.UnlinkOps)
767         err := os.Remove(path)
768         o.stats.TickErr(err)
769         return err
770 }
771
772 func (o *osWithStats) Rename(a, b string) error {
773         o.stats.TickOps("rename")
774         o.stats.Tick(&o.stats.RenameOps)
775         err := os.Rename(a, b)
776         o.stats.TickErr(err)
777         return err
778 }
779
780 func (o *osWithStats) Stat(path string) (os.FileInfo, error) {
781         o.stats.TickOps("stat")
782         o.stats.Tick(&o.stats.StatOps)
783         fi, err := os.Stat(path)
784         o.stats.TickErr(err)
785         return fi, err
786 }
787
788 func (o *osWithStats) TempFile(dir, base string) (*os.File, error) {
789         o.stats.TickOps("create")
790         o.stats.Tick(&o.stats.CreateOps)
791         f, err := ioutil.TempFile(dir, base)
792         o.stats.TickErr(err)
793         return f, err
794 }