7121: Replace Get(loc,true) with CompareAndTouch(). Add Compare method to Volume...
[arvados.git] / services / keepstore / volume_unix.go
1 // A UnixVolume is a Volume backed by a locally mounted disk.
2 //
3 package main
4
5 import (
6         "bytes"
7         "fmt"
8         "io"
9         "io/ioutil"
10         "log"
11         "os"
12         "path/filepath"
13         "regexp"
14         "strconv"
15         "strings"
16         "sync"
17         "syscall"
18         "time"
19 )
20
21 // A UnixVolume stores and retrieves blocks in a local directory.
22 type UnixVolume struct {
23         root      string // path to the volume's root directory
24         serialize bool
25         readonly  bool
26         mutex     sync.Mutex
27 }
28
29 func (v *UnixVolume) Touch(loc string) error {
30         if v.readonly {
31                 return MethodDisabledError
32         }
33         p := v.blockPath(loc)
34         f, err := os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
35         if err != nil {
36                 return err
37         }
38         defer f.Close()
39         if v.serialize {
40                 v.mutex.Lock()
41                 defer v.mutex.Unlock()
42         }
43         if e := lockfile(f); e != nil {
44                 return e
45         }
46         defer unlockfile(f)
47         now := time.Now().Unix()
48         utime := syscall.Utimbuf{now, now}
49         return syscall.Utime(p, &utime)
50 }
51
52 func (v *UnixVolume) Mtime(loc string) (time.Time, error) {
53         p := v.blockPath(loc)
54         if fi, err := os.Stat(p); err != nil {
55                 return time.Time{}, err
56         } else {
57                 return fi.ModTime(), nil
58         }
59 }
60
61 // Open the given file, apply the serialize lock if enabled, and call
62 // the given function if and when the file is ready to read.
63 func (v *UnixVolume) getFunc(path string, fn func(io.Reader) error) error {
64         f, err := os.Open(path)
65         if err != nil {
66                 return err
67         }
68         defer f.Close()
69         if v.serialize {
70                 v.mutex.Lock()
71                 defer v.mutex.Unlock()
72         }
73         return fn(f)
74 }
75
76 // stat is os.Stat() with some extra sanity checks.
77 func (v *UnixVolume) stat(path string) (os.FileInfo, error) {
78         stat, err := os.Stat(path)
79         if err == nil {
80                 if stat.Size() < 0 {
81                         err = os.ErrInvalid
82                 } else if stat.Size() > BLOCKSIZE {
83                         err = TooLongError
84                 }
85         }
86         return stat, err
87 }
88
89 // Get retrieves a block identified by the locator string "loc", and
90 // returns its contents as a byte slice.
91 //
92 // Get returns a nil buffer IFF it returns a non-nil error.
93 func (v *UnixVolume) Get(loc string) ([]byte, error) {
94         path := v.blockPath(loc)
95         stat, err := v.stat(path)
96         if err != nil {
97                 return nil, err
98         }
99         buf := bufs.Get(int(stat.Size()))
100         err = v.getFunc(path, func(rdr io.Reader) error {
101                 _, err = io.ReadFull(rdr, buf)
102                 return err
103         })
104         if err != nil {
105                 bufs.Put(buf)
106                 return nil, err
107         }
108         return buf, nil
109 }
110
111 // Compare returns nil if Get(loc) would return the same content as
112 // cmp. It is functionally equivalent to Get() followed by
113 // bytes.Compare(), but uses less memory.
114 //
115 // TODO(TC): Before returning CollisionError, compute the MD5 digest
116 // of the data on disk (i.e., known-to-be-equal data in cmp +
117 // remaining data on disk) and return DiskHashError instead of
118 // CollisionError if it doesn't equal loc[:32].
119 func (v *UnixVolume) Compare(loc string, cmp []byte) error {
120         path := v.blockPath(loc)
121         stat, err := v.stat(path)
122         if err != nil {
123                 return err
124         }
125         bufLen := 1 << 20
126         if int64(bufLen) > stat.Size() {
127                 bufLen = int(stat.Size())
128         }
129         buf := make([]byte, bufLen)
130         return v.getFunc(path, func(rdr io.Reader) error {
131                 // Loop invariants: all data read so far matched what
132                 // we expected, and the first N bytes of cmp are
133                 // expected to equal the next N bytes read from
134                 // reader.
135                 for {
136                         n, err := rdr.Read(buf)
137                         if n > len(cmp) {
138                                 // file on disk is too long
139                                 return CollisionError
140                         } else if n > 0 && bytes.Compare(cmp[:n], buf[:n]) != 0 {
141                                 return CollisionError
142                         }
143                         cmp = cmp[n:]
144                         if err == io.EOF {
145                                 if len(cmp) != 0 {
146                                         // file on disk is too short
147                                         return CollisionError
148                                 }
149                                 return nil
150                         } else if err != nil {
151                                 return err
152                         }
153                 }
154         })
155 }
156
157 // Put stores a block of data identified by the locator string
158 // "loc".  It returns nil on success.  If the volume is full, it
159 // returns a FullError.  If the write fails due to some other error,
160 // that error is returned.
161 func (v *UnixVolume) Put(loc string, block []byte) error {
162         if v.readonly {
163                 return MethodDisabledError
164         }
165         if v.IsFull() {
166                 return FullError
167         }
168         bdir := v.blockDir(loc)
169         if err := os.MkdirAll(bdir, 0755); err != nil {
170                 log.Printf("%s: could not create directory %s: %s",
171                         loc, bdir, err)
172                 return err
173         }
174
175         tmpfile, tmperr := ioutil.TempFile(bdir, "tmp"+loc)
176         if tmperr != nil {
177                 log.Printf("ioutil.TempFile(%s, tmp%s): %s", bdir, loc, tmperr)
178                 return tmperr
179         }
180         bpath := v.blockPath(loc)
181
182         if v.serialize {
183                 v.mutex.Lock()
184                 defer v.mutex.Unlock()
185         }
186         if _, err := tmpfile.Write(block); err != nil {
187                 log.Printf("%s: writing to %s: %s\n", v, bpath, err)
188                 tmpfile.Close()
189                 os.Remove(tmpfile.Name())
190                 return err
191         }
192         if err := tmpfile.Close(); err != nil {
193                 log.Printf("closing %s: %s\n", tmpfile.Name(), err)
194                 os.Remove(tmpfile.Name())
195                 return err
196         }
197         if err := os.Rename(tmpfile.Name(), bpath); err != nil {
198                 log.Printf("rename %s %s: %s\n", tmpfile.Name(), bpath, err)
199                 os.Remove(tmpfile.Name())
200                 return err
201         }
202         return nil
203 }
204
205 // Status returns a VolumeStatus struct describing the volume's
206 // current state, or nil if an error occurs.
207 //
208 func (v *UnixVolume) Status() *VolumeStatus {
209         var fs syscall.Statfs_t
210         var devnum uint64
211
212         if fi, err := os.Stat(v.root); err == nil {
213                 devnum = fi.Sys().(*syscall.Stat_t).Dev
214         } else {
215                 log.Printf("%s: os.Stat: %s\n", v, err)
216                 return nil
217         }
218
219         err := syscall.Statfs(v.root, &fs)
220         if err != nil {
221                 log.Printf("%s: statfs: %s\n", v, err)
222                 return nil
223         }
224         // These calculations match the way df calculates disk usage:
225         // "free" space is measured by fs.Bavail, but "used" space
226         // uses fs.Blocks - fs.Bfree.
227         free := fs.Bavail * uint64(fs.Bsize)
228         used := (fs.Blocks - fs.Bfree) * uint64(fs.Bsize)
229         return &VolumeStatus{v.root, devnum, free, used}
230 }
231
232 var blockDirRe = regexp.MustCompile(`^[0-9a-f]+$`)
233
234 // IndexTo writes (to the given Writer) a list of blocks found on this
235 // volume which begin with the specified prefix. If the prefix is an
236 // empty string, IndexTo writes a complete list of blocks.
237 //
238 // Each block is given in the format
239 //
240 //     locator+size modification-time {newline}
241 //
242 // e.g.:
243 //
244 //     e4df392f86be161ca6ed3773a962b8f3+67108864 1388894303
245 //     e4d41e6fd68460e0e3fc18cc746959d2+67108864 1377796043
246 //     e4de7a2810f5554cd39b36d8ddb132ff+67108864 1388701136
247 //
248 func (v *UnixVolume) IndexTo(prefix string, w io.Writer) error {
249         var lastErr error = nil
250         rootdir, err := os.Open(v.root)
251         if err != nil {
252                 return err
253         }
254         defer rootdir.Close()
255         for {
256                 names, err := rootdir.Readdirnames(1)
257                 if err == io.EOF {
258                         return lastErr
259                 } else if err != nil {
260                         return err
261                 }
262                 if !strings.HasPrefix(names[0], prefix) && !strings.HasPrefix(prefix, names[0]) {
263                         // prefix excludes all blocks stored in this dir
264                         continue
265                 }
266                 if !blockDirRe.MatchString(names[0]) {
267                         continue
268                 }
269                 blockdirpath := filepath.Join(v.root, names[0])
270                 blockdir, err := os.Open(blockdirpath)
271                 if err != nil {
272                         log.Print("Error reading ", blockdirpath, ": ", err)
273                         lastErr = err
274                         continue
275                 }
276                 for {
277                         fileInfo, err := blockdir.Readdir(1)
278                         if err == io.EOF {
279                                 break
280                         } else if err != nil {
281                                 log.Print("Error reading ", blockdirpath, ": ", err)
282                                 lastErr = err
283                                 break
284                         }
285                         name := fileInfo[0].Name()
286                         if !strings.HasPrefix(name, prefix) {
287                                 continue
288                         }
289                         _, err = fmt.Fprint(w,
290                                 name,
291                                 "+", fileInfo[0].Size(),
292                                 " ", fileInfo[0].ModTime().Unix(),
293                                 "\n")
294                 }
295                 blockdir.Close()
296         }
297 }
298
299 func (v *UnixVolume) Delete(loc string) error {
300         // Touch() must be called before calling Write() on a block.  Touch()
301         // also uses lockfile().  This avoids a race condition between Write()
302         // and Delete() because either (a) the file will be deleted and Touch()
303         // will signal to the caller that the file is not present (and needs to
304         // be re-written), or (b) Touch() will update the file's timestamp and
305         // Delete() will read the correct up-to-date timestamp and choose not to
306         // delete the file.
307
308         if v.readonly {
309                 return MethodDisabledError
310         }
311         if v.serialize {
312                 v.mutex.Lock()
313                 defer v.mutex.Unlock()
314         }
315         p := v.blockPath(loc)
316         f, err := os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
317         if err != nil {
318                 return err
319         }
320         defer f.Close()
321         if e := lockfile(f); e != nil {
322                 return e
323         }
324         defer unlockfile(f)
325
326         // If the block has been PUT in the last blob_signature_ttl
327         // seconds, return success without removing the block. This
328         // protects data from garbage collection until it is no longer
329         // possible for clients to retrieve the unreferenced blocks
330         // anyway (because the permission signatures have expired).
331         if fi, err := os.Stat(p); err != nil {
332                 return err
333         } else {
334                 if time.Since(fi.ModTime()) < blob_signature_ttl {
335                         return nil
336                 }
337         }
338         return os.Remove(p)
339 }
340
341 // blockDir returns the fully qualified directory name for the directory
342 // where loc is (or would be) stored on this volume.
343 func (v *UnixVolume) blockDir(loc string) string {
344         return filepath.Join(v.root, loc[0:3])
345 }
346
347 // blockPath returns the fully qualified pathname for the path to loc
348 // on this volume.
349 func (v *UnixVolume) blockPath(loc string) string {
350         return filepath.Join(v.blockDir(loc), loc)
351 }
352
353 // IsFull returns true if the free space on the volume is less than
354 // MIN_FREE_KILOBYTES.
355 //
356 func (v *UnixVolume) IsFull() (isFull bool) {
357         fullSymlink := v.root + "/full"
358
359         // Check if the volume has been marked as full in the last hour.
360         if link, err := os.Readlink(fullSymlink); err == nil {
361                 if ts, err := strconv.Atoi(link); err == nil {
362                         fulltime := time.Unix(int64(ts), 0)
363                         if time.Since(fulltime).Hours() < 1.0 {
364                                 return true
365                         }
366                 }
367         }
368
369         if avail, err := v.FreeDiskSpace(); err == nil {
370                 isFull = avail < MIN_FREE_KILOBYTES
371         } else {
372                 log.Printf("%s: FreeDiskSpace: %s\n", v, err)
373                 isFull = false
374         }
375
376         // If the volume is full, timestamp it.
377         if isFull {
378                 now := fmt.Sprintf("%d", time.Now().Unix())
379                 os.Symlink(now, fullSymlink)
380         }
381         return
382 }
383
384 // FreeDiskSpace returns the number of unused 1k blocks available on
385 // the volume.
386 //
387 func (v *UnixVolume) FreeDiskSpace() (free uint64, err error) {
388         var fs syscall.Statfs_t
389         err = syscall.Statfs(v.root, &fs)
390         if err == nil {
391                 // Statfs output is not guaranteed to measure free
392                 // space in terms of 1K blocks.
393                 free = fs.Bavail * uint64(fs.Bsize) / 1024
394         }
395         return
396 }
397
398 func (v *UnixVolume) String() string {
399         return fmt.Sprintf("[UnixVolume %s]", v.root)
400 }
401
402 func (v *UnixVolume) Writable() bool {
403         return !v.readonly
404 }
405
406 // lockfile and unlockfile use flock(2) to manage kernel file locks.
407 func lockfile(f *os.File) error {
408         return syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
409 }
410
411 func unlockfile(f *os.File) error {
412         return syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
413 }