summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorCheahuychou Mao <mao.cheahuychou@gmail.com>2022-09-19 23:55:21 +0000
committerEvergreen Agent <no-reply@evergreen.mongodb.com>2022-09-20 19:14:39 +0000
commit722d0d3ba9eb5579998b75f35613224f2c32efe5 (patch)
treee0891a20347551112e8beccb41fc8e791f0258e6 /src
parent0baa1bacf682849154e1df565f0bd63ee203c8ca (diff)
downloadmongo-722d0d3ba9eb5579998b75f35613224f2c32efe5.tar.gz
SERVER-68753 Make analyzeShardKey command calculate metrics about the monotonicity
Diffstat (limited to 'src')
-rw-r--r--src/mongo/base/error_codes.yml2
-rw-r--r--src/mongo/db/s/analyze_shard_key_cmd_util.cpp87
-rw-r--r--src/mongo/s/SConscript1
-rw-r--r--src/mongo/s/analyze_shard_key_cmd.idl13
-rw-r--r--src/mongo/s/analyze_shard_key_server_parameters.idl47
-rw-r--r--src/mongo/s/commands/cluster_analyze_shard_key_cmd.cpp98
6 files changed, 215 insertions, 33 deletions
diff --git a/src/mongo/base/error_codes.yml b/src/mongo/base/error_codes.yml
index 4234bdfe85b..c2e8fcd1a5d 100644
--- a/src/mongo/base/error_codes.yml
+++ b/src/mongo/base/error_codes.yml
@@ -494,6 +494,8 @@ error_codes:
- {code: 382, name: RemoteCommandExecutionError, extra: RemoteCommandExecutionErrorInfo, categories: [InternalOnly]}
+ - {code: 383, name: CollectionIsEmptyLocally, categories: [InternalOnly]}
+
# Error codes 4000-8999 are reserved.
# Non-sequential error codes for compatibility only)
diff --git a/src/mongo/db/s/analyze_shard_key_cmd_util.cpp b/src/mongo/db/s/analyze_shard_key_cmd_util.cpp
index 4ed56091ddc..766e78cb228 100644
--- a/src/mongo/db/s/analyze_shard_key_cmd_util.cpp
+++ b/src/mongo/db/s/analyze_shard_key_cmd_util.cpp
@@ -29,13 +29,18 @@
#include "mongo/platform/basic.h"
+#include <boost/math/statistics/bivariate_statistics.hpp>
+
+#include "mongo/db/bson/dotted_path_support.h"
#include "mongo/db/db_raii.h"
#include "mongo/db/dbdirectclient.h"
#include "mongo/db/pipeline/aggregate_command_gen.h"
+#include "mongo/db/query/internal_plans.h"
#include "mongo/db/s/analyze_shard_key_cmd_util.h"
#include "mongo/db/s/shard_key_index_util.h"
#include "mongo/logv2/log.h"
#include "mongo/rpc/factory.h"
+#include "mongo/s/analyze_shard_key_server_parameters_gen.h"
#include "mongo/s/grid.h"
#include "mongo/s/query/cluster_aggregate.h"
#include "mongo/s/service_entry_point_mongos.h"
@@ -319,6 +324,81 @@ CardinalityFrequencyMetricsBundle calculateCardinalityAndFrequency(OperationCont
return bundle;
}
+/**
+ * Returns the monotonicity metrics for the given shard key, i.e. whether the value of the given
+ * shard key is monotonically changing in insertion order. If the collection is clustered or the
+ * shard key does not have a supporting index, returns 'unknown'.
+ */
+MonotonicityTypeEnum calculateMonotonicity(OperationContext* opCtx,
+ const CollectionPtr& collection,
+ const BSONObj& shardKey) {
+ if (collection->isClustered()) {
+ return MonotonicityTypeEnum::kUnknown;
+ }
+
+ if (KeyPattern::isHashedKeyPattern(shardKey) && shardKey.nFields() == 1) {
+ return MonotonicityTypeEnum::kNotMonotonic;
+ }
+
+ auto index = findShardKeyPrefixedIndex(opCtx,
+ collection,
+ collection->getIndexCatalog(),
+ shardKey,
+ /*requireSingleKey=*/true);
+
+ if (!index) {
+ return MonotonicityTypeEnum::kUnknown;
+ }
+ // Non-clustered indexes always have an associated IndexDescriptor.
+ invariant(index->descriptor());
+
+ std::vector<int64_t> recordIds;
+ BSONObj prevKey;
+
+ KeyPattern indexKeyPattern(index->keyPattern());
+ auto exec = InternalPlanner::indexScan(opCtx,
+ &collection,
+ index->descriptor(),
+ indexKeyPattern.globalMin(),
+ indexKeyPattern.globalMax(),
+ BoundInclusion::kExcludeBothStartAndEndKeys,
+ PlanYieldPolicy::YieldPolicy::INTERRUPT_ONLY);
+ try {
+ RecordId recordId;
+ BSONObj recordVal;
+ while (PlanExecutor::ADVANCED == exec->getNext(&recordVal, &recordId)) {
+ auto currentKey = dotted_path_support::extractElementsBasedOnTemplate(
+ recordVal.replaceFieldNames(shardKey), shardKey);
+ if (SimpleBSONObjComparator::kInstance.evaluate(prevKey == currentKey)) {
+ continue;
+ }
+ prevKey = currentKey;
+ recordIds.push_back(recordId.getLong());
+ }
+ } catch (DBException& ex) {
+ LOGV2_WARNING(6875301, "Internal error while reading", "ns"_attr = collection->ns());
+ ex.addContext("Executor error while reading during 'analyzeShardKey' command");
+ throw;
+ }
+
+ invariant(recordIds.size() > 0);
+
+ auto coefficient = [&] {
+ auto& y = recordIds;
+ std::vector<int64_t> x(y.size());
+ std::iota(x.begin(), x.end(), 1);
+ return boost::math::statistics::correlation_coefficient<std::vector<int64_t>>(x, y);
+ }();
+ auto coefficientThreshold = gMonotonicityCorrelationCoefficientThreshold.load();
+ LOGV2(6875302,
+ "Calculating monotonicity",
+ "coefficient"_attr = coefficient,
+ "coefficientThreshold"_attr = coefficientThreshold);
+
+ return abs(coefficient) >= coefficientThreshold ? MonotonicityTypeEnum::kMonotonic
+ : MonotonicityTypeEnum::kNotMonotonic;
+}
+
} // namespace
KeyCharacteristicsMetrics calculateKeyCharacteristicsMetrics(OperationContext* opCtx,
@@ -335,6 +415,12 @@ KeyCharacteristicsMetrics calculateKeyCharacteristicsMetrics(OperationContext* o
str::stream() << "Cannot analyze a shard key for a non-existing collection",
collection);
+ uassert(serverGlobalParams.clusterRole == ClusterRole::ShardServer
+ ? ErrorCodes::CollectionIsEmptyLocally
+ : ErrorCodes::InvalidOptions,
+ "Cannot analyze a shard key for an empty collection",
+ collection->numRecords(opCtx) > 0);
+
auto indexSpec = findCompatiblePrefixedIndex(
opCtx, *collection, collection->getIndexCatalog(), shardKeyBson);
@@ -345,6 +431,7 @@ KeyCharacteristicsMetrics calculateKeyCharacteristicsMetrics(OperationContext* o
indexKeyBson = indexSpec->keyPattern.getOwned();
metrics.setIsUnique(shardKeyBson.nFields() == indexKeyBson.nFields() ? indexSpec->isUnique
: false);
+ metrics.setMonotonicity(calculateMonotonicity(opCtx, *collection, shardKeyBson));
}
auto bundle = calculateCardinalityAndFrequency(
diff --git a/src/mongo/s/SConscript b/src/mongo/s/SConscript
index 6997dfdbc58..c99dd308612 100644
--- a/src/mongo/s/SConscript
+++ b/src/mongo/s/SConscript
@@ -137,6 +137,7 @@ env.Library(
source=[
'analyze_shard_key_cmd.idl',
'analyze_shard_key_feature_flag.idl',
+ 'analyze_shard_key_server_parameters.idl',
'cannot_implicitly_create_collection_info.cpp',
'catalog/mongo_version_range.cpp',
'catalog/type_changelog.cpp',
diff --git a/src/mongo/s/analyze_shard_key_cmd.idl b/src/mongo/s/analyze_shard_key_cmd.idl
index 1c437d262a4..650e00d6738 100644
--- a/src/mongo/s/analyze_shard_key_cmd.idl
+++ b/src/mongo/s/analyze_shard_key_cmd.idl
@@ -33,6 +33,15 @@ imports:
- "mongo/db/basic_types.idl"
- "mongo/db/keypattern.idl"
+enums:
+ MonotonicityType:
+ description: "The monotonicity type of a shard key."
+ type: string
+ values:
+ kMonotonic: "monotonic"
+ kNotMonotonic: "not monotonic"
+ kUnknown: "unknown"
+
structs:
percentileMetrics:
description: "The percentile metrics for a set of non-negative integers."
@@ -76,6 +85,10 @@ structs:
description: "The percentile metrics for the number of documents for each distinct shard key
value."
optional: true
+ monotonicity:
+ type: MonotonicityType
+ description: "The monotonicity of the shard key values in insertion order."
+ optional: true
analyzeShardKeyResponse:
description: "The response for the 'analyzeShardKey' command."
diff --git a/src/mongo/s/analyze_shard_key_server_parameters.idl b/src/mongo/s/analyze_shard_key_server_parameters.idl
new file mode 100644
index 00000000000..22da669e452
--- /dev/null
+++ b/src/mongo/s/analyze_shard_key_server_parameters.idl
@@ -0,0 +1,47 @@
+# Copyright (C) 2022-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.
+#
+
+# Server parameters for the 'analyzeShardKey' command.
+
+global:
+ cpp_namespace: "mongo::analyze_shard_key"
+
+imports:
+ - "mongo/db/basic_types.idl"
+
+server_parameters:
+ monotonicityCorrelationCoefficientThreshold:
+ description: The correlation coefficient threshold used to determine if a shard key is
+ monotonically changing.
+ set_at: [startup, runtime]
+ cpp_vartype: AtomicWord<double>
+ cpp_varname: gMonotonicityCorrelationCoefficientThreshold
+ default: 0.7
+ validator:
+ gt: 0
+ lte: 1
diff --git a/src/mongo/s/commands/cluster_analyze_shard_key_cmd.cpp b/src/mongo/s/commands/cluster_analyze_shard_key_cmd.cpp
index 371f336516c..22acef5ea7f 100644
--- a/src/mongo/s/commands/cluster_analyze_shard_key_cmd.cpp
+++ b/src/mongo/s/commands/cluster_analyze_shard_key_cmd.cpp
@@ -44,15 +44,21 @@ namespace mongo {
namespace {
-ShardId getRandomOwningShardId(const ChunkManager& cm, const CachedDatabaseInfo& dbInfo) {
+/**
+ * Returns a new command object with shard version and/or database version appended to it based on
+ * the given routing info.
+ */
+BSONObj makeVersionedCmdObj(const ChunkManager& cm,
+ const BSONObj& unversionedCmdObj,
+ ShardId shardId) {
if (cm.isSharded()) {
- std::set<ShardId> shardIds;
- cm.getAllShardIds(&shardIds);
- auto it = shardIds.begin();
- std::advance(it, std::rand() % shardIds.size());
- return *it;
+ auto placementVersion = cm.getVersion(shardId);
+ return appendShardVersion(
+ unversionedCmdObj,
+ ShardVersion(placementVersion, CollectionIndexes(placementVersion, boost::none)));
}
- return dbInfo->getPrimary();
+ auto versionedCmdObj = appendShardVersion(unversionedCmdObj, ShardVersion::UNSHARDED());
+ return appendDbVersionIfPresent(versionedCmdObj, cm.dbVersion());
}
class AnalyzeShardKeyCmd : public TypedCommand<AnalyzeShardKeyCmd> {
@@ -68,37 +74,63 @@ public:
const auto& nss = ns();
const auto& catalogCache = Grid::get(opCtx)->catalogCache();
const auto cm = uassertStatusOK(catalogCache->getCollectionRoutingInfo(opCtx, nss));
- const auto dbInfo = uassertStatusOK(catalogCache->getDatabase(opCtx, nss.db()));
- auto shardId = getRandomOwningShardId(cm, dbInfo);
- uassert(ErrorCodes::IllegalOperation,
- "Cannot analyze a shard key for a collection on the config server",
- shardId != ShardId::kConfigServerId);
- const auto shard =
- uassertStatusOK(Grid::get(opCtx)->shardRegistry()->getShard(opCtx, shardId));
-
- auto cmdObj = CommandHelpers::filterCommandRequestForPassthrough(request().toBSON({}));
+ std::set<ShardId> candidateShardIds;
if (cm.isSharded()) {
- cmdObj = appendShardVersion(
- cmdObj,
- ShardVersion(cm.getVersion(shardId),
- CollectionIndexes(cm.getVersion(shardId), boost::none)));
+ cm.getAllShardIds(&candidateShardIds);
} else {
- cmdObj = appendShardVersion(cmdObj, ShardVersion::UNSHARDED());
- cmdObj = appendDbVersionIfPresent(cmdObj, dbInfo->getVersion());
+ candidateShardIds.insert(cm.dbPrimary());
}
- auto swResponse = shard->runCommandWithFixedRetryAttempts(
- opCtx,
- ReadPreferenceSetting{ReadPreference::SecondaryPreferred},
- NamespaceString::kAdminDb.toString(),
- cmdObj,
- Shard::RetryPolicy::kIdempotent);
- uassertStatusOK(Shard::CommandResponse::getEffectiveStatus(swResponse));
-
- auto response = AnalyzeShardKeyResponse::parse(
- IDLParserContext("clusterAnalyzeShardKey"), swResponse.getValue().response);
- return response;
+ const auto unversionedCmdObj =
+ CommandHelpers::filterCommandRequestForPassthrough(request().toBSON({}));
+ while (true) {
+ // Select a random shard.
+ invariant(!candidateShardIds.empty());
+ auto it = candidateShardIds.begin();
+ std::advance(it, std::rand() % candidateShardIds.size());
+ auto shardId = *it;
+ candidateShardIds.erase(shardId);
+
+ uassert(ErrorCodes::IllegalOperation,
+ "Cannot analyze a shard key for a collection on the config server",
+ shardId != ShardId::kConfigServerId);
+
+ // Build a versioned command for the selected shard.
+ auto versionedCmdObj = makeVersionedCmdObj(cm, unversionedCmdObj, shardId);
+
+ // Execute the command against the shard.
+ auto shard =
+ uassertStatusOK(Grid::get(opCtx)->shardRegistry()->getShard(opCtx, shardId));
+ auto swResponse = shard->runCommandWithFixedRetryAttempts(
+ opCtx,
+ ReadPreferenceSetting{ReadPreference::SecondaryPreferred},
+ NamespaceString::kAdminDb.toString(),
+ versionedCmdObj,
+ Shard::RetryPolicy::kIdempotent);
+ auto status = Shard::CommandResponse::getEffectiveStatus(swResponse);
+
+ if (status == ErrorCodes::CollectionIsEmptyLocally) {
+ uassert(ErrorCodes::InvalidOptions,
+ "Cannot analyze a shard key for an empty collection",
+ !candidateShardIds.empty());
+
+ LOGV2(6875300,
+ "Failed to analyze shard key on the selected shard since it did not "
+ "have any documents for the collection locally. Retrying on a different "
+ "shard.",
+ "nss"_attr = nss,
+ "key"_attr = request().getKey(),
+ "shardId"_attr = shardId,
+ "error"_attr = status);
+ continue;
+ }
+
+ uassertStatusOK(status);
+ auto response = AnalyzeShardKeyResponse::parse(
+ IDLParserContext("clusterAnalyzeShardKey"), swResponse.getValue().response);
+ return response;
+ }
}
private: