HAProxy Fails to Execute Lua Script Correctly and Cannot Detect Backend

0

I am attempting to implement a script to execute actions based on the state of my backend nodes. Below is the initial section of my lua script and also haproxy backend config

Despite these settings, I consistently receive the error message: “No backend associated with the transaction.”

I’ve tried changing the Lua invocation to the frontend and rearranging several lines, but the issue persists. As I’m relatively new to Lua, I would appreciate any guidance on what I might be missing.

-- haproxy.lua

-- Track the previous states of nodeA and nodeB
local previous_state_nodeA = "up"  -- initial state assumed to be up
local previous_state_nodeB = "backup"  -- initial state assumed to be backup

core.register_action("server_state_change", { "http-req", "tcp-req" }, function(txn)
    -- Verify if the transaction is linked to a backend
    if txn.b ~= nil then
        local be = txn.b
        local server = be:get_server(txn.sf:srv_name())
        local state = server:get_stats()["status"]

        if be.name == "mybackend" then
            if server.name == "nodeA" then
                -- Execute action if state change detected for nodeA
                check_and_trigger_action_nodeA(state)
            elseif server.name == "nodeB" then
                -- Execute action if state change detected for nodeB
                check_and_trigger_action_nodeB(state)
            end
        end
    else
        -- Log an error when no backend is associated with the transaction
        core.log(core.err, "No backend associated with the transaction")
    end
end)

Here are the details of my backend configuration:

backend mybackend
    mode http
    balance roundrobin
    http-request lua.server_state_change

    cookie Cookie prefix nocache
    default-server inter 3s fall 3 rise 2
    server nodeA nodea.example.net:80 check
    server nodeB nodeb.example.net:80 check backup