Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support not-equal matcher for PromQL metric names #5385

Open
wants to merge 7 commits into
base: main
Choose a base branch
from

Conversation

killme2008
Copy link
Contributor

@killme2008 killme2008 commented Jan 16, 2025

I hereby agree to the terms of the GreptimeDB CLA.

Refer to a related PR or issue link (optional)

Close #5375

What's changed and what's your intention?

  • Supports regex matches (or not) for __name__ in Prometheus APIs, currently limited to /api/v1/query_range and /api/v1/query.

  • Caps the query metric tables at a maximum of 1024.

PR Checklist

Please convert it to a draft if some of the following conditions are not met.

  • I have written the necessary rustdoc comments.
  • I have added the necessary unit tests and integration tests.
  • This PR requires documentation updates.
  • API changes are backward compatible.
  • Schema or data changes are backward compatible.

Summary by CodeRabbit

Release Notes

  • New Features

    • Added support for querying Prometheus metric names
    • Enhanced Prometheus query handling with more flexible matcher support
  • Performance

    • Introduced new performance tracking metrics for PromQL queries
  • Dependencies

    • Updated workspace dependencies for frontend and servers packages
  • Error Handling

    • Improved error management for Prometheus-related operations
    • Added new error variants for specific query and record batch scenarios

These changes expand the Prometheus query capabilities and improve overall system robustness.

@killme2008 killme2008 requested a review from a team as a code owner January 16, 2025 11:54
Copy link
Contributor

coderabbitai bot commented Jan 16, 2025

Important

Review skipped

Auto reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This pull request introduces enhanced PromQL query capabilities for metric name matching in GreptimeDB. The changes add support for more complex metric name queries, including regex matching and not-equal comparisons. By introducing new dependencies, error handling mechanisms, and query processing logic, the implementation allows for more flexible metric name filtering across the database's Prometheus-compatible API.

Changes

File Change Summary
src/frontend/Cargo.toml Added workspace dependencies for datatypes and promql-parser
src/frontend/src/error.rs Added two new error variants: CollectRecordbatch and PrometheusMetricNamesQueryPlan
src/frontend/src/instance.rs Added query_metric_names method to PrometheusHandler trait
src/frontend/src/instance/promql.rs Implemented handle_query_metric_names method for processing metric name queries
src/frontend/src/metrics.rs Added new Prometheus metric PROMQL_QUERY_METRICS_ELAPSED
src/servers/Cargo.toml Added store-api workspace dependency
src/servers/src/http/prometheus.rs Enhanced Prometheus query handling with new methods and error management
src/servers/src/prometheus.rs Added metric_name_matchers_to_plan function for creating DataFrame from matchers
src/servers/src/prometheus_handler.rs Added query_metric_names method to PrometheusHandler trait

Sequence Diagram

sequenceDiagram
    participant Client
    participant PrometheusAPI
    participant QueryHandler
    participant CatalogManager
    participant QueryEngine

    Client->>PrometheusAPI: Send PromQL Query
    PrometheusAPI->>QueryHandler: Process Query with Matchers
    QueryHandler->>CatalogManager: Retrieve Table Information
    CatalogManager-->>QueryHandler: Return Table Metadata
    QueryHandler->>QueryEngine: Generate Logical Plan
    QueryEngine->>QueryEngine: Execute Query
    QueryEngine-->>QueryHandler: Return Metric Names
    QueryHandler-->>PrometheusAPI: Return Filtered Metric Names
    PrometheusAPI-->>Client: Respond with Results
Loading

Assessment against linked issues

Objective Addressed Explanation
Support regex matchers for __name__
Limit table number to prevent OOM Implemented with MAX_METRICS_NUM
Do not implement != matcher Regex and regex negation supported

Possibly related PRs

Suggested reviewers

  • MichaelScofield
  • v0y4g3r
  • waynexia
  • fengjiachun

Poem

🐰 Metric Matcher's Dance

In PromQL's wild and winding way,
Regex queries now come to play,
With matchers sharp and logic bright,
Our database leaps to new height!

