spacewander commented on code in PR #7643: URL: https://github.com/apache/apisix/pull/7643#discussion_r949823849
########## apisix/plugins/elasticsearch-logger.lua: ########## @@ -0,0 +1,166 @@ +-- +-- Licensed to the Apache Software Foundation (ASF) under one or more +-- contributor license agreements. See the NOTICE file distributed with +-- this work for additional information regarding copyright ownership. +-- The ASF licenses this file to You under the Apache License, Version 2.0 +-- (the "License"); you may not use this file except in compliance with +-- the License. You may obtain a copy of the License at +-- +-- http://www.apache.org/licenses/LICENSE-2.0 +-- +-- Unless required by applicable law or agreed to in writing, software +-- distributed under the License is distributed on an "AS IS" BASIS, +-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +-- See the License for the specific language governing permissions and +-- limitations under the License. +-- + +local core = require("apisix.core") +local http = require("resty.http") +local log_util = require("apisix.utils.log-util") +local bp_manager_mod = require("apisix.utils.batch-processor-manager") +local plugin = require("apisix.plugin") + +local ngx = ngx +local str_format = core.string.format +local str_byte = string.byte + +local plugin_name = "elasticsearch-logger" +local batch_processor_manager = bp_manager_mod.new(plugin_name) + + +local schema = { + type = "object", + properties = { + meta_format = { + type = "string", + default = "default", + enum = {"default", "origin"}, + }, + endpoint_addr = core.schema.uri_def, + field = { + type = "object", + properties = { + index = { type = "string"}, + type = { type = "string"} + }, + required = {"index"} + }, + auth = { + type = "object", + properties = { + username = { + type = "string", + }, + password = { + type = "string", + }, + }, + required = {"username", "password"}, + }, + timeout = { + type = "integer", + minimum = 1, + default = 10 + }, + ssl_verify = { + type = "boolean", + default = true + } + }, + required = { "endpoint_addr", "field" }, +} + + +local _M = { + version = 0.1, + priority = 413, + name = plugin_name, + schema = batch_processor_manager:wrap_schema(schema), +} + + +function _M.check_schema(conf) + return core.schema.check(schema, conf) +end + + +local function get_logger_entry(conf, ctx) + local entry + local metadata = plugin.plugin_metadata(plugin_name) + core.log.info("metadata: ", core.json.delay_encode(metadata)) + if metadata and metadata.value.log_format + and core.table.nkeys(metadata.value.log_format) > 0 + then + entry = log_util.get_custom_format_log(ctx, metadata.value.log_format) + core.log.info("custom log format entry: ", core.json.delay_encode(entry)) + else + entry = log_util.get_full_log(ngx, conf) + core.log.info("full log entry: ", core.json.delay_encode(entry)) + end + + return core.json.encode({ + create = { + _index = conf.field.index, + _type = conf.field.type + } + }) .. "\n" .. + core.json.encode(entry) .. "\n" +end + + +local function send_to_elasticsearch(conf, entries) + local httpc, err = http.new() + if not httpc then + return false, str_format("create http error: %s", err) + end + + local uri = conf.endpoint_addr .. + (str_byte(conf.endpoint_addr, -1) == str_byte("/") and "_bulk" or "/_bulk") + local body = core.table.concat(entries, "") + local headers = {["Content-Type"] = "application/json"} + if conf.auth and conf.auth.username and conf.auth.password then Review Comment: We don't need to check username & password as they are already checked by the schema. ########## t/plugin/elasticsearch-logger.t: ########## @@ -0,0 +1,301 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +use t::APISIX 'no_plan'; + +repeat_each(1); +no_long_string(); +no_root_location(); +no_shuffle(); + +add_block_preprocessor(sub { + my ($block) = @_; + + if ((!defined $block->error_log) && (!defined $block->no_error_log)) { + $block->set_value("no_error_log", "[error]"); + } + + if (!defined $block->request) { + $block->set_value("request", "GET /t"); + } + +}); + +run_tests(); + +__DATA__ + +=== TEST 1: sanity +--- config + location /t { + content_by_lua_block { + local ok, err + local configs = { + -- full configuration + { + endpoint_addr = "http://127.0.0.1:9200", + field = { + index = "services", + type = "collector" + }, + auth = { + username = "elastic", + password = "123456" + }, + ssl_verify = false, + timeout = 60, + max_retry_count = 0, + retry_delay = 1, + buffer_duration = 60, + inactive_timeout = 2, + batch_max_size = 10, + }, + -- minimize configuration + { + endpoint_addr = "http://127.0.0.1:9200", + field = { + index = "services" + } + }, + -- property "endpoint_addr" is required + { + field = { + index = "services" + } + }, + -- property "field" is required + { + endpoint_addr = "http://127.0.0.1:9200", + }, + -- property "index" is required + { + endpoint_addr = "http://127.0.0.1:9200", + field = {} + } + } + + local plugin = require("apisix.plugins.elasticsearch-logger") + for i = 1, #configs do + ok, err = plugin.check_schema(configs[i]) + if err then + ngx.say(err) + else + ngx.say("passed") + end + end + } + } +--- response_body_like +passed +passed +property "endpoint_addr" is required +property "field" is required +property "field" validation failed: property "index" is required + + + +=== TEST 2: set route +--- 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_addr = "http://127.0.0.1:9200", + field = { + index = "services" + }, + batch_max_size = 1, + inactive_timeout = 1 + } + } + }) + + if code >= 300 then + ngx.status = code + end + ngx.say(body) + } + } +--- response_body +passed + + + +=== TEST 3: test route (success write) +--- request +GET /hello +--- wait: 2 +--- response_body +hello world + + + +=== TEST 4: set route (auth) +--- 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_addr = "http://127.0.0.1:9201", + field = { + index = "services" + }, + auth = { + username = "elastic", + password = "123456" + }, + batch_max_size = 1, + inactive_timeout = 1 + } + } + }) + + if code >= 300 then + ngx.status = code + end + ngx.say(body) + } + } +--- response_body +passed + + + +=== TEST 5: test route (auth success) +--- request +GET /hello +--- wait: 2 +--- response_body +hello world + + + +=== TEST 6: set route (no auth) +--- 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_addr = "http://127.0.0.1:9201", + field = { + index = "services" + }, + batch_max_size = 1, + inactive_timeout = 1 + } + } + }) + + if code >= 300 then + ngx.status = code + end + ngx.say(body) + } + } +--- response_body +passed + + + +=== TEST 7: test route (no auth, failed) +--- request +GET /hello +--- wait: 2 +--- response_body +hello world +--- error_log +Batch Processor[elasticsearch-logger] failed to process entries +Batch Processor[elasticsearch-logger] exceeded the max_retry_count + + + +=== TEST 8: set route (error auth) +--- 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_addr = "http://127.0.0.1:9201", + field = { + index = "services" + }, + auth = { + username = "elastic", + password = "111111" + }, + batch_max_size = 1, + inactive_timeout = 1 + } + } + }) + + if code >= 300 then + ngx.status = code + end + ngx.say(body) + } + } +--- response_body +passed + + + +=== TEST 9: test route (error auth failed) +--- request +GET /hello +--- wait: 2 +--- response_body +hello world +--- error_log +Batch Processor[elasticsearch-logger] failed to process entries +Batch Processor[elasticsearch-logger] exceeded the max_retry_count Review Comment: Let's add a test that we check the log data with the custom log format from plugin metadata. ########## t/plugin/elasticsearch-logger.t: ########## @@ -0,0 +1,301 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +use t::APISIX 'no_plan'; + +repeat_each(1); +no_long_string(); +no_root_location(); +no_shuffle(); + +add_block_preprocessor(sub { + my ($block) = @_; + + if ((!defined $block->error_log) && (!defined $block->no_error_log)) { + $block->set_value("no_error_log", "[error]"); + } + + if (!defined $block->request) { + $block->set_value("request", "GET /t"); + } + +}); + +run_tests(); + +__DATA__ + +=== TEST 1: sanity +--- config + location /t { + content_by_lua_block { + local ok, err + local configs = { + -- full configuration + { + endpoint_addr = "http://127.0.0.1:9200", + field = { + index = "services", + type = "collector" + }, + auth = { + username = "elastic", + password = "123456" + }, + ssl_verify = false, + timeout = 60, + max_retry_count = 0, + retry_delay = 1, + buffer_duration = 60, + inactive_timeout = 2, + batch_max_size = 10, + }, + -- minimize configuration + { + endpoint_addr = "http://127.0.0.1:9200", + field = { + index = "services" + } + }, + -- property "endpoint_addr" is required + { + field = { + index = "services" + } + }, + -- property "field" is required + { + endpoint_addr = "http://127.0.0.1:9200", + }, + -- property "index" is required + { + endpoint_addr = "http://127.0.0.1:9200", + field = {} + } + } + + local plugin = require("apisix.plugins.elasticsearch-logger") + for i = 1, #configs do + ok, err = plugin.check_schema(configs[i]) + if err then + ngx.say(err) + else + ngx.say("passed") + end + end + } + } +--- response_body_like +passed +passed +property "endpoint_addr" is required +property "field" is required +property "field" validation failed: property "index" is required + + + +=== TEST 2: set route +--- 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_addr = "http://127.0.0.1:9200", + field = { + index = "services" + }, + batch_max_size = 1, + inactive_timeout = 1 + } + } + }) + + if code >= 300 then + ngx.status = code + end + ngx.say(body) + } + } +--- response_body +passed + + + +=== TEST 3: test route (success write) +--- request +GET /hello +--- wait: 2 +--- response_body +hello world Review Comment: We need to check the `Batch Processor[...] successfully processed the entries` log to make sure it is successfully written. We need to also verify the log data received by the stub server or via injected check. ########## apisix/plugins/elasticsearch-logger.lua: ########## @@ -0,0 +1,166 @@ +-- +-- Licensed to the Apache Software Foundation (ASF) under one or more +-- contributor license agreements. See the NOTICE file distributed with +-- this work for additional information regarding copyright ownership. +-- The ASF licenses this file to You under the Apache License, Version 2.0 +-- (the "License"); you may not use this file except in compliance with +-- the License. You may obtain a copy of the License at +-- +-- http://www.apache.org/licenses/LICENSE-2.0 +-- +-- Unless required by applicable law or agreed to in writing, software +-- distributed under the License is distributed on an "AS IS" BASIS, +-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +-- See the License for the specific language governing permissions and +-- limitations under the License. +-- + +local core = require("apisix.core") +local http = require("resty.http") +local log_util = require("apisix.utils.log-util") +local bp_manager_mod = require("apisix.utils.batch-processor-manager") +local plugin = require("apisix.plugin") + +local ngx = ngx +local str_format = core.string.format +local str_byte = string.byte + +local plugin_name = "elasticsearch-logger" +local batch_processor_manager = bp_manager_mod.new(plugin_name) + + +local schema = { + type = "object", + properties = { + meta_format = { + type = "string", + default = "default", + enum = {"default", "origin"}, + }, + endpoint_addr = core.schema.uri_def, + field = { + type = "object", + properties = { + index = { type = "string"}, + type = { type = "string"} + }, + required = {"index"} + }, + auth = { + type = "object", + properties = { + username = { + type = "string", + }, + password = { + type = "string", + }, + }, + required = {"username", "password"}, + }, + timeout = { + type = "integer", + minimum = 1, + default = 10 + }, + ssl_verify = { + type = "boolean", + default = true + } + }, + required = { "endpoint_addr", "field" }, +} + + +local _M = { + version = 0.1, + priority = 413, + name = plugin_name, + schema = batch_processor_manager:wrap_schema(schema), +} + + +function _M.check_schema(conf) + return core.schema.check(schema, conf) +end + + +local function get_logger_entry(conf, ctx) + local entry + local metadata = plugin.plugin_metadata(plugin_name) + core.log.info("metadata: ", core.json.delay_encode(metadata)) + if metadata and metadata.value.log_format + and core.table.nkeys(metadata.value.log_format) > 0 + then + entry = log_util.get_custom_format_log(ctx, metadata.value.log_format) + core.log.info("custom log format entry: ", core.json.delay_encode(entry)) + else + entry = log_util.get_full_log(ngx, conf) + core.log.info("full log entry: ", core.json.delay_encode(entry)) + end + + return core.json.encode({ + create = { + _index = conf.field.index, + _type = conf.field.type + } + }) .. "\n" .. + core.json.encode(entry) .. "\n" +end + + +local function send_to_elasticsearch(conf, entries) + local httpc, err = http.new() + if not httpc then + return false, str_format("create http error: %s", err) + end + + local uri = conf.endpoint_addr .. + (str_byte(conf.endpoint_addr, -1) == str_byte("/") and "_bulk" or "/_bulk") Review Comment: Look like we can require the endpoint_addr doesn't end with `/` in the schema. So that we don't need to check it in per-request manner. ########## docs/en/latest/plugins/elasticsearch-logger.md: ########## @@ -0,0 +1,206 @@ +--- +title: elasticsearch-logger +keywords: + - APISIX + - API Gateway + - Plugin + - Elasticsearch-logger +description: This document contains information about the Apache APISIX elasticsearch-logger Plugin. +--- + +<!-- +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +--> + +## Description + +The `elasticsearch-logger` Plugin is used to forward logs to [Elasticsearch](https://www.elastic.co/guide/en/welcome-to-elastic/current/getting-started-general-purpose.html) for analysis and storage. + +When the Plugin is enabled, APISIX will serialize the request context information to [Elasticsearch Bulk format](https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html#docs-bulk) and submit it to the batch queue. When the maximum batch size is exceeded, the data in the queue is pushed to Elasticsearch. See [batch processor](../batch-processor.md) for more details. + +## Attributes + +| Name | Required | Default | Description | +| ------------- | -------- | --------------------------- | ------------------------------------------------------------ | +| endpoint_addr | True | | Elasticsearch API | +| field | True | | Elasticsearch `field` configuration | +| field.index | True | | Elasticsearch [_index field](https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-index-field.html#mapping-index-field) | +| field.type | False | Elasticsearch default value | Elasticsearch [_type field](https://www.elastic.co/guide/en/elasticsearch/reference/7.17/mapping-type-field.html#mapping-type-field) | +| auth | False | | Elasticsearch [authentication](https://www.elastic.co/guide/en/elasticsearch/reference/current/setting-up-authentication.html) configuration | +| auth.username | False | | Elasticsearch [authentication](https://www.elastic.co/guide/en/elasticsearch/reference/current/setting-up-authentication.html) username | Review Comment: The username & password are required. -- 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]
