summaryrefslogtreecommitdiff
path: root/src/mongo/db/commands/create_indexes.cpp
blob: e4a66da2d4b42b266cd76e71a12524779ecef29e (plain)
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
/**
 *    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_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kIndex

#include "mongo/platform/basic.h"

#include <string>
#include <vector>

#include "mongo/base/string_data.h"
#include "mongo/db/auth/authorization_session.h"
#include "mongo/db/catalog/collection.h"
#include "mongo/db/catalog/create_collection.h"
#include "mongo/db/catalog/database.h"
#include "mongo/db/catalog/database_holder.h"
#include "mongo/db/catalog/index_key_validate.h"
#include "mongo/db/catalog/multi_index_block.h"
#include "mongo/db/catalog/uncommitted_collections.h"
#include "mongo/db/command_generic_argument.h"
#include "mongo/db/commands.h"
#include "mongo/db/concurrency/d_concurrency.h"
#include "mongo/db/concurrency/write_conflict_exception.h"
#include "mongo/db/db_raii.h"
#include "mongo/db/index/index_descriptor.h"
#include "mongo/db/index_builds_coordinator.h"
#include "mongo/db/op_observer.h"
#include "mongo/db/ops/insert.h"
#include "mongo/db/repl/repl_client_info.h"
#include "mongo/db/repl/repl_set_config.h"
#include "mongo/db/repl/replication_coordinator.h"
#include "mongo/db/s/collection_sharding_runtime.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/storage/two_phase_index_build_knobs_gen.h"
#include "mongo/db/views/view_catalog.h"
#include "mongo/logv2/log.h"
#include "mongo/platform/compiler.h"
#include "mongo/s/shard_key_pattern.h"
#include "mongo/util/scopeguard.h"
#include "mongo/util/uuid.h"

namespace mongo {

namespace {
// This failpoint simulates a WriteConflictException during createIndexes where the collection is
// implicitly created.
MONGO_FAIL_POINT_DEFINE(createIndexesWriteConflict);

// This failpoint causes createIndexes with an implicit collection creation to hang before the
// collection is created.
MONGO_FAIL_POINT_DEFINE(hangBeforeCreateIndexesCollectionCreate);
MONGO_FAIL_POINT_DEFINE(hangBeforeIndexBuildAbortOnInterrupt);
MONGO_FAIL_POINT_DEFINE(hangAfterIndexBuildAbort);

// This failpoint hangs between logging the index build UUID and starting the index build
// through the IndexBuildsCoordinator.
MONGO_FAIL_POINT_DEFINE(hangCreateIndexesBeforeStartingIndexBuild);

constexpr auto kIndexesFieldName = "indexes"_sd;
constexpr auto kCommandName = "createIndexes"_sd;
constexpr auto kCommitQuorumFieldName = "commitQuorum"_sd;
constexpr auto kIgnoreUnknownIndexOptionsName = "ignoreUnknownIndexOptions"_sd;
constexpr auto kCreateCollectionAutomaticallyFieldName = "createdCollectionAutomatically"_sd;
constexpr auto kNumIndexesBeforeFieldName = "numIndexesBefore"_sd;
constexpr auto kNumIndexesAfterFieldName = "numIndexesAfter"_sd;
constexpr auto kNoteFieldName = "note"_sd;

/**
 * Parses the index specifications from 'cmdObj', validates them, and returns equivalent index
 * specifications that have any missing attributes filled in. If any index specification is
 * malformed, then an error status is returned.
 */
