fault-injection

IMPORTANT

abort 属性将直接返回给客户端指定的响应码并且终止其他插件的执行。

delay 属性将延迟某个请求,并且还会执行配置的其他插件。

abortdelay 属性至少要配置一个。

fault-injection - 图2tip

vars 是由 lua-resty-expr 的表达式组成的列表,它可以灵活的实现规则之间的 AND/OR 关系,示例如下::

你可以在指定路由启用 fault-injection 插件,并指定 abort 属性。如下所示:

  1. curl http://127.0.0.1:9180/apisix/admin/routes/1 \
  2. -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d '
  3. {
  4. "plugins": {
  5. "fault-injection": {
  6. "abort": {
  7. "http_status": 200,
  8. "body": "Fault Injection!"
  9. }
  10. }
  11. },
  12. "upstream": {
  13. "nodes": {
  14. "127.0.0.1:1980": 1
  15. },
  16. "type": "roundrobin"
  17. },
  18. "uri": "/hello"
  19. }'

同样,我们也可以指定 delay 属性。如下所示:

  1. curl http://127.0.0.1:9180/apisix/admin/routes/1 \
  2. -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d '
  3. {
  4. "plugins": {
  5. "fault-injection": {
  6. "delay": {
  7. "duration": 3
  8. }
  9. }
  10. },
  11. "upstream": {
  12. "nodes": {
  13. },
  14. },
  15. "uri": "/hello"
  16. }'

还可以同时为指定路由启用 fault-injection 插件,并指定 abort 属性和 delay 属性的 vars 规则。如下所示:

  1. curl http://127.0.0.1:9180/apisix/admin/routes/1 \
  2. -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d '
  3. {
  4. "plugins": {
  5. "fault-injection": {
  6. "abort": {
  7. "http_status": 403,
  8. "body": "Fault Injection!\n",
  9. "vars": [
  10. [
  11. [ "arg_name","==","jack" ]
  12. ]
  13. ]
  14. },
  15. "delay": {
  16. "duration": 2,
  17. "vars": [
  18. [
  19. [ "http_age","==","18" ]
  20. ]
  21. ]
  22. }
  23. }
  24. },
  25. "upstream": {
  26. "nodes": {
  27. "127.0.0.1:1980": 1
  28. },
  29. "type": "roundrobin"
  30. },
  31. "uri": "/hello"
  32. }'

通过上述示例启用插件后,可以向路由发起如下请求:

  1. HTTP/1.1 200 OK
  2. Date: Mon, 13 Jan 2020 13:50:04 GMT
  3. Transfer-Encoding: chunked
  4. Connection: keep-alive
  5. Fault Injection!
  1. time curl http://127.0.0.1:9080/hello -i
  1. HTTP/1.1 200 OK
  2. Content-Type: application/octet-stream
  3. Content-Length: 6
  4. Connection: keep-alive
  5. Server: APISIX web server
  6. Date: Tue, 14 Jan 2020 14:30:54 GMT
  7. Last-Modified: Sat, 11 Jan 2020 12:46:21 GMT
  8. hello
  9. real 0m3.034s
  10. user 0m0.007s
  11. sys 0m0.010s

你可以在 fault-injection 插件中使用 vars 规则设置特定规则:

使用不同的 name 参数测试路由:

  1. curl "http://127.0.0.1:9080/hello?name=allen" -i

没有故障注入的情况下,你可以得到如下结果:

  1. HTTP/1.1 200 OK
  2. Content-Type: application/octet-stream
  3. Transfer-Encoding: chunked
  4. Connection: keep-alive
  5. Date: Wed, 20 Jan 2021 07:21:57 GMT
  6. Server: APISIX/2.2
  7. hello

如果我们将 name 设置为与配置相匹配的名称,fault-injection 插件将被执行:

  1. curl "http://127.0.0.1:9080/hello?name=jack" -i
  1. curl http://127.0.0.1:9180/apisix/admin/routes/1 \
  2. -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d '
  3. {
  4. "uri": "/hello",
  5. "plugins": {},
  6. "upstream": {
  7. "type": "roundrobin",
  8. "nodes": {
  9. "127.0.0.1:1980": 1
  10. }