1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
|
// Copyright 2016 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.
// +build !nohwmon
package collector
import (
"errors"
"io/ioutil"
"os"
"path"
"path/filepath"
"regexp"
"strconv"
"strings"
"github.com/prometheus/client_golang/prometheus"
)
const (
hwMonSubsystem = "hwmon"
)
var (
hwmonInvalidMetricChars = regexp.MustCompile("[^a-z0-9:_]")
hwmonFilenameFormat = regexp.MustCompile(`^(?P<type>[^0-9]+)(?P<id>[0-9]*)?(_(?P<property>.+))?$`)
hwmonLabelDesc = []string{"chip", "sensor"}
hwmonSensorTypes = []string{
"vrm", "beep_enable", "update_interval", "in", "cpu", "fan",
"pwm", "temp", "curr", "power", "energy", "humidity",
"intrusion",
}
)
func init() {
Factories["hwmon"] = NewHwMonCollector
}
type hwMonCollector struct{}
// Takes a prometheus registry and returns a new Collector exposing
// /sys/class/hwmon stats (similar to lm-sensors).
func NewHwMonCollector() (Collector, error) {
return &hwMonCollector{}, nil
}
func cleanMetricName(name string) string {
lower := strings.ToLower(name)
replaced := hwmonInvalidMetricChars.ReplaceAllLiteralString(lower, "_")
cleaned := strings.Trim(replaced, "_")
return cleaned
}
func addValueFile(data map[string]map[string]string, sensor string, prop string, file string) {
raw, e := ioutil.ReadFile(file)
if e != nil {
return
}
value := strings.Trim(string(raw), "\n")
if _, ok := data[sensor]; !ok {
data[sensor] = make(map[string]string)
}
data[sensor][prop] = value
}
// Split a sensor name into <type><num>_<property>
func explodeSensorFilename(filename string) (ok bool, sensorType string, sensorNum int, sensorProperty string) {
matches := hwmonFilenameFormat.FindStringSubmatch(filename)
if len(matches) == 0 {
return false, sensorType, sensorNum, sensorProperty
}
for i, match := range hwmonFilenameFormat.SubexpNames() {
if i >= len(matches) {
return true, sensorType, sensorNum, sensorProperty
}
if match == "type" {
sensorType = matches[i]
}
if match == "property" {
sensorProperty = matches[i]
}
if match == "id" && len(matches[i]) > 0 {
if num, err := strconv.Atoi(matches[i]); err == nil {
sensorNum = num
} else {
return false, sensorType, sensorNum, sensorProperty
}
}
}
return true, sensorType, sensorNum, sensorProperty
}
func collectSensorData(dir string, data map[string]map[string]string) (err error) {
sensorFiles, dirError := ioutil.ReadDir(dir)
if dirError != nil {
return dirError
}
for _, file := range sensorFiles {
filename := file.Name()
ok, sensorType, sensorNum, sensorProperty := explodeSensorFilename(filename)
if !ok {
continue
}
for _, t := range hwmonSensorTypes {
if t == sensorType {
addValueFile(data, sensorType+strconv.Itoa(sensorNum), sensorProperty, path.Join(dir, file.Name()))
break
}
}
}
return nil
}
func (c *hwMonCollector) updateHwmon(ch chan<- prometheus.Metric, dir string) (err error) {
hwmonName, err := c.hwmonName(dir)
if err != nil {
return err
}
data := make(map[string]map[string]string)
err = collectSensorData(dir, data)
if err != nil {
return err
}
if _, err := os.Stat(path.Join(dir, "device")); err == nil {
err := collectSensorData(path.Join(dir, "device"), data)
if err != nil {
return err
}
}
// format all sensors
for sensor, sensorData := range data {
_, sensorType, _, _ := explodeSensorFilename(sensor)
if labelText, ok := sensorData["label"]; ok {
label := cleanMetricName(labelText)
if label != "" {
sensor = label
}
}
labels := []string{hwmonName, sensor}
if sensorType == "beep_enable" {
value := 0.0
if sensorData[""] == "1" {
value = 1.0
}
metricName := "node_hwmon_beep_enabled"
desc := prometheus.NewDesc(metricName, "Hardware beep enabled", hwmonLabelDesc, nil)
ch <- prometheus.MustNewConstMetric(
desc, prometheus.GaugeValue, value, labels...)
continue
}
if sensorType == "vrm" {
parsedValue, err := strconv.ParseFloat(sensorData[""], 64)
if err != nil {
continue
}
metricName := "node_hwmon_voltage_regulator_version"
desc := prometheus.NewDesc(metricName, "Hardware voltage regulator", hwmonLabelDesc, nil)
ch <- prometheus.MustNewConstMetric(
desc, prometheus.GaugeValue, parsedValue, labels...)
continue
}
if sensorType == "update_interval" {
parsedValue, err := strconv.ParseFloat(sensorData[""], 64)
if err != nil {
continue
}
metricName := "node_hwmon_update_interval_seconds"
desc := prometheus.NewDesc(metricName, "Hardware monitor update interval", hwmonLabelDesc, nil)
ch <- prometheus.MustNewConstMetric(
desc, prometheus.GaugeValue, parsedValue*0.001, labels...)
continue
}
prefix := "node_hwmon_" + sensorType
for element, value := range sensorData {
if element == "label" {
continue
}
name := prefix
if element == "input" {
// input is actually the value
if _, ok := sensorData[""]; ok {
name = name + "_input"
}
} else if element != "" {
name = name + "_" + cleanMetricName(element)
}
parsedValue, err := strconv.ParseFloat(value, 64)
if err != nil {
continue
}
// special elements, fault, alarm & beep should be handed out without units
if element == "fault" || element == "alarm" {
desc := prometheus.NewDesc(name, "Hardware sensor "+element+" status ("+sensorType+")", hwmonLabelDesc, nil)
ch <- prometheus.MustNewConstMetric(desc, prometheus.GaugeValue, parsedValue, labels...)
continue
}
if element == "beep" {
desc := prometheus.NewDesc(name+"_enabled", "Hardware monitor sensor has beeping enabled", hwmonLabelDesc, nil)
ch <- prometheus.MustNewConstMetric(desc, prometheus.GaugeValue, parsedValue, labels...)
continue
}
// everything else should get a unit
if sensorType == "in" || sensorType == "cpu" {
desc := prometheus.NewDesc(name+"_volts", "Hardware monitor for voltage ("+element+")", hwmonLabelDesc, nil)
ch <- prometheus.MustNewConstMetric(
desc, prometheus.GaugeValue, parsedValue*0.001, labels...)
continue
}
if sensorType == "temp" && element != "type" {
desc := prometheus.NewDesc(name+"_celsius", "Hardware monitor for temperature ("+element+")", hwmonLabelDesc, nil)
ch <- prometheus.MustNewConstMetric(
desc, prometheus.GaugeValue, parsedValue*0.001, labels...)
continue
}
if sensorType == "curr" {
desc := prometheus.NewDesc(name+"_amps", "Hardware monitor for current ("+element+")", hwmonLabelDesc, nil)
ch <- prometheus.MustNewConstMetric(
desc, prometheus.GaugeValue, parsedValue*0.001, labels...)
continue
}
if sensorType == "energy" {
desc := prometheus.NewDesc(name+"_joule_total", "Hardware monitor for joules used so far ("+element+")", hwmonLabelDesc, nil)
ch <- prometheus.MustNewConstMetric(
desc, prometheus.CounterValue, parsedValue/1000000.0, labels...)
continue
}
if sensorType == "power" && element == "accuracy" {
desc := prometheus.NewDesc(name, "Hardware monitor power meter accuracy, as a ratio", hwmonLabelDesc, nil)
ch <- prometheus.MustNewConstMetric(
desc, prometheus.GaugeValue, parsedValue/1000000.0, labels...)
continue
}
if sensorType == "power" && (element == "average_interval" || element == "average_interval_min" || element == "average_interval_max") {
desc := prometheus.NewDesc(name+"_seconds", "Hardware monitor power usage update interval ("+element+")", hwmonLabelDesc, nil)
ch <- prometheus.MustNewConstMetric(
desc, prometheus.GaugeValue, parsedValue*0.001, labels...)
continue
}
if sensorType == "power" {
desc := prometheus.NewDesc(name+"_watt", "Hardware monitor for power usage in watts ("+element+")", hwmonLabelDesc, nil)
ch <- prometheus.MustNewConstMetric(
desc, prometheus.GaugeValue, parsedValue/1000000.0, labels...)
continue
}
if sensorType == "humidity" {
desc := prometheus.NewDesc(name, "Hardware monitor for humidity, as a ratio (multiply with 100.0 to get the humidity as a percentage) ("+element+")", hwmonLabelDesc, nil)
ch <- prometheus.MustNewConstMetric(
desc, prometheus.GaugeValue, parsedValue/1000000.0, labels...)
continue
}
if sensorType == "fan" && (element == "input" || element == "min" || element == "max" || element == "target") {
desc := prometheus.NewDesc(name+"_rpm", "Hardware monitor for fan revolutions per minute ("+element+")", hwmonLabelDesc, nil)
ch <- prometheus.MustNewConstMetric(
desc, prometheus.GaugeValue, parsedValue, labels...)
continue
}
// fallback, just dump the metric as is
desc := prometheus.NewDesc(name, "Hardware monitor "+sensorType+" element "+element, hwmonLabelDesc, nil)
ch <- prometheus.MustNewConstMetric(
desc, prometheus.GaugeValue, parsedValue, labels...)
}
}
return nil
}
func (c *hwMonCollector) hwmonName(dir string) (string, error) {
// generate a name for a sensor path
// sensor numbering depends on the order of linux module loading and
// is thus unstable.
// However the path of the device has to be stable:
// - /sys/devices/<bus>/<device>
// Some hardware monitors have a "name" file that exports a human
// readbale name that can be used.
// human readable names would be bat0 or coretemp, while a path string
// could be platform_applesmc.768
// preference 1: construct a name based on device name, always unique
devicePath, devErr := filepath.EvalSymlinks(path.Join(dir, "device"))
if devErr == nil {
devPathPrefix, devName := path.Split(devicePath)
_, devType := path.Split(strings.TrimRight(devPathPrefix, "/"))
cleanDevName := cleanMetricName(devName)
cleanDevType := cleanMetricName(devType)
if cleanDevType != "" && cleanDevName != "" {
return cleanDevType + "_" + cleanDevName, nil
}
if cleanDevName != "" {
return cleanDevName, nil
}
}
// preference 2: is there a name file
sysnameRaw, nameErr := ioutil.ReadFile(path.Join(dir, "name"))
if nameErr == nil && string(sysnameRaw) != "" {
cleanName := cleanMetricName(string(sysnameRaw))
if cleanName != "" {
return cleanName, nil
}
}
// it looks bad, name and device don't provide enough information
// return a hwmon[0-9]* name
realDir, err := filepath.EvalSymlinks(dir)
if err != nil {
return "", err
}
// take the last path element, this will be hwmonX
_, name := path.Split(realDir)
cleanName := cleanMetricName(name)
if cleanName != "" {
return cleanName, nil
}
return "", errors.New("Could not derive a monitoring name for " + dir)
}
func (c *hwMonCollector) Update(ch chan<- prometheus.Metric) (err error) {
// Step 1: scan /sys/class/hwmon, resolve all symlinks and call
// updatesHwmon for each folder
hwmonPathName := path.Join(sysFilePath("class"), "hwmon")
hwmonFiles, err := ioutil.ReadDir(hwmonPathName)
if err != nil {
return err
}
for _, hwDir := range hwmonFiles {
hwmonXPathName := path.Join(hwmonPathName, hwDir.Name())
if hwDir.Mode()&os.ModeSymlink > 0 {
hwDir, err = os.Stat(hwmonXPathName)
if err != nil {
continue
}
}
if !hwDir.IsDir() {
continue
}
if lastErr := c.updateHwmon(ch, hwmonXPathName); lastErr != nil {
err = lastErr
}
}
return err
}
|