/
index_catalog_impl.cpp
1875 lines (1597 loc) · 78.7 KB
/
index_catalog_impl.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_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kIndex
#include "mongo/platform/basic.h"
#include "mongo/db/catalog/index_catalog_impl.h"
#include <vector>
#include "mongo/base/init.h"
#include "mongo/bson/simple_bsonelement_comparator.h"
#include "mongo/bson/simple_bsonobj_comparator.h"
#include "mongo/db/audit.h"
#include "mongo/db/catalog/clustered_collection_util.h"
#include "mongo/db/catalog/collection.h"
#include "mongo/db/catalog/index_build_block.h"
#include "mongo/db/catalog/index_catalog_entry_impl.h"
#include "mongo/db/catalog/index_key_validate.h"
#include "mongo/db/catalog/uncommitted_collections.h"
#include "mongo/db/client.h"
#include "mongo/db/clientcursor.h"
#include "mongo/db/concurrency/write_conflict_exception.h"
#include "mongo/db/curop.h"
#include "mongo/db/field_ref.h"
#include "mongo/db/fts/fts_spec.h"
#include "mongo/db/index/index_access_method.h"
#include "mongo/db/index/index_descriptor.h"
#include "mongo/db/index/s2_access_method.h"
#include "mongo/db/index/s2_bucket_access_method.h"
#include "mongo/db/index_names.h"
#include "mongo/db/jsobj.h"
#include "mongo/db/keypattern.h"
#include "mongo/db/matcher/expression.h"
#include "mongo/db/multi_key_path_tracker.h"
#include "mongo/db/operation_context.h"
#include "mongo/db/ops/delete.h"
#include "mongo/db/query/collation/collation_spec.h"
#include "mongo/db/query/collation/collator_factory_interface.h"
#include "mongo/db/query/collection_index_usage_tracker_decoration.h"
#include "mongo/db/query/collection_query_info.h"
#include "mongo/db/query/internal_plans.h"
#include "mongo/db/query/query_knobs_gen.h"
#include "mongo/db/repl/replication_coordinator.h"
#include "mongo/db/repl_set_member_in_standalone_mode.h"
#include "mongo/db/server_options.h"
#include "mongo/db/service_context.h"
#include "mongo/db/storage/durable_catalog.h"
#include "mongo/db/storage/execution_context.h"
#include "mongo/db/storage/historical_ident_tracker.h"
#include "mongo/db/storage/kv/kv_engine.h"
#include "mongo/db/storage/storage_engine_init.h"
#include "mongo/db/storage/storage_parameters_gen.h"
#include "mongo/db/storage/storage_util.h"
#include "mongo/db/ttl_collection_cache.h"
#include "mongo/db/vector_clock.h"
#include "mongo/logv2/log.h"
#include "mongo/util/assert_util.h"
#include "mongo/util/fail_point.h"
#include "mongo/util/represent_as.h"
#include "mongo/util/str.h"
namespace mongo {
MONGO_FAIL_POINT_DEFINE(skipUnindexingDocumentWhenDeleted);
MONGO_FAIL_POINT_DEFINE(skipIndexNewRecords);
// This failpoint causes the check for TTL indexes on capped collections to be ignored.
MONGO_FAIL_POINT_DEFINE(ignoreTTLIndexCappedCollectionCheck);
using std::string;
using std::unique_ptr;
using std::vector;
using IndexVersion = IndexDescriptor::IndexVersion;
const BSONObj IndexCatalogImpl::_idObj = BSON("_id" << 1);
namespace {
/**
* Similar to _isSpecOK(), checks if the indexSpec is valid, conflicts, or already exists as a
* clustered index.
*
* Returns Status::OK() if no clustered index exists or the 'indexSpec' does not conflict with it.
* Returns ErrorCodes::IndexAlreadyExists if the 'indexSpec' already exists as the clustered index.
* Returns an error if the indexSpec fields conflict with the clustered index.
*/
Status isSpecOKClusteredIndexCheck(const BSONObj& indexSpec,
const boost::optional<ClusteredCollectionInfo>& collInfo) {
auto key = indexSpec.getObjectField("key");
bool keysMatch = clustered_util::matchesClusterKey(key, collInfo);
bool clusteredOptionPresent =
indexSpec.hasField("clustered") && indexSpec.getBoolField("clustered");
if (clusteredOptionPresent && !keysMatch) {
// The 'clustered' option implies the indexSpec must match the clustered index.
return Status(ErrorCodes::Error(6243700),
"Cannot create index with option 'clustered' that does not match an existing "
"clustered index");
}
auto name = indexSpec.getStringField("name");
bool namesMatch =
!collInfo.is_initialized() || collInfo->getIndexSpec().getName().get() == name;
if (!keysMatch && !namesMatch) {
// The indexes don't conflict at all.
return Status::OK();
}
// The collection is guaranteed to be clustered since at least the name or key matches a
// clustered index.
auto clusteredIndexSpec = collInfo->getIndexSpec();
if (namesMatch && !keysMatch) {
// Prohibit creating an index with the same 'name' as the cluster key but different key
// pattern.
return Status(ErrorCodes::Error(6100906),
str::stream() << "Cannot create an index where the name matches the "
"clusteredIndex but the key does not -"
<< " indexSpec: " << indexSpec
<< ", clusteredIndex: " << collInfo->getIndexSpec().toBSON());
}
// Users should be able to call createIndexes on the cluster key. If a name isn't specified, a
// default one is generated. Silently ignore mismatched names.
BSONElement vElt = indexSpec["v"];
auto version = representAs<int>(vElt.number());
if (clusteredIndexSpec.getV() != version) {
return Status(ErrorCodes::Error(6100908),
"Cannot create an index with the same key pattern as the collection's "
"clusteredIndex but a different 'v' field");
}
if (indexSpec.hasField("unique") && indexSpec.getBoolField("unique") == false) {
return Status(ErrorCodes::Error(6100909),
"Cannot create an index with the same key pattern as the collection's "
"clusteredIndex but a different 'unique' field");
}
// The indexSpec matches the clustered index, which already exists implicitly.
return Status(ErrorCodes::IndexAlreadyExists,
"The index already exists implicitly as the collection's clustered index");
};
} // namespace
// -------------
std::unique_ptr<IndexCatalog> IndexCatalogImpl::clone() const {
return std::make_unique<IndexCatalogImpl>(*this);
}
Status IndexCatalogImpl::init(OperationContext* opCtx, Collection* collection) {
vector<string> indexNames;
collection->getAllIndexes(&indexNames);
const bool replSetMemberInStandaloneMode =
getReplSetMemberInStandaloneMode(opCtx->getServiceContext());
boost::optional<Timestamp> recoveryTs = boost::none;
if (auto storageEngine = opCtx->getServiceContext()->getStorageEngine();
storageEngine->supportsRecoveryTimestamp()) {
recoveryTs = storageEngine->getRecoveryTimestamp();
}
for (size_t i = 0; i < indexNames.size(); i++) {
const string& indexName = indexNames[i];
BSONObj spec = collection->getIndexSpec(indexName).getOwned();
BSONObj keyPattern = spec.getObjectField("key");
auto descriptor = std::make_unique<IndexDescriptor>(_getAccessMethodName(keyPattern), spec);
// TTL indexes are not compatible with capped collections.
// Note that TTL deletion is supported on capped clustered collections via bounded
// collection scan, which does not use an index.
if (spec.hasField(IndexDescriptor::kExpireAfterSecondsFieldName) &&
!collection->isCapped()) {
TTLCollectionCache::get(opCtx->getServiceContext())
.registerTTLInfo(collection->uuid(), indexName);
}
bool ready = collection->isIndexReady(indexName);
if (!ready) {
auto buildUUID = collection->getIndexBuildUUID(indexName);
invariant(buildUUID,
str::stream() << "collection: " << collection->ns() << "index:" << indexName);
// We intentionally do not drop or rebuild unfinished two-phase index builds before
// initializing the IndexCatalog when starting a replica set member in standalone mode.
// This is because the index build cannot complete until it receives a replicated commit
// or abort oplog entry.
if (replSetMemberInStandaloneMode) {
// Indicate that this index is "frozen". It is not ready but is not currently in
// progress either. These indexes may be dropped.
auto flags = CreateIndexEntryFlags::kInitFromDisk | CreateIndexEntryFlags::kFrozen;
IndexCatalogEntry* entry =
createIndexEntry(opCtx, collection, std::move(descriptor), flags);
fassert(31433, !entry->isReady(opCtx));
} else {
// Initializing with unfinished indexes may occur during rollback or startup.
auto flags = CreateIndexEntryFlags::kInitFromDisk;
IndexCatalogEntry* entry =
createIndexEntry(opCtx, collection, std::move(descriptor), flags);
fassert(4505500, !entry->isReady(opCtx));
}
} else {
auto flags = CreateIndexEntryFlags::kInitFromDisk | CreateIndexEntryFlags::kIsReady;
IndexCatalogEntry* entry =
createIndexEntry(opCtx, collection, std::move(descriptor), flags);
fassert(17340, entry->isReady(opCtx));
// When initializing indexes from disk, we conservatively set the minimumVisibleSnapshot
// to non _id indexes to the recovery timestamp. The _id index is left visible. It's
// assumed if the collection is visible, it's _id is valid to be used.
if (recoveryTs && !entry->descriptor()->isIdIndex()) {
entry->setMinimumVisibleSnapshot(recoveryTs.get());
}
}
}
CollectionQueryInfo::get(collection).init(opCtx, collection);
return Status::OK();
}
std::unique_ptr<IndexCatalog::IndexIterator> IndexCatalogImpl::getIndexIterator(
OperationContext* const opCtx, const bool includeUnfinishedIndexes) const {
if (!includeUnfinishedIndexes) {
// If the caller only wants the ready indexes, we return an iterator over the catalog's
// ready indexes vector. When the user advances this iterator, it will filter out any
// indexes that were not ready at the OperationContext's read timestamp.
return std::make_unique<ReadyIndexesIterator>(
opCtx, _readyIndexes.begin(), _readyIndexes.end());
}
// If the caller wants all indexes, for simplicity of implementation, we copy the pointers to
// a new vector. The vector's ownership is passed to the iterator. The query code path from an
// external client is not expected to hit this case so the cost isn't paid by the important
// code path.
auto allIndexes = std::make_unique<std::vector<IndexCatalogEntry*>>();
for (auto it = _readyIndexes.begin(); it != _readyIndexes.end(); ++it) {
allIndexes->push_back(it->get());
}
for (auto it = _buildingIndexes.begin(); it != _buildingIndexes.end(); ++it) {
allIndexes->push_back(it->get());
}
return std::make_unique<AllIndexesIterator>(opCtx, std::move(allIndexes));
}
string IndexCatalogImpl::_getAccessMethodName(const BSONObj& keyPattern) const {
string pluginName = IndexNames::findPluginName(keyPattern);
// This assert will be triggered when downgrading from a future version that
// supports an index plugin unsupported by this version.
uassert(17197,
str::stream() << "Invalid index type '" << pluginName << "' "
<< "in index " << keyPattern,
IndexNames::isKnownName(pluginName));
return pluginName;
}
// ---------------------------
StatusWith<BSONObj> IndexCatalogImpl::_validateAndFixIndexSpec(OperationContext* opCtx,
const CollectionPtr& collection,
const BSONObj& original) const {
Status status = _isSpecOk(opCtx, collection, original);
if (!status.isOK()) {
return status;
}
auto swFixed = _fixIndexSpec(opCtx, collection, original);
if (!swFixed.isOK()) {
return swFixed;
}
// we double check with new index spec
status = _isSpecOk(opCtx, collection, swFixed.getValue());
if (!status.isOK()) {
return status;
}
return swFixed;
}
Status IndexCatalogImpl::_isNonIDIndexAndNotAllowedToBuild(OperationContext* opCtx,
const BSONObj& spec) const {
const BSONObj key = spec.getObjectField("key");
invariant(!key.isEmpty());
if (!IndexDescriptor::isIdIndexPattern(key)) {
// 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 (!repl::ReplicationCoordinator::get(opCtx)->buildsIndexes()) {
// We return an IndexAlreadyExists error so that the caller can catch it and silently
// skip building it.
return Status(ErrorCodes::IndexAlreadyExists,
"this replica set member's 'buildIndexes' setting is set to false");
}
}
return Status::OK();
}
void IndexCatalogImpl::_logInternalState(OperationContext* opCtx,
const CollectionPtr& collection,
long long numIndexesInCollectionCatalogEntry,
const std::vector<std::string>& indexNamesToDrop,
bool haveIdIndex) {
invariant(opCtx->lockState()->isCollectionLockedForMode(collection->ns(), MODE_X));
LOGV2_ERROR(20365,
"Internal Index Catalog state",
"numIndexesTotal"_attr = numIndexesTotal(opCtx),
"numIndexesInCollectionCatalogEntry"_attr = numIndexesInCollectionCatalogEntry,
"numReadyIndexes"_attr = _readyIndexes.size(),
"numBuildingIndexes"_attr = _buildingIndexes.size(),
"indexNamesToDrop"_attr = indexNamesToDrop,
"haveIdIndex"_attr = haveIdIndex);
// Report the ready indexes.
for (const auto& entry : _readyIndexes) {
const IndexDescriptor* desc = entry->descriptor();
LOGV2_ERROR(20367,
"readyIndex",
"index"_attr = desc->indexName(),
"indexInfo"_attr = redact(desc->infoObj()));
}
// Report the in-progress indexes.
for (const auto& entry : _buildingIndexes) {
const IndexDescriptor* desc = entry->descriptor();
LOGV2_ERROR(20369,
"buildingIndex",
"index"_attr = desc->indexName(),
"indexInfo"_attr = redact(desc->infoObj()));
}
LOGV2_ERROR(20370, "Internal Collection Catalog Entry state:");
std::vector<std::string> allIndexes;
std::vector<std::string> readyIndexes;
collection->getAllIndexes(&allIndexes);
collection->getReadyIndexes(&readyIndexes);
for (const auto& index : allIndexes) {
LOGV2_ERROR(20372,
"allIndexes",
"index"_attr = index,
"spec"_attr = redact(collection->getIndexSpec(index)));
}
for (const auto& index : readyIndexes) {
LOGV2_ERROR(20374,
"readyIndexes",
"index"_attr = index,
"spec"_attr = redact(collection->getIndexSpec(index)));
}
}
StatusWith<BSONObj> IndexCatalogImpl::prepareSpecForCreate(
OperationContext* opCtx,
const CollectionPtr& collection,
const BSONObj& original,
const boost::optional<ResumeIndexInfo>& resumeInfo) const {
auto swValidatedAndFixed = _validateAndFixIndexSpec(opCtx, collection, original);
if (!swValidatedAndFixed.isOK()) {
return swValidatedAndFixed.getStatus().withContext(
str::stream() << "Error in specification " << original.toString());
}
auto validatedSpec = swValidatedAndFixed.getValue();
// Check whether this is a TTL index being created on a capped collection.
// TODO SERVER-61545 The feature compatibility version check in this if statement can be removed
// once 6.0 is LTS.
if (collection && collection->isCapped() &&
validatedSpec.hasField(IndexDescriptor::kExpireAfterSecondsFieldName) &&
((!serverGlobalParams.featureCompatibility.isVersionInitialized()) ||
serverGlobalParams.featureCompatibility.isGreaterThanOrEqualTo(
multiversion::FeatureCompatibilityVersion::kVersion_5_2)) &&
MONGO_likely(!ignoreTTLIndexCappedCollectionCheck.shouldFail())) {
return {ErrorCodes::CannotCreateIndex, "Cannot create TTL index on a capped collection"};
}
// Check whether this is a non-_id index and there are any settings disallowing this server
// from building non-_id indexes.
Status status = _isNonIDIndexAndNotAllowedToBuild(opCtx, validatedSpec);
if (!status.isOK()) {
return status;
}
// First check against only the ready indexes for conflicts.
status = _doesSpecConflictWithExisting(opCtx, collection, validatedSpec, false);
if (!status.isOK()) {
return status;
}
if (resumeInfo) {
// Don't check against unfinished indexes if this index is being resumed, since it will
// conflict with itself.
return validatedSpec;
}
// Now we will check against all indexes, in-progress included.
//
// The index catalog cannot currently iterate over only in-progress indexes. So by previously
// checking against only ready indexes without error, we know that any errors encountered
// checking against all indexes occurred due to an in-progress index.
status = _doesSpecConflictWithExisting(opCtx, collection, validatedSpec, true);
if (!status.isOK()) {
if (ErrorCodes::IndexAlreadyExists == status.code()) {
// Callers need to be able to distinguish conflicts against ready indexes versus
// in-progress indexes.
return {ErrorCodes::IndexBuildAlreadyInProgress, status.reason()};
}
return status;
}
return validatedSpec;
}
std::vector<BSONObj> IndexCatalogImpl::removeExistingIndexesNoChecks(
OperationContext* const opCtx,
const CollectionPtr& collection,
const std::vector<BSONObj>& indexSpecsToBuild) const {
std::vector<BSONObj> result;
// Filter out ready and in-progress index builds, and any non-_id indexes if 'buildIndexes' is
// set to false in the replica set's config.
for (const auto& spec : indexSpecsToBuild) {
// returned to be built by the caller.
if (ErrorCodes::OK != _isNonIDIndexAndNotAllowedToBuild(opCtx, spec)) {
continue;
}
// _doesSpecConflictWithExisting currently does more work than we require here: we are only
// interested in the index already exists error.
if (ErrorCodes::IndexAlreadyExists ==
_doesSpecConflictWithExisting(
opCtx, collection, spec, true /*includeUnfinishedIndexes*/)) {
continue;
}
result.push_back(spec);
}
return result;
}
std::vector<BSONObj> IndexCatalogImpl::removeExistingIndexes(
OperationContext* const opCtx,
const CollectionPtr& collection,
const std::vector<BSONObj>& indexSpecsToBuild,
const bool removeIndexBuildsToo) const {
std::vector<BSONObj> result;
for (const auto& spec : indexSpecsToBuild) {
auto prepareResult = prepareSpecForCreate(opCtx, collection, spec);
if (prepareResult == ErrorCodes::IndexAlreadyExists ||
(removeIndexBuildsToo && prepareResult == ErrorCodes::IndexBuildAlreadyInProgress)) {
continue;
}
uassertStatusOK(prepareResult);
result.push_back(prepareResult.getValue());
}
return result;
}
IndexCatalogEntry* IndexCatalogImpl::createIndexEntry(OperationContext* opCtx,
Collection* collection,
std::unique_ptr<IndexDescriptor> descriptor,
CreateIndexEntryFlags flags) {
Status status = _isSpecOk(opCtx, collection, descriptor->infoObj());
if (!status.isOK()) {
LOGV2_FATAL_NOTRACE(28782,
"Found an invalid index",
"descriptor"_attr = descriptor->infoObj(),
"namespace"_attr = collection->ns(),
"error"_attr = redact(status));
}
auto engine = opCtx->getServiceContext()->getStorageEngine();
std::string ident = engine->getCatalog()->getIndexIdent(
opCtx, collection->getCatalogId(), descriptor->indexName());
bool isReadyIndex = CreateIndexEntryFlags::kIsReady & flags;
bool frozen = CreateIndexEntryFlags::kFrozen & flags;
invariant(!frozen || !isReadyIndex);
auto* const descriptorPtr = descriptor.get();
auto entry = std::make_shared<IndexCatalogEntryImpl>(
opCtx, collection, ident, std::move(descriptor), frozen);
IndexDescriptor* desc = entry->descriptor();
// In some cases, it may be necessary to update the index metadata in the storage engine in
// order to obtain the correct SortedDataInterface. One such scenario is found in converting an
// index to be unique.
bool isUpdateMetadata = CreateIndexEntryFlags::kUpdateMetadata & flags;
if (isUpdateMetadata) {
engine->getEngine()->alterIdentMetadata(opCtx, ident, desc);
}
const auto& collOptions = collection->getCollectionOptions();
std::unique_ptr<SortedDataInterface> sdi =
engine->getEngine()->getSortedDataInterface(opCtx, collOptions, ident, desc);
std::unique_ptr<IndexAccessMethod> accessMethod =
IndexAccessMethodFactory::get(opCtx)->make(entry.get(), std::move(sdi));
entry->init(std::move(accessMethod));
IndexCatalogEntry* save = entry.get();
if (isReadyIndex) {
_readyIndexes.add(std::move(entry));
} else {
_buildingIndexes.add(std::move(entry));
}
bool initFromDisk = CreateIndexEntryFlags::kInitFromDisk & flags;
if (!initFromDisk && UncommittedCollections::getForTxn(opCtx, collection->ns()) == nullptr) {
const std::string indexName = descriptorPtr->indexName();
opCtx->recoveryUnit()->onRollback(
[collectionDecorations = collection->getSharedDecorations(),
indexName = std::move(indexName)] {
CollectionIndexUsageTrackerDecoration::get(collectionDecorations)
.unregisterIndex(indexName);
});
}
return save;
}
StatusWith<BSONObj> IndexCatalogImpl::createIndexOnEmptyCollection(OperationContext* opCtx,
Collection* collection,
BSONObj spec) {
invariant(collection->uuid() == collection->uuid());
UncommittedCollections::get(opCtx).invariantHasExclusiveAccessToCollection(opCtx,
collection->ns());
invariant(collection->isEmpty(opCtx),
str::stream() << "Collection must be empty. Collection: " << collection->ns()
<< " UUID: " << collection->uuid()
<< " Count (from size storer): " << collection->numRecords(opCtx));
StatusWith<BSONObj> statusWithSpec = prepareSpecForCreate(opCtx, collection, spec);
Status status = statusWithSpec.getStatus();
if (!status.isOK())
return status;
spec = statusWithSpec.getValue();
// now going to touch disk
boost::optional<UUID> buildUUID = boost::none;
IndexBuildBlock indexBuildBlock(
collection->ns(), spec, IndexBuildMethod::kForeground, buildUUID);
status = indexBuildBlock.init(opCtx, collection);
if (!status.isOK())
return status;
// sanity checks, etc...
IndexCatalogEntry* entry = indexBuildBlock.getEntry(opCtx, collection);
invariant(entry);
IndexDescriptor* descriptor = entry->descriptor();
invariant(descriptor);
status = entry->accessMethod()->initializeAsEmpty(opCtx);
if (!status.isOK())
return status;
indexBuildBlock.success(opCtx, collection);
// sanity check
invariant(collection->isIndexReady(descriptor->indexName()));
return spec;
}
namespace {
constexpr int kMaxNumIndexesAllowed = 64;
/**
* Recursive function which confirms whether 'expression' is valid for use in partial indexes.
* Recursion is restricted to 'internalPartialFilterExpressionMaxDepth' levels.
*/
Status _checkValidFilterExpressions(const MatchExpression* expression,
bool timeseriesMetricIndexesFeatureFlagEnabled,
int level = 0) {
if (!expression)
return Status::OK();
const auto kMaxDepth = internalPartialFilterExpressionMaxDepth.load();
if (timeseriesMetricIndexesFeatureFlagEnabled && (level + 1) > kMaxDepth) {
return Status(ErrorCodes::CannotCreateIndex,
str::stream()
<< "partialFilterExpression depth may not exceed " << kMaxDepth);
}
switch (expression->matchType()) {
case MatchExpression::AND:
if (!timeseriesMetricIndexesFeatureFlagEnabled) {
if (level > 0)
return Status(ErrorCodes::CannotCreateIndex,
"$and only supported in partialFilterExpression at top level");
}
for (size_t i = 0; i < expression->numChildren(); i++) {
Status status = _checkValidFilterExpressions(
expression->getChild(i), timeseriesMetricIndexesFeatureFlagEnabled, level + 1);
if (!status.isOK())
return status;
}
return Status::OK();
case MatchExpression::OR:
if (!timeseriesMetricIndexesFeatureFlagEnabled) {
return Status(ErrorCodes::CannotCreateIndex,
str::stream() << "Expression not supported in partial index: "
<< expression->debugString());
}
for (size_t i = 0; i < expression->numChildren(); i++) {
Status status = _checkValidFilterExpressions(
expression->getChild(i), timeseriesMetricIndexesFeatureFlagEnabled, level + 1);
if (!status.isOK()) {
return status;
}
}
return Status::OK();
case MatchExpression::GEO:
case MatchExpression::INTERNAL_BUCKET_GEO_WITHIN:
case MatchExpression::INTERNAL_EXPR_EQ:
case MatchExpression::INTERNAL_EXPR_LT:
case MatchExpression::INTERNAL_EXPR_LTE:
case MatchExpression::INTERNAL_EXPR_GT:
case MatchExpression::INTERNAL_EXPR_GTE:
case MatchExpression::MATCH_IN:
if (timeseriesMetricIndexesFeatureFlagEnabled) {
return Status::OK();
}
return Status(ErrorCodes::CannotCreateIndex,
str::stream() << "Expression not supported in partial index: "
<< expression->debugString());
case MatchExpression::EQ:
case MatchExpression::LT:
case MatchExpression::LTE:
case MatchExpression::GT:
case MatchExpression::GTE:
case MatchExpression::EXISTS:
case MatchExpression::TYPE_OPERATOR:
return Status::OK();
default:
return Status(ErrorCodes::CannotCreateIndex,
str::stream() << "Expression not supported in partial index: "
<< expression->debugString());
}
}
/**
* Adjust the provided index spec BSONObj depending on the type of index obj describes.
*
* This is a no-op unless the object describes a TEXT or a GEO_2DSPHERE index. TEXT and
* GEO_2DSPHERE provide additional validation on the index spec, and tweak the index spec
* object to conform to their expected format.
*/
StatusWith<BSONObj> adjustIndexSpecObject(const BSONObj& obj) {
std::string pluginName = IndexNames::findPluginName(obj.getObjectField("key"));
if (IndexNames::TEXT == pluginName) {
return fts::FTSSpec::fixSpec(obj);
}
if (IndexNames::GEO_2DSPHERE == pluginName) {
return S2AccessMethod::fixSpec(obj);
}
if (IndexNames::GEO_2DSPHERE_BUCKET == pluginName) {
return S2BucketAccessMethod::fixSpec(obj);
}
return obj;
}
} // namespace
Status IndexCatalogImpl::checkValidFilterExpressions(
const MatchExpression* expression, bool timeseriesMetricIndexesFeatureFlagEnabled) {
return _checkValidFilterExpressions(expression, timeseriesMetricIndexesFeatureFlagEnabled);
}
Status IndexCatalogImpl::_isSpecOk(OperationContext* opCtx,
const CollectionPtr& collection,
const BSONObj& spec) const {
const NamespaceString& nss = collection->ns();
BSONElement vElt = spec["v"];
if (!vElt) {
return {ErrorCodes::InternalError,
str::stream()
<< "An internal operation failed to specify the 'v' field, which is a required "
"property of an index specification: "
<< spec};
}
if (!vElt.isNumber()) {
return Status(ErrorCodes::CannotCreateIndex,
str::stream() << "non-numeric value for \"v\" field: " << vElt);
}
auto vEltAsInt = representAs<int>(vElt.number());
if (!vEltAsInt) {
return {ErrorCodes::CannotCreateIndex,
str::stream() << "Index version must be representable as a 32-bit integer, but got "
<< vElt.toString(false, false)};
}
auto indexVersion = static_cast<IndexVersion>(*vEltAsInt);
if (indexVersion >= IndexVersion::kV2) {
auto status = index_key_validate::validateIndexSpecFieldNames(spec);
if (!status.isOK()) {
return status;
}
}
if (!IndexDescriptor::isIndexVersionSupported(indexVersion)) {
return Status(ErrorCodes::CannotCreateIndex,
str::stream() << "this version of mongod cannot build new indexes "
<< "of version number " << static_cast<int>(indexVersion));
}
if (nss.isOplog())
return Status(ErrorCodes::CannotCreateIndex, "cannot have an index on the oplog");
// logical name of the index
const BSONElement nameElem = spec["name"];
if (nameElem.type() != String)
return Status(ErrorCodes::CannotCreateIndex, "index name must be specified as a string");
const StringData name = nameElem.valueStringData();
if (name.find('\0') != std::string::npos)
return Status(ErrorCodes::CannotCreateIndex, "index name cannot contain NUL bytes");
if (name.empty())
return Status(ErrorCodes::CannotCreateIndex, "index name cannot be empty");
const BSONObj key = spec.getObjectField("key");
const Status keyStatus = index_key_validate::validateKeyPattern(key, indexVersion);
if (!keyStatus.isOK()) {
return Status(ErrorCodes::CannotCreateIndex,
str::stream()
<< "bad index key pattern " << key << ": " << keyStatus.reason());
}
const string pluginName = IndexNames::findPluginName(key);
std::unique_ptr<CollatorInterface> collator;
BSONElement collationElement = spec.getField("collation");
if (collationElement) {
if (collationElement.type() != BSONType::Object) {
return Status(ErrorCodes::CannotCreateIndex,
"\"collation\" for an index must be a document");
}
auto statusWithCollator = CollatorFactoryInterface::get(opCtx->getServiceContext())
->makeFromBSON(collationElement.Obj());
if (!statusWithCollator.isOK()) {
return statusWithCollator.getStatus();
}
collator = std::move(statusWithCollator.getValue());
if (!collator) {
return {ErrorCodes::InternalError,
str::stream() << "An internal operation specified the collation "
<< CollationSpec::kSimpleSpec
<< " explicitly, which should instead be implied by omitting the "
"'collation' field from the index specification"};
}
if (static_cast<IndexVersion>(vElt.numberInt()) < IndexVersion::kV2) {
return {ErrorCodes::CannotCreateIndex,
str::stream() << "Index version " << vElt.fieldNameStringData() << "="
<< vElt.numberInt() << " does not support the '"
<< collationElement.fieldNameStringData() << "' option"};
}
if ((pluginName != IndexNames::BTREE) && (pluginName != IndexNames::GEO_2DSPHERE) &&
(pluginName != IndexNames::HASHED) && (pluginName != IndexNames::WILDCARD)) {
return Status(ErrorCodes::CannotCreateIndex,
str::stream()
<< "Index type '" << pluginName
<< "' does not support collation: " << collator->getSpec().toBSON());
}
}
const bool isSparse = spec["sparse"].trueValue();
if (pluginName == IndexNames::WILDCARD) {
if (isSparse) {
return Status(ErrorCodes::CannotCreateIndex,
str::stream() << "Index type '" << pluginName
<< "' does not support the sparse option");
}
if (spec["unique"].trueValue()) {
return Status(ErrorCodes::CannotCreateIndex,
str::stream() << "Index type '" << pluginName
<< "' does not support the unique option");
}
if (spec.getField("expireAfterSeconds")) {
return Status(ErrorCodes::CannotCreateIndex,
str::stream()
<< "Index type '" << pluginName << "' cannot be a TTL index");
}
}
// Create an ExpressionContext, used to parse the match expression and to house the collator for
// the remaining checks.
boost::intrusive_ptr<ExpressionContext> expCtx(
new ExpressionContext(opCtx, std::move(collator), nss));
// Ensure if there is a filter, its valid.
BSONElement filterElement = spec.getField("partialFilterExpression");
if (filterElement) {
if (isSparse) {
return Status(ErrorCodes::CannotCreateIndex,
"cannot mix \"partialFilterExpression\" and \"sparse\" options");
}
if (filterElement.type() != Object) {
return Status(ErrorCodes::CannotCreateIndex,
"\"partialFilterExpression\" for an index must be a document");
}
// Parsing the partial filter expression is not expected to fail here since the
// expression would have been successfully parsed upstream during index creation.
StatusWithMatchExpression statusWithMatcher =
MatchExpressionParser::parse(filterElement.Obj(),
expCtx,
ExtensionsCallbackNoop(),
MatchExpressionParser::kBanAllSpecialFeatures);
if (!statusWithMatcher.isOK()) {
return statusWithMatcher.getStatus();
}
const std::unique_ptr<MatchExpression> filterExpr = std::move(statusWithMatcher.getValue());
Status status =
_checkValidFilterExpressions(filterExpr.get(),
feature_flags::gTimeseriesMetricIndexes.isEnabled(
serverGlobalParams.featureCompatibility));
if (!status.isOK()) {
return status;
}
}
BSONElement clusteredElt = spec["clustered"];
if (collection->isClustered() || (clusteredElt && clusteredElt.trueValue())) {
// Clustered collections require checks to ensure the spec does not conflict with the
// implicit clustered index that exists on the clustered collection.
auto status = isSpecOKClusteredIndexCheck(spec, collection->getClusteredInfo());
if (!status.isOK()) {
return status;
}
}
if (IndexDescriptor::isIdIndexPattern(key)) {
if (collection->isClustered() &&
!clustered_util::matchesClusterKey(key, collection->getClusteredInfo())) {
return Status(
ErrorCodes::CannotCreateIndex,
"cannot create the _id index on a clustered collection not clustered by _id");
}
BSONElement uniqueElt = spec["unique"];
if (uniqueElt && !uniqueElt.trueValue()) {
return Status(ErrorCodes::CannotCreateIndex, "_id index cannot be non-unique");
}
if (filterElement) {
return Status(ErrorCodes::CannotCreateIndex, "_id index cannot be a partial index");
}
if (isSparse) {
return Status(ErrorCodes::CannotCreateIndex, "_id index cannot be sparse");
}
if (collationElement &&
!CollatorInterface::collatorsMatch(expCtx->getCollator(),
collection->getDefaultCollator())) {
return Status(ErrorCodes::CannotCreateIndex,
"_id index must have the collection default collation");
}
}
// --- only storage engine checks allowed below this ----
BSONElement storageEngineElement = spec.getField("storageEngine");
if (storageEngineElement.eoo()) {
return Status::OK();
}
if (storageEngineElement.type() != mongo::Object) {
return Status(ErrorCodes::CannotCreateIndex,
"\"storageEngine\" options must be a document if present");
}
BSONObj storageEngineOptions = storageEngineElement.Obj();
if (storageEngineOptions.isEmpty()) {
return Status(ErrorCodes::CannotCreateIndex,
"Empty \"storageEngine\" options are invalid. "
"Please remove the field or include valid options.");
}
Status storageEngineStatus = validateStorageOptions(
opCtx->getServiceContext(), storageEngineOptions, [](const auto& x, const auto& y) {
return x->validateIndexStorageOptions(y);
});
if (!storageEngineStatus.isOK()) {
return storageEngineStatus;
}
return Status::OK();
}
Status IndexCatalogImpl::_doesSpecConflictWithExisting(OperationContext* opCtx,
const CollectionPtr& collection,
const BSONObj& spec,
const bool includeUnfinishedIndexes) const {
StringData name = spec.getStringField(IndexDescriptor::kIndexNameFieldName);
invariant(name[0]);
const BSONObj key = spec.getObjectField(IndexDescriptor::kKeyPatternFieldName);
if (spec["clustered"]) {
// Not an error, but the spec is already validated against the collection options by
// _isSpecOK now and we know that if 'clustered' is true, then the index already exists.
return Status(ErrorCodes::IndexAlreadyExists, "The clustered index is implicitly built");
}
{
// Check whether an index with the specified candidate name already exists in the catalog.
const IndexDescriptor* desc = findIndexByName(opCtx, name, includeUnfinishedIndexes);
if (desc) {
// Index already exists with same name. Check whether the options are the same as well.
IndexDescriptor candidate(_getAccessMethodName(key), spec);
auto indexComparison =
candidate.compareIndexOptions(opCtx, collection->ns(), getEntry(desc));
// Key pattern or another uniquely-identifying option differs. We can build this index,
// but not with the specified (duplicate) name. User must specify another index name.
if (indexComparison == IndexDescriptor::Comparison::kDifferent) {
return Status(ErrorCodes::IndexKeySpecsConflict,
str::stream()
<< "An existing index has the same name as the "
"requested index. When index names are not specified, they "
"are auto generated and can cause conflicts. Please refer to "
"our documentation. Requested index: "
<< spec << ", existing index: " << desc->infoObj());
}
// The candidate's key and uniquely-identifying options are equivalent to an existing
// index, but some other options are not identical. Return a message to that effect.
if (indexComparison == IndexDescriptor::Comparison::kEquivalent) {
return Status(ErrorCodes::IndexOptionsConflict,
str::stream() << "An equivalent index already exists with the same "
"name but different options. Requested index: "
<< spec << ", existing index: " << desc->infoObj());
}
// If we've reached this point, the requested index is identical to an existing index.
invariant(indexComparison == IndexDescriptor::Comparison::kIdentical);
// If an identical index exists, but it is frozen, return an error with a different
// error code to the user, forcing the user to drop before recreating the index.
auto entry = getEntry(desc);
if (entry->isFrozen()) {
return Status(ErrorCodes::CannotCreateIndex,