19 log "github.com/Sirupsen/logrus"
22 type unixVolumeAdder struct {
26 // String implements flag.Value
27 func (s *unixVolumeAdder) String() string {
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 {
41 vs.Config.Volumes = append(vs.Config.Volumes, &UnixVolume{
43 ReadOnly: deprecated.flagReadonly,
44 Serialize: deprecated.flagSerializeIO,
50 VolumeTypes = append(VolumeTypes, func() VolumeWithExamples { return &UnixVolume{} })
52 flag.Var(&unixVolumeAdder{theConfig}, "volumes", "see Volumes configuration")
53 flag.Var(&unixVolumeAdder{theConfig}, "volume", "see Volumes configuration")
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 {
61 f, err := os.Open(ProcMounts)
63 log.Fatalf("opening %s: %s", ProcMounts, err)
65 scanner := bufio.NewScanner(f)
67 args := strings.Fields(scanner.Text())
68 if err := scanner.Err(); err != nil {
69 log.Fatalf("reading %s: %s", ProcMounts, err)
71 dev, mount := args[0], args[1]
75 if dev != "tmpfs" && !strings.HasPrefix(dev, "/dev/") {
78 keepdir := mount + "/keep"
79 if st, err := os.Stat(keepdir); err != nil || !st.IsDir() {
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], ",") {
87 deprecated.flagReadonly = true
94 if err := vs.Set(keepdir); err != nil {
95 log.Printf("adding %q: %s", keepdir, err)
99 deprecated.flagReadonly = flagReadonlyWas
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
109 DirectoryReplication int
111 // something to lock during IO, typically a sync.Mutex (or nil
116 // Examples implements VolumeWithExamples.
117 func (*UnixVolume) Examples() []Volume {
120 Root: "/mnt/local-disk",
122 DirectoryReplication: 1,
125 Root: "/mnt/network-disk",
127 DirectoryReplication: 2,
132 // Type implements Volume
133 func (v *UnixVolume) Type() string {
137 // Start implements Volume
138 func (v *UnixVolume) Start() error {
140 v.locker = &sync.Mutex{}
142 if !strings.HasPrefix(v.Root, "/") {
143 return fmt.Errorf("volume root does not start with '/': %q", v.Root)
145 if v.DirectoryReplication == 0 {
146 v.DirectoryReplication = 1
148 _, err := os.Stat(v.Root)
152 // Touch sets the timestamp for the given locator to the current time
153 func (v *UnixVolume) Touch(loc string) error {
155 return MethodDisabledError
157 p := v.blockPath(loc)
158 f, err := os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
163 if err := v.lock(context.TODO()); err != nil {
167 if e := lockfile(f); e != nil {
171 ts := syscall.NsecToTimespec(time.Now().UnixNano())
172 return syscall.UtimesNano(p, []syscall.Timespec{ts, ts})
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)
180 return time.Time{}, err
182 return fi.ModTime(), nil
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 {
192 f, err := os.Open(path)
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)
206 } else if stat.Size() > BlockSize {
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)
219 func (v *UnixVolume) get(ctx context.Context, loc string, w *io.PipeWriter) {
220 path := v.blockPath(loc)
221 stat, err := v.stat(path)
223 w.CloseWithError(v.translateError(err))
226 err = v.getFunc(ctx, path, func(rdr io.Reader) error {
227 n, err := io.Copy(w, rdr)
228 if err == nil && n != stat.Size() {
229 err = io.ErrUnexpectedEOF
233 w.CloseWithError(err)
236 // Compare returns nil if Get(loc) would return the same content as
237 // expect. It is functionally equivalent to Get() followed by
238 // bytes.Compare(), but uses less memory.
239 func (v *UnixVolume) Compare(ctx context.Context, loc string, expect []byte) error {
240 path := v.blockPath(loc)
241 if _, err := v.stat(path); err != nil {
242 return v.translateError(err)
244 return v.getFunc(ctx, path, func(rdr io.Reader) error {
245 return compareReaderWithBuf(ctx, rdr, expect, loc[:32])
249 // Put stores a block of data identified by the locator string
250 // "loc". It returns nil on success. If the volume is full, it
251 // returns a FullError. If the write fails due to some other error,
252 // that error is returned.
253 func (v *UnixVolume) Put(ctx context.Context, loc string, block []byte) error {
254 return putWithPipe(ctx, loc, block, v.put)
257 func (v *UnixVolume) put(ctx context.Context, loc string, rdr io.ReadCloser) error {
259 return MethodDisabledError
264 bdir := v.blockDir(loc)
265 if err := os.MkdirAll(bdir, 0755); err != nil {
266 log.Printf("%s: could not create directory %s: %s",
271 tmpfile, tmperr := ioutil.TempFile(bdir, "tmp"+loc)
273 log.Printf("ioutil.TempFile(%s, tmp%s): %s", bdir, loc, tmperr)
277 bpath := v.blockPath(loc)
279 if err := v.lock(ctx); err != nil {
280 log.Println("lock err:", err)
284 if _, err := io.Copy(tmpfile, rdr); err != nil {
285 log.Printf("%s: writing to %s: %s\n", v, bpath, err)
287 os.Remove(tmpfile.Name())
290 if err := rdr.Close(); err != nil {
292 os.Remove(tmpfile.Name())
295 if err := tmpfile.Close(); err != nil {
296 log.Printf("closing %s: %s\n", tmpfile.Name(), err)
297 os.Remove(tmpfile.Name())
300 if err := os.Rename(tmpfile.Name(), bpath); err != nil {
301 log.Printf("rename %s %s: %s\n", tmpfile.Name(), bpath, err)
302 os.Remove(tmpfile.Name())
308 // Status returns a VolumeStatus struct describing the volume's
309 // current state, or nil if an error occurs.
311 func (v *UnixVolume) Status() *VolumeStatus {
312 var fs syscall.Statfs_t
315 if fi, err := os.Stat(v.Root); err == nil {
316 devnum = fi.Sys().(*syscall.Stat_t).Dev
318 log.Printf("%s: os.Stat: %s\n", v, err)
322 err := syscall.Statfs(v.Root, &fs)
324 log.Printf("%s: statfs: %s\n", v, err)
327 // These calculations match the way df calculates disk usage:
328 // "free" space is measured by fs.Bavail, but "used" space
329 // uses fs.Blocks - fs.Bfree.
330 free := fs.Bavail * uint64(fs.Bsize)
331 used := (fs.Blocks - fs.Bfree) * uint64(fs.Bsize)
332 return &VolumeStatus{
340 var blockDirRe = regexp.MustCompile(`^[0-9a-f]+$`)
341 var blockFileRe = regexp.MustCompile(`^[0-9a-f]{32}$`)
343 // IndexTo writes (to the given Writer) a list of blocks found on this
344 // volume which begin with the specified prefix. If the prefix is an
345 // empty string, IndexTo writes a complete list of blocks.
347 // Each block is given in the format
349 // locator+size modification-time {newline}
353 // e4df392f86be161ca6ed3773a962b8f3+67108864 1388894303
354 // e4d41e6fd68460e0e3fc18cc746959d2+67108864 1377796043
355 // e4de7a2810f5554cd39b36d8ddb132ff+67108864 1388701136
357 func (v *UnixVolume) IndexTo(prefix string, w io.Writer) error {
359 rootdir, err := os.Open(v.Root)
363 defer rootdir.Close()
365 names, err := rootdir.Readdirnames(1)
368 } else if err != nil {
371 if !strings.HasPrefix(names[0], prefix) && !strings.HasPrefix(prefix, names[0]) {
372 // prefix excludes all blocks stored in this dir
375 if !blockDirRe.MatchString(names[0]) {
378 blockdirpath := filepath.Join(v.Root, names[0])
379 blockdir, err := os.Open(blockdirpath)
381 log.Print("Error reading ", blockdirpath, ": ", err)
386 fileInfo, err := blockdir.Readdir(1)
389 } else if err != nil {
390 log.Print("Error reading ", blockdirpath, ": ", err)
394 name := fileInfo[0].Name()
395 if !strings.HasPrefix(name, prefix) {
398 if !blockFileRe.MatchString(name) {
401 _, err = fmt.Fprint(w,
403 "+", fileInfo[0].Size(),
404 " ", fileInfo[0].ModTime().UnixNano(),
411 // Trash trashes the block data from the unix storage
412 // If TrashLifetime == 0, the block is deleted
413 // Else, the block is renamed as path/{loc}.trash.{deadline},
414 // where deadline = now + TrashLifetime
415 func (v *UnixVolume) Trash(loc string) error {
416 // Touch() must be called before calling Write() on a block. Touch()
417 // also uses lockfile(). This avoids a race condition between Write()
418 // and Trash() because either (a) the file will be trashed and Touch()
419 // will signal to the caller that the file is not present (and needs to
420 // be re-written), or (b) Touch() will update the file's timestamp and
421 // Trash() will read the correct up-to-date timestamp and choose not to
425 return MethodDisabledError
427 if err := v.lock(context.TODO()); err != nil {
431 p := v.blockPath(loc)
432 f, err := os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
437 if e := lockfile(f); e != nil {
442 // If the block has been PUT in the last blobSignatureTTL
443 // seconds, return success without removing the block. This
444 // protects data from garbage collection until it is no longer
445 // possible for clients to retrieve the unreferenced blocks
446 // anyway (because the permission signatures have expired).
447 if fi, err := os.Stat(p); err != nil {
449 } else if time.Since(fi.ModTime()) < time.Duration(theConfig.BlobSignatureTTL) {
453 if theConfig.TrashLifetime == 0 {
456 return os.Rename(p, fmt.Sprintf("%v.trash.%d", p, time.Now().Add(theConfig.TrashLifetime.Duration()).Unix()))
459 // Untrash moves block from trash back into store
460 // Look for path/{loc}.trash.{deadline} in storage,
461 // and rename the first such file as path/{loc}
462 func (v *UnixVolume) Untrash(loc string) (err error) {
464 return MethodDisabledError
467 files, err := ioutil.ReadDir(v.blockDir(loc))
473 return os.ErrNotExist
477 prefix := fmt.Sprintf("%v.trash.", loc)
478 for _, f := range files {
479 if strings.HasPrefix(f.Name(), prefix) {
481 err = os.Rename(v.blockPath(f.Name()), v.blockPath(loc))
488 if foundTrash == false {
489 return os.ErrNotExist
495 // blockDir returns the fully qualified directory name for the directory
496 // where loc is (or would be) stored on this volume.
497 func (v *UnixVolume) blockDir(loc string) string {
498 return filepath.Join(v.Root, loc[0:3])
501 // blockPath returns the fully qualified pathname for the path to loc
503 func (v *UnixVolume) blockPath(loc string) string {
504 return filepath.Join(v.blockDir(loc), loc)
507 // IsFull returns true if the free space on the volume is less than
510 func (v *UnixVolume) IsFull() (isFull bool) {
511 fullSymlink := v.Root + "/full"
513 // Check if the volume has been marked as full in the last hour.
514 if link, err := os.Readlink(fullSymlink); err == nil {
515 if ts, err := strconv.Atoi(link); err == nil {
516 fulltime := time.Unix(int64(ts), 0)
517 if time.Since(fulltime).Hours() < 1.0 {
523 if avail, err := v.FreeDiskSpace(); err == nil {
524 isFull = avail < MinFreeKilobytes
526 log.Printf("%s: FreeDiskSpace: %s\n", v, err)
530 // If the volume is full, timestamp it.
532 now := fmt.Sprintf("%d", time.Now().Unix())
533 os.Symlink(now, fullSymlink)
538 // FreeDiskSpace returns the number of unused 1k blocks available on
541 func (v *UnixVolume) FreeDiskSpace() (free uint64, err error) {
542 var fs syscall.Statfs_t
543 err = syscall.Statfs(v.Root, &fs)
545 // Statfs output is not guaranteed to measure free
546 // space in terms of 1K blocks.
547 free = fs.Bavail * uint64(fs.Bsize) / 1024
552 func (v *UnixVolume) String() string {
553 return fmt.Sprintf("[UnixVolume %s]", v.Root)
556 // Writable returns false if all future Put, Mtime, and Delete calls
557 // are expected to fail.
558 func (v *UnixVolume) Writable() bool {
562 // Replication returns the number of replicas promised by the
563 // underlying device (as specified in configuration).
564 func (v *UnixVolume) Replication() int {
565 return v.DirectoryReplication
568 // lock acquires the serialize lock, if one is in use. If ctx is done
569 // before the lock is acquired, lock returns ctx.Err() instead of
570 // acquiring the lock.
571 func (v *UnixVolume) lock(ctx context.Context) error {
575 locked := make(chan struct{})
582 log.Print("ctx Done")
584 log.Print("waiting <-locked")
586 log.Print("unlocking")
591 log.Print("got lock")
596 // unlock releases the serialize lock, if one is in use.
597 func (v *UnixVolume) unlock() {
604 // lockfile and unlockfile use flock(2) to manage kernel file locks.
605 func lockfile(f *os.File) error {
606 return syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
609 func unlockfile(f *os.File) error {
610 return syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
613 // Where appropriate, translate a more specific filesystem error to an
614 // error recognized by handlers, like os.ErrNotExist.
615 func (v *UnixVolume) translateError(err error) error {
618 // stat() returns a PathError if the parent directory
619 // (not just the file itself) is missing
620 return os.ErrNotExist
626 var unixTrashLocRegexp = regexp.MustCompile(`/([0-9a-f]{32})\.trash\.(\d+)$`)
628 // EmptyTrash walks hierarchy looking for {hash}.trash.*
629 // and deletes those with deadline < now.
630 func (v *UnixVolume) EmptyTrash() {
631 var bytesDeleted, bytesInTrash int64
632 var blocksDeleted, blocksInTrash int
634 err := filepath.Walk(v.Root, func(path string, info os.FileInfo, err error) error {
636 log.Printf("EmptyTrash: filepath.Walk: %v: %v", path, err)
639 if info.Mode().IsDir() {
642 matches := unixTrashLocRegexp.FindStringSubmatch(path)
643 if len(matches) != 3 {
646 deadline, err := strconv.ParseInt(matches[2], 10, 64)
648 log.Printf("EmptyTrash: %v: ParseInt(%v): %v", path, matches[2], err)
651 bytesInTrash += info.Size()
653 if deadline > time.Now().Unix() {
656 err = os.Remove(path)
658 log.Printf("EmptyTrash: Remove %v: %v", path, err)
661 bytesDeleted += info.Size()
667 log.Printf("EmptyTrash error for %v: %v", v.String(), err)
670 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)