8784: Fix test for latest firefox.
[arvados.git] / services / keepstore / volume_unix.go
1 package main
2
3 import (
4         "bufio"
5         "context"
6         "flag"
7         "fmt"
8         "io"
9         "io/ioutil"
10         "os"
11         "os/exec"
12         "path/filepath"
13         "regexp"
14         "strconv"
15         "strings"
16         "sync"
17         "syscall"
18         "time"
19
20         log "github.com/Sirupsen/logrus"
21 )
22
23 type unixVolumeAdder struct {
24         *Config
25 }
26
27 // String implements flag.Value
28 func (s *unixVolumeAdder) String() string {
29         return "-"
30 }
31
32 func (vs *unixVolumeAdder) Set(path string) error {
33         if dirs := strings.Split(path, ","); len(dirs) > 1 {
34                 log.Print("DEPRECATED: using comma-separated volume list.")
35                 for _, dir := range dirs {
36                         if err := vs.Set(dir); err != nil {
37                                 return err
38                         }
39                 }
40                 return nil
41         }
42         vs.Config.Volumes = append(vs.Config.Volumes, &UnixVolume{
43                 Root:      path,
44                 ReadOnly:  deprecated.flagReadonly,
45                 Serialize: deprecated.flagSerializeIO,
46         })
47         return nil
48 }
49
50 func init() {
51         VolumeTypes = append(VolumeTypes, func() VolumeWithExamples { return &UnixVolume{} })
52
53         flag.Var(&unixVolumeAdder{theConfig}, "volumes", "see Volumes configuration")
54         flag.Var(&unixVolumeAdder{theConfig}, "volume", "see Volumes configuration")
55 }
56
57 // Discover adds a UnixVolume for every directory named "keep" that is
58 // located at the top level of a device- or tmpfs-backed mount point
59 // other than "/". It returns the number of volumes added.
60 func (vs *unixVolumeAdder) Discover() int {
61         added := 0
62         f, err := os.Open(ProcMounts)
63         if err != nil {
64                 log.Fatalf("opening %s: %s", ProcMounts, err)
65         }
66         scanner := bufio.NewScanner(f)
67         for scanner.Scan() {
68                 args := strings.Fields(scanner.Text())
69                 if err := scanner.Err(); err != nil {
70                         log.Fatalf("reading %s: %s", ProcMounts, err)
71                 }
72                 dev, mount := args[0], args[1]
73                 if mount == "/" {
74                         continue
75                 }
76                 if dev != "tmpfs" && !strings.HasPrefix(dev, "/dev/") {
77                         continue
78                 }
79                 keepdir := mount + "/keep"
80                 if st, err := os.Stat(keepdir); err != nil || !st.IsDir() {
81                         continue
82                 }
83                 // Set the -readonly flag (but only for this volume)
84                 // if the filesystem is mounted readonly.
85                 flagReadonlyWas := deprecated.flagReadonly
86                 for _, fsopt := range strings.Split(args[3], ",") {
87                         if fsopt == "ro" {
88                                 deprecated.flagReadonly = true
89                                 break
90                         }
91                         if fsopt == "rw" {
92                                 break
93                         }
94                 }
95                 if err := vs.Set(keepdir); err != nil {
96                         log.Printf("adding %q: %s", keepdir, err)
97                 } else {
98                         added++
99                 }
100                 deprecated.flagReadonly = flagReadonlyWas
101         }
102         return added
103 }
104
105 // A UnixVolume stores and retrieves blocks in a local directory.
106 type UnixVolume struct {
107         Root                 string // path to the volume's root directory
108         ReadOnly             bool
109         Serialize            bool
110         DirectoryReplication int
111
112         // something to lock during IO, typically a sync.Mutex (or nil
113         // to skip locking)
114         locker sync.Locker
115
116         os osWithStats
117 }
118
119 // DeviceID returns a globally unique ID for the volume's root
120 // directory, consisting of the filesystem's UUID and the path from
121 // filesystem root to storage directory, joined by "/". For example,
122 // the DeviceID for a local directory "/mnt/xvda1/keep" might be
123 // "fa0b6166-3b55-4994-bd3f-92f4e00a1bb0/keep".
124 func (v *UnixVolume) DeviceID() string {
125         giveup := func(f string, args ...interface{}) string {
126                 log.Printf(f+"; using blank DeviceID for volume %s", append(args, v)...)
127                 return ""
128         }
129         buf, err := exec.Command("findmnt", "--noheadings", "--target", v.Root).CombinedOutput()
130         if err != nil {
131                 return giveup("findmnt: %s (%q)", err, buf)
132         }
133         findmnt := strings.Fields(string(buf))
134         if len(findmnt) < 2 {
135                 return giveup("could not parse findmnt output: %q", buf)
136         }
137         fsRoot, dev := findmnt[0], findmnt[1]
138
139         absRoot, err := filepath.Abs(v.Root)
140         if err != nil {
141                 return giveup("resolving relative path %q: %s", v.Root, err)
142         }
143         realRoot, err := filepath.EvalSymlinks(absRoot)
144         if err != nil {
145                 return giveup("resolving symlinks in %q: %s", absRoot, err)
146         }
147
148         // Find path from filesystem root to realRoot
149         var fsPath string
150         if strings.HasPrefix(realRoot, fsRoot+"/") {
151                 fsPath = realRoot[len(fsRoot):]
152         } else if fsRoot == "/" {
153                 fsPath = realRoot
154         } else if fsRoot == realRoot {
155                 fsPath = ""
156         } else {
157                 return giveup("findmnt reports mount point %q which is not a prefix of volume root %q", fsRoot, realRoot)
158         }
159
160         if !strings.HasPrefix(dev, "/") {
161                 return giveup("mount %q device %q is not a path", fsRoot, dev)
162         }
163
164         fi, err := os.Stat(dev)
165         if err != nil {
166                 return giveup("stat %q: %s\n", dev, err)
167         }
168         ino := fi.Sys().(*syscall.Stat_t).Ino
169
170         // Find a symlink in /dev/disk/by-uuid/ whose target is (i.e.,
171         // has the same inode as) the mounted device
172         udir := "/dev/disk/by-uuid"
173         d, err := os.Open(udir)
174         if err != nil {
175                 return giveup("opening %q: %s", udir, err)
176         }
177         uuids, err := d.Readdirnames(0)
178         if err != nil {
179                 return giveup("reading %q: %s", udir, err)
180         }
181         for _, uuid := range uuids {
182                 link := filepath.Join(udir, uuid)
183                 fi, err = os.Stat(link)
184                 if err != nil {
185                         log.Printf("error: stat %q: %s", link, err)
186                         continue
187                 }
188                 if fi.Sys().(*syscall.Stat_t).Ino == ino {
189                         return uuid + fsPath
190                 }
191         }
192         return giveup("could not find entry in %q matching %q", udir, dev)
193 }
194
195 // Examples implements VolumeWithExamples.
196 func (*UnixVolume) Examples() []Volume {
197         return []Volume{
198                 &UnixVolume{
199                         Root:                 "/mnt/local-disk",
200                         Serialize:            true,
201                         DirectoryReplication: 1,
202                 },
203                 &UnixVolume{
204                         Root:                 "/mnt/network-disk",
205                         Serialize:            false,
206                         DirectoryReplication: 2,
207                 },
208         }
209 }
210
211 // Type implements Volume
212 func (v *UnixVolume) Type() string {
213         return "Directory"
214 }
215
216 // Start implements Volume
217 func (v *UnixVolume) Start() error {
218         if v.Serialize {
219                 v.locker = &sync.Mutex{}
220         }
221         if !strings.HasPrefix(v.Root, "/") {
222                 return fmt.Errorf("volume root does not start with '/': %q", v.Root)
223         }
224         if v.DirectoryReplication == 0 {
225                 v.DirectoryReplication = 1
226         }
227         _, err := v.os.Stat(v.Root)
228         return err
229 }
230
231 // Touch sets the timestamp for the given locator to the current time
232 func (v *UnixVolume) Touch(loc string) error {
233         if v.ReadOnly {
234                 return MethodDisabledError
235         }
236         p := v.blockPath(loc)
237         f, err := v.os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
238         if err != nil {
239                 return err
240         }
241         defer f.Close()
242         if err := v.lock(context.TODO()); err != nil {
243                 return err
244         }
245         defer v.unlock()
246         if e := v.lockfile(f); e != nil {
247                 return e
248         }
249         defer v.unlockfile(f)
250         ts := syscall.NsecToTimespec(time.Now().UnixNano())
251         v.os.stats.Tick(&v.os.stats.UtimesOps)
252         err = syscall.UtimesNano(p, []syscall.Timespec{ts, ts})
253         v.os.stats.TickErr(err)
254         return err
255 }
256
257 // Mtime returns the stored timestamp for the given locator.
258 func (v *UnixVolume) Mtime(loc string) (time.Time, error) {
259         p := v.blockPath(loc)
260         fi, err := v.os.Stat(p)
261         if err != nil {
262                 return time.Time{}, err
263         }
264         return fi.ModTime(), nil
265 }
266
267 // Lock the locker (if one is in use), open the file for reading, and
268 // call the given function if and when the file is ready to read.
269 func (v *UnixVolume) getFunc(ctx context.Context, path string, fn func(io.Reader) error) error {
270         if err := v.lock(ctx); err != nil {
271                 return err
272         }
273         defer v.unlock()
274         f, err := v.os.Open(path)
275         if err != nil {
276                 return err
277         }
278         defer f.Close()
279         return fn(NewCountingReader(ioutil.NopCloser(f), v.os.stats.TickInBytes))
280 }
281
282 // stat is os.Stat() with some extra sanity checks.
283 func (v *UnixVolume) stat(path string) (os.FileInfo, error) {
284         stat, err := v.os.Stat(path)
285         if err == nil {
286                 if stat.Size() < 0 {
287                         err = os.ErrInvalid
288                 } else if stat.Size() > BlockSize {
289                         err = TooLongError
290                 }
291         }
292         return stat, err
293 }
294
295 // Get retrieves a block, copies it to the given slice, and returns
296 // the number of bytes copied.
297 func (v *UnixVolume) Get(ctx context.Context, loc string, buf []byte) (int, error) {
298         return getWithPipe(ctx, loc, buf, v)
299 }
300
301 // ReadBlock implements BlockReader.
302 func (v *UnixVolume) ReadBlock(ctx context.Context, loc string, w io.Writer) error {
303         path := v.blockPath(loc)
304         stat, err := v.stat(path)
305         if err != nil {
306                 return v.translateError(err)
307         }
308         return v.getFunc(ctx, path, func(rdr io.Reader) error {
309                 n, err := io.Copy(w, rdr)
310                 if err == nil && n != stat.Size() {
311                         err = io.ErrUnexpectedEOF
312                 }
313                 return err
314         })
315 }
316
317 // Compare returns nil if Get(loc) would return the same content as
318 // expect. It is functionally equivalent to Get() followed by
319 // bytes.Compare(), but uses less memory.
320 func (v *UnixVolume) Compare(ctx context.Context, loc string, expect []byte) error {
321         path := v.blockPath(loc)
322         if _, err := v.stat(path); err != nil {
323                 return v.translateError(err)
324         }
325         return v.getFunc(ctx, path, func(rdr io.Reader) error {
326                 return compareReaderWithBuf(ctx, rdr, expect, loc[:32])
327         })
328 }
329
330 // Put stores a block of data identified by the locator string
331 // "loc".  It returns nil on success.  If the volume is full, it
332 // returns a FullError.  If the write fails due to some other error,
333 // that error is returned.
334 func (v *UnixVolume) Put(ctx context.Context, loc string, block []byte) error {
335         return putWithPipe(ctx, loc, block, v)
336 }
337
338 // ReadBlock implements BlockWriter.
339 func (v *UnixVolume) WriteBlock(ctx context.Context, loc string, rdr io.Reader) error {
340         if v.ReadOnly {
341                 return MethodDisabledError
342         }
343         if v.IsFull() {
344                 return FullError
345         }
346         bdir := v.blockDir(loc)
347         if err := os.MkdirAll(bdir, 0755); err != nil {
348                 log.Printf("%s: could not create directory %s: %s",
349                         loc, bdir, err)
350                 return err
351         }
352
353         tmpfile, tmperr := v.os.TempFile(bdir, "tmp"+loc)
354         if tmperr != nil {
355                 log.Printf("ioutil.TempFile(%s, tmp%s): %s", bdir, loc, tmperr)
356                 return tmperr
357         }
358
359         bpath := v.blockPath(loc)
360
361         if err := v.lock(ctx); err != nil {
362                 return err
363         }
364         defer v.unlock()
365         n, err := io.Copy(tmpfile, rdr)
366         v.os.stats.TickOutBytes(uint64(n))
367         if err != nil {
368                 log.Printf("%s: writing to %s: %s\n", v, bpath, err)
369                 tmpfile.Close()
370                 v.os.Remove(tmpfile.Name())
371                 return err
372         }
373         if err := tmpfile.Close(); err != nil {
374                 log.Printf("closing %s: %s\n", tmpfile.Name(), err)
375                 v.os.Remove(tmpfile.Name())
376                 return err
377         }
378         if err := v.os.Rename(tmpfile.Name(), bpath); err != nil {
379                 log.Printf("rename %s %s: %s\n", tmpfile.Name(), bpath, err)
380                 return v.os.Remove(tmpfile.Name())
381         }
382         return nil
383 }
384
385 // Status returns a VolumeStatus struct describing the volume's
386 // current state, or nil if an error occurs.
387 //
388 func (v *UnixVolume) Status() *VolumeStatus {
389         fi, err := v.os.Stat(v.Root)
390         if err != nil {
391                 log.Printf("%s: os.Stat: %s\n", v, err)
392                 return nil
393         }
394         devnum := fi.Sys().(*syscall.Stat_t).Dev
395
396         var fs syscall.Statfs_t
397         if err := syscall.Statfs(v.Root, &fs); err != nil {
398                 log.Printf("%s: statfs: %s\n", v, err)
399                 return nil
400         }
401         // These calculations match the way df calculates disk usage:
402         // "free" space is measured by fs.Bavail, but "used" space
403         // uses fs.Blocks - fs.Bfree.
404         free := fs.Bavail * uint64(fs.Bsize)
405         used := (fs.Blocks - fs.Bfree) * uint64(fs.Bsize)
406         return &VolumeStatus{
407                 MountPoint: v.Root,
408                 DeviceNum:  devnum,
409                 BytesFree:  free,
410                 BytesUsed:  used,
411         }
412 }
413
414 var blockDirRe = regexp.MustCompile(`^[0-9a-f]+$`)
415 var blockFileRe = regexp.MustCompile(`^[0-9a-f]{32}$`)
416
417 // IndexTo writes (to the given Writer) a list of blocks found on this
418 // volume which begin with the specified prefix. If the prefix is an
419 // empty string, IndexTo writes a complete list of blocks.
420 //
421 // Each block is given in the format
422 //
423 //     locator+size modification-time {newline}
424 //
425 // e.g.:
426 //
427 //     e4df392f86be161ca6ed3773a962b8f3+67108864 1388894303
428 //     e4d41e6fd68460e0e3fc18cc746959d2+67108864 1377796043
429 //     e4de7a2810f5554cd39b36d8ddb132ff+67108864 1388701136
430 //
431 func (v *UnixVolume) IndexTo(prefix string, w io.Writer) error {
432         var lastErr error
433         rootdir, err := v.os.Open(v.Root)
434         if err != nil {
435                 return err
436         }
437         defer rootdir.Close()
438         v.os.stats.Tick(&v.os.stats.ReaddirOps)
439         for {
440                 names, err := rootdir.Readdirnames(1)
441                 if err == io.EOF {
442                         return lastErr
443                 } else if err != nil {
444                         return err
445                 }
446                 if !strings.HasPrefix(names[0], prefix) && !strings.HasPrefix(prefix, names[0]) {
447                         // prefix excludes all blocks stored in this dir
448                         continue
449                 }
450                 if !blockDirRe.MatchString(names[0]) {
451                         continue
452                 }
453                 blockdirpath := filepath.Join(v.Root, names[0])
454                 blockdir, err := v.os.Open(blockdirpath)
455                 if err != nil {
456                         log.Print("Error reading ", blockdirpath, ": ", err)
457                         lastErr = err
458                         continue
459                 }
460                 v.os.stats.Tick(&v.os.stats.ReaddirOps)
461                 for {
462                         fileInfo, err := blockdir.Readdir(1)
463                         if err == io.EOF {
464                                 break
465                         } else if err != nil {
466                                 log.Print("Error reading ", blockdirpath, ": ", err)
467                                 lastErr = err
468                                 break
469                         }
470                         name := fileInfo[0].Name()
471                         if !strings.HasPrefix(name, prefix) {
472                                 continue
473                         }
474                         if !blockFileRe.MatchString(name) {
475                                 continue
476                         }
477                         _, err = fmt.Fprint(w,
478                                 name,
479                                 "+", fileInfo[0].Size(),
480                                 " ", fileInfo[0].ModTime().UnixNano(),
481                                 "\n")
482                 }
483                 blockdir.Close()
484         }
485 }
486
487 // Trash trashes the block data from the unix storage
488 // If TrashLifetime == 0, the block is deleted
489 // Else, the block is renamed as path/{loc}.trash.{deadline},
490 // where deadline = now + TrashLifetime
491 func (v *UnixVolume) Trash(loc string) error {
492         // Touch() must be called before calling Write() on a block.  Touch()
493         // also uses lockfile().  This avoids a race condition between Write()
494         // and Trash() because either (a) the file will be trashed and Touch()
495         // will signal to the caller that the file is not present (and needs to
496         // be re-written), or (b) Touch() will update the file's timestamp and
497         // Trash() will read the correct up-to-date timestamp and choose not to
498         // trash the file.
499
500         if v.ReadOnly {
501                 return MethodDisabledError
502         }
503         if err := v.lock(context.TODO()); err != nil {
504                 return err
505         }
506         defer v.unlock()
507         p := v.blockPath(loc)
508         f, err := v.os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
509         if err != nil {
510                 return err
511         }
512         defer f.Close()
513         if e := v.lockfile(f); e != nil {
514                 return e
515         }
516         defer v.unlockfile(f)
517
518         // If the block has been PUT in the last blobSignatureTTL
519         // seconds, return success without removing the block. This
520         // protects data from garbage collection until it is no longer
521         // possible for clients to retrieve the unreferenced blocks
522         // anyway (because the permission signatures have expired).
523         if fi, err := v.os.Stat(p); err != nil {
524                 return err
525         } else if time.Since(fi.ModTime()) < time.Duration(theConfig.BlobSignatureTTL) {
526                 return nil
527         }
528
529         if theConfig.TrashLifetime == 0 {
530                 return v.os.Remove(p)
531         }
532         return v.os.Rename(p, fmt.Sprintf("%v.trash.%d", p, time.Now().Add(theConfig.TrashLifetime.Duration()).Unix()))
533 }
534
535 // Untrash moves block from trash back into store
536 // Look for path/{loc}.trash.{deadline} in storage,
537 // and rename the first such file as path/{loc}
538 func (v *UnixVolume) Untrash(loc string) (err error) {
539         if v.ReadOnly {
540                 return MethodDisabledError
541         }
542
543         v.os.stats.Tick(&v.os.stats.ReaddirOps)
544         files, err := ioutil.ReadDir(v.blockDir(loc))
545         if err != nil {
546                 return err
547         }
548
549         if len(files) == 0 {
550                 return os.ErrNotExist
551         }
552
553         foundTrash := false
554         prefix := fmt.Sprintf("%v.trash.", loc)
555         for _, f := range files {
556                 if strings.HasPrefix(f.Name(), prefix) {
557                         foundTrash = true
558                         err = v.os.Rename(v.blockPath(f.Name()), v.blockPath(loc))
559                         if err == nil {
560                                 break
561                         }
562                 }
563         }
564
565         if foundTrash == false {
566                 return os.ErrNotExist
567         }
568
569         return
570 }
571
572 // blockDir returns the fully qualified directory name for the directory
573 // where loc is (or would be) stored on this volume.
574 func (v *UnixVolume) blockDir(loc string) string {
575         return filepath.Join(v.Root, loc[0:3])
576 }
577
578 // blockPath returns the fully qualified pathname for the path to loc
579 // on this volume.
580 func (v *UnixVolume) blockPath(loc string) string {
581         return filepath.Join(v.blockDir(loc), loc)
582 }
583
584 // IsFull returns true if the free space on the volume is less than
585 // MinFreeKilobytes.
586 //
587 func (v *UnixVolume) IsFull() (isFull bool) {
588         fullSymlink := v.Root + "/full"
589
590         // Check if the volume has been marked as full in the last hour.
591         if link, err := os.Readlink(fullSymlink); err == nil {
592                 if ts, err := strconv.Atoi(link); err == nil {
593                         fulltime := time.Unix(int64(ts), 0)
594                         if time.Since(fulltime).Hours() < 1.0 {
595                                 return true
596                         }
597                 }
598         }
599
600         if avail, err := v.FreeDiskSpace(); err == nil {
601                 isFull = avail < MinFreeKilobytes
602         } else {
603                 log.Printf("%s: FreeDiskSpace: %s\n", v, err)
604                 isFull = false
605         }
606
607         // If the volume is full, timestamp it.
608         if isFull {
609                 now := fmt.Sprintf("%d", time.Now().Unix())
610                 os.Symlink(now, fullSymlink)
611         }
612         return
613 }
614
615 // FreeDiskSpace returns the number of unused 1k blocks available on
616 // the volume.
617 //
618 func (v *UnixVolume) FreeDiskSpace() (free uint64, err error) {
619         var fs syscall.Statfs_t
620         err = syscall.Statfs(v.Root, &fs)
621         if err == nil {
622                 // Statfs output is not guaranteed to measure free
623                 // space in terms of 1K blocks.
624                 free = fs.Bavail * uint64(fs.Bsize) / 1024
625         }
626         return
627 }
628
629 func (v *UnixVolume) String() string {
630         return fmt.Sprintf("[UnixVolume %s]", v.Root)
631 }
632
633 // Writable returns false if all future Put, Mtime, and Delete calls
634 // are expected to fail.
635 func (v *UnixVolume) Writable() bool {
636         return !v.ReadOnly
637 }
638
639 // Replication returns the number of replicas promised by the
640 // underlying device (as specified in configuration).
641 func (v *UnixVolume) Replication() int {
642         return v.DirectoryReplication
643 }
644
645 // InternalStats returns I/O and filesystem ops counters.
646 func (v *UnixVolume) InternalStats() interface{} {
647         return &v.os.stats
648 }
649
650 // lock acquires the serialize lock, if one is in use. If ctx is done
651 // before the lock is acquired, lock returns ctx.Err() instead of
652 // acquiring the lock.
653 func (v *UnixVolume) lock(ctx context.Context) error {
654         if v.locker == nil {
655                 return nil
656         }
657         locked := make(chan struct{})
658         go func() {
659                 v.locker.Lock()
660                 close(locked)
661         }()
662         select {
663         case <-ctx.Done():
664                 go func() {
665                         <-locked
666                         v.locker.Unlock()
667                 }()
668                 return ctx.Err()
669         case <-locked:
670                 return nil
671         }
672 }
673
674 // unlock releases the serialize lock, if one is in use.
675 func (v *UnixVolume) unlock() {
676         if v.locker == nil {
677                 return
678         }
679         v.locker.Unlock()
680 }
681
682 // lockfile and unlockfile use flock(2) to manage kernel file locks.
683 func (v *UnixVolume) lockfile(f *os.File) error {
684         v.os.stats.Tick(&v.os.stats.FlockOps)
685         err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
686         v.os.stats.TickErr(err)
687         return err
688 }
689
690 func (v *UnixVolume) unlockfile(f *os.File) error {
691         err := syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
692         v.os.stats.TickErr(err)
693         return err
694 }
695
696 // Where appropriate, translate a more specific filesystem error to an
697 // error recognized by handlers, like os.ErrNotExist.
698 func (v *UnixVolume) translateError(err error) error {
699         switch err.(type) {
700         case *os.PathError:
701                 // stat() returns a PathError if the parent directory
702                 // (not just the file itself) is missing
703                 return os.ErrNotExist
704         default:
705                 return err
706         }
707 }
708
709 var unixTrashLocRegexp = regexp.MustCompile(`/([0-9a-f]{32})\.trash\.(\d+)$`)
710
711 // EmptyTrash walks hierarchy looking for {hash}.trash.*
712 // and deletes those with deadline < now.
713 func (v *UnixVolume) EmptyTrash() {
714         var bytesDeleted, bytesInTrash int64
715         var blocksDeleted, blocksInTrash int
716
717         err := filepath.Walk(v.Root, func(path string, info os.FileInfo, err error) error {
718                 if err != nil {
719                         log.Printf("EmptyTrash: filepath.Walk: %v: %v", path, err)
720                         return nil
721                 }
722                 if info.Mode().IsDir() {
723                         return nil
724                 }
725                 matches := unixTrashLocRegexp.FindStringSubmatch(path)
726                 if len(matches) != 3 {
727                         return nil
728                 }
729                 deadline, err := strconv.ParseInt(matches[2], 10, 64)
730                 if err != nil {
731                         log.Printf("EmptyTrash: %v: ParseInt(%v): %v", path, matches[2], err)
732                         return nil
733                 }
734                 bytesInTrash += info.Size()
735                 blocksInTrash++
736                 if deadline > time.Now().Unix() {
737                         return nil
738                 }
739                 err = v.os.Remove(path)
740                 if err != nil {
741                         log.Printf("EmptyTrash: Remove %v: %v", path, err)
742                         return nil
743                 }
744                 bytesDeleted += info.Size()
745                 blocksDeleted++
746                 return nil
747         })
748
749         if err != nil {
750                 log.Printf("EmptyTrash error for %v: %v", v.String(), err)
751         }
752
753         log.Printf("EmptyTrash stats for %v: Deleted %v bytes in %v blocks. Remaining in trash: %v bytes in %v blocks.", v.String(), bytesDeleted, blocksDeleted, bytesInTrash-bytesDeleted, blocksInTrash-blocksDeleted)
754 }
755
756 type unixStats struct {
757         statsTicker
758         OpenOps    uint64
759         StatOps    uint64
760         FlockOps   uint64
761         UtimesOps  uint64
762         CreateOps  uint64
763         RenameOps  uint64
764         UnlinkOps  uint64
765         ReaddirOps uint64
766 }
767
768 func (s *unixStats) TickErr(err error) {
769         if err == nil {
770                 return
771         }
772         s.statsTicker.TickErr(err, fmt.Sprintf("%T", err))
773 }
774
775 type osWithStats struct {
776         stats unixStats
777 }
778
779 func (o *osWithStats) Open(name string) (*os.File, error) {
780         o.stats.Tick(&o.stats.OpenOps)
781         f, err := os.Open(name)
782         o.stats.TickErr(err)
783         return f, err
784 }
785
786 func (o *osWithStats) OpenFile(name string, flag int, perm os.FileMode) (*os.File, error) {
787         o.stats.Tick(&o.stats.OpenOps)
788         f, err := os.OpenFile(name, flag, perm)
789         o.stats.TickErr(err)
790         return f, err
791 }
792
793 func (o *osWithStats) Remove(path string) error {
794         o.stats.Tick(&o.stats.UnlinkOps)
795         err := os.Remove(path)
796         o.stats.TickErr(err)
797         return err
798 }
799
800 func (o *osWithStats) Rename(a, b string) error {
801         o.stats.Tick(&o.stats.RenameOps)
802         err := os.Rename(a, b)
803         o.stats.TickErr(err)
804         return err
805 }
806
807 func (o *osWithStats) Stat(path string) (os.FileInfo, error) {
808         o.stats.Tick(&o.stats.StatOps)
809         fi, err := os.Stat(path)
810         o.stats.TickErr(err)
811         return fi, err
812 }
813
814 func (o *osWithStats) TempFile(dir, base string) (*os.File, error) {
815         o.stats.Tick(&o.stats.CreateOps)
816         f, err := ioutil.TempFile(dir, base)
817         o.stats.TickErr(err)
818         return f, err
819 }