11644: Accept index/pull/trash requests for a specific mount.
[arvados.git] / services / keepstore / volume.go
1 package main
2
3 import (
4         "context"
5         "crypto/rand"
6         "io"
7         "math/big"
8         "sync/atomic"
9         "time"
10 )
11
12 type BlockWriter interface {
13         // WriteBlock reads all data from r, writes it to a backing
14         // store as "loc", and returns the number of bytes written.
15         WriteBlock(ctx context.Context, loc string, r io.Reader) error
16 }
17
18 type BlockReader interface {
19         // ReadBlock retrieves data previously stored as "loc" and
20         // writes it to w.
21         ReadBlock(ctx context.Context, loc string, w io.Writer) error
22 }
23
24 // A Volume is an interface representing a Keep back-end storage unit:
25 // for example, a single mounted disk, a RAID array, an Amazon S3 volume,
26 // etc.
27 type Volume interface {
28         // Volume type as specified in config file. Examples: "S3",
29         // "Directory".
30         Type() string
31
32         // Do whatever private setup tasks and configuration checks
33         // are needed. Return non-nil if the volume is unusable (e.g.,
34         // invalid config).
35         Start() error
36
37         // Get a block: copy the block data into buf, and return the
38         // number of bytes copied.
39         //
40         // loc is guaranteed to consist of 32 or more lowercase hex
41         // digits.
42         //
43         // Get should not verify the integrity of the data: it should
44         // just return whatever was found in its backing
45         // store. (Integrity checking is the caller's responsibility.)
46         //
47         // If an error is encountered that prevents it from
48         // retrieving the data, that error should be returned so the
49         // caller can log (and send to the client) a more useful
50         // message.
51         //
52         // If the error is "not found", and there's no particular
53         // reason to expect the block to be found (other than that a
54         // caller is asking for it), the returned error should satisfy
55         // os.IsNotExist(err): this is a normal condition and will not
56         // be logged as an error (except that a 404 will appear in the
57         // access log if the block is not found on any other volumes
58         // either).
59         //
60         // If the data in the backing store is bigger than len(buf),
61         // then Get is permitted to return an error without reading
62         // any of the data.
63         //
64         // len(buf) will not exceed BlockSize.
65         Get(ctx context.Context, loc string, buf []byte) (int, error)
66
67         // Compare the given data with the stored data (i.e., what Get
68         // would return). If equal, return nil. If not, return
69         // CollisionError or DiskHashError (depending on whether the
70         // data on disk matches the expected hash), or whatever error
71         // was encountered opening/reading the stored data.
72         Compare(ctx context.Context, loc string, data []byte) error
73
74         // Put writes a block to an underlying storage device.
75         //
76         // loc is as described in Get.
77         //
78         // len(block) is guaranteed to be between 0 and BlockSize.
79         //
80         // If a block is already stored under the same name (loc) with
81         // different content, Put must either overwrite the existing
82         // data with the new data or return a non-nil error. When
83         // overwriting existing data, it must never leave the storage
84         // device in an inconsistent state: a subsequent call to Get
85         // must return either the entire old block, the entire new
86         // block, or an error. (An implementation that cannot peform
87         // atomic updates must leave the old data alone and return an
88         // error.)
89         //
90         // Put also sets the timestamp for the given locator to the
91         // current time.
92         //
93         // Put must return a non-nil error unless it can guarantee
94         // that the entire block has been written and flushed to
95         // persistent storage, and that its timestamp is current. Of
96         // course, this guarantee is only as good as the underlying
97         // storage device, but it is Put's responsibility to at least
98         // get whatever guarantee is offered by the storage device.
99         //
100         // Put should not verify that loc==hash(block): this is the
101         // caller's responsibility.
102         Put(ctx context.Context, loc string, block []byte) error
103
104         // Touch sets the timestamp for the given locator to the
105         // current time.
106         //
107         // loc is as described in Get.
108         //
109         // If invoked at time t0, Touch must guarantee that a
110         // subsequent call to Mtime will return a timestamp no older
111         // than {t0 minus one second}. For example, if Touch is called
112         // at 2015-07-07T01:23:45.67890123Z, it is acceptable for a
113         // subsequent Mtime to return any of the following:
114         //
115         //   - 2015-07-07T01:23:45.00000000Z
116         //   - 2015-07-07T01:23:45.67890123Z
117         //   - 2015-07-07T01:23:46.67890123Z
118         //   - 2015-07-08T00:00:00.00000000Z
119         //
120         // It is not acceptable for a subsequente Mtime to return
121         // either of the following:
122         //
123         //   - 2015-07-07T00:00:00.00000000Z -- ERROR
124         //   - 2015-07-07T01:23:44.00000000Z -- ERROR
125         //
126         // Touch must return a non-nil error if the timestamp cannot
127         // be updated.
128         Touch(loc string) error
129
130         // Mtime returns the stored timestamp for the given locator.
131         //
132         // loc is as described in Get.
133         //
134         // Mtime must return a non-nil error if the given block is not
135         // found or the timestamp could not be retrieved.
136         Mtime(loc string) (time.Time, error)
137
138         // IndexTo writes a complete list of locators with the given
139         // prefix for which Get() can retrieve data.
140         //
141         // prefix consists of zero or more lowercase hexadecimal
142         // digits.
143         //
144         // Each locator must be written to the given writer using the
145         // following format:
146         //
147         //   loc "+" size " " timestamp "\n"
148         //
149         // where:
150         //
151         //   - size is the number of bytes of content, given as a
152         //     decimal number with one or more digits
153         //
154         //   - timestamp is the timestamp stored for the locator,
155         //     given as a decimal number of seconds after January 1,
156         //     1970 UTC.
157         //
158         // IndexTo must not write any other data to writer: for
159         // example, it must not write any blank lines.
160         //
161         // If an error makes it impossible to provide a complete
162         // index, IndexTo must return a non-nil error. It is
163         // acceptable to return a non-nil error after writing a
164         // partial index to writer.
165         //
166         // The resulting index is not expected to be sorted in any
167         // particular order.
168         IndexTo(prefix string, writer io.Writer) error
169
170         // Trash moves the block data from the underlying storage
171         // device to trash area. The block then stays in trash for
172         // -trash-lifetime interval before it is actually deleted.
173         //
174         // loc is as described in Get.
175         //
176         // If the timestamp for the given locator is newer than
177         // BlobSignatureTTL, Trash must not trash the data.
178         //
179         // If a Trash operation overlaps with any Touch or Put
180         // operations on the same locator, the implementation must
181         // ensure one of the following outcomes:
182         //
183         //   - Touch and Put return a non-nil error, or
184         //   - Trash does not trash the block, or
185         //   - Both of the above.
186         //
187         // If it is possible for the storage device to be accessed by
188         // a different process or host, the synchronization mechanism
189         // should also guard against races with other processes and
190         // hosts. If such a mechanism is not available, there must be
191         // a mechanism for detecting unsafe configurations, alerting
192         // the operator, and aborting or falling back to a read-only
193         // state. In other words, running multiple keepstore processes
194         // with the same underlying storage device must either work
195         // reliably or fail outright.
196         //
197         // Corollary: A successful Touch or Put guarantees a block
198         // will not be trashed for at least BlobSignatureTTL
199         // seconds.
200         Trash(loc string) error
201
202         // Untrash moves block from trash back into store
203         Untrash(loc string) error
204
205         // Status returns a *VolumeStatus representing the current
206         // in-use and available storage capacity and an
207         // implementation-specific volume identifier (e.g., "mount
208         // point" for a UnixVolume).
209         Status() *VolumeStatus
210
211         // String returns an identifying label for this volume,
212         // suitable for including in log messages. It should contain
213         // enough information to uniquely identify the underlying
214         // storage device, but should not contain any credentials or
215         // secrets.
216         String() string
217
218         // Writable returns false if all future Put, Mtime, and Delete
219         // calls are expected to fail.
220         //
221         // If the volume is only temporarily unwritable -- or if Put
222         // will fail because it is full, but Mtime or Delete can
223         // succeed -- then Writable should return false.
224         Writable() bool
225
226         // Replication returns the storage redundancy of the
227         // underlying device. It will be passed on to clients in
228         // responses to PUT requests.
229         Replication() int
230
231         // EmptyTrash looks for trashed blocks that exceeded TrashLifetime
232         // and deletes them from the volume.
233         EmptyTrash()
234 }
235
236 // A VolumeWithExamples provides example configs to display in the
237 // -help message.
238 type VolumeWithExamples interface {
239         Volume
240         Examples() []Volume
241 }
242
243 // A VolumeManager tells callers which volumes can read, which volumes
244 // can write, and on which volume the next write should be attempted.
245 type VolumeManager interface {
246         // Mounts returns all mounts (volume attachments).
247         Mounts() []*VolumeMount
248
249         // Lookup returns the volume under the given mount
250         // UUID. Returns nil if the mount does not exist. If
251         // write==true, returns nil if the volume is not writable.
252         Lookup(uuid string, write bool) Volume
253
254         // AllReadable returns all volumes.
255         AllReadable() []Volume
256
257         // AllWritable returns all volumes that aren't known to be in
258         // a read-only state. (There is no guarantee that a write to
259         // one will succeed, though.)
260         AllWritable() []Volume
261
262         // NextWritable returns the volume where the next new block
263         // should be written. A VolumeManager can select a volume in
264         // order to distribute activity across spindles, fill up disks
265         // with more free space, etc.
266         NextWritable() Volume
267
268         // VolumeStats returns the ioStats used for tracking stats for
269         // the given Volume.
270         VolumeStats(Volume) *ioStats
271
272         // Close shuts down the volume manager cleanly.
273         Close()
274 }
275
276 // A VolumeMount is an attachment of a Volume to a VolumeManager.
277 type VolumeMount struct {
278         UUID     string
279         DeviceID string
280         ReadOnly bool
281         Tier     int
282         volume   Volume
283 }
284
285 // Generate a UUID the way API server would for a "KeepVolumeMount"
286 // object.
287 func (*VolumeMount) generateUUID() string {
288         var max big.Int
289         _, ok := max.SetString("zzzzzzzzzzzzzzz", 36)
290         if !ok {
291                 panic("big.Int parse failed")
292         }
293         r, err := rand.Int(rand.Reader, &max)
294         if err != nil {
295                 panic(err)
296         }
297         return "zzzzz-ivpuk-" + r.Text(36)
298 }
299
300 // RRVolumeManager is a round-robin VolumeManager: the Nth call to
301 // NextWritable returns the (N % len(writables))th writable Volume
302 // (where writables are all Volumes v where v.Writable()==true).
303 type RRVolumeManager struct {
304         mounts    []*VolumeMount
305         readables []Volume
306         writables []Volume
307         counter   uint32
308         iostats   map[Volume]*ioStats
309 }
310
311 // MakeRRVolumeManager initializes RRVolumeManager
312 func MakeRRVolumeManager(volumes []Volume) *RRVolumeManager {
313         vm := &RRVolumeManager{
314                 iostats: make(map[Volume]*ioStats),
315         }
316         for _, v := range volumes {
317                 mnt := &VolumeMount{
318                         UUID:     (*VolumeMount)(nil).generateUUID(),
319                         DeviceID: "",
320                         ReadOnly: !v.Writable(),
321                         Tier:     1,
322                         volume:   v,
323                 }
324                 if v, ok := v.(interface {
325                         DeviceID() string
326                 }); ok {
327                         mnt.DeviceID = v.DeviceID()
328                 }
329                 vm.iostats[v] = &ioStats{}
330                 vm.mounts = append(vm.mounts, mnt)
331                 vm.readables = append(vm.readables, v)
332                 if v.Writable() {
333                         vm.writables = append(vm.writables, v)
334                 }
335         }
336         return vm
337 }
338
339 func (vm *RRVolumeManager) Mounts() []*VolumeMount {
340         return vm.mounts
341 }
342
343 func (vm *RRVolumeManager) Lookup(uuid string, needWrite bool) Volume {
344         for _, mnt := range vm.mounts {
345                 if mnt.UUID == uuid && (!needWrite || !mnt.ReadOnly) {
346                         return mnt.volume
347                 }
348         }
349         return nil
350 }
351
352 // AllReadable returns an array of all readable volumes
353 func (vm *RRVolumeManager) AllReadable() []Volume {
354         return vm.readables
355 }
356
357 // AllWritable returns an array of all writable volumes
358 func (vm *RRVolumeManager) AllWritable() []Volume {
359         return vm.writables
360 }
361
362 // NextWritable returns the next writable
363 func (vm *RRVolumeManager) NextWritable() Volume {
364         if len(vm.writables) == 0 {
365                 return nil
366         }
367         i := atomic.AddUint32(&vm.counter, 1)
368         return vm.writables[i%uint32(len(vm.writables))]
369 }
370
371 // VolumeStats returns an ioStats for the given volume.
372 func (vm *RRVolumeManager) VolumeStats(v Volume) *ioStats {
373         return vm.iostats[v]
374 }
375
376 // Close the RRVolumeManager
377 func (vm *RRVolumeManager) Close() {
378 }
379
380 // VolumeStatus describes the current condition of a volume
381 type VolumeStatus struct {
382         MountPoint string
383         DeviceNum  uint64
384         BytesFree  uint64
385         BytesUsed  uint64
386 }
387
388 // ioStats tracks I/O statistics for a volume or server
389 type ioStats struct {
390         Errors     uint64
391         Ops        uint64
392         CompareOps uint64
393         GetOps     uint64
394         PutOps     uint64
395         TouchOps   uint64
396         InBytes    uint64
397         OutBytes   uint64
398 }
399
400 type InternalStatser interface {
401         InternalStats() interface{}
402 }