1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
25 type unixVolumeAdder struct {
29 // String implements flag.Value
30 func (s *unixVolumeAdder) String() string {
34 func (vs *unixVolumeAdder) Set(path string) error {
35 if dirs := strings.Split(path, ","); len(dirs) > 1 {
36 log.Print("DEPRECATED: using comma-separated volume list.")
37 for _, dir := range dirs {
38 if err := vs.Set(dir); err != nil {
44 vs.Config.Volumes = append(vs.Config.Volumes, &UnixVolume{
46 ReadOnly: deprecated.flagReadonly,
47 Serialize: deprecated.flagSerializeIO,
53 VolumeTypes = append(VolumeTypes, func() VolumeWithExamples { return &UnixVolume{} })
55 flag.Var(&unixVolumeAdder{theConfig}, "volumes", "see Volumes configuration")
56 flag.Var(&unixVolumeAdder{theConfig}, "volume", "see Volumes configuration")
59 // Discover adds a UnixVolume for every directory named "keep" that is
60 // located at the top level of a device- or tmpfs-backed mount point
61 // other than "/". It returns the number of volumes added.
62 func (vs *unixVolumeAdder) Discover() int {
64 f, err := os.Open(ProcMounts)
66 log.Fatalf("opening %s: %s", ProcMounts, err)
68 scanner := bufio.NewScanner(f)
70 args := strings.Fields(scanner.Text())
71 if err := scanner.Err(); err != nil {
72 log.Fatalf("reading %s: %s", ProcMounts, err)
74 dev, mount := args[0], args[1]
78 if dev != "tmpfs" && !strings.HasPrefix(dev, "/dev/") {
81 keepdir := mount + "/keep"
82 if st, err := os.Stat(keepdir); err != nil || !st.IsDir() {
85 // Set the -readonly flag (but only for this volume)
86 // if the filesystem is mounted readonly.
87 flagReadonlyWas := deprecated.flagReadonly
88 for _, fsopt := range strings.Split(args[3], ",") {
90 deprecated.flagReadonly = true
97 if err := vs.Set(keepdir); err != nil {
98 log.Printf("adding %q: %s", keepdir, err)
102 deprecated.flagReadonly = flagReadonlyWas
107 // A UnixVolume stores and retrieves blocks in a local directory.
108 type UnixVolume struct {
109 Root string // path to the volume's root directory
112 DirectoryReplication int
113 StorageClasses []string
115 // something to lock during IO, typically a sync.Mutex (or nil
122 // DeviceID returns a globally unique ID for the volume's root
123 // directory, consisting of the filesystem's UUID and the path from
124 // filesystem root to storage directory, joined by "/". For example,
125 // the DeviceID for a local directory "/mnt/xvda1/keep" might be
126 // "fa0b6166-3b55-4994-bd3f-92f4e00a1bb0/keep".
127 func (v *UnixVolume) DeviceID() string {
128 giveup := func(f string, args ...interface{}) string {
129 log.Printf(f+"; using blank DeviceID for volume %s", append(args, v)...)
132 buf, err := exec.Command("findmnt", "--noheadings", "--target", v.Root).CombinedOutput()
134 return giveup("findmnt: %s (%q)", err, buf)
136 findmnt := strings.Fields(string(buf))
137 if len(findmnt) < 2 {
138 return giveup("could not parse findmnt output: %q", buf)
140 fsRoot, dev := findmnt[0], findmnt[1]
142 absRoot, err := filepath.Abs(v.Root)
144 return giveup("resolving relative path %q: %s", v.Root, err)
146 realRoot, err := filepath.EvalSymlinks(absRoot)
148 return giveup("resolving symlinks in %q: %s", absRoot, err)
151 // Find path from filesystem root to realRoot
153 if strings.HasPrefix(realRoot, fsRoot+"/") {
154 fsPath = realRoot[len(fsRoot):]
155 } else if fsRoot == "/" {
157 } else if fsRoot == realRoot {
160 return giveup("findmnt reports mount point %q which is not a prefix of volume root %q", fsRoot, realRoot)
163 if !strings.HasPrefix(dev, "/") {
164 return giveup("mount %q device %q is not a path", fsRoot, dev)
167 fi, err := os.Stat(dev)
169 return giveup("stat %q: %s\n", dev, err)
171 ino := fi.Sys().(*syscall.Stat_t).Ino
173 // Find a symlink in /dev/disk/by-uuid/ whose target is (i.e.,
174 // has the same inode as) the mounted device
175 udir := "/dev/disk/by-uuid"
176 d, err := os.Open(udir)
178 return giveup("opening %q: %s", udir, err)
180 uuids, err := d.Readdirnames(0)
182 return giveup("reading %q: %s", udir, err)
184 for _, uuid := range uuids {
185 link := filepath.Join(udir, uuid)
186 fi, err = os.Stat(link)
188 log.Printf("error: stat %q: %s", link, err)
191 if fi.Sys().(*syscall.Stat_t).Ino == ino {
195 return giveup("could not find entry in %q matching %q", udir, dev)
198 // Examples implements VolumeWithExamples.
199 func (*UnixVolume) Examples() []Volume {
202 Root: "/mnt/local-disk",
204 DirectoryReplication: 1,
207 Root: "/mnt/network-disk",
209 DirectoryReplication: 2,
214 // Type implements Volume
215 func (v *UnixVolume) Type() string {
219 // Start implements Volume
220 func (v *UnixVolume) Start() error {
222 v.locker = &sync.Mutex{}
224 if !strings.HasPrefix(v.Root, "/") {
225 return fmt.Errorf("volume root does not start with '/': %q", v.Root)
227 if v.DirectoryReplication == 0 {
228 v.DirectoryReplication = 1
230 _, err := v.os.Stat(v.Root)
234 // Touch sets the timestamp for the given locator to the current time
235 func (v *UnixVolume) Touch(loc string) error {
237 return MethodDisabledError
239 p := v.blockPath(loc)
240 f, err := v.os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
245 if err := v.lock(context.TODO()); err != nil {
249 if e := v.lockfile(f); e != nil {
252 defer v.unlockfile(f)
253 ts := syscall.NsecToTimespec(time.Now().UnixNano())
254 v.os.stats.Tick(&v.os.stats.UtimesOps)
255 err = syscall.UtimesNano(p, []syscall.Timespec{ts, ts})
256 v.os.stats.TickErr(err)
260 // Mtime returns the stored timestamp for the given locator.
261 func (v *UnixVolume) Mtime(loc string) (time.Time, error) {
262 p := v.blockPath(loc)
263 fi, err := v.os.Stat(p)
265 return time.Time{}, err
267 return fi.ModTime(), nil
270 // Lock the locker (if one is in use), open the file for reading, and
271 // call the given function if and when the file is ready to read.
272 func (v *UnixVolume) getFunc(ctx context.Context, path string, fn func(io.Reader) error) error {
273 if err := v.lock(ctx); err != nil {
277 f, err := v.os.Open(path)
282 return fn(NewCountingReader(ioutil.NopCloser(f), v.os.stats.TickInBytes))
285 // stat is os.Stat() with some extra sanity checks.
286 func (v *UnixVolume) stat(path string) (os.FileInfo, error) {
287 stat, err := v.os.Stat(path)
291 } else if stat.Size() > BlockSize {
298 // Get retrieves a block, copies it to the given slice, and returns
299 // the number of bytes copied.
300 func (v *UnixVolume) Get(ctx context.Context, loc string, buf []byte) (int, error) {
301 return getWithPipe(ctx, loc, buf, v)
304 // ReadBlock implements BlockReader.
305 func (v *UnixVolume) ReadBlock(ctx context.Context, loc string, w io.Writer) error {
306 path := v.blockPath(loc)
307 stat, err := v.stat(path)
309 return v.translateError(err)
311 return v.getFunc(ctx, path, func(rdr io.Reader) error {
312 n, err := io.Copy(w, rdr)
313 if err == nil && n != stat.Size() {
314 err = io.ErrUnexpectedEOF
320 // Compare returns nil if Get(loc) would return the same content as
321 // expect. It is functionally equivalent to Get() followed by
322 // bytes.Compare(), but uses less memory.
323 func (v *UnixVolume) Compare(ctx context.Context, loc string, expect []byte) error {
324 path := v.blockPath(loc)
325 if _, err := v.stat(path); err != nil {
326 return v.translateError(err)
328 return v.getFunc(ctx, path, func(rdr io.Reader) error {
329 return compareReaderWithBuf(ctx, rdr, expect, loc[:32])
333 // Put stores a block of data identified by the locator string
334 // "loc". It returns nil on success. If the volume is full, it
335 // returns a FullError. If the write fails due to some other error,
336 // that error is returned.
337 func (v *UnixVolume) Put(ctx context.Context, loc string, block []byte) error {
338 return putWithPipe(ctx, loc, block, v)
341 // ReadBlock implements BlockWriter.
342 func (v *UnixVolume) WriteBlock(ctx context.Context, loc string, rdr io.Reader) error {
344 return MethodDisabledError
349 bdir := v.blockDir(loc)
350 if err := os.MkdirAll(bdir, 0755); err != nil {
351 log.Printf("%s: could not create directory %s: %s",
356 tmpfile, tmperr := v.os.TempFile(bdir, "tmp"+loc)
358 log.Printf("ioutil.TempFile(%s, tmp%s): %s", bdir, loc, tmperr)
362 bpath := v.blockPath(loc)
364 if err := v.lock(ctx); err != nil {
368 n, err := io.Copy(tmpfile, rdr)
369 v.os.stats.TickOutBytes(uint64(n))
371 log.Printf("%s: writing to %s: %s\n", v, bpath, err)
373 v.os.Remove(tmpfile.Name())
376 if err := tmpfile.Close(); err != nil {
377 log.Printf("closing %s: %s\n", tmpfile.Name(), err)
378 v.os.Remove(tmpfile.Name())
381 if err := v.os.Rename(tmpfile.Name(), bpath); err != nil {
382 log.Printf("rename %s %s: %s\n", tmpfile.Name(), bpath, err)
383 return v.os.Remove(tmpfile.Name())
388 // Status returns a VolumeStatus struct describing the volume's
389 // current state, or nil if an error occurs.
391 func (v *UnixVolume) Status() *VolumeStatus {
392 fi, err := v.os.Stat(v.Root)
394 log.Printf("%s: os.Stat: %s\n", v, err)
397 devnum := fi.Sys().(*syscall.Stat_t).Dev
399 var fs syscall.Statfs_t
400 if err := syscall.Statfs(v.Root, &fs); err != nil {
401 log.Printf("%s: statfs: %s\n", v, err)
404 // These calculations match the way df calculates disk usage:
405 // "free" space is measured by fs.Bavail, but "used" space
406 // uses fs.Blocks - fs.Bfree.
407 free := fs.Bavail * uint64(fs.Bsize)
408 used := (fs.Blocks - fs.Bfree) * uint64(fs.Bsize)
409 return &VolumeStatus{
417 var blockDirRe = regexp.MustCompile(`^[0-9a-f]+$`)
418 var blockFileRe = regexp.MustCompile(`^[0-9a-f]{32}$`)
420 // IndexTo writes (to the given Writer) a list of blocks found on this
421 // volume which begin with the specified prefix. If the prefix is an
422 // empty string, IndexTo writes a complete list of blocks.
424 // Each block is given in the format
426 // locator+size modification-time {newline}
430 // e4df392f86be161ca6ed3773a962b8f3+67108864 1388894303
431 // e4d41e6fd68460e0e3fc18cc746959d2+67108864 1377796043
432 // e4de7a2810f5554cd39b36d8ddb132ff+67108864 1388701136
434 func (v *UnixVolume) IndexTo(prefix string, w io.Writer) error {
436 rootdir, err := v.os.Open(v.Root)
440 defer rootdir.Close()
441 v.os.stats.Tick(&v.os.stats.ReaddirOps)
443 names, err := rootdir.Readdirnames(1)
446 } else if err != nil {
449 if !strings.HasPrefix(names[0], prefix) && !strings.HasPrefix(prefix, names[0]) {
450 // prefix excludes all blocks stored in this dir
453 if !blockDirRe.MatchString(names[0]) {
456 blockdirpath := filepath.Join(v.Root, names[0])
457 blockdir, err := v.os.Open(blockdirpath)
459 log.Print("Error reading ", blockdirpath, ": ", err)
463 v.os.stats.Tick(&v.os.stats.ReaddirOps)
465 fileInfo, err := blockdir.Readdir(1)
468 } else if err != nil {
469 log.Print("Error reading ", blockdirpath, ": ", err)
473 name := fileInfo[0].Name()
474 if !strings.HasPrefix(name, prefix) {
477 if !blockFileRe.MatchString(name) {
480 _, err = fmt.Fprint(w,
482 "+", fileInfo[0].Size(),
483 " ", fileInfo[0].ModTime().UnixNano(),
486 log.Print("Error writing : ", err)
495 // Trash trashes the block data from the unix storage
496 // If TrashLifetime == 0, the block is deleted
497 // Else, the block is renamed as path/{loc}.trash.{deadline},
498 // where deadline = now + TrashLifetime
499 func (v *UnixVolume) Trash(loc string) error {
500 // Touch() must be called before calling Write() on a block. Touch()
501 // also uses lockfile(). This avoids a race condition between Write()
502 // and Trash() because either (a) the file will be trashed and Touch()
503 // will signal to the caller that the file is not present (and needs to
504 // be re-written), or (b) Touch() will update the file's timestamp and
505 // Trash() will read the correct up-to-date timestamp and choose not to
509 return MethodDisabledError
511 if err := v.lock(context.TODO()); err != nil {
515 p := v.blockPath(loc)
516 f, err := v.os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
521 if e := v.lockfile(f); e != nil {
524 defer v.unlockfile(f)
526 // If the block has been PUT in the last blobSignatureTTL
527 // seconds, return success without removing the block. This
528 // protects data from garbage collection until it is no longer
529 // possible for clients to retrieve the unreferenced blocks
530 // anyway (because the permission signatures have expired).
531 if fi, err := v.os.Stat(p); err != nil {
533 } else if time.Since(fi.ModTime()) < time.Duration(theConfig.BlobSignatureTTL) {
537 if theConfig.TrashLifetime == 0 {
538 return v.os.Remove(p)
540 return v.os.Rename(p, fmt.Sprintf("%v.trash.%d", p, time.Now().Add(theConfig.TrashLifetime.Duration()).Unix()))
543 // Untrash moves block from trash back into store
544 // Look for path/{loc}.trash.{deadline} in storage,
545 // and rename the first such file as path/{loc}
546 func (v *UnixVolume) Untrash(loc string) (err error) {
548 return MethodDisabledError
551 v.os.stats.Tick(&v.os.stats.ReaddirOps)
552 files, err := ioutil.ReadDir(v.blockDir(loc))
558 return os.ErrNotExist
562 prefix := fmt.Sprintf("%v.trash.", loc)
563 for _, f := range files {
564 if strings.HasPrefix(f.Name(), prefix) {
566 err = v.os.Rename(v.blockPath(f.Name()), v.blockPath(loc))
573 if foundTrash == false {
574 return os.ErrNotExist
580 // blockDir returns the fully qualified directory name for the directory
581 // where loc is (or would be) stored on this volume.
582 func (v *UnixVolume) blockDir(loc string) string {
583 return filepath.Join(v.Root, loc[0:3])
586 // blockPath returns the fully qualified pathname for the path to loc
588 func (v *UnixVolume) blockPath(loc string) string {
589 return filepath.Join(v.blockDir(loc), loc)
592 // IsFull returns true if the free space on the volume is less than
595 func (v *UnixVolume) IsFull() (isFull bool) {
596 fullSymlink := v.Root + "/full"
598 // Check if the volume has been marked as full in the last hour.
599 if link, err := os.Readlink(fullSymlink); err == nil {
600 if ts, err := strconv.Atoi(link); err == nil {
601 fulltime := time.Unix(int64(ts), 0)
602 if time.Since(fulltime).Hours() < 1.0 {
608 if avail, err := v.FreeDiskSpace(); err == nil {
609 isFull = avail < MinFreeKilobytes
611 log.Printf("%s: FreeDiskSpace: %s\n", v, err)
615 // If the volume is full, timestamp it.
617 now := fmt.Sprintf("%d", time.Now().Unix())
618 os.Symlink(now, fullSymlink)
623 // FreeDiskSpace returns the number of unused 1k blocks available on
626 func (v *UnixVolume) FreeDiskSpace() (free uint64, err error) {
627 var fs syscall.Statfs_t
628 err = syscall.Statfs(v.Root, &fs)
630 // Statfs output is not guaranteed to measure free
631 // space in terms of 1K blocks.
632 free = fs.Bavail * uint64(fs.Bsize) / 1024
637 func (v *UnixVolume) String() string {
638 return fmt.Sprintf("[UnixVolume %s]", v.Root)
641 // Writable returns false if all future Put, Mtime, and Delete calls
642 // are expected to fail.
643 func (v *UnixVolume) Writable() bool {
647 // Replication returns the number of replicas promised by the
648 // underlying device (as specified in configuration).
649 func (v *UnixVolume) Replication() int {
650 return v.DirectoryReplication
653 // GetStorageClasses implements Volume
654 func (v *UnixVolume) GetStorageClasses() []string {
655 return v.StorageClasses
658 // InternalStats returns I/O and filesystem ops counters.
659 func (v *UnixVolume) InternalStats() interface{} {
663 // lock acquires the serialize lock, if one is in use. If ctx is done
664 // before the lock is acquired, lock returns ctx.Err() instead of
665 // acquiring the lock.
666 func (v *UnixVolume) lock(ctx context.Context) error {
670 locked := make(chan struct{})
687 // unlock releases the serialize lock, if one is in use.
688 func (v *UnixVolume) unlock() {
695 // lockfile and unlockfile use flock(2) to manage kernel file locks.
696 func (v *UnixVolume) lockfile(f *os.File) error {
697 v.os.stats.Tick(&v.os.stats.FlockOps)
698 err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
699 v.os.stats.TickErr(err)
703 func (v *UnixVolume) unlockfile(f *os.File) error {
704 err := syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
705 v.os.stats.TickErr(err)
709 // Where appropriate, translate a more specific filesystem error to an
710 // error recognized by handlers, like os.ErrNotExist.
711 func (v *UnixVolume) translateError(err error) error {
714 // stat() returns a PathError if the parent directory
715 // (not just the file itself) is missing
716 return os.ErrNotExist
722 var unixTrashLocRegexp = regexp.MustCompile(`/([0-9a-f]{32})\.trash\.(\d+)$`)
724 // EmptyTrash walks hierarchy looking for {hash}.trash.*
725 // and deletes those with deadline < now.
726 func (v *UnixVolume) EmptyTrash() {
727 var bytesDeleted, bytesInTrash int64
728 var blocksDeleted, blocksInTrash int
730 err := filepath.Walk(v.Root, func(path string, info os.FileInfo, err error) error {
732 log.Printf("EmptyTrash: filepath.Walk: %v: %v", path, err)
735 if info.Mode().IsDir() {
738 matches := unixTrashLocRegexp.FindStringSubmatch(path)
739 if len(matches) != 3 {
742 deadline, err := strconv.ParseInt(matches[2], 10, 64)
744 log.Printf("EmptyTrash: %v: ParseInt(%v): %v", path, matches[2], err)
747 bytesInTrash += info.Size()
749 if deadline > time.Now().Unix() {
752 err = v.os.Remove(path)
754 log.Printf("EmptyTrash: Remove %v: %v", path, err)
757 bytesDeleted += info.Size()
763 log.Printf("EmptyTrash error for %v: %v", v.String(), err)
766 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)
769 type unixStats struct {
781 func (s *unixStats) TickErr(err error) {
785 s.statsTicker.TickErr(err, fmt.Sprintf("%T", err))
788 type osWithStats struct {
792 func (o *osWithStats) Open(name string) (*os.File, error) {
793 o.stats.Tick(&o.stats.OpenOps)
794 f, err := os.Open(name)
799 func (o *osWithStats) OpenFile(name string, flag int, perm os.FileMode) (*os.File, error) {
800 o.stats.Tick(&o.stats.OpenOps)
801 f, err := os.OpenFile(name, flag, perm)
806 func (o *osWithStats) Remove(path string) error {
807 o.stats.Tick(&o.stats.UnlinkOps)
808 err := os.Remove(path)
813 func (o *osWithStats) Rename(a, b string) error {
814 o.stats.Tick(&o.stats.RenameOps)
815 err := os.Rename(a, b)
820 func (o *osWithStats) Stat(path string) (os.FileInfo, error) {
821 o.stats.Tick(&o.stats.StatOps)
822 fi, err := os.Stat(path)
827 func (o *osWithStats) TempFile(dir, base string) (*os.File, error) {
828 o.stats.Tick(&o.stats.CreateOps)
829 f, err := ioutil.TempFile(dir, base)