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