You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@apisix.apache.org by GitBox <gi...@apache.org> on 2022/01/28 02:06:09 UTC

[GitHub] [apisix] spacewander commented on a change in pull request #6215: feat: clickhouse logger

spacewander commented on a change in pull request #6215:
URL: https://github.com/apache/apisix/pull/6215#discussion_r794146392



##########
File path: docs/en/latest/plugins/clickhouse-logger.md
##########
@@ -0,0 +1,157 @@
+---
+title: clickhouse-logger
+---
+
+<!--
+#
+# 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.
+#
+-->
+
+## Summary
+
+- [**Name**](#name)
+- [**Attributes**](#attributes)
+- [**How To Enable**](#how-to-enable)
+- [**Test Plugin**](#test-plugin)
+- [**Metadata**](#metadata)
+- [**Disable Plugin**](#disable-plugin)
+
+## Name
+
+`clickhouse-logger` is a plugin which push Log data requests to clickhouse.
+
+## Attributes
+
+| 名称             | 类型    | 必选项  | 默认值         | 有效值  | 描述                                             |
+| ---------------- | ------- | ------ | ------------- | ------- | ------------------------------------------------ |
+| endpoint_addr    | string  | required   |               |         | The `clickhouse` endpoint.                  |
+| database         | string  | required   |               |         | The DB name to store log.                   |
+| logtable         | string  | required   |               |         | The table name.                             |
+| user             | string  | required   |               |         |clickhouse user.                             |
+| password         | string  | required   |               |         |clickhouse password.                         |
+| timeout          | integer | optional   | 3             | [1,...] | Time to keep the connection alive after sending a request.                   |
+| name             | string  | optional   | "clickhouse logger" |         | A unique identifier to identity the logger.                             |
+| batch_max_size   | integer | optional   | 100           | [1,...] | Set the maximum number of logs sent in each batch. When the number of logs reaches the set maximum, all logs will be automatically pushed to the clickhouse.  |
+| max_retry_count  | integer | optional   | 0             | [0,...] | Maximum number of retries before removing from the processing pipe line.        |
+| retry_delay      | integer | optional   | 1             | [0,...] | Number of seconds the process execution should be delayed if the execution fails.             |
+
+## How To Enable
+
+The following is an example of how to enable the `click-logger` for a specific route.

Review comment:
       ```suggestion
   The following is an example of how to enable the `clickhoush-logger` for a specific route.
   ```

##########
File path: apisix/plugins/clickhouse-logger.lua
##########
@@ -0,0 +1,231 @@
+--
+-- 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 batch_processor = require("apisix.utils.batch-processor")
+local log_util        = require("apisix.utils.log-util")
+local core            = require("apisix.core")
+local http            = require("resty.http")
+local url             = require("net.url")
+local plugin          = require("apisix.plugin")
+
+local ngx      = ngx
+local tostring = tostring
+local ipairs   = ipairs
+local timer_at = ngx.timer.at
+
+local plugin_name = "clickhouse-logger"
+local stale_timer_running = false
+local buffers = {}
+
+local schema = {
+    type = "object",
+    properties = {
+        endpoint_addr = core.schema.uri_def,
+        user = {type = "string", default = ""},
+        password = {type = "string", default = ""},
+        database = {type = "string", default = ""},
+        logtable = {type = "string", default = ""},
+        timeout = {type = "integer", minimum = 1, default = 3},
+        name = {type = "string", default = "clickhouse logger"},
+        max_retry_count = {type = "integer", minimum = 0, default = 0},
+        retry_delay = {type = "integer", minimum = 0, default = 1},
+        batch_max_size = {type = "integer", minimum = 1, default = 100}
+    },
+    required = {"endpoint_addr", "user", "password", "database", "logtable"}
+}
+
+
+local metadata_schema = {
+    type = "object",
+    properties = {
+        log_format = log_util.metadata_schema_log_format,
+    },
+}
+
+
+local _M = {
+    version = 0.1,
+    priority = 399,
+    name = plugin_name,
+    schema = schema,
+    metadata_schema = metadata_schema,
+}
+
+
+function _M.check_schema(conf, schema_type)
+    if schema_type == core.schema.TYPE_METADATA then
+        return core.schema.check(metadata_schema, conf)
+    end
+    return core.schema.check(schema, conf)
+end
+
+
+local function send_http_data(conf, log_message)
+    local err_msg
+    local res = true
+    local url_decoded = url.parse(conf.endpoint_addr)
+    local host = url_decoded.host
+    local port = url_decoded.port
+
+    core.log.info("sending a batch logs to ", conf.endpoint_addr)
+
+    if ((not port) and url_decoded.scheme == "https") then
+        port = 443
+    elseif not port then
+        port = 80
+    end
+
+    local httpc = http.new()
+    httpc:set_timeout(conf.timeout * 1000)
+    local ok, err = httpc:connect(host, port)
+
+    if not ok then
+        return false, "failed to connect to host[" .. host .. "] port["
+            .. tostring(port) .. "] " .. err
+    end
+
+    if url_decoded.scheme == "https" then
+        ok, err = httpc:ssl_handshake(true, host, false)
+        if not ok then
+            return false, "failed to perform SSL with host[" .. host .. "] "
+                .. "port[" .. tostring(port) .. "] " .. err
+        end
+    end
+    url_decoded.query['database'] = conf.database
+
+    local httpc_res, httpc_err = httpc:request({
+        method = "POST",
+        path = url_decoded.path,
+        query = url_decoded.query,
+        body = "INSERT INTO " .. conf.logtable .." FORMAT JSONEachRow " .. log_message,
+        headers = {
+            ["Host"] = url_decoded.host,
+            ["Content-Type"] = "application/json",
+            ["X-ClickHouse-User"] = conf.user,
+            ["X-ClickHouse-Key"] = conf.password,
+        }
+    })
+
+    if not httpc_res then
+        return false, "error while sending data to [" .. host .. "] port["
+            .. tostring(port) .. "] " .. httpc_err
+    end
+
+    -- some error occurred in the server
+    if httpc_res.status >= 400 then
+        res =  false
+        err_msg = "server returned status code[" .. httpc_res.status .. "] host["
+            .. host .. "] port[" .. tostring(port) .. "] "
+            .. "body[" .. httpc_res:read_body() .. "]"
+    end
+
+    return res, err_msg
+end
+
+
+-- remove stale objects from the memory after timer expires
+local function remove_stale_objects(premature)
+    if premature then
+        return
+    end
+
+    for key, batch in ipairs(buffers) do
+        if #batch.entry_buffer.entries == 0 and #batch.batch_to_process == 0 then
+            core.log.warn("removing batch processor stale object, conf: ",
+                          core.json.delay_encode(key))
+            buffers[key] = nil
+        end
+    end
+
+    stale_timer_running = false
+end
+
+
+function _M.log(conf, ctx)
+    local metadata = plugin.plugin_metadata("http-logger")
+    core.log.info("metadata: ", core.json.delay_encode(metadata))
+    local entry
+
+    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)
+    else
+        entry = log_util.get_full_log(ngx, conf)
+    end
+
+    if not entry.route_id then

Review comment:
       Could we remove this special logic for route_id? Actually, we want to remove it from http-logger if we can break the compatibility.

##########
File path: t/plugin/clickhouse-logger.t
##########
@@ -0,0 +1,194 @@
+#
+# 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();
+
+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: Full configuration verification
+--- config
+    location /t {
+        content_by_lua_block {
+            local plugin = require("apisix.plugins.clickhouse-logger")
+            local ok, err = plugin.check_schema({
+                "timeout": 3,
+                "retry_delay": 1,
+                "batch_max_size": 500,
+                "user": "default",
+                "password": "a",
+                "database": "default",
+                "logtable": "t",
+                "endpoint_addr": "http://127.0.0.1:8123",
+                "max_retry_count": 1,
+                "name": "clickhouse logger"
+            })
+
+            if not ok then
+                ngx.say(err)
+            else
+                ngx.say("passed")
+            end
+        }
+    }
+--- response_body
+passed
+
+
+
+=== TEST 2: Basic configuration verification
+--- config
+    location /t {
+        content_by_lua_block {
+            local plugin = require("apisix.plugins.clickhouse-logger")
+            local ok, err = plugin.check_schema({
+                "user": "default",
+                "password": "a",
+                "database": "default",
+                "logtable": "t",
+                "endpoint_addr": "http://127.0.0.1:8123"
+            })
+
+            if not ok then
+                ngx.say(err)
+            else
+                ngx.say("passed")
+            end
+        }
+    }
+--- response_body
+passed
+
+
+
+=== TEST 3: auth configure undefined
+--- config
+    location /t {
+        content_by_lua_block {
+            local plugin = require("apisix.plugins.clickhouse-logger")
+            local ok, err = plugin.check_schema({
+                log_id = "syslog",
+                max_retry_count = 0,
+                retry_delay = 1,
+                buffer_duration = 60,
+                inactive_timeout = 10,
+                batch_max_size = 100,
+            })
+            if not ok then
+                ngx.say(err)
+            else
+                ngx.say("passed")
+            end
+        }
+    }
+--- response_body
+value should match only one schema, but matches none
+
+
+
+=== TEST 4: add plugin on routes
+--- 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,
+                 [[{
+                        "plugins": {
+                            "clickhouse-logger": {
+                                "user": "default",
+                                "password": "a",
+                                "database": "default",
+                                "logtable": "t",
+                                "endpoint_addr": "http://127.0.0.1:8123"
+                            }
+                        },
+                        "upstream": {
+                            "nodes": {
+                                "127.0.0.1:1982": 1
+                            },
+                            "type": "roundrobin"
+                        },
+                        "uri": "/opentracing"
+                }]],
+                [[{
+                    "node": {
+                        "value": {
+                            "plugins": {
+                                "clickhouse-logger": {
+                                    "user": "default",
+                                    "password": "a",
+                                    "database": "default",
+                                    "logtable": "t",
+                                    "endpoint_addr": "http://127.0.0.1:8123"
+                                }
+                            },
+                            "upstream": {
+                                "nodes": {
+                                    "127.0.0.1:1982": 1
+                                },
+                                "type": "roundrobin"
+                            },
+                            "uri": "/opentracing"
+                        },
+                        "key": "/apisix/routes/1"
+                    },
+                    "action": "set"
+                }]]
+                )
+
+            if code >= 300 then
+                ngx.status = code
+            end
+            ngx.say(body)
+        }
+    }
+--- request
+GET /t
+--- response_body
+passed
+--- no_error_log
+[error]
+
+
+
+=== TEST 5: access local server
+--- request
+GET /opentracing
+--- response_body
+opentracing
+--- error_log
+Batch Processor[http logger] successfully processed the entries

Review comment:
       We need to use a mock server to check the upload data, like https://github.com/apache/apisix/blob/5f6d16041f64402eb2af2c8380d532e6238c8717/t/plugin/loggly.t#L42-L61




-- 
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: notifications-unsubscribe@apisix.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org