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