7121: Update comment to match new argument name.
[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 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.locker != nil {
40                 v.locker.Lock()
41                 defer v.locker.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 // Lock the locker (if one is in use), open the file for reading, and
62 // call 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         if v.locker != nil {
65                 v.locker.Lock()
66                 defer v.locker.Unlock()
67         }
68         f, err := os.Open(path)
69         if err != nil {
70                 return err
71         }
72         defer f.Close()
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 // expect. It is functionally equivalent to Get() followed by
113 // bytes.Compare(), but uses less memory.
114 func (v *UnixVolume) Compare(loc string, expect []byte) error {
115         path := v.blockPath(loc)
116         stat, err := v.stat(path)
117         if err != nil {
118                 return err
119         }
120         bufLen := 1 << 20
121         if int64(bufLen) > stat.Size() {
122                 bufLen = int(stat.Size())
123         }
124         cmp := expect
125         buf := make([]byte, bufLen)
126         return v.getFunc(path, func(rdr io.Reader) error {
127                 // Loop invariants: all data read so far matched what
128                 // we expected, and the first N bytes of cmp are
129                 // expected to equal the next N bytes read from
130                 // reader.
131                 for {
132                         n, err := rdr.Read(buf)
133                         if n > len(cmp) || bytes.Compare(cmp[:n], buf[:n]) != 0 {
134                                 return collisionOrCorrupt(loc[:32], expect[:len(expect)-len(cmp)], buf[:n], rdr)
135                         }
136                         cmp = cmp[n:]
137                         if err == io.EOF {
138                                 if len(cmp) != 0 {
139                                         return collisionOrCorrupt(loc[:32], expect[:len(expect)-len(cmp)], nil, nil)
140                                 }
141                                 return nil
142                         } else if err != nil {
143                                 return err
144                         }
145                 }
146         })
147 }
148
149 // Put stores a block of data identified by the locator string
150 // "loc".  It returns nil on success.  If the volume is full, it
151 // returns a FullError.  If the write fails due to some other error,
152 // that error is returned.
153 func (v *UnixVolume) Put(loc string, block []byte) error {
154         if v.readonly {
155                 return MethodDisabledError
156         }
157         if v.IsFull() {
158                 return FullError
159         }
160         bdir := v.blockDir(loc)
161         if err := os.MkdirAll(bdir, 0755); err != nil {
162                 log.Printf("%s: could not create directory %s: %s",
163                         loc, bdir, err)
164                 return err
165         }
166
167         tmpfile, tmperr := ioutil.TempFile(bdir, "tmp"+loc)
168         if tmperr != nil {
169                 log.Printf("ioutil.TempFile(%s, tmp%s): %s", bdir, loc, tmperr)
170                 return tmperr
171         }
172         bpath := v.blockPath(loc)
173
174         if v.locker != nil {
175                 v.locker.Lock()
176                 defer v.locker.Unlock()
177         }
178         if _, err := tmpfile.Write(block); err != nil {
179                 log.Printf("%s: writing to %s: %s\n", v, bpath, err)
180                 tmpfile.Close()
181                 os.Remove(tmpfile.Name())
182                 return err
183         }
184         if err := tmpfile.Close(); err != nil {
185                 log.Printf("closing %s: %s\n", tmpfile.Name(), err)
186                 os.Remove(tmpfile.Name())
187                 return err
188         }
189         if err := os.Rename(tmpfile.Name(), bpath); err != nil {
190                 log.Printf("rename %s %s: %s\n", tmpfile.Name(), bpath, err)
191                 os.Remove(tmpfile.Name())
192                 return err
193         }
194         return nil
195 }
196
197 // Status returns a VolumeStatus struct describing the volume's
198 // current state, or nil if an error occurs.
199 //
200 func (v *UnixVolume) Status() *VolumeStatus {
201         var fs syscall.Statfs_t
202         var devnum uint64
203
204         if fi, err := os.Stat(v.root); err == nil {
205                 devnum = fi.Sys().(*syscall.Stat_t).Dev
206         } else {
207                 log.Printf("%s: os.Stat: %s\n", v, err)
208                 return nil
209         }
210
211         err := syscall.Statfs(v.root, &fs)
212         if err != nil {
213                 log.Printf("%s: statfs: %s\n", v, err)
214                 return nil
215         }
216         // These calculations match the way df calculates disk usage:
217         // "free" space is measured by fs.Bavail, but "used" space
218         // uses fs.Blocks - fs.Bfree.
219         free := fs.Bavail * uint64(fs.Bsize)
220         used := (fs.Blocks - fs.Bfree) * uint64(fs.Bsize)
221         return &VolumeStatus{v.root, devnum, free, used}
222 }
223
224 var blockDirRe = regexp.MustCompile(`^[0-9a-f]+$`)
225
226 // IndexTo writes (to the given Writer) a list of blocks found on this
227 // volume which begin with the specified prefix. If the prefix is an
228 // empty string, IndexTo writes a complete list of blocks.
229 //
230 // Each block is given in the format
231 //
232 //     locator+size modification-time {newline}
233 //
234 // e.g.:
235 //
236 //     e4df392f86be161ca6ed3773a962b8f3+67108864 1388894303
237 //     e4d41e6fd68460e0e3fc18cc746959d2+67108864 1377796043
238 //     e4de7a2810f5554cd39b36d8ddb132ff+67108864 1388701136
239 //
240 func (v *UnixVolume) IndexTo(prefix string, w io.Writer) error {
241         var lastErr error = nil
242         rootdir, err := os.Open(v.root)
243         if err != nil {
244                 return err
245         }
246         defer rootdir.Close()
247         for {
248                 names, err := rootdir.Readdirnames(1)
249                 if err == io.EOF {
250                         return lastErr
251                 } else if err != nil {
252                         return err
253                 }
254                 if !strings.HasPrefix(names[0], prefix) && !strings.HasPrefix(prefix, names[0]) {
255                         // prefix excludes all blocks stored in this dir
256                         continue
257                 }
258                 if !blockDirRe.MatchString(names[0]) {
259                         continue
260                 }
261                 blockdirpath := filepath.Join(v.root, names[0])
262                 blockdir, err := os.Open(blockdirpath)
263                 if err != nil {
264                         log.Print("Error reading ", blockdirpath, ": ", err)
265                         lastErr = err
266                         continue
267                 }
268                 for {
269                         fileInfo, err := blockdir.Readdir(1)
270                         if err == io.EOF {
271                                 break
272                         } else if err != nil {
273                                 log.Print("Error reading ", blockdirpath, ": ", err)
274                                 lastErr = err
275                                 break
276                         }
277                         name := fileInfo[0].Name()
278                         if !strings.HasPrefix(name, prefix) {
279                                 continue
280                         }
281                         _, err = fmt.Fprint(w,
282                                 name,
283                                 "+", fileInfo[0].Size(),
284                                 " ", fileInfo[0].ModTime().Unix(),
285                                 "\n")
286                 }
287                 blockdir.Close()
288         }
289 }
290
291 func (v *UnixVolume) Delete(loc string) error {
292         // Touch() must be called before calling Write() on a block.  Touch()
293         // also uses lockfile().  This avoids a race condition between Write()
294         // and Delete() because either (a) the file will be deleted and Touch()
295         // will signal to the caller that the file is not present (and needs to
296         // be re-written), or (b) Touch() will update the file's timestamp and
297         // Delete() will read the correct up-to-date timestamp and choose not to
298         // delete the file.
299
300         if v.readonly {
301                 return MethodDisabledError
302         }
303         if v.locker != nil {
304                 v.locker.Lock()
305                 defer v.locker.Unlock()
306         }
307         p := v.blockPath(loc)
308         f, err := os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
309         if err != nil {
310                 return err
311         }
312         defer f.Close()
313         if e := lockfile(f); e != nil {
314                 return e
315         }
316         defer unlockfile(f)
317
318         // If the block has been PUT in the last blob_signature_ttl
319         // seconds, return success without removing the block. This
320         // protects data from garbage collection until it is no longer
321         // possible for clients to retrieve the unreferenced blocks
322         // anyway (because the permission signatures have expired).
323         if fi, err := os.Stat(p); err != nil {
324                 return err
325         } else {
326                 if time.Since(fi.ModTime()) < blob_signature_ttl {
327                         return nil
328                 }
329         }
330         return os.Remove(p)
331 }
332
333 // blockDir returns the fully qualified directory name for the directory
334 // where loc is (or would be) stored on this volume.
335 func (v *UnixVolume) blockDir(loc string) string {
336         return filepath.Join(v.root, loc[0:3])
337 }
338
339 // blockPath returns the fully qualified pathname for the path to loc
340 // on this volume.
341 func (v *UnixVolume) blockPath(loc string) string {
342         return filepath.Join(v.blockDir(loc), loc)
343 }
344
345 // IsFull returns true if the free space on the volume is less than
346 // MIN_FREE_KILOBYTES.
347 //
348 func (v *UnixVolume) IsFull() (isFull bool) {
349         fullSymlink := v.root + "/full"
350
351         // Check if the volume has been marked as full in the last hour.
352         if link, err := os.Readlink(fullSymlink); err == nil {
353                 if ts, err := strconv.Atoi(link); err == nil {
354                         fulltime := time.Unix(int64(ts), 0)
355                         if time.Since(fulltime).Hours() < 1.0 {
356                                 return true
357                         }
358                 }
359         }
360
361         if avail, err := v.FreeDiskSpace(); err == nil {
362                 isFull = avail < MIN_FREE_KILOBYTES
363         } else {
364                 log.Printf("%s: FreeDiskSpace: %s\n", v, err)
365                 isFull = false
366         }
367
368         // If the volume is full, timestamp it.
369         if isFull {
370                 now := fmt.Sprintf("%d", time.Now().Unix())
371                 os.Symlink(now, fullSymlink)
372         }
373         return
374 }
375
376 // FreeDiskSpace returns the number of unused 1k blocks available on
377 // the volume.
378 //
379 func (v *UnixVolume) FreeDiskSpace() (free uint64, err error) {
380         var fs syscall.Statfs_t
381         err = syscall.Statfs(v.root, &fs)
382         if err == nil {
383                 // Statfs output is not guaranteed to measure free
384                 // space in terms of 1K blocks.
385                 free = fs.Bavail * uint64(fs.Bsize) / 1024
386         }
387         return
388 }
389
390 func (v *UnixVolume) String() string {
391         return fmt.Sprintf("[UnixVolume %s]", v.root)
392 }
393
394 func (v *UnixVolume) Writable() bool {
395         return !v.readonly
396 }
397
398 // lockfile and unlockfile use flock(2) to manage kernel file locks.
399 func lockfile(f *os.File) error {
400         return syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
401 }
402
403 func unlockfile(f *os.File) error {
404         return syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
405 }