diff --git a/CHANGELOG.md b/CHANGELOG.md index 91e86c9..d638403 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,11 @@ This file only calls out major changes. Please see [the list of Git commits]( https://github.com/api7/nginx-lua-prometheus/commits/main) for the full list of changes. +## 1.3.0 + +- Accept an optional exact label filter in `metric_data()` and `collect()`. + Samples without the selected label remain visible. + ## 1.2.0 - Accept an optional `error_metric_labels` map in `metric_data()` and diff --git a/README.md b/README.md index a887689..7bea2ec 100644 --- a/README.md +++ b/README.md @@ -271,6 +271,13 @@ metric on this call. An omitted or empty map emits the bare error metric. An invalid label map is logged and counted as an error, and the bare error metric is emitted. +The optional `options.label_filter = {name = "instance_id", value = "local-id"}` +keeps samples that have the given label value or do not have that label. The +value can be a string, number, or boolean. This filters the output for this +call, including labels supplied by `error_metric_labels`, without changing +stored samples. An invalid filter is logged and counted as an error, and the +output is left unfiltered. + ### counter:inc() **syntax:** counter:inc(*value*, *label_values*) diff --git a/dist.ini b/dist.ini index aedc8f6..64d6620 100644 --- a/dist.ini +++ b/dist.ini @@ -1,6 +1,6 @@ name = nginx-lua-prometheus-api7 abstract = Prometheus metric library for Nginx -version = 1.2.0 +version = 1.3.0 author = Anton Tolchanov is_original = no license = mit diff --git a/integration/index.lua b/integration/index.lua index 893ddb6..4b92b87 100644 --- a/integration/index.lua +++ b/integration/index.lua @@ -87,4 +87,13 @@ peer_removable:del() target:set(42) assert(table.concat(peer:metric_data()):find("\ntarget 42\n", 1, true), "public API omitted the returning metric") + +-- Reader and writer can register different metric families in the same dict. +local owned = p:gauge("writer_only", "Writer-only metric", {"instance_id"}) +owned:set(11, {"old"}) +owned:set(22, {"new"}) +local data = table.concat(peer:metric_data({label_filter = {name = "instance_id", value = "new"}})) +assert(data:find('writer_only{instance_id="new"} 22\n', 1, true)) +assert(not data:find('writer_only{instance_id="old"}', 1, true)) +assert(data:find("\ntail 1\n", 1, true)) ngx.say("ok") diff --git a/prometheus.lua b/prometheus.lua index 5da4441..1357839 100644 --- a/prometheus.lua +++ b/prometheus.lua @@ -958,6 +958,55 @@ local function error_metric_full_name(name, labels) return full_metric_name(name, names, values) end +local function compile_label_filter(filter) + if type(filter) ~= "table" or type(filter.name) ~= "string" then + return nil, "label_filter must specify a label name" + end + local value_type = type(filter.value) + if value_type ~= "string" and value_type ~= "number" and value_type ~= "boolean" then + return nil, "label_filter value must be a string, number, or boolean" + end + local err = check_metric_and_label_names("label_filter", {filter.name}) + if err then + return nil, err + end + local label = filter.name .. '="' + return { + name = filter.name, + first = "{" .. label, + next = "," .. label, + expected = full_metric_name("", {filter.name}, {filter.value}):sub(2, -2), + } +end + +local function matches_label_filter(key, filter) + if not key:find(filter.first, 1, true) and not key:find(filter.next, 1, true) then + return true + end + + -- A candidate can occur at the end of another label value. Walk fields from + -- the opening brace and skip escaped characters inside quoted values. + local start = key:find("{", 1, true) + 1 + while true do + local value_open = key:find('="', start, true) + if not value_open then + return true + end + if key:sub(start, value_open - 1) == filter.name then + return key:sub(start, start + #filter.expected - 1) == filter.expected + end + + local close = key:find('["\\]', value_open + 2) + while close and key:sub(close, close) == "\\" do + close = key:find('["\\]', close + 2) + end + if not close or key:sub(close + 1, close + 1) ~= "," then + return true + end + start = close + 2 + end +end + -- Prometheus compatible metric data as an array of strings. -- -- Returns: @@ -979,6 +1028,14 @@ function Prometheus:metric_data(options) error_name = name end end + local label_filter + if type(options) == "table" and options.label_filter ~= nil then + local err + label_filter, err = compile_label_filter(options.label_filter) + if err then + self:log_error(err) + end + end -- Force a manual sync of counter local state (mostly to make tests work). self._counter:sync() @@ -993,7 +1050,11 @@ function Prometheus:metric_data(options) for _, key in ipairs(keys) do yield() - local value, err = self.dict:get(key) + local value, err + if not label_filter or matches_label_filter( + key == self.error_metric_name and error_name or key, label_filter) then + value, err = self.dict:get(key) + end if value then local short_name = short_metric_name(key) if not seen_metrics[short_name] then diff --git a/prometheus_test.lua b/prometheus_test.lua index 853b6a9..0eb7320 100644 --- a/prometheus_test.lua +++ b/prometheus_test.lua @@ -289,6 +289,65 @@ function TestPrometheus:testInvalidErrorMetricLabels() end end +function TestPrometheus:testMetricDataLabelFilter() + local p = self.p + local requests = p:gauge("requests", "Requests", {"route", "instance_id"}) + local duration = p:histogram("duration", "Duration", {"instance_id"}, {0.1, 1}) + local other = p:gauge("other", "Other", {"remote_instance_id", "route"}) + p:gauge("unlabelled", "Unlabelled"):set(5) + p:gauge("retired", "Retired", {"instance_id"}):set(6, {"old"}) + + local current = 'new"\\\n' + requests:set(1, {"a", current}) + requests:set(2, {"a", current .. "suffix"}) + requests:set(3, {"a", "old"}) + duration:observe(0.5, {current}) + duration:observe(0.7, {"old"}) + other:set(4, {"old", 'request{instance_id="old",instance_id="old"'}) + p:log_error("test") + + local options = { + label_filter = {name = "instance_id", value = current}, + error_metric_labels = {instance_id = current}, + } + local output = table.concat(p:metric_data(options)) + local expected_label = 'instance_id="new\\"\\\\\\n"' + luaunit.assertStrContains(output, 'requests{route="a",' .. expected_label .. '} 1\n') + luaunit.assertStrContains(output, '# TYPE duration histogram\n') + luaunit.assertStrContains(output, 'duration_bucket{' .. expected_label .. ',le="+Inf"} 1\n') + luaunit.assertStrContains(output, 'duration_count{' .. expected_label .. '} 1\n') + luaunit.assertStrContains(output, 'duration_sum{' .. expected_label .. '} 0.5\n') + luaunit.assertNotStrContains(output, 'duration_bucket{instance_id="old"') + luaunit.assertNotStrContains(output, 'duration_count{instance_id="old"') + luaunit.assertNotStrContains(output, 'duration_sum{instance_id="old"') + luaunit.assertNotStrContains(output, 'suffix') + luaunit.assertNotStrContains(output, 'retired') + luaunit.assertStrContains(output, 'other{remote_instance_id="old",route=') + luaunit.assertStrContains(output, '\nunlabelled 5\n') + luaunit.assertStrContains(output, 'nginx_metric_errors_total{' .. expected_label .. '} 1\n') + + options.label_filter.value = "old" + output = table.concat(p:metric_data(options)) + luaunit.assertStrContains(output, 'requests{route="a",instance_id="old"} 3\n') + luaunit.assertNotStrContains(output, expected_label) + luaunit.assertNotStrContains(output, 'nginx_metric_errors_total') + luaunit.assertStrContains(table.concat(p:metric_data()), 'retired{instance_id="old"} 6\n') +end + +function TestPrometheus:testMetricDataLabelFilterUsesFieldBoundaries() + local p = self.p + p:gauge("without_instance", "Without instance", {"route"}):set(3, {"books,instance_id="}) + local gauge = p:gauge("with_instance", "With instance", {"route", "instance_id"}) + local route = 'books"\\,instance_id=' + gauge:set(5, {route, "local"}) + gauge:set(7, {route, "remote"}) + + local output = table.concat(p:metric_data({label_filter = {name = "instance_id", value = "local"}})) + luaunit.assertStrContains(output, 'without_instance{route="books,instance_id="} 3\n') + luaunit.assertStrContains(output, ',instance_id="local"} 5\n') + luaunit.assertNotStrContains(output, ',instance_id="remote"}') +end + function TestPrometheus:testInitWorker() self.dict = setmetatable({}, SimpleDict) ngx.shared.metrics = self.dict diff --git a/rockspec/nginx-lua-prometheus-api7-1.2.0-1.rockspec b/rockspec/nginx-lua-prometheus-api7-1.3.0-1.rockspec similarity index 94% rename from rockspec/nginx-lua-prometheus-api7-1.2.0-1.rockspec rename to rockspec/nginx-lua-prometheus-api7-1.3.0-1.rockspec index da83029..4818291 100644 --- a/rockspec/nginx-lua-prometheus-api7-1.2.0-1.rockspec +++ b/rockspec/nginx-lua-prometheus-api7-1.3.0-1.rockspec @@ -1,11 +1,11 @@ -- Note, this file must have version in its name -- (see https://github.com/knyar/nginx-lua-prometheus/issues/27) package = "nginx-lua-prometheus-api7" -version = "1.2.0-1" +version = "1.3.0-1" source = { url = "git+https://github.com/api7/nginx-lua-prometheus.git", - tag = "1.2.0", + tag = "1.3.0", } description = {