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