-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
shardingtest.js
1965 lines (1678 loc) · 74.5 KB
/
shardingtest.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
/**
* Starts up a sharded cluster with the given specifications. The cluster will be fully operational
* after the execution of this constructor function.
*
* In addition to its own methods, ShardingTest inherits all the functions from the 'sh' utility
* with the db set as the first mongos instance in the test (i.e. s0).
*
* @param {Object} params Contains the key-value pairs for the cluster
* configuration. Accepted keys are:
*
* {
* name {string}: name for this test
* shouldFailInit {boolean}: if set, assert that this will fail initialization
* verbose {number}: the verbosity for the mongos
* chunkSize {number}: the chunk size to use as configuration for the cluster
*
* mongos {number|Object|Array.<Object>}: number of mongos or mongos
* configuration object(s)(*). @see MongoRunner.runMongos
*
* rs {Object|Array.<Object>}: replica set configuration object. Can
* contain:
* {
* nodes {number}: number of replica members. Defaults to 3.
* protocolVersion {number}: protocol version of replset used by the
* replset initiation.
* For other options, @see ReplSetTest#initiate
* }
*
* shards {number|Object|Array.<Object>}: number of shards or shard
* configuration object(s)(*). @see MongoRunner.runMongod
*
* config {number|Object|Array.<Object>}: number of config server or
* config server configuration object(s)(*). @see MongoRunner.runMongod
*
* (*) There are two ways For multiple configuration objects.
* (1) Using the object format. Example:
*
* { d0: { verbose: 5 }, d1: { auth: '' }, rs2: { oplogsize: 10 }}
*
* In this format, d = mongod, s = mongos & c = config servers
*
* (2) Using the array format. Example:
*
* [{ verbose: 5 }, { auth: '' }]
*
* Note: you can only have single server shards for array format.
*
* Note: A special "bridgeOptions" property can be specified in both the object and array
* formats to configure the options for the mongobridge corresponding to that node. These
* options are merged with the params.bridgeOptions options, where the node-specific
* options take precedence.
*
* other: {
* rs: same as above
* chunkSize: same as above
* keyFile {string}: the location of the keyFile
*
* shardOptions {Object}: same as the shards property above.
* Can be used to specify options that are common all shards.
*
* configOptions {Object}: same as the config property above.
* Can be used to specify options that are common all config servers.
* mongosOptions {Object}: same as the mongos property above.
* Can be used to specify options that are common all mongos.
* enableBalancer {boolean} : if true, enable the balancer
* enableBalancer setting
* manualAddShard {boolean}: shards will not be added if true.
*
* migrationLockAcquisitionMaxWaitMS {number}: number of milliseconds to acquire the migration
* lock.
*
* useBridge {boolean}: If true, then a mongobridge process is started for each node in the
* sharded cluster. Defaults to false.
*
* causallyConsistent {boolean}: Specifies whether the connections to the replica set nodes
* should be created with the 'causal consistency' flag enabled, which means they will
* gossip the cluster time and add readConcern afterClusterTime where applicable.
* Defaults to false.
*
* bridgeOptions {Object}: Options to apply to all mongobridge processes. Defaults to {}.
*
* // replica Set only:
* rsOptions {Object}: same as the rs property above. Can be used to
* specify options that are common all replica members.
* useHostname {boolean}: if true, use hostname of machine,
* otherwise use localhost
* numReplicas {number}
*
* configShard {boolean}: Add the config server as a shard if true.
* useAutoBootstrapProcedure {boolean}: Use the auto-bootstrapping procedure on every shard
* and config server if set to true.
* }
* }
*
* Member variables:
* s {Mongo} - connection to the first mongos
* s0, s1, ... {Mongo} - connection to different mongos
* rs0, rs1, ... {ReplSetTest} - test objects to replica sets
* shard0, shard1, ... {Mongo} - connection to shards
* config0, config1, ... {Mongo} - connection to config servers
* c0, c1, ... {Mongo} - same as config0, config1, ...
* configRS - the config ReplSetTest object
*/
var ShardingTest = function ShardingTest(params) {
if (!(this instanceof ShardingTest)) {
return new ShardingTest(params);
}
// Used for counting the test duration
this._startTime = new Date();
// Timeout to be used for operations scheduled by the sharding test, which must wait for write
// concern (5 minutes)
const kDefaultWTimeoutMs = 5 * 60 * 1000;
// Ensure we don't mutate the passed-in parameters.
params = Object.extend({}, params, true);
// Publicly exposed variables
/**
* Tries to load the 'jstests/libs/legacyThreadSupport.js' dependency. Returns true if the file
* is loaded successfully, and false otherwise.
*/
function tryLoadParallelTester() {
if (typeof globalThis.Thread !== 'undefined') {
return true;
}
try {
/* eslint-disable-next-line no-restricted-syntax */
load("jstests/libs/legacyThreadSupport.js"); // For Thread.
return true;
} catch (e) {
return false;
}
}
/**
* Constructs a human-readable string representing a chunk's range.
*/
function _rangeToString(r) {
return tojsononeline(r.min) + " -> " + tojsononeline(r.max);
}
/**
* Extends the ShardingTest class with the methods exposed by the sh utility class.
*/
function _extendWithShMethods(st) {
Object.keys(sh).forEach(function(fn) {
if (typeof sh[fn] !== 'function') {
return;
}
assert.eq(undefined,
st[fn],
'ShardingTest contains a method ' + fn +
' which duplicates a method with the same name on sh. ' +
'Please select a different function name.');
st[fn] = function() {
const oldDb = globalThis.db;
globalThis.db = st.getDB('test');
try {
return sh[fn].apply(sh, arguments);
} finally {
globalThis.db = oldDb;
}
};
});
}
/**
* Configures the cluster based on the specified parameters (balancer state, etc).
*/
function _configureCluster(st) {
if (!st._otherParams.enableBalancer) {
st.stopBalancer();
}
}
function connectionURLTheSame(a, b) {
if (a == b)
return true;
if (!a || !b)
return false;
if (a.host)
return connectionURLTheSame(a.host, b);
if (b.host)
return connectionURLTheSame(a, b.host);
if (a.name)
return connectionURLTheSame(a.name, b);
if (b.name)
return connectionURLTheSame(a, b.name);
if (a.indexOf("/") < 0 && b.indexOf("/") < 0) {
a = a.split(":");
b = b.split(":");
if (a.length != b.length)
return false;
if (a.length == 2 && a[1] != b[1])
return false;
if (a[0] == "localhost" || a[0] == "127.0.0.1")
a[0] = getHostName();
if (b[0] == "localhost" || b[0] == "127.0.0.1")
b[0] = getHostName();
return a[0] == b[0];
} else {
var a0 = a.split("/")[0];
var b0 = b.split("/")[0];
return a0 == b0;
}
}
assert(connectionURLTheSame("foo", "foo"));
assert(!connectionURLTheSame("foo", "bar"));
assert(connectionURLTheSame("foo/a,b", "foo/b,a"));
assert(!connectionURLTheSame("foo/a,b", "bar/a,b"));
// ShardingTest API
ShardingTest.prototype.getDB = function(name) {
return this.s.getDB(name);
};
/**
* Finds the _id of the primary shard for database 'dbname', e.g., 'test-rs0'
*/
ShardingTest.prototype.getPrimaryShardIdForDatabase = function(dbname) {
var x = this.config.databases.findOne({_id: "" + dbname});
if (x) {
return x.primary;
}
var countDBsFound = 0;
this.config.databases.find().forEach(function(db) {
countDBsFound++;
printjson(db);
});
throw Error("couldn't find dbname: " + dbname +
" in config.databases. Total DBs: " + countDBsFound);
};
ShardingTest.prototype.getNonPrimaries = function(dbname) {
var x = this.config.databases.findOne({_id: dbname});
if (!x) {
this.config.databases.find().forEach(printjson);
throw Error("couldn't find dbname: " + dbname +
" total: " + this.config.databases.count());
}
return this.config.shards.find({_id: {$ne: x.primary}}).map(z => z._id);
};
ShardingTest.prototype.getConnNames = function() {
var names = [];
for (var i = 0; i < this._connections.length; i++) {
names.push(this._connections[i].name);
}
return names;
};
/**
* Find the connection to the primary shard for database 'dbname'.
*/
ShardingTest.prototype.getPrimaryShard = function(dbname) {
var dbPrimaryShardId = this.getPrimaryShardIdForDatabase(dbname);
var primaryShard = this.config.shards.findOne({_id: dbPrimaryShardId});
if (primaryShard) {
const shardConnectionString = primaryShard.host;
var rsName = shardConnectionString.substring(0, shardConnectionString.indexOf("/"));
for (var i = 0; i < this._connections.length; i++) {
var c = this._connections[i];
if (connectionURLTheSame(shardConnectionString, c.name) ||
connectionURLTheSame(rsName, c.name))
return c;
}
}
throw Error("can't find server connection for db '" + dbname +
"'s primary shard: " + tojson(primaryShard));
};
ShardingTest.prototype.normalize = function(x) {
var z = this.config.shards.findOne({host: x});
if (z)
return z._id;
return x;
};
/**
* Find a different shard connection than the one given.
*/
ShardingTest.prototype.getOther = function(one) {
if (this._connections.length < 2) {
throw Error("getOther only works with 2 shards");
}
if (one._mongo) {
one = one._mongo;
}
for (var i = 0; i < this._connections.length; i++) {
if (this._connections[i] != one) {
return this._connections[i];
}
}
return null;
};
ShardingTest.prototype.getAnother = function(one) {
if (this._connections.length < 2) {
throw Error("getAnother() only works with multiple servers");
}
if (one._mongo) {
one = one._mongo;
}
for (var i = 0; i < this._connections.length; i++) {
if (this._connections[i] == one)
return this._connections[(i + 1) % this._connections.length];
}
};
ShardingTest.prototype.stopAllConfigServers = function(opts, forRestart = undefined) {
this.configRS.stopSet(undefined, forRestart, opts);
};
/**
* Returns boolean for whether the sharding test is compatible to shutdown in parallel.
*/
function isShutdownParallelSupported(st, opts = {}) {
if (!tryLoadParallelTester()) {
return false;
}
if (st._useBridge) {
// Keep the current behavior of shutting down each replica set shard and the
// CSRS individually when otherParams.useBridge === true. There appear to only
// be 8 instances of {useBridge: true} with ShardingTest and the implementation
// complexity is too high
return false;
}
if (st._otherParams.configOptions &&
st._otherParams.configOptions.clusterAuthMode === "x509") {
// The mongo shell performing X.509 authentication as a cluster member requires
// starting a parallel shell and using the server's (not the client's)
// certificate. The ReplSetTest instance constructed in a Thread wouldn't have
// copied the path to the server's certificate. We therefore fall back to
// initiating the CSRS and replica set shards sequentially when X.509
// authentication is being used.
return false;
}
if (st._otherParams.configOptions &&
st._otherParams.configOptions.tlsMode === "preferTLS") {
return false;
}
if (st._otherParams.configOptions &&
st._otherParams.configOptions.sslMode === "requireSSL") {
return false;
}
if (opts.parallelSupported !== undefined && opts.parallelSupported === false) {
// The test has chosen to opt out of parallel shutdown
return false;
}
return true;
}
/**
* Returns the replica sets args for sets that are to be terminated in parallel threads.
*/
function replicaSetsToTerminate(st, shardRS) {
const replicaSetsToTerminate = [];
[...(shardRS.map(obj => obj.test))].forEach(rst => {
// Generating a list of live nodes in the replica set
const liveNodes = [];
const pidValues = [];
rst.nodes.forEach(function(node) {
try {
node.getDB('admin')._helloOrLegacyHello();
liveNodes.push(node);
} catch (err) {
// Ignore since the node is not live
print("ShardingTest replicaSetsToTerminate ignoring: " + node.host);
return;
}
if (!node.pid) {
// Getting the pid for the node
let serverStatus;
rst.keyFile = rst.keyFile ? rst.keyFile : this.keyFile;
if (rst.keyFile) {
serverStatus = authutil.asCluster(node, rst.keyFile, () => {
return node.getDB("admin").serverStatus();
});
} else {
serverStatus = node.getDB("admin").serverStatus();
}
if (serverStatus["pid"]) {
node.pid = serverStatus["pid"];
} else {
// Shutdown requires PID values for every node. The case we are
// unable to obtain a PID value is rare, however, should it
// occur, the code will throw this error.
throw 'Could not obtain node PID value. Shutdown failed.';
}
}
pidValues.push(node.pid.valueOf());
});
if (pidValues.length > 0) {
// the number of livenodes must match the number of pidvalues being passed in
// rst.Args to ensure the replica set is constructed correctly
assert(liveNodes.length == pidValues.length);
replicaSetsToTerminate.push({
// Arguments for each replica set within parallel threads.
rstArgs: {
name: rst.name,
nodeHosts: liveNodes.map(node => `${node.host}`),
nodeOptions: rst.nodeOptions,
// Mixed-mode SSL tests may specify a keyFile per replica set rather
// than one for the whole cluster.
keyFile: rst.keyFile ? rst.keyFile : this.keyFile,
host: st._otherParams.useHostname ? hostName : "localhost",
waitForKeys: false,
pidValue: pidValues
},
});
}
});
return replicaSetsToTerminate;
}
ShardingTest.prototype.stopAllShards = function(opts = {}, forRestart = undefined) {
if (isShutdownParallelSupported(this, opts)) {
const threads = [];
try {
for (let {rstArgs} of replicaSetsToTerminate(this, this._rs)) {
const thread = new Thread((rstArgs, signal, forRestart, opts) => {
try {
const rst = new ReplSetTest({rstArgs});
rst.stopSet(signal, forRestart, opts);
return {ok: 1};
} catch (e) {
return {
ok: 0,
hosts: rstArgs.nodeHosts,
name: rstArgs.name,
error: e.toString(),
stack: e.stack,
};
}
}, rstArgs, 15, forRestart, opts);
thread.start();
threads.push(thread);
}
} finally {
// Wait for each thread to finish. Throw an error if any thread fails.
const returnData = threads.map(thread => {
thread.join();
return thread.returnData();
});
returnData.forEach(res => {
assert.commandWorked(res,
'terminating shard or config server replica sets failed');
});
}
} else {
// The replica sets shutting down serially
this._rs.forEach((rs) => {
rs.test.stopSet(15, forRestart, opts);
});
}
};
ShardingTest.prototype.stopAllMongos = function(opts) {
for (var i = 0; i < this._mongos.length; i++) {
this.stopMongos(i, opts);
}
};
ShardingTest.prototype.stop = function(opts = {}) {
this.checkMetadataConsistency();
this.checkUUIDsConsistentAcrossCluster();
this.checkIndexesConsistentAcrossCluster();
this.checkOrphansAreDeleted();
this.checkRoutingTableConsistency();
this.checkShardFilteringMetadata();
if (jsTestOptions().alwaysUseLogFiles) {
if (opts.noCleanData === false) {
throw new Error("Always using log files, but received conflicting option.");
}
opts.noCleanData = true;
}
this.stopAllMongos(opts);
let startTime = new Date(); // Measure the execution time of shutting down shards.
this.stopAllShards(opts);
print("ShardingTest stopped all shards, took " + (new Date() - startTime) + "ms for " +
this._connections.length + " shards.");
if (!isConfigShardMode) {
this.stopAllConfigServers(opts);
}
var timeMillis = new Date().getTime() - this._startTime.getTime();
print('*** ShardingTest ' + this._testName + " completed successfully in " +
(timeMillis / 1000) + " seconds ***");
};
ShardingTest.prototype.stopOnFail = function() {
try {
this.stopAllMongos();
} catch (e) {
print("Did not successfully stop all mongos.");
}
try {
this.stopAllShards();
} catch (e) {
print("Did not successfully stop all shards.");
}
try {
this.stopAllConfigServers();
} catch (e) {
print("Did not successfully stop all config servers.");
}
};
ShardingTest.prototype.adminCommand = function(cmd) {
var res = this.admin.runCommand(cmd);
if (res && res.ok == 1)
return true;
throw _getErrorWithCode(res, "command " + tojson(cmd) + " failed: " + tojson(res));
};
ShardingTest.prototype.restartAllConfigServers = function(opts) {
this.configRS.startSet(opts, true);
};
ShardingTest.prototype.restartAllShards = function(opts) {
this._rs.forEach((rs) => {
rs.test.startSet(opts, true);
});
};
ShardingTest.prototype.restartAllMongos = function(opts) {
for (var i = 0; i < this._mongos.length; i++) {
this.restartMongos(i, opts);
}
};
ShardingTest.prototype.forEachConnection = function(fn) {
this._connections.forEach(function(conn) {
fn(conn);
});
};
ShardingTest.prototype.forEachMongos = function(fn) {
this._mongos.forEach(function(conn) {
fn(conn);
});
};
ShardingTest.prototype.forEachConfigServer = function(fn) {
this.configRS.nodes.forEach(function(conn) {
fn(conn);
});
};
ShardingTest.prototype.printChangeLog = function() {
this.config.changelog.find().forEach(function(z) {
var msg = z.server + "\t" + z.time + "\t" + z.what;
for (var i = z.what.length; i < 15; i++)
msg += " ";
msg += " " + z.ns + "\t";
if (z.what == "split") {
msg += _rangeToString(z.details.before) + " -->> (" +
_rangeToString(z.details.left) + "), (" + _rangeToString(z.details.right) + ")";
} else if (z.what == "multi-split") {
msg += _rangeToString(z.details.before) + " -->> (" + z.details.number + "/" +
z.details.of + " " + _rangeToString(z.details.chunk) + ")";
} else {
msg += tojsononeline(z.details);
}
print("ShardingTest " + msg);
});
};
ShardingTest.prototype.getChunksString = function(ns) {
if (ns) {
let query = {};
let sorting_criteria = {};
const collection = this.config.collections.findOne({_id: ns});
if (!collection) {
return "";
}
if (collection.timestamp) {
const collectionUUID = collection.uuid;
assert.neq(collectionUUID, null);
query.uuid = collectionUUID;
sorting_criteria = {uuid: 1, min: 1};
} else {
query.ns = ns;
sorting_criteria = {ns: 1, min: 1};
}
let s = "";
this.config.chunks.find(query).sort(sorting_criteria).forEach(function(z) {
s += " \t" + z._id + "\t" + z.lastmod.t + "|" + z.lastmod.i + "\t" + tojson(z.min) +
" -> " + tojson(z.max) + " " + z.shard + " " + ns + "\n";
});
return s;
} else {
// call get chunks String for every namespace in the collections
let collections_cursor = this.config.collections.find();
let s = "";
while (collections_cursor.hasNext()) {
var ns = collections_cursor.next()._id;
s += this.getChunksString(ns);
}
return s;
}
};
ShardingTest.prototype.printChunks = function(ns) {
print("ShardingTest " + this.getChunksString(ns));
};
ShardingTest.prototype.printShardingStatus = function(verbose) {
printShardingStatus(this.config, verbose);
};
ShardingTest.prototype.printCollectionInfo = function(ns, msg) {
var out = "";
if (msg) {
out += msg + "\n";
}
out += "sharding collection info: " + ns + "\n";
for (var i = 0; i < this._connections.length; i++) {
var c = this._connections[i];
out += " mongod " + c + " " +
tojson(c.getCollection(ns).getShardVersion(), " ", true) + "\n";
}
for (var i = 0; i < this._mongos.length; i++) {
var c = this._mongos[i];
out += " mongos " + c + " " +
tojson(c.getCollection(ns).getShardVersion(), " ", true) + "\n";
}
out += this.getChunksString(ns);
print("ShardingTest " + out);
};
/**
* Returns the number of shards which contain the given dbName.collName collection
*/
ShardingTest.prototype.onNumShards = function(dbName, collName) {
return this.shardCounts(dbName, collName)
.reduce((total, currentValue) => total + (currentValue > 0 ? 1 : 0), 0);
};
/**
* Returns an array of the size of numShards where each element is the number of documents on
* that particular shard
*/
ShardingTest.prototype.shardCounts = function(dbName, collName) {
return this._connections.map((connection) =>
connection.getDB(dbName).getCollection(collName).count());
};
ShardingTest.prototype.chunkCounts = function(collName, dbName) {
dbName = dbName || "test";
var x = {};
this.config.shards.find().forEach(function(z) {
x[z._id] = 0;
});
var coll = this.config.collections.findOne({_id: dbName + "." + collName});
var chunksQuery = (function() {
if (coll.timestamp != null) {
return {uuid: coll.uuid};
} else {
return {ns: dbName + "." + collName};
}
}());
this.config.chunks.find(chunksQuery).forEach(function(z) {
if (x[z.shard])
x[z.shard]++;
else
x[z.shard] = 1;
});
return x;
};
ShardingTest.prototype.chunkDiff = function(collName, dbName) {
var c = this.chunkCounts(collName, dbName);
var min = Number.MAX_VALUE;
var max = 0;
for (var s in c) {
if (c[s] < min)
min = c[s];
if (c[s] > max)
max = c[s];
}
print("ShardingTest input: " + tojson(c) + " min: " + min + " max: " + max);
return max - min;
};
/**
* Waits up to the specified timeout (with a default of 60s) for the collection to be
* considered well balanced.
**/
ShardingTest.prototype.awaitBalance = function(collName, dbName, timeToWait, interval) {
const coll = this.s.getCollection(dbName + "." + collName);
this.awaitCollectionBalance(coll, timeToWait, interval);
};
ShardingTest.prototype.getShard = function(coll, query, includeEmpty) {
var shards = this.getShardsForQuery(coll, query, includeEmpty);
assert.eq(shards.length, 1);
return shards[0];
};
/**
* Returns the shards on which documents matching a particular query reside.
*/
ShardingTest.prototype.getShardsForQuery = function(coll, query, includeEmpty) {
if (!coll.getDB) {
coll = this.s.getCollection(coll);
}
var explain = coll.find(query).explain("executionStats");
var shards = [];
var execStages = explain.executionStats.executionStages;
var plannerShards = explain.queryPlanner.winningPlan.shards;
if (execStages.shards) {
for (var i = 0; i < execStages.shards.length; i++) {
var hasResults = execStages.shards[i].executionStages.nReturned &&
execStages.shards[i].executionStages.nReturned > 0;
if (includeEmpty || hasResults) {
shards.push(plannerShards[i].connectionString);
}
}
}
for (var i = 0; i < shards.length; i++) {
for (var j = 0; j < this._connections.length; j++) {
if (connectionURLTheSame(this._connections[j], shards[i])) {
shards[i] = this._connections[j];
break;
}
}
}
return shards;
};
ShardingTest.prototype.shardColl = function(collName, key, split, move, dbName, waitForDelete) {
split = (split != false ? (split || key) : split);
move = (split != false && move != false ? (move || split) : false);
if (collName.getDB)
dbName = "" + collName.getDB();
else
dbName = dbName || "test";
var c = dbName + "." + collName;
if (collName.getDB) {
c = "" + collName;
}
assert.commandWorked(this.s.adminCommand({enableSharding: dbName}));
var result = assert.commandWorked(this.s.adminCommand({shardcollection: c, key: key}));
if (split == false) {
return;
}
result = assert.commandWorked(this.s.adminCommand({split: c, middle: split}));
if (move == false) {
return;
}
for (var i = 0; i < 5; i++) {
var otherShard = this.getOther(this.getPrimaryShard(dbName)).name;
let cmd = {movechunk: c, find: move, to: otherShard};
if (waitForDelete != null) {
cmd._waitForDelete = waitForDelete;
}
const result = this.s.adminCommand(cmd);
if (result.ok)
break;
sleep(5 * 1000);
}
assert.commandWorked(result);
};
/**
* Wait for sharding to be initialized.
*/
ShardingTest.prototype.waitForShardingInitialized = function(timeoutMs = 60 * 1000) {
const getShardVersion = (client, timeout) => {
assert.soon(() => {
// The choice of namespace (local.fooCollection) does not affect the output.
var res = client.adminCommand({getShardVersion: "local.fooCollection"});
return res.ok == 1;
}, "timeout waiting for sharding to be initialized on mongod", timeout, 0.1);
};
var start = new Date();
for (var i = 0; i < this._rs.length; ++i) {
var replSet = this._rs[i];
if (!replSet)
continue;
const nodes = replSet.test.nodes;
const keyFileUsed = replSet.test.keyFile;
for (var j = 0; j < nodes.length; ++j) {
const diff = (new Date()).getTime() - start.getTime();
var currNode = nodes[j];
// Skip arbiters
if (currNode.getDB('admin')._helloOrLegacyHello().arbiterOnly) {
continue;
}
const tlsOptions = ['preferTLS', 'requireTLS'];
const sslOptions = ['preferSSL', 'requireSSL'];
const TLSEnabled = currNode.fullOptions &&
(tlsOptions.includes(currNode.fullOptions.tlsMode) ||
sslOptions.includes(currNode.fullOptions.sslMode));
const x509AuthRequired = (conn.fullOptions && conn.fullOptions.clusterAuthMode &&
conn.fullOptions.clusterAuthMode === "x509");
if (keyFileUsed) {
authutil.asCluster(currNode, keyFileUsed, () => {
getShardVersion(currNode, timeoutMs - diff);
});
} else if (x509AuthRequired && TLSEnabled) {
const exitCode = _runMongoProgram(
...["mongo",
currNode.host,
"--tls",
"--tlsAllowInvalidHostnames",
"--tlsCertificateKeyFile",
currNode.fullOptions.tlsCertificateKeyFile
? currNode.fullOptions.tlsCertificateKeyFile
: currNode.fullOptions.sslPEMKeyFile,
"--tlsCAFile",
currNode.fullOptions.tlsCAFile ? currNode.fullOptions.tlsCAFile
: currNode.fullOptions.sslCAFile,
"--authenticationDatabase=$external",
"--authenticationMechanism=MONGODB-X509",
"--eval",
`(${getShardVersion.toString()})(db.getMongo(), ` +
(timeoutMs - diff).toString() + `)`,
]);
assert.eq(0, exitCode, "parallel shell for x509 auth failed");
} else {
getShardVersion(currNode, timeoutMs - diff);
}
}
}
};
/**
* Kills the mongos with index n.
*
* @param {boolean} [extraOptions.waitPid=true] if true, we will wait for the process to
* terminate after stopping it.
*/
ShardingTest.prototype.stopMongos = function(n, opts, {
waitpid: waitpid = true,
} = {}) {
if (this._useBridge) {
MongoRunner.stopMongos(this._unbridgedMongos[n], undefined, opts, waitpid);
this["s" + n].stop();
} else {
MongoRunner.stopMongos(this["s" + n], undefined, opts, waitpid);
}
};
/**
* Kills the config server mongod with index n.
*/
ShardingTest.prototype.stopConfigServer = function(n, opts) {
this.configRS.stop(n, undefined, opts);
};
/**
* Stops and restarts a mongos process.
*
* If 'opts' is not specified, starts the mongos with its previous parameters. If 'opts' is
* specified and 'opts.restart' is false or missing, starts mongos with the parameters specified
* in 'opts'. If opts is specified and 'opts.restart' is true, merges the previous options
* with the options specified in 'opts', with the options in 'opts' taking precedence.
*
* Warning: Overwrites the old s (if n = 0) admin, config, and sn member variables.
*/
ShardingTest.prototype.restartMongos = function(n, opts) {
var mongos;
if (this._useBridge) {
mongos = this._unbridgedMongos[n];
} else {
mongos = this["s" + n];
}
opts = opts || mongos;
opts.port = opts.port || mongos.port;
this.stopMongos(n);
if (this._useBridge) {
var bridgeOptions =
(opts !== mongos) ? opts.bridgeOptions : mongos.fullOptions.bridgeOptions;
bridgeOptions = Object.merge(this._otherParams.bridgeOptions, bridgeOptions || {});
bridgeOptions = Object.merge(bridgeOptions, {
hostName: this._otherParams.useHostname ? hostName : "localhost",
port: this._mongos[n].port,
// The mongos processes identify themselves to mongobridge as host:port, where the
// host is the actual hostname of the machine and not localhost.
dest: hostName + ":" + opts.port,
});
this._mongos[n] = new MongoBridge(bridgeOptions);
}
if (opts.restart) {
opts = Object.merge(mongos.fullOptions, opts);
}
var newConn = MongoRunner.runMongos(opts);
if (!newConn) {
throw new Error("Failed to restart mongos " + n);
}
if (this._useBridge) {
this._mongos[n].connectToBridge();
this._unbridgedMongos[n] = newConn;
} else {
this._mongos[n] = newConn;
}
this['s' + n] = this._mongos[n];
if (n == 0) {
this.s = this._mongos[n];
this.admin = this._mongos[n].getDB('admin');
this.config = this._mongos[n].getDB('config');
}
};