1.. toctree::
2   :maxdepth: 2
3
4
5How Lua runs in HAProxy
6=======================
7
8HAProxy Lua running contexts
9----------------------------
10
11The Lua code executed in HAProxy can be processed in 2 main modes. The first one
12is the **initialisation mode**, and the second is the **runtime mode**.
13
14* In the **initialisation mode**, we can perform DNS solves, but we cannot
15  perform socket I/O. In this initialisation mode, HAProxy still blocked during
16  the execution of the Lua program.
17
18* In the **runtime mode**, we cannot perform DNS solves, but we can use sockets.
19  The execution of the Lua code is multiplexed with the requests processing, so
20  the Lua code seems to be run in blocking, but it is not the case.
21
22The Lua code is loaded in one or more files. These files contains main code and
23functions. Lua have 6 execution context.
24
251. The Lua file **body context**. It is executed during the load of the Lua file
26   in the HAProxy `[global]` section with the directive `lua-load`. It is
27   executed in initialisation mode. This section is use for configuring Lua
28   bindings in HAProxy.
29
302. The Lua **init context**. It is a Lua function executed just after the
31   HAProxy configuration parsing. The execution is in initialisation mode. In
32   this context the HAProxy environment are already initialized. It is useful to
33   check configuration, or initializing socket connections or tasks. These
34   functions are declared in the body context with the Lua function
35   `core.register_init()`. The prototype of the function is a simple function
36   without return value and without parameters, like this: `function fcn()`.
37
383. The Lua **task context**. It is a Lua function executed after the start
39   of the HAProxy scheduler, and just after the declaration of the task with the
40   Lua function `core.register_task()`. This context can be concurrent with the
41   traffic processing. It is executed in runtime mode. The prototype of the
42   function is a simple function without return value and without parameters,
43   like this: `function fcn()`.
44
454. The **action context**. It is a Lua function conditionally executed. These
46   actions are registered by the Lua directives "`core.register_action()`". The
47   prototype of the Lua called function is a function with doesn't returns
48   anything and that take an object of class TXN as entry. `function fcn(txn)`.
49
505. The **sample-fetch context**. This function takes a TXN object as entry
51   argument and returns a string. These types of function cannot execute any
52   blocking function. They are useful to aggregate some of original HAProxy
53   sample-fetches and return the result. The prototype of the function is
54   `function string fcn(txn)`. These functions can be registered with the Lua
55   function `core.register_fetches()`. Each declared sample-fetch is prefixed by
56   the string "lua.".
57
58   **NOTE**: It is possible that this function cannot found the required data
59   in the original HAProxy sample-fetches, in this case, it cannot return the
60   result. This case is not yet supported
61
626. The **converter context**. It is a Lua function that takes a string as input
63   and returns another string as output. These types of function are stateless,
64   it cannot access to any context. They don't execute any blocking function.
65   The call prototype is `function string fcn(string)`. This function can be
66   registered with the Lua function `core.register_converters()`. Each declared
67   converter is prefixed by the string "lua.".
68
69HAProxy Lua Hello world
70-----------------------
71
72HAProxy configuration file (`hello_world.conf`):
73
74::
75
76    global
77       lua-load hello_world.lua
78
79    listen proxy
80       bind 127.0.0.1:10001
81       tcp-request inspect-delay 1s
82       tcp-request content use-service lua.hello_world
83
84HAProxy Lua file (`hello_world.lua`):
85
86.. code-block:: lua
87
88    core.register_service("hello_world", "tcp", function(applet)
89       applet:send("hello world\n")
90    end)
91
92How to start HAProxy for testing this configuration:
93
94::
95
96    ./haproxy -f hello_world.conf
97
98On other terminal, you can test with telnet:
99
100::
101
102    #:~ telnet 127.0.0.1 10001
103    hello world
104
105Core class
106==========
107
108.. js:class:: core
109
110   The "core" class contains all the HAProxy core functions. These function are
111   useful for the controlling the execution flow, registering hooks, manipulating
112   global maps or ACL, ...
113
114   "core" class is basically provided with HAProxy. No `require` line is
115   required to uses these function.
116
117   The "core" class is static, it is not possible to create a new object of this
118   type.
119
120.. js:attribute:: core.emerg
121
122  :returns: integer
123
124  This attribute is an integer, it contains the value of the loglevel "emergency" (0).
125
126.. js:attribute:: core.alert
127
128  :returns: integer
129
130  This attribute is an integer, it contains the value of the loglevel "alert" (1).
131
132.. js:attribute:: core.crit
133
134  :returns: integer
135
136  This attribute is an integer, it contains the value of the loglevel "critical" (2).
137
138.. js:attribute:: core.err
139
140  :returns: integer
141
142  This attribute is an integer, it contains the value of the loglevel "error" (3).
143
144.. js:attribute:: core.warning
145
146  :returns: integer
147
148  This attribute is an integer, it contains the value of the loglevel "warning" (4).
149
150.. js:attribute:: core.notice
151
152  :returns: integer
153
154  This attribute is an integer, it contains the value of the loglevel "notice" (5).
155
156.. js:attribute:: core.info
157
158  :returns: integer
159
160  This attribute is an integer, it contains the value of the loglevel "info" (6).
161
162.. js:attribute:: core.debug
163
164  :returns: integer
165
166  This attribute is an integer, it contains the value of the loglevel "debug" (7).
167
168.. js:attribute:: core.proxies
169
170  **context**: task, action, sample-fetch, converter
171
172  This attribute is an array of declared proxies (frontend and backends). Each
173  proxy give an access to his list of listeners and servers. Each entry is of
174  type :ref:`proxy_class`
175
176.. js:function:: core.log(loglevel, msg)
177
178  **context**: body, init, task, action, sample-fetch, converter
179
180  This function sends a log. The log is sent, according with the HAProxy
181  configuration file, on the default syslog server if it is configured and on
182  the stderr if it is allowed.
183
184  :param integer loglevel: Is the log level asociated with the message. It is a
185    number between 0 and 7.
186  :param string msg: The log content.
187  :see: :js:attr:`core.emerg`, :js:attr:`core.alert`, :js:attr:`core.crit`,
188    :js:attr:`core.err`, :js:attr:`core.warning`, :js:attr:`core.notice`,
189    :js:attr:`core.info`, :js:attr:`core.debug` (log level definitions)
190  :see: :js:func:`core.Debug`
191  :see: :js:func:`core.Info`
192  :see: :js:func:`core.Warning`
193  :see: :js:func:`core.Alert`
194
195.. js:function:: core.Debug(msg)
196
197  **context**: body, init, task, action, sample-fetch, converter
198
199  :param string msg: The log content.
200  :see: :js:func:`core.log`
201
202  Does the same job than:
203
204.. code-block:: lua
205
206  function Debug(msg)
207    core.log(core.debug, msg)
208  end
209..
210
211.. js:function:: core.Info(msg)
212
213  **context**: body, init, task, action, sample-fetch, converter
214
215  :param string msg: The log content.
216  :see: :js:func:`core.log`
217
218.. code-block:: lua
219
220  function Info(msg)
221    core.log(core.info, msg)
222  end
223..
224
225.. js:function:: core.Warning(msg)
226
227  **context**: body, init, task, action, sample-fetch, converter
228
229  :param string msg: The log content.
230  :see: :js:func:`core.log`
231
232.. code-block:: lua
233
234  function Warning(msg)
235    core.log(core.warning, msg)
236  end
237..
238
239.. js:function:: core.Alert(msg)
240
241  **context**: body, init, task, action, sample-fetch, converter
242
243  :param string msg: The log content.
244  :see: :js:func:`core.log`
245
246.. code-block:: lua
247
248  function Alert(msg)
249    core.log(core.alert, msg)
250  end
251..
252
253.. js:function:: core.add_acl(filename, key)
254
255  **context**: init, task, action, sample-fetch, converter
256
257  Add the ACL *key* in the ACLs list referenced by the file *filename*.
258
259  :param string filename: the filename that reference the ACL entries.
260  :param string key: the key which will be added.
261
262.. js:function:: core.del_acl(filename, key)
263
264  **context**: init, task, action, sample-fetch, converter
265
266  Delete the ACL entry referenced by the key *key* in the list of ACLs
267  referenced by *filename*.
268
269  :param string filename: the filename that reference the ACL entries.
270  :param string key: the key which will be deleted.
271
272.. js:function:: core.del_map(filename, key)
273
274  **context**: init, task, action, sample-fetch, converter
275
276  Delete the map entry indexed with the specified key in the list of maps
277  referenced by his filename.
278
279  :param string filename: the filename that reference the map entries.
280  :param string key: the key which will be deleted.
281
282.. js:function:: core.get_info()
283
284  **context**: body, init, task, action, sample-fetch, converter
285
286  Returns HAProxy core informations. We can found information like the uptime,
287  the pid, memory pool usage, tasks number, ...
288
289  These information are also returned by the management sockat via the command
290  "show info". See the management socket documentation fpor more information
291  about the content of these variables.
292
293  :returns: an array of values.
294
295.. js:function:: core.now()
296
297  **context**: body, init, task, action
298
299  This function returns the current time. The time returned is fixed by the
300  HAProxy core and assures than the hour will be monotnic and that the system
301  call 'gettimeofday' will not be called too. The time is refreshed between each
302  Lua execution or resume, so two consecutive call to the function "now" will
303  probably returns the same result.
304
305  :returns: an array which contains two entries "sec" and "usec". "sec"
306    contains the current at the epoch format, and "usec" contains the
307    current microseconds.
308
309.. js:function:: core.http_date(date)
310
311  **context**: body, init, task, action
312
313  This function take a string repsenting http date, and returns an integer
314  containing the corresponding date with a epoch format. A valid http date
315  me respect the format IMF, RFC850 or ASCTIME.
316
317  :param string date: a date http-date formatted
318  :returns: integer containing epoch date
319  :see: :js:func:`core.imf_date`.
320  :see: :js:func:`core.rfc850_date`.
321  :see: :js:func:`core.asctime_date`.
322  :see: https://tools.ietf.org/html/rfc7231#section-7.1.1.1
323
324.. js:function:: core.imf_date(date)
325
326  **context**: body, init, task, action
327
328  This function take a string repsenting IMF date, and returns an integer
329  containing the corresponding date with a epoch format.
330
331  :param string date: a date IMF formatted
332  :returns: integer containing epoch date
333  :see: https://tools.ietf.org/html/rfc7231#section-7.1.1.1
334
335  The IMF format is like this:
336
337.. code-block:: text
338
339	Sun, 06 Nov 1994 08:49:37 GMT
340..
341
342.. js:function:: core.rfc850_date(date)
343
344  **context**: body, init, task, action
345
346  This function take a string repsenting RFC850 date, and returns an integer
347  containing the corresponding date with a epoch format.
348
349  :param string date: a date RFC859 formatted
350  :returns: integer containing epoch date
351  :see: https://tools.ietf.org/html/rfc7231#section-7.1.1.1
352
353  The RFC850 format is like this:
354
355.. code-block:: text
356
357	Sunday, 06-Nov-94 08:49:37 GMT
358..
359
360.. js:function:: core.asctime_date(date)
361
362  **context**: body, init, task, action
363
364  This function take a string repsenting ASCTIME date, and returns an integer
365  containing the corresponding date with a epoch format.
366
367  :param string date: a date ASCTIME formatted
368  :returns: integer containing epoch date
369  :see: https://tools.ietf.org/html/rfc7231#section-7.1.1.1
370
371  The ASCTIME format is like this:
372
373.. code-block:: text
374
375	Sun Nov  6 08:49:37 1994
376..
377
378.. js:function:: core.rfc850_date(date)
379
380  **context**: body, init, task, action
381
382  This function take a string repsenting http date, and returns an integer
383  containing the corresponding date with a epoch format.
384
385  :param string date: a date http-date formatted
386
387.. js:function:: core.asctime_date(date)
388
389  **context**: body, init, task, action
390
391  This function take a string repsenting http date, and returns an integer
392  containing the corresponding date with a epoch format.
393
394  :param string date: a date http-date formatted
395
396.. js:function:: core.msleep(milliseconds)
397
398  **context**: body, init, task, action
399
400  The `core.msleep()` stops the Lua execution between specified milliseconds.
401
402  :param integer milliseconds: the required milliseconds.
403
404.. js:attribute:: core.proxies
405
406  **context**: body, init, task, action, sample-fetch, converter
407
408  proxies is an array containing the list of all proxies declared in the
409  configuration file. Each entry of the proxies array is an object of type
410  :ref:`proxy_class`
411
412.. js:function:: core.register_action(name, actions, func)
413
414  **context**: body
415
416  Register a Lua function executed as action. All the registered action can be
417  used in HAProxy with the prefix "lua.". An action gets a TXN object class as
418  input.
419
420  :param string name: is the name of the converter.
421  :param table actions: is a table of string describing the HAProxy actions who
422                        want to register to. The expected actions are 'tcp-req',
423                        'tcp-res', 'http-req' or 'http-res'.
424  :param function func: is the Lua function called to work as converter.
425
426  The prototype of the Lua function used as argument is:
427
428.. code-block:: lua
429
430  function(txn)
431..
432
433  * **txn** (:ref:`txn_class`): this is a TXN object used for manipulating the
434            current request or TCP stream.
435
436  Here, an exemple of action registration. the action juste send an 'Hello world'
437  in the logs.
438
439.. code-block:: lua
440
441  core.register_action("hello-world", { "tcp-req", "http-req" }, function(txn)
442     txn:Info("Hello world")
443  end)
444..
445
446  This example code is used in HAproxy configuration like this:
447
448::
449
450  frontend tcp_frt
451    mode tcp
452    tcp-request content lua.hello-world
453
454  frontend http_frt
455    mode http
456    http-request lua.hello-world
457
458.. js:function:: core.register_converters(name, func)
459
460  **context**: body
461
462  Register a Lua function executed as converter. All the registered converters
463  can be used in HAProxy with the prefix "lua.". An converter get a string as
464  input and return a string as output. The registered function can take up to 9
465  values as parameter. All the value are strings.
466
467  :param string name: is the name of the converter.
468  :param function func: is the Lua function called to work as converter.
469
470  The prototype of the Lua function used as argument is:
471
472.. code-block:: lua
473
474  function(str, [p1 [, p2 [, ... [, p5]]]])
475..
476
477  * **str** (*string*): this is the input value automatically converted in
478    string.
479  * **p1** .. **p5** (*string*): this is a list of string arguments declared in
480    the haroxy configuration file. The number of arguments doesn't exceed 5.
481    The order and the nature of these is conventionally choose by the
482    developper.
483
484.. js:function:: core.register_fetches(name, func)
485
486  **context**: body
487
488  Register a Lua function executed as sample fetch. All the registered sample
489  fetchs can be used in HAProxy with the prefix "lua.". A Lua sample fetch
490  return a string as output. The registered function can take up to 9 values as
491  parameter. All the value are strings.
492
493  :param string name: is the name of the converter.
494  :param function func: is the Lua function called to work as sample fetch.
495
496  The prototype of the Lua function used as argument is:
497
498.. code-block:: lua
499
500    string function(txn, [p1 [, p2 [, ... [, p5]]]])
501..
502
503  * **txn** (:ref:`txn_class`): this is the txn object associated with the current
504    request.
505  * **p1** .. **p5** (*string*): this is a list of string arguments declared in
506    the haroxy configuration file. The number of arguments doesn't exceed 5.
507    The order and the nature of these is conventionally choose by the
508    developper.
509  * **Returns**: A string containing some data, ot nil if the value cannot be
510    returned now.
511
512  lua example code:
513
514.. code-block:: lua
515
516    core.register_fetches("hello", function(txn)
517        return "hello"
518    end)
519..
520
521  HAProxy example configuration:
522
523::
524
525    frontend example
526       http-request redirect location /%[lua.hello]
527
528.. js:function:: core.register_service(name, mode, func)
529
530  **context**: body
531
532  Register a Lua function executed as a service. All the registered service can
533  be used in HAProxy with the prefix "lua.". A service gets an object class as
534  input according with the required mode.
535
536  :param string name: is the name of the converter.
537  :param string mode: is string describing the required mode. Only 'tcp' or
538                      'http' are allowed.
539  :param function func: is the Lua function called to work as converter.
540
541  The prototype of the Lua function used as argument is:
542
543.. code-block:: lua
544
545  function(applet)
546..
547
548  * **applet** *applet*  will be a :ref:`applettcp_class` or a
549    :ref:`applethttp_class`. It depends the type of registered applet. An applet
550    registered with the 'http' value for the *mode* parameter will gets a
551    :ref:`applethttp_class`. If the *mode* value is 'tcp', the applet will gets
552    a :ref:`applettcp_class`.
553
554  **warning**: Applets of type 'http' cannot be called from 'tcp-*'
555  rulesets. Only the 'http-*' rulesets are authorized, this means
556  that is not possible to call an HTTP applet from a proxy in tcp
557  mode. Applets of type 'tcp' can be called from anywhre.
558
559  Here, an exemple of service registration. the service just send an 'Hello world'
560  as an http response.
561
562.. code-block:: lua
563
564  core.register_service("hello-world", "http", function(applet)
565     local response = "Hello World !"
566     applet:set_status(200)
567     applet:add_header("content-length", string.len(response))
568     applet:add_header("content-type", "text/plain")
569     applet:start_response()
570     applet:send(response)
571  end)
572..
573
574  This example code is used in HAproxy configuration like this:
575
576::
577
578    frontend example
579       http-request use-service lua.hello-world
580
581.. js:function:: core.register_init(func)
582
583  **context**: body
584
585  Register a function executed after the configuration parsing. This is useful
586  to check any parameters.
587
588  :param function func: is the Lua function called to work as initializer.
589
590  The prototype of the Lua function used as argument is:
591
592.. code-block:: lua
593
594    function()
595..
596
597  It takes no input, and no output is expected.
598
599.. js:function:: core.register_task(func)
600
601  **context**: body, init, task, action, sample-fetch, converter
602
603  Register and start independent task. The task is started when the HAProxy
604  main scheduler starts. For example this type of tasks can be executed to
605  perform complex health checks.
606
607  :param function func: is the Lua function called to work as initializer.
608
609  The prototype of the Lua function used as argument is:
610
611.. code-block:: lua
612
613    function()
614..
615
616  It takes no input, and no output is expected.
617
618.. js:function:: core.register_cli([path], usage, func)
619
620  **context**: body
621
622  Register and start independent task. The task is started when the HAProxy
623  main scheduler starts. For example this type of tasks can be executed to
624  perform complex health checks.
625
626  :param array path: is the sequence of word for which the cli execute the Lua
627    binding.
628  :param string usage: is the usage message displayed in the help.
629  :param function func: is the Lua function called to handle the CLI commands.
630
631  The prototype of the Lua function used as argument is:
632
633.. code-block:: lua
634
635    function(AppletTCP, [arg1, [arg2, [...]]])
636..
637
638  I/O are managed with the :ref:`applettcp_class` object. Args are given as
639  paramter. The args embbed the registred path. If the path is declared like
640  this:
641
642.. code-block:: lua
643
644    core.register_cli({"show", "ssl", "stats"}, "Display SSL stats..", function(applet, arg1, arg2, arg3, arg4, arg5)
645	 end)
646..
647
648  And we execute this in the prompt:
649
650.. code-block:: text
651
652    > prompt
653    > show ssl stats all
654..
655
656  Then, arg1, arg2 and arg3 will contains respectivey "show", "ssl" and "stats".
657  arg4 will contain "all". arg5 contains nil.
658
659.. js:function:: core.set_nice(nice)
660
661  **context**: task, action, sample-fetch, converter
662
663  Change the nice of the current task or current session.
664
665  :param integer nice: the nice value, it must be between -1024 and 1024.
666
667.. js:function:: core.set_map(filename, key, value)
668
669  **context**: init, task, action, sample-fetch, converter
670
671  set the value *value* associated to the key *key* in the map referenced by
672  *filename*.
673
674  :param string filename: the Map reference
675  :param string key: the key to set or replace
676  :param string value: the associated value
677
678.. js:function:: core.sleep(int seconds)
679
680  **context**: body, init, task, action
681
682  The `core.sleep()` functions stop the Lua execution between specified seconds.
683
684  :param integer seconds: the required seconds.
685
686.. js:function:: core.tcp()
687
688  **context**: init, task, action
689
690  This function returns a new object of a *socket* class.
691
692  :returns: A :ref:`socket_class` object.
693
694.. js:function:: core.concat()
695
696  **context**: body, init, task, action, sample-fetch, converter
697
698  This function retruns a new concat object.
699
700  :returns: A :ref:`concat_class` object.
701
702.. js:function:: core.done(data)
703
704  **context**: body, init, task, action, sample-fetch, converter
705
706  :param any data: Return some data for the caller. It is useful with
707    sample-fetches and sample-converters.
708
709  Immediately stops the current Lua execution and returns to the caller which
710  may be a sample fetch, a converter or an action and returns the specified
711  value (ignored for actions). It is used when the LUA process finishes its
712  work and wants to give back the control to HAProxy without executing the
713  remaining code. It can be seen as a multi-level "return".
714
715.. js:function:: core.yield()
716
717  **context**: task, action, sample-fetch, converter
718
719  Give back the hand at the HAProxy scheduler. It is used when the LUA
720  processing consumes a lot of processing time.
721
722.. js:function:: core.parse_addr(address)
723
724  **context**: body, init, task, action, sample-fetch, converter
725
726  :param network: is a string describing an ipv4 or ipv6 address and optionally
727    its network length, like this: "127.0.0.1/8" or "aaaa::1234/32".
728  :returns: a userdata containing network or nil if an error occurs.
729
730  Parse ipv4 or ipv6 adresses and its facultative associated network.
731
732.. js:function:: core.match_addr(addr1, addr2)
733
734  **context**: body, init, task, action, sample-fetch, converter
735
736  :param addr1: is an address created with "core.parse_addr".
737  :param addr2: is an address created with "core.parse_addr".
738  :returns: boolean, true if the network of the addresses matche, else returns
739    false.
740
741  Match two networks. For example "127.0.0.1/32" matchs "127.0.0.0/8". The order
742  of network is not important.
743
744.. js:function:: core.tokenize(str, separators [, noblank])
745
746  **context**: body, init, task, action, sample-fetch, converter
747
748  This function is useful for tokenizing an entry, or splitting some messages.
749  :param string str: The string which will be split.
750  :param string separators: A string containing a list of separators.
751  :param boolean noblank: Ignore empty entries.
752  :returns: an array of string.
753
754  For example:
755
756.. code-block:: lua
757
758	local array = core.tokenize("This function is useful, for tokenizing an entry.", "., ", true)
759	print_r(array)
760..
761
762  Returns this array:
763
764.. code-block:: text
765
766	(table) table: 0x21c01e0 [
767	    1: (string) "This"
768	    2: (string) "function"
769	    3: (string) "is"
770	    4: (string) "useful"
771	    5: (string) "for"
772	    6: (string) "tokenizing"
773	    7: (string) "an"
774	    8: (string) "entry"
775	]
776..
777
778.. _proxy_class:
779
780Proxy class
781============
782
783.. js:class:: Proxy
784
785  This class provides a way for manipulating proxy and retrieving information
786  like statistics.
787
788.. js:attribute:: Proxy.servers
789
790  Contain an array with the attached servers. Each server entry is an object of
791  type :ref:`server_class`.
792
793.. js:attribute:: Proxy.listeners
794
795  Contain an array with the attached listeners. Each listeners entry is an
796  object of type :ref:`listener_class`.
797
798.. js:function:: Proxy.pause(px)
799
800  Pause the proxy. See the management socket documentation for more information.
801
802  :param class_proxy px: A :ref:`proxy_class` which indicates the manipulated
803    proxy.
804
805.. js:function:: Proxy.resume(px)
806
807  Resume the proxy. See the management socket documentation for more
808  information.
809
810  :param class_proxy px: A :ref:`proxy_class` which indicates the manipulated
811    proxy.
812
813.. js:function:: Proxy.stop(px)
814
815  Stop the proxy. See the management socket documentation for more information.
816
817  :param class_proxy px: A :ref:`proxy_class` which indicates the manipulated
818    proxy.
819
820.. js:function:: Proxy.shut_bcksess(px)
821
822  Kill the session attached to a backup server. See the management socket
823  documentation for more information.
824
825  :param class_proxy px: A :ref:`proxy_class` which indicates the manipulated
826    proxy.
827
828.. js:function:: Proxy.get_cap(px)
829
830  Returns a string describing the capabilities of the proxy.
831
832  :param class_proxy px: A :ref:`proxy_class` which indicates the manipulated
833    proxy.
834  :returns: a string "frontend", "backend", "proxy" or "ruleset".
835
836.. js:function:: Proxy.get_mode(px)
837
838  Returns a string describing the mode of the current proxy.
839
840  :param class_proxy px: A :ref:`proxy_class` which indicates the manipulated
841    proxy.
842  :returns: a string "tcp", "http", "health" or "unknown"
843
844.. js:function:: Proxy.get_stats(px)
845
846  Returns an array containg the proxy statistics. The statistics returned are
847  not the same if the proxy is frontend or a backend.
848
849  :param class_proxy px: A :ref:`proxy_class` which indicates the manipulated
850    proxy.
851  :returns: a key/value array containing stats
852
853.. _server_class:
854
855Server class
856============
857
858.. js:function:: Server.is_draining(sv)
859
860  Return true if the server is currently draining stiky connections.
861
862  :param class_server sv: A :ref:`server_class` which indicates the manipulated
863    server.
864  :returns: a boolean
865
866.. js:function:: Server.set_weight(sv, weight)
867
868  Dynamically change the weight of the serveur. See the management socket
869  documentation for more information about the format of the string.
870
871  :param class_server sv: A :ref:`server_class` which indicates the manipulated
872    server.
873  :param string weight: A string describing the server weight.
874
875.. js:function:: Server.get_weight(sv)
876
877  This function returns an integer representing the serveur weight.
878
879  :param class_server sv: A :ref:`server_class` which indicates the manipulated
880    server.
881  :returns: an integer.
882
883.. js:function:: Server.set_addr(sv, addr)
884
885  Dynamically change the address of the serveur. See the management socket
886  documentation for more information about the format of the string.
887
888  :param class_server sv: A :ref:`server_class` which indicates the manipulated
889    server.
890  :param string weight: A string describing the server address.
891
892.. js:function:: Server.get_addr(sv)
893
894  Returns a string describing the address of the serveur.
895
896  :param class_server sv: A :ref:`server_class` which indicates the manipulated
897    server.
898  :returns: A string
899
900.. js:function:: Server.get_stats(sv)
901
902  Returns server statistics.
903
904  :param class_server sv: A :ref:`server_class` which indicates the manipulated
905    server.
906  :returns: a key/value array containing stats
907
908.. js:function:: Server.shut_sess(sv)
909
910  Shutdown all the sessions attached to the server. See the management socket
911  documentation for more information about this function.
912
913  :param class_server sv: A :ref:`server_class` which indicates the manipulated
914    server.
915
916.. js:function:: Server.set_drain(sv)
917
918  Drain sticky sessions. See the management socket documentation for more
919  information about this function.
920
921  :param class_server sv: A :ref:`server_class` which indicates the manipulated
922    server.
923
924.. js:function:: Server.set_maint(sv)
925
926  Set maintenance mode. See the management socket documentation for more
927  information about this function.
928
929  :param class_server sv: A :ref:`server_class` which indicates the manipulated
930    server.
931
932.. js:function:: Server.set_ready(sv)
933
934  Set normal mode. See the management socket documentation for more information
935  about this function.
936
937  :param class_server sv: A :ref:`server_class` which indicates the manipulated
938    server.
939
940.. js:function:: Server.check_enable(sv)
941
942  Enable health checks. See the management socket documentation for more
943  information about this function.
944
945  :param class_server sv: A :ref:`server_class` which indicates the manipulated
946    server.
947
948.. js:function:: Server.check_disable(sv)
949
950  Disable health checks. See the management socket documentation for more
951  information about this function.
952
953  :param class_server sv: A :ref:`server_class` which indicates the manipulated
954    server.
955
956.. js:function:: Server.check_force_up(sv)
957
958  Force health-check up. See the management socket documentation for more
959  information about this function.
960
961  :param class_server sv: A :ref:`server_class` which indicates the manipulated
962    server.
963
964.. js:function:: Server.check_force_nolb(sv)
965
966  Force health-check nolb mode. See the management socket documentation for more
967  information about this function.
968
969  :param class_server sv: A :ref:`server_class` which indicates the manipulated
970    server.
971
972.. js:function:: Server.check_force_down(sv)
973
974  Force health-check down. See the management socket documentation for more
975  information about this function.
976
977  :param class_server sv: A :ref:`server_class` which indicates the manipulated
978    server.
979
980.. js:function:: Server.agent_enable(sv)
981
982  Enable agent check. See the management socket documentation for more
983  information about this function.
984
985  :param class_server sv: A :ref:`server_class` which indicates the manipulated
986    server.
987
988.. js:function:: Server.agent_disable(sv)
989
990  Disable agent check. See the management socket documentation for more
991  information about this function.
992
993  :param class_server sv: A :ref:`server_class` which indicates the manipulated
994    server.
995
996.. js:function:: Server.agent_force_up(sv)
997
998  Force agent check up. See the management socket documentation for more
999  information about this function.
1000
1001  :param class_server sv: A :ref:`server_class` which indicates the manipulated
1002    server.
1003
1004.. js:function:: Server.agent_force_down(sv)
1005
1006  Force agent check down. See the management socket documentation for more
1007  information about this function.
1008
1009  :param class_server sv: A :ref:`server_class` which indicates the manipulated
1010    server.
1011
1012.. _listener_class:
1013
1014Listener class
1015==============
1016
1017.. js:function:: Listener.get_stats(ls)
1018
1019  Returns server statistics.
1020
1021  :param class_listener ls: A :ref:`listener_class` which indicates the
1022    manipulated listener.
1023  :returns: a key/value array containing stats
1024
1025.. _concat_class:
1026
1027Concat class
1028============
1029
1030.. js:class:: Concat
1031
1032  This class provides a fast way for string concatenation. The way using native
1033  Lua concatenation like the code below is slow for some reasons.
1034
1035.. code-block:: lua
1036
1037  str = "string1"
1038  str = str .. ", string2"
1039  str = str .. ", string3"
1040..
1041
1042  For each concatenation, Lua:
1043  * allocate memory for the result,
1044  * catenate the two string copying the strings in the new memory bloc,
1045  * free the old memory block containing the string whoch is no longer used.
1046  This process does many memory move, allocation and free. In addition, the
1047  memory is not really freed, it is just mark mark as unsused and wait for the
1048  garbage collector.
1049
1050  The Concat class provide an alternative way for catenating strings. It uses
1051  the internal Lua mechanism (it does not allocate memory), but it doesn't copy
1052  the data more than once.
1053
1054  On my computer, the following loops spends 0.2s for the Concat method and
1055  18.5s for the pure Lua implementation. So, the Concat class is about 1000x
1056  faster than the embedded solution.
1057
1058.. code-block:: lua
1059
1060  for j = 1, 100 do
1061    c = core.concat()
1062    for i = 1, 20000 do
1063      c:add("#####")
1064    end
1065  end
1066..
1067
1068.. code-block:: lua
1069
1070  for j = 1, 100 do
1071    c = ""
1072    for i = 1, 20000 do
1073      c = c .. "#####"
1074    end
1075  end
1076..
1077
1078.. js:function:: Concat.add(concat, string)
1079
1080  This function adds a string to the current concatenated string.
1081
1082  :param class_concat concat: A :ref:`concat_class` which contains the currently
1083    builded string.
1084  :param string string: A new string to concatenate to the current builded
1085    string.
1086
1087.. js:function:: Concat.dump(concat)
1088
1089  This function returns the concanated string.
1090
1091  :param class_concat concat: A :ref:`concat_class` which contains the currently
1092    builded string.
1093  :returns: the concatenated string
1094
1095.. _fetches_class:
1096
1097Fetches class
1098=============
1099
1100.. js:class:: Fetches
1101
1102  This class contains a lot of internal HAProxy sample fetches. See the
1103  HAProxy "configuration.txt" documentation for more information about her
1104  usage. they are the chapters 7.3.2 to 7.3.6.
1105
1106  **warning** some sample fetches are not available in some context. These
1107  limitations are specified in this documentation when theire useful.
1108
1109  :see: :js:attr:`TXN.f`
1110  :see: :js:attr:`TXN.sf`
1111
1112  Fetches are useful for:
1113
1114  * get system time,
1115  * get environment variable,
1116  * get random numbers,
1117  * known backend status like the number of users in queue or the number of
1118    connections established,
1119  * client information like ip source or destination,
1120  * deal with stick tables,
1121  * Established SSL informations,
1122  * HTTP information like headers or method.
1123
1124.. code-block:: lua
1125
1126  function action(txn)
1127    -- Get source IP
1128    local clientip = txn.f:src()
1129  end
1130..
1131
1132.. _converters_class:
1133
1134Converters class
1135================
1136
1137.. js:class:: Converters
1138
1139  This class contains a lot of internal HAProxy sample converters. See the
1140  HAProxy documentation "configuration.txt" for more information about her
1141  usage. Its the chapter 7.3.1.
1142
1143  :see: :js:attr:`TXN.c`
1144  :see: :js:attr:`TXN.sc`
1145
1146  Converters provides statefull transformation. They are useful for:
1147
1148  * converting input to base64,
1149  * applying hash on input string (djb2, crc32, sdbm, wt6),
1150  * format date,
1151  * json escape,
1152  * extracting preferred language comparing two lists,
1153  * turn to lower or upper chars,
1154  * deal with stick tables.
1155
1156.. _channel_class:
1157
1158Channel class
1159=============
1160
1161.. js:class:: Channel
1162
1163  HAProxy uses two buffers for the processing of the requests. The first one is
1164  used with the request data (from the client to the server) and the second is
1165  used for the response data (from the server to the client).
1166
1167  Each buffer contains two types of data. The first type is the incoming data
1168  waiting for a processing. The second part is the outgoing data already
1169  processed. Usually, the incoming data is processed, after it is tagged as
1170  outgoing data, and finally it is sent. The following functions provides tools
1171  for manipulating these data in a buffer.
1172
1173  The following diagram shows where the channel class function are applied.
1174
1175  **Warning**: It is not possible to read from the response in request action,
1176  and it is not possible to read for the request channel in response action.
1177
1178.. image:: _static/channel.png
1179
1180.. js:function:: Channel.dup(channel)
1181
1182  This function returns a string that contain the entire buffer. The data is
1183  not remove from the buffer and can be reprocessed later.
1184
1185  If the buffer cant receive more data, a 'nil' value is returned.
1186
1187  :param class_channel channel: The manipulated Channel.
1188  :returns: a string containing all the available data or nil.
1189
1190.. js:function:: Channel.get(channel)
1191
1192  This function returns a string that contain the entire buffer. The data is
1193  consumed from the buffer.
1194
1195  If the buffer cant receive more data, a 'nil' value is returned.
1196
1197  :param class_channel channel: The manipulated Channel.
1198  :returns: a string containing all the available data or nil.
1199
1200.. js:function:: Channel.getline(channel)
1201
1202  This function returns a string that contain the first line of the buffer. The
1203  data is consumed. If the data returned doesn't contains a final '\n' its
1204  assumed than its the last available data in the buffer.
1205
1206  If the buffer cant receive more data, a 'nil' value is returned.
1207
1208  :param class_channel channel: The manipulated Channel.
1209  :returns: a string containing the available line or nil.
1210
1211.. js:function:: Channel.set(channel, string)
1212
1213  This function replace the content of the buffer by the string. The function
1214  returns the copied length, otherwise, it returns -1.
1215
1216  The data set with this function are not send. They wait for the end of
1217  HAProxy processing, so the buffer can be full.
1218
1219  :param class_channel channel: The manipulated Channel.
1220  :param string string: The data which will sent.
1221  :returns: an integer containing the amount of bytes copied or -1.
1222
1223.. js:function:: Channel.append(channel, string)
1224
1225  This function append the string argument to the content of the buffer. The
1226  function returns the copied length, otherwise, it returns -1.
1227
1228  The data set with this function are not send. They wait for the end of
1229  HAProxy processing, so the buffer can be full.
1230
1231  :param class_channel channel: The manipulated Channel.
1232  :param string string: The data which will sent.
1233  :returns: an integer containing the amount of bytes copied or -1.
1234
1235.. js:function:: Channel.send(channel, string)
1236
1237  This function required immediate send of the data. Unless if the connection
1238  is close, the buffer is regularly flushed and all the string can be sent.
1239
1240  :param class_channel channel: The manipulated Channel.
1241  :param string string: The data which will sent.
1242  :returns: an integer containing the amount of bytes copied or -1.
1243
1244.. js:function:: Channel.get_in_length(channel)
1245
1246  This function returns the length of the input part of the buffer.
1247
1248  :param class_channel channel: The manipulated Channel.
1249  :returns: an integer containing the amount of available bytes.
1250
1251.. js:function:: Channel.get_out_length(channel)
1252
1253  This function returns the length of the output part of the buffer.
1254
1255  :param class_channel channel: The manipulated Channel.
1256  :returns: an integer containing the amount of available bytes.
1257
1258.. js:function:: Channel.forward(channel, int)
1259
1260  This function transfer bytes from the input part of the buffer to the output
1261  part.
1262
1263  :param class_channel channel: The manipulated Channel.
1264  :param integer int: The amount of data which will be forwarded.
1265
1266.. js:function:: Channel.is_full(channel)
1267
1268  This function returns true if the buffer channel is full.
1269
1270  :returns: a boolean
1271
1272.. _http_class:
1273
1274HTTP class
1275==========
1276
1277.. js:class:: HTTP
1278
1279   This class contain all the HTTP manipulation functions.
1280
1281.. js:function:: HTTP.req_get_headers(http)
1282
1283  Returns an array containing all the request headers.
1284
1285  :param class_http http: The related http object.
1286  :returns: array of headers.
1287  :see: :js:func:`HTTP.res_get_headers`
1288
1289  This is the form of the returned array:
1290
1291.. code-block:: lua
1292
1293  HTTP:req_get_headers()['<header-name>'][<header-index>] = "<header-value>"
1294
1295  local hdr = HTTP:req_get_headers()
1296  hdr["host"][0] = "www.test.com"
1297  hdr["accept"][0] = "audio/basic q=1"
1298  hdr["accept"][1] = "audio/*, q=0.2"
1299  hdr["accept"][2] = "*/*, q=0.1"
1300..
1301
1302.. js:function:: HTTP.res_get_headers(http)
1303
1304  Returns an array containing all the response headers.
1305
1306  :param class_http http: The related http object.
1307  :returns: array of headers.
1308  :see: :js:func:`HTTP.req_get_headers`
1309
1310  This is the form of the returned array:
1311
1312.. code-block:: lua
1313
1314  HTTP:res_get_headers()['<header-name>'][<header-index>] = "<header-value>"
1315
1316  local hdr = HTTP:req_get_headers()
1317  hdr["host"][0] = "www.test.com"
1318  hdr["accept"][0] = "audio/basic q=1"
1319  hdr["accept"][1] = "audio/*, q=0.2"
1320  hdr["accept"][2] = "*.*, q=0.1"
1321..
1322
1323.. js:function:: HTTP.req_add_header(http, name, value)
1324
1325  Appends an HTTP header field in the request whose name is
1326  specified in "name" and whose value is defined in "value".
1327
1328  :param class_http http: The related http object.
1329  :param string name: The header name.
1330  :param string value: The header value.
1331  :see: :js:func:`HTTP.res_add_header`
1332
1333.. js:function:: HTTP.res_add_header(http, name, value)
1334
1335  appends an HTTP header field in the response whose name is
1336  specified in "name" and whose value is defined in "value".
1337
1338  :param class_http http: The related http object.
1339  :param string name: The header name.
1340  :param string value: The header value.
1341  :see: :js:func:`HTTP.req_add_header`
1342
1343.. js:function:: HTTP.req_del_header(http, name)
1344
1345  Removes all HTTP header fields in the request whose name is
1346  specified in "name".
1347
1348  :param class_http http: The related http object.
1349  :param string name: The header name.
1350  :see: :js:func:`HTTP.res_del_header`
1351
1352.. js:function:: HTTP.res_del_header(http, name)
1353
1354  Removes all HTTP header fields in the response whose name is
1355  specified in "name".
1356
1357  :param class_http http: The related http object.
1358  :param string name: The header name.
1359  :see: :js:func:`HTTP.req_del_header`
1360
1361.. js:function:: HTTP.req_set_header(http, name, value)
1362
1363  This variable replace all occurence of all header "name", by only
1364  one containing the "value".
1365
1366  :param class_http http: The related http object.
1367  :param string name: The header name.
1368  :param string value: The header value.
1369  :see: :js:func:`HTTP.res_set_header`
1370
1371  This function does the same work as the folowwing code:
1372
1373.. code-block:: lua
1374
1375   function fcn(txn)
1376      TXN.http:req_del_header("header")
1377      TXN.http:req_add_header("header", "value")
1378   end
1379..
1380
1381.. js:function:: HTTP.res_set_header(http, name, value)
1382
1383  This variable replace all occurence of all header "name", by only
1384  one containing the "value".
1385
1386  :param class_http http: The related http object.
1387  :param string name: The header name.
1388  :param string value: The header value.
1389  :see: :js:func:`HTTP.req_rep_header()`
1390
1391.. js:function:: HTTP.req_rep_header(http, name, regex, replace)
1392
1393  Matches the regular expression in all occurrences of header field "name"
1394  according to "regex", and replaces them with the "replace" argument. The
1395  replacement value can contain back references like \1, \2, ... This
1396  function works with the request.
1397
1398  :param class_http http: The related http object.
1399  :param string name: The header name.
1400  :param string regex: The match regular expression.
1401  :param string replace: The replacement value.
1402  :see: :js:func:`HTTP.res_rep_header()`
1403
1404.. js:function:: HTTP.res_rep_header(http, name, regex, string)
1405
1406  Matches the regular expression in all occurrences of header field "name"
1407  according to "regex", and replaces them with the "replace" argument. The
1408  replacement value can contain back references like \1, \2, ... This
1409  function works with the request.
1410
1411  :param class_http http: The related http object.
1412  :param string name: The header name.
1413  :param string regex: The match regular expression.
1414  :param string replace: The replacement value.
1415  :see: :js:func:`HTTP.req_rep_header()`
1416
1417.. js:function:: HTTP.req_set_method(http, method)
1418
1419  Rewrites the request method with the parameter "method".
1420
1421  :param class_http http: The related http object.
1422  :param string method: The new method.
1423
1424.. js:function:: HTTP.req_set_path(http, path)
1425
1426  Rewrites the request path with the "path" parameter.
1427
1428  :param class_http http: The related http object.
1429  :param string path: The new path.
1430
1431.. js:function:: HTTP.req_set_query(http, query)
1432
1433  Rewrites the request's query string which appears after the first question
1434  mark ("?") with the parameter "query".
1435
1436  :param class_http http: The related http object.
1437  :param string query: The new query.
1438
1439.. js:function:: HTTP.req_set_uri(http, uri)
1440
1441  Rewrites the request URI with the parameter "uri".
1442
1443  :param class_http http: The related http object.
1444  :param string uri: The new uri.
1445
1446.. js:function:: HTTP.res_set_status(http, status [, reason])
1447
1448  Rewrites the response status code with the parameter "code".
1449
1450  If no custom reason is provided, it will be generated from the status.
1451
1452  :param class_http http: The related http object.
1453  :param integer status: The new response status code.
1454  :param string reason: The new response reason (optional).
1455
1456.. _txn_class:
1457
1458TXN class
1459=========
1460
1461.. js:class:: TXN
1462
1463  The txn class contain all the functions relative to the http or tcp
1464  transaction (Note than a tcp stream is the same than a tcp transaction, but
1465  an HTTP transaction is not the same than a tcp stream).
1466
1467  The usage of this class permits to retrieve data from the requests, alter it
1468  and forward it.
1469
1470  All the functions provided by this class are available in the context
1471  **sample-fetches** and **actions**.
1472
1473.. js:attribute:: TXN.c
1474
1475  :returns: An :ref:`converters_class`.
1476
1477  This attribute contains a Converters class object.
1478
1479.. js:attribute:: TXN.sc
1480
1481  :returns: An :ref:`converters_class`.
1482
1483  This attribute contains a Converters class object. The functions of
1484  this object returns always a string.
1485
1486.. js:attribute:: TXN.f
1487
1488  :returns: An :ref:`fetches_class`.
1489
1490  This attribute contains a Fetches class object.
1491
1492.. js:attribute:: TXN.sf
1493
1494  :returns: An :ref:`fetches_class`.
1495
1496  This attribute contains a Fetches class object. The functions of
1497  this object returns always a string.
1498
1499.. js:attribute:: TXN.req
1500
1501  :returns: An :ref:`channel_class`.
1502
1503  This attribute contains a channel class object for the request buffer.
1504
1505.. js:attribute:: TXN.res
1506
1507  :returns: An :ref:`channel_class`.
1508
1509  This attribute contains a channel class object for the response buffer.
1510
1511.. js:attribute:: TXN.http
1512
1513  :returns: An :ref:`http_class`.
1514
1515  This attribute contains an HTTP class object. It is avalaible only if the
1516  proxy has the "mode http" enabled.
1517
1518.. js:function:: TXN.log(TXN, loglevel, msg)
1519
1520  This function sends a log. The log is sent, according with the HAProxy
1521  configuration file, on the default syslog server if it is configured and on
1522  the stderr if it is allowed.
1523
1524  :param class_txn txn: The class txn object containing the data.
1525  :param integer loglevel: Is the log level asociated with the message. It is a
1526    number between 0 and 7.
1527  :param string msg: The log content.
1528  :see: :js:attr:`core.emerg`, :js:attr:`core.alert`, :js:attr:`core.crit`,
1529    :js:attr:`core.err`, :js:attr:`core.warning`, :js:attr:`core.notice`,
1530    :js:attr:`core.info`, :js:attr:`core.debug` (log level definitions)
1531  :see: :js:func:`TXN.deflog`
1532  :see: :js:func:`TXN.Debug`
1533  :see: :js:func:`TXN.Info`
1534  :see: :js:func:`TXN.Warning`
1535  :see: :js:func:`TXN.Alert`
1536
1537.. js:function:: TXN.deflog(TXN, msg)
1538
1539  Sends a log line with the default loglevel for the proxy ssociated with the
1540  transaction.
1541
1542  :param class_txn txn: The class txn object containing the data.
1543  :param string msg: The log content.
1544  :see: :js:func:`TXN.log
1545
1546.. js:function:: TXN.Debug(txn, msg)
1547
1548  :param class_txn txn: The class txn object containing the data.
1549  :param string msg: The log content.
1550  :see: :js:func:`TXN.log`
1551
1552  Does the same job than:
1553
1554.. code-block:: lua
1555
1556  function Debug(txn, msg)
1557    TXN.log(txn, core.debug, msg)
1558  end
1559..
1560
1561.. js:function:: TXN.Info(txn, msg)
1562
1563  :param class_txn txn: The class txn object containing the data.
1564  :param string msg: The log content.
1565  :see: :js:func:`TXN.log`
1566
1567.. code-block:: lua
1568
1569  function Debug(txn, msg)
1570    TXN.log(txn, core.info, msg)
1571  end
1572..
1573
1574.. js:function:: TXN.Warning(txn, msg)
1575
1576  :param class_txn txn: The class txn object containing the data.
1577  :param string msg: The log content.
1578  :see: :js:func:`TXN.log`
1579
1580.. code-block:: lua
1581
1582  function Debug(txn, msg)
1583    TXN.log(txn, core.warning, msg)
1584  end
1585..
1586
1587.. js:function:: TXN.Alert(txn, msg)
1588
1589  :param class_txn txn: The class txn object containing the data.
1590  :param string msg: The log content.
1591  :see: :js:func:`TXN.log`
1592
1593.. code-block:: lua
1594
1595  function Debug(txn, msg)
1596    TXN.log(txn, core.alert, msg)
1597  end
1598..
1599
1600.. js:function:: TXN.get_priv(txn)
1601
1602  Return Lua data stored in the current transaction (with the `TXN.set_priv()`)
1603  function. If no data are stored, it returns a nil value.
1604
1605  :param class_txn txn: The class txn object containing the data.
1606  :returns: the opaque data previsously stored, or nil if nothing is
1607     avalaible.
1608
1609.. js:function:: TXN.set_priv(txn, data)
1610
1611  Store any data in the current HAProxy transaction. This action replace the
1612  old stored data.
1613
1614  :param class_txn txn: The class txn object containing the data.
1615  :param opaque data: The data which is stored in the transaction.
1616
1617.. js:function:: TXN.set_var(TXN, var, value)
1618
1619  Converts a Lua type in a HAProxy type and store it in a variable <var>.
1620
1621  :param class_txn txn: The class txn object containing the data.
1622  :param string var: The variable name according with the HAProxy variable syntax.
1623  :param type value: The value associated to the variable. The type can be string or
1624                     integer.
1625
1626.. js:function:: TXN.unset_var(TXN, var)
1627
1628  Unset the variable <var>.
1629
1630  :param class_txn txn: The class txn object containing the data.
1631  :param string var: The variable name according with the HAProxy variable syntax.
1632
1633.. js:function:: TXN.get_var(TXN, var)
1634
1635  Returns data stored in the variable <var> converter in Lua type.
1636
1637  :param class_txn txn: The class txn object containing the data.
1638  :param string var: The variable name according with the HAProxy variable syntax.
1639
1640.. js:function:: TXN.done(txn)
1641
1642  This function terminates processing of the transaction and the associated
1643  session. It can be used when a critical error is detected or to terminate
1644  processing after some data have been returned to the client (eg: a redirect).
1645
1646  *Warning*: It not make sense to call this function from sample-fetches. In
1647  this case the behaviour of this one is the same than core.done(): it quit
1648  the Lua execution. The transaction is really aborted only from an action
1649  registered function.
1650
1651  :param class_txn txn: The class txn object containing the data.
1652
1653.. js:function:: TXN.set_loglevel(txn, loglevel)
1654
1655  Is used to change the log level of the current request. The "loglevel" must
1656  be an integer between 0 and 7.
1657
1658  :param class_txn txn: The class txn object containing the data.
1659  :param integer loglevel: The required log level. This variable can be one of
1660  :see: :js:attr:`core.emerg`, :js:attr:`core.alert`, :js:attr:`core.crit`,
1661    :js:attr:`core.err`, :js:attr:`core.warning`, :js:attr:`core.notice`,
1662    :js:attr:`core.info`, :js:attr:`core.debug` (log level definitions)
1663
1664.. js:function:: TXN.set_tos(txn, tos)
1665
1666  Is used to set the TOS or DSCP field value of packets sent to the client to
1667  the value passed in "tos" on platforms which support this.
1668
1669  :param class_txn txn: The class txn object containing the data.
1670  :param integer tos: The new TOS os DSCP.
1671
1672.. js:function:: TXN.set_mark(txn, mark)
1673
1674  Is used to set the Netfilter MARK on all packets sent to the client to the
1675  value passed in "mark" on platforms which support it.
1676
1677  :param class_txn txn: The class txn object containing the data.
1678  :param integer mark: The mark value.
1679
1680.. _socket_class:
1681
1682Socket class
1683============
1684
1685.. js:class:: Socket
1686
1687  This class must be compatible with the Lua Socket class. Only the 'client'
1688  functions are available. See the Lua Socket documentation:
1689
1690  `http://w3.impa.br/~diego/software/luasocket/tcp.html
1691  <http://w3.impa.br/~diego/software/luasocket/tcp.html>`_
1692
1693.. js:function:: Socket.close(socket)
1694
1695  Closes a TCP object. The internal socket used by the object is closed and the
1696  local address to which the object was bound is made available to other
1697  applications. No further operations (except for further calls to the close
1698  method) are allowed on a closed Socket.
1699
1700  :param class_socket socket: Is the manipulated Socket.
1701
1702  Note: It is important to close all used sockets once they are not needed,
1703  since, in many systems, each socket uses a file descriptor, which are limited
1704  system resources. Garbage-collected objects are automatically closed before
1705  destruction, though.
1706
1707.. js:function:: Socket.connect(socket, address[, port])
1708
1709  Attempts to connect a socket object to a remote host.
1710
1711
1712  In case of error, the method returns nil followed by a string describing the
1713  error. In case of success, the method returns 1.
1714
1715  :param class_socket socket: Is the manipulated Socket.
1716  :param string address: can be an IP address or a host name. See below for more
1717                         information.
1718  :param integer port: must be an integer number in the range [1..64K].
1719  :returns: 1 or nil.
1720
1721  an address field extension permits to use the connect() function to connect to
1722  other stream than TCP. The syntax containing a simpleipv4 or ipv6 address is
1723  the basically expected format. This format requires the port.
1724
1725  Other format accepted are a socket path like "/socket/path", it permits to
1726  connect to a socket. abstract namespaces are supported with the prefix
1727  "abns@", and finaly a filedescriotr can be passed with the prefix "fd@".
1728  The prefix "ipv4@", "ipv6@" and "unix@" are also supported. The port can be
1729  passed int the string. The syntax "127.0.0.1:1234" is valid. in this case, the
1730  parameter *port* is ignored.
1731
1732.. js:function:: Socket.connect_ssl(socket, address, port)
1733
1734  Same behavior than the function socket:connect, but uses SSL.
1735
1736  :param class_socket socket: Is the manipulated Socket.
1737  :returns: 1 or nil.
1738
1739.. js:function:: Socket.getpeername(socket)
1740
1741  Returns information about the remote side of a connected client object.
1742
1743  Returns a string with the IP address of the peer, followed by the port number
1744  that peer is using for the connection. In case of error, the method returns
1745  nil.
1746
1747  :param class_socket socket: Is the manipulated Socket.
1748  :returns: a string containing the server information.
1749
1750.. js:function:: Socket.getsockname(socket)
1751
1752  Returns the local address information associated to the object.
1753
1754  The method returns a string with local IP address and a number with the port.
1755  In case of error, the method returns nil.
1756
1757  :param class_socket socket: Is the manipulated Socket.
1758  :returns: a string containing the client information.
1759
1760.. js:function:: Socket.receive(socket, [pattern [, prefix]])
1761
1762  Reads data from a client object, according to the specified read pattern.
1763  Patterns follow the Lua file I/O format, and the difference in performance
1764  between all patterns is negligible.
1765
1766  :param class_socket socket: Is the manipulated Socket.
1767  :param string|integer pattern: Describe what is required (see below).
1768  :param string prefix: A string which will be prefix the returned data.
1769  :returns:  a string containing the required data or nil.
1770
1771  Pattern can be any of the following:
1772
1773  * **`*a`**: reads from the socket until the connection is closed. No
1774              end-of-line translation is performed;
1775
1776  * **`*l`**: reads a line of text from the Socket. The line is terminated by a
1777              LF character (ASCII 10), optionally preceded by a CR character
1778              (ASCII 13). The CR and LF characters are not included in the
1779              returned line.  In fact, all CR characters are ignored by the
1780              pattern. This is the default pattern.
1781
1782  * **number**: causes the method to read a specified number of bytes from the
1783                Socket. Prefix is an optional string to be concatenated to the
1784                beginning of any received data before return.
1785
1786  * **empty**: If the pattern is left empty, the default option is `*l`.
1787
1788  If successful, the method returns the received pattern. In case of error, the
1789  method returns nil followed by an error message which can be the string
1790  'closed' in case the connection was closed before the transmission was
1791  completed or the string 'timeout' in case there was a timeout during the
1792  operation. Also, after the error message, the function returns the partial
1793  result of the transmission.
1794
1795  Important note: This function was changed severely. It used to support
1796  multiple patterns (but I have never seen this feature used) and now it
1797  doesn't anymore.  Partial results used to be returned in the same way as
1798  successful results. This last feature violated the idea that all functions
1799  should return nil on error.  Thus it was changed too.
1800
1801.. js:function:: Socket.send(socket, data [, start [, end ]])
1802
1803  Sends data through client object.
1804
1805  :param class_socket socket: Is the manipulated Socket.
1806  :param string data: The data that will be sent.
1807  :param integer start: The start position in the buffer of the data which will
1808   be sent.
1809  :param integer end: The end position in the buffer of the data which will
1810   be sent.
1811  :returns: see below.
1812
1813  Data is the string to be sent. The optional arguments i and j work exactly
1814  like the standard string.sub Lua function to allow the selection of a
1815  substring to be sent.
1816
1817  If successful, the method returns the index of the last byte within [start,
1818  end] that has been sent. Notice that, if start is 1 or absent, this is
1819  effectively the total number of bytes sent. In case of error, the method
1820  returns nil, followed by an error message, followed by the index of the last
1821  byte within [start, end] that has been sent. You might want to try again from
1822  the byte following that. The error message can be 'closed' in case the
1823  connection was closed before the transmission was completed or the string
1824  'timeout' in case there was a timeout during the operation.
1825
1826  Note: Output is not buffered. For small strings, it is always better to
1827  concatenate them in Lua (with the '..' operator) and send the result in one
1828  call instead of calling the method several times.
1829
1830.. js:function:: Socket.setoption(socket, option [, value])
1831
1832  Just implemented for compatibility, this cal does nothing.
1833
1834.. js:function:: Socket.settimeout(socket, value [, mode])
1835
1836  Changes the timeout values for the object. All I/O operations are blocking.
1837  That is, any call to the methods send, receive, and accept will block
1838  indefinitely, until the operation completes. The settimeout method defines a
1839  limit on the amount of time the I/O methods can block. When a timeout time
1840  has elapsed, the affected methods give up and fail with an error code.
1841
1842  The amount of time to wait is specified as the value parameter, in seconds.
1843
1844  The timeout modes are bot implemented, the only settable timeout is the
1845  inactivity time waiting for complete the internal buffer send or waiting for
1846  receive data.
1847
1848  :param class_socket socket: Is the manipulated Socket.
1849  :param integer value: The timeout value.
1850
1851.. _map_class:
1852
1853Map class
1854=========
1855
1856.. js:class:: Map
1857
1858  This class permits to do some lookup in HAProxy maps. The declared maps can
1859  be modified during the runtime throught the HAProxy management socket.
1860
1861.. code-block:: lua
1862
1863  default = "usa"
1864
1865  -- Create and load map
1866  geo = Map.new("geo.map", Map._ip);
1867
1868  -- Create new fetch that returns the user country
1869  core.register_fetches("country", function(txn)
1870    local src;
1871    local loc;
1872
1873    src = txn.f:fhdr("x-forwarded-for");
1874    if (src == nil) then
1875      src = txn.f:src()
1876      if (src == nil) then
1877        return default;
1878      end
1879    end
1880
1881    -- Perform lookup
1882    loc = geo:lookup(src);
1883
1884    if (loc == nil) then
1885      return default;
1886    end
1887
1888    return loc;
1889  end);
1890
1891.. js:attribute:: Map._int
1892
1893  See the HAProxy configuration.txt file, chapter "Using ACLs and fetching
1894  samples" ans subchapter "ACL basics" to understand this pattern matching
1895  method.
1896
1897  Note that :js:attr:`Map.int` is also available for compatibility.
1898
1899.. js:attribute:: Map._ip
1900
1901  See the HAProxy configuration.txt file, chapter "Using ACLs and fetching
1902  samples" ans subchapter "ACL basics" to understand this pattern matching
1903  method.
1904
1905  Note that :js:attr:`Map.ip` is also available for compatibility.
1906
1907.. js:attribute:: Map._str
1908
1909  See the HAProxy configuration.txt file, chapter "Using ACLs and fetching
1910  samples" ans subchapter "ACL basics" to understand this pattern matching
1911  method.
1912
1913  Note that :js:attr:`Map.str` is also available for compatibility.
1914
1915.. js:attribute:: Map._beg
1916
1917  See the HAProxy configuration.txt file, chapter "Using ACLs and fetching
1918  samples" ans subchapter "ACL basics" to understand this pattern matching
1919  method.
1920
1921  Note that :js:attr:`Map.beg` is also available for compatibility.
1922
1923.. js:attribute:: Map._sub
1924
1925  See the HAProxy configuration.txt file, chapter "Using ACLs and fetching
1926  samples" ans subchapter "ACL basics" to understand this pattern matching
1927  method.
1928
1929  Note that :js:attr:`Map.sub` is also available for compatibility.
1930
1931.. js:attribute:: Map._dir
1932
1933  See the HAProxy configuration.txt file, chapter "Using ACLs and fetching
1934  samples" ans subchapter "ACL basics" to understand this pattern matching
1935  method.
1936
1937  Note that :js:attr:`Map.dir` is also available for compatibility.
1938
1939.. js:attribute:: Map._dom
1940
1941  See the HAProxy configuration.txt file, chapter "Using ACLs and fetching
1942  samples" ans subchapter "ACL basics" to understand this pattern matching
1943  method.
1944
1945  Note that :js:attr:`Map.dom` is also available for compatibility.
1946
1947.. js:attribute:: Map._end
1948
1949  See the HAProxy configuration.txt file, chapter "Using ACLs and fetching
1950  samples" ans subchapter "ACL basics" to understand this pattern matching
1951  method.
1952
1953.. js:attribute:: Map._reg
1954
1955  See the HAProxy configuration.txt file, chapter "Using ACLs and fetching
1956  samples" ans subchapter "ACL basics" to understand this pattern matching
1957  method.
1958
1959  Note that :js:attr:`Map.reg` is also available for compatibility.
1960
1961
1962.. js:function:: Map.new(file, method)
1963
1964  Creates and load a map.
1965
1966  :param string file: Is the file containing the map.
1967  :param integer method: Is the map pattern matching method. See the attributes
1968    of the Map class.
1969  :returns: a class Map object.
1970  :see: The Map attributes: :js:attr:`Map._int`, :js:attr:`Map._ip`,
1971    :js:attr:`Map._str`, :js:attr:`Map._beg`, :js:attr:`Map._sub`,
1972    :js:attr:`Map._dir`, :js:attr:`Map._dom`, :js:attr:`Map._end` and
1973    :js:attr:`Map._reg`.
1974
1975.. js:function:: Map.lookup(map, str)
1976
1977  Perform a lookup in a map.
1978
1979  :param class_map map: Is the class Map object.
1980  :param string str: Is the string used as key.
1981  :returns: a string containing the result or nil if no match.
1982
1983.. js:function:: Map.slookup(map, str)
1984
1985  Perform a lookup in a map.
1986
1987  :param class_map map: Is the class Map object.
1988  :param string str: Is the string used as key.
1989  :returns: a string containing the result or empty string if no match.
1990
1991.. _applethttp_class:
1992
1993AppletHTTP class
1994================
1995
1996.. js:class:: AppletHTTP
1997
1998  This class is used with applets that requires the 'http' mode. The http applet
1999  can be registered with the *core.register_service()* function. They are used
2000  for processing an http request like a server in back of HAProxy.
2001
2002  This is an hello world sample code:
2003
2004.. code-block:: lua
2005
2006  core.register_service("hello-world", "http", function(applet)
2007     local response = "Hello World !"
2008     applet:set_status(200)
2009     applet:add_header("content-length", string.len(response))
2010     applet:add_header("content-type", "text/plain")
2011     applet:start_response()
2012     applet:send(response)
2013  end)
2014
2015.. js:attribute:: AppletHTTP.c
2016
2017  :returns: A :ref:`converters_class`
2018
2019  This attribute contains a Converters class object.
2020
2021.. js:attribute:: AppletHTTP.sc
2022
2023  :returns: A :ref:`converters_class`
2024
2025  This attribute contains a Converters class object. The
2026  functions of this object returns always a string.
2027
2028.. js:attribute:: AppletHTTP.f
2029
2030  :returns: A :ref:`fetches_class`
2031
2032  This attribute contains a Fetches class object. Note that the
2033  applet execution place cannot access to a valid HAProxy core HTTP
2034  transaction, so some sample fecthes related to the HTTP dependant
2035  values (hdr, path, ...) are not available.
2036
2037.. js:attribute:: AppletHTTP.sf
2038
2039  :returns: A :ref:`fetches_class`
2040
2041  This attribute contains a Fetches class object. The functions of
2042  this object returns always a string. Note that the applet
2043  execution place cannot access to a valid HAProxy core HTTP
2044  transaction, so some sample fecthes related to the HTTP dependant
2045  values (hdr, path, ...) are not available.
2046
2047.. js:attribute:: AppletHTTP.method
2048
2049  :returns: string
2050
2051  The attribute method returns a string containing the HTTP
2052  method.
2053
2054.. js:attribute:: AppletHTTP.version
2055
2056  :returns: string
2057
2058  The attribute version, returns a string containing the HTTP
2059  request version.
2060
2061.. js:attribute:: AppletHTTP.path
2062
2063  :returns: string
2064
2065  The attribute path returns a string containing the HTTP
2066  request path.
2067
2068.. js:attribute:: AppletHTTP.qs
2069
2070  :returns: string
2071
2072  The attribute qs returns a string containing the HTTP
2073  request query string.
2074
2075.. js:attribute:: AppletHTTP.length
2076
2077  :returns: integer
2078
2079  The attribute length returns an integer containing the HTTP
2080  body length.
2081
2082.. js:attribute:: AppletHTTP.headers
2083
2084  :returns: array
2085
2086  The attribute headers returns an array containing the HTTP
2087  headers. The header names are always in lower case. As the header name can be
2088  encountered more than once in each request, the value is indexed with 0 as
2089  first index value. The array have this form:
2090
2091.. code-block:: lua
2092
2093  AppletHTTP.headers['<header-name>'][<header-index>] = "<header-value>"
2094
2095  AppletHTTP.headers["host"][0] = "www.test.com"
2096  AppletHTTP.headers["accept"][0] = "audio/basic q=1"
2097  AppletHTTP.headers["accept"][1] = "audio/*, q=0.2"
2098  AppletHTTP.headers["accept"][2] = "*/*, q=0.1"
2099..
2100
2101.. js:function:: AppletHTTP.set_status(applet, code [, reason])
2102
2103  This function sets the HTTP status code for the response. The allowed code are
2104  from 100 to 599.
2105
2106  :param class_AppletHTTP applet: An :ref:`applethttp_class`
2107  :param integer code: the status code returned to the client.
2108  :param string reason: the status reason returned to the client (optional).
2109
2110.. js:function:: AppletHTTP.add_header(applet, name, value)
2111
2112  This function add an header in the response. Duplicated headers are not
2113  collapsed. The special header *content-length* is used to determinate the
2114  response length. If it not exists, a *transfer-encoding: chunked* is set, and
2115  all the write from the funcion *AppletHTTP:send()* become a chunk.
2116
2117  :param class_AppletHTTP applet: An :ref:`applethttp_class`
2118  :param string name: the header name
2119  :param string value: the header value
2120
2121.. js:function:: AppletHTTP.start_response(applet)
2122
2123  This function indicates to the HTTP engine that it can process and send the
2124  response headers. After this called we cannot add headers to the response; We
2125  cannot use the *AppletHTTP:send()* function if the
2126  *AppletHTTP:start_response()* is not called.
2127
2128  :param class_AppletHTTP applet: An :ref:`applethttp_class`
2129
2130.. js:function:: AppletHTTP.getline(applet)
2131
2132  This function returns a string containing one line from the http body. If the
2133  data returned doesn't contains a final '\\n' its assumed than its the last
2134  available data before the end of stream.
2135
2136  :param class_AppletHTTP applet: An :ref:`applethttp_class`
2137  :returns: a string. The string can be empty if we reach the end of the stream.
2138
2139.. js:function:: AppletHTTP.receive(applet, [size])
2140
2141  Reads data from the HTTP body, according to the specified read *size*. If the
2142  *size* is missing, the function tries to read all the content of the stream
2143  until the end. If the *size* is bigger than the http body, it returns the
2144  amount of data avalaible.
2145
2146  :param class_AppletHTTP applet: An :ref:`applethttp_class`
2147  :param integer size: the required read size.
2148  :returns: always return a string,the string can be empty is the connexion is
2149            closed.
2150
2151.. js:function:: AppletHTTP.send(applet, msg)
2152
2153  Send the message *msg* on the http request body.
2154
2155  :param class_AppletHTTP applet: An :ref:`applethttp_class`
2156  :param string msg: the message to send.
2157
2158.. js:function:: AppletHTTP.get_priv(applet)
2159
2160  Return Lua data stored in the current transaction. If no data are stored,
2161  it returns a nil value.
2162
2163  :param class_AppletHTTP applet: An :ref:`applethttp_class`
2164  :returns: the opaque data previsously stored, or nil if nothing is
2165     avalaible.
2166  :see: :js:func:`AppletHTTP.set_priv`
2167
2168.. js:function:: AppletHTTP.set_priv(applet, data)
2169
2170  Store any data in the current HAProxy transaction. This action replace the
2171  old stored data.
2172
2173  :param class_AppletHTTP applet: An :ref:`applethttp_class`
2174  :param opaque data: The data which is stored in the transaction.
2175  :see: :js:func:`AppletHTTP.get_priv`
2176
2177.. _applettcp_class:
2178
2179AppletTCP class
2180===============
2181
2182.. js:class:: AppletTCP
2183
2184  This class is used with applets that requires the 'tcp' mode. The tcp applet
2185  can be registered with the *core.register_service()* function. They are used
2186  for processing a tcp stream like a server in back of HAProxy.
2187
2188.. js:attribute:: AppletTCP.c
2189
2190  :returns: A :ref:`converters_class`
2191
2192  This attribute contains a Converters class object.
2193
2194.. js:attribute:: AppletTCP.sc
2195
2196  :returns: A :ref:`converters_class`
2197
2198  This attribute contains a Converters class object. The
2199  functions of this object returns always a string.
2200
2201.. js:attribute:: AppletTCP.f
2202
2203  :returns: A :ref:`fetches_class`
2204
2205  This attribute contains a Fetches class object.
2206
2207.. js:attribute:: AppletTCP.sf
2208
2209  :returns: A :ref:`fetches_class`
2210
2211  This attribute contains a Fetches class object.
2212
2213.. js:function:: AppletTCP.getline(applet)
2214
2215  This function returns a string containing one line from the stream. If the
2216  data returned doesn't contains a final '\\n' its assumed than its the last
2217  available data before the end of stream.
2218
2219  :param class_AppletTCP applet: An :ref:`applettcp_class`
2220  :returns: a string. The string can be empty if we reach the end of the stream.
2221
2222.. js:function:: AppletTCP.receive(applet, [size])
2223
2224  Reads data from the TCP stream, according to the specified read *size*. If the
2225  *size* is missing, the function tries to read all the content of the stream
2226  until the end.
2227
2228  :param class_AppletTCP applet: An :ref:`applettcp_class`
2229  :param integer size: the required read size.
2230  :returns: always return a string,the string can be empty is the connexion is
2231            closed.
2232
2233.. js:function:: AppletTCP.send(appletmsg)
2234
2235  Send the message on the stream.
2236
2237  :param class_AppletTCP applet: An :ref:`applettcp_class`
2238  :param string msg: the message to send.
2239
2240.. js:function:: AppletTCP.get_priv(applet)
2241
2242  Return Lua data stored in the current transaction. If no data are stored,
2243  it returns a nil value.
2244
2245  :param class_AppletTCP applet: An :ref:`applettcp_class`
2246  :returns: the opaque data previsously stored, or nil if nothing is
2247     avalaible.
2248  :see: :js:func:`AppletTCP.set_priv`
2249
2250.. js:function:: AppletTCP.set_priv(applet, data)
2251
2252  Store any data in the current HAProxy transaction. This action replace the
2253  old stored data.
2254
2255  :param class_AppletTCP applet: An :ref:`applettcp_class`
2256  :param opaque data: The data which is stored in the transaction.
2257  :see: :js:func:`AppletTCP.get_priv`
2258
2259External Lua libraries
2260======================
2261
2262A lot of useful lua libraries can be found here:
2263
2264* `https://lua-toolbox.com/ <https://lua-toolbox.com/>`_
2265
2266Redis acces:
2267
2268* `https://github.com/nrk/redis-lua <https://github.com/nrk/redis-lua>`_
2269
2270This is an example about the usage of the Redis library with HAProxy. Note that
2271each call of any function of this library can throw an error if the socket
2272connection fails.
2273
2274.. code-block:: lua
2275
2276    -- load the redis library
2277    local redis = require("redis");
2278
2279    function do_something(txn)
2280
2281       -- create and connect new tcp socket
2282       local tcp = core.tcp();
2283       tcp:settimeout(1);
2284       tcp:connect("127.0.0.1", 6379);
2285
2286       -- use the redis library with this new socket
2287       local client = redis.connect({socket=tcp});
2288       client:ping();
2289
2290    end
2291
2292OpenSSL:
2293
2294* `http://mkottman.github.io/luacrypto/index.html
2295  <http://mkottman.github.io/luacrypto/index.html>`_
2296
2297* `https://github.com/brunoos/luasec/wiki
2298  <https://github.com/brunoos/luasec/wiki>`_
2299
2300