refs #10524
[arvados.git] / services / keepstore / volume_unix.go
1 package main
2
3 import (
4         "bufio"
5         "context"
6         "flag"
7         "fmt"
8         "io"
9         "io/ioutil"
10         "os"
11         "path/filepath"
12         "regexp"
13         "strconv"
14         "strings"
15         "sync"
16         "syscall"
17         "time"
18
19         log "github.com/Sirupsen/logrus"
20 )
21
22 type unixVolumeAdder struct {
23         *Config
24 }
25
26 // String implements flag.Value
27 func (s *unixVolumeAdder) String() string {
28         return "-"
29 }
30
31 func (vs *unixVolumeAdder) Set(path string) error {
32         if dirs := strings.Split(path, ","); len(dirs) > 1 {
33                 log.Print("DEPRECATED: using comma-separated volume list.")
34                 for _, dir := range dirs {
35                         if err := vs.Set(dir); err != nil {
36                                 return err
37                         }
38                 }
39                 return nil
40         }
41         vs.Config.Volumes = append(vs.Config.Volumes, &UnixVolume{
42                 Root:      path,
43                 ReadOnly:  deprecated.flagReadonly,
44                 Serialize: deprecated.flagSerializeIO,
45         })
46         return nil
47 }
48
49 func init() {
50         VolumeTypes = append(VolumeTypes, func() VolumeWithExamples { return &UnixVolume{} })
51
52         flag.Var(&unixVolumeAdder{theConfig}, "volumes", "see Volumes configuration")
53         flag.Var(&unixVolumeAdder{theConfig}, "volume", "see Volumes configuration")
54 }
55
56 // Discover adds a UnixVolume for every directory named "keep" that is
57 // located at the top level of a device- or tmpfs-backed mount point
58 // other than "/". It returns the number of volumes added.
59 func (vs *unixVolumeAdder) Discover() int {
60         added := 0
61         f, err := os.Open(ProcMounts)
62         if err != nil {
63                 log.Fatalf("opening %s: %s", ProcMounts, err)
64         }
65         scanner := bufio.NewScanner(f)
66         for scanner.Scan() {
67                 args := strings.Fields(scanner.Text())
68                 if err := scanner.Err(); err != nil {
69                         log.Fatalf("reading %s: %s", ProcMounts, err)
70                 }
71                 dev, mount := args[0], args[1]
72                 if mount == "/" {
73                         continue
74                 }
75                 if dev != "tmpfs" && !strings.HasPrefix(dev, "/dev/") {
76                         continue
77                 }
78                 keepdir := mount + "/keep"
79                 if st, err := os.Stat(keepdir); err != nil || !st.IsDir() {
80                         continue
81                 }
82                 // Set the -readonly flag (but only for this volume)
83                 // if the filesystem is mounted readonly.
84                 flagReadonlyWas := deprecated.flagReadonly
85                 for _, fsopt := range strings.Split(args[3], ",") {
86                         if fsopt == "ro" {
87                                 deprecated.flagReadonly = true
88                                 break
89                         }
90                         if fsopt == "rw" {
91                                 break
92                         }
93                 }
94                 if err := vs.Set(keepdir); err != nil {
95                         log.Printf("adding %q: %s", keepdir, err)
96                 } else {
97                         added++
98                 }
99                 deprecated.flagReadonly = flagReadonlyWas
100         }
101         return added
102 }
103
104 // A UnixVolume stores and retrieves blocks in a local directory.
105 type UnixVolume struct {
106         Root                 string // path to the volume's root directory
107         ReadOnly             bool
108         Serialize            bool
109         DirectoryReplication int
110
111         // something to lock during IO, typically a sync.Mutex (or nil
112         // to skip locking)
113         locker sync.Locker
114 }
115
116 // Examples implements VolumeWithExamples.
117 func (*UnixVolume) Examples() []Volume {
118         return []Volume{
119                 &UnixVolume{
120                         Root:                 "/mnt/local-disk",
121                         Serialize:            true,
122                         DirectoryReplication: 1,
123                 },
124                 &UnixVolume{
125                         Root:                 "/mnt/network-disk",
126                         Serialize:            false,
127                         DirectoryReplication: 2,
128                 },
129         }
130 }
131
132 // Type implements Volume
133 func (v *UnixVolume) Type() string {
134         return "Directory"
135 }
136
137 // Start implements Volume
138 func (v *UnixVolume) Start() error {
139         if v.Serialize {
140                 v.locker = &sync.Mutex{}
141         }
142         if !strings.HasPrefix(v.Root, "/") {
143                 return fmt.Errorf("volume root does not start with '/': %q", v.Root)
144         }
145         if v.DirectoryReplication == 0 {
146                 v.DirectoryReplication = 1
147         }
148         _, err := os.Stat(v.Root)
149         return err
150 }
151
152 // Touch sets the timestamp for the given locator to the current time
153 func (v *UnixVolume) Touch(loc string) error {
154         if v.ReadOnly {
155                 return MethodDisabledError
156         }
157         p := v.blockPath(loc)
158         f, err := os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
159         if err != nil {
160                 return err
161         }
162         defer f.Close()
163         if v.locker != nil {
164                 v.locker.Lock()
165                 defer v.locker.Unlock()
166         }
167         if e := lockfile(f); e != nil {
168                 return e
169         }
170         defer unlockfile(f)
171         ts := syscall.NsecToTimespec(time.Now().UnixNano())
172         return syscall.UtimesNano(p, []syscall.Timespec{ts, ts})
173 }
174
175 // Mtime returns the stored timestamp for the given locator.
176 func (v *UnixVolume) Mtime(loc string) (time.Time, error) {
177         p := v.blockPath(loc)
178         fi, err := os.Stat(p)
179         if err != nil {
180                 return time.Time{}, err
181         }
182         return fi.ModTime(), nil
183 }
184
185 // Lock the locker (if one is in use), open the file for reading, and
186 // call the given function if and when the file is ready to read.
187 func (v *UnixVolume) getFunc(ctx context.Context, path string, fn func(io.Reader) error) error {
188         if v.locker != nil {
189                 v.locker.Lock()
190                 defer v.locker.Unlock()
191         }
192         if ctx.Err() != nil {
193                 return ctx.Err()
194         }
195         f, err := os.Open(path)
196         if err != nil {
197                 return err
198         }
199         defer f.Close()
200         return fn(f)
201 }
202
203 // stat is os.Stat() with some extra sanity checks.
204 func (v *UnixVolume) stat(path string) (os.FileInfo, error) {
205         stat, err := os.Stat(path)
206         if err == nil {
207                 if stat.Size() < 0 {
208                         err = os.ErrInvalid
209                 } else if stat.Size() > BlockSize {
210                         err = TooLongError
211                 }
212         }
213         return stat, err
214 }
215
216 // Get retrieves a block, copies it to the given slice, and returns
217 // the number of bytes copied.
218 func (v *UnixVolume) Get(ctx context.Context, loc string, buf []byte) (int, error) {
219         path := v.blockPath(loc)
220         stat, err := v.stat(path)
221         if err != nil {
222                 return 0, v.translateError(err)
223         }
224         if stat.Size() > int64(len(buf)) {
225                 return 0, TooLongError
226         }
227         var read int
228         size := int(stat.Size())
229         err = v.getFunc(ctx, path, func(rdr io.Reader) error {
230                 read, err = io.ReadFull(rdr, buf[:size])
231                 return err
232         })
233         return read, err
234 }
235
236 // Compare returns nil if Get(loc) would return the same content as
237 // expect. It is functionally equivalent to Get() followed by
238 // bytes.Compare(), but uses less memory.
239 func (v *UnixVolume) Compare(ctx context.Context, loc string, expect []byte) error {
240         path := v.blockPath(loc)
241         if _, err := v.stat(path); err != nil {
242                 return v.translateError(err)
243         }
244         return v.getFunc(ctx, path, func(rdr io.Reader) error {
245                 return compareReaderWithBuf(ctx, rdr, expect, loc[:32])
246         })
247 }
248
249 // Put stores a block of data identified by the locator string
250 // "loc".  It returns nil on success.  If the volume is full, it
251 // returns a FullError.  If the write fails due to some other error,
252 // that error is returned.
253 func (v *UnixVolume) Put(ctx context.Context, loc string, block []byte) error {
254         if v.ReadOnly {
255                 return MethodDisabledError
256         }
257         if v.IsFull() {
258                 return FullError
259         }
260         bdir := v.blockDir(loc)
261         if err := os.MkdirAll(bdir, 0755); err != nil {
262                 log.Printf("%s: could not create directory %s: %s",
263                         loc, bdir, err)
264                 return err
265         }
266
267         tmpfile, tmperr := ioutil.TempFile(bdir, "tmp"+loc)
268         if tmperr != nil {
269                 log.Printf("ioutil.TempFile(%s, tmp%s): %s", bdir, loc, tmperr)
270                 return tmperr
271         }
272         bpath := v.blockPath(loc)
273
274         if v.locker != nil {
275                 v.locker.Lock()
276                 defer v.locker.Unlock()
277         }
278         select {
279         case <-ctx.Done():
280                 return ctx.Err()
281         default:
282         }
283         if _, err := tmpfile.Write(block); err != nil {
284                 log.Printf("%s: writing to %s: %s\n", v, bpath, err)
285                 tmpfile.Close()
286                 os.Remove(tmpfile.Name())
287                 return err
288         }
289         if err := tmpfile.Close(); err != nil {
290                 log.Printf("closing %s: %s\n", tmpfile.Name(), err)
291                 os.Remove(tmpfile.Name())
292                 return err
293         }
294         if err := os.Rename(tmpfile.Name(), bpath); err != nil {
295                 log.Printf("rename %s %s: %s\n", tmpfile.Name(), bpath, err)
296                 os.Remove(tmpfile.Name())
297                 return err
298         }
299         return nil
300 }
301
302 // Status returns a VolumeStatus struct describing the volume's
303 // current state, or nil if an error occurs.
304 //
305 func (v *UnixVolume) Status() *VolumeStatus {
306         var fs syscall.Statfs_t
307         var devnum uint64
308
309         if fi, err := os.Stat(v.Root); err == nil {
310                 devnum = fi.Sys().(*syscall.Stat_t).Dev
311         } else {
312                 log.Printf("%s: os.Stat: %s\n", v, err)
313                 return nil
314         }
315
316         err := syscall.Statfs(v.Root, &fs)
317         if err != nil {
318                 log.Printf("%s: statfs: %s\n", v, err)
319                 return nil
320         }
321         // These calculations match the way df calculates disk usage:
322         // "free" space is measured by fs.Bavail, but "used" space
323         // uses fs.Blocks - fs.Bfree.
324         free := fs.Bavail * uint64(fs.Bsize)
325         used := (fs.Blocks - fs.Bfree) * uint64(fs.Bsize)
326         return &VolumeStatus{
327                 MountPoint: v.Root,
328                 DeviceNum:  devnum,
329                 BytesFree:  free,
330                 BytesUsed:  used,
331         }
332 }
333
334 var blockDirRe = regexp.MustCompile(`^[0-9a-f]+$`)
335 var blockFileRe = regexp.MustCompile(`^[0-9a-f]{32}$`)
336
337 // IndexTo writes (to the given Writer) a list of blocks found on this
338 // volume which begin with the specified prefix. If the prefix is an
339 // empty string, IndexTo writes a complete list of blocks.
340 //
341 // Each block is given in the format
342 //
343 //     locator+size modification-time {newline}
344 //
345 // e.g.:
346 //
347 //     e4df392f86be161ca6ed3773a962b8f3+67108864 1388894303
348 //     e4d41e6fd68460e0e3fc18cc746959d2+67108864 1377796043
349 //     e4de7a2810f5554cd39b36d8ddb132ff+67108864 1388701136
350 //
351 func (v *UnixVolume) IndexTo(prefix string, w io.Writer) error {
352         var lastErr error
353         rootdir, err := os.Open(v.Root)
354         if err != nil {
355                 return err
356         }
357         defer rootdir.Close()
358         for {
359                 names, err := rootdir.Readdirnames(1)
360                 if err == io.EOF {
361                         return lastErr
362                 } else if err != nil {
363                         return err
364                 }
365                 if !strings.HasPrefix(names[0], prefix) && !strings.HasPrefix(prefix, names[0]) {
366                         // prefix excludes all blocks stored in this dir
367                         continue
368                 }
369                 if !blockDirRe.MatchString(names[0]) {
370                         continue
371                 }
372                 blockdirpath := filepath.Join(v.Root, names[0])
373                 blockdir, err := os.Open(blockdirpath)
374                 if err != nil {
375                         log.Print("Error reading ", blockdirpath, ": ", err)
376                         lastErr = err
377                         continue
378                 }
379                 for {
380                         fileInfo, err := blockdir.Readdir(1)
381                         if err == io.EOF {
382                                 break
383                         } else if err != nil {
384                                 log.Print("Error reading ", blockdirpath, ": ", err)
385                                 lastErr = err
386                                 break
387                         }
388                         name := fileInfo[0].Name()
389                         if !strings.HasPrefix(name, prefix) {
390                                 continue
391                         }
392                         if !blockFileRe.MatchString(name) {
393                                 continue
394                         }
395                         _, err = fmt.Fprint(w,
396                                 name,
397                                 "+", fileInfo[0].Size(),
398                                 " ", fileInfo[0].ModTime().UnixNano(),
399                                 "\n")
400                 }
401                 blockdir.Close()
402         }
403 }
404
405 // Trash trashes the block data from the unix storage
406 // If TrashLifetime == 0, the block is deleted
407 // Else, the block is renamed as path/{loc}.trash.{deadline},
408 // where deadline = now + TrashLifetime
409 func (v *UnixVolume) Trash(loc string) error {
410         // Touch() must be called before calling Write() on a block.  Touch()
411         // also uses lockfile().  This avoids a race condition between Write()
412         // and Trash() because either (a) the file will be trashed and Touch()
413         // will signal to the caller that the file is not present (and needs to
414         // be re-written), or (b) Touch() will update the file's timestamp and
415         // Trash() will read the correct up-to-date timestamp and choose not to
416         // trash the file.
417
418         if v.ReadOnly {
419                 return MethodDisabledError
420         }
421         if v.locker != nil {
422                 v.locker.Lock()
423                 defer v.locker.Unlock()
424         }
425         p := v.blockPath(loc)
426         f, err := os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
427         if err != nil {
428                 return err
429         }
430         defer f.Close()
431         if e := lockfile(f); e != nil {
432                 return e
433         }
434         defer unlockfile(f)
435
436         // If the block has been PUT in the last blobSignatureTTL
437         // seconds, return success without removing the block. This
438         // protects data from garbage collection until it is no longer
439         // possible for clients to retrieve the unreferenced blocks
440         // anyway (because the permission signatures have expired).
441         if fi, err := os.Stat(p); err != nil {
442                 return err
443         } else if time.Since(fi.ModTime()) < time.Duration(theConfig.BlobSignatureTTL) {
444                 return nil
445         }
446
447         if theConfig.TrashLifetime == 0 {
448                 return os.Remove(p)
449         }
450         return os.Rename(p, fmt.Sprintf("%v.trash.%d", p, time.Now().Add(theConfig.TrashLifetime.Duration()).Unix()))
451 }
452
453 // Untrash moves block from trash back into store
454 // Look for path/{loc}.trash.{deadline} in storage,
455 // and rename the first such file as path/{loc}
456 func (v *UnixVolume) Untrash(loc string) (err error) {
457         if v.ReadOnly {
458                 return MethodDisabledError
459         }
460
461         files, err := ioutil.ReadDir(v.blockDir(loc))
462         if err != nil {
463                 return err
464         }
465
466         if len(files) == 0 {
467                 return os.ErrNotExist
468         }
469
470         foundTrash := false
471         prefix := fmt.Sprintf("%v.trash.", loc)
472         for _, f := range files {
473                 if strings.HasPrefix(f.Name(), prefix) {
474                         foundTrash = true
475                         err = os.Rename(v.blockPath(f.Name()), v.blockPath(loc))
476                         if err == nil {
477                                 break
478                         }
479                 }
480         }
481
482         if foundTrash == false {
483                 return os.ErrNotExist
484         }
485
486         return
487 }
488
489 // blockDir returns the fully qualified directory name for the directory
490 // where loc is (or would be) stored on this volume.
491 func (v *UnixVolume) blockDir(loc string) string {
492         return filepath.Join(v.Root, loc[0:3])
493 }
494
495 // blockPath returns the fully qualified pathname for the path to loc
496 // on this volume.
497 func (v *UnixVolume) blockPath(loc string) string {
498         return filepath.Join(v.blockDir(loc), loc)
499 }
500
501 // IsFull returns true if the free space on the volume is less than
502 // MinFreeKilobytes.
503 //
504 func (v *UnixVolume) IsFull() (isFull bool) {
505         fullSymlink := v.Root + "/full"
506
507         // Check if the volume has been marked as full in the last hour.
508         if link, err := os.Readlink(fullSymlink); err == nil {
509                 if ts, err := strconv.Atoi(link); err == nil {
510                         fulltime := time.Unix(int64(ts), 0)
511                         if time.Since(fulltime).Hours() < 1.0 {
512                                 return true
513                         }
514                 }
515         }
516
517         if avail, err := v.FreeDiskSpace(); err == nil {
518                 isFull = avail < MinFreeKilobytes
519         } else {
520                 log.Printf("%s: FreeDiskSpace: %s\n", v, err)
521                 isFull = false
522         }
523
524         // If the volume is full, timestamp it.
525         if isFull {
526                 now := fmt.Sprintf("%d", time.Now().Unix())
527                 os.Symlink(now, fullSymlink)
528         }
529         return
530 }
531
532 // FreeDiskSpace returns the number of unused 1k blocks available on
533 // the volume.
534 //
535 func (v *UnixVolume) FreeDiskSpace() (free uint64, err error) {
536         var fs syscall.Statfs_t
537         err = syscall.Statfs(v.Root, &fs)
538         if err == nil {
539                 // Statfs output is not guaranteed to measure free
540                 // space in terms of 1K blocks.
541                 free = fs.Bavail * uint64(fs.Bsize) / 1024
542         }
543         return
544 }
545
546 func (v *UnixVolume) String() string {
547         return fmt.Sprintf("[UnixVolume %s]", v.Root)
548 }
549
550 // Writable returns false if all future Put, Mtime, and Delete calls
551 // are expected to fail.
552 func (v *UnixVolume) Writable() bool {
553         return !v.ReadOnly
554 }
555
556 // Replication returns the number of replicas promised by the
557 // underlying device (as specified in configuration).
558 func (v *UnixVolume) Replication() int {
559         return v.DirectoryReplication
560 }
561
562 // lockfile and unlockfile use flock(2) to manage kernel file locks.
563 func lockfile(f *os.File) error {
564         return syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
565 }
566
567 func unlockfile(f *os.File) error {
568         return syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
569 }
570
571 // Where appropriate, translate a more specific filesystem error to an
572 // error recognized by handlers, like os.ErrNotExist.
573 func (v *UnixVolume) translateError(err error) error {
574         switch err.(type) {
575         case *os.PathError:
576                 // stat() returns a PathError if the parent directory
577                 // (not just the file itself) is missing
578                 return os.ErrNotExist
579         default:
580                 return err
581         }
582 }
583
584 var unixTrashLocRegexp = regexp.MustCompile(`/([0-9a-f]{32})\.trash\.(\d+)$`)
585
586 // EmptyTrash walks hierarchy looking for {hash}.trash.*
587 // and deletes those with deadline < now.
588 func (v *UnixVolume) EmptyTrash() {
589         var bytesDeleted, bytesInTrash int64
590         var blocksDeleted, blocksInTrash int
591
592         err := filepath.Walk(v.Root, func(path string, info os.FileInfo, err error) error {
593                 if err != nil {
594                         log.Printf("EmptyTrash: filepath.Walk: %v: %v", path, err)
595                         return nil
596                 }
597                 if info.Mode().IsDir() {
598                         return nil
599                 }
600                 matches := unixTrashLocRegexp.FindStringSubmatch(path)
601                 if len(matches) != 3 {
602                         return nil
603                 }
604                 deadline, err := strconv.ParseInt(matches[2], 10, 64)
605                 if err != nil {
606                         log.Printf("EmptyTrash: %v: ParseInt(%v): %v", path, matches[2], err)
607                         return nil
608                 }
609                 bytesInTrash += info.Size()
610                 blocksInTrash++
611                 if deadline > time.Now().Unix() {
612                         return nil
613                 }
614                 err = os.Remove(path)
615                 if err != nil {
616                         log.Printf("EmptyTrash: Remove %v: %v", path, err)
617                         return nil
618                 }
619                 bytesDeleted += info.Size()
620                 blocksDeleted++
621                 return nil
622         })
623
624         if err != nil {
625                 log.Printf("EmptyTrash error for %v: %v", v.String(), err)
626         }
627
628         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)
629 }