### HAProxy Lua AppletHTTP Hello World Example Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/index A basic 'Hello World' example demonstrating how to register an HTTP applet and send a simple text response. It shows how to set the status code, add headers like content-length and content-type, start the response, and send the message. ```lua 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) ``` -------------------------------- ### HAProxy Lua HTTPClient Example Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/_sources/index Example of using the HTTPClient class to send a POST request. ```lua local httpclient = core.httpclient() local response = httpclient:post{url="http://127.0.0.1", body=body, dst="unix@/var/run/http.sock"} ``` -------------------------------- ### HAProxy Configuration Example Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/_sources/index Example HAProxy configuration snippet demonstrating the use of a Lua service for handling TCP requests. ```haproxyconf bind 127.0.0.1:10001 tcp-request inspect-delay 1s tcp-request content use-service lua.hello_world ``` -------------------------------- ### HAProxy Lua API: Reply Construction Example Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/_sources/index Example demonstrating how to create and populate an HTTP reply object in Lua, including setting status, headers, and body. ```lua 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("

invalid request

") ``` -------------------------------- ### HAProxy Lua Action Example Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/index Example of registering a Lua action in HAProxy to deny HTTP requests. ```lua core.register_action("deny", { "http-req" }, function (txn) return act.DENY end) ``` -------------------------------- ### HAProxy Lua Filter Registration Example Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/index A comprehensive Lua example demonstrating how to define a filter class, register it with HAProxy, and implement various callback functions to trace HTTP request and response details. ```Lua 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 -- Process response body else -- Process request body end return filter.CONTINUE end ``` -------------------------------- ### HAProxy Lua HTTP Response Structure Example Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/_sources/index Example structure of a response object returned by the HTTPClient. ```lua response = { status = 400, reason = "Bad request", headers = { ["content-type"] = { "text/html" }, ["cache-control"] = { "no-cache", "no-store" }, }, body = "

invalid request

