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, Index 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 locator := filepath.Base(path)
242 // Skip directories that do not match prefix.
243 // We know there is nothing interesting inside.
245 !strings.HasPrefix(locator, prefix) &&
246 !strings.HasPrefix(prefix, locator) {
247 return filepath.SkipDir
249 // Skip any file that is not apparently a locator, e.g. .meta files
250 if info.IsDir() || !IsValidLocator(locator) {
253 // Print filenames beginning with prefix
254 if !strings.HasPrefix(locator, prefix) {
257 _, err = fmt.Fprintf(w, "%s+%d %d\n",
258 locator, info.Size(), info.ModTime().Unix())
263 func (v *UnixVolume) Delete(loc string) error {
264 // Touch() must be called before calling Write() on a block. Touch()
265 // also uses lockfile(). This avoids a race condition between Write()
266 // and Delete() because either (a) the file will be deleted and Touch()
267 // will signal to the caller that the file is not present (and needs to
268 // be re-written), or (b) Touch() will update the file's timestamp and
269 // Delete() will read the correct up-to-date timestamp and choose not to
273 return MethodDisabledError
275 p := v.blockPath(loc)
276 f, err := os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
281 if e := lockfile(f); e != nil {
286 // If the block has been PUT in the last blob_signature_ttl
287 // seconds, return success without removing the block. This
288 // protects data from garbage collection until it is no longer
289 // possible for clients to retrieve the unreferenced blocks
290 // anyway (because the permission signatures have expired).
291 if fi, err := os.Stat(p); err != nil {
294 if time.Since(fi.ModTime()) < blob_signature_ttl {
301 // blockDir returns the fully qualified directory name for the directory
302 // where loc is (or would be) stored on this volume.
303 func (v *UnixVolume) blockDir(loc string) string {
304 return filepath.Join(v.root, loc[0:3])
307 // blockPath returns the fully qualified pathname for the path to loc
309 func (v *UnixVolume) blockPath(loc string) string {
310 return filepath.Join(v.blockDir(loc), loc)
313 // IsFull returns true if the free space on the volume is less than
314 // MIN_FREE_KILOBYTES.
316 func (v *UnixVolume) IsFull() (isFull bool) {
317 fullSymlink := v.root + "/full"
319 // Check if the volume has been marked as full in the last hour.
320 if link, err := os.Readlink(fullSymlink); err == nil {
321 if ts, err := strconv.Atoi(link); err == nil {
322 fulltime := time.Unix(int64(ts), 0)
323 if time.Since(fulltime).Hours() < 1.0 {
329 if avail, err := v.FreeDiskSpace(); err == nil {
330 isFull = avail < MIN_FREE_KILOBYTES
332 log.Printf("%s: FreeDiskSpace: %s\n", v, err)
336 // If the volume is full, timestamp it.
338 now := fmt.Sprintf("%d", time.Now().Unix())
339 os.Symlink(now, fullSymlink)
344 // FreeDiskSpace returns the number of unused 1k blocks available on
347 func (v *UnixVolume) FreeDiskSpace() (free uint64, err error) {
348 var fs syscall.Statfs_t
349 err = syscall.Statfs(v.root, &fs)
351 // Statfs output is not guaranteed to measure free
352 // space in terms of 1K blocks.
353 free = fs.Bavail * uint64(fs.Bsize) / 1024
358 func (v *UnixVolume) String() string {
359 return fmt.Sprintf("[UnixVolume %s]", v.root)
362 func (v *UnixVolume) Writable() bool {
366 // lockfile and unlockfile use flock(2) to manage kernel file locks.
367 func lockfile(f *os.File) error {
368 return syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
371 func unlockfile(f *os.File) error {
372 return syscall.Flock(int(f.Fd()), syscall.LOCK_UN)