10467: local directory driver: skip disk IO if client disconnects before lock is...
[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 err := v.lock(context.TODO()); err != nil {
164                 return err
165         }
166         defer v.unlock()
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 err := v.lock(ctx); err != nil {
189                 return err
190         }
191         defer v.unlock()
192         f, err := os.Open(path)
193         if err != nil {
194                 return err
195         }
196         defer f.Close()
197         return fn(f)
198 }
199
200 // stat is os.Stat() with some extra sanity checks.
201 func (v *UnixVolume) stat(path string) (os.FileInfo, error) {
202         stat, err := os.Stat(path)
203         if err == nil {
204                 if stat.Size() < 0 {
205                         err = os.ErrInvalid
206                 } else if stat.Size() > BlockSize {
207                         err = TooLongError
208                 }
209         }
210         return stat, err
211 }
212
213 // Get retrieves a block, copies it to the given slice, and returns
214 // the number of bytes copied.
215 func (v *UnixVolume) Get(ctx context.Context, loc string, buf []byte) (int, error) {
216         return getWithPipe(ctx, loc, buf, v.get)
217 }
218
219 func (v *UnixVolume) get(ctx context.Context, loc string, w *io.PipeWriter) {
220         path := v.blockPath(loc)
221         stat, err := v.stat(path)
222         if err != nil {
223                 w.CloseWithError(v.translateError(err))
224                 return
225         }
226         err = v.getFunc(ctx, path, func(rdr io.Reader) error {
227                 n, err := io.Copy(w, rdr)
228                 if err == nil && n != stat.Size() {
229                         err = io.ErrUnexpectedEOF
230                 }
231                 return err
232         })
233         w.CloseWithError(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         return putWithPipe(ctx, loc, block, v.put)
255 }
256
257 func (v *UnixVolume) put(ctx context.Context, loc string, rdr io.ReadCloser) error {
258         if v.ReadOnly {
259                 return MethodDisabledError
260         }
261         if v.IsFull() {
262                 return FullError
263         }
264         bdir := v.blockDir(loc)
265         if err := os.MkdirAll(bdir, 0755); err != nil {
266                 log.Printf("%s: could not create directory %s: %s",
267                         loc, bdir, err)
268                 return err
269         }
270
271         tmpfile, tmperr := ioutil.TempFile(bdir, "tmp"+loc)
272         if tmperr != nil {
273                 log.Printf("ioutil.TempFile(%s, tmp%s): %s", bdir, loc, tmperr)
274                 return tmperr
275         }
276
277         bpath := v.blockPath(loc)
278
279         if err := v.lock(ctx); err != nil {
280                 log.Println("lock err:", err)
281                 return err
282         }
283         defer v.unlock()
284         if _, err := io.Copy(tmpfile, rdr); err != nil {
285                 log.Printf("%s: writing to %s: %s\n", v, bpath, err)
286                 tmpfile.Close()
287                 os.Remove(tmpfile.Name())
288                 return err
289         }
290         if err := rdr.Close(); err != nil {
291                 tmpfile.Close()
292                 os.Remove(tmpfile.Name())
293                 return err
294         }
295         if err := tmpfile.Close(); err != nil {
296                 log.Printf("closing %s: %s\n", tmpfile.Name(), err)
297                 os.Remove(tmpfile.Name())
298                 return err
299         }
300         if err := os.Rename(tmpfile.Name(), bpath); err != nil {
301                 log.Printf("rename %s %s: %s\n", tmpfile.Name(), bpath, err)
302                 os.Remove(tmpfile.Name())
303                 return err
304         }
305         return nil
306 }
307
308 // Status returns a VolumeStatus struct describing the volume's
309 // current state, or nil if an error occurs.
310 //
311 func (v *UnixVolume) Status() *VolumeStatus {
312         var fs syscall.Statfs_t
313         var devnum uint64
314
315         if fi, err := os.Stat(v.Root); err == nil {
316                 devnum = fi.Sys().(*syscall.Stat_t).Dev
317         } else {
318                 log.Printf("%s: os.Stat: %s\n", v, err)
319                 return nil
320         }
321
322         err := syscall.Statfs(v.Root, &fs)
323         if err != nil {
324                 log.Printf("%s: statfs: %s\n", v, err)
325                 return nil
326         }
327         // These calculations match the way df calculates disk usage:
328         // "free" space is measured by fs.Bavail, but "used" space
329         // uses fs.Blocks - fs.Bfree.
330         free := fs.Bavail * uint64(fs.Bsize)
331         used := (fs.Blocks - fs.Bfree) * uint64(fs.Bsize)
332         return &VolumeStatus{
333                 MountPoint: v.Root,
334                 DeviceNum:  devnum,
335                 BytesFree:  free,
336                 BytesUsed:  used,
337         }
338 }
339
340 var blockDirRe = regexp.MustCompile(`^[0-9a-f]+$`)
341 var blockFileRe = regexp.MustCompile(`^[0-9a-f]{32}$`)
342
343 // IndexTo writes (to the given Writer) a list of blocks found on this
344 // volume which begin with the specified prefix. If the prefix is an
345 // empty string, IndexTo writes a complete list of blocks.
346 //
347 // Each block is given in the format
348 //
349 //     locator+size modification-time {newline}
350 //
351 // e.g.:
352 //
353 //     e4df392f86be161ca6ed3773a962b8f3+67108864 1388894303
354 //     e4d41e6fd68460e0e3fc18cc746959d2+67108864 1377796043
355 //     e4de7a2810f5554cd39b36d8ddb132ff+67108864 1388701136
356 //
357 func (v *UnixVolume) IndexTo(prefix string, w io.Writer) error {
358         var lastErr error
359         rootdir, err := os.Open(v.Root)
360         if err != nil {
361                 return err
362         }
363         defer rootdir.Close()
364         for {
365                 names, err := rootdir.Readdirnames(1)
366                 if err == io.EOF {
367                         return lastErr
368                 } else if err != nil {
369                         return err
370                 }
371                 if !strings.HasPrefix(names[0], prefix) && !strings.HasPrefix(prefix, names[0]) {
372                         // prefix excludes all blocks stored in this dir
373                         continue
374                 }
375                 if !blockDirRe.MatchString(names[0]) {
376                         continue
377                 }
378                 blockdirpath := filepath.Join(v.Root, names[0])
379                 blockdir, err := os.Open(blockdirpath)
380                 if err != nil {
381                         log.Print("Error reading ", blockdirpath, ": ", err)
382                         lastErr = err
383                         continue
384                 }
385                 for {
386                         fileInfo, err := blockdir.Readdir(1)
387                         if err == io.EOF {
388                                 break
389                         } else if err != nil {
390                                 log.Print("Error reading ", blockdirpath, ": ", err)
391                                 lastErr = err
392                                 break
393                         }
394                         name := fileInfo[0].Name()
395                         if !strings.HasPrefix(name, prefix) {
396                                 continue
397                         }
398                         if !blockFileRe.MatchString(name) {
399                                 continue
400                         }
401                         _, err = fmt.Fprint(w,
402                                 name,
403                                 "+", fileInfo[0].Size(),
404                                 " ", fileInfo[0].ModTime().UnixNano(),
405                                 "\n")
406                 }
407                 blockdir.Close()
408         }
409 }
410
411 // Trash trashes the block data from the unix storage
412 // If TrashLifetime == 0, the block is deleted
413 // Else, the block is renamed as path/{loc}.trash.{deadline},
414 // where deadline = now + TrashLifetime
415 func (v *UnixVolume) Trash(loc string) error {
416         // Touch() must be called before calling Write() on a block.  Touch()
417         // also uses lockfile().  This avoids a race condition between Write()
418         // and Trash() because either (a) the file will be trashed and Touch()
419         // will signal to the caller that the file is not present (and needs to
420         // be re-written), or (b) Touch() will update the file's timestamp and
421         // Trash() will read the correct up-to-date timestamp and choose not to
422         // trash the file.
423
424         if v.ReadOnly {
425                 return MethodDisabledError
426         }
427         if err := v.lock(context.TODO()); err != nil {
428                 return err
429         }
430         defer v.unlock()
431         p := v.blockPath(loc)
432         f, err := os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
433         if err != nil {
434                 return err
435         }
436         defer f.Close()
437         if e := lockfile(f); e != nil {
438                 return e
439         }
440         defer unlockfile(f)
441
442         // If the block has been PUT in the last blobSignatureTTL
443         // seconds, return success without removing the block. This
444         // protects data from garbage collection until it is no longer
445         // possible for clients to retrieve the unreferenced blocks
446         // anyway (because the permission signatures have expired).
447         if fi, err := os.Stat(p); err != nil {
448                 return err
449         } else if time.Since(fi.ModTime()) < time.Duration(theConfig.BlobSignatureTTL) {
450                 return nil
451         }
452
453         if theConfig.TrashLifetime == 0 {
454                 return os.Remove(p)
455         }
456         return os.Rename(p, fmt.Sprintf("%v.trash.%d", p, time.Now().Add(theConfig.TrashLifetime.Duration()).Unix()))
457 }
458
459 // Untrash moves block from trash back into store
460 // Look for path/{loc}.trash.{deadline} in storage,
461 // and rename the first such file as path/{loc}
462 func (v *UnixVolume) Untrash(loc string) (err error) {
463         if v.ReadOnly {
464                 return MethodDisabledError
465         }
466
467         files, err := ioutil.ReadDir(v.blockDir(loc))
468         if err != nil {
469                 return err
470         }
471
472         if len(files) == 0 {
473                 return os.ErrNotExist
474         }
475
476         foundTrash := false
477         prefix := fmt.Sprintf("%v.trash.", loc)
478         for _, f := range files {
479                 if strings.HasPrefix(f.Name(), prefix) {
480                         foundTrash = true
481                         err = os.Rename(v.blockPath(f.Name()), v.blockPath(loc))
482                         if err == nil {
483                                 break
484                         }
485                 }
486         }
487
488         if foundTrash == false {
489                 return os.ErrNotExist
490         }
491
492         return
493 }
494
495 // blockDir returns the fully qualified directory name for the directory
496 // where loc is (or would be) stored on this volume.
497 func (v *UnixVolume) blockDir(loc string) string {
498         return filepath.Join(v.Root, loc[0:3])
499 }
500
501 // blockPath returns the fully qualified pathname for the path to loc
502 // on this volume.
503 func (v *UnixVolume) blockPath(loc string) string {
504         return filepath.Join(v.blockDir(loc), loc)
505 }
506
507 // IsFull returns true if the free space on the volume is less than
508 // MinFreeKilobytes.
509 //
510 func (v *UnixVolume) IsFull() (isFull bool) {
511         fullSymlink := v.Root + "/full"
512
513         // Check if the volume has been marked as full in the last hour.
514         if link, err := os.Readlink(fullSymlink); err == nil {
515                 if ts, err := strconv.Atoi(link); err == nil {
516                         fulltime := time.Unix(int64(ts), 0)
517                         if time.Since(fulltime).Hours() < 1.0 {
518                                 return true
519                         }
520                 }
521         }
522
523         if avail, err := v.FreeDiskSpace(); err == nil {
524                 isFull = avail < MinFreeKilobytes
525         } else {
526                 log.Printf("%s: FreeDiskSpace: %s\n", v, err)
527                 isFull = false
528         }
529
530         // If the volume is full, timestamp it.
531         if isFull {
532                 now := fmt.Sprintf("%d", time.Now().Unix())
533                 os.Symlink(now, fullSymlink)
534         }
535         return
536 }
537
538 // FreeDiskSpace returns the number of unused 1k blocks available on
539 // the volume.
540 //
541 func (v *UnixVolume) FreeDiskSpace() (free uint64, err error) {
542         var fs syscall.Statfs_t
543         err = syscall.Statfs(v.Root, &fs)
544         if err == nil {
545                 // Statfs output is not guaranteed to measure free
546                 // space in terms of 1K blocks.
547                 free = fs.Bavail * uint64(fs.Bsize) / 1024
548         }
549         return
550 }
551
552 func (v *UnixVolume) String() string {
553         return fmt.Sprintf("[UnixVolume %s]", v.Root)
554 }
555
556 // Writable returns false if all future Put, Mtime, and Delete calls
557 // are expected to fail.
558 func (v *UnixVolume) Writable() bool {
559         return !v.ReadOnly
560 }
561
562 // Replication returns the number of replicas promised by the
563 // underlying device (as specified in configuration).
564 func (v *UnixVolume) Replication() int {
565         return v.DirectoryReplication
566 }
567
568 // lock acquires the serialize lock, if one is in use. If ctx is done
569 // before the lock is acquired, lock returns ctx.Err() instead of
570 // acquiring the lock.
571 func (v *UnixVolume) lock(ctx context.Context) error {
572         if v.locker == nil {
573                 return nil
574         }
575         locked := make(chan struct{})
576         go func() {
577                 v.locker.Lock()
578                 close(locked)
579         }()
580         select {
581         case <-ctx.Done():
582                 log.Print("ctx Done")
583                 go func() {
584                         log.Print("waiting <-locked")
585                         <-locked
586                         log.Print("unlocking")
587                         v.locker.Unlock()
588                 }()
589                 return ctx.Err()
590         case <-locked:
591                 log.Print("got lock")
592                 return nil
593         }
594 }
595
596 // unlock releases the serialize lock, if one is in use.
597 func (v *UnixVolume) unlock() {
598         if v.locker == nil {
599                 return
600         }
601         v.locker.Unlock()
602 }
603
604 // lockfile and unlockfile use flock(2) to manage kernel file locks.
605 func lockfile(f *os.File) error {
606         return syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
607 }
608
609 func unlockfile(f *os.File) error {
610         return syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
611 }
612
613 // Where appropriate, translate a more specific filesystem error to an
614 // error recognized by handlers, like os.ErrNotExist.
615 func (v *UnixVolume) translateError(err error) error {
616         switch err.(type) {
617         case *os.PathError:
618                 // stat() returns a PathError if the parent directory
619                 // (not just the file itself) is missing
620                 return os.ErrNotExist
621         default:
622                 return err
623         }
624 }
625
626 var unixTrashLocRegexp = regexp.MustCompile(`/([0-9a-f]{32})\.trash\.(\d+)$`)
627
628 // EmptyTrash walks hierarchy looking for {hash}.trash.*
629 // and deletes those with deadline < now.
630 func (v *UnixVolume) EmptyTrash() {
631         var bytesDeleted, bytesInTrash int64
632         var blocksDeleted, blocksInTrash int
633
634         err := filepath.Walk(v.Root, func(path string, info os.FileInfo, err error) error {
635                 if err != nil {
636                         log.Printf("EmptyTrash: filepath.Walk: %v: %v", path, err)
637                         return nil
638                 }
639                 if info.Mode().IsDir() {
640                         return nil
641                 }
642                 matches := unixTrashLocRegexp.FindStringSubmatch(path)
643                 if len(matches) != 3 {
644                         return nil
645                 }
646                 deadline, err := strconv.ParseInt(matches[2], 10, 64)
647                 if err != nil {
648                         log.Printf("EmptyTrash: %v: ParseInt(%v): %v", path, matches[2], err)
649                         return nil
650                 }
651                 bytesInTrash += info.Size()
652                 blocksInTrash++
653                 if deadline > time.Now().Unix() {
654                         return nil
655                 }
656                 err = os.Remove(path)
657                 if err != nil {
658                         log.Printf("EmptyTrash: Remove %v: %v", path, err)
659                         return nil
660                 }
661                 bytesDeleted += info.Size()
662                 blocksDeleted++
663                 return nil
664         })
665
666         if err != nil {
667                 log.Printf("EmptyTrash error for %v: %v", v.String(), err)
668         }
669
670         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)
671 }