1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
24 log "github.com/Sirupsen/logrus"
27 type unixVolumeAdder struct {
31 // String implements flag.Value
32 func (s *unixVolumeAdder) String() string {
36 func (vs *unixVolumeAdder) Set(path string) error {
37 if dirs := strings.Split(path, ","); len(dirs) > 1 {
38 log.Print("DEPRECATED: using comma-separated volume list.")
39 for _, dir := range dirs {
40 if err := vs.Set(dir); err != nil {
46 vs.Config.Volumes = append(vs.Config.Volumes, &UnixVolume{
48 ReadOnly: deprecated.flagReadonly,
49 Serialize: deprecated.flagSerializeIO,
55 VolumeTypes = append(VolumeTypes, func() VolumeWithExamples { return &UnixVolume{} })
57 flag.Var(&unixVolumeAdder{theConfig}, "volumes", "see Volumes configuration")
58 flag.Var(&unixVolumeAdder{theConfig}, "volume", "see Volumes configuration")
61 // Discover adds a UnixVolume for every directory named "keep" that is
62 // located at the top level of a device- or tmpfs-backed mount point
63 // other than "/". It returns the number of volumes added.
64 func (vs *unixVolumeAdder) Discover() int {
66 f, err := os.Open(ProcMounts)
68 log.Fatalf("opening %s: %s", ProcMounts, err)
70 scanner := bufio.NewScanner(f)
72 args := strings.Fields(scanner.Text())
73 if err := scanner.Err(); err != nil {
74 log.Fatalf("reading %s: %s", ProcMounts, err)
76 dev, mount := args[0], args[1]
80 if dev != "tmpfs" && !strings.HasPrefix(dev, "/dev/") {
83 keepdir := mount + "/keep"
84 if st, err := os.Stat(keepdir); err != nil || !st.IsDir() {
87 // Set the -readonly flag (but only for this volume)
88 // if the filesystem is mounted readonly.
89 flagReadonlyWas := deprecated.flagReadonly
90 for _, fsopt := range strings.Split(args[3], ",") {
92 deprecated.flagReadonly = true
99 if err := vs.Set(keepdir); err != nil {
100 log.Printf("adding %q: %s", keepdir, err)
104 deprecated.flagReadonly = flagReadonlyWas
109 // A UnixVolume stores and retrieves blocks in a local directory.
110 type UnixVolume struct {
111 Root string // path to the volume's root directory
114 DirectoryReplication int
116 // something to lock during IO, typically a sync.Mutex (or nil
123 // DeviceID returns a globally unique ID for the volume's root
124 // directory, consisting of the filesystem's UUID and the path from
125 // filesystem root to storage directory, joined by "/". For example,
126 // the DeviceID for a local directory "/mnt/xvda1/keep" might be
127 // "fa0b6166-3b55-4994-bd3f-92f4e00a1bb0/keep".
128 func (v *UnixVolume) DeviceID() string {
129 giveup := func(f string, args ...interface{}) string {
130 log.Printf(f+"; using blank DeviceID for volume %s", append(args, v)...)
133 buf, err := exec.Command("findmnt", "--noheadings", "--target", v.Root).CombinedOutput()
135 return giveup("findmnt: %s (%q)", err, buf)
137 findmnt := strings.Fields(string(buf))
138 if len(findmnt) < 2 {
139 return giveup("could not parse findmnt output: %q", buf)
141 fsRoot, dev := findmnt[0], findmnt[1]
143 absRoot, err := filepath.Abs(v.Root)
145 return giveup("resolving relative path %q: %s", v.Root, err)
147 realRoot, err := filepath.EvalSymlinks(absRoot)
149 return giveup("resolving symlinks in %q: %s", absRoot, err)
152 // Find path from filesystem root to realRoot
154 if strings.HasPrefix(realRoot, fsRoot+"/") {
155 fsPath = realRoot[len(fsRoot):]
156 } else if fsRoot == "/" {
158 } else if fsRoot == realRoot {
161 return giveup("findmnt reports mount point %q which is not a prefix of volume root %q", fsRoot, realRoot)
164 if !strings.HasPrefix(dev, "/") {
165 return giveup("mount %q device %q is not a path", fsRoot, dev)
168 fi, err := os.Stat(dev)
170 return giveup("stat %q: %s\n", dev, err)
172 ino := fi.Sys().(*syscall.Stat_t).Ino
174 // Find a symlink in /dev/disk/by-uuid/ whose target is (i.e.,
175 // has the same inode as) the mounted device
176 udir := "/dev/disk/by-uuid"
177 d, err := os.Open(udir)
179 return giveup("opening %q: %s", udir, err)
181 uuids, err := d.Readdirnames(0)
183 return giveup("reading %q: %s", udir, err)
185 for _, uuid := range uuids {
186 link := filepath.Join(udir, uuid)
187 fi, err = os.Stat(link)
189 log.Printf("error: stat %q: %s", link, err)
192 if fi.Sys().(*syscall.Stat_t).Ino == ino {
196 return giveup("could not find entry in %q matching %q", udir, dev)
199 // Examples implements VolumeWithExamples.
200 func (*UnixVolume) Examples() []Volume {
203 Root: "/mnt/local-disk",
205 DirectoryReplication: 1,
208 Root: "/mnt/network-disk",
210 DirectoryReplication: 2,
215 // Type implements Volume
216 func (v *UnixVolume) Type() string {
220 // Start implements Volume
221 func (v *UnixVolume) Start() error {
223 v.locker = &sync.Mutex{}
225 if !strings.HasPrefix(v.Root, "/") {
226 return fmt.Errorf("volume root does not start with '/': %q", v.Root)
228 if v.DirectoryReplication == 0 {
229 v.DirectoryReplication = 1
231 _, err := v.os.Stat(v.Root)
235 // Touch sets the timestamp for the given locator to the current time
236 func (v *UnixVolume) Touch(loc string) error {
238 return MethodDisabledError
240 p := v.blockPath(loc)
241 f, err := v.os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
246 if err := v.lock(context.TODO()); err != nil {
250 if e := v.lockfile(f); e != nil {
253 defer v.unlockfile(f)
254 ts := syscall.NsecToTimespec(time.Now().UnixNano())
255 v.os.stats.Tick(&v.os.stats.UtimesOps)
256 err = syscall.UtimesNano(p, []syscall.Timespec{ts, ts})
257 v.os.stats.TickErr(err)
261 // Mtime returns the stored timestamp for the given locator.
262 func (v *UnixVolume) Mtime(loc string) (time.Time, error) {
263 p := v.blockPath(loc)
264 fi, err := v.os.Stat(p)
266 return time.Time{}, err
268 return fi.ModTime(), nil
271 // Lock the locker (if one is in use), open the file for reading, and
272 // call the given function if and when the file is ready to read.
273 func (v *UnixVolume) getFunc(ctx context.Context, path string, fn func(io.Reader) error) error {
274 if err := v.lock(ctx); err != nil {
278 f, err := v.os.Open(path)
283 return fn(NewCountingReader(ioutil.NopCloser(f), v.os.stats.TickInBytes))
286 // stat is os.Stat() with some extra sanity checks.
287 func (v *UnixVolume) stat(path string) (os.FileInfo, error) {
288 stat, err := v.os.Stat(path)
292 } else if stat.Size() > BlockSize {
299 // Get retrieves a block, copies it to the given slice, and returns
300 // the number of bytes copied.
301 func (v *UnixVolume) Get(ctx context.Context, loc string, buf []byte) (int, error) {
302 return getWithPipe(ctx, loc, buf, v)
305 // ReadBlock implements BlockReader.
306 func (v *UnixVolume) ReadBlock(ctx context.Context, loc string, w io.Writer) error {
307 path := v.blockPath(loc)
308 stat, err := v.stat(path)
310 return v.translateError(err)
312 return v.getFunc(ctx, path, func(rdr io.Reader) error {
313 n, err := io.Copy(w, rdr)
314 if err == nil && n != stat.Size() {
315 err = io.ErrUnexpectedEOF
321 // Compare returns nil if Get(loc) would return the same content as
322 // expect. It is functionally equivalent to Get() followed by
323 // bytes.Compare(), but uses less memory.
324 func (v *UnixVolume) Compare(ctx context.Context, loc string, expect []byte) error {
325 path := v.blockPath(loc)
326 if _, err := v.stat(path); err != nil {
327 return v.translateError(err)
329 return v.getFunc(ctx, path, func(rdr io.Reader) error {
330 return compareReaderWithBuf(ctx, rdr, expect, loc[:32])
334 // Put stores a block of data identified by the locator string
335 // "loc". It returns nil on success. If the volume is full, it
336 // returns a FullError. If the write fails due to some other error,
337 // that error is returned.
338 func (v *UnixVolume) Put(ctx context.Context, loc string, block []byte) error {
339 return putWithPipe(ctx, loc, block, v)
342 // ReadBlock implements BlockWriter.
343 func (v *UnixVolume) WriteBlock(ctx context.Context, loc string, rdr io.Reader) error {
345 return MethodDisabledError
350 bdir := v.blockDir(loc)
351 if err := os.MkdirAll(bdir, 0755); err != nil {
352 log.Printf("%s: could not create directory %s: %s",
357 tmpfile, tmperr := v.os.TempFile(bdir, "tmp"+loc)
359 log.Printf("ioutil.TempFile(%s, tmp%s): %s", bdir, loc, tmperr)
363 bpath := v.blockPath(loc)
365 if err := v.lock(ctx); err != nil {
369 n, err := io.Copy(tmpfile, rdr)
370 v.os.stats.TickOutBytes(uint64(n))
372 log.Printf("%s: writing to %s: %s\n", v, bpath, err)
374 v.os.Remove(tmpfile.Name())
377 if err := tmpfile.Close(); err != nil {
378 log.Printf("closing %s: %s\n", tmpfile.Name(), err)
379 v.os.Remove(tmpfile.Name())
382 if err := v.os.Rename(tmpfile.Name(), bpath); err != nil {
383 log.Printf("rename %s %s: %s\n", tmpfile.Name(), bpath, err)
384 return v.os.Remove(tmpfile.Name())
389 // Status returns a VolumeStatus struct describing the volume's
390 // current state, or nil if an error occurs.
392 func (v *UnixVolume) Status() *VolumeStatus {
393 fi, err := v.os.Stat(v.Root)
395 log.Printf("%s: os.Stat: %s\n", v, err)
398 devnum := fi.Sys().(*syscall.Stat_t).Dev
400 var fs syscall.Statfs_t
401 if err := syscall.Statfs(v.Root, &fs); err != nil {
402 log.Printf("%s: statfs: %s\n", v, err)
405 // These calculations match the way df calculates disk usage:
406 // "free" space is measured by fs.Bavail, but "used" space
407 // uses fs.Blocks - fs.Bfree.
408 free := fs.Bavail * uint64(fs.Bsize)
409 used := (fs.Blocks - fs.Bfree) * uint64(fs.Bsize)
410 return &VolumeStatus{
418 var blockDirRe = regexp.MustCompile(`^[0-9a-f]+$`)
419 var blockFileRe = regexp.MustCompile(`^[0-9a-f]{32}$`)
421 // IndexTo writes (to the given Writer) a list of blocks found on this
422 // volume which begin with the specified prefix. If the prefix is an
423 // empty string, IndexTo writes a complete list of blocks.
425 // Each block is given in the format
427 // locator+size modification-time {newline}
431 // e4df392f86be161ca6ed3773a962b8f3+67108864 1388894303
432 // e4d41e6fd68460e0e3fc18cc746959d2+67108864 1377796043
433 // e4de7a2810f5554cd39b36d8ddb132ff+67108864 1388701136
435 func (v *UnixVolume) IndexTo(prefix string, w io.Writer) error {
437 rootdir, err := v.os.Open(v.Root)
441 defer rootdir.Close()
442 v.os.stats.Tick(&v.os.stats.ReaddirOps)
444 names, err := rootdir.Readdirnames(1)
447 } else if err != nil {
450 if !strings.HasPrefix(names[0], prefix) && !strings.HasPrefix(prefix, names[0]) {
451 // prefix excludes all blocks stored in this dir
454 if !blockDirRe.MatchString(names[0]) {
457 blockdirpath := filepath.Join(v.Root, names[0])
458 blockdir, err := v.os.Open(blockdirpath)
460 log.Print("Error reading ", blockdirpath, ": ", err)
464 v.os.stats.Tick(&v.os.stats.ReaddirOps)
466 fileInfo, err := blockdir.Readdir(1)
469 } else if err != nil {
470 log.Print("Error reading ", blockdirpath, ": ", err)
474 name := fileInfo[0].Name()
475 if !strings.HasPrefix(name, prefix) {
478 if !blockFileRe.MatchString(name) {
481 _, err = fmt.Fprint(w,
483 "+", fileInfo[0].Size(),
484 " ", fileInfo[0].ModTime().UnixNano(),
491 // Trash trashes the block data from the unix storage
492 // If TrashLifetime == 0, the block is deleted
493 // Else, the block is renamed as path/{loc}.trash.{deadline},
494 // where deadline = now + TrashLifetime
495 func (v *UnixVolume) Trash(loc string) error {
496 // Touch() must be called before calling Write() on a block. Touch()
497 // also uses lockfile(). This avoids a race condition between Write()
498 // and Trash() because either (a) the file will be trashed and Touch()
499 // will signal to the caller that the file is not present (and needs to
500 // be re-written), or (b) Touch() will update the file's timestamp and
501 // Trash() will read the correct up-to-date timestamp and choose not to
505 return MethodDisabledError
507 if err := v.lock(context.TODO()); err != nil {
511 p := v.blockPath(loc)
512 f, err := v.os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
517 if e := v.lockfile(f); e != nil {
520 defer v.unlockfile(f)
522 // If the block has been PUT in the last blobSignatureTTL
523 // seconds, return success without removing the block. This
524 // protects data from garbage collection until it is no longer
525 // possible for clients to retrieve the unreferenced blocks
526 // anyway (because the permission signatures have expired).
527 if fi, err := v.os.Stat(p); err != nil {
529 } else if time.Since(fi.ModTime()) < time.Duration(theConfig.BlobSignatureTTL) {
533 if theConfig.TrashLifetime == 0 {
534 return v.os.Remove(p)
536 return v.os.Rename(p, fmt.Sprintf("%v.trash.%d", p, time.Now().Add(theConfig.TrashLifetime.Duration()).Unix()))
539 // Untrash moves block from trash back into store
540 // Look for path/{loc}.trash.{deadline} in storage,
541 // and rename the first such file as path/{loc}
542 func (v *UnixVolume) Untrash(loc string) (err error) {
544 return MethodDisabledError
547 v.os.stats.Tick(&v.os.stats.ReaddirOps)
548 files, err := ioutil.ReadDir(v.blockDir(loc))
554 return os.ErrNotExist
558 prefix := fmt.Sprintf("%v.trash.", loc)
559 for _, f := range files {
560 if strings.HasPrefix(f.Name(), prefix) {
562 err = v.os.Rename(v.blockPath(f.Name()), v.blockPath(loc))
569 if foundTrash == false {
570 return os.ErrNotExist
576 // blockDir returns the fully qualified directory name for the directory
577 // where loc is (or would be) stored on this volume.
578 func (v *UnixVolume) blockDir(loc string) string {
579 return filepath.Join(v.Root, loc[0:3])
582 // blockPath returns the fully qualified pathname for the path to loc
584 func (v *UnixVolume) blockPath(loc string) string {
585 return filepath.Join(v.blockDir(loc), loc)
588 // IsFull returns true if the free space on the volume is less than
591 func (v *UnixVolume) IsFull() (isFull bool) {
592 fullSymlink := v.Root + "/full"
594 // Check if the volume has been marked as full in the last hour.
595 if link, err := os.Readlink(fullSymlink); err == nil {
596 if ts, err := strconv.Atoi(link); err == nil {
597 fulltime := time.Unix(int64(ts), 0)
598 if time.Since(fulltime).Hours() < 1.0 {
604 if avail, err := v.FreeDiskSpace(); err == nil {
605 isFull = avail < MinFreeKilobytes
607 log.Printf("%s: FreeDiskSpace: %s\n", v, err)
611 // If the volume is full, timestamp it.
613 now := fmt.Sprintf("%d", time.Now().Unix())
614 os.Symlink(now, fullSymlink)
619 // FreeDiskSpace returns the number of unused 1k blocks available on
622 func (v *UnixVolume) FreeDiskSpace() (free uint64, err error) {
623 var fs syscall.Statfs_t
624 err = syscall.Statfs(v.Root, &fs)
626 // Statfs output is not guaranteed to measure free
627 // space in terms of 1K blocks.
628 free = fs.Bavail * uint64(fs.Bsize) / 1024
633 func (v *UnixVolume) String() string {
634 return fmt.Sprintf("[UnixVolume %s]", v.Root)
637 // Writable returns false if all future Put, Mtime, and Delete calls
638 // are expected to fail.
639 func (v *UnixVolume) Writable() bool {
643 // Replication returns the number of replicas promised by the
644 // underlying device (as specified in configuration).
645 func (v *UnixVolume) Replication() int {
646 return v.DirectoryReplication
649 // InternalStats returns I/O and filesystem ops counters.
650 func (v *UnixVolume) InternalStats() interface{} {
654 // lock acquires the serialize lock, if one is in use. If ctx is done
655 // before the lock is acquired, lock returns ctx.Err() instead of
656 // acquiring the lock.
657 func (v *UnixVolume) lock(ctx context.Context) error {
661 locked := make(chan struct{})
678 // unlock releases the serialize lock, if one is in use.
679 func (v *UnixVolume) unlock() {
686 // lockfile and unlockfile use flock(2) to manage kernel file locks.
687 func (v *UnixVolume) lockfile(f *os.File) error {
688 v.os.stats.Tick(&v.os.stats.FlockOps)
689 err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
690 v.os.stats.TickErr(err)
694 func (v *UnixVolume) unlockfile(f *os.File) error {
695 err := syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
696 v.os.stats.TickErr(err)
700 // Where appropriate, translate a more specific filesystem error to an
701 // error recognized by handlers, like os.ErrNotExist.
702 func (v *UnixVolume) translateError(err error) error {
705 // stat() returns a PathError if the parent directory
706 // (not just the file itself) is missing
707 return os.ErrNotExist
713 var unixTrashLocRegexp = regexp.MustCompile(`/([0-9a-f]{32})\.trash\.(\d+)$`)
715 // EmptyTrash walks hierarchy looking for {hash}.trash.*
716 // and deletes those with deadline < now.
717 func (v *UnixVolume) EmptyTrash() {
718 var bytesDeleted, bytesInTrash int64
719 var blocksDeleted, blocksInTrash int
721 err := filepath.Walk(v.Root, func(path string, info os.FileInfo, err error) error {
723 log.Printf("EmptyTrash: filepath.Walk: %v: %v", path, err)
726 if info.Mode().IsDir() {
729 matches := unixTrashLocRegexp.FindStringSubmatch(path)
730 if len(matches) != 3 {
733 deadline, err := strconv.ParseInt(matches[2], 10, 64)
735 log.Printf("EmptyTrash: %v: ParseInt(%v): %v", path, matches[2], err)
738 bytesInTrash += info.Size()
740 if deadline > time.Now().Unix() {
743 err = v.os.Remove(path)
745 log.Printf("EmptyTrash: Remove %v: %v", path, err)
748 bytesDeleted += info.Size()
754 log.Printf("EmptyTrash error for %v: %v", v.String(), err)
757 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)
760 type unixStats struct {
772 func (s *unixStats) TickErr(err error) {
776 s.statsTicker.TickErr(err, fmt.Sprintf("%T", err))
779 type osWithStats struct {
783 func (o *osWithStats) Open(name string) (*os.File, error) {
784 o.stats.Tick(&o.stats.OpenOps)
785 f, err := os.Open(name)
790 func (o *osWithStats) OpenFile(name string, flag int, perm os.FileMode) (*os.File, error) {
791 o.stats.Tick(&o.stats.OpenOps)
792 f, err := os.OpenFile(name, flag, perm)
797 func (o *osWithStats) Remove(path string) error {
798 o.stats.Tick(&o.stats.UnlinkOps)
799 err := os.Remove(path)
804 func (o *osWithStats) Rename(a, b string) error {
805 o.stats.Tick(&o.stats.RenameOps)
806 err := os.Rename(a, b)
811 func (o *osWithStats) Stat(path string) (os.FileInfo, error) {
812 o.stats.Tick(&o.stats.StatOps)
813 fi, err := os.Stat(path)
818 func (o *osWithStats) TempFile(dir, base string) (*os.File, error) {
819 o.stats.Tick(&o.stats.CreateOps)
820 f, err := ioutil.TempFile(dir, base)