2020年2月10日星期一

利用Lua实现基于延迟动态调整HAProxy服务器权重(weight),优先选择延迟低的服务器

将下面的Lua代码上传到路由器上,假设命名为dynamic_set_weight.lua。
local function calculate_weight(ping_value,eresp)
    -- from 1 to 256
    return math.ceil(256/math.exp(0.1*(ping_value+eresp)))+1
end
local function adjust_weight()
    while true do
        for _, backend in pairs(core.backends) do
            for _, server in pairs(backend.servers) do
                local stat = server:get_stats()
                if stat['check_desc'] == 'Layer4 check passed' and stat['bin'] > 1000 then
                    -- adjust weight based on the ping value and the number of eresp
                    server:set_weight(calculate_weight(stat['check_duration'],stat['eresp']))
                end
            end
        end
        core.msleep(10000) -- 10s
    end
end

core.register_task(adjust_weight)
假设上传的位置为/usr/bin,则在HAProxy的配置文件里,在global下添加一行
lua-load /usr/bin/dynamic_set_weight.lua
重启HAProxy(OpenWRT上的命令为/etc/init.d/haproxy restart),一段时间后效果如图所示:
HAProxy Statistics Report

可以看到权重已经根据延迟做了调整。调整每10s进行一次,可以修改core.msleep括号内的数字对运行间隔进行调整。