Skip to content

Commit

Permalink
fix(prometheus): reduce expensive gsub call, and table.insert NYI
Browse files Browse the repository at this point in the history
  • Loading branch information
oowl committed Jun 2, 2023
1 parent d5d49e2 commit d062459
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 7 deletions.
3 changes: 3 additions & 0 deletions kong/plugins/prometheus/exporter.lua
Expand Up @@ -6,6 +6,8 @@ local concat = table.concat
local ngx_timer_pending_count = ngx.timer.pending_count
local ngx_timer_running_count = ngx.timer.running_count
local balancer = require("kong.runloop.balancer")
local yield = require("kong.tools.utils").yield

local get_all_upstreams = balancer.get_all_upstreams
if not balancer.get_all_upstreams then -- API changed since after Kong 2.5
get_all_upstreams = require("kong.runloop.balancer.upstreams").get_all_upstreams
Expand Down Expand Up @@ -457,6 +459,7 @@ local function metric_data(write_fn)
-- upstream targets accessible?
local upstreams_dict = get_all_upstreams()
for key, upstream_id in pairs(upstreams_dict) do
yield()
local _, upstream_name = key:match("^([^:]*):(.-)$")
upstream_name = upstream_name and upstream_name or key
-- based on logic from kong.db.dao.targets
Expand Down
20 changes: 13 additions & 7 deletions kong/plugins/prometheus/prometheus.lua
Expand Up @@ -69,6 +69,7 @@ local tonumber = tonumber
local st_format = string.format
local table_sort = table.sort
local tb_clear = require("table.clear")
local tb_new = require("table.new")
local yield = require("kong.tools.utils").yield


Expand Down Expand Up @@ -176,24 +177,29 @@ local function full_metric_name(name, label_names, label_values)
if not label_names then
return name
end
local label_parts = {}
local label_parts = tb_new(#label_names, 0)
local label_value
for idx, key in ipairs(label_names) do
local label_value
if type(label_values[idx]) == "string" then
local valid, pos = validate_utf8_string(label_values[idx])
if not valid then
label_value = string.sub(label_values[idx], 1, pos - 1)
:gsub("\\", "\\\\")
:gsub('"', '\\"')
else
label_value = label_values[idx]
:gsub("\\", "\\\\")
:gsub('"', '\\"')
end
else
label_value = tostring(label_values[idx])
end
table.insert(label_parts, key .. '="' .. label_value .. '"')

if string.find(label_value, "\\") then
label_value = ngx.re.gsub(label_value, "\\", "\\\\", "j")
end

if string.find(label_value, '"') then
label_value = ngx.re.gsub(label_value, '"', '\\"', "j")
end

label_parts[idx] = table.concat({key, '="', label_value, '"'})
end
return name .. "{" .. table.concat(label_parts, ",") .. "}"
end
Expand Down

0 comments on commit d062459

Please sign in to comment.