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