#!/usr/bin/lua5.1 local sys_stat = require "posix.sys.stat" local state_filename = '/run/prometheus-node-exporter_sensors/state' local sensors = require "sensors" local units = { temperature = "celsius", humidity = "percent", pressure = "pascals", gpio = "status", } local _typestring_printed = {} local function metric(name, mtype, labels, value) if nil == _typestring_printed[name] then print("# TYPE " .. name .. " " .. mtype) _typestring_printed[name] = 1 end local label_string = "" if labels then for label,value in pairs(labels) do label_string = label_string .. label .. '="' .. value .. '",' end label_string = "{" .. string.sub(label_string, 1, -2) .. "}" end print(string.format("%s%s %s", name, label_string, value)) end local function scrape(config, num_sensors) local readings, err = sensors.read(config) if not readings then return end metric("sensors_count_total", "gauge", nil, num_sensors) for name, values in pairs(readings) do labels = { name = name, kind = values._kind_ } for t, v in pairs(values) do local unit = units[t] if unit ~= nil then metric("sensors_" .. t .. "_" .. unit, "gauge", labels, v) end end end end local function _setup(config) local num_sensors, err = sensors.setup(config) if num_sensors == nil then error(err) end io.stderr:write(string.format("setup: %d sensors found.\n", num_sensors)) local f, err = io.open(state_filename, "w") if not f then error(err) end local ret, err = f:write(string.format("%d\n", num_sensors)) f:close() if not ret then error(err) end return num_sensors end local function setup(config) local s, _ = sys_stat.stat(state_filename) if s == nil then return _setup(config) end local f, err = io.open(state_filename, "r") if not f then error(err) end local data, err = f:read("*l") f:close() if not data then return _setup(config) end local num_sensors, err = tonumber(data) if num_sensors == nil then return _setup(config) end return num_sensors end function main() local config, err = sensors.read_config('/etc/prometheus/exporter/node/sensors.json') if config == nil then error(err) end local num_sensors = setup(config) scrape(config, num_sensors, units) end main()