summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorCheahuychou Mao <mao.cheahuychou@gmail.com>2022-09-20 17:58:41 +0000
committerEvergreen Agent <no-reply@evergreen.mongodb.com>2022-09-20 19:14:39 +0000
commit17e74a7fe2bb2e9efd7ae7de6861e99a4559be65 (patch)
treeba4c2c930089612b2cf2fae9ba491c4f7bbac564
parent722d0d3ba9eb5579998b75f35613224f2c32efe5 (diff)
downloadmongo-17e74a7fe2bb2e9efd7ae7de6861e99a4559be65.tar.gz
SERVER-69367 Make analyzeShardKey command calculate the number of orphan documents
-rw-r--r--jstests/sharding/analyze_shard_key/num_orphan_docs.js120
-rw-r--r--src/mongo/db/s/analyze_shard_key_cmd_util.cpp66
-rw-r--r--src/mongo/s/analyze_shard_key_cmd.idl5
3 files changed, 191 insertions, 0 deletions
diff --git a/jstests/sharding/analyze_shard_key/num_orphan_docs.js b/jstests/sharding/analyze_shard_key/num_orphan_docs.js
new file mode 100644
index 00000000000..a2f612a864b
--- /dev/null
+++ b/jstests/sharding/analyze_shard_key/num_orphan_docs.js
@@ -0,0 +1,120 @@
+/**
+ * Tests that the analyzeShardKey command only returns the number of orphan documents if the
+ * collection is sharded.
+ *
+ * @tags: [requires_fcv_62, featureFlagAnalyzeShardKey]
+ */
+(function() {
+"use strict";
+
+load("jstests/libs/fail_point_util.js");
+
+function testAnalyzeShardKeyUnshardedCollection(conn) {
+ const dbName = "testDb";
+ const collName = "testCollUnsharded";
+ const ns = dbName + "." + collName;
+ const coll = conn.getCollection(ns);
+
+ const candidateKey = {candidateKey: 1};
+ assert.commandWorked(coll.createIndex(candidateKey));
+ assert.commandWorked(coll.insert([{candidateKey: 1}]));
+
+ const res = conn.adminCommand({analyzeShardKey: ns, key: candidateKey});
+ assert.eq(res.numDocs, 1, res);
+ assert.eq(res.cardinality, 1, res);
+ assert.eq(bsonWoCompare(res.frequency, {p99: 1, p95: 1, p90: 1, p80: 1, p50: 1}), 0, res);
+ assert(!res.hasOwnProperty("numOrphanDocs"), res);
+
+ assert(coll.drop());
+}
+
+function testAnalyzeShardKeyShardedCollection(st) {
+ const dbName = "testDb";
+ const collName = "testCollSharded";
+ const ns = dbName + "." + collName;
+ const coll = st.s.getCollection(ns);
+ const currentKey = {currentKey: 1};
+ const candidateKey = {candidateKey: 1};
+
+ assert.commandWorked(coll.createIndex(currentKey));
+ assert.commandWorked(coll.createIndex(candidateKey));
+ assert.commandWorked(coll.insert([
+ {currentKey: -10, candidateKey: -10},
+ {currentKey: -5, candidateKey: -5},
+ {currentKey: 0, candidateKey: 0},
+ {currentKey: 5, candidateKey: 5},
+ {currentKey: 10, candidateKey: 10}
+ ]));
+
+ assert.commandWorked(st.s.adminCommand({enableSharding: dbName}));
+ st.ensurePrimaryShard(dbName, st.shard0.shardName);
+ assert.commandWorked(st.s.adminCommand({shardCollection: ns, key: currentKey}));
+
+ // Analyze a shard key while no shards have orphan documents. Chunk distribution:
+ // shard0: [MinKey, 0]
+ // shard1: [0, MaxKey]
+ assert.commandWorked(st.s.adminCommand({split: ns, middle: {currentKey: 0}}));
+ assert.commandWorked(st.s.adminCommand(
+ {moveChunk: ns, find: {currentKey: 0}, to: st.shard1.shardName, _waitForDelete: true}));
+ let res = st.s.adminCommand({analyzeShardKey: ns, key: candidateKey});
+ assert.eq(res.numDocs, 5, res);
+ assert.eq(res.cardinality, 5, res);
+ assert.eq(bsonWoCompare(res.frequency, {p99: 1, p95: 1, p90: 1, p80: 1, p50: 1}), 0, res);
+ assert(res.hasOwnProperty("numOrphanDocs"), res);
+ assert.eq(res.numOrphanDocs, 0, res);
+
+ // Pause range deletion on both shards.
+ let suspendRangeDeletionFp0 = configureFailPoint(st.shard0, "suspendRangeDeletion");
+ let suspendRangeDeletionFp1 = configureFailPoint(st.shard1, "suspendRangeDeletion");
+
+ // Analyze a shard key while one shard has orphan documents. Chunk distribution:
+ // shard0: [MinKey, -5]
+ // shard1: [-5, 0], [0, MaxKey]
+ assert.commandWorked(st.s.adminCommand({split: ns, middle: {currentKey: -5}}));
+ assert.commandWorked(
+ st.s.adminCommand({moveChunk: ns, find: {currentKey: -5}, to: st.shard1.shardName}));
+ res = st.s.adminCommand({analyzeShardKey: ns, key: candidateKey});
+ assert.eq(res.numDocs, 6, res);
+ assert.eq(res.cardinality, 5, res);
+ assert.eq(bsonWoCompare(res.frequency, {p99: 2, p95: 2, p90: 2, p80: 1, p50: 1}), 0, res);
+ assert(res.hasOwnProperty("numOrphanDocs"), res);
+ assert.eq(res.numOrphanDocs, 1, res);
+
+ // Analyze a shard key while two shards have orphan documents. Chunk distribution:
+ // shard0: [MinKey, -5], [5, MaxKey]
+ // shard1: [-5, 0], [0, 5]
+ assert.commandWorked(st.s.adminCommand({split: ns, middle: {currentKey: 5}}));
+ assert.commandWorked(
+ st.s.adminCommand({moveChunk: ns, find: {currentKey: 5}, to: st.shard0.shardName}));
+ res = st.s.adminCommand({analyzeShardKey: ns, key: candidateKey});
+ assert.eq(res.numDocs, 8, res);
+ assert.eq(res.cardinality, 5, res);
+ assert.eq(bsonWoCompare(res.frequency, {p99: 2, p95: 2, p90: 2, p80: 2, p50: 2}), 0, res);
+ assert(res.hasOwnProperty("numOrphanDocs"), res);
+ assert.eq(res.numOrphanDocs, 3, res);
+
+ suspendRangeDeletionFp0.off();
+ suspendRangeDeletionFp1.off();
+ assert(coll.drop());
+}
+
+{
+ const st = new ShardingTest({shards: 2, rs: {nodes: 2}});
+
+ testAnalyzeShardKeyUnshardedCollection(st.s);
+ testAnalyzeShardKeyShardedCollection(st);
+
+ st.stop();
+}
+
+{
+ const rst = new ReplSetTest({nodes: 2});
+ rst.startSet();
+ rst.initiate();
+ const primary = rst.getPrimary();
+
+ testAnalyzeShardKeyUnshardedCollection(primary);
+
+ rst.stopSet();
+}
+})();
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 766e78cb228..62b708d4851 100644
--- a/src/mongo/db/s/analyze_shard_key_cmd_util.cpp
+++ b/src/mongo/db/s/analyze_shard_key_cmd_util.cpp
@@ -37,10 +37,12 @@
#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/range_deletion_task_gen.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/cluster_commands_helpers.h"
#include "mongo/s/grid.h"
#include "mongo/s/query/cluster_aggregate.h"
#include "mongo/s/service_entry_point_mongos.h"
@@ -59,6 +61,7 @@ constexpr StringData kNumDocsFieldName = "numDocs"_sd;
constexpr StringData kCardinalityFieldName = "cardinality"_sd;
constexpr StringData kFrequencyFieldName = "frequency"_sd;
constexpr StringData kIndexFieldName = "index"_sd;
+constexpr StringData kNumOrphanDocsFieldName = "numOrphanDocs"_sd;
const std::vector<double> kPercentiles{0.99, 0.95, 0.9, 0.8, 0.5};
@@ -399,6 +402,67 @@ MonotonicityTypeEnum calculateMonotonicity(OperationContext* opCtx,
: MonotonicityTypeEnum::kNotMonotonic;
}
+/**
+ * Returns the number of orphan documents. If the collection is unsharded, returns none.
+ */
+boost::optional<int64_t> getNumOrphanDocuments(OperationContext* opCtx,
+ const NamespaceString& nss) {
+ if (serverGlobalParams.clusterRole != ClusterRole::ShardServer) {
+ return boost::none;
+ }
+
+ auto cm =
+ uassertStatusOK(Grid::get(opCtx)->catalogCache()->getCollectionRoutingInfo(opCtx, nss));
+
+ if (!cm.isSharded()) {
+ return boost::none;
+ }
+
+ std::vector<BSONObj> pipeline;
+ pipeline.push_back(
+ BSON("$match" << BSON(RangeDeletionTask::kCollectionUuidFieldName << cm.getUUID())));
+ pipeline.push_back(
+ BSON("$group" << BSON("_id" << BSONNULL << kNumOrphanDocsFieldName
+ << BSON("$sum"
+ << "$" + RangeDeletionTask::kNumOrphanDocsFieldName))));
+ AggregateCommandRequest aggRequest(NamespaceString::kRangeDeletionNamespace, pipeline);
+ auto cmdObj = applyReadWriteConcern(
+ opCtx, true /* appendRC */, true /* appendWC */, aggRequest.toBSON({}));
+
+ std::set<ShardId> shardIds;
+ cm.getAllShardIds(&shardIds);
+ std::vector<AsyncRequestsSender::Request> requests;
+ for (const auto& shardId : shardIds) {
+ requests.emplace_back(shardId, cmdObj);
+ }
+ auto shardResults = gatherResponses(opCtx,
+ NamespaceString::kConfigDb,
+ ReadPreferenceSetting(ReadPreference::SecondaryPreferred),
+ Shard::RetryPolicy::kIdempotent,
+ requests);
+
+ long long numOrphanDocs = 0;
+ for (const auto& shardResult : shardResults) {
+ const auto shardResponse = uassertStatusOK(std::move(shardResult.swResponse));
+ uassertStatusOK(shardResponse.status);
+ const auto cmdResult = shardResponse.data;
+ uassertStatusOK(getStatusFromCommandResult(cmdResult));
+
+ auto firstBatch = cmdResult.firstElement()["firstBatch"].Obj();
+ BSONObjIterator it(firstBatch);
+
+ if (!it.more()) {
+ continue;
+ }
+
+ auto doc = it.next().Obj();
+ invariant(!it.more());
+ numOrphanDocs += doc.getField(kNumOrphanDocsFieldName).exactNumberLong();
+ }
+
+ return numOrphanDocs;
+}
+
} // namespace
KeyCharacteristicsMetrics calculateKeyCharacteristicsMetrics(OperationContext* opCtx,
@@ -440,6 +504,8 @@ KeyCharacteristicsMetrics calculateKeyCharacteristicsMetrics(OperationContext* o
metrics.setCardinality(bundle.cardinality);
metrics.setFrequency(bundle.frequency);
+ metrics.setNumOrphanDocs(getNumOrphanDocuments(opCtx, nss));
+
return metrics;
}
diff --git a/src/mongo/s/analyze_shard_key_cmd.idl b/src/mongo/s/analyze_shard_key_cmd.idl
index 650e00d6738..fa0998f609d 100644
--- a/src/mongo/s/analyze_shard_key_cmd.idl
+++ b/src/mongo/s/analyze_shard_key_cmd.idl
@@ -89,6 +89,11 @@ structs:
type: MonotonicityType
description: "The monotonicity of the shard key values in insertion order."
optional: true
+ numOrphanDocs:
+ type: long
+ description: "The number of the orphan documents in the collection."
+ validator: { gte: 0 }
+ optional: true
analyzeShardKeyResponse:
description: "The response for the 'analyzeShardKey' command."