Scroll to navigation

HAPROXY-LUA(1) haproxy-lua HAPROXY-LUA(1)

NAME

haproxy-lua - haproxy-lua Documentation

HAPROXY LUA RUNNING CONTEXTS

The Lua code executed in HAProxy can be processed in 2 main modes. The first one is the initialisation mode, and the second is the runtime mode.

  • In the initialisation mode, we can perform DNS solves, but we cannot perform socket I/O. In this initialisation mode, HAProxy still blocked during the execution of the Lua program.
  • In the runtime mode, we cannot perform 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.

The Lua code is loaded in one or more files. These files contains main code and functions. Lua have 6 execution context.

1.
The Lua file body context. It is executed during the load of the Lua file in the HAProxy [global] section with the directive lua-load. It is executed in initialisation mode. This section is use for configuring Lua bindings in HAProxy.
2.
The Lua init context. It is a Lua function executed just after the HAProxy configuration parsing. The execution is in initialisation mode. In this context the HAProxy environment are already initialized. It is useful to check configuration, or initializing socket connections or tasks. These functions are 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().
3.
The Lua task context. It is 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 is executed in runtime mode. The prototype of the function is a simple function without return value and without parameters, like this: function fcn().
4.
The action context. It is a Lua function conditionally executed. These actions are registered by the Lua directives "core.register_action()". The prototype of the Lua called function is a function with doesn't returns anything and that take an object of class TXN as entry. function fcn(txn).
5.
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 are useful to aggregate some of original HAProxy sample-fetches and return the result. The prototype of the function is function string fcn(txn). These functions can be registered with the Lua function core.register_fetches(). Each declared sample-fetch is prefixed by the string "lua.".

NOTE: It is possible that this function cannot found the required data in the original HAProxy sample-fetches, in this case, it cannot return the result. This case is not yet supported

6.
The converter context. It is a Lua function that takes a string as input and returns another string as output. These types of function are stateless, it cannot access to 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 function core.register_converters(). Each declared converter is prefixed by the string "lua.".

HAPROXY LUA HELLO WORLD

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 other terminal, you can test with telnet:

#:~ telnet 127.0.0.1 10001
hello world


The "core" class contains all the HAProxy core functions. These function are useful for the controlling the execution flow, registering hooks, manipulating global maps or ACL, ...

"core" class is basically provided with HAProxy. No require line is required to uses these function.

The "core" class is static, it is not possible to create a new object of this type.


integer

This attribute is an integer, it contains the value of the loglevel "emergency" (0).


integer

This attribute is an integer, it contains the value of the loglevel "alert" (1).


integer

This attribute is an integer, it contains the value of the loglevel "critical" (2).


integer

This attribute is an integer, it contains the value of the loglevel "error" (3).


integer

This attribute is an integer, it contains the value of the loglevel "warning" (4).


integer

This attribute is an integer, it contains the value of the loglevel "notice" (5).


integer

This attribute is an integer, it contains the value of the loglevel "info" (6).


integer

This attribute is an integer, it contains the value of the loglevel "debug" (7).


context: task, action, sample-fetch, converter

This attribute is a table of declared proxies (frontend and backends). Each proxy give an access to his list of listeners and servers. The table is indexed by proxy name, and each entry is of type Proxy class.

Warning, if you are declared frontend and backend with the same name, only one of these are listed.

core.backends
core.frontends


context: task, action, sample-fetch, converter

This attribute is a table of declared proxies with backend capability. Each proxy give an access to his list of listeners and servers. The table is indexed by the backend name, and each entry is of type Proxy class.

core.proxies
core.frontends


context: task, action, sample-fetch, converter

This attribute is a table of declared proxies with frontend capability. Each proxy give an access to his list of listeners and servers. The table is indexed by the frontend name, and each entry is of type Proxy class.

core.proxies
core.backends


context: body, init, task, action, sample-fetch, converter

This function sends a log. The log is sent, according with the HAProxy configuration file, on the default syslog server if it is configured and on the stderr if it is allowed.

  • loglevel (integer) -- Is the log level associated with the message. It is a number between 0 and 7.
  • msg (string) -- The log content.

core.emerg, core.alert, core.crit, core.err, core.warning, core.notice, core.info, core.debug (log level definitions)
core.Debug()
core.Info()
core.Warning()
core.Alert()


context: body, init, task, action, sample-fetch, converter
msg (string) -- The log content.

core.log()

Does the same job than:


function Debug(msg)

core.log(core.debug, msg) end


context: body, init, task, action, sample-fetch, converter
msg (string) -- The log content.

core.log()


function Info(msg)

core.log(core.info, msg) end


context: body, init, task, action, sample-fetch, converter
msg (string) -- The log content.

core.log()


function Warning(msg)

core.log(core.warning, msg) end


context: body, init, task, action, sample-fetch, converter
msg (string) -- The log content.

core.log()


function Alert(msg)

core.log(core.alert, msg) end


context: init, task, action, sample-fetch, converter

Add the ACL key in the ACLs list referenced by the file filename.

  • filename (string) -- the filename that reference the ACL entries.
  • key (string) -- the key which will be added.



context: init, task, action, sample-fetch, converter

Delete the ACL entry referenced by the key key in the list of ACLs referenced by filename.

  • filename (string) -- the filename that reference the ACL entries.
  • key (string) -- the key which will be deleted.



context: init, task, action, sample-fetch, converter

Delete the map entry indexed with the specified key in the list of maps referenced by his filename.

  • filename (string) -- the filename that reference the map entries.
  • key (string) -- the key which will be deleted.



