5748: Write index data to http.ResponseWriter, instead of using string
[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         "fmt"
7         "io"
8         "io/ioutil"
9         "log"
10         "os"
11         "path/filepath"
12         "strconv"
13         "strings"
14         "syscall"
15         "time"
16 )
17
18 // IORequests are encapsulated Get or Put requests.  They are used to
19 // implement serialized I/O (i.e. only one read/write operation per
20 // volume). When running in serialized mode, the Keep front end sends
21 // IORequests on a channel to an IORunner, which handles them one at a
22 // time and returns an IOResponse.
23 //
24 type IOMethod int
25
26 const (
27         KeepGet IOMethod = iota
28         KeepPut
29 )
30
31 type IORequest struct {
32         method IOMethod
33         loc    string
34         data   []byte
35         reply  chan *IOResponse
36 }
37
38 type IOResponse struct {
39         data []byte
40         err  error
41 }
42
43 // A UnixVolume has the following properties:
44 //
45 //   root
46 //       the path to the volume's root directory
47 //   queue
48 //       A channel of IORequests. If non-nil, all I/O requests for
49 //       this volume should be queued on this channel; the result
50 //       will be delivered on the IOResponse channel supplied in the
51 //       request.
52 //
53 type UnixVolume struct {
54         root     string // path to this volume
55         queue    chan *IORequest
56         readonly bool
57 }
58
59 func (v *UnixVolume) IOHandler() {
60         for req := range v.queue {
61                 var result IOResponse
62                 switch req.method {
63                 case KeepGet:
64                         result.data, result.err = v.Read(req.loc)
65                 case KeepPut:
66                         result.err = v.Write(req.loc, req.data)
67                 }
68                 req.reply <- &result
69         }
70 }
71
72 func MakeUnixVolume(root string, serialize bool, readonly bool) *UnixVolume {
73         v := &UnixVolume{
74                 root:     root,
75                 queue:    nil,
76                 readonly: readonly,
77         }
78         if serialize {
79                 v.queue = make(chan *IORequest)
80                 go v.IOHandler()
81         }
82         return v
83 }
84
85 func (v *UnixVolume) Get(loc string) ([]byte, error) {
86         if v.queue == nil {
87                 return v.Read(loc)
88         }
89         reply := make(chan *IOResponse)
90         v.queue <- &IORequest{KeepGet, loc, nil, reply}
91         response := <-reply
92         return response.data, response.err
93 }
94
95 func (v *UnixVolume) Put(loc string, block []byte) error {
96         if v.readonly {
97                 return MethodDisabledError
98         }
99         if v.queue == nil {
100                 return v.Write(loc, block)
101         }
102         reply := make(chan *IOResponse)
103         v.queue <- &IORequest{KeepPut, loc, block, reply}
104         response := <-reply
105         return response.err
106 }
107
108 func (v *UnixVolume) Touch(loc string) error {
109         if v.readonly {
110                 return MethodDisabledError
111         }
112         p := v.blockPath(loc)
113         f, err := os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
114         if err != nil {
115                 return err
116         }
117         defer f.Close()
118         if e := lockfile(f); e != nil {
119                 return e
120         }
121         defer unlockfile(f)
122         now := time.Now().Unix()
123         utime := syscall.Utimbuf{now, now}
124         return syscall.Utime(p, &utime)
125 }
126
127 func (v *UnixVolume) Mtime(loc string) (time.Time, error) {
128         p := v.blockPath(loc)
129         if fi, err := os.Stat(p); err != nil {
130                 return time.Time{}, err
131         } else {
132                 return fi.ModTime(), nil
133         }
134 }
135
136 // Read retrieves a block identified by the locator string "loc", and
137 // returns its contents as a byte slice.
138 //
139 // If the block could not be opened or read, Read returns a nil slice
140 // and the os.Error that was generated.
141 //
142 // If the block is present but its content hash does not match loc,
143 // Read returns the block and a CorruptError.  It is the caller's
144 // responsibility to decide what (if anything) to do with the
145 // corrupted data block.
146 //
147 func (v *UnixVolume) Read(loc string) ([]byte, error) {
148         buf, err := ioutil.ReadFile(v.blockPath(loc))
149         return buf, err
150 }
151
152 // Write stores a block of data identified by the locator string
153 // "loc".  It returns nil on success.  If the volume is full, it
154 // returns a FullError.  If the write fails due to some other error,
155 // that error is returned.
156 //
157 func (v *UnixVolume) Write(loc string, block []byte) error {
158         if v.IsFull() {
159                 return FullError
160         }
161         bdir := v.blockDir(loc)
162         if err := os.MkdirAll(bdir, 0755); err != nil {
163                 log.Printf("%s: could not create directory %s: %s",
164                         loc, bdir, err)
165                 return err
166         }
167
168         tmpfile, tmperr := ioutil.TempFile(bdir, "tmp"+loc)
169         if tmperr != nil {
170                 log.Printf("ioutil.TempFile(%s, tmp%s): %s", bdir, loc, tmperr)
171                 return tmperr
172         }
173         bpath := v.blockPath(loc)
174
175         if _, err := tmpfile.Write(block); err != nil {
176                 log.Printf("%s: writing to %s: %s\n", v, bpath, err)
177                 return err
178         }
179         if err := tmpfile.Close(); err != nil {
180                 log.Printf("closing %s: %s\n", tmpfile.Name(), err)
181                 os.Remove(tmpfile.Name())
182                 return err
183         }
184         if err := os.Rename(tmpfile.Name(), bpath); err != nil {
185                 log.Printf("rename %s %s: %s\n", tmpfile.Name(), bpath, err)
186                 os.Remove(tmpfile.Name())
187                 return err
188         }
189         return nil
190 }
191
192 // Status returns a VolumeStatus struct describing the volume's
193 // current state.
194 //
195 func (v *UnixVolume) Status() *VolumeStatus {
196         var fs syscall.Statfs_t
197         var devnum uint64
198
199         if fi, err := os.Stat(v.root); err == nil {
200                 devnum = fi.Sys().(*syscall.Stat_t).Dev
201         } else {
202                 log.Printf("%s: os.Stat: %s\n", v, err)
203                 return nil
204         }
205
206         err := syscall.Statfs(v.root, &fs)
207         if err != nil {
208                 log.Printf("%s: statfs: %s\n", v, err)
209                 return nil
210         }
211         // These calculations match the way df calculates disk usage:
212         // "free" space is measured by fs.Bavail, but "used" space
213         // uses fs.Blocks - fs.Bfree.
214         free := fs.Bavail * uint64(fs.Bsize)
215         used := (fs.Blocks - fs.Bfree) * uint64(fs.Bsize)
216         return &VolumeStatus{v.root, devnum, free, used}
217 }
218
219 // IndexTo writes (to the given Writer) a list of blocks found on this
220 // volume which begin with the specified prefix. If the prefix is an
221 // empty string, Index writes a complete list of blocks.
222 //
223 // Each block is given in the format
224 //
225 //     locator+size modification-time {newline}
226 //
227 // e.g.:
228 //
229 //     e4df392f86be161ca6ed3773a962b8f3+67108864 1388894303
230 //     e4d41e6fd68460e0e3fc18cc746959d2+67108864 1377796043
231 //     e4de7a2810f5554cd39b36d8ddb132ff+67108864 1388701136
232 //
233 func (v *UnixVolume) IndexTo(prefix string, w io.Writer) error {
234         return filepath.Walk(v.root,
235                 func(path string, info os.FileInfo, err error) error {
236                         if err != nil {
237                                 log.Printf("%s: IndexTo Walk error at %s: %s",
238                                         v, path, err)
239                                 return nil
240                         }
241                         locator := filepath.Base(path)
242                         // Skip directories that do not match prefix.
243                         // We know there is nothing interesting inside.
244                         if info.IsDir() &&
245                                 !strings.HasPrefix(locator, prefix) &&
246                                 !strings.HasPrefix(prefix, locator) {
247                                 return filepath.SkipDir
248                         }
249                         // Skip any file that is not apparently a locator, e.g. .meta files
250                         if info.IsDir() || !IsValidLocator(locator) {
251                                 return nil
252                         }
253                         // Print filenames beginning with prefix
254                         if !strings.HasPrefix(locator, prefix) {
255                                 return nil
256                         }
257                         _, err = fmt.Fprintf(w, "%s+%d %d\n",
258                                 locator, info.Size(), info.ModTime().Unix())
259                         return err
260                 })
261 }
262
263 func (v *UnixVolume) Delete(loc string) error {
264         // Touch() must be called before calling Write() on a block.  Touch()
265         // also uses lockfile().  This avoids a race condition between Write()
266         // and Delete() because either (a) the file will be deleted and Touch()
267         // will signal to the caller that the file is not present (and needs to
268         // be re-written), or (b) Touch() will update the file's timestamp and
269         // Delete() will read the correct up-to-date timestamp and choose not to
270         // delete the file.
271
272         if v.readonly {
273                 return MethodDisabledError
274         }
275         p := v.blockPath(loc)
276         f, err := os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
277         if err != nil {
278                 return err
279         }
280         defer f.Close()
281         if e := lockfile(f); e != nil {
282                 return e
283         }
284         defer unlockfile(f)
285
286         // If the block has been PUT in the last blob_signature_ttl
287         // seconds, return success without removing the block. This
288         // protects data from garbage collection until it is no longer
289         // possible for clients to retrieve the unreferenced blocks
290         // anyway (because the permission signatures have expired).
291         if fi, err := os.Stat(p); err != nil {
292                 return err
293         } else {
294                 if time.Since(fi.ModTime()) < blob_signature_ttl {
295                         return nil
296                 }
297         }
298         return os.Remove(p)
299 }
300
301 // blockDir returns the fully qualified directory name for the directory
302 // where loc is (or would be) stored on this volume.
303 func (v *UnixVolume) blockDir(loc string) string {
304         return filepath.Join(v.root, loc[0:3])
305 }
306
307 // blockPath returns the fully qualified pathname for the path to loc
308 // on this volume.
309 func (v *UnixVolume) blockPath(loc string) string {
310         return filepath.Join(v.blockDir(loc), loc)
311 }
312
313 // IsFull returns true if the free space on the volume is less than
314 // MIN_FREE_KILOBYTES.
315 //
316 func (v *UnixVolume) IsFull() (isFull bool) {
317         fullSymlink := v.root + "/full"
318
319         // Check if the volume has been marked as full in the last hour.
320         if link, err := os.Readlink(fullSymlink); err == nil {
321                 if ts, err := strconv.Atoi(link); err == nil {
322                         fulltime := time.Unix(int64(ts), 0)
323                         if time.Since(fulltime).Hours() < 1.0 {
324                                 return true
325                         }
326                 }
327         }
328
329         if avail, err := v.FreeDiskSpace(); err == nil {
330                 isFull = avail < MIN_FREE_KILOBYTES
331         } else {
332                 log.Printf("%s: FreeDiskSpace: %s\n", v, err)
333                 isFull = false
334         }
335
336         // If the volume is full, timestamp it.
337         if isFull {
338                 now := fmt.Sprintf("%d", time.Now().Unix())
339                 os.Symlink(now, fullSymlink)
340         }
341         return
342 }
343
344 // FreeDiskSpace returns the number of unused 1k blocks available on
345 // the volume.
346 //
347 func (v *UnixVolume) FreeDiskSpace() (free uint64, err error) {
348         var fs syscall.Statfs_t
349         err = syscall.Statfs(v.root, &fs)
350         if err == nil {
351                 // Statfs output is not guaranteed to measure free
352                 // space in terms of 1K blocks.
353                 free = fs.Bavail * uint64(fs.Bsize) / 1024
354         }
355         return
356 }
357
358 func (v *UnixVolume) String() string {
359         return fmt.Sprintf("[UnixVolume %s]", v.root)
360 }
361
362 func (v *UnixVolume) Writable() bool {
363         return !v.readonly
364 }
365
366 // lockfile and unlockfile use flock(2) to manage kernel file locks.
367 func lockfile(f *os.File) error {
368         return syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
369 }
370
371 func unlockfile(f *os.File) error {
372         return syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
373 }