prometheus-node-exporter-lua: use buffered io, remove concat

netclass collector scrape time goes from 230ms to 170ms

Signed-off-by: Etienne Champetier <champetier.etienne@gmail.com>
This commit is contained in:
Etienne Champetier
2025-06-29 12:21:54 -04:00
parent f18594a00f
commit 00d420e801
2 changed files with 21 additions and 16 deletions

View File

@@ -32,21 +32,24 @@ end
-- Metric printing
function print_metric(metric, labels, value)
local label_string = ""
if type(value) == "nil" then
return
end
out:write(metric)
if labels then
out:write("{")
coma = ""
for label,value in pairs(labels) do
label_string = label_string .. label .. '="' .. value .. '",'
out:write(coma, label, '="', value, '"')
coma = ","
end
label_string = "{" .. string.sub(label_string, 1, -2) .. "}"
out:write("}")
end
output(string.format("%s%s %s", metric, label_string, value))
out:write(" ", value, "\n")
end
function metric(name, mtype, labels, value)
output("# TYPE " .. name .. " " .. mtype)
out:write("# TYPE ", name, " ", mtype, "\n")
local outputter = function(labels, value)
print_metric(name, labels, value)
end
@@ -83,15 +86,18 @@ end
-- Web server-specific functions
function handle_request(env)
-- use buffered output instead uhttpd.send()
out = io.open("/proc/self/fd/1", "a+")
out:setvbuf("full")
if env.PATH_INFO ~= '/metrics' then
uhttpd.send("Status: 404 Not Found\r\n")
uhttpd.send("Server: lua-metrics\r\n")
uhttpd.send("Content-Type: text/plain\r\n\r\n")
uhttpd.send("ERROR: File Not Found.")
out:write("Status: 404 Not Found\r\n")
out:write("Server: lua-metrics\r\n")
out:write("Content-Type: text/plain\r\n\r\n")
out:write("ERROR: File Not Found.")
else
uhttpd.send("Status: 200 OK\r\n")
uhttpd.send("Server: lua-metrics\r\n")
uhttpd.send("Content-Type: text/plain; version=0.0.4\r\n\r\n")
out:write("Status: 200 OK\r\n")
out:write("Server: lua-metrics\r\n")
out:write("Content-Type: text/plain; version=0.0.4\r\n\r\n")
local cols = {}
for c in env.QUERY_STRING:gmatch("collect[^=]*=([^&]+)") do
cols[#cols+1] = c
@@ -101,6 +107,7 @@ function handle_request(env)
end
run_all_collectors(cols)
end
out:flush()
end
-- Main program
@@ -115,9 +122,7 @@ for c in ls_fd:lines() do
end
ls_fd:close()
output = function (str) uhttpd.send(str.."\n") end
if arg ~= nil then
output = print
out = io.output()
run_all_collectors(col_names)
end