-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler_backup_xdr.go
251 lines (210 loc) · 6.21 KB
/
handler_backup_xdr.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
// 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"
"fmt"
"log/slog"
"sync"
"github.com./aerospike/backup-go/internal/asinfo"
"github.com./aerospike/backup-go/internal/logging"
"github.com./aerospike/backup-go/internal/metrics"
"github.com./aerospike/backup-go/internal/processors"
"github.com./aerospike/backup-go/models"
"github.com./aerospike/backup-go/pipeline"
"github.com./google/uuid"
)
// HandlerBackupXDR handles a backup job over XDR protocol.
type HandlerBackupXDR struct {
id string
ctx context.Context
cancel context.CancelFunc
readProcessor *recordReaderProcessor[*models.ASBXToken]
writerProcessor *fileWriterProcessor[*models.ASBXToken]
encoder Encoder[*models.ASBXToken]
config *ConfigBackupXDR
infoClient *asinfo.InfoClient
stats *models.BackupStats
logger *slog.Logger
errors chan error
// For graceful shutdown.
wg sync.WaitGroup
pl *pipeline.Pipeline[*models.ASBXToken]
// records per second collector.
rpsCollector *metrics.Collector
// kilobytes per second collector.
kbpsCollector *metrics.Collector
}
// newHandlerBackupXDR returns a new xdr backup handler.
func newBackupXDRHandler(
ctx context.Context,
config *ConfigBackupXDR,
aerospikeClient AerospikeClient,
writer Writer,
logger *slog.Logger,
) *HandlerBackupXDR {
id := uuid.NewString()
logger = logging.WithHandler(logger, id, logging.HandlerTypeBackup, writer.GetType())
metricMessage := fmt.Sprintf("%s metrics %s", logging.HandlerTypeBackup, id)
// redefine context cancel.
ctx, cancel := context.WithCancel(ctx)
encoder := NewEncoder[*models.ASBXToken](config.EncoderType, config.Namespace, false)
stats := models.NewBackupStats()
infoClient := asinfo.NewInfoClientFromAerospike(aerospikeClient, config.InfoPolicy, config.InfoRetryPolicy)
rpsCollector := metrics.NewCollector(
ctx,
logger,
metrics.MetricRecordsPerSecond,
metricMessage,
config.MetricsEnabled,
)
kbpsCollector := metrics.NewCollector(
ctx,
logger,
metrics.MetricKilobytesPerSecond,
metricMessage,
config.MetricsEnabled,
)
readProcessor := newRecordReaderProcessor[*models.ASBXToken](
config,
aerospikeClient,
infoClient,
nil,
nil,
rpsCollector,
logger,
)
writerProcessor := newFileWriterProcessor[*models.ASBXToken](
emptyPrefixSuffix,
emptyPrefixSuffix,
nil,
writer,
encoder,
config.EncryptionPolicy,
config.SecretAgentConfig,
config.CompressionPolicy,
nil,
stats,
nil,
kbpsCollector,
config.FileLimit,
config.ParallelWrite,
logger,
)
return &HandlerBackupXDR{
id: id,
ctx: ctx,
cancel: cancel,
encoder: encoder,
readProcessor: readProcessor,
writerProcessor: writerProcessor,
config: config,
infoClient: infoClient,
stats: stats,
logger: logger,
errors: make(chan error, 1),
rpsCollector: rpsCollector,
kbpsCollector: kbpsCollector,
}
}
// run runs the backup job.
// currently this should only be run once.
func (bh *HandlerBackupXDR) run() {
bh.wg.Add(1)
bh.stats.Start()
go doWork(bh.errors, bh.logger, func() error {
defer bh.wg.Done()
return bh.backup(bh.ctx)
})
}
func (bh *HandlerBackupXDR) backup(ctx context.Context) error {
var err error
// Count total records.
bh.stats.TotalRecords, err = bh.infoClient.GetRecordCount(bh.config.Namespace, nil)
if err != nil {
return fmt.Errorf("failed to get records count: %w", err)
}
// Read workers.
readWorkers, err := bh.readProcessor.newReadWorkersXDR(ctx)
if err != nil {
return fmt.Errorf("failed create read workers: %w", err)
}
// Write workers.
backupWriters, err := bh.writerProcessor.newWriters(ctx)
if err != nil {
return fmt.Errorf("failed to create storage writers: %w", err)
}
defer closeWriters(backupWriters, bh.logger)
writeWorkers := bh.writerProcessor.newWriteWorkers(backupWriters)
// Process workers.
composeProcessor := newTokenWorker[*models.ASBXToken](
processors.NewTokenCounter[*models.ASBXToken](&bh.stats.ReadRecords),
1)
// Create a pipeline and start.
pl, err := pipeline.NewPipeline(
pipeline.ModeSingleParallel, bh.splitFunc,
readWorkers,
composeProcessor,
writeWorkers,
)
if err != nil {
return fmt.Errorf("failed to create pipeline: %w", err)
}
// Assign, so we can get pl stats.
bh.pl = pl
return pl.Run(ctx)
}
// Wait waits for the backup job to complete and returns an error if the job failed.
func (bh *HandlerBackupXDR) Wait(ctx context.Context) error {
defer func() {
bh.stats.Stop()
}()
select {
case <-bh.ctx.Done():
// When global context is done, wait until all routines finish their work properly.
// Global context - is context that was passed to Backup() method.
bh.wg.Wait()
return bh.ctx.Err()
case <-ctx.Done():
// When local context is done, we cancel global context.
// Then wait until all routines finish their work properly.
// Local context - is context that was passed to Wait() method.
bh.cancel()
bh.wg.Wait()
return ctx.Err()
case err := <-bh.errors:
return err
}
}
// splitFunc distributes token between pipeline workers.
func (bh *HandlerBackupXDR) splitFunc(t *models.ASBXToken) int {
partPerWorker := MaxPartitions / bh.config.ParallelWrite
var id int
if partPerWorker > 0 {
id = t.Key.PartitionId() / partPerWorker
}
if id >= bh.config.ParallelWrite {
return id - 1
}
return id
}
// GetStats returns the stats of the backup job.
func (bh *HandlerBackupXDR) GetStats() *models.BackupStats {
return bh.stats
}
// GetMetrics returns the rpsCollector of the backup job.
func (bh *HandlerBackupXDR) GetMetrics() *models.Metrics {
pr, pw := bh.pl.GetMetrics()
return models.NewMetrics(pr, pw, bh.rpsCollector, bh.kbpsCollector)
}