🎉 Hop, hop, hooray! 🎉


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@killme2008 killme2008 marked this pull request as draft January 16, 2025 11:54
@github-actions github-actions bot added the docs-not-required This change does not impact docs. label Jan 16, 2025
@killme2008 killme2008 marked this pull request as ready for review January 17, 2025 14:09
@github-actions github-actions bot added docs-required This change requires docs update. docs-not-required This change does not impact docs. and removed docs-not-required This change does not impact docs. docs-required This change requires docs update. labels Jan 17, 2025
@killme2008
Copy link
Contributor Author

@coderabbitai review

Copy link
Contributor

coderabbitai bot commented Jan 17, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Nitpick comments (5)
src/servers/src/prometheus.rs (1)

79-80: Handle potential empty conditions without using .unwrap()

While the comment states that conditions must not be empty, using .unwrap() can cause a panic if assumptions change. Consider handling the possibility of an empty conditions vector more safely.

Apply this diff to replace .unwrap() with proper error handling:

     // Safety: conditions MUST not be empty, reduce always return Some(expr).
-    let conditions = conditions.into_iter().reduce(Expr::and).unwrap();
+    let conditions = conditions.into_iter().reduce(Expr::and).context(error::EmptyConditionsSnafu)?;
src/servers/src/http/prometheus.rs (2)

143-145: Handle unsupported PrometheusResponse variants or provide appropriate feedback

In the append method, non-matrix and non-vector PrometheusResponse variants are ignored in the _ case. This might lead to silent failures or missed data when other variants are encountered. Consider handling these cases explicitly or logging a warning to aid in debugging.

Apply this diff to log a warning for unsupported variants:

     _ => {
-        // TODO(dennis): process other cases?
+        tracing::warn!("Unsupported PrometheusResponse variant encountered in append");
     }

305-306: Add a comment to justify the use of .unwrap() in reduce operation

The call to .unwrap() assumes that responses is not empty. While previous checks ensure that metric_names is not empty, making responses non-empty, adding a comment to explain this assumption improves code clarity.

Consider adding the following comment:

// Safety: responses must contain at least one element as metric_names is not empty.
responses
    .into_iter()
    .reduce(|mut acc, resp| {
        acc.data.append(resp.data);
        acc
    })
    .unwrap()
src/frontend/src/metrics.rs (1)

32-37: Add histogram buckets for better latency tracking.

While the metric is well-defined, consider adding bucket definitions similar to GRPC_HANDLE_QUERY_ELAPSED for more granular latency tracking.

 pub static ref PROMQL_QUERY_METRICS_ELAPSED: HistogramVec = register_histogram_vec!(
     "greptime_frontend_promql_query_metrics_elapsed",
     "frontend promql query metric names elapsed",
-    &["db"]
+    &["db"],
+    vec![0.005, 0.01, 0.05, 0.1, 0.5, 1.0, 5.0, 10.0, 60.0, 300.0]
 )
 .unwrap();
tests-integration/src/test_util.rs (1)

441-444: Consider adding error handling in the test utility function.

While using unwrap() is common in test code, consider adding basic error handling or at least error logging to help debug test failures.

 async fn run_sql(sql: &str, instance: &GreptimeDbStandalone) {
-    let result = instance.instance.do_query(sql, QueryContext::arc()).await;
-    let _ = result.first().unwrap().as_ref().unwrap();
+    let result = instance.instance.do_query(sql, QueryContext::arc()).await;
+    if let Some(first) = result.first() {
+        if let Err(e) = first {
+            eprintln!("Failed to execute SQL: {}, error: {}", sql, e);
+        }
+    }
 }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8d5d400 and 961d7df.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (12)
  • src/frontend/Cargo.toml (2 hunks)
  • src/frontend/src/error.rs (3 hunks)
  • src/frontend/src/instance.rs (3 hunks)
  • src/frontend/src/instance/promql.rs (1 hunks)
  • src/frontend/src/metrics.rs (1 hunks)
  • src/servers/Cargo.toml (1 hunks)
  • src/servers/src/http/prometheus.rs (9 hunks)
  • src/servers/src/lib.rs (1 hunks)
  • src/servers/src/prometheus.rs (1 hunks)
  • src/servers/src/prometheus_handler.rs (2 hunks)
  • tests-integration/src/test_util.rs (2 hunks)
  • tests-integration/tests/http.rs (2 hunks)
