serverless

Description

There are two serverless Plugins in APISIX: serverless-pre-function and serverless-post-function. The former runs at the beginning of the specified phase, while the latter runs at the end of the specified phase.

Both Plugins have the same attributes.

Attributes

NameTypeRequiredDefaultValid valuesDescription
phasestringFalse[“access”][“rewrite”, “access”, “header_filter”, “body_filter”, “log”, “before_proxy”]Phase before or after which the serverless function is executed.
functionsarray[string]TrueList of functions that are executed sequentially.
serverless - 图1IMPORTANT

Only Lua functions are allowed here and not other Lua code.

For example, anonymous functions are legal:

  1. return function()
  2. ngx.log(ngx.ERR, 'one')
  3. end

Closures are also legal:

  1. local count = 1
  2. return function()
  3. count = count + 1
  4. ngx.say(count)
  5. end

But code other than functions are illegal:

  1. local count = 1
  2. ngx.say(count)
serverless - 图2note

From v2.6, conf and ctx are passed as the first two arguments to a serverless function like regular Plugins.

Prior to v2.12.0, the phase before_proxy was called balancer. This was updated considering that this method would run after access and before the request goes Upstream and is unrelated to balancer.

Enable Plugin

The example below enables the Plugin on a specific Route:

serverless - 图3note

You can fetch the admin_key from config.yaml and save to an environment variable with the following command:

  1. admin_key=$(yq '.deployment.admin.admin_key[0].key' conf/config.yaml | sed 's/"//g')
  1. curl http://127.0.0.1:9180/apisix/admin/routes/1 -H "X-API-KEY: $admin_key" -X PUT -d '
  2. {
  3. "uri": "/index.html",
  4. "plugins": {
  5. "serverless-pre-function": {
  6. "phase": "rewrite",
  7. "functions" : ["return function() ngx.log(ngx.ERR, \"serverless pre function\"); end"]
  8. },
  9. "serverless-post-function": {
  10. "phase": "rewrite",
  11. "functions" : ["return function(conf, ctx) ngx.log(ngx.ERR, \"match uri \", ctx.curr_req_matched and ctx.curr_req_matched._path); end"]
  12. }
  13. },
  14. "upstream": {
  15. "type": "roundrobin",
  16. "nodes": {
  17. "127.0.0.1:1980": 1
  18. }
  19. }
  20. }'

Example usage

Once you have configured the Plugin as shown above, you can make a request as shown below:

  1. curl -i http://127.0.0.1:9080/index.html

You will find a message “serverless pre-function” and “match uri /index.html” in the error.log.

Delete Plugin

To remove the serverless Plugin, you can delete the corresponding JSON configuration from the Plugin configuration. APISIX will automatically reload and you do not have to restart for this to take effect.

  1. curl http://127.0.0.1:9180/apisix/admin/routes/1 -H "X-API-KEY: $admin_key" -X PUT -d '
  2. {
  3. "methods": ["GET"],
  4. "uri": "/index.html",
  5. "upstream": {
  6. "type": "roundrobin",
  7. "nodes": {
  8. "127.0.0.1:1980": 1
  9. }
  10. }
  11. }'