Merge branch 'wtsi/python-api-timeout' refs #13542
[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         "sync/atomic"
22         "syscall"
23         "time"
24 )
25
26 type unixVolumeAdder struct {
27         *Config
28 }
29
30 // String implements flag.Value
31 func (s *unixVolumeAdder) String() string {
32         return "-"
33 }
34
35 func (vs *unixVolumeAdder) Set(path string) error {
36         if dirs := strings.Split(path, ","); len(dirs) > 1 {
37                 log.Print("DEPRECATED: using comma-separated volume list.")
38                 for _, dir := range dirs {
39                         if err := vs.Set(dir); err != nil {
40                                 return err
41                         }
42                 }
43                 return nil
44         }
45         vs.Config.Volumes = append(vs.Config.Volumes, &UnixVolume{
46                 Root:      path,
47                 ReadOnly:  deprecated.flagReadonly,
48                 Serialize: deprecated.flagSerializeIO,
49         })
50         return nil
51 }
52
53 func init() {
54         VolumeTypes = append(VolumeTypes, func() VolumeWithExamples { return &UnixVolume{} })
55
56         flag.Var(&unixVolumeAdder{theConfig}, "volumes", "see Volumes configuration")
57         flag.Var(&unixVolumeAdder{theConfig}, "volume", "see Volumes configuration")
58 }
59
60 // Discover adds a UnixVolume for every directory named "keep" that is
61 // located at the top level of a device- or tmpfs-backed mount point
62 // other than "/". It returns the number of volumes added.
63 func (vs *unixVolumeAdder) Discover() int {
64         added := 0
65         f, err := os.Open(ProcMounts)
66         if err != nil {
67                 log.Fatalf("opening %s: %s", ProcMounts, err)
68         }
69         scanner := bufio.NewScanner(f)
70         for scanner.Scan() {
71                 args := strings.Fields(scanner.Text())
72                 if err := scanner.Err(); err != nil {
73                         log.Fatalf("reading %s: %s", ProcMounts, err)
74                 }
75                 dev, mount := args[0], args[1]
76                 if mount == "/" {
77                         continue
78                 }
79                 if dev != "tmpfs" && !strings.HasPrefix(dev, "/dev/") {
80                         continue
81                 }
82                 keepdir := mount + "/keep"
83                 if st, err := os.Stat(keepdir); err != nil || !st.IsDir() {
84                         continue
85                 }
86                 // Set the -readonly flag (but only for this volume)
87                 // if the filesystem is mounted readonly.
88                 flagReadonlyWas := deprecated.flagReadonly
89                 for _, fsopt := range strings.Split(args[3], ",") {
90                         if fsopt == "ro" {
91                                 deprecated.flagReadonly = true
92                                 break
93                         }
94                         if fsopt == "rw" {
95                                 break
96                         }
97                 }
98                 if err := vs.Set(keepdir); err != nil {
99                         log.Printf("adding %q: %s", keepdir, err)
100                 } else {
101                         added++
102                 }
103                 deprecated.flagReadonly = flagReadonlyWas
104         }
105         return added
106 }
107
108 // A UnixVolume stores and retrieves blocks in a local directory.
109 type UnixVolume struct {
110         Root                 string // path to the volume's root directory
111         ReadOnly             bool
112         Serialize            bool
113         DirectoryReplication int
114         StorageClasses       []string
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                         if err != nil {
487                                 log.Print("Error writing : ", err)
488                                 lastErr = err
489                                 break
490                         }
491                 }
492                 blockdir.Close()
493         }
494 }
495
496 // Trash trashes the block data from the unix storage
497 // If TrashLifetime == 0, the block is deleted
498 // Else, the block is renamed as path/{loc}.trash.{deadline},
499 // where deadline = now + TrashLifetime
500 func (v *UnixVolume) Trash(loc string) error {
501         // Touch() must be called before calling Write() on a block.  Touch()
502         // also uses lockfile().  This avoids a race condition between Write()
503         // and Trash() because either (a) the file will be trashed and Touch()
504         // will signal to the caller that the file is not present (and needs to
505         // be re-written), or (b) Touch() will update the file's timestamp and
506         // Trash() will read the correct up-to-date timestamp and choose not to
507         // trash the file.
508
509         if v.ReadOnly {
510                 return MethodDisabledError
511         }
512         if err := v.lock(context.TODO()); err != nil {
513                 return err
514         }
515         defer v.unlock()
516         p := v.blockPath(loc)
517         f, err := v.os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
518         if err != nil {
519                 return err
520         }
521         defer f.Close()
522         if e := v.lockfile(f); e != nil {
523                 return e
524         }
525         defer v.unlockfile(f)
526
527         // If the block has been PUT in the last blobSignatureTTL
528         // seconds, return success without removing the block. This
529         // protects data from garbage collection until it is no longer
530         // possible for clients to retrieve the unreferenced blocks
531         // anyway (because the permission signatures have expired).
532         if fi, err := v.os.Stat(p); err != nil {
533                 return err
534         } else if time.Since(fi.ModTime()) < time.Duration(theConfig.BlobSignatureTTL) {
535                 return nil
536         }
537
538         if theConfig.TrashLifetime == 0 {
539                 return v.os.Remove(p)
540         }
541         return v.os.Rename(p, fmt.Sprintf("%v.trash.%d", p, time.Now().Add(theConfig.TrashLifetime.Duration()).Unix()))
542 }
543
544 // Untrash moves block from trash back into store
545 // Look for path/{loc}.trash.{deadline} in storage,
546 // and rename the first such file as path/{loc}
547 func (v *UnixVolume) Untrash(loc string) (err error) {
548         if v.ReadOnly {
549                 return MethodDisabledError
550         }
551
552         v.os.stats.Tick(&v.os.stats.ReaddirOps)
553         files, err := ioutil.ReadDir(v.blockDir(loc))
554         if err != nil {
555                 return err
556         }
557
558         if len(files) == 0 {
559                 return os.ErrNotExist
560         }
561
562         foundTrash := false
563         prefix := fmt.Sprintf("%v.trash.", loc)
564         for _, f := range files {
565                 if strings.HasPrefix(f.Name(), prefix) {
566                         foundTrash = true
567                         err = v.os.Rename(v.blockPath(f.Name()), v.blockPath(loc))
568                         if err == nil {
569                                 break
570                         }
571                 }
572         }
573
574         if foundTrash == false {
575                 return os.ErrNotExist
576         }
577
578         return
579 }
580
581 // blockDir returns the fully qualified directory name for the directory
582 // where loc is (or would be) stored on this volume.
583 func (v *UnixVolume) blockDir(loc string) string {
584         return filepath.Join(v.Root, loc[0:3])
585 }
586
587 // blockPath returns the fully qualified pathname for the path to loc
588 // on this volume.
589 func (v *UnixVolume) blockPath(loc string) string {
590         return filepath.Join(v.blockDir(loc), loc)
591 }
592
593 // IsFull returns true if the free space on the volume is less than
594 // MinFreeKilobytes.
595 //
596 func (v *UnixVolume) IsFull() (isFull bool) {
597         fullSymlink := v.Root + "/full"
598
599         // Check if the volume has been marked as full in the last hour.
600         if link, err := os.Readlink(fullSymlink); err == nil {
601                 if ts, err := strconv.Atoi(link); err == nil {
602                         fulltime := time.Unix(int64(ts), 0)
603                         if time.Since(fulltime).Hours() < 1.0 {
604                                 return true
605                         }
606                 }
607         }
608
609         if avail, err := v.FreeDiskSpace(); err == nil {
610                 isFull = avail < MinFreeKilobytes
611         } else {
612                 log.Printf("%s: FreeDiskSpace: %s\n", v, err)
613                 isFull = false
614         }
615
616         // If the volume is full, timestamp it.
617         if isFull {
618                 now := fmt.Sprintf("%d", time.Now().Unix())
619                 os.Symlink(now, fullSymlink)
620         }
621         return
622 }
623
624 // FreeDiskSpace returns the number of unused 1k blocks available on
625 // the volume.
626 //
627 func (v *UnixVolume) FreeDiskSpace() (free uint64, err error) {
628         var fs syscall.Statfs_t
629         err = syscall.Statfs(v.Root, &fs)
630         if err == nil {
631                 // Statfs output is not guaranteed to measure free
632                 // space in terms of 1K blocks.
633                 free = fs.Bavail * uint64(fs.Bsize) / 1024
634         }
635         return
636 }
637
638 func (v *UnixVolume) String() string {
639         return fmt.Sprintf("[UnixVolume %s]", v.Root)
640 }
641
642 // Writable returns false if all future Put, Mtime, and Delete calls
643 // are expected to fail.
644 func (v *UnixVolume) Writable() bool {
645         return !v.ReadOnly
646 }
647
648 // Replication returns the number of replicas promised by the
649 // underlying device (as specified in configuration).
650 func (v *UnixVolume) Replication() int {
651         return v.DirectoryReplication
652 }
653
654 // GetStorageClasses implements Volume
655 func (v *UnixVolume) GetStorageClasses() []string {
656         return v.StorageClasses
657 }
658
659 // InternalStats returns I/O and filesystem ops counters.
660 func (v *UnixVolume) InternalStats() interface{} {
661         return &v.os.stats
662 }
663
664 // lock acquires the serialize lock, if one is in use. If ctx is done
665 // before the lock is acquired, lock returns ctx.Err() instead of
666 // acquiring the lock.
667 func (v *UnixVolume) lock(ctx context.Context) error {
668         if v.locker == nil {
669                 return nil
670         }
671         locked := make(chan struct{})
672         go func() {
673                 v.locker.Lock()
674                 close(locked)
675         }()
676         select {
677         case <-ctx.Done():
678                 go func() {
679                         <-locked
680                         v.locker.Unlock()
681                 }()
682                 return ctx.Err()
683         case <-locked:
684                 return nil
685         }
686 }
687
688 // unlock releases the serialize lock, if one is in use.
689 func (v *UnixVolume) unlock() {
690         if v.locker == nil {
691                 return
692         }
693         v.locker.Unlock()
694 }
695
696 // lockfile and unlockfile use flock(2) to manage kernel file locks.
697 func (v *UnixVolume) lockfile(f *os.File) error {
698         v.os.stats.Tick(&v.os.stats.FlockOps)
699         err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
700         v.os.stats.TickErr(err)
701         return err
702 }
703
704 func (v *UnixVolume) unlockfile(f *os.File) error {
705         err := syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
706         v.os.stats.TickErr(err)
707         return err
708 }
709
710 // Where appropriate, translate a more specific filesystem error to an
711 // error recognized by handlers, like os.ErrNotExist.
712 func (v *UnixVolume) translateError(err error) error {
713         switch err.(type) {
714         case *os.PathError:
715                 // stat() returns a PathError if the parent directory
716                 // (not just the file itself) is missing
717                 return os.ErrNotExist
718         default:
719                 return err
720         }
721 }
722
723 var unixTrashLocRegexp = regexp.MustCompile(`/([0-9a-f]{32})\.trash\.(\d+)$`)
724
725 // EmptyTrash walks hierarchy looking for {hash}.trash.*
726 // and deletes those with deadline < now.
727 func (v *UnixVolume) EmptyTrash() {
728         var bytesDeleted, bytesInTrash int64
729         var blocksDeleted, blocksInTrash int64
730
731         doFile := func(path string, info os.FileInfo) {
732                 if info.Mode().IsDir() {
733                         return
734                 }
735                 matches := unixTrashLocRegexp.FindStringSubmatch(path)
736                 if len(matches) != 3 {
737                         return
738                 }
739                 deadline, err := strconv.ParseInt(matches[2], 10, 64)
740                 if err != nil {
741                         log.Printf("EmptyTrash: %v: ParseInt(%v): %v", path, matches[2], err)
742                         return
743                 }
744                 atomic.AddInt64(&bytesInTrash, info.Size())
745                 atomic.AddInt64(&blocksInTrash, 1)
746                 if deadline > time.Now().Unix() {
747                         return
748                 }
749                 err = v.os.Remove(path)
750                 if err != nil {
751                         log.Printf("EmptyTrash: Remove %v: %v", path, err)
752                         return
753                 }
754                 atomic.AddInt64(&bytesDeleted, info.Size())
755                 atomic.AddInt64(&blocksDeleted, 1)
756         }
757
758         type dirent struct {
759                 path string
760                 info os.FileInfo
761         }
762         var wg sync.WaitGroup
763         todo := make(chan dirent, theConfig.EmptyTrashWorkers)
764         for i := 0; i < 1 || i < theConfig.EmptyTrashWorkers; i++ {
765                 wg.Add(1)
766                 go func() {
767                         defer wg.Done()
768                         for e := range todo {
769                                 doFile(e.path, e.info)
770                         }
771                 }()
772         }
773
774         err := filepath.Walk(v.Root, func(path string, info os.FileInfo, err error) error {
775                 if err != nil {
776                         log.Printf("EmptyTrash: filepath.Walk: %v: %v", path, err)
777                         return nil
778                 }
779                 todo <- dirent{path, info}
780                 return nil
781         })
782         close(todo)
783         wg.Wait()
784
785         if err != nil {
786                 log.Printf("EmptyTrash error for %v: %v", v.String(), err)
787         }
788
789         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)
790 }
791
792 type unixStats struct {
793         statsTicker
794         OpenOps    uint64
795         StatOps    uint64
796         FlockOps   uint64
797         UtimesOps  uint64
798         CreateOps  uint64
799         RenameOps  uint64
800         UnlinkOps  uint64
801         ReaddirOps uint64
802 }
803
804 func (s *unixStats) TickErr(err error) {
805         if err == nil {
806                 return
807         }
808         s.statsTicker.TickErr(err, fmt.Sprintf("%T", err))
809 }
810
811 type osWithStats struct {
812         stats unixStats
813 }
814
815 func (o *osWithStats) Open(name string) (*os.File, error) {
816         o.stats.Tick(&o.stats.OpenOps)
817         f, err := os.Open(name)
818         o.stats.TickErr(err)
819         return f, err
820 }
821
822 func (o *osWithStats) OpenFile(name string, flag int, perm os.FileMode) (*os.File, error) {
823         o.stats.Tick(&o.stats.OpenOps)
824         f, err := os.OpenFile(name, flag, perm)
825         o.stats.TickErr(err)
826         return f, err
827 }
828
829 func (o *osWithStats) Remove(path string) error {
830         o.stats.Tick(&o.stats.UnlinkOps)
831         err := os.Remove(path)
832         o.stats.TickErr(err)
833         return err
834 }
835
836 func (o *osWithStats) Rename(a, b string) error {
837         o.stats.Tick(&o.stats.RenameOps)
838         err := os.Rename(a, b)
839         o.stats.TickErr(err)
840         return err
841 }
842
843 func (o *osWithStats) Stat(path string) (os.FileInfo, error) {
844         o.stats.Tick(&o.stats.StatOps)
845         fi, err := os.Stat(path)
846         o.stats.TickErr(err)
847         return fi, err
848 }
849
850 func (o *osWithStats) TempFile(dir, base string) (*os.File, error) {
851         o.stats.Tick(&o.stats.CreateOps)
852         f, err := ioutil.TempFile(dir, base)
853         o.stats.TickErr(err)
854         return f, err
855 }