21 type unixVolumeAdder struct {
25 // String implements flag.Value
26 func (s *unixVolumeAdder) String() string {
30 func (vs *unixVolumeAdder) Set(path string) error {
31 if dirs := strings.Split(path, ","); len(dirs) > 1 {
32 log.Print("DEPRECATED: using comma-separated volume list.")
33 for _, dir := range dirs {
34 if err := vs.Set(dir); err != nil {
40 vs.Config.Volumes = append(vs.Config.Volumes, &UnixVolume{
42 ReadOnly: deprecated.flagReadonly,
43 Serialize: deprecated.flagSerializeIO,
49 VolumeTypes = append(VolumeTypes, func() VolumeWithExamples { return &UnixVolume{} })
51 flag.Var(&unixVolumeAdder{theConfig}, "volumes", "see Volumes configuration")
52 flag.Var(&unixVolumeAdder{theConfig}, "volume", "see Volumes configuration")
55 // Discover adds a UnixVolume for every directory named "keep" that is
56 // located at the top level of a device- or tmpfs-backed mount point
57 // other than "/". It returns the number of volumes added.
58 func (vs *unixVolumeAdder) Discover() int {
60 f, err := os.Open(ProcMounts)
62 log.Fatalf("opening %s: %s", ProcMounts, err)
64 scanner := bufio.NewScanner(f)
66 args := strings.Fields(scanner.Text())
67 if err := scanner.Err(); err != nil {
68 log.Fatalf("reading %s: %s", ProcMounts, err)
70 dev, mount := args[0], args[1]
74 if dev != "tmpfs" && !strings.HasPrefix(dev, "/dev/") {
77 keepdir := mount + "/keep"
78 if st, err := os.Stat(keepdir); err != nil || !st.IsDir() {
81 // Set the -readonly flag (but only for this volume)
82 // if the filesystem is mounted readonly.
83 flagReadonlyWas := deprecated.flagReadonly
84 for _, fsopt := range strings.Split(args[3], ",") {
86 deprecated.flagReadonly = true
93 if err := vs.Set(keepdir); err != nil {
94 log.Printf("adding %q: %s", keepdir, err)
98 deprecated.flagReadonly = flagReadonlyWas
103 // A UnixVolume stores and retrieves blocks in a local directory.
104 type UnixVolume struct {
105 Root string // path to the volume's root directory
108 DirectoryReplication int
110 // something to lock during IO, typically a sync.Mutex (or nil
115 // Examples implements VolumeWithExamples.
116 func (*UnixVolume) Examples() []Volume {
119 Root: "/mnt/local-disk",
121 DirectoryReplication: 1,
124 Root: "/mnt/network-disk",
126 DirectoryReplication: 2,
131 // Type implements Volume
132 func (v *UnixVolume) Type() string {
136 // Start implements Volume
137 func (v *UnixVolume) Start() error {
139 v.locker = &sync.Mutex{}
141 if !strings.HasPrefix(v.Root, "/") {
142 return fmt.Errorf("volume root does not start with '/': %q", v.Root)
144 if v.DirectoryReplication == 0 {
145 v.DirectoryReplication = 1
147 _, err := os.Stat(v.Root)
151 // Touch sets the timestamp for the given locator to the current time
152 func (v *UnixVolume) Touch(loc string) error {
154 return MethodDisabledError
156 p := v.blockPath(loc)
157 f, err := os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
164 defer v.locker.Unlock()
166 if e := lockfile(f); e != nil {
170 ts := syscall.NsecToTimespec(time.Now().UnixNano())
171 return syscall.UtimesNano(p, []syscall.Timespec{ts, ts})
174 // Mtime returns the stored timestamp for the given locator.
175 func (v *UnixVolume) Mtime(loc string) (time.Time, error) {
176 p := v.blockPath(loc)
177 fi, err := os.Stat(p)
179 return time.Time{}, err
181 return fi.ModTime(), nil
184 // Lock the locker (if one is in use), open the file for reading, and
185 // call the given function if and when the file is ready to read.
186 func (v *UnixVolume) getFunc(ctx context.Context, path string, fn func(io.Reader) error) error {
189 defer v.locker.Unlock()
191 if ctx.Err() != nil {
194 f, err := os.Open(path)
202 // stat is os.Stat() with some extra sanity checks.
203 func (v *UnixVolume) stat(path string) (os.FileInfo, error) {
204 stat, err := os.Stat(path)
208 } else if stat.Size() > BlockSize {
215 // Get retrieves a block, copies it to the given slice, and returns
216 // the number of bytes copied.
217 func (v *UnixVolume) Get(ctx context.Context, loc string, buf []byte) (int, error) {
218 path := v.blockPath(loc)
219 stat, err := v.stat(path)
221 return 0, v.translateError(err)
223 if stat.Size() > int64(len(buf)) {
224 return 0, TooLongError
227 size := int(stat.Size())
228 err = v.getFunc(ctx, path, func(rdr io.Reader) error {
229 read, err = io.ReadFull(rdr, buf[:size])
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 {
254 return MethodDisabledError
259 bdir := v.blockDir(loc)
260 if err := os.MkdirAll(bdir, 0755); err != nil {
261 log.Printf("%s: could not create directory %s: %s",
266 tmpfile, tmperr := ioutil.TempFile(bdir, "tmp"+loc)
268 log.Printf("ioutil.TempFile(%s, tmp%s): %s", bdir, loc, tmperr)
271 bpath := v.blockPath(loc)
275 defer v.locker.Unlock()
282 if _, err := tmpfile.Write(block); err != nil {
283 log.Printf("%s: writing to %s: %s\n", v, bpath, err)
285 os.Remove(tmpfile.Name())
288 if err := tmpfile.Close(); err != nil {
289 log.Printf("closing %s: %s\n", tmpfile.Name(), err)
290 os.Remove(tmpfile.Name())
293 if err := os.Rename(tmpfile.Name(), bpath); err != nil {
294 log.Printf("rename %s %s: %s\n", tmpfile.Name(), bpath, err)
295 os.Remove(tmpfile.Name())
301 // Status returns a VolumeStatus struct describing the volume's
302 // current state, or nil if an error occurs.
304 func (v *UnixVolume) Status() *VolumeStatus {
305 var fs syscall.Statfs_t
308 if fi, err := os.Stat(v.Root); err == nil {
309 devnum = fi.Sys().(*syscall.Stat_t).Dev
311 log.Printf("%s: os.Stat: %s\n", v, err)
315 err := syscall.Statfs(v.Root, &fs)
317 log.Printf("%s: statfs: %s\n", v, err)
320 // These calculations match the way df calculates disk usage:
321 // "free" space is measured by fs.Bavail, but "used" space
322 // uses fs.Blocks - fs.Bfree.
323 free := fs.Bavail * uint64(fs.Bsize)
324 used := (fs.Blocks - fs.Bfree) * uint64(fs.Bsize)
325 return &VolumeStatus{
333 var blockDirRe = regexp.MustCompile(`^[0-9a-f]+$`)
334 var blockFileRe = regexp.MustCompile(`^[0-9a-f]{32}$`)
336 // IndexTo writes (to the given Writer) a list of blocks found on this
337 // volume which begin with the specified prefix. If the prefix is an
338 // empty string, IndexTo writes a complete list of blocks.
340 // Each block is given in the format
342 // locator+size modification-time {newline}
346 // e4df392f86be161ca6ed3773a962b8f3+67108864 1388894303
347 // e4d41e6fd68460e0e3fc18cc746959d2+67108864 1377796043
348 // e4de7a2810f5554cd39b36d8ddb132ff+67108864 1388701136
350 func (v *UnixVolume) IndexTo(prefix string, w io.Writer) error {
352 rootdir, err := os.Open(v.Root)
356 defer rootdir.Close()
358 names, err := rootdir.Readdirnames(1)
361 } else if err != nil {
364 if !strings.HasPrefix(names[0], prefix) && !strings.HasPrefix(prefix, names[0]) {
365 // prefix excludes all blocks stored in this dir
368 if !blockDirRe.MatchString(names[0]) {
371 blockdirpath := filepath.Join(v.Root, names[0])
372 blockdir, err := os.Open(blockdirpath)
374 log.Print("Error reading ", blockdirpath, ": ", err)
379 fileInfo, err := blockdir.Readdir(1)
382 } else if err != nil {
383 log.Print("Error reading ", blockdirpath, ": ", err)
387 name := fileInfo[0].Name()
388 if !strings.HasPrefix(name, prefix) {
391 if !blockFileRe.MatchString(name) {
394 _, err = fmt.Fprint(w,
396 "+", fileInfo[0].Size(),
397 " ", fileInfo[0].ModTime().UnixNano(),
404 // Trash trashes the block data from the unix storage
405 // If TrashLifetime == 0, the block is deleted
406 // Else, the block is renamed as path/{loc}.trash.{deadline},
407 // where deadline = now + TrashLifetime
408 func (v *UnixVolume) Trash(loc string) error {
409 // Touch() must be called before calling Write() on a block. Touch()
410 // also uses lockfile(). This avoids a race condition between Write()
411 // and Trash() because either (a) the file will be trashed and Touch()
412 // will signal to the caller that the file is not present (and needs to
413 // be re-written), or (b) Touch() will update the file's timestamp and
414 // Trash() will read the correct up-to-date timestamp and choose not to
418 return MethodDisabledError
422 defer v.locker.Unlock()
424 p := v.blockPath(loc)
425 f, err := os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
430 if e := lockfile(f); e != nil {
435 // If the block has been PUT in the last blobSignatureTTL
436 // seconds, return success without removing the block. This
437 // protects data from garbage collection until it is no longer
438 // possible for clients to retrieve the unreferenced blocks
439 // anyway (because the permission signatures have expired).
440 if fi, err := os.Stat(p); err != nil {
442 } else if time.Since(fi.ModTime()) < time.Duration(theConfig.BlobSignatureTTL) {
446 if theConfig.TrashLifetime == 0 {
449 return os.Rename(p, fmt.Sprintf("%v.trash.%d", p, time.Now().Add(theConfig.TrashLifetime.Duration()).Unix()))
452 // Untrash moves block from trash back into store
453 // Look for path/{loc}.trash.{deadline} in storage,
454 // and rename the first such file as path/{loc}
455 func (v *UnixVolume) Untrash(loc string) (err error) {
457 return MethodDisabledError
460 files, err := ioutil.ReadDir(v.blockDir(loc))
466 return os.ErrNotExist
470 prefix := fmt.Sprintf("%v.trash.", loc)
471 for _, f := range files {
472 if strings.HasPrefix(f.Name(), prefix) {
474 err = os.Rename(v.blockPath(f.Name()), v.blockPath(loc))
481 if foundTrash == false {
482 return os.ErrNotExist
488 // blockDir returns the fully qualified directory name for the directory
489 // where loc is (or would be) stored on this volume.
490 func (v *UnixVolume) blockDir(loc string) string {
491 return filepath.Join(v.Root, loc[0:3])
494 // blockPath returns the fully qualified pathname for the path to loc
496 func (v *UnixVolume) blockPath(loc string) string {
497 return filepath.Join(v.blockDir(loc), loc)
500 // IsFull returns true if the free space on the volume is less than
503 func (v *UnixVolume) IsFull() (isFull bool) {
504 fullSymlink := v.Root + "/full"
506 // Check if the volume has been marked as full in the last hour.
507 if link, err := os.Readlink(fullSymlink); err == nil {
508 if ts, err := strconv.Atoi(link); err == nil {
509 fulltime := time.Unix(int64(ts), 0)
510 if time.Since(fulltime).Hours() < 1.0 {
516 if avail, err := v.FreeDiskSpace(); err == nil {
517 isFull = avail < MinFreeKilobytes
519 log.Printf("%s: FreeDiskSpace: %s\n", v, err)
523 // If the volume is full, timestamp it.
525 now := fmt.Sprintf("%d", time.Now().Unix())
526 os.Symlink(now, fullSymlink)
531 // FreeDiskSpace returns the number of unused 1k blocks available on
534 func (v *UnixVolume) FreeDiskSpace() (free uint64, err error) {
535 var fs syscall.Statfs_t
536 err = syscall.Statfs(v.Root, &fs)
538 // Statfs output is not guaranteed to measure free
539 // space in terms of 1K blocks.
540 free = fs.Bavail * uint64(fs.Bsize) / 1024
545 func (v *UnixVolume) String() string {
546 return fmt.Sprintf("[UnixVolume %s]", v.Root)
549 // Writable returns false if all future Put, Mtime, and Delete calls
550 // are expected to fail.
551 func (v *UnixVolume) Writable() bool {
555 // Replication returns the number of replicas promised by the
556 // underlying device (as specified in configuration).
557 func (v *UnixVolume) Replication() int {
558 return v.DirectoryReplication
561 // lockfile and unlockfile use flock(2) to manage kernel file locks.
562 func lockfile(f *os.File) error {
563 return syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
566 func unlockfile(f *os.File) error {
567 return syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
570 // Where appropriate, translate a more specific filesystem error to an
571 // error recognized by handlers, like os.ErrNotExist.
572 func (v *UnixVolume) translateError(err error) error {
575 // stat() returns a PathError if the parent directory
576 // (not just the file itself) is missing
577 return os.ErrNotExist
583 var unixTrashLocRegexp = regexp.MustCompile(`/([0-9a-f]{32})\.trash\.(\d+)$`)
585 // EmptyTrash walks hierarchy looking for {hash}.trash.*
586 // and deletes those with deadline < now.
587 func (v *UnixVolume) EmptyTrash() {
588 var bytesDeleted, bytesInTrash int64
589 var blocksDeleted, blocksInTrash int
591 err := filepath.Walk(v.Root, func(path string, info os.FileInfo, err error) error {
593 log.Printf("EmptyTrash: filepath.Walk: %v: %v", path, err)
596 if info.Mode().IsDir() {
599 matches := unixTrashLocRegexp.FindStringSubmatch(path)
600 if len(matches) != 3 {
603 deadline, err := strconv.ParseInt(matches[2], 10, 64)
605 log.Printf("EmptyTrash: %v: ParseInt(%v): %v", path, matches[2], err)
608 bytesInTrash += info.Size()
610 if deadline > time.Now().Unix() {
613 err = os.Remove(path)
615 log.Printf("EmptyTrash: Remove %v: %v", path, err)
618 bytesDeleted += info.Size()
624 log.Printf("EmptyTrash error for %v: %v", v.String(), err)
627 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)