/
format_manager.go
493 lines (389 loc) · 13.1 KB
/
format_manager.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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
package format
import (
"context"
"crypto/rand"
"io"
"sync"
"time"
"github.com/pkg/errors"
"github.com/kopia/kopia/internal/ctxutil"
"github.com/kopia/kopia/internal/feature"
"github.com/kopia/kopia/internal/gather"
"github.com/kopia/kopia/repo/blob"
"github.com/kopia/kopia/repo/encryption"
"github.com/kopia/kopia/repo/hashing"
"github.com/kopia/kopia/repo/logging"
)
var log = logging.Module("kopia/repo/format")
// UniqueIDLengthBytes is the length of random unique ID of each repository.
const UniqueIDLengthBytes = 32
// Manager manages the contents of `kopia.repository` and `kopia.blobcfg`.
type Manager struct {
//nolint:containedctx
ctx context.Context // +checklocksignore
blobs blob.Storage // +checklocksignore
validDuration time.Duration // +checklocksignore
password string // +checklocksignore
cache blobCache // +checklocksignore
// provider for immutable parts of the format data, used to avoid locks.
immutable Provider
timeNow func() time.Time // +checklocksignore
// all the stuff protected by a mutex is valid until `validUntil`
mu sync.RWMutex
// +checklocks:mu
formatEncryptionKey []byte
// +checklocks:mu
j *KopiaRepositoryJSON
// +checklocks:mu
repoConfig *RepositoryConfig
// +checklocks:mu
blobCfgBlob BlobStorageConfiguration
// +checklocks:mu
current Provider
// +checklocks:mu
validUntil time.Time
// +checklocks:mu
loadedTime time.Time
// +checklocks:mu
refreshCounter int
// +checklocks:mu
ignoreCacheOnFirstRefresh bool
}
func (m *Manager) getOrRefreshFormat() (Provider, error) {
if err := m.maybeRefreshNotLocked(); err != nil {
return nil, err
}
m.mu.RLock()
defer m.mu.RUnlock()
return m.current, nil
}
func (m *Manager) maybeRefreshNotLocked() error {
m.mu.RLock()
val := m.validUntil
m.mu.RUnlock()
if m.timeNow().Before(val) {
return nil
}
// current format not valid anymore, kick off a refresh
return m.refresh(m.ctx)
}
// readAndCacheRepositoryBlobBytes reads the provided blob from the repository or cache directory.
// +checklocks:m.mu
func (m *Manager) readAndCacheRepositoryBlobBytes(ctx context.Context, blobID blob.ID) ([]byte, time.Time, error) {
if !m.ignoreCacheOnFirstRefresh {
if data, mtime, ok := m.cache.Get(ctx, blobID); ok {
// read from cache and still valid
age := m.timeNow().Sub(mtime)
if age < m.validDuration {
return data, mtime, nil
}
}
}
var b gather.WriteBuffer
defer b.Close()
if err := m.blobs.GetBlob(ctx, blobID, 0, -1, &b); err != nil {
return nil, time.Time{}, errors.Wrapf(err, "error getting %s blob", blobID)
}
data := b.ToByteSlice()
mtime, err := m.cache.Put(ctx, blobID, data)
return data, mtime, errors.Wrapf(err, "error adding %s blob", blobID)
}
// ValidCacheDuration returns the duration for which each blob in the cache is valid.
func (m *Manager) ValidCacheDuration() time.Duration {
return m.validDuration
}
// RefreshCount returns the number of time the format has been refreshed.
func (m *Manager) RefreshCount() int {
m.mu.RLock()
defer m.mu.RUnlock()
return m.refreshCounter
}
// refresh reads `kopia.repository` blob, potentially from cache and decodes it.
func (m *Manager) refresh(ctx context.Context) error {
m.mu.Lock()
defer m.mu.Unlock()
b, cacheMTime, err := m.readAndCacheRepositoryBlobBytes(ctx, KopiaRepositoryBlobID)
if err != nil {
return errors.Wrap(err, "unable to read format blob")
}
j, err := ParseKopiaRepositoryJSON(b)
if err != nil {
return errors.Wrap(err, "can't parse format blob")
}
b, err = addFormatBlobChecksumAndLength(b)
if err != nil {
return errors.Errorf("unable to add checksum")
}
var formatEncryptionKey []byte
// try decrypting using old key, if present to avoid deriving it, which is expensive
repoConfig, err := j.decryptRepositoryConfig(m.formatEncryptionKey)
if err == nil {
// still valid, no need to derive
formatEncryptionKey = m.formatEncryptionKey
} else {
formatEncryptionKey, err = j.DeriveFormatEncryptionKeyFromPassword(m.password)
if err != nil {
return errors.Wrap(err, "derive format encryption key")
}
repoConfig, err = j.decryptRepositoryConfig(formatEncryptionKey)
if err != nil {
return ErrInvalidPassword
}
}
var blobCfg BlobStorageConfiguration
if b2, _, err2 := m.readAndCacheRepositoryBlobBytes(ctx, KopiaBlobCfgBlobID); err2 == nil {
var e2 error
blobCfg, e2 = deserializeBlobCfgBytes(j, b2, formatEncryptionKey)
if e2 != nil {
return errors.Wrap(e2, "deserialize blob config")
}
} else if !errors.Is(err2, blob.ErrBlobNotFound) {
return errors.Wrap(err2, "load blob config")
}
prov, err := NewFormattingOptionsProvider(&repoConfig.ContentFormat, b)
if err != nil {
return errors.Wrap(err, "error creating format provider")
}
m.current = prov
m.j = j
m.repoConfig = repoConfig
m.validUntil = cacheMTime.Add(m.validDuration)
m.formatEncryptionKey = formatEncryptionKey
m.loadedTime = cacheMTime
m.blobCfgBlob = blobCfg
m.ignoreCacheOnFirstRefresh = false
if m.immutable == nil {
// on first refresh, set `immutable``
m.immutable = prov
}
m.refreshCounter++
return nil
}
// GetEncryptionAlgorithm returns the encryption algorithm.
func (m *Manager) GetEncryptionAlgorithm() string {
return m.immutable.GetEncryptionAlgorithm()
}
// GetHashFunction returns the hash function.
func (m *Manager) GetHashFunction() string {
return m.immutable.GetHashFunction()
}
// GetECCAlgorithm returns the ECC algorithm.
func (m *Manager) GetECCAlgorithm() string {
return m.immutable.GetECCAlgorithm()
}
// GetECCOverheadPercent returns the ECC overhead percent.
func (m *Manager) GetECCOverheadPercent() int {
return m.immutable.GetECCOverheadPercent()
}
// GetHmacSecret returns the HMAC function.
func (m *Manager) GetHmacSecret() []byte {
return m.immutable.GetHmacSecret()
}
// HashFunc returns the resolved hash function.
func (m *Manager) HashFunc() hashing.HashFunc {
return m.immutable.HashFunc()
}
// Encryptor returns the resolved encryptor.
func (m *Manager) Encryptor() encryption.Encryptor {
return m.immutable.Encryptor()
}
// GetMasterKey gets the master key.
func (m *Manager) GetMasterKey() []byte {
return m.immutable.GetMasterKey()
}
// SupportsPasswordChange returns true if the repository supports password change.
func (m *Manager) SupportsPasswordChange() bool {
return m.immutable.SupportsPasswordChange()
}
// RepositoryFormatBytes returns the bytes of `kopia.repository` blob.
// This function blocks to refresh the format blob if necessary.
func (m *Manager) RepositoryFormatBytes() ([]byte, error) {
f, err := m.getOrRefreshFormat()
if err != nil {
return nil, err
}
//nolint:wrapcheck
return f.RepositoryFormatBytes()
}
// GetMutableParameters gets mutable paramers of the repository.
// This function blocks to refresh the format blob if necessary.
func (m *Manager) GetMutableParameters() (MutableParameters, error) {
f, err := m.getOrRefreshFormat()
if err != nil {
return MutableParameters{}, err
}
//nolint:wrapcheck
return f.GetMutableParameters()
}
// UpgradeLockIntent returns the current lock intent.
func (m *Manager) UpgradeLockIntent() (*UpgradeLockIntent, error) {
if err := m.maybeRefreshNotLocked(); err != nil {
return nil, err
}
m.mu.RLock()
defer m.mu.RUnlock()
return m.repoConfig.UpgradeLock.Clone(), nil
}
// RequiredFeatures returns the list of features required to open the repository.
func (m *Manager) RequiredFeatures() ([]feature.Required, error) {
if err := m.maybeRefreshNotLocked(); err != nil {
return nil, err
}
m.mu.RLock()
defer m.mu.RUnlock()
return m.repoConfig.RequiredFeatures, nil
}
// LoadedTime gets the time when the config was last reloaded.
func (m *Manager) LoadedTime() time.Time {
m.mu.RLock()
defer m.mu.RUnlock()
return m.loadedTime
}
// updateRepoConfigLocked updates repository config and rewrites kopia.repository blob.
// +checklocks:m.mu
func (m *Manager) updateRepoConfigLocked(ctx context.Context) error {
if err := m.j.EncryptRepositoryConfig(m.repoConfig, m.formatEncryptionKey); err != nil {
return errors.Errorf("unable to encrypt format bytes")
}
if err := m.j.WriteKopiaRepositoryBlob(ctx, m.blobs, m.blobCfgBlob); err != nil {
return errors.Wrap(err, "unable to write format blob")
}
m.cache.Remove(ctx, []blob.ID{KopiaRepositoryBlobID})
return nil
}
// UniqueID gets the unique ID of a repository allocated at creation time.
func (m *Manager) UniqueID() []byte {
m.mu.RLock()
defer m.mu.RUnlock()
return m.j.UniqueID
}
// BlobCfgBlob gets the BlobStorageConfiguration.
func (m *Manager) BlobCfgBlob() (BlobStorageConfiguration, error) {
if err := m.maybeRefreshNotLocked(); err != nil {
return BlobStorageConfiguration{}, err
}
m.mu.RLock()
defer m.mu.RUnlock()
return m.blobCfgBlob, nil
}
// ObjectFormat gets the object format.
func (m *Manager) ObjectFormat() ObjectFormat {
m.mu.RLock()
defer m.mu.RUnlock()
return m.repoConfig.ObjectFormat
}
// FormatEncryptionKey gets the format encryption key derived from the password.
func (m *Manager) FormatEncryptionKey() []byte {
m.mu.RLock()
defer m.mu.RUnlock()
return m.formatEncryptionKey
}
// ScrubbedContentFormat returns scrubbed content format with all sensitive data replaced.
func (m *Manager) ScrubbedContentFormat() ContentFormat {
m.mu.RLock()
defer m.mu.RUnlock()
cf := m.repoConfig.ContentFormat
cf.MasterKey = nil
cf.HMACSecret = nil
return cf
}
// NewManager creates new format manager which automatically refreshes format blob on reads (in a blocking manner).
func NewManager(
ctx context.Context,
st blob.Storage,
cacheDir string,
validDuration time.Duration,
password string,
timeNow func() time.Time,
) (*Manager, error) {
return NewManagerWithCache(ctx, st, validDuration, password, timeNow, NewFormatBlobCache(cacheDir, validDuration, timeNow))
}
// NewManagerWithCache creates new format manager which automatically refreshes format blob on reads (in a blocking manner)
// and uses the provided cache.
func NewManagerWithCache(
ctx context.Context,
st blob.Storage,
validDuration time.Duration,
password string,
timeNow func() time.Time,
cache blobCache,
) (*Manager, error) {
var ignoreCacheOnFirstRefresh bool
if validDuration < 0 {
// valid duration less than zero indicates we want to skip cache on first access
validDuration = DefaultRepositoryBlobCacheDuration
ignoreCacheOnFirstRefresh = true
}
if validDuration > DefaultRepositoryBlobCacheDuration {
log(ctx).Infof("repository format cache duration capped at %v", DefaultRepositoryBlobCacheDuration)
validDuration = DefaultRepositoryBlobCacheDuration
}
m := &Manager{
ctx: ctxutil.Detach(ctx),
blobs: st,
validDuration: validDuration,
password: password,
cache: cache,
timeNow: timeNow,
ignoreCacheOnFirstRefresh: ignoreCacheOnFirstRefresh,
}
err := m.refresh(ctx)
return m, err
}
// ErrAlreadyInitialized indicates that repository has already been initialized.
var ErrAlreadyInitialized = errors.Errorf("repository already initialized")
// Initialize initializes the format blob in a given storage.
func Initialize(ctx context.Context, st blob.Storage, formatBlob *KopiaRepositoryJSON, repoConfig *RepositoryConfig, blobcfg BlobStorageConfiguration, password string) error {
// get the blob - expect ErrNotFound
var tmp gather.WriteBuffer
defer tmp.Close()
err := st.GetBlob(ctx, KopiaRepositoryBlobID, 0, -1, &tmp)
if err == nil {
return ErrAlreadyInitialized
}
if !errors.Is(err, blob.ErrBlobNotFound) {
return errors.Wrap(err, "unexpected error when checking for format blob")
}
err = st.GetBlob(ctx, KopiaBlobCfgBlobID, 0, -1, &tmp)
if err == nil {
return errors.Errorf("possible corruption: blobcfg blob exists, but format blob is not found")
}
if !errors.Is(err, blob.ErrBlobNotFound) {
return errors.Wrap(err, "unexpected error when checking for blobcfg blob")
}
if formatBlob.EncryptionAlgorithm == "" {
formatBlob.EncryptionAlgorithm = DefaultFormatEncryption
}
if formatBlob.KeyDerivationAlgorithm == "" {
formatBlob.KeyDerivationAlgorithm = DefaultKeyDerivationAlgorithm
}
if len(formatBlob.UniqueID) == 0 {
formatBlob.UniqueID = randomBytes(UniqueIDLengthBytes)
}
formatEncryptionKey, err := formatBlob.DeriveFormatEncryptionKeyFromPassword(password)
if err != nil {
return errors.Wrap(err, "unable to derive format encryption key")
}
if err = repoConfig.MutableParameters.Validate(); err != nil {
return errors.Wrap(err, "invalid parameters")
}
if err = blobcfg.Validate(); err != nil {
return errors.Wrap(err, "blob config")
}
if err = formatBlob.EncryptRepositoryConfig(repoConfig, formatEncryptionKey); err != nil {
return errors.Wrap(err, "unable to encrypt format bytes")
}
if err := formatBlob.WriteBlobCfgBlob(ctx, st, blobcfg, formatEncryptionKey); err != nil {
return errors.Wrap(err, "unable to write blobcfg blob")
}
if err := formatBlob.WriteKopiaRepositoryBlob(ctx, st, blobcfg); err != nil {
return errors.Wrap(err, "unable to write format blob")
}
return nil
}
var _ Provider = (*Manager)(nil)
func randomBytes(n int) []byte {
b := make([]byte, n)
io.ReadFull(rand.Reader, b) //nolint:errcheck
return b
}