🔇 Additional comments (12)
src/servers/src/prometheus_handler.rs (1)

36-41: LGTM! Well-documented trait method addition.

The new async method signature is well-designed for querying metric names with matchers, aligning perfectly with the PR objectives.

src/servers/src/lib.rs (1)

43-43: LGTM! Clean module addition.

The new prometheus module is properly declared and follows the file's alphabetical ordering convention.

src/frontend/src/error.rs (3)

172-177: LGTM! Well-structured error variant.

The CollectRecordbatch error variant follows the established pattern and includes proper error source tracking.


234-239: LGTM! Appropriate error handling for metric names query.

The PrometheusMetricNamesQueryPlan error variant properly handles errors from the prometheus metric names query plan creation.


366-370: LGTM! Proper status code mapping.

The status code mappings for both new error variants are appropriate and consistent with the existing error handling patterns.

tests-integration/src/test_util.rs (1)

454-467: LGTM! Well-structured test data setup.

The SQL commands are well organized:

  1. Creates a physical table first
  2. Creates metric tables referencing the physical table
  3. Inserts test data with appropriate timestamps
src/frontend/src/instance.rs (2)

23-23: LGTM! Clean module addition.

The new promql module is properly declared.


455-464: LGTM! Well-implemented error handling.

The implementation properly maps errors using BoxedError and follows the codebase's error handling patterns.

tests-integration/tests/http.rs (2)

701-724: LGTM! Comprehensive test coverage for the new matcher functionality.

The test cases effectively cover:

  1. Positive case with regex matching multiple metrics
  2. Specific case matching single metric
  3. Response content validation

616-616: LGTM! Field name validation added.

Simple but effective validation of field name values.

src/frontend/Cargo.toml (1)

40-40: LGTM! Dependencies properly added.

The new dependencies:

  • Use workspace versioning for consistency
  • Are alphabetically ordered
  • Support the new PromQL functionality

Also applies to: 51-51

src/servers/Cargo.toml (1)

105-105: LGTM! Verify dependency usage.

The addition of store-api as a workspace dependency follows the project's dependency management pattern.

Let's verify that this dependency is actually used in the codebase:

✅ Verification successful

Dependency verified and properly used

The store-api dependency is used to access schema-related constants necessary for implementing the metric name matcher and table limit features.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for store-api usage in the servers crate
rg "use store_api::" src/servers/

Length of output: 109


Script:

#!/bin/bash
# Check the specific imports and their usage
rg "use store_api::metric_engine_consts::" -A 3 src/servers/src/http/prometheus.rs

Length of output: 195

src/servers/src/prometheus.rs Show resolved Hide resolved
src/servers/src/prometheus.rs Show resolved Hide resolved
src/frontend/src/instance/promql.rs Show resolved Hide resolved
src/frontend/src/instance/promql.rs Show resolved Hide resolved
src/servers/src/http/prometheus.rs Show resolved Hide resolved
@waynexia waynexia requested a review from Copilot January 18, 2025 13:17

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot reviewed 6 out of 13 changed files in this pull request and generated no comments.

Files not reviewed (7)
  • src/servers/Cargo.toml: Evaluated as low risk
  • src/frontend/src/metrics.rs: Evaluated as low risk
  • src/servers/src/lib.rs: Evaluated as low risk
  • src/servers/src/prometheus_handler.rs: Evaluated as low risk
  • src/frontend/src/error.rs: Evaluated as low risk
  • src/frontend/Cargo.toml: Evaluated as low risk
  • src/frontend/src/instance.rs: Evaluated as low risk
Comments suppressed due to low confidence (1)

src/servers/src/http/prometheus.rs:864

  • The function update_metric_name_matcher should handle nested matchers to ensure all matchers are correctly updated.
/// Update the `__name__` matchers in expression into special value
Copy link
Member

@waynexia waynexia left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rest LGTM

tests-integration/src/test_util.rs Outdated Show resolved Hide resolved
tests-integration/tests/http.rs Show resolved Hide resolved
@killme2008 killme2008 force-pushed the feature/promql-query-name branch from e396177 to 06d782a Compare January 19, 2025 05:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
docs-not-required This change does not impact docs.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Allows wildcard queries for metric names in PromQL.
2 participants