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