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