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