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
|
'use strict';
/**
* Represents a MongoDB cluster.
*/
load('jstests/hooks/validate_collections.js'); // For validateCollections.
load('jstests/concurrency/fsm_libs/shard_fixture.js'); // For FSMShardingTest.
var Cluster = function(options) {
if (!(this instanceof Cluster)) {
return new Cluster(options);
}
function getObjectKeys(obj) {
var values = [];
if (typeof obj !== "object") {
return values;
}
Object.keys(obj).forEach(key => {
if (key.indexOf('.') > -1) {
throw new Error('illegal key specified ' + key);
}
var subKeys = getObjectKeys(obj[key]);
if (subKeys.length === 0) {
values.push(key);
} else {
subKeys.forEach(subKey => {
values.push(key + "." + subKey);
});
}
});
return values;
}
function validateClusterOptions(options) {
var allowedKeys = [
'replication.enabled',
'replication.numNodes',
'sameCollection',
'sameDB',
'setupFunctions',
'sharded.enabled',
'sharded.enableAutoSplit',
'sharded.enableBalancer',
'sharded.numMongos',
'sharded.numShards',
'sharded.stepdownOptions',
'sharded.stepdownOptions.configStepdown',
'sharded.stepdownOptions.shardStepdown',
'teardownFunctions',
];
getObjectKeys(options).forEach(function(option) {
assert.contains(option,
allowedKeys,
'invalid option: ' + tojson(option) + '; valid options are: ' +
tojson(allowedKeys));
});
options.replication = options.replication || {};
assert.eq('object', typeof options.replication);
options.replication.enabled = options.replication.enabled || false;
assert.eq('boolean', typeof options.replication.enabled);
if (typeof options.replication.numNodes !== 'undefined') {
assert(options.replication.enabled,
"Must have replication.enabled be true if 'replication.numNodes' is specified");
}
options.replication.numNodes = options.replication.numNodes || 3;
assert.eq('number', typeof options.replication.numNodes);
options.sameCollection = options.sameCollection || false;
assert.eq('boolean', typeof options.sameCollection);
options.sameDB = options.sameDB || false;
assert.eq('boolean', typeof options.sameDB);
options.sharded = options.sharded || {};
assert.eq('object', typeof options.sharded);
options.sharded.enabled = options.sharded.enabled || false;
assert.eq('boolean', typeof options.sharded.enabled);
if (typeof options.sharded.enableAutoSplit !== 'undefined') {
assert(options.sharded.enabled,
"Must have sharded.enabled be true if 'sharded.enableAutoSplit' is specified");
}
options.sharded.enableAutoSplit = options.sharded.enableAutoSplit || false;
assert.eq('boolean', typeof options.sharded.enableAutoSplit);
if (typeof options.sharded.enableBalancer !== 'undefined') {
assert(options.sharded.enabled,
"Must have sharded.enabled be true if 'sharded.enableBalancer' is specified");
}
options.sharded.enableBalancer = options.sharded.enableBalancer || false;
assert.eq('boolean', typeof options.sharded.enableBalancer);
if (typeof options.sharded.numMongos !== 'undefined') {
assert(options.sharded.enabled,
"Must have sharded.enabled be true if 'sharded.numMongos' is specified");
}
options.sharded.numMongos = options.sharded.numMongos || 2;
assert.eq('number', typeof options.sharded.numMongos);
if (typeof options.sharded.numShards !== 'undefined') {
assert(options.sharded.enabled,
"Must have sharded.enabled be true if 'sharded.numShards' is specified");
}
options.sharded.numShards = options.sharded.numShards || 2;
assert.eq('number', typeof options.sharded.numShards);
options.setupFunctions = options.setupFunctions || {};
assert.eq('object', typeof options.setupFunctions);
options.setupFunctions.mongod = options.setupFunctions.mongod || [];
assert(Array.isArray(options.setupFunctions.mongod),
'Expected setupFunctions.mongod to be an array');
assert(options.setupFunctions.mongod.every(f => (typeof f === 'function')),
'Expected setupFunctions.mongod to be an array of functions');
if (typeof options.setupFunctions.mongos !== 'undefined') {
assert(options.sharded.enabled,
"Must have sharded.enabled be true if 'setupFunctions.mongos' is specified");
}
options.setupFunctions.mongos = options.setupFunctions.mongos || [];
assert(Array.isArray(options.setupFunctions.mongos),
'Expected setupFunctions.mongos to be an array');
assert(options.setupFunctions.mongos.every(f => (typeof f === 'function')),
'Expected setupFunctions.mongos to be an array of functions');
options.setupFunctions.config = options.setupFunctions.config || [];
assert(Array.isArray(options.setupFunctions.config),
'Expected setupFunctions.config to be an array');
assert(options.setupFunctions.config.every(f => (typeof f === 'function')),
'Expected setupFunctions.config to be an array of functions');
options.teardownFunctions = options.teardownFunctions || {};
assert.eq('object', typeof options.teardownFunctions);
options.teardownFunctions.mongod = options.teardownFunctions.mongod || [];
assert(Array.isArray(options.teardownFunctions.mongod),
'Expected teardownFunctions.mongod to be an array');
assert(options.teardownFunctions.mongod.every(f => (typeof f === 'function')),
'Expected teardownFunctions.mongod to be an array of functions');
if (typeof options.teardownFunctions.mongos !== 'undefined') {
assert(options.sharded.enabled,
"Must have sharded.enabled be true if 'teardownFunctions.mongos' is specified");
}
options.teardownFunctions.mongos = options.teardownFunctions.mongos || [];
assert(Array.isArray(options.teardownFunctions.mongos),
'Expected teardownFunctions.mongos to be an array');
assert(options.teardownFunctions.mongos.every(f => (typeof f === 'function')),
'Expected teardownFunctions.mongos to be an array of functions');
options.teardownFunctions.config = options.teardownFunctions.config || [];
assert(Array.isArray(options.teardownFunctions.config),
'Expected teardownFunctions.config to be an array');
assert(options.teardownFunctions.config.every(f => (typeof f === 'function')),
'Expected teardownFunctions.config to be an array of functions');
}
var conn;
var secondaryConns;
var st;
var initialized = false;
var clusterStartTime;
var _conns = {mongos: [], mongod: []};
var nextConn = 0;
var replSets = [];
var rst;
validateClusterOptions(options);
Object.freeze(options);
this.setup = function setup() {
var verbosityLevel = 0;
if (initialized) {
throw new Error('cluster has already been initialized');
}
if (options.sharded.enabled) {
st = new FSMShardingTest(`mongodb://${db.getMongo().host}`);
conn = st.s(0); // First mongos
this.teardown = function teardown() {
options.teardownFunctions.mongod.forEach(this.executeOnMongodNodes);
options.teardownFunctions.mongos.forEach(this.executeOnMongosNodes);
options.teardownFunctions.config.forEach(this.executeOnConfigNodes);
};
this.reestablishConnectionsAfterFailover = function() {
// Call getPrimary() to re-establish the connections in FSMShardingTest
// as it is not a transparent proxy for ShardingTest.
st._configsvr.getPrimary();
for (let rst of st._shard_rsts) {
rst.getPrimary();
}
};
// Save all mongos, mongod, and ReplSet connections (if any).
var i;
i = 0;
while (st.s(i)) {
_conns.mongos.push(st.s(i++));
}
i = 0;
while (st.d(i)) {
_conns.mongod.push(st.d(i++));
}
i = 0;
while (st.rs(i)) {
var rs = st.rs(i++);
this._addReplicaSetConns(rs);
replSets.push(rs);
}
} else if (options.replication.enabled) {
rst = new ReplSetTest(db.getMongo().host);
conn = rst.getPrimary();
secondaryConns = rst.getSecondaries();
replSets = [rst];
this.teardown = function teardown() {
options.teardownFunctions.mongod.forEach(this.executeOnMongodNodes);
};
this._addReplicaSetConns(rst);
} else { // standalone server
conn = db.getMongo();
db.adminCommand({setParameter: 1, logLevel: verbosityLevel});
_conns.mongod = [conn];
}
initialized = true;
clusterStartTime = new Date();
options.setupFunctions.mongod.forEach(this.executeOnMongodNodes);
options.setupFunctions.config.forEach(this.executeOnConfigNodes);
if (options.sharded) {
options.setupFunctions.mongos.forEach(this.executeOnMongosNodes);
}
};
this._addReplicaSetConns = function _addReplicaSetConns(rsTest) {
_conns.mongod.push(rsTest.getPrimary());
rsTest.getSecondaries().forEach(function(secondaryConn) {
_conns.mongod.push(secondaryConn);
});
};
this.executeOnMongodNodes = function executeOnMongodNodes(fn) {
assert(initialized, 'cluster must be initialized first');
if (!fn || typeof(fn) !== 'function' || fn.length !== 1) {
throw new Error('mongod function must be a function that takes a db as an argument');
}
_conns.mongod.forEach(function(mongodConn) {
fn(mongodConn.getDB('admin'));
});
};
this.executeOnMongosNodes = function executeOnMongosNodes(fn) {
assert(initialized, 'cluster must be initialized first');
if (!fn || typeof(fn) !== 'function' || fn.length !== 1) {
throw new Error('mongos function must be a function that takes a db as an argument');
}
_conns.mongos.forEach(function(mongosConn) {
fn(mongosConn.getDB('admin'), true /* isMongos */);
});
};
this.executeOnConfigNodes = function executeOnConfigNodes(fn) {
assert(initialized, 'cluster must be initialized first');
if (!fn || typeof(fn) !== 'function' || fn.length !== 1) {
throw new Error('config function must be a function that takes a db as an argument');
}
st._configServers.forEach(function(conn) {
fn(conn.getDB('admin'));
});
};
this.synchronizeMongosClusterTimes = function synchronizeMongosClusterTimes() {
const contactConfigServerFn = ((mongosConn) => {
// The admin database is hosted on the config server.
assert.commandWorked(mongosConn.adminCommand({find: "foo"}));
});
// After the first iteration, the config server will have been gossiped the highest cluster
// time any mongos has seen. After the second iteration, each mongos should have been
// gossiped this time as well.
this.executeOnMongosNodes(contactConfigServerFn);
this.executeOnMongosNodes(contactConfigServerFn);
};
this.teardown = function teardown() {
assert(initialized, 'cluster must be initialized first');
options.teardownFunctions.mongod.forEach(this.executeOnMongodNodes);
};
this.getDB = function getDB(dbName) {
assert(initialized, 'cluster must be initialized first');
return conn.getDB(dbName);
};
this.getHost = function getHost() {
assert(initialized, 'cluster must be initialized first');
// Alternate mongos connections for sharded clusters
if (this.isSharded()) {
return _conns.mongos[nextConn++ % _conns.mongos.length].host;
}
return conn.host;
};
this.getSecondaryHost = function getSecondaryHost(dbName) {
assert(initialized, 'cluster must be initialized first');
if (this.isReplication() && !this.isSharded()) {
return secondaryConns[nextConn++ % secondaryConns.length].host;
}
return undefined;
};
this.getReplSetName = function getReplSetName() {
if (this.isReplication() && !this.isSharded()) {
return rst.name;
}
return undefined;
};
this.getReplSetNumNodes = function getReplSetNumNodes() {
assert(this.isReplication() && !this.isSharded(), 'cluster must be a replica set');
return options.replication.numNodes;
};
this.isSharded = function isSharded() {
return Cluster.isSharded(options);
};
this.isReplication = function isReplication() {
return Cluster.isReplication(options);
};
this.isStandalone = function isStandalone() {
return Cluster.isStandalone(options);
};
this.shardCollection = function shardCollection() {
assert(initialized, 'cluster must be initialized first');
assert(this.isSharded(), 'cluster is not sharded');
// If we are continuously stepping down shards, the config server may have stale view of the
// cluster, so retry on retryable errors, e.g. NotMaster.
if (this.shouldPerformContinuousStepdowns()) {
assert.soon(() => {
try {
st.shardColl.apply(st, arguments);
return true;
} catch (e) {
// The shardCollection command requires the config server primary to call
// listCollections and listIndexes on shards before sharding the collection,
// both of which can fail with a retryable error if the config server's view of
// the cluster is stale. This is safe to retry because no actual work has been
// done.
//
// TODO SERVER-30949: Remove this try catch block once listCollections and
// listIndexes automatically retry on NotMaster errors.
if (e.code === 18630 || // listCollections failure
e.code === 18631) { // listIndexes failure
print("Caught retryable error from shardCollection, retrying: " +
tojson(e));
return false;
}
throw e;
}
});
}
st.shardColl.apply(st, arguments);
};
// Provide a serializable form of the cluster for use in workload states. This
// method is required because we don't currently support the serialization of Mongo
// connection objects.
//
// Serialized format:
// {
// mongos: [
// "localhost:30998",
// "localhost:30999"
// ],
// config: [
// "localhost:29000",
// "localhost:29001",
// "localhost:29002"
// ],
// shards: {
// "test-rs0": [
// "localhost:20006",
// "localhost:20007",
// "localhost:20008"
// ],
// "test-rs1": [
// "localhost:20009",
// "localhost:20010",
// "localhost:20011"
// ]
// }
// }
this.getSerializedCluster = function getSerializedCluster() {
assert(initialized, 'cluster must be initialized first');
// TODO: Add support for non-sharded clusters.
if (!this.isSharded()) {
return '';
}
var cluster = {mongos: [], config: [], shards: {}};
var i = 0;
var mongos = st.s(0);
while (mongos) {
cluster.mongos.push(mongos.name);
++i;
mongos = st.s(i);
}
i = 0;
var config = st.c(0);
while (config) {
cluster.config.push(config.name);
++i;
config = st.c(i);
}
i = 0;
var shard = st.shard(0);
while (shard) {
if (shard.name.includes('/')) {
// If the shard is a replica set, the format of st.shard(0).name in ShardingTest is
// "test-rs0/localhost:20006,localhost:20007,localhost:20008".
var [setName, shards] = shard.name.split('/');
cluster.shards[setName] = shards.split(',');
} else {
// If the shard is a standalone mongod, the format of st.shard(0).name in
// ShardingTest is "localhost:20006".
cluster.shards[shard.shardName] = [shard.name];
}
++i;
shard = st.shard(i);
}
return cluster;
};
this.isBalancerEnabled = function isBalancerEnabled() {
return this.isSharded() && options.sharded.enableBalancer;
};
this.isAutoSplitEnabled = function isAutoSplitEnabled() {
return this.isSharded() && options.sharded.enableAutoSplit;
};
this.validateAllCollections = function validateAllCollections(phase) {
assert(initialized, 'cluster must be initialized first');
const isSteppingDownConfigServers = this.isSteppingDownConfigServers();
var _validateCollections = function _validateCollections(db, isMongos = false) {
// Validate all the collections on each node.
var res = db.adminCommand({listDatabases: 1});
assert.commandWorked(res);
res.databases.forEach(dbInfo => {
// Don't perform listCollections on the admin or config database through a mongos
// connection when stepping down the config server primary, because both are stored
// on the config server, and listCollections may return a not master error if the
// mongos is stale.
//
// TODO SERVER-30949: listCollections through mongos should automatically retry on
// NotMaster errors. Once that is true, remove this check.
if (isSteppingDownConfigServers && isMongos &&
(dbInfo.name === "admin" || dbInfo.name === "config")) {
return;
}
assert.commandWorked(
validateCollections(db.getSiblingDB(dbInfo.name), {full: true}),
phase + ' collection validation failed');
});
};
var startTime = Date.now();
jsTest.log('Starting to validate collections ' + phase);
this.executeOnMongodNodes(_validateCollections);
this.executeOnMongosNodes(_validateCollections);
var totalTime = Date.now() - startTime;
jsTest.log('Finished validating collections in ' + totalTime + ' ms, ' + phase);
};
this.checkReplicationConsistency = function checkReplicationConsistency(dbBlacklist, phase) {
assert(initialized, 'cluster must be initialized first');
if (!this.isReplication()) {
return;
}
var shouldCheckDBHashes = !this.isBalancerEnabled();
replSets.forEach(rst => {
var startTime = Date.now();
var res;
// Use '_master' instead of getPrimary() to avoid the detection of a new primary.
var primary = rst._master;
if (shouldCheckDBHashes) {
jsTest.log('Starting consistency checks for replica set with ' + primary.host +
' assumed to still be primary, ' + phase);
// Compare the dbhashes of the primary and secondaries.
rst.checkReplicatedDataHashes(phase, dbBlacklist);
var totalTime = Date.now() - startTime;
jsTest.log('Finished consistency checks of replica set with ' + primary.host +
' as primary in ' + totalTime + ' ms, ' + phase);
} else {
jsTest.log('Skipping consistency checks when the balancer is enabled, ' +
'for replica set with ' + primary.host +
' assumed to still be primary, ' + phase);
// Get the latest optime from the primary.
var replSetStatus = primary.adminCommand({replSetGetStatus: 1});
assert.commandWorked(replSetStatus, phase + ', error getting replication status');
var primaryInfo = replSetStatus.members.find(memberInfo => memberInfo.self);
assert(primaryInfo !== undefined,
phase + ', failed to find self in replication status: ' +
tojson(replSetStatus));
// Wait for all previous workload operations to complete, with "getLastError".
res = primary.getDB('test').runCommand({
getLastError: 1,
w: options.replication.numNodes,
wtimeout: 5 * 60 * 1000,
wOpTime: primaryInfo.optime
});
assert.commandWorked(res, phase + ', error awaiting replication');
}
});
};
this.recordConfigServerData = function recordConfigServerData(configServer) {
assert(initialized, 'cluster must be initialized first');
assert(this.isSharded(), 'cluster is not sharded');
var data = {};
var configDB = configServer.getDB('config');
// We record the contents of the 'lockpings' and 'locks' collections to make it easier to
// debug issues with distributed locks in the sharded cluster.
data.lockpings = configDB.lockpings.find({ping: {$gte: clusterStartTime}}).toArray();
// We suppress some fields from the result set to reduce the amount of data recorded.
data.locks =
configDB.locks.find({when: {$gte: clusterStartTime}}, {process: 0, ts: 0}).toArray();
return data;
};
this.recordAllConfigServerData = function recordAllConfigServerData() {
assert(initialized, 'cluster must be initialized first');
assert(this.isSharded(), 'cluster is not sharded');
var data = {};
st._configServers.forEach(config =>
(data[config.host] = this.recordConfigServerData(config)));
return data;
};
this.isRunningWiredTigerLSM = function isRunningWiredTigerLSM() {
var adminDB = this.getDB('admin');
if (this.isSharded()) {
// Get the storage engine the sharded cluster is configured to use from one of the
// shards since mongos won't report it.
adminDB = st.shard(0).getDB('admin');
}
var res = adminDB.runCommand({getCmdLineOpts: 1});
assert.commandWorked(res, 'failed to get command line options');
var wiredTigerOptions = {};
if (res.parsed && res.parsed.storage) {
wiredTigerOptions = res.parsed.storage.wiredTiger || {};
}
var wiredTigerCollectionConfig = wiredTigerOptions.collectionConfig || {};
var wiredTigerConfigString = wiredTigerCollectionConfig.configString || '';
return wiredTigerConfigString === 'type=lsm';
};
this.shouldPerformContinuousStepdowns = function shouldPerformContinuousStepdowns() {
return this.isSharded() && (typeof options.sharded.stepdownOptions !== 'undefined');
};
this.isSteppingDownConfigServers = function isSteppingDownConfigServers() {
return this.shouldPerformContinuousStepdowns() &&
options.sharded.stepdownOptions.configStepdown;
};
this.isSteppingDownShards = function isSteppingDownShards() {
return this.shouldPerformContinuousStepdowns() &&
options.sharded.stepdownOptions.shardStepdown;
};
this.awaitReplication = () => {
assert(this.isReplication(), 'cluster does not contain replica sets');
for (let rst of replSets) {
rst.awaitReplication();
}
};
};
/**
* Returns true if 'clusterOptions' represents a standalone mongod,
* and false otherwise.
*/
Cluster.isStandalone = function isStandalone(clusterOptions) {
return !clusterOptions.sharded.enabled && !clusterOptions.replication.enabled;
};
/**
* Returns true if 'clusterOptions' represents a replica set, and returns false otherwise.
*/
Cluster.isReplication = function isReplication(clusterOptions) {
return clusterOptions.replication.enabled;
};
/**
* Returns true if 'clusterOptions' represents a sharded configuration, and returns false otherwise.
*/
Cluster.isSharded = function isSharded(clusterOptions) {
return clusterOptions.sharded.enabled;
};
|