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{v.Root, devnum, free, used}
328 var blockDirRe = regexp.MustCompile(`^[0-9a-f]+$`)
329 var blockFileRe = regexp.MustCompile(`^[0-9a-f]{32}$`)
331 // IndexTo writes (to the given Writer) a list of blocks found on this
332 // volume which begin with the specified prefix. If the prefix is an
333 // empty string, IndexTo writes a complete list of blocks.
335 // Each block is given in the format
337 // locator+size modification-time {newline}
341 // e4df392f86be161ca6ed3773a962b8f3+67108864 1388894303
342 // e4d41e6fd68460e0e3fc18cc746959d2+67108864 1377796043
343 // e4de7a2810f5554cd39b36d8ddb132ff+67108864 1388701136
345 func (v *UnixVolume) IndexTo(prefix string, w io.Writer) error {
347 rootdir, err := os.Open(v.Root)
351 defer rootdir.Close()
353 names, err := rootdir.Readdirnames(1)
356 } else if err != nil {
359 if !strings.HasPrefix(names[0], prefix) && !strings.HasPrefix(prefix, names[0]) {
360 // prefix excludes all blocks stored in this dir
363 if !blockDirRe.MatchString(names[0]) {
366 blockdirpath := filepath.Join(v.Root, names[0])
367 blockdir, err := os.Open(blockdirpath)
369 log.Print("Error reading ", blockdirpath, ": ", err)
374 fileInfo, err := blockdir.Readdir(1)
377 } else if err != nil {
378 log.Print("Error reading ", blockdirpath, ": ", err)
382 name := fileInfo[0].Name()
383 if !strings.HasPrefix(name, prefix) {
386 if !blockFileRe.MatchString(name) {
389 _, err = fmt.Fprint(w,
391 "+", fileInfo[0].Size(),
392 " ", fileInfo[0].ModTime().UnixNano(),
399 // Trash trashes the block data from the unix storage
400 // If TrashLifetime == 0, the block is deleted
401 // Else, the block is renamed as path/{loc}.trash.{deadline},
402 // where deadline = now + TrashLifetime
403 func (v *UnixVolume) Trash(loc string) error {
404 // Touch() must be called before calling Write() on a block. Touch()
405 // also uses lockfile(). This avoids a race condition between Write()
406 // and Trash() because either (a) the file will be trashed and Touch()
407 // will signal to the caller that the file is not present (and needs to
408 // be re-written), or (b) Touch() will update the file's timestamp and
409 // Trash() will read the correct up-to-date timestamp and choose not to
413 return MethodDisabledError
417 defer v.locker.Unlock()
419 p := v.blockPath(loc)
420 f, err := os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
425 if e := lockfile(f); e != nil {
430 // If the block has been PUT in the last blobSignatureTTL
431 // seconds, return success without removing the block. This
432 // protects data from garbage collection until it is no longer
433 // possible for clients to retrieve the unreferenced blocks
434 // anyway (because the permission signatures have expired).
435 if fi, err := os.Stat(p); err != nil {
437 } else if time.Since(fi.ModTime()) < time.Duration(theConfig.BlobSignatureTTL) {
441 if theConfig.TrashLifetime == 0 {
444 return os.Rename(p, fmt.Sprintf("%v.trash.%d", p, time.Now().Add(theConfig.TrashLifetime.Duration()).Unix()))
447 // Untrash moves block from trash back into store
448 // Look for path/{loc}.trash.{deadline} in storage,
449 // and rename the first such file as path/{loc}
450 func (v *UnixVolume) Untrash(loc string) (err error) {
452 return MethodDisabledError
455 files, err := ioutil.ReadDir(v.blockDir(loc))
461 return os.ErrNotExist
465 prefix := fmt.Sprintf("%v.trash.", loc)
466 for _, f := range files {
467 if strings.HasPrefix(f.Name(), prefix) {
469 err = os.Rename(v.blockPath(f.Name()), v.blockPath(loc))
476 if foundTrash == false {
477 return os.ErrNotExist
483 // blockDir returns the fully qualified directory name for the directory
484 // where loc is (or would be) stored on this volume.
485 func (v *UnixVolume) blockDir(loc string) string {
486 return filepath.Join(v.Root, loc[0:3])
489 // blockPath returns the fully qualified pathname for the path to loc
491 func (v *UnixVolume) blockPath(loc string) string {
492 return filepath.Join(v.blockDir(loc), loc)
495 // IsFull returns true if the free space on the volume is less than
498 func (v *UnixVolume) IsFull() (isFull bool) {
499 fullSymlink := v.Root + "/full"
501 // Check if the volume has been marked as full in the last hour.
502 if link, err := os.Readlink(fullSymlink); err == nil {
503 if ts, err := strconv.Atoi(link); err == nil {
504 fulltime := time.Unix(int64(ts), 0)
505 if time.Since(fulltime).Hours() < 1.0 {
511 if avail, err := v.FreeDiskSpace(); err == nil {
512 isFull = avail < MinFreeKilobytes
514 log.Printf("%s: FreeDiskSpace: %s\n", v, err)
518 // If the volume is full, timestamp it.
520 now := fmt.Sprintf("%d", time.Now().Unix())
521 os.Symlink(now, fullSymlink)
526 // FreeDiskSpace returns the number of unused 1k blocks available on
529 func (v *UnixVolume) FreeDiskSpace() (free uint64, err error) {
530 var fs syscall.Statfs_t
531 err = syscall.Statfs(v.Root, &fs)
533 // Statfs output is not guaranteed to measure free
534 // space in terms of 1K blocks.
535 free = fs.Bavail * uint64(fs.Bsize) / 1024
540 func (v *UnixVolume) String() string {
541 return fmt.Sprintf("[UnixVolume %s]", v.Root)
544 // Writable returns false if all future Put, Mtime, and Delete calls
545 // are expected to fail.
546 func (v *UnixVolume) Writable() bool {
550 // Replication returns the number of replicas promised by the
551 // underlying device (as specified in configuration).
552 func (v *UnixVolume) Replication() int {
553 return v.DirectoryReplication
556 // lockfile and unlockfile use flock(2) to manage kernel file locks.
557 func lockfile(f *os.File) error {
558 return syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
561 func unlockfile(f *os.File) error {
562 return syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
565 // Where appropriate, translate a more specific filesystem error to an
566 // error recognized by handlers, like os.ErrNotExist.
567 func (v *UnixVolume) translateError(err error) error {
570 // stat() returns a PathError if the parent directory
571 // (not just the file itself) is missing
572 return os.ErrNotExist
578 var unixTrashLocRegexp = regexp.MustCompile(`/([0-9a-f]{32})\.trash\.(\d+)$`)
580 // EmptyTrash walks hierarchy looking for {hash}.trash.*
581 // and deletes those with deadline < now.
582 func (v *UnixVolume) EmptyTrash() {
583 var bytesDeleted, bytesInTrash int64
584 var blocksDeleted, blocksInTrash int
586 err := filepath.Walk(v.Root, func(path string, info os.FileInfo, err error) error {
588 log.Printf("EmptyTrash: filepath.Walk: %v: %v", path, err)
591 if info.Mode().IsDir() {
594 matches := unixTrashLocRegexp.FindStringSubmatch(path)
595 if len(matches) != 3 {
598 deadline, err := strconv.ParseInt(matches[2], 10, 64)
600 log.Printf("EmptyTrash: %v: ParseInt(%v): %v", path, matches[2], err)
603 bytesInTrash += info.Size()
605 if deadline > time.Now().Unix() {
608 err = os.Remove(path)
610 log.Printf("EmptyTrash: Remove %v: %v", path, err)
613 bytesDeleted += info.Size()
619 log.Printf("EmptyTrash error for %v: %v", v.String(), err)
622 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)