StatusWith<std::vector<BSONObj>> parseAndValidateIndexSpecs(
    OperationContext* opCtx,
    const NamespaceString& ns,
    const BSONObj& cmdObj,
    const ServerGlobalParams::FeatureCompatibility& featureCompatibility) {
    bool hasIndexesField = false;

    bool ignoreUnknownIndexOptions = false;
    if (cmdObj.hasField(kIgnoreUnknownIndexOptionsName)) {
        auto ignoreUnknownIndexOptionsElement = cmdObj.getField(kIgnoreUnknownIndexOptionsName);
        if (ignoreUnknownIndexOptionsElement.type() != BSONType::Bool) {
            return {ErrorCodes::TypeMismatch,
                    str::stream() << "The field '" << kIgnoreUnknownIndexOptionsName
                                  << "' must be a boolean, but got "
                                  << typeName(ignoreUnknownIndexOptionsElement.type())};
        }
        ignoreUnknownIndexOptions = ignoreUnknownIndexOptionsElement.boolean();
    }

    std::vector<BSONObj> indexSpecs;
    for (auto&& cmdElem : cmdObj) {
        auto cmdElemFieldName = cmdElem.fieldNameStringData();

        if (kIndexesFieldName == cmdElemFieldName) {
            if (cmdElem.type() != BSONType::Array) {
                return {ErrorCodes::TypeMismatch,
                        str::stream()
                            << "The field '" << kIndexesFieldName << "' must be an array, but got "
                            << typeName(cmdElem.type())};
            }

            for (auto&& indexesElem : cmdElem.Obj()) {
                if (indexesElem.type() != BSONType::Object) {
                    return {ErrorCodes::TypeMismatch,
                            str::stream() << "The elements of the '" << kIndexesFieldName
                                          << "' array must be objects, but got "
                                          << typeName(indexesElem.type())};
                }

                BSONObj parsedIndexSpec = indexesElem.Obj();
                if (ignoreUnknownIndexOptions) {
                    parsedIndexSpec = index_key_validate::removeUnknownFields(parsedIndexSpec);
                }

                auto indexSpecStatus = index_key_validate::validateIndexSpec(
                    opCtx, parsedIndexSpec, featureCompatibility);
                if (!indexSpecStatus.isOK()) {
                    return indexSpecStatus.getStatus().withContext(
                        str::stream() << "Error in specification " << parsedIndexSpec.toString());
                }
                auto indexSpec = indexSpecStatus.getValue();

                if (IndexDescriptor::isIdIndexPattern(
                        indexSpec[IndexDescriptor::kKeyPatternFieldName].Obj())) {
                    auto status = index_key_validate::validateIdIndexSpec(indexSpec);
                    if (!status.isOK()) {
                        return status;
                    }
                } else if (indexSpec[IndexDescriptor::kIndexNameFieldName].String() == "_id_"_sd) {
                    return {ErrorCodes::BadValue,
                            str::stream() << "The index name '_id_' is reserved for the _id index, "
                                             "which must have key pattern {_id: 1}, found "
                                          << indexSpec[IndexDescriptor::kKeyPatternFieldName]};
                } else if (indexSpec[IndexDescriptor::kIndexNameFieldName].String() == "*"_sd) {
                    // An index named '*' cannot be dropped on its own, because a dropIndex oplog
                    // entry with a '*' as an index name means "drop all indexes in this
                    // collection".  We disallow creation of such indexes to avoid this conflict.
                    return {ErrorCodes::BadValue, "The index name '*' is not valid."};
                } else if (ns.isSystem() && !indexSpec[IndexDescriptor::kHiddenFieldName].eoo()) {
                    return {ErrorCodes::BadValue, "Can't hide index on system collection"};
                }

                indexSpecs.push_back(std::move(indexSpec));
            }

            hasIndexesField = true;
        } else if (kCommandName == cmdElemFieldName || kCommitQuorumFieldName == cmdElemFieldName ||
                   kIgnoreUnknownIndexOptionsName == cmdElemFieldName ||
                   isGenericArgument(cmdElemFieldName)) {
            continue;
        } else {
            return {ErrorCodes::BadValue,
                    str::stream() << "Invalid field specified for " << kCommandName
                                  << " command: " << cmdElemFieldName};
        }
    }

    if (!hasIndexesField) {
        return {ErrorCodes::FailedToParse,
                str::stream() << "The '" << kIndexesFieldName
                              << "' field is a required argument of the " << kCommandName
                              << " command"};
    }

    if (indexSpecs.empty()) {
        return {ErrorCodes::BadValue, "Must specify at least one index to create"};
    }

    return indexSpecs;
}

void appendFinalIndexFieldsToResult(int numIndexesBefore,
                                    int numIndexesAfter,
                                    BSONObjBuilder& result,
                                    int numSpecs,
                                    boost::optional<CommitQuorumOptions> commitQuorum) {
    result.append(kNumIndexesBeforeFieldName, numIndexesBefore);
    result.append(kNumIndexesAfterFieldName, numIndexesAfter);
    if (numIndexesAfter == numIndexesBefore) {
        result.append(kNoteFieldName, "all indexes already exist");
    } else if (numIndexesAfter < numIndexesBefore + numSpecs) {
        result.append(kNoteFieldName, "index already exists");
    }

    // commitQuorum will be populated only when two phase index build is enabled.
    if (commitQuorum)
        commitQuorum->appendToBuilder(kCommitQuorumFieldName, &result);
}


