/
diskaccess.go
435 lines (351 loc) · 12.1 KB
/
diskaccess.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
// diskaccess ties together DB metadata read/write in addition to writing to disk
package stodiskaccess
import (
"bytes"
"compress/gzip"
"context"
"crypto/aes"
"crypto/cipher"
"encoding/binary"
"errors"
"fmt"
"hash/crc32"
"io"
"io/ioutil"
"os"
"github.com/function61/gokit/hashverifyreader"
"github.com/function61/gokit/jsonfile"
"github.com/function61/varasto/pkg/blobstore"
"github.com/function61/varasto/pkg/mutexmap"
"github.com/function61/varasto/pkg/stotypes"
"github.com/function61/varasto/pkg/stoutils"
)
var (
ErrVolumeDescriptorNotFound = errors.New("volume descriptor not found")
volumeDescriptorRef = stotypes.BlobRef{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}
)
type Controller struct {
metadataStore MetadataStore
mountedDrivers map[int]blobstore.Driver // only mounted drivers
routingCosts map[int]int // volume id => cost. lower (local disks) is better than higher (remote disks)
writingBlobs *mutexmap.M
}
type volumeDescriptor struct {
VolumeId string `json:"volume_uuid"`
}
func New(metadataStore MetadataStore) *Controller {
return &Controller{
metadataStore,
map[int]blobstore.Driver{},
map[int]int{},
mutexmap.New(),
}
}
// call only during server boot (this is not threadsafe)
func (d *Controller) Mount(ctx context.Context, volumeId int, expectedVolumeUuid string, driver blobstore.Driver) error {
if err := d.Mountable(ctx, volumeId, expectedVolumeUuid, driver); err != nil {
return err
}
d.mountedDrivers[volumeId] = driver
d.routingCosts[volumeId] = driver.RoutingCost()
return nil
}
// mount command currently wants to check if volume would be mountable without actually mounting it
func (d *Controller) Mountable(ctx context.Context, volumeId int, expectedVolumeUuid string, driver blobstore.Driver) error {
if _, exists := d.mountedDrivers[volumeId]; exists {
return errors.New("driver for volumeId already defined")
}
if err := d.verifyOnDiskVolumeUuid(ctx, driver, expectedVolumeUuid); err != nil {
return err
}
return nil
}
func (d *Controller) IsMounted(volumeId int) bool {
_, mounted := d.mountedDrivers[volumeId]
return mounted
}
// in theory we wouldn't need to do this since we could do a Fetch()-followed by Store(),
// but we can optimize by just transferring the raw on-disk format
func (d *Controller) Replicate(ctx context.Context, fromVolumeId int, toVolumeId int, ref stotypes.BlobRef) error {
fromDriver, err := d.driverFor(fromVolumeId)
if err != nil {
return err
}
toDriver, err := d.driverFor(toVolumeId)
if err != nil {
return err
}
expectedCrc32, err := d.metadataStore.QueryBlobCrc32(ref)
if err != nil {
return fmt.Errorf("Replicate() QueryBlobCrc32: %v", err)
}
rawContent, err := fromDriver.RawFetch(ctx, ref)
if err != nil {
return err
}
defer rawContent.Close()
crc32VerifiedReader := hashverifyreader.New(rawContent, crc32.NewIEEE(), expectedCrc32)
if err := toDriver.RawStore(ctx, ref, crc32VerifiedReader); err != nil {
return err
}
return d.metadataStore.WriteBlobReplicated(ref, toVolumeId)
}
func (d *Controller) WriteBlob(
volumeId int,
collId string,
ref stotypes.BlobRef,
content io.Reader,
maybeCompressible bool,
) error {
return d.WriteBlobNoVerify(
volumeId,
collId,
ref,
stoutils.BlobHashVerifier(content, ref),
maybeCompressible)
}
func (d *Controller) WriteBlobNoVerify(
volumeId int,
collId string,
ref stotypes.BlobRef,
content io.Reader,
maybeCompressible bool,
) error {
// FIXME: this will lock for a really long time if the HTTP connection breaks (TODO: benchmark for how long).
// should we have some kind of timeoutreader?
unlock, ok := d.writingBlobs.TryLock(ref.AsHex())
if !ok {
return fmt.Errorf("Another thread is currently writing blob[%s]", ref.AsHex())
}
defer unlock()
// since we're writing a blob (and not replicating), for safety we'll check that we haven't
// seen this blob before
if exists, err := d.metadataStore.QueryBlobExists(ref); err != nil || exists {
if err != nil { // error checking existence
return err
} else {
// blob exists, which is unexpected
return fmt.Errorf("WriteBlob() already exists: %s", ref.AsHex())
}
}
// this is going to take relatively long time, so we can't keep
// a transaction open
driver, err := d.driverFor(volumeId)
if err != nil {
return err
}
readCounter := writeCounter{}
contentCounted := readCounter.Tee(content)
encryptionKeyId, encryptionKey, err := d.metadataStore.QueryCollectionEncryptionKeyForNewBlobs(collId)
if err != nil {
return err
}
blobEncrypted, err := encryptAndCompressBlob(contentCounted, encryptionKey, ref, maybeCompressible)
if err != nil {
return err
}
if err := driver.RawStore(context.TODO(), ref, bytes.NewReader(blobEncrypted.CiphertextMaybeCompressed)); err != nil {
return fmt.Errorf("storing blob into volume %d failed: %v", volumeId, err)
}
meta := &BlobMeta{
Ref: ref,
RealSize: int32(readCounter.BytesWritten()),
SizeOnDisk: int32(len(blobEncrypted.CiphertextMaybeCompressed)),
IsCompressed: blobEncrypted.Compressed,
EncryptionKeyId: encryptionKeyId,
ExpectedCrc32: blobEncrypted.Crc32,
}
if err := d.metadataStore.WriteBlobCreated(meta, volumeId); err != nil {
return fmt.Errorf("WriteBlob() DB write: %v", err)
}
return nil
}
// does decrypt(optional_decompress(blobOnDisk))
// verifies blob integrity for you!
func (d *Controller) Fetch(ref stotypes.BlobRef, encryptionKeys []stotypes.KeyEnvelope, volumeId int) (io.ReadCloser, error) {
driver, err := d.driverFor(volumeId)
if err != nil {
return nil, err
}
meta, err := d.metadataStore.QueryBlobMetadata(ref, encryptionKeys)
if err != nil {
return nil, err
}
body, err := driver.RawFetch(context.TODO(), ref)
if err != nil {
return nil, err
}
// body.Close() will be called by readCloseWrapper
// reads crc32-verified ciphertext which contains maybe_gzipped(plaintext)
crc32VerifiedCiphertextReader := hashverifyreader.New(body, crc32.NewIEEE(), meta.ExpectedCrc32)
aesDecrypter, err := aes.NewCipher(meta.EncryptionKey)
if err != nil {
return nil, fmt.Errorf("Fetch() AES cipher: %v", err)
}
decrypted := &cipher.StreamReader{S: cipher.NewCTR(aesDecrypter, deriveIvFromBlobRef(ref)), R: crc32VerifiedCiphertextReader}
// assume no compression ..
uncompressedReader := io.Reader(decrypted)
if meta.IsCompressed { // .. but patch in decompression step if assumption incorrect
gzipReader, err := gzip.NewReader(decrypted)
if err != nil {
return nil, fmt.Errorf("Fetch() gzip: %v", err)
}
uncompressedReader = gzipReader
}
blobDecryptedUncompressed := stoutils.BlobHashVerifier(uncompressedReader, ref)
return &readCloseWrapper{blobDecryptedUncompressed, body}, nil
}
// currently looks for the first ID mounted on this node, but in the future could use richer heuristics:
// - is the HDD currently spinning
// - best latency & bandwidth
func (d *Controller) BestVolumeId(volumeIds []int) (int, error) {
lowestCost := 99
lowestCostVolumeId := 0
for _, volumeId := range volumeIds {
if !d.IsMounted(volumeId) {
continue
}
cost := d.routingCosts[volumeId]
if cost < lowestCost {
lowestCostVolumeId = volumeId
lowestCost = cost
}
}
if lowestCostVolumeId == 0 {
return 0, stotypes.ErrBlobNotAccessibleOnThisNode
}
return lowestCostVolumeId, nil
}
// runs a scrub for a blob in a given volume to detect errors
// https://en.wikipedia.org/wiki/Data_scrubbing
// we could actually just do a Fetch() but that would require access to the encryption keys.
// this way we can verify on-disk integrity without encryption keys.
func (d *Controller) Scrub(ref stotypes.BlobRef, volumeId int) (int64, error) {
driver, err := d.driverFor(volumeId)
if err != nil {
return 0, err
}
expectedCrc32, err := d.metadataStore.QueryBlobCrc32(ref)
if err != nil {
return 0, err
}
body, err := driver.RawFetch(context.TODO(), ref)
if err != nil {
return 0, err
}
defer body.Close()
verifiedReader := hashverifyreader.New(body, crc32.NewIEEE(), expectedCrc32)
bytesRead, err := io.Copy(ioutil.Discard, verifiedReader)
return bytesRead, err
}
// initializes volume for Varasto use by writing a volume descriptor (see verifyOnDiskVolumeUuid() for rationale)
func (d *Controller) Initialize(ctx context.Context, volumeUuid string, driver blobstore.Driver) error {
// this error is expected to happen before initialization
// (we check this so we know it's safe to initialize)
if err := d.verifyOnDiskVolumeUuid(ctx, driver, volumeUuid); err != ErrVolumeDescriptorNotFound {
return fmt.Errorf("cannot initialize because verifyOnDiskVolumeUuid: %v", err)
}
volDescriptor := &bytes.Buffer{}
if err := jsonfile.Marshal(volDescriptor, &volumeDescriptor{volumeUuid}); err != nil {
return err
}
return driver.RawStore(ctx, volumeDescriptorRef, volDescriptor)
}
// it's really dangerous to accidentally mount the wrong volume, so we'll keep a volume descriptor
// file at sha256=0000.. that contains the volume UUID that we can validate at mount time.
// will return ErrVolumeDescriptorNotFound if volume descriptor does not yet exist
func (d *Controller) verifyOnDiskVolumeUuid(ctx context.Context, driver blobstore.Driver, expectedVolumeUuid string) error {
body, err := driver.RawFetch(ctx, volumeDescriptorRef)
if err != nil {
if os.IsNotExist(err) {
return ErrVolumeDescriptorNotFound
}
return err
}
defer body.Close()
descriptor := volumeDescriptor{}
if err := jsonfile.Unmarshal(body, &descriptor, true); err != nil {
return err
}
if descriptor.VolumeId != expectedVolumeUuid {
return fmt.Errorf("unexpected volume UUID: %s", descriptor.VolumeId)
}
return nil
}
func (d *Controller) driverFor(volumeId int) (blobstore.Driver, error) {
driver, found := d.mountedDrivers[volumeId]
if !found {
return nil, fmt.Errorf("volume %d not found", volumeId)
}
return driver, nil
}
func encrypt(key []byte, plaintext io.Reader, br stotypes.BlobRef) ([]byte, error) {
aesEncrypter, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
streamCipher := cipher.NewCTR(aesEncrypter, deriveIvFromBlobRef(br))
var cipherText bytes.Buffer
ciphertextWriter := &cipher.StreamWriter{S: streamCipher, W: &cipherText}
// Copy the input to the output buffer, encrypting as we go.
if _, err := io.Copy(ciphertextWriter, plaintext); err != nil {
return nil, err
}
return cipherText.Bytes(), nil
}
// used for encryptAndCompressBlob()
type blobResult struct {
CiphertextMaybeCompressed []byte
Compressed bool
Crc32 []byte
}
// does encrypt(maybe_compress(plaintext))
func encryptAndCompressBlob(
contentReader io.Reader,
encryptionKey []byte,
ref stotypes.BlobRef,
maybeCompressible bool,
) (*blobResult, error) {
content, err := ioutil.ReadAll(contentReader)
if err != nil {
return nil, err
}
contentMaybeCompressed := content
contentIsCompressed := false
/* Here are perf measurements from my year 2012 CPU
concurrency=2 | by trying compression = 25.1 MB/s
concurrency=2 | no compression = 50.0 MB/s
concurrency=4 | no compression = 65.7 MB/s
66.3 MB/s
*/
if maybeCompressible {
var compressed bytes.Buffer
compressedWriter := gzip.NewWriter(&compressed)
if _, err := compressedWriter.Write(content); err != nil {
return nil, err
}
if err := compressedWriter.Close(); err != nil {
return nil, err
}
compressionRatio := float64(compressed.Len()) / float64(len(content))
wellCompressible := compressionRatio < 0.9
if wellCompressible {
contentMaybeCompressed = compressed.Bytes()
contentIsCompressed = true
}
}
ciphertextMaybeCompressed, err := encrypt(encryptionKey, bytes.NewReader(contentMaybeCompressed), ref)
if err != nil {
return nil, err
}
crc := make([]byte, 4)
binary.BigEndian.PutUint32(crc, crc32.ChecksumIEEE(ciphertextMaybeCompressed))
return &blobResult{
CiphertextMaybeCompressed: ciphertextMaybeCompressed,
Compressed: contentIsCompressed,
Crc32: crc,
}, nil
}
func deriveIvFromBlobRef(br stotypes.BlobRef) []byte {
return br.AsSha256Sum()[0:aes.BlockSize]
}