File

util/template.lua @ 11523:5f15ab7c6ae5

Statistics: Rewrite statistics backends to use OpenMetrics The metric subsystem of Prosody has had some shortcomings from the perspective of the current state-of-the-art in metric observability. The OpenMetrics standard [0] is a formalization of the data model (and serialization format) of the well-known and widely-used Prometheus [1] software stack. The previous stats subsystem of Prosody did not map well to that format (see e.g. [2] and [3]); the key reason is that it was trying to do too much math on its own ([2]) while lacking first-class support for "families" of metrics ([3]) and structured metric metadata (despite the `extra` argument to metrics, there was no standard way of representing common things like "tags" or "labels"). Even though OpenMetrics has grown from the Prometheus world of monitoring, it maps well to other popular monitoring stacks such as: - InfluxDB (labels can be mapped to tags and fields as necessary) - Carbon/Graphite (labels can be attached to the metric name with dot-separation) - StatsD (see graphite when assuming that graphite is used as backend, which is the default) The util.statsd module has been ported to use the OpenMetrics model as a proof of concept. An implementation which exposes the util.statistics backend data as Prometheus metrics is ready for publishing in prosody-modules (most likely as mod_openmetrics_prometheus to avoid breaking existing 0.11 deployments). At the same time, the previous measure()-based API had one major advantage: It is really simple and easy to use without requiring lots of knowledge about OpenMetrics or similar concepts. For that reason as well as compatibility with existing code, it is preserved and may even be extended in the future. However, code relying on the `stats-updated` event as well as `get_stats` from `statsmanager` will break because the data model has changed completely; in case of `stats-updated`, the code will simply not run (as the event was renamed in order to avoid conflicts); the `get_stats` function has been removed completely (so it will cause a traceback when it is attempted to be used). Note that the measure_*_event methods have been removed from the module API. I was unable to find any uses or documentation and thus deemed they should not be ported. Re-implementation is possible when necessary. [0]: https://openmetrics.io/ [1]: https://prometheus.io/ [2]: #959 [3]: #960
author Jonas Schäfer <jonas@wielicki.name>
date Sun, 18 Apr 2021 11:47:41 +0200
parent 8555:4f0f5b49bb03
child 12975:d10957394a3c
line wrap: on
line source

-- luacheck: ignore 213/i
local stanza_mt = require "util.stanza".stanza_mt;
local setmetatable = setmetatable;
local pairs = pairs;
local ipairs = ipairs;
local error = error;
local envload = require "util.envload".envload;
local debug = debug;
local t_remove = table.remove;
local parse_xml = require "util.xml".parse;

local _ENV = nil;
-- luacheck: std none

local function trim_xml(stanza)
	for i=#stanza,1,-1 do
		local child = stanza[i];
		if child.name then
			trim_xml(child);
		else
			child = child:gsub("^%s*", ""):gsub("%s*$", "");
			stanza[i] = child;
			if child == "" then t_remove(stanza, i); end
		end
	end
end

local function create_string_string(str)
	str = ("%q"):format(str);
	str = str:gsub("{([^}]*)}", function(s)
		return '"..(data["'..s..'"]or"").."';
	end);
	return str;
end
local function create_attr_string(attr, xmlns)
	local str = '{';
	for name,value in pairs(attr) do
		if name ~= "xmlns" or value ~= xmlns then
			str = str..("[%q]=%s;"):format(name, create_string_string(value));
		end
	end
	return str..'}';
end
local function create_clone_string(stanza, lookup, xmlns)
	if not lookup[stanza] then
		local s = ('setmetatable({name=%q,attr=%s,tags={'):format(stanza.name, create_attr_string(stanza.attr, xmlns));
		-- add tags
		for i,tag in ipairs(stanza.tags) do
			s = s..create_clone_string(tag, lookup, stanza.attr.xmlns)..";";
		end
		s = s..'};';
		-- add children
		for i,child in ipairs(stanza) do
			if child.name then
				s = s..create_clone_string(child, lookup, stanza.attr.xmlns)..";";
			else
				s = s..create_string_string(child)..";"
			end
		end
		s = s..'}, stanza_mt)';
		s = s:gsub('%.%.""', ""):gsub('([=;])""%.%.', "%1"):gsub(';"";', ";"); -- strip empty strings
		local n = #lookup + 1;
		lookup[n] = s;
		lookup[stanza] = "_"..n;
	end
	return lookup[stanza];
end
local function create_cloner(stanza, chunkname)
	local lookup = {};
	local name = create_clone_string(stanza, lookup, "");
	local src = "local setmetatable,stanza_mt=...;return function(data)";
	for i=1,#lookup do
		src = src.."local _"..i.."="..lookup[i]..";";
	end
	src = src.."return "..name..";end";
	local f,err = envload(src, chunkname);
	if not f then error(err); end
	return f(setmetatable, stanza_mt);
end

local template_mt = { __tostring = function(t) return t.name end };
local function create_template(templates, text)
	local stanza, err = parse_xml(text);
	if not stanza then error(err); end
	trim_xml(stanza);

	local info = debug.getinfo(3, "Sl");
	info = info and ("template(%s:%d)"):format(info.short_src:match("[^\\/]*$"), info.currentline) or "template(unknown)";

	local template = setmetatable({ apply = create_cloner(stanza, info), name = info, text = text }, template_mt);
	templates[text] = template;
	return template;
end

local templates = setmetatable({}, { __mode = 'k', __index = create_template });
return function(text)
	return templates[text];
end;