Merge branch '12315-exclude-child-procs'
[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                 }
486                 blockdir.Close()
487         }
488 }
489
490 // Trash trashes the block data from the unix storage
491 // If TrashLifetime == 0, the block is deleted
492 // Else, the block is renamed as path/{loc}.trash.{deadline},
493 // where deadline = now + TrashLifetime
494 func (v *UnixVolume) Trash(loc string) error {
495         // Touch() must be called before calling Write() on a block.  Touch()
496         // also uses lockfile().  This avoids a race condition between Write()
497         // and Trash() because either (a) the file will be trashed and Touch()
498         // will signal to the caller that the file is not present (and needs to
499         // be re-written), or (b) Touch() will update the file's timestamp and
500         // Trash() will read the correct up-to-date timestamp and choose not to
501         // trash the file.
502
503         if v.ReadOnly {
504                 return MethodDisabledError
505         }
506         if err := v.lock(context.TODO()); err != nil {
507                 return err
508         }
509         defer v.unlock()
510         p := v.blockPath(loc)
511         f, err := v.os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
512         if err != nil {
513                 return err
514         }
515         defer f.Close()
516         if e := v.lockfile(f); e != nil {
517                 return e
518         }
519         defer v.unlockfile(f)
520
521         // If the block has been PUT in the last blobSignatureTTL
522         // seconds, return success without removing the block. This
523         // protects data from garbage collection until it is no longer
524         // possible for clients to retrieve the unreferenced blocks
525         // anyway (because the permission signatures have expired).
526         if fi, err := v.os.Stat(p); err != nil {
527                 return err
528         } else if time.Since(fi.ModTime()) < time.Duration(theConfig.BlobSignatureTTL) {
529                 return nil
530         }
531
532         if theConfig.TrashLifetime == 0 {
533                 return v.os.Remove(p)
534         }
535         return v.os.Rename(p, fmt.Sprintf("%v.trash.%d", p, time.Now().Add(theConfig.TrashLifetime.Duration()).Unix()))
536 }
537
538 // Untrash moves block from trash back into store
539 // Look for path/{loc}.trash.{deadline} in storage,
540 // and rename the first such file as path/{loc}
541 func (v *UnixVolume) Untrash(loc string) (err error) {
542         if v.ReadOnly {
543                 return MethodDisabledError
544         }
545
546         v.os.stats.Tick(&v.os.stats.ReaddirOps)
547         files, err := ioutil.ReadDir(v.blockDir(loc))
548         if err != nil {
549                 return err
550         }
551
552         if len(files) == 0 {
553                 return os.ErrNotExist
554         }
555
556         foundTrash := false
557         prefix := fmt.Sprintf("%v.trash.", loc)
558         for _, f := range files {
559                 if strings.HasPrefix(f.Name(), prefix) {
560                         foundTrash = true
561                         err = v.os.Rename(v.blockPath(f.Name()), v.blockPath(loc))
562                         if err == nil {
563                                 break
564                         }
565                 }
566         }
567
568         if foundTrash == false {
569                 return os.ErrNotExist
570         }
571
572         return
573 }
574
575 // blockDir returns the fully qualified directory name for the directory
576 // where loc is (or would be) stored on this volume.
577 func (v *UnixVolume) blockDir(loc string) string {
578         return filepath.Join(v.Root, loc[0:3])
579 }
580
581 // blockPath returns the fully qualified pathname for the path to loc
582 // on this volume.
583 func (v *UnixVolume) blockPath(loc string) string {
584         return filepath.Join(v.blockDir(loc), loc)
585 }
586
587 // IsFull returns true if the free space on the volume is less than
588 // MinFreeKilobytes.
589 //
590 func (v *UnixVolume) IsFull() (isFull bool) {
591         fullSymlink := v.Root + "/full"
592
593         // Check if the volume has been marked as full in the last hour.
594         if link, err := os.Readlink(fullSymlink); err == nil {
595                 if ts, err := strconv.Atoi(link); err == nil {
596                         fulltime := time.Unix(int64(ts), 0)
597                         if time.Since(fulltime).Hours() < 1.0 {
598                                 return true
599                         }
600                 }
601         }
602
603         if avail, err := v.FreeDiskSpace(); err == nil {
604                 isFull = avail < MinFreeKilobytes
605         } else {
606                 log.Printf("%s: FreeDiskSpace: %s\n", v, err)
607                 isFull = false
608         }
609
610         // If the volume is full, timestamp it.
611         if isFull {
612                 now := fmt.Sprintf("%d", time.Now().Unix())
613                 os.Symlink(now, fullSymlink)
614         }
615         return
616 }
617
618 // FreeDiskSpace returns the number of unused 1k blocks available on
619 // the volume.
620 //
621 func (v *UnixVolume) FreeDiskSpace() (free uint64, err error) {
622         var fs syscall.Statfs_t
623         err = syscall.Statfs(v.Root, &fs)
624         if err == nil {
625                 // Statfs output is not guaranteed to measure free
626                 // space in terms of 1K blocks.
627                 free = fs.Bavail * uint64(fs.Bsize) / 1024
628         }
629         return
630 }
631
632 func (v *UnixVolume) String() string {
633         return fmt.Sprintf("[UnixVolume %s]", v.Root)
634 }
635
636 // Writable returns false if all future Put, Mtime, and Delete calls
637 // are expected to fail.
638 func (v *UnixVolume) Writable() bool {
639         return !v.ReadOnly
640 }
641
642 // Replication returns the number of replicas promised by the
643 // underlying device (as specified in configuration).
644 func (v *UnixVolume) Replication() int {
645         return v.DirectoryReplication
646 }
647
648 // GetStorageClasses implements Volume
649 func (v *UnixVolume) GetStorageClasses() []string {
650         return v.StorageClasses
651 }
652
653 // InternalStats returns I/O and filesystem ops counters.
654 func (v *UnixVolume) InternalStats() interface{} {
655         return &v.os.stats
656 }
657
658 // lock acquires the serialize lock, if one is in use. If ctx is done
659 // before the lock is acquired, lock returns ctx.Err() instead of
660 // acquiring the lock.
661 func (v *UnixVolume) lock(ctx context.Context) error {
662         if v.locker == nil {
663                 return nil
664         }
665         locked := make(chan struct{})
666         go func() {
667                 v.locker.Lock()
668                 close(locked)
669         }()
670         select {
671         case <-ctx.Done():
672                 go func() {
673                         <-locked
674                         v.locker.Unlock()
675                 }()
676                 return ctx.Err()
677         case <-locked:
678                 return nil
679         }
680 }
681
682 // unlock releases the serialize lock, if one is in use.
683 func (v *UnixVolume) unlock() {
684         if v.locker == nil {
685                 return
686         }
687         v.locker.Unlock()
688 }
689
690 // lockfile and unlockfile use flock(2) to manage kernel file locks.
691 func (v *UnixVolume) lockfile(f *os.File) error {
692         v.os.stats.Tick(&v.os.stats.FlockOps)
693         err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
694         v.os.stats.TickErr(err)
695         return err
696 }
697
698 func (v *UnixVolume) unlockfile(f *os.File) error {
699         err := syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
700         v.os.stats.TickErr(err)
701         return err
702 }
703
704 // Where appropriate, translate a more specific filesystem error to an
705 // error recognized by handlers, like os.ErrNotExist.
706 func (v *UnixVolume) translateError(err error) error {
707         switch err.(type) {
708         case *os.PathError:
709                 // stat() returns a PathError if the parent directory
710                 // (not just the file itself) is missing
711                 return os.ErrNotExist
712         default:
713                 return err
714         }
715 }
716
717 var unixTrashLocRegexp = regexp.MustCompile(`/([0-9a-f]{32})\.trash\.(\d+)$`)
718
719 // EmptyTrash walks hierarchy looking for {hash}.trash.*
720 // and deletes those with deadline < now.
721 func (v *UnixVolume) EmptyTrash() {
722         var bytesDeleted, bytesInTrash int64
723         var blocksDeleted, blocksInTrash int
724
725         err := filepath.Walk(v.Root, func(path string, info os.FileInfo, err error) error {
726                 if err != nil {
727                         log.Printf("EmptyTrash: filepath.Walk: %v: %v", path, err)
728                         return nil
729                 }
730                 if info.Mode().IsDir() {
731                         return nil
732                 }
733                 matches := unixTrashLocRegexp.FindStringSubmatch(path)
734                 if len(matches) != 3 {
735                         return nil
736                 }
737                 deadline, err := strconv.ParseInt(matches[2], 10, 64)
738                 if err != nil {
739                         log.Printf("EmptyTrash: %v: ParseInt(%v): %v", path, matches[2], err)
740                         return nil
741                 }
742                 bytesInTrash += info.Size()
743                 blocksInTrash++
744                 if deadline > time.Now().Unix() {
745                         return nil
746                 }
747                 err = v.os.Remove(path)
748                 if err != nil {
749                         log.Printf("EmptyTrash: Remove %v: %v", path, err)
750                         return nil
751                 }
752                 bytesDeleted += info.Size()
753                 blocksDeleted++
754                 return nil
755         })
756
757         if err != nil {
758                 log.Printf("EmptyTrash error for %v: %v", v.String(), err)
759         }
760
761         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)
762 }
763
764 type unixStats struct {
765         statsTicker
766         OpenOps    uint64
767         StatOps    uint64
768         FlockOps   uint64
769         UtimesOps  uint64
770         CreateOps  uint64
771         RenameOps  uint64
772         UnlinkOps  uint64
773         ReaddirOps uint64
774 }
775
776 func (s *unixStats) TickErr(err error) {
777         if err == nil {
778                 return
779         }
780         s.statsTicker.TickErr(err, fmt.Sprintf("%T", err))
781 }
782
783 type osWithStats struct {
784         stats unixStats
785 }
786
787 func (o *osWithStats) Open(name string) (*os.File, error) {
788         o.stats.Tick(&o.stats.OpenOps)
789         f, err := os.Open(name)
790         o.stats.TickErr(err)
791         return f, err
792 }
793
794 func (o *osWithStats) OpenFile(name string, flag int, perm os.FileMode) (*os.File, error) {
795         o.stats.Tick(&o.stats.OpenOps)
796         f, err := os.OpenFile(name, flag, perm)
797         o.stats.TickErr(err)
798         return f, err
799 }
800
801 func (o *osWithStats) Remove(path string) error {
802         o.stats.Tick(&o.stats.UnlinkOps)
803         err := os.Remove(path)
804         o.stats.TickErr(err)
805         return err
806 }
807
808 func (o *osWithStats) Rename(a, b string) error {
809         o.stats.Tick(&o.stats.RenameOps)
810         err := os.Rename(a, b)
811         o.stats.TickErr(err)
812         return err
813 }
814
815 func (o *osWithStats) Stat(path string) (os.FileInfo, error) {
816         o.stats.Tick(&o.stats.StatOps)
817         fi, err := os.Stat(path)
818         o.stats.TickErr(err)
819         return fi, err
820 }
821
822 func (o *osWithStats) TempFile(dir, base string) (*os.File, error) {
823         o.stats.Tick(&o.stats.CreateOps)
824         f, err := ioutil.TempFile(dir, base)
825         o.stats.TickErr(err)
826         return f, err
827 }