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)
219 // ReadBlock implements BlockReader.
220 func (v *UnixVolume) ReadBlock(ctx context.Context, loc string, w io.Writer) error {
221 path := v.blockPath(loc)
222 stat, err := v.stat(path)
224 return v.translateError(err)
226 return 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
235 // Compare returns nil if Get(loc) would return the same content as
236 // expect. It is functionally equivalent to Get() followed by
237 // bytes.Compare(), but uses less memory.
238 func (v *UnixVolume) Compare(ctx context.Context, loc string, expect []byte) error {
239 path := v.blockPath(loc)
240 if _, err := v.stat(path); err != nil {
241 return v.translateError(err)
243 return v.getFunc(ctx, path, func(rdr io.Reader) error {
244 return compareReaderWithBuf(ctx, rdr, expect, loc[:32])
248 // Put stores a block of data identified by the locator string
249 // "loc". It returns nil on success. If the volume is full, it
250 // returns a FullError. If the write fails due to some other error,
251 // that error is returned.
252 func (v *UnixVolume) Put(ctx context.Context, loc string, block []byte) error {
253 return putWithPipe(ctx, loc, block, v)
256 // ReadBlock implements BlockWriter.
257 func (v *UnixVolume) WriteBlock(ctx context.Context, loc string, rdr io.Reader) 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 {
283 if _, err := io.Copy(tmpfile, rdr); err != nil {
284 log.Printf("%s: writing to %s: %s\n", v, bpath, err)
286 os.Remove(tmpfile.Name())
289 if err := tmpfile.Close(); err != nil {
290 log.Printf("closing %s: %s\n", tmpfile.Name(), err)
291 os.Remove(tmpfile.Name())
294 if err := os.Rename(tmpfile.Name(), bpath); err != nil {
295 log.Printf("rename %s %s: %s\n", tmpfile.Name(), bpath, err)
296 os.Remove(tmpfile.Name())
302 // Status returns a VolumeStatus struct describing the volume's
303 // current state, or nil if an error occurs.
305 func (v *UnixVolume) Status() *VolumeStatus {
306 var fs syscall.Statfs_t
309 if fi, err := os.Stat(v.Root); err == nil {
310 devnum = fi.Sys().(*syscall.Stat_t).Dev
312 log.Printf("%s: os.Stat: %s\n", v, err)
316 err := syscall.Statfs(v.Root, &fs)
318 log.Printf("%s: statfs: %s\n", v, err)
321 // These calculations match the way df calculates disk usage:
322 // "free" space is measured by fs.Bavail, but "used" space
323 // uses fs.Blocks - fs.Bfree.
324 free := fs.Bavail * uint64(fs.Bsize)
325 used := (fs.Blocks - fs.Bfree) * uint64(fs.Bsize)
326 return &VolumeStatus{
334 var blockDirRe = regexp.MustCompile(`^[0-9a-f]+$`)
335 var blockFileRe = regexp.MustCompile(`^[0-9a-f]{32}$`)
337 // IndexTo writes (to the given Writer) a list of blocks found on this
338 // volume which begin with the specified prefix. If the prefix is an
339 // empty string, IndexTo writes a complete list of blocks.
341 // Each block is given in the format
343 // locator+size modification-time {newline}
347 // e4df392f86be161ca6ed3773a962b8f3+67108864 1388894303
348 // e4d41e6fd68460e0e3fc18cc746959d2+67108864 1377796043
349 // e4de7a2810f5554cd39b36d8ddb132ff+67108864 1388701136
351 func (v *UnixVolume) IndexTo(prefix string, w io.Writer) error {
353 rootdir, err := os.Open(v.Root)
357 defer rootdir.Close()
359 names, err := rootdir.Readdirnames(1)
362 } else if err != nil {
365 if !strings.HasPrefix(names[0], prefix) && !strings.HasPrefix(prefix, names[0]) {
366 // prefix excludes all blocks stored in this dir
369 if !blockDirRe.MatchString(names[0]) {
372 blockdirpath := filepath.Join(v.Root, names[0])
373 blockdir, err := os.Open(blockdirpath)
375 log.Print("Error reading ", blockdirpath, ": ", err)
380 fileInfo, err := blockdir.Readdir(1)
383 } else if err != nil {
384 log.Print("Error reading ", blockdirpath, ": ", err)
388 name := fileInfo[0].Name()
389 if !strings.HasPrefix(name, prefix) {
392 if !blockFileRe.MatchString(name) {
395 _, err = fmt.Fprint(w,
397 "+", fileInfo[0].Size(),
398 " ", fileInfo[0].ModTime().UnixNano(),
405 // Trash trashes the block data from the unix storage
406 // If TrashLifetime == 0, the block is deleted
407 // Else, the block is renamed as path/{loc}.trash.{deadline},
408 // where deadline = now + TrashLifetime
409 func (v *UnixVolume) Trash(loc string) error {
410 // Touch() must be called before calling Write() on a block. Touch()
411 // also uses lockfile(). This avoids a race condition between Write()
412 // and Trash() because either (a) the file will be trashed and Touch()
413 // will signal to the caller that the file is not present (and needs to
414 // be re-written), or (b) Touch() will update the file's timestamp and
415 // Trash() will read the correct up-to-date timestamp and choose not to
419 return MethodDisabledError
421 if err := v.lock(context.TODO()); err != nil {
425 p := v.blockPath(loc)
426 f, err := os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
431 if e := lockfile(f); e != nil {
436 // If the block has been PUT in the last blobSignatureTTL
437 // seconds, return success without removing the block. This
438 // protects data from garbage collection until it is no longer
439 // possible for clients to retrieve the unreferenced blocks
440 // anyway (because the permission signatures have expired).
441 if fi, err := os.Stat(p); err != nil {
443 } else if time.Since(fi.ModTime()) < time.Duration(theConfig.BlobSignatureTTL) {
447 if theConfig.TrashLifetime == 0 {
450 return os.Rename(p, fmt.Sprintf("%v.trash.%d", p, time.Now().Add(theConfig.TrashLifetime.Duration()).Unix()))
453 // Untrash moves block from trash back into store
454 // Look for path/{loc}.trash.{deadline} in storage,
455 // and rename the first such file as path/{loc}
456 func (v *UnixVolume) Untrash(loc string) (err error) {
458 return MethodDisabledError
461 files, err := ioutil.ReadDir(v.blockDir(loc))
467 return os.ErrNotExist
471 prefix := fmt.Sprintf("%v.trash.", loc)
472 for _, f := range files {
473 if strings.HasPrefix(f.Name(), prefix) {
475 err = os.Rename(v.blockPath(f.Name()), v.blockPath(loc))
482 if foundTrash == false {
483 return os.ErrNotExist
489 // blockDir returns the fully qualified directory name for the directory
490 // where loc is (or would be) stored on this volume.
491 func (v *UnixVolume) blockDir(loc string) string {
492 return filepath.Join(v.Root, loc[0:3])
495 // blockPath returns the fully qualified pathname for the path to loc
497 func (v *UnixVolume) blockPath(loc string) string {
498 return filepath.Join(v.blockDir(loc), loc)
501 // IsFull returns true if the free space on the volume is less than
504 func (v *UnixVolume) IsFull() (isFull bool) {
505 fullSymlink := v.Root + "/full"
507 // Check if the volume has been marked as full in the last hour.
508 if link, err := os.Readlink(fullSymlink); err == nil {
509 if ts, err := strconv.Atoi(link); err == nil {
510 fulltime := time.Unix(int64(ts), 0)
511 if time.Since(fulltime).Hours() < 1.0 {
517 if avail, err := v.FreeDiskSpace(); err == nil {
518 isFull = avail < MinFreeKilobytes
520 log.Printf("%s: FreeDiskSpace: %s\n", v, err)
524 // If the volume is full, timestamp it.
526 now := fmt.Sprintf("%d", time.Now().Unix())
527 os.Symlink(now, fullSymlink)
532 // FreeDiskSpace returns the number of unused 1k blocks available on
535 func (v *UnixVolume) FreeDiskSpace() (free uint64, err error) {
536 var fs syscall.Statfs_t
537 err = syscall.Statfs(v.Root, &fs)
539 // Statfs output is not guaranteed to measure free
540 // space in terms of 1K blocks.
541 free = fs.Bavail * uint64(fs.Bsize) / 1024
546 func (v *UnixVolume) String() string {
547 return fmt.Sprintf("[UnixVolume %s]", v.Root)
550 // Writable returns false if all future Put, Mtime, and Delete calls
551 // are expected to fail.
552 func (v *UnixVolume) Writable() bool {
556 // Replication returns the number of replicas promised by the
557 // underlying device (as specified in configuration).
558 func (v *UnixVolume) Replication() int {
559 return v.DirectoryReplication
562 // lock acquires the serialize lock, if one is in use. If ctx is done
563 // before the lock is acquired, lock returns ctx.Err() instead of
564 // acquiring the lock.
565 func (v *UnixVolume) lock(ctx context.Context) error {
569 locked := make(chan struct{})
586 // unlock releases the serialize lock, if one is in use.
587 func (v *UnixVolume) unlock() {
594 // lockfile and unlockfile use flock(2) to manage kernel file locks.
595 func lockfile(f *os.File) error {
596 return syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
599 func unlockfile(f *os.File) error {
600 return syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
603 // Where appropriate, translate a more specific filesystem error to an
604 // error recognized by handlers, like os.ErrNotExist.
605 func (v *UnixVolume) translateError(err error) error {
608 // stat() returns a PathError if the parent directory
609 // (not just the file itself) is missing
610 return os.ErrNotExist
616 var unixTrashLocRegexp = regexp.MustCompile(`/([0-9a-f]{32})\.trash\.(\d+)$`)
618 // EmptyTrash walks hierarchy looking for {hash}.trash.*
619 // and deletes those with deadline < now.
620 func (v *UnixVolume) EmptyTrash() {
621 var bytesDeleted, bytesInTrash int64
622 var blocksDeleted, blocksInTrash int
624 err := filepath.Walk(v.Root, func(path string, info os.FileInfo, err error) error {
626 log.Printf("EmptyTrash: filepath.Walk: %v: %v", path, err)
629 if info.Mode().IsDir() {
632 matches := unixTrashLocRegexp.FindStringSubmatch(path)
633 if len(matches) != 3 {
636 deadline, err := strconv.ParseInt(matches[2], 10, 64)
638 log.Printf("EmptyTrash: %v: ParseInt(%v): %v", path, matches[2], err)
641 bytesInTrash += info.Size()
643 if deadline > time.Now().Unix() {
646 err = os.Remove(path)
648 log.Printf("EmptyTrash: Remove %v: %v", path, err)
651 bytesDeleted += info.Size()
657 log.Printf("EmptyTrash error for %v: %v", v.String(), err)
660 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)