Add 'apps/arv-web/' from commit 'f9732ad8460d013c2f28363655d0d1b91894dca5'
[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 }
56
57 func (v *UnixVolume) IOHandler() {
58         for req := range v.queue {
59                 var result IOResponse
60                 switch req.method {
61                 case KeepGet:
62                         result.data, result.err = v.Read(req.loc)
63                 case KeepPut:
64                         result.err = v.Write(req.loc, req.data)
65                 }
66                 req.reply <- &result
67         }
68 }
69
70 func MakeUnixVolume(root string, serialize bool) (v UnixVolume) {
71         if serialize {
72                 v = UnixVolume{root, make(chan *IORequest)}
73                 go v.IOHandler()
74         } else {
75                 v = UnixVolume{root, nil}
76         }
77         return
78 }
79
80 func (v *UnixVolume) Get(loc string) ([]byte, error) {
81         if v.queue == nil {
82                 return v.Read(loc)
83         }
84         reply := make(chan *IOResponse)
85         v.queue <- &IORequest{KeepGet, loc, nil, reply}
86         response := <-reply
87         return response.data, response.err
88 }
89
90 func (v *UnixVolume) Put(loc string, block []byte) error {
91         if v.queue == nil {
92                 return v.Write(loc, block)
93         }
94         reply := make(chan *IOResponse)
95         v.queue <- &IORequest{KeepPut, loc, block, reply}
96         response := <-reply
97         return response.err
98 }
99
100 func (v *UnixVolume) Touch(loc string) error {
101         p := v.blockPath(loc)
102         f, err := os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
103         if err != nil {
104                 return err
105         }
106         defer f.Close()
107         if e := lockfile(f); e != nil {
108                 return e
109         }
110         defer unlockfile(f)
111         now := time.Now().Unix()
112         utime := syscall.Utimbuf{now, now}
113         return syscall.Utime(p, &utime)
114 }
115
116 func (v *UnixVolume) Mtime(loc string) (time.Time, error) {
117         p := v.blockPath(loc)
118         if fi, err := os.Stat(p); err != nil {
119                 return time.Time{}, err
120         } else {
121                 return fi.ModTime(), nil
122         }
123 }
124
125 // Read retrieves a block identified by the locator string "loc", and
126 // returns its contents as a byte slice.
127 //
128 // If the block could not be opened or read, Read returns a nil slice
129 // and the os.Error that was generated.
130 //
131 // If the block is present but its content hash does not match loc,
132 // Read returns the block and a CorruptError.  It is the caller's
133 // responsibility to decide what (if anything) to do with the
134 // corrupted data block.
135 //
136 func (v *UnixVolume) Read(loc string) ([]byte, error) {
137         buf, err := ioutil.ReadFile(v.blockPath(loc))
138         return buf, err
139 }
140
141 // Write stores a block of data identified by the locator string
142 // "loc".  It returns nil on success.  If the volume is full, it
143 // returns a FullError.  If the write fails due to some other error,
144 // that error is returned.
145 //
146 func (v *UnixVolume) Write(loc string, block []byte) error {
147         if v.IsFull() {
148                 return FullError
149         }
150         bdir := v.blockDir(loc)
151         if err := os.MkdirAll(bdir, 0755); err != nil {
152                 log.Printf("%s: could not create directory %s: %s",
153                         loc, bdir, err)
154                 return err
155         }
156
157         tmpfile, tmperr := ioutil.TempFile(bdir, "tmp"+loc)
158         if tmperr != nil {
159                 log.Printf("ioutil.TempFile(%s, tmp%s): %s", bdir, loc, tmperr)
160                 return tmperr
161         }
162         bpath := v.blockPath(loc)
163
164         if _, err := tmpfile.Write(block); err != nil {
165                 log.Printf("%s: writing to %s: %s\n", v, bpath, err)
166                 return err
167         }
168         if err := tmpfile.Close(); err != nil {
169                 log.Printf("closing %s: %s\n", tmpfile.Name(), err)
170                 os.Remove(tmpfile.Name())
171                 return err
172         }
173         if err := os.Rename(tmpfile.Name(), bpath); err != nil {
174                 log.Printf("rename %s %s: %s\n", tmpfile.Name(), bpath, err)
175                 os.Remove(tmpfile.Name())
176                 return err
177         }
178         return nil
179 }
180
181 // Status returns a VolumeStatus struct describing the volume's
182 // current state.
183 //
184 func (v *UnixVolume) Status() *VolumeStatus {
185         var fs syscall.Statfs_t
186         var devnum uint64
187
188         if fi, err := os.Stat(v.root); err == nil {
189                 devnum = fi.Sys().(*syscall.Stat_t).Dev
190         } else {
191                 log.Printf("%s: os.Stat: %s\n", v, err)
192                 return nil
193         }
194
195         err := syscall.Statfs(v.root, &fs)
196         if err != nil {
197                 log.Printf("%s: statfs: %s\n", v, err)
198                 return nil
199         }
200         // These calculations match the way df calculates disk usage:
201         // "free" space is measured by fs.Bavail, but "used" space
202         // uses fs.Blocks - fs.Bfree.
203         free := fs.Bavail * uint64(fs.Bsize)
204         used := (fs.Blocks - fs.Bfree) * uint64(fs.Bsize)
205         return &VolumeStatus{v.root, devnum, free, used}
206 }
207
208 // Index returns a list of blocks found on this volume which begin with
209 // the specified prefix. If the prefix is an empty string, Index returns
210 // a complete list of blocks.
211 //
212 // The return value is a multiline string (separated by
213 // newlines). Each line is in the format
214 //
215 //     locator+size modification-time
216 //
217 // e.g.:
218 //
219 //     e4df392f86be161ca6ed3773a962b8f3+67108864 1388894303
220 //     e4d41e6fd68460e0e3fc18cc746959d2+67108864 1377796043
221 //     e4de7a2810f5554cd39b36d8ddb132ff+67108864 1388701136
222 //
223 func (v *UnixVolume) Index(prefix string) (output string) {
224         filepath.Walk(v.root,
225                 func(path string, info os.FileInfo, err error) error {
226                         // This WalkFunc inspects each path in the volume
227                         // and prints an index line for all files that begin
228                         // with prefix.
229                         if err != nil {
230                                 log.Printf("IndexHandler: %s: walking to %s: %s",
231                                         v, path, err)
232                                 return nil
233                         }
234                         locator := filepath.Base(path)
235                         // Skip directories that do not match prefix.
236                         // We know there is nothing interesting inside.
237                         if info.IsDir() &&
238                                 !strings.HasPrefix(locator, prefix) &&
239                                 !strings.HasPrefix(prefix, locator) {
240                                 return filepath.SkipDir
241                         }
242                         // Skip any file that is not apparently a locator, e.g. .meta files
243                         if !IsValidLocator(locator) {
244                                 return nil
245                         }
246                         // Print filenames beginning with prefix
247                         if !info.IsDir() && strings.HasPrefix(locator, prefix) {
248                                 output = output + fmt.Sprintf(
249                                         "%s+%d %d\n", locator, info.Size(), info.ModTime().Unix())
250                         }
251                         return nil
252                 })
253
254         return
255 }
256
257 func (v *UnixVolume) Delete(loc string) error {
258         p := v.blockPath(loc)
259         f, err := os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
260         if err != nil {
261                 return err
262         }
263         defer f.Close()
264         if e := lockfile(f); e != nil {
265                 return e
266         }
267         defer unlockfile(f)
268
269         // If the block has been PUT more recently than -permission_ttl,
270         // return success without removing the block.  This guards against
271         // a race condition where a block is old enough that Data Manager
272         // has added it to the trash list, but the user submitted a PUT
273         // for the block since then.
274         if fi, err := os.Stat(p); err != nil {
275                 return err
276         } else {
277                 if time.Since(fi.ModTime()) < permission_ttl {
278                         return nil
279                 }
280         }
281         return os.Remove(p)
282 }
283
284 // blockDir returns the fully qualified directory name for the directory
285 // where loc is (or would be) stored on this volume.
286 func (v *UnixVolume) blockDir(loc string) string {
287         return filepath.Join(v.root, loc[0:3])
288 }
289
290 // blockPath returns the fully qualified pathname for the path to loc
291 // on this volume.
292 func (v *UnixVolume) blockPath(loc string) string {
293         return filepath.Join(v.blockDir(loc), loc)
294 }
295
296 // IsFull returns true if the free space on the volume is less than
297 // MIN_FREE_KILOBYTES.
298 //
299 func (v *UnixVolume) IsFull() (isFull bool) {
300         fullSymlink := v.root + "/full"
301
302         // Check if the volume has been marked as full in the last hour.
303         if link, err := os.Readlink(fullSymlink); err == nil {
304                 if ts, err := strconv.Atoi(link); err == nil {
305                         fulltime := time.Unix(int64(ts), 0)
306                         if time.Since(fulltime).Hours() < 1.0 {
307                                 return true
308                         }
309                 }
310         }
311
312         if avail, err := v.FreeDiskSpace(); err == nil {
313                 isFull = avail < MIN_FREE_KILOBYTES
314         } else {
315                 log.Printf("%s: FreeDiskSpace: %s\n", v, err)
316                 isFull = false
317         }
318
319         // If the volume is full, timestamp it.
320         if isFull {
321                 now := fmt.Sprintf("%d", time.Now().Unix())
322                 os.Symlink(now, fullSymlink)
323         }
324         return
325 }
326
327 // FreeDiskSpace returns the number of unused 1k blocks available on
328 // the volume.
329 //
330 func (v *UnixVolume) FreeDiskSpace() (free uint64, err error) {
331         var fs syscall.Statfs_t
332         err = syscall.Statfs(v.root, &fs)
333         if err == nil {
334                 // Statfs output is not guaranteed to measure free
335                 // space in terms of 1K blocks.
336                 free = fs.Bavail * uint64(fs.Bsize) / 1024
337         }
338         return
339 }
340
341 func (v *UnixVolume) String() string {
342         return fmt.Sprintf("[UnixVolume %s]", v.root)
343 }
344
345 // lockfile and unlockfile use flock(2) to manage kernel file locks.
346 func lockfile(f *os.File) error {
347         return syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
348 }
349
350 func unlockfile(f *os.File) error {
351         return syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
352 }