context: body, init, task, action, sample-fetch, converter

Returns HAProxy core information. We can found information like the uptime, the pid, memory pool usage, tasks number, ...

These information are also returned by the management socket via the command "show info". See the management socket documentation for more information about the content of these variables.

an array of values.


context: body, init, task, action

This function returns the current time. The time returned is fixed by the HAProxy core and assures than the hour will be monotonic and that the system call 'gettimeofday' will not be called too. The time is refreshed between each Lua execution or resume, so two consecutive call to the function "now" will probably returns the same result.

a table which contains two entries "sec" and "usec". "sec" contains the current at the epoch format, and "usec" contains the current microseconds.


context: body, init, task, action

This function take a string representing http date, and returns an integer containing the corresponding date with a epoch format. A valid http date me respect the format IMF, RFC850 or ASCTIME.

date (string) -- a date http-date formatted

integer containing epoch date
core.imf_date().
core.rfc850_date().
core.asctime_date().
https://tools.ietf.org/html/rfc7231#section-7.1.1.1


context: body, init, task, action

This function take a string representing IMF date, and returns an integer containing the corresponding date with a epoch format.

date (string) -- a date IMF formatted

integer containing epoch date
https://tools.ietf.org/html/rfc7231#section-7.1.1.1

The IMF format is like this:


Sun, 06 Nov 1994 08:49:37 GMT


context: body, init, task, action

This function take a string representing RFC850 date, and returns an integer containing the corresponding date with a epoch format.

date (string) -- a date RFC859 formatted

integer containing epoch date
https://tools.ietf.org/html/rfc7231#section-7.1.1.1

The RFC850 format is like this:


Sunday, 06-Nov-94 08:49:37 GMT


context: body, init, task, action

This function take a string representing ASCTIME date, and returns an integer containing the corresponding date with a epoch format.

date (string) -- a date ASCTIME formatted

integer containing epoch date
https://tools.ietf.org/html/rfc7231#section-7.1.1.1

The ASCTIME format is like this:


Sun Nov  6 08:49:37 1994


context: body, init, task, action

This function take a string representing http date, and returns an integer containing the corresponding date with a epoch format.

date (string) -- a date http-date formatted



context: body, init, task, action

This function take a string representing http date, and returns an integer containing the corresponding date with a epoch format.

date (string) -- a date http-date formatted



context: body, init, task, action

The core.msleep() stops the Lua execution between specified milliseconds.

milliseconds (integer) -- the required milliseconds.



context: body, init, task, action, sample-fetch, converter

Proxies is a table containing the list of all proxies declared in the configuration file. The table is indexed by the proxy name, and each entry of the proxies table is an object of type Proxy class.

Warning, if you have declared a frontend and backend with the same name, only one of these are listed.


context: body

Register a Lua function executed as action. All the registered action can be used in HAProxy with the prefix "lua.". An action gets a TXN object class as input.

  • name (string) -- is the name of the converter.
  • actions (table) -- is a table of string describing the HAProxy actions who want to register to. The expected actions are 'tcp-req', 'tcp-res', 'http-req' or 'http-res'.
  • nb_args (integer) -- is the expected number of argument for the action. By default the value is 0.
  • func (function) -- is the Lua function called to work as converter.


The prototype of the Lua function used as argument is:


function(txn [, arg1 [, arg2]])



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


context: body

Register a Lua function executed as converter. All the registered converters can be used in HAProxy with the prefix "lua.". An converter get a string as input and return a string as output. The registered function can take up to 9 values as parameter. All the value are strings.

  • 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 choose by the developer.



context: body

Register a Lua function executed as sample fetch. All the registered sample fetch can be used in HAProxy with the prefix "lua.". A Lua sample fetch return a string as output. The registered function can take up to 9 values as parameter. All the value are strings.

  • name (string) -- is the name of the converter.
  • 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 choose by the developer.
  • Returns: A string containing some data, or nil if 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]


context: body

Register a Lua function executed as a service. All the registered service can be used in HAProxy with the prefix "lua.". A service gets an object class as input according with the required mode.

  • name (string) -- is the name of the converter.
  • mode (string) -- is string describing the required mode. Only 'tcp' or 'http' are allowed.
  • func (function) -- is the Lua function called to work as converter.


The prototype of the Lua function used as argument is:


function(applet)


applet applet will be a AppletTCP class or a AppletHTTP class. It depends the type of registered applet. An applet registered with the 'http' value for the mode parameter will gets a AppletHTTP class. If the mode value is 'tcp', the applet will gets a AppletTCP class.

warning: Applets of type 'http' cannot be called from 'tcp-' rulesets. Only the 'http-' rulesets are authorized, this means that is not possible to call an HTTP applet from a proxy in tcp mode. Applets of type 'tcp' can be called from anywhere.

Here, an example of service registration. The service just send an 'Hello world' as an http response.



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


context: body

Register a function executed after the configuration parsing. This is useful to check any parameters.

func (function) -- is the Lua function called to work as initializer.


The prototype of the Lua function used as argument is:


function()


It takes no input, and no output is expected.


context: body, init, task, action, sample-fetch, converter

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.

func (function) -- is the Lua function called to work as initializer.


The prototype of the Lua function used as argument is:


function()


It takes no input, and no output is expected.


context: body

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.

  • path (array) -- is the sequence of word for which the cli execute the Lua binding.
  • usage (string) -- is the usage message displayed in the help.
  • func (function) -- is the Lua function called to handle the CLI commands.


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.


context: task, action, sample-fetch, converter

Change the nice of the current task or current session.

