Haproxy Lua example

HAProxy is a powerful load balancer which can be used to Load Balance your Webservers, Database servers and many more. In Version 1.6 , Haproxy introduced Lua support. This feature allows user to write new features inside Haproxy without much knowledge about Haproxy internals or C language. We have already discussed this feature in another post here .

Please checkout this link to know how to build Haproxy with Lua support and few Haproxy-Lua examples

In this article we will see one simple Lua program embedded into Haproxy , this program displays the live haproxy configuration on your browser.

Let us see how the script works with Haproxy.  See the Haproxy configuration file contents below

 

global
daemon
log /dev/log local0
log /dev/log local1 notice
stats socket /var/run/haproxy/socket
server-state-file global
server-state-base /var/state/haproxy/
lua-load /mnt/haproxy/showconfig.lua
defaults
option dontlognull
listen stats
bind 0.0.0.0:9090
balance
mode http
stats enable
acl showconfig path /_showconfig
http-request use-service lua.showconfig if showconfig

  • Haproxy configuration  binds on server port number 9000 using mode http.
  • It defines a new acl named “showconfig” for the request URI “/_showconfig”
  • Any requests with the defined ACL will be processed using LUA.

The lua script, showconfig.lua has the following contents

function readfile(cmdline)
local found = false
local filename = ”
for s in string.gmatch(cmdline, ‘%g+’) do
if s == ‘-f’ then
found = true
elseif found then
filename = s
break
end
end
local f = io.open(filename, “rb”)
local config = f:read(“*all”)
f:close()
return config
end
function loadfile()
local f = io.open(‘/proc/self/cmdline’, “rb”)
local cmdline = f:read(“*all”)
f:close()
return readfile(cmdline)
end
core.register_init(function()
haproxyconfig = loadfile()
end)
core.register_service(“showconfig”, “http”, function(applet)
applet:set_status(200)
applet:add_header(“content-length”, string.len(haproxyconfig))
applet:add_header(“content-type”, “text/plain”)
applet:start_response()
applet:send(haproxyconfig)
end)

This lua application, reads the haproxy configuration file and print it to the HTTP response. Make sure you keep this file under the folder “/mnt/haproxy/” .

You can start haproxy using the following command

haproxy -f /etc/haproxy/haproxy.cfg -d

Once you started haproxy, you should be able to view the haproxy config file at the following URL

http://yourserverip:9090/_showconfig

You can watch the messages on the console, if you face any issue.

haproxy-with-lua

Feel free to contact me if you face any issue 🙂

One thought on “Haproxy Lua example

Leave a Reply

Your email address will not be published. Required fields are marked *