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

fix(metric name): support multiple __name__ matcher #71

Merged
merged 5 commits into from
Jul 10, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,8 @@ AST: VectorSelector(VectorSelector { name: Some("http_requests_total"), matchers

## PromQL compliance

This crate declares compatible with [prometheus 0372e25][prom-0372e25], which is
prometheus release 2.40 at Nov 29, 2022. Any revision on PromQL after this
commit is not guaranteed.
This crate declares compatible with [prometheus v2.45.0][prom-v2.45.0], which is
released at 2023-06-23. Any revision on PromQL after this commit is not guaranteed.
yuanbohan marked this conversation as resolved.
Show resolved Hide resolved

## Community Extensions

Expand Down Expand Up @@ -74,5 +73,5 @@ Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
licensed as above, without any additional terms or conditions.

[prom-0372e25]: https://github.com/prometheus/prometheus/tree/0372e259baf014bbade3134fd79bcdfd8cbdef2c
[prom-v2.45.0]: https://github.com/prometheus/prometheus/tree/v2.45.0
[querying-prometheus]: https://prometheus.io/docs/prometheus/latest/querying/basics/
15 changes: 8 additions & 7 deletions src/label/matcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,13 +136,14 @@ impl Matchers {
self.matchers.is_empty() || self.matchers.iter().all(|m| m.is_match(""))
}

/// find all the matchers whose name equals the specified name.
pub fn find_matchers(&self, name: &str) -> Vec<&String> {
self.matchers
.iter()
.filter(|m| m.name.eq_ignore_ascii_case(name))
.map(|m| &m.value)
.collect()
/// find the matcher's value whose name equals the specified name.
pub fn find_matcher(&self, name: &str) -> Option<String> {
for m in &self.matchers {
if m.name.eq(name) {
return Some(m.value.clone());
}
}
None
}
}

Expand Down
54 changes: 23 additions & 31 deletions src/parser/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::label::{Labels, Matcher, Matchers, METRIC_NAME};
use crate::label::{Labels, Matchers, METRIC_NAME};
use crate::parser::token::{
self, token_display, T_BOTTOMK, T_COUNT_VALUES, T_END, T_QUANTILE, T_START, T_TOPK,
};
Expand Down Expand Up @@ -369,12 +369,11 @@ pub struct VectorSelector {

impl From<String> for VectorSelector {
fn from(name: String) -> Self {
let matcher = Matcher::new_eq_metric_matcher(name.clone());
VectorSelector {
name: Some(name),
offset: None,
at: None,
matchers: Matchers::one(matcher),
matchers: Matchers::empty(),
}
}
}
Expand All @@ -386,15 +385,14 @@ impl From<String> for VectorSelector {
/// Basic usage:
///
/// ``` rust
/// use promql_parser::parser::{Expr, VectorSelector};
/// use promql_parser::label::{MatchOp, Matcher, Matchers};
/// use promql_parser::label::Matchers;
/// use promql_parser::parser::VectorSelector;
///
/// let matcher = Matcher::new_eq_metric_matcher(String::from("foo"));
/// let vs = VectorSelector {
/// name: Some(String::from("foo")),
/// offset: None,
/// at: None,
/// matchers: Matchers::one(matcher),
/// matchers: Matchers::empty(),
/// };
///
/// assert_eq!(VectorSelector::from("foo"), vs);
Expand Down Expand Up @@ -768,12 +766,11 @@ impl From<f64> for Expr {
/// Basic usage:
///
/// ``` rust
/// use promql_parser::label::Matchers;
/// use promql_parser::parser::{Expr, VectorSelector};
/// use promql_parser::label::{MatchOp, Matcher, Matchers};
///
/// let name = String::from("foo");
/// let matcher = Matcher::new_eq_metric_matcher(name.clone());
/// let vs = Expr::new_vector_selector(Some(name), Matchers::one(matcher));
/// let vs = Expr::new_vector_selector(Some(name), Matchers::empty());
///
/// assert_eq!(Expr::from(VectorSelector::from("foo")), vs.unwrap());
/// ```
Expand Down Expand Up @@ -976,16 +973,13 @@ fn check_ast_for_call(ex: Call) -> Result<Expr, String> {
}

// special cases from https://prometheus.io/docs/prometheus/latest/querying/functions
if name.eq_ignore_ascii_case("exp") {
if name.eq("exp") {
if let Some(val) = ex.args.first().and_then(|ex| ex.scalar_value()) {
if val.is_nan() || val.is_infinite() {
return Ok(Expr::Call(ex));
}
}
} else if name.eq_ignore_ascii_case("ln")
|| name.eq_ignore_ascii_case("log2")
|| name.eq_ignore_ascii_case("log10")
{
} else if name.eq("ln") || name.eq("log2") || name.eq("log10") {
if let Some(val) = ex.args.first().and_then(|ex| ex.scalar_value()) {
if val.is_nan() || val.is_infinite() || val <= 0.0 {
return Ok(Expr::Call(ex));
Expand Down Expand Up @@ -1032,23 +1026,21 @@ fn check_ast_for_subquery(ex: SubqueryExpr) -> Result<Expr, String> {
}

fn check_ast_for_vector_selector(ex: VectorSelector) -> Result<Expr, String> {
// A Vector selector must contain at least one non-empty matcher to prevent
// implicit selection of all metrics (e.g. by a typo).
if ex.matchers.is_empty_matchers() {
return Err("vector selector must contain at least one non-empty matcher".into());
}

let mut du = ex.matchers.find_matchers(METRIC_NAME);
if du.len() >= 2 {
// this is to ensure that the err information can be predicted with fixed order
du.sort();
return Err(format!(
"metric name must not be set twice: '{}' or '{}'",
du[0], du[1]
));
match ex.name {
Some(ref name) => match ex.matchers.find_matcher(METRIC_NAME) {
Some(val) => Err(format!(
"metric name must not be set twice: '{}' or '{}'",
name, val
)),
None => Ok(Expr::VectorSelector(ex)),
},
None if ex.matchers.is_empty_matchers() => {
// When name is None, a vector selector must contain at least one non-empty matcher
// to prevent implicit selection of all metrics (e.g. by a typo).
Err("vector selector must contain at least one non-empty matcher".into())
}
_ => Ok(Expr::VectorSelector(ex)),
}

Ok(Expr::VectorSelector(ex))
}

#[cfg(test)]
Expand Down
Loading
Loading