nice (integer) -- the nice value, it must be between -1024 and 1024.



context: init, task, action, sample-fetch, converter

Set the value value associated to the key key in the map referenced by filename.

  • filename (string) -- the Map reference
  • key (string) -- the key to set or replace
  • value (string) -- the associated value



context: body, init, task, action

The core.sleep() functions stop the Lua execution between specified seconds.

seconds (integer) -- the required seconds.



context: init, task, action

This function returns a new object of a socket class.

A Socket class object.


context: body, init, task, action, sample-fetch, converter

This function returns a new concat object.

A Concat class object.


context: body, init, task, action, sample-fetch, converter
data (any) -- Return some data for the caller. It is useful with sample-fetches and sample-converters.


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). 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".


context: task, action, sample-fetch, converter

Give back the hand at the HAProxy scheduler. It is used when the LUA processing consumes a lot of processing time.


context: body, init, task, action, sample-fetch, converter
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".

a userdata containing network or nil if an error occurs.

Parse ipv4 or ipv6 addresses and its facultative associated network.


context: body, init, task, action, sample-fetch, converter
  • addr1 -- is an address created with "core.parse_addr".
  • addr2 -- is an address created with "core.parse_addr".

boolean, true if the network of the addresses match, else returns false.

Match two networks. For example "127.0.0.1/32" matches "127.0.0.0/8". The order of network is not important.


context: body, init, task, action, sample-fetch, converter

This function is useful for tokenizing an entry, or splitting some messages. :param string str: The string which will be split. :param string separators: A string containing a list of separators. :param boolean noblank: Ignore empty entries. :returns: an array of string.

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" ]


This class provides a way for manipulating proxy and retrieving information like statistics.

Contain the name of the proxy.

Contain the unique identifier of the proxy.

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.

Contains a stick table object attached to the proxy.

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.

Pause the proxy. See the management socket documentation for more information.
px (class_proxy) -- A Proxy class which indicates the manipulated proxy.



Resume the proxy. See the management socket documentation for more information.
px (class_proxy) -- A Proxy class which indicates the manipulated proxy.



Stop the proxy. See the management socket documentation for more information.
px (class_proxy) -- A Proxy class which indicates the manipulated proxy.



Kill the session attached to a backup server. See the management socket documentation for more information.
px (class_proxy) -- A Proxy class which indicates the manipulated proxy.



Returns a string describing the capabilities of the proxy.
px (class_proxy) -- A Proxy class which indicates the manipulated proxy.

a string "frontend", "backend", "proxy" or "ruleset".


Returns a string describing the mode of the current proxy.
px (class_proxy) -- A Proxy class which indicates the manipulated proxy.

a string "tcp", "http", "health" or "unknown"


Returns a table containing the proxy statistics. The statistics returned are not the same if the proxy is frontend or a backend.
px (class_proxy) -- A Proxy class which indicates the manipulated proxy.

a key/value table containing stats


This class provides a way for manipulating servers and retrieving information.

Contain the name of the server.

Contain the proxy unique identifier of the server.

Return true if the server is currently draining sticky connections.
sv (class_server) -- A Server class which indicates the manipulated server.

a boolean


Dynamically change the maximum connections of the server. See the management socket documentation for more information about the format of the string.
  • sv (class_server) -- A Server class which indicates the manipulated server.
  • maxconn (string) -- A string describing the server maximum connections.



This function returns an integer representing the server maximum connections.
sv (class_server) -- A Server class which indicates the manipulated server.

an integer.


Dynamically change the weight of the server. See the management socket documentation for more information about the format of the string.
  • sv (class_server) -- A Server class which indicates the manipulated server.
  • weight (string) -- A string describing the server weight.



This function returns an integer representing the server weight.
sv (class_server) -- A Server class which indicates the manipulated server.

an integer.


Dynamically change the address of the server. See the management socket documentation for more information about the format of the string.
  • sv (class_server) -- A Server class which indicates the manipulated server.
  • addr (string) -- A string describing the server address.



Returns a string describing the address of the server.
sv (class_server) -- A Server class which indicates the manipulated server.

A string


Returns server statistics.
sv (class_server) -- A Server class which indicates the manipulated server.

a key/value table containing stats


Shutdown all the sessions attached to the server. See the management socket documentation for more information about this function.
sv (class_server) -- A Server class which indicates the manipulated server.



Drain sticky sessions. See the management socket documentation for more information about this function.
sv (class_server) -- A Server class which indicates the manipulated server.



Set maintenance mode. See the management socket documentation for more information about this function.
sv (class_server) -- A Server class which indicates the manipulated server.



Set normal mode. See the management socket documentation for more information about this function.
sv (class_server) -- A Server class which indicates the manipulated server.



Enable health checks. See the management socket documentation for more information about this function.
sv (class_server) -- A Server class which indicates the manipulated server.



Disable health checks. See the management socket documentation for more information about this function.
sv (class_server) -- A Server class which indicates the manipulated server.



Force health-check up. See the management socket documentation for more information about this function.
sv (class_server) -- A Server class which indicates the manipulated server.



Force health-check nolb mode. See the management socket documentation for more information about this function.
sv (class_server) -- A Server class which indicates the manipulated server.



Force health-check down. See the management socket documentation for more information about this function.
sv (class_server) -- A Server class which indicates the manipulated server.



Enable agent check. See the management socket documentation for more information about this function.
sv (class_server) -- A Server class which indicates the manipulated server.



Disable agent check. See the management socket documentation for more information about this function.
sv (class_server) -- A Server class which indicates the manipulated server.