/**
 * Ensures that the options passed in for TTL indexes are valid.
 */
Status validateTTLOptions(OperationContext* opCtx, const BSONObj& cmdObj) {
    const std::string kExpireAfterSeconds = "expireAfterSeconds";

    const BSONElement& indexes = cmdObj[kIndexesFieldName];
    for (const auto& index : indexes.Array()) {
        BSONObj indexObj = index.Obj();
        if (!indexObj.hasField(kExpireAfterSeconds)) {
            continue;
        }

        const BSONElement expireAfterSecondsElt = indexObj[kExpireAfterSeconds];
        if (!expireAfterSecondsElt.isNumber()) {
            return {ErrorCodes::CannotCreateIndex,
                    str::stream() << "TTL index '" << kExpireAfterSeconds
                                  << "' option must be numeric, but received a type of '"
                                  << typeName(expireAfterSecondsElt.type())
                                  << "'. Index spec: " << indexObj};
        }

        if (expireAfterSecondsElt.safeNumberLong() < 0) {
            return {ErrorCodes::CannotCreateIndex,
                    str::stream() << "TTL index '" << kExpireAfterSeconds
                                  << "' option cannot be less than 0. Index spec: " << indexObj};
        }

        const std::string tooLargeErr = str::stream()
            << "TTL index '" << kExpireAfterSeconds
            << "' option must be within an acceptable range, try a lower number. Index spec: "
            << indexObj;

        // There are two cases where we can encounter an issue here.
        // The first case is when we try to cast to millseconds from seconds, which could cause an
        // overflow. The second case is where 'expireAfterSeconds' is larger than the current epoch
        // time.
        try {
            auto expireAfterMillis =
                duration_cast<Milliseconds>(Seconds(expireAfterSecondsElt.safeNumberLong()));
            if (expireAfterMillis > Date_t::now().toDurationSinceEpoch()) {
                return {ErrorCodes::CannotCreateIndex, tooLargeErr};
            }
        } catch (const AssertionException&) {
            return {ErrorCodes::CannotCreateIndex, tooLargeErr};
        }

        const BSONObj key = indexObj["key"].Obj();
        if (key.nFields() != 1) {
            return {ErrorCodes::CannotCreateIndex,
                    str::stream() << "TTL indexes are single-field indexes, compound indexes do "
                                     "not support TTL. Index spec: "
                                  << indexObj};
        }
    }

    return Status::OK();
}

/**
 * Retrieves the commit quorum from 'cmdObj' if it is present. If it isn't, we provide a default
 * commit quorum, which consists of all the data-bearing nodes.
 */
boost::optional<CommitQuorumOptions> parseAndGetCommitQuorum(OperationContext* opCtx,
                                                             IndexBuildProtocol protocol,
                                                             const BSONObj& cmdObj) {
    auto replCoord = repl::ReplicationCoordinator::get(opCtx);
    auto commitQuorumEnabled = (enableIndexBuildCommitQuorum) ? true : false;

    if (cmdObj.hasField(kCommitQuorumFieldName)) {
        uassert(ErrorCodes::BadValue,
                str::stream() << "Standalones can't specify commitQuorum",
                replCoord->isReplEnabled());
        uassert(ErrorCodes::BadValue,
                str::stream() << "commitQuorum is supported only for two phase index builds with "
                                 "commit quorum support enabled ",
                (IndexBuildProtocol::kTwoPhase == protocol && commitQuorumEnabled));
        CommitQuorumOptions commitQuorum;
        uassertStatusOK(commitQuorum.parse(cmdObj.getField(kCommitQuorumFieldName)));
        uassertStatusOK(replCoord->checkIfCommitQuorumCanBeSatisfied(commitQuorum));
        return commitQuorum;
    }

    if (IndexBuildProtocol::kTwoPhase == protocol) {
        // Setting CommitQuorum to 0 will make the index build to opt out of voting proces.
        return (replCoord->isReplEnabled() && commitQuorumEnabled)
            ? CommitQuorumOptions(CommitQuorumOptions::kVotingMembers)
            : CommitQuorumOptions(CommitQuorumOptions::kDisabled);
    }

    return boost::none;
}

