You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@kudu.apache.org by al...@apache.org on 2026/09/04 02:05:06 UTC
(kudu) branch master updated: [metrics] Support merge_rules aggregation in /metrics_prometheus
This is an automated email from the ASF dual-hosted git repository.
asf-gitbox-commits pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/kudu.git
The following commit(s) were added to refs/heads/master by this push:
new 4d7e35e58 [metrics] Support merge_rules aggregation in /metrics_prometheus
4d7e35e58 is described below
commit 4d7e35e58cc081b5ecc336a047709af97ac45ccb
Author: Yan-Daojiang <ya...@163.com>
AuthorDate: Tue Sep 1 11:22:52 2026 +0800
[metrics] Support merge_rules aggregation in /metrics_prometheus
The /metrics_prometheus endpoint now supports the same entity merging
that the /metrics JSON endpoint has offered for years, so that per-tablet
metrics can be aggregated into per-table (or any user-defined) entities
before being exported. On clusters with a large number of tablets this
drastically cuts down the number of exported Prometheus time series,
which is the dominant source of cardinality pressure when scraping Kudu
natively.
Merging is requested either per-request via the 'merge_rules' query
parameter (identical syntax to the JSON endpoint, e.g.
?merge_rules=tablet|table|table_name), or server-wide via the new
--metrics_prometheus_default_merge_rules flag, which is applied whenever
a request does not carry its own 'merge_rules'. A request parameter takes
precedence over the flag.
Change-Id: I76a365de3b328f2beefd460626cc0c896537e713
Reviewed-on: http://gerrit.cloudera.org:8080/24779
Tested-by: Alexey Serbin <al...@apache.org>
Reviewed-by: Alexey Serbin <al...@apache.org>
---
src/kudu/server/default_path_handlers.cc | 25 +--
src/kudu/util/metrics-test.cc | 305 +++++++++++++++++++++++++++++++
src/kudu/util/metrics.cc | 126 ++++++++++++-
src/kudu/util/metrics.h | 38 ++++
src/kudu/util/prometheus_writer.cc | 9 +
src/kudu/util/prometheus_writer.h | 10 +
6 files changed, 497 insertions(+), 16 deletions(-)
diff --git a/src/kudu/server/default_path_handlers.cc b/src/kudu/server/default_path_handlers.cc
index a886a5504..2f9315d90 100644
--- a/src/kudu/server/default_path_handlers.cc
+++ b/src/kudu/server/default_path_handlers.cc
@@ -120,6 +120,10 @@ DECLARE_string(webserver_certificate_file);
namespace kudu {
namespace {
+// Query parameter selecting the entity merge rules for the '/metrics' and
+// '/metrics_prometheus' endpoints.
+constexpr const char* const kMergeRulesParam = "merge_rules";
+
// Html/Text formatting tags
struct Tags {
string pre_tag, end_pre_tag, line_break, header, end_header;
@@ -517,17 +521,7 @@ static void WriteMetricsAsJson(const MetricRegistry* const metrics,
return;
}
- vector<string> merge_rules = ParseArray(req.parsed_args, "merge_rules");
- for (const auto& merge_rule : merge_rules) {
- vector<string> values;
- SplitStringUsing(merge_rule, "|", &values);
- if (values.size() == 3) {
- // Index 0: entity type needed to be merged.
- // Index 1: 'merge_to' field of MergeAttributes.
- // Index 2: 'attribute_to_merge_by' field of MergeAttributes.
- EmplaceIfNotPresent(&opts.merge_rules, values[0], MergeAttributes(values[1], values[2]));
- }
- }
+ ParseMergeRules(ParseArray(req.parsed_args, kMergeRulesParam), &opts.merge_rules);
JsonWriter::Mode json_mode = ParseBool(req.parsed_args, "compact") ?
JsonWriter::COMPACT : JsonWriter::PRETTY;
@@ -545,7 +539,14 @@ static void WriteMetricsAsPrometheus(const MetricRegistry* const metrics,
if (!ParseMetricFilters(req, resp, &opts.filters)) {
return;
}
- if (FLAGS_metrics_prometheus_use_entity_labels) {
+
+ // A 'merge_rules' query parameter takes precedence over the server-side
+ // default configured via --metrics_prometheus_default_merge_rules.
+ GetPrometheusMergeRules(ParseArray(req.parsed_args, kMergeRulesParam), &opts.merge_rules);
+
+ // The hostname label is emitted either in the label-based non-merged format,
+ // or whenever merging is active (merged output is always label-based).
+ if (FLAGS_metrics_prometheus_use_entity_labels || !opts.merge_rules.empty()) {
opts.hostname = hostname;
}
diff --git a/src/kudu/util/metrics-test.cc b/src/kudu/util/metrics-test.cc
index 057957217..a7afeeefb 100644
--- a/src/kudu/util/metrics-test.cc
+++ b/src/kudu/util/metrics-test.cc
@@ -58,6 +58,7 @@ using std::vector;
DECLARE_int32(metrics_retirement_age_ms);
DECLARE_bool(metrics_prometheus_use_entity_labels);
DECLARE_bool(metrics_prometheus_export_hostname);
+DECLARE_string(metrics_prometheus_default_merge_rules);
namespace kudu {
@@ -267,6 +268,271 @@ TEST_F(MetricsTest, TableAndTabletLegacyPrometheusTest) {
);
}
+// Merge several tablet entities into table-level entities in the Prometheus
+// output, mimicking the collector's 'merge_rules=tablet|table|table_name'.
+// Counter values are summed per table and the per-tablet time series collapse
+// into a single per-table series, which is the key cardinality win.
+TEST_F(MetricsTest, MergedTabletPrometheusTest) {
+ MetricRegistry registry;
+
+ auto tablet1 = METRIC_ENTITY_tablet.Instantiate(®istry, "tablet-1");
+ tablet1->SetAttribute("table_name", "table_a");
+ METRIC_tablet_test_counter.Instantiate(tablet1)->IncrementBy(11);
+
+ auto tablet2 = METRIC_ENTITY_tablet.Instantiate(®istry, "tablet-2");
+ tablet2->SetAttribute("table_name", "table_a");
+ METRIC_tablet_test_counter.Instantiate(tablet2)->IncrementBy(4);
+
+ auto tablet3 = METRIC_ENTITY_tablet.Instantiate(®istry, "tablet-3");
+ tablet3->SetAttribute("table_name", "table_b");
+ METRIC_tablet_test_counter.Instantiate(tablet3)->IncrementBy(100);
+
+ MetricPrometheusOptions opts;
+ opts.merge_rules.emplace("tablet", MergeAttributes("table", "table_name"));
+
+ ostringstream output;
+ PrometheusWriter writer(&output);
+ ASSERT_OK(registry.WriteAsPrometheus(&writer, opts));
+
+ const auto& out = output.str();
+ // HELP/TYPE is emitted exactly once even though several entities are merged.
+ ASSERT_EQ(1, CountSubstring(out, "# HELP kudu_tablet_test_counter "));
+ ASSERT_EQ(1, CountSubstring(out, "# TYPE kudu_tablet_test_counter "));
+ // table_a aggregates the two tablets: 11 + 4 = 15.
+ ASSERT_STR_CONTAINS(out,
+ "kudu_tablet_test_counter{type=\"table\",id=\"table_a\",unit_type=\"bytes\"} 15\n");
+ // table_b has a single tablet: 100.
+ ASSERT_STR_CONTAINS(out,
+ "kudu_tablet_test_counter{type=\"table\",id=\"table_b\",unit_type=\"bytes\"} 100\n");
+ // The individual tablet IDs must not leak into the merged output.
+ ASSERT_STR_NOT_CONTAINS(out, "id=\"tablet-1\"");
+ ASSERT_STR_NOT_CONTAINS(out, "id=\"tablet-2\"");
+ ASSERT_STR_NOT_CONTAINS(out, "id=\"tablet-3\"");
+ // Only two data lines (one per table) are exported for this metric.
+ ASSERT_EQ(2, CountSubstring(out, "kudu_tablet_test_counter{"));
+}
+
+// The hostname label is attached to merged output when hostname export is on,
+// and omitted otherwise. Merged output is label-based regardless of
+// --metrics_prometheus_use_entity_labels.
+TEST_F(MetricsTest, MergedPrometheusHostnameLabelTest) {
+ google::FlagSaver saver;
+
+ MetricRegistry registry;
+ auto tablet = METRIC_ENTITY_tablet.Instantiate(®istry, "tablet-1");
+ tablet->SetAttribute("table_name", "table_a");
+ METRIC_tablet_test_counter.Instantiate(tablet)->IncrementBy(7);
+
+ MetricPrometheusOptions opts;
+ opts.merge_rules.emplace("tablet", MergeAttributes("table", "table_name"));
+ opts.hostname = "host-a";
+
+ FLAGS_metrics_prometheus_export_hostname = true;
+ {
+ ostringstream output;
+ PrometheusWriter writer(&output);
+ ASSERT_OK(registry.WriteAsPrometheus(&writer, opts));
+ ASSERT_STR_CONTAINS(output.str(),
+ "kudu_tablet_test_counter{type=\"table\",id=\"table_a\","
+ "hostname=\"host-a\",unit_type=\"bytes\"} 7\n");
+ }
+
+ FLAGS_metrics_prometheus_export_hostname = false;
+ {
+ ostringstream output;
+ PrometheusWriter writer(&output);
+ ASSERT_OK(registry.WriteAsPrometheus(&writer, opts));
+ ASSERT_STR_CONTAINS(output.str(),
+ "kudu_tablet_test_counter{type=\"table\",id=\"table_a\",unit_type=\"bytes\"} 7\n");
+ ASSERT_STR_NOT_CONTAINS(output.str(), "hostname=");
+ }
+}
+
+// An entity that lacks the merge-by attribute is skipped (not merged and not
+// exported), consistent with the JSON endpoint, and must not crash.
+TEST_F(MetricsTest, MergedPrometheusMissingAttributeTest) {
+ MetricRegistry registry;
+
+ auto tablet1 = METRIC_ENTITY_tablet.Instantiate(®istry, "tablet-1");
+ tablet1->SetAttribute("table_name", "table_a");
+ METRIC_tablet_test_counter.Instantiate(tablet1)->IncrementBy(9);
+
+ // No 'table_name' attribute set on this tablet.
+ auto tablet2 = METRIC_ENTITY_tablet.Instantiate(®istry, "tablet-2");
+ METRIC_tablet_test_counter.Instantiate(tablet2)->IncrementBy(123);
+
+ MetricPrometheusOptions opts;
+ opts.merge_rules.emplace("tablet", MergeAttributes("table", "table_name"));
+
+ ostringstream output;
+ PrometheusWriter writer(&output);
+ ASSERT_OK(registry.WriteAsPrometheus(&writer, opts));
+
+ const auto& out = output.str();
+ ASSERT_STR_CONTAINS(out,
+ "kudu_tablet_test_counter{type=\"table\",id=\"table_a\",unit_type=\"bytes\"} 9\n");
+ // The value of the tablet without a 'table_name' attribute is dropped.
+ ASSERT_STR_NOT_CONTAINS(out, "123");
+ ASSERT_EQ(1, CountSubstring(out, "kudu_tablet_test_counter{"));
+}
+
+// An entity whose type is not targeted by any merge rule (e.g. a 'table'
+// entity on the master when only 'tablet' is merged) must be exported as-is,
+// preserving its native attribute labels such as table_name -- not collapsed
+// into the bare type/id label set used for merged entities.
+TEST_F(MetricsTest, MergedPrometheusPassThroughKeepsAttributesTest) {
+ google::FlagSaver saver;
+ FLAGS_metrics_prometheus_use_entity_labels = true;
+
+ MetricRegistry registry;
+
+ // A 'table' entity as present on the master, carrying a table_name attribute.
+ auto table = METRIC_ENTITY_table.Instantiate(®istry, "table-id-1");
+ table->SetAttribute("table_name", "my_table");
+ METRIC_table_test_counter.Instantiate(table)->IncrementBy(42);
+
+ // A 'tablet' entity which IS targeted by the rule and gets merged.
+ auto tablet = METRIC_ENTITY_tablet.Instantiate(®istry, "tablet-1");
+ tablet->SetAttribute("table_name", "my_table");
+ METRIC_tablet_test_counter.Instantiate(tablet)->IncrementBy(7);
+
+ MetricPrometheusOptions opts;
+ opts.merge_rules.emplace("tablet", MergeAttributes("table", "table_name"));
+
+ ostringstream output;
+ PrometheusWriter writer(&output);
+ ASSERT_OK(registry.WriteAsPrometheus(&writer, opts));
+
+ const auto& out = output.str();
+ // The pass-through 'table' entity keeps its full native label set (including
+ // table_name), even though a 'tablet' merge rule was supplied.
+ ASSERT_STR_CONTAINS(out,
+ "kudu_table_test_counter{type=\"table\",id=\"table-id-1\","
+ "table_name=\"my_table\",unit_type=\"bytes\"} 42\n");
+ // The targeted 'tablet' entity is still merged into a bare type/id series.
+ ASSERT_STR_CONTAINS(out,
+ "kudu_tablet_test_counter{type=\"table\",id=\"my_table\",unit_type=\"bytes\"} 7\n");
+ // The raw tablet ID must not leak.
+ ASSERT_STR_NOT_CONTAINS(out, "id=\"tablet-1\"");
+}
+
+// Aggregate tablet entities by their 'partition' attribute, as one would do for
+// a hash-partitioned table where each tablet carries a partition description.
+// Tablets sharing a partition value collapse into a single series, and the
+// (space/paren-containing) partition string is used verbatim as the 'id' label.
+TEST_F(MetricsTest, MergedPrometheusByPartitionAttributeTest) {
+ MetricRegistry registry;
+
+ auto tablet1 = METRIC_ENTITY_tablet.Instantiate(®istry, "tablet-1");
+ tablet1->SetAttribute("partition", "HASH (col_x) PARTITION 3");
+ METRIC_tablet_test_counter.Instantiate(tablet1)->IncrementBy(8);
+
+ auto tablet2 = METRIC_ENTITY_tablet.Instantiate(®istry, "tablet-2");
+ tablet2->SetAttribute("partition", "HASH (col_x) PARTITION 3");
+ METRIC_tablet_test_counter.Instantiate(tablet2)->IncrementBy(2);
+
+ auto tablet3 = METRIC_ENTITY_tablet.Instantiate(®istry, "tablet-3");
+ tablet3->SetAttribute("partition", "HASH (col_x) PARTITION 5");
+ METRIC_tablet_test_counter.Instantiate(tablet3)->IncrementBy(1);
+
+ MetricPrometheusOptions opts;
+ opts.merge_rules.emplace("tablet", MergeAttributes("partition", "partition"));
+
+ ostringstream output;
+ PrometheusWriter writer(&output);
+ ASSERT_OK(registry.WriteAsPrometheus(&writer, opts));
+
+ const auto& out = output.str();
+ // The two tablets in 'PARTITION 3' aggregate to 10; the odd one is on its own.
+ ASSERT_STR_CONTAINS(out,
+ "kudu_tablet_test_counter{type=\"partition\","
+ "id=\"HASH (col_x) PARTITION 3\",unit_type=\"bytes\"} 10\n");
+ ASSERT_STR_CONTAINS(out,
+ "kudu_tablet_test_counter{type=\"partition\","
+ "id=\"HASH (col_x) PARTITION 5\",unit_type=\"bytes\"} 1\n");
+ ASSERT_STR_NOT_CONTAINS(out, "id=\"tablet-1\"");
+ ASSERT_EQ(2, CountSubstring(out, "kudu_tablet_test_counter{"));
+}
+
+// The server-wide --metrics_prometheus_default_merge_rules is applied when a
+// request carries no 'merge_rules' of its own.
+TEST_F(MetricsTest, PrometheusDefaultMergeRulesFromFlagTest) {
+ google::FlagSaver saver;
+ FLAGS_metrics_prometheus_default_merge_rules = "tablet|table|table_name";
+
+ MetricRegistry registry;
+ auto tablet1 = METRIC_ENTITY_tablet.Instantiate(®istry, "tablet-1");
+ tablet1->SetAttribute("table_name", "table_a");
+ METRIC_tablet_test_counter.Instantiate(tablet1)->IncrementBy(3);
+ auto tablet2 = METRIC_ENTITY_tablet.Instantiate(®istry, "tablet-2");
+ tablet2->SetAttribute("table_name", "table_a");
+ METRIC_tablet_test_counter.Instantiate(tablet2)->IncrementBy(4);
+
+ // No per-request rules: the flag default drives the aggregation.
+ MetricPrometheusOptions opts;
+ GetPrometheusMergeRules(/*request_merge_rules=*/{}, &opts.merge_rules);
+
+ ostringstream output;
+ PrometheusWriter writer(&output);
+ ASSERT_OK(registry.WriteAsPrometheus(&writer, opts));
+
+ const auto& out = output.str();
+ ASSERT_STR_CONTAINS(out,
+ "kudu_tablet_test_counter{type=\"table\",id=\"table_a\",unit_type=\"bytes\"} 7\n");
+ ASSERT_STR_NOT_CONTAINS(out, "id=\"tablet-1\"");
+}
+
+// Rules supplied with the request take precedence over the flag default.
+TEST_F(MetricsTest, PrometheusRequestMergeRulesOverrideFlagTest) {
+ google::FlagSaver saver;
+ // The flag would merge tablets into 'table' entities by 'table_name'...
+ FLAGS_metrics_prometheus_default_merge_rules = "tablet|table|table_name";
+
+ MetricRegistry registry;
+ auto tablet1 = METRIC_ENTITY_tablet.Instantiate(®istry, "tablet-1");
+ tablet1->SetAttribute("table_name", "table_a");
+ tablet1->SetAttribute("partition", "p0");
+ METRIC_tablet_test_counter.Instantiate(tablet1)->IncrementBy(5);
+ auto tablet2 = METRIC_ENTITY_tablet.Instantiate(®istry, "tablet-2");
+ tablet2->SetAttribute("table_name", "table_a");
+ tablet2->SetAttribute("partition", "p0");
+ METRIC_tablet_test_counter.Instantiate(tablet2)->IncrementBy(6);
+
+ // ...but the request merges into 'partition' entities by 'partition' instead.
+ MetricPrometheusOptions opts;
+ GetPrometheusMergeRules(/*request_merge_rules=*/{"tablet|partition|partition"},
+ &opts.merge_rules);
+
+ ostringstream output;
+ PrometheusWriter writer(&output);
+ ASSERT_OK(registry.WriteAsPrometheus(&writer, opts));
+
+ const auto& out = output.str();
+ ASSERT_STR_CONTAINS(out,
+ "kudu_tablet_test_counter{type=\"partition\",id=\"p0\",unit_type=\"bytes\"} 11\n");
+ // The flag's 'table' merge target must not appear.
+ ASSERT_STR_NOT_CONTAINS(out, "type=\"table\"");
+}
+
+// A malformed --metrics_prometheus_default_merge_rules yields no rules, so no
+// aggregation is attempted; a well-formed rule sharing the value still applies.
+TEST_F(MetricsTest, PrometheusMalformedDefaultMergeRulesFlagTest) {
+ google::FlagSaver saver;
+
+ // Malformed value (only two '|'-separated parts): no rules are resolved.
+ FLAGS_metrics_prometheus_default_merge_rules = "tablet|table";
+ MetricMergeRules rules;
+ GetPrometheusMergeRules(/*request_merge_rules=*/{}, &rules);
+ ASSERT_TRUE(rules.empty());
+
+ // A malformed rule alongside a valid one: only the valid rule survives.
+ FLAGS_metrics_prometheus_default_merge_rules = "garbage,tablet|table|table_name";
+ rules.clear();
+ GetPrometheusMergeRules(/*request_merge_rules=*/{}, &rules);
+ ASSERT_EQ(1, rules.size());
+ ASSERT_TRUE(ContainsKey(rules, "tablet"));
+}
+
TEST_F(MetricsTest, CounterPrometheusTest) {
scoped_refptr<Counter> requests(new Counter(&METRIC_test_counter));
@@ -925,6 +1191,45 @@ TEST_F(MetricsTest, HistogramLegacyPrometheusTest) {
ASSERT_EQ(kExpectedOutput, output.str());
}
+// Histograms are merged by combining the underlying HdrHistogram data, so the
+// aggregated _sum and _count are exact (unlike aggregating pre-computed
+// quantiles on the Prometheus server side).
+TEST_F(MetricsTest, MergedHistogramPrometheusTest) {
+ // entity_ and entity_same_attr_ share attr_for_merge="same_attr";
+ // entity_diff_attr_ has attr_for_merge="diff_attr".
+ scoped_refptr<Histogram> hist1 = METRIC_test_hist.Instantiate(entity_);
+ hist1->IncrementBy(10, 2); // sum 20, count 2
+ scoped_refptr<Histogram> hist2 = METRIC_test_hist.Instantiate(entity_same_attr_);
+ hist2->IncrementBy(30, 3); // sum 90, count 3
+ scoped_refptr<Histogram> hist3 = METRIC_test_hist.Instantiate(entity_diff_attr_);
+ hist3->IncrementBy(5, 4); // sum 20, count 4
+
+ MetricPrometheusOptions opts;
+ opts.merge_rules.emplace("test_entity",
+ MergeAttributes("merged_entity", "attr_for_merge"));
+
+ ostringstream output;
+ PrometheusWriter writer(&output);
+ ASSERT_OK(registry_.WriteAsPrometheus(&writer, opts));
+
+ const auto& out = output.str();
+ ASSERT_EQ(1, CountSubstring(out, "# TYPE kudu_test_hist summary\n"));
+ // same_attr aggregates entity_ and entity_same_attr_: sum 110, count 5.
+ ASSERT_STR_CONTAINS(out,
+ "kudu_test_hist_sum{type=\"merged_entity\",id=\"same_attr\","
+ "unit_type=\"milliseconds\"} 110\n");
+ ASSERT_STR_CONTAINS(out,
+ "kudu_test_hist_count{type=\"merged_entity\",id=\"same_attr\","
+ "unit_type=\"units\"} 5\n");
+ // diff_attr has a single entity: sum 20, count 4.
+ ASSERT_STR_CONTAINS(out,
+ "kudu_test_hist_sum{type=\"merged_entity\",id=\"diff_attr\","
+ "unit_type=\"milliseconds\"} 20\n");
+ ASSERT_STR_CONTAINS(out,
+ "kudu_test_hist_count{type=\"merged_entity\",id=\"diff_attr\","
+ "unit_type=\"units\"} 4\n");
+}
+
TEST_F(MetricsTest, JsonPrintTest) {
scoped_refptr<Counter> test_counter = METRIC_test_counter.Instantiate(entity_);
test_counter->Increment();
diff --git a/src/kudu/util/metrics.cc b/src/kudu/util/metrics.cc
index a03d0df4b..d67accfaa 100644
--- a/src/kudu/util/metrics.cc
+++ b/src/kudu/util/metrics.cc
@@ -26,6 +26,7 @@
#include "kudu/gutil/map-util.h"
#include "kudu/gutil/singleton.h"
#include "kudu/gutil/strings/join.h"
+#include "kudu/gutil/strings/split.h"
#include "kudu/gutil/strings/substitute.h"
#include "kudu/util/flag_tags.h"
#include "kudu/util/hdr_histogram.h"
@@ -52,6 +53,43 @@ DEFINE_bool(metrics_prometheus_export_hostname, true,
"e.g. when using Prometheus relabel_configs for custom labeling.");
TAG_FLAG(metrics_prometheus_export_hostname, runtime);
+DEFINE_string(metrics_prometheus_default_merge_rules, "",
+ "The default entity merge rules applied by the '/metrics_prometheus' "
+ "endpoint when the request does not carry a 'merge_rules' query "
+ "parameter. The value is a comma-separated list of rules, each in the "
+ "form '<entity_type>|<merge_to>|<attribute_to_merge_by>'. For example, "
+ "'tablet|table|table_name' merges all tablet entities into table-level "
+ "entities keyed by their 'table_name' attribute, which drastically "
+ "reduces the number of exported time series on clusters with many "
+ "tablets. Empty by default, i.e. no merging is performed unless a "
+ "request asks for it.");
+TAG_FLAG(metrics_prometheus_default_merge_rules, advanced);
+TAG_FLAG(metrics_prometheus_default_merge_rules, runtime);
+TAG_FLAG(metrics_prometheus_default_merge_rules, evolving);
+DEFINE_validator(metrics_prometheus_default_merge_rules,
+ [](const char* flag_name, const std::string& value) {
+ // An empty value disables default merging and is always valid. Otherwise
+ // warn about (but tolerate) malformed rules so that a typo surfaces in the
+ // logs instead of silently disabling aggregation. Well-formed rules in the
+ // same value are still applied; see GetPrometheusMergeRules().
+ if (value.empty()) {
+ return true;
+ }
+ std::vector<std::string> raw_merge_rules;
+ SplitStringUsing(value, ",", &raw_merge_rules);
+ for (const auto& raw_merge_rule : raw_merge_rules) {
+ std::vector<std::string> parts;
+ SplitStringUsing(raw_merge_rule, "|", &parts);
+ if (parts.size() != 3) {
+ LOG(WARNING) << strings::Substitute(
+ "ignoring malformed rule '$0' in --$1: expected the form "
+ "'<entity_type>|<merge_to>|<attribute_to_merge_by>'",
+ raw_merge_rule, flag_name);
+ }
+ }
+ return true;
+});
+
// Process/server-wide metrics should go into the 'server' entity.
// More complex applications will define other entities.
METRIC_DEFINE_entity(server);
@@ -115,6 +153,61 @@ void WriteToJson(JsonWriter* writer,
}
}
+void WriteToPrometheus(PrometheusWriter* writer,
+ const MergedEntityMetrics& merged_entity_metrics,
+ const MetricPrometheusOptions& opts) {
+ // The hostname label, if any, is identical for every merged entity, so
+ // compute it once up front rather than per entity.
+ string hostname_label;
+ if (FLAGS_metrics_prometheus_export_hostname && !opts.hostname.empty()) {
+ hostname_label = ",hostname=\"" + EscapePrometheusLabelValue(opts.hostname) + "\"";
+ }
+ for (const auto& entity_metrics : merged_entity_metrics) {
+ if (entity_metrics.second.empty()) {
+ continue;
+ }
+ // A merged entity is always exported in the label-based format: the
+ // merged-to type and merged-by attribute value become 'type' and 'id'
+ // labels, so that the entity ID is not baked into the metric name.
+ string labels = BuildMergedPrometheusLabels(entity_metrics.first.type_,
+ entity_metrics.first.id_);
+ labels += hostname_label;
+ for (const auto& [prototype, metric] : entity_metrics.second) {
+ WARN_NOT_OK(metric->WriteAsPrometheus(writer, "kudu_", labels),
+ Substitute("unable to write '$0' ($1) in Prometheus format",
+ prototype->name(), prototype->description()));
+ }
+ }
+}
+
+void ParseMergeRules(const vector<string>& raw_merge_rules,
+ MetricMergeRules* merge_rules) {
+ for (const auto& raw_merge_rule : raw_merge_rules) {
+ vector<string> values;
+ SplitStringUsing(raw_merge_rule, "|", &values);
+ if (values.size() == 3) {
+ // Index 0: entity type to be merged.
+ // Index 1: 'merge_to' field of MergeAttributes.
+ // Index 2: 'attribute_to_merge_by' field of MergeAttributes.
+ EmplaceIfNotPresent(merge_rules, values[0], MergeAttributes(values[1], values[2]));
+ }
+ }
+}
+
+void GetPrometheusMergeRules(const vector<string>& request_merge_rules,
+ MetricMergeRules* merge_rules) {
+ // A request's own 'merge_rules' take precedence over the server-side default.
+ if (!request_merge_rules.empty()) {
+ ParseMergeRules(request_merge_rules, merge_rules);
+ return;
+ }
+ if (!FLAGS_metrics_prometheus_default_merge_rules.empty()) {
+ vector<string> default_merge_rules;
+ SplitStringUsing(FLAGS_metrics_prometheus_default_merge_rules, ",", &default_merge_rules);
+ ParseMergeRules(default_merge_rules, merge_rules);
+ }
+}
+
//
// MetricUnit
//
@@ -613,9 +706,29 @@ Status MetricRegistry::WriteAsPrometheus(
std::lock_guard l(lock_);
entities = entities_;
}
- for (const auto& e : entities) {
- WARN_NOT_OK(e.second->WriteAsPrometheus(writer, opts),
- Substitute("Failed to write entity $0 as Prometheus", e.second->id()));
+ if (opts.merge_rules.empty()) {
+ for (const auto& e : entities) {
+ WARN_NOT_OK(e.second->WriteAsPrometheus(writer, opts),
+ Substitute("Failed to write entity $0 as Prometheus", e.second->id()));
+ }
+ } else {
+ MergedEntityMetrics collections;
+ for (const auto& e : entities) {
+ // A merge rule only targets entities whose prototype name is one of its
+ // keys. Entities that are not targeted by any rule (e.g. 'table' or
+ // 'server' entities when only 'tablet' is being merged) are exported
+ // as-is via the regular per-entity path, which preserves their native
+ // attribute labels such as table_name/table_id. Only targeted entities
+ // are aggregated and exported with 'type'/'id' labels.
+ if (!ContainsKey(opts.merge_rules, e.second->prototype_->name())) {
+ WARN_NOT_OK(e.second->WriteAsPrometheus(writer, opts),
+ Substitute("Failed to write entity $0 as Prometheus", e.second->id()));
+ continue;
+ }
+ WARN_NOT_OK(e.second->CollectTo(&collections, opts.filters, opts.merge_rules),
+ Substitute("Failed to collect entity $0", e.second->id()));
+ }
+ WriteToPrometheus(writer, collections, opts);
}
entities.clear(); // necessary to deref metrics we just dumped before doing retirement scan.
@@ -1212,7 +1325,12 @@ Status Histogram::WriteAsPrometheus(PrometheusWriter* writer,
// the output.
const HdrHistogram h(*histogram_);
string out;
- if (FLAGS_metrics_prometheus_use_entity_labels) {
+ // Use the label-based format when it is enabled globally, or whenever a
+ // non-empty label set is supplied (e.g. for merge_rules-aggregated output,
+ // which is always label-based regardless of the global flag). For all
+ // existing non-merged callers labels are empty whenever the flag is off, so
+ // this preserves the legacy behaviour in those cases.
+ if (FLAGS_metrics_prometheus_use_entity_labels || !labels.empty()) {
// New format: labels injected, no space after comma, _sum/_count carry unit_type.
static constexpr const char* const kFmt =
"$0$1{$2unit_type=\"$3\",quantile=\"$4\"} $5\n";
diff --git a/src/kudu/util/metrics.h b/src/kudu/util/metrics.h
index 6901ec50a..cb2c80137 100644
--- a/src/kudu/util/metrics.h
+++ b/src/kudu/util/metrics.h
@@ -465,6 +465,23 @@ struct MergeAttributes {
// Entity prototype name -> MergeAttributes.
typedef std::unordered_map<std::string, MergeAttributes> MetricMergeRules;
+
+// Parse raw merge rules (each of the form
+// "<entity_type>|<merge_to>|<attribute_to_merge_by>") into 'merge_rules',
+// ignoring malformed rules (i.e. not exactly three '|'-separated parts). This
+// mirrors the lenient behaviour of the /metrics and /metrics_prometheus
+// endpoints.
+void ParseMergeRules(const std::vector<std::string>& raw_merge_rules,
+ MetricMergeRules* merge_rules);
+
+// Resolve the effective merge rules for a /metrics_prometheus request into
+// 'merge_rules'. Rules supplied with the request ('request_merge_rules') take
+// precedence over the server-wide default configured via
+// --metrics_prometheus_default_merge_rules, which is applied only when the
+// request carries none. Malformed rules are ignored.
+void GetPrometheusMergeRules(const std::vector<std::string>& request_merge_rules,
+ MetricMergeRules* merge_rules);
+
struct MetricJsonOptions {
MetricJsonOptions() :
include_raw_histograms(false),
@@ -526,6 +543,27 @@ struct MetricPrometheusOptions {
// and --metrics_prometheus_export_hostname are true.
// Empty when hostname is unavailable.
std::string hostname;
+
+ // Entities whose prototype name is in merge_rules's key set will be merged
+ // into a new entity before being exported, following the same semantics as
+ // the JSON end-point (see struct MergeAttributes for details). A merged
+ // entity is exported with 'type' and 'id' Prometheus labels identifying the
+ // merged-to type and the value of the merged-by attribute, e.g. merging
+ // 'tablet' entities into 'table' by 'table_name' yields metric lines like
+ // kudu_on_disk_size{type="table",id="my_table",...}.
+ //
+ // Merging is the recommended way to cut down the number of exported time
+ // series on clusters with a large number of tablets. When merge_rules is
+ // empty, every entity is exported as-is.
+ //
+ // NOTE: merged entities are always exported in the label-based format,
+ // regardless of --metrics_prometheus_use_entity_labels.
+ // NOTE: entities whose prototype name is NOT in merge_rules's key set are
+ // exported as-is (without merging), preserving their native attribute
+ // labels such as table_name/table_id. This matters e.g. on the master,
+ // where 'table' entities must keep their table_name label even when a
+ // 'tablet' merge rule is supplied.
+ MetricMergeRules merge_rules;
};
class MetricEntityPrototype {
diff --git a/src/kudu/util/prometheus_writer.cc b/src/kudu/util/prometheus_writer.cc
index 20a0191f0..cc742c81f 100644
--- a/src/kudu/util/prometheus_writer.cc
+++ b/src/kudu/util/prometheus_writer.cc
@@ -117,3 +117,12 @@ string BuildGenericPrometheusLabels(
}
return labels;
}
+
+string BuildMergedPrometheusLabels(
+ const string& entity_type,
+ const string& entity_id) {
+ string labels;
+ labels += "type=\"" + EscapePrometheusLabelValue(entity_type) + "\"";
+ labels += ",id=\"" + EscapePrometheusLabelValue(entity_id) + "\"";
+ return labels;
+}
diff --git a/src/kudu/util/prometheus_writer.h b/src/kudu/util/prometheus_writer.h
index 23396abd0..bd12957b0 100644
--- a/src/kudu/util/prometheus_writer.h
+++ b/src/kudu/util/prometheus_writer.h
@@ -82,3 +82,13 @@ std::string BuildGenericPrometheusLabels(
const std::string& entity_type,
const std::string& entity_id,
const std::unordered_map<std::string, std::string>& attrs);
+
+// Build Prometheus label string for a merged metric entity produced by
+// merge_rules aggregation. Unlike BuildPrometheusLabels(), this does not
+// restrict the entity type, because the merged-to type is user-defined via the
+// 'merge_to' field of a merge rule and need not be one of the well-known entity
+// types. Both values are escaped. Returns labels of the form:
+// type="<entity_type>",id="<entity_id>"
+std::string BuildMergedPrometheusLabels(
+ const std::string& entity_type,
+ const std::string& entity_id);