Serverless Functions
Serverless functions 由两个插件组成:serverless-pre-function 和 serverless-post-function。这些插件允许在函数挂钩的执行阶段的开始和结束时执行用户 定义的逻辑。
编写函数提示
Serverless 插件中只允许使用 Lua 函数,不允许使用其他 Lua 代码。
例如,匿名函数是合法的:
return function()
ngx.log(ngx.ERR, 'one')
end
闭包也是合法的:
local count = 1
return function()
count = count + 1
ngx.say(count)
end
但除函数以外的代码是非法的 :
local count = 1
ngx.say(count)
示例
以下示例演示了如何在不同场景下配置 serverless-pre-function 和 serverless-post-function 插件。
在阶段前后记录信息
以下示例演示了如何配置 serverless 插件以执行自定义逻辑,在 rewrite 阶段前后将信息记录到错误日志中。
创建一个路由如下:
- APISIX Admin API
- ADC
- Ingress Controller
curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"id": "serverless-pre-route",
"uri": "/anything",
"plugins": {
"serverless-pre-function": {
"phase": "rewrite",
"functions" : [
"return function()
ngx.log(ngx.ERR, \"serverless pre function\");
end"
]
},
"serverless-post-function": {
"phase": "rewrite",
"functions" : [
"return function(conf, ctx)
ngx.log(ngx.ERR, \"match uri \", ctx.curr_req_matched and ctx.curr_req_matched._path);
end"
]
}
},
"upstream": {
"type": "roundrobin",
"nodes": {
"httpbin.org:80": 1
}
}
}'
services:
- name: httpbin
routes:
- name: serverless-pre-route
uris:
- /anything
plugins:
serverless-pre-function:
phase: rewrite
functions:
- |
return function()
ngx.log(ngx.ERR, "serverless pre function")
end
serverless-post-function:
phase: rewrite
functions:
- |
return function(conf, ctx)
ngx.log(ngx.ERR, "match uri ", ctx.curr_req_matched and ctx.curr_req_matched._path)
end
upstream:
type: roundrobin
nodes:
- host: httpbin.org
port: 80
weight: 1
将配置同步到网关:
adc sync -f adc.yaml
- Gateway API
- APISIX CRD
apiVersion: v1
kind: Service
metadata:
namespace: aic
name: httpbin-external-domain
spec:
type: ExternalName
externalName: httpbin.org
---
apiVersion: apisix.apache.org/v1alpha1
kind: PluginConfig
metadata:
namespace: aic
name: serverless-functions-plugin-config
spec:
plugins:
- name: serverless-pre-function
config:
phase: rewrite
functions:
- |
return function()
ngx.log(ngx.ERR, "serverless pre function")
end
- name: serverless-post-function
config:
phase: rewrite
functions:
- |
return function(conf, ctx)
ngx.log(ngx.ERR, "match uri ", ctx.curr_req_matched and ctx.curr_req_matched._path)
end
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
namespace: aic
name: serverless-pre-route
spec:
parentRefs:
- name: apisix
rules:
- matches:
- path:
type: Exact
value: /anything
filters:
- type: ExtensionRef
extensionRef:
group: apisix.apache.org
kind: PluginConfig
name: serverless-functions-plugin-config
backendRefs:
- name: httpbin-external-domain
port: 80
apiVersion: apisix.apache.org/v2
kind: ApisixUpstream
metadata:
namespace: aic
name: httpbin-external-domain
spec:
ingressClassName: apisix
externalNodes:
- type: Domain
name: httpbin.org
---
apiVersion: apisix.apache.org/v2
kind: ApisixRoute
metadata:
namespace: aic
name: serverless-pre-route
spec:
ingressClassName: apisix
http:
- name: serverless-pre-route
match:
paths:
- /anything
upstreams:
- name: httpbin-external-domain
plugins:
- name: serverless-pre-function
config:
phase: rewrite
functions:
- |
return function()
ngx.log(ngx.ERR, "serverless pre function")
end
- name: serverless-post-function
config:
phase: rewrite
functions:
- |
return function(conf, ctx)
ngx.log(ngx.ERR, "match uri ", ctx.curr_req_matched and ctx.curr_req_matched._path)
end
应用配置:
kubectl apply -f serverless-functions-ic.yaml
❶ 将 serverless pre-function 逻辑挂钩到 rewrite 阶段。
❷ 定义一个 Lua 函数,在错误日志中记录一条 serverless pre function 消息。
❸ 将 serverless post-function 逻辑挂钩到 rewrite 阶段。
❹ 定义一个 Lua 函数,在错误日志中记录匹配的 URI。conf 和 ctx 可以像其他插件一样作为前两个参数传递,其中 conf 是插件配置,ctx 是请求上下文。
发送请求到路由:
curl -i "http://127.0.0.1:9080/anything"
你应该收到 HTTP/1.1 200 OK 响应,并在错误日志中看到以下条目:
2024/05/09 15:07:09 [error] 51#51: *3963 [lua] [string "return function() ngx.log(ngx.ERR, "serverles..."]:1: func(): serverless pre function, client: 172.21.0.1, server: _, request: "GET /anything HTTP/1.1", host: "127.0.0.1:9080"
2024/05/09 15:16:58 [error] 50#50: *9343 [lua] [string "return function(conf, ctx) ngx.log(ngx.ERR, "..."]:1: func(): match uri /anything, client: 172.21.0.1, server: _, request: "GET /anything HTTP/1.1", host: "127.0.0.1:9080"
第一个条目由 pre-function 添加,第二个条目由 post-function 添加。
注册自定义变量
以下示例使用 Serverless Function 注册自定义内置变量,并将其值添加到 Syslog 条目中。
由于 Ingress Controller 不支持配置路由标签,因此无法使用它完成此示例。
固定版本的 rsyslog Collector 镜像仅发布 amd64 版本。设置 正在运行的 APISIX 或 API7 网关容器名称:
export GATEWAY_CONTAINER=replace-with-gateway-container-name
创建专用网络:
docker network create gateway-rsyslog-net
将网关连接到该网络:
docker network connect gateway-rsyslog-net "$GATEWAY_CONTAINER"
启动已启用 TCP 接收的 Collector:
docker run -d \
--platform linux/amd64 \
--name rsyslog-collector \
--network gateway-rsyslog-net \
-e ENABLE_TCP=on \
-e ENABLE_UDP=off \
rsyslog/rsyslog-collector:2026-04
创建一个带有 serverless 函数的服务以注册自定义变量 a6_route_labels,启用日志插件以稍后记录自定义变量,并配置上游:
- APISIX Admin API
- ADC
curl "http://127.0.0.1:9180/apisix/admin/services" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"id": "srv_custom_var",
"plugins": {
"serverless-pre-function": {
"phase": "rewrite",
"functions": [
"return function() local core = require \"apisix.core\"; core.ctx.register_var(\"a6_route_labels\", function(ctx) local route = ctx.matched_route and ctx.matched_route.value; if route and route.labels then return route.labels end; return nil end) end"
]
},
"syslog": {
"host": "rsyslog-collector",
"port": 514,
"flush_limit": 1
}
},
"upstream": {
"nodes": {
"httpbin.org:80": 1
}
}
}'
services:
- name: srv-custom-var
labels:
docs-example: serverless-custom-variable
plugins:
serverless-pre-function:
phase: rewrite
functions:
- |
return function()
local core = require("apisix.core")
core.ctx.register_var("a6_route_labels", function(ctx)
local route = ctx.matched_route and ctx.matched_route.value
if route and route.labels then
return route.labels
end
return nil
end)
end
syslog:
host: rsyslog-collector
port: 514
flush_limit: 1
upstream:
nodes:
- host: httpbin.org
port: 80
weight: 1
预览带有示例标签的服务变更:
adc diff -f adc.yaml \
--include-resource-type service \
--label-selector docs-example=serverless-custom-variable
同步已审查的变更:
adc sync -f adc.yaml \
--include-resource-type service \
--label-selector docs-example=serverless-custom-variable
❶ functions: 注册一个自定义变量 a6_route_labels 并从匹配路由的 labels 属性中获取变量值。
❷ 配置网关可访问的 Collector 主机名和 TCP 端口。
❸ flush_limit: 设置为 1 以立即将日志推送到 syslog 服务器。
接下来,通过配置插件元数据,使用新变量更新所有 syslog 实例的日志格式:
- Admin API
- ADC
curl "http://127.0.0.1:9180/apisix/admin/plugin_metadata/syslog" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"log_format_extra": {
"host": "$host",
"client_ip": "$remote_addr",
"labels": "$a6_route_labels"
}
}'
插件元数据是全局集合,无法通过标签选择器隔离。修改该条目前,请先导出完整集合:
adc dump -o adc-metadata.yaml --with-id \
--include-resource-type plugin_metadata
在保留 adc-metadata.yaml 中所有其他条目的同时,添加或更新 syslog 条目:
plugin_metadata:
# 保留导出文件中的所有其他插件元数据条目。
syslog:
log_format_extra:
host: "$host"
client_ip: "$remote_addr"
labels: "$a6_route_labels"
预览完整的元数据变更,并确认其中没有非预期的更新或删除:
adc diff -f adc-metadata.yaml \
--include-resource-type plugin_metadata
同步已审查的插件元数据集合:
adc sync -f adc-metadata.yaml \
--include-resource-type plugin_metadata
❶ $host 和 $remote_addr:NGINX 变量。
❷ $a6_route_labels: 自定义变量。
最后,在服务中创建一个路由:
- APISIX Admin API
- ADC
curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"id": "route_custom_var",
"uri": "/get",
"service_id": "srv_custom_var",
"labels": {
"key": "test_a6_route_labels"
}
}'
更新 adc.yaml,在保留现有插 件和上游的同时为服务添加路由:
services:
- name: srv-custom-var
labels:
docs-example: serverless-custom-variable
plugins:
serverless-pre-function:
phase: rewrite
functions:
- |
return function()
local core = require("apisix.core")
core.ctx.register_var("a6_route_labels", function(ctx)
local route = ctx.matched_route and ctx.matched_route.value
if route and route.labels then
return route.labels
end
return nil
end)
end
syslog:
host: rsyslog-collector
port: 514
flush_limit: 1
routes:
- name: route-custom-var
uris:
- /get
labels:
key: test_a6_route_labels
upstream:
nodes:
- host: httpbin.org
port: 80
weight: 1
预览带有示例标签的服务变更:
adc diff -f adc.yaml \
--include-resource-type service \
--label-selector docs-example=serverless-custom-variable
同步已审查的变更:
adc sync -f adc.yaml \
--include-resource-type service \
--label-selector docs-example=serverless-custom-variable
❶ service_id: 对应之前创建的服务。
❷ labels: 要与自定义变量一起记录的路由信息。
在另一个终端中跟踪 Collector 日志:
docker exec rsyslog-collector tail -f /var/log/all.log
发送请求以验证变量注册:
curl "http://127.0.0.1:9080/get"
Collector 会为每行加上 Syslog 元数据前缀。JSON 消息应类似如下:
{
"host": "127.0.0.1",
"route_id": "route_custom_var",
"client_ip": "192.168.155.1",
"labels": {
"key": "test_a6_route_labels"
},
"service_id": "srv_custom_var"
}
使用 ADC 配置时,route_id 和 service_id 是生成的标识符,labels 还会包含服务所有权标签 docs-example: serverless-custom-variable。
这验证了自定义变量已注册,并且它成功记录了路由中的 labels 信息。
修改响应体中的特定字段
以下示例演示了如何使用 serverless 插件从 JSON 响应体中删除特定字段。
在进行删除之前,首先配置如下路由以查看未修改的响应:
- Admin API
- ADC
- Ingress Controller
curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"id":"serverless-remove-body-info",
"uri": "/get",
"upstream": {
"type": "roundrobin",
"nodes": {
"httpbin.org:80": 1
}
}
}'
services:
- name: httpbin
routes:
- name: serverless-remove-body-info
uris:
- /get
upstream:
type: roundrobin
nodes:
- host: httpbin.org
port: 80
weight: 1
将配置同步到网关:
adc sync -f adc.yaml
- Gateway API
- APISIX CRD
apiVersion: v1
kind: Service
metadata:
namespace: aic
name: httpbin-external-domain
spec:
type: ExternalName
externalName: httpbin.org
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
namespace: aic
name: serverless-remove-body-info
spec:
parentRefs:
- name: apisix
rules:
- matches:
- path:
type: Exact
value: /get
backendRefs:
- name: httpbin-external-domain
port: 80
apiVersion: apisix.apache.org/v2
kind: ApisixUpstream
metadata:
namespace: aic
name: httpbin-external-domain
spec:
ingressClassName: apisix
externalNodes:
- type: Domain
name: httpbin.org
---
apiVersion: apisix.apache.org/v2
kind: ApisixRoute
metadata:
namespace: aic
name: serverless-remove-body-info
spec:
ingressClassName: apisix
http:
- name: serverless-remove-body-info
match:
paths:
- /get
upstreams:
- name: httpbin-external-domain
应用配置:
kubectl apply -f serverless-remove-body-ic.yaml
发送请求到路由:
curl "http://127.0.0.1:9080/get"
你应该看到类似于以下的响应,其中包含你的主机和代理的 IP 信息:
{
"args": {},
"headers": {
"Accept": "*/*",
"Host": "127.0.0.1",
"User-Agent": "curl/8.4.0",
"X-Amzn-Trace-Id": "Root=1-663db30f-51448a1b635f2f4338a4fcfc",
"X-Forwarded-Host": "127.0.0.1"
},
"origin": "172.19.0.1, 43.252.208.84",
"url": "http://127.0.0.1/get"
}
要从响应中删除 origin 字段,请使用 serverless 插件更新路由:
- Admin API
- ADC
- Ingress Controller
curl "http://127.0.0.1:9180/apisix/admin/routes/serverless-remove-body-info" -X PATCH \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"plugins": {
"serverless-pre-function": {
"phase": "header_filter",
"functions" : [
"return function(conf, ctx)
local core = require(\"apisix.core\")
core.response.clear_header_as_body_modified()
end"
]
},
"serverless-post-function": {
"phase": "body_filter",
"functions" : [
"return function(conf, ctx)
local cjson = require(\"cjson\")
local core = require(\"apisix.core\")
local body = core.response.hold_body_chunk(ctx)
if not body then
return
end
body = cjson.decode(body)
body.origin = nil
body = cjson.encode(body)
ngx.arg[1] = body
end"
]
}
}
}'
services:
- name: httpbin
routes:
- name: serverless-remove-body-info
uris:
- /get
plugins:
serverless-pre-function:
phase: header_filter
functions:
- |
return function(conf, ctx)
local core = require("apisix.core")
core.response.clear_header_as_body_modified()
end
serverless-post-function:
phase: body_filter
functions:
- |
return function(conf, ctx)
local cjson = require("cjson")
local core = require("apisix.core")
local body = core.response.hold_body_chunk(ctx)
if not body then
return
end
body = cjson.decode(body)
body.origin = nil
body = cjson.encode(body)
ngx.arg[1] = body
end
upstream:
type: roundrobin
nodes:
- host: httpbin.org
port: 80
weight: 1
将配置同步到网关:
adc sync -f adc.yaml
- Gateway API
- APISIX CRD
# 其他配置
# ---
apiVersion: apisix.apache.org/v1alpha1
kind: PluginConfig
metadata:
namespace: aic
name: serverless-remove-body-plugin-config
spec:
plugins:
- name: serverless-pre-function
config:
phase: header_filter
functions:
- |
return function(conf, ctx)
local core = require("apisix.core")
core.response.clear_header_as_body_modified()
end
- name: serverless-post-function
config:
phase: body_filter
functions:
- |
return function(conf, ctx)
local cjson = require("cjson")
local core = require("apisix.core")
local body = core.response.hold_body_chunk(ctx)
if not body then
return
end
body = cjson.decode(body)
body.origin = nil
body = cjson.encode(body)
ngx.arg[1] = body
end
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
namespace: aic
name: serverless-remove-body-info
spec:
parentRefs:
- name: apisix
rules:
- matches:
- path:
type: Exact
value: /get
filters:
- type: ExtensionRef
extensionRef:
group: apisix.apache.org
kind: PluginConfig
name: serverless-remove-body-plugin-config
backendRefs:
- name: httpbin-external-domain
port: 80
# 其他配置
# ---
apiVersion: apisix.apache.org/v2
kind: ApisixRoute
metadata:
namespace: aic
name: serverless-remove-body-info
spec:
ingressClassName: apisix
http:
- name: serverless-remove-body-info
match:
paths:
- /get
upstreams:
- name: httpbin-external-domain
plugins:
- name: serverless-pre-function
config:
phase: header_filter
functions:
- |
return function(conf, ctx)
local core = require("apisix.core")
core.response.clear_header_as_body_modified()
end
- name: serverless-post-function
config:
phase: body_filter
functions:
- |
return function(conf, ctx)
local cjson = require("cjson")
local core = require("apisix.core")
local body = core.response.hold_body_chunk(ctx)
if not body then
return
end
body = cjson.decode(body)
body.origin = nil
body = cjson.encode(body)
ngx.arg[1] = body
end
应用配置:
kubectl apply -f serverless-remove-body-ic.yaml
❶ 在 header_filter 阶段执行 pre-function。
❷ 在 body_filter 阶段执行后置函数。
前置函数调用 clear_header_as_body_modified,以清除 Content-Length 等与响应体相关的响应头。后置函数使用 hold_body_chunk 收集响应体,解码 JSON 数据,移除 origin 字段,并将更新后的响应体写回响应。
再次发送请求到路由:
curl "http://127.0.0.1:9080/get"
你应该看到没有 origin 信息的响应:
{
"url":"http://127.0.0.1/get",
"args":{},
"headers":{
"X-Forwarded-Host":"127.0.0.1",
"Host":"127.0.0.1",
"Accept":"*/*",
"User-Agent":"curl/8.4.0",
"X-Amzn-Trace-Id":"Root=1-663db276-1c15276864294d963c6e1755"
}
}
对于更简单的响应修改,例如修改 HTTP 状态码、请求头或整个响应体,请使用 response-rewrite 插件。