/**
 * Returns a vector of index specs with the filled in collection default options and removes any
 * indexes that already exist on the collection -- both ready indexes and in-progress builds. If the
 * returned vector is empty after returning, no new indexes need to be built. Throws on error.
 */
std::vector<BSONObj> resolveDefaultsAndRemoveExistingIndexes(OperationContext* opCtx,
                                                             const Collection* collection,
                                                             std::vector<BSONObj> indexSpecs) {
    // Normalize the specs' collations, wildcard projections, and partial filters as applicable.
    auto normalSpecs = IndexBuildsCoordinator::normalizeIndexSpecs(opCtx, collection, indexSpecs);

    return collection->getIndexCatalog()->removeExistingIndexes(
        opCtx, normalSpecs, false /*removeIndexBuildsToo*/);
}

/**
 * Fills in command result with number of indexes when there are no indexes to add.
 */
void fillCommandResultWithIndexesAlreadyExistInfo(int numIndexes, BSONObjBuilder* result) {
    result->append("numIndexesBefore", numIndexes);
    result->append("numIndexesAfter", numIndexes);
    result->append("note", "all indexes already exist");
};

/**
 * Returns true, after filling in the command result, if the index creation can return early.
 */
bool indexesAlreadyExist(OperationContext* opCtx,
                         const Collection* collection,
                         const std::vector<BSONObj>& specs,
                         BSONObjBuilder* result) {
    auto specsCopy = resolveDefaultsAndRemoveExistingIndexes(opCtx, collection, specs);
    if (specsCopy.size() > 0) {
        return false;
    }

    auto numIndexes = collection->getIndexCatalog()->numIndexesTotal(opCtx);
    fillCommandResultWithIndexesAlreadyExistInfo(numIndexes, result);

    return true;
}

/**
 * Checks database sharding state. Throws exception on error.
 */
void checkDatabaseShardingState(OperationContext* opCtx, const NamespaceString& ns) {
    auto dss = DatabaseShardingState::get(opCtx, ns.db());
    auto dssLock = DatabaseShardingState::DSSLock::lockShared(opCtx, dss);
    dss->checkDbVersion(opCtx, dssLock);

    Lock::CollectionLock collLock(opCtx, ns, MODE_IS);
    try {
        const auto collDesc =
            CollectionShardingState::get(opCtx, ns)->getCollectionDescription(opCtx);
        if (!collDesc.isSharded()) {
            auto mpsm = dss->getMovePrimarySourceManager(dssLock);

            if (mpsm) {
                LOGV2(
                    4909200, "assertMovePrimaryInProgress", "movePrimaryNss"_attr = ns.toString());

                uasserted(ErrorCodes::MovePrimaryInProgress,
                          "movePrimary is in progress for namespace " + ns.toString());
            }
        }
    } catch (const DBException& ex) {
        if (ex.toStatus() != ErrorCodes::MovePrimaryInProgress) {
            LOGV2(4909201, "Error when getting colleciton description", "what"_attr = ex.what());
            return;
        }
        throw;
    }
}

/**
 * Attempts to create indexes in `specs` on a non-existent collection (or empty collection created
 * in the same multi-document transaction) with namespace `ns`. In the former case, the collection
 * is implicitly created.
 * Returns a BSONObj containing fields to be appended to the result of the calling function.
 * `commitQuorum` is passed only to be appended to the result, for completeness. It is otherwise
 * unused.
 * Expects to be run at the end of a larger writeConflictRetry loop.
 */
