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
57 func (v *UnixVolume) IOHandler() {
58 for req := range v.queue {
62 result.data, result.err = v.Read(req.loc)
64 result.err = v.Write(req.loc, req.data)
70 func MakeUnixVolume(root string, serialize bool) (v UnixVolume) {
72 v = UnixVolume{root, make(chan *IORequest)}
75 v = UnixVolume{root, nil}
80 func (v *UnixVolume) Get(loc string) ([]byte, error) {
84 reply := make(chan *IOResponse)
85 v.queue <- &IORequest{KeepGet, loc, nil, reply}
87 return response.data, response.err
90 func (v *UnixVolume) Put(loc string, block []byte) error {
92 return v.Write(loc, block)
94 reply := make(chan *IOResponse)
95 v.queue <- &IORequest{KeepPut, loc, block, reply}
100 func (v *UnixVolume) Touch(loc string) error {
101 p := v.blockPath(loc)
102 f, err := os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
107 if e := lockfile(f); e != nil {
111 now := time.Now().Unix()
112 utime := syscall.Utimbuf{now, now}
113 return syscall.Utime(p, &utime)
116 func (v *UnixVolume) Mtime(loc string) (time.Time, error) {
117 p := v.blockPath(loc)
118 if fi, err := os.Stat(p); err != nil {
119 return time.Time{}, err
121 return fi.ModTime(), nil
125 // Read retrieves a block identified by the locator string "loc", and
126 // returns its contents as a byte slice.
128 // If the block could not be opened or read, Read returns a nil slice
129 // and the os.Error that was generated.
131 // If the block is present but its content hash does not match loc,
132 // Read returns the block and a CorruptError. It is the caller's
133 // responsibility to decide what (if anything) to do with the
134 // corrupted data block.
136 func (v *UnixVolume) Read(loc string) ([]byte, error) {
137 buf, err := ioutil.ReadFile(v.blockPath(loc))
141 // Write stores a block of data identified by the locator string
142 // "loc". It returns nil on success. If the volume is full, it
143 // returns a FullError. If the write fails due to some other error,
144 // that error is returned.
146 func (v *UnixVolume) Write(loc string, block []byte) error {
150 bdir := v.blockDir(loc)
151 if err := os.MkdirAll(bdir, 0755); err != nil {
152 log.Printf("%s: could not create directory %s: %s",
157 tmpfile, tmperr := ioutil.TempFile(bdir, "tmp"+loc)
159 log.Printf("ioutil.TempFile(%s, tmp%s): %s", bdir, loc, tmperr)
162 bpath := v.blockPath(loc)
164 if _, err := tmpfile.Write(block); err != nil {
165 log.Printf("%s: writing to %s: %s\n", v, bpath, err)
168 if err := tmpfile.Close(); err != nil {
169 log.Printf("closing %s: %s\n", tmpfile.Name(), err)
170 os.Remove(tmpfile.Name())
173 if err := os.Rename(tmpfile.Name(), bpath); err != nil {
174 log.Printf("rename %s %s: %s\n", tmpfile.Name(), bpath, err)
175 os.Remove(tmpfile.Name())
181 // Status returns a VolumeStatus struct describing the volume's
184 func (v *UnixVolume) Status() *VolumeStatus {
185 var fs syscall.Statfs_t
188 if fi, err := os.Stat(v.root); err == nil {
189 devnum = fi.Sys().(*syscall.Stat_t).Dev
191 log.Printf("%s: os.Stat: %s\n", v, err)
195 err := syscall.Statfs(v.root, &fs)
197 log.Printf("%s: statfs: %s\n", v, err)
200 // These calculations match the way df calculates disk usage:
201 // "free" space is measured by fs.Bavail, but "used" space
202 // uses fs.Blocks - fs.Bfree.
203 free := fs.Bavail * uint64(fs.Bsize)
204 used := (fs.Blocks - fs.Bfree) * uint64(fs.Bsize)
205 return &VolumeStatus{v.root, devnum, free, used}
208 // Index returns a list of blocks found on this volume which begin with
209 // the specified prefix. If the prefix is an empty string, Index returns
210 // a complete list of blocks.
212 // The return value is a multiline string (separated by
213 // newlines). Each line is in the format
215 // locator+size modification-time
219 // e4df392f86be161ca6ed3773a962b8f3+67108864 1388894303
220 // e4d41e6fd68460e0e3fc18cc746959d2+67108864 1377796043
221 // e4de7a2810f5554cd39b36d8ddb132ff+67108864 1388701136
223 func (v *UnixVolume) Index(prefix string) (output string) {
224 filepath.Walk(v.root,
225 func(path string, info os.FileInfo, err error) error {
226 // This WalkFunc inspects each path in the volume
227 // and prints an index line for all files that begin
230 log.Printf("IndexHandler: %s: walking to %s: %s",
234 locator := filepath.Base(path)
235 // Skip directories that do not match prefix.
236 // We know there is nothing interesting inside.
238 !strings.HasPrefix(locator, prefix) &&
239 !strings.HasPrefix(prefix, locator) {
240 return filepath.SkipDir
242 // Skip any file that is not apparently a locator, e.g. .meta files
243 if !IsValidLocator(locator) {
246 // Print filenames beginning with prefix
247 if !info.IsDir() && strings.HasPrefix(locator, prefix) {
248 output = output + fmt.Sprintf(
249 "%s+%d %d\n", locator, info.Size(), info.ModTime().Unix())
257 func (v *UnixVolume) Delete(loc string) error {
258 // Touch() must be called before calling Write() on a block. Touch()
259 // also uses lockfile(). This avoids a race condition between Write()
260 // and Delete() because either (a) the file will be deleted and Touch()
261 // will signal to the caller that the file is not present (and needs to
262 // be re-written), or (b) Touch() will update the file's timestamp and
263 // Delete() will read the correct up-to-date timestamp and choose not to
266 p := v.blockPath(loc)
267 f, err := os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
272 if e := lockfile(f); e != nil {
277 // If the block has been PUT more recently than -permission_ttl,
278 // return success without removing the block. This guards against
279 // a race condition where a block is old enough that Data Manager
280 // has added it to the trash list, but the user submitted a PUT
281 // for the block since then.
282 if fi, err := os.Stat(p); err != nil {
285 if time.Since(fi.ModTime()) < permission_ttl {
292 // blockDir returns the fully qualified directory name for the directory
293 // where loc is (or would be) stored on this volume.
294 func (v *UnixVolume) blockDir(loc string) string {
295 return filepath.Join(v.root, loc[0:3])
298 // blockPath returns the fully qualified pathname for the path to loc
300 func (v *UnixVolume) blockPath(loc string) string {
301 return filepath.Join(v.blockDir(loc), loc)
304 // IsFull returns true if the free space on the volume is less than
305 // MIN_FREE_KILOBYTES.
307 func (v *UnixVolume) IsFull() (isFull bool) {
308 fullSymlink := v.root + "/full"
310 // Check if the volume has been marked as full in the last hour.
311 if link, err := os.Readlink(fullSymlink); err == nil {
312 if ts, err := strconv.Atoi(link); err == nil {
313 fulltime := time.Unix(int64(ts), 0)
314 if time.Since(fulltime).Hours() < 1.0 {
320 if avail, err := v.FreeDiskSpace(); err == nil {
321 isFull = avail < MIN_FREE_KILOBYTES
323 log.Printf("%s: FreeDiskSpace: %s\n", v, err)
327 // If the volume is full, timestamp it.
329 now := fmt.Sprintf("%d", time.Now().Unix())
330 os.Symlink(now, fullSymlink)
335 // FreeDiskSpace returns the number of unused 1k blocks available on
338 func (v *UnixVolume) FreeDiskSpace() (free uint64, err error) {
339 var fs syscall.Statfs_t
340 err = syscall.Statfs(v.root, &fs)
342 // Statfs output is not guaranteed to measure free
343 // space in terms of 1K blocks.
344 free = fs.Bavail * uint64(fs.Bsize) / 1024
349 func (v *UnixVolume) String() string {
350 return fmt.Sprintf("[UnixVolume %s]", v.root)
353 // lockfile and unlockfile use flock(2) to manage kernel file locks.
354 func lockfile(f *os.File) error {
355 return syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
358 func unlockfile(f *os.File) error {
359 return syscall.Flock(int(f.Fd()), syscall.LOCK_UN)