diff --git a/cmd/promtool/rules_test.go b/cmd/promtool/rules_test.go index 0c5d85aca..f1f3b756e 100644 --- a/cmd/promtool/rules_test.go +++ b/cmd/promtool/rules_test.go @@ -207,3 +207,67 @@ func createMultiRuleTestFiles(path string) error { ` return ioutil.WriteFile(path, []byte(recordingRules), 0777) } + +// TestBackfillLabels confirms that the labels in the rule file override the labels from the metrics +// received from Prometheus Query API, including the __name__ label. +func TestBackfillLabels(t *testing.T) { + tmpDir, err := ioutil.TempDir("", "backfilldata") + require.NoError(t, err) + defer func() { + require.NoError(t, os.RemoveAll(tmpDir)) + }() + ctx := context.Background() + + start := time.Date(2009, time.November, 10, 6, 34, 0, 0, time.UTC) + mockAPISamples := []*model.SampleStream{ + { + Metric: model.Metric{"name1": "override", "__name__": "override"}, + Values: []model.SamplePair{{Timestamp: model.TimeFromUnixNano(start.UnixNano()), Value: 123}}, + }, + } + ruleImporter, err := newTestRuleImporter(ctx, start, tmpDir, mockAPISamples) + require.NoError(t, err) + + path := filepath.Join(tmpDir, "test.file") + recordingRules := `groups: +- name: group0 + rules: + - record: rule1 + expr: ruleExpr + labels: + name1: val1 +` + require.NoError(t, ioutil.WriteFile(path, []byte(recordingRules), 0777)) + errs := ruleImporter.loadGroups(ctx, []string{path}) + for _, err := range errs { + require.NoError(t, err) + } + + errs = ruleImporter.importAll(ctx) + for _, err := range errs { + require.NoError(t, err) + } + + opts := tsdb.DefaultOptions() + opts.AllowOverlappingBlocks = true + db, err := tsdb.Open(tmpDir, nil, nil, opts, nil) + require.NoError(t, err) + + q, err := db.Querier(context.Background(), math.MinInt64, math.MaxInt64) + require.NoError(t, err) + + t.Run("correct-labels", func(t *testing.T) { + selectedSeries := q.Select(false, nil, labels.MustNewMatcher(labels.MatchRegexp, "", ".*")) + for selectedSeries.Next() { + series := selectedSeries.At() + expectedLabels := labels.Labels{ + labels.Label{Name: "__name__", Value: "rule1"}, + labels.Label{Name: "name1", Value: "val1"}, + } + require.Equal(t, expectedLabels, series.Labels()) + } + require.NoError(t, selectedSeries.Err()) + require.NoError(t, q.Close()) + require.NoError(t, db.Close()) + }) +}