19 // A UnixVolume stores and retrieves blocks in a local directory.
20 type UnixVolume struct {
21 // path to the volume's root directory
23 // something to lock during IO, typically a sync.Mutex (or nil
29 // Touch sets the timestamp for the given locator to the current time
30 func (v *UnixVolume) Touch(loc string) error {
32 return MethodDisabledError
35 f, err := os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
42 defer v.locker.Unlock()
44 if e := lockfile(f); e != nil {
48 now := time.Now().Unix()
49 utime := syscall.Utimbuf{now, now}
50 return syscall.Utime(p, &utime)
53 // Mtime returns the stored timestamp for the given locator.
54 func (v *UnixVolume) Mtime(loc string) (time.Time, error) {
58 return time.Time{}, err
60 return fi.ModTime(), nil
63 // Lock the locker (if one is in use), open the file for reading, and
64 // call the given function if and when the file is ready to read.
65 func (v *UnixVolume) getFunc(path string, fn func(io.Reader) error) error {
68 defer v.locker.Unlock()
70 f, err := os.Open(path)
78 // stat is os.Stat() with some extra sanity checks.
79 func (v *UnixVolume) stat(path string) (os.FileInfo, error) {
80 stat, err := os.Stat(path)
84 } else if stat.Size() > BlockSize {
91 // Get retrieves a block identified by the locator string "loc", and
92 // returns its contents as a byte slice.
94 // Get returns a nil buffer IFF it returns a non-nil error.
95 func (v *UnixVolume) Get(loc string) ([]byte, error) {
96 path := v.blockPath(loc)
97 stat, err := v.stat(path)
101 buf := bufs.Get(int(stat.Size()))
102 err = v.getFunc(path, func(rdr io.Reader) error {
103 _, err = io.ReadFull(rdr, buf)
113 // Compare returns nil if Get(loc) would return the same content as
114 // expect. It is functionally equivalent to Get() followed by
115 // bytes.Compare(), but uses less memory.
116 func (v *UnixVolume) Compare(loc string, expect []byte) error {
117 path := v.blockPath(loc)
118 stat, err := v.stat(path)
123 if int64(bufLen) > stat.Size() {
124 bufLen = int(stat.Size())
127 buf := make([]byte, bufLen)
128 return v.getFunc(path, func(rdr io.Reader) error {
129 // Loop invariants: all data read so far matched what
130 // we expected, and the first N bytes of cmp are
131 // expected to equal the next N bytes read from
134 n, err := rdr.Read(buf)
135 if n > len(cmp) || bytes.Compare(cmp[:n], buf[:n]) != 0 {
136 return collisionOrCorrupt(loc[:32], expect[:len(expect)-len(cmp)], buf[:n], rdr)
141 return collisionOrCorrupt(loc[:32], expect[:len(expect)-len(cmp)], nil, nil)
144 } else if err != nil {
151 // Put stores a block of data identified by the locator string
152 // "loc". It returns nil on success. If the volume is full, it
153 // returns a FullError. If the write fails due to some other error,
154 // that error is returned.
155 func (v *UnixVolume) Put(loc string, block []byte) error {
157 return MethodDisabledError
162 bdir := v.blockDir(loc)
163 if err := os.MkdirAll(bdir, 0755); err != nil {
164 log.Printf("%s: could not create directory %s: %s",
169 tmpfile, tmperr := ioutil.TempFile(bdir, "tmp"+loc)
171 log.Printf("ioutil.TempFile(%s, tmp%s): %s", bdir, loc, tmperr)
174 bpath := v.blockPath(loc)
178 defer v.locker.Unlock()
180 if _, err := tmpfile.Write(block); err != nil {
181 log.Printf("%s: writing to %s: %s\n", v, bpath, err)
183 os.Remove(tmpfile.Name())
186 if err := tmpfile.Close(); err != nil {
187 log.Printf("closing %s: %s\n", tmpfile.Name(), err)
188 os.Remove(tmpfile.Name())
191 if err := os.Rename(tmpfile.Name(), bpath); err != nil {
192 log.Printf("rename %s %s: %s\n", tmpfile.Name(), bpath, err)
193 os.Remove(tmpfile.Name())
199 // Status returns a VolumeStatus struct describing the volume's
200 // current state, or nil if an error occurs.
202 func (v *UnixVolume) Status() *VolumeStatus {
203 var fs syscall.Statfs_t
206 if fi, err := os.Stat(v.root); err == nil {
207 devnum = fi.Sys().(*syscall.Stat_t).Dev
209 log.Printf("%s: os.Stat: %s\n", v, err)
213 err := syscall.Statfs(v.root, &fs)
215 log.Printf("%s: statfs: %s\n", v, err)
218 // These calculations match the way df calculates disk usage:
219 // "free" space is measured by fs.Bavail, but "used" space
220 // uses fs.Blocks - fs.Bfree.
221 free := fs.Bavail * uint64(fs.Bsize)
222 used := (fs.Blocks - fs.Bfree) * uint64(fs.Bsize)
223 return &VolumeStatus{v.root, devnum, free, used}
226 var blockDirRe = regexp.MustCompile(`^[0-9a-f]+$`)
228 // IndexTo writes (to the given Writer) a list of blocks found on this
229 // volume which begin with the specified prefix. If the prefix is an
230 // empty string, IndexTo writes a complete list of blocks.
232 // Each block is given in the format
234 // locator+size modification-time {newline}
238 // e4df392f86be161ca6ed3773a962b8f3+67108864 1388894303
239 // e4d41e6fd68460e0e3fc18cc746959d2+67108864 1377796043
240 // e4de7a2810f5554cd39b36d8ddb132ff+67108864 1388701136
242 func (v *UnixVolume) IndexTo(prefix string, w io.Writer) error {
243 var lastErr error = nil
244 rootdir, err := os.Open(v.root)
248 defer rootdir.Close()
250 names, err := rootdir.Readdirnames(1)
253 } else if err != nil {
256 if !strings.HasPrefix(names[0], prefix) && !strings.HasPrefix(prefix, names[0]) {
257 // prefix excludes all blocks stored in this dir
260 if !blockDirRe.MatchString(names[0]) {
263 blockdirpath := filepath.Join(v.root, names[0])
264 blockdir, err := os.Open(blockdirpath)
266 log.Print("Error reading ", blockdirpath, ": ", err)
271 fileInfo, err := blockdir.Readdir(1)
274 } else if err != nil {
275 log.Print("Error reading ", blockdirpath, ": ", err)
279 name := fileInfo[0].Name()
280 if !strings.HasPrefix(name, prefix) {
283 _, err = fmt.Fprint(w,
285 "+", fileInfo[0].Size(),
286 " ", fileInfo[0].ModTime().Unix(),
293 // Delete deletes the block data from the unix storage
294 func (v *UnixVolume) Delete(loc string) error {
295 // Touch() must be called before calling Write() on a block. Touch()
296 // also uses lockfile(). This avoids a race condition between Write()
297 // and Delete() because either (a) the file will be deleted and Touch()
298 // will signal to the caller that the file is not present (and needs to
299 // be re-written), or (b) Touch() will update the file's timestamp and
300 // Delete() will read the correct up-to-date timestamp and choose not to
304 return MethodDisabledError
308 defer v.locker.Unlock()
310 p := v.blockPath(loc)
311 f, err := os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
316 if e := lockfile(f); e != nil {
321 // If the block has been PUT in the last blob_signature_ttl
322 // seconds, return success without removing the block. This
323 // protects data from garbage collection until it is no longer
324 // possible for clients to retrieve the unreferenced blocks
325 // anyway (because the permission signatures have expired).
326 if fi, err := os.Stat(p); err != nil {
329 if time.Since(fi.ModTime()) < blob_signature_ttl {
336 // blockDir returns the fully qualified directory name for the directory
337 // where loc is (or would be) stored on this volume.
338 func (v *UnixVolume) blockDir(loc string) string {
339 return filepath.Join(v.root, loc[0:3])
342 // blockPath returns the fully qualified pathname for the path to loc
344 func (v *UnixVolume) blockPath(loc string) string {
345 return filepath.Join(v.blockDir(loc), loc)
348 // IsFull returns true if the free space on the volume is less than
351 func (v *UnixVolume) IsFull() (isFull bool) {
352 fullSymlink := v.root + "/full"
354 // Check if the volume has been marked as full in the last hour.
355 if link, err := os.Readlink(fullSymlink); err == nil {
356 if ts, err := strconv.Atoi(link); err == nil {
357 fulltime := time.Unix(int64(ts), 0)
358 if time.Since(fulltime).Hours() < 1.0 {
364 if avail, err := v.FreeDiskSpace(); err == nil {
365 isFull = avail < MinFreeKilobytes
367 log.Printf("%s: FreeDiskSpace: %s\n", v, err)
371 // If the volume is full, timestamp it.
373 now := fmt.Sprintf("%d", time.Now().Unix())
374 os.Symlink(now, fullSymlink)
379 // FreeDiskSpace returns the number of unused 1k blocks available on
382 func (v *UnixVolume) FreeDiskSpace() (free uint64, err error) {
383 var fs syscall.Statfs_t
384 err = syscall.Statfs(v.root, &fs)
386 // Statfs output is not guaranteed to measure free
387 // space in terms of 1K blocks.
388 free = fs.Bavail * uint64(fs.Bsize) / 1024
393 func (v *UnixVolume) String() string {
394 return fmt.Sprintf("[UnixVolume %s]", v.root)
397 // Writable returns false if all future Put, Mtime, and Delete calls are expected to fail.
398 func (v *UnixVolume) Writable() bool {
402 // lockfile and unlockfile use flock(2) to manage kernel file locks.
403 func lockfile(f *os.File) error {
404 return syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
407 func unlockfile(f *os.File) error {
408 return syscall.Flock(int(f.Fd()), syscall.LOCK_UN)