BSONObj runCreateIndexesOnNewCollection(OperationContext* opCtx,
                                        const NamespaceString& ns,
                                        const std::vector<BSONObj>& specs,
                                        boost::optional<CommitQuorumOptions> commitQuorum,
                                        bool createCollImplicitly) {
    BSONObjBuilder createResult;

    WriteUnitOfWork wunit(opCtx);

    auto databaseHolder = DatabaseHolder::get(opCtx);
    auto db = databaseHolder->getDb(opCtx, ns.db());
    uassert(ErrorCodes::CommandNotSupportedOnView,
            "Cannot create indexes on a view",
            !db || !ViewCatalog::get(db)->lookup(opCtx, ns.ns()));

    if (createCollImplicitly) {
        // We need to create the collection.
        BSONObjBuilder builder;
        builder.append("create", ns.coll());
        CollectionOptions options;
        builder.appendElements(options.toBSON());
        BSONObj idIndexSpec;

        if (MONGO_unlikely(hangBeforeCreateIndexesCollectionCreate.shouldFail())) {
            // Simulate a scenario where a conflicting collection creation occurs
            // mid-index build.
            LOGV2(20437,
                  "Hanging create collection due to failpoint "
                  "'hangBeforeCreateIndexesCollectionCreate'");
            hangBeforeCreateIndexesCollectionCreate.pauseWhileSet();
        }

        auto createStatus =
            createCollection(opCtx, ns.db().toString(), builder.obj().getOwned(), idIndexSpec);

        if (createStatus == ErrorCodes::NamespaceExists) {
            throw WriteConflictException();
        }

        uassertStatusOK(createStatus);
    }

    // By this point, we have exclusive access to our collection, either because we created the
    // collection implicitly as part of createIndexes or because the collection was created earlier
    // in the same multi-document transaction.
    auto collection = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, ns);
    UncommittedCollections::get(opCtx).invariantHasExclusiveAccessToCollection(opCtx,
                                                                               collection->ns());
    invariant(opCtx->inMultiDocumentTransaction() || createCollImplicitly);

    uassert(ErrorCodes::OperationNotSupportedInTransaction,
            str::stream() << "Cannot create new indexes on non-empty collection " << ns
                          << " in a multi-document transaction.",
            collection->numRecords(opCtx) == 0);

    const int numIndexesBefore = IndexBuildsCoordinator::getNumIndexesTotal(opCtx, collection);
    auto filteredSpecs =
        IndexBuildsCoordinator::prepareSpecListForCreate(opCtx, collection, ns, specs);
    // It's possible for 'filteredSpecs' to be empty if we receive a createIndexes request for the
    // _id index and also create the collection implicitly. By this point, the _id index has already
    // been created, and there is no more work to be done.
    if (!filteredSpecs.empty()) {
        IndexBuildsCoordinator::createIndexesOnEmptyCollection(
            opCtx, collection->uuid(), filteredSpecs, false);
    }

    const int numIndexesAfter = IndexBuildsCoordinator::getNumIndexesTotal(opCtx, collection);

    if (MONGO_unlikely(createIndexesWriteConflict.shouldFail())) {
        throw WriteConflictException();
    }
    wunit.commit();

    appendFinalIndexFieldsToResult(
        numIndexesBefore, numIndexesAfter, createResult, int(specs.size()), commitQuorum);

    return createResult.obj();
}

