19 // A UnixVolume stores and retrieves blocks in a local directory.
20 type UnixVolume struct {
21 root string // path to the volume's root directory
27 func (v *UnixVolume) Touch(loc string) error {
29 return MethodDisabledError
32 f, err := os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
39 defer v.mutex.Unlock()
41 if e := lockfile(f); e != nil {
45 now := time.Now().Unix()
46 utime := syscall.Utimbuf{now, now}
47 return syscall.Utime(p, &utime)
50 func (v *UnixVolume) Mtime(loc string) (time.Time, error) {
52 if fi, err := os.Stat(p); err != nil {
53 return time.Time{}, err
55 return fi.ModTime(), nil
59 // Open the given file, apply the serialize lock if enabled, and call
60 // the given function if and when the file is ready to read.
61 func (v *UnixVolume) getFunc(path string, fn func(io.Reader) error) error {
62 f, err := os.Open(path)
69 defer v.mutex.Unlock()
74 // stat is os.Stat() with some extra sanity checks.
75 func (v *UnixVolume) stat(path string) (os.FileInfo, error) {
76 stat, err := os.Stat(path)
80 } else if stat.Size() > BLOCKSIZE {
87 // Get retrieves a block identified by the locator string "loc", and
88 // returns its contents as a byte slice.
90 // Get returns a nil buffer IFF it returns a non-nil error.
91 func (v *UnixVolume) Get(loc string) ([]byte, error) {
92 path := v.blockPath(loc)
93 stat, err := v.stat(path)
97 buf := bufs.Get(int(stat.Size()))
98 err = v.getFunc(path, func(rdr io.Reader) error {
99 _, err = io.ReadFull(rdr, buf)
109 // Compare returns nil if Get(loc) would return the same content as
110 // cmp. It is functionally equivalent to Get() followed by
111 // bytes.Compare(), but uses less memory.
112 func (v *UnixVolume) Compare(loc string, expect []byte) error {
113 path := v.blockPath(loc)
114 stat, err := v.stat(path)
119 if int64(bufLen) > stat.Size() {
120 bufLen = int(stat.Size())
123 buf := make([]byte, bufLen)
124 return v.getFunc(path, func(rdr io.Reader) error {
125 // Loop invariants: all data read so far matched what
126 // we expected, and the first N bytes of cmp are
127 // expected to equal the next N bytes read from
130 n, err := rdr.Read(buf)
131 if n > len(cmp) || bytes.Compare(cmp[:n], buf[:n]) != 0 {
132 return collisionOrCorrupt(loc[:32], expect[:len(expect)-len(cmp)], buf[:n], rdr)
137 return collisionOrCorrupt(loc[:32], expect[:len(expect)-len(cmp)], nil, nil)
140 } else if err != nil {
147 // Put stores a block of data identified by the locator string
148 // "loc". It returns nil on success. If the volume is full, it
149 // returns a FullError. If the write fails due to some other error,
150 // that error is returned.
151 func (v *UnixVolume) Put(loc string, block []byte) error {
153 return MethodDisabledError
158 bdir := v.blockDir(loc)
159 if err := os.MkdirAll(bdir, 0755); err != nil {
160 log.Printf("%s: could not create directory %s: %s",
165 tmpfile, tmperr := ioutil.TempFile(bdir, "tmp"+loc)
167 log.Printf("ioutil.TempFile(%s, tmp%s): %s", bdir, loc, tmperr)
170 bpath := v.blockPath(loc)
174 defer v.mutex.Unlock()
176 if _, err := tmpfile.Write(block); err != nil {
177 log.Printf("%s: writing to %s: %s\n", v, bpath, err)
179 os.Remove(tmpfile.Name())
182 if err := tmpfile.Close(); err != nil {
183 log.Printf("closing %s: %s\n", tmpfile.Name(), err)
184 os.Remove(tmpfile.Name())
187 if err := os.Rename(tmpfile.Name(), bpath); err != nil {
188 log.Printf("rename %s %s: %s\n", tmpfile.Name(), bpath, err)
189 os.Remove(tmpfile.Name())
195 // Status returns a VolumeStatus struct describing the volume's
196 // current state, or nil if an error occurs.
198 func (v *UnixVolume) Status() *VolumeStatus {
199 var fs syscall.Statfs_t
202 if fi, err := os.Stat(v.root); err == nil {
203 devnum = fi.Sys().(*syscall.Stat_t).Dev
205 log.Printf("%s: os.Stat: %s\n", v, err)
209 err := syscall.Statfs(v.root, &fs)
211 log.Printf("%s: statfs: %s\n", v, err)
214 // These calculations match the way df calculates disk usage:
215 // "free" space is measured by fs.Bavail, but "used" space
216 // uses fs.Blocks - fs.Bfree.
217 free := fs.Bavail * uint64(fs.Bsize)
218 used := (fs.Blocks - fs.Bfree) * uint64(fs.Bsize)
219 return &VolumeStatus{v.root, devnum, free, used}
222 var blockDirRe = regexp.MustCompile(`^[0-9a-f]+$`)
224 // IndexTo writes (to the given Writer) a list of blocks found on this
225 // volume which begin with the specified prefix. If the prefix is an
226 // empty string, IndexTo writes a complete list of blocks.
228 // Each block is given in the format
230 // locator+size modification-time {newline}
234 // e4df392f86be161ca6ed3773a962b8f3+67108864 1388894303
235 // e4d41e6fd68460e0e3fc18cc746959d2+67108864 1377796043
236 // e4de7a2810f5554cd39b36d8ddb132ff+67108864 1388701136
238 func (v *UnixVolume) IndexTo(prefix string, w io.Writer) error {
239 var lastErr error = nil
240 rootdir, err := os.Open(v.root)
244 defer rootdir.Close()
246 names, err := rootdir.Readdirnames(1)
249 } else if err != nil {
252 if !strings.HasPrefix(names[0], prefix) && !strings.HasPrefix(prefix, names[0]) {
253 // prefix excludes all blocks stored in this dir
256 if !blockDirRe.MatchString(names[0]) {
259 blockdirpath := filepath.Join(v.root, names[0])
260 blockdir, err := os.Open(blockdirpath)
262 log.Print("Error reading ", blockdirpath, ": ", err)
267 fileInfo, err := blockdir.Readdir(1)
270 } else if err != nil {
271 log.Print("Error reading ", blockdirpath, ": ", err)
275 name := fileInfo[0].Name()
276 if !strings.HasPrefix(name, prefix) {
279 _, err = fmt.Fprint(w,
281 "+", fileInfo[0].Size(),
282 " ", fileInfo[0].ModTime().Unix(),
289 func (v *UnixVolume) Delete(loc string) error {
290 // Touch() must be called before calling Write() on a block. Touch()
291 // also uses lockfile(). This avoids a race condition between Write()
292 // and Delete() because either (a) the file will be deleted and Touch()
293 // will signal to the caller that the file is not present (and needs to
294 // be re-written), or (b) Touch() will update the file's timestamp and
295 // Delete() will read the correct up-to-date timestamp and choose not to
299 return MethodDisabledError
303 defer v.mutex.Unlock()
305 p := v.blockPath(loc)
306 f, err := os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
311 if e := lockfile(f); e != nil {
316 // If the block has been PUT in the last blob_signature_ttl
317 // seconds, return success without removing the block. This
318 // protects data from garbage collection until it is no longer
319 // possible for clients to retrieve the unreferenced blocks
320 // anyway (because the permission signatures have expired).
321 if fi, err := os.Stat(p); err != nil {
324 if time.Since(fi.ModTime()) < blob_signature_ttl {
331 // blockDir returns the fully qualified directory name for the directory
332 // where loc is (or would be) stored on this volume.
333 func (v *UnixVolume) blockDir(loc string) string {
334 return filepath.Join(v.root, loc[0:3])
337 // blockPath returns the fully qualified pathname for the path to loc
339 func (v *UnixVolume) blockPath(loc string) string {
340 return filepath.Join(v.blockDir(loc), loc)
343 // IsFull returns true if the free space on the volume is less than
344 // MIN_FREE_KILOBYTES.
346 func (v *UnixVolume) IsFull() (isFull bool) {
347 fullSymlink := v.root + "/full"
349 // Check if the volume has been marked as full in the last hour.
350 if link, err := os.Readlink(fullSymlink); err == nil {
351 if ts, err := strconv.Atoi(link); err == nil {
352 fulltime := time.Unix(int64(ts), 0)
353 if time.Since(fulltime).Hours() < 1.0 {
359 if avail, err := v.FreeDiskSpace(); err == nil {
360 isFull = avail < MIN_FREE_KILOBYTES
362 log.Printf("%s: FreeDiskSpace: %s\n", v, err)
366 // If the volume is full, timestamp it.
368 now := fmt.Sprintf("%d", time.Now().Unix())
369 os.Symlink(now, fullSymlink)
374 // FreeDiskSpace returns the number of unused 1k blocks available on
377 func (v *UnixVolume) FreeDiskSpace() (free uint64, err error) {
378 var fs syscall.Statfs_t
379 err = syscall.Statfs(v.root, &fs)
381 // Statfs output is not guaranteed to measure free
382 // space in terms of 1K blocks.
383 free = fs.Bavail * uint64(fs.Bsize) / 1024
388 func (v *UnixVolume) String() string {
389 return fmt.Sprintf("[UnixVolume %s]", v.root)
392 func (v *UnixVolume) Writable() bool {
396 // lockfile and unlockfile use flock(2) to manage kernel file locks.
397 func lockfile(f *os.File) error {
398 return syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
401 func unlockfile(f *os.File) error {
402 return syscall.Flock(int(f.Fd()), syscall.LOCK_UN)