a7ad6f9e499c80439c27cb1beed33060674ed776
[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"
8         "io/ioutil"
9         "log"
10         "os"
11         "path/filepath"
12         "regexp"
13         "strconv"
14         "strings"
15         "sync"
16         "syscall"
17         "time"
18 )
19
20 // A UnixVolume stores and retrieves blocks in a local directory.
21 type UnixVolume struct {
22         root      string // path to the volume's root directory
23         serialize bool
24         readonly  bool
25         mutex     sync.Mutex
26 }
27
28 func (v *UnixVolume) Touch(loc string) error {
29         if v.readonly {
30                 return MethodDisabledError
31         }
32         p := v.blockPath(loc)
33         f, err := os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
34         if err != nil {
35                 return err
36         }
37         defer f.Close()
38         if v.serialize {
39                 v.mutex.Lock()
40                 defer v.mutex.Unlock()
41         }
42         if e := lockfile(f); e != nil {
43                 return e
44         }
45         defer unlockfile(f)
46         now := time.Now().Unix()
47         utime := syscall.Utimbuf{now, now}
48         return syscall.Utime(p, &utime)
49 }
50
51 func (v *UnixVolume) Mtime(loc string) (time.Time, error) {
52         p := v.blockPath(loc)
53         if fi, err := os.Stat(p); err != nil {
54                 return time.Time{}, err
55         } else {
56                 return fi.ModTime(), nil
57         }
58 }
59
60 // Get retrieves a block identified by the locator string "loc", and
61 // returns its contents as a byte slice.
62 //
63 // If the block could not be found, opened, or read, Get returns a nil
64 // slice and whatever non-nil error was returned by Stat or ReadFile.
65 func (v *UnixVolume) Get(loc string) ([]byte, error) {
66         path := v.blockPath(loc)
67         stat, err := os.Stat(path)
68         if err != nil {
69                 return nil, err
70         }
71         if stat.Size() < 0 {
72                 return nil, os.ErrInvalid
73         } else if stat.Size() == 0 {
74                 return bufs.Get(0), nil
75         } else if stat.Size() > BLOCKSIZE {
76                 return nil, TooLongError
77         }
78         f, err := os.Open(path)
79         if err != nil {
80                 return nil, err
81         }
82         defer f.Close()
83         buf := bufs.Get(int(stat.Size()))
84         if v.serialize {
85                 v.mutex.Lock()
86                 defer v.mutex.Unlock()
87         }
88         _, err = io.ReadFull(f, buf)
89         if err != nil {
90                 bufs.Put(buf)
91                 return nil, err
92         }
93         return buf, nil
94 }
95
96 // Put stores a block of data identified by the locator string
97 // "loc".  It returns nil on success.  If the volume is full, it
98 // returns a FullError.  If the write fails due to some other error,
99 // that error is returned.
100 func (v *UnixVolume) Put(loc string, block []byte) error {
101         if v.readonly {
102                 return MethodDisabledError
103         }
104         if v.IsFull() {
105                 return FullError
106         }
107         bdir := v.blockDir(loc)
108         if err := os.MkdirAll(bdir, 0755); err != nil {
109                 log.Printf("%s: could not create directory %s: %s",
110                         loc, bdir, err)
111                 return err
112         }
113
114         tmpfile, tmperr := ioutil.TempFile(bdir, "tmp"+loc)
115         if tmperr != nil {
116                 log.Printf("ioutil.TempFile(%s, tmp%s): %s", bdir, loc, tmperr)
117                 return tmperr
118         }
119         bpath := v.blockPath(loc)
120
121         if v.serialize {
122                 v.mutex.Lock()
123                 defer v.mutex.Unlock()
124         }
125         if _, err := tmpfile.Write(block); err != nil {
126                 log.Printf("%s: writing to %s: %s\n", v, bpath, err)
127                 tmpfile.Close()
128                 os.Remove(tmpfile.Name())
129                 return err
130         }
131         if err := tmpfile.Close(); err != nil {
132                 log.Printf("closing %s: %s\n", tmpfile.Name(), err)
133                 os.Remove(tmpfile.Name())
134                 return err
135         }
136         if err := os.Rename(tmpfile.Name(), bpath); err != nil {
137                 log.Printf("rename %s %s: %s\n", tmpfile.Name(), bpath, err)
138                 os.Remove(tmpfile.Name())
139                 return err
140         }
141         return nil
142 }
143
144 // Status returns a VolumeStatus struct describing the volume's
145 // current state, or nil if an error occurs.
146 //
147 func (v *UnixVolume) Status() *VolumeStatus {
148         var fs syscall.Statfs_t
149         var devnum uint64
150
151         if fi, err := os.Stat(v.root); err == nil {
152                 devnum = fi.Sys().(*syscall.Stat_t).Dev
153         } else {
154                 log.Printf("%s: os.Stat: %s\n", v, err)
155                 return nil
156         }
157
158         err := syscall.Statfs(v.root, &fs)
159         if err != nil {
160                 log.Printf("%s: statfs: %s\n", v, err)
161                 return nil
162         }
163         // These calculations match the way df calculates disk usage:
164         // "free" space is measured by fs.Bavail, but "used" space
165         // uses fs.Blocks - fs.Bfree.
166         free := fs.Bavail * uint64(fs.Bsize)
167         used := (fs.Blocks - fs.Bfree) * uint64(fs.Bsize)
168         return &VolumeStatus{v.root, devnum, free, used}
169 }
170
171 var blockDirRe = regexp.MustCompile(`^[0-9a-f]+$`)
172
173 // IndexTo writes (to the given Writer) a list of blocks found on this
174 // volume which begin with the specified prefix. If the prefix is an
175 // empty string, IndexTo writes a complete list of blocks.
176 //
177 // Each block is given in the format
178 //
179 //     locator+size modification-time {newline}
180 //
181 // e.g.:
182 //
183 //     e4df392f86be161ca6ed3773a962b8f3+67108864 1388894303
184 //     e4d41e6fd68460e0e3fc18cc746959d2+67108864 1377796043
185 //     e4de7a2810f5554cd39b36d8ddb132ff+67108864 1388701136
186 //
187 func (v *UnixVolume) IndexTo(prefix string, w io.Writer) error {
188         var lastErr error = nil
189         rootdir, err := os.Open(v.root)
190         if err != nil {
191                 return err
192         }
193         defer rootdir.Close()
194         for {
195                 names, err := rootdir.Readdirnames(1)
196                 if err == io.EOF {
197                         return lastErr
198                 } else if err != nil {
199                         return err
200                 }
201                 if !strings.HasPrefix(names[0], prefix) && !strings.HasPrefix(prefix, names[0]) {
202                         // prefix excludes all blocks stored in this dir
203                         continue
204                 }
205                 if !blockDirRe.MatchString(names[0]) {
206                         continue
207                 }
208                 blockdirpath := filepath.Join(v.root, names[0])
209                 blockdir, err := os.Open(blockdirpath)
210                 if err != nil {
211                         log.Print("Error reading ", blockdirpath, ": ", err)
212                         lastErr = err
213                         continue
214                 }
215                 for {
216                         fileInfo, err := blockdir.Readdir(1)
217                         if err == io.EOF {
218                                 break
219                         } else if err != nil {
220                                 log.Print("Error reading ", blockdirpath, ": ", err)
221                                 lastErr = err
222                                 break
223                         }
224                         name := fileInfo[0].Name()
225                         if !strings.HasPrefix(name, prefix) {
226                                 continue
227                         }
228                         _, err = fmt.Fprint(w,
229                                 name,
230                                 "+", fileInfo[0].Size(),
231                                 " ", fileInfo[0].ModTime().Unix(),
232                                 "\n")
233                 }
234                 blockdir.Close()
235         }
236 }
237
238 func (v *UnixVolume) Delete(loc string) error {
239         // Touch() must be called before calling Write() on a block.  Touch()
240         // also uses lockfile().  This avoids a race condition between Write()
241         // and Delete() because either (a) the file will be deleted and Touch()
242         // will signal to the caller that the file is not present (and needs to
243         // be re-written), or (b) Touch() will update the file's timestamp and
244         // Delete() will read the correct up-to-date timestamp and choose not to
245         // delete the file.
246
247         if v.readonly {
248                 return MethodDisabledError
249         }
250         if v.serialize {
251                 v.mutex.Lock()
252                 defer v.mutex.Unlock()
253         }
254         p := v.blockPath(loc)
255         f, err := os.OpenFile(p, os.O_RDWR|os.O_APPEND, 0644)
256         if err != nil {
257                 return err
258         }
259         defer f.Close()
260         if e := lockfile(f); e != nil {
261                 return e
262         }
263         defer unlockfile(f)
264
265         // If the block has been PUT in the last blob_signature_ttl
266         // seconds, return success without removing the block. This
267         // protects data from garbage collection until it is no longer
268         // possible for clients to retrieve the unreferenced blocks
269         // anyway (because the permission signatures have expired).
270         if fi, err := os.Stat(p); err != nil {
271                 return err
272         } else {
273                 if time.Since(fi.ModTime()) < blob_signature_ttl {
274                         return nil
275                 }
276         }
277         return os.Remove(p)
278 }
279
280 // blockDir returns the fully qualified directory name for the directory
281 // where loc is (or would be) stored on this volume.
282 func (v *UnixVolume) blockDir(loc string) string {
283         return filepath.Join(v.root, loc[0:3])
284 }
285
286 // blockPath returns the fully qualified pathname for the path to loc
287 // on this volume.
288 func (v *UnixVolume) blockPath(loc string) string {
289         return filepath.Join(v.blockDir(loc), loc)
290 }
291
292 // IsFull returns true if the free space on the volume is less than
293 // MIN_FREE_KILOBYTES.
294 //
295 func (v *UnixVolume) IsFull() (isFull bool) {
296         fullSymlink := v.root + "/full"
297
298         // Check if the volume has been marked as full in the last hour.
299         if link, err := os.Readlink(fullSymlink); err == nil {
300                 if ts, err := strconv.Atoi(link); err == nil {
301                         fulltime := time.Unix(int64(ts), 0)
302                         if time.Since(fulltime).Hours() < 1.0 {
303                                 return true
304                         }
305                 }
306         }
307
308         if avail, err := v.FreeDiskSpace(); err == nil {
309                 isFull = avail < MIN_FREE_KILOBYTES
310         } else {
311                 log.Printf("%s: FreeDiskSpace: %s\n", v, err)
312                 isFull = false
313         }
314
315         // If the volume is full, timestamp it.
316         if isFull {
317                 now := fmt.Sprintf("%d", time.Now().Unix())
318                 os.Symlink(now, fullSymlink)
319         }
320         return
321 }
322
323 // FreeDiskSpace returns the number of unused 1k blocks available on
324 // the volume.
325 //
326 func (v *UnixVolume) FreeDiskSpace() (free uint64, err error) {
327         var fs syscall.Statfs_t
328         err = syscall.Statfs(v.root, &fs)
329         if err == nil {
330                 // Statfs output is not guaranteed to measure free
331                 // space in terms of 1K blocks.
332                 free = fs.Bavail * uint64(fs.Bsize) / 1024
333         }
334         return
335 }
336
337 func (v *UnixVolume) String() string {
338         return fmt.Sprintf("[UnixVolume %s]", v.root)
339 }
340
341 func (v *UnixVolume) Writable() bool {
342         return !v.readonly
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 }