20 log "github.com/Sirupsen/logrus"
23 type unixVolumeAdder struct {
27 // String implements flag.Value
28 func (s *unixVolumeAdder) String() string {
32 func (vs *unixVolumeAdder) Set(path string) error {
33 if dirs := strings.Split(path, ","); len(dirs) > 1 {
34 log.Print("DEPRECATED: using comma-separated volume list.")
35 for _, dir := range dirs {
36 if err := vs.Set(dir); err != nil {
42 vs.Config.Volumes = append(vs.Config.Volumes, &UnixVolume{
44 ReadOnly: deprecated.flagReadonly,
45 Serialize: deprecated.flagSerializeIO,
51 VolumeTypes = append(VolumeTypes, func() VolumeWithExamples { return &UnixVolume{} })
53 flag.Var(&unixVolumeAdder{theConfig}, "volumes", "see Volumes configuration")
54 flag.Var(&unixVolumeAdder{theConfig}, "volume", "see Volumes configuration")
57 // Discover adds a UnixVolume for every directory named "keep" that is
58 // located at the top level of a device- or tmpfs-backed mount point
59 // other than "/". It returns the number of volumes added.
60 func (vs *unixVolumeAdder) Discover() int {
62 f, err := os.Open(ProcMounts)
64 log.Fatalf("opening %s: %s", ProcMounts, err)
66 scanner := bufio.NewScanner(f)
68 args := strings.Fields(scanner.Text())
69 if err := scanner.Err(); err != nil {
70 log.Fatalf("reading %s: %s", ProcMounts, err)
72 dev, mount := args[0], args[1]
76 if dev != "tmpfs" && !strings.HasPrefix(dev, "/dev/") {
79 keepdir := mount + "/keep"
80 if st, err := os.Stat(keepdir); err != nil || !st.IsDir() {
83 // Set the -readonly flag (but only for this volume)
84 // if the filesystem is mounted readonly.
85 flagReadonlyWas := deprecated.flagReadonly
86 for _, fsopt := range strings.Split(args[3], ",") {
88 deprecated.flagReadonly = true
95 if err := vs.Set(keepdir); err != nil {
96 log.Printf("adding %q: %s", keepdir, err)
100 deprecated.flagReadonly = flagReadonlyWas
105 // A UnixVolume stores and retrieves blocks in a local directory.
106 type UnixVolume struct {
107 Root string // path to the volume's root directory
110 DirectoryReplication int
112 // something to lock during IO, typically a sync.Mutex (or nil
119 // DeviceID returns a globally unique ID for the volume's root
120 // directory, consisting of the filesystem's UUID and the path from
121 // filesystem root to storage directory, joined by "/". For example,
122 // the DeviceID for a local directory "/mnt/xvda1/keep" might be
123 // "fa0b6166-3b55-4994-bd3f-92f4e00a1bb0/keep".
124 func (v *UnixVolume) DeviceID() string {
125 giveup := func(f string, args ...interface{}) string {
126 log.Printf(f+"; using blank DeviceID for volume %s", append(args, v)...)
129 buf, err := exec.Command("findmnt", "--noheadings", "--target", v.Root).CombinedOutput()
131 return giveup("findmnt: %s (%q)", err, buf)
133 findmnt := strings.Fields(string(buf))
134 if len(findmnt) < 2 {
135 return giveup("could not parse findmnt output: %q", buf)
137 fsRoot, dev := findmnt[0], findmnt[1]
139 absRoot, err := filepath.Abs(v.Root)
141 return giveup("resolving relative path %q: %s", v.Root, err)
143 realRoot, err := filepath.EvalSymlinks(absRoot)
145 return giveup("resolving symlinks in %q: %s", absRoot, err)
148 // Find path from filesystem root to realRoot
150 if strings.HasPrefix(realRoot, fsRoot+"/") {
151 fsPath = realRoot[len(fsRoot):]
152 } else if fsRoot == "/" {
154 } else if fsRoot == realRoot {
157 return giveup("findmnt reports mount point %q which is not a prefix of volume root %q", fsRoot, realRoot)
160 if !strings.HasPrefix(dev, "/") {
161 return giveup("mount %q device %q is not a path", fsRoot, dev)
164 fi, err := os.Stat(dev)
166 return giveup("stat %q: %s\n", dev, err)
168 ino := fi.Sys().(*syscall.Stat_t).Ino
170 // Find a symlink in /dev/disk/by-uuid/ whose target is (i.e.,
171 // has the same inode as) the mounted device
172 udir := "/dev/disk/by-uuid"
173 d, err := os.Open(udir)
175 return giveup("opening %q: %s", udir, err)
177 uuids, err := d.Readdirnames(0)
179 return giveup("reading %q: %s", udir, err)
181 for _, uuid := range uuids {
182 link := filepath.Join(udir, uuid)
183 fi, err = os.Stat(link)
185 log.Printf("error: stat %q: %s", link, err)
188 if fi.Sys().(*syscall.Stat_t).Ino == ino {
192 return giveup("could not find entry in %q matching %q", udir, dev)
195 // Examples implements VolumeWithExamples.
196 func (*UnixVolume) Examples() []Volume {
199 Root: "/mnt/local-disk",
201 DirectoryReplication: 1,
204 Root: "/mnt/network-disk",
206 DirectoryReplication: 2,
211 // Type implements Volume
212 func (v *UnixVolume) Type() string {
216 // Start implements Volume
217 func (v *UnixVolume) Start() error {
219 v.locker = &sync.Mutex{}
221 if !strings.HasPrefix(v.Root, "/") {
222 return fmt.Errorf("volume root does not start with '/': %q", v.Root)
224 if v.DirectoryReplication == 0 {
225 v.DirectoryReplication = 1
227 _, err := v.os.Stat(v.Root)
231 // Touch sets the timestamp for the given locator to the current time
232 func (v *UnixVolume) Touch(loc string) error {
234 return MethodDisabledError
236 p := v.blockPath(loc)
237 f, err := v.os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
242 if err := v.lock(context.TODO()); err != nil {
246 if e := v.lockfile(f); e != nil {
249 defer v.unlockfile(f)
250 ts := syscall.NsecToTimespec(time.Now().UnixNano())
251 v.os.stats.Tick(&v.os.stats.UtimesOps)
252 err = syscall.UtimesNano(p, []syscall.Timespec{ts, ts})
253 v.os.stats.TickErr(err)
257 // Mtime returns the stored timestamp for the given locator.
258 func (v *UnixVolume) Mtime(loc string) (time.Time, error) {
259 p := v.blockPath(loc)
260 fi, err := v.os.Stat(p)
262 return time.Time{}, err
264 return fi.ModTime(), nil
267 // Lock the locker (if one is in use), open the file for reading, and
268 // call the given function if and when the file is ready to read.
269 func (v *UnixVolume) getFunc(ctx context.Context, path string, fn func(io.Reader) error) error {
270 if err := v.lock(ctx); err != nil {
274 f, err := v.os.Open(path)
279 return fn(NewCountingReader(ioutil.NopCloser(f), v.os.stats.TickInBytes))
282 // stat is os.Stat() with some extra sanity checks.
283 func (v *UnixVolume) stat(path string) (os.FileInfo, error) {
284 stat, err := v.os.Stat(path)
288 } else if stat.Size() > BlockSize {
295 // Get retrieves a block, copies it to the given slice, and returns
296 // the number of bytes copied.
297 func (v *UnixVolume) Get(ctx context.Context, loc string, buf []byte) (int, error) {
298 return getWithPipe(ctx, loc, buf, v)
301 // ReadBlock implements BlockReader.
302 func (v *UnixVolume) ReadBlock(ctx context.Context, loc string, w io.Writer) error {
303 path := v.blockPath(loc)
304 stat, err := v.stat(path)
306 return v.translateError(err)
308 return v.getFunc(ctx, path, func(rdr io.Reader) error {
309 n, err := io.Copy(w, rdr)
310 if err == nil && n != stat.Size() {
311 err = io.ErrUnexpectedEOF
317 // Compare returns nil if Get(loc) would return the same content as
318 // expect. It is functionally equivalent to Get() followed by
319 // bytes.Compare(), but uses less memory.
320 func (v *UnixVolume) Compare(ctx context.Context, loc string, expect []byte) error {
321 path := v.blockPath(loc)
322 if _, err := v.stat(path); err != nil {
323 return v.translateError(err)
325 return v.getFunc(ctx, path, func(rdr io.Reader) error {
326 return compareReaderWithBuf(ctx, rdr, expect, loc[:32])
330 // Put stores a block of data identified by the locator string
331 // "loc". It returns nil on success. If the volume is full, it
332 // returns a FullError. If the write fails due to some other error,
333 // that error is returned.
334 func (v *UnixVolume) Put(ctx context.Context, loc string, block []byte) error {
335 return putWithPipe(ctx, loc, block, v)
338 // ReadBlock implements BlockWriter.
339 func (v *UnixVolume) WriteBlock(ctx context.Context, loc string, rdr io.Reader) error {
341 return MethodDisabledError
346 bdir := v.blockDir(loc)
347 if err := os.MkdirAll(bdir, 0755); err != nil {
348 log.Printf("%s: could not create directory %s: %s",
353 tmpfile, tmperr := v.os.TempFile(bdir, "tmp"+loc)
355 log.Printf("ioutil.TempFile(%s, tmp%s): %s", bdir, loc, tmperr)
359 bpath := v.blockPath(loc)
361 if err := v.lock(ctx); err != nil {
365 n, err := io.Copy(tmpfile, rdr)
366 v.os.stats.TickOutBytes(uint64(n))
368 log.Printf("%s: writing to %s: %s\n", v, bpath, err)
370 v.os.Remove(tmpfile.Name())
373 if err := tmpfile.Close(); err != nil {
374 log.Printf("closing %s: %s\n", tmpfile.Name(), err)
375 v.os.Remove(tmpfile.Name())
378 if err := v.os.Rename(tmpfile.Name(), bpath); err != nil {
379 log.Printf("rename %s %s: %s\n", tmpfile.Name(), bpath, err)
380 return v.os.Remove(tmpfile.Name())
385 // Status returns a VolumeStatus struct describing the volume's
386 // current state, or nil if an error occurs.
388 func (v *UnixVolume) Status() *VolumeStatus {
389 fi, err := v.os.Stat(v.Root)
391 log.Printf("%s: os.Stat: %s\n", v, err)
394 devnum := fi.Sys().(*syscall.Stat_t).Dev
396 var fs syscall.Statfs_t
397 if err := syscall.Statfs(v.Root, &fs); err != nil {
398 log.Printf("%s: statfs: %s\n", v, err)
401 // These calculations match the way df calculates disk usage:
402 // "free" space is measured by fs.Bavail, but "used" space
403 // uses fs.Blocks - fs.Bfree.
404 free := fs.Bavail * uint64(fs.Bsize)
405 used := (fs.Blocks - fs.Bfree) * uint64(fs.Bsize)
406 return &VolumeStatus{
414 var blockDirRe = regexp.MustCompile(`^[0-9a-f]+$`)
415 var blockFileRe = regexp.MustCompile(`^[0-9a-f]{32}$`)
417 // IndexTo writes (to the given Writer) a list of blocks found on this
418 // volume which begin with the specified prefix. If the prefix is an
419 // empty string, IndexTo writes a complete list of blocks.
421 // Each block is given in the format
423 // locator+size modification-time {newline}
427 // e4df392f86be161ca6ed3773a962b8f3+67108864 1388894303
428 // e4d41e6fd68460e0e3fc18cc746959d2+67108864 1377796043
429 // e4de7a2810f5554cd39b36d8ddb132ff+67108864 1388701136
431 func (v *UnixVolume) IndexTo(prefix string, w io.Writer) error {
433 rootdir, err := v.os.Open(v.Root)
437 defer rootdir.Close()
438 v.os.stats.Tick(&v.os.stats.ReaddirOps)
440 names, err := rootdir.Readdirnames(1)
443 } else if err != nil {
446 if !strings.HasPrefix(names[0], prefix) && !strings.HasPrefix(prefix, names[0]) {
447 // prefix excludes all blocks stored in this dir
450 if !blockDirRe.MatchString(names[0]) {
453 blockdirpath := filepath.Join(v.Root, names[0])
454 blockdir, err := v.os.Open(blockdirpath)
456 log.Print("Error reading ", blockdirpath, ": ", err)
460 v.os.stats.Tick(&v.os.stats.ReaddirOps)
462 fileInfo, err := blockdir.Readdir(1)
465 } else if err != nil {
466 log.Print("Error reading ", blockdirpath, ": ", err)
470 name := fileInfo[0].Name()
471 if !strings.HasPrefix(name, prefix) {
474 if !blockFileRe.MatchString(name) {
477 _, err = fmt.Fprint(w,
479 "+", fileInfo[0].Size(),
480 " ", fileInfo[0].ModTime().UnixNano(),
487 // Trash trashes the block data from the unix storage
488 // If TrashLifetime == 0, the block is deleted
489 // Else, the block is renamed as path/{loc}.trash.{deadline},
490 // where deadline = now + TrashLifetime
491 func (v *UnixVolume) Trash(loc string) error {
492 // Touch() must be called before calling Write() on a block. Touch()
493 // also uses lockfile(). This avoids a race condition between Write()
494 // and Trash() because either (a) the file will be trashed and Touch()
495 // will signal to the caller that the file is not present (and needs to
496 // be re-written), or (b) Touch() will update the file's timestamp and
497 // Trash() will read the correct up-to-date timestamp and choose not to
501 return MethodDisabledError
503 if err := v.lock(context.TODO()); err != nil {
507 p := v.blockPath(loc)
508 f, err := v.os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
513 if e := v.lockfile(f); e != nil {
516 defer v.unlockfile(f)
518 // If the block has been PUT in the last blobSignatureTTL
519 // seconds, return success without removing the block. This
520 // protects data from garbage collection until it is no longer
521 // possible for clients to retrieve the unreferenced blocks
522 // anyway (because the permission signatures have expired).
523 if fi, err := v.os.Stat(p); err != nil {
525 } else if time.Since(fi.ModTime()) < time.Duration(theConfig.BlobSignatureTTL) {
529 if theConfig.TrashLifetime == 0 {
530 return v.os.Remove(p)
532 return v.os.Rename(p, fmt.Sprintf("%v.trash.%d", p, time.Now().Add(theConfig.TrashLifetime.Duration()).Unix()))
535 // Untrash moves block from trash back into store
536 // Look for path/{loc}.trash.{deadline} in storage,
537 // and rename the first such file as path/{loc}
538 func (v *UnixVolume) Untrash(loc string) (err error) {
540 return MethodDisabledError
543 v.os.stats.Tick(&v.os.stats.ReaddirOps)
544 files, err := ioutil.ReadDir(v.blockDir(loc))
550 return os.ErrNotExist
554 prefix := fmt.Sprintf("%v.trash.", loc)
555 for _, f := range files {
556 if strings.HasPrefix(f.Name(), prefix) {
558 err = v.os.Rename(v.blockPath(f.Name()), v.blockPath(loc))
565 if foundTrash == false {
566 return os.ErrNotExist
572 // blockDir returns the fully qualified directory name for the directory
573 // where loc is (or would be) stored on this volume.
574 func (v *UnixVolume) blockDir(loc string) string {
575 return filepath.Join(v.Root, loc[0:3])
578 // blockPath returns the fully qualified pathname for the path to loc
580 func (v *UnixVolume) blockPath(loc string) string {
581 return filepath.Join(v.blockDir(loc), loc)
584 // IsFull returns true if the free space on the volume is less than
587 func (v *UnixVolume) IsFull() (isFull bool) {
588 fullSymlink := v.Root + "/full"
590 // Check if the volume has been marked as full in the last hour.
591 if link, err := os.Readlink(fullSymlink); err == nil {
592 if ts, err := strconv.Atoi(link); err == nil {
593 fulltime := time.Unix(int64(ts), 0)
594 if time.Since(fulltime).Hours() < 1.0 {
600 if avail, err := v.FreeDiskSpace(); err == nil {
601 isFull = avail < MinFreeKilobytes
603 log.Printf("%s: FreeDiskSpace: %s\n", v, err)
607 // If the volume is full, timestamp it.
609 now := fmt.Sprintf("%d", time.Now().Unix())
610 os.Symlink(now, fullSymlink)
615 // FreeDiskSpace returns the number of unused 1k blocks available on
618 func (v *UnixVolume) FreeDiskSpace() (free uint64, err error) {
619 var fs syscall.Statfs_t
620 err = syscall.Statfs(v.Root, &fs)
622 // Statfs output is not guaranteed to measure free
623 // space in terms of 1K blocks.
624 free = fs.Bavail * uint64(fs.Bsize) / 1024
629 func (v *UnixVolume) String() string {
630 return fmt.Sprintf("[UnixVolume %s]", v.Root)
633 // Writable returns false if all future Put, Mtime, and Delete calls
634 // are expected to fail.
635 func (v *UnixVolume) Writable() bool {
639 // Replication returns the number of replicas promised by the
640 // underlying device (as specified in configuration).
641 func (v *UnixVolume) Replication() int {
642 return v.DirectoryReplication
645 // InternalStats returns I/O and filesystem ops counters.
646 func (v *UnixVolume) InternalStats() interface{} {
650 // lock acquires the serialize lock, if one is in use. If ctx is done
651 // before the lock is acquired, lock returns ctx.Err() instead of
652 // acquiring the lock.
653 func (v *UnixVolume) lock(ctx context.Context) error {
657 locked := make(chan struct{})
674 // unlock releases the serialize lock, if one is in use.
675 func (v *UnixVolume) unlock() {
682 // lockfile and unlockfile use flock(2) to manage kernel file locks.
683 func (v *UnixVolume) lockfile(f *os.File) error {
684 v.os.stats.Tick(&v.os.stats.FlockOps)
685 err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
686 v.os.stats.TickErr(err)
690 func (v *UnixVolume) unlockfile(f *os.File) error {
691 err := syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
692 v.os.stats.TickErr(err)
696 // Where appropriate, translate a more specific filesystem error to an
697 // error recognized by handlers, like os.ErrNotExist.
698 func (v *UnixVolume) translateError(err error) error {
701 // stat() returns a PathError if the parent directory
702 // (not just the file itself) is missing
703 return os.ErrNotExist
709 var unixTrashLocRegexp = regexp.MustCompile(`/([0-9a-f]{32})\.trash\.(\d+)$`)
711 // EmptyTrash walks hierarchy looking for {hash}.trash.*
712 // and deletes those with deadline < now.
713 func (v *UnixVolume) EmptyTrash() {
714 var bytesDeleted, bytesInTrash int64
715 var blocksDeleted, blocksInTrash int
717 err := filepath.Walk(v.Root, func(path string, info os.FileInfo, err error) error {
719 log.Printf("EmptyTrash: filepath.Walk: %v: %v", path, err)
722 if info.Mode().IsDir() {
725 matches := unixTrashLocRegexp.FindStringSubmatch(path)
726 if len(matches) != 3 {
729 deadline, err := strconv.ParseInt(matches[2], 10, 64)
731 log.Printf("EmptyTrash: %v: ParseInt(%v): %v", path, matches[2], err)
734 bytesInTrash += info.Size()
736 if deadline > time.Now().Unix() {
739 err = v.os.Remove(path)
741 log.Printf("EmptyTrash: Remove %v: %v", path, err)
744 bytesDeleted += info.Size()
750 log.Printf("EmptyTrash error for %v: %v", v.String(), err)
753 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)
756 type unixStats struct {
768 func (s *unixStats) TickErr(err error) {
772 s.statsTicker.TickErr(err, fmt.Sprintf("%T", err))
775 type osWithStats struct {
779 func (o *osWithStats) Open(name string) (*os.File, error) {
780 o.stats.Tick(&o.stats.OpenOps)
781 f, err := os.Open(name)
786 func (o *osWithStats) OpenFile(name string, flag int, perm os.FileMode) (*os.File, error) {
787 o.stats.Tick(&o.stats.OpenOps)
788 f, err := os.OpenFile(name, flag, perm)
793 func (o *osWithStats) Remove(path string) error {
794 o.stats.Tick(&o.stats.UnlinkOps)
795 err := os.Remove(path)
800 func (o *osWithStats) Rename(a, b string) error {
801 o.stats.Tick(&o.stats.RenameOps)
802 err := os.Rename(a, b)
807 func (o *osWithStats) Stat(path string) (os.FileInfo, error) {
808 o.stats.Tick(&o.stats.StatOps)
809 fi, err := os.Stat(path)
814 func (o *osWithStats) TempFile(dir, base string) (*os.File, error) {
815 o.stats.Tick(&o.stats.CreateOps)
816 f, err := ioutil.TempFile(dir, base)