-
Notifications
You must be signed in to change notification settings - Fork 19
/
MongoClientInterface.js
2532 lines (2410 loc) · 96.4 KB
/
MongoClientInterface.js
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
/*
* we assume good default setting of write concern is good for all
* bulk writes. Note that bulk writes are not transactions but ordered
* writes. They may fail in between. To some extend those situations
* may generate orphans but not alter the proper conduct of operations
* (what he user wants and what we acknowledge to the user).
*
* Orphan situations may be recovered by the Lifecycle.
*
* We use proper atomic operations when needed.
*/
const async = require('async');
const constants = require('../../../constants');
const { reshapeExceptionError } = require('../../../errorUtils');
const errors = require('../../../errors').default;
const BucketInfo = require('../../../models/BucketInfo').default;
const ObjectMD = require('../../../models/ObjectMD').default;
const jsutil = require('../../../jsutil');
const MongoClient = require('mongodb').MongoClient;
const Uuid = require('uuid');
const diskusage = require('diskusage');
const genVID = require('../../../versioning/VersionID').generateVersionId;
const listAlgos = require('../../../algos/list/exportAlgos');
const LRUCache = require('../../../algos/cache/LRUCache');
const MongoReadStream = require('./readStream');
const MongoUtils = require('./utils');
const Skip = require('../../../algos/list/skip');
const MergeStream = require('../../../algos/stream/MergeStream');
const { Transform } = require('stream');
const { Version } = require('../../../versioning/Version');
const { formatMasterKey, formatVersionKey } = require('./utils');
const VID_NONE = '';
const USERSBUCKET = '__usersbucket';
const METASTORE = '__metastore';
const INFOSTORE = '__infostore';
const __UUID = 'uuid';
const PENSIEVE = 'PENSIEVE';
const __COUNT_ITEMS = 'countitems';
const ASYNC_REPAIR_TIMEOUT = 15000;
const CONNECT_TIMEOUT_MS = 5000;
// MongoDB default
const SOCKET_TIMEOUT_MS = 360000;
const CONCURRENT_CURSORS = 10;
const initialInstanceID = process.env.INITIAL_INSTANCE_ID;
let uidCounter = 0;
const BUCKET_VERSIONS = require('../../../versioning/constants')
.VersioningConstants.BucketVersioningKeyFormat;
const DB_PREFIXES = require('../../../versioning/constants')
.VersioningConstants.DbPrefixes;
function generateVersionId(replicationGroupId) {
// generate a unique number for each member of the nodejs cluster
return genVID(`${process.pid}.${uidCounter++}`,
replicationGroupId);
}
function inc(str) {
return str ? (str.slice(0, str.length - 1) +
String.fromCharCode(str.charCodeAt(str.length - 1) + 1)) : str;
}
/**
* @constructor
*
* @param {Object} params - constructor params
* @param {String} params.replicaSetHosts - replicaSetMembers for mongo
* @param {String} params.replicationGroupId - replication group id
* used here to generate version id's
* @param {String} params.replicaSet - name of mongo replica setup
* @param {String} params.path - path value
* // Does backbeat use this at all? Can we make this optional and
* // set a default so when instantiate the client elsewhere don't need?
* @param {String} params.database - name of database
* @param {function} params.isLocationTransient - optional function
* to get the transient attribute of a location by name
* @param {werelogs.Logger} params.logger - logger instance
* @param {String} [params.path] - path for mongo volume
*/
class MongoClientInterface {
constructor(params) {
const { replicaSetHosts, writeConcern, replicaSet, readPreference, path,
database, logger, replicationGroupId, authCredentials,
isLocationTransient, shardCollections } = params;
const cred = MongoUtils.credPrefix(authCredentials);
this.mongoUrl = `mongodb://${cred}${replicaSetHosts}/` +
`?w=${writeConcern}&readPreference=${readPreference}`;
if (!shardCollections) {
this.mongoUrl += `&replicaSet=${replicaSet}`;
}
this.logger = logger;
this.client = null;
this.db = null;
this.path = path;
this.replicationGroupId = replicationGroupId;
this.database = database;
this.isLocationTransient = isLocationTransient;
this.shardCollections = shardCollections;
this.concurrentCursors = (process.env.CONCURRENT_CURSORS &&
!Number.isNaN(process.env.CONCURRENT_CURSORS))
? Number.parseInt(process.env.CONCURRENT_CURSORS, 10)
: CONCURRENT_CURSORS;
this.bucketVFormatCache = new LRUCache(constants.maxCachedBuckets);
this.defaultBucketKeyFormat = [BUCKET_VERSIONS.v0, BUCKET_VERSIONS.v1]
.includes(process.env.DEFAULT_BUCKET_KEY_FORMAT) ? process.env.DEFAULT_BUCKET_KEY_FORMAT
: BUCKET_VERSIONS.v1;
this.cacheHit = 0;
this.cacheMiss = 0;
this.cacheHitMissLoggerInterval = null;
}
setup(cb) {
// FIXME: constructors shall not have side effect so there
// should be an async_init(cb) method in the wrapper to
// initialize this backend
if ((process.env.MONGO_CONNECT_TIMEOUT_MS &&
Number.isNaN(process.env.MONGO_CONNECT_TIMEOUT_MS)) ||
(process.env.MONGO_SOCKET_TIMEOUT_MS &&
Number.isNaN(process.env.MONGO_SOCKET_TIMEOUT_MS))) {
this.logger.error('MongoDB connect and socket timeouts must be a ' +
'number. Using default value(s).');
}
const connectTimeoutMS = Number.parseInt(
process.env.MONGO_CONNECT_TIMEOUT_MS, 10) || CONNECT_TIMEOUT_MS;
const socketTimeoutMS = Number.parseInt(
process.env.MONGO_SOCKET_TIMEOUT_MS, 10) || SOCKET_TIMEOUT_MS;
const options = {
connectTimeoutMS,
socketTimeoutMS,
useNewUrlParser: true,
};
if (process.env.MONGO_POOL_SIZE &&
!Number.isNaN(process.env.MONGO_POOL_SIZE)) {
options.poolSize = Number.parseInt(process.env.MONGO_POOL_SIZE, 10);
}
return MongoClient.connect(this.mongoUrl, options)
.then(client => {
this.logger.info('connected to mongodb');
this.client = client;
this.db = client.db(this.database, {
ignoreUndefined: true,
});
this.adminDb = client.db('admin');
// log cache hit/miss every 5min
this.cacheHitMissLoggerInterval = setInterval(() => {
let hitRatio = (this.cacheHit / (this.cacheHit + this.cacheMiss)) || 0;
hitRatio = hitRatio.toFixed(3);
this.logger.debug('MongoClientInterface: Bucket vFormat cache hit/miss (5min)',
{ hits: this.cacheHit, misses: this.cacheMiss, hitRatio });
this.cacheHit = 0;
this.cacheMiss = 0;
}, 300000);
return this.usersBucketHack(cb);
})
.catch(err => {
this.logger.error('error connecting to mongodb', { error: err.message });
return cb(errors.InternalError);
});
}
usersBucketHack(cb) {
/* FIXME: Since the bucket creation API is expecting the
usersBucket to have attributes, we pre-create the
usersBucket attributes here (see bucketCreation.js line
36)*/
const usersBucketAttr = new BucketInfo(constants.usersBucket,
'admin', 'admin', new Date().toJSON(),
BucketInfo.currentModelVersion());
return this.createBucket(
constants.usersBucket,
usersBucketAttr,
this.logger,
err => {
if (err) {
this.logger.fatal('error writing usersBucket ' +
'attributes to metastore',
{ error: err });
throw (errors.InternalError);
}
return cb();
});
}
close(cb) {
if (this.client) {
clearInterval(this.cacheHitMissLoggerInterval);
return this.client.close(true)
.then(() => cb())
.catch(() => cb());
}
return cb();
}
getCollection(name) {
/* mongo has a problem with .. in collection names */
const newName = (name === constants.usersBucket) ?
USERSBUCKET : name;
return this.db.collection(newName);
}
/**
* Creates a bucket with the provided metadata
* @param {string} bucketName bucket name
* @param {Object} bucketMD bucket metadata
* @param {Object} log logger
* @param {Function} cb callback
* @return {undefined}
*/
createBucket(bucketName, bucketMD, log, cb) {
// FIXME: there should be a version of BucketInfo.serialize()
// that does not JSON.stringify()
const bucketInfo = BucketInfo.fromObj(bucketMD);
const bucketMDStr = bucketInfo.serialize();
const newBucketMD = JSON.parse(bucketMDStr);
const m = this.getCollection(METASTORE);
const payload = {
$set: {
_id: bucketName,
value: newBucketMD,
},
};
if (bucketName !== constants.usersBucket &&
bucketName !== PENSIEVE &&
!bucketName.startsWith(constants.mpuBucketPrefix)) {
payload.$set.vFormat = this.defaultBucketKeyFormat;
} else {
payload.$set.vFormat = BUCKET_VERSIONS.v0;
}
// we don't have to test bucket existence here as it is done
// on the upper layers
m.updateOne({
_id: bucketName,
}, payload, {
upsert: true,
})
.then(() => {
// caching bucket vFormat
this.bucketVFormatCache.add(bucketName, payload.vFormat);
this.lastItemScanTime = null;
// NOTE: We do not need to create a collection for
// "constants.usersBucket" and "PENSIEVE" since it has already
// been created
if (bucketName !== constants.usersBucket && bucketName !== PENSIEVE) {
return this.db.createCollection(bucketName)
.then(() => {
if (this.shardCollections) {
const cmd = {
shardCollection: `${this.database}.${bucketName}`,
key: { _id: 1 },
};
return this.adminDb.command(cmd, {}).then(() => cb()).catch(err => {
log.error(
'createBucket: enabling sharding',
{ error: err });
return cb(errors.InternalError);
});
}
return cb();
});
}
return cb();
})
.catch(err => {
log.error('createBucket: error creating bucket', { error: err.message });
return cb(errors.InternalError);
});
}
/**
* Gets bucket metadata
* @param {String} bucketName bucket name
* @param {Object} log logger
* @param {Function} cb callback
* @return {undefined}
*/
getBucketAttributes(bucketName, log, cb) {
const m = this.getCollection(METASTORE);
m.findOne({
_id: bucketName,
})
.then(doc => {
if (!doc) {
return cb(errors.NoSuchBucket);
}
// FIXME: there should be a version of BucketInfo.deserialize()
// that properly inits w/o JSON.parse()
const bucketMDStr = JSON.stringify(doc.value);
const bucketMD = BucketInfo.deSerialize(bucketMDStr);
return cb(null, bucketMD);
})
.catch(err => {
log.error(
'getBucketAttributes: error getting bucket attributes',
{ error: err.message });
return cb(errors.InternalError);
});
return undefined;
}
/**
* Gets the bucket key format
* @param {String} bucketName bucket name
* @param {Object} log logger
* @param {Function} cb callback
* @return {undefined}
*/
getBucketVFormat(bucketName, log, cb) {
// retreiving vFormat from cache
const cachedVFormat = this.bucketVFormatCache.get(bucketName);
if (cachedVFormat) {
this.cacheHit++;
return cb(null, cachedVFormat);
}
this.cacheMiss++;
const m = this.getCollection(METASTORE);
m.findOne({
_id: bucketName,
})
.then(doc => {
if (!doc) {
return cb(null, BUCKET_VERSIONS.v0);
}
const vFormat = doc.vFormat || BUCKET_VERSIONS.v0;
this.bucketVFormatCache.add(bucketName, vFormat);
return cb(null, vFormat);
})
.catch(err => {
log.error(
'getBucketVFormat: error getting bucket vFormat',
{ bucket: bucketName, error: err.message },
);
return cb(errors.InternalError);
});
return undefined;
}
getBucketAndObject(bucketName, objName, params, log, cb) {
this.getBucketAttributes(bucketName, log, (err, bucket) => {
if (err) {
log.error(
'getBucketAttributes: error getting bucket attributes',
{ error: err.message });
return cb(err);
}
this.getObject(bucketName, objName, params, log, (err, obj) => {
if (err) {
if (err.is.NoSuchKey) {
return cb(null,
{
bucket:
BucketInfo.fromObj(bucket).serialize(),
});
}
log.error('getObject: error getting object',
{ error: err.message });
return cb(err);
}
return cb(null, {
bucket: BucketInfo.fromObj(bucket).serialize(),
obj: JSON.stringify(obj),
});
});
return undefined;
});
}
putBucketAttributes(bucketName, bucketMD, log, cb) {
// FIXME: there should be a version of BucketInfo.serialize()
// that does not JSON.stringify()
const bucketInfo = BucketInfo.fromObj(bucketMD);
const bucketMDStr = bucketInfo.serialize();
const newBucketMD = JSON.parse(bucketMDStr);
const m = this.getCollection(METASTORE);
m.updateOne({
_id: bucketName,
}, {
$set: {
_id: bucketName,
value: newBucketMD,
},
}, {
upsert: true,
})
.then(() => cb())
.catch(err => {
log.error(
'putBucketAttributes: error putting bucket attributes',
{ error: err.message });
return cb(errors.InternalError);
});
}
/**
*
* @param {String} bucketName - name of bucket
* @param {String} capabilityName - name of capability
* @param {String} [capabilityField] - name of capability field
* @param {Object} capability - capability object
* @param {Sbject} log - logger
* @param {Function} cb - callback
* @return {undefined}
*/
putBucketAttributesCapabilities(bucketName, capabilityName, capabilityField, capability, log, cb) {
const m = this.getCollection(METASTORE);
const updateString = capabilityField ?
`value.capabilities.${capabilityName}.${capabilityField}` :
`value.capabilities.${capabilityName}`;
m.updateOne({
_id: bucketName,
}, {
$set: {
_id: bucketName,
[updateString]: capability,
},
}, {
upsert: true,
}).then(() => cb()).catch(err => {
log.error(
'putBucketAttributesCapabilities: error putting bucket attributes',
{ error: err.message });
return cb(errors.InternalError);
});
}
/**
* Delete bucket attributes capability
* @param {String} bucketName - name of bucket
* @param {String} capabilityName - name of capability
* @param {String} [capabilityField] - name of capability field
* @param {Object} log - logger
* @param {Function} cb - callback
* @return {undefined}
**/
deleteBucketAttributesCapability(bucketName, capabilityName, capabilityField, log, cb) {
const m = this.getCollection(METASTORE);
const updateString = capabilityField ?
`value.capabilities.${capabilityName}.${capabilityField}` :
`value.capabilities.${capabilityName}`;
m.updateOne({
_id: bucketName,
}, {
$unset: {
[updateString]: '',
},
}).then(() => cb()).catch(err => {
if (err) {
log.error(
'deleteBucketAttributesCapability: error deleting bucket attributes',
{ error: err.message });
return cb(errors.InternalError);
}
return cb();
});
}
/*
* Delete bucket from metastore
*/
deleteBucketStep2(bucketName, log, cb) {
const m = this.getCollection(METASTORE);
m.findOneAndDelete({
_id: bucketName,
}, {})
.then(result => {
if (result.ok !== 1) {
log.error('deleteBucketStep2: failed deleting bucket');
return cb(errors.InternalError);
}
// removing cached bucket metadata
this.bucketVFormatCache.remove(bucketName);
return cb(null);
})
.catch(err => {
log.error('deleteBucketStep2: error deleting bucket',
{ error: err.message });
return cb(errors.InternalError);
});
}
/*
* Drop the bucket then process to step 2. Checking
* the count is already done by the upper layer. We don't need to be
* atomic because the call is protected by a delete_pending flag
* in the upper layer.
* 2 cases here:
* 1) the collection may not yet exist (or being already dropped
* by a previous call)
* 2) the collection may exist.
*/
deleteBucket(bucketName, log, cb) {
const c = this.getCollection(bucketName);
c.drop({})
.then(() => {
this.deleteBucketStep2(bucketName, log, err => {
if (err) {
return cb(err);
}
this.lastItemScanTime = null;
return cb(null);
});
})
.catch(err => {
if (err.codeName === 'NamespaceNotFound') {
return this.deleteBucketStep2(bucketName, log, cb);
}
log.error('deleteBucket: error deleting bucket',
{ error: err.message });
return cb(errors.InternalError);
});
}
/**
* Returns the suitable mongo operation to perform
* depending on the version being put
* In v1 the master gets deleted instead of being
* updated like in v0 when the last version is a delete
* marker
* @param {Boolean} isDeleteMarker isDeleteMarker tag
* @param {String} vFormat vFormat of bucket
* @param {Object} filter filter to get master
* @param {Object} update value to update master with
* @param {Boolean} upsert if upserting is needed
* @return {Object} mongo operation
*/
updateDeleteMaster(isDeleteMarker, vFormat, filter, update, upsert) {
// delete master when we are in v1 and the version is a delete
// marker
if (isDeleteMarker && vFormat === BUCKET_VERSIONS.v1) {
return {
deleteOne: {
filter,
},
};
}
// in v0 or if the version is not a delete marker the master
// simply gets updated
return {
updateOne: {
filter,
update,
upsert,
},
};
}
/**
* In this case we generate a versionId and
* sequentially create the object THEN update the master.
* Master is deleted when version put is a delete marker
*
* It is possible that 2 version creations are inverted
* in flight so we also check that we update a master only
* if the version in place is greater that the one we set.
*
* We also test the existence of the versionId property
* to manage the case of an object created before the
* versioning was enabled.
* @param {Object} c bucket collection
* @param {String} bucketName bucket name
* @param {String} objName object name
* @param {Object} objVal object metadata
* @param {Object} params params
* @param {String} params.vFormat object key format
* @param {Object} log logger
* @param {Function} cb callback
* @param {boolean} isRetry is function call a retry
* @return {undefined}
*/
putObjectVerCase1(c, bucketName, objName, objVal, params, log, cb, isRetry) {
const versionId = generateVersionId(this.replicationGroupId);
// eslint-disable-next-line
objVal.versionId = versionId;
const versionKey = formatVersionKey(objName, versionId, params.vFormat);
const masterKey = formatMasterKey(objName, params.vFormat);
// initiating array of operations with version creation
const ops = [{
updateOne: {
filter: {
_id: versionKey,
},
update: {
$set: { _id: versionKey, value: objVal },
},
upsert: true,
},
}];
// filter to get master
const filter = {
_id: masterKey,
$or: [{
'value.versionId': {
$exists: false,
},
},
{
'value.versionId': {
$gt: objVal.versionId,
},
},
],
};
// values to update master
const update = {
$set: { _id: masterKey, value: objVal },
};
// updating or deleting master depending on the last version put
// in v0 the master gets updated, in v1 the master gets deleted if version is
// a delete marker or updated otherwise.
const masterOp = this.updateDeleteMaster(objVal.isDeleteMarker, params.vFormat, filter, update, true);
ops.push(masterOp);
c.bulkWrite(ops, {
ordered: true,
})
.then(() => cb(null, `{"versionId": "${versionId}"}`))
.catch((err) => {
/*
* Related to https://jira.mongodb.org/browse/SERVER-14322
* It happens when we are pushing two versions "at the same time"
* and the master one does not exist. In MongoDB, two threads are
* trying to create the same key, the master version, and one of
* them, the one with the highest versionID (less recent one),
* fails.
* We check here than than the MongoDB error is related to the
* second operation, the master version update and than the error
* code is the one related to mentionned issue.
*/
if (err.code === 11000) {
log.debug('putObjectVerCase1: error putting object version', {
code: err.code,
error: err.errmsg,
isRetry: isRetry ? true : false, // eslint-disable-line no-unneeded-ternary
});
let count = err.result.upsertedCount;
if (typeof count !== 'number') {
count = err.result.nUpserted;
}
if (typeof count === 'number' && count !== 1) {
// This may be a race condition, when two different S3 Connector try to put the same
// version id
if (!isRetry) {
// retrying with a new version id
return process.nextTick(() =>
this.putObjectVerCase1(c, bucketName, objName, objVal, params, log, cb, true));
}
log.error('putObjectVerCase1: race condition upserting versionId', {
error: err.errmsg,
});
return cb(errors.InternalError);
}
// Otherwise this error is expected, it means that two differents version was put at the
// same time
return cb(null, `{"versionId": "${versionId}"}`);
}
log.error('putObjectVerCase1: error putting object version', {
error: err.errmsg,
});
return cb(errors.InternalError);
});
}
/**
* Case used when versioning has been disabled after objects
* have been created with versions
* @param {Object} c bucket collection
* @param {String} bucketName bucket name
* @param {String} objName object name
* @param {Object} objVal object metadata
* @param {Object} params params
* @param {String} params.vFormat object key format
* @param {Object} log logger
* @param {Function} cb callback
* @return {undefined}
*/
putObjectVerCase2(c, bucketName, objName, objVal, params, log, cb) {
const versionId = generateVersionId(this.replicationGroupId);
// eslint-disable-next-line
objVal.versionId = versionId;
const masterKey = formatMasterKey(objName, params.vFormat);
c.updateOne({ _id: masterKey },
{ $set: { value: objVal }, $setOnInsert: { _id: masterKey } },
{ upsert: true },
)
.then(() => cb(null, `{"versionId": "${objVal.versionId}"}`))
.catch((err) => {
log.error('putObjectVerCase2: error putting object version', { error: err.message });
return cb(errors.InternalError);
});
}
/**
* In this case the caller provides a versionId. This function will
* check if the object exists then sequentially update the object
* (or create if doesn't exist) with given versionId THEN the master
* if the provided versionId matches the one of the master. There
* is a potential race condition where if two putObjectVerCase3 are
* occurring at the same time and the master version doesn't exist,
* then one will upsert and update the master and one will fail with
* the KeyAlreadyExists error.
* @param {Object} c bucket collection
* @param {String} bucketName bucket name
* @param {String} objName object name
* @param {Object} objVal object metadata
* @param {Object} params params
* @param {String} params.vFormat object key format
* @param {String} params.versionId object version
* @param {Object} log logger
* @param {Function} cb callback
* @return {undefined}
*/
putObjectVerCase3(c, bucketName, objName, objVal, params, log, cb) {
// eslint-disable-next-line
objVal.versionId = params.versionId;
const versionKey = formatVersionKey(objName, params.versionId, params.vFormat);
const masterKey = formatMasterKey(objName, params.vFormat);
const putObjectEntry = (ops, callback) => {
c.bulkWrite(ops, {
ordered: true,
})
.then(() => callback(null, `{"versionId": "${objVal.versionId}"}`))
.catch(err => {
log.error('putObjectVerCase3: error putting object version', { error: err.message });
if (err.code === 11000) {
// We want duplicate key error logged however in
// case of the race condition mentioned above, the
// InternalError will allow for automatic retries
log.error('putObjectVerCase3:', errors.KeyAlreadyExists);
return callback(errors.InternalError);
}
return callback(errors.NoSuchVersion);
});
};
c.findOne({ _id: masterKey }).then(checkObj => {
const objUpsert = !checkObj;
// initiating array of operations with version creation/update
const ops = [{
updateOne: {
filter: {
_id: versionKey,
},
update: {
$set: {
_id: versionKey,
value: objVal,
},
},
upsert: true,
},
}];
// filter to get master
const filter = {
'_id': masterKey,
'value.versionId': objVal.versionId,
};
// values to update master
const update = {
$set: { _id: masterKey, value: objVal },
};
c.findOne({ _id: versionKey }).then(verObj => {
// existing versioned entry update.
// if master entry doesn't exist, skip upsert of master
if (verObj && !checkObj) {
putObjectEntry(ops, cb);
return null;
}
// updating or deleting master depending on the last version put
// in v0 the master gets updated, in v1 the master gets deleted if version is
// a delete marker or updated otherwise.
const masterOp = this.updateDeleteMaster(
objVal.isDeleteMarker,
params.vFormat,
filter,
update,
objUpsert,
);
ops.push(masterOp);
putObjectEntry(ops, cb);
return null;
}).catch(() => {
log.error('putObjectVerCase3: mongoDB error finding object');
return cb(errors.InternalError);
});
return null;
}).catch(() => {
log.error('putObjectVerCase3: mongoDB error finding object');
return cb(errors.InternalError);
});
}
/**
* In this case the caller provides a versionId. We assume that
* objVal already contains the destination versionId. We first
* update the version if it exists or create it. We then call
* getLatestVersion() to get the latest version. We update the
* master only if the returned version is greater or equal than
* the stored one. Caveat: this function is not optimized for
* multiple updates to the same objName, a batch would be more
* suited to avoid the parallel attempts to update the master.
* @param {Object} c bucket collection
* @param {String} bucketName bucket name
* @param {String} objName object name
* @param {Object} objVal object metadata
* @param {Object} params params
* @param {String} params.vFormat object key format
* @param {String} params.versionId object version
* @param {Object} log logger
* @param {Function} cb callback
* @return {undefined}
*/
putObjectVerCase4(c, bucketName, objName, objVal, params, log, cb) {
const versionKey = formatVersionKey(objName, params.versionId, params.vFormat);
const masterKey = formatMasterKey(objName, params.vFormat);
c.updateOne({
_id: versionKey,
}, {
$set: {
_id: versionKey,
value: objVal,
},
}, {
upsert: true,
}).then(() => this.getLatestVersion(c, objName, params.vFormat, log, (err, mstObjVal) => {
if (err && err.is.NoSuchKey) {
return cb(err);
}
if (err) {
log.error('getLatestVersion: getting latest version',
{ error: err.message });
return cb(err);
}
MongoUtils.serialize(mstObjVal);
const ops = [];
// filter to get master
const filter = {
'_id': masterKey,
'value.versionId': {
// We break the semantic correctness here with
// $gte instead of $gt because we do not have
// a microVersionId to capture the micro
// changes (tags, ACLs, etc). If we do not use
// $gte currently the micro changes are not
// propagated. We are now totally dependent of
// the order of changes (which Backbeat
// replication and ingestion can hopefully
// ensure), but this would not work e.g. in
// the case of an active-active replication.
$gte: mstObjVal.versionId,
},
};
// values to update master
const update = {
$set: { _id: masterKey, value: mstObjVal },
};
// updating or deleting master depending on the last version put
// in v0 the master gets updated, in v1 the master gets deleted if version is
// a delete marker or updated otherwise.
const masterOp = this.updateDeleteMaster(mstObjVal.isDeleteMarker, params.vFormat, filter, update,
true);
ops.push(masterOp);
return c.bulkWrite(ops, {
ordered: true,
}).then(() => cb(null, `{"versionId": "${objVal.versionId}"}`)).catch((err) => {
// we accept that the update fails if
// condition is not met, meaning that a more
// recent master was already in place
if (err.code === 11000) {
return cb(null, `{"versionId": "${objVal.versionId}"}`);
}
log.error('putObjectVerCase4: error upserting master', { error: err.message });
return cb(errors.InternalError);
});
})).catch(err => {
log.error(
'putObjectVerCase4: error upserting object version',
{ error: err.message });
return cb(errors.InternalError);
});
}
/**
* Put object when versioning is not enabled
* @param {Object} c bucket collection
* @param {String} bucketName bucket name
* @param {String} objName object name
* @param {Object} objVal object metadata
* @param {Object} params params
* @param {Object} log logger
* @param {Function} cb callback
* @return {undefined}
*/
putObjectNoVer(c, bucketName, objName, objVal, params, log, cb) {
const masterKey = formatMasterKey(objName, params.vFormat);
c.updateOne({
_id: masterKey,
}, {
$set: {
_id: masterKey,
value: objVal,
},
}, {
upsert: true,
}).then(() => cb()).catch((err) => {
log.error('putObjectNoVer: error putting obect with no versioning', { error: err.message });
return cb(errors.InternalError);
});
}
/**
* Returns the putObjectVerCase function to use
* depending on params
* @param {Object} params params
* @return {Function} suitable putObjectVerCase function
*/
getPutObjectVerStrategy(params) {
if (params.versionId === '') {
return this.putObjectVerCase2;
} else if (params.versionId) {
if (!params.repairMaster) {
return this.putObjectVerCase3;
}
return this.putObjectVerCase4;
} else if (params.versioning) {
return this.putObjectVerCase1;
}
return this.putObjectNoVer;
}
/**
* puts object metadata in bucket
* @param {String} bucketName bucket name
* @param {String} objName object name
* @param {Object} objVal object metadata
* @param {object} params params
* @param {Object} log logger
* @param {Function} cb callback
* @return {undefined}
*/
putObject(bucketName, objName, objVal, params, log, cb) {
MongoUtils.serialize(objVal);
const c = this.getCollection(bucketName);
const _params = Object.assign({}, params);
return this.getBucketVFormat(bucketName, log, (err, vFormat) => {
if (err) {
return cb(err);
}
_params.vFormat = vFormat;
if (params) {
const putObjectVer = this.getPutObjectVerStrategy(params)
.bind(this);
return putObjectVer(c, bucketName, objName, objVal, _params, log,
cb);
}
return this.putObjectNoVer(c, bucketName, objName, objVal,
_params, log, cb);
});
}
/**
* gets versioned and non versioned object metadata
* @param {String} bucketName bucket name
* @param {String} objName object name
* @param {object} params params
* @param {String} params.versionId version of object (optional)
* @param {Object} log logger
* @param {Function} cb callback
* @return {undefined}
*/
getObject(bucketName, objName, params, log, cb) {
const c = this.getCollection(bucketName);
let key;
async.waterfall([
next => this.getBucketVFormat(bucketName, log, next),
(vFormat, next) => {
if (params && params.versionId) {
key = formatVersionKey(objName, params.versionId, vFormat);
} else {
key = formatMasterKey(objName, vFormat);