1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
26 type unixVolumeAdder struct {
30 // String implements flag.Value
31 func (s *unixVolumeAdder) String() string {
35 func (vs *unixVolumeAdder) Set(path string) error {
36 if dirs := strings.Split(path, ","); len(dirs) > 1 {
37 log.Print("DEPRECATED: using comma-separated volume list.")
38 for _, dir := range dirs {
39 if err := vs.Set(dir); err != nil {
45 vs.Config.Volumes = append(vs.Config.Volumes, &UnixVolume{
47 ReadOnly: deprecated.flagReadonly,
48 Serialize: deprecated.flagSerializeIO,
54 VolumeTypes = append(VolumeTypes, func() VolumeWithExamples { return &UnixVolume{} })
56 flag.Var(&unixVolumeAdder{theConfig}, "volumes", "see Volumes configuration")
57 flag.Var(&unixVolumeAdder{theConfig}, "volume", "see Volumes configuration")
60 // Discover adds a UnixVolume for every directory named "keep" that is
61 // located at the top level of a device- or tmpfs-backed mount point
62 // other than "/". It returns the number of volumes added.
63 func (vs *unixVolumeAdder) Discover() int {
65 f, err := os.Open(ProcMounts)
67 log.Fatalf("opening %s: %s", ProcMounts, err)
69 scanner := bufio.NewScanner(f)
71 args := strings.Fields(scanner.Text())
72 if err := scanner.Err(); err != nil {
73 log.Fatalf("reading %s: %s", ProcMounts, err)
75 dev, mount := args[0], args[1]
79 if dev != "tmpfs" && !strings.HasPrefix(dev, "/dev/") {
82 keepdir := mount + "/keep"
83 if st, err := os.Stat(keepdir); err != nil || !st.IsDir() {
86 // Set the -readonly flag (but only for this volume)
87 // if the filesystem is mounted readonly.
88 flagReadonlyWas := deprecated.flagReadonly
89 for _, fsopt := range strings.Split(args[3], ",") {
91 deprecated.flagReadonly = true
98 if err := vs.Set(keepdir); err != nil {
99 log.Printf("adding %q: %s", keepdir, err)
103 deprecated.flagReadonly = flagReadonlyWas
108 // A UnixVolume stores and retrieves blocks in a local directory.
109 type UnixVolume struct {
110 Root string // path to the volume's root directory
113 DirectoryReplication int
114 StorageClasses []string
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(),
487 log.Print("Error writing : ", err)
496 // Trash trashes the block data from the unix storage
497 // If TrashLifetime == 0, the block is deleted
498 // Else, the block is renamed as path/{loc}.trash.{deadline},
499 // where deadline = now + TrashLifetime
500 func (v *UnixVolume) Trash(loc string) error {
501 // Touch() must be called before calling Write() on a block. Touch()
502 // also uses lockfile(). This avoids a race condition between Write()
503 // and Trash() because either (a) the file will be trashed and Touch()
504 // will signal to the caller that the file is not present (and needs to
505 // be re-written), or (b) Touch() will update the file's timestamp and
506 // Trash() will read the correct up-to-date timestamp and choose not to
510 return MethodDisabledError
512 if err := v.lock(context.TODO()); err != nil {
516 p := v.blockPath(loc)
517 f, err := v.os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
522 if e := v.lockfile(f); e != nil {
525 defer v.unlockfile(f)
527 // If the block has been PUT in the last blobSignatureTTL
528 // seconds, return success without removing the block. This
529 // protects data from garbage collection until it is no longer
530 // possible for clients to retrieve the unreferenced blocks
531 // anyway (because the permission signatures have expired).
532 if fi, err := v.os.Stat(p); err != nil {
534 } else if time.Since(fi.ModTime()) < time.Duration(theConfig.BlobSignatureTTL) {
538 if theConfig.TrashLifetime == 0 {
539 return v.os.Remove(p)
541 return v.os.Rename(p, fmt.Sprintf("%v.trash.%d", p, time.Now().Add(theConfig.TrashLifetime.Duration()).Unix()))
544 // Untrash moves block from trash back into store
545 // Look for path/{loc}.trash.{deadline} in storage,
546 // and rename the first such file as path/{loc}
547 func (v *UnixVolume) Untrash(loc string) (err error) {
549 return MethodDisabledError
552 v.os.stats.Tick(&v.os.stats.ReaddirOps)
553 files, err := ioutil.ReadDir(v.blockDir(loc))
559 return os.ErrNotExist
563 prefix := fmt.Sprintf("%v.trash.", loc)
564 for _, f := range files {
565 if strings.HasPrefix(f.Name(), prefix) {
567 err = v.os.Rename(v.blockPath(f.Name()), v.blockPath(loc))
574 if foundTrash == false {
575 return os.ErrNotExist
581 // blockDir returns the fully qualified directory name for the directory
582 // where loc is (or would be) stored on this volume.
583 func (v *UnixVolume) blockDir(loc string) string {
584 return filepath.Join(v.Root, loc[0:3])
587 // blockPath returns the fully qualified pathname for the path to loc
589 func (v *UnixVolume) blockPath(loc string) string {
590 return filepath.Join(v.blockDir(loc), loc)
593 // IsFull returns true if the free space on the volume is less than
596 func (v *UnixVolume) IsFull() (isFull bool) {
597 fullSymlink := v.Root + "/full"
599 // Check if the volume has been marked as full in the last hour.
600 if link, err := os.Readlink(fullSymlink); err == nil {
601 if ts, err := strconv.Atoi(link); err == nil {
602 fulltime := time.Unix(int64(ts), 0)
603 if time.Since(fulltime).Hours() < 1.0 {
609 if avail, err := v.FreeDiskSpace(); err == nil {
610 isFull = avail < MinFreeKilobytes
612 log.Printf("%s: FreeDiskSpace: %s\n", v, err)
616 // If the volume is full, timestamp it.
618 now := fmt.Sprintf("%d", time.Now().Unix())
619 os.Symlink(now, fullSymlink)
624 // FreeDiskSpace returns the number of unused 1k blocks available on
627 func (v *UnixVolume) FreeDiskSpace() (free uint64, err error) {
628 var fs syscall.Statfs_t
629 err = syscall.Statfs(v.Root, &fs)
631 // Statfs output is not guaranteed to measure free
632 // space in terms of 1K blocks.
633 free = fs.Bavail * uint64(fs.Bsize) / 1024
638 func (v *UnixVolume) String() string {
639 return fmt.Sprintf("[UnixVolume %s]", v.Root)
642 // Writable returns false if all future Put, Mtime, and Delete calls
643 // are expected to fail.
644 func (v *UnixVolume) Writable() bool {
648 // Replication returns the number of replicas promised by the
649 // underlying device (as specified in configuration).
650 func (v *UnixVolume) Replication() int {
651 return v.DirectoryReplication
654 // GetStorageClasses implements Volume
655 func (v *UnixVolume) GetStorageClasses() []string {
656 return v.StorageClasses
659 // InternalStats returns I/O and filesystem ops counters.
660 func (v *UnixVolume) InternalStats() interface{} {
664 // lock acquires the serialize lock, if one is in use. If ctx is done
665 // before the lock is acquired, lock returns ctx.Err() instead of
666 // acquiring the lock.
667 func (v *UnixVolume) lock(ctx context.Context) error {
671 locked := make(chan struct{})
688 // unlock releases the serialize lock, if one is in use.
689 func (v *UnixVolume) unlock() {
696 // lockfile and unlockfile use flock(2) to manage kernel file locks.
697 func (v *UnixVolume) lockfile(f *os.File) error {
698 v.os.stats.Tick(&v.os.stats.FlockOps)
699 err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
700 v.os.stats.TickErr(err)
704 func (v *UnixVolume) unlockfile(f *os.File) error {
705 err := syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
706 v.os.stats.TickErr(err)
710 // Where appropriate, translate a more specific filesystem error to an
711 // error recognized by handlers, like os.ErrNotExist.
712 func (v *UnixVolume) translateError(err error) error {
715 // stat() returns a PathError if the parent directory
716 // (not just the file itself) is missing
717 return os.ErrNotExist
723 var unixTrashLocRegexp = regexp.MustCompile(`/([0-9a-f]{32})\.trash\.(\d+)$`)
725 // EmptyTrash walks hierarchy looking for {hash}.trash.*
726 // and deletes those with deadline < now.
727 func (v *UnixVolume) EmptyTrash() {
728 var bytesDeleted, bytesInTrash int64
729 var blocksDeleted, blocksInTrash int64
731 doFile := func(path string, info os.FileInfo) {
732 if info.Mode().IsDir() {
735 matches := unixTrashLocRegexp.FindStringSubmatch(path)
736 if len(matches) != 3 {
739 deadline, err := strconv.ParseInt(matches[2], 10, 64)
741 log.Printf("EmptyTrash: %v: ParseInt(%v): %v", path, matches[2], err)
744 atomic.AddInt64(&bytesInTrash, info.Size())
745 atomic.AddInt64(&blocksInTrash, 1)
746 if deadline > time.Now().Unix() {
749 err = v.os.Remove(path)
751 log.Printf("EmptyTrash: Remove %v: %v", path, err)
754 atomic.AddInt64(&bytesDeleted, info.Size())
755 atomic.AddInt64(&blocksDeleted, 1)
762 var wg sync.WaitGroup
763 todo := make(chan dirent, theConfig.EmptyTrashWorkers)
764 for i := 0; i < 1 || i < theConfig.EmptyTrashWorkers; i++ {
768 for e := range todo {
769 doFile(e.path, e.info)
774 err := filepath.Walk(v.Root, func(path string, info os.FileInfo, err error) error {
776 log.Printf("EmptyTrash: filepath.Walk: %v: %v", path, err)
779 todo <- dirent{path, info}
786 log.Printf("EmptyTrash error for %v: %v", v.String(), err)
789 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)
792 type unixStats struct {
804 func (s *unixStats) TickErr(err error) {
808 s.statsTicker.TickErr(err, fmt.Sprintf("%T", err))
811 type osWithStats struct {
815 func (o *osWithStats) Open(name string) (*os.File, error) {
816 o.stats.Tick(&o.stats.OpenOps)
817 f, err := os.Open(name)
822 func (o *osWithStats) OpenFile(name string, flag int, perm os.FileMode) (*os.File, error) {
823 o.stats.Tick(&o.stats.OpenOps)
824 f, err := os.OpenFile(name, flag, perm)
829 func (o *osWithStats) Remove(path string) error {
830 o.stats.Tick(&o.stats.UnlinkOps)
831 err := os.Remove(path)
836 func (o *osWithStats) Rename(a, b string) error {
837 o.stats.Tick(&o.stats.RenameOps)
838 err := os.Rename(a, b)
843 func (o *osWithStats) Stat(path string) (os.FileInfo, error) {
844 o.stats.Tick(&o.stats.StatOps)
845 fi, err := os.Stat(path)
850 func (o *osWithStats) TempFile(dir, base string) (*os.File, error) {
851 o.stats.Tick(&o.stats.CreateOps)
852 f, err := ioutil.TempFile(dir, base)