Prometheus: Auto legend handling (#45367)

* Legend editor is working

* It's working

* Progress on auto legend mode

* Fixes

* added unit tests

* Added go tests

* Fixing tests

* Fix issue with timing and internal state

* Update public/app/plugins/datasource/prometheus/querybuilder/components/PromQueryCodeEditor.tsx

Co-authored-by: Ivana Huckova <30407135+ivanahuckova@users.noreply.github.com>
This commit is contained in:
Torkel Ödegaard
2022-02-16 14:06:33 +01:00
committed by GitHub
parent da91c93f4a
commit cfa24a3cfb
10 changed files with 293 additions and 53 deletions

View File

@@ -39,6 +39,8 @@ const (
varRateIntervalAlt = "${__rate_interval}"
)
const legendFormatAuto = "__auto"
type TimeSeriesQueryType string
const (
@@ -137,11 +139,14 @@ func (s *Service) executeTimeSeriesQuery(ctx context.Context, req *backend.Query
}
func formatLegend(metric model.Metric, query *PrometheusQuery) string {
var legend string
var legend = metric.String()
if query.LegendFormat == "" {
legend = metric.String()
} else {
if query.LegendFormat == legendFormatAuto {
// If we have labels set legend to empty string to utilize the auto naming system
if len(metric) > 0 {
legend = ""
}
} else if query.LegendFormat != "" {
result := legendFormat.ReplaceAllFunc([]byte(query.LegendFormat), func(in []byte) []byte {
labelName := strings.Replace(string(in), "{{", "", 1)
labelName = strings.Replace(labelName, "}}", "", 1)
@@ -335,8 +340,12 @@ func matrixToDataFrames(matrix model.Matrix, query *PrometheusQuery, frames data
timeField.Name = data.TimeSeriesTimeFieldName
timeField.Config = &data.FieldConfig{Interval: float64(query.Step.Milliseconds())}
valueField.Name = data.TimeSeriesValueFieldName
valueField.Config = &data.FieldConfig{DisplayNameFromDS: name}
valueField.Labels = tags
if name != "" {
valueField.Config = &data.FieldConfig{DisplayNameFromDS: name}
}
frames = append(frames, newDataFrame(name, "matrix", timeField, valueField))
}

View File

@@ -52,6 +52,30 @@ func TestPrometheus_timeSeriesQuery_formatLeged(t *testing.T) {
require.Equal(t, `{job="grafana"}`, formatLegend(metric, query))
})
t.Run("When legendFormat = __auto and no labels", func(t *testing.T) {
metric := map[p.LabelName]p.LabelValue{}
query := &PrometheusQuery{
LegendFormat: legendFormatAuto,
Expr: `{job="grafana"}`,
}
require.Equal(t, `{job="grafana"}`, formatLegend(metric, query))
})
t.Run("When legendFormat = __auto with labels", func(t *testing.T) {
metric := map[p.LabelName]p.LabelValue{
p.LabelName("app"): p.LabelValue("backend"),
}
query := &PrometheusQuery{
LegendFormat: legendFormatAuto,
Expr: `{job="grafana"}`,
}
require.Equal(t, "", formatLegend(metric, query))
})
}
func TestPrometheus_timeSeriesQuery_parseTimeSeriesQuery(t *testing.T) {