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
|
/**
* 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::kCommand
#include "mongo/platform/basic.h"
#include "mongo/db/commands/feature_compatibility_version.h"
#include <fmt/format.h>
#include "mongo/base/status.h"
#include "mongo/db/catalog_raii.h"
#include "mongo/db/commands/feature_compatibility_version_documentation.h"
#include "mongo/db/commands/feature_compatibility_version_gen.h"
#include "mongo/db/commands/feature_compatibility_version_parser.h"
#include "mongo/db/dbdirectclient.h"
#include "mongo/db/namespace_string.h"
#include "mongo/db/operation_context.h"
#include "mongo/db/repl/optime.h"
#include "mongo/db/repl/replication_coordinator.h"
#include "mongo/db/repl/replication_process.h"
#include "mongo/db/repl/storage_interface.h"
#include "mongo/db/s/collection_sharding_state.h"
#include "mongo/db/s/sharding_state.h"
#include "mongo/db/service_context.h"
#include "mongo/db/storage/storage_engine.h"
#include "mongo/db/wire_version.h"
#include "mongo/db/write_concern_options.h"
#include "mongo/logv2/log.h"
#include "mongo/rpc/get_status_from_command_result.h"
#include "mongo/transport/service_entry_point.h"
namespace mongo {
using repl::UnreplicatedWritesBlock;
using FCVP = FeatureCompatibilityVersionParser;
using FCVParams = ServerGlobalParams::FeatureCompatibility;
using FCV = FCVParams::Version;
using namespace fmt::literals;
namespace {
/**
* Utility class for recording permitted transitions between feature compatibility versions and
* their on-disk representation as FeatureCompatibilityVersionDocument objects.
*/
const class FCVTransitions {
public:
FCVTransitions() {
auto makeFCVDoc = [](
// What features we support during the transition.
FCV effectiveVersion,
// The transition's goal FCV.
boost::optional<FCV> targetVersion = boost::none,
// The previous FCV while downgrading.
boost::optional<FCV> previousVersion = boost::none) {
FeatureCompatibilityVersionDocument fcvDoc;
fcvDoc.setVersion(effectiveVersion);
fcvDoc.setTargetVersion(targetVersion);
fcvDoc.setPreviousVersion(previousVersion);
return fcvDoc;
};
// Steady states - they have FCV documents but no _transitions entries.
for (auto fcv :
std::vector{FCVParams::kLastLTS, FCVParams::kLastContinuous, FCVParams::kLatest}) {
_fcvDocuments[fcv] = makeFCVDoc(fcv);
}
for (auto [from, upgrading, to] :
std::vector{std::make_tuple(FCVParams::kLastLTS,
FCVParams::kUpgradingFromLastLTSToLatest,
FCVParams::kLatest),
std::make_tuple(FCVParams::kLastContinuous,
FCVParams::kUpgradingFromLastContinuousToLatest,
FCVParams::kLatest)}) {
for (auto isFromConfigServer : std::vector{false, true}) {
// Start or complete upgrading to latest. If this release's lastContinuous ==
// lastLTS then the second loop iteration just overwrites the first.
_transitions[{from, to, isFromConfigServer}] = upgrading;
_transitions[{upgrading, to, isFromConfigServer}] = to;
}
_fcvDocuments[upgrading] = makeFCVDoc(from /* effective */, to /* target */);
}
if (FCVParams::kLastLTS != FCVParams::kLastContinuous) {
// Only config servers may request an upgrade from lastLTS to lastContinuous.
_transitions[{FCVParams::kLastLTS, FCVParams::kLastContinuous, true}] =
FCVParams::kUpgradingFromLastLTSToLastContinuous;
_transitions[{FCVParams::kUpgradingFromLastLTSToLastContinuous,
FCVParams::kLastContinuous,
true}] = FCVParams::kLastContinuous;
_fcvDocuments[FCVParams::kUpgradingFromLastLTSToLastContinuous] = makeFCVDoc(
FCVParams::kLastLTS /* effective */, FCVParams::kLastContinuous /* target */);
}
for (auto [downgrading, to] :
std::vector{std::make_tuple(FCVParams::kDowngradingFromLatestToLastContinuous,
FCVParams::kLastContinuous),
std::make_tuple(FCVParams::kDowngradingFromLatestToLastLTS,
FCVParams::kLastLTS)}) {
for (auto isFromConfigServer : std::vector{false, true}) {
// Start or complete downgrade from latest. If this release's lastContinuous ==
// lastLTS then the second loop iteration just overwrites the first.
_transitions[{FCVParams::kLatest, to, isFromConfigServer}] = downgrading;
_transitions[{downgrading, to, isFromConfigServer}] = to;
}
_fcvDocuments[downgrading] =
makeFCVDoc(to /* effective */, to /* target */, FCVParams::kLatest /* previous */
);
}
}
/**
* True if a server in ServerGlobalParams::FeatureCompatibility::Version "fromVersion" can
* transition to "newVersion". Different rules apply if the request is from a config server.
*/
bool permitsTransition(FCV fromVersion, FCV newVersion, bool isFromConfigServer) const {
return _transitions.find({fromVersion, newVersion, isFromConfigServer}) !=
_transitions.end();
}
/**
* Get a feature compatibility version enum value from a document representing the
* ServerGlobalParams::FeatureCompatibility::Version, or uassert if the document is invalid.
*/
FCV versionFromFCVDoc(const FeatureCompatibilityVersionDocument& fcvDoc) const {
auto it = std::find_if(_fcvDocuments.begin(), _fcvDocuments.end(), [&](const auto& value) {
return value.second == fcvDoc;
});
uassert(5147400, "invalid feature compatibility document", it != _fcvDocuments.end());
return it->first;
}
/**
* Return an FCV representing the transition fromVersion -> newVersion. It may be transitional
* (such as kUpgradingFromLastLTSToLastContinuous) or not (such as kLastLTS). Different rules
* apply if the upgrade/downgrade request is from a config server.
*/
FCV getTransitionalVersion(FCV fromVersion, FCV newVersion, bool isFromConfigServer) const {
auto it = _transitions.find({fromVersion, newVersion, isFromConfigServer});
fassert(5147401, it != _transitions.end());
return it->second;
}
/**
* Get the document representation of a (perhaps transitional) version.
*/
FeatureCompatibilityVersionDocument getFCVDocument(FCV currentVersion) const {
auto it = _fcvDocuments.find(currentVersion);
fassert(5147402, it != _fcvDocuments.end());
return it->second;
}
private:
stdx::unordered_map<FCV, FeatureCompatibilityVersionDocument> _fcvDocuments;
// Map: (fromVersion, newVersion, isFromConfigServer) -> transitional version.
stdx::unordered_map<std::tuple<FCV, FCV, bool>, FCV> _transitions;
} fcvTransitions;
/**
* Taken in shared mode by any operations that need to ensure that the FCV does not change during
* its execution.
*
* setFCV takes this lock in exclusive mode when changing the FCV value.
*/
Lock::ResourceMutex fcvLock("featureCompatibilityVersionLock");
// lastFCVUpdateTimestamp contains the latest oplog entry timestamp which updated the FCV.
// It is reset on rollback.
Timestamp lastFCVUpdateTimestamp;
SimpleMutex lastFCVUpdateTimestampMutex;
bool isWriteableStorageEngine() {
return !storageGlobalParams.readOnly && (storageGlobalParams.engine != "devnull");
}
/**
* Build update command for featureCompatibilityVersion document updates.
*/
void runUpdateCommand(OperationContext* opCtx, const FeatureCompatibilityVersionDocument& fcvDoc) {
DBDirectClient client(opCtx);
NamespaceString nss(NamespaceString::kServerConfigurationNamespace);
BSONObjBuilder updateCmd;
updateCmd.append("update", nss.coll());
{
BSONArrayBuilder updates(updateCmd.subarrayStart("updates"));
{
BSONObjBuilder updateSpec(updates.subobjStart());
{
BSONObjBuilder queryFilter(updateSpec.subobjStart("q"));
queryFilter.append("_id", FeatureCompatibilityVersionParser::kParameterName);
}
{
BSONObjBuilder updateMods(updateSpec.subobjStart("u"));
fcvDoc.serialize(&updateMods);
}
updateSpec.appendBool("upsert", true);
}
}
auto timeout = opCtx->getWriteConcern().isImplicitDefaultWriteConcern()
? WriteConcernOptions::kNoTimeout
: opCtx->getWriteConcern().wTimeout;
auto newWC = WriteConcernOptions(
WriteConcernOptions::kMajority, WriteConcernOptions::SyncMode::UNSET, timeout);
updateCmd.append(WriteConcernOptions::kWriteConcernField, newWC.toBSON());
// Update the featureCompatibilityVersion document stored in the server configuration
// collection.
BSONObj updateResult;
client.runCommand(nss.db().toString(), updateCmd.obj(), updateResult);
uassertStatusOK(getStatusFromWriteCommandReply(updateResult));
}
} // namespace
boost::optional<BSONObj> FeatureCompatibilityVersion::findFeatureCompatibilityVersionDocument(
OperationContext* opCtx) {
AutoGetCollection autoColl(opCtx, NamespaceString::kServerConfigurationNamespace, MODE_IX);
invariant(autoColl.ensureDbExists(), NamespaceString::kServerConfigurationNamespace.ns());
const auto query = BSON("_id" << FeatureCompatibilityVersionParser::kParameterName);
const auto swFcv = repl::StorageInterface::get(opCtx)->findById(
opCtx, NamespaceString::kServerConfigurationNamespace, query["_id"]);
if (!swFcv.isOK()) {
return boost::none;
}
return swFcv.getValue();
}
void FeatureCompatibilityVersion::validateSetFeatureCompatibilityVersionRequest(
OperationContext* opCtx, const SetFeatureCompatibilityVersion& setFCVRequest, FCV fromVersion) {
auto newVersion = setFCVRequest.getCommandParameter();
auto isFromConfigServer = setFCVRequest.getFromConfigServer().value_or(false);
uassert(
5147403,
"cannot set featureCompatibilityVersion to '{}' while featureCompatibilityVersion is '{}'"_format(
FCVP::toString(newVersion), FCVP::toString(fromVersion)),
fcvTransitions.permitsTransition(fromVersion, newVersion, isFromConfigServer));
auto setFCVPhase = setFCVRequest.getPhase();
if (!isFromConfigServer || !setFCVPhase) {
return;
}
auto changeTimestamp = setFCVRequest.getChangeTimestamp();
invariant(changeTimestamp);
auto fcvObj = findFeatureCompatibilityVersionDocument(opCtx);
auto fcvDoc = FeatureCompatibilityVersionDocument::parse(
IDLParserErrorContext("featureCompatibilityVersionDocument"), fcvObj.get());
auto previousTimestamp = fcvDoc.getChangeTimestamp();
if (setFCVPhase == SetFCVPhaseEnum::kStart) {
uassert(
5563501,
"Shard received a timestamp for phase 1 of the 'setFeatureCompatibilityVersion' "
"command which is too old, so the request is discarded. This may indicate that the "
"request is related to a previous invocation of the 'setFeatureCompatibilityVersion' "
"command which, for example, was temporarily stuck on network.",
!previousTimestamp || previousTimestamp <= changeTimestamp);
} else {
uassert(5563601,
"Cannot transition to fully upgraded or fully downgraded state if the shard is not "
"in kUpgrading or kDowngrading state",
serverGlobalParams.featureCompatibility.isUpgradingOrDowngrading());
tassert(5563502,
"Shard received a request for phase 2 of the 'setFeatureCompatibilityVersion' "
"command that cannot be correlated with the previous one, so the request is "
"discarded. This may indicate that the request for step 1 was not received or "
"processed properly.",
previousTimestamp);
uassert(5563503,
"Shard received a timestamp for phase 2 of the 'setFeatureCompatibilityVersion' "
"command that does not match the one received for phase 1, so the request is "
"discarded. This could indicate, for example, that the request is related to a "
"previous invocation of the 'setFeatureCompatibilityVersion' command which, for "
"example, was temporarily stuck on network.",
previousTimestamp == changeTimestamp);
}
}
void FeatureCompatibilityVersion::updateFeatureCompatibilityVersionDocument(
OperationContext* opCtx,
ServerGlobalParams::FeatureCompatibility::Version fromVersion,
ServerGlobalParams::FeatureCompatibility::Version newVersion,
bool isFromConfigServer,
boost::optional<Timestamp> changeTimestamp,
bool setTargetVersion) {
// We may have just stepped down, in which case we should not proceed.
opCtx->checkForInterrupt();
// Only transition to fully upgraded or downgraded states when we
// have completed all required upgrade/downgrade behavior.
auto transitioningVersion = setTargetVersion &&
serverGlobalParams.featureCompatibility.isUpgradingOrDowngrading(fromVersion)
? fromVersion
: fcvTransitions.getTransitionalVersion(fromVersion, newVersion, isFromConfigServer);
FeatureCompatibilityVersionDocument fcvDoc =
fcvTransitions.getFCVDocument(transitioningVersion);
// The timestamp must be removed when downgrading to version 4.9 or 4.4. This is necessary to
// avoid the presence of an unknown field that old binaries are unable to deserialize.
if (transitioningVersion == ServerGlobalParams::FeatureCompatibility::Version::kVersion49 ||
transitioningVersion ==
ServerGlobalParams::FeatureCompatibility::Version::kFullyDowngradedTo44) {
fcvDoc.setChangeTimestamp(boost::none);
} else {
fcvDoc.setChangeTimestamp(changeTimestamp);
}
runUpdateCommand(opCtx, fcvDoc);
}
void FeatureCompatibilityVersion::setIfCleanStartup(OperationContext* opCtx,
repl::StorageInterface* storageInterface) {
if (!isCleanStartUp())
return;
// If the server was not started with --shardsvr, the default featureCompatibilityVersion on
// clean startup is the upgrade version. If it was started with --shardsvr, the default
// featureCompatibilityVersion is the downgrade version, so that it can be safely added to a
// downgrade version cluster. The config server will run setFeatureCompatibilityVersion as part
// of addShard.
const bool storeUpgradeVersion = serverGlobalParams.clusterRole != ClusterRole::ShardServer;
UnreplicatedWritesBlock unreplicatedWritesBlock(opCtx);
NamespaceString nss(NamespaceString::kServerConfigurationNamespace);
{
CollectionOptions options;
options.uuid = CollectionUUID::gen();
uassertStatusOK(storageInterface->createCollection(opCtx, nss, options));
}
FeatureCompatibilityVersionDocument fcvDoc;
if (storeUpgradeVersion) {
fcvDoc.setVersion(FCVParams::kLatest);
} else {
fcvDoc.setVersion(FCVParams::kLastLTS);
}
// We then insert the featureCompatibilityVersion document into the server configuration
// collection. The server parameter will be updated on commit by the op observer.
uassertStatusOK(storageInterface->insertDocument(
opCtx,
nss,
repl::TimestampedBSONObj{fcvDoc.toBSON(), Timestamp()},
repl::OpTime::kUninitializedTerm)); // No timestamp or term because this write is not
// replicated.
}
bool FeatureCompatibilityVersion::isCleanStartUp() {
StorageEngine* storageEngine = getGlobalServiceContext()->getStorageEngine();
std::vector<std::string> dbNames = storageEngine->listDatabases();
for (auto&& dbName : dbNames) {
if (dbName != "local") {
return false;
}
}
return true;
}
void FeatureCompatibilityVersion::updateMinWireVersion() {
WireSpec& wireSpec = WireSpec::instance();
const auto currentFcv = serverGlobalParams.featureCompatibility.getVersion();
if (currentFcv == FCVParams::kLatest ||
(serverGlobalParams.featureCompatibility.isUpgradingOrDowngrading() &&
currentFcv != FCVParams::kUpgradingFromLastLTSToLastContinuous)) {
// FCV == kLatest or FCV is upgrading/downgrading to or from kLatest.
WireSpec::Specification newSpec = *wireSpec.get();
newSpec.incomingInternalClient.minWireVersion = LATEST_WIRE_VERSION;
newSpec.outgoing.minWireVersion = LATEST_WIRE_VERSION;
wireSpec.reset(std::move(newSpec));
} else if (currentFcv == FCVParams::kUpgradingFromLastLTSToLastContinuous ||
currentFcv == FCVParams::kLastContinuous) {
// FCV == kLastContinuous or upgrading to kLastContinuous.
WireSpec::Specification newSpec = *wireSpec.get();
newSpec.incomingInternalClient.minWireVersion = LAST_CONT_WIRE_VERSION;
newSpec.outgoing.minWireVersion = LAST_CONT_WIRE_VERSION;
wireSpec.reset(std::move(newSpec));
} else {
invariant(currentFcv == FCVParams::kLastLTS);
WireSpec::Specification newSpec = *wireSpec.get();
newSpec.incomingInternalClient.minWireVersion = LAST_LTS_WIRE_VERSION;
newSpec.outgoing.minWireVersion = LAST_LTS_WIRE_VERSION;
wireSpec.reset(std::move(newSpec));
}
}
void FeatureCompatibilityVersion::initializeForStartup(OperationContext* opCtx) {
// Global write lock must be held.
invariant(opCtx->lockState()->isW());
auto featureCompatibilityVersion = findFeatureCompatibilityVersionDocument(opCtx);
if (!featureCompatibilityVersion) {
return;
}
// If the server configuration collection already contains a valid featureCompatibilityVersion
// document, cache it in-memory as a server parameter.
auto swVersion = FeatureCompatibilityVersionParser::parse(*featureCompatibilityVersion);
// Note this error path captures all cases of an FCV document existing, but with any
// unacceptable value. This includes unexpected cases with no path forward such as the FCV value
// not being a string.
if (!swVersion.isOK()) {
uassertStatusOK({ErrorCodes::MustDowngrade,
str::stream()
<< "UPGRADE PROBLEM: Found an invalid featureCompatibilityVersion "
"document (ERROR: "
<< swVersion.getStatus()
<< "). If the current featureCompatibilityVersion is below 4.4, see "
"the documentation on upgrading at "
<< feature_compatibility_version_documentation::kUpgradeLink << "."});
}
auto version = swVersion.getValue();
serverGlobalParams.mutableFeatureCompatibility.setVersion(version);
FeatureCompatibilityVersion::updateMinWireVersion();
// On startup, if the version is in an upgrading or downgrading state, print a warning.
if (serverGlobalParams.featureCompatibility.isUpgradingOrDowngrading()) {
LOGV2_WARNING_OPTIONS(
4978301,
{logv2::LogTag::kStartupWarnings},
"A featureCompatibilityVersion upgrade/downgrade did not complete. To fix this, use "
"the setFeatureCompatibilityVersion command to resume the upgrade/downgrade",
"currentfeatureCompatibilityVersion"_attr =
FeatureCompatibilityVersionParser::toString(version));
}
}
// Fatally asserts if the featureCompatibilityVersion document is not initialized, when required.
void FeatureCompatibilityVersion::fassertInitializedAfterStartup(OperationContext* opCtx) {
Lock::GlobalWrite lk(opCtx);
const auto replProcess = repl::ReplicationProcess::get(opCtx);
const auto& replSettings = repl::ReplicationCoordinator::get(opCtx)->getSettings();
// The node did not complete the last initial sync. If the initial sync flag is set and we are
// part of a replica set, we expect the version to be initialized as part of initial sync after
// startup.
bool needInitialSync = replSettings.usingReplSets() && replProcess &&
replProcess->getConsistencyMarkers()->getInitialSyncFlag(opCtx);
if (needInitialSync) {
return;
}
auto fcvDocument = findFeatureCompatibilityVersionDocument(opCtx);
auto const storageEngine = opCtx->getServiceContext()->getStorageEngine();
auto dbNames = storageEngine->listDatabases();
bool nonLocalDatabases = std::any_of(dbNames.begin(), dbNames.end(), [](auto name) {
return name != NamespaceString::kLocalDb;
});
// Fail to start up if there is no featureCompatibilityVersion document and there are non-local
// databases present.
if (!fcvDocument && nonLocalDatabases) {
LOGV2_FATAL_NOTRACE(40652,
"Unable to start up mongod due to missing featureCompatibilityVersion "
"document. Please run with --repair to restore the document.");
}
// If we are part of a replica set and are started up with no data files, we do not set the
// featureCompatibilityVersion until a primary is chosen. For this case, we expect the in-memory
// featureCompatibilityVersion parameter to still be uninitialized until after startup.
if (isWriteableStorageEngine() && (!replSettings.usingReplSets() || nonLocalDatabases)) {
invariant(serverGlobalParams.featureCompatibility.isVersionInitialized());
}
}
Lock::ExclusiveLock FeatureCompatibilityVersion::enterFCVChangeRegion(OperationContext* opCtx) {
invariant(!opCtx->lockState()->isLocked());
return Lock::ExclusiveLock(opCtx->lockState(), fcvLock);
}
void FeatureCompatibilityVersion::advanceLastFCVUpdateTimestamp(Timestamp fcvUpdateTimestamp) {
stdx::lock_guard lk(lastFCVUpdateTimestampMutex);
if (fcvUpdateTimestamp > lastFCVUpdateTimestamp) {
lastFCVUpdateTimestamp = fcvUpdateTimestamp;
}
}
void FeatureCompatibilityVersion::clearLastFCVUpdateTimestamp() {
stdx::lock_guard lk(lastFCVUpdateTimestampMutex);
lastFCVUpdateTimestamp = Timestamp();
}
/**
* Read-only server parameter for featureCompatibilityVersion.
*/
// No ability to specify 'none' as set_at type,
// so use 'startup' in the IDL file, then override to none here.
FeatureCompatibilityVersionParameter::FeatureCompatibilityVersionParameter(StringData name,
ServerParameterType)
: ServerParameter(ServerParameterSet::getGlobal(), name, false, false) {}
void FeatureCompatibilityVersionParameter::append(OperationContext* opCtx,
BSONObjBuilder& b,
const std::string& name) {
uassert(ErrorCodes::UnknownFeatureCompatibilityVersion,
str::stream() << name << " is not yet known.",
serverGlobalParams.featureCompatibility.isVersionInitialized());
BSONObjBuilder featureCompatibilityVersionBuilder(b.subobjStart(name));
auto version = serverGlobalParams.featureCompatibility.getVersion();
FeatureCompatibilityVersionDocument fcvDoc = fcvTransitions.getFCVDocument(version);
featureCompatibilityVersionBuilder.appendElements(fcvDoc.toBSON().removeField("_id"));
if (!fcvDoc.getTargetVersion()) {
// If the FCV has been recently set to the fully upgraded FCV but is not part of the
// majority snapshot, then if we do a binary upgrade, we may see the old FCV at startup. It
// is not safe to do oplog application on the new binary at that point. So we make sure
// that when we report the FCV, it is in the majority snapshot.
// (The same consideration applies at downgrade, where if a recently-set fully downgraded
// FCV is not part of the majority snapshot, the downgraded binary will see the upgrade FCV
// and fail.)
const auto replCoordinator = repl::ReplicationCoordinator::get(opCtx);
const bool isReplSet = replCoordinator &&
replCoordinator->getReplicationMode() == repl::ReplicationCoordinator::modeReplSet;
auto neededMajorityTimestamp = [] {
stdx::lock_guard lk(lastFCVUpdateTimestampMutex);
return lastFCVUpdateTimestamp;
}();
if (isReplSet && !neededMajorityTimestamp.isNull()) {
auto status = replCoordinator->awaitTimestampCommitted(opCtx, neededMajorityTimestamp);
// If majority reads are not supported, we will take a full snapshot on clean shutdown
// and the new FCV will be included, so upgrade is possible.
if (status.code() != ErrorCodes::CommandNotSupported)
uassertStatusOK(
status.withContext("Most recent 'featureCompatibilityVersion' was not in the "
"majority snapshot on this node"));
}
}
}
Status FeatureCompatibilityVersionParameter::setFromString(const std::string&) {
return {ErrorCodes::IllegalOperation,
str::stream() << name() << " cannot be set via setParameter. See "
<< feature_compatibility_version_documentation::kCompatibilityLink
<< "."};
}
FixedFCVRegion::FixedFCVRegion(OperationContext* opCtx)
: _lk([&] {
invariant(!opCtx->lockState()->isLocked());
invariant(!opCtx->lockState()->isRSTLLocked());
return Lock::SharedLock(opCtx->lockState(), fcvLock);
}()) {}
FixedFCVRegion::~FixedFCVRegion() = default;
const ServerGlobalParams::FeatureCompatibility& FixedFCVRegion::operator*() const {
return serverGlobalParams.featureCompatibility;
}
const ServerGlobalParams::FeatureCompatibility* FixedFCVRegion::operator->() const {
return &serverGlobalParams.featureCompatibility;
}
bool FixedFCVRegion::operator==(
const ServerGlobalParams::FeatureCompatibility::Version& other) const {
return serverGlobalParams.featureCompatibility.getVersion() == other;
}
bool FixedFCVRegion::operator!=(
const ServerGlobalParams::FeatureCompatibility::Version& other) const {
return !(*this == other);
}
} // namespace mongo
|