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