/
index_builds_coordinator.cpp
3182 lines (2763 loc) · 147 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.
*/
#include "mongo/db/index_builds_coordinator.h"
#include <boost/filesystem/operations.hpp>
#include <boost/iterator/transform_iterator.hpp>
#include <fmt/format.h>
#include "mongo/db/catalog/clustered_collection_util.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_raii.h"
#include "mongo/db/concurrency/exception_util.h"
#include "mongo/db/concurrency/lock_state.h"
#include "mongo/db/concurrency/replication_state_transition_lock_guard.h"
#include "mongo/db/curop.h"
#include "mongo/db/db_raii.h"
#include "mongo/db/dbhelpers.h"
#include "mongo/db/index/wildcard_key_generator.h"
#include "mongo/db/index_build_entry_helpers.h"
#include "mongo/db/op_observer/op_observer.h"
#include "mongo/db/operation_context.h"
#include "mongo/db/repl/cloner_utils.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/db/storage/encryption_hooks.h"
#include "mongo/db/storage/storage_util.h"
#include "mongo/db/storage/two_phase_index_build_knobs_gen.h"
#include "mongo/logv2/log.h"
#include "mongo/s/shard_key_pattern.h"
#include "mongo/util/assert_util.h"
#include "mongo/util/scoped_counter.h"
#include "mongo/util/str.h"
#include "mongo/util/testing_proctor.h"
#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kStorage
namespace mongo {
MONGO_FAIL_POINT_DEFINE(hangAfterIndexBuildFirstDrain);
MONGO_FAIL_POINT_DEFINE(hangAfterIndexBuildSecondDrain);
MONGO_FAIL_POINT_DEFINE(hangAfterIndexBuildDumpsInsertsFromBulk);
MONGO_FAIL_POINT_DEFINE(hangAfterInitializingIndexBuild);
MONGO_FAIL_POINT_DEFINE(hangBeforeCompletingAbort);
MONGO_FAIL_POINT_DEFINE(failIndexBuildOnCommit);
MONGO_FAIL_POINT_DEFINE(hangIndexBuildBeforeAbortCleanUp);
MONGO_FAIL_POINT_DEFINE(hangIndexBuildOnStepUp);
MONGO_FAIL_POINT_DEFINE(hangAfterSettingUpResumableIndexBuild);
MONGO_FAIL_POINT_DEFINE(hangIndexBuildBeforeCommit);
MONGO_FAIL_POINT_DEFINE(hangBeforeBuildingIndex);
MONGO_FAIL_POINT_DEFINE(hangBeforeBuildingIndexSecond);
MONGO_FAIL_POINT_DEFINE(hangIndexBuildBeforeWaitingUntilMajorityOpTime);
MONGO_FAIL_POINT_DEFINE(failSetUpResumeIndexBuild);
IndexBuildsCoordinator::IndexBuildsSSS::IndexBuildsSSS()
: ServerStatusSection("indexBuilds"),
registered(0),
scanCollection(0),
drainSideWritesTable(0),
drainSideWritesTablePreCommit(0),
waitForCommitQuorum(0),
drainSideWritesTableOnCommit(0),
processConstraintsViolatonTableOnCommit(0),
commit(0) {}
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;
constexpr StringData kPrepareUniqueFieldName = "prepareUnique"_sd;
/**
* Checks if unique index specification is compatible with sharding configuration.
*/
void checkShardKeyRestrictions(OperationContext* opCtx,
const NamespaceString& nss,
const BSONObj& newIdxKey) {
CollectionCatalog::get(opCtx)->invariantHasExclusiveAccessToCollection(opCtx, nss);
const auto collDesc = CollectionShardingState::assertCollectionLockedAndAcquire(opCtx, nss)
->getCollectionDescription(opCtx);
if (!collDesc.isSharded())
return;
const ShardKeyPattern shardKeyPattern(collDesc.getKeyPattern());
uassert(ErrorCodes::CannotCreateIndex,
str::stream() << "cannot create index with 'unique' or 'prepareUnique' option over "
<< newIdxKey << " with shard key pattern " << shardKeyPattern.toBSON(),
shardKeyPattern.isIndexUniquenessCompatible(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,
const CollectionPtr& collection,
IndexBuildProtocol protocol) {
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;
}
// Secondaries should not bypass index build registration (and _runIndexBuild()) for two phase
// index builds because they need to report index build progress to the primary per commit
// quorum.
if (IndexBuildProtocol::kTwoPhase == protocol && !replCoord->canAcceptWritesFor(opCtx, nss)) {
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);
}
/**
* Removes the index build from the config.system.indexBuilds collection after the primary has
* written the commitIndexBuild or abortIndexBuild oplog entry.
*/
void removeIndexBuildEntryAfterCommitOrAbort(OperationContext* opCtx,
const NamespaceStringOrUUID& dbAndUUID,
const CollectionPtr& indexBuildEntryCollection,
const ReplIndexBuildState& replState) {
if (IndexBuildProtocol::kSinglePhase == replState.protocol) {
return;
}
auto replCoord = repl::ReplicationCoordinator::get(opCtx);
if (!replCoord->canAcceptWritesFor(opCtx, dbAndUUID)) {
return;
}
if (replCoord->getSettings().shouldRecoverFromOplogAsStandalone()) {
// Writes to the 'config.system.indexBuilds' collection are replicated and the index entry
// will be removed when the delete oplog entry is replayed at a later time.
return;
}
if (replState.isSettingUp()) {
// The index build document is not written to config.system.indexBuilds collection yet.
return;
}
auto status = indexbuildentryhelpers::removeIndexBuildEntry(
opCtx, indexBuildEntryCollection, replState.buildUUID);
if (!status.isOK()) {
LOGV2_FATAL_NOTRACE(4763501,
"Failed to remove index build from system collection",
"buildUUID"_attr = replState.buildUUID,
"collectionUUID"_attr = replState.collectionUUID,
"db"_attr = replState.dbName,
"indexNames"_attr = replState.indexNames,
"indexSpecs"_attr = replState.indexSpecs,
"error"_attr = status);
}
}
/**
* Replicates a commitIndexBuild oplog entry for two-phase builds, which signals downstream
* secondary nodes to commit the index build.
*/
void onCommitIndexBuild(OperationContext* opCtx,
const NamespaceString& nss,
std::shared_ptr<ReplIndexBuildState> replState) {
const auto& buildUUID = replState->buildUUID;
replState->commit(opCtx);
if (IndexBuildProtocol::kSinglePhase == replState->protocol) {
return;
}
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;
// 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->canAcceptWritesFor(opCtx, nss)) {
invariant(!opCtx->recoveryUnit()->getCommitTimestamp().isNull(),
str::stream() << "commitIndexBuild: " << buildUUID);
return;
}
opObserver->onCommitIndexBuild(opCtx, nss, collUUID, buildUUID, indexSpecs, fromMigrate);
}
/**
* Replicates an abortIndexBuild oplog entry for two-phase builds, which signals downstream
* secondary nodes to abort the index build.
*/
void onAbortIndexBuild(OperationContext* opCtx,
const NamespaceString& nss,
ReplIndexBuildState& replState,
const Status& cause) {
if (IndexBuildProtocol::kTwoPhase != replState.protocol) {
return;
}
invariant(opCtx->lockState()->isWriteLocked(), replState.buildUUID.toString());
auto opObserver = opCtx->getServiceContext()->getOpObserver();
auto collUUID = replState.collectionUUID;
auto fromMigrate = false;
opObserver->onAbortIndexBuild(
opCtx, nss, collUUID, replState.buildUUID, replState.indexSpecs, cause, fromMigrate);
}
/**
* 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 unlockRSTL(OperationContext* opCtx) {
invariant(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",
"buildUUID"_attr = replState->buildUUID,
"collectionUUID"_attr = replState->collectionUUID,
logAttrs(nss),
"error"_attr = status);
}
/**
* Iterates over index builds with the provided function.
*/
void forEachIndexBuild(
const std::vector<std::shared_ptr<ReplIndexBuildState>>& indexBuilds,
StringData context,
std::function<void(std::shared_ptr<ReplIndexBuildState> replState)> onIndexBuild) {
if (indexBuilds.empty()) {
return;
}
auto indexBuildLogger = [](const auto& indexBuild) {
BSONObjBuilder builder;
builder.append("buildUUID"_sd, indexBuild->buildUUID.toBSON());
builder.append("collectionUUID"_sd, indexBuild->collectionUUID.toBSON());
BSONArrayBuilder names;
for (const auto& indexName : indexBuild->indexNames) {
names.append(indexName);
}
builder.append("indexNames"_sd, names.arr());
builder.append("protocol"_sd,
indexBuild->protocol == IndexBuildProtocol::kTwoPhase ? "two phase"_sd
: "single phase"_sd);
return builder.obj();
};
auto begin = boost::make_transform_iterator(indexBuilds.begin(), indexBuildLogger);
auto end = boost::make_transform_iterator(indexBuilds.end(), indexBuildLogger);
LOGV2(20650,
"Active index builds",
"context"_attr = context,
"builds"_attr = logv2::seqLog(begin, end));
if (onIndexBuild) {
for (const auto& indexBuild : indexBuilds) {
onIndexBuild(indexBuild);
}
}
}
/**
* 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();
}
/**
* Fetches the latest oplog entry's optime. Bypasses the oplog visibility rules.
*/
repl::OpTime getLatestOplogOpTime(OperationContext* opCtx) {
// Reset the snapshot so that it is ensured to see the latest oplog entries.
opCtx->recoveryUnit()->abandonSnapshot();
// Helpers::getLast will bypass the oplog visibility rules by doing a backwards collection
// scan.
BSONObj oplogEntryBSON;
// This operation does not perform any writes, but the index building code is sensitive to
// exceptions and we must protect it from unanticipated write conflicts from reads.
writeConflictRetry(
opCtx, "getLatestOplogOpTime", NamespaceString::kRsOplogNamespace.ns(), [&]() {
invariant(Helpers::getLast(opCtx, NamespaceString::kRsOplogNamespace, oplogEntryBSON));
});
auto optime = repl::OpTime::parseFromOplogEntry(oplogEntryBSON);
invariant(optime.isOK(),
str::stream() << "Found an invalid oplog entry: " << oplogEntryBSON
<< ", error: " << optime.getStatus());
return optime.getValue();
}
/**
* Returns true if the index build is resumable.
*/
bool isIndexBuildResumable(OperationContext* opCtx,
const ReplIndexBuildState& replState,
const IndexBuildsCoordinator::IndexBuildOptions& indexBuildOptions) {
if (replState.protocol != IndexBuildProtocol::kTwoPhase) {
return false;
}
if (indexBuildOptions.applicationMode != IndexBuildsCoordinator::ApplicationMode::kNormal) {
return false;
}
// This check may be unnecessary due to current criteria for resumable index build support in
// storage engine.
if (!serverGlobalParams.enableMajorityReadConcern) {
return false;
}
// The last optime could be null if the node is in initial sync while building the index.
// This check may be redundant with the 'applicationMode' check and the replication requirement
// for two phase index builds.
auto replCoord = repl::ReplicationCoordinator::get(opCtx);
if (replCoord->getReplicationMode() == repl::ReplicationCoordinator::modeNone) {
return false;
}
// When we are applying a startIndexBuild oplog entry during the oplog application phase of
// startup recovery, the last optime here derived from the local oplog may not be a valid
// optime to wait on for the majority commit point since the rest of the replica set may
// be on a different branch of history.
if (inReplicationRecovery(opCtx->getServiceContext())) {
LOGV2(5039100,
"Index build: in replication recovery. Not waiting for last optime before "
"interceptors to be majority committed",
"buildUUID"_attr = replState.buildUUID);
return false;
}
if (!opCtx->getServiceContext()->getStorageEngine()->supportsResumableIndexBuilds()) {
return false;
}
// Only index builds with the default "all-voters" commit quorum running on voting nodes should
// be resumable. A node that cannot contribute to the commit quorum should not be waiting for
// the majority commit point when trying to commit the index build.
// IndexBuildsOptions::commitQuorum will be set if we are primary. Otherwise, we have to check
// the config.system.indexBuilds collection.
if (indexBuildOptions.commitQuorum) {
if (CommitQuorumOptions::kVotingMembers != indexBuildOptions.commitQuorum->mode) {
return false;
}
} else {
// The commit quorum may be updated using the setIndexBuildCommitQuorum command, so we will
// rely on the deadline to unblock ourselves from the majority wait if the commit quorum is
// no longer "all-voters".
auto swCommitQuorum = indexbuildentryhelpers::getCommitQuorum(opCtx, replState.buildUUID);
if (!swCommitQuorum.isOK()) {
LOGV2(5044600,
"Index build: cannot read commit quorum from config db, will not be resumable",
"buildUUID"_attr = replState.buildUUID,
"error"_attr = swCommitQuorum.getStatus());
return false;
}
auto commitQuorum = swCommitQuorum.getValue();
if (CommitQuorumOptions::kVotingMembers != commitQuorum.mode) {
return false;
}
}
// Ensure that this node is a voting member in the replica set config.
auto hap = replCoord->getMyHostAndPort();
if (auto memberConfig = replCoord->findConfigMemberByHostAndPort(hap)) {
if (!memberConfig->isVoter()) {
return false;
}
} else {
// We cannot determine our member config, so skip the majority wait and leave this index
// build as non-resumable.
return false;
}
return true;
}
/**
* Returns the ReadSource to be used for a drain occurring before the commit quorum has been
* satisfied.
*/
RecoveryUnit::ReadSource getReadSourceForDrainBeforeCommitQuorum(
const ReplIndexBuildState& replState) {
return replState.isResumable() ? RecoveryUnit::ReadSource::kMajorityCommitted
: RecoveryUnit::ReadSource::kNoTimestamp;
}
} // 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());
}
std::vector<std::string> IndexBuildsCoordinator::extractIndexNames(
const std::vector<BSONObj>& specs) {
std::vector<std::string> indexNames;
for (const auto& spec : specs) {
std::string name = spec.getStringField(IndexDescriptor::kIndexNameFieldName).toString();
invariant(!name.empty(),
str::stream() << "Bad spec passed into ReplIndexBuildState constructor, missing '"
<< IndexDescriptor::kIndexNameFieldName << "' field: " << spec);
indexNames.push_back(name);
}
return indexNames;
}
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;
}
CollectionWriter collection(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).toString();
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);
}
CollectionWriter collection(opCtx, nss);
{
// These steps are combined into a single WUOW to ensure there are no commits without the
// indexes for repair.
WriteUnitOfWork wuow(opCtx);
// We need to initialize the collection to rebuild the indexes. The collection may already
// be initialized when rebuilding multiple unfinished indexes on the same collection.
if (!collection->isInitialized()) {
collection.getWritableCollection(opCtx)->init(opCtx);
}
if (storageGlobalParams.repair) {
Status status = _dropIndexesForRepair(opCtx, collection, indexNames);
if (!status.isOK()) {
return status;
}
} else {
// Unfinished index builds that are not resumable will drop and recreate the index table
// using the same ident to avoid doing untimestamped writes to the catalog.
for (const auto& indexName : indexNames) {
auto indexCatalog = collection.getWritableCollection(opCtx)->getIndexCatalog();
auto desc =
indexCatalog->findIndexByName(opCtx,
indexName,
IndexCatalog::InclusionPolicy::kUnfinished |
IndexCatalog::InclusionPolicy::kFrozen);
Status status = indexCatalog->resetUnfinishedIndexForRecovery(
opCtx, collection.getWritableCollection(opCtx), desc);
if (!status.isOK()) {
return status;
}
const auto durableBuildUUID = collection->getIndexBuildUUID(indexName);
// A build UUID is present if and only if we are rebuilding a two-phase build.
invariant((protocol == IndexBuildProtocol::kTwoPhase) ==
durableBuildUUID.has_value());
// 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);
}
}
auto replIndexBuildState = std::make_shared<ReplIndexBuildState>(
buildUUID, collection->uuid(), nss.dbName(), specs, protocol);
Status status = activeIndexBuilds.registerIndexBuild(replIndexBuildState);
if (!status.isOK()) {
return status;
}
indexBuildsSSS.registered.addAndFetch(1);
IndexBuildsManager::SetupOptions options;
options.protocol = protocol;
// All indexes are dropped during repair and should be rebuilt normally.
options.forRecovery = !storageGlobalParams.repair;
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();
}
Status IndexBuildsCoordinator::_dropIndexesForRepair(OperationContext* opCtx,
CollectionWriter& collection,
const std::vector<std::string>& indexNames) {
invariant(collection->isInitialized());
for (const auto& indexName : indexNames) {
auto indexCatalog = collection.getWritableCollection(opCtx)->getIndexCatalog();
auto descriptor =
indexCatalog->findIndexByName(opCtx, indexName, IndexCatalog::InclusionPolicy::kReady);
if (descriptor) {
Status s =
indexCatalog->dropIndex(opCtx, collection.getWritableCollection(opCtx), descriptor);
if (!s.isOK()) {
return s;
}
continue;
}
// The index must be unfinished or frozen if it isn't ready.
descriptor = indexCatalog->findIndexByName(opCtx,
indexName,
IndexCatalog::InclusionPolicy::kUnfinished |
IndexCatalog::InclusionPolicy::kFrozen);
invariant(descriptor);
Status s = indexCatalog->dropUnfinishedIndex(
opCtx, collection.getWritableCollection(opCtx), descriptor);
if (!s.isOK()) {
return s;
}
}
return Status::OK();
}
Status IndexBuildsCoordinator::_setUpResumeIndexBuild(OperationContext* opCtx,
const DatabaseName& dbName,
const UUID& collectionUUID,
const std::vector<BSONObj>& specs,
const UUID& buildUUID,
const ResumeIndexInfo& resumeInfo) {
NamespaceStringOrUUID nssOrUuid{dbName, collectionUUID};
if (MONGO_unlikely(failSetUpResumeIndexBuild.shouldFail())) {
return {ErrorCodes::FailPointEnabled, "failSetUpResumeIndexBuild fail point is enabled"};
}
Lock::DBLock dbLock(opCtx, dbName, MODE_IX);
CollectionNamespaceOrUUIDLock collLock(opCtx, nssOrUuid, MODE_X);
CollectionWriter collection(opCtx, resumeInfo.getCollectionUUID());
invariant(collection);
auto durableCatalog = DurableCatalog::get(opCtx);
for (const auto& spec : specs) {
std::string indexName =
spec.getStringField(IndexDescriptor::kIndexNameFieldName).toString();
if (indexName.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");
}
// Check that the information in the durable catalog matches the resume info.
uassert(4841702,
"Index not found in durable catalog while attempting to resume index build",
collection->isIndexPresent(indexName));
const auto durableBuildUUID = collection->getIndexBuildUUID(indexName);
uassert(ErrorCodes::IndexNotFound,
str::stream() << "Cannot resume index build with a buildUUID: " << buildUUID
<< " that did not match the buildUUID in the durable catalog: "
<< durableBuildUUID,
durableBuildUUID == buildUUID);
auto indexIdent =
durableCatalog->getIndexIdent(opCtx, collection->getCatalogId(), indexName);
uassert(
4841703,
str::stream() << "No index ident found on disk that matches the index build to resume: "
<< indexName,
indexIdent.size() > 0);
uassertStatusOK(collection->checkMetaDataForIndex(indexName, spec));
}
if (!collection->isInitialized()) {
WriteUnitOfWork wuow(opCtx);
collection.getWritableCollection(opCtx)->init(opCtx);
wuow.commit();
}
auto protocol = IndexBuildProtocol::kTwoPhase;
auto replIndexBuildState = std::make_shared<ReplIndexBuildState>(
buildUUID, collection->uuid(), dbName, specs, protocol);
Status status = activeIndexBuilds.registerIndexBuild(replIndexBuildState);
if (!status.isOK()) {
return status;
}
indexBuildsSSS.registered.addAndFetch(1);
IndexBuildsManager::SetupOptions options;
options.protocol = protocol;
status = _indexBuildsManager.setUpIndexBuild(
opCtx, collection, specs, buildUUID, MultiIndexBlock::kNoopOnInitFn, options, resumeInfo);
if (!status.isOK()) {
activeIndexBuilds.unregisterIndexBuild(&_indexBuildsManager, replIndexBuildState);
}
return status;
}
void IndexBuildsCoordinator::waitForAllIndexBuildsToStopForShutdown(OperationContext* opCtx) {
activeIndexBuilds.waitForAllIndexBuildsToStopForShutdown(opCtx);
}
std::vector<UUID> IndexBuildsCoordinator::abortCollectionIndexBuilds(
OperationContext* opCtx,
const NamespaceString collectionNss,
const UUID collectionUUID,
const std::string& reason) {
auto collIndexBuilds = [&]() -> std::vector<std::shared_ptr<ReplIndexBuildState>> {
auto indexBuildFilter = [=](const auto& replState) {
return collectionUUID == replState.collectionUUID;
};
return activeIndexBuilds.filterIndexBuilds(indexBuildFilter);
}();
if (collIndexBuilds.empty()) {
return {};
}
LOGV2(23879,
"About to abort all index builders",
"namespace"_attr = collectionNss,
"uuid"_attr = collectionUUID,
"reason"_attr = reason);
std::vector<UUID> buildUUIDs;
for (const auto& replState : collIndexBuilds) {
if (abortIndexBuildByBuildUUID(
opCtx, replState->buildUUID, IndexBuildAction::kPrimaryAbort, reason)) {
buildUUIDs.push_back(replState->buildUUID);
}
}
return buildUUIDs;
}
void IndexBuildsCoordinator::abortDatabaseIndexBuilds(OperationContext* opCtx,
const DatabaseName& dbName,
const std::string& reason) {
LOGV2(4612302,
"About to abort all index builders running for collections in the given database",
"database"_attr = dbName,
"reason"_attr = reason);
auto builds = [&]() -> std::vector<std::shared_ptr<ReplIndexBuildState>> {
auto indexBuildFilter = [=](const auto& replState) { return dbName == replState.dbName; };
return activeIndexBuilds.filterIndexBuilds(indexBuildFilter);
}();
for (const auto& replState : builds) {
if (!abortIndexBuildByBuildUUID(
opCtx, replState->buildUUID, IndexBuildAction::kPrimaryAbort, reason)) {
// The index build may already be in the midst of tearing down.
LOGV2(5010502,
"Index build: failed to abort index build for database drop",
"buildUUID"_attr = replState->buildUUID,
"database"_attr = dbName,
"collectionUUID"_attr = replState->collectionUUID);
}
}
}
void IndexBuildsCoordinator::abortTenantIndexBuilds(OperationContext* opCtx,
MigrationProtocolEnum protocol,
StringData tenantId,
const std::string& reason) {
LOGV2(4886203,
"About to abort all index builders running for collections belonging to the given tenant",
"tenantId"_attr = tenantId,
"reason"_attr = reason);
auto builds = [&]() -> std::vector<std::shared_ptr<ReplIndexBuildState>> {
auto indexBuildFilter = [=](const auto& replState) {
// Abort *all* index builds at the start of shard merge.
return protocol == MigrationProtocolEnum::kShardMerge ||
repl::ClonerUtils::isDatabaseForTenant(replState.dbName.toStringWithTenantId(),
tenantId);
};
return activeIndexBuilds.filterIndexBuilds(indexBuildFilter);
}();
std::vector<std::shared_ptr<ReplIndexBuildState>> buildsWaitingToFinish;
buildsWaitingToFinish.reserve(builds.size());
const auto indexBuildActionStr =
indexBuildActionToString(IndexBuildAction::kTenantMigrationAbort);
for (const auto& replState : builds) {
if (!abortIndexBuildByBuildUUID(
opCtx, replState->buildUUID, IndexBuildAction::kTenantMigrationAbort, reason)) {
// The index build may already be in the midst of tearing down.
LOGV2(4886204,
"Index build: failed to abort index build for tenant migration",
"tenantId"_attr = tenantId,
"buildUUID"_attr = replState->buildUUID,
"db"_attr = replState->dbName,
"collectionUUID"_attr = replState->collectionUUID,
"buildAction"_attr = indexBuildActionStr);
buildsWaitingToFinish.push_back(replState);
}
}
for (const auto& replState : buildsWaitingToFinish) {
LOGV2(6221600,
"Waiting on the index build to unregister before continuing the tenant migration.",
"tenantId"_attr = tenantId,
"buildUUID"_attr = replState->buildUUID,
"db"_attr = replState->dbName,
"collectionUUID"_attr = replState->collectionUUID,
"buildAction"_attr = indexBuildActionStr);
awaitNoIndexBuildInProgressForCollection(
opCtx, replState->collectionUUID, replState->protocol);
}
}
void IndexBuildsCoordinator::abortAllIndexBuildsForInitialSync(OperationContext* opCtx,
const std::string& reason) {
LOGV2(4833200, "About to abort all index builders running", "reason"_attr = reason);
auto builds = [&]() -> std::vector<std::shared_ptr<ReplIndexBuildState>> {
auto indexBuildFilter = [](const auto& replState) { return true; };
return activeIndexBuilds.filterIndexBuilds(indexBuildFilter);
}();
for (const auto& replState : builds) {
if (!abortIndexBuildByBuildUUID(
opCtx, replState->buildUUID, IndexBuildAction::kInitialSyncAbort, reason)) {
// The index build may already be in the midst of tearing down.
LOGV2(5010503,
"Index build: failed to abort index build for initial sync",
"buildUUID"_attr = replState->buildUUID,
"database"_attr = replState->dbName,
"collectionUUID"_attr = replState->collectionUUID);
}
}
}
void IndexBuildsCoordinator::abortUserIndexBuildsForUserWriteBlocking(OperationContext* opCtx) {
LOGV2(6511600,
"About to abort index builders running on user databases for user write blocking");
auto builds = [&]() -> std::vector<std::shared_ptr<ReplIndexBuildState>> {
auto indexBuildFilter = [](const auto& replState) {
return !NamespaceString(replState.dbName).isOnInternalDb();
};
return activeIndexBuilds.filterIndexBuilds(indexBuildFilter);
}();
std::vector<std::shared_ptr<ReplIndexBuildState>> buildsWaitingToFinish;
for (const auto& replState : builds) {
if (!abortIndexBuildByBuildUUID(opCtx,
replState->buildUUID,
IndexBuildAction::kPrimaryAbort,
"User write blocking")) {
// If the index build is already finishing and thus can't be aborted, we must wait on
// it.
LOGV2(6511601,
"Index build: failed to abort index build for write blocking, will wait for "
"completion instead",
"buildUUID"_attr = replState->buildUUID,
"db"_attr = replState->dbName,
"collectionUUID"_attr = replState->collectionUUID);
buildsWaitingToFinish.push_back(replState);
}
}
// Before returning, we must wait on all index builds which could not be aborted to finish.
// Otherwise, index builds started before enabling user write block mode could commit after
// enabling it.
for (const auto& replState : buildsWaitingToFinish) {
LOGV2(6511602,
"Waiting on index build to finish for user write blocking",
"buildUUID"_attr = replState->buildUUID,
"db"_attr = replState->dbName,
"collectionUUID"_attr = replState->collectionUUID);
awaitNoIndexBuildInProgressForCollection(
opCtx, replState->collectionUUID, replState->protocol);
}
}
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,
ApplicationMode applicationMode,
const IndexBuildOplogEntry& oplogEntry) {
const auto collUUID = oplogEntry.collUUID;
const auto nss = getNsFromUUID(opCtx, collUUID);
IndexBuildsCoordinator::IndexBuildOptions indexBuildOptions;
indexBuildOptions.applicationMode = applicationMode;
// If this is an initial syncing node, drop any conflicting ready index specs prior to
// proceeding with building them.
if (indexBuildOptions.applicationMode == ApplicationMode::kInitialSync) {
auto dbAndUUID = NamespaceStringOrUUID(nss.db().toString(), collUUID);
writeConflictRetry(opCtx, "IndexBuildsCoordinator::applyStartIndexBuild", nss.ns(), [&] {
WriteUnitOfWork wuow(opCtx);
AutoGetCollection coll(opCtx, dbAndUUID, MODE_X);
invariant(coll,
str::stream() << "Collection with UUID " << collUUID << " was dropped.");
IndexCatalog* indexCatalog = coll.getWritableCollection(opCtx)->getIndexCatalog();
for (const auto& spec : oplogEntry.indexSpecs) {
std::string name =
spec.getStringField(IndexDescriptor::kIndexNameFieldName).toString();
uassert(ErrorCodes::BadValue,
str::stream() << "Index spec is missing the 'name' field " << spec,
!name.empty());
if (auto desc = indexCatalog->findIndexByName(
opCtx, name, IndexCatalog::InclusionPolicy::kReady)) {
uassertStatusOK(
indexCatalog->dropIndex(opCtx, coll.getWritableCollection(opCtx), desc));
}
}
wuow.commit();
});
}
auto indexBuildsCoord = IndexBuildsCoordinator::get(opCtx);
uassertStatusOK(
indexBuildsCoord
->startIndexBuild(opCtx,
nss.dbName(),
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);
// If this node's replica set config uses buildIndexes:false, then do not attempt to commit an
// index that would have never been started.
if (!repl::ReplicationCoordinator::get(opCtx)->buildsIndexes()) {
return;
}
uassert(31417,
str::stream()
<< "No commit timestamp set while applying commitIndexBuild operation. Build UUID: "
<< buildUUID,
!opCtx->recoveryUnit()->getCommitTimestamp().isNull());