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