-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathLifecycleTask.js
More file actions
1960 lines (1824 loc) · 82.9 KB
/
LifecycleTask.js
File metadata and controls
1960 lines (1824 loc) · 82.9 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
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
const async = require('async');
const { errors, versioning } = require('arsenal');
const { ObjectMD } = require('arsenal').models;
const {
LifecycleDateTime,
LifecycleUtils,
} = require('arsenal').s3middleware.lifecycleHelpers;
const { CompareResult, MinHeap } = require('arsenal').algorithms.Heap;
const {
ListObjectsCommand,
ListObjectVersionsCommand,
ListMultipartUploadsCommand,
GetObjectTaggingCommand,
HeadObjectCommand,
GetBucketVersioningCommand,
} = require('@aws-sdk/client-s3');
const { attachReqUids } = require('@scality/cloudserverclient');
const config = require('../../../lib/Config');
const BackbeatTask = require('../../../lib/tasks/BackbeatTask');
const ActionQueueEntry = require('../../../lib/models/ActionQueueEntry');
const ReplicationAPI = require('../../replication/ReplicationAPI');
const { LifecycleMetrics, LIFECYCLE_MARKER_METRICS_LOCATION } = require('../LifecycleMetrics');
const locationsConfig = require('../../../conf/locationConfig.json') || {};
const { rulesSupportTransition } = require('../util/rules');
const { traceHeadersFromCurrentContext } = require('../../../lib/tracing/kafkaTraceContext');
const { decode } = versioning.VersionID;
const errorTransitionInProgress = errors.InternalError.
customizeDescription('transition is currently in progress');
const errorTransitionColdObject = errors.InternalError.
customizeDescription('transitioning a cold object is forbidden');
const errorObjectTemporarilyRestored = errors.InternalError.
customizeDescription('object temporarily restored');
const errorReplicationInProgress = errors.InternalError.
customizeDescription('replication of the object is currently in progress');
const errorLocationPaused = errors.InternalError.
customizeDescription('lifecycle events to location have been paused');
const errorCircuitBreakerTripped = errors.Throttling.
customizeDescription('circuit breaker tripped, skipping action');
// Default max AWS limit is 1000 for both list objects and list object versions
const MAX_KEYS = process.env.CI === 'true' ? 3 : 1000;
// concurrency mainly used in async calls
const CONCURRENCY_DEFAULT = 10;
// Max number of retries (with exp. backoff) that can be be performed for a single
// entry. We don't use the default, to avoid retrying for a long time (5 minutes)
// which could make Kafka timeout. 4 retries (e.g. 5 attempts) should be around 8
// seconds.
const MAX_RETRIES = 4;
// Maximum number of retries when processing entries in the range.
// We will retry a few times, but limit the total number of retries to ensure the
// range is processed timely. Not retrying is not too bad, as the next run will.
// We are processing 10 entries at a time, so a range should take around 1 second.
// Since entries get processed in parallel, they will get distributed accross the
// parallel tasks, so the total delay of retries should about 1m30s.
const MAX_RETRIES_TOTAL = CONCURRENCY_DEFAULT * MAX_RETRIES * 10;
/**
* compare 2 version by their stale dates returning:
* - LT (-1) if v1 is less than v2
* - EQ (0) if v1 equals v2
* - GT (1) if v1 is greater than v2
* @param {object} v1 - object version
* @param {object} v2 - object version
* @returns {number} -
*/
function noncurrentVersionCompare(v1, v2) {
const v1Date = new Date(v1.staleDate);
const v2Date = new Date(v2.staleDate);
if (v1Date < v2Date) {
return CompareResult.LT;
}
if (v1Date > v2Date) {
return CompareResult.GT;
}
return CompareResult.EQ;
}
class LifecycleTask extends BackbeatTask {
/**
* Processes Kafka Bucket entries and determines if specific Lifecycle
* actions apply to an object, version of an object, or MPU.
*
* @constructor
* @param {LifecycleBucketProcessor} lp - lifecycle processor instance
*/
constructor(lp) {
const lpState = lp.getStateVars();
super(lpState.processConfig?.retry);
Object.assign(this, lpState);
const { transitionOneDayEarlier, expireOneDayEarlier, timeProgressionFactor } = this.lcOptions;
this._lifecycleDateTime = new LifecycleDateTime({
transitionOneDayEarlier,
expireOneDayEarlier,
timeProgressionFactor,
});
this.setSupportedRules(this.supportedRules);
this._totalRetries = 0;
}
setSupportedRules(supportedRules) {
this._lifecycleUtils = new LifecycleUtils(
supportedRules,
this._lifecycleDateTime
);
this._supportedRules = supportedRules;
}
/**
* Send entry back to bucket task topic
* @param {Object} entry - The Kafka entry to send to the topic
* @param {Function} cb - The callback to call
* @return {undefined}
*/
_sendBucketEntry(entry, cb) {
// Bucket-task re-queue: keep normal parent-child semantics so the
// continuation stays in the same trace as the originating conductor
// scan. Re-queues happen rarely (only when a bucket is too big to
// finish in one batch) so the trace stays small.
const headers = traceHeadersFromCurrentContext();
const kafkaEntry = { message: JSON.stringify(entry) };
if (headers) kafkaEntry.headers = headers;
const entries = [kafkaEntry];
this.producer.sendToTopic(this.bucketTasksTopic, entries, err => {
LifecycleMetrics.onKafkaPublish(null, 'BucketTopic', 'bucket', err, 1);
return cb(err);
});
}
/**
* This function forces syncing the latest data mover topic
* offsets to the 'lifecycle' metrics snapshot. It is called when
* a bucket listing completes.
*
* By doing this, we ensure that when the bucket tasks queue is
* fully processed (no lag), the snapshot of data mover offsets
* will be beyond all transition tasks to be executed by the data
* mover, hence the conductor can check whether anything remains
* to be transitioned by the data mover (and skip the next task if
* so).
*
*
* @param {Werelogs.Logger} log - Logger object
* @return {undefined}
*/
_snapshotDataMoverTopicOffsets(log) {
// TODO: if multiple topics are used in replication API, i.e, one per
// location (implemented during cold-storage epic), handle them separately
this.kafkaBacklogMetrics.snapshotTopicOffsets(
this.producer.getKafkaProducer(),
ReplicationAPI.getDataMoverTopic(), 'lifecycle', err => {
if (err) {
log.error('error during snapshot of topic offsets', {
topic: ReplicationAPI.getDataMoverTopic(),
error: err.message,
});
}
});
}
/**
* Send entry to the object task topic
* @param {ActionQueueEntry} entry - The action entry to send to the topic
* @param {Function} cb - The callback to call
* @return {undefined}
*/
_sendObjectAction(entry, cb) {
const location = entry.getAttribute('details.dataStoreName');
const shouldBreak = this.circuitBreakers.tripped(
'expiration',
location,
this.objectTasksTopic,
);
if (shouldBreak) {
process.nextTick(() => cb(errorCircuitBreakerTripped));
return;
}
LifecycleMetrics.onLifecycleTriggered(this.log, 'bucket',
entry.getActionType() === 'deleteMPU' ? 'expiration:mpu' : 'expiration',
location,
Date.now() - entry.getAttribute('transitionTime'));
// Attach traceparent so the downstream consumer can link back to
// this bucket-processor span. The consumer always creates a new
// root trace with a Link (never parent-child across Kafka).
const headers = traceHeadersFromCurrentContext();
const kafkaEntry = { message: entry.toKafkaMessage() };
if (headers) kafkaEntry.headers = headers;
const entries = [kafkaEntry];
this.producer.sendToTopic(this.objectTasksTopic, entries, err => {
LifecycleMetrics.onKafkaPublish(null, 'ObjectTopic', 'bucket', err, 1);
return cb(err);
});
}
/**
* Handles non-versioned objects
* @param {object} bucketData - bucket data
* @param {array} bucketLCRules - array of bucket lifecycle rules
* @param {number} nbRetries - Number of time the process has been retried
* @param {Logger.newRequestLogger} log - logger object
* @param {function} done - callback(error, data)
* @return {undefined}
*/
_getObjectList(bucketData, bucketLCRules, nbRetries, log, done) {
const params = {
Bucket: bucketData.target.bucket,
MaxKeys: MAX_KEYS,
};
if (bucketData.details.marker) {
params.Marker = bucketData.details.marker;
}
const command = new ListObjectsCommand(params);
attachReqUids(command, log.getSerializedUids());
async.waterfall([
next => this.s3target.send(command)
.then(data => {
LifecycleMetrics.onS3Request(log, 'listObjects', 'bucket', null);
return next(null, data);
})
.catch(err => {
LifecycleMetrics.onS3Request(log, 'listObjects', 'bucket', err);
log.error('error listing bucket objects', {
method: 'LifecycleTask._getObjectList',
error: err,
bucket: params.Bucket,
});
return next(err);
}),
(data, next) => {
const contents = data.Contents || [];
if (data.IsTruncated && nbRetries === 0) {
// re-queue to Kafka topic bucketTasksTopic
// with bucket name and `data.marker` only once.
let marker = data.NextMarker;
if (!marker && contents.length > 0) {
marker = contents[contents.length - 1].Key;
}
const entry = Object.assign({}, bucketData, {
contextInfo: { reqId: log.getSerializedUids() },
details: { marker },
});
this._sendBucketEntry(entry, err => {
if (!err) {
log.debug(
'sent kafka entry for bucket consumption', {
method: 'LifecycleTask._getObjectList',
});
}
});
}
this._compareRulesToList(bucketData, bucketLCRules,
contents, log, 'Disabled', next);
},
], done);
}
/**
* Adds object to the noncurrent version helper Heap object.
* If the heap cap is reached:
* - compare the smallest object and the current object
* - if the current object is smaller:
* - remove top object and add the current object into the heap
* - return top object to be expired
* - if the top of the heap is smaller:
* - return the current object to be expired
* If the heap cap has not been reached:
* - add the current object into the heap and return null
* @param {string} bucketName - bucket name
* @param {object} rule - rule object
* @param {object} version - object version
* @return {object | null} - null or the version to be expired
*/
_ncvHeapAdd(bucketName, rule, version) {
const ncve = 'NoncurrentVersionExpiration';
const nncv = 'NewerNoncurrentVersions';
if (!rule[ncve] || !rule[ncve][nncv]) {
return null;
}
if (!this.ncvHeap.has(bucketName)) {
this.ncvHeap.set(bucketName, new Map());
}
if (!this.ncvHeap.get(bucketName).has(version.Key)) {
this.ncvHeap.get(bucketName).set(version.Key, new Map());
}
const ncvHeapObject = this.ncvHeap.get(bucketName).get(version.Key);
const nncvSize = parseInt(rule[ncve][nncv], 10);
const ruleId = rule[ncve].ID;
if (!ncvHeapObject.get(ruleId)) {
ncvHeapObject.set(ruleId, new MinHeap(nncvSize, noncurrentVersionCompare));
}
const heap = ncvHeapObject.get(ruleId);
if (heap.size < nncvSize) {
heap.add(version);
return null;
}
const heapTop = heap.peek();
if (noncurrentVersionCompare(version, heapTop) === CompareResult.LT) {
return version;
}
const toExpire = heap.remove();
heap.add(version);
return toExpire;
}
/**
* clear objects level entries from helper Heap object.
* @param {string} bucketName - bucket name
* @param {Set} uniqueObjectKeys - Set of unique object keys
* @return {undefined} -
*/
_ncvHeapObjectsClear(bucketName, uniqueObjectKeys) {
if (!this.ncvHeap.has(bucketName)) {
return;
}
const ncvHeapBucket = this.ncvHeap.get(bucketName);
uniqueObjectKeys.forEach(key => {
if (!ncvHeapBucket.has(key)) {
return;
}
ncvHeapBucket.get(key).clear();
ncvHeapBucket.delete(key);
});
return;
}
/**
* clear bucket level entry from helper Heap object.
* @param {string} bucketName - bucket name
* @return {undefined} -
*/
_ncvHeapBucketClear(bucketName) {
if (!this.ncvHeap.has(bucketName)) {
return;
}
const ncvHeapBucket = this.ncvHeap.get(bucketName);
// remove references to Heap objects under each Key entries
ncvHeapBucket.forEach(objMap => objMap.clear());
// remove references to Key maps under each Bucket entries
ncvHeapBucket.clear();
// delete reference to bucket Map
this.ncvHeap.delete(bucketName);
return;
}
/**
* Handles versioned objects (both enabled and suspended)
* @param {object} bucketData - bucket data
* @param {array} bucketLCRules - array of bucket lifecycle rules
* @param {string} versioningStatus - 'Enabled' or 'Suspended'
* @param {number} nbRetries - Number of time the process has been retried
* @param {Logger.newRequestLogger} log - logger object
* @param {function} done - callback(error, data)
* @return {undefined}
*/
_getObjectVersions(bucketData, bucketLCRules, versioningStatus, nbRetries, log, done) {
const paramDetails = {};
if (bucketData.details.versionIdMarker &&
bucketData.details.keyMarker) {
paramDetails.KeyMarker = bucketData.details.keyMarker;
paramDetails.VersionIdMarker = bucketData.details.versionIdMarker;
}
this._listVersions(bucketData, paramDetails, log, (err, data) => {
if (err) {
// error already logged at source
return done(err);
}
// all versions including delete markers
const { error, sortedList: allVersions } = this._mergeSortedVersionsAndDeleteMarkers(
data.Versions || [], data.DeleteMarkers || [], log,
);
if (error) {
return done(error);
}
// for all versions and delete markers, add stale date property
const allVersionsWithStaleDate = this._addStaleDateToVersions(
bucketData.details, allVersions);
// create Set of unique keys not matching the next marker to
// indicate the object level entries to be cleared at the end
// of the processing step
const uniqueObjectKeysNotNextMarker = new Set();
if (data.NextKeyMarker) {
allVersions.forEach(v => {
if (v.Key !== data.NextKeyMarker) {
uniqueObjectKeysNotNextMarker.add(v.Key);
}
});
}
// sending bucket entry - only once - for checking next listing
if (data.IsTruncated && allVersions.length > 0 && nbRetries === 0) {
// Uses last version whether Version or DeleteMarker
const last = allVersions[allVersions.length - 1];
const entry = Object.assign({}, bucketData, {
contextInfo: {
reqId: log.getSerializedUids(),
},
details: {
keyMarker: data.NextKeyMarker,
versionIdMarker: data.NextVersionIdMarker,
prevDate: last.LastModified,
},
});
this._sendBucketEntry(entry, err => {
if (!err) {
log.debug('sent kafka entry for bucket ' +
'consumption', {
method: 'LifecycleTask._getObjectVersions',
});
}
});
}
// if no versions to process, skip further processing for this
// batch
if (allVersionsWithStaleDate.length === 0) {
return done(null);
}
// for each version, get their relative rules, compare with
// bucket rules, match with `staleDate` to
// NoncurrentVersionExpiration Days and send expiration if
// rules all apply
return this._compareRulesToList(bucketData, bucketLCRules,
allVersionsWithStaleDate, log, versioningStatus,
err => {
if (err) {
return done(err);
}
if (!data.IsTruncated) {
// end of bucket listing
// clear bucket level entry and all object entries
this._ncvHeapBucketClear(bucketData.target.bucket);
} else {
// clear object level entries that have been processed
this._ncvHeapObjectsClear(
bucketData.target.bucket,
uniqueObjectKeysNotNextMarker
);
}
return done();
});
});
}
/**
* Handles incomplete multipart uploads
* @param {object} bucketData - bucket data
* @param {array} bucketLCRules - array of bucket lifecycle rules
* @param {object} params - params for AWS S3 `listObjectVersions`
* @param {number} nbRetries - Number of time the process has been retried
* @param {Logger.newRequestLogger} log - logger object
* @param {function} done - callback(error, data)
* @return {undefined}
*/
_getMPUs(bucketData, bucketLCRules, params, nbRetries, log, done) {
const command = new ListMultipartUploadsCommand(params);
attachReqUids(command, log.getSerializedUids());
async.waterfall([
next => this.s3target.send(command)
.then(data => {
LifecycleMetrics.onS3Request(log, 'listMultipartUploads', 'bucket', null);
return next(null, data);
})
.catch(err => {
LifecycleMetrics.onS3Request(log, 'listMultipartUploads', 'bucket', err);
log.error('error checking buckets MPUs', {
method: 'LifecycleTask._getMPUs',
error: err,
bucket: params.Bucket,
});
return next(err);
}),
(data, next) => {
if (data.IsTruncated && nbRetries === 0) {
// re-queue to kafka with `NextUploadIdMarker` &
// `NextKeyMarker` only once.
const entry = Object.assign({}, bucketData, {
contextInfo: {
reqId: log.getSerializedUids(),
},
details: {
keyMarker: data.NextKeyMarker,
uploadIdMarker: data.NextUploadIdMarker,
},
});
return this._sendBucketEntry(entry, err => {
if (!err) {
log.debug(
'sent kafka entry for bucket consumption', {
method: 'LifecycleTask._getMPUs',
});
}
return next(null, data);
});
}
return process.nextTick(() => next(null, data));
},
], (err, data) => {
if (err) {
return done(err);
}
this._compareMPUUploads(bucketData, bucketLCRules,
data.Uploads || [], log);
return done();
});
}
/** _decodeVID - decode the version id
* @param {string} versionId - version ID
* @param {Logger.newRequestLogger} log - logger object
* @return {Object} result - { error, decodedVersionId }
* @return {Error} result.error - if decoding failed
* @return {String} result.decodedVersionId - decoded version id
*/
_decodeVID(versionId, log) {
if (versionId === 'null') {
return { error: null, decodedVersionId: versionId };
}
const decoded = decode(versionId);
if (decoded instanceof Error) {
const invalidErr = errors.InternalError.customizeDescription('Invalid version id');
log.error('error decoding version id', {
method: 'LifecycleTask._decodeVID',
error: invalidErr,
versionId,
});
return { error: invalidErr, decodedVersionId: null };
}
return { error: null, decodedVersionId: decoded };
}
/**
* Helper method to merge and sort Versions and DeleteMarkers lists
* @param {array} versions - versions list
* @param {array} deleteMarkers - delete markers list
* @param {Logger.newRequestLogger} log - logger object
* @return {object} result - { error, sortedList }
* @return {Error} result.error - if decoding failed
* @return {array} result.sortedList - merge sorted array
*/
_mergeSortedVersionsAndDeleteMarkers(versions, deleteMarkers, log) {
const sortedList = [];
// Version index counter
let vIdx = 0;
// Delete Marker index counter
let dmIdx = 0;
while (vIdx < versions.length || dmIdx < deleteMarkers.length) {
if (versions[vIdx] === undefined) {
// versions list is empty, just need to merge remaining DM's
sortedList.push(deleteMarkers[dmIdx++]);
} else if (deleteMarkers[dmIdx] === undefined) {
// DM's list is empty, just need to merge remaining versions
sortedList.push(versions[vIdx++]);
} else if (versions[vIdx].Key !== deleteMarkers[dmIdx].Key) {
// 1. by Key name, alphabetical order sorted by ascii values
const isVKeyNewer = (versions[vIdx].Key <
deleteMarkers[dmIdx].Key);
if (isVKeyNewer) {
sortedList.push(versions[vIdx++]);
} else {
sortedList.push(deleteMarkers[dmIdx++]);
}
} else {
// The `Key` names of the versions and delete markers are the same.
// Compare the `LastModified` timestamps of the versions and delete markers.
const versionLastModified = new Date(versions[vIdx].LastModified);
const deleteMarkerLastModified = new Date(deleteMarkers[dmIdx].LastModified);
const isVersionLastModifiedNewer = versionLastModified > deleteMarkerLastModified;
const isDMLastModifiedNewer = deleteMarkerLastModified > versionLastModified;
if (isVersionLastModifiedNewer) {
sortedList.push(versions[vIdx++]);
} else if (isDMLastModifiedNewer) {
sortedList.push(deleteMarkers[dmIdx++]);
} else {
// If the version and the delete marker have the same last modified date
const nullVersion = (versions[vIdx].VersionId === 'null'
|| deleteMarkers[dmIdx].VersionId === 'null');
// and either of them is a null version, we cannot decode the version ID,
// so we push the version object onto the sorted list first.
if (nullVersion) {
sortedList.push(versions[vIdx++]);
} else {
// and neither of them are null, we decode the version IDs and compare them.
// A lower version ID indicates a more recent version.
// What is the purpose of decoding the version ID?
// The version ID string is a combination of the current time in milliseconds
// and the position of the request in that millisecond.
// This means that two version IDs with the same last modified date can be sorted,
// because the position of the request is also included in the version ID.
const { error: decodeVidError, decodedVersionId } =
this._decodeVID(versions[vIdx].VersionId, log);
if (decodeVidError) {
return { error: decodeVidError, sortedList: null };
}
const { error: decodedDMError, decodedVersionId: decodedDMId } =
this._decodeVID(deleteMarkers[dmIdx].VersionId, log);
if (decodedDMError) {
return { error: decodedDMError, sortedList: null };
}
const isVersionVidNewer = decodedVersionId < decodedDMId;
if (isVersionVidNewer) {
sortedList.push(versions[vIdx++]);
} else {
sortedList.push(deleteMarkers[dmIdx++]);
}
}
}
}
}
return { error: null, sortedList };
}
/**
* Helper method to add a staleDate property to each Version and
* DeleteMarker
* @param {object} bucketDetails - details property from Kafka Bucket entry
* @param {string} [bucketDetails.keyMarker] - previous listing key name
* @param {string} [bucketDetails.prevDate] - previous listing LastModified
* @param {array} list - list of sorted versions and delete markers
* @return {array} an updated array of Versions and DeleteMarkers with
* applied staleDate
*/
_addStaleDateToVersions(bucketDetails, list) {
const appliedList = [];
for (let i = 0; i < list.length; i++) {
const dupe = Object.assign({}, list[i]);
if (dupe.IsLatest) {
// IsLatest version should not have a staleDate
dupe.staleDate = undefined;
} else if (i === 0) {
// first item in list. bucket details may apply
dupe.staleDate = (bucketDetails.keyMarker === dupe.Key) ?
bucketDetails.prevDate : undefined;
} else {
dupe.staleDate = list[i - 1].LastModified;
}
appliedList.push(dupe);
}
return appliedList;
}
/**
* Wrapper for AWS S3 listObjectVersions
* @param {object} bucketData - bucket data
* @param {object} paramDetails - any extra param details (i.e. key marker,
* version id marker, prefix)
* @param {Logger.newRequestLogger} log - logger object
* @param {function} cb - cb(error, dataList)
* @return {undefined}
*/
_listVersions(bucketData, paramDetails, log, cb) {
const params = {
Bucket: bucketData.target.bucket,
MaxKeys: MAX_KEYS,
};
if (paramDetails.VersionIdMarker && paramDetails.KeyMarker) {
params.KeyMarker = paramDetails.KeyMarker;
params.VersionIdMarker = paramDetails.VersionIdMarker;
}
if (paramDetails.Prefix) {
params.Prefix = paramDetails.Prefix;
}
const command = new ListObjectVersionsCommand(params);
attachReqUids(command, log.getSerializedUids());
this.s3target.send(command)
.then(data => {
LifecycleMetrics.onS3Request(log, 'listObjectVersions', 'bucket', null);
return cb(null, data);
})
.catch(err => {
LifecycleMetrics.onS3Request(log, 'listObjectVersions', 'bucket', err);
log.error('error listing versioned bucket objects', {
method: 'LifecycleTask._listVersions',
error: err,
bucket: params.Bucket,
prefix: params.Prefix,
});
return cb(err);
});
}
/**
* Check that at least one rule has a tag or more.
* @param {array} rules - array of rules
* @return {boolean} true if at least one rule has a tag, false otherwise
*/
_rulesHaveTag(rules) {
return rules.some(rule => {
if (!rule.Filter) {
return false;
}
const tags = rule.Filter.And
? rule.Filter.And.Tags
: (rule.Filter.Tag && [rule.Filter.Tag]);
return tags && tags.length > 0;
});
}
/**
* Get object tagging if at least one lifecycle rule has a tag or more.
* @param {object} tagParams - s3.getObjectTagging parameters
* @param {string} tagParams.Bucket - bucket name
* @param {string} tagParams.Key - object key name
* @param {string} tagParams.VersionId - object version id
* @param {array} bucketLCRules - array of bucket lifecycle rules
* @param {Logger.newRequestLogger} log - logger object
* @param {function} cb - callback(error, tags)
* @return {undefined}
*/
_getObjectTagging(tagParams, bucketLCRules, log, cb) {
if (!this._rulesHaveTag(bucketLCRules)) {
return process.nextTick(() => cb(null, { TagSet: [] }));
}
const command = new GetObjectTaggingCommand(tagParams);
attachReqUids(command, log.getSerializedUids());
return this.s3target.send(command)
.then(tags => {
LifecycleMetrics.onS3Request(log, 'getObjectTagging', 'bucket', null);
return cb(null, tags);
})
.catch(err => {
LifecycleMetrics.onS3Request(log, 'getObjectTagging', 'bucket', err);
log.error('failed to get tags', {
method: 'LifecycleTask._getObjectTagging',
error: err,
bucket: tagParams.Bucket,
objectKey: tagParams.Key,
objectVersion: tagParams.VersionId,
});
return cb(err);
});
}
/**
* Handles comparing rules for objects
* @param {object} bucketData - bucket data
* @param {object} bucketData.target - target bucket info
* @param {string} bucketData.target.bucket - bucket name
* @param {string} bucketData.target.owner - owner id
* @param {string} [bucketData.prefix] - prefix
* @param {string} [bucketData.details.keyMarker] - next key
* marker for versioned buckets
* @param {string} [bucketData.details.versionIdMarker] - next
* version id marker for versioned buckets
* @param {string} [bucketData.details.marker] - next
* continuation token marker for non-versioned buckets
* @param {array} bucketLCRules - array of bucket lifecycle rules
* @param {object} object - object or object version
* @param {Logger.newRequestLogger} log - logger object
* @param {function} done - callback(error, data)
* @return {undefined}
*/
_getRules(bucketData, bucketLCRules, object, log, done) {
if (this._isDeleteMarker(object)) {
// DeleteMarkers don't have any tags, so avoid calling
// `getObjectTagging` which will throw an error
const filteredRules = this._lifecycleUtils.filterRules(bucketLCRules, object, []);
return done(null, this._lifecycleUtils.getApplicableRules(filteredRules, object));
}
const tagParams = { Bucket: bucketData.target.bucket, Key: object.Key };
if (object.VersionId) {
tagParams.VersionId = object.VersionId;
}
return this._getObjectTagging(tagParams, bucketLCRules, log, (err, tags) => {
if (err) {
return done(err);
}
// tags.TagSet === [{ Key: '', Value: '' }, ...]
const filteredRules = this._lifecycleUtils.filterRules(bucketLCRules, object, tags);
// reduce filteredRules to only get earliest dates
return done(null, this._lifecycleUtils.getApplicableRules(filteredRules, object));
});
}
/**
* check if rule applies for a given date or calculed days.
* @param {array} rule - bucket lifecycle rule
* @param {number} daysSinceInitiated - Days passed since entity (object or version) last modified
* NOTE: entity is not an in-progress MPU or a delete marker.
* @param {number} currentDate - current date
* @return {boolean} true if rule applies - false otherwise.
*/
_isRuleApplying(rule, daysSinceInitiated, currentDate) {
if (rule.Expiration && this._supportedRules.includes('Expiration')) {
if (rule.Expiration.Days !== undefined && daysSinceInitiated >= rule.Expiration.Days) {
return true;
}
if (rule.Expiration.Date && rule.Expiration.Date < currentDate) {
return true;
}
// Expiration.ExpiredObjectDeleteMarker rule's action does not apply
// since object is not a delete marker.
// AbortIncompleteMultipartUpload.DaysAfterInitiation rule's action does not apply
// since in-progress MPUs are beeing handled separetly prior to this checks.
}
if (rule.Transitions && rule.Transitions.length > 0
&& this._supportedRules.includes('Transition')) {
return rule.Transitions.some(t => {
if (t.Days !== undefined && daysSinceInitiated >= t.Days) {
return true;
}
if (t.Date && t.Date < currentDate) {
return true;
}
return false;
});
}
return false;
}
/**
* Check if entity (object or version) is eligible for expiration or transition based on its date.
* This function was introduced to avoid having to go further into processing
* (call getObjectTagging, headObject...) if the entity was not eligible based on its date.
* @param {array} rules - array of bucket lifecycle rules
* @param {object} entity - object or object version
* NOTE: entity is not an in-progress MPU or a delete marker.
* @param {string} versioningStatus - 'Enabled', 'Suspended', or 'Disabled'
* @return {boolean} true if eligible - false otherwise.
*/
_isEntityEligible(rules, entity, versioningStatus) {
const currentDate = this._lifecycleDateTime.getCurrentDate();
const daysSinceInitiated = this._lifecycleDateTime.findDaysSince(
new Date(entity.LastModified)
);
const { staleDate } = entity;
const daysSinceStaled = staleDate ?
this._lifecycleDateTime.findDaysSince(new Date(staleDate)) : null;
// Always eligible if object is a current version delete marker because
// it requires extra s3 call (list versions).
if (entity.IsLatest && this._isDeleteMarker(entity)) {
return true;
}
return rules.some(rule => {
if (rule.Status === 'Disabled') {
return false;
}
if (versioningStatus === 'Enabled' || versioningStatus === 'Suspended') {
if (entity.IsLatest) {
return this._isRuleApplying(rule, daysSinceInitiated, currentDate);
}
if (!staleDate) {
// NOTE: this should never happen. A non-current version should always have
// a stale date. If it is the case, we will log later for debug purposes.
return true;
}
if (rule.NoncurrentVersionExpiration
&& this._supportedRules.includes('NoncurrentVersionExpiration')) {
if (rule.NoncurrentVersionExpiration.NoncurrentDays !== undefined &&
daysSinceStaled >= rule.NoncurrentVersionExpiration.NoncurrentDays) {
return true;
}
}
if (rule.NoncurrentVersionTransitions && rule.NoncurrentVersionTransitions.length > 0
&& this._supportedRules.includes('NoncurrentVersionTransition')) {
return rule.NoncurrentVersionTransitions.some(t =>
(t.NoncurrentDays !== undefined && daysSinceInitiated >= t.NoncurrentDays));
}
return false;
}
return this._isRuleApplying(rule, daysSinceInitiated, currentDate);
});
}
/**
* Get rules and compare with each object or version
* @param {object} bucketData - bucket data
* @param {array} lcRules - array of bucket lifecycle rules
* @param {array} contents - list of objects or object versions
* @param {Logger.newRequestLogger} log - logger object
* @param {string} versioningStatus - 'Enabled', 'Suspended', or 'Disabled'
* @param {function} done - callback(error, data)
* @return {undefined}
*/
_compareRulesToList(bucketData, lcRules, contents, log, versioningStatus,
done) {
if (!contents.length) {
return done();
}
return async.eachLimit(contents, CONCURRENCY_DEFAULT, (obj, cb) => {
const eligible =
this._isEntityEligible(lcRules, obj, versioningStatus);
if (!eligible) {
log.debug('entity is not eligible for lifecycle', {
bucket: bucketData.target.bucket,
key: obj.Key,
versionId: obj.VersionId,
isLatest: obj.IsLatest,
lastModified: obj.LastModified,
staleDate: obj.staleDate,
versioningStatus,
});
return process.nextTick(cb);
}
// We don't want to retry the _whole_ list if only a single entry fails,
// so we possibly retry each individual entry here, and ignore errors.
// Ignoring error is not too bad, the entry will be picked up again on
// next lifecycle run
return this._retryEntry({
logFields: {
key: obj.Key,
versionId: obj.VersionId,
staleDate: obj.staleDate,
versioningStatus,
},
log,
actionFunc: done => async.waterfall([
next => this._getRules(bucketData, lcRules, obj, log, next),
(applicableRules, next) => {
if (versioningStatus === 'Enabled' || versioningStatus === 'Suspended') {
return this._compareVersion(bucketData, obj, contents,
applicableRules, versioningStatus, log, next);
}
return this._compareObject(bucketData, obj, applicableRules, log,
next);
},
], done),
}, cb);
}, done);
}
/**
* Retries processing an entry, respecting both individual and global retry
* limits to avoid stalling the whole process.
*
* @param {Object} params - The parameters object.
* @param {Function} params.actionFunc - The action function to retry.
* @param {Object} params.log - The logger object.
* @param {Object} params.logFields - The logger fields object.
* @param {Function} cb - The callback function to execute after the retries.
* @returns {void}
*/
_retryEntry(params, cb) {
const { actionFunc, log, logFields } = params;
this.retry({
actionDesc: 'compare rules lifecycle entry',