HaProxy 1.8 - 粘贴表格并将 haproxy 计算的速率作为请求标头传递到后端

HaProxy 1.8 - 粘贴表格并将 haproxy 计算的速率作为请求标头传递到后端

我读过这篇关于棍棒桌的文章:https://www.haproxy.com/blog/introduction-to-haproxy-stick-tables/

我想在我的 haproxy 配置中添加速率限制。但在添加硬限制之前,我想知道每个客户发出了多少请求,以便了解一个好的限制阈值是多少,并在将其添加为硬限制之前能够联系超过此限制的客户。

我的后端已准备好在自定义级别存储和记录这些类型的信息。我在步骤 1 中需要做的就是让 haproxy 传递以下值:

  • 每个 ip 的请求率(http_req_rate),描述每 X 时间的 http 请求数(用于防止 http 泛洪)
  • 每个 IP 的连接速率 ​​(conn_rate),描述新连接的数量(使用保持活动时,此数字将与 http_req_rate 不同)(用于防止 tcp syn flood)
  • 每个 IP 的当前连接数(conn_cur)(用于防止连接表耗尽)

我已制作以下配置来完成这项工作:

(global, listen, default and frontend sections not relevant)

// # round robin balancing between the various backends
backend app
  # Bind the 3 stick-tables counting to 3 slots named track-sc0, -sc1 and -sc2
  http-request track-sc0 src table sticktable_st_src_http_req_rate
  http-request track-sc1 src table sticktable_st_src_conn_cur
  http-request track-sc2 src table sticktable_st_src_conn_rate

  # Save current values in variables to be able to parse them on to backends
  http-request set-var(req.http_req_rate) sc_http_req_rate(0)
  http-request set-var(req.conn_cur) sc_conn_cur(1)
  http-request set-var(req.conn_rate) sc_conn_rate(2)

  # Finally copy the variables into request headers for the real backends to read the values
  http-request set-header X-HaProxy-http_req_rate %[var(req.http_req_rate)]
  http-request set-header X-HaProxy-conn_cur      %[var(req.conn_cur)]
  http-request set-header X-HaProxy-conn_rate     %[var(req.conn_rate)]

  ...
  server localtest 192.168.1.130:80 check

backend sticktable_st_src_http_req_rate
  stick-table type ip size 1m expire 10s store http_req_rate(10s)

backend sticktable_st_src_conn_cur
  stick-table type ip size 1m expire 10s store conn_cur

backend sticktable_st_src_conn_rate
  stick-table type ip size 1m expire 10s store conn_rate(10s)

尽管这确实能起到作用,但当有 3-5 个后端部分都需要这样做时,就会变得有点混乱。

另一件事是它看起来不太聪明,

1)定义三个后端 2)在 3 个跟踪命令中使用这三个后端 3)将它们复制到临时变量中(因为我不知道如何将它们直接解析为请求标头 4)在设置请求标头时引用临时变量。

是否可以以任何方式压缩或简化此配置以使其看起来更干燥?

HaProxy 版本 1.8

谢谢

答案1

如果您只是想查看 stick 表的值,您可以使用运行时 API(stat socket):https://www.haproxy.com/blog/dynamic-configuration-haproxy-runtime-api/并使用“show table < table-name >”命令。

关于您的配置:
1. 您不需要为每个计数器设置单独的 stick 表。您可以将所有计数器存储在同一个表中。2
. 您不需要使用中间变量

backend app
  # Enable counters tracking
  http-request track-sc0 src table sticktable_st_src_rates
  # Put counters in HTTP headers
  http-request set-header X-HaProxy-http_req_rate %[sc_http_req_rate(0)]
  http-request set-header X-HaProxy-conn_cur      %[sc_conn_cur(0)]
  http-request set-header X-HaProxy-conn_rate     %[sc_conn_rate(0)]

  ...
  server localtest 192.168.1.130:80 check

backend sticktable_st_src_rates
  stick-table type ip size 1m expire 10s store http_req_rate(10s),conn_cur,conn_rate(10s) 

相关内容