summaryrefslogtreecommitdiff
path: root/src/mongo/db/catalog/index_catalog_impl.h
blob: 3c09fec3fb4d5659331d5f0dc9a15737509b1ade (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
/**
 *    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.
 */

#pragma once

#include <vector>

#include "mongo/db/catalog/index_catalog.h"

#include "mongo/db/catalog/index_catalog_entry.h"
#include "mongo/db/index/index_build_interceptor.h"
#include "mongo/db/index/multikey_paths.h"
#include "mongo/db/jsobj.h"
#include "mongo/db/operation_context.h"
#include "mongo/db/record_id.h"
#include "mongo/db/server_options.h"
#include "mongo/db/storage/record_store.h"

namespace mongo {

class Client;
class Collection;
class CollectionPtr;

class IndexDescriptor;
struct InsertDeleteOptions;

/**
 * IndexCatalogImpl is stored as a member of CollectionImpl. When the Collection is cloned this is
 * cloned with it by making shallow copies of the contained IndexCatalogEntry. The IndexCatalogEntry
 * instances are shared across multiple Collection instances.
 */
class IndexCatalogImpl : public IndexCatalog {
public:
    /**
     * Creates a cloned IndexCatalogImpl. Will make shallow copies of IndexCatalogEntryContainers so
     * the IndexCatalogEntry will be shared across IndexCatalogImpl instances'
     */
    std::unique_ptr<IndexCatalog> clone() const override;

    // must be called before used
    void init(OperationContext* opCtx, Collection* collection) override;

    /**
     * Must be called before used.
     */
    void initFromExisting(OperationContext* opCtx,
                          Collection* collection,
                          boost::optional<Timestamp> readTimestamp) override;

    // ---- accessors -----

    bool haveAnyIndexes() const override;
    bool haveAnyIndexesInProgress() const override;
    int numIndexesTotal() const override;
    int numIndexesReady() const override;
    int numIndexesInProgress() const override;

    /**
     * this is in "alive" until the Collection goes away
     * in which case everything from this tree has to go away.
     */

    bool haveIdIndex(OperationContext* opCtx) const override;

    /**
     * Returns the spec for the id index to create by default for this collection.
     */
    BSONObj getDefaultIdIndexSpec(const CollectionPtr& collection) const override;

    const IndexDescriptor* findIdIndex(OperationContext* opCtx) const override;

    /**
     * Find index by name.  The index name uniquely identifies an index.
     *
     * @return null if cannot find
     */
    const IndexDescriptor* findIndexByName(
        OperationContext* opCtx,
        StringData name,
        InclusionPolicy inclusionPolicy = InclusionPolicy::kReady) const override;

    /**
     * Find index by matching key pattern and options. The key pattern, collation spec, and partial
     * filter expression together uniquely identify an index.
     *
     * @return null if cannot find index, otherwise the index with a matching signature.
     */
    const IndexDescriptor* findIndexByKeyPatternAndOptions(
        OperationContext* opCtx,
        const BSONObj& key,
        const BSONObj& indexSpec,
        InclusionPolicy inclusionPolicy = InclusionPolicy::kReady) const override;

    /**
     * Find indexes with a matching key pattern, putting them into the vector 'matches'.  The key
     * pattern alone does not uniquely identify an index.
     *
     * Consider using 'findIndexByName' if expecting to match one index.
     */
    void findIndexesByKeyPattern(OperationContext* opCtx,
                                 const BSONObj& key,
                                 InclusionPolicy inclusionPolicy,
                                 std::vector<const IndexDescriptor*>* matches) const override;
    void findIndexByType(OperationContext* opCtx,
                         const std::string& type,
                         std::vector<const IndexDescriptor*>& matches,
                         InclusionPolicy inclusionPolicy = InclusionPolicy::kReady) const override;


    /**
     * Reload the index definition for 'oldDesc' from the CollectionCatalogEntry.  'oldDesc'
     * must be a ready index that is already registered with the index catalog.  Returns an
     * unowned pointer to the descriptor for the new index definition.
     *
     * Use this method to notify the IndexCatalog that the spec for this index has changed.
     *
     * It is invalid to dereference 'oldDesc' after calling this method.
     *
     * The caller must hold the collection X lock and ensure no index builds are in progress
     * on the collection.
     */
    const IndexDescriptor* refreshEntry(OperationContext* opCtx,
                                        Collection* collection,
                                        const IndexDescriptor* oldDesc,
                                        CreateIndexEntryFlags flags) override;

    const IndexCatalogEntry* getEntry(const IndexDescriptor* desc) const override;

    std::shared_ptr<const IndexCatalogEntry> getEntryShared(const IndexDescriptor*) const override;

    std::shared_ptr<IndexCatalogEntry> getEntryShared(const IndexDescriptor*) override;

    std::vector<std::shared_ptr<const IndexCatalogEntry>> getAllReadyEntriesShared() const override;

    using IndexIterator = IndexCatalog::IndexIterator;
    std::unique_ptr<IndexIterator> getIndexIterator(OperationContext* opCtx,
                                                    InclusionPolicy inclusionPolicy) const override;

    // ---- index set modifiers ------

    IndexCatalogEntry* createIndexEntry(OperationContext* opCtx,
                                        Collection* collection,
                                        std::unique_ptr<IndexDescriptor> descriptor,
                                        CreateIndexEntryFlags flags) override;

    /**
     * Call this only on an empty collection from inside a WriteUnitOfWork. Index creation on an
     * empty collection can be rolled back as part of a larger WUOW. Returns the full specification
     * of the created index, as it is stored in this index catalog.
     */
    StatusWith<BSONObj> createIndexOnEmptyCollection(OperationContext* opCtx,
                                                     Collection* collection,
                                                     BSONObj spec) override;

    StatusWith<BSONObj> prepareSpecForCreate(
        OperationContext* opCtx,
        const CollectionPtr& collection,
        const BSONObj& original,
        const boost::optional<ResumeIndexInfo>& resumeInfo = boost::none) const override;

    std::vector<BSONObj> removeExistingIndexes(OperationContext* opCtx,
                                               const CollectionPtr& collection,
                                               const std::vector<BSONObj>& indexSpecsToBuild,
                                               bool removeIndexBuildsToo) const override;

    std::vector<BSONObj> removeExistingIndexesNoChecks(
        OperationContext* opCtx,
        const CollectionPtr& collection,
        const std::vector<BSONObj>& indexSpecsToBuild) const override;

    void dropIndexes(OperationContext* opCtx,
                     Collection* collection,
                     std::function<bool(const IndexDescriptor*)> matchFn,
                     std::function<void(const IndexDescriptor*)> onDropFn) override;
    void dropAllIndexes(OperationContext* opCtx,
                        Collection* collection,
                        bool includingIdIndex,
                        std::function<void(const IndexDescriptor*)> onDropFn) override;

    Status dropIndex(OperationContext* opCtx,
                     Collection* collection,
                     const IndexDescriptor* desc) override;
    Status resetUnfinishedIndexForRecovery(OperationContext* opCtx,
                                           Collection* collection,
                                           const IndexDescriptor* desc) override;
    Status dropUnfinishedIndex(OperationContext* opCtx,
                               Collection* collection,
                               const IndexDescriptor* desc) override;

    Status dropIndexEntry(OperationContext* opCtx,
                          Collection* collection,
                          IndexCatalogEntry* entry) override;


    void deleteIndexFromDisk(OperationContext* opCtx,
                             Collection* collection,
                             const std::string& indexName) override;

    struct IndexKillCriteria {
        std::string ns;
        std::string name;
        BSONObj key;
    };

    // ---- modify single index

    void setMultikeyPaths(OperationContext* opCtx,
                          const CollectionPtr& coll,
                          const IndexDescriptor* desc,
                          const KeyStringSet& multikeyMetadataKeys,
                          const MultikeyPaths& multikeyPaths) const override;

    // ----- data modifiers ------

    /**
     * When 'keysInsertedOut' is not null, it will be set to the number of index keys inserted by
     * this operation.
     *
     * This method may throw.
     */
    Status indexRecords(OperationContext* opCtx,
                        const CollectionPtr& coll,
                        const std::vector<BsonRecord>& bsonRecords,
                        int64_t* keysInsertedOut) const override;

    /**
     * See IndexCatalog::updateRecord
     */
    Status updateRecord(OperationContext* opCtx,
                        const CollectionPtr& coll,
                        const BSONObj& oldDoc,
                        const BSONObj& newDoc,
                        const RecordId& recordId,
                        int64_t* keysInsertedOut,
                        int64_t* keysDeletedOut) const override;
    /**
     * When 'keysDeletedOut' is not null, it will be set to the number of index keys removed by
     * this operation.
     */
    void unindexRecord(OperationContext* opCtx,
                       const CollectionPtr& collection,
                       const BSONObj& obj,
                       const RecordId& loc,
                       bool noWarn,
                       int64_t* keysDeletedOut,
                       CheckRecordId checkRecordId = CheckRecordId::Off) const override;

    Status compactIndexes(OperationContext* opCtx) const override;

    inline std::string getAccessMethodName(const BSONObj& keyPattern) override {
        return _getAccessMethodName(keyPattern);
    }

    std::string::size_type getLongestIndexNameLength(OperationContext* opCtx) const override;

    // public static helpers

    BSONObj fixIndexKey(const BSONObj& key) const override;

    /**
     * Fills out 'options' in order to indicate whether to allow dups or relax
     * index constraints, as needed by replication.
     */
    void prepareInsertDeleteOptions(OperationContext* opCtx,
                                    const NamespaceString&,
                                    const IndexDescriptor* desc,
                                    InsertDeleteOptions* options) const override;

    void indexBuildSuccess(OperationContext* opCtx,
                           Collection* coll,
                           IndexCatalogEntry* index) override;

    /**
     * Returns a status indicating whether 'expression' is valid for use in a partial index
     * partialFilterExpression.
     */
    static Status checkValidFilterExpressions(const MatchExpression* expression,
                                              bool timeseriesMetricIndexesFeatureFlagEnabled);

private:
    static const BSONObj _idObj;  // { _id : 1 }

    /**
     * Helper for init() and initFromExisting().
     */
    void _init(OperationContext* opCtx,
               Collection* collection,
               boost::optional<Timestamp> readTimestamp,
               bool fromExisting);

    /**
     * In addition to IndexNames::findPluginName, validates that it is a known index type.
     * If all you need is to check for a certain type, just use IndexNames::findPluginName.
     *
     * Uasserts if the index type is unknown.
     */
    std::string _getAccessMethodName(const BSONObj& keyPattern) const;

    Status _indexFilteredRecords(OperationContext* opCtx,
                                 const CollectionPtr& coll,
                                 const IndexCatalogEntry* index,
                                 const std::vector<BsonRecord>& bsonRecords,
                                 int64_t* keysInsertedOut) const;

    Status _indexRecords(OperationContext* opCtx,
                         const CollectionPtr& coll,
                         const IndexCatalogEntry* index,
                         const std::vector<BsonRecord>& bsonRecords,
                         int64_t* keysInsertedOut) const;

    Status _updateRecord(OperationContext* opCtx,
                         const CollectionPtr& coll,
                         const IndexCatalogEntry* index,
                         const BSONObj& oldDoc,
                         const BSONObj& newDoc,
                         const RecordId& recordId,
                         int64_t* keysInsertedOut,
                         int64_t* keysDeletedOut) const;

    void _unindexRecord(OperationContext* opCtx,
                        const CollectionPtr& collection,
                        const IndexCatalogEntry* entry,
                        const BSONObj& obj,
                        const RecordId& loc,
                        bool logIfError,
                        int64_t* keysDeletedOut,
                        CheckRecordId checkRecordId = CheckRecordId::Off) const;

    /**
     * Helper to remove the index from disk.
     * The index should be removed from the in-memory catalog beforehand.
     */
    void _deleteIndexFromDisk(OperationContext* opCtx,
                              Collection* collection,
                              const std::string& indexName,
                              std::shared_ptr<IndexCatalogEntry> entry);

    /**
     * Applies a set of transformations to the user-provided index object 'spec' to make it
     * conform to the standard for insertion.  Removes the '_id' field if it exists, applies
     * plugin-level transformations if appropriate, etc.
     */
    StatusWith<BSONObj> _fixIndexSpec(OperationContext* opCtx,
                                      const CollectionPtr& collection,
                                      const BSONObj& spec) const;

    Status _isSpecOk(OperationContext* opCtx,
                     const CollectionPtr& collection,
                     const BSONObj& spec) const;

    /**
     * Validates the 'original' index specification, alters any legacy fields and does plugin-level
     * transformations for text and geo indexes. Returns a clean spec ready to be built, or an
     * error.
     */
    StatusWith<BSONObj> _validateAndFixIndexSpec(OperationContext* opCtx,
                                                 const CollectionPtr& collection,
                                                 const BSONObj& original) const;

    /**
     * Checks whether there are any spec conflicts with existing ready indexes or in-progress index
     * builds. Also checks whether any limits set on this server would be exceeded by building the
     * index. 'includeUnfinishedIndexes' dictates whether in-progress index builds are checked for
     * conflicts, along with ready indexes.
     *
     * Returns IndexAlreadyExists for both ready and in-progress index builds. Can also return other
     * errors.
     */
    Status _doesSpecConflictWithExisting(OperationContext* opCtx,
                                         const CollectionPtr& collection,
                                         const BSONObj& spec,
                                         InclusionPolicy inclusionPolicy) const;

    /**
     * Returns true if the replica set member's config has {buildIndexes:false} set, which means
     * we are not allowed to build non-_id indexes on this server, AND this index spec is for a
     * non-_id index.
     */
    Status _isNonIDIndexAndNotAllowedToBuild(OperationContext* opCtx, const BSONObj& spec) const;

    void _logInternalState(OperationContext* opCtx,
                           const CollectionPtr& collection,
                           long long numIndexesInCollectionCatalogEntry,
                           const std::vector<std::string>& indexNamesToDrop);

    IndexCatalogEntryContainer _readyIndexes;
    IndexCatalogEntryContainer _buildingIndexes;
    IndexCatalogEntryContainer _frozenIndexes;
};
}  // namespace mongo