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