1 // A UnixVolume is a Volume backed by a locally mounted disk.
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 // Get retrieves a block identified by the locator string "loc", and
60 // returns its contents as a byte slice.
62 // If the block could not be found, opened, or read, Get returns a nil
63 // slice and whatever non-nil error was returned by Stat or ReadFile.
64 func (v *UnixVolume) Get(loc string) ([]byte, error) {
65 path := v.blockPath(loc)
66 stat, err := os.Stat(path)
71 return nil, os.ErrInvalid
72 } else if stat.Size() == 0 {
73 return bufs.Get(0), nil
74 } else if stat.Size() > BLOCKSIZE {
75 return nil, TooLongError
77 f, err := os.Open(path)
82 buf := bufs.Get(int(stat.Size()))
85 defer v.mutex.Unlock()
87 _, err = io.ReadFull(f, buf)
95 // Put stores a block of data identified by the locator string
96 // "loc". It returns nil on success. If the volume is full, it
97 // returns a FullError. If the write fails due to some other error,
98 // that error is returned.
99 func (v *UnixVolume) Put(loc string, block []byte) error {
101 return MethodDisabledError
106 bdir := v.blockDir(loc)
107 if err := os.MkdirAll(bdir, 0755); err != nil {
108 log.Printf("%s: could not create directory %s: %s",
113 tmpfile, tmperr := ioutil.TempFile(bdir, "tmp"+loc)
115 log.Printf("ioutil.TempFile(%s, tmp%s): %s", bdir, loc, tmperr)
118 bpath := v.blockPath(loc)
122 defer v.mutex.Unlock()
124 if _, err := tmpfile.Write(block); err != nil {
125 log.Printf("%s: writing to %s: %s\n", v, bpath, err)
127 os.Remove(tmpfile.Name())
130 if err := tmpfile.Close(); err != nil {
131 log.Printf("closing %s: %s\n", tmpfile.Name(), err)
132 os.Remove(tmpfile.Name())
135 if err := os.Rename(tmpfile.Name(), bpath); err != nil {
136 log.Printf("rename %s %s: %s\n", tmpfile.Name(), bpath, err)
137 os.Remove(tmpfile.Name())
143 // Status returns a VolumeStatus struct describing the volume's
146 func (v *UnixVolume) Status() *VolumeStatus {
147 var fs syscall.Statfs_t
150 if fi, err := os.Stat(v.root); err == nil {
151 devnum = fi.Sys().(*syscall.Stat_t).Dev
153 log.Printf("%s: os.Stat: %s\n", v, err)
157 err := syscall.Statfs(v.root, &fs)
159 log.Printf("%s: statfs: %s\n", v, err)
162 // These calculations match the way df calculates disk usage:
163 // "free" space is measured by fs.Bavail, but "used" space
164 // uses fs.Blocks - fs.Bfree.
165 free := fs.Bavail * uint64(fs.Bsize)
166 used := (fs.Blocks - fs.Bfree) * uint64(fs.Bsize)
167 return &VolumeStatus{v.root, devnum, free, used}
170 // IndexTo writes (to the given Writer) a list of blocks found on this
171 // volume which begin with the specified prefix. If the prefix is an
172 // empty string, IndexTo writes a complete list of blocks.
174 // Each block is given in the format
176 // locator+size modification-time {newline}
180 // e4df392f86be161ca6ed3773a962b8f3+67108864 1388894303
181 // e4d41e6fd68460e0e3fc18cc746959d2+67108864 1377796043
182 // e4de7a2810f5554cd39b36d8ddb132ff+67108864 1388701136
184 func (v *UnixVolume) IndexTo(prefix string, w io.Writer) error {
185 return filepath.Walk(v.root,
186 func(path string, info os.FileInfo, err error) error {
188 log.Printf("%s: IndexTo Walk error at %s: %s",
192 basename := filepath.Base(path)
194 !strings.HasPrefix(basename, prefix) &&
195 !strings.HasPrefix(prefix, basename) {
196 // Skip directories that do not match
197 // prefix. We know there is nothing
198 // interesting inside.
199 return filepath.SkipDir
202 !IsValidLocator(basename) ||
203 !strings.HasPrefix(basename, prefix) {
206 _, err = fmt.Fprintf(w, "%s+%d %d\n",
207 basename, info.Size(), info.ModTime().Unix())
212 func (v *UnixVolume) Delete(loc string) error {
213 // Touch() must be called before calling Write() on a block. Touch()
214 // also uses lockfile(). This avoids a race condition between Write()
215 // and Delete() because either (a) the file will be deleted and Touch()
216 // will signal to the caller that the file is not present (and needs to
217 // be re-written), or (b) Touch() will update the file's timestamp and
218 // Delete() will read the correct up-to-date timestamp and choose not to
222 return MethodDisabledError
226 defer v.mutex.Unlock()
228 p := v.blockPath(loc)
229 f, err := os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
234 if e := lockfile(f); e != nil {
239 // If the block has been PUT in the last blob_signature_ttl
240 // seconds, return success without removing the block. This
241 // protects data from garbage collection until it is no longer
242 // possible for clients to retrieve the unreferenced blocks
243 // anyway (because the permission signatures have expired).
244 if fi, err := os.Stat(p); err != nil {
247 if time.Since(fi.ModTime()) < blob_signature_ttl {
254 // blockDir returns the fully qualified directory name for the directory
255 // where loc is (or would be) stored on this volume.
256 func (v *UnixVolume) blockDir(loc string) string {
257 return filepath.Join(v.root, loc[0:3])
260 // blockPath returns the fully qualified pathname for the path to loc
262 func (v *UnixVolume) blockPath(loc string) string {
263 return filepath.Join(v.blockDir(loc), loc)
266 // IsFull returns true if the free space on the volume is less than
267 // MIN_FREE_KILOBYTES.
269 func (v *UnixVolume) IsFull() (isFull bool) {
270 fullSymlink := v.root + "/full"
272 // Check if the volume has been marked as full in the last hour.
273 if link, err := os.Readlink(fullSymlink); err == nil {
274 if ts, err := strconv.Atoi(link); err == nil {
275 fulltime := time.Unix(int64(ts), 0)
276 if time.Since(fulltime).Hours() < 1.0 {
282 if avail, err := v.FreeDiskSpace(); err == nil {
283 isFull = avail < MIN_FREE_KILOBYTES
285 log.Printf("%s: FreeDiskSpace: %s\n", v, err)
289 // If the volume is full, timestamp it.
291 now := fmt.Sprintf("%d", time.Now().Unix())
292 os.Symlink(now, fullSymlink)
297 // FreeDiskSpace returns the number of unused 1k blocks available on
300 func (v *UnixVolume) FreeDiskSpace() (free uint64, err error) {
301 var fs syscall.Statfs_t
302 err = syscall.Statfs(v.root, &fs)
304 // Statfs output is not guaranteed to measure free
305 // space in terms of 1K blocks.
306 free = fs.Bavail * uint64(fs.Bsize) / 1024
311 func (v *UnixVolume) String() string {
312 return fmt.Sprintf("[UnixVolume %s]", v.root)
315 func (v *UnixVolume) Writable() bool {
319 // lockfile and unlockfile use flock(2) to manage kernel file locks.
320 func lockfile(f *os.File) error {
321 return syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
324 func unlockfile(f *os.File) error {
325 return syscall.Flock(int(f.Fd()), syscall.LOCK_UN)