", } ``` -------------------------------- ### HAProxy Lua Hello World Example Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/index Demonstrates a basic HAProxy Lua configuration to send a 'hello world' message to clients. Includes the HAProxy configuration file and the Lua script. ```haproxy.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 ``` ```hello_world.lua core.register_service("hello_world", "tcp", function(applet) applet:send("hello world\n") end) ``` ```bash ./haproxy -f hello_world.conf ``` ```bash #:~ telnet 127.0.0.1 10001 ``` -------------------------------- ### HAProxy Lua Event Subscription Example Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/index Demonstrates combining core.event_sub() with Server.event_sub() and core.register_task() to track server additions and handle UP/DOWN events asynchronously. ```lua 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) ``` -------------------------------- ### HAProxy Lua Initialization Context Registration Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/_sources/index Shows how to register a Lua function to be executed in the HAProxy initialization context. This function runs after configuration parsing and is useful for setup tasks. ```lua function fcn() end core.register_init(fcn) ``` -------------------------------- ### HAProxy Lua API: AppletHTTP Hello World Example Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/_sources/index Demonstrates how to use the AppletHTTP class to create a simple HTTP server that responds with 'Hello World !'. This involves registering a service with 'http' mode and setting response headers and content. ```lua 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) ``` -------------------------------- ### Accessing HAProxy Sample Fetches Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/_sources/index Shows how to access HAProxy's internal sample fetches using the Fetches class. The example demonstrates retrieving the client's source IP address. ```lua function action(txn) -- Get source IP local clientip = txn.f:src() end ``` -------------------------------- ### HAProxy Lua Debugging Output Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/_sources/index Example output from the print_r function, showing a Lua table structure with string elements. ```text (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" ] ``` -------------------------------- ### Register and Start HAProxy Lua Task Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/_sources/index Registers and starts an independent task that runs when the HAProxy main scheduler starts. Tasks can be used for complex health checks and can accept up to 4 optional arguments. ```APIDOC 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. :param function func: is the Lua function called to work as an async task. Up to 4 optional arguments (all types supported) may be passed to the function. (They will be passed as-is to the task function) 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. See also :js:func:`core.queue` to dynamically pass data between main context and tasks or even between tasks. ``` -------------------------------- ### HAProxy Lua API - AppletHTTP Methods Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/genindex Documentation for the AppletHTTP class methods in the HAProxy Lua API. Includes functions for managing HTTP requests and responses, such as adding headers, getting variables, and sending responses. ```APIDOC AppletHTTP.add_header(name, value) Adds an HTTP header to the response. AppletHTTP.get_priv(key) Retrieves a private variable associated with the AppletHTTP instance. AppletHTTP.get_var(name) Retrieves an HTTP request variable. AppletHTTP.getline() Reads a line from the HTTP request. AppletHTTP.receive(size) Receives a specified number of bytes from the HTTP request. AppletHTTP.send(data) Sends data as part of the HTTP response. AppletHTTP.set_priv(key, value) Sets a private variable associated with the AppletHTTP instance. AppletHTTP.set_status(code, message) Sets the HTTP status code and message for the response. AppletHTTP.set_var(name, value) Sets an HTTP request variable. AppletHTTP.start_response() Starts the HTTP response, sending headers and status. AppletHTTP.unset_var(name) Unsets an HTTP request variable. ``` -------------------------------- ### AppletHTTP Class Methods Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/index Documentation for the methods of the AppletHTTP class, used for constructing and sending HTTP responses. This includes setting status codes, adding headers, starting the response, and reading/sending data. ```APIDOC AppletHTTP.set_status(_applet_, _code_[, _reason_]) This function sets the HTTP status code for the response. The allowed code are from 100 to 599. Arguments: 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). AppletHTTP.add_header(_applet_, _name_, _value_) This function adds a header in the response. Duplicated headers are not collapsed. 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 function _AppletHTTP:send()_ become a chunk. Arguments: applet (_class_AppletHTTP_) – An AppletHTTP class name (_string_) – the header name value (_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 called we cannot add headers to the response; We cannot use the _AppletHTTP:send()_ function if the _AppletHTTP:start_response()_ is not called. 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 class size (_integer_) – the required read size. Returns: always return a string,the string can be empty is the connection is closed. AppletHTTP.send(_applet_, _msg_) ``` -------------------------------- ### HAProxy Lua Task Context Registration Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/_sources/index Illustrates registering a Lua function for the task context, which runs concurrently with traffic processing after the HAProxy scheduler starts. ```lua function fcn() end core.register_task(fcn) ``` -------------------------------- ### HAProxy Queue Inter-Task Example Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/_sources/index Demonstrates how to use the Queue class for inter-task communication in HAProxy Lua scripts, showing a master task pushing data and a worker task popping data. ```lua -- 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) ``` -------------------------------- ### HAProxy Redis Client Integration Example Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/index Demonstrates how to use the redis-lua library within HAProxy to interact with a Redis server. It covers loading the library, creating a TCP socket, connecting to Redis, and sending a PING command. Note that socket connection failures can cause errors. ```lua -- 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 ``` -------------------------------- ### Lua Filter Example for HAProxy Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/_sources/index A comprehensive Lua script demonstrating how to create a custom filter in HAProxy. It includes functions for analyzing TCP payloads, handling HTTP headers and payloads, and registering the filter with the core. ```lua 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) ``` -------------------------------- ### HAProxy HTTP Client API Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/genindex Provides methods for making HTTP requests using a client. Supports common HTTP methods like GET, POST, PUT, DELETE, and HEAD. ```APIDOC HTTPClient() - Represents an HTTP client. HTTPClient.delete(url) - Sends an HTTP DELETE request. HTTPClient.get(url) - Sends an HTTP GET request. HTTPClient.head(url) - Sends an HTTP HEAD request. HTTPClient.post(url, body) - Sends an HTTP POST request. HTTPClient.put(url, body) - Sends an HTTP PUT request. ``` -------------------------------- ### HAProxy Lua API - Channel Methods Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/genindex Documentation for the Channel class methods in the HAProxy Lua API. Provides functionalities for manipulating data streams, including appending, getting data, forwarding, and managing channel state. ```APIDOC Channel.append(data) Appends data to the channel. Channel.data() Returns the current data in the channel. Channel.dup() Creates a duplicate of the channel. Channel.forward(channel) Forwards the channel's data to another channel. Channel.get() Retrieves data from the channel. Channel.get_in_len() Gets the length of data available for input in the channel. Channel.get_out_len() Gets the length of data available for output in the channel. Channel.getline() Reads a line from the channel. Channel.input(data) Writes data into the channel for input. Channel.insert(data) Inserts data at the beginning of the channel. Channel.is_full() Checks if the channel is full. Channel.is_resp() Checks if the channel is a response channel. Channel.line() Reads a line from the channel, similar to getline. Channel.may_recv() Checks if data can be received from the channel without blocking. Channel.output(data) Writes data to the channel for output. Channel.prepend(data) Prepends data to the beginning of the channel. Channel.remove(length) Removes a specified number of bytes from the channel. Channel.send(data) Sends data through the channel. Channel.set(data) Sets the entire content of the channel to the provided data. ``` -------------------------------- ### HAProxy Lua API: HTTP Request/Response Header Management Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/index Provides functions to get, add, delete, and set HTTP headers for both requests and responses. Includes examples of how to access and modify header values. ```APIDOC HTTP.req_get_headers(http) Returns a table containing all the request headers. Arguments: http (class_http): The related http object. Returns: table of headers. Example: HTTP:req_get_headers()[''][] = "" 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. Example: HTTP:res_get_headers()[''][] = "" 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 a HTTP header field in the request whose name is specified in “name” and whose value is defined in “value”. 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 a HTTP header field in the response whose name is specified in “name” and whose value is defined in “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”. 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”. 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 variable replace all occurrence of all header “name”, by only one containing the “value”. Arguments: http (class_http): The related http object. name (string): The header name. value (string): The header value. See: HTTP.res_set_header() Example: 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 function replaces all occurrence of all header “name”, by only one containing the “value”. Arguments: http (class_http): The related http object. name (string): The header name. value (string): The header value. See: HTTP.req_rep_header() ``` -------------------------------- ### HAProxy Lua 'Hello World' Service Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/_sources/index Demonstrates a basic HAProxy Lua service that sends 'hello world' to clients. It requires loading the Lua script in the HAProxy global configuration and setting up a listener to use the Lua service. ```haproxy-config 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 ``` ```lua core.register_service("hello_world", "tcp", function(applet) applet:send("hello world\n") end) ``` -------------------------------- ### HAProxy Lua API Reference Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/index Provides reference for core HAProxy Lua API functions including service registration, initialization, task management, CLI command registration, and configuration settings. ```APIDOC core.register_service(_name_, _mode_, _func_) 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. Arguments: name (string): is the name of the service. mode (string): is string describing the required mode. Only ‘tcp’ or ‘http’ are allowed. func (function): is the Lua function called to work as service. The prototype of the Lua function used as argument is: function(applet) core.register_init(_func_) Register a function executed after the configuration parsing. This is useful to check any parameters. Arguments: func (function): is the Lua function called to work as initializer. The prototype of the Lua function used as argument is: function() core.register_task(_func_[, _arg1_[, _arg2_[, _..._[, _arg4_]]]]) 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. Arguments: func (function): is the Lua function called to work as an async task. Up to 4 optional arguments (all types supported) may be passed to the function. The prototype of the Lua function used as argument is: function([arg1[, arg2[, ...[, arg4]]]]) core.register_cli([_path_, ]_usage_, _func_) Register a custom cli that will be available from haproxy stats socket. Arguments: 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, [...]]]) core.set_nice(_nice_) Change the nice of the current task or current session. Arguments: nice (integer): the nice value, it must be between -1024 and 1024. core.set_map(_name_, _key_, _value_) LEGACY Set the value _value_ associated to the key _key_ in the map referenced by _name_. Arguments: name (string): the Map reference key (string): the key to set or replace value (string): the associated value core.sleep(_int seconds_) The core.sleep() functions stop the Lua execution between specified seconds. Arguments: ``` -------------------------------- ### HTTPMessage.set: Replace Data in HTTP Message Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/index Replaces a specified number of bytes in an HTTP message with new string data, starting at a given offset. Supports positive and negative offsets relative to the message start or end. ```APIDOC HTTPMessage.set(_http_msg_, _string_[, _offset_[, _length_]]) Replaces **length** bytes of incoming data of the HTTP message **http_msg**, starting at offset **offset**, by the string **string**. 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. 0 by 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. ``` -------------------------------- ### AppletHTTP: Get Variable Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/index Retrieves data stored in a variable and converts it to a Lua type. Related to `set_var` and `unset_var`. ```APIDOC AppletHTTP.get_var(applet, var) Arguments: applet (_class_AppletHTTP_) – An AppletHTTP class var (_string_) – The variable name according with the HAProxy variable syntax. ``` -------------------------------- ### Register HAProxy Sample Fetch Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/_sources/index Registers a Lua function to be used as a sample fetch in HAProxy. Sample fetches return a string output and can accept up to 5 string arguments. ```APIDOC core.register_fetches(name, func) :param string name: is the name of the sample fetch. :param function func: is the Lua function called to work as sample fetch. The prototype of the Lua function used as argument is: .. code-block:: lua string function(txn, [p1 [, p2 [, ... [, p5]]]]) .. * **txn** (:ref:`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 nil if the value cannot be returned now. lua example code: .. code-block:: lua core.register_fetches("hello", function(txn) return "hello" end) .. HAProxy example configuration: :: ``` -------------------------------- ### Redis Client Library Usage Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/_sources/index Example of using the redis-lua library within HAProxy. Note that socket connection errors can occur. ```lua -- 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 ``` -------------------------------- ### HAProxy Lua API - Core Methods and Attributes Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/genindex Documentation for the core class in the HAProxy Lua API. Includes methods for managing ACLs, logging, date formatting, network operations, and various utility functions, as well as attributes for logging levels and system information. ```APIDOC core.add_acl(name, pattern) Adds a new Access Control List (ACL). core.alert Attribute representing the alert log level. core.Alert(message) Logs a message at the alert level. core.asctime_date() Returns the current date and time inasctime format. core.backends Attribute listing available backend servers. core.concat(str1, str2, ...) Concatenates multiple strings. core.crit Attribute representing the critical log level. core.debug Attribute representing the debug log level. core.Debug(message) Logs a message at the debug level. core.del_acl(name) Deletes an existing ACL. core.del_map(name) Deletes a map. core.disable_legacy_mailers() Disables legacy mailer functionality. core.done() Indicates completion of a task or operation. core.emerg Attribute representing the emergency log level. core.err Attribute representing the error log level. core.event_sub(event_name, callback) Subscribes to an event. core.frontends Attribute listing available frontend listeners. core.get_info() Retrieves general information about the HAProxy instance. core.get_patref(pattern) Retrieves a pattern reference. core.get_var(var_name) Retrieves the value of a global variable. core.http_date() Returns the current date and time in HTTP date format. core.httpclient(url, method, headers, body) Performs an HTTP client request. core.imf_date() Returns the current date and time in IMF format. core.info Attribute representing the informational log level. core.Info(message) Logs a message at the informational level. core.log(level, message) Logs a message with a specified log level. core.match_addr(ip_address, ip_network) Checks if an IP address matches an IP network. core.msleep(milliseconds) Pauses execution for a specified number of milliseconds. core.notice Attribute representing the notice log level. core.now() Returns the current timestamp. core.parse_addr(address_string) Parses an address string into IP address and port. core.proxies Attribute listing available proxy configurations. core.queue(queue_name, item) Adds an item to a named queue. core.register_action(name, action_func) Registers a custom action. core.register_cli(name, cli_func) Registers a custom CLI command. core.register_converters(converter_table) Registers custom data converters. core.register_fetches(fetch_table) Registers custom fetchers. core.register_filter(name, filter_func) Registers a custom filter. core.register_init(init_func) Registers a function to be called during initialization. core.register_service(name, service_func) Registers a custom service. core.register_task(name, task_func) Registers a custom task. core.rfc850_date() Returns the current date and time in RFC850 format. core.set_map(name, key, value) Sets a key-value pair in a map. core.set_nice(level) Sets the niceness level for the process. core.silent Attribute representing the silent log level. core.sleep(seconds) Pauses execution for a specified number of seconds. core.tcp() Creates a new TCP object. core.thread Attribute indicating if the code is running in a separate thread. core.tokenize(string, delimiter) Splits a string into tokens based on a delimiter. core.wait(condition_func, timeout) Waits for a condition to be met. core.warning Attribute representing the warning log level. core.Warning(message) Logs a message at the warning level. core.yield() Yields control to the scheduler. ``` -------------------------------- ### HTTPMessage.remove() - Lua Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/_sources/index Removes a specified number of bytes from the incoming data of an HTTP message, starting at an optional offset. Supports relative offsets. ```lua HTTPMessage.remove(http_msg[, offset[, length]]) ``` -------------------------------- ### HTTPMessage Data Manipulation Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/index Functions for inserting, copying, and removing data from HTTP messages. Supports offsets relative to the start or end of the message data. ```APIDOC HTTPMessage.insert(http_msg, string, offset) Copies the string 'string' at the offset 'offset' in the incoming data of the HTTP message 'http_msg'. - http_msg: The HTTP message object. - string: The data to copy. - offset: The offset to copy the data. Defaults to 0. Negative values are relative to the end. Returns: Copied length on success, -1 on failure. ``` ```APIDOC HTTPMessage.prepend(http_msg, string) Copies the string 'string' in front of the incoming data of the HTTP message 'http_msg'. - http_msg: The HTTP message object. - string: The data to copy. Returns: Copied length on success, -1 on failure. ``` ```APIDOC HTTPMessage.remove(http_msg, offset, length) Removes 'length' bytes of incoming data from 'http_msg', starting at 'offset'. - http_msg: The HTTP message object. - offset: The starting offset for removal. Defaults to 0. Negative values are relative to the end. - length: The number of bytes to remove. Defaults to removing all data from the offset. Returns: Number of bytes removed on success. ``` ```APIDOC HTTPMessage.send(http_msg, string) Immediately sends the string 'string' by copying it to the beginning of the incoming data of 'http_msg' and forwarding it. - http_msg: The HTTP message object. - string: The data to send. Returns: Copied length on success, -1 on failure. ``` -------------------------------- ### HAProxy Lua Sample-Fetch Context Registration Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/_sources/index Shows how to register a Lua function for the sample-fetch context, which takes a TXN object and returns a string, useful for aggregating HAProxy sample-fetches. ```lua function string fcn(txn) end core.register_fetches(fcn) ``` -------------------------------- ### Socket Data Transmission Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/_sources/index Sends data through a client socket object. Allows specifying a substring of the data to be sent using start and end indices. ```APIDOC Socket.send(socket, data [, start [, end]]) - Sends data through a client object. - Parameters: - socket (class_socket): The socket object. - data (string): The data to send. - start (integer, optional): Start position in the data buffer. - end (integer, optional): End position in the data buffer. - Returns: Index of the last byte sent on success. On error, returns nil, an error message ('closed'), and the index of the last byte sent. ``` -------------------------------- ### HAProxy Configuration with Lua Load Parameters Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/index This snippet shows the HAProxy configuration file (`hello_world.conf`) that loads a Lua script (`hello_world.lua`) and passes a string parameter to it. ```haproxyconf 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 ``` -------------------------------- ### AppletHTTP: Get Private Data Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/index Retrieves Lua data stored within the current HAProxy transaction. Returns nil if no data is present. Related to `set_priv`. ```APIDOC AppletHTTP.get_priv(applet) Arguments: applet (_class_AppletHTTP_) – An AppletHTTP class Returns: the opaque data previously stored, or nil if nothing is available. ``` -------------------------------- ### HAProxy Lua API - Act Attributes and Methods Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/genindex Documentation for the act class and its associated attributes in the HAProxy Lua API. Defines constants for action outcomes and provides a method for waking up a process. ```APIDOC act.ABORT Constant representing an abort action. act.CONTINUE Constant representing a continue action. act.DENY Constant representing a deny action. act.DONE Constant representing a done action. act.ERROR Constant representing an error action. act.INVALID Constant representing an invalid action. act.STOP Constant representing a stop action. act.YIELD Constant representing a yield action. act:wake_time() Wakes up a process after a specified time. ``` -------------------------------- ### Socket Get Peer Name Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/index Retrieves information about the remote endpoint of an established connection. It returns the peer's IP address and the port number they are using. ```APIDOC Socket.getpeername(_socket_) -- 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. -- Arguments: -- socket (_class_socket_) – Is the manipulated Socket. -- Returns: -- a string containing the server information. ``` -------------------------------- ### HAProxy Lua API: Queue Class Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/genindex Documentation for the Queue class and its methods in the HAProxy Lua API. Includes methods for managing a queue, such as alarm, pop, push, and size. ```APIDOC Queue() - Represents a queue data structure. Queue.alarm() - Triggers an alarm for the queue. Queue.pop() - Removes and returns an element from the queue. Queue.pop_wait() - Removes and returns an element from the queue, waiting if necessary. Queue.push(element) - Adds an element to the queue. - Parameters: - element: The element to add to the queue. Queue.size() - Returns the current number of elements in the queue. ``` -------------------------------- ### AppletHTTP Variable Management Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/_sources/index Functions for setting, getting, and unsetting variables within the AppletHTTP class. Includes options for conditional setting and details on variable scope. ```APIDOC AppletHTTP.set_var(applet, var, value[, ifexist]) Converts a Lua type in a HAProxy type and store it in a variable . :param class_AppletHTTP applet: An :ref:`applethttp_class` :param string var: The variable name according with the HAProxy variable syntax. :param type value: The value associated to the variable. The type ca be string or integer. :param boolean ifexist: If this parameter is set to true the 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. :see: :js:func:`AppletHTTP.unset_var` :see: :js:func:`AppletHTTP.get_var` AppletHTTP.unset_var(applet, var) Unset the variable . :param class_AppletHTTP applet: An :ref:`applethttp_class` :param string var: The variable name according with the HAProxy variable syntax. :see: :js:func:`AppletHTTP.set_var` :see: :js:func:`AppletHTTP.get_var` AppletHTTP.get_var(applet, var) Returns data stored in the variable converter in Lua type. :param class_AppletHTTP applet: An :ref:`applethttp_class` :param string var: The variable name according with the HAProxy variable syntax. :see: :js:func:`AppletHTTP.set_var` :see: :js:func:`AppletHTTP.unset_var` ``` -------------------------------- ### Proxy Class Methods Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/_sources/index Provides functions to interact with HAProxy proxies, including getting unique identifiers, pausing, resuming, stopping, and retrieving status information. ```APIDOC Proxy.get_uuid() Returns the unique identifier of the proxy. Proxy.pause(px) Pause the proxy. :param class_proxy px: A :ref:`proxy_class` which indicates the manipulated proxy. Proxy.resume(px) Resume the proxy. :param class_proxy px: A :ref:`proxy_class` which indicates the manipulated proxy. Proxy.stop(px) Stop the proxy. :param class_proxy px: A :ref:`proxy_class` which indicates the manipulated proxy. Proxy.shut_bcksess(px) Kill the session attached to a backup server. :param class_proxy px: A :ref:`proxy_class` which indicates the manipulated proxy. Proxy.get_cap(px) Returns a string describing the capabilities of the proxy. :param class_proxy px: A :ref:`proxy_class` 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. :param class_proxy px: A :ref:`proxy_class` 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. :param class_proxy px: A :ref:`proxy_class` 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. :param class_proxy px: A :ref:`proxy_class` 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. :param class_proxy px: A :ref:`proxy_class` which indicates the manipulated proxy. :returns: a key/value table containing stats Proxy.get_mailers(px) **LEGACY** Returns a table containing mailers config for the current proxy or nil if mailers are not available for the proxy. :param class_proxy px: A :ref:`proxy_class` which indicates the manipulated proxy. :returns: a :ref:`proxy_mailers_class` containing proxy mailers config ``` -------------------------------- ### HAProxy Lua Map Class Initialization and Fetch Registration Source: https://www.arpalert.org/src/haproxy-lua-api/3.2/index Demonstrates how to create a new Map object using Map.new and register a fetch function to retrieve country information based on IP addresses using the Map's lookup capability. ```lua 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); ```