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