/
index_builds_coordinator.cpp
2350 lines (2031 loc) · 106 KB
/
index_builds_coordinator.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) 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.
*/
#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kStorage
#include "mongo/platform/basic.h"
#include "mongo/db/index_builds_coordinator.h"
#include "mongo/db/catalog/collection_catalog.h"
#include "mongo/db/catalog/commit_quorum_options.h"
#include "mongo/db/catalog/database_holder.h"
#include "mongo/db/catalog/index_build_entry_gen.h"
#include "mongo/db/catalog/index_timestamp_helper.h"
#include "mongo/db/catalog/uncommitted_collections.h"
#include "mongo/db/catalog_raii.h"
#include "mongo/db/concurrency/locker.h"
#include "mongo/db/concurrency/write_conflict_exception.h"
#include "mongo/db/curop.h"
#include "mongo/db/db_raii.h"
#include "mongo/db/index_build_entry_helpers.h"
#include "mongo/db/op_observer.h"
#include "mongo/db/operation_context.h"
#include "mongo/db/repl/member_state.h"
#include "mongo/db/repl/replication_coordinator.h"
#include "mongo/db/repl/timestamp_block.h"
#include "mongo/db/s/collection_sharding_state.h"
#include "mongo/db/s/database_sharding_state.h"
#include "mongo/db/server_options.h"
#include "mongo/db/server_recovery.h"
#include "mongo/db/service_context.h"
#include "mongo/db/storage/durable_catalog.h"
#include "mongo/logv2/log.h"
#include "mongo/s/shard_key_pattern.h"
#include "mongo/util/assert_util.h"
#include "mongo/util/str.h"
namespace mongo {
using namespace indexbuildentryhelpers;
MONGO_FAIL_POINT_DEFINE(hangAfterIndexBuildFirstDrain);
MONGO_FAIL_POINT_DEFINE(hangAfterIndexBuildSecondDrain);
MONGO_FAIL_POINT_DEFINE(hangAfterIndexBuildDumpsInsertsFromBulk);
namespace {
constexpr StringData kCreateIndexesFieldName = "createIndexes"_sd;
constexpr StringData kCommitIndexBuildFieldName = "commitIndexBuild"_sd;
constexpr StringData kAbortIndexBuildFieldName = "abortIndexBuild"_sd;
constexpr StringData kIndexesFieldName = "indexes"_sd;
constexpr StringData kKeyFieldName = "key"_sd;
constexpr StringData kUniqueFieldName = "unique"_sd;
/**
* Checks if unique index specification is compatible with sharding configuration.
*/
void checkShardKeyRestrictions(OperationContext* opCtx,
const NamespaceString& nss,
const BSONObj& newIdxKey) {
UncommittedCollections::get(opCtx).invariantHasExclusiveAccessToCollection(opCtx, nss);
const auto metadata = CollectionShardingState::get(opCtx, nss)->getCurrentMetadata();
if (!metadata->isSharded())
return;
const ShardKeyPattern shardKeyPattern(metadata->getKeyPattern());
uassert(ErrorCodes::CannotCreateIndex,
str::stream() << "cannot create unique index over " << newIdxKey
<< " with shard key pattern " << shardKeyPattern.toBSON(),
shardKeyPattern.isUniqueIndexCompatible(newIdxKey));
}
/**
* Returns true if we should build the indexes an empty collection using the IndexCatalog and
* bypass the index build registration.
*/
bool shouldBuildIndexesOnEmptyCollectionSinglePhased(OperationContext* opCtx,
Collection* collection) {
const auto& nss = collection->ns();
invariant(opCtx->lockState()->isCollectionLockedForMode(nss, MODE_X), str::stream() << nss);
auto replCoord = repl::ReplicationCoordinator::get(opCtx);
// Check whether the replica set member's config has {buildIndexes:false} set, which means
// we are not allowed to build non-_id indexes on this server.
if (!replCoord->buildsIndexes()) {
return false;
}
// We use the fast count information, through Collection::numRecords(), to determine if the
// collection is empty. However, this information is either unavailable or inaccurate when the
// node is in certain replication states, such as recovery or rollback. In these cases, we
// have to build the index by scanning the collection.
auto memberState = replCoord->getMemberState();
if (memberState.rollback()) {
return false;
}
if (inReplicationRecovery(opCtx->getServiceContext())) {
return false;
}
// Now, it's fine to trust Collection::isEmpty().
// Fast counts are prone to both false positives and false negatives on unclean shutdowns. False
// negatives can cause to skip index building. And, false positives can cause mismatch in number
// of index entries among the nodes in the replica set. So, verify the collection is really
// empty by opening the WT cursor and reading the first document.
return collection->isEmpty(opCtx);
}
/*
* Determines whether to skip the index build state transition check.
* Index builder not using ReplIndexBuildState::waitForNextAction to signal primary and secondaries
* to commit or abort signal will violate index build state transition i.e, they can move from
* prepareAbort to Committed and from Committed to prepareAbort. So, we should skip state transition
* verification. Otherwise, we would invariant.
*/
bool shouldSkipIndexBuildStateTransitionCheck(OperationContext* opCtx,
IndexBuildProtocol protocol) {
const auto replCoord = repl::ReplicationCoordinator::get(opCtx);
if (replCoord->getSettings().usingReplSets() && protocol == IndexBuildProtocol::kTwoPhase) {
return false;
}
return true;
}
/**
* Signal downstream secondary nodes to commit index build.
*/
void onCommitIndexBuild(OperationContext* opCtx,
const NamespaceString& nss,
ReplIndexBuildState& replState,
bool replSetAndNotPrimaryAtStart) {
const auto& buildUUID = replState.buildUUID;
invariant(IndexBuildProtocol::kTwoPhase == replState.protocol,
str::stream() << "onCommitIndexBuild: " << buildUUID);
invariant(opCtx->lockState()->isWriteLocked(),
str::stream() << "onCommitIndexBuild: " << buildUUID);
auto opObserver = opCtx->getServiceContext()->getOpObserver();
const auto& collUUID = replState.collectionUUID;
const auto& indexSpecs = replState.indexSpecs;
auto fromMigrate = false;
auto skipCheck = shouldSkipIndexBuildStateTransitionCheck(opCtx, replState.protocol);
{
stdx::unique_lock<Latch> lk(replState.mutex);
replState.indexBuildState.setState(IndexBuildState::kCommitted, skipCheck);
}
// Since two phase index builds are allowed to survive replication state transitions, we should
// check if the node is currently a primary before attempting to write to the oplog.
auto replCoord = repl::ReplicationCoordinator::get(opCtx);
if (!replCoord->getSettings().usingReplSets()) {
return;
}
if (!replCoord->canAcceptWritesFor(opCtx, nss)) {
invariant(!opCtx->recoveryUnit()->getCommitTimestamp().isNull(),
str::stream() << "commitIndexBuild: " << buildUUID);
return;
}
opObserver->onCommitIndexBuild(opCtx, nss, collUUID, buildUUID, indexSpecs, fromMigrate);
}
/**
* Signal downstream secondary nodes to abort index build.
*/
void onAbortIndexBuild(OperationContext* opCtx,
const NamespaceString& nss,
ReplIndexBuildState& replState,
const Status& cause) {
if (!serverGlobalParams.featureCompatibility.isVersionInitialized()) {
return;
}
if (serverGlobalParams.featureCompatibility.getVersion() !=
ServerGlobalParams::FeatureCompatibility::Version::kFullyUpgradedTo44) {
return;
}
invariant(opCtx->lockState()->isWriteLocked(), replState.buildUUID.toString());
auto opObserver = opCtx->getServiceContext()->getOpObserver();
auto collUUID = replState.collectionUUID;
auto fromMigrate = false;
auto skipCheck = shouldSkipIndexBuildStateTransitionCheck(opCtx, replState.protocol);
{
stdx::unique_lock<Latch> lk(replState.mutex);
replState.indexBuildState.setState(IndexBuildState::kAborted, skipCheck);
}
opObserver->onAbortIndexBuild(
opCtx, nss, collUUID, replState.buildUUID, replState.indexSpecs, cause, fromMigrate);
}
/**
* Aborts the index build identified by the provided 'replIndexBuildState'.
* It gets called by drop database/collection/index command.
*/
void abortIndexBuild(WithLock lk,
OperationContext* opCtx,
IndexBuildsManager* indexBuildsManager,
std::shared_ptr<ReplIndexBuildState> replIndexBuildState,
const std::string& reason) {
auto protocol = replIndexBuildState->protocol;
stdx::unique_lock<Latch> replStateLock(replIndexBuildState->mutex);
if (protocol == IndexBuildProtocol::kTwoPhase &&
replIndexBuildState->waitForNextAction->getFuture().isReady()) {
const auto nextAction = replIndexBuildState->waitForNextAction->getFuture().get();
invariant(nextAction == IndexBuildAction::kCommitQuorumSatisfied ||
nextAction == IndexBuildAction::kPrimaryAbort);
// Index build coordinator already received a signal to commit or abort. So, it's ok
// to return and wait for the index build to complete. The index build coordinator
// will not perform the signaled action (i.e, will not commit or abort the index build)
// only when the node steps down. When the node steps down, the caller of this function,
// drop commands (user operation) will also get interrupted. So, we no longer need to
// abort the index build on step down.
return;
}
auto skipCheck = shouldSkipIndexBuildStateTransitionCheck(opCtx, replIndexBuildState->protocol);
// Set the state on replIndexBuildState and indexBuildsManager. And, then signal the value. It's
// important we do all these 3 things in a critical section by holding mutex lock.
replIndexBuildState->indexBuildState.setState(
IndexBuildState::kPrepareAbort, skipCheck, boost::none, reason);
indexBuildsManager->abortIndexBuild(replIndexBuildState->buildUUID, reason);
if (protocol == IndexBuildProtocol::kTwoPhase) {
// Only for 2 phase we need to use signaling logic.
// Promise can be set only once.
replIndexBuildState->waitForNextAction->emplaceValue(IndexBuildAction::kPrimaryAbort);
}
}
/**
* We do not need synchronization with step up and step down. Dropping the RSTL is important because
* otherwise if we held the RSTL it would create deadlocks with prepared transactions on step up and
* step down. A deadlock could result if the index build was attempting to acquire a Collection S
* or X lock while a prepared transaction held a Collection IX lock, and a step down was waiting to
* acquire the RSTL in mode X.
*/
void unlockRSTLForIndexCleanup(OperationContext* opCtx) {
opCtx->lockState()->unlockRSTLforPrepare();
invariant(!opCtx->lockState()->isRSTLLocked());
}
/**
* Logs the index build failure error in a standard format.
*/
void logFailure(Status status,
const NamespaceString& nss,
std::shared_ptr<ReplIndexBuildState> replState) {
LOGV2(
20649,
"Index build failed: {replState_buildUUID}: {nss} ( {replState_collectionUUID} ): {status}",
"replState_buildUUID"_attr = replState->buildUUID,
"nss"_attr = nss,
"replState_collectionUUID"_attr = replState->collectionUUID,
"status"_attr = status);
}
/**
* Iterates over index builds with the provided function.
*/
void forEachIndexBuild(
const std::vector<std::shared_ptr<ReplIndexBuildState>>& indexBuilds,
StringData logPrefix,
std::function<void(std::shared_ptr<ReplIndexBuildState> replState)> onIndexBuild) {
if (indexBuilds.empty()) {
return;
}
LOGV2(20650,
"{logPrefix}active index builds: {indexBuilds_size}",
"logPrefix"_attr = logPrefix,
"indexBuilds_size"_attr = indexBuilds.size());
for (auto replState : indexBuilds) {
std::string indexNamesStr;
str::joinStringDelim(replState->indexNames, &indexNamesStr, ',');
LOGV2(20651,
"{logPrefix}{replState_buildUUID}: collection: {replState_collectionUUID}; indexes: "
"{replState_indexNames_size} [{indexNamesStr}]; method: "
"{IndexBuildProtocol_kTwoPhase_replState_protocol_two_phase_single_phase}",
"logPrefix"_attr = logPrefix,
"replState_buildUUID"_attr = replState->buildUUID,
"replState_collectionUUID"_attr = replState->collectionUUID,
"replState_indexNames_size"_attr = replState->indexNames.size(),
"indexNamesStr"_attr = indexNamesStr,
"IndexBuildProtocol_kTwoPhase_replState_protocol_two_phase_single_phase"_attr =
(IndexBuildProtocol::kTwoPhase == replState->protocol ? "two phase"
: "single phase"));
onIndexBuild(replState);
}
}
/**
* Updates currentOp for commitIndexBuild or abortIndexBuild.
*/
void updateCurOpForCommitOrAbort(OperationContext* opCtx, StringData fieldName, UUID buildUUID) {
BSONObjBuilder builder;
buildUUID.appendToBuilder(&builder, fieldName);
stdx::unique_lock<Client> lk(*opCtx->getClient());
auto curOp = CurOp::get(opCtx);
builder.appendElementsUnique(curOp->opDescription());
auto opDescObj = builder.obj();
curOp->setLogicalOp_inlock(LogicalOp::opCommand);
curOp->setOpDescription_inlock(opDescObj);
curOp->ensureStarted();
}
} // namespace
const auto getIndexBuildsCoord =
ServiceContext::declareDecoration<std::unique_ptr<IndexBuildsCoordinator>>();
void IndexBuildsCoordinator::set(ServiceContext* serviceContext,
std::unique_ptr<IndexBuildsCoordinator> ibc) {
auto& indexBuildsCoordinator = getIndexBuildsCoord(serviceContext);
invariant(!indexBuildsCoordinator);
indexBuildsCoordinator = std::move(ibc);
}
IndexBuildsCoordinator* IndexBuildsCoordinator::get(ServiceContext* serviceContext) {
auto& indexBuildsCoordinator = getIndexBuildsCoord(serviceContext);
invariant(indexBuildsCoordinator);
return indexBuildsCoordinator.get();
}
IndexBuildsCoordinator* IndexBuildsCoordinator::get(OperationContext* OperationContext) {
return get(OperationContext->getServiceContext());
}
IndexBuildsCoordinator::~IndexBuildsCoordinator() {
invariant(_databaseIndexBuilds.empty());
invariant(_collectionIndexBuilds.empty());
}
bool IndexBuildsCoordinator::supportsTwoPhaseIndexBuild() {
auto storageEngine = getGlobalServiceContext()->getStorageEngine();
return storageEngine->supportsTwoPhaseIndexBuild();
}
StatusWith<std::pair<long long, long long>> IndexBuildsCoordinator::rebuildIndexesForRecovery(
OperationContext* opCtx,
const NamespaceString& nss,
const std::vector<BSONObj>& specs,
const UUID& buildUUID,
RepairData repair) {
const auto protocol = IndexBuildProtocol::kSinglePhase;
auto status = _startIndexBuildForRecovery(opCtx, nss, specs, buildUUID, protocol);
if (!status.isOK()) {
return status;
}
auto& collectionCatalog = CollectionCatalog::get(getGlobalServiceContext());
Collection* collection = collectionCatalog.lookupCollectionByNamespace(opCtx, nss);
// Complete the index build.
return _runIndexRebuildForRecovery(opCtx, collection, buildUUID, repair);
}
Status IndexBuildsCoordinator::_startIndexBuildForRecovery(OperationContext* opCtx,
const NamespaceString& nss,
const std::vector<BSONObj>& specs,
const UUID& buildUUID,
IndexBuildProtocol protocol) {
invariant(opCtx->lockState()->isCollectionLockedForMode(nss, MODE_X));
std::vector<std::string> indexNames;
for (auto& spec : specs) {
std::string name = spec.getStringField(IndexDescriptor::kIndexNameFieldName);
if (name.empty()) {
return Status(ErrorCodes::CannotCreateIndex,
str::stream()
<< "Cannot create an index for a spec '" << spec
<< "' without a non-empty string value for the 'name' field");
}
indexNames.push_back(name);
}
auto& collectionCatalog = CollectionCatalog::get(getGlobalServiceContext());
Collection* collection = collectionCatalog.lookupCollectionByNamespace(opCtx, nss);
auto indexCatalog = collection->getIndexCatalog();
{
// These steps are combined into a single WUOW to ensure there are no commits without
// the indexes.
// 1) Drop all unfinished indexes.
// 2) Start, but do not complete the index build process.
WriteUnitOfWork wuow(opCtx);
for (size_t i = 0; i < indexNames.size(); i++) {
bool includeUnfinished = false;
auto descriptor =
indexCatalog->findIndexByName(opCtx, indexNames[i], includeUnfinished);
if (descriptor) {
Status s = indexCatalog->dropIndex(opCtx, descriptor);
if (!s.isOK()) {
return s;
}
continue;
}
// If the index is not present in the catalog, then we are trying to drop an already
// aborted index. This may happen when rollback-via-refetch restarts an index build
// after an abort has been rolled back.
if (!DurableCatalog::get(opCtx)->isIndexPresent(
opCtx, collection->getCatalogId(), indexNames[i])) {
LOGV2(20652,
"The index for build {buildUUID} was not found while trying to drop the "
"index during recovery: {indexNames_i}",
"buildUUID"_attr = buildUUID,
"indexNames_i"_attr = indexNames[i]);
continue;
}
const auto durableBuildUUID = DurableCatalog::get(opCtx)->getIndexBuildUUID(
opCtx, collection->getCatalogId(), indexNames[i]);
// A build UUID is present if and only if we are rebuilding a two-phase build.
invariant((protocol == IndexBuildProtocol::kTwoPhase) ==
durableBuildUUID.is_initialized());
// When a buildUUID is present, it must match the build UUID parameter to this
// function.
invariant(!durableBuildUUID || *durableBuildUUID == buildUUID,
str::stream() << "durable build UUID: " << durableBuildUUID
<< "buildUUID: " << buildUUID);
// If the unfinished index is in the IndexCatalog, drop it through there, otherwise drop
// it from the DurableCatalog. Rollback-via-refetch does not clear any in-memory state,
// so we should do it manually here.
includeUnfinished = true;
descriptor = indexCatalog->findIndexByName(opCtx, indexNames[i], includeUnfinished);
if (descriptor) {
Status s = indexCatalog->dropUnfinishedIndex(opCtx, descriptor);
if (!s.isOK()) {
return s;
}
} else {
Status status = DurableCatalog::get(opCtx)->removeIndex(
opCtx, collection->getCatalogId(), indexNames[i]);
if (!status.isOK()) {
return status;
}
}
}
// We need to initialize the collection to rebuild the indexes. The collection may already
// be initialized when rebuilding indexes with rollback-via-refetch.
if (!collection->isInitialized()) {
collection->init(opCtx);
}
auto dbName = nss.db().toString();
auto replIndexBuildState =
std::make_shared<ReplIndexBuildState>(buildUUID,
collection->uuid(),
dbName,
specs,
protocol,
/*commitQuorum=*/boost::none);
Status status = [&]() {
stdx::unique_lock<Latch> lk(_mutex);
return _registerIndexBuild(lk, replIndexBuildState);
}();
if (!status.isOK()) {
return status;
}
IndexBuildsManager::SetupOptions options;
status = _indexBuildsManager.setUpIndexBuild(
opCtx, collection, specs, buildUUID, MultiIndexBlock::kNoopOnInitFn, options);
if (!status.isOK()) {
// An index build failure during recovery is fatal.
logFailure(status, nss, replIndexBuildState);
fassertNoTrace(51086, status);
}
wuow.commit();
}
return Status::OK();
}
std::string IndexBuildsCoordinator::_indexBuildActionToString(IndexBuildAction action) {
if (action == IndexBuildAction::kNoAction) {
return "No action";
} else if (action == IndexBuildAction::kOplogCommit) {
return "Oplog commit";
} else if (action == IndexBuildAction::kOplogAbort) {
return "Oplog abort";
} else if (action == IndexBuildAction::kRollbackAbort) {
return "Rollback abort";
} else if (action == IndexBuildAction::kPrimaryAbort) {
return "Primary abort";
} else if (action == IndexBuildAction::kCommitQuorumSatisfied) {
return "Commit quorum Satisfied";
}
MONGO_UNREACHABLE;
}
void IndexBuildsCoordinator::waitForAllIndexBuildsToStopForShutdown() {
stdx::unique_lock<Latch> lk(_mutex);
// All index builds should have been signaled to stop via the ServiceContext.
// Wait for all the index builds to stop.
for (auto& dbIt : _databaseIndexBuilds) {
// Take a shared ptr, rather than accessing the Tracker through the map's iterator, so that
// the object does not destruct while we are waiting, causing a use-after-free memory error.
auto dbIndexBuildsSharedPtr = dbIt.second;
dbIndexBuildsSharedPtr->waitUntilNoIndexBuildsRemain(lk);
}
}
std::vector<UUID> IndexBuildsCoordinator::_abortCollectionIndexBuilds(stdx::unique_lock<Latch>& lk,
OperationContext* opCtx,
const UUID& collectionUUID,
const std::string& reason,
bool shouldWait) {
auto collIndexBuildsIt = _collectionIndexBuilds.find(collectionUUID);
if (collIndexBuildsIt == _collectionIndexBuilds.end()) {
return {};
}
LOGV2(23879,
"About to abort all index builders on collection with UUID: {collectionUUID}",
"collectionUUID"_attr = collectionUUID);
std::vector<UUID> buildUUIDs = collIndexBuildsIt->second->getIndexBuildUUIDs(lk);
collIndexBuildsIt->second->runOperationOnAllBuilds(
lk, opCtx, &_indexBuildsManager, abortIndexBuild, reason);
if (!shouldWait) {
return buildUUIDs;
}
// Take a shared ptr, rather than accessing the Tracker through the map's iterator, so that the
// object does not destruct while we are waiting, causing a use-after-free memory error.
auto collIndexBuildsSharedPtr = collIndexBuildsIt->second;
collIndexBuildsSharedPtr->waitUntilNoIndexBuildsRemain(lk);
return buildUUIDs;
}
void IndexBuildsCoordinator::abortCollectionIndexBuilds(OperationContext* opCtx,
const UUID& collectionUUID,
const std::string& reason) {
stdx::unique_lock<Latch> lk(_mutex);
const bool shouldWait = true;
_abortCollectionIndexBuilds(lk, opCtx, collectionUUID, reason, shouldWait);
}
std::vector<UUID> IndexBuildsCoordinator::abortCollectionIndexBuildsNoWait(
OperationContext* opCtx, const UUID& collectionUUID, const std::string& reason) {
stdx::unique_lock<Latch> lk(_mutex);
const bool shouldWait = false;
return _abortCollectionIndexBuilds(lk, opCtx, collectionUUID, reason, shouldWait);
}
void IndexBuildsCoordinator::_abortDatabaseIndexBuilds(stdx::unique_lock<Latch>& lk,
OperationContext* opCtx,
const StringData& db,
const std::string& reason,
bool shouldWait) {
auto dbIndexBuilds = _databaseIndexBuilds[db];
if (!dbIndexBuilds) {
return;
}
LOGV2(4612302,
"About to abort all index builders running for collections in the given database",
"database"_attr = db);
dbIndexBuilds->runOperationOnAllBuilds(
lk, opCtx, &_indexBuildsManager, abortIndexBuild, reason);
if (!shouldWait) {
return;
}
// 'dbIndexBuilds' is a shared ptr, so it can be safely waited upon without destructing before
// waitUntilNoIndexBuildsRemain() returns, which would cause a use-after-free memory error.
dbIndexBuilds->waitUntilNoIndexBuildsRemain(lk);
}
void IndexBuildsCoordinator::abortDatabaseIndexBuilds(OperationContext* opCtx,
StringData db,
const std::string& reason) {
stdx::unique_lock<Latch> lk(_mutex);
const bool shouldWait = true;
_abortDatabaseIndexBuilds(lk, opCtx, db, reason, shouldWait);
}
void IndexBuildsCoordinator::abortDatabaseIndexBuildsNoWait(OperationContext* opCtx,
StringData db,
const std::string& reason) {
stdx::unique_lock<Latch> lk(_mutex);
const bool shouldWait = false;
_abortDatabaseIndexBuilds(lk, opCtx, db, reason, shouldWait);
}
namespace {
NamespaceString getNsFromUUID(OperationContext* opCtx, const UUID& uuid) {
auto& catalog = CollectionCatalog::get(opCtx);
auto nss = catalog.lookupNSSByUUID(opCtx, uuid);
uassert(ErrorCodes::NamespaceNotFound, "No namespace with UUID " + uuid.toString(), nss);
return *nss;
}
} // namespace
void IndexBuildsCoordinator::applyStartIndexBuild(OperationContext* opCtx,
const IndexBuildOplogEntry& oplogEntry) {
const auto collUUID = oplogEntry.collUUID;
const auto nss = getNsFromUUID(opCtx, collUUID);
IndexBuildsCoordinator::IndexBuildOptions indexBuildOptions;
invariant(oplogEntry.commitQuorum);
indexBuildOptions.commitQuorum = oplogEntry.commitQuorum.get();
indexBuildOptions.replSetAndNotPrimaryAtStart = true;
auto indexBuildsCoord = IndexBuildsCoordinator::get(opCtx);
uassertStatusOK(
indexBuildsCoord
->startIndexBuild(opCtx,
nss.db().toString(),
collUUID,
oplogEntry.indexSpecs,
oplogEntry.buildUUID,
/* This oplog entry is only replicated for two-phase index builds */
IndexBuildProtocol::kTwoPhase,
indexBuildOptions)
.getStatus());
}
void IndexBuildsCoordinator::applyCommitIndexBuild(OperationContext* opCtx,
const IndexBuildOplogEntry& oplogEntry) {
const auto collUUID = oplogEntry.collUUID;
const auto nss = getNsFromUUID(opCtx, collUUID);
const auto& buildUUID = oplogEntry.buildUUID;
updateCurOpForCommitOrAbort(opCtx, kCommitIndexBuildFieldName, buildUUID);
uassert(31417,
str::stream()
<< "No commit timestamp set while applying commitIndexBuild operation. Build UUID: "
<< buildUUID,
!opCtx->recoveryUnit()->getCommitTimestamp().isNull());
auto indexBuildsCoord = IndexBuildsCoordinator::get(opCtx);
auto swReplState = indexBuildsCoord->_getIndexBuild(buildUUID);
if (swReplState == ErrorCodes::NoSuchKey) {
// If the index build was not found, we must restart the build. For some reason the index
// build has already been aborted on this node. This is possible in certain infrequent race
// conditions with stepdown, shutdown, and user interruption.
// Also, it can be because, when this node was previously in
// initial sync state and this index build was in progress on sync source. And, initial sync
// does not start the in progress index builds.
LOGV2(20653,
"Could not find an active index build with UUID {buildUUID} while processing a "
"commitIndexBuild oplog entry. Restarting the index build on "
"collection {nss} ({collUUID}) at optime {opCtx_recoveryUnit_getCommitTimestamp}",
"buildUUID"_attr = buildUUID,
"nss"_attr = nss,
"collUUID"_attr = collUUID,
"opCtx_recoveryUnit_getCommitTimestamp"_attr =
opCtx->recoveryUnit()->getCommitTimestamp());
IndexBuildsCoordinator::IndexBuildOptions indexBuildOptions;
indexBuildOptions.replSetAndNotPrimaryAtStart = true;
// It's ok to set the commitQuorum value as 0, as we have already received the
// commitIndexBuild oplog entry. No way in future, this index build will be coordinated by
// this node.
indexBuildOptions.commitQuorum = CommitQuorumOptions(0);
// This spawns a new thread and returns immediately.
auto fut = uassertStatusOK(indexBuildsCoord->startIndexBuild(
opCtx,
nss.db().toString(),
collUUID,
oplogEntry.indexSpecs,
buildUUID,
/* This oplog entry is only replicated for two-phase index builds */
IndexBuildProtocol::kTwoPhase,
indexBuildOptions));
// In certain optimized cases that return early, the future will already be set, and the
// index build will already have been torn-down. Any subsequent calls to look up the index
// build will fail immediately without any error information.
if (fut.isReady()) {
// Throws if there were errors building the index.
fut.get();
return;
}
}
auto replState = uassertStatusOK(indexBuildsCoord->_getIndexBuild(buildUUID));
while (true) {
stdx::unique_lock<Latch> lk(replState->mutex);
if (replState->waitForNextAction->getFuture().isReady()) {
// If future wait is made uninterruptible, then the shutdown can stuck behind
// oplog applier if the indexBuildCoordinator thread died after interruption on
// shutdown. And, commitIndexBuild oplog entry will stuck waiting for reset of the
// promise.
const auto nextAction = replState->waitForNextAction->getFuture().get(opCtx);
invariant(nextAction == IndexBuildAction::kCommitQuorumSatisfied);
// Retry until the current promise result is consumed by the index builder thread and
// a new empty promise got created by the indexBuildscoordinator thread.
// Don't hammer it.
sleepmillis(1);
continue;
}
auto skipCheck = shouldSkipIndexBuildStateTransitionCheck(opCtx, replState->protocol);
replState->indexBuildState.setState(IndexBuildState::kPrepareCommit,
skipCheck,
opCtx->recoveryUnit()->getCommitTimestamp());
// Promise can be set only once.
// We can't skip signaling here if a signal is already set because the previous commit or
// abort signal might have been sent to handle for primary case.
replState->waitForNextAction->emplaceValue(IndexBuildAction::kOplogCommit);
break;
}
auto fut = replState->sharedPromise.getFuture();
LOGV2(20654,
"Index build joined after commit: {buildUUID}: {fut_waitNoThrow_opCtx}",
"buildUUID"_attr = buildUUID,
"fut_waitNoThrow_opCtx"_attr = fut.waitNoThrow(opCtx));
// Throws if there was an error building the index.
fut.get();
}
void IndexBuildsCoordinator::applyAbortIndexBuild(OperationContext* opCtx,
const IndexBuildOplogEntry& oplogEntry) {
const auto collUUID = oplogEntry.collUUID;
const auto nss = getNsFromUUID(opCtx, collUUID);
const auto& buildUUID = oplogEntry.buildUUID;
updateCurOpForCommitOrAbort(opCtx, kCommitIndexBuildFieldName, buildUUID);
invariant(oplogEntry.cause);
uassert(31420,
str::stream()
<< "No commit timestamp set while applying abortIndexBuild operation. Build UUID: "
<< buildUUID,
!opCtx->recoveryUnit()->getCommitTimestamp().isNull());
std::string abortReason(str::stream()
<< "abortIndexBuild oplog entry encountered: " << *oplogEntry.cause);
auto indexBuildsCoord = IndexBuildsCoordinator::get(opCtx);
indexBuildsCoord->abortIndexBuildByBuildUUID(opCtx,
buildUUID,
IndexBuildAction::kOplogAbort,
opCtx->recoveryUnit()->getCommitTimestamp(),
abortReason);
}
void IndexBuildsCoordinator::abortIndexBuildOnError(OperationContext* opCtx,
const UUID& buildUUID,
Status abortStatus) {
// Use a null abort timestamp because the index build will generate a ghost timestamp
// for the single-phase build on cleanup.
std::string abortReason(str::stream() << "Index build interrupted: " << buildUUID << ": "
<< abortStatus.toString());
abortIndexBuildByBuildUUIDNoWait(
opCtx, buildUUID, IndexBuildAction::kPrimaryAbort, boost::none, abortReason);
}
void IndexBuildsCoordinator::abortIndexBuildByBuildUUID(OperationContext* opCtx,
const UUID& buildUUID,
IndexBuildAction signalAction,
boost::optional<Timestamp> abortTimestamp,
boost::optional<std::string> reason) {
if (!abortIndexBuildByBuildUUIDNoWait(opCtx, buildUUID, signalAction, abortTimestamp, reason)) {
return;
}
auto replState =
invariant(_getIndexBuild(buildUUID),
str::stream() << "Abort timestamp: "
<< abortTimestamp.get_value_or(Timestamp()).toString());
auto fut = replState->sharedPromise.getFuture();
LOGV2(20655,
"Index build joined after abort: {buildUUID}: {fut_waitNoThrow}",
"buildUUID"_attr = buildUUID,
"fut_waitNoThrow"_attr = fut.waitNoThrow());
}
boost::optional<UUID> IndexBuildsCoordinator::abortIndexBuildByIndexNamesNoWait(
OperationContext* opCtx,
const UUID& collectionUUID,
const std::vector<std::string>& indexNames,
boost::optional<std::string> reason) {
boost::optional<UUID> buildUUID;
auto indexBuilds = _getIndexBuilds();
auto onIndexBuild = [&](std::shared_ptr<ReplIndexBuildState> replState) {
if (replState->collectionUUID != collectionUUID) {
return;
}
bool matchedBuilder = std::is_permutation(indexNames.begin(),
indexNames.end(),
replState->indexNames.begin(),
replState->indexNames.end());
if (!matchedBuilder) {
return;
}
LOGV2(23880,
"About to abort index builder: {replState_buildUUID} on collection: "
"{collectionUUID}. First index: {replState_indexNames_front}",
"replState_buildUUID"_attr = replState->buildUUID,
"collectionUUID"_attr = collectionUUID,
"replState_indexNames_front"_attr = replState->indexNames.front());
if (this->abortIndexBuildByBuildUUIDNoWait(opCtx,
replState->buildUUID,
IndexBuildAction::kPrimaryAbort,
boost::none,
reason)) {
buildUUID = replState->buildUUID;
}
};
forEachIndexBuild(indexBuilds,
"IndexBuildsCoordinator::abortIndexBuildByIndexNamesNoWait - "_sd,
onIndexBuild);
return buildUUID;
}
bool IndexBuildsCoordinator::hasIndexBuilder(OperationContext* opCtx,
const UUID& collectionUUID,
const std::vector<std::string>& indexNames) const {
bool foundIndexBuilder = false;
boost::optional<UUID> buildUUID;
auto indexBuilds = _getIndexBuilds();
auto onIndexBuild = [&](std::shared_ptr<ReplIndexBuildState> replState) {
if (replState->collectionUUID != collectionUUID) {
return;
}
bool matchedBuilder = std::is_permutation(indexNames.begin(),
indexNames.end(),
replState->indexNames.begin(),
replState->indexNames.end());
if (!matchedBuilder) {
return;
}
foundIndexBuilder = true;
};
forEachIndexBuild(indexBuilds, "IndexBuildsCoordinator::hasIndexBuilder - "_sd, onIndexBuild);
return foundIndexBuilder;
}
bool IndexBuildsCoordinator::abortIndexBuildByBuildUUIDNoWait(
OperationContext* opCtx,
const UUID& buildUUID,
IndexBuildAction signalAction,
boost::optional<Timestamp> abortTimestamp,
boost::optional<std::string> reason) {
// We need to avoid race between commit and abort index build.
while (true) {
// It is possible to receive an abort for a non-existent index build. Abort should always
// succeed, so suppress the error.
auto replStateResult = _getIndexBuild(buildUUID);
if (!replStateResult.isOK()) {
LOGV2(20656,
"ignoring error while aborting index build {buildUUID}: "
"{replStateResult_getStatus}",
"buildUUID"_attr = buildUUID,
"replStateResult_getStatus"_attr = replStateResult.getStatus());
return false;
}
auto replState = replStateResult.getValue();
auto protocol = replState->protocol;
stdx::unique_lock<Latch> lk(replState->mutex);
if (protocol == IndexBuildProtocol::kTwoPhase &&
replState->waitForNextAction->getFuture().isReady()) {
const auto nextAction = replState->waitForNextAction->getFuture().get(opCtx);
invariant(nextAction == IndexBuildAction::kCommitQuorumSatisfied ||
nextAction == IndexBuildAction::kPrimaryAbort);
// Index build coordinator already received a signal to commit or abort. So, it's ok
// to return and wait for the index build to complete if we are trying to signal
// 'kPrimaryAbort'. The index build coordinator will not perform the signaled action
// (i.e, will not commit or abort the index build) only when the node steps down. When
// the node steps down, the caller of this function, dropIndexes/createIndexes command
// (user operation) will also get interrupted. So, we no longer need to abort the index
// build on step down.
//
// Currently dropIndexes command calls this function with the
// collection lock held in IX mode, So, there are possibilities, we might block the
// index build from completing, leading to 3 way deadlocks involving step down,
// dropIndexes command, IndexBuildCoordinator thread.
if (signalAction == IndexBuildAction::kPrimaryAbort)
return true;
// Retry until the current promise result is consumed by the index builder thread and
// a new empty promise got created by the indexBuildscoordinator thread. Or, until the
// index build got torn down after index build commit.
// Don't hammer it.
sleepmillis(1);
continue;
}
auto skipCheck = shouldSkipIndexBuildStateTransitionCheck(opCtx, replState->protocol);
// Set the state on replState and _indexBuildsManager. And, then signal the value. It's
// important we do all these 3 things in a critical section by holding mutex lock.
replState->indexBuildState.setState(
IndexBuildState::kPrepareAbort, skipCheck, abortTimestamp, reason);
_indexBuildsManager.abortIndexBuild(buildUUID, reason.get_value_or(""));
if (protocol == IndexBuildProtocol::kTwoPhase) {
// Only for 2 phase we need to use signaling logic.
// Promise can be set only once.
replState->waitForNextAction->emplaceValue(signalAction);
}
break;
}
return true;
}
/**
* Returns true if index specs include any unique indexes. Due to uniqueness constraints set up at
* the start of the index build, we are not able to support failing over a two phase index build on
* a unique index to a new primary on stepdown.
*/
namespace {
// TODO(SERVER-44654): remove when unique indexes support failover
bool containsUniqueIndexes(const std::vector<BSONObj>& specs) {
for (const auto& spec : specs) {
if (spec["unique"].trueValue()) {
return true;
}
}
return false;
}
} // namespace
std::size_t IndexBuildsCoordinator::getActiveIndexBuildCount(OperationContext* opCtx) {
auto indexBuilds = _getIndexBuilds();
// We use forEachIndexBuild() to log basic details on the current index builds and don't intend
// to modify any of the index builds, hence the no-op.
auto onIndexBuild = [](std::shared_ptr<ReplIndexBuildState> replState) {};
forEachIndexBuild(indexBuilds, "index build still running: "_sd, onIndexBuild);
return indexBuilds.size();
}
void IndexBuildsCoordinator::onStepUp(OperationContext* opCtx) {
LOGV2(20657, "IndexBuildsCoordinator::onStepUp - this node is stepping up to primary");
// This would create an empty table even for FCV 4.2 to handle case where a primary node started
// with FCV 4.2, and then upgraded FCV 4.4.
ensureIndexBuildEntriesNamespaceExists(opCtx);
auto indexBuilds = _getIndexBuilds();
auto onIndexBuild = [this, opCtx](std::shared_ptr<ReplIndexBuildState> replState) {
if (IndexBuildProtocol::kTwoPhase != replState->protocol) {
return;
}
// TODO(SERVER-44654): re-enable failover support for unique indexes.