1 // A UnixVolume is a Volume backed by a locally mounted disk.
18 // IORequests are encapsulated Get or Put requests. They are used to
19 // implement serialized I/O (i.e. only one read/write operation per
20 // volume). When running in serialized mode, the Keep front end sends
21 // IORequests on a channel to an IORunner, which handles them one at a
22 // time and returns an IOResponse.
27 KeepGet IOMethod = iota
31 type IORequest struct {
35 reply chan *IOResponse
38 type IOResponse struct {
43 // A UnixVolume has the following properties:
46 // the path to the volume's root directory
48 // A channel of IORequests. If non-nil, all I/O requests for
49 // this volume should be queued on this channel; the result
50 // will be delivered on the IOResponse channel supplied in the
53 type UnixVolume struct {
54 root string // path to this volume
59 func (v *UnixVolume) IOHandler() {
60 for req := range v.queue {
64 result.data, result.err = v.Read(req.loc)
66 result.err = v.Write(req.loc, req.data)
72 func MakeUnixVolume(root string, serialize bool, readonly bool) *UnixVolume {
79 v.queue = make(chan *IORequest)
85 func (v *UnixVolume) Get(loc string) ([]byte, error) {
89 reply := make(chan *IOResponse)
90 v.queue <- &IORequest{KeepGet, loc, nil, reply}
92 return response.data, response.err
95 func (v *UnixVolume) Put(loc string, block []byte) error {
97 return MethodDisabledError
100 return v.Write(loc, block)
102 reply := make(chan *IOResponse)
103 v.queue <- &IORequest{KeepPut, loc, block, reply}
108 func (v *UnixVolume) Touch(loc string) error {
110 return MethodDisabledError
112 p := v.blockPath(loc)
113 f, err := os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
118 if e := lockfile(f); e != nil {
122 now := time.Now().Unix()
123 utime := syscall.Utimbuf{now, now}
124 return syscall.Utime(p, &utime)
127 func (v *UnixVolume) Mtime(loc string) (time.Time, error) {
128 p := v.blockPath(loc)
129 if fi, err := os.Stat(p); err != nil {
130 return time.Time{}, err
132 return fi.ModTime(), nil
136 // Read retrieves a block identified by the locator string "loc", and
137 // returns its contents as a byte slice.
139 // If the block could not be opened or read, Read returns a nil slice
140 // and the os.Error that was generated.
142 // If the block is present but its content hash does not match loc,
143 // Read returns the block and a CorruptError. It is the caller's
144 // responsibility to decide what (if anything) to do with the
145 // corrupted data block.
147 func (v *UnixVolume) Read(loc string) ([]byte, error) {
148 buf, err := ioutil.ReadFile(v.blockPath(loc))
152 // Write stores a block of data identified by the locator string
153 // "loc". It returns nil on success. If the volume is full, it
154 // returns a FullError. If the write fails due to some other error,
155 // that error is returned.
157 func (v *UnixVolume) Write(loc string, block []byte) error {
161 bdir := v.blockDir(loc)
162 if err := os.MkdirAll(bdir, 0755); err != nil {
163 log.Printf("%s: could not create directory %s: %s",
168 tmpfile, tmperr := ioutil.TempFile(bdir, "tmp"+loc)
170 log.Printf("ioutil.TempFile(%s, tmp%s): %s", bdir, loc, tmperr)
173 bpath := v.blockPath(loc)
175 if _, err := tmpfile.Write(block); err != nil {
176 log.Printf("%s: writing to %s: %s\n", v, bpath, err)
179 if err := tmpfile.Close(); err != nil {
180 log.Printf("closing %s: %s\n", tmpfile.Name(), err)
181 os.Remove(tmpfile.Name())
184 if err := os.Rename(tmpfile.Name(), bpath); err != nil {
185 log.Printf("rename %s %s: %s\n", tmpfile.Name(), bpath, err)
186 os.Remove(tmpfile.Name())
192 // Status returns a VolumeStatus struct describing the volume's
195 func (v *UnixVolume) Status() *VolumeStatus {
196 var fs syscall.Statfs_t
199 if fi, err := os.Stat(v.root); err == nil {
200 devnum = fi.Sys().(*syscall.Stat_t).Dev
202 log.Printf("%s: os.Stat: %s\n", v, err)
206 err := syscall.Statfs(v.root, &fs)
208 log.Printf("%s: statfs: %s\n", v, err)
211 // These calculations match the way df calculates disk usage:
212 // "free" space is measured by fs.Bavail, but "used" space
213 // uses fs.Blocks - fs.Bfree.
214 free := fs.Bavail * uint64(fs.Bsize)
215 used := (fs.Blocks - fs.Bfree) * uint64(fs.Bsize)
216 return &VolumeStatus{v.root, devnum, free, used}
219 // IndexTo writes (to the given Writer) a list of blocks found on this
220 // volume which begin with the specified prefix. If the prefix is an
221 // empty string, IndexTo writes a complete list of blocks.
223 // Each block is given in the format
225 // locator+size modification-time {newline}
229 // e4df392f86be161ca6ed3773a962b8f3+67108864 1388894303
230 // e4d41e6fd68460e0e3fc18cc746959d2+67108864 1377796043
231 // e4de7a2810f5554cd39b36d8ddb132ff+67108864 1388701136
233 func (v *UnixVolume) IndexTo(prefix string, w io.Writer) error {
234 return filepath.Walk(v.root,
235 func(path string, info os.FileInfo, err error) error {
237 log.Printf("%s: IndexTo Walk error at %s: %s",
241 basename := filepath.Base(path)
243 !strings.HasPrefix(basename, prefix) &&
244 !strings.HasPrefix(prefix, basename) {
245 // Skip directories that do not match
246 // prefix. We know there is nothing
247 // interesting inside.
248 return filepath.SkipDir
251 !IsValidLocator(basename) ||
252 !strings.HasPrefix(basename, prefix) {
255 _, err = fmt.Fprintf(w, "%s+%d %d\n",
256 basename, info.Size(), info.ModTime().Unix())
261 func (v *UnixVolume) Delete(loc string) error {
262 // Touch() must be called before calling Write() on a block. Touch()
263 // also uses lockfile(). This avoids a race condition between Write()
264 // and Delete() because either (a) the file will be deleted and Touch()
265 // will signal to the caller that the file is not present (and needs to
266 // be re-written), or (b) Touch() will update the file's timestamp and
267 // Delete() will read the correct up-to-date timestamp and choose not to
271 return MethodDisabledError
273 p := v.blockPath(loc)
274 f, err := os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
279 if e := lockfile(f); e != nil {
284 // If the block has been PUT in the last blob_signature_ttl
285 // seconds, return success without removing the block. This
286 // protects data from garbage collection until it is no longer
287 // possible for clients to retrieve the unreferenced blocks
288 // anyway (because the permission signatures have expired).
289 if fi, err := os.Stat(p); err != nil {
292 if time.Since(fi.ModTime()) < blob_signature_ttl {
299 // blockDir returns the fully qualified directory name for the directory
300 // where loc is (or would be) stored on this volume.
301 func (v *UnixVolume) blockDir(loc string) string {
302 return filepath.Join(v.root, loc[0:3])
305 // blockPath returns the fully qualified pathname for the path to loc
307 func (v *UnixVolume) blockPath(loc string) string {
308 return filepath.Join(v.blockDir(loc), loc)
311 // IsFull returns true if the free space on the volume is less than
312 // MIN_FREE_KILOBYTES.
314 func (v *UnixVolume) IsFull() (isFull bool) {
315 fullSymlink := v.root + "/full"
317 // Check if the volume has been marked as full in the last hour.
318 if link, err := os.Readlink(fullSymlink); err == nil {
319 if ts, err := strconv.Atoi(link); err == nil {
320 fulltime := time.Unix(int64(ts), 0)
321 if time.Since(fulltime).Hours() < 1.0 {
327 if avail, err := v.FreeDiskSpace(); err == nil {
328 isFull = avail < MIN_FREE_KILOBYTES
330 log.Printf("%s: FreeDiskSpace: %s\n", v, err)
334 // If the volume is full, timestamp it.
336 now := fmt.Sprintf("%d", time.Now().Unix())
337 os.Symlink(now, fullSymlink)
342 // FreeDiskSpace returns the number of unused 1k blocks available on
345 func (v *UnixVolume) FreeDiskSpace() (free uint64, err error) {
346 var fs syscall.Statfs_t
347 err = syscall.Statfs(v.root, &fs)
349 // Statfs output is not guaranteed to measure free
350 // space in terms of 1K blocks.
351 free = fs.Bavail * uint64(fs.Bsize) / 1024
356 func (v *UnixVolume) String() string {
357 return fmt.Sprintf("[UnixVolume %s]", v.root)
360 func (v *UnixVolume) Writable() bool {
364 // lockfile and unlockfile use flock(2) to manage kernel file locks.
365 func lockfile(f *os.File) error {
366 return syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
369 func unlockfile(f *os.File) error {
370 return syscall.Flock(int(f.Fd()), syscall.LOCK_UN)