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