Force agent check up. See the management socket documentation for more information about this function.
sv (class_server) -- A Server class which indicates the manipulated server.



Force agent check down. See the management socket documentation for more information about this function.
sv (class_server) -- A Server class which indicates the manipulated server.



Returns server statistics.
ls (class_listener) -- A Listener class which indicates the manipulated listener.

a key/value table containing stats


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"


For each concatenation, Lua: * allocate memory for the result, * catenate the two string copying the strings in the new memory block, * free the old memory block containing the string which is no longer used. This process does many memory move, allocation and free. In addition, the memory is not really freed, it is just mark mark as unused and wait for the garbage collector.

The Concat class provide an alternative way to concatenate strings. It uses the internal Lua mechanism (it does not allocate memory), but it doesn't copy the data more than once.

On my computer, the following loops spends 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.



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


This function adds a string to the current concatenated string.
  • concat (class_concat) -- A Concat class which contains the currently built string.
  • string (string) -- A new string to concatenate to the current built string.



This function returns the concatenated string.
concat (class_concat) -- A Concat class which contains the currently built string.

the concatenated string


This class contains a lot of internal HAProxy sample fetches. See the HAProxy "configuration.txt" documentation for more information about her usage. They are the chapters 7.3.2 to 7.3.6.

warning some sample fetches are not available in some context. These limitations are specified in this documentation when they're useful.

TXN.f
TXN.sf

Fetches are useful for:

  • get system time,
  • get environment variable,
  • get random numbers,
  • known backend status like the number of users in queue or the number of connections established,
  • client information like ip source or destination,
  • deal with stick tables,
  • Established SSL information,
  • HTTP information like headers or method.


function action(txn)

-- Get source IP
local clientip = txn.f:src() end


This class contains a lot of internal HAProxy sample converters. See the HAProxy documentation "configuration.txt" for more information about her usage. Its the chapter 7.3.1.
TXN.c
TXN.sc

Converters provides statefull transformation. They are useful for:

  • converting input to base64,
  • applying hash on input string (djb2, crc32, sdbm, wt6),
  • format date,
  • json escape,
  • extracting preferred language comparing two lists,
  • turn to lower or upper chars,
  • deal with stick tables.


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).

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.

Warning: It is not possible to read from the response in request action, and it is not possible to read for the request channel in response action.


[image]
This function returns a string that contain the entire buffer. The data is not remove from the buffer and can be reprocessed later.

If the buffer can't receive more data, a 'nil' value is returned.

channel (class_channel) -- The manipulated Channel.

a string containing all the available data or nil.


This function returns a string that contain the entire buffer. The data is consumed from the buffer.

If the buffer can't receive more data, a 'nil' value is returned.

channel (class_channel) -- The manipulated Channel.

a string containing all the available data or nil.


This function returns a string that contain the first line of the buffer. The data is consumed. If the data returned doesn't contains a final 'n' its assumed than its the last available data in the buffer.

If the buffer can't receive more data, a 'nil' value is returned.

channel (class_channel) -- The manipulated Channel.

a string containing the available line or nil.


This function replace the content of the buffer by the string. The function returns the copied length, otherwise, it returns -1.

The data set with this function are not send. They wait for the end of HAProxy processing, so the buffer can be full.

  • channel (class_channel) -- The manipulated Channel.
  • string (string) -- The data which will sent.

an integer containing the amount of bytes copied or -1.


This function append the string argument to the content of the buffer. The function returns the copied length, otherwise, it returns -1.

The data set with this function are not send. They wait for the end of HAProxy processing, so the buffer can be full.

  • channel (class_channel) -- The manipulated Channel.
  • string (string) -- The data which will sent.

an integer containing the amount of bytes copied or -1.


This function required immediate send of the data. Unless if the connection is close, the buffer is regularly flushed and all the string can be sent.
  • channel (class_channel) -- The manipulated Channel.
  • string (string) -- The data which will sent.

an integer containing the amount of bytes copied or -1.


This function returns the length of the input part of the buffer.
channel (class_channel) -- The manipulated Channel.

an integer containing the amount of available bytes.


This function returns the length of the output part of the buffer.
channel (class_channel) -- The manipulated Channel.

an integer containing the amount of available bytes.


This function transfer bytes from the input part of the buffer to the output part.
  • channel (class_channel) -- The manipulated Channel.
  • int (integer) -- The amount of data which will be forwarded.



This function returns true if the buffer channel is full.
a boolean


This class contain all the HTTP manipulation functions.

Returns a table containing all the request headers.
http (class_http) -- The related http object.

table of headers.
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"


Returns a table containing all the response headers.
http (class_http) -- The related http object.

table of headers.
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"


Appends an HTTP header field in the request whose name is specified in "name" and whose value is defined in "value".
  • http (class_http) -- The related http object.
  • name (string) -- The header name.
  • value (string) -- The header value.

HTTP.res_add_header()


Appends an HTTP header field in the response whose name is specified in "name" and whose value is defined in "value".
  • http (class_http) -- The related http object.
  • name (string) -- The header name.
  • value (string) -- The header value.

HTTP.req_add_header()


Removes all HTTP header fields in the request whose name is specified in "name".
  • http (class_http) -- The related http object.
  • name (string) -- The header name.

HTTP.res_del_header()


Removes all HTTP header fields in the response whose name is specified in "name".
  • http (class_http) -- The related http object.
  • name (string) -- The header name.

HTTP.req_del_header()


This variable replace all occurrence of all header "name", by only one containing the "value".
  • http (class_http) -- The related http object.
  • name (string) -- The header name.
  • value (string) -- The header value.

HTTP.res_set_header()

