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/04/29 10:14:29 UTC

[GitHub] [apisix] spacewander commented on a diff in pull request #6968: feat: support hook response body for ext-plugin

spacewander commented on code in PR #6968:
URL: https://github.com/apache/apisix/pull/6968#discussion_r861664746


##########
apisix/plugins/ext-plugin-post-resp.lua:
##########
@@ -0,0 +1,103 @@
+--
+-- 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 ext = require("apisix.plugins.ext-plugin.init")
+local constants = require("apisix.constants")
+local http = require("resty.http")
+
+
+local name = "ext-plugin-post-resp"
+local _M = {
+    version = 0.1,
+    priority = -4000,
+    name = name,
+    schema = ext.schema,
+}
+
+
+local function get_response(ctx)
+    local httpc = http.new()
+    local ok, err = httpc:connect({
+        scheme = ctx.upstream_scheme,
+        host = ctx.picked_server.host,
+        port = ctx.picked_server.port,
+    })
+
+    if not ok then
+        return nil, err
+    end
+
+    local params = {
+        path = ctx.var.uri,

Review Comment:
   Should use upstream_uri



##########
conf/config-default.yaml:
##########
@@ -397,6 +397,7 @@ plugins:                          # plugin list (sorted by priority)
   - openwhisk                      # priority: -1901
   - serverless-post-function       # priority: -2000
   - ext-plugin-post-req            # priority: -3000
+  #- ext-plugin-post-resp          # priority: -4000

Review Comment:
   We can enable it by default?



##########
apisix/plugins/ext-plugin/init.lua:
##########
@@ -682,6 +683,96 @@ local rpc_handlers = {
 
         return true
     end,
+    nil,

Review Comment:
   Better to add a comment about the skipped key.



##########
apisix/plugins/ext-plugin-post-resp.lua:
##########
@@ -0,0 +1,103 @@
+--
+-- 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 ext = require("apisix.plugins.ext-plugin.init")
+local constants = require("apisix.constants")
+local http = require("resty.http")
+
+
+local name = "ext-plugin-post-resp"
+local _M = {
+    version = 0.1,
+    priority = -4000,
+    name = name,
+    schema = ext.schema,
+}
+
+
+local function get_response(ctx)
+    local httpc = http.new()
+    local ok, err = httpc:connect({
+        scheme = ctx.upstream_scheme,
+        host = ctx.picked_server.host,
+        port = ctx.picked_server.port,
+    })
+
+    if not ok then
+        return nil, err
+    end
+
+    local params = {
+        path = ctx.var.uri,
+        headers = core.request.headers(ctx),
+        method = core.request.get_method(ctx),
+    }
+
+    local body, err = core.request.get_body()
+    if err then
+        return nil, err
+    end
+
+    if body then
+        params["body"] = body
+    end
+
+    if ctx.var.is_args == "?" then
+        params["query"] = ctx.var.args or ""
+    end
+
+    local res, err = httpc:request(params)
+    if not res then
+        return nil, err
+    end
+    return res, err
+end
+
+
+function _M.check_schema(conf)
+    return core.schema.check(_M.schema, conf)
+end
+
+
+function _M.response(conf, ctx)
+     -- TODO: request
+     local res, err = get_response(ctx)
+    if not res or err then
+        core.log.error("failed to request: ", err or "")
+        return core.response.exit(503)
+    end
+    ctx.runner_ext_response = res
+
+    core.log.info("response info, status: ", res.status)
+     local headers = res.headers
+     local code, body = ext.communicate(conf, ctx, name, constants.RPC_HTTP_RESP_CALL)
+     if code or body then
+         -- TODO: chunk
+         return code, body
+     end
+     core.log.info("ext-plugin will send response")
+     -- send origin response
+     -- TODO: chunk
+     core.response.set_header(headers)

Review Comment:
   We should hide some headers like Nginx's proxy_hide_header directive?



##########
t/plugin/ext-plugin/response_body.t:
##########
@@ -0,0 +1,141 @@
+#
+# 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) = @_;
+
+    $block->set_value("stream_conf_enable", 1);
+
+    if (!defined $block->extra_stream_config) {
+        my $stream_config = <<_EOC_;
+    server {
+        listen unix:\$TEST_NGINX_HTML_DIR/nginx.sock;
+
+        content_by_lua_block {
+            local ext = require("lib.ext-plugin")
+            ext.go({})
+        }
+    }
+
+_EOC_
+        $block->set_value("extra_stream_config", $stream_config);
+    }
+
+    my $unix_socket_path = $ENV{"TEST_NGINX_HTML_DIR"} . "/nginx.sock";
+    my $cmd = $block->ext_plugin_cmd // "['sleep', '5s']";
+    my $extra_yaml_config = <<_EOC_;
+ext-plugin:
+    path_for_test: $unix_socket_path
+    cmd: $cmd
+plugins:
+    - ext-plugin-post-resp
+_EOC_
+
+    $block->set_value("extra_yaml_config", $extra_yaml_config);
+
+    if (!$block->request) {
+        $block->set_value("request", "GET /t");
+    }
+
+    if (!$block->error_log) {
+        $block->set_value("no_error_log", "[error]\n[alert]");
+    }
+});
+
+run_tests;
+
+__DATA__
+
+=== TEST 1: add route
+--- config
+    location /t {
+        content_by_lua_block {
+            local json = require("toolkit.json")
+            local t = require("lib.test_admin")
+
+            local code, message, res = t.test('/apisix/admin/routes/1',
+                ngx.HTTP_PUT,
+                 [[{
+                    "uri": "/hello",
+                    "plugins": {
+                        "ext-plugin-post-resp": {
+                        }
+                    },
+                    "upstream": {
+                        "nodes": {
+                            "127.0.0.1:1980": 1
+                        },
+                        "type": "roundrobin"
+                    }
+                }]]
+            )
+
+            if code >= 300 then
+                ngx.status = code
+                ngx.say(message)
+                return
+            end
+
+            ngx.say(message)
+        }
+    }
+--- response_body
+passed
+
+
+
+=== TEST 2: check input
+--- request
+GET /hello
+--- extra_stream_config
+    server {
+        listen unix:$TEST_NGINX_HTML_DIR/nginx.sock;
+
+        content_by_lua_block {
+            local ext = require("lib.ext-plugin")
+            ext.go({check_input = true})
+        }
+    }
+--- error_code: 200
+--- response_body
+hello world
+
+
+
+=== TEST 3: motify body

