-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler_backup.go
527 lines (436 loc) · 14.8 KB
/
handler_backup.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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
// Copyright 2024 Aerospike, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package backup
import (
"context"
"errors"
"fmt"
"io"
"log/slog"
"sync/atomic"
"github.com/aerospike/backup-go/internal/asinfo"
"github.com/aerospike/backup-go/internal/logging"
"github.com/aerospike/backup-go/internal/processors"
"github.com/aerospike/backup-go/io/aerospike"
"github.com/aerospike/backup-go/io/compression"
"github.com/aerospike/backup-go/io/counter"
"github.com/aerospike/backup-go/io/encryption"
"github.com/aerospike/backup-go/io/lazy"
"github.com/aerospike/backup-go/io/sized"
"github.com/aerospike/backup-go/models"
"github.com/aerospike/backup-go/pipeline"
"github.com/google/uuid"
"golang.org/x/sync/semaphore"
"golang.org/x/time/rate"
)
// Writer provides access to backup storage.
// Exported for integration tests.
type Writer interface {
// NewWriter returns new writer for backup logic to use. Each call creates
// a new writer, they might be working in parallel. Backup logic will close
// the writer after backup is done. Header func is executed on a writer
// after creation (on each one in case of multipart file).
NewWriter(ctx context.Context, filename string) (io.WriteCloser, error)
// GetType returns the type of storage. Used in logging.
GetType() string
// RemoveFiles removes a backup file or files from directory.
RemoveFiles(ctx context.Context) error
}
// BackupHandler handles a backup job.
type BackupHandler struct {
// Global backup context for a whole backup process.
ctx context.Context
cancel context.CancelFunc
writer Writer
encoder Encoder
config *BackupConfig
aerospikeClient AerospikeClient
logger *slog.Logger
firstFileHeaderWritten *atomic.Bool
limiter *rate.Limiter
infoClient *asinfo.InfoClient
scanLimiter *semaphore.Weighted
errors chan error
id string
stats models.BackupStats
// Backup state for continuation.
state *State
}
// newBackupHandler creates a new BackupHandler.
func newBackupHandler(
ctx context.Context,
config *BackupConfig,
ac AerospikeClient,
logger *slog.Logger,
writer Writer,
reader StreamingReader,
scanLimiter *semaphore.Weighted,
) (*BackupHandler, error) {
id := uuid.NewString()
// For estimates calculations, a writer will be nil.
storageType := ""
if writer != nil {
storageType = writer.GetType()
}
logger = logging.WithHandler(logger, id, logging.HandlerTypeBackup, storageType)
limiter := makeBandwidthLimiter(config.Bandwidth)
// redefine context cancel.
ctx, cancel := context.WithCancel(ctx)
var state *State
if config.StateFile != "" {
var err error
state, err = NewState(ctx, config, reader, writer, logger)
if err != nil {
cancel()
return nil, fmt.Errorf("failed to initialize state: %w", err)
}
// If it is a continuation operation, we load partition filters from state.
if config.isStateContinue() {
// change filters in config.
config.PartitionFilters, err = state.loadPartitionFilters()
if err != nil {
cancel()
return nil, fmt.Errorf("failed to load partition filters for : %w", err)
}
}
}
return &BackupHandler{
ctx: ctx,
cancel: cancel,
config: config,
aerospikeClient: ac,
id: id,
logger: logger,
writer: writer,
firstFileHeaderWritten: &atomic.Bool{},
encoder: NewEncoder(config.EncoderType, config.Namespace, config.Compact),
limiter: limiter,
infoClient: asinfo.NewInfoClientFromAerospike(ac, config.InfoPolicy),
scanLimiter: scanLimiter,
state: state,
}, nil
}
// run runs the backup job.
// currently this should only be run once.
func (bh *BackupHandler) run() {
bh.errors = make(chan error, 1)
bh.stats.Start()
go doWork(bh.errors, bh.logger, func() error {
return bh.backupSync(bh.ctx)
})
}
// getEstimate calculates backup size estimate.
func (bh *BackupHandler) getEstimate(ctx context.Context, recordsNumber int64) (uint64, error) {
totalCount, err := bh.infoClient.GetRecordCount(bh.config.Namespace, bh.config.SetList)
if err != nil {
return 0, fmt.Errorf("failed to count records: %w", err)
}
// Calculate headers size.
header := bh.encoder.GetHeader()
headerSize := len(header) * bh.config.ParallelWrite
// Calculate records size.
samples, samplesData, err := bh.getEstimateSamples(ctx, recordsNumber)
if err != nil {
return 0, fmt.Errorf("failed to estimate samples: %w", err)
}
// Calculate compress ratio. For uncompressed data it would be 1.
compressRatio, err := getCompressRatio(bh.config.CompressionPolicy, samplesData)
if err != nil {
return 0, fmt.Errorf("failed to get compress ratio: %w", err)
}
bh.logger.Debug("compression", slog.Float64("ratio", compressRatio))
result := getEstimate(samples, float64(totalCount), bh.logger)
// Add headers.
result += float64(headerSize)
// Apply compression ratio. (For uncompressed it will be 1)
result /= compressRatio
return uint64(result), nil
}
// getEstimateSamples returns slice of samples and its content for estimate calculations.
func (bh *BackupHandler) getEstimateSamples(ctx context.Context, recordsNumber int64,
) (samples []float64, samplesData []byte, err error) {
scanPolicy := *bh.config.ScanPolicy
scanPolicy.MaxRecords = recordsNumber
// we need to set the RawCDT flag
// in the scan policy so that maps and lists are returned as raw blob bins
scanPolicy.RawCDT = true
nodes := bh.aerospikeClient.GetNodes()
handler := newBackupRecordsHandler(bh.config, bh.aerospikeClient, bh.logger, bh.scanLimiter, bh.state)
readerConfig := handler.recordReaderConfigForNode(nodes, &scanPolicy)
recordReader := aerospike.NewRecordReader(ctx, bh.aerospikeClient, readerConfig, bh.logger)
// Timestamp processor.
tsProcessor := processors.NewVoidTimeSetter(bh.logger)
for {
t, err := recordReader.Read()
if err != nil {
if errors.Is(err, io.EOF) {
break
}
return nil, nil, fmt.Errorf("failed to read records: %w", err)
}
t, err = tsProcessor.Process(t)
if err != nil {
return nil, nil, fmt.Errorf("failed to process token: %w", err)
}
data, err := bh.encoder.EncodeToken(t)
if err != nil {
return nil, nil, fmt.Errorf("failed to encode token: %w", err)
}
samples = append(samples, float64(len(data)))
samplesData = append(samplesData, data...)
}
return samples, samplesData, nil
}
func (bh *BackupHandler) backupSync(ctx context.Context) error {
backupWriters, err := bh.makeWriters(ctx, bh.config.ParallelWrite)
if err != nil {
return err
}
defer closeWriters(backupWriters, bh.logger)
// backup secondary indexes and UDFs on the first writer
// this is done to match the behavior of the
// backup c tool and keep the backup files more consistent
// at some point we may want to treat the secondary indexes/UDFs
// like records and back them up as part of the same pipeline
// but doing so would cause them to be mixed in with records in the backup file(s)
err = bh.backupSIndexesAndUDFs(ctx, backupWriters[0])
if err != nil {
return err
}
if bh.config.NoRecords {
// no need to run backup handler
return nil
}
writeWorkers := bh.makeWriteWorkers(backupWriters)
handler := newBackupRecordsHandler(bh.config, bh.aerospikeClient, bh.logger, bh.scanLimiter, bh.state)
bh.stats.TotalRecords, err = handler.countRecords(ctx, bh.infoClient)
if err != nil {
return err
}
if bh.config.isStateContinue() {
// Have to reload filter, as on count records cursor is moving and future scans returns nothing.
bh.config.PartitionFilters, err = bh.state.loadPartitionFilters()
if err != nil {
return err
}
}
return handler.run(ctx, writeWorkers, &bh.stats.ReadRecords)
}
func (bh *BackupHandler) makeWriteWorkers(
backupWriters []io.WriteCloser,
) []pipeline.Worker[*models.Token] {
writeWorkers := make([]pipeline.Worker[*models.Token], len(backupWriters))
for i, w := range backupWriters {
var dataWriter pipeline.DataWriter[*models.Token] = newTokenWriter(bh.encoder, w, bh.logger, nil)
if bh.state != nil {
stInfo := newStateInfo(bh.state.RecordsStateChan, i)
dataWriter = newTokenWriter(bh.encoder, w, bh.logger, stInfo)
}
dataWriter = newWriterWithTokenStats(dataWriter, &bh.stats, bh.logger)
writeWorkers[i] = pipeline.NewWriteWorker(dataWriter, bh.limiter)
}
return writeWorkers
}
func (bh *BackupHandler) makeWriters(ctx context.Context, n int) ([]io.WriteCloser, error) {
backupWriters := make([]io.WriteCloser, n)
for i := 0; i < n; i++ {
writer, err := bh.newWriter(ctx, i)
if err != nil {
return nil, err
}
backupWriters[i] = writer
}
return backupWriters, nil
}
func closeWriters(backupWriters []io.WriteCloser, logger *slog.Logger) {
for _, w := range backupWriters {
if err := w.Close(); err != nil {
logger.Error("failed to close backup file", "error", err)
}
}
}
// newWriter creates a new writer based on the current configuration.
// If FileLimit is set, it returns a sized writer limited to FileLimit bytes.
// The returned writer may be compressed or encrypted depending on the BackupHandler's
// configuration.
func (bh *BackupHandler) newWriter(ctx context.Context, n int) (io.WriteCloser, error) {
if bh.config.FileLimit > 0 {
// For saving state operation, we init writer with a communication channel.
if bh.config.isStateFirstRun() || bh.config.isStateContinue() {
return sized.NewWriter(ctx, n, bh.state.SaveCommandChan, bh.config.FileLimit, bh.newConfiguredWriter)
}
return sized.NewWriter(ctx, n, nil, bh.config.FileLimit, bh.newConfiguredWriter)
}
return lazy.NewWriter(ctx, bh.newConfiguredWriter)
}
func (bh *BackupHandler) newConfiguredWriter(ctx context.Context) (io.WriteCloser, error) {
suffix := ""
if bh.state != nil {
suffix = bh.state.getFileSuffix()
}
filename := bh.encoder.GenerateFilename(bh.config.OutputFilePrefix, suffix)
storageWriter, err := bh.writer.NewWriter(ctx, filename)
if err != nil {
return nil, err
}
countingWriter := counter.NewWriter(storageWriter, &bh.stats.BytesWritten)
encryptedWriter, err := newEncryptionWriter(
bh.config.EncryptionPolicy,
bh.config.SecretAgentConfig,
countingWriter,
)
if err != nil {
return nil, fmt.Errorf("cannot set encryption: %w", err)
}
zippedWriter, err := newCompressionWriter(bh.config.CompressionPolicy, encryptedWriter)
if err != nil {
return nil, err
}
_, err = zippedWriter.Write(bh.encoder.GetHeader())
if err != nil {
return nil, err
}
bh.stats.IncFiles()
return zippedWriter, nil
}
// newCompressionWriter returns compression writer for compressing backup.
func newCompressionWriter(
policy *CompressionPolicy, writer io.WriteCloser,
) (io.WriteCloser, error) {
if policy == nil || policy.Mode == CompressNone {
return writer, nil
}
if policy.Mode == CompressZSTD {
return compression.NewWriter(writer, policy.Level)
}
return nil, fmt.Errorf("unknown compression mode %s", policy.Mode)
}
// newEncryptionWriter returns encryption writer for encrypting backup.
func newEncryptionWriter(
policy *EncryptionPolicy, saConfig *SecretAgentConfig, writer io.WriteCloser,
) (io.WriteCloser, error) {
if policy == nil || policy.Mode == EncryptNone {
return writer, nil
}
privateKey, err := ReadPrivateKey(policy, saConfig)
if err != nil {
return nil, err
}
return encryption.NewWriter(writer, privateKey)
}
func makeBandwidthLimiter(bandwidth int) *rate.Limiter {
if bandwidth > 0 {
return rate.NewLimiter(rate.Limit(bandwidth), bandwidth)
}
return nil
}
func (bh *BackupHandler) backupSIndexesAndUDFs(
ctx context.Context,
writer io.WriteCloser,
) error {
if !bh.config.NoIndexes {
err := bh.backupSIndexes(ctx, writer)
if err != nil {
return fmt.Errorf("failed to backup secondary indexes: %w", err)
}
}
if !bh.config.NoUDFs {
err := bh.backupUDFs(ctx, writer)
if err != nil {
return fmt.Errorf("failed to backup UDFs: %w", err)
}
}
return nil
}
// GetStats returns the stats of the backup job
func (bh *BackupHandler) GetStats() *models.BackupStats {
return &bh.stats
}
// Wait waits for the backup job to complete and returns an error if the job failed.
func (bh *BackupHandler) Wait(ctx context.Context) error {
defer func() {
bh.stats.Stop()
}()
select {
case <-bh.ctx.Done():
// Wait for global context.
return bh.ctx.Err()
case <-ctx.Done():
// Process local context.
bh.cancel()
return ctx.Err()
case err := <-bh.errors:
return err
}
}
func (bh *BackupHandler) backupSIndexes(
ctx context.Context,
writer io.Writer,
) error {
reader := aerospike.NewSIndexReader(bh.infoClient, bh.config.Namespace, bh.logger)
sindexReadWorker := pipeline.NewReadWorker[*models.Token](reader)
sindexWriter := pipeline.DataWriter[*models.Token](newTokenWriter(bh.encoder, writer, bh.logger, nil))
if bh.state != nil {
stInfo := newStateInfo(bh.state.RecordsStateChan, -1)
sindexWriter = pipeline.DataWriter[*models.Token](
newTokenWriter(
bh.encoder,
writer,
bh.logger,
stInfo,
),
)
}
sindexWriter = newWriterWithTokenStats(sindexWriter, &bh.stats, bh.logger)
sindexWriteWorker := pipeline.NewWriteWorker(sindexWriter, bh.limiter)
sindexPipeline, err := pipeline.NewPipeline[*models.Token](
bh.config.SyncPipelines,
[]pipeline.Worker[*models.Token]{sindexReadWorker},
[]pipeline.Worker[*models.Token]{sindexWriteWorker},
)
if err != nil {
return err
}
return sindexPipeline.Run(ctx)
}
func (bh *BackupHandler) backupUDFs(
ctx context.Context,
writer io.Writer,
) error {
reader := aerospike.NewUDFReader(bh.infoClient, bh.logger)
udfReadWorker := pipeline.NewReadWorker[*models.Token](reader)
udfWriter := pipeline.DataWriter[*models.Token](newTokenWriter(bh.encoder, writer, bh.logger, nil))
if bh.state != nil {
stInfo := newStateInfo(bh.state.RecordsStateChan, -1)
udfWriter = pipeline.DataWriter[*models.Token](
newTokenWriter(
bh.encoder,
writer,
bh.logger,
stInfo,
),
)
}
udfWriter = newWriterWithTokenStats(udfWriter, &bh.stats, bh.logger)
udfWriteWorker := pipeline.NewWriteWorker(udfWriter, bh.limiter)
udfPipeline, err := pipeline.NewPipeline[*models.Token](
bh.config.SyncPipelines,
[]pipeline.Worker[*models.Token]{udfReadWorker},
[]pipeline.Worker[*models.Token]{udfWriteWorker},
)
if err != nil {
return err
}
return udfPipeline.Run(ctx)
}