Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 74 additions & 13 deletions apisix/plugins/elasticsearch-logger.lua
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,21 @@ local bp_manager_mod = require("apisix.utils.batch-processor-manager")
local ngx = ngx
local ngx_re = ngx.re
local str_format = core.string.format
local math_min = math.min
local math_random = math.random
local os_date = os.date
local error = error
local pcall = pcall
local type = type
local pairs = pairs
local ipairs = ipairs

local ok_time, resty_time = pcall(require, "resty.core.time")
local monotonic_now = (ok_time and resty_time and resty_time.monotonic_time) or ngx.now

local PROBE_RETRY_BASE_DELAY = 1
local PROBE_RETRY_MAX_DELAY = 60

local plugin_name = "elasticsearch-logger"
local batch_processor_manager = bp_manager_mod.new(plugin_name)

Expand Down Expand Up @@ -157,7 +165,7 @@ end
local function get_es_major_version(uri, conf)
local httpc = http.new()
if not httpc then
return nil, "failed to create http client"
return nil, "failed to create http client", true
end

local headers = {}
Expand All @@ -181,25 +189,26 @@ local function get_es_major_version(uri, conf)
headers = headers,
})
if not res then
return false, err
return nil, err, true
end
if res.status ~= 200 then
local retryable = res.status == 408 or res.status == 429 or res.status >= 500
return nil, str_format("server returned status: %d, body: %s",
res.status, res.body or "")
res.status, res.body or ""), retryable
end
local json_body, err = core.json.decode(res.body)
if not json_body then
return nil, "failed to decode response body: " .. err
return nil, "failed to decode response body: " .. err, false
end
-- checked before use: a probe that raises would fail its batch, and the next one
local version = type(json_body) == "table" and json_body.version
if type(version) ~= "table" or type(version.number) ~= "string" then
return nil, "failed to get version from response body"
return nil, "failed to get version from response body", false
end

local major_version = version.number:match("^(%d+)%.")
if not major_version then
return nil, "invalid version format: " .. version.number
return nil, "invalid version format: " .. version.number, false
end

return major_version
Expand Down Expand Up @@ -257,32 +266,74 @@ end


-- conf._es_version is the major version of the cluster the conf sends to, or false once
-- its probe has failed. The version is probed from the batch timer, so that no request
-- waits for it. Batches sent before the first probe returns probe as well; after that,
-- a failed probe is not repeated: only Elasticsearch 5 and 6 need the version, while a
-- cluster that refuses GET / (it needs the `monitor` cluster privilege) would otherwise
-- cost a request and an error line for every batch.
-- its probe has failed permanently (or once a bulk write succeeded without `_type`).
-- The version is probed from the batch timer, so that no request waits for it. Batches
-- sent before the first probe returns probe as well; after a permanent failure (such as
-- 401/403 when credentials lack the `monitor` cluster privilege), the probe is not
-- repeated. After a transient failure (network error, timeout, 408, 429, or 5xx),
-- retries are rate-bounded with capped exponential backoff so Elasticsearch 5 and 6
-- clusters can recover once reachable without probing on every batch.
local function fetch_and_update_es_version(conf)
if conf._es_version ~= nil then
return
end

local probe = conf._es_version_probe
if probe then
if probe.in_flight or monotonic_now() < probe.next_probe_at then
return
end
probe.in_flight = true
end

local selected_endpoint_addr
if conf.endpoint_addr then
selected_endpoint_addr = conf.endpoint_addr
else
selected_endpoint_addr = conf.endpoint_addrs[math_random(#conf.endpoint_addrs)]
end
local major_version, err = get_es_major_version(selected_endpoint_addr, conf)
local ok, major_version, err, retryable = pcall(get_es_major_version,
selected_endpoint_addr, conf)
if probe then
probe.in_flight = false
end
if not ok then
error(major_version)
end
if err then
core.log.error("failed to get Elasticsearch version: ", err)
-- keep a version that a concurrent batch has got in the meantime
if conf._es_version == nil then
if conf._es_version ~= nil then
return
end

if not retryable then
set_runtime_state(conf, "_es_version", false)
if conf._es_version_probe ~= nil then
set_runtime_state(conf, "_es_version_probe", nil)
end
return
end

local state = conf._es_version_probe
if not state then
state = {
delay = PROBE_RETRY_BASE_DELAY,
next_probe_at = monotonic_now() + PROBE_RETRY_BASE_DELAY,
in_flight = false,
}
set_runtime_state(conf, "_es_version_probe", state)
elseif probe then
state.delay = math_min(state.delay * 2, PROBE_RETRY_MAX_DELAY)
state.next_probe_at = monotonic_now() + state.delay
end
return
end

set_runtime_state(conf, "_es_version", major_version)
if conf._es_version_probe ~= nil then
set_runtime_state(conf, "_es_version_probe", nil)
end
end


Expand Down Expand Up @@ -353,6 +404,16 @@ local function send_to_elasticsearch(conf, entries)
resp.status, resp.body or "")
end

if conf._es_version == nil and conf._es_version_probe ~= nil then
local resp_body = resp.body and core.json.decode(resp.body)
if not (type(resp_body) == "table" and resp_body.errors == true) then
-- The cluster accepted a bulk request without `_type`, so it does not
-- need Elasticsearch 5/6 handling; stop retrying failed version probes.
set_runtime_state(conf, "_es_version", false)
set_runtime_state(conf, "_es_version_probe", nil)
end
end

return true
end

Expand Down
201 changes: 201 additions & 0 deletions t/plugin/elasticsearch-logger2.t
Original file line number Diff line number Diff line change
Expand Up @@ -1107,3 +1107,204 @@ qr/init plugin-level conf version: \d+ while logging request, client: /]
failed to run log_by_lua
is not supported by JSON
failed to process entries