This function does the same work as the following code:


function fcn(txn)

TXN.http:req_del_header("header")
TXN.http:req_add_header("header", "value") end


This variable replace all occurrence of all header "name", by only one containing the "value".
  • http (class_http) -- The related http object.
  • name (string) -- The header name.
  • value (string) -- The header value.

HTTP.req_rep_header()


Matches the regular expression in all occurrences of header field "name" according to "regex", and replaces them with the "replace" argument. The replacement value can contain back references like 1, 2, ... This function works with the request.
  • http (class_http) -- The related http object.
  • name (string) -- The header name.
  • regex (string) -- The match regular expression.
  • replace (string) -- The replacement value.

HTTP.res_rep_header()


Matches the regular expression in all occurrences of header field "name" according to "regex", and replaces them with the "replace" argument. The replacement value can contain back references like 1, 2, ... This function works with the request.
  • http (class_http) -- The related http object.
  • name (string) -- The header name.
  • regex (string) -- The match regular expression.
  • replace (string) -- The replacement value.

HTTP.req_rep_header()


Rewrites the request method with the parameter "method".
  • http (class_http) -- The related http object.
  • method (string) -- The new method.



Rewrites the request path with the "path" parameter.
  • http (class_http) -- The related http object.
  • path (string) -- The new path.



Rewrites the request's query string which appears after the first question mark ("?") with the parameter "query".
  • http (class_http) -- The related http object.
  • query (string) -- The new query.



Rewrites the request URI with the parameter "uri".
  • http (class_http) -- The related http object.
  • uri (string) -- The new uri.



Rewrites the response status code with the parameter "code".

If no custom reason is provided, it will be generated from the status.

  • http (class_http) -- The related http object.
  • status (integer) -- The new response status code.
  • reason (string) -- The new response reason (optional).



The txn class contain all the functions relative to the http or tcp transaction (Note than a tcp stream is the same than a tcp transaction, but an HTTP transaction is not the same than a tcp stream).

The usage of this class permits to retrieve data from the requests, alter it and forward it.

All the functions provided by this class are available in the context sample-fetches and actions.


An Converters class.

This attribute contains a Converters class object.


An Converters class.

This attribute contains a Converters class object. The functions of this object returns always a string.


An Fetches class.

This attribute contains a Fetches class object.


An Fetches class.

This attribute contains a Fetches class object. The functions of this object returns always a string.


An Channel class.

This attribute contains a channel class object for the request buffer.


An Channel class.

This attribute contains a channel class object for the response buffer.


An HTTP class.

This attribute contains an HTTP class object. It is available only if the proxy has the "mode http" enabled.


This function sends a log. The log is sent, according with the HAProxy configuration file, on the default syslog server if it is configured and on the stderr if it is allowed.
  • txn (class_txn) -- The class txn object containing the data.
  • loglevel (integer) -- Is the log level associated with the message. It is a number between 0 and 7.
  • msg (string) -- The log content.

core.emerg, core.alert, core.crit, core.err, core.warning, core.notice, core.info, core.debug (log level definitions)
TXN.deflog()
TXN.Debug()
TXN.Info()
TXN.Warning()
TXN.Alert()


Sends a log line with the default loglevel for the proxy associated with the transaction.
  • txn (class_txn) -- The class txn object containing the data.
  • msg (string) -- The log content.

