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