diff options
author | mathisbessamdb <mathis.bessa@mongodb.com> | 2023-04-24 22:59:20 +0000 |
---|---|---|
committer | Evergreen Agent <no-reply@evergreen.mongodb.com> | 2023-04-26 22:00:17 +0000 |
commit | 18659bb538d2ba53d5c93ac5a9df834c7cb7fe41 (patch) | |
tree | 25ab82a3e0c32f9710df132a45f36bf5d4f38ee6 | |
parent | 54c93d835e07dad55dd38f89928e3206a61a1234 (diff) | |
download | mongo-18659bb538d2ba53d5c93ac5a9df834c7cb7fe41.tar.gz |
SERVER-74493 Make DatabaseName constructors private
55 files changed, 213 insertions, 165 deletions
diff --git a/src/mongo/client/dbclient_base.cpp b/src/mongo/client/dbclient_base.cpp index 5dd34d38758..1ee0cbd67aa 100644 --- a/src/mongo/client/dbclient_base.cpp +++ b/src/mongo/client/dbclient_base.cpp @@ -448,7 +448,7 @@ bool DBClientBase::auth(const string& dbname, } void DBClientBase::logout(const string& dbname, BSONObj& info) { - runCommand(DatabaseName(boost::none, dbname), BSON("logout" << 1), info); + runCommand(DatabaseNameUtil::deserialize(boost::none, dbname), BSON("logout" << 1), info); } bool DBClientBase::isPrimary(bool& isPrimary, BSONObj* info) { @@ -461,7 +461,7 @@ bool DBClientBase::isPrimary(bool& isPrimary, BSONObj* info) { BSONObj o; if (info == nullptr) info = &o; - bool ok = runCommand(DatabaseName(boost::none, "admin"), bob.obj(), *info); + bool ok = runCommand(DatabaseName::kAdmin, bob.obj(), *info); isPrimary = info->getField(_apiParameters.getVersion() ? "isWritablePrimary" : "ismaster").trueValue(); return ok; @@ -553,7 +553,7 @@ vector<BSONObj> DBClientBase::getDatabaseInfos(const BSONObj& filter, BSONObj cmd = bob.done(); BSONObj res; - if (runCommand(DatabaseName(boost::none, "admin"), cmd, res, QueryOption_SecondaryOk)) { + if (runCommand(DatabaseName::kAdmin, cmd, res, QueryOption_SecondaryOk)) { BSONObj dbs = res["databases"].Obj(); BSONObjIterator it(dbs); while (it.more()) { diff --git a/src/mongo/client/dbclient_connection.cpp b/src/mongo/client/dbclient_connection.cpp index b35954c14d4..8631ada0bf4 100644 --- a/src/mongo/client/dbclient_connection.cpp +++ b/src/mongo/client/dbclient_connection.cpp @@ -435,7 +435,7 @@ Status DBClientConnection::connectSocketOnly( void DBClientConnection::logout(const string& dbname, BSONObj& info) { authCache.erase(dbname); _internalAuthOnReconnect = false; - runCommand(DatabaseName(boost::none, dbname), BSON("logout" << 1), info); + runCommand(DatabaseNameUtil::deserialize(boost::none, dbname), BSON("logout" << 1), info); } std::pair<rpc::UniqueReply, DBClientBase*> DBClientConnection::runCommandWithTarget( diff --git a/src/mongo/db/auth/auth_name.h b/src/mongo/db/auth/auth_name.h index 6c5b052e5c7..af30050350e 100644 --- a/src/mongo/db/auth/auth_name.h +++ b/src/mongo/db/auth/auth_name.h @@ -111,7 +111,7 @@ public: } DatabaseName getDatabaseName() const { - return DatabaseName(_tenant, _db); + return DatabaseName::createDatabaseNameForAuth(_tenant, _db); } /** diff --git a/src/mongo/db/catalog/SConscript b/src/mongo/db/catalog/SConscript index 0cbf81433f2..76256a7887b 100644 --- a/src/mongo/db/catalog/SConscript +++ b/src/mongo/db/catalog/SConscript @@ -566,7 +566,6 @@ env.Library( '$BUILD_DIR/mongo/db/ttl_collection_cache', '$BUILD_DIR/mongo/db/views/view_catalog_helpers', '$BUILD_DIR/mongo/db/views/views', - '$BUILD_DIR/mongo/util/namespace_string_database_name_util', 'cannot_convert_index_to_unique_info', 'clustered_collection_options', 'collection_crud', @@ -649,6 +648,7 @@ env.Library( ], LIBDEPS_PRIVATE=[ '$BUILD_DIR/mongo/base', + '$BUILD_DIR/mongo/util/namespace_string_database_name_util', ], ) diff --git a/src/mongo/db/catalog/collection_catalog.cpp b/src/mongo/db/catalog/collection_catalog.cpp index d89e4f90797..c419e83ef34 100644 --- a/src/mongo/db/catalog/collection_catalog.cpp +++ b/src/mongo/db/catalog/collection_catalog.cpp @@ -1789,8 +1789,8 @@ Status CollectionCatalog::_iterAllDbNamesHelper( const std::function<std::pair<DatabaseName, UUID>(const DatabaseName&)>& nextUpperBound) const { // _orderedCollections is sorted by <dbName, uuid>. upper_bound will return the iterator to the // first element in _orderedCollections greater than <firstDbName, maxUuid>. - auto iter = - _orderedCollections.upper_bound(std::make_pair(DatabaseName(tenantId, ""), maxUuid)); + auto iter = _orderedCollections.upper_bound( + std::make_pair(DatabaseNameUtil::deserialize(tenantId, ""), maxUuid)); while (iter != _orderedCollections.end()) { auto dbName = iter->first.first; if (tenantId && dbName.tenantId() != tenantId) { @@ -1842,7 +1842,8 @@ std::set<TenantId> CollectionCatalog::getAllTenants() const { return Status::OK(); }, [](const DatabaseName& dbName) { - return std::make_pair(DatabaseName(dbName.tenantId(), "\xff"), maxUuid); + return std::make_pair(DatabaseNameUtil::deserialize(dbName.tenantId(), "\xff"), + maxUuid); }); return ret; } diff --git a/src/mongo/db/catalog/collection_catalog_test.cpp b/src/mongo/db/catalog/collection_catalog_test.cpp index 7533a220c1b..babf9692df9 100644 --- a/src/mongo/db/catalog/collection_catalog_test.cpp +++ b/src/mongo/db/catalog/collection_catalog_test.cpp @@ -595,6 +595,7 @@ TEST_F(CollectionCatalogTest, GetAllDbNamesForTenant) { } TEST_F(CollectionCatalogTest, GetAllTenants) { + RAIIServerParameterControllerForTest multitenanyController("multitenancySupport", true); TenantId tid1 = TenantId(OID::gen()); TenantId tid2 = TenantId(OID::gen()); std::vector<NamespaceString> nsss = { diff --git a/src/mongo/db/catalog/collection_uuid_mismatch_info.cpp b/src/mongo/db/catalog/collection_uuid_mismatch_info.cpp index 6b267d8829a..8484678a512 100644 --- a/src/mongo/db/catalog/collection_uuid_mismatch_info.cpp +++ b/src/mongo/db/catalog/collection_uuid_mismatch_info.cpp @@ -28,6 +28,7 @@ */ #include "mongo/db/catalog/collection_uuid_mismatch_info.h" +#include "mongo/util/database_name_util.h" #include "mongo/base/init.h" #include "mongo/bson/bsonobjbuilder.h" @@ -45,7 +46,7 @@ constexpr StringData kActualCollectionFieldName = "actualCollection"_sd; std::shared_ptr<const ErrorExtraInfo> CollectionUUIDMismatchInfo::parse(const BSONObj& obj) { auto actualNamespace = obj[kActualCollectionFieldName]; return std::make_shared<CollectionUUIDMismatchInfo>( - DatabaseName(boost::none, obj[kDbFieldName].str()), + DatabaseNameUtil::deserialize(boost::none, obj[kDbFieldName].str()), UUID::parse(obj[kCollectionUUIDFieldName]).getValue(), obj[kExpectedCollectionFieldName].str(), actualNamespace.isNull() ? boost::none : boost::make_optional(actualNamespace.str())); diff --git a/src/mongo/db/cloner.cpp b/src/mongo/db/cloner.cpp index 0041768fe28..c3aae94fd88 100644 --- a/src/mongo/db/cloner.cpp +++ b/src/mongo/db/cloner.cpp @@ -94,7 +94,7 @@ struct DefaultClonerImpl::BatchHandler { void operator()(DBClientCursor& cursor) { boost::optional<Lock::DBLock> dbLock; // TODO SERVER-63111 Once the Cloner holds a DatabaseName obj, use _dbName directly - DatabaseName dbName(boost::none, _dbName); + DatabaseName dbName = DatabaseNameUtil::deserialize(boost::none, _dbName); dbLock.emplace(opCtx, dbName, MODE_X); uassert(ErrorCodes::NotWritablePrimary, str::stream() << "Not primary while cloning collection " @@ -144,7 +144,7 @@ struct DefaultClonerImpl::BatchHandler { // TODO SERVER-63111 Once the cloner takes in a DatabaseName obj, use _dbName // directly - DatabaseName dbName(boost::none, _dbName); + DatabaseName dbName = DatabaseNameUtil::deserialize(boost::none, _dbName); dbLock.emplace(opCtx, dbName, MODE_X); // Check if everything is still all right. @@ -349,7 +349,7 @@ Status DefaultClonerImpl::_createCollectionsForDb( const std::vector<CreateCollectionParams>& createCollectionParams, const std::string& dbName) { auto databaseHolder = DatabaseHolder::get(opCtx); - const DatabaseName tenantDbName(boost::none, dbName); + const DatabaseName tenantDbName = DatabaseNameUtil::deserialize(boost::none, dbName); auto db = databaseHolder->openDb(opCtx, tenantDbName); invariant(opCtx->lockState()->isDbLockedForMode(tenantDbName, MODE_X)); @@ -497,8 +497,9 @@ StatusWith<std::vector<BSONObj>> DefaultClonerImpl::getListOfCollections( } // Gather the list of collections to clone // TODO SERVER-63111 Once the cloner takes in a DatabaseName obj, use dBName directly - std::list<BSONObj> initialCollections = getConn()->getCollectionInfos( - DatabaseName(boost::none, dBName), ListCollectionsFilter::makeTypeCollectionFilter()); + std::list<BSONObj> initialCollections = + getConn()->getCollectionInfos(DatabaseNameUtil::deserialize(boost::none, dBName), + ListCollectionsFilter::makeTypeCollectionFilter()); return _filterCollectionsForClone(dBName, initialCollections); } @@ -551,7 +552,7 @@ Status DefaultClonerImpl::copyDb(OperationContext* opCtx, { // TODO SERVER-63111 Once the cloner takes in a DatabaseName obj, use dBName directly - DatabaseName dbName(boost::none, dBName); + DatabaseName dbName = DatabaseNameUtil::deserialize(boost::none, dBName); Lock::DBLock dbXLock(opCtx, dbName, MODE_X); uassert(ErrorCodes::NotWritablePrimary, str::stream() << "Not primary while cloning database " << dBName diff --git a/src/mongo/db/commands.cpp b/src/mongo/db/commands.cpp index b76843755c2..35330fbabc5 100644 --- a/src/mongo/db/commands.cpp +++ b/src/mongo/db/commands.cpp @@ -321,7 +321,9 @@ NamespaceStringOrUUID CommandHelpers::parseNsOrUUID(const DatabaseName& dbName, } std::string CommandHelpers::parseNsFromCommand(StringData dbname, const BSONObj& cmdObj) { - return parseNsFromCommand({boost::none, dbname}, cmdObj).ns().toString(); + return parseNsFromCommand(DatabaseNameUtil::deserialize(boost::none, dbname), cmdObj) + .ns() + .toString(); } NamespaceString CommandHelpers::parseNsFromCommand(const DatabaseName& dbName, diff --git a/src/mongo/db/commands/current_op_common.cpp b/src/mongo/db/commands/current_op_common.cpp index 6cd8cb22e26..8f17e041bf0 100644 --- a/src/mongo/db/commands/current_op_common.cpp +++ b/src/mongo/db/commands/current_op_common.cpp @@ -110,9 +110,9 @@ bool CurrentOpCommandBase::run(OperationContext* opCtx, pipeline.push_back(groupBuilder.obj()); // Pipeline is complete; create an AggregateCommandRequest for $currentOp. - AggregateCommandRequest request( - NamespaceString::makeCollectionlessAggregateNSS(DatabaseName(dbName.tenantId(), "admin")), - std::move(pipeline)); + AggregateCommandRequest request(NamespaceString::makeCollectionlessAggregateNSS( + DatabaseNameUtil::deserialize(dbName.tenantId(), "admin")), + std::move(pipeline)); // Run the pipeline and obtain a CursorResponse. auto aggResults = uassertStatusOK(runAggregation(opCtx, request)); diff --git a/src/mongo/db/commands/oplog_application_checks.cpp b/src/mongo/db/commands/oplog_application_checks.cpp index 5588fd37f96..73e267f6007 100644 --- a/src/mongo/db/commands/oplog_application_checks.cpp +++ b/src/mongo/db/commands/oplog_application_checks.cpp @@ -93,7 +93,7 @@ Status OplogApplicationChecks::checkOperationAuthorization(OperationContext* opC // renameCollection commands must be run on the 'admin' database. Its arguments are // fully qualified namespaces. Catalog internals don't know the op produced by running // renameCollection was originally run on 'admin', so we must restore this. - dbNameForAuthCheck = DatabaseName(nss.tenantId(), "admin"); + dbNameForAuthCheck = DatabaseNameUtil::deserialize(nss.tenantId(), "admin"); } // TODO reuse the parse result for when we run() later. Note that when running, diff --git a/src/mongo/db/concurrency/SConscript b/src/mongo/db/concurrency/SConscript index 1a94a2cc627..efd2d335cf2 100644 --- a/src/mongo/db/concurrency/SConscript +++ b/src/mongo/db/concurrency/SConscript @@ -43,6 +43,7 @@ env.Library( ], LIBDEPS=[ '$BUILD_DIR/mongo/base', + '$BUILD_DIR/mongo/util/namespace_string_database_name_util', ], ) diff --git a/src/mongo/db/concurrency/lock_manager_defs.cpp b/src/mongo/db/concurrency/lock_manager_defs.cpp index a437d3b5964..38f3976c0ea 100644 --- a/src/mongo/db/concurrency/lock_manager_defs.cpp +++ b/src/mongo/db/concurrency/lock_manager_defs.cpp @@ -32,10 +32,8 @@ namespace mongo { // Hardcoded resource IDs. -const ResourceId resourceIdLocalDB = - ResourceId(RESOURCE_DATABASE, DatabaseName(boost::none, "local")); -const ResourceId resourceIdAdminDB = - ResourceId(RESOURCE_DATABASE, DatabaseName(boost::none, "admin")); +const ResourceId resourceIdLocalDB = ResourceId(RESOURCE_DATABASE, DatabaseName::kLocal); +const ResourceId resourceIdAdminDB = ResourceId(RESOURCE_DATABASE, DatabaseName::kAdmin); const ResourceId resourceIdGlobal = ResourceId(RESOURCE_GLOBAL, static_cast<uint8_t>(ResourceGlobalId::kGlobal)); const ResourceId resourceIdParallelBatchWriterMode = diff --git a/src/mongo/db/database_name.h b/src/mongo/db/database_name.h index 050356547cb..0abccea3210 100644 --- a/src/mongo/db/database_name.h +++ b/src/mongo/db/database_name.h @@ -112,41 +112,24 @@ public: * Constructs an empty DatabaseName. */ DatabaseName() = default; + /** - * Constructs a DatabaseName from the given tenantId and database name. - * "dbName" is expected only consist of a db name. It is the caller's responsibility to ensure - * the dbName is a valid db name. + * This function constructs a DatabaseName without checking for presence of TenantId. It + * must only be used by auth systems which are not yet tenant aware. + * + * TODO SERVER-76294 Remove this function. Any remaining call sites must be changed to use a + * function on DatabaseNameUtil. */ - DatabaseName(boost::optional<TenantId> tenantId, StringData dbString) { - uassert(ErrorCodes::InvalidNamespace, - "'.' is an invalid character in a db name: " + dbString, - dbString.find('.') == std::string::npos); - uassert(ErrorCodes::InvalidNamespace, - "database names cannot have embedded null characters", - dbString.find('\0') == std::string::npos); - uassert(ErrorCodes::InvalidNamespace, - fmt::format("db name must be at most {} characters, found: {}", - kMaxDatabaseNameLength, - dbString.size()), - dbString.size() <= kMaxDatabaseNameLength); - - uint8_t details = dbString.size() & kDatabaseNameOffsetEndMask; - size_t dbStartIndex = kDataOffset; - if (tenantId) { - dbStartIndex += OID::kOIDSize; - details |= kTenantIdMask; - } - - _data.resize(dbStartIndex + dbString.size()); - *reinterpret_cast<uint8_t*>(_data.data()) = details; - if (tenantId) { - std::memcpy(_data.data() + kDataOffset, tenantId->_oid.view().view(), OID::kOIDSize); - } - if (!dbString.empty()) { - std::memcpy(_data.data() + dbStartIndex, dbString.rawData(), dbString.size()); - } + static DatabaseName createDatabaseNameForAuth(const boost::optional<TenantId>& tenantId, + StringData dbString) { + return DatabaseName(tenantId, dbString); } + /** + * This function constructs a DatabaseName without checking for presence of TenantId. + * + * MUST only be used for tests. + */ static DatabaseName createDatabaseName_forTest(boost::optional<TenantId> tenantId, StringData dbString) { return DatabaseName(tenantId, dbString); @@ -266,6 +249,43 @@ public: private: friend class NamespaceString; + friend class NamespaceStringOrUUID; + friend class DatabaseNameUtil; + + /** + * Constructs a DatabaseName from the given tenantId and database name. + * "dbName" is expected only consist of a db name. It is the caller's responsibility to ensure + * the dbName is a valid db name. + */ + DatabaseName(boost::optional<TenantId> tenantId, StringData dbString) { + uassert(ErrorCodes::InvalidNamespace, + "'.' is an invalid character in a db name: " + dbString, + dbString.find('.') == std::string::npos); + uassert(ErrorCodes::InvalidNamespace, + "database names cannot have embedded null characters", + dbString.find('\0') == std::string::npos); + uassert(ErrorCodes::InvalidNamespace, + fmt::format("db name must be at most {} characters, found: {}", + kMaxDatabaseNameLength, + dbString.size()), + dbString.size() <= kMaxDatabaseNameLength); + + uint8_t details = dbString.size() & kDatabaseNameOffsetEndMask; + size_t dbStartIndex = kDataOffset; + if (tenantId) { + dbStartIndex += OID::kOIDSize; + details |= kTenantIdMask; + } + + _data.resize(dbStartIndex + dbString.size()); + *reinterpret_cast<uint8_t*>(_data.data()) = details; + if (tenantId) { + std::memcpy(_data.data() + kDataOffset, tenantId->_oid.view().view(), OID::kOIDSize); + } + if (!dbString.empty()) { + std::memcpy(_data.data() + dbStartIndex, dbString.rawData(), dbString.size()); + } + } static constexpr size_t kDataOffset = sizeof(uint8_t); static constexpr uint8_t kTenantIdMask = 0x80; diff --git a/src/mongo/db/database_name_test.cpp b/src/mongo/db/database_name_test.cpp index 7d45e38ddd4..c025fc82c6d 100644 --- a/src/mongo/db/database_name_test.cpp +++ b/src/mongo/db/database_name_test.cpp @@ -166,14 +166,15 @@ TEST(DatabaseNameTest, EmptyDbString) { ASSERT_EQ(empty.toString(), ""); ASSERT_EQ(empty.toStringWithTenantId(), ""); - DatabaseName emptyFromStringData{StringData()}; + DatabaseName emptyFromStringData = + DatabaseName::createDatabaseName_forTest(boost::none, StringData()); ASSERT_EQ(emptyFromStringData.db(), ""); ASSERT_FALSE(emptyFromStringData.tenantId()); ASSERT_EQ(emptyFromStringData.toString(), ""); ASSERT_EQ(emptyFromStringData.toStringWithTenantId(), ""); TenantId tenantId(OID::gen()); - DatabaseName emptyWithTenantId{tenantId, ""}; + DatabaseName emptyWithTenantId = DatabaseName::createDatabaseName_forTest(tenantId, ""); ASSERT_EQ(emptyWithTenantId.db(), ""); ASSERT(emptyWithTenantId.tenantId()); ASSERT_EQ(emptyWithTenantId.toString(), ""); diff --git a/src/mongo/db/pipeline/document_source_merge_spec.cpp b/src/mongo/db/pipeline/document_source_merge_spec.cpp index d98b567f5c5..490e6a5ec24 100644 --- a/src/mongo/db/pipeline/document_source_merge_spec.cpp +++ b/src/mongo/db/pipeline/document_source_merge_spec.cpp @@ -66,7 +66,7 @@ NamespaceString mergeTargetNssParseFromBSON(boost::optional<TenantId> tenantId, coll && !coll->empty()); return NamespaceStringUtil::parseNamespaceFromRequest( - spec.getDb().value_or(DatabaseName(tenantId, "")), *coll); + spec.getDb().value_or(DatabaseNameUtil::deserialize(tenantId, "")), *coll); } void mergeTargetNssSerializeToBSON(const NamespaceString& targetNss, diff --git a/src/mongo/db/repl/initial_sync_base_cloner.cpp b/src/mongo/db/repl/initial_sync_base_cloner.cpp index 6f6888fe9ce..b3aa0e3f565 100644 --- a/src/mongo/db/repl/initial_sync_base_cloner.cpp +++ b/src/mongo/db/repl/initial_sync_base_cloner.cpp @@ -145,8 +145,7 @@ Status InitialSyncBaseCloner::checkInitialSyncIdIsUnchanged() { Status InitialSyncBaseCloner::checkRollBackIdIsUnchanged() { BSONObj info; try { - getClient()->runCommand( - DatabaseName(boost::none, "admin"), BSON("replSetGetRBID" << 1), info); + getClient()->runCommand(DatabaseName::kAdmin, BSON("replSetGetRBID" << 1), info); } catch (DBException& e) { if (ErrorCodes::isRetriableError(e)) { static constexpr char errorMsg[] = diff --git a/src/mongo/db/repl/isself.cpp b/src/mongo/db/repl/isself.cpp index cc35bcacf4b..d328d24fbc5 100644 --- a/src/mongo/db/repl/isself.cpp +++ b/src/mongo/db/repl/isself.cpp @@ -293,7 +293,7 @@ bool isSelfSlowPath(const HostAndPort& hostAndPort, } } BSONObj out; - bool ok = conn.runCommand(DatabaseName(boost::none, "admin"), BSON("_isSelf" << 1), out); + bool ok = conn.runCommand(DatabaseName::kAdmin, BSON("_isSelf" << 1), out); bool me = ok && out["id"].type() == jstOID && instanceId == out["id"].OID(); return me; diff --git a/src/mongo/db/repl/rollback_source_impl.cpp b/src/mongo/db/repl/rollback_source_impl.cpp index b4c65fc2581..1dd097c23e9 100644 --- a/src/mongo/db/repl/rollback_source_impl.cpp +++ b/src/mongo/db/repl/rollback_source_impl.cpp @@ -61,8 +61,7 @@ const HostAndPort& RollbackSourceImpl::getSource() const { int RollbackSourceImpl::getRollbackId() const { bo info; - _getConnection()->runCommand( - DatabaseName(boost::none, "admin"), BSON("replSetGetRBID" << 1), info); + _getConnection()->runCommand(DatabaseName::kAdmin, BSON("replSetGetRBID" << 1), info); return info["rbid"].numberInt(); } diff --git a/src/mongo/db/repl/shard_merge_recipient_service.cpp b/src/mongo/db/repl/shard_merge_recipient_service.cpp index 9b9476ae710..4ac467ff094 100644 --- a/src/mongo/db/repl/shard_merge_recipient_service.cpp +++ b/src/mongo/db/repl/shard_merge_recipient_service.cpp @@ -1573,8 +1573,7 @@ ShardMergeRecipientService::Instance::_fetchRetryableWritesOplogBeforeStartOpTim BSONObj readResult; BSONObj cmd = ClonerUtils::buildMajorityWaitRequest(*operationTime); - _client.get()->runCommand( - DatabaseName(boost::none, "admin"), cmd, readResult, QueryOption_SecondaryOk); + _client.get()->runCommand(DatabaseName::kAdmin, cmd, readResult, QueryOption_SecondaryOk); uassertStatusOKWithContext( getStatusFromCommandResult(readResult), "Failed to wait for retryable writes pre-fetch result majority committed"); diff --git a/src/mongo/db/repl/tenant_all_database_cloner.cpp b/src/mongo/db/repl/tenant_all_database_cloner.cpp index ca207c074b5..cc72c941d43 100644 --- a/src/mongo/db/repl/tenant_all_database_cloner.cpp +++ b/src/mongo/db/repl/tenant_all_database_cloner.cpp @@ -99,8 +99,7 @@ BaseCloner::AfterStageBehavior TenantAllDatabaseCloner::listDatabasesStage() { BSONObj readResult; BSONObj cmd = ClonerUtils::buildMajorityWaitRequest(_operationTime); - getClient()->runCommand( - DatabaseName(boost::none, "admin"), cmd, readResult, QueryOption_SecondaryOk); + getClient()->runCommand(DatabaseName::kAdmin, cmd, readResult, QueryOption_SecondaryOk); uassertStatusOKWithContext( getStatusFromCommandResult(readResult), "TenantAllDatabaseCloner failed to get listDatabases result majority-committed"); @@ -163,7 +162,8 @@ BaseCloner::AfterStageBehavior TenantAllDatabaseCloner::listExistingDatabasesSta clonedDatabases.emplace_back(dbName); BSONObj res; - client.runCommand(DatabaseName(boost::none, dbName), BSON("dbStats" << 1), res); + client.runCommand( + DatabaseNameUtil::deserialize(boost::none, dbName), BSON("dbStats" << 1), res); if (auto status = getStatusFromCommandResult(res); !status.isOK()) { LOGV2_WARNING(5522900, "Skipping recording of data size metrics for database due to failure " @@ -233,7 +233,8 @@ BaseCloner::AfterStageBehavior TenantAllDatabaseCloner::initializeStatsStage() { long long approxTotalDataSizeLeftOnRemote = 0; for (const auto& dbName : _databases) { BSONObj res; - getClient()->runCommand(DatabaseName(boost::none, dbName), BSON("dbStats" << 1), res); + getClient()->runCommand( + DatabaseNameUtil::deserialize(boost::none, dbName), BSON("dbStats" << 1), res); if (auto status = getStatusFromCommandResult(res); !status.isOK()) { LOGV2_WARNING(5426600, "Skipping recording of data size metrics for database due to failure " diff --git a/src/mongo/db/repl/tenant_collection_cloner.cpp b/src/mongo/db/repl/tenant_collection_cloner.cpp index cf90d924069..cfc7e399cbe 100644 --- a/src/mongo/db/repl/tenant_collection_cloner.cpp +++ b/src/mongo/db/repl/tenant_collection_cloner.cpp @@ -244,8 +244,7 @@ BaseCloner::AfterStageBehavior TenantCollectionCloner::listIndexesStage() { BSONObj readResult; BSONObj cmd = ClonerUtils::buildMajorityWaitRequest(_operationTime); - getClient()->runCommand( - DatabaseName(boost::none, "admin"), cmd, readResult, QueryOption_SecondaryOk); + getClient()->runCommand(DatabaseName::kAdmin, cmd, readResult, QueryOption_SecondaryOk); uassertStatusOKWithContext( getStatusFromCommandResult(readResult), "TenantCollectionCloner failed to get listIndexes result majority-committed"); diff --git a/src/mongo/db/repl/tenant_database_cloner.cpp b/src/mongo/db/repl/tenant_database_cloner.cpp index 2fa7147e1fc..b8614403b62 100644 --- a/src/mongo/db/repl/tenant_database_cloner.cpp +++ b/src/mongo/db/repl/tenant_database_cloner.cpp @@ -87,8 +87,9 @@ BaseCloner::AfterStageBehavior TenantDatabaseCloner::listCollectionsStage() { // This will be set after a successful listCollections command. _operationTime = Timestamp(); - auto collectionInfos = getClient()->getCollectionInfos( - DatabaseName(boost::none, _dbName), ListCollectionsFilter::makeTypeCollectionFilter()); + auto collectionInfos = + getClient()->getCollectionInfos(DatabaseNameUtil::deserialize(boost::none, _dbName), + ListCollectionsFilter::makeTypeCollectionFilter()); // Do a majority read on the sync source to make sure the collections listed exist on a majority // of nodes in the set. We do not check the rollbackId - rollback would lead to the sync source @@ -115,8 +116,7 @@ BaseCloner::AfterStageBehavior TenantDatabaseCloner::listCollectionsStage() { BSONObj readResult; BSONObj cmd = ClonerUtils::buildMajorityWaitRequest(_operationTime); - getClient()->runCommand( - DatabaseName(boost::none, "admin"), cmd, readResult, QueryOption_SecondaryOk); + getClient()->runCommand(DatabaseName::kAdmin, cmd, readResult, QueryOption_SecondaryOk); uassertStatusOKWithContext( getStatusFromCommandResult(readResult), "TenantDatabaseCloner failed to get listCollections result majority-committed"); @@ -198,8 +198,9 @@ BaseCloner::AfterStageBehavior TenantDatabaseCloner::listExistingCollectionsStag long long approxTotalDBSizeOnDisk = 0; std::vector<UUID> clonedCollectionUUIDs; - auto collectionInfos = client.getCollectionInfos( - DatabaseName(boost::none, _dbName), ListCollectionsFilter::makeTypeCollectionFilter()); + auto collectionInfos = + client.getCollectionInfos(DatabaseNameUtil::deserialize(boost::none, _dbName), + ListCollectionsFilter::makeTypeCollectionFilter()); for (auto&& info : collectionInfos) { ListCollectionResult result; try { @@ -225,8 +226,9 @@ BaseCloner::AfterStageBehavior TenantDatabaseCloner::listExistingCollectionsStag clonedCollectionUUIDs.emplace_back(result.getInfo().getUuid()); BSONObj res; - client.runCommand( - DatabaseName(boost::none, _dbName), BSON("collStats" << result.getName()), res); + client.runCommand(DatabaseNameUtil::deserialize(boost::none, _dbName), + BSON("collStats" << result.getName()), + res); if (auto status = getStatusFromCommandResult(res); !status.isOK()) { LOGV2_WARNING(5522901, "Skipping recording of data size metrics for database due to failure " diff --git a/src/mongo/db/repl/tenant_migration_recipient_service.cpp b/src/mongo/db/repl/tenant_migration_recipient_service.cpp index d37becd27e8..8cd46747445 100644 --- a/src/mongo/db/repl/tenant_migration_recipient_service.cpp +++ b/src/mongo/db/repl/tenant_migration_recipient_service.cpp @@ -1722,8 +1722,7 @@ TenantMigrationRecipientService::Instance::_fetchRetryableWritesOplogBeforeStart BSONObj readResult; BSONObj cmd = ClonerUtils::buildMajorityWaitRequest(*operationTime); - _client.get()->runCommand( - DatabaseName(boost::none, "admin"), cmd, readResult, QueryOption_SecondaryOk); + _client.get()->runCommand(DatabaseName::kAdmin, cmd, readResult, QueryOption_SecondaryOk); uassertStatusOKWithContext( getStatusFromCommandResult(readResult), "Failed to wait for retryable writes pre-fetch result majority committed"); diff --git a/src/mongo/db/s/check_sharding_index_command.cpp b/src/mongo/db/s/check_sharding_index_command.cpp index b1094698bde..87e7b1a4eea 100644 --- a/src/mongo/db/s/check_sharding_index_command.cpp +++ b/src/mongo/db/s/check_sharding_index_command.cpp @@ -81,7 +81,8 @@ public: const BSONObj& jsobj, std::string& errmsg, BSONObjBuilder& result) override { - const NamespaceString nss(parseNs({boost::none, dbname}, jsobj)); + const NamespaceString nss( + parseNs(DatabaseNameUtil::deserialize(boost::none, dbname), jsobj)); BSONObj keyPattern = jsobj.getObjectField("keyPattern"); if (keyPattern.isEmpty()) { diff --git a/src/mongo/db/s/cluster_pipeline_cmd_d.cpp b/src/mongo/db/s/cluster_pipeline_cmd_d.cpp index 1b3eed4242a..6f10665d8b4 100644 --- a/src/mongo/db/s/cluster_pipeline_cmd_d.cpp +++ b/src/mongo/db/s/cluster_pipeline_cmd_d.cpp @@ -76,7 +76,8 @@ struct ClusterPipelineCommandD { opMsgRequest.body.replaceFieldNames(BSON(AggregateCommandRequest::kCommandName << 1)); return aggregation_request_helper::parseFromBSON( opCtx, - DatabaseName(opMsgRequest.getValidatedTenantId(), opMsgRequest.getDatabase()), + DatabaseNameUtil::deserialize(opMsgRequest.getValidatedTenantId(), + opMsgRequest.getDatabase()), modifiedRequestBody, explainVerbosity, apiStrict); diff --git a/src/mongo/db/s/config/set_cluster_parameter_coordinator.cpp b/src/mongo/db/s/config/set_cluster_parameter_coordinator.cpp index a88bb921b53..050c6fb5e1d 100644 --- a/src/mongo/db/s/config/set_cluster_parameter_coordinator.cpp +++ b/src/mongo/db/s/config/set_cluster_parameter_coordinator.cpp @@ -146,7 +146,7 @@ void SetClusterParameterCoordinator::_sendSetClusterParameterToAllShards( LOGV2_DEBUG(6387001, 1, "Sending setClusterParameter to shards:", "shards"_attr = shards); ShardsvrSetClusterParameter request(_doc.getParameter()); - request.setDbName(DatabaseName(_doc.getTenantId(), DatabaseName::kAdmin.db())); + request.setDbName(DatabaseNameUtil::deserialize(_doc.getTenantId(), DatabaseName::kAdmin.db())); request.setClusterParameterTime(*_doc.getClusterParameterTime()); sharding_util::sendCommandToShards( opCtx, @@ -161,7 +161,7 @@ void SetClusterParameterCoordinator::_commit(OperationContext* opCtx) { SetClusterParameter setClusterParameterRequest(_doc.getParameter()); setClusterParameterRequest.setDbName( - DatabaseName(_doc.getTenantId(), DatabaseName::kAdmin.db())); + DatabaseNameUtil::deserialize(_doc.getTenantId(), DatabaseName::kAdmin.db())); std::unique_ptr<ServerParameterService> parameterService = std::make_unique<ClusterParameterService>(); DBDirectClient client(opCtx); diff --git a/src/mongo/db/s/config/sharding_catalog_manager_shard_operations.cpp b/src/mongo/db/s/config/sharding_catalog_manager_shard_operations.cpp index 657d24f9bc5..01702c95259 100644 --- a/src/mongo/db/s/config/sharding_catalog_manager_shard_operations.cpp +++ b/src/mongo/db/s/config/sharding_catalog_manager_shard_operations.cpp @@ -1222,7 +1222,8 @@ void ShardingCatalogManager::_setClusterParametersLocally(OperationContext* opCt SetClusterParameter setClusterParameterRequest( BSON(parameter["_id"].String() << parameter.filterFieldsUndotted( BSON("_id" << 1 << "clusterParameterTime" << 1), false))); - setClusterParameterRequest.setDbName(DatabaseName(tenantId, DatabaseName::kAdmin.db())); + setClusterParameterRequest.setDbName( + DatabaseNameUtil::deserialize(tenantId, DatabaseName::kAdmin.db())); std::unique_ptr<ServerParameterService> parameterService = std::make_unique<ClusterParameterService>(); SetClusterParameterInvocation invocation{std::move(parameterService), dbService}; @@ -1361,14 +1362,16 @@ void ShardingCatalogManager::_pushClusterParametersToNewShard( ShardsvrSetClusterParameter setClusterParamsCmd( BSON(parameter["_id"].String() << parameter.filterFieldsUndotted( BSON("_id" << 1 << "clusterParameterTime" << 1), false))); - setClusterParamsCmd.setDbName(DatabaseName(tenantId, DatabaseName::kAdmin.db())); + setClusterParamsCmd.setDbName( + DatabaseNameUtil::deserialize(tenantId, DatabaseName::kAdmin.db())); setClusterParamsCmd.setClusterParameterTime( parameter["clusterParameterTime"].timestamp()); const auto cmdResponse = _runCommandForAddShard( opCtx, targeter.get(), - DatabaseName(tenantId, DatabaseName::kAdmin.db()).toStringWithTenantId(), + DatabaseNameUtil::deserialize(tenantId, DatabaseName::kAdmin.db()) + .toStringWithTenantId(), CommandHelpers::appendMajorityWriteConcern(setClusterParamsCmd.toBSON({}))); uassertStatusOK(Shard::CommandResponse::getEffectiveStatus(cmdResponse)); } diff --git a/src/mongo/db/s/drop_database_coordinator.cpp b/src/mongo/db/s/drop_database_coordinator.cpp index ec03418ae8b..00713aea956 100644 --- a/src/mongo/db/s/drop_database_coordinator.cpp +++ b/src/mongo/db/s/drop_database_coordinator.cpp @@ -138,7 +138,7 @@ public: : _opCtx(opCtx), _dbName(std::move(dbName)), _reason(std::move(reason)) { // TODO SERVER-67438 Once ScopedDatabaseCriticalSection holds a DatabaseName obj, use dbName // directly - DatabaseName databaseName(boost::none, _dbName); + DatabaseName databaseName = DatabaseNameUtil::deserialize(boost::none, _dbName); Lock::DBLock dbLock(_opCtx, databaseName, MODE_X); auto scopedDss = DatabaseShardingState::assertDbLockedAndAcquireExclusive(_opCtx, databaseName); @@ -151,7 +151,7 @@ public: UninterruptibleLockGuard guard(_opCtx->lockState()); // NOLINT. // TODO SERVER-67438 Once ScopedDatabaseCriticalSection holds a DatabaseName obj, use dbName // directly - DatabaseName databaseName(boost::none, _dbName); + DatabaseName databaseName = DatabaseNameUtil::deserialize(boost::none, _dbName); Lock::DBLock dbLock(_opCtx, databaseName, MODE_X); auto scopedDss = DatabaseShardingState::assertDbLockedAndAcquireExclusive(_opCtx, databaseName); @@ -279,7 +279,7 @@ void DropDatabaseCoordinator::_dropShardedCollection( } void DropDatabaseCoordinator::_clearDatabaseInfoOnPrimary(OperationContext* opCtx) { - DatabaseName dbName(boost::none, _dbName); + DatabaseName dbName = DatabaseNameUtil::deserialize(boost::none, _dbName); AutoGetDb autoDb(opCtx, dbName, MODE_X); auto scopedDss = DatabaseShardingState::assertDbLockedAndAcquireExclusive(opCtx, dbName); scopedDss->clearDbInfo(opCtx); diff --git a/src/mongo/db/s/get_database_version_command.cpp b/src/mongo/db/s/get_database_version_command.cpp index 8491b251b1d..9f0de300b15 100644 --- a/src/mongo/db/s/get_database_version_command.cpp +++ b/src/mongo/db/s/get_database_version_command.cpp @@ -79,7 +79,7 @@ public: str::stream() << definition()->getName() << " can only be run on shard servers", serverGlobalParams.clusterRole.has(ClusterRole::ShardServer)); - DatabaseName dbName(boost::none, _targetDb()); + DatabaseName dbName = DatabaseNameUtil::deserialize(boost::none, _targetDb()); AutoGetDb autoDb(opCtx, dbName, MODE_IS); const auto scopedDss = DatabaseShardingState::assertDbLockedAndAcquireShared(opCtx, dbName); diff --git a/src/mongo/db/s/migration_destination_manager_commands.cpp b/src/mongo/db/s/migration_destination_manager_commands.cpp index 6e289ccf0cd..4869dc74015 100644 --- a/src/mongo/db/s/migration_destination_manager_commands.cpp +++ b/src/mongo/db/s/migration_destination_manager_commands.cpp @@ -117,7 +117,7 @@ public: opCtx->setAlwaysInterruptAtStepDownOrUp_UNSAFE(); uassertStatusOK(ShardingState::get(opCtx)->canAcceptShardedCommands()); - auto nss = NamespaceString(parseNs({boost::none, dbname}, cmdObj)); + auto nss = parseNs(DatabaseNameUtil::deserialize(boost::none, dbname), cmdObj); auto cloneRequest = uassertStatusOK(StartChunkCloneRequest::createFromCommand(nss, cmdObj)); diff --git a/src/mongo/db/s/move_primary/move_primary_database_cloner_test.cpp b/src/mongo/db/s/move_primary/move_primary_database_cloner_test.cpp index 46d9c753503..b3c95413a1a 100644 --- a/src/mongo/db/s/move_primary/move_primary_database_cloner_test.cpp +++ b/src/mongo/db/s/move_primary/move_primary_database_cloner_test.cpp @@ -88,16 +88,16 @@ protected: _catalogClient = std::make_unique<StaticCatalogClient>(recipientShardedColls); - auto cloner = - std::make_unique<MovePrimaryDatabaseCloner>(DatabaseName(boost::none, _dbName), - donorShardedColls, - ts, - sharedData ? sharedData : getSharedData(), - _source, - _mockClient.get(), - &_storageInterface, - _dbWorkThreadPool.get(), - _catalogClient.get()); + auto cloner = std::make_unique<MovePrimaryDatabaseCloner>( + DatabaseName::createDatabaseName_forTest(boost::none, _dbName), + donorShardedColls, + ts, + sharedData ? sharedData : getSharedData(), + _source, + _mockClient.get(), + &_storageInterface, + _dbWorkThreadPool.get(), + _catalogClient.get()); return cloner; } @@ -125,9 +125,9 @@ protected: } BSONObj createListExistingCollectionsOnDonorResponse(const std::vector<BSONObj>& collections) { - auto ns = - NamespaceString::makeCollectionlessAggregateNSS(DatabaseName(boost::none, "admin")) - .toString(); + auto ns = NamespaceString::makeCollectionlessAggregateNSS( + DatabaseName::createDatabaseName_forTest(boost::none, "admin")) + .toString(); BSONObjBuilder bob; { BSONObjBuilder cursorBob(bob.subobjStart("cursor")); diff --git a/src/mongo/db/s/resharding/resharding_coordinator_commit_monitor.cpp b/src/mongo/db/s/resharding/resharding_coordinator_commit_monitor.cpp index 68f640d13b6..c4d4c814c93 100644 --- a/src/mongo/db/s/resharding/resharding_coordinator_commit_monitor.cpp +++ b/src/mongo/db/s/resharding/resharding_coordinator_commit_monitor.cpp @@ -61,7 +61,7 @@ MONGO_FAIL_POINT_DEFINE(hangBeforeQueryingRecipients); BSONObj makeCommandObj(const NamespaceString& ns) { auto command = _shardsvrReshardingOperationTime(ns); - command.setDbName(DatabaseName(ns.tenantId(), DatabaseName::kAdmin.db())); + command.setDbName(DatabaseNameUtil::deserialize(ns.tenantId(), DatabaseName::kAdmin.db())); return command.toBSON({}); } diff --git a/src/mongo/db/s/shard_key_util.cpp b/src/mongo/db/s/shard_key_util.cpp index e9e6a6ca988..37f443a59c3 100644 --- a/src/mongo/db/s/shard_key_util.cpp +++ b/src/mongo/db/s/shard_key_util.cpp @@ -289,7 +289,7 @@ void ValidationBehaviorsShardCollection::verifyUsefulNonMultiKeyIndex( const NamespaceString& nss, const BSONObj& proposedKey) const { BSONObj res; auto success = _localClient->runCommand( - DatabaseName(boost::none, "admin"), + DatabaseName::kAdmin, BSON(kCheckShardingIndexCmdName << nss.ns() << kKeyPatternField << proposedKey), res); uassert(ErrorCodes::InvalidOptions, res["errmsg"].str(), success); diff --git a/src/mongo/db/s/shard_server_op_observer.cpp b/src/mongo/db/s/shard_server_op_observer.cpp index 657db377baa..39878a64023 100644 --- a/src/mongo/db/s/shard_server_op_observer.cpp +++ b/src/mongo/db/s/shard_server_op_observer.cpp @@ -363,7 +363,7 @@ void ShardServerOpObserver::onUpdate(OperationContext* opCtx, // block. AllowLockAcquisitionOnTimestampedUnitOfWork allowLockAcquisition(opCtx->lockState()); - DatabaseName dbName(boost::none, db); + DatabaseName dbName = DatabaseNameUtil::deserialize(boost::none, db); AutoGetDb autoDb(opCtx, dbName, MODE_X); auto scopedDss = DatabaseShardingState::assertDbLockedAndAcquireExclusive(opCtx, dbName); @@ -599,7 +599,7 @@ void ShardServerOpObserver::onDelete(OperationContext* opCtx, // TODO SERVER-58223: evaluate whether this is safe or whether acquiring the lock can block. AllowLockAcquisitionOnTimestampedUnitOfWork allowLockAcquisition(opCtx->lockState()); - DatabaseName dbName(boost::none, deletedDatabase); + DatabaseName dbName = DatabaseNameUtil::deserialize(boost::none, deletedDatabase); AutoGetDb autoDb(opCtx, dbName, MODE_X); auto scopedDss = DatabaseShardingState::assertDbLockedAndAcquireExclusive(opCtx, dbName); scopedDss->clearDbInfo(opCtx); diff --git a/src/mongo/db/s/shardsvr_merge_chunks_command.cpp b/src/mongo/db/s/shardsvr_merge_chunks_command.cpp index 4169f3235d5..1b44983f85b 100644 --- a/src/mongo/db/s/shardsvr_merge_chunks_command.cpp +++ b/src/mongo/db/s/shardsvr_merge_chunks_command.cpp @@ -168,7 +168,8 @@ public: BSONObjBuilder& result) override { uassertStatusOK(ShardingState::get(opCtx)->canAcceptShardedCommands()); - const NamespaceString nss(parseNs({boost::none, dbname}, cmdObj)); + const NamespaceString nss( + parseNs(DatabaseNameUtil::deserialize(boost::none, dbname), cmdObj)); std::vector<BSONObj> bounds; if (!FieldParser::extract(cmdObj, boundsField, &bounds, &errmsg)) { diff --git a/src/mongo/db/s/shardsvr_move_primary_command.cpp b/src/mongo/db/s/shardsvr_move_primary_command.cpp index 97cf2be04a6..48a976c2606 100644 --- a/src/mongo/db/s/shardsvr_move_primary_command.cpp +++ b/src/mongo/db/s/shardsvr_move_primary_command.cpp @@ -92,7 +92,7 @@ public: const auto movePrimaryRequest = ShardMovePrimary::parse(IDLParserContext("_shardsvrMovePrimary"), cmdObj); - const auto dbName = parseNs({boost::none, ""}, cmdObj).dbName(); + const auto dbName = parseNs(DatabaseName(), cmdObj).dbName(); const NamespaceString dbNss(dbName); const auto toShardArg = movePrimaryRequest.getTo(); diff --git a/src/mongo/db/s/shardsvr_split_chunk_command.cpp b/src/mongo/db/s/shardsvr_split_chunk_command.cpp index f547cfb9543..88e7f7aa8b3 100644 --- a/src/mongo/db/s/shardsvr_split_chunk_command.cpp +++ b/src/mongo/db/s/shardsvr_split_chunk_command.cpp @@ -99,7 +99,8 @@ public: BSONObjBuilder& result) override { uassertStatusOK(ShardingState::get(opCtx)->canAcceptShardedCommands()); - const NamespaceString nss(parseNs({boost::none, dbname}, cmdObj)); + const NamespaceString nss( + parseNs(DatabaseNameUtil::deserialize(boost::none, dbname), cmdObj)); // Check whether parameters passed to splitChunk are sound BSONObj keyPatternObj; diff --git a/src/mongo/db/s/split_vector_command.cpp b/src/mongo/db/s/split_vector_command.cpp index 2e2bf3cb9b3..1d48af10f28 100644 --- a/src/mongo/db/s/split_vector_command.cpp +++ b/src/mongo/db/s/split_vector_command.cpp @@ -92,7 +92,8 @@ public: string& errmsg, BSONObjBuilder& result) override { - const NamespaceString nss(parseNs({boost::none, dbname}, jsobj)); + const NamespaceString nss( + parseNs(DatabaseNameUtil::deserialize(boost::none, dbname), jsobj)); BSONObj keyPattern = jsobj.getObjectField("keyPattern"); if (keyPattern.isEmpty()) { diff --git a/src/mongo/rpc/op_msg.cpp b/src/mongo/rpc/op_msg.cpp index 55b0c647bf7..d3637e7bc2c 100644 --- a/src/mongo/rpc/op_msg.cpp +++ b/src/mongo/rpc/op_msg.cpp @@ -254,7 +254,8 @@ OpMsg OpMsg::parse(const Message& message, Client* client) try { } OpMsgRequest OpMsgRequest::fromDBAndBody(StringData db, BSONObj body, const BSONObj& extraFields) { - return OpMsgRequestBuilder::create({boost::none, db}, std::move(body), extraFields); + return OpMsgRequestBuilder::create( + DatabaseNameUtil::deserialize(boost::none, db), std::move(body), extraFields); } boost::optional<TenantId> parseDollarTenant(const BSONObj body) { diff --git a/src/mongo/s/client/sharding_connection_hook.cpp b/src/mongo/s/client/sharding_connection_hook.cpp index be6498ccc6f..16886b25b21 100644 --- a/src/mongo/s/client/sharding_connection_hook.cpp +++ b/src/mongo/s/client/sharding_connection_hook.cpp @@ -76,8 +76,7 @@ void ShardingConnectionHook::onCreate(DBClientBase* conn) { if (conn->type() == ConnectionString::ConnectionType::kStandalone) { BSONObj isMasterResponse; - if (!conn->runCommand( - DatabaseName(boost::none, "admin"), BSON("ismaster" << 1), isMasterResponse)) { + if (!conn->runCommand(DatabaseName::kAdmin, BSON("ismaster" << 1), isMasterResponse)) { uassertStatusOK(getStatusFromCommandResult(isMasterResponse)); } diff --git a/src/mongo/s/commands/cluster_count_cmd.h b/src/mongo/s/commands/cluster_count_cmd.h index 1ec1f9edfec..2f1989776cd 100644 --- a/src/mongo/s/commands/cluster_count_cmd.h +++ b/src/mongo/s/commands/cluster_count_cmd.h @@ -107,7 +107,8 @@ public: Impl::checkCanRunHere(opCtx); CommandHelpers::handleMarkKillOnClientDisconnect(opCtx); - const NamespaceString nss(parseNs({boost::none, dbname}, cmdObj)); + const NamespaceString nss( + parseNs(DatabaseNameUtil::deserialize(boost::none, dbname), cmdObj)); uassert(ErrorCodes::InvalidNamespace, str::stream() << "Invalid namespace specified '" << nss.toStringForErrorMsg() << "'", diff --git a/src/mongo/s/commands/cluster_find_and_modify_cmd.cpp b/src/mongo/s/commands/cluster_find_and_modify_cmd.cpp index bfcaac9b4d7..d8b3c820341 100644 --- a/src/mongo/s/commands/cluster_find_and_modify_cmd.cpp +++ b/src/mongo/s/commands/cluster_find_and_modify_cmd.cpp @@ -417,7 +417,8 @@ Status FindAndModifyCmd::explain(OperationContext* opCtx, const OpMsgRequest& request, ExplainOptions::Verbosity verbosity, rpc::ReplyBuilderInterface* result) const { - const DatabaseName dbName(request.getValidatedTenantId(), request.getDatabase()); + const DatabaseName dbName = + DatabaseNameUtil::deserialize(request.getValidatedTenantId(), request.getDatabase()); const BSONObj& cmdObj = [&]() { // Check whether the query portion needs to be rewritten for FLE. auto findAndModifyRequest = write_ops::FindAndModifyCommandRequest::parse( diff --git a/src/mongo/s/commands/cluster_find_cmd.h b/src/mongo/s/commands/cluster_find_cmd.h index cd46d911895..e917cc3301e 100644 --- a/src/mongo/s/commands/cluster_find_cmd.h +++ b/src/mongo/s/commands/cluster_find_cmd.h @@ -105,7 +105,8 @@ public: Invocation(const ClusterFindCmdBase* definition, const OpMsgRequest& request) : CommandInvocation(definition), _request(request), - _dbName(request.getValidatedTenantId(), request.getDatabase()) {} + _dbName(DatabaseNameUtil::deserialize(request.getValidatedTenantId(), + request.getDatabase())) {} private: bool supportsWriteConcern() const override { diff --git a/src/mongo/s/commands/cluster_merge_chunks_cmd.cpp b/src/mongo/s/commands/cluster_merge_chunks_cmd.cpp index 4812db80d8c..a8e5be63a22 100644 --- a/src/mongo/s/commands/cluster_merge_chunks_cmd.cpp +++ b/src/mongo/s/commands/cluster_merge_chunks_cmd.cpp @@ -94,7 +94,8 @@ public: const BSONObj& cmdObj, std::string& errmsg, BSONObjBuilder& result) override { - const NamespaceString nss(parseNs({boost::none, dbname}, cmdObj)); + const NamespaceString nss( + parseNs(DatabaseNameUtil::deserialize(boost::none, dbname), cmdObj)); std::vector<BSONObj> bounds; if (!FieldParser::extract(cmdObj, boundsField, &bounds, &errmsg)) { diff --git a/src/mongo/s/commands/cluster_pipeline_cmd_s.cpp b/src/mongo/s/commands/cluster_pipeline_cmd_s.cpp index 8930e532fa6..45287691651 100644 --- a/src/mongo/s/commands/cluster_pipeline_cmd_s.cpp +++ b/src/mongo/s/commands/cluster_pipeline_cmd_s.cpp @@ -64,7 +64,8 @@ struct ClusterPipelineCommandS { bool apiStrict) { return aggregation_request_helper::parseFromBSON( opCtx, - DatabaseName(opMsgRequest.getValidatedTenantId(), opMsgRequest.getDatabase()), + DatabaseNameUtil::deserialize(opMsgRequest.getValidatedTenantId(), + opMsgRequest.getDatabase()), opMsgRequest.body, explainVerbosity, apiStrict); diff --git a/src/mongo/s/commands/cluster_split_cmd.cpp b/src/mongo/s/commands/cluster_split_cmd.cpp index adeed2b44cf..e60362f48a5 100644 --- a/src/mongo/s/commands/cluster_split_cmd.cpp +++ b/src/mongo/s/commands/cluster_split_cmd.cpp @@ -132,7 +132,8 @@ public: const BSONObj& cmdObj, std::string& errmsg, BSONObjBuilder& result) override { - const NamespaceString nss(parseNs({boost::none, dbname}, cmdObj)); + const NamespaceString nss( + parseNs(DatabaseNameUtil::deserialize(boost::none, dbname), cmdObj)); const auto cri = uassertStatusOK( Grid::get(opCtx)->catalogCache()->getShardedCollectionRoutingInfoWithRefresh(opCtx, diff --git a/src/mongo/scripting/mozjs/mongo.cpp b/src/mongo/scripting/mozjs/mongo.cpp index 8ebcf06e796..901e08390b7 100644 --- a/src/mongo/scripting/mozjs/mongo.cpp +++ b/src/mongo/scripting/mozjs/mongo.cpp @@ -320,7 +320,8 @@ void MongoBase::Functions::_runCommandImpl::call(JSContext* cx, JS::CallArgs arg str::stream() << "The options parameter to runCommand must be a number", args.get(2).isNumber()); auto options = ValueWriter(cx, args.get(2)).toInt32(); - return rpc::upconvertRequest({boost::none, database}, cmd, options); + return rpc::upconvertRequest( + DatabaseName::createDatabaseName_forTest(boost::none, database), cmd, options); }); } diff --git a/src/mongo/scripting/mozjs/session.cpp b/src/mongo/scripting/mozjs/session.cpp index 3a18c6c401c..9b862f1dba1 100644 --- a/src/mongo/scripting/mozjs/session.cpp +++ b/src/mongo/scripting/mozjs/session.cpp @@ -129,7 +129,7 @@ void endSession(SessionHolder* holder) { << holder->txnNumber << "autocommit" << false); [[maybe_unused]] auto ignored = - holder->client->runCommand(DatabaseName(boost::none, "admin"), abortObj, out); + holder->client->runCommand(DatabaseName::kAdmin, abortObj, out); } EndSessions es; @@ -137,7 +137,7 @@ void endSession(SessionHolder* holder) { es.setEndSessions({holder->lsid}); [[maybe_unused]] auto ignored = - holder->client->runCommand(DatabaseName(boost::none, "admin"), es.toBSON(), out); + holder->client->runCommand(DatabaseName::kAdmin, es.toBSON(), out); holder->client.reset(); } diff --git a/src/mongo/shell/bench.cpp b/src/mongo/shell/bench.cpp index b71e82a5a50..fd78b6ffdf5 100644 --- a/src/mongo/shell/bench.cpp +++ b/src/mongo/shell/bench.cpp @@ -179,7 +179,7 @@ void abortTransaction(DBClientBase* conn, BSONObj abortTransactionCmd = BSON("abortTransaction" << 1); BSONObj abortCommandResult; const bool successful = runCommandWithSession(conn, - DatabaseName(boost::none, "admin"), + DatabaseName::kAdmin, abortTransactionCmd, kMultiStatementTransactionOption, lsid, @@ -926,8 +926,7 @@ void BenchRunWorker::generateLoadOnConnection(DBClientBase* conn) { BSONObj result; uassert(40640, str::stream() << "Unable to create session due to error " << result, - conn->runCommand( - DatabaseName(boost::none, "admin"), BSON("startSession" << 1), result)); + conn->runCommand(DatabaseName::kAdmin, BSON("startSession" << 1), result)); lsid.emplace(LogicalSessionIdToClient::parse(IDLParserContext("lsid"), result["id"].Obj())); } @@ -1093,12 +1092,13 @@ void BenchRunOp::executeOnce(DBClientBase* conn, BSONObj result; { BenchRunEventTrace _bret(&state->stats->commandCounter); - ok = runCommandWithSession(conn, - DatabaseName(this->tenantId, this->ns), - fixQuery(this->command, *state->bsonTemplateEvaluator), - this->options, - lsid, - &result); + ok = runCommandWithSession( + conn, + DatabaseName::createDatabaseName_forTest(this->tenantId, this->ns), + fixQuery(this->command, *state->bsonTemplateEvaluator), + this->options, + lsid, + &result); } if (!ok) { ++state->stats->errCount; @@ -1115,12 +1115,13 @@ void BenchRunOp::executeOnce(DBClientBase* conn, uassert(ErrorCodes::CommandFailed, str::stream() << "getMore command failed; reply was: " << getMoreCommandResult, - runCommandWithSession(conn, - DatabaseName(this->tenantId, this->ns), - getMoreRequest.toBSON({}), - kNoOptions, - lsid, - &getMoreCommandResult)); + runCommandWithSession( + conn, + DatabaseName::createDatabaseName_forTest(this->tenantId, this->ns), + getMoreRequest.toBSON({}), + kNoOptions, + lsid, + &getMoreCommandResult)); cursorResponse = uassertStatusOK(CursorResponse::parseFromBSON(getMoreCommandResult)); count += cursorResponse.getBatch().size(); @@ -1258,7 +1259,8 @@ void BenchRunOp::executeOnce(DBClientBase* conn, txnNumberForOp = state->txnNumber; } runCommandWithSession(conn, - DatabaseName(this->tenantId, nsToDatabaseSubstring(this->ns)), + DatabaseName::createDatabaseName_forTest( + this->tenantId, nsToDatabaseSubstring(this->ns)), builder.done(), kNoOptions, lsid, @@ -1296,7 +1298,8 @@ void BenchRunOp::executeOnce(DBClientBase* conn, txnNumberForOp = state->txnNumber; } runCommandWithSession(conn, - DatabaseName(this->tenantId, nsToDatabaseSubstring(this->ns)), + DatabaseName::createDatabaseName_forTest( + this->tenantId, nsToDatabaseSubstring(this->ns)), builder.done(), kNoOptions, lsid, @@ -1326,7 +1329,8 @@ void BenchRunOp::executeOnce(DBClientBase* conn, txnNumberForOp = state->txnNumber; } runCommandWithSession(conn, - DatabaseName(this->tenantId, nsToDatabaseSubstring(this->ns)), + DatabaseName::createDatabaseName_forTest( + this->tenantId, nsToDatabaseSubstring(this->ns)), builder.done(), kNoOptions, lsid, diff --git a/src/mongo/shell/encrypted_dbclient_base.cpp b/src/mongo/shell/encrypted_dbclient_base.cpp index d35ced39e49..6cd1572be6d 100644 --- a/src/mongo/shell/encrypted_dbclient_base.cpp +++ b/src/mongo/shell/encrypted_dbclient_base.cpp @@ -240,8 +240,9 @@ EncryptedDBClientBase::RunCommandReturn EncryptedDBClientBase::handleEncryptionR auto& request = params.request; auto commandName = request.getCommandName().toString(); const DatabaseName dbName = request.body.hasField("$tenant") - ? DatabaseName(TenantId(request.body["$tenant"].OID()), request.getDatabase()) - : DatabaseName(boost::none, request.getDatabase()); + ? DatabaseNameUtil::deserialize(TenantId(request.body["$tenant"].OID()), + request.getDatabase()) + : DatabaseName::createDatabaseName_forTest(boost::none, request.getDatabase()); if (std::find(kEncryptedCommands.begin(), kEncryptedCommands.end(), StringData(commandName)) == std::end(kEncryptedCommands)) { diff --git a/src/mongo/shell/shell_utils.cpp b/src/mongo/shell/shell_utils.cpp index 698bb89292b..7fd8d842e4f 100644 --- a/src/mongo/shell/shell_utils.cpp +++ b/src/mongo/shell/shell_utils.cpp @@ -750,7 +750,7 @@ void ConnectionRegistry::registerConnection(DBClientBase& client, StringData uri command = BSON("whatsmyuri" << 1); } - if (client.runCommand({boost::none, "admin"}, command, info)) { + if (client.runCommand(DatabaseName::kAdmin, command, info)) { stdx::lock_guard<Latch> lk(_mutex); _connectionUris[uri.toString()].insert(info["you"].str()); } @@ -771,7 +771,7 @@ void ConnectionRegistry::killOperationsOnAllConnections(bool withPrompt) const { const std::set<std::string>& uris = connection.second; BSONObj currentOpRes; - conn->runCommand({boost::none, "admin"}, BSON("currentOp" << 1), currentOpRes); + conn->runCommand(DatabaseName::kAdmin, BSON("currentOp" << 1), currentOpRes); if (!currentOpRes["inprog"].isABSONObj()) { // We don't have permissions (or the call didn't succeed) - go to the next connection. continue; @@ -808,7 +808,7 @@ void ConnectionRegistry::killOperationsOnAllConnections(bool withPrompt) const { if (!withPrompt || prompter.confirm()) { BSONObj info; conn->runCommand( - {boost::none, "admin"}, BSON("killOp" << 1 << "op" << op["opid"]), info); + DatabaseName::kAdmin, BSON("killOp" << 1 << "op" << op["opid"]), info); } else { return; } diff --git a/src/mongo/util/database_name_util.cpp b/src/mongo/util/database_name_util.cpp index bd988f6c37c..bc2b999cc5e 100644 --- a/src/mongo/util/database_name_util.cpp +++ b/src/mongo/util/database_name_util.cpp @@ -89,7 +89,8 @@ std::string DatabaseNameUtil::serializeForCommands(const DatabaseName& dbName, } -DatabaseName parseDbNameFromStringExpectTenantIdInMultitenancyMode(StringData dbName) { +DatabaseName DatabaseNameUtil::parseDbNameFromStringExpectTenantIdInMultitenancyMode( + StringData dbName) { if (!gMultitenancySupport) { return DatabaseName(boost::none, dbName); } @@ -115,7 +116,7 @@ DatabaseName DatabaseNameUtil::deserialize(boost::optional<TenantId> tenantId, StringData db, const SerializationContext& context) { if (db.empty()) { - return DatabaseName(); + return DatabaseName(tenantId, ""); } if (!gMultitenancySupport) { @@ -144,7 +145,7 @@ DatabaseName DatabaseNameUtil::deserializeForStorage(boost::optional<TenantId> t return DatabaseName(std::move(tenantId), db); } - auto dbName = parseDbNameFromStringExpectTenantIdInMultitenancyMode(db); + auto dbName = DatabaseNameUtil::parseDbNameFromStringExpectTenantIdInMultitenancyMode(db); // TenantId could be prefixed, or passed in separately (or both) and namespace is always // constructed with the tenantId separately. if (tenantId != boost::none) { diff --git a/src/mongo/util/database_name_util.h b/src/mongo/util/database_name_util.h index f3668fd28dc..352f24a9dd8 100644 --- a/src/mongo/util/database_name_util.h +++ b/src/mongo/util/database_name_util.h @@ -104,6 +104,9 @@ public: boost::optional<TenantId> tenantId, StringData db, const SerializationContext& context = SerializationContext()); + +private: + static DatabaseName parseDbNameFromStringExpectTenantIdInMultitenancyMode(StringData dbName); }; } // namespace mongo diff --git a/src/mongo/util/database_name_util_test.cpp b/src/mongo/util/database_name_util_test.cpp index ef18f6e79cb..d573ee33434 100644 --- a/src/mongo/util/database_name_util_test.cpp +++ b/src/mongo/util/database_name_util_test.cpp @@ -164,25 +164,25 @@ TEST(DatabaseNameUtilTest, SerializeMissingExpectPrefix_CommandReply) { { // No prefix, no tenantId. // request --> { ns: database.coll } - auto dbName = DatabaseName(boost::none, dbnString); + auto dbName = DatabaseName::createDatabaseName_forTest(boost::none, dbnString); ASSERT_EQ(DatabaseNameUtil::serializeForCommands(dbName, ctxt_noTenantId), dbnString); } { // Has prefix, no tenantId. // request --> { ns: tenantId_database.coll } - auto dbName = DatabaseName(boost::none, dbnPrefixString); + auto dbName = DatabaseName::createDatabaseName_forTest(boost::none, dbnPrefixString); ASSERT_EQ(DatabaseNameUtil::serializeForCommands(dbName, ctxt_noTenantId), dbnPrefixString); } { // No prefix, has tenantId. // request --> { ns: database.coll, $tenant: tenantId } - auto dbName = DatabaseName(tenantId, dbnString); + auto dbName = DatabaseName::createDatabaseName_forTest(tenantId, dbnString); ASSERT_EQ(DatabaseNameUtil::serializeForCommands(dbName, ctxt_withTenantId), dbnString); } { // Has prefix, has tenantId. *** we shouldn't see this from Atlas Proxy // request --> { ns: tenantId_database.coll, $tenant: tenantId } - auto dbName = DatabaseName(tenantId, dbnPrefixString); + auto dbName = DatabaseName::createDatabaseName_forTest(tenantId, dbnPrefixString); ASSERT_EQ(DatabaseNameUtil::serializeForCommands(dbName, ctxt_withTenantId), dbnPrefixString); } @@ -205,25 +205,25 @@ TEST(DatabaseNameUtilTest, SerializeExpectPrefixFalse_CommandReply) { { // No prefix, no tenantId. // request --> { ns: database.coll, expectPrefix: false } - auto dbName = DatabaseName(boost::none, dbnString); + auto dbName = DatabaseName::createDatabaseName_forTest(boost::none, dbnString); ASSERT_EQ(DatabaseNameUtil::serializeForCommands(dbName, ctxt_noTenantId), dbnString); } { // Has prefix, no tenantId. *** we shouldn't see this from Atlas Proxy // request --> { ns: tenantId_database.coll, expectPrefix: false } - auto dbName = DatabaseName(boost::none, dbnPrefixString); + auto dbName = DatabaseName::createDatabaseName_forTest(boost::none, dbnPrefixString); ASSERT_EQ(DatabaseNameUtil::serializeForCommands(dbName, ctxt_noTenantId), dbnPrefixString); } { // No prefix, has tenantId. // request --> { ns: database.coll, $tenant: tenantId, expectPrefix: false } - auto dbName = DatabaseName(tenantId, dbnString); + auto dbName = DatabaseName::createDatabaseName_forTest(tenantId, dbnString); ASSERT_EQ(DatabaseNameUtil::serializeForCommands(dbName, ctxt_withTenantId), dbnString); } { // Has prefix, has tenantId. *** we shouldn't see this from Atlas Proxy // request --> { ns: tenantId_database.coll, $tenant: tenantId, expectPrefix: false } - auto dbName = DatabaseName(tenantId, dbnPrefixString); + auto dbName = DatabaseName::createDatabaseName_forTest(tenantId, dbnPrefixString); ASSERT_EQ(DatabaseNameUtil::serializeForCommands(dbName, ctxt_withTenantId), dbnPrefixString); } @@ -247,19 +247,19 @@ TEST(DatabaseNameUtilTest, SerializeExpectPrefixTrue_CommandReply) { { // No prefix, no tenantId. *** we shouldn't see this from Atlas Proxy // request --> { ns: database.coll, expectPrefix: true } - auto dbName = DatabaseName(boost::none, dbnString); + auto dbName = DatabaseName::createDatabaseName_forTest(boost::none, dbnString); ASSERT_EQ(DatabaseNameUtil::serializeForCommands(dbName, ctxt_noTenantId), dbnString); } { // Has prefix, no tenantId. // request --> { ns: tenantId_database.coll, expectPrefix: true } - auto dbName = DatabaseName(boost::none, dbnPrefixString); + auto dbName = DatabaseName::createDatabaseName_forTest(boost::none, dbnPrefixString); ASSERT_EQ(DatabaseNameUtil::serializeForCommands(dbName, ctxt_noTenantId), dbnPrefixString); } { // No prefix, has tenantId. *** we shouldn't see this from Atlas Proxy // request --> { ns: database.coll, $tenant: tenantId, expectPrefix: true } - auto dbName = DatabaseName(tenantId, dbnString); + auto dbName = DatabaseName::createDatabaseName_forTest(tenantId, dbnString); ASSERT_EQ(DatabaseNameUtil::serializeForCommands(dbName, ctxt_noTenantId), dbnPrefixString); } @@ -267,7 +267,7 @@ TEST(DatabaseNameUtilTest, SerializeExpectPrefixTrue_CommandReply) { // request --> { ns: tenantId_database.coll, $tenant: tenantId, expectPrefix: true } const std::string nsDoublePrefixString = str::stream() << tenantId.toString() << "_" << tenantId.toString() << "_" << dbnString; - auto dbName = DatabaseName(tenantId, dbnPrefixString); + auto dbName = DatabaseName::createDatabaseName_forTest(tenantId, dbnPrefixString); ASSERT_EQ(DatabaseNameUtil::serializeForCommands(dbName, ctxt_noTenantId), nsDoublePrefixString); } |