1 // A UnixVolume is a Volume backed by a locally mounted disk.
17 // IORequests are encapsulated Get or Put requests. They are used to
18 // implement serialized I/O (i.e. only one read/write operation per
19 // volume). When running in serialized mode, the Keep front end sends
20 // IORequests on a channel to an IORunner, which handles them one at a
21 // time and returns an IOResponse.
26 KeepGet IOMethod = iota
30 type IORequest struct {
34 reply chan *IOResponse
37 type IOResponse struct {
42 // A UnixVolume has the following properties:
45 // the path to the volume's root directory
47 // A channel of IORequests. If non-nil, all I/O requests for
48 // this volume should be queued on this channel; the result
49 // will be delivered on the IOResponse channel supplied in the
52 type UnixVolume struct {
53 root string // path to this volume
58 func (v *UnixVolume) IOHandler() {
59 for req := range v.queue {
63 result.data, result.err = v.Read(req.loc)
65 result.err = v.Write(req.loc, req.data)
71 func MakeUnixVolume(root string, serialize bool, readonly bool) *UnixVolume {
78 v.queue = make(chan *IORequest)
84 func (v *UnixVolume) Get(loc string) ([]byte, error) {
88 reply := make(chan *IOResponse)
89 v.queue <- &IORequest{KeepGet, loc, nil, reply}
91 return response.data, response.err
94 func (v *UnixVolume) Put(loc string, block []byte) error {
96 return MethodDisabledError
99 return v.Write(loc, block)
101 reply := make(chan *IOResponse)
102 v.queue <- &IORequest{KeepPut, loc, block, reply}
107 func (v *UnixVolume) Touch(loc string) error {
109 return MethodDisabledError
111 p := v.blockPath(loc)
112 f, err := os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
117 if e := lockfile(f); e != nil {
121 now := time.Now().Unix()
122 utime := syscall.Utimbuf{now, now}
123 return syscall.Utime(p, &utime)
126 func (v *UnixVolume) Mtime(loc string) (time.Time, error) {
127 p := v.blockPath(loc)
128 if fi, err := os.Stat(p); err != nil {
129 return time.Time{}, err
131 return fi.ModTime(), nil
135 // Read retrieves a block identified by the locator string "loc", and
136 // returns its contents as a byte slice.
138 // If the block could not be opened or read, Read returns a nil slice
139 // and the os.Error that was generated.
141 // If the block is present but its content hash does not match loc,
142 // Read returns the block and a CorruptError. It is the caller's
143 // responsibility to decide what (if anything) to do with the
144 // corrupted data block.
146 func (v *UnixVolume) Read(loc string) ([]byte, error) {
147 buf, err := ioutil.ReadFile(v.blockPath(loc))
151 // Write 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.
156 func (v *UnixVolume) Write(loc string, block []byte) error {
160 bdir := v.blockDir(loc)
161 if err := os.MkdirAll(bdir, 0755); err != nil {
162 log.Printf("%s: could not create directory %s: %s",
167 tmpfile, tmperr := ioutil.TempFile(bdir, "tmp"+loc)
169 log.Printf("ioutil.TempFile(%s, tmp%s): %s", bdir, loc, tmperr)
172 bpath := v.blockPath(loc)
174 if _, err := tmpfile.Write(block); err != nil {
175 log.Printf("%s: writing to %s: %s\n", v, bpath, err)
178 if err := tmpfile.Close(); err != nil {
179 log.Printf("closing %s: %s\n", tmpfile.Name(), err)
180 os.Remove(tmpfile.Name())
183 if err := os.Rename(tmpfile.Name(), bpath); err != nil {
184 log.Printf("rename %s %s: %s\n", tmpfile.Name(), bpath, err)
185 os.Remove(tmpfile.Name())
191 // Status returns a VolumeStatus struct describing the volume's
194 func (v *UnixVolume) Status() *VolumeStatus {
195 var fs syscall.Statfs_t
198 if fi, err := os.Stat(v.root); err == nil {
199 devnum = fi.Sys().(*syscall.Stat_t).Dev
201 log.Printf("%s: os.Stat: %s\n", v, err)
205 err := syscall.Statfs(v.root, &fs)
207 log.Printf("%s: statfs: %s\n", v, err)
210 // These calculations match the way df calculates disk usage:
211 // "free" space is measured by fs.Bavail, but "used" space
212 // uses fs.Blocks - fs.Bfree.
213 free := fs.Bavail * uint64(fs.Bsize)
214 used := (fs.Blocks - fs.Bfree) * uint64(fs.Bsize)
215 return &VolumeStatus{v.root, devnum, free, used}
218 // Index returns a list of blocks found on this volume which begin with
219 // the specified prefix. If the prefix is an empty string, Index returns
220 // a complete list of blocks.
222 // The return value is a multiline string (separated by
223 // newlines). Each line is in the format
225 // locator+size modification-time
229 // e4df392f86be161ca6ed3773a962b8f3+67108864 1388894303
230 // e4d41e6fd68460e0e3fc18cc746959d2+67108864 1377796043
231 // e4de7a2810f5554cd39b36d8ddb132ff+67108864 1388701136
233 func (v *UnixVolume) Index(prefix string) (output string) {
234 filepath.Walk(v.root,
235 func(path string, info os.FileInfo, err error) error {
236 // This WalkFunc inspects each path in the volume
237 // and prints an index line for all files that begin
240 log.Printf("IndexHandler: %s: walking to %s: %s",
244 locator := filepath.Base(path)
245 // Skip directories that do not match prefix.
246 // We know there is nothing interesting inside.
248 !strings.HasPrefix(locator, prefix) &&
249 !strings.HasPrefix(prefix, locator) {
250 return filepath.SkipDir
252 // Skip any file that is not apparently a locator, e.g. .meta files
253 if !IsValidLocator(locator) {
256 // Print filenames beginning with prefix
257 if !info.IsDir() && strings.HasPrefix(locator, prefix) {
258 output = output + fmt.Sprintf(
259 "%s+%d %d\n", locator, info.Size(), info.ModTime().Unix())
267 func (v *UnixVolume) Delete(loc string) error {
268 // Touch() must be called before calling Write() on a block. Touch()
269 // also uses lockfile(). This avoids a race condition between Write()
270 // and Delete() because either (a) the file will be deleted and Touch()
271 // will signal to the caller that the file is not present (and needs to
272 // be re-written), or (b) Touch() will update the file's timestamp and
273 // Delete() will read the correct up-to-date timestamp and choose not to
277 return MethodDisabledError
279 p := v.blockPath(loc)
280 f, err := os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
285 if e := lockfile(f); e != nil {
290 // If the block has been PUT in the last blob_signature_ttl
291 // seconds, return success without removing the block. This
292 // protects data from garbage collection until it is no longer
293 // possible for clients to retrieve the unreferenced blocks
294 // anyway (because the permission signatures have expired).
295 if fi, err := os.Stat(p); err != nil {
298 if time.Since(fi.ModTime()) < blob_signature_ttl {
305 // blockDir returns the fully qualified directory name for the directory
306 // where loc is (or would be) stored on this volume.
307 func (v *UnixVolume) blockDir(loc string) string {
308 return filepath.Join(v.root, loc[0:3])
311 // blockPath returns the fully qualified pathname for the path to loc
313 func (v *UnixVolume) blockPath(loc string) string {
314 return filepath.Join(v.blockDir(loc), loc)
317 // IsFull returns true if the free space on the volume is less than
318 // MIN_FREE_KILOBYTES.
320 func (v *UnixVolume) IsFull() (isFull bool) {
321 fullSymlink := v.root + "/full"
323 // Check if the volume has been marked as full in the last hour.
324 if link, err := os.Readlink(fullSymlink); err == nil {
325 if ts, err := strconv.Atoi(link); err == nil {
326 fulltime := time.Unix(int64(ts), 0)
327 if time.Since(fulltime).Hours() < 1.0 {
333 if avail, err := v.FreeDiskSpace(); err == nil {
334 isFull = avail < MIN_FREE_KILOBYTES
336 log.Printf("%s: FreeDiskSpace: %s\n", v, err)
340 // If the volume is full, timestamp it.
342 now := fmt.Sprintf("%d", time.Now().Unix())
343 os.Symlink(now, fullSymlink)
348 // FreeDiskSpace returns the number of unused 1k blocks available on
351 func (v *UnixVolume) FreeDiskSpace() (free uint64, err error) {
352 var fs syscall.Statfs_t
353 err = syscall.Statfs(v.root, &fs)
355 // Statfs output is not guaranteed to measure free
356 // space in terms of 1K blocks.
357 free = fs.Bavail * uint64(fs.Bsize) / 1024
362 func (v *UnixVolume) String() string {
363 return fmt.Sprintf("[UnixVolume %s]", v.root)
366 func (v *UnixVolume) Writable() bool {
370 // lockfile and unlockfile use flock(2) to manage kernel file locks.
371 func lockfile(f *os.File) error {
372 return syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
375 func unlockfile(f *os.File) error {
376 return syscall.Flock(int(f.Fd()), syscall.LOCK_UN)