-
Notifications
You must be signed in to change notification settings - Fork 380
Expand file tree
/
Copy pathshardingtest-8.1.js
More file actions
2387 lines (2044 loc) · 94.7 KB
/
shardingtest-8.1.js
File metadata and controls
2387 lines (2044 loc) · 94.7 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
/* Changes to shardingtest.js copied over from 10gen/mongo repo at commit
* 6d7a9ba952ab4a8428d83699ba26314efe55506c.
* 1. Comment out import of FeatureFlagUtil and its single use case
* 2. Change import paths throughout file to correct location in shell_common/libs directory,
* assuming we're running the shell from test/qa-tests or test/legacy42
* 3. When setting maxTransactionLockRequestTimeoutMillis, don't initialize jsTest.options().setParameters because that will get reset every time
* jsTest.options() is called. jsTest.options() is based on TestData, so initialize that instead.
*/
//import {FeatureFlagUtil} from "jstests/libs/feature_flag_util.js";
import {Thread} from "../shell_common/libs/parallelTester-8.1.js";
import {ReplSetTest} from "../shell_common/libs/replsettest-8.1.js";
// Symbol used to override the constructor. Please do not use this, it's only meant to aid
// in migrating the jstest corpus to proper module usage.
export const kOverrideConstructor = Symbol('overrideConstructor');
// Timeout to be used for operations scheduled by the sharding test, which must wait for write
// concern (5 minutes)
const kDefaultWTimeoutMs = 5 * 60 * 1000;
// Oplog collection name
const kOplogName = 'oplog.rs';
export class ShardingTest {
// ShardingTest API
getDB(name) {
return this.s.getDB(name);
}
/**
* Finds the _id of the primary shard for database 'dbname', e.g., 'test-rs0'
*/
getPrimaryShardIdForDatabase(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++;
jsTest.log.info({db});
});
throw Error("couldn't find dbname: " + dbname +
" in config.databases. Total DBs: " + countDBsFound);
}
getNonPrimaries(dbname) {
var x = this.config.databases.findOne({_id: dbname});
if (!x) {
this.config.databases.find().forEach(jsTest.log.info);
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);
}
printNodes() {
jsTest.log.info("ShardingTest " + this._testName,
{config: this._configDB, shards: this._connections, mongos: this._mongos});
}
getConnNames() {
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'.
*/
getPrimaryShard(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));
}
// TODO SERVER-95358 remove once 9.0 becomes last LTS.
getMergeType(db) {
// if (FeatureFlagUtil.isPresentAndEnabled(db, "AggMongosToRouter")) {
// return "router";
// }
return "mongos";
}
normalize(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.
*/
getOther(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;
}
getAnother(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];
}
}
stopAllConfigServers(opts, forRestart = undefined) {
this.configRS.stopSet(undefined, forRestart, opts);
}
stopAllShards(opts = {}, forRestart = undefined) {
if (isShutdownParallelSupported(this, opts)) {
const threads = [];
try {
for (let {rstArgs} of replicaSetsToTerminate(this, this._rs)) {
const thread = new Thread(async (rstArgs, signal, forRestart, opts) => {
const {ReplSetTest} = await import("../shell_common/libs/replsettest-8.1.js");
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);
});
}
}
stopAllMongos(opts) {
for (var i = 0; i < this._mongos.length; i++) {
this.stopMongos(i, opts);
}
}
awaitMigrations() {
this.stopBalancer();
const numShards = this._rs.length;
for (let i = 0; i < numShards; i++) {
assert.commandWorked(this["shard" + i].adminCommand({"_shardsvrJoinMigrations": 1}));
}
}
isReplicaSetEndpointActive() {
const numShards = this._rs.length;
return numShards == 1 && this._rs[0].test.isReplicaSetEndpointActive();
}
stop(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);
if (jsTestOptions().runningWithConfigStepdowns && this.isConfigShardMode) {
// In case of a cluster with a config shard, the config server replica set is stopped
// via stopAllShards, which doesn't stop the continuous stepdown stop.
this.configRS.stopContinuousFailover();
}
let startTime = new Date(); // Measure the execution time of shutting down shards.
this.stopAllShards(opts);
jsTest.log.info("ShardingTest stopped all shards, took " + (new Date() - startTime) +
"ms for " + this._connections.length + " shards.");
if (!this.isConfigShardMode) {
this.stopAllConfigServers(opts);
}
var timeMillis = new Date().getTime() - this._startTime.getTime();
jsTest.log.info('*** ShardingTest ' + this._testName + " completed successfully in " +
(timeMillis / 1000) + " seconds ***");
}
stopOnFail() {
try {
this.stopAllMongos();
} catch (e) {
jsTest.log.info("Did not successfully stop all mongos.");
}
try {
this.stopAllShards();
} catch (e) {
jsTest.log.info("Did not successfully stop all shards.");
}
try {
this.stopAllConfigServers();
} catch (e) {
jsTest.log.info("Did not successfully stop all config servers.");
}
}
adminCommand(cmd) {
var res = this.admin.runCommand(cmd);
if (res && res.ok == 1)
return true;
throw _getErrorWithCode(res, "command " + tojson(cmd) + " failed: " + tojson(res));
}
restartAllConfigServers(opts) {
this.configRS.startSet(opts, true);
this.configRS.nodes.forEach((node) => {
// node.routerPort is undefined if this node doesn't expose an embedded router, so this
// loop only applies for embedded routers.
const routerN = this._findRouterByPort(node.routerPort);
if (routerN !== undefined) {
this.reconnectToEmbeddedRouter(routerN);
}
});
// We wait until a primary has been chosen since startSet can return without having elected
// one. This can cause issues that expect a functioning replicaset once this method returns.
this.configRS.waitForPrimary();
}
restartAllShards(opts) {
this._rs.forEach((rs) => {
rs.test.startSet(opts, true);
rs.test.nodes.forEach((node) => {
// node.routerPort is undefined if this node doesn't expose an embedded router, so
// this loop only applies for embedded routers.
const routerN = this._findRouterByPort(node.routerPort);
if (routerN !== undefined) {
this.reconnectToEmbeddedRouter(routerN);
}
});
// We wait until a primary has been chosen since startSet can return without having
// elected one. This can cause issues that expect a functioning replicaset once this
// method returns.
rs.test.waitForPrimary();
});
}
restartAllMongos(opts) {
for (var i = 0; i < this._mongos.length; i++) {
this.restartMongos(i, opts);
}
}
forEachConnection(fn) {
this._connections.forEach(function(conn) {
fn(conn);
});
}
forEachMongos(fn) {
this._mongos.forEach(function(conn) {
fn(conn);
});
}
forEachConfigServer(fn) {
this.configRS.nodes.forEach(function(conn) {
fn(conn);
});
}
printChangeLog() {
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);
}
jsTest.log.info("ShardingTest " + msg);
});
}
getChunksString(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;
}
}
printChunks(ns) {
jsTest.log.info("ShardingTest " + this.getChunksString(ns));
}
printShardingStatus(verbose) {
printShardingStatus(this.config, verbose);
}
printCollectionInfo(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);
jsTest.log.info("ShardingTest " + out);
}
/**
* Returns the number of shards which contain the given dbName.collName collection
*/
onNumShards(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
*/
shardCounts(dbName, collName) {
return this._connections.map((connection) =>
connection.getDB(dbName).getCollection(collName).count());
}
chunkCounts(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;
}
chunkDiff(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];
}
jsTest.log.info("ShardingTest input", {chunkCounts: c, min, max});
return max - min;
}
/**
* Waits up to the specified timeout (with a default of 60s) for the collection to be
* considered well balanced.
**/
awaitBalance(collName, dbName, timeToWait, interval) {
const coll = this.s.getCollection(dbName + "." + collName);
this.awaitCollectionBalance(coll, timeToWait, interval);
}
getShard(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.
*/
getShardsForQuery(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;
}
shardColl(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.
*/
waitForShardingInitialized(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 =
(this.s.fullOptions && this.s.fullOptions.clusterAuthMode &&
this.s.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.
*/
stopMongos(n, opts, {
waitpid: waitpid = true,
} = {}) {
if (this._useBridge) {
MongoRunner.stopMongos(this._unbridgedMongos[n], undefined, opts, waitpid);
this["s" + n].stop();
} else {
let mongos = this["s" + n];
// this isn't a real mongos, it's the embedded router of a mongod. Don't do anything.
if (mongos.isEmbeddedRouter) {
return;
}
MongoRunner.stopMongos(mongos, undefined, opts, waitpid);
}
}
/**
* Kills the config server mongod with index n.
*/
stopConfigServer(n, opts) {
this.configRS.stop(n, undefined, opts);
}
/**
* Stops and restarts a mongos process. The operation fails if this connection is not against a
* mongos process (i.e. an embedded router).
*
* 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.
*
* 'stopOpts' are the options passed to the mongos when it is stopping.
*
* Warning: Overwrites the old s (if n = 0) admin, config, and sn member variables.
*/
restartMongos(n, opts, stopOpts) {
var mongos;
if (this._useBridge) {
mongos = this._unbridgedMongos[n];
} else {
mongos = this["s" + n];
}
assert(!mongos.isEmbeddedRouter,
"This mongos is an embedded router, it can't be restarted separately");
opts = opts || mongos;
opts.port = opts.port || mongos.port;
this.stopMongos(n, stopOpts);
if (this._useBridge) {
const hostName =
this._otherParams.host === undefined ? getHostName() : this._otherParams.host;
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');
}
}
/**
* Restarts a router node. The node can be either a standalone mongoS, or a mongoD with an
* embedded router. If the node is a mongoD with embedded router, this command will wait until
* the triggered election finishes. As a consequence, the primary of the affected RS could
* change.
*
* If 'opts' is not specified, starts the node with its previous parameters. If 'opts' is
* specified and 'opts.restart' is false or missing, starts the node 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.
*/
restartRouterNode(n, opts) {
const routerConn = (() => {
if (this._useBridge) {
return this._unbridgedMongos[n];
} else {
return this["s" + n];
}
})();
if (!routerConn.isEmbeddedRouter) {
this.restartMongos(n, opts);
return;
}
assert(!this._useBridge, "BUG: mongobridge and embedded router are not compatible");
const nodeInfo = routerConn.nodeInfo;
if (nodeInfo.isConfig) {
this.restartConfigServer(nodeInfo.index, opts);
} else {
nodeInfo.rs.restart(nodeInfo.index, opts);
}
this.reconnectToEmbeddedRouter(n);
// Wait for any election to succeed.
nodeInfo.rs.awaitNodesAgreeOnPrimary();
}
reconnectToEmbeddedRouter(n) {
const routerConn = (() => {
if (this._useBridge) {
return this._unbridgedMongos[n];
} else {
return this["s" + n];
}
})();
const nodeInfo = routerConn.nodeInfo;
const mongodConn = nodeInfo.rs.nodes[nodeInfo.index];
const newConn =
MongoRunner.awaitConnection({pid: mongodConn.pid, port: mongodConn.routerPort});
newConn.isEmbeddedRouter = true;
newConn.port = mongodConn.routerPort;
newConn.nodeInfo = nodeInfo;
newConn.fullOptions = mongodConn.fullOptions;
newConn.commandLine = mongodConn.commandLine;
newConn.name = routerConn.name;
newConn.host = routerConn.host;
this._mongos[n] = newConn;
this["s" + n] = newConn;
if (n == 0) {
this.s = this._mongos[n];
this.admin = this._mongos[n].getDB('admin');
this.config = this._mongos[n].getDB('config');
}
}
/** @private */
_findRouterByPort(port) {
if (port === undefined) {
return undefined;
}
for (let n = 0; n < this._mongos.length; n++) {
if (this._mongos[n].port == port) {
return n;
}
}
return undefined;
}
/**
* Shuts down and restarts replica set for a given shard and
* updates shard connection information.
*
* @param {string} prevShardName
* @param {object} replSet The replica set object. Defined in replsettest.js
*/
shutdownAndRestartPrimaryOnShard(shardName, replSet) {
const n = this._shardReplSetToIndex[replSet.name];
const originalPrimaryConn = replSet.getPrimary();
const SIGTERM = 15;
replSet.restart(originalPrimaryConn, {}, SIGTERM);
replSet.awaitNodesAgreeOnPrimary();
replSet.awaitSecondaryNodes();
this._connections[n] = new Mongo(replSet.getURL());
this._connections[n].shardName = shardName;
this._connections[n].rs = replSet;
this["shard" + n] = this._connections[n];
}
/**
* Kills and restarts replica set for a given shard and
* updates shard connection information.
*
* @param {string} prevShardName
* @param {object} replSet The replica set object. Defined in replsettest.js
*/
killAndRestartPrimaryOnShard(shardName, replSet) {
const n = this._shardReplSetToIndex[replSet.name];
const originalPrimaryConn = replSet.getPrimary();
const SIGKILL = 9;
const opts = {allowedExitCode: MongoRunner.EXIT_SIGKILL};
replSet.restart(originalPrimaryConn, opts, SIGKILL);
replSet.awaitNodesAgreeOnPrimary();
this._connections[n] = new Mongo(replSet.getURL());
this._connections[n].shardName = shardName;
this._connections[n].rs = replSet;
this["shard" + n] = this._connections[n];
}
/**
* Restarts each node in a particular shard replica set using the shard's original startup
* options by default.
*
* Option { startClean : true } forces clearing the data directory.
* Option { auth : Object } object that contains the auth details for admin credentials.
* Should contain the fields 'user' and 'pwd'
*
*
* @param {int} shard server number (0, 1, 2, ...) to be restarted
*/
restartShardRS(n, options, signal, wait) {
const prevShardName = this._connections[n].shardName;
for (let i = 0; i < this["rs" + n].nodeList().length; i++) {
this["rs" + n].restart(i);
}
this["rs" + n].awaitSecondaryNodes();
this._connections[n] = new Mongo(this["rs" + n].getURL(), undefined, {gRPC: false});
this._connections[n].shardName = prevShardName;
this._connections[n].rs = this["rs" + n];
this["shard" + n] = this._connections[n];
}
/**
* Stops and restarts a config server mongod process.
*
* If opts is specified, the new mongod is started using those options. Otherwise, it is
* started
* with its previous parameters.
*
* Warning: Overwrites the old cn/confign member variables.
*/
restartConfigServer(n, options, signal, wait) {
this.configRS.restart(n, options, signal, wait);
this["config" + n] = this.configRS.nodes[n];
this["c" + n] = this.configRS.nodes[n];
}
/**
* Returns a document {isMixedVersion: <bool>, oldestBinVersion: <string>}.
* The 'isMixedVersion' field is true if any settings to ShardingTest or jsTestOptions indicate
* this is a multiversion cluster.
* The 'oldestBinVersion' field is set to the oldest binary version used in this cluster, one of
* 'latest', 'last-continuous' and 'last-lts'.
* Note: Mixed version cluster with binary versions older than 'last-lts' is not supported. If
* such binary exists in the cluster, this function assumes this is not a mixed version cluster
* and returns 'oldestBinVersion' as 'latest'.
*
* Checks for bin versions via:
* jsTestOptions().mongosBinVersion,
* otherParams.configOptions.binVersion,
* otherParams.mongosOptions.binVersion
*/
getClusterVersionInfo() {
let hasLastLTS = clusterHasBinVersion(this, "last-lts");
let hasLastContinuous = clusterHasBinVersion(this, "last-continuous");
if ((lastLTSFCV !== lastContinuousFCV) && hasLastLTS && hasLastContinuous) {
throw new Error("Can only specify one of 'last-lts' and 'last-continuous' " +
"in binVersion, not both.");
}
if (hasLastLTS) {
return {isMixedVersion: true, oldestBinVersion: "last-lts"};
} else if (hasLastContinuous) {
return {isMixedVersion: true, oldestBinVersion: "last-continuous"};
} else {
return {isMixedVersion: false, oldestBinVersion: "latest"};
}
}
/**
* Runs a find on the namespace to force a refresh of the node's catalog cache.
*/
refreshCatalogCacheForNs(node, ns) {
node.getCollection(ns).findOne();
}
/**
* Waits for all operations to fully replicate on all shards.
*/
awaitReplicationOnShards() {
this._rs.forEach(replSet => replSet.test.awaitReplication());
}
/**
* Query the oplog from a given node.
*/
findOplog(conn, query, limit) {
return conn.getDB('local')
.getCollection(kOplogName)
.find(query)
.sort({$natural: -1})
.limit(limit);
}
/**
* Returns all nodes in the cluster including shards, config servers and mongoses.
*/
getAllNodes() {
let nodes = [];
nodes.concat([this._configDB, this._connections, this._mongos]);
return [...new Set(nodes)];
}
/**
* Returns all shards in the cluster.
*/
getAllShards() {
return this._rs.map(obj => obj.test);
}
/**