From 69f5fa0c1ea7dd0ade8fe694d753780ad125c175 Mon Sep 17 00:00:00 2001 From: Brian Brazil Date: Fri, 11 Sep 2015 12:09:34 +0100 Subject: [PATCH] promql: Add vector function. Currently the only way to convert a scalar to a vector is to use absent(), which isn't very clean. This adds a vector() function that's the inverse of scalar() and lets your optionally set labels. Example usage would be vector(time() % 86400) < 3600 to filter to only the first hour of the day. --- promql/functions.go | 31 +++++++++++++++++++++++++++++++ promql/testdata/functions.test | 15 +++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/promql/functions.go b/promql/functions.go index 80de10efb..a5ecd92e5 100644 --- a/promql/functions.go +++ b/promql/functions.go @@ -650,6 +650,30 @@ func funcLabelReplace(ev *evaluator, args Expressions) model.Value { return vector } +// === vector(s scalar, vector model.ValVectora={}) Vector === +func funcVector(ev *evaluator, args Expressions) model.Value { + m := model.Metric{} + if len(args) >= 2 { + if vs, ok := args[1].(*VectorSelector); ok { + for _, matcher := range vs.LabelMatchers { + if matcher.Type == metric.Equal && matcher.Name != model.MetricNameLabel { + m[matcher.Name] = matcher.Value + } + } + } + } + return vector{ + &sample{ + Metric: metric.Metric{ + Metric: m, + Copied: true, + }, + Value: model.SampleValue(ev.evalFloat(args[0])), + Timestamp: ev.Timestamp, + }, + } +} + var functions = map[string]*Function{ "abs": { Name: "abs", @@ -845,6 +869,13 @@ var functions = map[string]*Function{ ReturnType: model.ValVector, Call: funcTopk, }, + "vector": { + Name: "vector", + ArgTypes: []model.ValueType{model.ValScalar, model.ValVector}, + ReturnType: model.ValVector, + OptionalArgs: 1, + Call: funcVector, + }, } // getFunction returns a predefined Function object for the given name. diff --git a/promql/testdata/functions.test b/promql/testdata/functions.test index f203b24a0..778042d4d 100644 --- a/promql/testdata/functions.test +++ b/promql/testdata/functions.test @@ -146,3 +146,18 @@ eval_fail instant at 0m label_replace(testmetric, "invalid-label-name", "", "src # label_replace fails when there would be duplicated identical output label sets. eval_fail instant at 0m label_replace(testmetric, "src", "", "", "") + +clear + +# Tests for vector. +eval instant at 0m vector(1) + {} 1 + +eval instant at 60m vector(time()) + {} 3600 + +eval instant at 0m vector(1, {a="b"}) + {a="b"} 1 + +eval instant at 0m vector(1, {a="b", c=~"d", e!="f", g!~"h", a="z"}) + {a="z"} 1