:js:func:
`
TXN.log


  • txn (class_txn) -- The class txn object containing the data.
  • msg (string) -- The log content.

TXN.log()

Does the same job than:


function Debug(txn, msg)

TXN.log(txn, core.debug, msg) end


  • txn (class_txn) -- The class txn object containing the data.
  • msg (string) -- The log content.

TXN.log()


function Debug(txn, msg)

TXN.log(txn, core.info, msg) end


  • txn (class_txn) -- The class txn object containing the data.
  • msg (string) -- The log content.

TXN.log()


function Debug(txn, msg)

TXN.log(txn, core.warning, msg) end


  • txn (class_txn) -- The class txn object containing the data.
  • msg (string) -- The log content.

TXN.log()


function Debug(txn, msg)

TXN.log(txn, core.alert, msg) end


Return Lua data stored in the current transaction (with the TXN.set_priv()) function. If no data are stored, it returns a nil value.
txn (class_txn) -- The class txn object containing the data.

the opaque data previously stored, or nil if nothing is available.


Store any data in the current HAProxy transaction. This action replace the old stored data.
  • txn (class_txn) -- The class txn object containing the data.
  • data (opaque) -- The data which is stored in the transaction.



Converts a Lua type in a HAProxy type and store it in a variable <var>.
  • txn (class_txn) -- The class txn object containing the data.
  • var (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 to a truthy value the variable will only be set if it was defined elsewhere (i.e. used within the configuration). It is highly recommended to always set this to true.



Unset the variable <var>.
  • txn (class_txn) -- The class txn object containing the data.
  • var (string) -- The variable name according with the HAProxy variable syntax.



Returns data stored in the variable <var> converter in Lua type.
  • txn (class_txn) -- The class txn object containing the data.
  • var (string) -- The variable name according with the HAProxy variable syntax.



Return a new reply object
reply (table) -- A table containing info to initialize the reply fields.

A Reply class object.

The table used to initialized the reply object may contain following entries :

  • status : The reply status code. the code 200 is used by default.
  • reason : The reply reason. The reason corresponding to the status code is used by default.
  • headers : An list of headers, indexed by header name. Empty by default. For a given name, multiple values are possible, 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>" }


This function terminates processing of the transaction and the associated session and optionally reply to the client for HTTP sessions.
  • txn (class_txn) -- The class txn object containing the data.
  • reply (class_reply) -- The class reply object to return to the client.


This functions can be used when a critical error is detected or to terminate processing after some data have been returned to the client (eg: a redirect). To do so, a reply may be provided. This object is optional and may contain a status code, a reason, a header list and a body. All these fields are optionnals. When not provided, the default values are used. By default, with an empty reply object, an empty HTTP 200 response is returned to the client. If no reply object is provided, the transaction is terminated without any reply.

The reply object may be fully created in lua or the class Reply may be used to create 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 not make sense to call this function from sample-fetches. In this case the behaviour of this one is the same than core.done(): it quit the Lua execution. The transaction is really aborted only from an action registered function.
TXN.reply(), Reply()



Is used to change the log level of the current request. The "loglevel" must be an integer between 0 and 7.
  • txn (class_txn) -- The class txn object containing the data.
  • loglevel (integer) -- The required log level. This variable can be one of

core.emerg, core.alert, core.crit, core.err, core.warning, core.notice, core.info, core.debug (log level definitions)


Is used to set the TOS or DSCP field value of packets sent to the client to the value passed in "tos" on platforms which support this.
  • txn (class_txn) -- The class txn object containing the data.
  • tos (integer) -- The new TOS os DSCP.



Is used to set the Netfilter MARK on all packets sent to the client to the value passed in "mark" on platforms which support it.
  • txn (class_txn) -- The class txn object containing the data.
  • mark (integer) -- The mark value.



This function adjusts the priority class of the transaction. The value should be within the range -2047..2047. Values outside this range will be truncated.

See the HAProxy configuration.txt file keyword "http-request" action "set-priority-class" for details.


This function adjusts the priority offset of the transaction. The value should be within the range -524287..524287. Values outside this range will be truncated.

See the HAProxy configuration.txt file keyword "http-request" action "set-priority-offset" for details.


context: action

This class represents an HTTP response message. It provides some methods to enrich it.


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>")


TXN.reply()



The reply status code. By default, the status code is set to 200.
integer


The reason string describing the status code.
string


A table indexing all reply headers by name. To each name is associated an ordered list of values.
Lua table


{

["content-type"] = { "text/html" },
["cache-control"] = {"no-cache", "no-store" },
x_header_name = { "value1", "value2", ... }
... }


The reply payload.
string


Set the reply status code and optionally the reason-phrase. If the reason is not provided, the default reason corresponding to the status code is used.
  • reply (class_reply) -- The related Reply object.
  • status (integer) -- The reply status code.
  • reason (string) -- The reply status reason (optional).



Add a header to the reply object. If the header does not already exist, a new entry is created with its name as index and a one-element list containing its value as value. Otherwise, the header value is appended to the ordered list of values associated to the header name.
  • reply (class_reply) -- The related Reply object.
  • name (string) -- The header field name.
  • value (string) -- The header field value.



Remove all occurrences of a header name from the reply object.
  • reply (class_reply) -- The related Reply object.
  • name (string) -- The header field name.



Set the reply payload.
  • reply (class_reply) -- The related Reply object.
  • body (string) -- The reply payload.



This class must be compatible with the Lua Socket class. Only the 'client' functions are available. See the Lua Socket documentation:

http://w3.impa.br/~diego/software/luasocket/tcp.html


Closes a TCP object. The internal socket used by the object is closed and the local address to which the object was bound is made available to other applications. No further operations (except for further calls to the close method) are allowed on a closed Socket.
socket (class_socket) -- Is the manipulated Socket.


Note: It is important to close all used sockets once they are not needed, since, in many systems, each socket uses a file descriptor, which are limited system resources. Garbage-collected objects are automatically closed before destruction, though.


Attempts to connect a socket object to a remote host.

In case of error, the method returns nil followed by a string describing the error. In case of success, the method returns 1.

  • socket (class_socket) -- Is the manipulated Socket.
  • address (string) -- can be an IP address or a host name. See below for more information.
  • port (integer) -- must be an integer number in the range [1..64K].

1 or nil.

An address field extension permits to use the connect() function to connect to other stream than TCP. The syntax containing a simpleipv4 or ipv6 address is the basically expected format. This format requires the port.

Other format accepted are a socket path like "/socket/path", it permits to 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 prefix "ipv4@", "ipv6@" and "unix@" are also supported. The port can be passed int the string. The syntax "127.0.0.1:1234" is valid. In this case, the parameter port must not be set.


Same behavior than the function socket:connect, but uses SSL.
socket (class_socket) -- Is the manipulated Socket.

1 or nil.


Returns information about the remote side of a connected client object.

Returns a string with the IP address of the peer, followed by the port number that peer is using for the connection. In case of error, the method returns nil.

socket (class_socket) -- Is the manipulated Socket.

a string containing the server information.


Returns the local address information associated to the object.

The method returns a string with local IP address and a number with the port. In case of error, the method returns nil.

socket (class_socket) -- Is the manipulated Socket.

a string containing the client information.


Reads data from a client object, according to the specified read pattern. Patterns follow the Lua file I/O format, and the difference in performance between all patterns is negligible.
  • socket (class_socket) -- Is the manipulated Socket.
  • pattern (string|integer) -- Describe what is required (see below).
  • prefix (string) -- A string which will be prefix the returned data.

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.

Socket. Prefix is 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. In case of error, the method returns nil followed by an error message which can be the string 'closed' in case the connection was closed before the transmission was completed or the string 'timeout' in case there was a timeout during the operation. Also, after the error message, the function returns the partial result of the transmission.

Important note: This function was changed severely. It used to support multiple patterns (but I have never seen this feature used) and now it doesn't anymore. Partial results used to be returned in the same way as successful results. This last feature violated the idea that all functions should return nil on error. Thus it was changed too.


Sends data through client object.
  • socket (class_socket) -- Is the manipulated Socket.
  • 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.

see below.

Data is the string to be sent. The optional arguments i and j work exactly like the standard string.sub Lua function to allow the selection of a substring to be sent.

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. In case of 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. The error message can be 'closed' in case the connection was closed before the transmission was completed or the string 'timeout' in case 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.


Just implemented for compatibility, this cal does nothing.

Changes the timeout values for the object. All I/O operations are blocking. That is, any call to the methods send, receive, and accept will block indefinitely, until the operation completes. The settimeout method defines a limit on the amount of time the I/O methods can block. When a timeout time 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 for complete the internal buffer send or waiting for receive data.

  • socket (class_socket) -- Is the manipulated Socket.
  • value (float) -- The timeout value. Use floating point to specify milliseconds.



This class allows the usage of HAProxy regexes because classic lua doesn't provides 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 regexes compilation is a heavy process, it is better to define all your regexes in the body context and use it during the runtime.


-- 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


Create and compile a regex.
  • regex (string) -- The regular expression according with the libc or pcre standard
  • case_sensitive (boolean) -- Match is case sensitive or not.

boolean status and Regex class or string containing fail reason.


Execute the regex.
  • regex (class_regex) -- A Regex class object.
  • str (string) -- The input string will be compared with the compiled regex.

a boolean status according with the match result.


Execute the regex and return matched expressions.
  • map (class_map) -- A Regex class object.
  • str (string) -- The input string will be compared with the compiled regex.

a boolean status according with the match result, and a table containing all the string matched in order of declaration.


This class permits to do some lookup in HAProxy maps. The declared maps can be modified during the runtime through the HAProxy management socket.

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);


See the HAProxy configuration.txt file, chapter "Using ACLs and fetching samples" and subchapter "ACL basics" to understand this pattern matching method.

Note that Map.int is also available for compatibility.


See the HAProxy configuration.txt file, chapter "Using ACLs and fetching samples" and subchapter "ACL basics" to understand this pattern matching method.

Note that Map.ip is also available for compatibility.


See the HAProxy configuration.txt file, chapter "Using ACLs and fetching samples" and subchapter "ACL basics" to understand this pattern matching method.

Note that Map.str is also available for compatibility.


See the HAProxy configuration.txt file, chapter "Using ACLs and fetching samples" and subchapter "ACL basics" to understand this pattern matching method.

Note that Map.beg is also available for compatibility.


See the HAProxy configuration.txt file, chapter "Using ACLs and fetching samples" and subchapter "ACL basics" to understand this pattern matching method.

Note that Map.sub is also available for compatibility.


See the HAProxy configuration.txt file, chapter "Using ACLs and fetching samples" and subchapter "ACL basics" to understand this pattern matching method.

Note that Map.dir is also available for compatibility.


See the HAProxy configuration.txt file, chapter "Using ACLs and fetching samples" and subchapter "ACL basics" to understand this pattern matching method.

Note that Map.dom is also available for compatibility.


See the HAProxy configuration.txt file, chapter "Using ACLs and fetching samples" and subchapter "ACL basics" to understand this pattern matching method.

See the HAProxy configuration.txt file, chapter "Using ACLs and fetching samples" and subchapter "ACL basics" to understand this pattern matching method.

Note that Map.reg is also available for compatibility.


Creates and load a map.
  • file (string) -- Is the file containing the map.
  • method (integer) -- Is the map pattern matching method. See the attributes of the Map class.

a class Map object.
The Map attributes: Map._int, Map._ip, Map._str, Map._beg, Map._sub, Map._dir, Map._dom, Map._end and Map._reg.


Perform a lookup in a map.
  • map (class_map) -- Is the class Map object.
  • str (string) -- Is the string used as key.

a string containing the result or nil if no match.


Perform a lookup in a map.
  • map (class_map) -- Is the class Map object.
  • str (string) -- Is the string used as key.

a string containing the result or empty string if no match.


This class is used with applets that requires the 'http' mode. The http applet can be registered with the core.register_service() function. They are used for processing an http request like a server 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)


A Converters class

This attribute contains a Converters class object.


A Converters class

This attribute contains a Converters class object. The functions of this object returns always a string.


A Fetches class

This attribute contains a Fetches class object. Note that the applet execution place cannot access to a valid HAProxy core HTTP transaction, so some sample fetches related to the HTTP dependent values (hdr, path, ...) are not available.


A Fetches class

This attribute contains a Fetches class object. The functions of this object returns always a string. Note that the applet execution place cannot access to a valid HAProxy core HTTP transaction, so some sample fetches related to the HTTP dependent values (hdr, path, ...) are not available.


string

The attribute method returns a string containing the HTTP method.


string

The attribute version, returns a string containing the HTTP request version.


string

The attribute path returns a string containing the HTTP request path.


string

The attribute qs returns a string containing the HTTP request query string.


integer

The attribute length returns an integer containing the HTTP body length.


table

The attribute headers returns a table containing the HTTP headers. The header names are always in lower case. As the header name can be encountered more than once in each request, the value is indexed with 0 as first index value. The table have this form:


AppletHTTP.headers['<header-name>'][<header-index>] = "<header-value>"
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"


This function sets the HTTP status code for the response. The allowed code are from 100 to 599.
  • applet (class_AppletHTTP) -- An AppletHTTP class
  • code (integer) -- the status code returned to the client.
  • reason (string) -- the status reason returned to the client (optional).



This function add an header in the response. Duplicated headers are not collapsed. The special header content-length is used to determinate the response length. If it not exists, a transfer-encoding: chunked is set, and all the write from the function AppletHTTP:send() become a chunk.
  • applet (class_AppletHTTP) -- An AppletHTTP class
  • name (string) -- the header name
  • value (string) -- the header value



This function indicates to the HTTP engine that it can process and send the response headers. After this called we cannot add headers to the response; We cannot use the AppletHTTP:send() function if the AppletHTTP:start_response() is not called.
applet (class_AppletHTTP) -- An AppletHTTP class



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.
applet (class_AppletHTTP) -- An AppletHTTP class

a string. The string can be empty if we reach the end of the stream.


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.
  • applet (class_AppletHTTP) -- An AppletHTTP class
  • size (integer) -- the required read size.

always return a string,the string can be empty is the connection is closed.


Send the message msg on the http request body.
  • applet (class_AppletHTTP) -- An AppletHTTP class
  • msg (string) -- the message to send.



Return Lua data stored in the current transaction. If no data are stored, it returns a nil value.
applet (class_AppletHTTP) -- An AppletHTTP class

the opaque data previously stored, or nil if nothing is available.
AppletHTTP.set_priv()


Store any data in the current HAProxy transaction. This action replace the old stored data.
  • applet (class_AppletHTTP) -- An AppletHTTP class
  • data (opaque) -- The data which is stored in the transaction.

AppletHTTP.get_priv()


Converts a Lua type in a HAProxy type and store it in a variable <var>.
  • applet (class_AppletHTTP) -- An AppletHTTP class
  • var (string) -- The variable name according with the HAProxy variable syntax.
  • value (type) -- The value associated to the variable. The type ca be string or integer.
  • ifexist (boolean) -- If this parameter is set to a truthy value the variable will only be set if it was defined elsewhere (i.e. used within the configuration). It is highly recommended to always set this to true.

AppletHTTP.unset_var()
AppletHTTP.get_var()


Unset the variable <var>.
  • applet (class_AppletHTTP) -- An AppletHTTP class
  • var (string) -- The variable name according with the HAProxy variable syntax.

AppletHTTP.set_var()
AppletHTTP.get_var()


Returns data stored in the variable <var> converter in Lua type.
  • applet (class_AppletHTTP) -- An AppletHTTP class
  • var (string) -- The variable name according with the HAProxy variable syntax.

AppletHTTP.set_var()
AppletHTTP.unset_var()


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.

A Converters class

This attribute contains a Converters class object.


A Converters class

This attribute contains a Converters class object. The functions of this object returns always a string.


A Fetches class

This attribute contains a Fetches class object.


A Fetches class

This attribute contains a Fetches class object.


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.
applet (class_AppletTCP) -- An AppletTCP class

a string. The string can be empty if we reach the end of the stream.


Reads data from the TCP stream, 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.
  • applet (class_AppletTCP) -- An AppletTCP class
  • size (integer) -- the required read size.

always return a string,the string can be empty is the connection is closed.


Send the message on the stream.
  • applet (class_AppletTCP) -- An AppletTCP class
  • msg (string) -- the message to send.



Return Lua data stored in the current transaction. If no data are stored, it returns a nil value.
applet (class_AppletTCP) -- An AppletTCP class

the opaque data previously stored, or nil if nothing is available.
AppletTCP.set_priv()


Store any data in the current HAProxy transaction. This action replace the old stored data.
  • applet (class_AppletTCP) -- An AppletTCP class
  • data (opaque) -- The data which is stored in the transaction.

AppletTCP.get_priv()


Converts a Lua type in a HAProxy type and stores it in a variable <var>.
  • applet (class_AppletTCP) -- An AppletTCP class
  • var (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 to a truthy value the variable will only be set if it was defined elsewhere (i.e. used within the configuration). It is highly recommended to always set this to true.

AppletTCP.unset_var()
AppletTCP.get_var()


Unsets the variable <var>.
  • applet (class_AppletTCP) -- An AppletTCP class
  • var (string) -- The variable name according with the HAProxy variable syntax.

AppletTCP.unset_var()
AppletTCP.set_var()


Returns data stored in the variable <var> converter in Lua type.
  • applet (class_AppletTCP) -- An AppletTCP class
  • var (string) -- The variable name according with the HAProxy variable syntax.

AppletTCP.unset_var()
AppletTCP.set_var()


context: task, action, sample-fetch

This class can be used to access the HAProxy stick tables from Lua.


Returns stick table attributes as a Lua table. See HAProxy documentation for "stick-table" for canonical info, or check out example bellow.
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" }


Returns stick table entry for given <key>
key (string) -- Stick table key (IP addresses and strings are supported)

Lua table


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.

filter (table) -- Stick table filter

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} }


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)


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.
integer


This attribute is an integer (1). It instructs HAProxy to stop the current ruleset processing on the message.

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.

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.
integer


This attribute is an integer (4). It instructs HAProxy to stop the message processing.
integer


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, an HTTP 502 error is returned and the server response is discarded.
integer


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.
integer


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, an HTTP 502 error is returned and the server response is discarded.
integer


context: action

Set the script pause timeout to the specified time, defined in milliseconds.

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.


A lot of useful lua libraries can be found here:


Redis client library:


This is an example about the usage of the Redis library with HAProxy. Note that each call of 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

2022, Thierry FOURNIER

March 10, 2022 1.0