-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathReplicateObject.js
More file actions
806 lines (764 loc) · 33.2 KB
/
ReplicateObject.js
File metadata and controls
806 lines (764 loc) · 33.2 KB
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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
const async = require('async');
const AWS = require('aws-sdk');
const errors = require('arsenal').errors;
const jsutil = require('arsenal').jsutil;
const ObjectMDLocation = require('arsenal').models.ObjectMDLocation;
const BackbeatClient = require('../../../lib/clients/BackbeatClient');
const BackbeatMetadataProxy = require('../../../lib/BackbeatMetadataProxy');
const mapLimitWaitPendingIfError = require('../../../lib/util/mapLimitWaitPendingIfError').default;
const { attachReqUids, TIMEOUT_MS } = require('../../../lib/clients/utils');
const getExtMetrics = require('../utils/getExtMetrics');
const BackbeatTask = require('../../../lib/tasks/BackbeatTask');
const { getAccountCredentials } = require('../../../lib/credentials/AccountCredentials');
const RoleCredentials = require('../../../lib/credentials/RoleCredentials');
const { metricsExtension, metricsTypeQueued, metricsTypeCompleted, replicationStages } = require('../constants');
function _extractAccountIdFromRole(role) {
return role.split(':')[4];
}
// BACKBEAT_INJECT_REPLICATION_ERROR_RATE variable can be set to randomly introduce errors.
// When set, the value is the target percentage of errors.
const BACKBEAT_INJECT_REPLICATION_ERROR_RATE =
process.env.BACKBEAT_INJECT_REPLICATION_ERROR_RATE / 100;
class ReplicateObject extends BackbeatTask {
/**
* Process a single replication entry
*
* @constructor
* @param {QueueProcessor} qp - queue processor instance
*/
constructor(qp) {
const qpState = qp.getStateVars();
super();
Object.assign(this, qpState);
this.retryParams = this.repConfig.queueProcessor.retry.scality;
if (this.destConfig && this.destConfig.bootstrapList) {
const destination = this.destConfig.bootstrapList
.find(endpoint => endpoint.site === this.site) || {};
this.destType = destination.type;
const retryParams =
this.repConfig.queueProcessor.retry[destination.type];
if (retryParams) {
this.retryParams = retryParams;
}
}
this.sourceRole = null;
this.targetRole = null;
this.destBackbeatHost = null;
this.s3sourceCredentials = null;
this.s3destCredentials = null;
this.S3source = null;
this.backbeatSource = null;
this.backbeatSourceProxy = null;
this.backbeatDest = null;
}
_createCredentials(where, authConfig, roleArn, log) {
const accountCredentials = getAccountCredentials(authConfig, log);
if (accountCredentials) {
return accountCredentials;
}
let vaultclient;
if (where === 'source') {
vaultclient = this.vaultclientCache.getClient('source:s3');
} else { // target
const { host, port } = this.destHosts.pickHost();
vaultclient = this.vaultclientCache.getClient('dest:s3',
host, port);
}
return new RoleCredentials(vaultclient, 'replication', roleArn, log);
}
_setupRoles(entry, log, cb) {
this.retry({
actionDesc: 'get bucket replication configuration',
logFields: { entry: entry.getLogInfo() },
actionFunc: done => this._setupRolesOnce(entry, log, done),
// Rely on AWS SDK notion of retryable error to decide if
// we should set the entry replication status to FAILED
// (non retryable) or retry later.
shouldRetryFunc: err => err.retryable,
log,
}, cb);
}
_setTargetAccountMd(destEntry, targetRole, log, cb) {
if (!this.destHosts) {
log.warn('cannot process entry: no target site configured',
{ entry: destEntry.getLogInfo() });
return cb(errors.InternalError);
}
this._setupDestClients(this.targetRole, log);
return this.retry({
actionDesc: 'lookup target account attributes',
logFields: { entry: destEntry.getLogInfo() },
actionFunc: done => this._setTargetAccountMdOnce(
destEntry, targetRole, log, done),
// this call uses our own Vault client which does not set
// the 'retryable' field
shouldRetryFunc: err =>
(err.InternalError || err.code === 'InternalError' ||
err.ServiceUnavailable || err.code === 'ServiceUnavailable'),
onRetryFunc: () => {
this.destHosts.pickNextHost();
this._setupDestClients(this.targetRole, log);
},
log,
}, cb);
}
_getAndPutPart(sourceEntry, destEntry, part, log, cb) {
const partLogger = this.logger.newRequestLogger(log.getUids());
this.retry({
actionDesc: 'stream part data',
logFields: { entry: sourceEntry.getLogInfo(), part },
actionFunc: done => this._getAndPutPartOnce(
sourceEntry, destEntry, part, partLogger, done),
shouldRetryFunc: err => err.retryable,
onRetryFunc: err => {
if (err.origin === 'target') {
this.destHosts.pickNextHost();
this._setupDestClients(this.targetRole, partLogger);
}
},
log: partLogger,
}, cb);
}
_putMetadata(entry, mdOnly, log, cb) {
this.retry({
actionDesc: 'update metadata on target',
logFields: { entry: entry.getLogInfo() },
actionFunc: done => this._putMetadataOnce(entry, mdOnly,
log, done),
shouldRetryFunc: err => err.retryable,
onRetryFunc: err => {
if (err.origin === 'target') {
this.destHosts.pickNextHost();
this._setupDestClients(this.targetRole, log);
}
},
log,
}, cb);
}
_getUpdatedSourceEntry(params) {
const { sourceEntry, replicationStatus } = params;
const entry = replicationStatus === 'COMPLETED' ?
sourceEntry.toCompletedEntry(this.site) :
sourceEntry.toFailedEntry(this.site);
const versionId =
sourceEntry.getReplicationSiteDataStoreVersionId(this.site);
return entry.setReplicationSiteDataStoreVersionId(this.site,
versionId);
}
_publishReplicationStatus(sourceEntry, replicationStatus, params) {
const { log, reason, kafkaEntry } = params;
const entryParams = { sourceEntry, replicationStatus };
const updatedSourceEntry = this._getUpdatedSourceEntry(entryParams);
const updateData = sourceEntry.getReplicationContent().includes('DATA');
const kafkaEntries = [updatedSourceEntry.toKafkaEntry(this.site)];
this.replicationStatusProducer.send(kafkaEntries, err => {
if (err) {
log.error('error in entry delivery to replication status topic', {
method: 'ReplicateObject._publishReplicationStatus',
topic: this.repConfig.replicationStatusTopic,
entry: updatedSourceEntry.getLogInfo(),
replicationStatus,
error: err,
});
} else {
log.info('replication status published', {
topic: this.repConfig.replicationStatusTopic,
entry: updatedSourceEntry.getLogInfo(),
replicationStatus,
reason,
});
this.metricsHandler.metadataReplicationStatus({ replicationStatus, location: this.site });
if (updateData) {
this.metricsHandler.dataReplicationStatus({ replicationStatus, location: this.site });
}
}
// Commit whether there was an error or not to allow
// progress of the consumer, as best effort measure when
// there are errors. We can count on the sweeper to retry
// entries that failed to be published to kafka (because
// they will keep their PENDING status).
if (this.consumer) {
this.consumer.onEntryCommittable(kafkaEntry);
}
});
}
_setupRolesOnce(entry, log, cb) {
log.debug('getting bucket replication',
{ entry: entry.getLogInfo() });
const entryRolesString = entry.getReplicationRoles();
let entryRoles;
if (entryRolesString !== undefined) {
entryRoles = entryRolesString.split(',');
}
if (entryRoles === undefined || entryRoles.length !== 2) {
log.error('expecting two roles separated by a ' +
'comma in entry replication configuration',
{
method: 'ReplicateObject._setupRolesOnce',
entry: entry.getLogInfo(),
roles: entryRolesString,
});
return cb(errors.BadRole);
}
this.sourceRole = entryRoles[0];
this.targetRole = entryRoles[1];
this._setupSourceClients(this.sourceRole, log);
const req = this.S3source.getBucketReplication(
{ Bucket: entry.getBucket() });
attachReqUids(req, log);
return req.send((err, data) => {
if (err) {
// eslint-disable-next-line no-param-reassign
err.origin = 'source';
log.error('error getting replication ' +
'configuration from S3',
{
method: 'ReplicateObject._setupRolesOnce',
entry: entry.getLogInfo(),
origin: 'source',
peer: this.sourceConfig.s3,
error: err.message,
httpStatus: err.statusCode,
});
return cb(err);
}
const replicationEnabled = (
data.ReplicationConfiguration.Rules.some(
rule => entry.getObjectKey().startsWith(rule.Prefix)
&& rule.Status === 'Enabled'));
if (!replicationEnabled) {
log.debug('replication disabled for object',
{
method: 'ReplicateObject._setupRolesOnce',
entry: entry.getLogInfo(),
});
return cb(errors.PreconditionFailed.customizeDescription(
'replication disabled for object'));
}
const roles = data.ReplicationConfiguration.Role.split(',');
if (roles.length !== 2) {
log.error('expecting two roles separated by a ' +
'comma in bucket replication configuration',
{
method: 'ReplicateObject._setupRolesOnce',
entry: entry.getLogInfo(),
roles,
});
return cb(errors.BadRole);
}
if (roles[0] !== entryRoles[0]) {
log.error('role in replication entry for source does ' +
'not match role in bucket replication configuration ',
{
method: 'ReplicateObject._setupRolesOnce',
entry: entry.getLogInfo(),
entryRole: entryRoles[0],
bucketRole: roles[0],
});
return cb(errors.BadRole);
}
if (roles[1] !== entryRoles[1]) {
log.error('role in replication entry for target does ' +
'not match role in bucket replication configuration ',
{
method: 'ReplicateObject._setupRolesOnce',
entry: entry.getLogInfo(),
entryRole: entryRoles[1],
bucketRole: roles[1],
});
return cb(errors.BadRole);
}
return cb(null, roles[0], roles[1]);
});
}
_setTargetAccountMdOnce(destEntry, targetRole, log, cb) {
log.debug('changing target account owner',
{ entry: destEntry.getLogInfo() });
const targetAccountId = _extractAccountIdFromRole(targetRole);
this.s3destCredentials.lookupAccountAttributes(
targetAccountId, (err, accountAttr) => {
if (err) {
// eslint-disable-next-line no-param-reassign
err.origin = 'target';
let peer;
if (this.destConfig.auth.type === 'role') {
peer = this.destBackbeatHost;
if (this.destConfig.auth.vault) {
const { host, port } = this.destConfig.auth.vault;
if (host) {
// no proxy is used, log the vault host/port
peer = { host, port };
}
}
}
log.error('an error occurred when looking up target ' +
'account attributes',
{
method: 'ReplicateObject._setTargetAccountMdOnce',
entry: destEntry.getLogInfo(),
origin: 'target',
peer,
error: err.message,
});
return cb(err);
}
log.debug('setting owner info in target metadata',
{
entry: destEntry.getLogInfo(),
accountAttr,
});
destEntry.setOwnerId(accountAttr.canonicalID);
destEntry.setOwnerDisplayName(accountAttr.displayName);
return cb();
});
}
_getAndPutData(sourceEntry, destEntry, log, cb) {
log.debug('replicating data', { entry: sourceEntry.getLogInfo() });
if (sourceEntry.getLocation().some(part => {
const partObj = new ObjectMDLocation(part);
return partObj.getDataStoreETag() === undefined;
})) {
const errMessage =
'cannot replicate object without dataStoreETag property';
log.error(errMessage, {
method: 'ReplicateObject._getAndPutData',
entry: sourceEntry.getLogInfo(),
});
return cb(errors.InternalError.customizeDescription(errMessage));
}
// For Replication Replay testing, set the BACKBEAT_INJECT_REPLICATION_ERROR_RATE variable
if (BACKBEAT_INJECT_REPLICATION_ERROR_RATE) {
if (Math.random() < BACKBEAT_INJECT_REPLICATION_ERROR_RATE) {
return process.nextTick(() => cb(new Error('Replication error')));
}
}
const locations = sourceEntry.getReducedLocations();
const mpuConcLimit = this.repConfig.queueProcessor.mpuPartsConcurrency;
return mapLimitWaitPendingIfError(locations, mpuConcLimit, (part, done) => {
this._getAndPutPart(sourceEntry, destEntry, part, log, done);
}, (err, destLocations) => {
if (err) {
return this._deleteOrphans(destEntry, destLocations, log, () => cb(err));
}
return cb(null, destLocations);
});
}
_publishReadMetrics(size, readStartTime) {
const serviceName = this.serviceName;
this.metricsHandler.timeElapsed({
serviceName,
location: this.site,
replicationStage: replicationStages.sourceDataRead,
}, Date.now() - readStartTime);
this.metricsHandler.sourceDataBytes({ serviceName, location: this.site }, size);
this.metricsHandler.reads({ serviceName, location: this.site });
}
_publishDataWriteMetrics(size, sourceEntry, writeStartTime) {
const serviceName = this.serviceName;
this.metricsHandler.timeElapsed({
serviceName,
location: this.site,
replicationStage: replicationStages.destinationDataWrite,
}, Date.now() - writeStartTime);
this.metricsHandler.dataReplicationBytes({ serviceName, location: this.site }, size);
this.metricsHandler.writes({
serviceName,
location: this.site,
replicationContent: 'data',
});
const extMetrics = getExtMetrics(this.site, size, sourceEntry);
this.mProducer.publishMetrics(extMetrics,
metricsTypeCompleted, metricsExtension, () => {});
}
_publishMetadataWriteMetrics(buffer, writeStartTime) {
const serviceName = this.serviceName;
this.metricsHandler.timeElapsed({
serviceName,
location: this.site,
replicationStage: replicationStages.destinationMetadataWrite,
}, Date.now() - writeStartTime);
this.metricsHandler.metadataReplicationBytes({
serviceName,
location: this.site,
}, Buffer.byteLength(buffer));
this.metricsHandler.writes({
serviceName,
location: this.site,
replicationContent: 'metadata',
});
}
_getAndPutPartOnce(sourceEntry, destEntry, part, log, done) {
const doneOnce = jsutil.once(done);
const partObj = new ObjectMDLocation(part);
const partNumber = partObj.getPartNumber();
const partSize = partObj.getPartSize();
let destReq = null;
let sourceReqAborted = false;
let destReqAborted = false;
const sourceReq = this.S3source.getObject({
Bucket: sourceEntry.getBucket(),
Key: sourceEntry.getObjectKey(),
VersionId: sourceEntry.getEncodedVersionId(),
PartNumber: partNumber,
});
attachReqUids(sourceReq, log);
sourceReq.on('error', err => {
if (!sourceReqAborted && !destReqAborted) {
destReq.abort();
destReqAborted = true;
}
// eslint-disable-next-line no-param-reassign
err.origin = 'source';
if (err.statusCode === 404) {
return doneOnce(err);
}
if (!sourceReqAborted) {
log.error('an error occurred on getObject from S3',
{
method: 'ReplicateObject._getAndPutPartOnce',
entry: sourceEntry.getLogInfo(),
part,
origin: 'source',
peer: this.sourceConfig.s3,
error: err.message,
httpStatus: err.statusCode,
});
}
return doneOnce(err);
});
const incomingMsg = sourceReq.createReadStream();
const readStartTime = Date.now();
incomingMsg.on('error', err => {
if (!sourceReqAborted && !destReqAborted) {
destReq.abort();
destReqAborted = true;
}
if (err.statusCode === 404) {
return doneOnce(errors.ObjNotFound);
}
if (!sourceReqAborted) {
// eslint-disable-next-line no-param-reassign
err.origin = 'source';
// eslint-disable-next-line no-param-reassign
err.retryable = true;
log.error('an error occurred when streaming data from S3',
{
method: 'ReplicateObject._getAndPutPartOnce',
entry: destEntry.getLogInfo(),
part,
origin: 'source',
peer: this.sourceConfig.s3,
error: err.message,
});
}
return doneOnce(err);
});
incomingMsg.on('end', () => {
this._publishReadMetrics(partSize, readStartTime);
});
log.debug('putting data', { entry: destEntry.getLogInfo(), part });
destReq = this.backbeatDest.putData({
Bucket: destEntry.getBucket(),
Key: destEntry.getObjectKey(),
CanonicalID: destEntry.getOwnerId(),
ContentLength: partSize,
ContentMD5: partObj.getPartETag(),
Body: incomingMsg,
});
attachReqUids(destReq, log);
const writeStartTime = Date.now();
return destReq.send((err, data) => {
if (err) {
if (!destReqAborted) {
sourceReq.abort();
sourceReqAborted = true;
// eslint-disable-next-line no-param-reassign
err.origin = 'target';
log.error('an error occurred on putData to S3',
{
method: 'ReplicateObject._getAndPutPartOnce',
entry: destEntry.getLogInfo(),
part,
origin: 'target',
peer: this.destBackbeatHost,
error: err.message,
});
}
return doneOnce(err);
}
partObj.setDataLocation(data.Location[0]);
// Set encryption parameters that were used to encrypt the
// target data in the object metadata, or reset them if
// there was no encryption
const { ServerSideEncryption, SSECustomerAlgorithm, SSEKMSKeyId } = data;
destEntry.setAmzServerSideEncryption(ServerSideEncryption || '');
destEntry.setAmzEncryptionCustomerAlgorithm(SSECustomerAlgorithm || '');
destEntry.setAmzEncryptionKeyId(SSEKMSKeyId || '');
this._publishDataWriteMetrics(partSize, sourceEntry, writeStartTime);
return doneOnce(null, partObj.getValue());
});
}
_putMetadataOnce(entry, mdOnly, log, cb) {
log.debug('putting metadata', {
where: 'target', entry: entry.getLogInfo(),
replicationStatus: entry.getReplicationSiteStatus(this.site),
});
const cbOnce = jsutil.once(cb);
// sends extra header x-scal-replication-content to the target
// if it's a metadata operation only
const replicationContent = (mdOnly ? 'METADATA' : undefined);
const mdBlob = entry.getSerialized();
const req = this.backbeatDest.putMetadata({
Bucket: entry.getBucket(),
Key: entry.getObjectKey(),
VersionId: entry.getEncodedVersionId(),
ContentLength: Buffer.byteLength(mdBlob),
Body: mdBlob,
ReplicationContent: replicationContent,
});
attachReqUids(req, log);
const writeStartTime = Date.now();
req.send((err, data) => {
if (err) {
// eslint-disable-next-line no-param-reassign
err.origin = 'target';
if (err.ObjNotFound || err.code === 'ObjNotFound') {
return cbOnce(err);
}
log.error('an error occurred when putting metadata to S3',
{
method: 'ReplicateObject._putMetadataOnce',
entry: entry.getLogInfo(),
origin: 'target',
peer: this.destBackbeatHost,
error: err.message,
});
return cbOnce(err);
}
this._publishMetadataWriteMetrics(mdBlob, writeStartTime);
return cbOnce(null, data);
});
}
_deleteOrphans(entry, locations, log, cb) {
const writtenLocations = locations
.filter(loc => loc)
.map(loc => ({ key: loc.key, dataStoreName: loc.dataStoreName }));
if (writtenLocations.length === 0) {
return process.nextTick(cb);
}
log.info('deleting orphan data after replication failure',
{
method: 'ReplicateObject._deleteOrphans',
entry: entry.getLogInfo(),
peer: this.destBackbeatHost,
});
const req = this.backbeatDest.batchDelete({
Bucket: entry.getBucket(),
Key: entry.getObjectKey(),
Locations: writtenLocations,
});
attachReqUids(req, log);
return req.send(err => {
if (err) {
log.error('an error occurred during batch delete of orphan data',
{
method: 'ReplicateObject._deleteOrphans',
entry: entry.getLogInfo(),
origin: 'target',
peer: this.destBackbeatHost,
error: err.message,
});
writtenLocations.forEach(location => {
log.error('orphan data location was not deleted', {
method: 'ReplicateObject._deleteOrphans',
entry: entry.getLogInfo(),
location,
});
});
}
// do not return the batch delete error, only log it
return cb();
});
}
_setupSourceClients(sourceRole, log) {
this.s3sourceCredentials =
this._createCredentials('source', this.sourceConfig.auth,
sourceRole, log);
// Disable retries, use our own retry policy (mandatory for
// putData route in order to fetch data again from source).
const sourceS3 = this.sourceConfig.s3;
this.S3source = new AWS.S3({
endpoint: `${this.sourceConfig.transport}://` +
`${sourceS3.host}:${sourceS3.port}`,
credentials: this.s3sourceCredentials,
sslEnabled: this.sourceConfig.transport === 'https',
s3ForcePathStyle: true,
signatureVersion: 'v4',
httpOptions: { agent: this.sourceHTTPAgent, timeout: 0 },
maxRetries: 0,
});
this.backbeatSource = new BackbeatClient({
endpoint: `${this.sourceConfig.transport}://` +
`${sourceS3.host}:${sourceS3.port}`,
credentials: this.s3sourceCredentials,
sslEnabled: this.sourceConfig.transport === 'https',
httpOptions: { agent: this.sourceHTTPAgent, timeout: TIMEOUT_MS, connectTimeout: TIMEOUT_MS },
maxRetries: 0,
});
this.backbeatSourceProxy = new BackbeatMetadataProxy(
`${this.sourceConfig.transport}://` +
`${sourceS3.host}:${sourceS3.port}`,
this.sourceConfig.auth, this.sourceHTTPAgent);
this.backbeatSourceProxy.setSourceRole(sourceRole);
this.backbeatSourceProxy.setBackbeatClient(this.backbeatSource);
}
_setupDestClients(targetRole, log) {
this.s3destCredentials =
this._createCredentials('target', this.destConfig.auth,
targetRole, log);
this.destBackbeatHost = this.destHosts.pickHost();
this.backbeatDest = new BackbeatClient({
endpoint: `${this.destConfig.transport}://` +
`${this.destBackbeatHost.host}:${this.destBackbeatHost.port}`,
credentials: this.s3destCredentials,
sslEnabled: this.destConfig.transport === 'https',
httpOptions: { agent: this.destHTTPAgent, timeout: 0 },
maxRetries: 0,
});
}
processQueueEntry(sourceEntry, kafkaEntry, done) {
const log = this.logger.newRequestLogger();
const destEntry = sourceEntry.toReplicaEntry(this.site);
log.debug('processing entry',
{ entry: sourceEntry.getLogInfo() });
const lastModified = new Date(sourceEntry.getLastModified());
this.metricsHandler.rpo({
serviceName: this.serviceName,
location: this.site,
}, (Date.now() - lastModified) / 1000);
if (sourceEntry.getIsDeleteMarker()) {
return async.waterfall([
next => {
this._setupRoles(sourceEntry, log, next);
},
(sourceRole, targetRole, next) => {
this._setTargetAccountMd(destEntry, targetRole, log,
next);
},
// put metadata in target bucket
next => {
// TODO check that bucket role matches role in metadata
this._putMetadata(destEntry, false, log, next);
},
], err => this._handleReplicationOutcome(
err, sourceEntry, destEntry, kafkaEntry, log, done));
}
const mdOnly = !sourceEntry.getReplicationContent().includes('DATA');
return async.waterfall([
// get data stream from source bucket
next => {
this._setupRoles(sourceEntry, log, next);
},
(sourceRole, targetRole, next) => {
this._setTargetAccountMd(destEntry, targetRole, log, next);
},
// Get data from source bucket and put it on the target bucket
next => {
if (!mdOnly) {
const extMetrics = getExtMetrics(this.site,
sourceEntry.getContentLength(), sourceEntry);
this.mProducer.publishMetrics(extMetrics,
metricsTypeQueued, metricsExtension, () => {});
return this._getAndPutData(sourceEntry, destEntry, log,
next);
}
return next(null, []);
},
// update location, replication status and put metadata in
// target bucket
(destLocations, next) => {
destEntry.setLocation(destLocations);
this._putMetadata(destEntry, mdOnly, log, err => {
if (err) {
return this._deleteOrphans(
destEntry, destLocations, log, () => next(err));
}
return next();
});
},
], err => this._handleReplicationOutcome(
err, sourceEntry, destEntry, kafkaEntry, log, done));
}
_processQueueEntryRetryFull(sourceEntry, destEntry, kafkaEntry, log, done) {
log.debug('reprocessing entry as full replication',
{ entry: sourceEntry.getLogInfo() });
return async.waterfall([
next => this._getAndPutData(sourceEntry, destEntry, log, next),
// update location, replication status and put metadata in
// target bucket
(location, next) => {
destEntry.setLocation(location);
this._putMetadata(destEntry, false, log, next);
},
], err => this._handleReplicationOutcome(
err, sourceEntry, destEntry, kafkaEntry, log, done));
}
_handleReplicationOutcome(err, sourceEntry, destEntry, kafkaEntry,
log, done) {
if (!err) {
log.debug('replication succeeded for object, publishing ' +
'replication status as COMPLETED',
{ entry: sourceEntry.getLogInfo() });
this._publishReplicationStatus(
sourceEntry, 'COMPLETED', { kafkaEntry, log });
return done(null, { committable: false });
}
if (err.BadRole ||
(err.origin === 'source' &&
(err.NoSuchEntity || err.code === 'NoSuchEntity' ||
err.AccessDenied || err.code === 'AccessDenied'))) {
log.error('replication failed permanently for object, ' +
'processing skipped',
{
failMethod: err.method,
entry: sourceEntry.getLogInfo(),
origin: err.origin,
error: err.description,
});
return done();
}
if (err.ObjNotFound || err.code === 'ObjNotFound') {
if (err.origin === 'source') {
log.info('replication skipped: ' +
'source object version does not exist',
{ entry: sourceEntry.getLogInfo() });
return done();
}
log.info('target object version does not exist, retrying ' +
'a full replication',
{ entry: sourceEntry.getLogInfo() });
// TODO: Is this the right place to capture retry metrics?
return this._processQueueEntryRetryFull(
sourceEntry, destEntry, kafkaEntry, log, done);
}
if (err.InvalidObjectState || err.code === 'InvalidObjectState') {
log.info('replication skipped: invalid object state',
{ entry: sourceEntry.getLogInfo() });
return done();
}
log.debug('replication failed permanently for object, ' +
'publishing replication status as FAILED',
{
failMethod: err.method,
entry: sourceEntry.getLogInfo(),
error: err.description,
});
this._publishReplicationStatus(sourceEntry, 'FAILED', {
log,
reason: err.description,
kafkaEntry,
});
return done(null, { committable: false });
}
}
module.exports = ReplicateObject;