Skip to content

Commit

Permalink
Include prom_name value in metricID.
Browse files Browse the repository at this point in the history
This should avoid problems when multiple configs match the same sensor
and MQTT name to derive different values.
  • Loading branch information
Christian Schneider committed Dec 11, 2023
1 parent 0561fb6 commit 5a21fb7
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
17 changes: 11 additions & 6 deletions pkg/metrics/extractor.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,13 @@ import (
type Extractor func(topic string, payload []byte, deviceID string) (MetricCollection, error)

// metricID returns a deterministic identifier per metic config which is safe to use in a file path.
func metricID(topic, metric, deviceID string) string {
id := fmt.Sprintf("%s-%s-%s", deviceID, topic, metric)
re := regexp.MustCompile(`[^-a-zA-Z0-9]`)
return re.ReplaceAllString(id, "_")
func metricID(topic, metric, deviceID, promName string) string {
re := regexp.MustCompile(`[^a-zA-Z0-9]`)
deviceID = re.ReplaceAllString(deviceID, "_")
topic = re.ReplaceAllString(topic, "_")
metric = re.ReplaceAllString(metric, "_")
promName = re.ReplaceAllString(promName, "_")
return fmt.Sprintf("%s-%s-%s-%s", deviceID, topic, metric, promName)
}

func NewJSONObjectExtractor(p Parser) Extractor {
Expand All @@ -35,7 +38,8 @@ func NewJSONObjectExtractor(p Parser) Extractor {
continue
}

m, err := p.parseMetric(config, metricID(topic, path, deviceID), rawValue)
id := metricID(topic, path, deviceID, config.PrometheusName)
m, err := p.parseMetric(config, id, rawValue)
if err != nil {
return nil, fmt.Errorf("failed to parse valid metric value: %w", err)
}
Expand All @@ -59,7 +63,8 @@ func NewMetricPerTopicExtractor(p Parser, metricNameRegex *config.Regexp) Extrac
return nil, nil
}

m, err := p.parseMetric(config, metricID(topic, metricName, deviceID), string(payload))
id := metricID(topic, metricName, deviceID, config.PrometheusName)
m, err := p.parseMetric(config, id, string(payload))
if err != nil {
return nil, fmt.Errorf("failed to parse metric: %w", err)
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/metrics/parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -537,7 +537,7 @@ func TestParser_parseMetric(t *testing.T) {
return
}

id := metricID("", tt.args.metricPath, tt.args.deviceID)
id := metricID("", tt.args.metricPath, tt.args.deviceID, config.PrometheusName)
got, err := p.parseMetric(config, id, tt.args.value)
if (err != nil) != tt.wantErr {
t.Errorf("parseMetric() error = %v, wantErr %v", err, tt.wantErr)
Expand Down

0 comments on commit 5a21fb7

Please sign in to comment.