bzp2010 commented on code in PR #12383:
URL: https://github.com/apache/apisix/pull/12383#discussion_r2222074851
##########
apisix/plugins/prometheus.lua:
##########
@@ -55,4 +55,11 @@ function _M.api()
end
+function _M.init()
+ local local_conf = core.config.local_conf()
+ local enabled_in_stream = core.table.array_find(local_conf.stream_plugins,
"prometheus")
+ exporter.http_init(enabled_in_stream)
Review Comment:
### NOTE
The prometheus plugin, loaded by the http subsystem, will register http
metrics there, and will decide whether to register stream metrics (xrpc)
depending on whether the stream subsystem has been started.
This is mainly for metrics generation needs in privileged processes, stream
data is not really reported at any phase in the http subsystem.
##########
apisix/plugins/prometheus.lua:
##########
@@ -35,6 +34,7 @@ local _M = {
priority = 500,
name = plugin_name,
log = exporter.http_log,
+ destroy = exporter.destroy,
Review Comment:
### NOTE
This will always destroy the plugin (the prometheus instance in it) when
reloading it using the Admin API and loading it again based on the latest
configuration.
If a reload is performed after a plugin is removed from the profile list,
this plugin will not be restored again. Until the next reload.
Technically, `exporter.destroy` just backs up that instance of the
prometheus module and copies it to another variable.
This will cause the export API to stop working, at which point it will
always return a `{}`, which is consistent with the current behavior.
Under the hood, the timer will also stop working, no longer generating
metrics based on interval timing, and the metrics computation overhead
introduced by APISIX is completely eliminated.
When the next plugin reload occurs, if prometheus is re-enabled, the timer
will resume running.
Regarding the background timer introduced by the prometheus third-party
library, unfortunately, it never stops running.
It is registered with `ngx.timer.every` to perform the task of synchronizing
the shdict at regular intervals, and this overhead cannot be paused or resumed
by external intervention unless we fork and modify the library itself.
So this destruction does not mean that the prometheus instance is actually
destroyed, the synchronization timer is stopped, and the shdict is cleared.
none of this happens.
##########
t/cli/test_prometheus_run_in_privileged.sh:
##########
Review Comment:
### NOTE
The export API will no longer be exposed to privileged processes, which
provides isolation of HTTP traffic from root privileges for enhanced security.
Therefore this is no longer needed.
##########
t/plugin/prometheus.t:
##########
@@ -37,6 +37,14 @@ add_block_preprocessor(sub {
if (!defined $block->request) {
$block->set_value("request", "GET /t");
}
+
+ if (!defined $block->yaml_config) {
+ $block->set_value("yaml_config", <<'EOF');
+plugin_attr:
+ prometheus:
+ refresh_interval: 0.1
Review Comment:
### NOTE
We use smaller values when we need an extremely fast refresh.
You don't need to worry about timers being executed too often or
overlapping, if a metrics generation process doesn't complete, the next one
will never start.
##########
apisix/plugin.lua:
##########
@@ -356,15 +354,6 @@ function _M.load(config)
if not ok then
core.log.error("failed to load plugins: ", err)
end
-
- local enabled = core.table.array_find(http_plugin_names,
"prometheus") ~= nil
- local active = exporter.get_prometheus() ~= nil
- if not enabled then
- exporter.destroy()
- end
- if enabled and not active then
- exporter.http_init()
- end
Review Comment:
Add some description under this comment explaining why we removed it and
moved to init and destroy hooks.
##########
apisix/plugin.lua:
##########
@@ -808,18 +797,18 @@ do
end
-function _M.init_worker()
+function _M.init_prometheus()
local _, http_plugin_names, stream_plugin_names = get_plugin_names()
+ local enabled_in_http = core.table.array_find(http_plugin_names,
"prometheus")
+ local enabled_in_stream = core.table.array_find(stream_plugin_names,
"prometheus")
- -- some plugins need to be initialized in init* phases
- if is_http and core.table.array_find(http_plugin_names, "prometheus") then
- local prometheus_enabled_in_stream =
- core.table.array_find(stream_plugin_names, "prometheus")
-
require("apisix.plugins.prometheus.exporter").http_init(prometheus_enabled_in_stream)
- elseif not is_http and core.table.array_find(stream_plugin_names,
"prometheus") then
- require("apisix.plugins.prometheus.exporter").stream_init()
+ if is_http and (enabled_in_http or enabled_in_stream) then
Review Comment:
### NOTE
We will always only handle metrics generation in the http subsystem.
1. This will ensure that there is no duplication of execution on http and
stream to waste compute resources.
2. This simplifies the design.
3. Whether or not the user has http enabled (i.e., whether or not it is in
stream only mode), an http block for the Prometheus export API and its server
block (:9091) will always be present, otherwise Prometheus would be pointless.
This means that we can always have an http subsystem context for periodic
generation of timers and metrics anyway, even if we are currently in stream
only mode.
##########
apisix/cli/ngx_tpl.lua:
##########
@@ -100,18 +100,14 @@ http {
}
server {
- {% if use_apisix_base then %}
Review Comment:
The export API will no longer be exposed to privileged processes, which
provides isolation of HTTP traffic from root privileges for enhanced security.
Therefore this is no longer needed.
##########
apisix/plugins/prometheus/exporter.lua:
##########
@@ -498,10 +524,71 @@ local function collect(ctx, stream_only)
end
end
+ return core.table.concat(prometheus:metric_data())
+end
+
+
+local function exporter_timer(premature, yieldable)
+ if premature then
+ return
+ end
+
+ if not prometheus then
+ return
+ end
+
+ local refresh_interval = DEFAULT_REFRESH_INTERVAL
+ local attr = plugin.plugin_attr("prometheus")
+ if attr and attr.refresh_interval then
+ refresh_interval = attr.refresh_interval
+ end
+
+ ngx.timer.at(refresh_interval, exporter_timer, true)
+
+ if exporter_timer_running then
+ core.log.warn("Previous calculation still running, skipping")
+ return
+ end
+
+ exporter_timer_running = true
+
+ local ok, res = pcall(collect, yieldable)
+ if not ok then
+ core.log.error("Failed to collect metrics: ", res)
+ return
+ end
+ shdict_prometheus_cache:set(CACHED_METRICS_KEY, res)
+
+ exporter_timer_running = false
+end
+
+
+local function init_exporter_timer()
+ if process.type() ~= "privileged agent" then
+ return
+ end
+
+ exporter_timer(false, false)
+end
+_M.init_exporter_timer = init_exporter_timer
+
+
+local function get_cached_metrics()
+ if not prometheus or not metrics then
+ core.log.error("prometheus: plugin is not initialized, please make
sure ",
+ " 'prometheus_metrics' shared dict is present in nginx
template")
+ return 500, {message = "An unexpected error occurred"}
+ end
+
core.response.set_header("content_type", "text/plain")
- return 200, core.table.concat(prometheus:metric_data())
+ local cached_metrics_text = shdict_prometheus_cache:get(CACHED_METRICS_KEY)
+ if not cached_metrics_text then
+ core.log.error("Failed to retrieve cached metrics: data is nil")
+ return 500, "Failed to retrieve metrics: no data available"
Review Comment:
Is it more standard to return a JSON with reference to
https://github.com/apache/apisix/pull/12383/files#diff-390eaff60bfa1071dd1850bce9c7689452eaa13f07bf45a927921ecf05886d1bR580
?
##########
apisix/plugins/prometheus/exporter.lua:
##########
@@ -498,10 +524,71 @@ local function collect(ctx, stream_only)
end
end
+ return core.table.concat(prometheus:metric_data())
+end
+
+
+local function exporter_timer(premature, yieldable)
+ if premature then
+ return
+ end
+
+ if not prometheus then
Review Comment:
### NOTE
This is used for dynamic disable (by plugin reload API) of the plugin, i.e.
done in `exporter.destroy`.
This is where we stop if the prometheus instance is "destroyed", and as you
can see, this will happen before scheduling the next timer task, which means
the timer will stop.
Technically, this is the advantage of `ngx.timer.at` over `ngx.timer.every`,
every is not terminable, the developer can't get an "instance" of a timer to
pause or stop it.
But by using `ngx.timer.at`, we can precisely control whether or not to
continue scheduling the next timed task, which allows us to stop the timer. If
you need to resume it, just re-execute `ngx.timer.at(0)`.
##########
apisix/plugins/prometheus/exporter.lua:
##########
@@ -454,34 +477,37 @@ local function collect(ctx, stream_only)
local config = core.config.new()
-- config server status
- local vars = ngx.var or {}
- local hostname = vars.hostname or ""
+ local hostname = core.utils.gethostname() or ""
local version = core.version.VERSION or ""
+ local local_conf = core.config.local_conf()
+ local stream_only = local_conf.apisix.proxy_mode == "stream"
-- we can't get etcd index in metric server if only stream subsystem is
enabled
if config.type == "etcd" and not stream_only then
-- etcd modify index
etcd_modify_index()
- local version, err = config:server_version()
- if version then
- metrics.etcd_reachable:set(1)
+ if yieldable then
Review Comment:
### NOTE
Metrics contains the etcd reachability report and the etcd latest modified
index report, which relies on communication with etcd.
According to openresty's restrictions, yield is prohibited in the
`init_worker` phase, i.e. cosocket-based communication with etcd is not allowed.
So we skip a capture here until the timer does them.
##########
apisix/stream/plugins/prometheus.lua:
##########
@@ -35,6 +35,8 @@ local _M = {
priority = 500,
name = plugin_name,
log = exporter.stream_log,
+ destroy = exporter.destroy,
+ init = exporter.stream_init,
Review Comment:
### NOTE
Initialization in the stream subsystem is very pure, it just requires
unconditional registration of stream metrics and xrpc metrics. It doesn't need
to care if the http subsystem is enabled or not.
##########
apisix/plugins/prometheus.lua:
##########
@@ -55,4 +55,11 @@ function _M.api()
end
+function _M.init()
Review Comment:
### NOTE
We turned to using the built-in hooks of the plugin system, namely `init` to
initialize the prometheus instance and prometheus metrics registration.
Note, however, that data padding only occurs the first time the plugin is
started (it is usually when the worker is started, i.e. the `init_prometheus`
call in `init.lua http_init_worker`) and every timer.
This initialization just registers the metrics, but doesn't really populate
the data.
##########
apisix/plugins/prometheus/exporter.lua:
##########
@@ -498,10 +524,71 @@ local function collect(ctx, stream_only)
end
end
+ return core.table.concat(prometheus:metric_data())
+end
+
+
+local function exporter_timer(premature, yieldable)
+ if premature then
+ return
+ end
+
+ if not prometheus then
+ return
+ end
+
+ local refresh_interval = DEFAULT_REFRESH_INTERVAL
+ local attr = plugin.plugin_attr("prometheus")
+ if attr and attr.refresh_interval then
+ refresh_interval = attr.refresh_interval
+ end
+
+ ngx.timer.at(refresh_interval, exporter_timer, true)
+
+ if exporter_timer_running then
+ core.log.warn("Previous calculation still running, skipping")
+ return
+ end
+
+ exporter_timer_running = true
+
+ local ok, res = pcall(collect, yieldable)
+ if not ok then
+ core.log.error("Failed to collect metrics: ", res)
+ return
+ end
+ shdict_prometheus_cache:set(CACHED_METRICS_KEY, res)
+
+ exporter_timer_running = false
+end
+
+
+local function init_exporter_timer()
+ if process.type() ~= "privileged agent" then
+ return
+ end
+
+ exporter_timer(false, false)
Review Comment:
### NOTE
The initialization of the timer will perform an acquisition task
synchronously, i.e. the first acquisition will always occur in the init_worker
phase, which provides initial access to the metrics data.
If at any time , the metrics data (the string in the prometheus-cache
shdict) is not available, the API will report an error and log it. This is by
design not very likely to happen.
##########
apisix/plugins/prometheus/exporter.lua:
##########
@@ -211,6 +221,14 @@ end
function _M.stream_init()
+ -- FIXME:
+ -- Now the HTTP subsystem loads the stream plugin unintentionally, which
shouldn't happen.
+ -- It breaks the initialization logic of the plugin,
+ -- here it is temporarily fixed using a workaround.
+ if ngx.config.subsystem ~= "stream" then
+ return
+ end
Review Comment:
Please create an issue for this. thx
##########
apisix/plugins/prometheus/exporter.lua:
##########
@@ -530,16 +617,16 @@ end
_M.get_api = get_api
-function _M.export_metrics(stream_only)
+function _M.export_metrics()
if not prometheus then
- core.response.exit(200, "{}")
+ return core.response.exit(200, "{}")
Review Comment:
JFI, this behavior seems to be inconsistent with what is in
get_cached_metrics and we need to confirm which mode should be used. cc
@membphis
BTW, prometheus to nil will happen when the plugin is dynamically disabled.
##########
apisix/plugin.lua:
##########
@@ -808,18 +797,18 @@ do
end
-function _M.init_worker()
+function _M.init_prometheus()
local _, http_plugin_names, stream_plugin_names = get_plugin_names()
+ local enabled_in_http = core.table.array_find(http_plugin_names,
"prometheus")
+ local enabled_in_stream = core.table.array_find(stream_plugin_names,
"prometheus")
- -- some plugins need to be initialized in init* phases
- if is_http and core.table.array_find(http_plugin_names, "prometheus") then
- local prometheus_enabled_in_stream =
- core.table.array_find(stream_plugin_names, "prometheus")
-
require("apisix.plugins.prometheus.exporter").http_init(prometheus_enabled_in_stream)
- elseif not is_http and core.table.array_find(stream_plugin_names,
"prometheus") then
- require("apisix.plugins.prometheus.exporter").stream_init()
+ if is_http and (enabled_in_http or enabled_in_stream) then
Review Comment:
Please add some comments to the code to document the design intent.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]