HAPROXY-LUA(1)
💖 HAPROXY-LUA 💖
okay bestie, welcome to haproxy-lua — this is the official haproxy-lua Documentation, and yes it's a whole manual page, yes it's long, and yes we're getting through all of it together. grab a snack 🍓
✨ NAME ✨
haproxy-lua — haproxy-lua Documentation. that's it, that's the vibe. 💅
🌈 HAPROXY LUA RUNNING CONTEXTS 🌈
okok so the Lua code that runs inside HAProxy gets processed in 2 main modes. first one is initialisation mode, second one is runtime mode. two moods, two energies. 🦋
- In the initialisation mode, we CAN do DNS solves, but we CANNOT do socket I/O. and lowkey HAProxy is still blocked during the execution of the Lua program in this mode. 😭
- In the runtime mode, we CANNOT do DNS solves, but we CAN use sockets. the execution of the Lua code is multiplexed with the requests processing, so the Lua code seems to be run in blocking, but it is not the case. it's giving multitasking queen, fr fr. 👑
the Lua code is loaded in one or more files. these files contain main code and functions. Lua has 8 execution contexts. eight. a whole squad. 🫶
- The Lua file body context. it gets executed during the load of the Lua file in the HAProxy
[global]section with the directivelua-load. it runs in initialisation mode. this section is used for configuring Lua bindings in HAProxy. ✨ - The Lua init context. it's a Lua function executed just after the HAProxy configuration parsing. the execution is in initialisation mode. in this context the HAProxy environment is already initialized. super useful for checking config, or initializing socket connections or tasks. these functions get declared in the body context with the Lua function
core.register_init(). the prototype of the function is a simple function without return value and without parameters, like this:function fcn(). - The Lua task context. it's a Lua function executed after the start of the HAProxy scheduler, and just after the declaration of the task with the Lua function
core.register_task(). this context CAN be concurrent with the traffic processing. it runs in runtime mode. the prototype of the function is a simple function without return value and without parameters, like this:function fcn(). - The action context. it's a Lua function conditionally executed. these actions get registered by the Lua directives
"core.register_action()". the prototype of the Lua called function is a function which doesn't return anything and that takes an object of class TXN as entry:function fcn(txn). - The sample-fetch context. this function takes a TXN object as entry argument and returns a string. these types of function CANNOT execute any blocking function. they're useful for aggregating some of the original HAProxy sample-fetches and returning the result. the prototype of the function is
function string fcn(txn). these functions can be registered with the Lua functioncore.register_fetches(). each declared sample-fetch is prefixed by the string"lua.". 💫
Note: it is possible that this function cannot find the required data in the original HAProxy sample-fetches, and in this case, it cannot return the result. this case is not yet supported. 🙈
- The converter context. it's a Lua function that takes a string as input and returns another string as output. these types of function are stateless, it cannot access any context. they don't execute any blocking function. the call prototype is
function string fcn(string). this function can be registered with the Lua functioncore.register_converters(). each declared converter is prefixed by the string"lua.". - The filter context: it's a Lua object based on a class defining filter callback functions. Lua filters are registered using
core.register_filter(). each declared filter is prefixed by the string"lua.". - The event context: inside a function that handles events subscribed through
core.event_sub()orServer.event_sub().
🎀 HAPROXY LUA HELLO WORLD 🎀
iconic classic. the hello world. let's gooo 🌸
HAProxy configuration file (hello_world.conf):
global
lua-load hello_world.lua
listen proxy
bind 127.0.0.1:10001
tcp-request inspect-delay 1s
tcp-request content use-service lua.hello_world
HAProxy Lua file (hello_world.lua):
core.register_service("hello_world", "tcp", function(applet)
applet:send("hello world\n")
end)
how to start HAProxy for testing this configuration:
./haproxy -f hello_world.conf
on another terminal, you can test with telnet:
#:~ telnet 127.0.0.1 10001
hello world
slay. it literally said hello world back to you. 🥹✨
💜 USAGE OF LOAD PARAMETERS 💜
HAProxy lua-load(-per-thread) directives allow a list of parameters after the lua file name. these parameters are accessible through an array of args using this code local args = table.pack(...) in the body of the loaded file. cute right? 🎀
below, a new version of the hello world using load parameters. a glow-up, honestly. 💅
HAProxy configuration file (hello_world.conf):
global
lua-load hello_world.lua "this is not an hello world"
listen proxy
bind 127.0.0.1:10001
tcp-request inspect-delay 1s
tcp-request content use-service lua.hello_world
HAProxy Lua file (hello_world.lua):
local args = table.pack(...)
core.register_service("hello_world", "tcp", function(applet)
applet:send(args[1] .. "\n")
end)
👑 class core() 👑
the "core" class contains all the HAProxy core functions. these functions are useful for controlling the execution flow, registering hooks, manipulating global maps or ACL, ... basically the whole control room. 🔥
"core" class is basically provided with HAProxy. no require line is required to use these functions.
the "core" class is static, it is not possible to create a new object of this type. no clones, no copies, one of one. 💀
core.silent
Returns integer
this attribute is an integer, it contains the value -1. it's a special value used to disable logging. shhh. 🤫
core.emerg
Returns integer
this attribute is an integer, it contains the value of the loglevel "emergency" (0).
core.alert
Returns integer
this attribute is an integer, it contains the value of the loglevel "alert" (1).
core.crit
Returns integer
this attribute is an integer, it contains the value of the loglevel "critical" (2).
core.err
Returns integer
this attribute is an integer, it contains the value of the loglevel "error" (3).
core.warning
Returns integer
this attribute is an integer, it contains the value of the loglevel "warning" (4).
core.notice
Returns integer
this attribute is an integer, it contains the value of the loglevel "notice" (5).
core.info
Returns integer
this attribute is an integer, it contains the value of the loglevel "info" (6).
core.debug
Returns integer
this attribute is an integer, it contains the value of the loglevel "debug" (7).
core.proxies
context: init, task, action, sample-fetch, converter
this attribute is a table of declared proxies (frontend and backends). each proxy gives access to its list of listeners and servers. the table is indexed by proxy name, and each entry is of type Proxy class. 💖
Warning: if you declared a frontend and backend with the same name, only one of them will be listed. awkward 😭
See core.backends
See core.frontends
core.backends
context: init, task, action, sample-fetch, converter
this attribute is a table of declared proxies with backend capability. each proxy gives access to its list of listeners and servers. the table is indexed by the backend name, and each entry is of type Proxy class.
See core.proxies
See core.frontends
core.frontends
context: init, task, action, sample-fetch, converter
this attribute is a table of declared proxies with frontend capability. each proxy gives access to its list of listeners and servers. the table is indexed by the frontend name, and each entry is of type Proxy class.
See core.proxies
See core.backends
core.thread
context: task, action, sample-fetch, converter, applet
this variable contains the executing thread number starting at 1. 0 is a special case for the common lua context. so, if thread is 0, the Lua scope is shared by all threads, otherwise the scope is dedicated to a single thread. a program which needs to execute some parts exactly once regardless of the number of threads can check that core.thread is 0 or 1. 🧠✨
core.log(loglevel, msg)
context: body, init, task, action, sample-fetch, converter
this function sends a log. the log is sent, according with the HAProxy configuration file, to the loggers relevant to the current context and/or to stderr if it is allowed. 🗣️
the exact behaviour depends on tune.lua.log.loggers and tune.lua.log.stderr.
Arguments
- loglevel (integer) — is the log level associated with the message. it is a number between
0and7. - msg (string) — the log content.
See core.emerg, core.alert, core.crit, core.err, core.warning, core.notice, core.info, core.debug (log level definitions)
See core.Debug()
See core.Info()
See core.Warning()
See core.Alert()
core.Debug(msg)
context: body, init, task, action, sample-fetch, converter
Arguments
- msg (string) — the log content.
See core.log()
does the same job than:
function Debug(msg)
core.log(core.debug, msg)
end
core.Info(msg)
context: body, init, task, action, sample-fetch, converter
Arguments
- msg (string) — the log content.
See core.log()
function Info(msg)
core.log(core.info, msg)
end
core.Warning(msg)
context: body, init, task, action, sample-fetch, converter
Arguments
- msg (string) — the log content.
See core.log()
function Warning(msg)
core.log(core.warning, msg)
end
core.Alert(msg)
context: body, init, task, action, sample-fetch, converter
Arguments
- msg (string) — the log content.
...and honestly the same vibe applies to the sibling log helpers, iykyk:
function Alert(msg)
core.log(core.alert, msg)
end
See core.log().
💅 core.get_patref(name)
context: init, task, action, sample-fetch, converter
Bestie, this one snags the pattern object that HAProxy goes by. It's the generic pattern reference, which is the thing that handles both ACLs and Maps 👑
Arguments
- name (string) — the reference name
Returns
A Patref class object. slay.
🎀 core.add_acl(name, key)
LEGACY
context: init, task, action, sample-fetch, converter
Adds the ACL key into the ACLs list that's referenced by name.
Arguments
- name (string) — the name that references the ACL entries.
- key (string) — the key that's gonna get added.
Note: This function is not optimal because of systematic Map reference lookup 😭 use Patref.add() instead, fr fr.
🌸 core.del_acl(name, key)
LEGACY
context: init, task, action, sample-fetch, converter
Deletes the ACL entry referenced by the key key in the list of ACLs referenced by name.
Arguments
- name (string) — the name that references the ACL entries.
- key (string) — the key that's getting deleted.
Note: Again — not optimal, all that systematic Map reference lookup 💀 use Patref.del() instead.
🦋 core.del_map(name, key)
LEGACY
context: init, task, action, sample-fetch, converter
Deletes the map entry indexed with the specified key in the list of maps referenced by its name.
Arguments
- name (string) — the name that references the map entries.
- key (string) — the key that's getting deleted.
Note: You already know — not optimal because of the systematic Map reference lookup 🙈 use Patref.del() instead.
✨ core.get_info()
context: body, init, task, action, sample-fetch, converter
Hands you back HAProxy core info 🫶 the good stuff: uptime, the pid, memory pool usage, tasks number, all of it.
This same info also comes out of the management socket via the command "show info". Peep the management socket documentation if you wanna know more about what's inside these variables.
Returns
an array of values.
💜 core.get_var()
context: body, init, task, action, sample-fetch, converter
Returns data stored in the variable <var> converter in Lua type. Heads up: this is limited to "proc." scoped variables only, no cap.
Arguments
- var (string) — the variable name in
"proc."scope, according with the HAProxy variable syntax.
🌈 core.now()
context: body, init, task, action
Returns the current time, periodt ⏰ The time returned is fixed by the HAProxy core and assures that the hour will be monotonic, and that the system call 'gettimeofday' won't get called too. The time gets refreshed between each Lua execution or resume — so two consecutive calls to "now" will probably return the same result 👀
Returns
a table with two entries, "sec" and "usec". "sec" holds the current time in epoch format, and "usec" holds the current microseconds.
🍓 core.http_date(date)
context: body, init, task, action
Takes a string representing an http date, and returns an integer with the corresponding date in epoch format. A valid http date has to respect the format IMF, RFC850 or ASCTIME, bestie.
Arguments
- date (string) — a date, http-date formatted
Returns
integer containing epoch date
See core.imf_date().
See core.rfc850_date().
See core.asctime_date().
See https://tools.ietf.org/html/rfc7231#section-7.1.1.1
🧚 core.imf_date(date)
context: body, init, task, action
Takes a string representing an IMF date, and returns an integer with the corresponding date in epoch format.
Arguments
- date (string) — a date, IMF formatted
Returns
integer containing epoch date
See https://tools.ietf.org/html/rfc7231#section-7.1.1.1
The IMF format is giving:
Sun, 06 Nov 1994 08:49:37 GMT
👑 core.rfc850_date(date)
context: body, init, task, action
Takes a string representing an RFC850 date, and returns an integer with the corresponding date in epoch format.
Arguments
- date (string) — a date, RFC859 formatted
Returns
integer containing epoch date
See https://tools.ietf.org/html/rfc7231#section-7.1.1.1
The RFC850 format is giving:
Sunday, 06-Nov-94 08:49:37 GMT
🔥 core.asctime_date(date)
context: body, init, task, action
Takes a string representing an ASCTIME date, and returns an integer with the corresponding date in epoch format.
Arguments
- date (string) — a date, ASCTIME formatted
Returns
integer containing epoch date
See https://tools.ietf.org/html/rfc7231#section-7.1.1.1
The ASCTIME format is giving:
Sun Nov 6 08:49:37 1994
😴 core.msleep(milliseconds)
context: task, action
core.msleep() stops the Lua execution for the specified number of milliseconds ✋ like a lil nap for your code.
Arguments
- milliseconds (integer) — the required milliseconds.
🎬 core.register_action(name, actions, func[, nb_args])
context: body
Registers a Lua function that gets executed as an action. Every registered action can be used in HAProxy with the prefix "lua.". An action gets a TXN object class as input, main character energy only 💅
Arguments
- name (string) — is the name of the action.
- actions (table) — is a table of string describing the HAProxy actions facilities where to expose the new action. Expected facilities are:
'tcp-req','tcp-res','http-req','http-res','http-after-res'. - func (function) — is the Lua function called to work as an action.
- nb_args (integer) — is the expected number of argument for the action. By default the value is
0.
The prototype of the Lua function used as argument is:
function(txn [, arg1 [, arg2]])
txn(TXN class): this is a TXN object used for manipulating the current request or TCP stream.argX: this is argument provided through the HAProxy configuration file.
Here, an example of action registration. The action just send an 'Hello world' in the logs. 📝
core.register_action("hello-world", { "tcp-req", "http-req" }, function(txn)
txn:Info("Hello world")
end)
This example code is used in HAProxy configuration like this:
frontend tcp_frt
mode tcp
tcp-request content lua.hello-world
frontend http_frt
mode http
http-request lua.hello-world
A second example using arguments:
function hello_world(txn, arg)
txn:Info("Hello world for " .. arg)
end
core.register_action("hello-world", { "tcp-req", "http-req" }, hello_world, 2)
This example code is used in HAProxy configuration like this:
frontend tcp_frt
mode tcp
tcp-request content lua.hello-world everybody
🔄 core.register_converters(name, func)
context: body
Registers a Lua function that gets executed as a converter. Every registered converter can be used in HAProxy with the prefix "lua.". A converter gets a string as input and returns a string as output. The registered function can take up to 9 values as parameter, and all the values are strings, bestie.
Arguments
- name (string) — is the name of the converter.
- func (function) — is the Lua function called to work as converter.
The prototype of the Lua function used as argument is:
function(str, [p1 [, p2 [, ... [, p5]]]])
str(string): this is the input value automatically converted in string.p1 .. p5(string): this is a list of string arguments declared in the HAProxy configuration file. The number of arguments doesn't exceed 5. The order and the nature of these is conventionally chosen by the developer.
🎣 core.register_fetches(name, func)
context: body
Registers a Lua function that gets executed as a sample fetch. Every registered sample fetch can be used in HAProxy with the prefix "lua.". A Lua sample fetch returns a string as output. The registered function can take up to 9 values as parameter, and all of them are strings.
Arguments
- name (string) — is the name of the sample fetch.
- func (function) — is the Lua function called to work as sample fetch.
The prototype of the Lua function used as argument is:
string function(txn, [p1 [, p2 [, ... [, p5]]]])
txn(TXN class): this is the txn object associated with the current request.p1 .. p5(string): this is a list of string arguments declared in the HAProxy configuration file. The number of arguments doesn't exceed 5. The order and the nature of these is conventionally chosen by the developer.- Returns: A string containing some data, or
nilif the value cannot be returned now.
lua example code:
core.register_fetches("hello", function(txn)
return "hello"
end)
HAProxy example configuration:
frontend example
http-request redirect location /%[lua.hello]
🫧 core.register_filter(name, Flt, func)
context: body
Registers a Lua function used to declare a filter. Every registered filter can by used in HAProxy with the prefix "lua." ✨
Arguments
- name (string) — is the name of the filter.
- Flt (table) — is a Lua class containing the filter definition (id, flags, callbacks).
func(function) — this is the Lua function that gets called to create the Lua filter, bestie. 💖
The prototype of the Lua function used as argument is:
function(flt, args)
flt— is a filter object based on the class provided incore.register_filter()function. It's giving filter energy. ✨args— is a table of strings containing all arguments provided through the HAProxy configuration file, on the filter line. Like, all the tea. 🍵
It must return the filter to use or nil to ignore it. Here, an example of filter registration.
core.register_filter("my-filter", MyFilter, function(flt, args)
flt.args = args -- Save arguments
return flt
end)
This example code is used in HAProxy configuration like this:
frontend http
mode http
filter lua.my-filter arg1 arg2 arg3
see Filter — go check that out, bestie. 💅
core.register_service(name, mode, func)
context: body
Register a Lua function executed as a service. All the registered services can be used in HAProxy with the prefix lua.. A service gets an object class as input according with the required mode. It's like a little service you can call. 👑
Arguments
name(string) — is the name of the service. Gotta name it something cute. 💖mode(string) — is string describing the required mode. Only'tcp'or'http'are allowed. Periodt. 💅func(function) — is the Lua function called to work as service. Main character energy. 🌟
The prototype of the Lua function used as argument is:
function(applet)
applet—appletwill be aAppletTCPclass or aAppletHTTPclass. It depends the type of registered applet. An applet registered with the'http'value for the mode parameter will gets aAppletHTTPclass. If the mode value is'tcp', the applet will gets aAppletTCPclass. Slay. 🦋
⚠️ Warning, bestie! Applets of type'http'cannot be called from'tcp-'rulesets. Only the'http-'rulesets are authorized, this means that is not possible to call a HTTP applet from a proxy in tcp mode. Applets of type'tcp'can be called from anywhere. So know the difference, okay? 💀
Here, an example of service registration. The service just send an 'Hello world' as an http response. So cute. 🎀
core.register_service("hello-world", "http", function(applet)
local response = "Hello World !"
applet:set_status(200)
applet:add_header("content-length", string.len(response))
applet:add_header("content-type", "text/plain")
applet:start_response()
applet:send(response)
end)
This example code is used in HAProxy configuration like this:
frontend example
http-request use-service lua.hello-world
core.register_init(func)
context: body
Register a function executed after the configuration parsing. This is useful to check any parameters. Like a little pre-flight check. ✈️
Arguments
func(function) — is the Lua function called to work as initializer. It's the setup queen. 👑
The prototype of the Lua function used as argument is:
function()
It takes no input, and no output is expected. Zero drama. 🧘
core.register_task(func[, arg1[, arg2[, ...[, arg4]]]])
context: body, init, task, action, sample-fetch, converter, event
Register and start independent task. The task is started when the HAProxy main scheduler starts. For example this type of tasks can be executed to perform complex health checks. Like a background bestie doing the most. 💪
Arguments
func(function) — is the Lua function called to work as an async task. Async queen. ⏳
Up to 4 optional arguments (all types supported) may be passed to the function. (They will be passed as-is to the task function) No edits, no filter. 💅
The prototype of the Lua function used as argument is:
function([arg1[, arg2[, ...[, arg4]]]])
It takes up to 4 optional arguments (provided when registering), and no output is expected. Keep it chill. 😎
See also core.queue() to dynamically pass data between main context and tasks or even between tasks. So handy. 📦
core.register_cli([path], usage, func)
context: body
Register a custom cli that will be available from haproxy stats socket. You can make your own commands, bestie. 💻
Arguments
path(array) — is the sequence of word for which the cli execute the Lua binding. Like a breadcrumb trail. 🍞usage(string) — is the usage message displayed in the help. Gotta tell people how to use it. 📖func(function) — is the Lua function called to handle the CLI commands. The brains of the operation. 🧠
The prototype of the Lua function used as argument is:
function(AppletTCP, [arg1, [arg2, [...]]])
I/O are managed with the AppletTCP class object. Args are given as parameter. The args embed the registered path. If the path is declared like this:
core.register_cli({"show", "ssl", "stats"}, "Display SSL stats..", function(applet, arg1, arg2, arg3, arg4, arg5)
end)
And we execute this in the prompt:
> prompt
> show ssl stats all
Then, arg1, arg2 and arg3 will contains respectively "show", "ssl" and "stats". arg4 will contain "all". arg5 contains nil. So that's how the args stack up. 🥞
core.set_nice(nice)
context: task, action, sample-fetch, converter
Change the nice of the current task or current session. Be nice, okay? 💖
Arguments
nice(integer) — the nice value, it must be between-1024and1024. Stay in that range, bestie. 📏
core.set_map(name, key, value)
LEGACY 🕰️
context: init, task, action, sample-fetch, converter
Set the value associated to the key in the map referenced by name. Map magic. 🗺️
Arguments
name(string) — the Map referencekey(string) — the key to set or replacevalue(string) — the associated value
📝 Note: This function is not optimal due to systematic Map reference lookup. It is recommended to use Patref.set() instead. So maybe don't use this one, bestie. Just a heads up. 💅
core.sleep(int seconds)
context: task, action
The core.sleep() functions stop the Lua execution between specified seconds. Like a nap but for code. 😴
Arguments
seconds(integer) — the required seconds. Zzz. 💤
core.tcp()
context: task, action
This function returns a new object of a socket class. Socket realness. 🔌
Returns
A Socket class object. Slay. 💅
core.httpclient()
context: task, action
This function returns a new object of a httpclient class. An httpclient object must be used to process one and only one request. It must never be reused to process several requests. One and done, no cap. 🚫
Returns
A HTTPClient class object. ✨
core.concat()
context: body, init, task, action, sample-fetch, converter
This function returns a new concat object. Concatenation vibes. 🔗
Returns
A Concat class object. 💖
core.queue()
context: body, init, task, event, action, sample-fetch, converter
This function returns a new queue object. Queue up, bestie. 🎟️
Returns
A Queue class object. 🦋
core.done(data)
context: body, init, task, action, sample-fetch, converter
Arguments
data(any) — Return some data for the caller. It is useful with sample-fetches and sample-converters. Share the data, bestie. 📤
Immediately stops the current Lua execution and returns to the caller which may be a sample fetch, a converter or an action and returns the specified value (ignored for actions and init). It is used when the LUA process finishes its work and wants to give back the control to HAProxy without executing the remaining code. It can be seen as a multi-level "return". So dramatic, but necessary. 💅
core.wait([milliseconds])
context: task, action
Give back the hand at the HAProxy scheduler. Unlike core.yield() the task will not be woken up automatically to resume as fast as possible. Instead, it will wait for an event to wake the task. If milliseconds argument is provided then the Lua execution will be automatically resumed passed this delay even if no event caused the task to wake itself up. So you can set a timer. ⏰
Arguments
milliseconds(integer) — automatic wakeup passed this delay. (optional) Set it if you want a lil snooze button. 😴
core.yield()
context: task, action
Give back the hand at the HAProxy scheduler. It is used when the LUA processing consumes a lot of processing time. Lua execution will be resumed automatically (automatic reschedule). So yield, and let it come back. 💫
core.parse_addr(address)
context: body, init, task, action, sample-fetch, converter
Arguments
network— is a string describing an ipv4 or ipv6 address and optionally its network length, like this:"127.0.0.1/8"or"aaaa::1234/32". Address realness. 🌐
Returns
a userdata containing network or nil if an error occurs. 👀
Parse ipv4 or ipv6 addresses and its facultative associated network. Network parsing queen. 👑
core.match_addr(addr1, addr2)
context: body, init, task, action, sample-fetch, converter
Arguments
addr1— is an address created with"core.parse_addr".addr2— is an address created with"core.parse_addr".
Returns
boolean,trueif the network of the addresses match, else returnsfalse. Simple. 💅
Match two networks. For example "127.0.0.1/32" matches "127.0.0.0/8". The order of network is not important. So don't stress about which one comes first. 🧘
core.tokenize(str, separators[, noblank])
context: body, init, task, action, sample-fetch, converter
This function is useful for tokenizing an entry, or splitting some messages.
str(string) — The string which will be split.separators(string) — A string containing a list of separators.noblank(boolean) — Ignore empty entries.- Returns: an array of string.
Tokenize it, bestie. 🔍
For example:
local array = core.tokenize("This function is useful, for tokenizing an entry.", "., ", true)
print_r(array)
Returns this array:
(table) table: 0x21c01e0 [
1: (string) "This"
2: (string) "function"
3: (string) "is"
4: (string) "useful"
5: (string) "for"
6: (string) "tokenizing"
7: (string) "an"
8: (string) "entry"
]
core.event_sub(event_types, func)
context: body, init, task, action, sample-fetch, converter
Register a function that will be called on specific system events. Event subscription, so you never miss a thing. 📅
Arguments
event_types(array) — an array of strings, one per event type you wanna subscribe to 💖func(function) — the Lua function that gets called whenever one of those subscribed events actually happens.
Returns
An EventSub class object. slay.
See
Server.event_sub().
✨ The event types you can subscribe to ✨
SERVER Family: (the whole fam 🫶)
SERVER_ADD— fires when a server gets addedSERVER_DEL— fires when a server gets removedSERVER_DOWN— fires when a server state goes from UP to DOWNSERVER_UP— fires when a server state goes from DOWN to UPSERVER_STATE— fires when a server state changesSERVER_ADMIN— fires when a server's administrative state changesSERVER_CHECK— fires when a server's check status change gets reported. ok bestie be careful with this one because subscribing to it can generate so many events, like it's giving spam 😭
Note: useSERVERinevent_typesto subscribe to all the server event types at once. but ngl this should really only be used for testing purposes, because a single event source could result in multiple event types being generated (e.g.:SERVER_STATEwill always be generated for eachSERVER_DOWNorSERVER_UP). iykyk.
The prototype of the Lua function used as argument is:
function(event, event_data, sub, when)
event(string) — the event type (one of theevent_typesyou specified when subscribing)event_data— specific to each event family (for the SERVER family, this is aServerEventclass object)sub— a class to manage the subscription from within the event (anEventSubclass object)when— timestamp corresponding to the date when the event was generated. it's an integer representing the number of seconds elapsed since Epoch. you may provide it as an optional argument to theos.date()lua function to convert it to a string according to a given format string 💅
Warning: the callback function will only be scheduled on the very same thread that performed the subscription. Moreover, each thread treats events sequentially. it means that if you have, let's saySERVER_UPfollowed by aSERVER_DOWNin a short timelapse, then the cb function will first be called withSERVER_UP, and once it's done handling the event, the cb function will be called again withSERVER_DOWN. This is to ensure event consistency when it comes to logging / triggering logic from lua. Your lua cb function may yield if needed, but you're pleased to process the event as fast as possible to prevent the event queue from growing up, depending on the event flow that is expected for the given subscription. To prevent abuses, if the event queue for the current subscription goes over a certain amount of unconsumed events, the subscription will pause itself automatically for as long as it takes for your handler to catch up. This would lead to events being missed, so an error will be reported in the logs to warn you about that. This is not something you want to let happen too often, it may indicate that you subscribed to an event that is occurring too frequently or/and that your callback function is too slow to keep up the pace and you should review it. If you want to do some parallel processing because your callback functions are slow: you might want to create subtasks from lua usingcore.register_task()from within your callback function to perform the heavy job in a dedicated task and allow remaining events to be processed more quickly. periodt. 🧚
core.use_native_mailers_config()
context: body
Inform haproxy that the script will make use of the native "mailers" config section (although legacy). In other words, inform haproxy that Proxy.get_mailers() will be used later in the program. 👑
🌸 class Proxy() 🌸
This class provides a way for manipulating proxy and retrieving information like statistics.
Proxy.name
Contain the name of the proxy.
Warning: this attribute is now deprecated and will eventually be removed. Please use Proxy.get_name() function instead. 🙈
Proxy.get_name()
Returns the name of the proxy.
Proxy.uuid
Contain the unique identifier of the proxy.
Warning: this attribute is now deprecated and will eventually be removed. Please use Proxy.get_uuid() function instead. 🙈
Proxy.get_uuid()
Returns the unique identifier of the proxy.
Proxy.servers
Contain a table with the attached servers. The table is indexed by server name, and each server entry is an object of type Server class.
Proxy.stktable
Contains a stick table object of type StickTable class attached to the proxy.
Proxy.listeners
Contain a table with the attached listeners. The table is indexed by listener name, and each each listeners entry is an object of type Listener class.
Proxy.pause(px)
Pause the proxy. See the management socket documentation for more information. 💖
Arguments
px(class_proxy) — aProxyclass which indicates the manipulated proxy.
Proxy.resume(px)
Resume the proxy. See the management socket documentation for more information. ✨
Arguments
px(class_proxy) — aProxyclass which indicates the manipulated proxy.
Proxy.stop(px)
Stop the proxy. See the management socket documentation for more information. 💀
Arguments
px(class_proxy) — aProxyclass which indicates the manipulated proxy.
Proxy.shut_bcksess(px)
Kill the session attached to a backup server. See the management socket documentation for more information. 🔥
Arguments
px(class_proxy) — aProxyclass which indicates the manipulated proxy.
Proxy.get_cap(px)
Returns a string describing the capabilities of the proxy.
Arguments
px(class_proxy) — aProxyclass which indicates the manipulated proxy.
Returns a string "frontend", "backend", "proxy" or "ruleset".
Proxy.get_mode(px)
Returns a string describing the mode of the current proxy.
Arguments
px(class_proxy) — aProxyclass which indicates the manipulated proxy.
Returns a string "tcp", "http", "syslog" or "unknown"
Proxy.get_srv_act(px)
Returns the number of current active servers for the current proxy that are eligible for LB.
Arguments
px(class_proxy) — aProxyclass which indicates the manipulated proxy.
Returns an integer
Proxy.get_srv_bck(px)
Returns the number backup servers for the current proxy that are eligible for LB.
Arguments
px(class_proxy) — aProxyclass which indicates the manipulated proxy.
Returns an integer
Proxy.get_stats(px)
Returns a table containing the proxy statistics. The statistics returned are not the same if the proxy is frontend or a backend.
Arguments
px(class_proxy) — aProxyclass which indicates the manipulated proxy.
Returns a key/value table containing stats
Proxy.get_mailers(px)
LEGACY (iykyk 👵)
Returns a table containing legacy mailers config (from haproxy configuration file) for the current proxy or nil if mailers are not available for the proxy.
Warning: when relying onProxy.get_mailers()to retrieve mailers configuration,core.use_native_mailers_config()must be called first from body or init context to inform haproxy that Lua makes use of the legacy mailers config. no cap, don't skip this step 😭
Arguments
px(class_proxy) — aProxyclass which indicates the manipulated proxy.
Returns a ProxyMailers class containing proxy mailers config
LEGACY
💌 class ProxyMailers() 💌
This class provides mailers config for a given proxy.
ProxyMailers.track_server_health
Boolean set to true if the option "log-health-checks" is configured on the proxy, meaning that all server checks event should trigger email alerts. 📬
ProxyMailers.log_level
An integer, the maximum log level that triggers email alerts. It is a number between 0 and 7 as defined by option "email-alert level".
ProxyMailers.mailservers
An array containing the list of mail servers that should receive email alerts. Each array entry is a name:desc pair where desc represents the full server address (including port) as described in haproxy's configuration file.
ProxyMailers.mailservers_timeout
An integer representing the maximum time in milliseconds to wait for the email to be sent. See "timeout mail" directive from "mailers" section in haproxy configuration file.
ProxyMailers.smtp_hostname
A string containing the hostname to use for the SMTP transaction. (option "email-alert myhostname")
ProxyMailers.smtp_from
A string containing the "MAIL FROM" address to use for the SMTP transaction. (option "email-alert from")
ProxyMailers.smtp_to
A string containing the "RCPT TO" address to use for the SMTP transaction. (option "email-alert to")
🦋 class Server() 🦋
This class provides a way for manipulating servers and retrieving information.
Server.name
Contain the name of the server.
Warning: this attribute is now deprecated and will eventually be removed. Please use Server.get_name() function instead. 🙈
Server.get_name(sv)
Returns the name of the server.
Server.puid
Contain the proxy unique identifier of the server.
⚠️ Warning: this attribute is deprecated now and one day it's just gonna be gone — poof. Please use the Server.get_puid() function instead. 💅
✨ Server.get_puid(sv)
Returns the proxy unique identifier of the server. 💖
🦋 Server.get_rid(sv)
Returns the rid (revision ID) of the server. It's an unsigned integer that gets set whenever a server is created. The value comes from a global counter that starts at 0 and bumps up every time one or more server deletions are followed by a server addition (meaning old name/id reuse could totally happen, no cap).
Mash the server name/id together with the server rid and boom — you've got a process-wide unique identifier. 👑
🌸 Server.is_draining(sv)
Return true if the server is currently draining sticky connections.
Arguments
sv(class_server) — a Server class which indicates the manipulated server.
Returns
a boolean
🌈 Server.is_backup(sv)
Return true if the server is a backup server.
Arguments
sv(class_server) — a Server class which indicates the manipulated server.
Returns
a boolean
⭐ Server.is_dynamic(sv)
Return true if the server was instantiated at runtime (e.g.: from the cli).
Arguments
sv(class_server) — a Server class which indicates the manipulated server.
Returns
a boolean
💜 Server.get_cur_sess(sv)
Return the number of currently active sessions on the server.
Arguments
sv(class_server) — a Server class which indicates the manipulated server.
Returns
an integer
🧚 Server.get_pend_conn(sv)
Return the number of pending connections to the server.
Arguments
sv(class_server) — a Server class which indicates the manipulated server.
Returns
an integer
🔥 Server.set_maxconn(sv, weight)
Dynamically change the maximum connections of the server. Peep the management socket documentation for more info about the format of the string.
Arguments
sv(class_server) — a Server class which indicates the manipulated server.maxconn(string) — a string describing the server maximum connections.
🎀 Server.get_maxconn(sv, weight)
This function returns an integer representing the server maximum connections.
Arguments
sv(class_server) — a Server class which indicates the manipulated server.
Returns
an integer.
🍓 Server.set_weight(sv, weight)
Dynamically change the weight of the server. Peep the management socket documentation for more info about the format of the string.
Arguments
sv(class_server) — a Server class which indicates the manipulated server.weight(string) — a string describing the server weight.
🫶 Server.get_weight(sv)
This function returns an integer representing the server weight.
Arguments
sv(class_server) — a Server class which indicates the manipulated server.
Returns
an integer.
🦋 Server.set_addr(sv, addr[, port])
Dynamically change the address of the server. Peep the management socket documentation for more info about the format of the string.
Arguments
sv(class_server) — a Server class which indicates the manipulated server.addr(string) — a string describing the server address.
💖 Server.get_addr(sv)
Returns a string describing the address of the server.
Arguments
sv(class_server) — a Server class which indicates the manipulated server.
Returns
A string
✨ Server.get_stats(sv)
Returns server statistics.
Arguments
sv(class_server) — a Server class which indicates the manipulated server.
Returns
a key/value table containing stats
👑 Server.get_proxy(sv)
Returns the parent proxy to which the server belongs.
Arguments
sv(class_server) — a Server class which indicates the manipulated server.
Returns
a Proxy class or nil if not available
💅 Server.shut_sess(sv)
Shutdown all the sessions attached to the server. Peep the management socket documentation for more info about this function.
Arguments
sv(class_server) — a Server class which indicates the manipulated server.
🌸 Server.set_drain(sv)
Drain sticky sessions. Peep the management socket documentation for more info about this function.
Arguments
sv(class_server) — a Server class which indicates the manipulated server.
🔧 Server.set_maint(sv)
Set maintenance mode. Peep the management socket documentation for more info about this function.
Arguments
sv(class_server) — a Server class which indicates the manipulated server.
⭐ Server.set_ready(sv)
Set normal mode. Peep the management socket documentation for more info about this function.
Arguments
sv(class_server) — a Server class which indicates the manipulated server.
🌈 Server.check_enable(sv)
Enable health checks. Peep the management socket documentation for more info about this function.
Arguments
sv(class_server) — a Server class which indicates the manipulated server.
🙈 Server.check_disable(sv)
Disable health checks. Peep the management socket documentation for more info about this function.
Arguments
sv(class_server) — a Server class which indicates the manipulated server.
🔥 Server.check_force_up(sv)
Force health-check up. Peep the management socket documentation for more info about this function.
Arguments
sv(class_server) — a Server class which indicates the manipulated server.
💜 Server.check_force_nolb(sv)
Force health-check nolb mode. Peep the management socket documentation for more info about this function.
Arguments
sv(class_server) — a Server class which indicates the manipulated server.
😭 Server.check_force_down(sv)
Force health-check down. Peep the management socket documentation for more info about this function.
Arguments
sv(class_server) — a Server class which indicates the manipulated server.
🧚 Server.agent_enable(sv)
Enable agent check. Peep the management socket documentation for more info about this function.
Arguments
sv(class_server) — a Server class which indicates the manipulated server.
🎀 Server.agent_disable(sv)
Disable agent check. Peep the management socket documentation for more info about this function.
Arguments
sv(class_server) — a Server class which indicates the manipulated server.
💖 Server.agent_force_up(sv)
Force agent check up. Peep the management socket documentation for more info about this function.
Arguments
sv(class_server) — a Server class which indicates the manipulated server.
🍓 Server.agent_force_down(sv)
Force agent check down. Peep the management socket documentation for more info about this function.
Arguments
sv(class_server) — a Server class which indicates the manipulated server.
🦋 Server.tracking(sv)
Check if the current server is tracking another server.
Arguments
sv(class_server) — a Server class which indicates the manipulated server.
Returns
A Server class which indicates the tracked server, or nil if the server doesn't track another one.
✨ Server.get_trackers(sv)
Check if the current server is being tracked by other servers.
Arguments
sv(class_server) — a Server class which indicates the manipulated server.
Returns
An array of Server class which indicates the tracking servers (might be empty)
👑 Server.event_sub(sv, event_types, func)
Register a function that's gonna get called on specific server events. It works exactly like core.event_sub() except that the subscription happens inside the server's dedicated subscription list instead of the global one. (So your callback function only gets called for server events affecting sv.) 🔔
See core.event_sub() for function usage.
The big slay here: a key advantage of using Server.event_sub() over core.event_sub() for servers is that Server.event_sub() lets you get notified for server events of a single server only. That means you don't need extra filtering inside your callback function if you only care about one server, and it also prevents useless wakeups. Obsessed. 💅
For instance, if you want to be notified for UP/DOWN events on a given set of servers, it's recommended to do multiple per-server subscriptions, since it'll be more efficient than doing a single global subscription that filters the received events. Unless you really want to be notified for server events of ALL servers — which could make sense given your setup, but should be avoided if you have an important number of servers, because it'll add a significant load on your haproxy process in case of multiple server state changes in a short amount of time. 😭
✨ Note: You can also vibe-combinecore.event_sub()withServer.event_sub(). And bestie — don't forget that you can totally usecore.register_task()from inside your callback function if you need to. (ie: parallel work. we stay multitasking 💅)
Here's a working example combining core.event_sub() with Server.event_sub() and core.register_task() (this is only serving as a demo, it's not necessarily useful to do so, iykyk):
core.event_sub({"SERVER_ADD"}, function(event, data, sub)
-- in the global event handler
if data["reference"] ~= nil then
print("Tracking new server: ", data["name"])
data["reference"]:event_sub({"SERVER_UP", "SERVER_DOWN"}, function(event, data, sub)
-- in the per-server event handler
if data["reference"] ~= nil then
core.register_task(function(server)
-- subtask to perform some async work (e.g.: HTTP API calls, sending emails...)
print("ASYNC: SERVER ", server:get_name(), " is ", event == "SERVER_UP" and "UP" or "DOWN")
end, data["reference"])
end
end)
end
end)
So in this example, first we track global server addition events. For every newly added server ("add server" on the cli), we register a UP/DOWN server subscription. Then the callback function schedules the event handling in an async subtask, and that subtask receives the server reference as an argument. cute, right? 🦋
🌸 Listener.get_stats(ls)
Returns server statistics, no cap. 📊
Arguments
ls(class_listener) — a Listener class that indicates the manipulated listener.
Returns
a key/value table containing stats ✨
🎀 EventSub.unsub()
Ends the subscription. The callback function will not be called again. that's it, that's the function. bye bestie 👋
👑 class ServerEvent()
This class is provided with every SERVER events.
See core.event_sub() for more info.
💜 ServerEvent.name
Contains the name of the server.
💜 ServerEvent.puid
Contains the proxy-unique uid of the server
💜 ServerEvent.rid
Contains the revision ID of the server
💜 ServerEvent.proxy_name
Contains the name of the proxy to which the server belongs
💜 ServerEvent.proxy_uuid
Contains the uuid of the proxy to which the server belongs
💜 ServerEvent.reference
Reference to the live server (A Server class).
⚠️ Warning: Not available if the server was removed in the meantime. (Will never be set for SERVER_DEL event since the server does not exist anymore 😭)
💜 ServerEvent.state
A ServerEventState class
✨ Note: Only available for SERVER_STATE event
💜 ServerEvent.admin
A ServerEventAdmin class
✨ Note: Only available for SERVER_ADMIN event
💜 ServerEvent.check
A ServerEventCheckRes class
✨ Note: Only available for SERVER_CHECK event
🧚 class ServerEventCheckRes()
This class describes the result of a server's check. 🔍
🌈 ServerEventCheckRes.result
Effective check result.
Check result is a string and will be set to one of the following values:
"FAILED": the check failed"PASSED": the check succeeded"CONDPASS": the check conditionally passed
🌈 ServerEventCheckRes.agent
Boolean set to true if the check is an agent check. Else it is a health check.
🌈 ServerEventCheckRes.duration
Check's duration in milliseconds
🌈 ServerEventCheckRes.reason
Check's status. An array containing three fields:
short: a string representing check status short namedesc: a string representing check status descriptioncode: an integer, this extra information is provided for checks that went through the data analysis stage (>= layer 5)
🌈 ServerEventCheckRes.health
An array containing values about check's health (integers):
cur: current health counter:0to(rise - 1)= BADriseto(rise + fall - 1)= GOOD
rise: server will be considered as operational afterriseconsecutive successful checksfall: server will be considered as dead afterfallconsecutive unsuccessful checks
🦋 class ServerEventState()
This class contains additional info related to SERVER_STATE event. ✨
💖 ServerEventState.admin
Boolean set to true if the server state change is due to an administrative change. Else it is an operational change.
💖 ServerEventState.check
A ServerEventCheckRes class, provided if the state change is due to a server check (must be an operational change).
💖 ServerEventState.cause
Printable state change cause. Might be empty.
💖 ServerEventState.new_state
New server state due to operational or admin change.
It is a string that can be any of the following values:
"STOPPED": The server is down"STOPPING": The server is up but soft-stopping"STARTING": The server is warming up"RUNNING": The server is fully up
💖 ServerEventState.old_state
Previous server state prior to the operational or admin change.
Can be any value described in new_state, but they should differ.
💖 ServerEventState.requeued
Number of connections that were requeued due to the server state change.
For a server going DOWN: it is the number of pending server connections that are requeued to the backend (such connections will be redispatched to any server that is suitable according to the configured load balancing algorithm).
For a server doing UP: it is the number of pending connections on the backend that may be redispatched to the server according to the load balancing algorithm that is in use.
🍓 class ServerEventAdmin()
This class contains additional info related to SERVER_ADMIN event.
🎀 ServerEventAdmin.cause
Printable admin state change cause. Might be empty.
🎀 ServerEventAdmin.new_admin
New server admin state due to the admin change.
It is an array of string containing a composition of following values:
"MAINT": server is in maintenance mode"FMAINT": server is in forced maintenance mode (MAINTis also set)"IMAINT": server is in inherited maintenance mode (MAINTis also set)"RMAINT": server is in resolve maintenance mode (MAINTis also set)"CMAINT": server is in config maintenance mode (MAINTis also set)"DRAIN": server is in drain mode"FDRAIN": server is in forced drain mode (DRAINis also set)"IDRAIN": server is in inherited drain mode (DRAINis also set)
🎀 ServerEventAdmin.old_admin
Previous server admin state prior to the admin change.
Values are presented as in new_admin, but they should differ. (Comparing old and new helps to find out the change(s))
🎀 ServerEventAdmin.requeued
Same as ServerEventState.requeued but when the requeue is due to the server administrative state change.
🌈 class Queue()
This class provides a generic FIFO storage mechanism that may be shared between multiple lua contexts to easily pass data between them, as stock Lua doesn't provide easy methods for passing data between multiple coroutines. like, a little mailbox for your coroutines 📬
inter-task example:
-- script wide shared queue
local queue = core.queue()
-- master task
core.register_task(function()
-- send the date every second
while true do
queue:push(os.date("%c", core.now().sec))
core.sleep(1)
end
end)
-- worker task
core.register_task(function()
while true do
-- print the date sent by master
print(queue:pop_wait())
end
end)
Of course, queue may also be used as a local storage mechanism.
Use core.queue() to get a new Queue object.
⭐ Queue.alarm()
context: task, action, service
Sets a wakeup alarm on the current Lua context so that when new data becomes available on the Queue, the current Lua context is woken up automatically. It can be combined with core.wait() to wait for Queue events.
Arguments
queue(class_queue) — A Queue class to the current queue
⭐ Queue.size(queue)
This function returns the number of items within the Queue.
Arguments
queue(class_queue) — A Queue class to the current queue
⭐ Queue.push(queue, item)
This function pushes the item (may be of any type) to the queue. Pushed item cannot be nil or invalid, or an error will be thrown. 🚨
Arguments
queue(class_queue) — A Queue class to the current queue
Returns
boolean true for success and false for error
⭐ Queue.pop(queue)
This function immediately tries to pop an item from the queue. It returns nil of no item is available at the time of the call.
Arguments
queue(class_queue) — A Queue class to the current queue
Returns
the item at the top of the stack (any type) or nil if no items
⭐ Queue.pop_wait(queue)
context: task
This is an alternative to pop() that may be used within task contexts.
The call waits for data if no item is currently available. This may be useful when used in a while loop to prevent cpu waste. 🔥 (your cpu will thank you)
Note that this requires yielding, thus it is only available within contexts that support yielding (mainly task context).
Arguments
queue(class_queue) — A Queue class to the current queue
Returns
the item at the top of the stack (any type) or nil in case of error
💫 class Concat()
This class provides a fast way for string concatenation. The way using native Lua concatenation like the code below is slow for some reasons. 😤
str = "string1"
str = str .. ", string2"
str = str .. ", string3"
okay so for each concatenation, Lua is out here doing the most:
- allocates memory for the result 💾
- catenates the two strings, copying the strings into that new memory block
- frees the old memory block that held the string nobody's using anymore
and that's a whole lot of memory moving, allocating and freeing for every single ... and the plot twist? the memory isn't even really freed — it's just marked as unused and left sitting there waiting for the garbage collector. tragic. 💀
so the Concat class is the alternative way to concatenate strings. it uses the internal Lua mechanism (so no memory allocation, bestie) and it doesn't copy the data more than once. slay. ✨
on the author's computer, the following loops spend 0.2s for the Concat method and 18.5s for the pure Lua implementation. so the Concat class is about 1000x faster than the embedded solution. not me being dramatic, that's literally the numbers. 🔥
for j = 1, 100 do
c = core.concat()
for i = 1, 20000 do
c:add("#####")
end
end
for j = 1, 100 do
c = ""
for i = 1, 20000 do
c = c .. "#####"
end
end
🧵 Concat.add(concat, string)
this function adds a string to the current concatenated string. yes bestie, it just adds. 🫶
Arguments
concat(class_concat) — a Concat class which contains the currently built string.string(string) — a new string to concatenate to the current built string.
🧵 Concat.dump(concat)
this function returns the concatenated string. your hard work, materialised. 💅
Arguments
concat(class_concat) — a Concat class which contains the currently built string.
Returns the concatenated string
📚 class Fetches()
this class contains a lot of internal HAProxy sample fetches. see the HAProxy "configuration.txt" documentation for more information (chapters 7.3.2 to 7.3.6).
⚠️ Warning: some sample fetches are not available in some contexts. these limitations are specified in this documentation when they're useful. iykyk. 🙈
- 🌸 See
TXN.f - 🌸 See
TXN.sf
fetches are lowkey useful to:
- get system time,
- get environment variable,
- get random numbers,
- know backend status like the number of users in queue or the number of connections established,
- get client information like ip source or destination,
- deal with stick tables,
- fetch established SSL information,
- fetch HTTP information like headers or method.
function action(txn)
-- Get source IP
local clientip = txn.f:src()
end
🔄 class Converters()
this class contains a lot of internal HAProxy sample converters. see the HAProxy documentation "configuration.txt" for more information about her usage. it's the chapter 7.3.1. (yes, "her". iconic behaviour, no notes. 👑)
- 🦋 See
TXN.c - 🦋 See
TXN.sc
converters provide stateful transformation. they're useful to:
- convert input to base64,
- apply hash on input string (
djb2,crc32,sdbm,wt6), - format date,
- json escape,
- extract preferred language comparing two lists,
- turn to lower or upper chars,
- deal with stick tables.
🌈 class Channel()
context: action, sample-fetch, convert, filter
HAProxy uses two buffers for the processing of the requests. the first one is used with the request data (from the client to the server) and the second is used for the response data (from the server to the client). two lanes, one vibe check each. 🛣️
each buffer contains two types of data. the first type is the incoming data waiting for a processing. the second part is the outgoing data already processed. usually, the incoming data is processed, after it is tagged as outgoing data, and finally it is sent. the following functions provides tools for manipulating these data in a buffer.
the following diagram shows where the channel class function are applied. [image]
⚠️ Warning: it is not possible to read from the response in request action, and it is not possible to read from the request channel in response action. no peeking in the other lane, bestie.
⚠️ Warning: it is forbidden to alter the Channels buffer from HTTP contexts. so onlyChannel.input(),Channel.output(),Channel.may_recv(),Channel.is_full()andChannel.is_resp()can be called from a HTTP context. hands off the buffer. 🙅♀️
all the functions provided by this class are available in the sample-fetches, actions and filters contexts. for filters, incoming data (offset and length) are relative to the filter. some functions may yield, but only for actions. yield is not possible for sample-fetches, converters and filters.
➕ Channel.append(channel, string)
this function copies the string string at the end of incoming data of the channel buffer. the function returns the copied length on success or -1 if data cannot be copied.
same that Channel.insert(channel, string, channel:input())().
Arguments
channel(class_channel) — the manipulated Channel.string(string) — the data to copy at the end of incoming data.
Returns an integer containing the amount of bytes copied or -1.
🔍 Channel.data(channel[, offset[, length]])
this function returns length bytes of incoming data from the channel buffer, starting at the offset offset. the data are not removed from the buffer. just looking, not touching. 👀
by default, if no length is provided, all incoming data found, starting at the given offset, are returned. if length is set to -1, the function tries to retrieve a maximum of data and, if called by an action, it yields if necessary. it also waits for more data if the requested length exceeds the available amount of incoming data. not providing an offset is the same as setting it to 0. a positive offset is relative to the beginning of incoming data of the channel buffer while negative offset is relative to the end.
if there is no incoming data and the channel can't receive more data, a 'nil' value is returned.
Arguments
channel(class_channel) — the manipulated Channel.offset(integer) — optional the offset in incoming data to start to get data.0by default. may be negative to be relative to the end of incoming data.length(integer) — optional the expected length of data to retrieve. all incoming data by default. may be set to-1to get a maximum of data.
Returns a string containing the data found or nil.
⏩ Channel.forward(channel, length)
this function forwards length bytes of data from the channel buffer. if the requested length exceeds the available amount of incoming data, and if called by an action, the function yields, waiting for more data to forward. it returns the amount of data forwarded.
Arguments
channel(class_channel) — the manipulated Channel.int(integer) — the amount of data to forward.
📥 Channel.input(channel)
this function returns the length of incoming data in the channel buffer. when called by a filter, this value is relative to the filter.
Arguments
channel(class_channel) — the manipulated Channel.
Returns an integer containing the amount of available bytes.
📌 Channel.insert(channel, string[, offset])
this function copies the string string at the offset offset in incoming data of the channel buffer. the function returns the copied length on success or -1 if data cannot be copied.
by default, if no offset is provided, the string is copied in front of incoming data. a positive offset is relative to the beginning of incoming data of the channel buffer while negative offset is relative to their end.
Arguments
channel(class_channel) — the manipulated Channel.string(string) — the data to copy into incoming data.offset(integer) — optional the offset in incoming data where to copy data.0by default. may be negative to be relative to the end of incoming data.
Returns an integer containing the amount of bytes copied or -1.
🈵 Channel.is_full(channel)
this function returns true if the channel buffer is full. she's booked and busy. 😮💨
Arguments
channel(class_channel) — the manipulated Channel.
Returns a boolean
📤 Channel.is_resp(channel)
this function returns true if the channel is the response one.
Arguments
channel(class_channel) — the manipulated Channel.
Returns a boolean
📏 Channel.line(channel[, offset[, length]])
this function parses length bytes of incoming data of the channel buffer, starting at offset offset, and returns the first line found, including the '\n'. the data are not removed from the buffer. if no line is found, all data are returned.
by default, if no length is provided, all incoming data, starting at the given offset, are evaluated. if length is set to -1, the function tries to retrieve a maximum of data and, if called by an action, yields if necessary. it also waits for more data if the requested length exceeds the available amount of incoming data. not providing an offset is the same as setting it to 0. a positive offset is relative to the beginning of incoming data of the channel buffer while negative offset is relative to the end.
if there is no incoming data and the channel can't receive more data, a 'nil' value is returned.
Arguments
channel(class_channel) — the manipulated Channel.offset(integer) — optional the offset in incoming data to start to parse data.0by default. may be negative to be relative to the end of incoming data.length(integer) — optional, bestie. This is how much data we're parsing. It does all the incoming data by default, and you can set it to-1if you want the max amount of data possible. 💅
Returns
a string with the line we found, or nil. That's it, that's the whole vibe. ✨
🌸 Channel.may_recv(channel)
Okay so this one just tells you true if the channel can still receive data. Simple, honest, iconic. 🫶
Arguments
channel(class_channel) — the Channel you're messing with.
Returns
a boolean. ✨
🌸 Channel.output(channel)
This gives you the length of the outgoing data sitting in the channel buffer. Little detail that matters: when a filter calls this, the value is relative to that filter. 👑
Arguments
channel(class_channel) — the Channel you're messing with.
Returns
an integer with the amount of available bytes. 💖
🌸 Channel.prepend(channel, string)
This copies the string string right in front of the incoming data of the channel buffer. Returns the copied length if it ate, or -1 if the data just can't be copied. 😭
Literally the same as Channel.insert(channel, string, 0)() — no cap.
Arguments
channel(class_channel) — the Channel you're messing with.string(string) — the data to copy in front of incoming data.
Returns
an integer with the amount of bytes copied, or -1. 💀
🌸 Channel.remove(channel[, offset[, length]])
This one removes length bytes of incoming data from the channel buffer, starting at offset. It hands you back the number of bytes removed when it works. ✨
By default, if you don't pass a length, all incoming data starting at the given offset gets yeeted. Not passing an offset is the same as setting it to 0. And here's the lore: a positive offset is relative to the beginning of the incoming data of the channel buffer, while a negative offset is relative to the end. 🦋
Arguments
channel(class_channel) — the Channel you're messing with.offset(integer) — optional. Where in the incoming data to start removing.0by default. May be negative to be relative to the end of incoming data.length(integer) — optional. How much data to remove. All incoming data by default.
Returns
an integer with the amount of bytes removed. 💜
🌸 Channel.send(channel, string)
This function demands an immediate send of the string string. That means the string gets copied at the beginning of the incoming data of the channel buffer and immediately forwarded. Unless the connection is closed — and if it's called by an action — this function yields so it can copy and forward the whole string. Periodt. 💅
Arguments
channel(class_channel) — the Channel you're messing with.string(string) — the data to send.
Returns
an integer with the amount of bytes copied, or -1. 🍓
🌸 Channel.set(channel, string[, offset[, length]])
This replaces length bytes of incoming data of the channel buffer — starting at offset — with the string string. Returns the copied length on success, or -1 if the data cannot be copied. 😭
By default, if no length is given, all incoming data starting at the given offset gets replaced. Not providing an offset is the same as setting it to 0. Positive offset = relative to the beginning of incoming data of the channel buffer, negative offset = relative to the end. 🧚
Arguments
channel(class_channel) — the Channel you're messing with.string(string) — the data to copy into incoming data.offset(integer) — optional. Where in the incoming data to start the replacement.0by default. May be negative to be relative to the end of incoming data.length(integer) — optional. How much data to replace. All incoming data by default.
Returns
an integer with the amount of bytes copied, or -1. 💖
🌸 Channel.dup(channel)
DEPRECATED 😬
This returns all the incoming data found in the channel buffer. The data is not removed from the buffer and can be reprocessed later — so it's very much still sitting there. 🙈
If there's no incoming data and the channel can't receive more, a 'nil' value is returned.
Arguments
channel(class_channel) — the Channel you're messing with.
Returns
a string with all the data found, or nil.
Warning: This function is deprecated. Channel.data() must be used instead. 🚨
🌸 Channel.get(channel)
DEPRECATED 😬
This returns all the incoming data found in the channel buffer and removes them from the buffer. ✨
If there's no incoming data and the channel can't receive more data, a 'nil' value is returned.
Arguments
channel(class_channel) — the Channel you're messing with.
Returns
a string containing all the data found, or nil.
Warning: This function is deprecated.Channel.data()must be used to retrieve data followed by a call toChannel:remove()to remove data. 🚨
local data = chn:data()
chn:remove(0, data:len())
🌸 Channel.getline(channel)
DEPRECATED 😬
This returns the first line found in the incoming data of the channel buffer, '\n' included. The returned data gets removed from the buffer. If no line is found, and if it's called by an action, this function yields to wait for more data — unless the channel can't receive more data, in which case all the data is returned. 🦋
If there's no incoming data and the channel can't receive more data, a 'nil' value is returned.
Arguments
channel(class_channel) — the Channel you're messing with.
Returns
a string containing the line found, or nil.
Warning: This function is deprecated.Channel.line()must be used to retrieve a line followed by a call toChannel:remove()to remove data. 🚨
local line = chn:line(0, -1)
chn:remove(0, line:len())
🌸 Channel.get_in_len(channel)
DEPRECATED 😬
This returns the length of the input part of the buffer. And when a filter calls it, the value is relative to that filter. 👑
Arguments
channel(class_channel) — the Channel you're messing with.
Returns
an integer with the amount of available bytes.
Warning: This function is deprecated. Channel.input() must be used instead. 🚨
🌸 Channel.get_out_len(channel)
DEPRECATED 😬
This returns the length of the output part of the buffer. Same filter lore as above: when called by a filter, the value is relative to the filter. ✨
Arguments
channel(class_channel) — the Channel you're messing with.
Returns
an integer with the amount of available bytes.
Warning: This function is deprecated. Channel.output() must be used instead. 🚨
👑 class HTTP()
This class is literally holding all the HTTP manipulation functions. The whole toolkit, bestie. 💅
🌈 HTTP.req_get_headers(http)
Returns a table containing all the request headers. Every single one. Obsessed. ✨
Arguments
http(class_http) — the related http object.
Returns
table of headers.
See HTTP.res_get_headers()
This is the form of the returned table:
HTTP:req_get_headers()['<header-name>'][<header-index>] = "<header-value>"
local hdr = HTTP:req_get_headers()
hdr["host"][0] = "www.test.com"
hdr["accept"][0] = "audio/basic q=1"
hdr["accept"][1] = "audio/*, q=0.2"
hdr["accept"][2] = "*/*, q=0.1"
🌈 HTTP.res_get_headers(http)
Returns a table containing all the response headers. 👑
Arguments
http(class_http) — the related http object.
Returns
table of headers.
See HTTP.req_get_headers()
This is the form of the returned table:
HTTP:res_get_headers()['<header-name>'][<header-index>] = "<header-value>"
local hdr = HTTP:req_get_headers()
hdr["host"][0] = "www.test.com"
hdr["accept"][0] = "audio/basic q=1"
hdr["accept"][1] = "audio/*, q=0.2"
hdr["accept"][2] = "*.*, q=0.1"
🌈 HTTP.req_add_header(http, name, value)
Appends an HTTP header field to the request — the name is whatever you put in "name" and the value is whatever you put in "value". Slay. 💅
Arguments
http(class_http) — the related http object.name(string) — the header name.value(string) — the header value.
See HTTP.res_add_header()
🌈 HTTP.res_add_header(http, name, value)
Appends an HTTP header field to the response — name from "name", value from "value". ✨
Arguments
http(class_http) — the related http object.name(string) — the header name.value(string) — the header value.
See HTTP.req_add_header()
🌈 HTTP.req_del_header(http, name)
Removes all HTTP header fields in the request whose name is specified in "name". All of them. Gone. Not even a trace. 💀
Arguments
http(class_http) — the related http object.name(string) — the header name.
See HTTP.res_del_header()
🌈 HTTP.res_del_header(http, name)
Removes all HTTP header fields in the response whose name is specified in "name". Byeeeee. 👋
Arguments
http(class_http) — the related http object.name(string) — the header name.
See HTTP.req_del_header()
🌈 HTTP.req_set_header(http, name, value)
This one replaces all occurrences of every header "name" with just one single header containing the "value". Clean. Efficient. Main character energy. 👑
Arguments
http(class_http) — the related http object.name(string) — the header name.value(string) — the header value.
See HTTP.res_set_header()
okay so this function is lowkey just doing the following under the hood 🫶:
function fcn(txn)
TXN.http:req_del_header("header")
TXN.http:req_add_header("header", "value")
end
HTTP.res_set_header(http, name, value)
This one replaces all the occurrences of every header called name, and leaves you with exactly one that holds value. one header to rule them all, no cap 💅
Arguments
http(class_http) — the related http object, your bestie for this call.name(string) — the header name.value(string) — the header value.
See HTTP.req_rep_header() — the request-side twin ✨
HTTP.req_rep_header(http, name, regex, replace)
Matches the regular expression across all occurrences of the header field name according to regex, then swaps them out for the replace argument. and the replacement value can contain back references like 1, 2, ... ✨ This function works with the request.
Arguments
http(class_http) — the related http object.name(string) — the header name.regex(string) — the match regular expression.replace(string) — the replacement value.
See HTTP.res_rep_header() — for the response side 🦋
HTTP.res_rep_header(http, name, regex, string)
Matches the regular expression across all occurrences of the header field name according to regex, then replaces them with the replace argument. The replacement value can contain back references like 1, 2, ... 💖 This function works with the request.
Arguments
http(class_http) — the related http object.name(string) — the header name.regex(string) — the match regular expression.replace(string) — the replacement value.
See HTTP.req_rep_header() — the request-side version, go look 👀
HTTP.req_set_method(http, method)
Rewrites the request method with the method parameter. glow up for your verb, periodt 🌈
Arguments
http(class_http) — the related http object.method(string) — the new method.
HTTP.req_set_path(http, path)
Rewrites the request path with the path parameter.
Arguments
http(class_http) — the related http object.path(string) — the new path.
HTTP.req_set_query(http, query)
Rewrites the request's query string — yep, the bit that shows up after the first question mark (?) — using the query parameter.
Arguments
http(class_http) — the related http object.query(string) — the new query.
HTTP.req_set_uri(http, uri)
Rewrites the request URI with the uri parameter.
Arguments
http(class_http) — the related http object.uri(string) — the new uri.
HTTP.res_set_status(http, status[, reason])
Rewrites the response status code with the code parameter.
If you don't hand it a custom reason, it just gets generated from the status. auto-generated reason is giving main character energy 👑
Arguments
http(class_http) — the related http object.status(integer) — the new response status code.reason(string) — the new response reason (optional).
class HTTPClient()
Okay so the httpclient class lets you fire off outbound HTTP requests through a super simple API, with zero knowledge of HAProxy's internals required. you literally don't need to know anything about the guts of it, iconic 🎀
but listen — any instance must be used to process one and only one request. It must never be reused to process several requests. one instance, one request, that's the rule 🚫
HTTPClient.get(httpclient, request)
HTTPClient.head(httpclient, request)
HTTPClient.put(httpclient, request)
HTTPClient.post(httpclient, request)
HTTPClient.delete(httpclient, request)
Send a HTTP request and wait for a response. GET, HEAD, PUT, POST and DELETE methods can be used. The HTTPClient will send asynchronously the data and is able to send and receive more than HAProxy bufsize. so yeah, it eats big payloads for breakfast 💪
The HTTPClient interface is not able to decompress responses, so it is not recommended to send an Accept-Encoding in the request, so that the response is received uncompressed. keep it crunchy-fresh, no gzip mystery 🍓
Arguments
httpclient(class) — is the manipulatedHTTPClient.request(table) — is a table containing the parameters of the request that will be send.request.url(string) — is a mandatory parameter for the request that contains the URL.request.body(string) — is an optional parameter for the request that contains the body to send.request.headers(table) — is an optional parameter for the request that contains the headers to send.request.dst(string) — is an optional parameter for the destination in haproxy address format.request.timeout(integer) — optional timeout parameter, set a"timeout server"on the connections.
Returns
Lua table containing the response
local httpclient = core.httpclient()
local response = httpclient:post{url="http://127.0.0.1", body=body, dst="unix@/var/run/http.sock"}
and the response you get back looks like this, so you know exactly what you're catching 👇
response = {
status = 400,
reason = "Bad request",
headers = {
["content-type"] = { "text/html" },
["cache-control"] = { "no-cache", "no-store" },
},
body = "<html><body><h1>invalid request<h1></body></html>",
}
class TXN()
The txn class contains all the functions relative to the http or tcp transaction. (and a lil heads up, bestie: a tcp stream is the same than a tcp transaction, but a HTTP transaction is not the same than a tcp stream. don't mix them up 🙈)
Using this class lets you retrieve data from the requests, alter it, and forward it. it's giving full control 💅
All the functions provided by this class are available in the context sample-fetches, actions and filters. everywhere you need them, fr fr ✨
TXN.c
Returns
An Converters class.
This attribute contains a Converters class object.
TXN.sc
Returns
An Converters class.
This attribute contains a Converters class object. The functions of this object returns always a string. consistency queen 💖
TXN.f
Returns
An Fetches class.
This attribute contains a Fetches class object.
TXN.sf
Returns
An Fetches class.
This attribute contains a Fetches class object. The functions of this object returns always a string.
TXN.req
Returns
An Channel class.
This attribute contains a channel class object for the request buffer. 📥
TXN.res
Returns
An Channel class.
This attribute contains a channel class object for the response buffer. 📤
TXN.http
Returns
An HTTP class.
This attribute contains a HTTP class object. It is available only if the proxy has the "mode http" enabled. no mode http, no TXN.http, sorry 🫠
TXN.http_req
Returns
An HTTPMessage class.
This attribute contains the request HTTPMessage class object. It is available only if the proxy has the "mode http" enabled and only in the filters context.
TXN.http_res
Returns
An HTTPMessage class.
This attribute contains the response HTTPMessage class object. It is available only if the proxy has the "mode http" enabled and only in the filters context.
TXN.log(TXN, loglevel, msg)
This function sends a log 🪵 The log is sent, according with the HAProxy configuration file, to the loggers relevant to the current context and/or to stderr if it is allowed.
the exact behaviour depends ontune.lua.log.loggersandtune.lua.log.stderr. don't come for me, it's literally in the config ✋
Arguments
txn(class_txn) — the class txn object containing the data.loglevel(integer) — is the log level associated with the message. It is a number between0and7.msg(string) — the log content.
See core.emerg, core.alert, core.crit, core.err, core.warning, core.notice, core.info, core.debug (log level definitions)
See TXN.deflog()
See TXN.Debug()
See TXN.Info()
See TXN.Warning()
See TXN.Alert()
TXN.deflog(TXN, msg)
Sends a log line with the default loglevel for the proxy associated with the transaction.
Arguments
txn(class_txn) — the class txn object containing the data.msg(string) — the log content.
See TXN.log()
TXN.Debug(txn, msg)
Arguments
txn(class_txn) — the class txn object containing the data.msg(string) — the log content.
See TXN.log()
Does the same job as:
function Debug(txn, msg)
TXN.log(txn, core.debug, msg)
end
TXN.Info(txn, msg)
Arguments
txn(class_txn) — the class txn object containing the data.msg(string) — the log content.
See TXN.log()
Does the same job as:
function Info(txn, msg)
TXN.log(txn, core.info, msg)
end
TXN.Warning(txn, msg)
Arguments
txn(class_txn) — the class txn object containing the data.msg(string) — the log content.
See TXN.log()
Does the same job as:
function Warning(txn, msg)
TXN.log(txn, core.warning, msg)
end
TXN.Alert(txn, msg)
Arguments
txn(class_txn) — the class txn object containing the data.msg(string) — the log content.
See TXN.log()
Does the same job as:
function Alert(txn, msg)
TXN.log(txn, core.alert, msg)
end
TXN.get_priv(txn)
Return Lua data stored in the current transaction (with the TXN.set_priv()) function. If no data are stored, it returns a nil value. so always check for nil before you go using it, bestie 💀
Arguments
txn(class_txn) — the class txn object containing the data.
Returns — the opaque data you stashed earlier, or nil if there's genuinely nothing in there 🫶
TXN.set_priv(txn, data)
okay so this one stashes literally any data you want inside the current HAProxy transaction. heads up tho — it replaces whatever was there before, no merging, no mercy 💅
Arguments ✨
txn(class_txn) — theclass_txnobject that's holding your data.data(opaque) — the data being stored in the transaction.
TXN.set_var(TXN, var, value[, ifexist])
converts a Lua type into a HAProxy type and tucks it into the variable <var>, slay ✨
Arguments
txn(class_txn) — theclass_txnobject that's holding your data.var(string) — the variable name, written the way HAProxy's variable syntax wants it.value(type) — the value you're attaching to that variable. Type-wise it can be astringor aninteger.ifexist(boolean) — set this totrueand the variable only gets set if it was defined elsewhere (i.e. it's actually used somewhere in the config). for global variables (the ones using the"proc"scope), it means they'll only ever be updated, never created. it is highly recommended to always set this totrue, bestie, fr fr.
TXN.unset_var(TXN, var)
unsets the variable <var>. that's it, that's the function, bye 👋
Arguments
txn(class_txn) — theclass_txnobject that's holding your data.var(string) — the variable name, per HAProxy's variable syntax.
TXN.get_var(TXN, var)
gives you back the data stored in variable <var>, converted into a Lua type. the way it hands you your stuff back in the right format? iconic 🎀
Arguments
txn(class_txn) — theclass_txnobject that's holding your data.var(string) — the variable name, per HAProxy's variable syntax.
TXN.reply([reply])
makes you a brand new reply object ✨
Arguments
reply(table) — a table of info used to initialize the reply's fields.
Returns — a Reply class object.
the table you use to initialize the reply object can carry these entries:
status— the reply status code.200is the default, no vibes needed.reason— the reply reason. defaults to whatever reason matches the status code.headers— a list of headers, indexed by header name. empty by default. for a given name you can have multiple values, and they're stored in an ordered list 👑body— the reply body. empty by default.
local reply = txn:reply{
status = 400,
reason = "Bad request",
headers = {
["content-type"] = { "text/html" },
["cache-control"] = {"no-cache", "no-store" }
},
body = "<html><body><h1>invalid request<h1></body></html>"
}
TXN.done(txn[, reply])
this one ends processing of the transaction and its associated session, and optionally replies to the client for HTTP sessions. main character energy, honestly 💅
Arguments
txn(class_txn) — theclass_txnobject that's holding your data.reply(class_reply) — theclass_replyobject to send back to the client.
you'd reach for this when a critical error pops up, or when you want to wrap things up after some data has already gone back to the client (like, say, a redirect 🙈). to do that you may pass a reply. that object is optional and can carry a status code, a reason, a header list and a body — and every single one of those fields is optional too. when you don't provide them, the defaults kick in. by default, with an empty reply object, the client gets an empty HTTP 200. if you pass no reply object at all, the transaction just gets terminated with no reply whatsoever. and if you do pass a reply object, it must not exceed the buffer size once it's converted into the internal HTTP representation. because for now there's no easy way to be sure it fits, it's probably better to keep it reasonably small 🍓
the reply object can be fully created in lua, or you can use the Reply class to build it.
local reply = txn:reply()
reply:set_status(400, "Bad request")
reply:add_header("content-type", "text/html")
reply:add_header("cache-control", "no-cache")
reply:add_header("cache-control", "no-store")
reply:set_body("<html><body><h1>invalid request<h1></body></html>")
txn:done(reply)
txn:done{
status = 400,
reason = "Bad request",
headers = {
["content-type"] = { "text/html" },
["cache-control"] = { "no-cache", "no-store" },
},
body = "<html><body><h1>invalid request<h1></body></html>"
}
Warning: it does not make sense to call this function from sample-fetches. in that case the behavior is the same as core.done(): it finishes the Lua execution. the transaction is only really aborted from an action registered function. 💀
See TXN.reply(), Reply
TXN.set_fc_tos(txn, tos)
sets the TOS or DSCP field value of packets sent to the client to whatever you pass in "tos" — on platforms that support it, obviously 🌈
Arguments
txn(class_txn) — theclass_txnobject that's holding your data.tos(integer) — the new TOS or DSCP.
TXN.set_fc_mark(txn, mark)
sets the Netfilter MARK on all packets sent to the client to the value you pass in "mark" — again, on platforms that support it ✨
Arguments
txn(class_txn) — theclass_txnobject that's holding your data.mark(integer) — the mark value.
TXN.set_loglevel(txn, loglevel)
changes the log level of the current request. the "loglevel" has to be an integer between 0 and 7, or the special value -1 if you want to disable logging entirely 🙈
Arguments
txn(class_txn) — theclass_txnobject that's holding your data.loglevel(integer) — the log level you want. this variable can be one of the ones below 👇
See core.silent, core.emerg, core.alert, core.crit, core.err, core.warning, core.notice, core.info, core.debug (log level definitions)
TXN.set_mark(txn, mark)
alias for TXN.set_fc_mark().
Warning: this function is deprecated. TXN.set_fc_mark() must be used instead 🫶
TXN.set_tos(txn, tos)
alias for TXN.set_fc_tos().
Warning: this function is deprecated. TXN.set_fc_tos() must be used instead 🫶
TXN.set_priority_class(txn, prio)
adjusts the priority class of the transaction. the value should land in the range -2047..2047, and anything outside that range gets truncated ✂️
See the HAProxy configuration.txt file keyword "http-request" action "set-priority-class" for the deets 📖
TXN.set_priority_offset(txn, prio)
adjusts the priority offset of the transaction. the value should land in the range -524287..524287, and anything outside that range gets truncated too ✂️
See the HAProxy configuration.txt file keyword "http-request" action "set-priority-offset" for the deets 📖
class Reply()
context: action
this class represents an HTTP response message 🎀 it gives you a bunch of methods to dress it up. once it's converted into the internal HTTP representation, the response message must not exceed the buffer size. because for now there's no easy way to know for sure that it fits, it's probably better to keep it reasonably small, bestie 🍓
See tune.bufsize in the configuration manual for the details.
local reply = txn:reply({status = 400}) -- default HTTP 400 reason-phase used
reply:add_header("content-type", "text/html")
reply:add_header("cache-control", "no-cache")
reply:add_header("cache-control", "no-store")
reply:set_body("<html><body><h1>invalid request<h1></body></html>")
See TXN.reply()
Reply.status
the reply status code. by default the status code is set to 200 ✨
Returns integer
Reply.reason
the reason string that describes the status code 💬
Returns string
Reply.headers
a table indexing all the reply headers by name. each name gets an ordered list of values attached to it 👑
Returns Lua table
{
["content-type"] = { "text/html" },
["cache-control"] = {"no-cache", "no-store" },
x_header_name = { "value1", "value2", ... }
...
}
Reply.body
the reply payload 🎁
Returns string
Reply.set_status(REPLY, status[, reason])
sets the reply status code, and optionally the reason-phrase. if you don't hand it a reason, it uses the default reason that matches your status code, no stress 💅
Arguments
reply(class_reply) — the related Reply object.status(integer) — the reply status code.reason(string) — the reply status reason (optional).
Reply.add_header(REPLY, name, value)
adds a header to the reply object. if that header doesn't exist yet, a fresh entry gets created with its name as the index and a one-element list holding its value as the value ✨ otherwise the header value just gets appended to the ordered list of values attached to that header name 🌸
Arguments
reply(class_reply) — the related Reply object.name(string) — the header field name.value(string) — the header field value.
Reply.del_header(REPLY, name)
removes all occurrences of a header name from the reply object. every last one, gone 💀
Arguments
reply(class_reply) — the related Reply object.name(string) — the header field name.
Reply.set_body(REPLY, body)
sets the reply payload 🎁
Arguments
reply(class_reply) — the related Reply object.body(string) — the reply payload.
class Socket() 🌸
okay so this class HAS to be compatible with the Lua Socket class. only the 'client' functions are available tho — we're not doing server stuff here. go read the Lua Socket docs if you want the full lore:
http://w3.impa.br/~diego/software/luasocket/tcp.html
Socket.close(socket) 🎀
closes a TCP object. the internal socket the object was using gets closed, and the local address it was bound to gets released back to other applications. after this, no further operations are allowed on a closed Socket — well, except calling close again, that one's fine.
Arguments 💖
socket(class_socket) — the Socket you're manipulating.
no cap, it's important to close all your used sockets once you don't need them anymore, because on a lot of systems every socket eats a file descriptor, and those are a limited system resource. that said, garbage-collected objects do get automatically closed before destruction, so it's not a total crisis. 🫶
Socket.connect(socket, address[, port]) ✨
tries to connect a socket object to a remote host.
if it fails, the method returns nil followed by a string describing the error. if it works, it returns 1. simple as that.
Arguments 💖
socket(class_socket) — the Socket you're manipulating.address(string) — can be an IP address or a host name. more info below bestie.port(integer) — must be an integer in the range[1..64K].
Returns 1 or nil.
so there's an address field extension that lets you use connect() to connect to streams other than TCP. the plain ipv4 or ipv6 address syntax is basically the expected format. this format requires the port.
other accepted formats include a socket path like "/socket/path" — that lets you connect to a socket. abstract namespaces are supported with the prefix "abns@", and finally a file descriptor can be passed with the prefix "fd@". the prefixes "ipv4@", "ipv6@" and "unix@" are also supported. the port can be passed inside the string — the syntax "127.0.0.1:1234" is valid. and in that case, the port parameter must not be set. okay? okay. 💅
Socket.connect_ssl(socket, address, port) 🔥
same behavior as the function socket:connect, but it uses SSL. slay.
Arguments 💖
socket(class_socket) — the Socket you're manipulating.
Returns 1 or nil.
Socket.getpeername(socket) 🦋
hands you info about the remote side of a connected client object.
it returns a string with the IP address of the peer, followed by the port number that peer is using for the connection. if something goes wrong, it returns nil.
Arguments 💖
socket(class_socket) — the Socket you're manipulating.
Returns a string containing the server information.
Socket.getsockname(socket) 🌈
returns the local address information associated with the object.
the method returns a string with local IP address and a number with the port. if there's an error, it returns nil.
Arguments 💖
socket(class_socket) — the Socket you're manipulating.
Returns a string containing the client information.
Socket.receive(socket[, pattern[, prefix]]) 🍓
reads data from a client object, according to the specified read pattern. patterns follow the Lua file I/O format, and ngl the performance difference between all the patterns is negligible.
Arguments 💖
socket(class_socket) — the Socket you're manipulating.pattern(string|integer) — describes what is required (see below).prefix(string) — a string which will be prefixed to the returned data.
Returns a string containing the required data or nil.
pattern can be any of the following:
*a: reads from the socket until the connection is closed. no end-of-line translation is performed;*l: reads a line of text from the Socket. the line is terminated by a LF character (ASCII 10), optionally preceded by a CR character (ASCII 13). the CR and LF characters are not included in the returned line. in fact, all CR characters are ignored by the pattern. this is the default pattern.- number: causes the method to read a specified number of bytes from the Socket.
prefixis an optional string to be concatenated to the beginning of any received data before return. - empty: if the pattern is left empty, the default option is
*l.
if successful, the method returns the received pattern. if there's an error, the method returns nil followed by an error message — which can be the string 'closed' if the connection was closed before the transmission was completed, or the string 'timeout' if there was a timeout during the operation. also, after the error message, the function returns the partial result of the transmission.
important note bestie: this function was changed severely. it used to support multiple patterns (but honestly nobody ever used that feature) and now it doesn't anymore. partial results used to be returned the same way as successful results. that last feature violated the whole idea that all functions should return nil on error. so yeah, that got changed too. 💀
Socket.send(socket, data[, start[, end]]) 👑
sends data through a client object.
Arguments 💖
socket(class_socket) — the Socket you're manipulating.data(string) — the data that will be sent.start(integer) — the start position in the buffer of the data which will be sent.end(integer) — the end position in the buffer of the data which will be sent.
Returns see below.
data is the string to be sent. the optional arguments i and j work exactly like the standard string.sub Lua function, so you can select a substring to send.
if successful, the method returns the index of the last byte within [start, end] that has been sent. notice that if start is 1 or absent, this is effectively the total number of bytes sent. if there's an error, the method returns nil, followed by an error message, followed by the index of the last byte within [start, end] that has been sent. you might want to try again from the byte following that one. the error message can be 'closed' if the connection was closed before the transmission was completed, or the string 'timeout' if there was a timeout during the operation.
note: output is not buffered. for small strings, it is always better to concatenate them in Lua (with the '..' operator) and send the result in one call, instead of calling the method several times. trust. 😭
Socket.setoption(socket, option[, value]) 🙈
just implemented for compatibility. this call does nothing. that's it, that's the whole function. 💅
Socket.settimeout(socket, value[, mode]) ⭐
changes the timeout values for the object. all I/O operations are blocking. like, any call to the methods send, receive, and accept will block indefinitely until the operation completes. the settimeout method defines a limit on how long the I/O methods can block. once a timeout has elapsed, the affected methods give up and fail with an error code.
the amount of time to wait is specified as the value parameter, in seconds.
the timeout modes are not implemented. the only settable timeout is the inactivity time waiting to complete the internal buffer send, or waiting for receive data.
Arguments 💖
socket(class_socket) — the Socket you're manipulating.value(float) — the timeout value. use floating point to specify milliseconds.
class Regex() 🧚
this class lets you use HAProxy regexes, because classic Lua doesn't provide regexes. this class inherits the HAProxy compilation options, so the regexes can be libc regex, pcre regex, or pcre JIT regex.
the expression matching number is limited to 20 per regex. the only available option is case sensitive.
because regex compilation is a heavy process, it's better to define all your regexes in the body context and use them during the runtime. big brain energy, iykyk. 💜
-- Create the regex
st, regex = Regex.new("needle (..) (...)", true);
-- Check compilation errors
if st == false then
print "error: " .. regex
end
-- Match the regexes
print(regex:exec("Looking for a needle in the haystack")) -- true
print(regex:exec("Lokking for a cat in the haystack")) -- false
-- Extract words
st, list = regex:match("Looking for a needle in the haystack")
print(st) -- true
print(list[1]) -- needle in the
print(list[2]) -- in
print(list[3]) -- the
Regex.new(regex, case_sensitive) 🎀
creates and compiles a regex.
Arguments 💖
regex(string) — the regular expression according with the libc or pcre standard.case_sensitive(boolean) — match is case sensitive or not.
Returns boolean status and Regex class, or a string containing the fail reason.
Regex.exec(regex, str) 🌸
executes the regex.
Arguments 💖
regex(class_regex) — a Regex class object.str(string) — the input string will be compared with the compiled regex.
Returns a boolean status according with the match result.
Regex.match(regex, str) 🦋
executes the regex and returns the matched expressions.
Arguments 💖
map(class_map) — a Regex class object.str(string) — the input string will be compared with the compiled regex.
Returns a boolean status according with the match result, and a table containing all the strings matched, in order of declaration.
🗺️ class Map() 💅
okay so bestie, this class is literally your all-access pass to doing lookups in HAProxy maps 💖 and the plot twist that makes it iconic? the maps you declared can be modified during the runtime through the HAProxy management socket 🔥 no restart needed, we love a glow-up.
here's the vibe in code, look at her:
default = "usa"
-- Create and load map
geo = Map.new("geo.map", Map._ip);
-- Create new fetch that returns the user country
core.register_fetches("country", function(txn)
local src;
local loc;
src = txn.f:fhdr("x-forwarded-for");
if (src == nil) then
src = txn.f:src()
if (src == nil) then
return default;
end
end
-- Perform lookup
loc = geo:lookup(src);
if (loc == nil) then
return default;
end
return loc;
end);
the pattern-matching methods 🎀
Map._int— go hit up the HAProxyconfiguration.txtfile, chapter "Using ACLs and fetching samples", subchapter "ACL basics" if you actually wanna understand this pattern matching method fr fr. also just so u know:Map.intis available too, for compatibility 💜Map._ip— same deal bestie: peep the HAProxyconfiguration.txtfile, chapter "Using ACLs and fetching samples", subchapter "ACL basics" to get how this pattern matching method works. and yes:Map.ipis also available for compatibility ✨Map._str— yep, HAProxyconfiguration.txt, chapter "Using ACLs and fetching samples", subchapter "ACL basics" — that's where this pattern matching method is explained. p.s.Map.stralso exists for compatibility 🦋Map._beg—configuration.txttime, chapter "Using ACLs and fetching samples", subchapter "ACL basics", that's the lore for this pattern matching method. oh andMap.begis available for compatibility too 🌸Map._sub— you know the drill: HAProxyconfiguration.txt, chapter "Using ACLs and fetching samples", subchapter "ACL basics" explains this pattern matching method.Map.sub= also available for compatibility 💅Map._dir— HAProxyconfiguration.txt, chapter "Using ACLs and fetching samples", subchapter "ACL basics" is where this pattern matching method lives. andMap.diris also available for compatibility 🔥Map._dom— for the deets on this pattern matching method: HAProxyconfiguration.txt, chapter "Using ACLs and fetching samples", subchapter "ACL basics".Map.domis also available for compatibility 🫶Map._end— HAProxyconfiguration.txt, chapter "Using ACLs and fetching samples", subchapter "ACL basics" — that's your study guide for this pattern matching method 👑Map._reg— HAProxyconfiguration.txt, chapter "Using ACLs and fetching samples", subchapter "ACL basics" explains this pattern matching method. alsoMap.regis available for compatibility 💜
Map.new(name, method)
creates and load a map ✨ that's it, that's the job.
Arguments
name(string) — is the name referencing the map 🏷️method(integer) — is the map pattern matching method. go look at the attributes of theMapclass for your options 👀
Returns — a class Map object 💖
See — the Map attributes: Map._int, Map._ip, Map._str, Map._beg, Map._sub, Map._dir, Map._dom, Map._end and Map._reg 🎀
Map.lookup(map, str)
perform a lookup in a map 🔍
Arguments
map(class_map) — is the classMapobjectstr(string) — is the string used as key 🔑
Returns — a string containing the result, or nil if there's no match 😭
Map.slookup(map, str)
perform a lookup in a map — same energy as above, different failing vibe 🔍
Arguments
map(class_map) — is the classMapobjectstr(string) — is the string used as key 🔑
Returns — a string containing the result, or an empty string if there's no match 🫶
🧚 class Patref() 🦋
okay so a Patref object is basically the Lua-side twin of the internal HAProxy pat_ref element — the exact thing that's used to store ACL and MAP elements 💾. it's identified by its name (aka its reference), which is often a filename — unless it's prefixed by virt@ for virtual references, or opt@ for references that don't necessarily point to real file 🎀.
and the bestie perk? from Lua, Patref class objects can be used to directly manipulate existing pattern reference storage 🔥. for convenience, Patref objects may be directly accessed and listed as a table thanks to the index and pairs metamethods ✨ — but ngI, heads up on the index metamethod: in case of duplicated entries, only the first matching entry gets returned 🙈.
Warning 💀 — not meant to be shared between multiple contexts. if multiple contexts need to work on the same pattern reference, each context should have its own patref object. no sharing, no drama, periodt.
and where do u even get one? the Patref object is obtained using the core.get_patref() function 👑
Patref.get_name(ref)
Returns — the name of the pattern reference object 🏷️
Patref.is_map(ref)
Returns — true if the pattern reference is used to handle maps instead of acl, false otherwise 🗺️
Patref.purge(ref)
completely prune all pattern reference entries pointed to by the Patref object 💀. and here's the quirky part — this special operation doesn't require committing. no commit arc needed, she just goes.
Patref.prepare(ref)
create a new empty version for the Patref Object 🎀. it's there so you can mess with the Patref object using the update methods without actually applying anything — nothing lands until the commit() method gets called ✨.
Patref.commit(ref)
tries to commit pending Patref object updates — meaning the updates you made to the local object get committed to the underlying pattern reference storage in an atomic manner upon success 💅. and if it flops: upon failure, local pending updates are lost 😭. upon success, all other pending updates on the pattern reference (e.g.: "prepare" from the cli or from other Patref Lua objects) that started before the new one will be pruned 🧹.
Returns — true on success and nil on failure (followed by an error message) 🌈
See — Patref.prepare() and Patref.giveup()
Patref.giveup(ref)
drop the pending patref version created using Patref:prepare(): get back to live dataset 🫶. it's giving "jk nevermind" and honestly? valid.
Patref.add(ref, key[, value])
add a new key to the pattern reference, with associated value for maps 🔑➕
Arguments
key(string) — the string used as a keyvalue(string) — the string used as value to be associated with the key (only relevant for maps) 🗺️
Returns — true on success and nil on failure (followed by an error message) 😭
Note — affects the live pattern reference version, unless Patref.prepare() was called and is still ongoing (waiting for commit or giveup) ✨
patref.add_bulk(ref, table)
adds multiple entries at once to the Pattern reference 📦✨. ngl it's recommended to use this one over Patref.prepare() when you're adding a lot of entries at once, because this one is more efficient 🔥.
Arguments
table(table) —
For ACL, a table of keys strings: t[0] = "key1", t[1] = "key2"...
For Maps, a table of key:value string pairs: t["key"] = "value" 🗺️
Returns — true on success and nil on failure (followed by an error message) 💔
Note — affects the live pattern reference version, unless Patref.prepare() was called and is still pending (waiting for commit or giveup) 🌸
Patref.del(ref, key)
delete all entries matching the input key in the pattern reference. and yes bestie, in case of duplicate keys, all keys are removed — no survivors 💀
Arguments
key(string) — the string used as a key 🔑
Returns — true on success and false on failure 🫶
Note — affects the live pattern reference version, unless Patref.prepare() was called and is still ongoing (waiting for commit or giveup) 🎀
Patref.set(ref, key, value[, force])
only relevant for maps 🗺️. set existing entries matching key to the provided value. and same as before — in case of duplicate keys, all matching keys will be set to the new value 💅
Arguments
key(string) — the string used as a keyvalue(string) — the string used as valueforce(boolean) — create the entry if it doesn't exist (optional, defaults tofalse) ✨
Returns — true on success and nil on failure (followed by an error message) 😭
Note — affects the live pattern reference version, unless Patref.prepare() was called and is still ongoing (waiting for commit or giveup) 🦋
Patref.event_sub(ref, event_types, func)
register a function that will be called on specific PAT_REF events 📣. see core.event_sub() for generalities. but please note — and this is the important tea ☕ — for performance reasons, pattern reference events can only be subscribed per pattern reference (not globally) 🔥. what that means is: the callback function you provide will only be called for events affecting the pattern reference pointed by the Patref object (ref) passed as parameter 👑
so if you wanna be notified about events on a given set of pattern references? totally fine, you can just perform as many per-patref subscriptions as needed, bestie 💖
also, for PAT_REF events, no event data is provided (that's the thing known as "event_data" in the callback function's prototype from core.event_sub()) 🙈
the list of the available event types for the PAT_REF family is:
PAT_REF_ADD— element was added to the current version of the pattern reference ➕PAT_REF_DEL— element was deleted from the current version of the pattern reference 💀PAT_REF_SET— element was modified in the current version of the pattern reference 🎀PAT_REF_CLEAR— all elements were cleared from the current version of the pattern reference 🧹PAT_REF_COMMIT— pending element(s) was/were committed in the current version of the pattern reference ✨
Note: put PAT_REF in your event_types and you're subscribed to every pattern reference event type at once, no cap 💅
And here's a lil working example that shows how to trigger a callback function for the pattern reference tied to the file "test.map" 🫶
core.register_init(function()
-- We assume that "test.map" is a map file referenced in haproxy config
-- file, thus it is loaded during config parsing and is expected to be
-- available at init Lua stage. Indeed, the below code wouldn't work if
-- used directly within body context, as at that time the config is not
-- fully parsed.
local map_patref = core.get_patref("test.map")
map_patref:event_sub({"PAT_REF_ADD"}, function(event, data, sub)
-- in the patref event handler
print("entry added!")
end)
end)
class AppletHTTP() 💖
okay so this class is the moment for applets that need the 'http' mode. The http applet gets registered with core.register_service(). They're literally used for processing an http request like a server hanging out in back of HAProxy 👑
This is an hello world sample code:
core.register_service("hello-world", "http", function(applet)
local response = "Hello World !"
applet:set_status(200)
applet:add_header("content-length", string.len(response))
applet:add_header("content-type", "text/plain")
applet:start_response()
applet:send(response)
end)
AppletHTTP.c 🌸
Returns: A Converters class
This attribute holds a Converters class object.
AppletHTTP.sc 🦋
Returns: A Converters class
This attribute holds a Converters class object. The functions of this object always return a string, periodt.
AppletHTTP.f 🎀
Returns: A Fetches class
This attribute holds a Fetches class object. Quick heads up bestie: the applet execution place cannot access a valid HAProxy core HTTP transaction, so some sample fetches related to the HTTP dependent values (hdr, path, ...) are not available. It's giving limited access, sorry 🥲
AppletHTTP.sf 💜
Returns: A Fetches class
This attribute holds a Fetches class object. The functions of this object always return a string. And same vibe check as above: the applet execution place cannot access a valid HAProxy core HTTP transaction, so some sample fetches related to the HTTP dependent values (hdr, path, ...) are not available.
AppletHTTP.method ✨
Returns: string
The attribute method hands you a string containing the HTTP method. iconic 🫶
AppletHTTP.version 🌈
Returns: string
The attribute version returns a string holding the HTTP request version.
AppletHTTP.path 💫
Returns: string
The attribute path returns a string holding the HTTP request path.
AppletHTTP.qs 🍓
Returns: string
The attribute qs returns a string holding the HTTP request query string.
AppletHTTP.length 🔥
Returns: integer
The attribute length returns an integer holding the HTTP body length.
AppletHTTP.headers 👑
Returns: table
The attribute headers returns a table holding the HTTP headers. The header names are always in lower case (that's the one rule, no exceptions). And because a header name can show up more than once in each request, the value is indexed with 0 as the first index value — yes, zero-indexed fr fr. The table has this form:
AppletHTTP.headers['<header-name>'][<header-index>] = "<header-value>"
so like:
AppletHTTP.headers["host"][0] = "www.test.com"
AppletHTTP.headers["accept"][0] = "audio/basic q=1"
AppletHTTP.headers["accept"][1] = "audio/*, q=0.2"
AppletHTTP.headers["accept"][2] = "*/*, q=0.1"
AppletHTTP.set_status(applet, code[, reason]) 💅
This function sets the HTTP status code for the response. The allowed codes are from 100 to 599 — stay in your lane, anything outside that is not it.
Arguments
applet(class_AppletHTTP) -- An AppletHTTP classcode(integer) -- the status code returned to the client.reason(string) -- the status reason returned to the client (optional).
AppletHTTP.add_header(applet, name, value) 🎀
This function adds a header into the response. Duplicated headers are not collapsed, so they all stay, main character energy. The special header content-length is used to determinate the response length. If it does not exist, a transfer-encoding: chunked is set, and all the write from the AppletHTTP:send() function become a chunk.
Arguments
applet(class_AppletHTTP) -- An AppletHTTP classname(string) -- the header namevalue(string) -- the header value
AppletHTTP.start_response(applet) 🔔
This function indicates to the HTTP engine that it can process and send the response headers. After this is called we cannot add headers to the response anymore, so say your goodbyes first 😭 And also: we cannot use the AppletHTTP:send() function if the AppletHTTP:start_response() is not called. The order matters, bestie.
Arguments
applet(class_AppletHTTP) -- An AppletHTTP class
AppletHTTP.getline(applet) 🧚
This function returns a string containing one line from the http body. If the data returned doesn't contains a final '\n' its assumed than its the last available data before the end of stream.
Arguments
applet(class_AppletHTTP) -- An AppletHTTP class
Returns: a string. The string can be empty if we reach the end of the stream.
AppletHTTP.receive(applet[, size]) 🌸
Reads data from the HTTP body, according to the specified read size. If the size is missing, the function tries to read all the content of the stream until the end. If the size is bigger than the http body, it returns the amount of data available.
Arguments
applet(class_AppletHTTP) -- An AppletHTTP classsize(integer) -- the required read size.
Returns: always return a string, the string can be empty is the connection is closed.
AppletHTTP.send(applet, msg) 📨
Send the message msg on the http request body.
Arguments
applet(class_AppletHTTP) -- An AppletHTTP classmsg(string) -- the message to send.
AppletHTTP.get_priv(applet) 🔐
Return Lua data stored in the current transaction. If no data are stored, it returns a nil value.
Arguments
applet(class_AppletHTTP) -- An AppletHTTP class
Returns: the opaque data previously stored, or nil if nothing is available.
See: AppletHTTP.set_priv()
AppletHTTP.set_priv(applet, data) 🗝️
Store any data in the current HAProxy transaction. This action replaces the old stored data — out with the old, in with the new ✨
Arguments
applet(class_AppletHTTP) -- An AppletHTTP classdata(opaque) -- The data which is stored in the transaction.
See: AppletHTTP.get_priv()
AppletHTTP.set_var(applet, var, value[, ifexist]) 💖
Converts a Lua type in a HAProxy type and store it in a variable var.
Arguments
applet(class_AppletHTTP) -- An AppletHTTP classvar(string) -- The variable name according with the HAProxy variable syntax.value(type) -- The value associated to the variable. The type ca bestringorinteger.ifexist(boolean) -- If this parameter is set totruethe variable will only be set if it was defined elsewhere (i.e. used within the configuration). For global variables (using the"proc"scope), they will only be updated and never created.
It is highly recommended to always set this to true. like, seriously, do it 💅
See: AppletHTTP.unset_var()
See: AppletHTTP.get_var()
AppletHTTP.unset_var(applet, var) 🙈
Unset the variable var. gone, deleted, no longer with us 🌈
Arguments
applet(class_AppletHTTP) -- An AppletHTTP classvar(string) -- The variable name according with the HAProxy variable syntax.
See: AppletHTTP.set_var()
See: AppletHTTP.get_var()
AppletHTTP.get_var(applet, var) 🫶
Returns data stored in the variable var converter in Lua type.
Arguments
applet(class_AppletHTTP) -- An AppletHTTP classvar(string) -- The variable name according with the HAProxy variable syntax.
See: AppletHTTP.set_var()
See: AppletHTTP.unset_var()
class AppletTCP() 🦋
This class is used with applets that requires the 'tcp' mode. The tcp applet can be registered with the core.register_service() function. They are used for processing a tcp stream like a server in back of HAProxy. same energy, different protocol, we love that for them 💖
AppletTCP.c 🌸
Returns: A Converters class
This attribute contains a Converters class object.
AppletTCP.sc ✨
Returns: A Converters class
This attribute contains a Converters class object. The functions of this object always return a string.
AppletTCP.f 🎀
Returns: A Fetches class
This attribute contains a Fetches class object.
AppletTCP.sf 💜
Returns: A Fetches class
This attribute contains a Fetches class object.
AppletTCP.getline(applet) 🍓
This function returns a string containing one line from the stream. If the data returned doesn't contains a final '\n' its assumed than its the last available data before the end of stream.
Arguments
applet(class_AppletTCP) -- An AppletTCP class
Returns: a string. The string can be empty if we reach the end of the stream.
AppletTCP.receive(applet[, size[, timeout]]) 💖
okay bestie, this one reads data from the TCP stream. You tell it how much to read with size — if size is missing, it tries to read the whole entire stream until the end. You can also pass an optional timeout in milliseconds. If you do, the function will return no later than that delay with whatever data is available, or nil if there is no data. If the connection is closed, you get an empty string. slay.
Arguments
applet(class_AppletTCP) — AnAppletTCPclasssize(integer) — the required read size.
Returns return nil if the timeout has expired and no data was available but can still be received. Otherwise, a string is returned, possibly an empty string if the connection is closed.
AppletTCP.try_receive(applet) ✨
Reads available data from the TCP stream and returns immediately. Returns a string containing read bytes or nil if no bytes are available at that time. An empty string is returned if the connection is closed.
Arguments
applet(class_AppletTCP) — AnAppletTCPclass
Returns return nil if no data was available but can still be received. Otherwise, a string is returned, possibly an empty string if the connection is closed.
AppletTCP.send(appletmsg) 📨
Send the message on the stream.
Arguments
applet(class_AppletTCP) — AnAppletTCPclassmsg(string) — the message to send.
AppletTCP.get_priv(applet) 🔐
Return Lua data stored in the current transaction. If no data are stored, it returns a nil value.
Arguments
applet(class_AppletTCP) — AnAppletTCPclass
Returns the opaque data previously stored, or nil if nothing is available.
See AppletTCP.set_priv()
AppletTCP.set_priv(applet, data) 🫶
Store any data in the current HAProxy transaction. This action replaces the old stored data.
Arguments
applet(class_AppletTCP) — AnAppletTCPclassdata(opaque) — The data which is stored in the transaction.
See AppletTCP.get_priv()
AppletTCP.set_var(applet, var, value[, ifexist]) 🌸
Converts a Lua type in a HAProxy type and stores it in a variable <var>.
Arguments
applet(class_AppletTCP) — AnAppletTCPclassvar(string) — The variable name according with the HAProxy variable syntax.value(type) — The value associated to the variable. The type can be string or integer.ifexist(boolean) — If this parameter is set totruethe variable will only be set if it was defined elsewhere (i.e. used within the configuration). For global variables (using the"proc"scope), they will only be updated and never created. It is highly recommended to always set this totrue.
See AppletTCP.unset_var()
See AppletTCP.get_var()
AppletTCP.unset_var(applet, var) 🧹
Unsets the variable <var>.
Arguments
applet(class_AppletTCP) — AnAppletTCPclassvar(string) — The variable name according with the HAProxy variable syntax.
See AppletTCP.unset_var()
See AppletTCP.set_var()
AppletTCP.get_var(applet, var) 🔍
Returns data stored in the variable <var> converter in Lua type.
Arguments
applet(class_AppletTCP) — AnAppletTCPclassvar(string) — The variable name according with the HAProxy variable syntax.
See AppletTCP.unset_var()
See AppletTCP.set_var()
class StickTable() 🦋
context: task, action, sample-fetch
This class can be used to access the HAProxy stick tables from Lua. no cap.
StickTable.info() 📊
Returns stick table attributes as a Lua table. See HAProxy documentation for "stick-table" for canonical info, or check out example below.
Returns Lua table
Assume our table has IPv4 key and gpc0 and conn_rate "columns":
{
expire=<int>, # Value in ms
size=<int>, # Maximum table size
used=<int>, # Actual number of entries in table
data={ # Data columns, with types as key, and periods as values
(-1 if type is not rate counter)
conn_rate=<int>,
gpc0=-1
},
length=<int>, # max string length for string table keys, key length
# otherwise
nopurge=<boolean>, # purge oldest entries when table is full
type="ip" # can be "ip", "ipv6", "integer", "string", "binary"
}
StickTable.lookup(key) 🔎
Returns stick table entry for given <key>
Arguments
key(string) — Stick table key (IP addresses and strings are supported)
Returns Lua table
StickTable.dump([filter]) 🗂️
Returns all entries in stick table. An optional filter can be used to extract entries with specific data values. Filter is a table with valid comparison operators as keys followed by data type name and value pairs. Check out the HAProxy docs for "show table" for more details. For the reference, the supported operators are: "eq", "ne", "le", "lt", "ge", "gt"
For large tables, execution of this function can take a long time (for HAProxy standards). That's also true when filter is used, so take care and measure the impact. 💀
Arguments
filter(table) — Stick table filter
Returns Stick table entries (table)
See below for example filter, which contains 4 entries (or comparisons). (Maximum number of filter entries is 4, defined in the source code)
local filter = {
{"gpc0", "gt", 30}, {"gpc1", "gt", 20}}, {"conn_rate", "le", 10}
}
class Act() 👑
context: action
This class contains all return codes an action may return. It is the lua equivalent to HAProxy "ACT_RET_*" code.
core.register_action("deny", { "http-req" }, function (txn)
return act.DENY
end)
act.CONTINUE 🏃♀️
This attribute is an integer (0). It instructs HAProxy to continue the current ruleset processing on the message. It is the default return code for a lua action.
Returns integer
act.STOP 🛑
This attribute is an integer (1). It instructs HAProxy to stop the current ruleset processing on the message.
act.YIELD ⏸️
This attribute is an integer (2). It instructs HAProxy to temporarily pause the message processing. It will be resumed later on the same rule. The corresponding lua script is re-executed for the start.
act.ERROR 😭
This attribute is an integer (3). It triggers an internal errors The message processing is stopped and the transaction is terminated. For HTTP streams, an HTTP 500 error is returned to the client.
Returns integer
act.DONE ✅
This attribute is an integer (4). It instructs HAProxy to stop the message processing.
Returns integer
act.DENY 🚫
This attribute is an integer (5). It denies the current message. The message processing is stopped and the transaction is terminated. For HTTP streams, an HTTP 403 error is returned to the client if the deny is returned during the request analysis. During the response analysis, a HTTP 502 error is returned and the server response is discarded.
Returns integer
act.ABORT 💥
This attribute is an integer (6). It aborts the current message. The message processing is stopped and the transaction is terminated. For HTTP streams, HAProxy assumes a response was already sent to the client. From the Lua actions point of view, when this code is used, the transaction is terminated with no reply.
Returns integer
act.INVALID 🚨
This attribute is an integer (7). It triggers an internal errors. The message processing is stopped and the transaction is terminated. For HTTP streams, an HTTP 400 error is returned to the client if the error is returned during the request analysis. During the response analysis, a HTTP 502 error is returned and the server response is discarded.
Returns integer
act:wake_time(milliseconds) ⏰
context: action
Set the script pause timeout to the specified time, defined in milliseconds.
Arguments
milliseconds(integer) — the required milliseconds.
This function may be used when a lua action returns act.YIELD, to force its wake-up at most after the specified number of milliseconds.
class filter() 🎀
context: filter
This class contains return codes some filter callback functions may return. It also contains configuration flags and some helper functions. To understand how the filter API works, see doc/internals/api/filters.txt documentation.
filter.CONTINUE 🌟
This attribute is an integer (1). It may be returned by some filter callback functions to instruct this filtering step is finished for this filter.
filter.WAIT ⏳
This attribute is an integer (0). It may be returned by some filter callback functions to instruct the filtering must be paused, waiting for more data or for an external event depending on this filter.
filter.ERROR ❌
This attribute is an integer (-1). It may be returned by some filter callback functions to trigger an error.
filter.FLT_CFG_FL_HTX 🏳️
This attribute is a flag corresponding to the filter flag FLT_CFG_FL_HTX. When it is set for a filter, it means the filter is able to filter HTTP streams.
filter.register_data_filter(chn) 🫧
context: filter
Bestie, this next one is filter.enable_data_filter — it enables the data filtering on the channel chn for the current filter. You can call it at any time from any callback functions that come before the data analysis. 💅
Arguments
chn(class_Channel) — A Channel class.
✨ filter.unregister_data_filter(chn) ✨
context: filter
Okay so this is the opposite of the last one — it disables the data filtering on the channel chn for the current filter. You can call it at any time from any callback functions. No cap. 🛑
Arguments
chn(class_Channel) — A Channel class.
✨ filter.wake_time(milliseconds) ✨
context: filter
Set the script pause timeout to the time you want, defined in milliseconds. 🕒
Arguments
milliseconds(integer) — the required milliseconds.
This function may be used from any lua filter callback function to force its wake-up at most after the specified number of milliseconds. Especially, when filter.CONTINUE is returned. Periodt. 💖
A filter is declared using the core.register_filter() function. The class you provide will be used to instantiate filters. It may define these attributes:
id— The filter identifier. It is a string that identifies the filter and is optional. ✨flags— The filter flags. Onlyfilter.FLT_CFG_FL_HTXmay be set for now. 🔥
Such a filter class must also define all required callback functions in the following list. Note that Filter.new() must be defined otherwise the filter is ignored. Others are optional. 💅
FILTER.new()— Called to instantiate a new filter. This function must be defined.- returns: a Lua object that will be used as filter instance for the current stream.
FILTER.start_analyze(flt, txn, chn)— Called when the analysis starts on the channelchn.FILTER.end_analyze(flt, txn, chn)— Called when the analysis ends on the channelchn.FILTER.http_headers(flt, txn, http_msg)— Called just before the HTTP payload analysis and after any processing on the HTTP messagehttp_msg. This callback function is only called for HTTP streams.FILTER.http_payload(flt, txn, http_msg)— Called during the HTTP payload analysis on the HTTP messagehttp_msg. This callback function is only called for HTTP streams.FILTER.http_end(flt, txn, http_msg)— Called after the HTTP payload analysis on the HTTP messagehttp_msg. This callback function is only called for HTTP streams.FILTER.tcp_payload(flt, txn, chn)— Called during the TCP payload analysis on the channelchn.
Here is a full example: 🎀
Trace = {}
Trace.id = "Lua trace filter"
Trace.flags = filter.FLT_CFG_FL_HTX;
Trace.__index = Trace
function Trace:new()
local trace = {}
setmetatable(trace, Trace)
trace.req_len = 0
trace.res_len = 0
return trace
end
function Trace:start_analyze(txn, chn)
if chn:is_resp() then
print("Start response analysis")
else
print("Start request analysis")
end
filter.register_data_filter(self, chn)
end
function Trace:end_analyze(txn, chn)
if chn:is_resp() then
print("End response analysis: "..self.res_len.." bytes filtered")
else
print("End request analysis: "..self.req_len.." bytes filtered")
end
end
function Trace:http_headers(txn, http_msg)
stline = http_msg:get_stline()
if http_msg.channel:is_resp() then
print("response:")
print(stline.version.." "..stline.code.." "..stline.reason)
else
print("request:")
print(stline.method.." "..stline.uri.." "..stline.version)
end
for n, hdrs in pairs(http_msg:get_headers()) do
for i,v in pairs(hdrs) do
print(n..": "..v)
end
end
return filter.CONTINUE
end
function Trace:http_payload(txn, http_msg)
body = http_msg:body(-20000)
if http_msg.channel:is_resp() then
self.res_len = self.res_len + body:len()
else
self.req_len = self.req_len + body:len()
end
end
core.register_filter("trace", Trace, function(trace, args)
return trace
end)
✨ class HTTPMessage() ✨
context: filter
This class contains all functions to manipulate a HTTP message. For now, this class is only available from a filter context. Iykyk. 🌸
✨ HTTPMessage.add_header(http_msg, name, value) ✨
Appends a HTTP header field in the HTTP message http_msg whose name is specified in name and whose value is defined in value. ✨
Arguments
http_msg(class_httpmessage) — The manipulated HTTP message.name(string) — The header name.value(string) — The header value.
✨ HTTPMessage.append(http_msg, string) ✨
This function copies the string string at the end of incoming data of the HTTP message http_msg. The function returns the copied length on success or -1 if data cannot be copied. 🫶
Same that HTTPMessage.insert(http_msg, string, http_msg:input())(). (Yes bestie, that's literally what it says. 💀)
Arguments
http_msg(class_httpmessage) — The manipulated HTTP message.string(string) — The data to copy at the end of incoming data.
Returns
an integer containing the amount of bytes copied or -1.
✨ HTTPMessage.body(http_msgl[, offset[, length]]) ✨
This function returns length bytes of incoming data from the HTTP message http_msg, starting at the offset offset. The data are not removed from the buffer. No cap. 🧚
By default, if no length is provided, all incoming data found, starting at the given offset, are returned. If length is set to -1, the function tries to retrieve a maximum of data. Because it is called in the filter context, it never yield. Not providing an offset is the same as setting it to 0. A positive offset is relative to the beginning of incoming data of the http_message buffer while negative offset is relative to their end. 📍
If there is no incoming data and the HTTP message can't receive more data, a nil value is returned. 🌙
Arguments
http_msg(class_httpmessage) — The manipulated HTTP message.offset(integer) — optional The offset in incoming data to start to get data.0by default. May be negative to be relative to the end of incoming data.length(integer) — optional The expected length of data to retrieve. All incoming data by default. May be set to-1to get a maximum of data.
Returns
a string containing the data found or nil.
✨ HTTPMessage.eom(http_msg) ✨
This function returns true if the end of message is reached for the HTTP message http_msg. 💅
Arguments
http_msg(class_httpmessage) — The manipulated HTTP message.
Returns
an integer containing the amount of available bytes.
✨ HTTPMessage.del_header(http_msg, name) ✨
Removes all HTTP header fields in the HTTP message http_msg whose name is specified in name. Bye felicia. 👋
Arguments
http_msg(class_httpmessage) — The manipulated HTTP message.name(string) — The header name.
✨ HTTPMessage.get_headers(http_msg) ✨
Returns a table containing all the headers of the HTTP message http_msg. 📋
Arguments
http_msg(class_httpmessage) — The manipulated HTTP message.
Returns
table of headers.
This is the form of the returned table:
http_msg:get_headers()['<header-name>'][<header-index>] = "<header-value>"
local hdr = http_msg:get_headers()
hdr["host"][0] = "www.test.com"
hdr["accept"][0] = "audio/basic q=1"
hdr["accept"][1] = "audio/*, q=0.2"
hdr["accept"][2] = "*.*, q=0.1"
✨ HTTPMessage.get_stline(http_msg) ✨
Returns a table containing the start-line of the HTTP message http_msg. 🎀
Arguments
http_msg(class_httpmessage) — The manipulated HTTP message.
Returns
the start-line.
This is the form of the returned table:
-- for the request :
{"method" = string, "uri" = string, "version" = string}
-- for the response:
{"version" = string, "code" = string, "reason" = string}
✨ HTTPMessage.forward(http_msg, length) ✨
This function forwards length bytes of data from the HTTP message http_msg. Because it is called in the filter context, it never yields. Only available incoming data may be forwarded, even if the requested length exceeds the available amount of incoming data. It returns the amount of data forwarded. 🚀
Arguments
http_msg(class_httpmessage) — The manipulated HTTP message.int(integer) — The amount of data to forward.
✨ HTTPMessage.input(http_msg) ✨
This function returns the length of incoming data in the HTTP message http_msg from the filter point of view. 👀
Arguments
http_msg(class_httpmessage) — The manipulated HTTP message.
Returns
an integer containing the amount of available bytes.
✨ HTTPMessage.insert(http_msg, string[, offset]) ✨
This function copies the string string at the offset offset in incoming data of the HTTP message http_msg. The function returns the copied length on success or -1 if data cannot be copied. ✨
By default, if no offset is provided, the string is copied in front of incoming data. A positive offset is relative to the beginning of incoming data of the HTTP message while negative offset is relative to their end. 📍
Arguments
http_msg(class_httpmessage) — The manipulated HTTP message.string(string) — The data to copy into incoming data.offset(integer) — optional, bestie 💫 the spot in the incoming data where the copying starts. It's0by default, and it can be negative if you want it counted from the end of the incoming data instead. Choose your fighter.
Returns an integer holding the amount of bytes copied — or -1 if it went sideways. 😭
💖 HTTPMessage.is_full(http_msg)
Returns true if the HTTP message http_msg is full. That's it, that's the whole vibe ✨
Arguments
http_msg(class_httpmessage) — the manipulated HTTP message.
Returns a boolean. 🫶
🌸 HTTPMessage.is_resp(http_msg)
Returns true if the HTTP message http_msg is the response one (and not the request one, obviously 💅).
Arguments
http_msg(class_httpmessage) — the manipulated HTTP message.
Returns a boolean. ⭐
🦋 HTTPMessage.may_recv(http_msg)
Returns true if the HTTP message http_msg may still receive data. Like, is there more coming or are we done here?
Arguments
http_msg(class_httpmessage) — the manipulated HTTP message.
Returns a boolean. 🌈
🎀 HTTPMessage.output(http_msg)
Hands you the length of the outgoing data of the HTTP message http_msg. Ngl this is the "how much stuff did we send out" counter.
Arguments
http_msg(class_httpmessage) — the manipulated HTTP message.
Returns an integer containing the amount of available bytes. 👑
✨ HTTPMessage.prepend(http_msg, string)
Copies string in front of the incoming data of the HTTP message http_msg. Returns the copied length on success, or -1 if the data can't be copied. 😤
It's literally the same thing as HTTPMessage.insert(http_msg, string, 0)().
Arguments
http_msg(class_httpmessage) — the manipulated HTTP message.string(string) — the data to copy in front of incoming data.
Returns an integer containing the amount of bytes copied or -1.
💜 HTTPMessage.remove(http_msg[, offset[, length]])
Removes length bytes of incoming data from the HTTP message http_msg, starting at offset. Returns the number of bytes removed on success. Poof, gone, no evidence 🫥
By default, if no length is given, all incoming data starting at the given offset gets removed. Not passing an offset at all is the same as setting it to 0. A positive offset is relative to the beginning of the incoming data of the HTTP message, while a negative offset is relative to the end.
Arguments
http_msg(class_httpmessage) — the manipulated HTTP message.offset(integer) — optional. The offset in incoming data where to start to remove data.0by default. May be negative to be relative to the end of incoming data.length(integer) — optional. The length of data to remove. All incoming data by default.
Returns an integer containing the amount of bytes removed.
🍓 HTTPMessage.rep_header(http_msg, name, regex, replace)
Matches the regular expression regex in all occurrences of the header field name, and replaces them with the string replace. The replacement value can contain back references like 1, 2, ... 👀
Heads up: this function acts on whole header lines, regardless of how many values they may contain. iykyk.
Arguments
http_msg(class_httpmessage) — the manipulated HTTP message.name(string) — the header name.regex(string) — the match regular expression.replace(string) — the replacement value.
🧚 HTTPMessage.rep_value(http_msg, name, regex, replace)
Matches the regular expression regex on every comma-delimited value of the header field name, and swaps them for the string replace. The replacement value can contain back references like 1, 2, ... ✨
So where rep_header goes line by line, this one goes value by value. Different energy, both iconic.
Arguments
http_msg(class_httpmessage) — the manipulated HTTP message.name(string) — the header name.regex(string) — the match regular expression.replace(string) — the replacement value.
💅 HTTPMessage.send(http_msg, string)
This one requires an immediate send of the string string. Meaning: the string is copied at the beginning of the incoming data of the HTTP message http_msg and forwarded immediately. And because it's called in the filter context, it never yields. No waiting, no queueing, it just goes 🚀
Arguments
http_msg(class_httpmessage) — the manipulated HTTP message.string(string) — the data to send.
Returns an integer containing the amount of bytes copied or -1.
🌟 HTTPMessage.set(http_msg, string[, offset[, length]])
Replaces length bytes of incoming data of the HTTP message http_msg, starting at offset, with the string string. Returns the copied length on success, or -1 if the data can't be copied. It's giving find-and-replace but make it low-level 💖
By default, if no length is provided, all incoming data starting at the given offset gets replaced. Not providing an offset is the same as setting it to 0. A positive offset is relative to the beginning of the incoming data of the HTTP message, while a negative offset is relative to the end.
Arguments
http_msg(class_httpmessage) — the manipulated HTTP message.string(string) — the data to copy into incoming data.offset(integer) — optional. The offset in incoming data where to start the data replacement.0by default. May be negative to be relative to the end of incoming data.length(integer) — optional. The length of data to replace. All incoming data by default.
Returns an integer containing the amount of bytes copied or -1.
🔥 HTTPMessage.set_body_len(http_msg, length)
Changes the expected payload length of the HTTP message http_msg. length can be an integer value — and in that case a "Content-Length" header gets added with that value. It's also possible to pass the "chunked" string instead of an integer to force the HTTP message to be chunk-encoded. In that case, a "Transfer-Encoding" header is added with the "chunked" value. In both cases, all existing "Content-Length" and "Transfer-Encoding" headers are removed. Clean slate, periodt. 🧼
This function should be used in the filter context to be able to alter the payload of the HTTP message. The internal state of the HTTP message is updated accordingly. And in that case, the HTTPMessage.add_header() or HTTPMessage.set_header() functions must be used. No skipping steps bestie 😤
Arguments
http_msg(class_httpmessage) — the manipulated HTTP message.length(type) — the new payload length to set. It can be an integer or the string"chunked".
Returns true if the payload length was successfully updated, false otherwise.
🫶 HTTPMessage.set_eom(http_msg)
Sets the end of message for the HTTP message http_msg. That's the mic drop moment 🎤
Arguments
http_msg(class_httpmessage) — the manipulated HTTP message.
🌈 HTTPMessage.set_header(http_msg, name, value)
Replaces all occurrences of all headers matching the name name with only one header containing the value value. Many become one. 💫
Arguments
http_msg(class_httpmessage) — the manipulated HTTP message.name(string) — the header name.value(string) — the header value.
This function does the same work as the following code:
http_msg:del_header("header")
http_msg:add_header("header", "value")
🎀 HTTPMessage.set_method(http_msg, method)
Rewrites the request method with the string method. The HTTP message http_msg must be the request. Don't try this on a response, it will not eat 💀
Arguments
http_msg(class_httpmessage) — the manipulated HTTP message.method(string) — the new method.
🦋 HTTPMessage.set_path(http_msg, path)
Rewrites the request path with the string path. The HTTP message http_msg must be the request.
Arguments
http_msg(class_httpmessage) — the manipulated HTTP message.method(string) — the new method.
Not me noticing the manpage calls this last argument method — it's literally copy-pasted from the one above 🙈 but yeah, the thing you're passing in is the new path. Facts only, no edits.
💖 HTTPMessage.set_query(http_msg, query)
Rewrites the request's query string — the bit that appears after the first question mark ("?") — with the string query. The HTTP message http_msg must be the request.
Arguments
http_msg(class_httpmessage) — the manipulated HTTP message.query(string) — the new query.
⭐ HTTPMessage.set_status(http_msg, status[, reason])
Rewrites the response status code with the integer code and optionally the reason reason. If no custom reason is provided, it gets generated from the status. The HTTP message http_msg must be the response. 👑
Arguments
http_msg(class_httpmessage) — the manipulated HTTP message.status(integer) — the new response status code.reason(string) — the new response reason (optional).
💜 HTTPMessage.set_uri(http_msg, uri)
Rewrites the request URI with the string uri. The HTTP message http_msg must be the request.
Arguments
http_msg(class_httpmessage) — the manipulated HTTP message.uri(string) — the new uri.
🍓 HTTPMessage.unset_eom(http_msg)
Removes the end of message for the HTTP message http_msg. Undoing the mic drop, iconic behaviour ✨
Arguments
http_msg(class_httpmessage) — the manipulated HTTP message.
👑 class CertCache()
This class lets you update an SSL certificate file in the memory of the current HAProxy process. It does the exact same thing as "set ssl cert" + "commit ssl cert" over the HAProxy CLI. Same result, but from inside your Lua, bestie 💅
💾 CertCache.set(certificate)
Okay bestie, this one updates a certificate in memory. That's it, that's the whole vibe. 💅
Arguments
certificate(table) — a table holding all the fields you wanna update. 🎀certificate.filename(string) — the mandatory filename of the cert you're updating. It must already exist in memory, no cap. If it's not there, this isn't it. 🙈certificate.crt(string) — a certificate in PEM format. It can also contain a private key, so that's a lil two-for-one situation. ✨certificate.key(string) — a private key in PEM format. 🔑certificate.ocsp(string) — an OCSP response in base64. (cfmanagement.txt— go read it, iykyk) 📜certificate.issuer(string) — the certificate of the OCSP issuer.certificate.sctl(string) — an SCTL file. ⭐
Note: This function may be slow. So it may only be used during startup (main or init context) or from a yield-capable runtime context. Do not just yeet it into some random non-yielding context, bestie, it will not go well. 😭
CertCache.set{filename="certs/localhost9994.pem.rsa", crt=crt}
A lot of useful lua libraries can be found here: 🌈
- Lua toolbox has been superseded by
https://luarocks.org/
The old lua toolbox source code is still available here https://github.com/catwell/lua-toolbox (DEPRECATED) — yeah it's giving vintage, not in a cute way. 💀
Redis client library: 🍓
This is an example about the usage of the Redis library within HAProxy. Note that each call to any function of this library can throw an error if the socket connection fails. 👀
-- load the redis library
local redis = require("redis");
function do_something(txn)
-- create and connect new tcp socket
local tcp = core.tcp();
tcp:settimeout(1);
tcp:connect("127.0.0.1", 6379);
-- use the redis library with this new socket
local client = redis.connect({socket=tcp});
client:ping();
end
OpenSSL: 🔐
👑 AUTHOR
Thierry FOURNIER
🎀 COPYRIGHT
2015, Thierry FOURNIER
and that's the whole page, bestie!! we made it to the end of HAPROXY-LUA(1) 🫶✨ this lil masterpiece is version <rainbow>1.0</rainbow>, dated <cyan>Sep 18, 2026</cyan>, and it's genuinely iconic. go forth and slay your Lua, ily 💖🦋
📦 where this page comes from
- ubuntu stonking: haproxy 3.4.2-1ubuntu4 · GPL-2.0-or-later
- 💖 girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms