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