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