Merge branch '11645-keepstore-storageclasses' closes #11645
[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         // Get the storage classes associated with this volume
245         GetStorageClasses() []string
246 }
247
248 // A VolumeWithExamples provides example configs to display in the
249 // -help message.
250 type VolumeWithExamples interface {
251         Volume
252         Examples() []Volume
253 }
254
255 // A VolumeManager tells callers which volumes can read, which volumes
256 // can write, and on which volume the next write should be attempted.
257 type VolumeManager interface {
258         // Mounts returns all mounts (volume attachments).
259         Mounts() []*VolumeMount
260
261         // Lookup returns the volume under the given mount
262         // UUID. Returns nil if the mount does not exist. If
263         // write==true, returns nil if the volume is not writable.
264         Lookup(uuid string, write bool) Volume
265
266         // AllReadable returns all volumes.
267         AllReadable() []Volume
268
269         // AllWritable returns all volumes that aren't known to be in
270         // a read-only state. (There is no guarantee that a write to
271         // one will succeed, though.)
272         AllWritable() []Volume
273
274         // NextWritable returns the volume where the next new block
275         // should be written. A VolumeManager can select a volume in
276         // order to distribute activity across spindles, fill up disks
277         // with more free space, etc.
278         NextWritable() Volume
279
280         // VolumeStats returns the ioStats used for tracking stats for
281         // the given Volume.
282         VolumeStats(Volume) *ioStats
283
284         // Close shuts down the volume manager cleanly.
285         Close()
286 }
287
288 // A VolumeMount is an attachment of a Volume to a VolumeManager.
289 type VolumeMount struct {
290         UUID           string
291         DeviceID       string
292         ReadOnly       bool
293         Replication    int
294         StorageClasses []string
295         volume         Volume
296 }
297
298 // Generate a UUID the way API server would for a "KeepVolumeMount"
299 // object.
300 func (*VolumeMount) generateUUID() string {
301         var max big.Int
302         _, ok := max.SetString("zzzzzzzzzzzzzzz", 36)
303         if !ok {
304                 panic("big.Int parse failed")
305         }
306         r, err := rand.Int(rand.Reader, &max)
307         if err != nil {
308                 panic(err)
309         }
310         return fmt.Sprintf("zzzzz-ivpuk-%015s", r.Text(36))
311 }
312
313 // RRVolumeManager is a round-robin VolumeManager: the Nth call to
314 // NextWritable returns the (N % len(writables))th writable Volume
315 // (where writables are all Volumes v where v.Writable()==true).
316 type RRVolumeManager struct {
317         mounts    []*VolumeMount
318         mountMap  map[string]*VolumeMount
319         readables []Volume
320         writables []Volume
321         counter   uint32
322         iostats   map[Volume]*ioStats
323 }
324
325 // MakeRRVolumeManager initializes RRVolumeManager
326 func MakeRRVolumeManager(volumes []Volume) *RRVolumeManager {
327         vm := &RRVolumeManager{
328                 iostats: make(map[Volume]*ioStats),
329         }
330         vm.mountMap = make(map[string]*VolumeMount)
331         for _, v := range volumes {
332                 sc := v.GetStorageClasses()
333                 if len(sc) == 0 {
334                         sc = []string{"default"}
335                 }
336                 mnt := &VolumeMount{
337                         UUID:           (*VolumeMount)(nil).generateUUID(),
338                         DeviceID:       v.DeviceID(),
339                         ReadOnly:       !v.Writable(),
340                         Replication:    v.Replication(),
341                         StorageClasses: sc,
342                         volume:         v,
343                 }
344                 vm.iostats[v] = &ioStats{}
345                 vm.mounts = append(vm.mounts, mnt)
346                 vm.mountMap[mnt.UUID] = mnt
347                 vm.readables = append(vm.readables, v)
348                 if v.Writable() {
349                         vm.writables = append(vm.writables, v)
350                 }
351         }
352         return vm
353 }
354
355 func (vm *RRVolumeManager) Mounts() []*VolumeMount {
356         return vm.mounts
357 }
358
359 func (vm *RRVolumeManager) Lookup(uuid string, needWrite bool) Volume {
360         if mnt, ok := vm.mountMap[uuid]; ok && (!needWrite || !mnt.ReadOnly) {
361                 return mnt.volume
362         } else {
363                 return nil
364         }
365 }
366
367 // AllReadable returns an array of all readable volumes
368 func (vm *RRVolumeManager) AllReadable() []Volume {
369         return vm.readables
370 }
371
372 // AllWritable returns an array of all writable volumes
373 func (vm *RRVolumeManager) AllWritable() []Volume {
374         return vm.writables
375 }
376
377 // NextWritable returns the next writable
378 func (vm *RRVolumeManager) NextWritable() Volume {
379         if len(vm.writables) == 0 {
380                 return nil
381         }
382         i := atomic.AddUint32(&vm.counter, 1)
383         return vm.writables[i%uint32(len(vm.writables))]
384 }
385
386 // VolumeStats returns an ioStats for the given volume.
387 func (vm *RRVolumeManager) VolumeStats(v Volume) *ioStats {
388         return vm.iostats[v]
389 }
390
391 // Close the RRVolumeManager
392 func (vm *RRVolumeManager) Close() {
393 }
394
395 // VolumeStatus describes the current condition of a volume
396 type VolumeStatus struct {
397         MountPoint string
398         DeviceNum  uint64
399         BytesFree  uint64
400         BytesUsed  uint64
401 }
402
403 // ioStats tracks I/O statistics for a volume or server
404 type ioStats struct {
405         Errors     uint64
406         Ops        uint64
407         CompareOps uint64
408         GetOps     uint64
409         PutOps     uint64
410         TouchOps   uint64
411         InBytes    uint64
412         OutBytes   uint64
413 }
414
415 type InternalStatser interface {
416         InternalStats() interface{}
417 }