bool runCreateIndexesWithCoordinator(OperationContext* opCtx,
                                     const std::string& dbname,
                                     const BSONObj& cmdObj,
                                     BSONObjBuilder& result) {
    const NamespaceString ns(CommandHelpers::parseNsCollectionRequired(dbname, cmdObj));

    uassertStatusOK(userAllowedWriteNS(ns));

    // Disallow users from creating new indexes on config.transactions since the sessions code
    // was optimized to not update indexes
    uassert(ErrorCodes::IllegalOperation,
            str::stream() << "not allowed to create index on " << ns.ns(),
            ns != NamespaceString::kSessionTransactionsTableNamespace);

    uassert(ErrorCodes::OperationNotSupportedInTransaction,
            str::stream() << "Cannot write to system collection " << ns.toString()
                          << " within a transaction.",
            !opCtx->inMultiDocumentTransaction() || !ns.isSystem());

    auto specs = uassertStatusOK(
        parseAndValidateIndexSpecs(opCtx, ns, cmdObj, serverGlobalParams.featureCompatibility));
    auto replCoord = repl::ReplicationCoordinator::get(opCtx);
    auto indexBuildsCoord = IndexBuildsCoordinator::get(opCtx);
    // Two phase index builds are designed to improve the availability of indexes in a replica set.
    auto protocol = !replCoord->isOplogDisabledFor(opCtx, ns) ? IndexBuildProtocol::kTwoPhase
                                                              : IndexBuildProtocol::kSinglePhase;
    auto commitQuorum = parseAndGetCommitQuorum(opCtx, protocol, cmdObj);

    Status validateTTL = validateTTLOptions(opCtx, cmdObj);
    uassertStatusOK(validateTTL);

    // Preliminary checks before handing control over to IndexBuildsCoordinator:
    // 1) We are in a replication mode that allows for index creation.
    // 2) Check sharding state.
    // 3) Check if we can create the index without handing control to the IndexBuildsCoordinator.
    OptionalCollectionUUID collectionUUID;
    {
        Lock::DBLock dbLock(opCtx, ns.db(), MODE_IS);
        checkDatabaseShardingState(opCtx, ns);
        if (!repl::ReplicationCoordinator::get(opCtx)->canAcceptWritesFor(opCtx, ns)) {
            uasserted(ErrorCodes::NotWritablePrimary,
                      str::stream() << "Not primary while creating indexes in " << ns.ns());
        }

        bool indexExists = writeConflictRetry(opCtx, "createCollectionWithIndexes", ns.ns(), [&] {
            AutoGetCollection autoColl(opCtx, ns, MODE_IS);
            auto collection = autoColl.getCollection();

            // Before potentially taking an exclusive collection lock, check if all indexes already
            // exist while holding an intent lock.
            if (collection && indexesAlreadyExist(opCtx, collection, specs, &result)) {
                repl::ReplClientInfo::forClient(opCtx->getClient())
                    .setLastOpToSystemLastOpTime(opCtx);
                return true;
            }

            if (collection &&
                !UncommittedCollections::get(opCtx).isUncommittedCollection(opCtx, ns)) {
                // The collection exists and was not created in the same multi-document transaction
                // as the createIndexes.
                collectionUUID = collection->uuid();
                result.appendBool(kCreateCollectionAutomaticallyFieldName, false);
                return false;
            }

            bool createCollImplicitly = collection ? false : true;

            auto createIndexesResult = runCreateIndexesOnNewCollection(
                opCtx, ns, specs, commitQuorum, createCollImplicitly);
            // No further sources of WriteConflicts can occur at this point, so it is safe to
            // append elements to `result` inside the writeConflictRetry loop.
            result.appendBool(kCreateCollectionAutomaticallyFieldName, true);
            result.appendElements(createIndexesResult);
            return true;
        });

        if (indexExists) {
            // No need to proceed if the index either already existed or has just been built.
            return true;
        }

        // If the index does not exist by this point, the index build must go through the index
        // builds coordinator and take an exclusive lock. We should not take exclusive locks inside
        // of transactions, so we fail early here if we are inside of a transaction.
        uassert(ErrorCodes::OperationNotSupportedInTransaction,
                str::stream() << "Cannot create new indexes on existing collection " << ns
                              << " in a multi-document transaction.",
                !opCtx->inMultiDocumentTransaction());
    }

    // Use AutoStatsTracker to update Top.
    boost::optional<AutoStatsTracker> statsTracker;
    statsTracker.emplace(opCtx,
                         ns,
                         Top::LockType::WriteLocked,
                         AutoStatsTracker::LogMode::kUpdateTopAndCurOp,
                         CollectionCatalog::get(opCtx).getDatabaseProfileLevel(ns.db()));

    auto buildUUID = UUID::gen();
    ReplIndexBuildState::IndexCatalogStats stats;
    IndexBuildsCoordinator::IndexBuildOptions indexBuildOptions = {commitQuorum};

    LOGV2(20438,
          "Index build: registering",
          "buildUUID"_attr = buildUUID,
          "namespace"_attr = ns,
          "collectionUUID"_attr = *collectionUUID,
          "indexes"_attr = specs.size(),
          "firstIndex"_attr = specs[0][IndexDescriptor::kIndexNameFieldName]);
    hangCreateIndexesBeforeStartingIndexBuild.pauseWhileSet(opCtx);

    bool shouldContinueInBackground = false;
    try {
        auto buildIndexFuture = uassertStatusOK(indexBuildsCoord->startIndexBuild(
            opCtx, dbname, *collectionUUID, specs, buildUUID, protocol, indexBuildOptions));

        auto deadline = opCtx->getDeadline();
        LOGV2(20440,
              "Index build: waiting for index build to complete",
              "buildUUID"_attr = buildUUID,
              "deadline"_attr = deadline);

        // Throws on error.
        try {
            stats = buildIndexFuture.get(opCtx);
        } catch (const ExceptionForCat<ErrorCategory::Interruption>& interruptionEx) {
            LOGV2(20441,
                  "Index build: received interrupt signal",
                  "buildUUID"_attr = buildUUID,
                  "signal"_attr = interruptionEx);

            hangBeforeIndexBuildAbortOnInterrupt.pauseWhileSet();

            if (IndexBuildProtocol::kTwoPhase == protocol) {
                // If this node is no longer a primary, the index build will continue to run in the
                // background and will complete when this node receives a commitIndexBuild oplog
                // entry from the new primary.
                if (ErrorCodes::InterruptedDueToReplStateChange == interruptionEx.code()) {
                    shouldContinueInBackground = true;
                    throw;
                }
            }

            // It is unclear whether the interruption originated from the current opCtx instance
            // for the createIndexes command or that the IndexBuildsCoordinator task was interrupted
            // independently of this command invocation. We'll defensively abort the index build
            // with the assumption that if the index build was already in the midst of tearing down,
            // this will be a no-op.
            {
                // The current OperationContext may be interrupted, which would prevent us from
                // taking locks. Use a new OperationContext to abort the index build.
                auto newClient = opCtx->getServiceContext()->makeClient("abort-index-build");
                AlternativeClientRegion acr(newClient);
                const auto abortCtx = cc().makeOperationContext();

                std::string abortReason(str::stream() << "Index build aborted: " << buildUUID
                                                      << ": " << interruptionEx.toString());
                if (indexBuildsCoord->abortIndexBuildByBuildUUID(
                        abortCtx.get(), buildUUID, IndexBuildAction::kPrimaryAbort, abortReason)) {
                    LOGV2(20443,
                          "Index build: aborted due to interruption",
                          "buildUUID"_attr = buildUUID);
                } else {
                    // The index build may already be in the midst of tearing down.
                    LOGV2(5010500,
                          "Index build: failed to abort index build",
                          "buildUUID"_attr = buildUUID);
                }
            }
            throw;
        } catch (const ExceptionForCat<ErrorCategory::NotMasterError>& ex) {
            LOGV2(20444,
                  "Index build: received interrupt signal due to change in replication state",
                  "buildUUID"_attr = buildUUID,
                  "ex"_attr = ex);

            // If this node is no longer a primary, the index build will continue to run in the
            // background and will complete when this node receives a commitIndexBuild oplog
            // entry from the new primary.
            if (IndexBuildProtocol::kTwoPhase == protocol) {
                shouldContinueInBackground = true;
                throw;
            }

            std::string abortReason(str::stream() << "Index build aborted: " << buildUUID << ": "
                                                  << ex.toString());
            if (indexBuildsCoord->abortIndexBuildByBuildUUID(
                    opCtx, buildUUID, IndexBuildAction::kPrimaryAbort, abortReason)) {
                LOGV2(20446,
                      "Index build: aborted due to NotPrimary error",
                      "buildUUID"_attr = buildUUID);
            } else {
                // The index build may already be in the midst of tearing down.
                LOGV2(5010501,
                      "Index build: failed to abort index build",
                      "buildUUID"_attr = buildUUID);
            }

            throw;
        }

        LOGV2(20447, "Index build: completed", "buildUUID"_attr = buildUUID);
    } catch (DBException& ex) {
        // If the collection is dropped after the initial checks in this function (before the
        // AutoStatsTracker is created), the IndexBuildsCoordinator (either startIndexBuild() or
        // the the task running the index build) may return NamespaceNotFound. This is not
        // considered an error and the command should return success.
        if (ErrorCodes::NamespaceNotFound == ex.code()) {
            LOGV2(20448,
                  "Index build: failed because collection dropped",
                  "buildUUID"_attr = buildUUID,
                  "namespace"_attr = ns,
                  "collectionUUID"_attr = *collectionUUID,
                  "exception"_attr = ex);
            return true;
        }

        if (shouldContinueInBackground) {
            LOGV2(4760400,
                  "Index build: ignoring interrupt and continuing in background",
                  "buildUUID"_attr = buildUUID);
        } else {
            LOGV2(20449, "Index build: failed", "buildUUID"_attr = buildUUID, "error"_attr = ex);
        }

        // All other errors should be forwarded to the caller with index build information included.
        ex.addContext(str::stream() << "Index build failed: " << buildUUID << ": Collection " << ns
                                    << " ( " << *collectionUUID << " )");

        // Set last op on error to provide the client with a specific optime to read the state of
        // the server when the createIndexes command failed.
        repl::ReplClientInfo::forClient(opCtx->getClient()).setLastOpToSystemLastOpTime(opCtx);

        throw;
    }

    // IndexBuildsCoordinator may write the createIndexes oplog entry on a different thread.
    // The current client's last op should be synchronized with the oplog to ensure consistent
    // getLastError results as the previous non-IndexBuildsCoordinator behavior.
    repl::ReplClientInfo::forClient(opCtx->getClient()).setLastOpToSystemLastOpTime(opCtx);

    appendFinalIndexFieldsToResult(
        stats.numIndexesBefore, stats.numIndexesAfter, result, int(specs.size()), commitQuorum);

    return true;
}

