Merge branch 'patch-1' of https://github.com/mr-c/arvados into mr-c-patch-1
[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 main
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         uuids, err := d.Readdirnames(0)
139         if err != nil {
140                 return giveup("reading %q: %s", udir, err)
141         }
142         for _, uuid := range uuids {
143                 link := filepath.Join(udir, uuid)
144                 fi, err = os.Stat(link)
145                 if err != nil {
146                         v.logger.WithError(err).Errorf("stat(%q) failed", link)
147                         continue
148                 }
149                 if fi.Sys().(*syscall.Stat_t).Ino == ino {
150                         return uuid + fsPath
151                 }
152         }
153         return giveup("could not find entry in %q matching %q", udir, dev)
154 }
155
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
160         }
161         p := v.blockPath(loc)
162         f, err := v.os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
163         if err != nil {
164                 return err
165         }
166         defer f.Close()
167         if err := v.lock(context.TODO()); err != nil {
168                 return err
169         }
170         defer v.unlock()
171         if e := v.lockfile(f); e != nil {
172                 return e
173         }
174         defer v.unlockfile(f)
175         ts := time.Now()
176         v.os.stats.TickOps("utimes")
177         v.os.stats.Tick(&v.os.stats.UtimesOps)
178         err = os.Chtimes(p, ts, ts)
179         v.os.stats.TickErr(err)
180         return err
181 }
182
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)
187         if err != nil {
188                 return time.Time{}, err
189         }
190         return fi.ModTime(), nil
191 }
192
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 {
197                 return err
198         }
199         defer v.unlock()
200         f, err := v.os.Open(path)
201         if err != nil {
202                 return err
203         }
204         defer f.Close()
205         return fn(NewCountingReader(ioutil.NopCloser(f), v.os.stats.TickInBytes))
206 }
207
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)
211         if err == nil {
212                 if stat.Size() < 0 {
213                         err = os.ErrInvalid
214                 } else if stat.Size() > BlockSize {
215                         err = TooLongError
216                 }
217         }
218         return stat, err
219 }
220
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)
225 }
226
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)
231         if err != nil {
232                 return v.translateError(err)
233         }
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
238                 }
239                 return err
240         })
241 }
242
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)
250         }
251         return v.getFunc(ctx, path, func(rdr io.Reader) error {
252                 return compareReaderWithBuf(ctx, rdr, expect, loc[:32])
253         })
254 }
255
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)
262 }
263
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
268         }
269         if v.IsFull() {
270                 return FullError
271         }
272         bdir := v.blockDir(loc)
273         if err := os.MkdirAll(bdir, 0755); err != nil {
274                 return fmt.Errorf("error creating directory %s: %s", bdir, err)
275         }
276
277         tmpfile, tmperr := v.os.TempFile(bdir, "tmp"+loc)
278         if tmperr != nil {
279                 return fmt.Errorf("TempFile(%s, tmp%s) failed: %s", bdir, loc, tmperr)
280         }
281
282         bpath := v.blockPath(loc)
283
284         if err := v.lock(ctx); err != nil {
285                 return err
286         }
287         defer v.unlock()
288         n, err := io.Copy(tmpfile, rdr)
289         v.os.stats.TickOutBytes(uint64(n))
290         if err != nil {
291                 err = fmt.Errorf("error writing %s: %s", bpath, err)
292                 tmpfile.Close()
293                 v.os.Remove(tmpfile.Name())
294                 return err
295         }
296         if err := tmpfile.Close(); err != nil {
297                 err = fmt.Errorf("error closing %s: %s", tmpfile.Name(), err)
298                 v.os.Remove(tmpfile.Name())
299                 return err
300         }
301         // ext4 uses a low-precision clock and effectively backdates
302         // files by up to 10 ms, sometimes across a 1-second boundary,
303         // which produces confusing results in logs and tests.  We
304         // avoid this by setting the output file's timestamps
305         // explicitly, using a higher resolution clock.
306         ts := time.Now()
307         v.os.stats.TickOps("utimes")
308         v.os.stats.Tick(&v.os.stats.UtimesOps)
309         if err = os.Chtimes(tmpfile.Name(), ts, ts); err != nil {
310                 err = fmt.Errorf("error setting timestamps on %s: %s", tmpfile.Name(), err)
311                 v.os.Remove(tmpfile.Name())
312                 return err
313         }
314         if err := v.os.Rename(tmpfile.Name(), bpath); err != nil {
315                 err = fmt.Errorf("error renaming %s to %s: %s", tmpfile.Name(), bpath, err)
316                 v.os.Remove(tmpfile.Name())
317                 return err
318         }
319         return nil
320 }
321
322 // Status returns a VolumeStatus struct describing the volume's
323 // current state, or nil if an error occurs.
324 //
325 func (v *UnixVolume) Status() *VolumeStatus {
326         fi, err := v.os.Stat(v.Root)
327         if err != nil {
328                 v.logger.WithError(err).Error("stat failed")
329                 return nil
330         }
331         devnum := fi.Sys().(*syscall.Stat_t).Dev
332
333         var fs syscall.Statfs_t
334         if err := syscall.Statfs(v.Root, &fs); err != nil {
335                 v.logger.WithError(err).Error("statfs failed")
336                 return nil
337         }
338         // These calculations match the way df calculates disk usage:
339         // "free" space is measured by fs.Bavail, but "used" space
340         // uses fs.Blocks - fs.Bfree.
341         free := fs.Bavail * uint64(fs.Bsize)
342         used := (fs.Blocks - fs.Bfree) * uint64(fs.Bsize)
343         return &VolumeStatus{
344                 MountPoint: v.Root,
345                 DeviceNum:  devnum,
346                 BytesFree:  free,
347                 BytesUsed:  used,
348         }
349 }
350
351 var blockDirRe = regexp.MustCompile(`^[0-9a-f]+$`)
352 var blockFileRe = regexp.MustCompile(`^[0-9a-f]{32}$`)
353
354 // IndexTo writes (to the given Writer) a list of blocks found on this
355 // volume which begin with the specified prefix. If the prefix is an
356 // empty string, IndexTo writes a complete list of blocks.
357 //
358 // Each block is given in the format
359 //
360 //     locator+size modification-time {newline}
361 //
362 // e.g.:
363 //
364 //     e4df392f86be161ca6ed3773a962b8f3+67108864 1388894303
365 //     e4d41e6fd68460e0e3fc18cc746959d2+67108864 1377796043
366 //     e4de7a2810f5554cd39b36d8ddb132ff+67108864 1388701136
367 //
368 func (v *UnixVolume) IndexTo(prefix string, w io.Writer) error {
369         var lastErr error
370         rootdir, err := v.os.Open(v.Root)
371         if err != nil {
372                 return err
373         }
374         defer rootdir.Close()
375         v.os.stats.TickOps("readdir")
376         v.os.stats.Tick(&v.os.stats.ReaddirOps)
377         for {
378                 names, err := rootdir.Readdirnames(1)
379                 if err == io.EOF {
380                         return lastErr
381                 } else if err != nil {
382                         return err
383                 }
384                 if !strings.HasPrefix(names[0], prefix) && !strings.HasPrefix(prefix, names[0]) {
385                         // prefix excludes all blocks stored in this dir
386                         continue
387                 }
388                 if !blockDirRe.MatchString(names[0]) {
389                         continue
390                 }
391                 blockdirpath := filepath.Join(v.Root, names[0])
392                 blockdir, err := v.os.Open(blockdirpath)
393                 if err != nil {
394                         v.logger.WithError(err).Errorf("error reading %q", blockdirpath)
395                         lastErr = fmt.Errorf("error reading %q: %s", blockdirpath, err)
396                         continue
397                 }
398                 v.os.stats.TickOps("readdir")
399                 v.os.stats.Tick(&v.os.stats.ReaddirOps)
400                 for {
401                         fileInfo, err := blockdir.Readdir(1)
402                         if err == io.EOF {
403                                 break
404                         } else if err != nil {
405                                 v.logger.WithError(err).Errorf("error reading %q", blockdirpath)
406                                 lastErr = fmt.Errorf("error reading %q: %s", blockdirpath, err)
407                                 break
408                         }
409                         name := fileInfo[0].Name()
410                         if !strings.HasPrefix(name, prefix) {
411                                 continue
412                         }
413                         if !blockFileRe.MatchString(name) {
414                                 continue
415                         }
416                         _, err = fmt.Fprint(w,
417                                 name,
418                                 "+", fileInfo[0].Size(),
419                                 " ", fileInfo[0].ModTime().UnixNano(),
420                                 "\n")
421                         if err != nil {
422                                 blockdir.Close()
423                                 return fmt.Errorf("error writing: %s", err)
424                         }
425                 }
426                 blockdir.Close()
427         }
428 }
429
430 // Trash trashes the block data from the unix storage
431 // If BlobTrashLifetime == 0, the block is deleted
432 // Else, the block is renamed as path/{loc}.trash.{deadline},
433 // where deadline = now + BlobTrashLifetime
434 func (v *UnixVolume) Trash(loc string) error {
435         // Touch() must be called before calling Write() on a block.  Touch()
436         // also uses lockfile().  This avoids a race condition between Write()
437         // and Trash() because either (a) the file will be trashed and Touch()
438         // will signal to the caller that the file is not present (and needs to
439         // be re-written), or (b) Touch() will update the file's timestamp and
440         // Trash() will read the correct up-to-date timestamp and choose not to
441         // trash the file.
442
443         if v.volume.ReadOnly || !v.cluster.Collections.BlobTrash {
444                 return MethodDisabledError
445         }
446         if err := v.lock(context.TODO()); err != nil {
447                 return err
448         }
449         defer v.unlock()
450         p := v.blockPath(loc)
451         f, err := v.os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
452         if err != nil {
453                 return err
454         }
455         defer f.Close()
456         if e := v.lockfile(f); e != nil {
457                 return e
458         }
459         defer v.unlockfile(f)
460
461         // If the block has been PUT in the last blobSignatureTTL
462         // seconds, return success without removing the block. This
463         // protects data from garbage collection until it is no longer
464         // possible for clients to retrieve the unreferenced blocks
465         // anyway (because the permission signatures have expired).
466         if fi, err := v.os.Stat(p); err != nil {
467                 return err
468         } else if time.Since(fi.ModTime()) < v.cluster.Collections.BlobSigningTTL.Duration() {
469                 return nil
470         }
471
472         if v.cluster.Collections.BlobTrashLifetime == 0 {
473                 return v.os.Remove(p)
474         }
475         return v.os.Rename(p, fmt.Sprintf("%v.trash.%d", p, time.Now().Add(v.cluster.Collections.BlobTrashLifetime.Duration()).Unix()))
476 }
477
478 // Untrash moves block from trash back into store
479 // Look for path/{loc}.trash.{deadline} in storage,
480 // and rename the first such file as path/{loc}
481 func (v *UnixVolume) Untrash(loc string) (err error) {
482         if v.volume.ReadOnly {
483                 return MethodDisabledError
484         }
485
486         v.os.stats.TickOps("readdir")
487         v.os.stats.Tick(&v.os.stats.ReaddirOps)
488         files, err := ioutil.ReadDir(v.blockDir(loc))
489         if err != nil {
490                 return err
491         }
492
493         if len(files) == 0 {
494                 return os.ErrNotExist
495         }
496
497         foundTrash := false
498         prefix := fmt.Sprintf("%v.trash.", loc)
499         for _, f := range files {
500                 if strings.HasPrefix(f.Name(), prefix) {
501                         foundTrash = true
502                         err = v.os.Rename(v.blockPath(f.Name()), v.blockPath(loc))
503                         if err == nil {
504                                 break
505                         }
506                 }
507         }
508
509         if foundTrash == false {
510                 return os.ErrNotExist
511         }
512
513         return
514 }
515
516 // blockDir returns the fully qualified directory name for the directory
517 // where loc is (or would be) stored on this volume.
518 func (v *UnixVolume) blockDir(loc string) string {
519         return filepath.Join(v.Root, loc[0:3])
520 }
521
522 // blockPath returns the fully qualified pathname for the path to loc
523 // on this volume.
524 func (v *UnixVolume) blockPath(loc string) string {
525         return filepath.Join(v.blockDir(loc), loc)
526 }
527
528 // IsFull returns true if the free space on the volume is less than
529 // MinFreeKilobytes.
530 //
531 func (v *UnixVolume) IsFull() (isFull bool) {
532         fullSymlink := v.Root + "/full"
533
534         // Check if the volume has been marked as full in the last hour.
535         if link, err := os.Readlink(fullSymlink); err == nil {
536                 if ts, err := strconv.Atoi(link); err == nil {
537                         fulltime := time.Unix(int64(ts), 0)
538                         if time.Since(fulltime).Hours() < 1.0 {
539                                 return true
540                         }
541                 }
542         }
543
544         if avail, err := v.FreeDiskSpace(); err == nil {
545                 isFull = avail < MinFreeKilobytes
546         } else {
547                 v.logger.WithError(err).Errorf("%s: FreeDiskSpace failed", v)
548                 isFull = false
549         }
550
551         // If the volume is full, timestamp it.
552         if isFull {
553                 now := fmt.Sprintf("%d", time.Now().Unix())
554                 os.Symlink(now, fullSymlink)
555         }
556         return
557 }
558
559 // FreeDiskSpace returns the number of unused 1k blocks available on
560 // the volume.
561 //
562 func (v *UnixVolume) FreeDiskSpace() (free uint64, err error) {
563         var fs syscall.Statfs_t
564         err = syscall.Statfs(v.Root, &fs)
565         if err == nil {
566                 // Statfs output is not guaranteed to measure free
567                 // space in terms of 1K blocks.
568                 free = fs.Bavail * uint64(fs.Bsize) / 1024
569         }
570         return
571 }
572
573 func (v *UnixVolume) String() string {
574         return fmt.Sprintf("[UnixVolume %s]", v.Root)
575 }
576
577 // InternalStats returns I/O and filesystem ops counters.
578 func (v *UnixVolume) InternalStats() interface{} {
579         return &v.os.stats
580 }
581
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 {
586         if v.locker == nil {
587                 return nil
588         }
589         t0 := time.Now()
590         locked := make(chan struct{})
591         go func() {
592                 v.locker.Lock()
593                 close(locked)
594         }()
595         select {
596         case <-ctx.Done():
597                 v.logger.Infof("client hung up while waiting for Serialize lock (%s)", time.Since(t0))
598                 go func() {
599                         <-locked
600                         v.locker.Unlock()
601                 }()
602                 return ctx.Err()
603         case <-locked:
604                 return nil
605         }
606 }
607
608 // unlock releases the serialize lock, if one is in use.
609 func (v *UnixVolume) unlock() {
610         if v.locker == nil {
611                 return
612         }
613         v.locker.Unlock()
614 }
615
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)
622         return err
623 }
624
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)
628         return err
629 }
630
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 {
634         switch err.(type) {
635         case *os.PathError:
636                 // stat() returns a PathError if the parent directory
637                 // (not just the file itself) is missing
638                 return os.ErrNotExist
639         default:
640                 return err
641         }
642 }
643
644 var unixTrashLocRegexp = regexp.MustCompile(`/([0-9a-f]{32})\.trash\.(\d+)$`)
645
646 // EmptyTrash walks hierarchy looking for {hash}.trash.*
647 // and deletes those with deadline < now.
648 func (v *UnixVolume) EmptyTrash() {
649         if v.cluster.Collections.BlobDeleteConcurrency < 1 {
650                 return
651         }
652
653         var bytesDeleted, bytesInTrash int64
654         var blocksDeleted, blocksInTrash int64
655
656         doFile := func(path string, info os.FileInfo) {
657                 if info.Mode().IsDir() {
658                         return
659                 }
660                 matches := unixTrashLocRegexp.FindStringSubmatch(path)
661                 if len(matches) != 3 {
662                         return
663                 }
664                 deadline, err := strconv.ParseInt(matches[2], 10, 64)
665                 if err != nil {
666                         v.logger.WithError(err).Errorf("EmptyTrash: %v: ParseInt(%q) failed", path, matches[2])
667                         return
668                 }
669                 atomic.AddInt64(&bytesInTrash, info.Size())
670                 atomic.AddInt64(&blocksInTrash, 1)
671                 if deadline > time.Now().Unix() {
672                         return
673                 }
674                 err = v.os.Remove(path)
675                 if err != nil {
676                         v.logger.WithError(err).Errorf("EmptyTrash: Remove(%q) failed", path)
677                         return
678                 }
679                 atomic.AddInt64(&bytesDeleted, info.Size())
680                 atomic.AddInt64(&blocksDeleted, 1)
681         }
682
683         type dirent struct {
684                 path string
685                 info os.FileInfo
686         }
687         var wg sync.WaitGroup
688         todo := make(chan dirent, v.cluster.Collections.BlobDeleteConcurrency)
689         for i := 0; i < v.cluster.Collections.BlobDeleteConcurrency; i++ {
690                 wg.Add(1)
691                 go func() {
692                         defer wg.Done()
693                         for e := range todo {
694                                 doFile(e.path, e.info)
695                         }
696                 }()
697         }
698
699         err := filepath.Walk(v.Root, func(path string, info os.FileInfo, err error) error {
700                 if err != nil {
701                         v.logger.WithError(err).Errorf("EmptyTrash: filepath.Walk(%q) failed", path)
702                         // Don't give up -- keep walking other
703                         // files/dirs
704                         return nil
705                 } else if !info.Mode().IsDir() {
706                         todo <- dirent{path, info}
707                         return nil
708                 } else if path == v.Root || blockDirRe.MatchString(info.Name()) {
709                         // Descend into a directory that we might have
710                         // put trash in.
711                         return nil
712                 } else {
713                         // Don't descend into other dirs.
714                         return filepath.SkipDir
715                 }
716         })
717         close(todo)
718         wg.Wait()
719
720         if err != nil {
721                 v.logger.WithError(err).Error("EmptyTrash failed")
722         }
723
724         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)
725 }
726
727 type unixStats struct {
728         statsTicker
729         OpenOps    uint64
730         StatOps    uint64
731         FlockOps   uint64
732         UtimesOps  uint64
733         CreateOps  uint64
734         RenameOps  uint64
735         UnlinkOps  uint64
736         ReaddirOps uint64
737 }
738
739 func (s *unixStats) TickErr(err error) {
740         if err == nil {
741                 return
742         }
743         s.statsTicker.TickErr(err, fmt.Sprintf("%T", err))
744 }
745
746 type osWithStats struct {
747         stats unixStats
748 }
749
750 func (o *osWithStats) Open(name string) (*os.File, error) {
751         o.stats.TickOps("open")
752         o.stats.Tick(&o.stats.OpenOps)
753         f, err := os.Open(name)
754         o.stats.TickErr(err)
755         return f, err
756 }
757
758 func (o *osWithStats) OpenFile(name string, flag int, perm os.FileMode) (*os.File, error) {
759         o.stats.TickOps("open")
760         o.stats.Tick(&o.stats.OpenOps)
761         f, err := os.OpenFile(name, flag, perm)
762         o.stats.TickErr(err)
763         return f, err
764 }
765
766 func (o *osWithStats) Remove(path string) error {
767         o.stats.TickOps("unlink")
768         o.stats.Tick(&o.stats.UnlinkOps)
769         err := os.Remove(path)
770         o.stats.TickErr(err)
771         return err
772 }
773
774 func (o *osWithStats) Rename(a, b string) error {
775         o.stats.TickOps("rename")
776         o.stats.Tick(&o.stats.RenameOps)
777         err := os.Rename(a, b)
778         o.stats.TickErr(err)
779         return err
780 }
781
782 func (o *osWithStats) Stat(path string) (os.FileInfo, error) {
783         o.stats.TickOps("stat")
784         o.stats.Tick(&o.stats.StatOps)
785         fi, err := os.Stat(path)
786         o.stats.TickErr(err)
787         return fi, err
788 }
789
790 func (o *osWithStats) TempFile(dir, base string) (*os.File, error) {
791         o.stats.TickOps("create")
792         o.stats.Tick(&o.stats.CreateOps)
793         f, err := ioutil.TempFile(dir, base)
794         o.stats.TickErr(err)
795         return f, err
796 }