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