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