=== TEST 27: a route on Elasticsearch 6 whose first version probe fails transiently
--- config
location /t {
content_by_lua_block {
local t = require("lib.test_admin").test
local code, body = t('/apisix/admin/routes/1', ngx.HTTP_PUT, {
uri = "/hello",
upstream = {
type = "roundrobin",
nodes = {
["127.0.0.1:1980"] = 1
}
},
plugins = {
["elasticsearch-logger"] = {
endpoint_addrs = {"http://127.0.0.1:1984/es6-flaky"},
field = {
index = "services"
},
auth = {
username = "elastic",
password = "123456"
},
batch_max_size = 1,
}
}
})
if code >= 300 then
ngx.status = code
ngx.say(body)
return
end

ngx.say("passed")
}
}
--- response_body
passed



=== TEST 28: Elasticsearch 6 recovers after a transient version probe failure with bounded backoff
--- http_config
lua_shared_dict es_probe_test 1m;
--- config
location = /es6-flaky {
access_by_lua_block {
local dict = ngx.shared.es_probe_test
local n = dict:incr("es6_probes", 1, 0)
if n == 1 then
ngx.status = 503
ngx.say("temporarily unavailable")
return ngx.exit(ngx.HTTP_OK)
end
}
proxy_pass http://127.0.0.1:9501/;
}
location /es6-flaky/ {
proxy_pass http://127.0.0.1:9501/;
}
location /t {
content_by_lua_block {
local http = require("resty.http")
local uri = "http://127.0.0.1:" .. ngx.var.server_port .. "/hello"
local dict = ngx.shared.es_probe_test

-- 1st request: initial version probe gets 503, bulk fails on ES 6
local res, err = http.new():request_uri(uri)
if not res or res.status ~= 200 then
ngx.say("request 1 failed: ", err or res.status)
return
end
ngx.sleep(0.3)

-- 2nd request within backoff window: must not re-probe
res, err = http.new():request_uri(uri)
if not res or res.status ~= 200 then
ngx.say("request 2 failed: ", err or res.status)
return
end
ngx.sleep(0.3)
local probes_during_backoff = dict:get("es6_probes") or 0

-- Wait past the 1s base backoff, then 3rd request probes and succeeds
ngx.sleep(0.8)
res, err = http.new():request_uri(uri)
if not res or res.status ~= 200 then
ngx.say("request 3 failed: ", err or res.status)
return
end
ngx.sleep(1.0)

-- 4th request uses the cached major version without probing again
res, err = http.new():request_uri(uri)
if not res or res.status ~= 200 then
ngx.say("request 4 failed: ", err or res.status)
return
end
ngx.sleep(1.0)

ngx.say("probes_during_backoff: ", probes_during_backoff)
ngx.say("probes_total: ", dict:get("es6_probes") or 0)
}
}
--- response_body
probes_during_backoff: 1
probes_total: 2
--- grep_error_log eval
qr/failed to get Elasticsearch version|successfully processed the entries/
--- grep_error_log_out
failed to get Elasticsearch version
successfully processed the entries
successfully processed the entries
--- error_log
"_type":"_doc"
--- timeout: 12



=== TEST 29: a route on Elasticsearch 8 whose version probe always returns 503
--- config
location /t {
content_by_lua_block {
local t = require("lib.test_admin").test
local code, body = t('/apisix/admin/routes/1', ngx.HTTP_PUT, {
uri = "/hello",
upstream = {
type = "roundrobin",
nodes = {
["127.0.0.1:1980"] = 1
}
},
plugins = {
["elasticsearch-logger"] = {
endpoint_addrs = {"http://127.0.0.1:1984/es8-no-probe"},
field = {
index = "services"
},
batch_max_size = 1,
}
}
})
if code >= 300 then
ngx.status = code
ngx.say(body)
return
end

ngx.say("passed")
}
}
--- response_body
passed



=== TEST 30: Elasticsearch 8 stops retrying version probes once a bulk write succeeds
--- http_config
lua_shared_dict es_probe_test 1m;
--- config
location = /es8-no-probe {
content_by_lua_block {
local dict = ngx.shared.es_probe_test
dict:incr("es8_probes", 1, 0)
ngx.status = 503
ngx.say("probe blocked")
}
}
location /es8-no-probe/ {
proxy_pass http://127.0.0.1:9200/;
}
location /t {
content_by_lua_block {
local http = require("resty.http")
local uri = "http://127.0.0.1:" .. ngx.var.server_port .. "/hello"
local dict = ngx.shared.es_probe_test

for i = 1, 3 do
local res, err = http.new():request_uri(uri)
if not res or res.status ~= 200 then
ngx.say("request ", i, " failed: ", err or res.status)
return
end
ngx.sleep(1.2)
end
ngx.say("probes_total: ", dict:get("es8_probes") or 0)
}
}
--- response_body
probes_total: 1
--- grep_error_log eval
qr/failed to get Elasticsearch version|successfully processed the entries/
--- grep_error_log_out
failed to get Elasticsearch version
successfully processed the entries
successfully processed the entries
successfully processed the entries
--- timeout: 10
Loading