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