7329: It appears that UnixVolume -> Compare method is falling in infinite loop due...
[arvados.git] / services / keepstore / volume_unix.go
1 package main
2
3 import (
4         "bytes"
5         "fmt"
6         "io"
7         "io/ioutil"
8         "log"
9         "os"
10         "path/filepath"
11         "regexp"
12         "strconv"
13         "strings"
14         "sync"
15         "syscall"
16         "time"
17 )
18
19 // A UnixVolume stores and retrieves blocks in a local directory.
20 type UnixVolume struct {
21         // path to the volume's root directory
22         root string
23         // something to lock during IO, typically a sync.Mutex (or nil
24         // to skip locking)
25         locker   sync.Locker
26         readonly bool
27 }
28
29 // Touch sets the timestamp for the given locator to the current time
30 func (v *UnixVolume) Touch(loc string) error {
31         if v.readonly {
32                 return MethodDisabledError
33         }
34         p := v.blockPath(loc)
35         f, err := os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
36         if err != nil {
37                 return err
38         }
39         defer f.Close()
40         if v.locker != nil {
41                 v.locker.Lock()
42                 defer v.locker.Unlock()
43         }
44         if e := lockfile(f); e != nil {
45                 return e
46         }
47         defer unlockfile(f)
48         now := time.Now().Unix()
49         utime := syscall.Utimbuf{now, now}
50         return syscall.Utime(p, &utime)
51 }
52
53 // Mtime returns the stored timestamp for the given locator.
54 func (v *UnixVolume) Mtime(loc string) (time.Time, error) {
55         p := v.blockPath(loc)
56         fi, err := os.Stat(p)
57         if err != nil {
58                 return time.Time{}, err
59         }
60         return fi.ModTime(), nil
61 }
62
63 // Lock the locker (if one is in use), open the file for reading, and
64 // call the given function if and when the file is ready to read.
65 func (v *UnixVolume) getFunc(path string, fn func(io.Reader) error) error {
66         if v.locker != nil {
67                 v.locker.Lock()
68                 defer v.locker.Unlock()
69         }
70         f, err := os.Open(path)
71         if err != nil {
72                 return err
73         }
74         defer f.Close()
75         return fn(f)
76 }
77
78 // stat is os.Stat() with some extra sanity checks.
79 func (v *UnixVolume) stat(path string) (os.FileInfo, error) {
80         stat, err := os.Stat(path)
81         if err == nil {
82                 if stat.Size() < 0 {
83                         err = os.ErrInvalid
84                 } else if stat.Size() > BlockSize {
85                         err = TooLongError
86                 }
87         }
88         return stat, err
89 }
90
91 // Get retrieves a block identified by the locator string "loc", and
92 // returns its contents as a byte slice.
93 //
94 // Get returns a nil buffer IFF it returns a non-nil error.
95 func (v *UnixVolume) Get(loc string) ([]byte, error) {
96         path := v.blockPath(loc)
97         stat, err := v.stat(path)
98         if err != nil {
99                 return nil, err
100         }
101         buf := bufs.Get(int(stat.Size()))
102         err = v.getFunc(path, func(rdr io.Reader) error {
103                 _, err = io.ReadFull(rdr, buf)
104                 return err
105         })
106         if err != nil {
107                 bufs.Put(buf)
108                 return nil, err
109         }
110         return buf, nil
111 }
112
113 // Compare returns nil if Get(loc) would return the same content as
114 // expect. It is functionally equivalent to Get() followed by
115 // bytes.Compare(), but uses less memory.
116 func (v *UnixVolume) Compare(loc string, expect []byte) error {
117         path := v.blockPath(loc)
118         stat, err := v.stat(path)
119         if err != nil {
120                 return err
121         }
122         bufLen := 1 << 20
123         if int64(bufLen) > stat.Size() {
124                 bufLen = int(stat.Size())
125         }
126         cmp := expect
127         buf := make([]byte, bufLen)
128         return v.getFunc(path, func(rdr io.Reader) error {
129                 // Loop invariants: all data read so far matched what
130                 // we expected, and the first N bytes of cmp are
131                 // expected to equal the next N bytes read from
132                 // reader.
133                 for {
134                         n, err := rdr.Read(buf)
135                         if n > len(cmp) || bytes.Compare(cmp[:n], buf[:n]) != 0 {
136                                 return collisionOrCorrupt(loc[:32], expect[:len(expect)-len(cmp)], buf[:n], rdr)
137                         }
138                         cmp = cmp[n:]
139                         if err == io.EOF {
140                                 if len(cmp) != 0 {
141                                         return collisionOrCorrupt(loc[:32], expect[:len(expect)-len(cmp)], nil, nil)
142                                 }
143                                 return nil
144                         } else if err != nil {
145                                 return err
146                         } else if len(expect) == 0 && n == 0 && bytes.Compare(buf, expect) == 0 {
147                                 // When reading an empty block, EOF is not returned. Probably a Go issue.
148                                 // This is resulting in an infinite loop resulting in #7329
149                                 // Handle empty block scenario explicitly until the EOF issue is resolved.
150                                 return nil
151                         }
152                 }
153         })
154 }
155
156 // Put stores a block of data identified by the locator string
157 // "loc".  It returns nil on success.  If the volume is full, it
158 // returns a FullError.  If the write fails due to some other error,
159 // that error is returned.
160 func (v *UnixVolume) Put(loc string, block []byte) error {
161         if v.readonly {
162                 return MethodDisabledError
163         }
164         if v.IsFull() {
165                 return FullError
166         }
167         bdir := v.blockDir(loc)
168         if err := os.MkdirAll(bdir, 0755); err != nil {
169                 log.Printf("%s: could not create directory %s: %s",
170                         loc, bdir, err)
171                 return err
172         }
173
174         tmpfile, tmperr := ioutil.TempFile(bdir, "tmp"+loc)
175         if tmperr != nil {
176                 log.Printf("ioutil.TempFile(%s, tmp%s): %s", bdir, loc, tmperr)
177                 return tmperr
178         }
179         bpath := v.blockPath(loc)
180
181         if v.locker != nil {
182                 v.locker.Lock()
183                 defer v.locker.Unlock()
184         }
185         if _, err := tmpfile.Write(block); err != nil {
186                 log.Printf("%s: writing to %s: %s\n", v, bpath, err)
187                 tmpfile.Close()
188                 os.Remove(tmpfile.Name())
189                 return err
190         }
191         if err := tmpfile.Close(); err != nil {
192                 log.Printf("closing %s: %s\n", tmpfile.Name(), err)
193                 os.Remove(tmpfile.Name())
194                 return err
195         }
196         if err := os.Rename(tmpfile.Name(), bpath); err != nil {
197                 log.Printf("rename %s %s: %s\n", tmpfile.Name(), bpath, err)
198                 os.Remove(tmpfile.Name())
199                 return err
200         }
201         return nil
202 }
203
204 // Status returns a VolumeStatus struct describing the volume's
205 // current state, or nil if an error occurs.
206 //
207 func (v *UnixVolume) Status() *VolumeStatus {
208         var fs syscall.Statfs_t
209         var devnum uint64
210
211         if fi, err := os.Stat(v.root); err == nil {
212                 devnum = fi.Sys().(*syscall.Stat_t).Dev
213         } else {
214                 log.Printf("%s: os.Stat: %s\n", v, err)
215                 return nil
216         }
217
218         err := syscall.Statfs(v.root, &fs)
219         if err != nil {
220                 log.Printf("%s: statfs: %s\n", v, err)
221                 return nil
222         }
223         // These calculations match the way df calculates disk usage:
224         // "free" space is measured by fs.Bavail, but "used" space
225         // uses fs.Blocks - fs.Bfree.
226         free := fs.Bavail * uint64(fs.Bsize)
227         used := (fs.Blocks - fs.Bfree) * uint64(fs.Bsize)
228         return &VolumeStatus{v.root, devnum, free, used}
229 }
230
231 var blockDirRe = regexp.MustCompile(`^[0-9a-f]+$`)
232
233 // IndexTo writes (to the given Writer) a list of blocks found on this
234 // volume which begin with the specified prefix. If the prefix is an
235 // empty string, IndexTo writes a complete list of blocks.
236 //
237 // Each block is given in the format
238 //
239 //     locator+size modification-time {newline}
240 //
241 // e.g.:
242 //
243 //     e4df392f86be161ca6ed3773a962b8f3+67108864 1388894303
244 //     e4d41e6fd68460e0e3fc18cc746959d2+67108864 1377796043
245 //     e4de7a2810f5554cd39b36d8ddb132ff+67108864 1388701136
246 //
247 func (v *UnixVolume) IndexTo(prefix string, w io.Writer) error {
248         var lastErr error = nil
249         rootdir, err := os.Open(v.root)
250         if err != nil {
251                 return err
252         }
253         defer rootdir.Close()
254         for {
255                 names, err := rootdir.Readdirnames(1)
256                 if err == io.EOF {
257                         return lastErr
258                 } else if err != nil {
259                         return err
260                 }
261                 if !strings.HasPrefix(names[0], prefix) && !strings.HasPrefix(prefix, names[0]) {
262                         // prefix excludes all blocks stored in this dir
263                         continue
264                 }
265                 if !blockDirRe.MatchString(names[0]) {
266                         continue
267                 }
268                 blockdirpath := filepath.Join(v.root, names[0])
269                 blockdir, err := os.Open(blockdirpath)
270                 if err != nil {
271                         log.Print("Error reading ", blockdirpath, ": ", err)
272                         lastErr = err
273                         continue
274                 }
275                 for {
276                         fileInfo, err := blockdir.Readdir(1)
277                         if err == io.EOF {
278                                 break
279                         } else if err != nil {
280                                 log.Print("Error reading ", blockdirpath, ": ", err)
281                                 lastErr = err
282                                 break
283                         }
284                         name := fileInfo[0].Name()
285                         if !strings.HasPrefix(name, prefix) {
286                                 continue
287                         }
288                         _, err = fmt.Fprint(w,
289                                 name,
290                                 "+", fileInfo[0].Size(),
291                                 " ", fileInfo[0].ModTime().Unix(),
292                                 "\n")
293                 }
294                 blockdir.Close()
295         }
296 }
297
298 // Delete deletes the block data from the unix storage
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.locker != nil {
312                 v.locker.Lock()
313                 defer v.locker.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 blobSignatureTTL
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()) < blobSignatureTTL {
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 // MinFreeKilobytes.
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 < MinFreeKilobytes
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 // Writable returns false if all future Put, Mtime, and Delete calls are expected to fail.
403 func (v *UnixVolume) Writable() bool {
404         return !v.readonly
405 }
406
407 // lockfile and unlockfile use flock(2) to manage kernel file locks.
408 func lockfile(f *os.File) error {
409         return syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
410 }
411
412 func unlockfile(f *os.File) error {
413         return syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
414 }