5748: Clean up comments and variable names.
[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, IndexTo 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                         basename := filepath.Base(path)
242                         if info.IsDir() &&
243                                 !strings.HasPrefix(basename, prefix) &&
244                                 !strings.HasPrefix(prefix, basename) {
245                                 // Skip directories that do not match
246                                 // prefix. We know there is nothing
247                                 // interesting inside.
248                                 return filepath.SkipDir
249                         }
250                         if info.IsDir() ||
251                                 !IsValidLocator(basename) ||
252                                 !strings.HasPrefix(basename, prefix) {
253                                 return nil
254                         }
255                         _, err = fmt.Fprintf(w, "%s+%d %d\n",
256                                 basename, info.Size(), info.ModTime().Unix())
257                         return err
258                 })
259 }
260
261 func (v *UnixVolume) Delete(loc string) error {
262         // Touch() must be called before calling Write() on a block.  Touch()
263         // also uses lockfile().  This avoids a race condition between Write()
264         // and Delete() because either (a) the file will be deleted and Touch()
265         // will signal to the caller that the file is not present (and needs to
266         // be re-written), or (b) Touch() will update the file's timestamp and
267         // Delete() will read the correct up-to-date timestamp and choose not to
268         // delete the file.
269
270         if v.readonly {
271                 return MethodDisabledError
272         }
273         p := v.blockPath(loc)
274         f, err := os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
275         if err != nil {
276                 return err
277         }
278         defer f.Close()
279         if e := lockfile(f); e != nil {
280                 return e
281         }
282         defer unlockfile(f)
283
284         // If the block has been PUT in the last blob_signature_ttl
285         // seconds, return success without removing the block. This
286         // protects data from garbage collection until it is no longer
287         // possible for clients to retrieve the unreferenced blocks
288         // anyway (because the permission signatures have expired).
289         if fi, err := os.Stat(p); err != nil {
290                 return err
291         } else {
292                 if time.Since(fi.ModTime()) < blob_signature_ttl {
293                         return nil
294                 }
295         }
296         return os.Remove(p)
297 }
298
299 // blockDir returns the fully qualified directory name for the directory
300 // where loc is (or would be) stored on this volume.
301 func (v *UnixVolume) blockDir(loc string) string {
302         return filepath.Join(v.root, loc[0:3])
303 }
304
305 // blockPath returns the fully qualified pathname for the path to loc
306 // on this volume.
307 func (v *UnixVolume) blockPath(loc string) string {
308         return filepath.Join(v.blockDir(loc), loc)
309 }
310
311 // IsFull returns true if the free space on the volume is less than
312 // MIN_FREE_KILOBYTES.
313 //
314 func (v *UnixVolume) IsFull() (isFull bool) {
315         fullSymlink := v.root + "/full"
316
317         // Check if the volume has been marked as full in the last hour.
318         if link, err := os.Readlink(fullSymlink); err == nil {
319                 if ts, err := strconv.Atoi(link); err == nil {
320                         fulltime := time.Unix(int64(ts), 0)
321                         if time.Since(fulltime).Hours() < 1.0 {
322                                 return true
323                         }
324                 }
325         }
326
327         if avail, err := v.FreeDiskSpace(); err == nil {
328                 isFull = avail < MIN_FREE_KILOBYTES
329         } else {
330                 log.Printf("%s: FreeDiskSpace: %s\n", v, err)
331                 isFull = false
332         }
333
334         // If the volume is full, timestamp it.
335         if isFull {
336                 now := fmt.Sprintf("%d", time.Now().Unix())
337                 os.Symlink(now, fullSymlink)
338         }
339         return
340 }
341
342 // FreeDiskSpace returns the number of unused 1k blocks available on
343 // the volume.
344 //
345 func (v *UnixVolume) FreeDiskSpace() (free uint64, err error) {
346         var fs syscall.Statfs_t
347         err = syscall.Statfs(v.root, &fs)
348         if err == nil {
349                 // Statfs output is not guaranteed to measure free
350                 // space in terms of 1K blocks.
351                 free = fs.Bavail * uint64(fs.Bsize) / 1024
352         }
353         return
354 }
355
356 func (v *UnixVolume) String() string {
357         return fmt.Sprintf("[UnixVolume %s]", v.root)
358 }
359
360 func (v *UnixVolume) Writable() bool {
361         return !v.readonly
362 }
363
364 // lockfile and unlockfile use flock(2) to manage kernel file locks.
365 func lockfile(f *os.File) error {
366         return syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
367 }
368
369 func unlockfile(f *os.File) error {
370         return syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
371 }