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
|
/**
* Copyright (C) 2018-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/platform/basic.h"
#include "mongo/client/remote_command_targeter_mock.h"
#include "mongo/db/catalog/create_collection.h"
#include "mongo/db/catalog_raii.h"
#include "mongo/db/dbdirectclient.h"
#include "mongo/db/logical_session_id_helpers.h"
#include "mongo/db/namespace_string.h"
#include "mongo/db/s/collection_sharding_runtime.h"
#include "mongo/db/s/migration_chunk_cloner_source_legacy.h"
#include "mongo/db/s/operation_sharding_state.h"
#include "mongo/db/s/shard_server_test_fixture.h"
#include "mongo/s/catalog/sharding_catalog_client_mock.h"
#include "mongo/s/catalog/type_shard.h"
#include "mongo/s/client/shard_registry.h"
#include "mongo/unittest/unittest.h"
#include "mongo/util/clock_source_mock.h"
namespace mongo {
namespace {
using executor::RemoteCommandRequest;
using unittest::assertGet;
const NamespaceString kNss("TestDB", "TestColl");
const std::string kShardKey = "X";
const BSONObj kShardKeyPattern{BSON(kShardKey << 1)};
const ConnectionString kConfigConnStr =
ConnectionString::forReplicaSet("Donor",
{HostAndPort("DonorHost1:1234"),
HostAndPort{"DonorHost2:1234"},
HostAndPort{"DonorHost3:1234"}});
const ConnectionString kDonorConnStr =
ConnectionString::forReplicaSet("Donor",
{HostAndPort("DonorHost1:1234"),
HostAndPort{"DonorHost2:1234"},
HostAndPort{"DonorHost3:1234"}});
const ConnectionString kRecipientConnStr =
ConnectionString::forReplicaSet("Recipient",
{HostAndPort("RecipientHost1:1234"),
HostAndPort("RecipientHost2:1234"),
HostAndPort("RecipientHost3:1234")});
class MigrationChunkClonerSourceLegacyTest : public ShardServerTestFixture {
protected:
void setUp() override {
ShardServerTestFixture::setUp();
// TODO: SERVER-26919 set the flag on the mock repl coordinator just for the window where it
// actually needs to bypass the op observer.
replicationCoordinator()->alwaysAllowWrites(true);
_client.emplace(operationContext());
{
auto donorShard = assertGet(
shardRegistry()->getShard(operationContext(), kDonorConnStr.getSetName()));
RemoteCommandTargeterMock::get(donorShard->getTargeter())
->setConnectionStringReturnValue(kDonorConnStr);
RemoteCommandTargeterMock::get(donorShard->getTargeter())
->setFindHostReturnValue(kDonorConnStr.getServers()[0]);
}
{
auto recipientShard = assertGet(
shardRegistry()->getShard(operationContext(), kRecipientConnStr.getSetName()));
RemoteCommandTargeterMock::get(recipientShard->getTargeter())
->setConnectionStringReturnValue(kRecipientConnStr);
RemoteCommandTargeterMock::get(recipientShard->getTargeter())
->setFindHostReturnValue(kRecipientConnStr.getServers()[0]);
}
auto clockSource = std::make_unique<ClockSourceMock>();
// Timestamps of "0 seconds" are not allowed, so we must advance our clock mock to the first
// real second.
clockSource->advance(Seconds(1));
operationContext()->getServiceContext()->setFastClockSource(std::move(clockSource));
_lsid = makeLogicalSessionId(operationContext());
}
void tearDown() override {
_client.reset();
ShardServerTestFixture::tearDown();
}
/**
* Returns the DBDirectClient instance to use for writes to the database.
*/
DBDirectClient* client() {
invariant(_client);
return _client.get_ptr();
}
/**
* Inserts the specified docs in 'kNss' and ensures the insert succeeded.
*/
void insertDocsInShardedCollection(const std::vector<BSONObj>& docs) {
if (docs.empty())
return;
auto response = client()->insertAcknowledged(kNss.ns(), docs);
ASSERT_OK(getStatusFromWriteCommandReply(response));
ASSERT_GT(response["n"].Int(), 0);
}
void deleteDocsInShardedCollection(BSONObj query) {
auto response = client()->removeAcknowledged(kNss.ns(), query);
ASSERT_OK(getStatusFromWriteCommandReply(response));
ASSERT_GT(response["n"].Int(), 0);
}
void updateDocsInShardedCollection(BSONObj query, BSONObj updated) {
auto response = client()->updateAcknowledged(kNss.ns(), query, updated);
ASSERT_OK(getStatusFromWriteCommandReply(response));
ASSERT_GT(response["n"].Int(), 0);
}
/**
* Creates a collection, which contains an index corresponding to kShardKeyPattern and insers
* the specified initial documents.
*/
void createShardedCollection(const std::vector<BSONObj>& initialDocs) {
{
OperationShardingState::ScopedAllowImplicitCollectionCreate_UNSAFE
unsafeCreateCollection(operationContext());
uassertStatusOK(createCollection(
operationContext(), kNss.db().toString(), BSON("create" << kNss.coll())));
}
const auto uuid = [&] {
AutoGetCollection autoColl(operationContext(), kNss, MODE_IX);
return autoColl.getCollection()->uuid();
}();
[&] {
const OID epoch = OID::gen();
auto rt = RoutingTableHistory::makeNew(
kNss,
uuid,
kShardKeyPattern,
nullptr,
false,
epoch,
boost::none /* timestamp */,
boost::none /* timeseriesFields */,
boost::none,
true,
{ChunkType{kNss,
ChunkRange{BSON(kShardKey << MINKEY), BSON(kShardKey << MAXKEY)},
ChunkVersion(1, 0, epoch, boost::none /* timestamp */),
ShardId("dummyShardId")}});
AutoGetDb autoDb(operationContext(), kNss.db(), MODE_IX);
Lock::CollectionLock collLock(operationContext(), kNss, MODE_IX);
CollectionShardingRuntime::get(operationContext(), kNss)
->setFilteringMetadata(
operationContext(),
CollectionMetadata(
ChunkManager(ShardId("dummyShardId"),
DatabaseVersion(UUID::gen()),
makeStandaloneRoutingTableHistory(std::move(rt)),
boost::none),
ShardId("dummyShardId")));
}();
client()->createIndex(kNss.ns(), kShardKeyPattern);
insertDocsInShardedCollection(initialDocs);
}
/**
* Shortcut to create BSON represenation of a moveChunk request for the specified range with
* fixed kDonorConnStr and kRecipientConnStr, respectively.
*/
static MoveChunkRequest createMoveChunkRequest(const ChunkRange& chunkRange) {
BSONObjBuilder cmdBuilder;
MoveChunkRequest::appendAsCommand(
&cmdBuilder,
kNss,
ChunkVersion(1, 0, OID::gen(), boost::none /* timestamp */),
kConfigConnStr,
kDonorConnStr.getSetName(),
kRecipientConnStr.getSetName(),
chunkRange,
1024 * 1024,
MigrationSecondaryThrottleOptions::create(MigrationSecondaryThrottleOptions::kDefault),
false,
MoveChunkRequest::ForceJumbo::kDoNotForce);
return assertGet(MoveChunkRequest::createFromCommand(kNss, cmdBuilder.obj()));
}
/**
* Instantiates a BSON object in which both "_id" and "X" are set to value.
*/
static BSONObj createCollectionDocument(int value) {
return BSON("_id" << value << "X" << value);
}
/**
* Instantiates a BSON object with different "_id" and "X" values.
*/
static BSONObj createCollectionDocumentForUpdate(int id, int value) {
return BSON("_id" << id << "X" << value);
}
/**
* Instantiates a BSON object with objsize close to size.
*/
static BSONObj createSizedCollectionDocument(int id, long long size) {
std::string value(size, 'x');
return BSON("_id" << id << "X" << id << "Y" << value);
}
protected:
LogicalSessionId _lsid;
TxnNumber _txnNumber{0};
private:
std::unique_ptr<ShardingCatalogClient> makeShardingCatalogClient() override {
class StaticCatalogClient final : public ShardingCatalogClientMock {
public:
StaticCatalogClient() = default;
StatusWith<repl::OpTimeWith<std::vector<ShardType>>> getAllShards(
OperationContext* opCtx, repl::ReadConcernLevel readConcern) override {
ShardType donorShard;
donorShard.setName(kDonorConnStr.getSetName());
donorShard.setHost(kDonorConnStr.toString());
ShardType recipientShard;
recipientShard.setName(kRecipientConnStr.getSetName());
recipientShard.setHost(kRecipientConnStr.toString());
return repl::OpTimeWith<std::vector<ShardType>>({donorShard, recipientShard});
}
};
return std::make_unique<StaticCatalogClient>();
}
boost::optional<DBDirectClient> _client;
};
TEST_F(MigrationChunkClonerSourceLegacyTest, CorrectDocumentsFetched) {
const std::vector<BSONObj> contents = {createCollectionDocument(99),
createCollectionDocument(100),
createCollectionDocument(199),
createCollectionDocument(200)};
createShardedCollection(contents);
MigrationChunkClonerSourceLegacy cloner(
createMoveChunkRequest(ChunkRange(BSON("X" << 100), BSON("X" << 200))),
kShardKeyPattern,
kDonorConnStr,
kRecipientConnStr.getServers()[0]);
{
auto futureStartClone = launchAsync([&]() {
onCommand([&](const RemoteCommandRequest& request) { return BSON("ok" << true); });
});
ASSERT_OK(cloner.startClone(operationContext(), UUID::gen(), _lsid, _txnNumber));
futureStartClone.default_timed_get();
}
// Ensure the initial clone documents are available
{
AutoGetCollection autoColl(operationContext(), kNss, MODE_IS);
{
BSONArrayBuilder arrBuilder;
ASSERT_OK(
cloner.nextCloneBatch(operationContext(), autoColl.getCollection(), &arrBuilder));
ASSERT_EQ(2, arrBuilder.arrSize());
const auto arr = arrBuilder.arr();
ASSERT_BSONOBJ_EQ(contents[1], arr[0].Obj());
ASSERT_BSONOBJ_EQ(contents[2], arr[1].Obj());
}
{
BSONArrayBuilder arrBuilder;
ASSERT_OK(
cloner.nextCloneBatch(operationContext(), autoColl.getCollection(), &arrBuilder));
ASSERT_EQ(0, arrBuilder.arrSize());
}
}
// Insert some documents in the chunk range to be included for migration
insertDocsInShardedCollection({createCollectionDocument(150)});
insertDocsInShardedCollection({createCollectionDocument(151)});
// Insert some documents which are outside of the chunk range and should not be included for
// migration
insertDocsInShardedCollection({createCollectionDocument(90)});
insertDocsInShardedCollection({createCollectionDocument(210)});
// Normally the insert above and the onInsert/onDelete callbacks below will happen under the
// same lock and write unit of work
{
AutoGetCollection autoColl(operationContext(), kNss, MODE_IX);
WriteUnitOfWork wuow(operationContext());
cloner.onInsertOp(operationContext(), createCollectionDocument(90), {});
cloner.onInsertOp(operationContext(), createCollectionDocument(150), {});
cloner.onInsertOp(operationContext(), createCollectionDocument(151), {});
cloner.onInsertOp(operationContext(), createCollectionDocument(210), {});
cloner.onDeleteOp(operationContext(), createCollectionDocument(80), {}, {});
cloner.onDeleteOp(operationContext(), createCollectionDocument(199), {}, {});
cloner.onDeleteOp(operationContext(), createCollectionDocument(220), {}, {});
wuow.commit();
}
{
AutoGetCollection autoColl(operationContext(), kNss, MODE_IS);
{
BSONArrayBuilder arrBuilder;
ASSERT_OK(
cloner.nextCloneBatch(operationContext(), autoColl.getCollection(), &arrBuilder));
ASSERT_EQ(0, arrBuilder.arrSize());
}
{
BSONObjBuilder modsBuilder;
ASSERT_OK(cloner.nextModsBatch(operationContext(), autoColl.getDb(), &modsBuilder));
const auto modsObj = modsBuilder.obj();
ASSERT_EQ(2U, modsObj["reload"].Array().size());
ASSERT_BSONOBJ_EQ(createCollectionDocument(150), modsObj["reload"].Array()[0].Obj());
ASSERT_BSONOBJ_EQ(createCollectionDocument(151), modsObj["reload"].Array()[1].Obj());
// The legacy chunk cloner cannot filter out deletes because we don't preserve the shard
// key on delete
ASSERT_EQ(3U, modsObj["deleted"].Array().size());
ASSERT_BSONOBJ_EQ(BSON("_id" << 80), modsObj["deleted"].Array()[0].Obj());
ASSERT_BSONOBJ_EQ(BSON("_id" << 199), modsObj["deleted"].Array()[1].Obj());
ASSERT_BSONOBJ_EQ(BSON("_id" << 220), modsObj["deleted"].Array()[2].Obj());
}
}
auto futureCommit = launchAsync([&]() {
onCommand([&](const RemoteCommandRequest& request) { return BSON("ok" << true); });
});
ASSERT_OK(cloner.commitClone(operationContext()));
futureCommit.default_timed_get();
}
TEST_F(MigrationChunkClonerSourceLegacyTest, RemoveDuplicateDocuments) {
const std::vector<BSONObj> contents = {createCollectionDocument(100),
createCollectionDocument(199)};
createShardedCollection(contents);
MigrationChunkClonerSourceLegacy cloner(
createMoveChunkRequest(ChunkRange(BSON("X" << 100), BSON("X" << 200))),
kShardKeyPattern,
kDonorConnStr,
kRecipientConnStr.getServers()[0]);
{
auto futureStartClone = launchAsync([&]() {
onCommand([&](const RemoteCommandRequest& request) { return BSON("ok" << true); });
});
ASSERT_OK(cloner.startClone(operationContext(), UUID::gen(), _lsid, _txnNumber));
futureStartClone.default_timed_get();
}
// Ensure the initial clone documents are available
{
AutoGetCollection autoColl(operationContext(), kNss, MODE_IS);
{
BSONArrayBuilder arrBuilder;
ASSERT_OK(
cloner.nextCloneBatch(operationContext(), autoColl.getCollection(), &arrBuilder));
ASSERT_EQ(2, arrBuilder.arrSize());
const auto arr = arrBuilder.arr();
ASSERT_BSONOBJ_EQ(contents[0], arr[0].Obj());
ASSERT_BSONOBJ_EQ(contents[1], arr[1].Obj());
}
}
{
AutoGetCollection autoColl(operationContext(), kNss, MODE_IX);
deleteDocsInShardedCollection(createCollectionDocument(100));
insertDocsInShardedCollection({createCollectionDocument(100)});
deleteDocsInShardedCollection(createCollectionDocument(100));
updateDocsInShardedCollection(createCollectionDocument(199),
createCollectionDocumentForUpdate(199, 198));
updateDocsInShardedCollection(createCollectionDocumentForUpdate(199, 198),
createCollectionDocumentForUpdate(199, 197));
WriteUnitOfWork wuow(operationContext());
cloner.onDeleteOp(operationContext(), createCollectionDocument(100), {}, {});
cloner.onInsertOp(operationContext(), createCollectionDocument(100), {});
cloner.onDeleteOp(operationContext(), createCollectionDocument(100), {}, {});
cloner.onUpdateOp(operationContext(),
createCollectionDocument(199),
createCollectionDocumentForUpdate(199, 198),
{},
{});
cloner.onUpdateOp(operationContext(),
createCollectionDocument(199),
createCollectionDocumentForUpdate(199, 197),
{},
{});
wuow.commit();
}
{
AutoGetCollection autoColl(operationContext(), kNss, MODE_IS);
{
BSONObjBuilder modsBuilder;
ASSERT_OK(cloner.nextModsBatch(operationContext(), autoColl.getDb(), &modsBuilder));
const auto modsObj = modsBuilder.obj();
ASSERT_EQ(1U, modsObj["reload"].Array().size());
ASSERT_BSONOBJ_EQ(createCollectionDocumentForUpdate(199, 197),
modsObj["reload"].Array()[0].Obj());
ASSERT_EQ(1U, modsObj["deleted"].Array().size());
ASSERT_BSONOBJ_EQ(BSON("_id" << 100), modsObj["deleted"].Array()[0].Obj());
}
}
auto futureCommit = launchAsync([&]() {
onCommand([&](const RemoteCommandRequest& request) { return BSON("ok" << true); });
});
ASSERT_OK(cloner.commitClone(operationContext()));
futureCommit.default_timed_get();
}
TEST_F(MigrationChunkClonerSourceLegacyTest, OneLargeDocumentTransferMods) {
const std::vector<BSONObj> contents = {createCollectionDocument(1)};
createShardedCollection(contents);
MigrationChunkClonerSourceLegacy cloner(
createMoveChunkRequest(ChunkRange(BSON("X" << 1), BSON("X" << 100))),
kShardKeyPattern,
kDonorConnStr,
kRecipientConnStr.getServers()[0]);
{
auto futureStartClone = launchAsync([&]() {
onCommand([&](const RemoteCommandRequest& request) { return BSON("ok" << true); });
});
ASSERT_OK(cloner.startClone(operationContext(), UUID::gen(), _lsid, _txnNumber));
futureStartClone.default_timed_get();
}
{
AutoGetCollection autoColl(operationContext(), kNss, MODE_IS);
{
BSONArrayBuilder arrBuilder;
ASSERT_OK(
cloner.nextCloneBatch(operationContext(), autoColl.getCollection(), &arrBuilder));
ASSERT_EQ(1, arrBuilder.arrSize());
}
}
{
AutoGetCollection autoColl(operationContext(), kNss, MODE_IX);
BSONObj insertDoc =
createSizedCollectionDocument(2, BSONObjMaxUserSize - kFixedCommandOverhead + 2 * 1024);
insertDocsInShardedCollection({insertDoc});
WriteUnitOfWork wuow(operationContext());
cloner.onInsertOp(operationContext(), insertDoc, {});
wuow.commit();
}
{
AutoGetCollection autoColl(operationContext(), kNss, MODE_IS);
{
BSONObjBuilder modsBuilder;
ASSERT_OK(cloner.nextModsBatch(operationContext(), autoColl.getDb(), &modsBuilder));
const auto modsObj = modsBuilder.obj();
ASSERT_EQ(1, modsObj["reload"].Array().size());
}
}
auto futureCommit = launchAsync([&]() {
onCommand([&](const RemoteCommandRequest& request) { return BSON("ok" << true); });
});
ASSERT_OK(cloner.commitClone(operationContext()));
futureCommit.default_timed_get();
}
TEST_F(MigrationChunkClonerSourceLegacyTest, ManySmallDocumentsTransferMods) {
const std::vector<BSONObj> contents = {createCollectionDocument(1)};
createShardedCollection(contents);
MigrationChunkClonerSourceLegacy cloner(
createMoveChunkRequest(ChunkRange(BSON("X" << 1), BSON("X" << 1000000))),
kShardKeyPattern,
kDonorConnStr,
kRecipientConnStr.getServers()[0]);
{
auto futureStartClone = launchAsync([&]() {
onCommand([&](const RemoteCommandRequest& request) { return BSON("ok" << true); });
});
ASSERT_OK(cloner.startClone(operationContext(), UUID::gen(), _lsid, _txnNumber));
futureStartClone.default_timed_get();
}
{
AutoGetCollection autoColl(operationContext(), kNss, MODE_IS);
{
BSONArrayBuilder arrBuilder;
ASSERT_OK(
cloner.nextCloneBatch(operationContext(), autoColl.getCollection(), &arrBuilder));
ASSERT_EQ(1, arrBuilder.arrSize());
}
}
long long numDocuments = 0;
{
AutoGetCollection autoColl(operationContext(), kNss, MODE_IX);
std::vector<BSONObj> insertDocs;
long long totalSize = 0;
long long id = 2;
while (true) {
BSONObj add = createSizedCollectionDocument(id++, 4 * 1024);
// The overhead for a BSONObjBuilder with 4KB documents is ~ 22 * 1024, so this is the
// max documents to fit in one batch
if (totalSize + add.objsize() > BSONObjMaxUserSize - kFixedCommandOverhead - 22 * 1024)
break;
insertDocs.push_back(add);
totalSize += add.objsize();
numDocuments++;
insertDocsInShardedCollection({add});
}
WriteUnitOfWork wuow(operationContext());
for (BSONObj add : insertDocs) {
cloner.onInsertOp(operationContext(), add, {});
}
wuow.commit();
}
{
AutoGetCollection autoColl(operationContext(), kNss, MODE_IS);
{
BSONObjBuilder modsBuilder;
ASSERT_OK(cloner.nextModsBatch(operationContext(), autoColl.getDb(), &modsBuilder));
const auto modsObj = modsBuilder.obj();
ASSERT_EQ(modsObj["reload"].Array().size(), numDocuments);
}
}
auto futureCommit = launchAsync([&]() {
onCommand([&](const RemoteCommandRequest& request) { return BSON("ok" << true); });
});
ASSERT_OK(cloner.commitClone(operationContext()));
futureCommit.default_timed_get();
}
TEST_F(MigrationChunkClonerSourceLegacyTest, CollectionNotFound) {
MigrationChunkClonerSourceLegacy cloner(
createMoveChunkRequest(ChunkRange(BSON("X" << 100), BSON("X" << 200))),
kShardKeyPattern,
kDonorConnStr,
kRecipientConnStr.getServers()[0]);
ASSERT_NOT_OK(cloner.startClone(operationContext(), UUID::gen(), _lsid, _txnNumber));
cloner.cancelClone(operationContext());
}
TEST_F(MigrationChunkClonerSourceLegacyTest, ShardKeyIndexNotFound) {
{
OperationShardingState::ScopedAllowImplicitCollectionCreate_UNSAFE unsafeCreateCollection(
operationContext());
uassertStatusOK(createCollection(
operationContext(), kNss.db().toString(), BSON("create" << kNss.coll())));
}
MigrationChunkClonerSourceLegacy cloner(
createMoveChunkRequest(ChunkRange(BSON("X" << 100), BSON("X" << 200))),
kShardKeyPattern,
kDonorConnStr,
kRecipientConnStr.getServers()[0]);
ASSERT_NOT_OK(cloner.startClone(operationContext(), UUID::gen(), _lsid, _txnNumber));
cloner.cancelClone(operationContext());
}
TEST_F(MigrationChunkClonerSourceLegacyTest, FailedToEngageRecipientShard) {
const std::vector<BSONObj> contents = {createCollectionDocument(99),
createCollectionDocument(100),
createCollectionDocument(199),
createCollectionDocument(200)};
createShardedCollection(contents);
MigrationChunkClonerSourceLegacy cloner(
createMoveChunkRequest(ChunkRange(BSON("X" << 100), BSON("X" << 200))),
kShardKeyPattern,
kDonorConnStr,
kRecipientConnStr.getServers()[0]);
{
auto futureStartClone = launchAsync([&]() {
onCommand([&](const RemoteCommandRequest& request) {
return Status(ErrorCodes::NetworkTimeout,
"Did not receive confirmation from donor");
});
});
auto startCloneStatus =
cloner.startClone(operationContext(), UUID::gen(), _lsid, _txnNumber);
ASSERT_EQ(ErrorCodes::NetworkTimeout, startCloneStatus.code());
futureStartClone.default_timed_get();
}
// Ensure that if the recipient tries to fetch some documents, the cloner won't crash
{
AutoGetCollection autoColl(operationContext(), kNss, MODE_IS);
{
BSONArrayBuilder arrBuilder;
ASSERT_OK(
cloner.nextCloneBatch(operationContext(), autoColl.getCollection(), &arrBuilder));
ASSERT_EQ(2, arrBuilder.arrSize());
}
{
BSONArrayBuilder arrBuilder;
ASSERT_OK(
cloner.nextCloneBatch(operationContext(), autoColl.getCollection(), &arrBuilder));
ASSERT_EQ(0, arrBuilder.arrSize());
}
}
// Cancel clone should not send a cancellation request to the donor because we failed to engage
// it (see comment in the startClone method)
cloner.cancelClone(operationContext());
}
} // namespace
} // namespace mongo
|