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