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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
|
// index_catalog.cpp
/**
* Copyright (C) 2013-2014 MongoDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* 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
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* 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 GNU Affero General 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/platform/basic.h"
#include "mongo/db/catalog/index_catalog.h"
#include <vector>
#include "mongo/db/audit.h"
#include "mongo/db/background.h"
#include "mongo/db/catalog/collection_catalog_entry.h"
#include "mongo/db/catalog/collection.h"
#include "mongo/db/catalog/database_catalog_entry.h"
#include "mongo/db/catalog/index_create.h"
#include "mongo/db/catalog/index_key_validate.h"
#include "mongo/db/client.h"
#include "mongo/db/clientcursor.h"
#include "mongo/db/curop.h"
#include "mongo/db/field_ref.h"
#include "mongo/db/global_environment_experiment.h"
#include "mongo/db/index/index_access_method.h"
#include "mongo/db/index/index_descriptor.h"
#include "mongo/db/index_legacy.h"
#include "mongo/db/index_names.h"
#include "mongo/db/jsobj.h"
#include "mongo/db/keypattern.h"
#include "mongo/db/ops/delete.h"
#include "mongo/db/query/internal_plans.h"
#include "mongo/db/repl/repl_coordinator_global.h"
#include "mongo/db/repl/rs.h" // this is ugly
#include "mongo/db/operation_context.h"
#include "mongo/util/assert_util.h"
#include "mongo/util/log.h"
namespace mongo {
MONGO_LOG_DEFAULT_COMPONENT_FILE(::mongo::logger::LogComponent::kIndexing);
static const int INDEX_CATALOG_INIT = 283711;
static const int INDEX_CATALOG_UNINIT = 654321;
// What's the default version of our indices?
const int DefaultIndexVersionNumber = 1;
const BSONObj IndexCatalog::_idObj = BSON( "_id" << 1 );
// -------------
IndexCatalog::IndexCatalog( Collection* collection )
: _magic(INDEX_CATALOG_UNINIT), _collection( collection ) {
}
IndexCatalog::~IndexCatalog() {
if ( _magic != INDEX_CATALOG_UNINIT ) {
// only do this check if we haven't been initialized
_checkMagic();
}
_magic = 123456;
}
Status IndexCatalog::init(OperationContext* txn) {
vector<string> indexNames;
_collection->getCatalogEntry()->getAllIndexes( &indexNames );
for ( size_t i = 0; i < indexNames.size(); i++ ) {
const string& indexName = indexNames[i];
BSONObj spec = _collection->getCatalogEntry()->getIndexSpec( indexName ).getOwned();
if ( !_collection->getCatalogEntry()->isIndexReady( indexName ) ) {
_unfinishedIndexes.push_back( spec );
continue;
}
BSONObj keyPattern = spec.getObjectField("key");
IndexDescriptor* descriptor = new IndexDescriptor( _collection,
_getAccessMethodName(txn, keyPattern),
spec );
IndexCatalogEntry* entry = _setupInMemoryStructures( txn, descriptor );
fassert( 17340, entry->isReady() );
}
if ( _unfinishedIndexes.size() ) {
// if there are left over indexes, we don't let anyone add/drop indexes
// until someone goes and fixes them
log() << "found " << _unfinishedIndexes.size()
<< " index(es) that wasn't finished before shutdown";
}
_magic = INDEX_CATALOG_INIT;
return Status::OK();
}
IndexCatalogEntry* IndexCatalog::_setupInMemoryStructures(OperationContext* txn,
IndexDescriptor* descriptor) {
auto_ptr<IndexDescriptor> descriptorCleanup( descriptor );
auto_ptr<IndexCatalogEntry> entry( new IndexCatalogEntry( _collection->ns().ns(),
_collection->getCatalogEntry(),
descriptorCleanup.release(),
_collection->infoCache() ) );
entry->init( _collection->_database->_dbEntry->getIndex( txn,
_collection->getCatalogEntry(),
entry.get() ) );
IndexCatalogEntry* save = entry.get();
_entries.add( entry.release() );
invariant( save == _entries.find( descriptor ) );
invariant( save == _entries.find( descriptor->indexName() ) );
return save;
}
bool IndexCatalog::ok() const {
return ( _magic == INDEX_CATALOG_INIT );
}
void IndexCatalog::_checkMagic() const {
if ( ok() ) {
return;
}
log() << "IndexCatalog::_magic wrong, is : " << _magic;
fassertFailed(17198);
}
Status IndexCatalog::_checkUnfinished() const {
if ( _unfinishedIndexes.size() == 0 )
return Status::OK();
return Status( ErrorCodes::InternalError,
str::stream()
<< "IndexCatalog has left over indexes that must be cleared"
<< " ns: " << _collection->ns().ns() );
}
bool IndexCatalog::_shouldOverridePlugin(OperationContext* txn,
const BSONObj& keyPattern) const {
string pluginName = IndexNames::findPluginName(keyPattern);
bool known = IndexNames::isKnownName(pluginName);
if ( !_collection->_database->getDatabaseCatalogEntry()->isOlderThan24( txn ) ) {
// RulesFor24+
// 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,
known);
return false;
}
// RulesFor22
if (!known) {
log() << "warning: can't find plugin [" << pluginName << "]" << endl;
return true;
}
if (!IndexNames::existedBefore24(pluginName)) {
warning() << "Treating index " << keyPattern << " as ascending since "
<< "it was created before 2.4 and '" << pluginName << "' "
<< "was not a valid type at that time."
<< endl;
return true;
}
return false;
}
string IndexCatalog::_getAccessMethodName(OperationContext* txn,
const BSONObj& keyPattern) const {
if ( _shouldOverridePlugin(txn, keyPattern) ) {
return "";
}
return IndexNames::findPluginName(keyPattern);
}
// ---------------------------
Status IndexCatalog::_upgradeDatabaseMinorVersionIfNeeded( OperationContext* txn,
const string& newPluginName ) {
// first check if requested index requires pdfile minor version to be bumped
if ( IndexNames::existedBefore24(newPluginName) ) {
return Status::OK();
}
Database* db = _collection->_database;
if ( !db->getDatabaseCatalogEntry()->isOlderThan24( txn ) ) {
return Status::OK(); // these checks have already been done
}
auto_ptr<PlanExecutor> exec(
InternalPlanner::collectionScan(txn,
db->_indexesName,
db->getCollection(txn, db->_indexesName)));
BSONObj index;
PlanExecutor::ExecState state;
while ( PlanExecutor::ADVANCED == (state = exec->getNext(&index, NULL)) ) {
const BSONObj key = index.getObjectField("key");
const string plugin = IndexNames::findPluginName(key);
if ( IndexNames::existedBefore24(plugin) )
continue;
const string errmsg = str::stream()
<< "Found pre-existing index " << index << " with invalid type '" << plugin << "'. "
<< "Disallowing creation of new index type '" << newPluginName << "'. See "
<< "http://dochub.mongodb.org/core/index-type-changes"
;
return Status( ErrorCodes::CannotCreateIndex, errmsg );
}
if ( PlanExecutor::IS_EOF != state ) {
warning() << "Internal error while reading system.indexes collection";
}
db->_dbEntry->markIndexSafe24AndUp( txn );
return Status::OK();
}
StatusWith<BSONObj> IndexCatalog::prepareSpecForCreate( OperationContext* txn,
const BSONObj& original ) const {
Status status = _isSpecOk( original );
if ( !status.isOK() )
return StatusWith<BSONObj>( status );
BSONObj fixed = _fixIndexSpec( original );
// we double check with new index spec
status = _isSpecOk( fixed );
if ( !status.isOK() )
return StatusWith<BSONObj>( status );
status = _doesSpecConflictWithExisting( txn, fixed );
if ( !status.isOK() )
return StatusWith<BSONObj>( status );
return StatusWith<BSONObj>( fixed );
}
Status IndexCatalog::createIndex( OperationContext* txn,
BSONObj spec,
bool mayInterrupt,
ShutdownBehavior shutdownBehavior ) {
txn->lockState()->assertWriteLocked( _collection->_database->name() );
_checkMagic();
Status status = _checkUnfinished();
if ( !status.isOK() )
return status;
StatusWith<BSONObj> statusWithSpec = prepareSpecForCreate( txn, spec );
status = statusWithSpec.getStatus();
if ( !status.isOK() )
return status;
spec = statusWithSpec.getValue();
string pluginName = IndexNames::findPluginName( spec["key"].Obj() );
if ( pluginName.size() ) {
Status s = _upgradeDatabaseMinorVersionIfNeeded( txn, pluginName );
if ( !s.isOK() )
return s;
}
// now going to touch disk
IndexBuildBlock indexBuildBlock(txn, _collection, spec);
status = indexBuildBlock.init();
if ( !status.isOK() )
return status;
// sanity checks, etc...
IndexCatalogEntry* entry = indexBuildBlock.getEntry();
invariant( entry );
IndexDescriptor* descriptor = entry->descriptor();
invariant( descriptor );
string idxName = descriptor->indexName(); // out copy for yields, etc...
invariant( entry == _entries.find( descriptor ) );
try {
Client& client = cc();
_inProgressIndexes[descriptor] = &client;
// buildAnIndex can yield. During a yield, the Collection that owns this
// IndexCatalog can be dropped, which means both the Collection and IndexCatalog
// can be destructed out from under us. The runner used by the index build will
// throw a particular exception when it detects that this occurred.
buildAnIndex( txn, _collection, entry, mayInterrupt );
indexBuildBlock.success();
InProgressIndexesMap::iterator it = _inProgressIndexes.find(descriptor);
_inProgressIndexes.erase(it);
// sanity check
invariant( _collection->getCatalogEntry()->isIndexReady( idxName ) );
return Status::OK();
}
catch ( const AssertionException& exc ) {
// At this point, *this may have been destructed, if we dropped the collection
// while we were yielding. indexBuildBlock will not touch an invalid _collection
// pointer if you call abort() on it.
log() << "index build failed." << " spec: " << spec << " error: " << exc;
if ( shutdownBehavior == SHUTDOWN_LEAVE_DIRTY &&
exc.getCode() == ErrorCodes::InterruptedAtShutdown ) {
indexBuildBlock.abort();
}
else if ( exc.getCode() == ErrorCodes::CursorNotFound ) {
// The cursor was killed because the collection was dropped. No need to clean up.
indexBuildBlock.abort();
}
else {
indexBuildBlock.fail();
InProgressIndexesMap::iterator it = _inProgressIndexes.find(descriptor);
_inProgressIndexes.erase(it);
}
return exc.toStatus();
}
}
IndexCatalog::IndexBuildBlock::IndexBuildBlock(OperationContext* txn,
Collection* collection,
const BSONObj& spec )
: _collection( collection ),
_catalog( collection->getIndexCatalog() ),
_ns( _catalog->_collection->ns().ns() ),
_spec( spec.getOwned() ),
_entry( NULL ),
_inProgress( false ),
_txn(txn) {
invariant( collection );
}
Status IndexCatalog::IndexBuildBlock::init() {
// we do special cleanup until we're far enough in
invariant( _inProgress == false );
// need this first for names, etc...
BSONObj keyPattern = _spec.getObjectField("key");
IndexDescriptor* descriptor = new IndexDescriptor( _collection,
IndexNames::findPluginName(keyPattern),
_spec );
auto_ptr<IndexDescriptor> descriptorCleaner( descriptor );
_indexName = descriptor->indexName();
_indexNamespace = descriptor->indexNamespace();
/// ---------- setup on disk structures ----------------
Status status = _collection->getCatalogEntry()->prepareForIndexBuild( _txn, descriptor );
if ( !status.isOK() )
return status;
// at this point we can do normal clean up procedure, so we mark ourselves
// as in progress.
_inProgress = true;
/// ---------- setup in memory structures ----------------
_entry = _catalog->_setupInMemoryStructures(_txn, descriptorCleaner.release());
return Status::OK();
}
IndexCatalog::IndexBuildBlock::~IndexBuildBlock() {
if ( !_inProgress ) {
// taken care of already when success() is called
return;
}
try {
fail();
}
catch ( const AssertionException& exc ) {
log() << "exception in ~IndexBuildBlock trying to cleanup: " << exc;
log() << " going to fassert to preserve state";
fassertFailed( 17345 );
}
}
void IndexCatalog::IndexBuildBlock::fail() {
if ( !_inProgress ) {
// taken care of already when success() is called
return;
}
Client::Context context( _txn,
_collection->ns().ns(),
_collection->_database );
// if we're here, the index build failed or was interrupted
_inProgress = false; // defensive
fassert( 17204, _catalog->_collection->ok() ); // defensive
IndexCatalogEntry* entry = _catalog->_entries.find( _indexName );
invariant( entry == _entry );
try {
if ( entry ) {
_catalog->_dropIndex(_txn, entry);
}
else {
_catalog->_deleteIndexFromDisk( _txn,
_indexName,
_indexNamespace );
}
}
catch (const DBException& exc) {
error() << "exception while cleaning up in-progress index build: " << exc.what();
fassertFailedWithStatus(17493, exc.toStatus());
}
}
void IndexCatalog::IndexBuildBlock::abort() {
_inProgress = false;
}
void IndexCatalog::IndexBuildBlock::success() {
fassert( 17206, _inProgress );
_inProgress = false;
fassert( 17207, _catalog->_collection->ok() );
_catalog->_collection->getCatalogEntry()->indexBuildSuccess( _txn, _indexName );
_catalog->_collection->infoCache()->addedIndex();
IndexDescriptor* desc = _catalog->findIndexByName( _indexName, true );
fassert( 17330, desc );
IndexCatalogEntry* entry = _catalog->_entries.find( desc );
fassert( 17331, entry && entry == _entry );
entry->setIsReady( true );
}
Status IndexCatalog::_isSpecOk( const BSONObj& spec ) const {
const NamespaceString& nss = _collection->ns();
if ( nss.isSystemDotIndexes() )
return Status( ErrorCodes::CannotCreateIndex,
"cannot create indexes on the system.indexes collection" );
if ( nss.isOplog() )
return Status( ErrorCodes::CannotCreateIndex,
"cannot create indexes on the oplog" );
if ( nss.coll() == "$freelist" ) {
// this isn't really proper, but we never want it and its not an error per se
return Status( ErrorCodes::IndexAlreadyExists, "cannot index freelist" );
}
StringData specNamespace = spec.getStringField("ns");
if ( specNamespace.size() == 0 )
return Status( ErrorCodes::CannotCreateIndex,
"the index spec needs a 'ns' field'" );
if ( nss.ns() != specNamespace )
return Status( ErrorCodes::CannotCreateIndex,
"the index spec ns does not match" );
// logical name of the index
const char *name = spec.getStringField("name");
if ( !name[0] )
return Status( ErrorCodes::CannotCreateIndex, "no index name specified" );
string indexNamespace = IndexDescriptor::makeIndexNamespace( specNamespace, name );
if ( indexNamespace.length() > NamespaceString::MaxNsLen )
return Status( ErrorCodes::CannotCreateIndex,
str::stream() << "namespace name generated from index name \"" <<
indexNamespace << "\" is too long (127 byte max)" );
const BSONObj key = spec.getObjectField("key");
const Status keyStatus = validateKeyPattern(key);
if (!keyStatus.isOK()) {
return Status( ErrorCodes::CannotCreateIndex,
str::stream() << "bad index key pattern " << key << ": "
<< keyStatus.reason() );
}
if ( _collection->isCapped() && spec["dropDups"].trueValue() ) {
return Status( ErrorCodes::CannotCreateIndex,
str::stream() << "Cannot create an index with dropDups=true on a "
<< "capped collection, as capped collections do "
<< "not allow document removal." );
}
if ( !IndexDescriptor::isIdIndexPattern( key ) ) {
// for non _id indexes, we check to see if replication has turned off all indexes
// we _always_ created _id index
repl::ReplicationCoordinator* replCoord = repl::getGlobalReplicationCoordinator();
if (replCoord->getReplicationMode() == repl::ReplicationCoordinator::modeReplSet &&
!repl::getGlobalReplicationCoordinator()->buildsIndexes()) {
// this is not exactly the right error code, but I think will make the most sense
return Status( ErrorCodes::IndexAlreadyExists, "no indexes per repl" );
}
}
return Status::OK();
}
Status IndexCatalog::_doesSpecConflictWithExisting( OperationContext* txn,
const BSONObj& spec ) const {
const char *name = spec.getStringField("name");
invariant( name[0] );
const BSONObj key = spec.getObjectField("key");
{
// Check both existing and in-progress indexes (2nd param = true)
const IndexDescriptor* desc = findIndexByName( name, true );
if ( desc ) {
// index already exists with same name
if ( !desc->keyPattern().equal( key ) )
return Status( ErrorCodes::IndexKeySpecsConflict,
str::stream() << "Trying to create an index "
<< "with same name " << name
<< " with different key spec " << key
<< " vs existing spec " << desc->keyPattern() );
IndexDescriptor temp( _collection,
_getAccessMethodName( txn, key ),
spec );
if ( !desc->areIndexOptionsEquivalent( &temp ) )
return Status( ErrorCodes::IndexOptionsConflict,
str::stream() << "Index with name: " << name
<< " already exists with different options" );
// Index already exists with the same options, so no need to build a new
// one (not an error). Most likely requested by a client using ensureIndex.
return Status( ErrorCodes::IndexAlreadyExists, name );
}
}
{
// Check both existing and in-progress indexes (2nd param = true)
const IndexDescriptor* desc = findIndexByKeyPattern(key, true);
if (desc) {
LOG(2) << "index already exists with diff name " << name
<< ' ' << key << endl;
IndexDescriptor temp( _collection,
_getAccessMethodName( txn, key ),
spec );
if ( !desc->areIndexOptionsEquivalent( &temp ) )
return Status( ErrorCodes::IndexOptionsConflict,
str::stream() << "Index with pattern: " << key
<< " already exists with different options" );
return Status( ErrorCodes::IndexAlreadyExists, name );
}
}
if ( _collection->getCatalogEntry()->getTotalIndexCount() >=
_collection->getCatalogEntry()->getMaxAllowedIndexes() ) {
string s = str::stream() << "add index fails, too many indexes for "
<< _collection->ns().ns() << " key:" << key.toString();
log() << s;
return Status( ErrorCodes::CannotCreateIndex, s );
}
// Refuse to build text index if another text index exists or is in progress.
// Collections should only have one text index.
string pluginName = IndexNames::findPluginName( key );
if ( pluginName == IndexNames::TEXT ) {
vector<IndexDescriptor*> textIndexes;
const bool includeUnfinishedIndexes = true;
findIndexByType( IndexNames::TEXT, textIndexes, includeUnfinishedIndexes );
if ( textIndexes.size() > 0 ) {
return Status( ErrorCodes::CannotCreateIndex,
str::stream() << "only one text index per collection allowed, "
<< "found existing text index \"" << textIndexes[0]->indexName()
<< "\"" );
}
}
return Status::OK();
}
Status IndexCatalog::ensureHaveIdIndex(OperationContext* txn) {
if ( haveIdIndex() )
return Status::OK();
dassert( _idObj["_id"].type() == NumberInt );
BSONObjBuilder b;
b.append( "name", "_id_" );
b.append( "ns", _collection->ns().ns() );
b.append( "key", _idObj );
BSONObj o = b.done();
Status s = createIndex(txn, o, false);
if ( s.isOK() || s.code() == ErrorCodes::IndexAlreadyExists ) {
return Status::OK();
}
return s;
}
Status IndexCatalog::dropAllIndexes(OperationContext* txn,
bool includingIdIndex) {
txn->lockState()->assertWriteLocked( _collection->_database->name() );
BackgroundOperation::assertNoBgOpInProgForNs( _collection->ns().ns() );
// there may be pointers pointing at keys in the btree(s). kill them.
// TODO: can this can only clear cursors on this index?
_collection->cursorCache()->invalidateAll( false );
// make sure nothing in progress
massert( 17348,
"cannot dropAllIndexes when index builds in progress",
numIndexesTotal() == numIndexesReady() );
bool haveIdIndex = false;
vector<string> indexNamesToDrop;
{
int seen = 0;
IndexIterator ii = getIndexIterator( true );
while ( ii.more() ) {
seen++;
IndexDescriptor* desc = ii.next();
if ( desc->isIdIndex() && includingIdIndex == false ) {
haveIdIndex = true;
continue;
}
indexNamesToDrop.push_back( desc->indexName() );
}
invariant( seen == numIndexesTotal() );
}
for ( size_t i = 0; i < indexNamesToDrop.size(); i++ ) {
string indexName = indexNamesToDrop[i];
IndexDescriptor* desc = findIndexByName( indexName, true );
invariant( desc );
LOG(1) << "\t dropAllIndexes dropping: " << desc->toString();
IndexCatalogEntry* entry = _entries.find( desc );
invariant( entry );
_dropIndex(txn, entry);
}
// verify state is sane post cleaning
long long numSystemIndexesEntries = 0;
{
Collection* systemIndexes =
_collection->_database->getCollection( txn, _collection->_database->_indexesName );
if ( systemIndexes ) {
EqualityMatchExpression expr;
BSONObj nsBSON = BSON( "ns" << _collection->ns() );
invariant( expr.init( "ns", nsBSON.firstElement() ).isOK() );
numSystemIndexesEntries = systemIndexes->countTableScan( txn, &expr );
}
else {
// this is ok, 0 is the right number
}
}
if ( haveIdIndex ) {
fassert( 17324, numIndexesTotal() == 1 );
fassert( 17325, numIndexesReady() == 1 );
fassert( 17326, numSystemIndexesEntries == 1 );
fassert( 17336, _entries.size() == 1 );
}
else {
if ( numIndexesTotal() || numSystemIndexesEntries || _entries.size() ) {
error() << "About to fassert - "
<< " numIndexesTotal(): " << numIndexesTotal()
<< " numSystemIndexesEntries: " << numSystemIndexesEntries
<< " _entries.size(): " << _entries.size()
<< " indexNamesToDrop: " << indexNamesToDrop.size()
<< " haveIdIndex: " << haveIdIndex;
}
fassert( 17327, numIndexesTotal() == 0 );
fassert( 17328, numSystemIndexesEntries == 0 );
fassert( 17337, _entries.size() == 0 );
}
return Status::OK();
}
Status IndexCatalog::dropIndex(OperationContext* txn,
IndexDescriptor* desc ) {
txn->lockState()->assertWriteLocked( _collection->_database->name() );
IndexCatalogEntry* entry = _entries.find( desc );
if ( !entry )
return Status( ErrorCodes::InternalError, "cannot find index to delete" );
if ( !entry->isReady() )
return Status( ErrorCodes::InternalError, "cannot delete not ready index" );
BackgroundOperation::assertNoBgOpInProgForNs( _collection->ns().ns() );
return _dropIndex(txn, entry);
}
Status IndexCatalog::_dropIndex(OperationContext* txn,
IndexCatalogEntry* entry ) {
/**
* IndexState in order
* <db>.system.indexes
* NamespaceDetails
* <db>.system.ns
*/
// ----- SANITY CHECKS -------------
if ( !entry )
return Status( ErrorCodes::BadValue, "IndexCatalog::_dropIndex passed NULL" );
_checkMagic();
Status status = _checkUnfinished();
if ( !status.isOK() )
return status;
// there may be pointers pointing at keys in the btree(s). kill them.
// TODO: can this can only clear cursors on this index?
_collection->cursorCache()->invalidateAll( false );
// wipe out stats
_collection->infoCache()->reset();
string indexNamespace = entry->descriptor()->indexNamespace();
string indexName = entry->descriptor()->indexName();
// --------- START REAL WORK ----------
audit::logDropIndex( currentClient.get(), indexName, _collection->ns().ns() );
_entries.remove( entry->descriptor() );
entry = NULL;
try {
// **** this is the first disk change ****
_deleteIndexFromDisk( txn,
indexName,
indexNamespace );
}
catch ( std::exception& ) {
// this is bad, and we don't really know state
// going to leak to make sure things are safe
log() << "error dropping index: " << indexNamespace
<< " going to leak some memory to be safe";
_collection->_database->_clearCollectionCache( indexNamespace );
throw;
}
_collection->_database->_clearCollectionCache( indexNamespace );
_checkMagic();
return Status::OK();
}
void IndexCatalog::_deleteIndexFromDisk( OperationContext* txn,
const string& indexName,
const string& indexNamespace ) {
Status status = _collection->getCatalogEntry()->removeIndex( txn, indexName );
if ( status.code() == ErrorCodes::NamespaceNotFound ) {
// this is ok, as we may be partially through index creation
}
else if ( !status.isOK() ) {
warning() << "couldn't drop index " << indexName
<< " on collection: " << _collection->ns()
<< " because of " << status.toString();
}
}
vector<BSONObj> IndexCatalog::getAndClearUnfinishedIndexes(OperationContext* txn) {
vector<BSONObj> toReturn = _unfinishedIndexes;
_unfinishedIndexes.clear();
for ( size_t i = 0; i < toReturn.size(); i++ ) {
BSONObj spec = toReturn[i];
BSONObj keyPattern = spec.getObjectField("key");
IndexDescriptor desc( _collection, _getAccessMethodName(txn, keyPattern), spec );
_deleteIndexFromDisk( txn,
desc.indexName(),
desc.indexNamespace() );
}
return toReturn;
}
bool IndexCatalog::isMultikey( const IndexDescriptor* idx ) {
IndexCatalogEntry* entry = _entries.find( idx );
invariant( entry );
return entry->isMultikey();
}
// ---------------------------
int IndexCatalog::numIndexesTotal() const {
return _collection->getCatalogEntry()->getTotalIndexCount();
}
int IndexCatalog::numIndexesReady() const {
return _collection->getCatalogEntry()->getCompletedIndexCount();
}
bool IndexCatalog::haveIdIndex() const {
return findIdIndex() != NULL;
}
IndexCatalog::IndexIterator::IndexIterator( const IndexCatalog* cat,
bool includeUnfinishedIndexes )
: _includeUnfinishedIndexes( includeUnfinishedIndexes ),
_catalog( cat ),
_iterator( cat->_entries.begin() ),
_start( true ),
_prev( NULL ),
_next( NULL ) {
}
bool IndexCatalog::IndexIterator::more() {
if ( _start ) {
_advance();
_start = false;
}
return _next != NULL;
}
IndexDescriptor* IndexCatalog::IndexIterator::next() {
if ( !more() )
return NULL;
_prev = _next;
_advance();
return _prev->descriptor();
}
IndexAccessMethod* IndexCatalog::IndexIterator::accessMethod( IndexDescriptor* desc ) {
invariant( desc == _prev->descriptor() );
return _prev->accessMethod();
}
void IndexCatalog::IndexIterator::_advance() {
_next = NULL;
while ( _iterator != _catalog->_entries.end() ) {
IndexCatalogEntry* entry = *_iterator;
++_iterator;
if ( _includeUnfinishedIndexes ||
entry->isReady() ) {
_next = entry;
return;
}
}
}
IndexDescriptor* IndexCatalog::findIdIndex() const {
IndexIterator ii = getIndexIterator( false );
while ( ii.more() ) {
IndexDescriptor* desc = ii.next();
if ( desc->isIdIndex() )
return desc;
}
return NULL;
}
IndexDescriptor* IndexCatalog::findIndexByName( const StringData& name,
bool includeUnfinishedIndexes ) const {
IndexIterator ii = getIndexIterator( includeUnfinishedIndexes );
while ( ii.more() ) {
IndexDescriptor* desc = ii.next();
if ( desc->indexName() == name )
return desc;
}
return NULL;
}
IndexDescriptor* IndexCatalog::findIndexByKeyPattern( const BSONObj& key,
bool includeUnfinishedIndexes ) const {
IndexIterator ii = getIndexIterator( includeUnfinishedIndexes );
while ( ii.more() ) {
IndexDescriptor* desc = ii.next();
if ( desc->keyPattern() == key )
return desc;
}
return NULL;
}
IndexDescriptor* IndexCatalog::findIndexByPrefix( const BSONObj &keyPattern,
bool requireSingleKey ) const {
IndexDescriptor* best = NULL;
IndexIterator ii = getIndexIterator( false );
while ( ii.more() ) {
IndexDescriptor* desc = ii.next();
if ( !keyPattern.isPrefixOf( desc->keyPattern() ) )
continue;
if( !desc->isMultikey() )
return desc;
if ( !requireSingleKey )
best = desc;
}
return best;
}
void IndexCatalog::findIndexByType( const string& type , vector<IndexDescriptor*>& matches,
bool includeUnfinishedIndexes ) const {
IndexIterator ii = getIndexIterator( includeUnfinishedIndexes );
while ( ii.more() ) {
IndexDescriptor* desc = ii.next();
if ( IndexNames::findPluginName( desc->keyPattern() ) == type ) {
matches.push_back( desc );
}
}
}
IndexAccessMethod* IndexCatalog::getIndex( const IndexDescriptor* desc ) {
IndexCatalogEntry* entry = _entries.find( desc );
massert( 17334, "cannot find index entry", entry );
return entry->accessMethod();
}
const IndexAccessMethod* IndexCatalog::getIndex( const IndexDescriptor* desc ) const {
return getEntry( desc )->accessMethod();
}
const IndexCatalogEntry* IndexCatalog::getEntry( const IndexDescriptor* desc ) const {
const IndexCatalogEntry* entry = _entries.find( desc );
massert( 17357, "cannot find index entry", entry );
return entry;
}
// ---------------------------
Status IndexCatalog::_indexRecord(OperationContext* txn,
IndexCatalogEntry* index,
const BSONObj& obj,
const DiskLoc &loc ) {
InsertDeleteOptions options;
options.logIfError = false;
bool isUnique =
KeyPattern::isIdKeyPattern(index->descriptor()->keyPattern()) ||
index->descriptor()->unique();
options.dupsAllowed =
repl::getGlobalReplicationCoordinator()->shouldIgnoreUniqueIndex(index->descriptor())
|| !isUnique;
int64_t inserted;
return index->accessMethod()->insert(txn, obj, loc, options, &inserted);
}
Status IndexCatalog::_unindexRecord(OperationContext* txn,
IndexCatalogEntry* index,
const BSONObj& obj,
const DiskLoc &loc,
bool logIfError) {
InsertDeleteOptions options;
options.logIfError = logIfError;
int64_t removed;
Status status = index->accessMethod()->remove(txn, obj, loc, options, &removed);
if ( !status.isOK() ) {
log() << "Couldn't unindex record " << obj.toString()
<< " from collection " << _collection->ns()
<< ". Status: " << status.toString();
}
return Status::OK();
}
void IndexCatalog::indexRecord(OperationContext* txn,
const BSONObj& obj,
const DiskLoc &loc ) {
for ( IndexCatalogEntryContainer::const_iterator i = _entries.begin();
i != _entries.end();
++i ) {
IndexCatalogEntry* entry = *i;
try {
Status s = _indexRecord( txn, entry, obj, loc );
uassert(s.location(), s.reason(), s.isOK() );
}
catch ( AssertionException& ae ) {
LOG(2) << "IndexCatalog::indexRecord failed: " << ae;
for ( IndexCatalogEntryContainer::const_iterator j = _entries.begin();
j != _entries.end();
++j ) {
IndexCatalogEntry* toDelete = *j;
try {
_unindexRecord(txn, toDelete, obj, loc, false);
}
catch ( DBException& e ) {
LOG(1) << "IndexCatalog::indexRecord rollback failed: " << e;
}
if ( toDelete == entry )
break;
}
throw;
}
}
}
void IndexCatalog::unindexRecord(OperationContext* txn,
const BSONObj& obj,
const DiskLoc& loc,
bool noWarn) {
for ( IndexCatalogEntryContainer::const_iterator i = _entries.begin();
i != _entries.end();
++i ) {
IndexCatalogEntry* entry = *i;
// If it's a background index, we DO NOT want to log anything.
bool logIfError = entry->isReady() ? !noWarn : false;
_unindexRecord(txn, entry, obj, loc, logIfError);
}
}
Status IndexCatalog::checkNoIndexConflicts( OperationContext* txn, const BSONObj &obj ) {
IndexIterator ii = getIndexIterator( true );
while ( ii.more() ) {
IndexDescriptor* descriptor = ii.next();
if ( !descriptor->unique() )
continue;
if (repl::getGlobalReplicationCoordinator()->shouldIgnoreUniqueIndex(descriptor))
continue;
IndexAccessMethod* iam = getIndex( descriptor );
InsertDeleteOptions options;
options.logIfError = false;
options.dupsAllowed = false;
UpdateTicket ticket;
Status ret = iam->validateUpdate(txn, BSONObj(), obj, DiskLoc(), options, &ticket);
if ( !ret.isOK() )
return ret;
}
return Status::OK();
}
BSONObj IndexCatalog::fixIndexKey( const BSONObj& key ) {
if ( IndexDescriptor::isIdIndexPattern( key ) ) {
return _idObj;
}
if ( key["_id"].type() == Bool && key.nFields() == 1 ) {
return _idObj;
}
return key;
}
BSONObj IndexCatalog::_fixIndexSpec( const BSONObj& spec ) {
BSONObj o = IndexLegacy::adjustIndexSpecObject( spec );
BSONObjBuilder b;
int v = DefaultIndexVersionNumber;
if( !o["v"].eoo() ) {
double vv = o["v"].Number();
// note (one day) we may be able to fresh build less versions than we can use
// isASupportedIndexVersionNumber() is what we can use
uassert(14803, str::stream() << "this version of mongod cannot build new indexes of version number " << vv,
vv == 0 || vv == 1);
v = (int) vv;
}
// idea is to put things we use a lot earlier
b.append("v", v);
if( o["unique"].trueValue() )
b.appendBool("unique", true); // normalize to bool true in case was int 1 or something...
BSONObj key = fixIndexKey( o["key"].Obj() );
b.append( "key", key );
string name = o["name"].String();
if ( IndexDescriptor::isIdIndexPattern( key ) ) {
name = "_id_";
}
b.append( "name", name );
{
BSONObjIterator i(o);
while ( i.more() ) {
BSONElement e = i.next();
string s = e.fieldName();
if ( s == "_id" ) {
// skip
}
else if ( s == "v" || s == "unique" ||
s == "key" || s == "name" ) {
// covered above
}
else if ( s == "key" ) {
b.append( "key", fixIndexKey( e.Obj() ) );
}
else {
b.append(e);
}
}
}
return b.obj();
}
std::vector<BSONObj>
IndexCatalog::killMatchingIndexBuilds(const IndexCatalog::IndexKillCriteria& criteria) {
std::vector<BSONObj> indexes;
for (InProgressIndexesMap::iterator it = _inProgressIndexes.begin();
it != _inProgressIndexes.end();
it++) {
// check criteria
IndexDescriptor* desc = it->first;
Client* client = it->second;
if (!criteria.ns.empty() && (desc->parentNS() != criteria.ns)) {
continue;
}
if (!criteria.name.empty() && (desc->indexName() != criteria.name)) {
continue;
}
if (!criteria.key.isEmpty() && (desc->keyPattern() != criteria.key)) {
continue;
}
indexes.push_back(desc->keyPattern());
CurOp* op = client->curop();
log() << "halting index build: " << desc->keyPattern();
// Note that we can only be here if the background index build in question is
// yielding. The bg index code is set up specially to check for interrupt
// immediately after it recovers from yield, such that no further work is done
// on the index build. Thus this thread does not have to synchronize with the
// bg index operation; we can just assume that it is safe to proceed.
getGlobalEnvironment()->killOperation(op->opNum());
}
if (indexes.size() > 0) {
log() << "halted " << indexes.size() << " index build(s)" << endl;
}
return indexes;
}
}
|