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 p := v.blockPath(loc)
259 f, err := os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
264 if e := lockfile(f); e != nil {
269 // If the block has been PUT more recently than -permission_ttl,
270 // return success without removing the block. This guards against
271 // a race condition where a block is old enough that Data Manager
272 // has added it to the trash list, but the user submitted a PUT
273 // for the block since then.
274 if fi, err := os.Stat(p); err != nil {
277 if time.Since(fi.ModTime()) < permission_ttl {
284 // blockDir returns the fully qualified directory name for the directory
285 // where loc is (or would be) stored on this volume.
286 func (v *UnixVolume) blockDir(loc string) string {
287 return filepath.Join(v.root, loc[0:3])
290 // blockPath returns the fully qualified pathname for the path to loc
292 func (v *UnixVolume) blockPath(loc string) string {
293 return filepath.Join(v.blockDir(loc), loc)
296 // IsFull returns true if the free space on the volume is less than
297 // MIN_FREE_KILOBYTES.
299 func (v *UnixVolume) IsFull() (isFull bool) {
300 fullSymlink := v.root + "/full"
302 // Check if the volume has been marked as full in the last hour.
303 if link, err := os.Readlink(fullSymlink); err == nil {
304 if ts, err := strconv.Atoi(link); err == nil {
305 fulltime := time.Unix(int64(ts), 0)
306 if time.Since(fulltime).Hours() < 1.0 {
312 if avail, err := v.FreeDiskSpace(); err == nil {
313 isFull = avail < MIN_FREE_KILOBYTES
315 log.Printf("%s: FreeDiskSpace: %s\n", v, err)
319 // If the volume is full, timestamp it.
321 now := fmt.Sprintf("%d", time.Now().Unix())
322 os.Symlink(now, fullSymlink)
327 // FreeDiskSpace returns the number of unused 1k blocks available on
330 func (v *UnixVolume) FreeDiskSpace() (free uint64, err error) {
331 var fs syscall.Statfs_t
332 err = syscall.Statfs(v.root, &fs)
334 // Statfs output is not guaranteed to measure free
335 // space in terms of 1K blocks.
336 free = fs.Bavail * uint64(fs.Bsize) / 1024
341 func (v *UnixVolume) String() string {
342 return fmt.Sprintf("[UnixVolume %s]", v.root)
345 // lockfile and unlockfile use flock(2) to manage kernel file locks.
346 func lockfile(f *os.File) error {
347 return syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
350 func unlockfile(f *os.File) error {
351 return syscall.Flock(int(f.Fd()), syscall.LOCK_UN)