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