diff --git a/collector/rapl_linux.go b/collector/rapl_linux.go index 5ed343bbe8..376adf8a0a 100644 --- a/collector/rapl_linux.go +++ b/collector/rapl_linux.go @@ -77,21 +77,29 @@ func (c *raplCollector) Update(ch chan<- prometheus.Metric) error { } return err } - index := strconv.Itoa(rz.Index) - - descriptor := prometheus.NewDesc( - prometheus.BuildFQName(namespace, "rapl", rz.Name+"_joules_total"), - "Current RAPL "+rz.Name+" value in joules", - []string{"index", "path"}, nil, - ) - ch <- prometheus.MustNewConstMetric( - descriptor, - prometheus.CounterValue, - float64(newMicrojoules)/1000000.0, - index, - rz.Path, - ) + index := strconv.Itoa(rz.Index) + ch <- getRzMetric(rz.Name, rz.Path, index, newMicrojoules) } return nil } + +// getRzMetric sanitize the raplZoneName and returns new metrics +func getRzMetric(raplZoneName, raplZonePath, index string, newMicrojoules uint64) prometheus.Metric { + // sanitizing rapl zone name for invalid metric name + raplZoneName = SanitizeMetricName(raplZoneName) + + descriptor := prometheus.NewDesc( + prometheus.BuildFQName(namespace, "rapl", raplZoneName+"_joules_total"), + "Current RAPL "+raplZoneName+" value in joules", + []string{"index", "path"}, nil, + ) + + return prometheus.MustNewConstMetric( + descriptor, + prometheus.CounterValue, + float64(newMicrojoules)/1000000.0, + index, + raplZonePath, + ) +} diff --git a/collector/rapl_linux_test.go b/collector/rapl_linux_test.go new file mode 100644 index 0000000000..b2706db584 --- /dev/null +++ b/collector/rapl_linux_test.go @@ -0,0 +1,49 @@ +// Copyright 2015 The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package collector + +import ( + "testing" +) + +func TestInvalidRaplName(t *testing.T) { + testCases := []struct { + desc string + name string + }{ + { + desc: "invalid metrics name with numeric", + name: "package9", + }, + { + desc: "invalid metrics name with dash", + name: "package-", + }, + { + desc: "invalid metrics name", + name: "package-0-die-0", + }, + } + + // these are irrelevant in this test so accepting default value + var raplZonePath, index string + var newMicrojoules uint64 + + for i := range testCases { + t.Run(testCases[i].desc, func(t *testing.T) { + // getRzMetric panics if any error occurs + getRzMetric(testCases[i].name, raplZonePath, index, newMicrojoules) + }) + } +}