-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
resharding_coordinator_service.cpp
1945 lines (1686 loc) · 91.8 KB
/
resharding_coordinator_service.cpp
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
/**
* Copyright (C) 2020-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/base/string_data.h"
#include "mongo/s/write_ops/batched_command_request.h"
#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kResharding
#include "mongo/platform/basic.h"
#include "mongo/db/s/resharding/resharding_coordinator_service.h"
#include "mongo/bson/bsonobj.h"
#include "mongo/bson/json.h"
#include "mongo/db/auth/authorization_session_impl.h"
#include "mongo/db/dbdirectclient.h"
#include "mongo/db/logical_session_cache.h"
#include "mongo/db/ops/write_ops.h"
#include "mongo/db/repl/primary_only_service.h"
#include "mongo/db/s/balancer/balance_stats.h"
#include "mongo/db/s/balancer/balancer_policy.h"
#include "mongo/db/s/config/initial_split_policy.h"
#include "mongo/db/s/config/sharding_catalog_manager.h"
#include "mongo/db/s/resharding/resharding_coordinator_commit_monitor.h"
#include "mongo/db/s/resharding/resharding_future_util.h"
#include "mongo/db/s/resharding/resharding_metrics.h"
#include "mongo/db/s/resharding/resharding_server_parameters_gen.h"
#include "mongo/db/s/resharding_util.h"
#include "mongo/db/s/sharding_ddl_util.h"
#include "mongo/db/s/sharding_logging.h"
#include "mongo/db/s/sharding_util.h"
#include "mongo/db/storage/duplicate_key_error_info.h"
#include "mongo/db/vector_clock.h"
#include "mongo/db/write_concern_options.h"
#include "mongo/logv2/log.h"
#include "mongo/rpc/get_status_from_command_result.h"
#include "mongo/s/catalog/type_chunk.h"
#include "mongo/s/catalog/type_tags.h"
#include "mongo/s/grid.h"
#include "mongo/s/request_types/abort_reshard_collection_gen.h"
#include "mongo/s/request_types/commit_reshard_collection_gen.h"
#include "mongo/s/request_types/drop_collection_if_uuid_not_matching_gen.h"
#include "mongo/s/request_types/flush_resharding_state_change_gen.h"
#include "mongo/s/request_types/flush_routing_table_cache_updates_gen.h"
#include "mongo/s/shard_id.h"
#include "mongo/s/write_ops/batched_command_response.h"
#include "mongo/util/assert_util.h"
#include "mongo/util/fail_point.h"
#include "mongo/util/future_util.h"
#include "mongo/util/string_map.h"
#include "mongo/util/uuid.h"
namespace mongo {
namespace {
using namespace fmt::literals;
MONGO_FAIL_POINT_DEFINE(reshardingPauseCoordinatorAfterPreparingToDonate);
MONGO_FAIL_POINT_DEFINE(reshardingPauseCoordinatorBeforeCloning);
MONGO_FAIL_POINT_DEFINE(reshardingPauseCoordinatorBeforeBlockingWrites);
MONGO_FAIL_POINT_DEFINE(reshardingPauseCoordinatorBeforeDecisionPersisted);
MONGO_FAIL_POINT_DEFINE(reshardingPauseCoordinatorBeforeRemovingStateDoc);
MONGO_FAIL_POINT_DEFINE(reshardingPauseCoordinatorBeforeCompletion);
MONGO_FAIL_POINT_DEFINE(reshardingPauseCoordinatorBeforeStartingErrorFlow);
MONGO_FAIL_POINT_DEFINE(reshardingPauseCoordinatorBeforePersistingStateTransition);
MONGO_FAIL_POINT_DEFINE(pauseBeforeTellDonorToRefresh);
MONGO_FAIL_POINT_DEFINE(pauseBeforeInsertCoordinatorDoc);
const std::string kReshardingCoordinatorActiveIndexName = "ReshardingCoordinatorActiveIndex";
const Backoff kExponentialBackoff(Seconds(1), Milliseconds::max());
const WriteConcernOptions kMajorityWriteConcern{
WriteConcernOptions::kMajority, WriteConcernOptions::SyncMode::UNSET, Seconds(0)};
bool shouldStopAttemptingToCreateIndex(Status status, const CancellationToken& token) {
return status.isOK() || token.isCanceled();
}
Date_t getCurrentTime() {
const auto svcCtx = cc().getServiceContext();
return svcCtx->getFastClockSource()->now();
}
void assertNumDocsModifiedMatchesExpected(const BatchedCommandRequest& request,
const BSONObj& response,
int expected) {
auto numDocsModified = response.getIntField("n");
uassert(5030401,
str::stream() << "Expected to match " << expected << " docs, but only matched "
<< numDocsModified << " for write request " << request.toString(),
expected == numDocsModified);
}
void appendShardEntriesToSetBuilder(const ReshardingCoordinatorDocument& coordinatorDoc,
BSONObjBuilder& setBuilder) {
BSONArrayBuilder donorShards(
setBuilder.subarrayStart(ReshardingCoordinatorDocument::kDonorShardsFieldName));
for (const auto& donorShard : coordinatorDoc.getDonorShards()) {
donorShards.append(donorShard.toBSON());
}
donorShards.doneFast();
BSONArrayBuilder recipientShards(
setBuilder.subarrayStart(ReshardingCoordinatorDocument::kRecipientShardsFieldName));
for (const auto& recipientShard : coordinatorDoc.getRecipientShards()) {
recipientShards.append(recipientShard.toBSON());
}
recipientShards.doneFast();
}
void unsetInitializingFields(BSONObjBuilder& updateBuilder) {
BSONObjBuilder unsetBuilder(updateBuilder.subobjStart("$unset"));
unsetBuilder.append(ReshardingCoordinatorDocument::kPresetReshardedChunksFieldName, "");
unsetBuilder.append(ReshardingCoordinatorDocument::kZonesFieldName, "");
unsetBuilder.doneFast();
}
void writeToCoordinatorStateNss(OperationContext* opCtx,
const ReshardingCoordinatorDocument& coordinatorDoc,
TxnNumber txnNumber) {
BatchedCommandRequest request([&] {
auto nextState = coordinatorDoc.getState();
switch (nextState) {
case CoordinatorStateEnum::kInitializing:
// Insert the new coordinator document.
return BatchedCommandRequest::buildInsertOp(
NamespaceString::kConfigReshardingOperationsNamespace,
std::vector<BSONObj>{coordinatorDoc.toBSON()});
case CoordinatorStateEnum::kDone:
// Remove the coordinator document.
return BatchedCommandRequest::buildDeleteOp(
NamespaceString::kConfigReshardingOperationsNamespace,
BSON("_id" << coordinatorDoc.getReshardingUUID()), // query
false // multi
);
default: {
// Partially update the coordinator document.
BSONObjBuilder updateBuilder;
{
BSONObjBuilder setBuilder(updateBuilder.subobjStart("$set"));
// Always update the state field.
setBuilder.append(ReshardingCoordinatorDocument::kStateFieldName,
CoordinatorState_serializer(coordinatorDoc.getState()));
if (auto cloneTimestamp = coordinatorDoc.getCloneTimestamp()) {
// If the cloneTimestamp exists, include it in the update.
setBuilder.append(ReshardingCoordinatorDocument::kCloneTimestampFieldName,
*cloneTimestamp);
}
if (auto abortReason = coordinatorDoc.getAbortReason()) {
// If the abortReason exists, include it in the update.
setBuilder.append(ReshardingCoordinatorDocument::kAbortReasonFieldName,
*abortReason);
}
if (auto approxBytesToCopy = coordinatorDoc.getApproxBytesToCopy()) {
// If the approxBytesToCopy exists, include it in the update.
setBuilder.append(
ReshardingCoordinatorDocument::kApproxBytesToCopyFieldName,
*approxBytesToCopy);
}
if (auto approxDocumentsToCopy = coordinatorDoc.getApproxDocumentsToCopy()) {
// If the approxDocumentsToCopy exists, include it in the update.
setBuilder.append(
ReshardingCoordinatorDocument::kApproxDocumentsToCopyFieldName,
*approxDocumentsToCopy);
}
if (nextState == CoordinatorStateEnum::kPreparingToDonate) {
appendShardEntriesToSetBuilder(coordinatorDoc, setBuilder);
setBuilder.doneFast();
unsetInitializingFields(updateBuilder);
}
}
return BatchedCommandRequest::buildUpdateOp(
NamespaceString::kConfigReshardingOperationsNamespace,
BSON("_id" << coordinatorDoc.getReshardingUUID()),
updateBuilder.obj(),
false, // upsert
false // multi
);
}
}
}());
auto expectedNumModified = (request.getBatchType() == BatchedCommandRequest::BatchType_Insert)
? boost::none
: boost::make_optional(1);
auto res = ShardingCatalogManager::get(opCtx)->writeToConfigDocumentInTxn(
opCtx, NamespaceString::kConfigReshardingOperationsNamespace, request, txnNumber);
if (expectedNumModified) {
assertNumDocsModifiedMatchesExpected(request, res, *expectedNumModified);
}
}
/**
* Creates reshardingFields.recipientFields for the resharding operation. Note: these should not
* change once the operation has begun.
*/
TypeCollectionRecipientFields constructRecipientFields(
const ReshardingCoordinatorDocument& coordinatorDoc) {
std::vector<DonorShardFetchTimestamp> donorShards;
for (const auto& donor : coordinatorDoc.getDonorShards()) {
DonorShardFetchTimestamp donorFetchTimestamp(donor.getId());
donorFetchTimestamp.setMinFetchTimestamp(donor.getMutableState().getMinFetchTimestamp());
donorShards.push_back(std::move(donorFetchTimestamp));
}
TypeCollectionRecipientFields recipientFields(
std::move(donorShards),
coordinatorDoc.getSourceUUID(),
coordinatorDoc.getSourceNss(),
resharding::gReshardingMinimumOperationDurationMillis.load());
emplaceCloneTimestampIfExists(recipientFields, coordinatorDoc.getCloneTimestamp());
emplaceApproxBytesToCopyIfExists(recipientFields,
coordinatorDoc.getReshardingApproxCopySizeStruct());
return recipientFields;
}
BSONObj createReshardingFieldsUpdateForOriginalNss(
OperationContext* opCtx,
const ReshardingCoordinatorDocument& coordinatorDoc,
boost::optional<OID> newCollectionEpoch,
boost::optional<Timestamp> newCollectionTimestamp) {
auto nextState = coordinatorDoc.getState();
switch (nextState) {
case CoordinatorStateEnum::kInitializing: {
// Append 'reshardingFields' to the config.collections entry for the original nss
TypeCollectionReshardingFields originalEntryReshardingFields(
coordinatorDoc.getReshardingUUID());
originalEntryReshardingFields.setState(coordinatorDoc.getState());
return BSON("$set" << BSON(CollectionType::kReshardingFieldsFieldName
<< originalEntryReshardingFields.toBSON()
<< CollectionType::kUpdatedAtFieldName
<< opCtx->getServiceContext()->getPreciseClockSource()->now()
<< CollectionType::kAllowMigrationsFieldName << false));
}
case CoordinatorStateEnum::kPreparingToDonate: {
TypeCollectionDonorFields donorFields(
coordinatorDoc.getTempReshardingNss(),
coordinatorDoc.getReshardingKey(),
extractShardIdsFromParticipantEntries(coordinatorDoc.getRecipientShards()));
BSONObjBuilder updateBuilder;
{
BSONObjBuilder setBuilder(updateBuilder.subobjStart("$set"));
{
setBuilder.append(CollectionType::kReshardingFieldsFieldName + "." +
TypeCollectionReshardingFields::kStateFieldName,
CoordinatorState_serializer(nextState));
setBuilder.append(CollectionType::kReshardingFieldsFieldName + "." +
TypeCollectionReshardingFields::kDonorFieldsFieldName,
donorFields.toBSON());
setBuilder.append(CollectionType::kUpdatedAtFieldName,
opCtx->getServiceContext()->getPreciseClockSource()->now());
}
setBuilder.doneFast();
}
return updateBuilder.obj();
}
case CoordinatorStateEnum::kCommitting: {
// Update the config.collections entry for the original nss to reflect the new sharded
// collection. Set 'uuid' to the reshardingUUID, 'key' to the new shard key,
// 'lastmodEpoch' to newCollectionEpoch, and 'timestamp' to newCollectionTimestamp. Also
// update the 'state' field and add the 'recipientFields' to the 'reshardingFields'
// section.
auto recipientFields = constructRecipientFields(coordinatorDoc);
BSONObj setFields =
BSON("uuid" << coordinatorDoc.getReshardingUUID() << "key"
<< coordinatorDoc.getReshardingKey().toBSON() << "lastmodEpoch"
<< newCollectionEpoch.get() << "lastmod"
<< opCtx->getServiceContext()->getPreciseClockSource()->now()
<< "reshardingFields.state"
<< CoordinatorState_serializer(coordinatorDoc.getState()).toString()
<< "reshardingFields.recipientFields" << recipientFields.toBSON());
if (newCollectionTimestamp.has_value()) {
setFields = setFields.addFields(BSON("timestamp" << newCollectionTimestamp.get()));
}
return BSON("$set" << setFields);
}
case mongo::CoordinatorStateEnum::kDone:
// Remove 'reshardingFields' from the config.collections entry
return BSON(
"$unset" << BSON(CollectionType::kReshardingFieldsFieldName
<< "" << CollectionType::kAllowMigrationsFieldName << "")
<< "$set"
<< BSON(CollectionType::kUpdatedAtFieldName
<< opCtx->getServiceContext()->getPreciseClockSource()->now()));
default: {
// Update the 'state' field, and 'abortReason' field if it exists, in the
// 'reshardingFields' section.
BSONObjBuilder updateBuilder;
{
BSONObjBuilder setBuilder(updateBuilder.subobjStart("$set"));
setBuilder.append("reshardingFields.state",
CoordinatorState_serializer(nextState).toString());
setBuilder.append("lastmod",
opCtx->getServiceContext()->getPreciseClockSource()->now());
if (auto abortReason = coordinatorDoc.getAbortReason()) {
// If the abortReason exists, include it in the update.
setBuilder.append("reshardingFields.abortReason", *abortReason);
auto abortStatus = getStatusFromAbortReason(coordinatorDoc);
setBuilder.append("reshardingFields.userCanceled",
abortStatus == ErrorCodes::ReshardCollectionAborted);
}
setBuilder.doneFast();
if (coordinatorDoc.getAbortReason()) {
updateBuilder.append("$unset",
BSON(CollectionType::kAllowMigrationsFieldName << ""));
}
}
return updateBuilder.obj();
}
}
}
void updateConfigCollectionsForOriginalNss(OperationContext* opCtx,
const ReshardingCoordinatorDocument& coordinatorDoc,
boost::optional<OID> newCollectionEpoch,
boost::optional<Timestamp> newCollectionTimestamp,
TxnNumber txnNumber) {
auto writeOp = createReshardingFieldsUpdateForOriginalNss(
opCtx, coordinatorDoc, newCollectionEpoch, newCollectionTimestamp);
auto request = BatchedCommandRequest::buildUpdateOp(
CollectionType::ConfigNS,
BSON(CollectionType::kNssFieldName << coordinatorDoc.getSourceNss().ns()), // query
writeOp,
false, // upsert
false // multi
);
auto res = ShardingCatalogManager::get(opCtx)->writeToConfigDocumentInTxn(
opCtx, CollectionType::ConfigNS, request, txnNumber);
assertNumDocsModifiedMatchesExpected(request, res, 1 /* expected */);
}
void writeToConfigCollectionsForTempNss(OperationContext* opCtx,
const ReshardingCoordinatorDocument& coordinatorDoc,
boost::optional<ChunkVersion> chunkVersion,
boost::optional<const BSONObj&> collation,
TxnNumber txnNumber) {
BatchedCommandRequest request([&] {
auto nextState = coordinatorDoc.getState();
switch (nextState) {
case CoordinatorStateEnum::kPreparingToDonate: {
// Insert new entry for the temporary nss into config.collections
auto collType = resharding::createTempReshardingCollectionType(
opCtx, coordinatorDoc, chunkVersion.get(), collation.get());
return BatchedCommandRequest::buildInsertOp(
CollectionType::ConfigNS, std::vector<BSONObj>{collType.toBSON()});
}
case CoordinatorStateEnum::kCloning: {
// Update the 'state', 'donorShards', 'approxCopySize', and 'cloneTimestamp' fields
// in the 'reshardingFields.recipient' section
BSONArrayBuilder donorShardsBuilder;
for (const auto& donor : coordinatorDoc.getDonorShards()) {
DonorShardFetchTimestamp donorShardFetchTimestamp(donor.getId());
donorShardFetchTimestamp.setMinFetchTimestamp(
donor.getMutableState().getMinFetchTimestamp());
donorShardsBuilder.append(donorShardFetchTimestamp.toBSON());
}
return BatchedCommandRequest::buildUpdateOp(
CollectionType::ConfigNS,
BSON(CollectionType::kNssFieldName
<< coordinatorDoc.getTempReshardingNss().ns()),
BSON("$set" << BSON(
"reshardingFields.state"
<< CoordinatorState_serializer(nextState).toString()
<< "reshardingFields.recipientFields.approxDocumentsToCopy"
<< coordinatorDoc.getApproxDocumentsToCopy().get()
<< "reshardingFields.recipientFields.approxBytesToCopy"
<< coordinatorDoc.getApproxBytesToCopy().get()
<< "reshardingFields.recipientFields.cloneTimestamp"
<< coordinatorDoc.getCloneTimestamp().get()
<< "reshardingFields.recipientFields.donorShards"
<< donorShardsBuilder.arr() << "lastmod"
<< opCtx->getServiceContext()->getPreciseClockSource()->now())),
false, // upsert
false // multi
);
}
case CoordinatorStateEnum::kCommitting:
// Remove the entry for the temporary nss
return BatchedCommandRequest::buildDeleteOp(
CollectionType::ConfigNS,
BSON(CollectionType::kNssFieldName
<< coordinatorDoc.getTempReshardingNss().ns()),
false // multi
);
default: {
// Update the 'state' field, and 'abortReason' field if it exists, in the
// 'reshardingFields' section.
BSONObjBuilder updateBuilder;
{
BSONObjBuilder setBuilder(updateBuilder.subobjStart("$set"));
setBuilder.append("reshardingFields.state",
CoordinatorState_serializer(nextState).toString());
setBuilder.append("lastmod",
opCtx->getServiceContext()->getPreciseClockSource()->now());
if (auto abortReason = coordinatorDoc.getAbortReason()) {
setBuilder.append("reshardingFields.abortReason", *abortReason);
auto abortStatus = getStatusFromAbortReason(coordinatorDoc);
setBuilder.append("reshardingFields.userCanceled",
abortStatus == ErrorCodes::ReshardCollectionAborted);
}
}
return BatchedCommandRequest::buildUpdateOp(
CollectionType::ConfigNS,
BSON(CollectionType::kNssFieldName
<< coordinatorDoc.getTempReshardingNss().ns()),
updateBuilder.obj(),
true, // upsert
false // multi
);
}
}
}());
auto expectedNumModified = (request.getBatchType() == BatchedCommandRequest::BatchType_Insert)
? boost::none
: boost::make_optional(1);
auto res = ShardingCatalogManager::get(opCtx)->writeToConfigDocumentInTxn(
opCtx, CollectionType::ConfigNS, request, txnNumber);
if (expectedNumModified) {
assertNumDocsModifiedMatchesExpected(request, res, *expectedNumModified);
}
}
void insertChunkAndTagDocsForTempNss(OperationContext* opCtx,
const std::vector<ChunkType>& initialChunks,
std::vector<BSONObj> newZones) {
// Insert new initial chunk documents for temp nss
std::vector<BSONObj> initialChunksBSON(initialChunks.size());
std::transform(initialChunks.begin(),
initialChunks.end(),
initialChunksBSON.begin(),
[](ChunkType chunk) { return chunk.toConfigBSON(); });
ShardingCatalogManager::get(opCtx)->insertConfigDocuments(
opCtx, ChunkType::ConfigNS, std::move(initialChunksBSON));
ShardingCatalogManager::get(opCtx)->insertConfigDocuments(opCtx, TagsType::ConfigNS, newZones);
}
// Requires that there be no session information on the opCtx.
void removeChunkAndTagsDocs(OperationContext* opCtx,
const BSONObj& tagsQuery,
const UUID& collUUID) {
// Remove all chunk documents for the original nss. We do not know how many chunk docs
// currently exist, so cannot pass a value for expectedNumModified
const auto chunksQuery = BSON(ChunkType::collectionUUID() << collUUID);
const auto tagDeleteOperationHint = BSON(TagsType::ns() << 1 << TagsType::min() << 1);
const auto catalogClient = Grid::get(opCtx)->catalogClient();
uassertStatusOK(catalogClient->removeConfigDocuments(
opCtx, ChunkType::ConfigNS, chunksQuery, kMajorityWriteConcern));
uassertStatusOK(catalogClient->removeConfigDocuments(
opCtx, TagsType::ConfigNS, tagsQuery, kMajorityWriteConcern, tagDeleteOperationHint));
}
void updateChunkAndTagsDocsForTempNss(OperationContext* opCtx,
const ReshardingCoordinatorDocument& coordinatorDoc,
OID newCollectionEpoch,
TxnNumber txnNumber) {
auto hint = BSON("ns" << 1 << "min" << 1);
auto tagsRequest = BatchedCommandRequest::buildUpdateOp(
TagsType::ConfigNS,
BSON(TagsType::ns(coordinatorDoc.getTempReshardingNss().ns())), // query
BSON("$set" << BSON("ns" << coordinatorDoc.getSourceNss().ns())), // update
false, // upsert
true, // multi
hint // hint
);
// Update the 'ns' field to be the original collection namespace for all tags documents that
// currently have 'ns' as the temporary collection namespace
auto tagsRes = ShardingCatalogManager::get(opCtx)->writeToConfigDocumentInTxn(
opCtx, TagsType::ConfigNS, tagsRequest, txnNumber);
}
/**
* Executes metadata changes in a transaction without bumping the collection version.
*/
void executeMetadataChangesInTxn(
OperationContext* opCtx,
unique_function<void(OperationContext*, TxnNumber)> changeMetadataFunc) {
ShardingCatalogManager::withTransaction(opCtx,
NamespaceString::kConfigReshardingOperationsNamespace,
[&](OperationContext* opCtx, TxnNumber txnNumber) {
changeMetadataFunc(opCtx, txnNumber);
});
}
BSONObj makeFlushRoutingTableCacheUpdatesCmd(const NamespaceString& nss) {
auto cmd = _flushRoutingTableCacheUpdatesWithWriteConcern(nss);
cmd.setSyncFromConfig(true);
cmd.setDbName(nss.db());
return cmd.toBSON(
BSON(WriteConcernOptions::kWriteConcernField << kMajorityWriteConcern.toBSON()));
}
} // namespace
namespace resharding {
CollectionType createTempReshardingCollectionType(
OperationContext* opCtx,
const ReshardingCoordinatorDocument& coordinatorDoc,
const ChunkVersion& chunkVersion,
const BSONObj& collation) {
CollectionType collType(coordinatorDoc.getTempReshardingNss(),
chunkVersion.epoch(),
chunkVersion.getTimestamp(),
opCtx->getServiceContext()->getPreciseClockSource()->now(),
coordinatorDoc.getReshardingUUID());
collType.setKeyPattern(coordinatorDoc.getReshardingKey());
collType.setDefaultCollation(collation);
collType.setUnique(false);
TypeCollectionReshardingFields tempEntryReshardingFields(coordinatorDoc.getReshardingUUID());
tempEntryReshardingFields.setState(coordinatorDoc.getState());
auto recipientFields = constructRecipientFields(coordinatorDoc);
tempEntryReshardingFields.setRecipientFields(std::move(recipientFields));
collType.setReshardingFields(std::move(tempEntryReshardingFields));
collType.setAllowMigrations(false);
return collType;
}
void cleanupSourceConfigCollections(OperationContext* opCtx,
const ReshardingCoordinatorDocument& coordinatorDoc) {
using Doc = Document;
using Arr = std::vector<Value>;
using V = Value;
auto createTagFilter = [](const V value) {
return V{Doc{{"$map",
V{Doc{{"input", V{Doc{{"$objectToArray", value}}}},
{"in", V{StringData("$$this.k")}}}}}}};
};
auto skipNewTagsFilter = Doc{
{"$ne",
Arr{createTagFilter(V{StringData("$min")}),
createTagFilter(V{Doc{{"$literal", coordinatorDoc.getReshardingKey().toBSON()}}})}}};
const auto removeTagsQuery =
BSON(TagsType::ns(coordinatorDoc.getSourceNss().ns()) << "$expr" << skipNewTagsFilter);
removeChunkAndTagsDocs(opCtx, removeTagsQuery, coordinatorDoc.getSourceUUID());
}
void writeDecisionPersistedState(OperationContext* opCtx,
const ReshardingCoordinatorDocument& coordinatorDoc,
OID newCollectionEpoch,
Timestamp newCollectionTimestamp) {
// No need to bump originalNss version because its epoch will be changed.
executeMetadataChangesInTxn(opCtx, [&](OperationContext* opCtx, TxnNumber txnNumber) {
// Update the config.reshardingOperations entry
writeToCoordinatorStateNss(opCtx, coordinatorDoc, txnNumber);
// Remove the config.collections entry for the temporary collection
writeToConfigCollectionsForTempNss(
opCtx, coordinatorDoc, boost::none, boost::none, txnNumber);
// Update the config.collections entry for the original namespace to reflect the new
// shard key, new epoch, and new UUID
updateConfigCollectionsForOriginalNss(
opCtx, coordinatorDoc, newCollectionEpoch, newCollectionTimestamp, txnNumber);
updateChunkAndTagsDocsForTempNss(opCtx, coordinatorDoc, newCollectionEpoch, txnNumber);
});
}
void insertCoordDocAndChangeOrigCollEntry(OperationContext* opCtx,
const ReshardingCoordinatorDocument& coordinatorDoc) {
ShardingCatalogManager::get(opCtx)->bumpCollectionVersionAndChangeMetadataInTxn(
opCtx, coordinatorDoc.getSourceNss(), [&](OperationContext* opCtx, TxnNumber txnNumber) {
auto doc = ShardingCatalogManager::get(opCtx)->findOneConfigDocumentInTxn(
opCtx,
CollectionType::ConfigNS,
txnNumber,
BSON(CollectionType::kNssFieldName << coordinatorDoc.getSourceNss().ns()));
uassert(5808200,
str::stream() << "config.collection entry not found for "
<< coordinatorDoc.getSourceNss().ns(),
doc);
CollectionType configCollDoc(*doc);
uassert(5808201,
str::stream() << "collection " << CollectionType::kAllowMigrationsFieldName
<< " setting is already set to false",
configCollDoc.getAllowMigrations());
// Insert the coordinator document to config.reshardingOperations.
invariant(coordinatorDoc.getActive());
try {
writeToCoordinatorStateNss(opCtx, coordinatorDoc, txnNumber);
} catch (const ExceptionFor<ErrorCodes::DuplicateKey>& ex) {
auto extraInfo = ex.extraInfo<DuplicateKeyErrorInfo>();
if (extraInfo->getKeyPattern().woCompare(BSON("active" << 1)) == 0) {
uasserted(ErrorCodes::ReshardCollectionInProgress,
str::stream()
<< "Only one resharding operation is allowed to be active at a "
"time, aborting resharding op for "
<< coordinatorDoc.getSourceNss());
}
throw;
}
// Update the config.collections entry for the original collection to include
// 'reshardingFields'
updateConfigCollectionsForOriginalNss(
opCtx, coordinatorDoc, boost::none, boost::none, txnNumber);
});
}
void writeParticipantShardsAndTempCollInfo(
OperationContext* opCtx,
const ReshardingCoordinatorDocument& updatedCoordinatorDoc,
std::vector<ChunkType> initialChunks,
std::vector<BSONObj> zones) {
const auto tagsQuery = BSON(TagsType::ns(updatedCoordinatorDoc.getTempReshardingNss().ns()));
removeChunkAndTagsDocs(opCtx, tagsQuery, updatedCoordinatorDoc.getReshardingUUID());
insertChunkAndTagDocsForTempNss(opCtx, initialChunks, zones);
ShardingCatalogManager::get(opCtx)->bumpCollectionVersionAndChangeMetadataInTxn(
opCtx,
updatedCoordinatorDoc.getSourceNss(),
[&](OperationContext* opCtx, TxnNumber txnNumber) {
// Insert the config.collections entry for the temporary resharding collection. The
// chunks all have the same epoch, so picking the last chunk here is arbitrary.
invariant(initialChunks.size() != 0);
auto chunkVersion = initialChunks.back().getVersion();
writeToConfigCollectionsForTempNss(
opCtx, updatedCoordinatorDoc, chunkVersion, CollationSpec::kSimpleSpec, txnNumber);
// Update on-disk state to reflect latest state transition.
writeToCoordinatorStateNss(opCtx, updatedCoordinatorDoc, txnNumber);
updateConfigCollectionsForOriginalNss(
opCtx, updatedCoordinatorDoc, boost::none, boost::none, txnNumber);
});
}
void writeStateTransitionAndCatalogUpdatesThenBumpShardVersions(
OperationContext* opCtx, const ReshardingCoordinatorDocument& coordinatorDoc) {
// Run updates to config.reshardingOperations and config.collections in a transaction
auto nextState = coordinatorDoc.getState();
std::vector<NamespaceString> collNames = {coordinatorDoc.getSourceNss()};
if (nextState < CoordinatorStateEnum::kCommitting) {
collNames.emplace_back(coordinatorDoc.getTempReshardingNss());
}
ShardingCatalogManager::get(opCtx)->bumpMultipleCollectionVersionsAndChangeMetadataInTxn(
opCtx, collNames, [&](OperationContext* opCtx, TxnNumber txnNumber) {
// Update the config.reshardingOperations entry
writeToCoordinatorStateNss(opCtx, coordinatorDoc, txnNumber);
// Update the config.collections entry for the original collection
updateConfigCollectionsForOriginalNss(
opCtx, coordinatorDoc, boost::none, boost::none, txnNumber);
// Update the config.collections entry for the temporary resharding collection. If we've
// already successfully committed that the operation will succeed, we've removed the
// entry for the temporary collection and updated the entry with original namespace to
// have the new shard key, UUID, and epoch
if (nextState < CoordinatorStateEnum::kCommitting) {
writeToConfigCollectionsForTempNss(
opCtx, coordinatorDoc, boost::none, boost::none, txnNumber);
}
});
}
void removeCoordinatorDocAndReshardingFields(OperationContext* opCtx,
const ReshardingCoordinatorDocument& coordinatorDoc,
boost::optional<Status> abortReason) {
// If the coordinator needs to abort and isn't in kInitializing, additional collections need to
// be cleaned up in the final transaction. Otherwise, cleanup for abort and success are the
// same.
const bool wasDecisionPersisted =
coordinatorDoc.getState() == CoordinatorStateEnum::kCommitting;
invariant((wasDecisionPersisted && !abortReason) || abortReason);
ReshardingCoordinatorDocument updatedCoordinatorDoc = coordinatorDoc;
updatedCoordinatorDoc.setState(CoordinatorStateEnum::kDone);
emplaceTruncatedAbortReasonIfExists(updatedCoordinatorDoc, abortReason);
const auto tagsQuery = BSON(TagsType::ns(coordinatorDoc.getTempReshardingNss().ns()));
// Once the decision has been persisted, the coordinator would have modified the
// config.chunks and config.collections entry. This means that the UUID of the
// non-temp collection is now the UUID of what was previously the UUID of the temp
// collection. So don't try to call remove as it will end up removing the metadata
// for the real collection.
if (!wasDecisionPersisted) {
const auto catalogClient = Grid::get(opCtx)->catalogClient();
uassertStatusOK(catalogClient->removeConfigDocuments(
opCtx,
CollectionType::ConfigNS,
BSON(CollectionType::kNssFieldName << coordinatorDoc.getTempReshardingNss().ns()),
kMajorityWriteConcern));
removeChunkAndTagsDocs(opCtx, tagsQuery, coordinatorDoc.getReshardingUUID());
}
ShardingCatalogManager::get(opCtx)->bumpCollectionVersionAndChangeMetadataInTxn(
opCtx,
updatedCoordinatorDoc.getSourceNss(),
[&](OperationContext* opCtx, TxnNumber txnNumber) {
// Remove entry for this resharding operation from config.reshardingOperations
writeToCoordinatorStateNss(opCtx, updatedCoordinatorDoc, txnNumber);
// Remove the resharding fields from the config.collections entry
updateConfigCollectionsForOriginalNss(
opCtx, updatedCoordinatorDoc, boost::none, boost::none, txnNumber);
});
}
} // namespace resharding
ChunkVersion ReshardingCoordinatorExternalState::calculateChunkVersionForInitialChunks(
OperationContext* opCtx) {
const auto now = VectorClock::get(opCtx)->getTime();
const auto timestamp = now.clusterTime().asTimestamp();
return ChunkVersion(1, 0, OID::gen(), timestamp);
}
std::vector<DonorShardEntry> constructDonorShardEntries(const std::set<ShardId>& donorShardIds) {
std::vector<DonorShardEntry> donorShards;
std::transform(donorShardIds.begin(),
donorShardIds.end(),
std::back_inserter(donorShards),
[](const ShardId& shardId) -> DonorShardEntry {
DonorShardContext donorCtx;
donorCtx.setState(DonorStateEnum::kUnused);
return DonorShardEntry{shardId, std::move(donorCtx)};
});
return donorShards;
}
std::vector<RecipientShardEntry> constructRecipientShardEntries(
const std::set<ShardId>& recipientShardIds) {
std::vector<RecipientShardEntry> recipientShards;
std::transform(recipientShardIds.begin(),
recipientShardIds.end(),
std::back_inserter(recipientShards),
[](const ShardId& shardId) -> RecipientShardEntry {
RecipientShardContext recipientCtx;
recipientCtx.setState(RecipientStateEnum::kUnused);
return RecipientShardEntry{shardId, std::move(recipientCtx)};
});
return recipientShards;
}
ReshardingCoordinatorExternalState::ParticipantShardsAndChunks
ReshardingCoordinatorExternalStateImpl::calculateParticipantShardsAndChunks(
OperationContext* opCtx, const ReshardingCoordinatorDocument& coordinatorDoc) {
const auto cm = uassertStatusOK(
Grid::get(opCtx)->catalogCache()->getShardedCollectionRoutingInfoWithRefresh(
opCtx, coordinatorDoc.getSourceNss()));
std::set<ShardId> donorShardIds;
cm.getAllShardIds(&donorShardIds);
std::set<ShardId> recipientShardIds;
std::vector<ChunkType> initialChunks;
// The database primary must always be a recipient to ensure it ends up with consistent
// collection metadata.
recipientShardIds.emplace(cm.dbPrimary());
if (const auto& chunks = coordinatorDoc.getPresetReshardedChunks()) {
auto version = calculateChunkVersionForInitialChunks(opCtx);
// Use the provided shardIds from presetReshardedChunks to construct the
// recipient list.
for (const auto& reshardedChunk : *chunks) {
recipientShardIds.emplace(reshardedChunk.getRecipientShardId());
initialChunks.emplace_back(coordinatorDoc.getReshardingUUID(),
ChunkRange{reshardedChunk.getMin(), reshardedChunk.getMax()},
version,
reshardedChunk.getRecipientShardId());
version.incMinor();
}
} else {
int numInitialChunks = coordinatorDoc.getNumInitialChunks()
? *coordinatorDoc.getNumInitialChunks()
: cm.numChunks();
ShardKeyPattern shardKey(coordinatorDoc.getReshardingKey());
const auto tempNs = coordinatorDoc.getTempReshardingNss();
boost::optional<std::vector<mongo::TagsType>> parsedZones;
auto rawBSONZones = coordinatorDoc.getZones();
if (rawBSONZones && rawBSONZones->size() != 0) {
parsedZones.emplace();
parsedZones->reserve(rawBSONZones->size());
for (const auto& zone : *rawBSONZones) {
ChunkRange range(zone.getMin(), zone.getMax());
TagsType tag(
coordinatorDoc.getTempReshardingNss(), zone.getZone().toString(), range);
parsedZones->push_back(tag);
}
}
auto initialSplitter = ReshardingSplitPolicy::make(opCtx,
coordinatorDoc.getSourceNss(),
tempNs,
shardKey,
numInitialChunks,
std::move(parsedZones));
// Note: The resharding initial split policy doesn't care about what is the real primary
// shard, so just pass in a random shard.
const SplitPolicyParams splitParams{coordinatorDoc.getReshardingUUID(),
*donorShardIds.begin()};
auto splitResult = initialSplitter.createFirstChunks(opCtx, shardKey, splitParams);
initialChunks = std::move(splitResult.chunks);
for (const auto& chunk : initialChunks) {
recipientShardIds.insert(chunk.getShard());
}
}
return {constructDonorShardEntries(donorShardIds),
constructRecipientShardEntries(recipientShardIds),
initialChunks};
}
void ReshardingCoordinatorExternalStateImpl::sendCommandToShards(
OperationContext* opCtx,
StringData dbName,
const BSONObj& command,
const std::vector<ShardId>& shardIds,
const std::shared_ptr<executor::TaskExecutor>& executor) {
sharding_ddl_util::sendAuthenticatedCommandToShards(opCtx, dbName, command, shardIds, executor);
}
ThreadPool::Limits ReshardingCoordinatorService::getThreadPoolLimits() const {
ThreadPool::Limits threadPoolLimit;
threadPoolLimit.maxThreads = resharding::gReshardingCoordinatorServiceMaxThreadCount;
return threadPoolLimit;
}
std::shared_ptr<repl::PrimaryOnlyService::Instance> ReshardingCoordinatorService::constructInstance(
BSONObj initialState) {
return std::make_shared<ReshardingCoordinator>(
this,
ReshardingCoordinatorDocument::parse(IDLParserErrorContext("ReshardingCoordinatorStateDoc"),
std::move(initialState)),
std::make_shared<ReshardingCoordinatorExternalStateImpl>());
}
ExecutorFuture<void> ReshardingCoordinatorService::_rebuildService(
std::shared_ptr<executor::ScopedTaskExecutor> executor, const CancellationToken& token) {
return AsyncTry([this] {
auto nss = getStateDocumentsNS();
AllowOpCtxWhenServiceRebuildingBlock allowOpCtxBlock(Client::getCurrent());
auto opCtxHolder = cc().makeOperationContext();
auto opCtx = opCtxHolder.get();
DBDirectClient client(opCtx);
BSONObj result;
client.runCommand(
nss.db().toString(),
BSON("createIndexes"
<< nss.coll().toString() << "indexes"
<< BSON_ARRAY(BSON("key" << BSON("active" << 1) << "name"
<< kReshardingCoordinatorActiveIndexName
<< "unique" << true))),
result);
uassertStatusOK(getStatusFromCommandResult(result));
})
.until([token](Status status) { return shouldStopAttemptingToCreateIndex(status, token); })
.withBackoffBetweenIterations(kExponentialBackoff)
.on(**executor, CancellationToken::uncancelable());
}
void ReshardingCoordinatorService::abortAllReshardCollection(OperationContext* opCtx) {
std::vector<SharedSemiFuture<void>> reshardingCoordinatorFutures;
for (auto& instance : getAllInstances(opCtx)) {
auto reshardingCoordinator =
checked_pointer_cast<ReshardingCoordinatorService::ReshardingCoordinator>(instance);
reshardingCoordinatorFutures.push_back(reshardingCoordinator->getCompletionFuture());
reshardingCoordinator->abort();
}
for (auto&& future : reshardingCoordinatorFutures) {
future.wait(opCtx);
}
}
ReshardingCoordinatorService::ReshardingCoordinator::ReshardingCoordinator(
const ReshardingCoordinatorService* coordinatorService,
const ReshardingCoordinatorDocument& coordinatorDoc,
std::shared_ptr<ReshardingCoordinatorExternalState> externalState)
: PrimaryOnlyService::TypedInstance<ReshardingCoordinator>(),
_id(coordinatorDoc.getReshardingUUID().toBSON()),
_coordinatorService(coordinatorService),
_metadata(coordinatorDoc.getCommonReshardingMetadata()),
_coordinatorDoc(coordinatorDoc),
_markKilledExecutor(std::make_shared<ThreadPool>([] {
ThreadPool::Options options;
options.poolName = "ReshardingCoordinatorCancelableOpCtxPool";
options.minThreads = 1;
options.maxThreads = 1;
return options;
}())),
_reshardingCoordinatorExternalState(externalState) {
_reshardingCoordinatorObserver = std::make_shared<ReshardingCoordinatorObserver>();
// If the coordinator is recovering from step-up, make sure to properly initialize the
// promises to reflect the latest state of this resharding operation.
if (coordinatorDoc.getState() > CoordinatorStateEnum::kInitializing) {
_reshardingCoordinatorObserver->onReshardingParticipantTransition(coordinatorDoc);
}
}
void ReshardingCoordinatorService::ReshardingCoordinator::installCoordinatorDoc(
OperationContext* opCtx, const ReshardingCoordinatorDocument& doc) noexcept {
invariant(doc.getReshardingUUID() == _coordinatorDoc.getReshardingUUID());
BSONObjBuilder bob;
bob.append("newState", CoordinatorState_serializer(doc.getState()));
bob.append("oldState", CoordinatorState_serializer(_coordinatorDoc.getState()));
bob.append("namespace", doc.getSourceNss().toString());
bob.append("collectionUUID", doc.getSourceUUID().toString());
bob.append("reshardingUUID", doc.getReshardingUUID().toString());
LOGV2_INFO(5343001,
"Transitioned resharding coordinator state",
"newState"_attr = CoordinatorState_serializer(doc.getState()),
"oldState"_attr = CoordinatorState_serializer(_coordinatorDoc.getState()),
"namespace"_attr = doc.getSourceNss(),
"collectionUUID"_attr = doc.getSourceUUID(),