1
2 /**
3 * Copyright (C) 2018-present MongoDB, Inc.
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the Server Side Public License, version 1,
7 * as published by MongoDB, Inc.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * Server Side Public License for more details.
13 *
14 * You should have received a copy of the Server Side Public License
15 * along with this program. If not, see
16 * <http://www.mongodb.com/licensing/server-side-public-license>.
17 *
18 * As a special exception, the copyright holders give permission to link the
19 * code of portions of this program with the OpenSSL library under certain
20 * conditions as described in each individual source file and distribute
21 * linked combinations including the program with the OpenSSL library. You
22 * must comply with the Server Side Public License in all respects for
23 * all of the code used other than as permitted herein. If you modify file(s)
24 * with this exception, you may extend this exception to your version of the
25 * file(s), but you are not obligated to do so. If you do not wish to do so,
26 * delete this exception statement from your version. If you delete this
27 * exception statement from all source files in the program, then also delete
28 * it in the license file.
29 */
30
31 #define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kStorage
32
33 #include "mongo/platform/basic.h"
34
35 #include "mongo/db/catalog/collection_info_cache_impl.h"
36
37 #include "mongo/base/init.h"
38 #include "mongo/db/catalog/collection.h"
39 #include "mongo/db/catalog/index_catalog.h"
40 #include "mongo/db/concurrency/d_concurrency.h"
41 #include "mongo/db/fts/fts_spec.h"
42 #include "mongo/db/index/index_descriptor.h"
43 #include "mongo/db/index_legacy.h"
44 #include "mongo/db/query/plan_cache.h"
45 #include "mongo/db/query/planner_ixselect.h"
46 #include "mongo/db/service_context.h"
47 #include "mongo/db/ttl_collection_cache.h"
48 #include "mongo/stdx/memory.h"
49 #include "mongo/util/clock_source.h"
50 #include "mongo/util/debug_util.h"
51 #include "mongo/util/log.h"
52
53 namespace mongo {
54 namespace {
MONGO_INITIALIZER(InitializeCollectionInfoCacheFactory)55 MONGO_INITIALIZER(InitializeCollectionInfoCacheFactory)(InitializerContext* const) {
56 CollectionInfoCache::registerFactory(
57 [](Collection* const collection, const NamespaceString& ns) {
58 return stdx::make_unique<CollectionInfoCacheImpl>(collection, ns);
59 });
60 return Status::OK();
61 }
62 } // namespace
63
CollectionInfoCacheImpl(Collection * collection,const NamespaceString & ns)64 CollectionInfoCacheImpl::CollectionInfoCacheImpl(Collection* collection, const NamespaceString& ns)
65 : _collection(collection),
66 _ns(ns),
67 _keysComputed(false),
68 _planCache(stdx::make_unique<PlanCache>(ns.ns())),
69 _querySettings(stdx::make_unique<QuerySettings>()),
70 _indexUsageTracker(getGlobalServiceContext()->getPreciseClockSource()) {}
71
~CollectionInfoCacheImpl()72 CollectionInfoCacheImpl::~CollectionInfoCacheImpl() {
73 // Necessary because the collection cache will not explicitly get updated upon database drop.
74 if (_hasTTLIndex) {
75 TTLCollectionCache& ttlCollectionCache = TTLCollectionCache::get(getGlobalServiceContext());
76 ttlCollectionCache.unregisterCollection(_ns);
77 }
78 }
79
getIndexKeys(OperationContext * opCtx) const80 const UpdateIndexData& CollectionInfoCacheImpl::getIndexKeys(OperationContext* opCtx) const {
81 // This requires "some" lock, and MODE_IS is an expression for that, for now.
82 dassert(opCtx->lockState()->isCollectionLockedForMode(_collection->ns().ns(), MODE_IS));
83 invariant(_keysComputed);
84 return _indexedPaths;
85 }
86
computeIndexKeys(OperationContext * opCtx)87 void CollectionInfoCacheImpl::computeIndexKeys(OperationContext* opCtx) {
88 _indexedPaths.clear();
89
90 bool hadTTLIndex = _hasTTLIndex;
91 _hasTTLIndex = false;
92
93 IndexCatalog::IndexIterator i = _collection->getIndexCatalog()->getIndexIterator(opCtx, true);
94 while (i.more()) {
95 IndexDescriptor* descriptor = i.next();
96
97 if (descriptor->getAccessMethodName() != IndexNames::TEXT) {
98 BSONObj key = descriptor->keyPattern();
99 const BSONObj& infoObj = descriptor->infoObj();
100 if (infoObj.hasField("expireAfterSeconds")) {
101 _hasTTLIndex = true;
102 }
103 BSONObjIterator j(key);
104 while (j.more()) {
105 BSONElement e = j.next();
106 _indexedPaths.addPath(e.fieldName());
107 }
108 } else {
109 fts::FTSSpec ftsSpec(descriptor->infoObj());
110
111 if (ftsSpec.wildcard()) {
112 _indexedPaths.allPathsIndexed();
113 } else {
114 for (size_t i = 0; i < ftsSpec.numExtraBefore(); ++i) {
115 _indexedPaths.addPath(ftsSpec.extraBefore(i));
116 }
117 for (fts::Weights::const_iterator it = ftsSpec.weights().begin();
118 it != ftsSpec.weights().end();
119 ++it) {
120 _indexedPaths.addPath(it->first);
121 }
122 for (size_t i = 0; i < ftsSpec.numExtraAfter(); ++i) {
123 _indexedPaths.addPath(ftsSpec.extraAfter(i));
124 }
125 // Any update to a path containing "language" as a component could change the
126 // language of a subdocument. Add the override field as a path component.
127 _indexedPaths.addPathComponent(ftsSpec.languageOverrideField());
128 }
129 }
130
131 // handle partial indexes
132 const IndexCatalogEntry* entry = i.catalogEntry(descriptor);
133 const MatchExpression* filter = entry->getFilterExpression();
134 if (filter) {
135 unordered_set<std::string> paths;
136 QueryPlannerIXSelect::getFields(filter, "", &paths);
137 for (auto it = paths.begin(); it != paths.end(); ++it) {
138 _indexedPaths.addPath(*it);
139 }
140 }
141 }
142
143 TTLCollectionCache& ttlCollectionCache = TTLCollectionCache::get(getGlobalServiceContext());
144
145 if (_hasTTLIndex != hadTTLIndex) {
146 if (_hasTTLIndex) {
147 ttlCollectionCache.registerCollection(_collection->ns());
148 } else {
149 ttlCollectionCache.unregisterCollection(_collection->ns());
150 }
151 }
152
153 _keysComputed = true;
154 }
155
notifyOfQuery(OperationContext * opCtx,const std::set<std::string> & indexesUsed)156 void CollectionInfoCacheImpl::notifyOfQuery(OperationContext* opCtx,
157 const std::set<std::string>& indexesUsed) {
158 // Record indexes used to fulfill query.
159 for (auto it = indexesUsed.begin(); it != indexesUsed.end(); ++it) {
160 // This index should still exist, since the PlanExecutor would have been killed if the
161 // index was dropped (and we would not get here).
162 dassert(NULL != _collection->getIndexCatalog()->findIndexByName(opCtx, *it));
163
164 _indexUsageTracker.recordIndexAccess(*it);
165 }
166 }
167
clearQueryCache()168 void CollectionInfoCacheImpl::clearQueryCache() {
169 LOG(1) << _collection->ns().ns() << ": clearing plan cache - collection info cache reset";
170 if (NULL != _planCache.get()) {
171 _planCache->clear();
172 }
173 }
174
getPlanCache() const175 PlanCache* CollectionInfoCacheImpl::getPlanCache() const {
176 return _planCache.get();
177 }
178
getQuerySettings() const179 QuerySettings* CollectionInfoCacheImpl::getQuerySettings() const {
180 return _querySettings.get();
181 }
182
updatePlanCacheIndexEntries(OperationContext * opCtx)183 void CollectionInfoCacheImpl::updatePlanCacheIndexEntries(OperationContext* opCtx) {
184 std::vector<IndexEntry> indexEntries;
185
186 // TODO We shouldn't need to include unfinished indexes, but we must here because the index
187 // catalog may be in an inconsistent state. SERVER-18346.
188 const bool includeUnfinishedIndexes = true;
189 IndexCatalog::IndexIterator ii =
190 _collection->getIndexCatalog()->getIndexIterator(opCtx, includeUnfinishedIndexes);
191 while (ii.more()) {
192 const IndexDescriptor* desc = ii.next();
193 const IndexCatalogEntry* ice = ii.catalogEntry(desc);
194 indexEntries.emplace_back(desc->keyPattern(),
195 desc->getAccessMethodName(),
196 desc->isMultikey(opCtx),
197 ice->getMultikeyPaths(opCtx),
198 desc->isSparse(),
199 desc->unique(),
200 desc->indexName(),
201 ice->getFilterExpression(),
202 desc->infoObj(),
203 ice->getCollator());
204 }
205
206 _planCache->notifyOfIndexEntries(indexEntries);
207 }
208
init(OperationContext * opCtx)209 void CollectionInfoCacheImpl::init(OperationContext* opCtx) {
210 // Requires exclusive collection lock.
211 invariant(opCtx->lockState()->isCollectionLockedForMode(_collection->ns().ns(), MODE_X));
212
213 const bool includeUnfinishedIndexes = false;
214 IndexCatalog::IndexIterator ii =
215 _collection->getIndexCatalog()->getIndexIterator(opCtx, includeUnfinishedIndexes);
216 while (ii.more()) {
217 const IndexDescriptor* desc = ii.next();
218 _indexUsageTracker.registerIndex(desc->indexName(), desc->keyPattern());
219 }
220
221 rebuildIndexData(opCtx);
222 }
223
addedIndex(OperationContext * opCtx,const IndexDescriptor * desc)224 void CollectionInfoCacheImpl::addedIndex(OperationContext* opCtx, const IndexDescriptor* desc) {
225 // Requires exclusive collection lock.
226 invariant(opCtx->lockState()->isCollectionLockedForMode(_collection->ns().ns(), MODE_X));
227 invariant(desc);
228
229 rebuildIndexData(opCtx);
230
231 _indexUsageTracker.registerIndex(desc->indexName(), desc->keyPattern());
232 }
233
droppedIndex(OperationContext * opCtx,StringData indexName)234 void CollectionInfoCacheImpl::droppedIndex(OperationContext* opCtx, StringData indexName) {
235 // Requires exclusive collection lock.
236 invariant(opCtx->lockState()->isCollectionLockedForMode(_collection->ns().ns(), MODE_X));
237
238 rebuildIndexData(opCtx);
239 _indexUsageTracker.unregisterIndex(indexName);
240 }
241
rebuildIndexData(OperationContext * opCtx)242 void CollectionInfoCacheImpl::rebuildIndexData(OperationContext* opCtx) {
243 clearQueryCache();
244
245 _keysComputed = false;
246 computeIndexKeys(opCtx);
247 updatePlanCacheIndexEntries(opCtx);
248 }
249
getIndexUsageStats() const250 CollectionIndexUsageMap CollectionInfoCacheImpl::getIndexUsageStats() const {
251 return _indexUsageTracker.getUsageStats();
252 }
253 } // namespace mongo
254