forked from kopia/kopia
-
Notifications
You must be signed in to change notification settings - Fork 5
/
providervalidation.go
402 lines (307 loc) · 10.8 KB
/
providervalidation.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
// Package providervalidation implements validation to ensure the blob storage is compatible with Kopia requirements.
package providervalidation
import (
"bytes"
"context"
cryptorand "crypto/rand"
"fmt"
"math/rand"
"os"
"sync"
"time"
"github.com/google/uuid"
"github.com/pkg/errors"
"golang.org/x/sync/errgroup"
"github.com/kopia/kopia/internal/clock"
"github.com/kopia/kopia/internal/gather"
"github.com/kopia/kopia/repo/blob"
"github.com/kopia/kopia/repo/logging"
)
// Options provides options for provider validation.
type Options struct {
MaxClockDrift time.Duration
ConcurrencyTestDuration time.Duration
NumPutBlobWorkers int
NumGetBlobWorkers int
NumGetMetadataWorkers int
NumListBlobsWorkers int
MaxBlobLength int
SupportIdempotentCreates bool
}
// DefaultOptions is the default set of options.
// nolint:gomnd
var DefaultOptions = Options{
MaxClockDrift: 3 * time.Minute,
ConcurrencyTestDuration: 30 * time.Second,
NumPutBlobWorkers: 3,
NumGetBlobWorkers: 3,
NumGetMetadataWorkers: 3,
NumListBlobsWorkers: 3,
MaxBlobLength: 10e6,
SupportIdempotentCreates: false,
}
const blobIDLength = 16
var log = logging.Module("providervalidation")
// ValidateProvider runs a series of tests against provided storage to validate that
// it can be used with Kopia.
// nolint:gomnd,funlen,gocyclo,cyclop
func ValidateProvider(ctx context.Context, st blob.Storage, opt Options) error {
if os.Getenv("KOPIA_SKIP_PROVIDER_VALIDATION") != "" {
return nil
}
uberPrefix := blob.ID("z" + uuid.NewString())
defer cleanupAllBlobs(ctx, st, uberPrefix)
prefix1 := uberPrefix + "a"
prefix2 := uberPrefix + "b"
log(ctx).Infof("Validating blob list responses")
if err := verifyBlobCount(ctx, st, uberPrefix, 0); err != nil {
return errors.Wrap(err, "invalid blob count")
}
log(ctx).Infof("Validating non-existent blob responses")
var out gather.WriteBuffer
defer out.Close()
// read non-existent full blob
if err := st.GetBlob(ctx, prefix1+"1", 0, -1, &out); !errors.Is(err, blob.ErrBlobNotFound) {
return errors.Errorf("got unexpected error when reading non-existent blob: %v", err)
}
// read non-existent partial blob
if err := st.GetBlob(ctx, prefix1+"1", 0, 5, &out); !errors.Is(err, blob.ErrBlobNotFound) {
return errors.Errorf("got unexpected error when reading non-existent partial blob: %v", err)
}
// get metadata for non-existent blob
if _, err := st.GetMetadata(ctx, prefix1+"1"); !errors.Is(err, blob.ErrBlobNotFound) {
return errors.Errorf("got unexpected error when getting metadata for non-existent blob: %v", err)
}
blobData := bytes.Repeat([]byte{1, 2, 3, 4, 5}, 1e6)
log(ctx).Infof("Writing blob (%v bytes)", len(blobData))
// write blob
if err := st.PutBlob(ctx, prefix1+"1", gather.FromSlice(blobData), blob.PutOptions{}); err != nil {
return errors.Wrap(err, "error writing blob #1")
}
log(ctx).Infof("Validating list responses...")
if err := verifyBlobCount(ctx, st, uberPrefix, 1); err != nil {
return errors.Wrap(err, "invalid uber blob count")
}
if err := verifyBlobCount(ctx, st, prefix1, 1); err != nil {
return errors.Wrap(err, "invalid blob count with prefix 1")
}
if err := verifyBlobCount(ctx, st, prefix2, 0); err != nil {
return errors.Wrap(err, "invalid blob count with prefix 2")
}
log(ctx).Infof("Validating partial reads...")
partialBlobCases := []struct {
offset int64
length int64
}{
{0, 10},
{1, 10},
{2, 1},
{5, 0},
{int64(len(blobData)) - 5, 5},
}
for _, tc := range partialBlobCases {
err := st.GetBlob(ctx, prefix1+"1", tc.offset, tc.length, &out)
if err != nil {
return errors.Wrapf(err, "got unexpected error when reading partial blob @%v+%v", tc.offset, tc.length)
}
if got, want := out.ToByteSlice(), blobData[tc.offset:tc.offset+tc.length]; !bytes.Equal(got, want) {
return errors.Errorf("got unexpected data after reading partial blob @%v+%v: %x, wanted %x", tc.offset, tc.length, got, want)
}
}
log(ctx).Infof("Validating full reads...")
// read full blob
err := st.GetBlob(ctx, prefix1+"1", 0, -1, &out)
if err != nil {
return errors.Wrap(err, "got unexpected error when reading partial blob")
}
if got, want := out.ToByteSlice(), blobData; !bytes.Equal(got, want) {
return errors.Errorf("got unexpected data after reading partial blob: %x, wanted %x", got, want)
}
log(ctx).Infof("Validating metadata...")
// get metadata for non-existent blob
bm, err := st.GetMetadata(ctx, prefix1+"1")
if err != nil {
return errors.Wrap(err, "got unexpected error when getting metadata for blob")
}
if got, want := bm.Length, int64(len(blobData)); got != want {
return errors.Errorf("invalid length returned by GetMetadata(): %v, wanted %v", got, want)
}
now := clock.Now()
timeDiff := now.Sub(bm.Timestamp)
if timeDiff < 0 {
timeDiff = -timeDiff
}
if timeDiff > opt.MaxClockDrift {
return errors.Errorf(
"newly-written blob has a timestamp very different from local clock: %v, expected %v. Max difference allowed is %v",
bm.Timestamp,
now,
opt.MaxClockDrift,
)
}
ct := newConcurrencyTest(st, prefix2, opt)
log(ctx).Infof("Running concurrency test for %v...", opt.ConcurrencyTestDuration)
if err := ct.run(ctx); err != nil {
return errors.Wrap(err, "error validating concurrency")
}
log(ctx).Infof("Validating blob recreation...")
if !opt.SupportIdempotentCreates {
err := st.PutBlob(ctx, "dummy_id", gather.FromSlice([]byte{99}), blob.PutOptions{DoNotRecreate: true})
if err == nil {
return errors.New("store should not support put-blob-no-overwrite, expected error")
}
}
log(ctx).Infof("All good.")
return nil
}
type concurrencyTest struct {
opt Options
st blob.Storage
prefix blob.ID
deadline time.Time
mu sync.Mutex
blobData map[blob.ID][]byte
blobIDs []blob.ID
blobWritten map[blob.ID]bool
}
func newConcurrencyTest(st blob.Storage, prefix blob.ID, opt Options) *concurrencyTest {
return &concurrencyTest{
opt: opt,
st: st,
prefix: prefix,
deadline: clock.Now().Add(opt.ConcurrencyTestDuration),
blobData: make(map[blob.ID][]byte),
blobWritten: make(map[blob.ID]bool),
}
}
func (c *concurrencyTest) putBlobWorker(ctx context.Context, worker int) func() error {
return func() error {
for clock.Now().Before(c.deadline) {
blobLen := blobIDLength + rand.Intn(c.opt.MaxBlobLength-blobIDLength) //nolint:gosec
data := make([]byte, blobLen)
if _, err := cryptorand.Read(data); err != nil {
return errors.Wrap(err, "unable to get randomness")
}
id := c.prefix + blob.ID(fmt.Sprintf("%x", data[0:16]))
c.mu.Lock()
c.blobData[id] = data
c.blobIDs = append(c.blobIDs, id)
c.mu.Unlock()
// sleep for a short time so that readers can start getting the blob when it's still
// not written.
c.randomSleep()
log(ctx).Debugf("PutBlob worker %v writing %v (%v bytes)", worker, id, len(data))
if err := c.st.PutBlob(ctx, id, gather.FromSlice(data), blob.PutOptions{}); err != nil {
return errors.Wrap(err, "error writing blob")
}
c.mu.Lock()
c.blobWritten[id] = true
c.mu.Unlock()
log(ctx).Debugf("PutBlob worker %v finished writing %v (%v bytes)", worker, id, len(data))
}
return nil
}
}
func (c *concurrencyTest) randomSleep() {
time.Sleep(time.Duration(rand.Intn(int(100 * time.Millisecond)))) //nolint:gosec,gomnd
}
func (c *concurrencyTest) pickBlob() (blob.ID, []byte, bool) {
c.mu.Lock()
defer c.mu.Unlock()
if len(c.blobIDs) == 0 {
return "", nil, false
}
id := c.blobIDs[rand.Intn(len(c.blobIDs))] // nolint:gosec
return id, c.blobData[id], c.blobWritten[id]
}
func (c *concurrencyTest) getBlobWorker(ctx context.Context, worker int) func() error {
return func() error {
var out gather.WriteBuffer
defer out.Close()
for clock.Now().Before(c.deadline) {
c.randomSleep()
blobID, blobData, fullyWritten := c.pickBlob()
if blobID == "" {
continue
}
log(ctx).Debugf("GetBlob worker %v reading %v", worker, blobID)
err := c.st.GetBlob(ctx, blobID, 0, -1, &out)
if err != nil {
if !errors.Is(err, blob.ErrBlobNotFound) || fullyWritten {
return errors.Wrapf(err, "unexpected error when reading %v", blobID)
}
log(ctx).Debugf("GetBlob worker %v - valid error when reading %v", worker, blobID)
continue
}
if !bytes.Equal(out.ToByteSlice(), blobData) {
return errors.Wrapf(err, "invalid data read for %v", blobID)
}
log(ctx).Debugf("GetBlob worker %v - valid data read %v", worker, blobID)
}
return nil
}
}
func (c *concurrencyTest) getMetadataWorker(ctx context.Context, worker int) func() error {
return func() error {
for clock.Now().Before(c.deadline) {
c.randomSleep()
blobID, blobData, fullyWritten := c.pickBlob()
if blobID == "" {
continue
}
log(ctx).Debugf("GetMetadata worker %v: %v", worker, blobID)
bm, err := c.st.GetMetadata(ctx, blobID)
if err != nil {
if !errors.Is(err, blob.ErrBlobNotFound) || fullyWritten {
return errors.Wrapf(err, "unexpected error when reading %v", blobID)
}
log(ctx).Debugf("GetMetadata worker %v - valid error when reading %v", worker, blobID)
continue
}
if bm.Length != int64(len(blobData)) {
return errors.Wrapf(err, "unexpected partial read - invalid length read for %v: %v wanted %v", blobID, bm.Length, len(blobData))
}
log(ctx).Debugf("GetMetadata worker %v - valid data read %v", worker, blobID)
}
return nil
}
}
func (c *concurrencyTest) listBlobWorker(ctx context.Context, worker int) func() error {
return func() error {
return nil
}
}
func (c *concurrencyTest) run(ctx context.Context) error {
eg, ctx := errgroup.WithContext(ctx)
for worker := 0; worker < c.opt.NumPutBlobWorkers; worker++ {
eg.Go(c.putBlobWorker(ctx, worker))
}
for worker := 0; worker < c.opt.NumGetBlobWorkers; worker++ {
eg.Go(c.getBlobWorker(ctx, worker))
}
for worker := 0; worker < c.opt.NumGetMetadataWorkers; worker++ {
eg.Go(c.getMetadataWorker(ctx, worker))
}
for worker := 0; worker < c.opt.NumListBlobsWorkers; worker++ {
eg.Go(c.listBlobWorker(ctx, worker))
}
return errors.Wrap(eg.Wait(), "encountered errors")
}
func cleanupAllBlobs(ctx context.Context, st blob.Storage, prefix blob.ID) {
log(ctx).Infof("Cleaning up temporary data...")
if err := st.ListBlobs(ctx, prefix, func(bm blob.Metadata) error {
return errors.Wrapf(st.DeleteBlob(ctx, bm.BlobID), "error deleting blob %v", bm.BlobID)
}); err != nil {
log(ctx).Debugf("error cleaning up")
}
}
func verifyBlobCount(ctx context.Context, st blob.Storage, prefix blob.ID, want int) error {
got, err := blob.ListAllBlobs(ctx, st, prefix)
if err != nil {
return errors.Wrap(err, "error listing blobs")
}
if len(got) != want {
return errors.Errorf("unexpected number of blobs returned for prefix %v: %v, wanted %v", prefix, len(got), want)
}
return nil
}