/**
 * { createIndexes : "bar",
 *   indexes : [ { ns : "test.bar", key : { x : 1 }, name: "x_1" } ],
 *   commitQuorum: "majority" }
 */
class CmdCreateIndex : public ErrmsgCommandDeprecated {
public:
    CmdCreateIndex() : ErrmsgCommandDeprecated(kCommandName) {}

    const std::set<std::string>& apiVersions() const {
        return kApiVersions1;
    }

    bool supportsWriteConcern(const BSONObj& cmd) const override {
        return true;
    }

    AllowedOnSecondary secondaryAllowed(ServiceContext*) const override {
        return AllowedOnSecondary::kNever;
    }

    Status checkAuthForCommand(Client* client,
                               const std::string& dbname,
                               const BSONObj& cmdObj) const override {
        ActionSet actions;
        actions.addAction(ActionType::createIndex);
        Privilege p(parseResourcePattern(dbname, cmdObj), actions);
        if (AuthorizationSession::get(client)->isAuthorizedForPrivilege(p))
            return Status::OK();
        return Status(ErrorCodes::Unauthorized, "Unauthorized");
    }

    bool errmsgRun(OperationContext* opCtx,
                   const std::string& dbname,
                   const BSONObj& cmdObj,
                   std::string& errmsg,
                   BSONObjBuilder& result) override {
        // If we encounter an IndexBuildAlreadyInProgress error for any of the requested index
        // specs, then we will wait for the build(s) to finish before trying again unless we are in
        // a multi-document transaction.
        const NamespaceString nss(CommandHelpers::parseNsCollectionRequired(dbname, cmdObj));
        bool shouldLogMessageOnAlreadyBuildingError = true;
        while (true) {
            try {
                return runCreateIndexesWithCoordinator(opCtx, dbname, cmdObj, result);
            } catch (const DBException& ex) {
                hangAfterIndexBuildAbort.pauseWhileSet();
                // We can only wait for an existing index build to finish if we are able to release
                // our locks, in order to allow the existing index build to proceed. We cannot
                // release locks in transactions, so we bypass the below logic in transactions.
                if (ex.toStatus() != ErrorCodes::IndexBuildAlreadyInProgress ||
                    opCtx->inMultiDocumentTransaction()) {
                    throw;
                }
                if (shouldLogMessageOnAlreadyBuildingError) {
                    auto bsonElem = cmdObj.getField(kIndexesFieldName);
                    LOGV2(20450,
                          "Received a request to create indexes: '{indexesFieldName}', but found "
                          "that at least one of the indexes is already being built, '{error}'. "
                          "This request will wait for the pre-existing index build to finish "
                          "before proceeding",
                          "Received a request to create indexes, "
                          "but found that at least one of the indexes is already being built."
                          "This request will wait for the pre-existing index build to finish "
                          "before proceeding",
                          "indexesFieldName"_attr = bsonElem,
                          "error"_attr = ex);
                    shouldLogMessageOnAlreadyBuildingError = false;
                }
                // Unset the response fields so we do not write duplicate fields.
                errmsg = "";
                result.resetToEmpty();
                // Reset the snapshot because we have released locks and need a fresh snapshot
                // if we reacquire the locks again later.
                opCtx->recoveryUnit()->abandonSnapshot();
                // This is a bit racy since we are not holding a lock across discovering an
                // in-progress build and starting to listen for completion. It is good enough,
                // however: we can only wait longer than needed, not less.
                IndexBuildsCoordinator::get(opCtx)->waitUntilAnIndexBuildFinishes(opCtx);
            }
        }
    }

} cmdCreateIndex;

}  // namespace
}  // namespace mongo