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
|
/**
* 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_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kSharding
#include "mongo/platform/basic.h"
#include "mongo/db/s/shard_filtering_metadata_refresh.h"
#include "mongo/db/catalog/database_holder.h"
#include "mongo/db/catalog_raii.h"
#include "mongo/db/commands/feature_compatibility_version.h"
#include "mongo/db/operation_context.h"
#include "mongo/db/s/collection_sharding_runtime.h"
#include "mongo/db/s/database_sharding_state.h"
#include "mongo/db/s/operation_sharding_state.h"
#include "mongo/db/s/sharding_state.h"
#include "mongo/db/s/sharding_statistics.h"
#include "mongo/s/catalog_cache.h"
#include "mongo/s/grid.h"
#include "mongo/util/fail_point_service.h"
#include "mongo/util/log.h"
namespace mongo {
MONGO_FAIL_POINT_DEFINE(skipDatabaseVersionMetadataRefresh);
MONGO_FAIL_POINT_DEFINE(skipShardFilteringMetadataRefresh);
namespace {
void onShardVersionMismatch(OperationContext* opCtx,
const NamespaceString& nss,
ChunkVersion shardVersionReceived,
bool forceRefreshFromThisThread) {
invariant(!opCtx->lockState()->isLocked());
invariant(!opCtx->getClient()->isInDirectClient());
invariant(ShardingState::get(opCtx)->canAcceptShardedCommands());
LOG(2) << "Metadata refresh requested for " << nss.ns() << " at shard version "
<< shardVersionReceived;
ShardingStatistics::get(opCtx).countStaleConfigErrors.addAndFetch(1);
// Ensure any ongoing migrations have completed before trying to do the refresh. This wait is
// just an optimization so that mongos does not exhaust its maximum number of StaleShardVersion
// retry attempts while the migration is being committed.
OperationShardingState::get(opCtx).waitForMigrationCriticalSectionSignal(opCtx);
const auto currentShardVersion = [&] {
// Avoid using AutoGetCollection() as it returns the InvalidViewDefinition error code
// if an invalid view is in the 'system.views' collection.
AutoGetDb autoDb(opCtx, nss.db(), MODE_IS);
Lock::CollectionLock collLock(opCtx, nss, MODE_IS);
return CollectionShardingState::get(opCtx, nss)->getCurrentShardVersionIfKnown();
}();
if (currentShardVersion) {
if (currentShardVersion->epoch() == shardVersionReceived.epoch() &&
currentShardVersion->majorVersion() >= shardVersionReceived.majorVersion()) {
// Don't need to remotely reload if we're in the same epoch and the requested version is
// smaller than the one we know about. This means that the remote side is behind.
return;
}
}
if (MONGO_FAIL_POINT(skipShardFilteringMetadataRefresh)) {
return;
}
forceShardFilteringMetadataRefresh(opCtx, nss, forceRefreshFromThisThread);
}
void onDbVersionMismatch(OperationContext* opCtx,
const StringData dbName,
const DatabaseVersion& clientDbVersion,
const boost::optional<DatabaseVersion>& serverDbVersion) {
invariant(!opCtx->lockState()->isLocked());
invariant(!opCtx->getClient()->isInDirectClient());
invariant(ShardingState::get(opCtx)->canAcceptShardedCommands());
if (serverDbVersion && serverDbVersion->getUuid() == clientDbVersion.getUuid() &&
serverDbVersion->getLastMod() >= clientDbVersion.getLastMod()) {
// The client was stale; do not trigger server-side refresh.
return;
}
// Ensure any ongoing movePrimary's have completed before trying to do the refresh. This wait is
// just an optimization so that mongos does not exhaust its maximum number of
// StaleDatabaseVersion retry attempts while the movePrimary is being committed.
OperationShardingState::get(opCtx).waitForMovePrimaryCriticalSectionSignal(opCtx);
if (MONGO_FAIL_POINT(skipDatabaseVersionMetadataRefresh)) {
return;
}
forceDatabaseRefresh(opCtx, dbName);
}
} // namespace
Status onShardVersionMismatchNoExcept(OperationContext* opCtx,
const NamespaceString& nss,
ChunkVersion shardVersionReceived,
bool forceRefreshFromThisThread) noexcept {
try {
onShardVersionMismatch(opCtx, nss, shardVersionReceived, forceRefreshFromThisThread);
return Status::OK();
} catch (const DBException& ex) {
log() << "Failed to refresh metadata for collection " << nss << causedBy(redact(ex));
return ex.toStatus();
}
}
ChunkVersion forceShardFilteringMetadataRefresh(OperationContext* opCtx,
const NamespaceString& nss,
bool forceRefreshFromThisThread) {
invariant(!opCtx->lockState()->isLocked());
invariant(!opCtx->getClient()->isInDirectClient());
auto* const shardingState = ShardingState::get(opCtx);
invariant(shardingState->canAcceptShardedCommands());
auto routingInfo =
uassertStatusOK(Grid::get(opCtx)->catalogCache()->getCollectionRoutingInfoWithRefresh(
opCtx, nss, forceRefreshFromThisThread));
auto cm = routingInfo.cm();
if (!cm) {
// No chunk manager, so unsharded. Avoid using AutoGetCollection() as it returns the
// InvalidViewDefinition error code if an invalid view is in the 'system.views' collection.
AutoGetDb autoDb(opCtx, nss.db(), MODE_IX);
Lock::CollectionLock collLock(opCtx, nss, MODE_IX);
CollectionShardingRuntime::get(opCtx, nss)
->setFilteringMetadata(opCtx, CollectionMetadata());
return ChunkVersion::UNSHARDED();
}
// Optimistic check with only IS lock in order to avoid threads piling up on the collection X
// lock below
{
// Avoid using AutoGetCollection() as it returns the InvalidViewDefinition error code
// if an invalid view is in the 'system.views' collection.
AutoGetDb autoDb(opCtx, nss.db(), MODE_IS);
Lock::CollectionLock collLock(opCtx, nss, MODE_IS);
auto optMetadata = CollectionShardingState::get(opCtx, nss)->getCurrentMetadataIfKnown();
// We already have newer version
if (optMetadata) {
const auto& metadata = *optMetadata;
if (metadata->isSharded() &&
metadata->getCollVersion().epoch() == cm->getVersion().epoch() &&
metadata->getCollVersion() >= cm->getVersion()) {
LOG(1) << "Skipping refresh of metadata for " << nss << " "
<< metadata->getCollVersion() << " with an older " << cm->getVersion();
return metadata->getShardVersion();
}
}
}
// Exclusive collection lock needed since we're now changing the metadata. Avoid using
// AutoGetCollection() as it returns the InvalidViewDefinition error code if an invalid view is
// in the 'system.views' collection.
AutoGetDb autoDb(opCtx, nss.db(), MODE_IX);
Lock::CollectionLock collLock(opCtx, nss, MODE_IX);
auto* const css = CollectionShardingRuntime::get(opCtx, nss);
{
auto optMetadata = CollectionShardingState::get(opCtx, nss)->getCurrentMetadataIfKnown();
// We already have newer version
if (optMetadata) {
const auto& metadata = *optMetadata;
if (metadata->isSharded() &&
metadata->getCollVersion().epoch() == cm->getVersion().epoch() &&
metadata->getCollVersion() >= cm->getVersion()) {
LOG(1) << "Skipping refresh of metadata for " << nss << " "
<< metadata->getCollVersion() << " with an older " << cm->getVersion();
return metadata->getShardVersion();
}
}
}
CollectionMetadata metadata(std::move(cm), shardingState->shardId());
const auto newShardVersion = metadata.getShardVersion();
css->setFilteringMetadata(opCtx, std::move(metadata));
return newShardVersion;
}
Status onDbVersionMismatchNoExcept(
OperationContext* opCtx,
const StringData dbName,
const DatabaseVersion& clientDbVersion,
const boost::optional<DatabaseVersion>& serverDbVersion) noexcept {
try {
onDbVersionMismatch(opCtx, dbName, clientDbVersion, serverDbVersion);
return Status::OK();
} catch (const DBException& ex) {
log() << "Failed to refresh databaseVersion for database " << dbName
<< causedBy(redact(ex));
return ex.toStatus();
}
}
void forceDatabaseRefresh(OperationContext* opCtx, const StringData dbName) {
invariant(!opCtx->lockState()->isLocked());
invariant(!opCtx->getClient()->isInDirectClient());
auto const shardingState = ShardingState::get(opCtx);
invariant(shardingState->canAcceptShardedCommands());
DatabaseVersion refreshedDbVersion;
try {
refreshedDbVersion =
uassertStatusOK(Grid::get(opCtx)->catalogCache()->getDatabaseWithRefresh(opCtx, dbName))
.databaseVersion();
} catch (const ExceptionFor<ErrorCodes::NamespaceNotFound>&) {
// db has been dropped, set the db version to boost::none
Lock::DBLock dbLock(opCtx, dbName, MODE_X);
auto dss = DatabaseShardingState::get(opCtx, dbName);
auto dssLock = DatabaseShardingState::DSSLock::lockExclusive(opCtx, dss);
dss->setDbVersion(opCtx, boost::none, dssLock);
return;
}
// First, check under a shared lock if another thread already updated the cached version.
// This is a best-effort optimization to make as few threads as possible to convoy on the
// exclusive lock below.
{
// Take the DBLock directly rather than using AutoGetDb, to prevent a recursive call
// into checkDbVersion().
Lock::DBLock dbLock(opCtx, dbName, MODE_IS);
auto dss = DatabaseShardingState::get(opCtx, dbName);
auto dssLock = DatabaseShardingState::DSSLock::lockShared(opCtx, dss);
const auto cachedDbVersion = dss->getDbVersion(opCtx, dssLock);
if (cachedDbVersion && cachedDbVersion->getUuid() == refreshedDbVersion.getUuid() &&
cachedDbVersion->getLastMod() >= refreshedDbVersion.getLastMod()) {
LOG(2) << "Skipping setting cached databaseVersion for " << dbName
<< " to refreshed version " << refreshedDbVersion.toBSON()
<< " because current cached databaseVersion is already "
<< cachedDbVersion->toBSON();
return;
}
}
// The cached version is older than the refreshed version; update the cached version.
Lock::DBLock dbLock(opCtx, dbName, MODE_X);
auto dss = DatabaseShardingState::get(opCtx, dbName);
auto dssLock = DatabaseShardingState::DSSLock::lockExclusive(opCtx, dss);
dss->setDbVersion(opCtx, std::move(refreshedDbVersion), dssLock);
}
} // namespace mongo
|