Review Comment:
   Need other test cases:
   1. modify header
   2. modify status
   3. upstream failed to response
   4. runner failed to response



##########
apisix/plugins/ext-plugin-post-resp.lua:
##########
@@ -0,0 +1,103 @@
+--
+-- 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 ext = require("apisix.plugins.ext-plugin.init")
+local constants = require("apisix.constants")
+local http = require("resty.http")
+
+
+local name = "ext-plugin-post-resp"
+local _M = {
+    version = 0.1,
+    priority = -4000,
+    name = name,
+    schema = ext.schema,
+}
+
+
+local function get_response(ctx)
+    local httpc = http.new()
+    local ok, err = httpc:connect({
+        scheme = ctx.upstream_scheme,
+        host = ctx.picked_server.host,
+        port = ctx.picked_server.port,
+    })
+
+    if not ok then
+        return nil, err
+    end
+
+    local params = {
+        path = ctx.var.uri,
+        headers = core.request.headers(ctx),
+        method = core.request.get_method(ctx),
+    }
+
+    local body, err = core.request.get_body()
+    if err then
+        return nil, err
+    end
+
+    if body then
+        params["body"] = body
+    end
+
+    if ctx.var.is_args == "?" then
+        params["query"] = ctx.var.args or ""
+    end
+
+    local res, err = httpc:request(params)
+    if not res then
+        return nil, err
+    end
+    return res, err
+end
+
+
+function _M.check_schema(conf)
+    return core.schema.check(_M.schema, conf)
+end
+
+
+function _M.response(conf, ctx)
+     -- TODO: request
+     local res, err = get_response(ctx)
+    if not res or err then
+        core.log.error("failed to request: ", err or "")
+        return core.response.exit(503)

Review Comment:
   Use 502 would be better?



##########
apisix/plugins/ext-plugin/init.lua:
##########
@@ -682,6 +683,96 @@ local rpc_handlers = {
 
         return true
     end,
+    nil,
+    function (conf, ctx, sock, entry)
+        local lrucache_id = core.lrucache.plugin_ctx_id(ctx, entry)
+        local token, err = core.lrucache.plugin_ctx(lrucache, ctx, entry, rpc_call,
+                                                    constants.RPC_PREPARE_CONF, conf, ctx,
+                                                    lrucache_id)
+        if not token then
+            return nil, err
+        end
+
+        builder:Clear()
+        local var = ctx.var
+
+        local res = ctx.runner_ext_response
+        local textEntries = {}
+        local hdrs = res.headers
+        for key, val in pairs(hdrs) do
+            local ty = type(val)
+            core.log.info("header: ", key, ": ", val)
+            if ty == "table" then
+                for _, v in ipairs(val) do
+                    core.table.insert(textEntries, build_headers(var, builder, key, v))
+                end
+            else
+                core.table.insert(textEntries, build_headers(var, builder, key, val))
+            end
+        end
+        local len = #textEntries
+        http_resp_call_req.StartHeadersVector(builder, len)
+        for i = len, 1, -1 do
+            builder:PrependUOffsetTRelative(textEntries[i])
+        end
+        local hdrs_vec = builder:EndVector(len)
+
+        local id = generate_id()
+        local status = res.status
+
+        http_resp_call_req.Start(builder)
+        http_resp_call_req.AddId(builder, id)
+        http_resp_call_req.AddStatus(builder, status)
+        http_resp_call_req.AddConfToken(builder, token)
+        http_resp_call_req.AddHeaders(builder, hdrs_vec)
+
+        local req = http_resp_call_req.End(builder)
+        builder:Finish(req)
+
+        local ok, err = send(sock, constants.RPC_HTTP_RESP_CALL, builder:Output())
+        if not ok then
+            return nil, "failed to send RPC_HTTP_RESP_CALL: " .. err
+        end
+
+        local ty, resp = receive(sock)
+        if ty == nil then
+            return nil, "failed to receive RPC_HTTP_RESP_CALL: " .. resp
+        end
+
+        if ty ~= constants.RPC_HTTP_RESP_CALL then
+            return nil, "failed to receive RPC_HTTP_RESP_CALL: unexpected type " .. ty
+        end
+
+        local buf = flatbuffers.binaryArray.New(resp)
+        local call_resp = http_resp_call_resp.GetRootAsResp(buf, 0)
+        local len = call_resp:HeadersLength()
+        if len > 0 then
+            local resp_headers = {}
+            for i = 1, len do
+                local entry = call_resp:Headers(i)
+                local name = str_lower(entry:Name())

Review Comment:
   We should exclude some headers like https://github.com/apache/apisix/blob/cc88a8db0ba64e1cb351e389ca5ec64c516073d6/apisix/plugins/ext-plugin/init.lua#L68?



-- 
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