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:: 59 It is possible that this function cannot found the required data in the 60 original HAProxy sample-fetches, in this case, it cannot return the 61 result. This case is not yet supported 62 636. The **converter context**. It is a Lua function that takes a string as input 64 and returns another string as output. These types of function are stateless, 65 it cannot access to any context. They don't execute any blocking function. 66 The call prototype is `function string fcn(string)`. This function can be 67 registered with the Lua function `core.register_converters()`. Each declared 68 converter is prefixed by the string "lua.". 69 70HAProxy Lua Hello world 71----------------------- 72 73HAProxy configuration file (`hello_world.conf`): 74 75:: 76 77 global 78 lua-load hello_world.lua 79 80 listen proxy 81 bind 127.0.0.1:10001 82 tcp-request inspect-delay 1s 83 tcp-request content use-service lua.hello_world 84 85HAProxy Lua file (`hello_world.lua`): 86 87.. code-block:: lua 88 89 core.register_service("hello_world", "tcp", function(applet) 90 applet:send("hello world\n") 91 end) 92 93How to start HAProxy for testing this configuration: 94 95:: 96 97 ./haproxy -f hello_world.conf 98 99On other terminal, you can test with telnet: 100 101:: 102 103 #:~ telnet 127.0.0.1 10001 104 hello world 105 106Core class 107========== 108 109.. js:class:: core 110 111 The "core" class contains all the HAProxy core functions. These function are 112 useful for the controlling the execution flow, registering hooks, manipulating 113 global maps or ACL, ... 114 115 "core" class is basically provided with HAProxy. No `require` line is 116 required to uses these function. 117 118 The "core" class is static, it is not possible to create a new object of this 119 type. 120 121.. js:attribute:: core.emerg 122 123 :returns: integer 124 125 This attribute is an integer, it contains the value of the loglevel "emergency" (0). 126 127.. js:attribute:: core.alert 128 129 :returns: integer 130 131 This attribute is an integer, it contains the value of the loglevel "alert" (1). 132 133.. js:attribute:: core.crit 134 135 :returns: integer 136 137 This attribute is an integer, it contains the value of the loglevel "critical" (2). 138 139.. js:attribute:: core.err 140 141 :returns: integer 142 143 This attribute is an integer, it contains the value of the loglevel "error" (3). 144 145.. js:attribute:: core.warning 146 147 :returns: integer 148 149 This attribute is an integer, it contains the value of the loglevel "warning" (4). 150 151.. js:attribute:: core.notice 152 153 :returns: integer 154 155 This attribute is an integer, it contains the value of the loglevel "notice" (5). 156 157.. js:attribute:: core.info 158 159 :returns: integer 160 161 This attribute is an integer, it contains the value of the loglevel "info" (6). 162 163.. js:attribute:: core.debug 164 165 :returns: integer 166 167 This attribute is an integer, it contains the value of the loglevel "debug" (7). 168 169.. js:attribute:: core.proxies 170 171 **context**: task, action, sample-fetch, converter 172 173 This attribute is a table of declared proxies (frontend and backends). Each 174 proxy give an access to his list of listeners and servers. The table is 175 indexed by proxy name, and each entry is of type :ref:`proxy_class`. 176 177 .. Warning:: 178 if you are declared frontend and backend with the same name, only one of 179 these are listed. 180 181 :see: :js:attr:`core.backends` 182 :see: :js:attr:`core.frontends` 183 184.. js:attribute:: core.backends 185 186 **context**: task, action, sample-fetch, converter 187 188 This attribute is a table of declared proxies with backend capability. Each 189 proxy give an access to his list of listeners and servers. The table is 190 indexed by the backend name, and each entry is of type :ref:`proxy_class`. 191 192 :see: :js:attr:`core.proxies` 193 :see: :js:attr:`core.frontends` 194 195.. js:attribute:: core.frontends 196 197 **context**: task, action, sample-fetch, converter 198 199 This attribute is a table of declared proxies with frontend capability. Each 200 proxy give an access to his list of listeners and servers. The table is 201 indexed by the frontend name, and each entry is of type :ref:`proxy_class`. 202 203 :see: :js:attr:`core.proxies` 204 :see: :js:attr:`core.backends` 205 206.. js:function:: core.log(loglevel, msg) 207 208 **context**: body, init, task, action, sample-fetch, converter 209 210 This function sends a log. The log is sent, according with the HAProxy 211 configuration file, on the default syslog server if it is configured and on 212 the stderr if it is allowed. 213 214 :param integer loglevel: Is the log level associated with the message. It is a 215 number between 0 and 7. 216 :param string msg: The log content. 217 :see: :js:attr:`core.emerg`, :js:attr:`core.alert`, :js:attr:`core.crit`, 218 :js:attr:`core.err`, :js:attr:`core.warning`, :js:attr:`core.notice`, 219 :js:attr:`core.info`, :js:attr:`core.debug` (log level definitions) 220 :see: :js:func:`core.Debug` 221 :see: :js:func:`core.Info` 222 :see: :js:func:`core.Warning` 223 :see: :js:func:`core.Alert` 224 225.. js:function:: core.Debug(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 Does the same job than: 233 234.. code-block:: lua 235 236 function Debug(msg) 237 core.log(core.debug, msg) 238 end 239.. 240 241.. js:function:: core.Info(msg) 242 243 **context**: body, init, task, action, sample-fetch, converter 244 245 :param string msg: The log content. 246 :see: :js:func:`core.log` 247 248.. code-block:: lua 249 250 function Info(msg) 251 core.log(core.info, msg) 252 end 253.. 254 255.. js:function:: core.Warning(msg) 256 257 **context**: body, init, task, action, sample-fetch, converter 258 259 :param string msg: The log content. 260 :see: :js:func:`core.log` 261 262.. code-block:: lua 263 264 function Warning(msg) 265 core.log(core.warning, msg) 266 end 267.. 268 269.. js:function:: core.Alert(msg) 270 271 **context**: body, init, task, action, sample-fetch, converter 272 273 :param string msg: The log content. 274 :see: :js:func:`core.log` 275 276.. code-block:: lua 277 278 function Alert(msg) 279 core.log(core.alert, msg) 280 end 281.. 282 283.. js:function:: core.add_acl(filename, key) 284 285 **context**: init, task, action, sample-fetch, converter 286 287 Add the ACL *key* in the ACLs list referenced by the file *filename*. 288 289 :param string filename: the filename that reference the ACL entries. 290 :param string key: the key which will be added. 291 292.. js:function:: core.del_acl(filename, key) 293 294 **context**: init, task, action, sample-fetch, converter 295 296 Delete the ACL entry referenced by the key *key* in the list of ACLs 297 referenced by *filename*. 298 299 :param string filename: the filename that reference the ACL entries. 300 :param string key: the key which will be deleted. 301 302.. js:function:: core.del_map(filename, key) 303 304 **context**: init, task, action, sample-fetch, converter 305 306 Delete the map entry indexed with the specified key in the list of maps 307 referenced by his filename. 308 309 :param string filename: the filename that reference the map entries. 310 :param string key: the key which will be deleted. 311 312.. js:function:: core.get_info() 313 314 **context**: body, init, task, action, sample-fetch, converter 315 316 Returns HAProxy core information. We can found information like the uptime, 317 the pid, memory pool usage, tasks number, ... 318 319 These information are also returned by the management socket via the command 320 "show info". See the management socket documentation for more information 321 about the content of these variables. 322 323 :returns: an array of values. 324 325.. js:function:: core.now() 326 327 **context**: body, init, task, action 328 329 This function returns the current time. The time returned is fixed by the 330 HAProxy core and assures than the hour will be monotonic and that the system 331 call 'gettimeofday' will not be called too. The time is refreshed between each 332 Lua execution or resume, so two consecutive call to the function "now" will 333 probably returns the same result. 334 335 :returns: a table which contains two entries "sec" and "usec". "sec" 336 contains the current at the epoch format, and "usec" contains the 337 current microseconds. 338 339.. js:function:: core.http_date(date) 340 341 **context**: body, init, task, action 342 343 This function take a string representing http date, and returns an integer 344 containing the corresponding date with a epoch format. A valid http date 345 me respect the format IMF, RFC850 or ASCTIME. 346 347 :param string date: a date http-date formatted 348 :returns: integer containing epoch date 349 :see: :js:func:`core.imf_date`. 350 :see: :js:func:`core.rfc850_date`. 351 :see: :js:func:`core.asctime_date`. 352 :see: https://tools.ietf.org/html/rfc7231#section-7.1.1.1 353 354.. js:function:: core.imf_date(date) 355 356 **context**: body, init, task, action 357 358 This function take a string representing IMF date, and returns an integer 359 containing the corresponding date with a epoch format. 360 361 :param string date: a date IMF formatted 362 :returns: integer containing epoch date 363 :see: https://tools.ietf.org/html/rfc7231#section-7.1.1.1 364 365 The IMF format is like this: 366 367.. code-block:: text 368 369 Sun, 06 Nov 1994 08:49:37 GMT 370.. 371 372.. js:function:: core.rfc850_date(date) 373 374 **context**: body, init, task, action 375 376 This function take a string representing RFC850 date, and returns an integer 377 containing the corresponding date with a epoch format. 378 379 :param string date: a date RFC859 formatted 380 :returns: integer containing epoch date 381 :see: https://tools.ietf.org/html/rfc7231#section-7.1.1.1 382 383 The RFC850 format is like this: 384 385.. code-block:: text 386 387 Sunday, 06-Nov-94 08:49:37 GMT 388.. 389 390.. js:function:: core.asctime_date(date) 391 392 **context**: body, init, task, action 393 394 This function take a string representing ASCTIME date, and returns an integer 395 containing the corresponding date with a epoch format. 396 397 :param string date: a date ASCTIME formatted 398 :returns: integer containing epoch date 399 :see: https://tools.ietf.org/html/rfc7231#section-7.1.1.1 400 401 The ASCTIME format is like this: 402 403.. code-block:: text 404 405 Sun Nov 6 08:49:37 1994 406.. 407 408.. js:function:: core.rfc850_date(date) 409 410 **context**: body, init, task, action 411 412 This function take a string representing http date, and returns an integer 413 containing the corresponding date with a epoch format. 414 415 :param string date: a date http-date formatted 416 417.. js:function:: core.asctime_date(date) 418 419 **context**: body, init, task, action 420 421 This function take a string representing http date, and returns an integer 422 containing the corresponding date with a epoch format. 423 424 :param string date: a date http-date formatted 425 426.. js:function:: core.msleep(milliseconds) 427 428 **context**: body, init, task, action 429 430 The `core.msleep()` stops the Lua execution between specified milliseconds. 431 432 :param integer milliseconds: the required milliseconds. 433 434.. js:attribute:: core.proxies 435 436 **context**: body, init, task, action, sample-fetch, converter 437 438 Proxies is a table containing the list of all proxies declared in the 439 configuration file. The table is indexed by the proxy name, and each entry 440 of the proxies table is an object of type :ref:`proxy_class`. 441 442 .. warning:: 443 if you have declared a frontend and backend with the same name, only one of 444 these are listed. 445 446.. js:function:: core.register_action(name, actions, func [, nb_args]) 447 448 **context**: body 449 450 Register a Lua function executed as action. All the registered action can be 451 used in HAProxy with the prefix "lua.". An action gets a TXN object class as 452 input. 453 454 :param string name: is the name of the converter. 455 :param table actions: is a table of string describing the HAProxy actions who 456 want to register to. The expected actions are 'tcp-req', 457 'tcp-res', 'http-req' or 'http-res'. 458 :param integer nb_args: is the expected number of argument for the action. 459 By default the value is 0. 460 :param function func: is the Lua function called to work as converter. 461 462 The prototype of the Lua function used as argument is: 463 464.. code-block:: lua 465 466 function(txn [, arg1 [, arg2]]) 467.. 468 469 * **txn** (:ref:`txn_class`): this is a TXN object used for manipulating the 470 current request or TCP stream. 471 472 * **argX**: this is argument provided through the HAProxy configuration file. 473 474 Here, an example of action registration. The action just send an 'Hello world' 475 in the logs. 476 477.. code-block:: lua 478 479 core.register_action("hello-world", { "tcp-req", "http-req" }, function(txn) 480 txn:Info("Hello world") 481 end) 482.. 483 484 This example code is used in HAproxy configuration like this: 485 486:: 487 488 frontend tcp_frt 489 mode tcp 490 tcp-request content lua.hello-world 491 492 frontend http_frt 493 mode http 494 http-request lua.hello-world 495.. 496 497 A second example using arguments 498 499.. code-block:: lua 500 501 function hello_world(txn, arg) 502 txn:Info("Hello world for " .. arg) 503 end 504 core.register_action("hello-world", { "tcp-req", "http-req" }, hello_world, 2) 505.. 506 507 This example code is used in HAproxy configuration like this: 508 509:: 510 511 frontend tcp_frt 512 mode tcp 513 tcp-request content lua.hello-world everybody 514.. 515.. js:function:: core.register_converters(name, func) 516 517 **context**: body 518 519 Register a Lua function executed as converter. All the registered converters 520 can be used in HAProxy with the prefix "lua.". An converter get a string as 521 input and return a string as output. The registered function can take up to 9 522 values as parameter. All the value are strings. 523 524 :param string name: is the name of the converter. 525 :param function func: is the Lua function called to work as converter. 526 527 The prototype of the Lua function used as argument is: 528 529.. code-block:: lua 530 531 function(str, [p1 [, p2 [, ... [, p5]]]]) 532.. 533 534 * **str** (*string*): this is the input value automatically converted in 535 string. 536 * **p1** .. **p5** (*string*): this is a list of string arguments declared in 537 the HAProxy configuration file. The number of arguments doesn't exceed 5. 538 The order and the nature of these is conventionally choose by the 539 developer. 540 541.. js:function:: core.register_fetches(name, func) 542 543 **context**: body 544 545 Register a Lua function executed as sample fetch. All the registered sample 546 fetch can be used in HAProxy with the prefix "lua.". A Lua sample fetch 547 return a string as output. The registered function can take up to 9 values as 548 parameter. All the value are strings. 549 550 :param string name: is the name of the converter. 551 :param function func: is the Lua function called to work as sample fetch. 552 553 The prototype of the Lua function used as argument is: 554 555.. code-block:: lua 556 557 string function(txn, [p1 [, p2 [, ... [, p5]]]]) 558.. 559 560 * **txn** (:ref:`txn_class`): this is the txn object associated with the current 561 request. 562 * **p1** .. **p5** (*string*): this is a list of string arguments declared in 563 the HAProxy configuration file. The number of arguments doesn't exceed 5. 564 The order and the nature of these is conventionally choose by the 565 developer. 566 * **Returns**: A string containing some data, or nil if the value cannot be 567 returned now. 568 569 lua example code: 570 571.. code-block:: lua 572 573 core.register_fetches("hello", function(txn) 574 return "hello" 575 end) 576.. 577 578 HAProxy example configuration: 579 580:: 581 582 frontend example 583 http-request redirect location /%[lua.hello] 584 585.. js:function:: core.register_service(name, mode, func) 586 587 **context**: body 588 589 Register a Lua function executed as a service. All the registered service can 590 be used in HAProxy with the prefix "lua.". A service gets an object class as 591 input according with the required mode. 592 593 :param string name: is the name of the converter. 594 :param string mode: is string describing the required mode. Only 'tcp' or 595 'http' are allowed. 596 :param function func: is the Lua function called to work as converter. 597 598 The prototype of the Lua function used as argument is: 599 600.. code-block:: lua 601 602 function(applet) 603.. 604 605 * **applet** *applet* will be a :ref:`applettcp_class` or a 606 :ref:`applethttp_class`. It depends the type of registered applet. An applet 607 registered with the 'http' value for the *mode* parameter will gets a 608 :ref:`applethttp_class`. If the *mode* value is 'tcp', the applet will gets 609 a :ref:`applettcp_class`. 610 611 .. warning:: 612 Applets of type 'http' cannot be called from 'tcp-*' rulesets. Only the 613 'http-*' rulesets are authorized, this means that is not possible to call 614 an HTTP applet from a proxy in tcp mode. Applets of type 'tcp' can be 615 called from anywhere. 616 617 Here, an example of service registration. The service just send an 'Hello world' 618 as an http response. 619 620.. code-block:: lua 621 622 core.register_service("hello-world", "http", function(applet) 623 local response = "Hello World !" 624 applet:set_status(200) 625 applet:add_header("content-length", string.len(response)) 626 applet:add_header("content-type", "text/plain") 627 applet:start_response() 628 applet:send(response) 629 end) 630.. 631 632 This example code is used in HAproxy configuration like this: 633 634:: 635 636 frontend example 637 http-request use-service lua.hello-world 638 639.. js:function:: core.register_init(func) 640 641 **context**: body 642 643 Register a function executed after the configuration parsing. This is useful 644 to check any parameters. 645 646 :param function func: is the Lua function called to work as initializer. 647 648 The prototype of the Lua function used as argument is: 649 650.. code-block:: lua 651 652 function() 653.. 654 655 It takes no input, and no output is expected. 656 657.. js:function:: core.register_task(func) 658 659 **context**: body, init, task, action, sample-fetch, converter 660 661 Register and start independent task. The task is started when the HAProxy 662 main scheduler starts. For example this type of tasks can be executed to 663 perform complex health checks. 664 665 :param function func: is the Lua function called to work as initializer. 666 667 The prototype of the Lua function used as argument is: 668 669.. code-block:: lua 670 671 function() 672.. 673 674 It takes no input, and no output is expected. 675 676.. js:function:: core.register_cli([path], usage, func) 677 678 **context**: body 679 680 Register and start independent task. The task is started when the HAProxy 681 main scheduler starts. For example this type of tasks can be executed to 682 perform complex health checks. 683 684 :param array path: is the sequence of word for which the cli execute the Lua 685 binding. 686 :param string usage: is the usage message displayed in the help. 687 :param function func: is the Lua function called to handle the CLI commands. 688 689 The prototype of the Lua function used as argument is: 690 691.. code-block:: lua 692 693 function(AppletTCP, [arg1, [arg2, [...]]]) 694.. 695 696 I/O are managed with the :ref:`applettcp_class` object. Args are given as 697 parameter. The args embed the registered path. If the path is declared like 698 this: 699 700.. code-block:: lua 701 702 core.register_cli({"show", "ssl", "stats"}, "Display SSL stats..", function(applet, arg1, arg2, arg3, arg4, arg5) 703 end) 704.. 705 706 And we execute this in the prompt: 707 708.. code-block:: text 709 710 > prompt 711 > show ssl stats all 712.. 713 714 Then, arg1, arg2 and arg3 will contains respectively "show", "ssl" and "stats". 715 arg4 will contain "all". arg5 contains nil. 716 717.. js:function:: core.set_nice(nice) 718 719 **context**: task, action, sample-fetch, converter 720 721 Change the nice of the current task or current session. 722 723 :param integer nice: the nice value, it must be between -1024 and 1024. 724 725.. js:function:: core.set_map(filename, key, value) 726 727 **context**: init, task, action, sample-fetch, converter 728 729 Set the value *value* associated to the key *key* in the map referenced by 730 *filename*. 731 732 :param string filename: the Map reference 733 :param string key: the key to set or replace 734 :param string value: the associated value 735 736.. js:function:: core.sleep(int seconds) 737 738 **context**: body, init, task, action 739 740 The `core.sleep()` functions stop the Lua execution between specified seconds. 741 742 :param integer seconds: the required seconds. 743 744.. js:function:: core.tcp() 745 746 **context**: init, task, action 747 748 This function returns a new object of a *socket* class. 749 750 :returns: A :ref:`socket_class` object. 751 752.. js:function:: core.concat() 753 754 **context**: body, init, task, action, sample-fetch, converter 755 756 This function returns a new concat object. 757 758 :returns: A :ref:`concat_class` object. 759 760.. js:function:: core.done(data) 761 762 **context**: body, init, task, action, sample-fetch, converter 763 764 :param any data: Return some data for the caller. It is useful with 765 sample-fetches and sample-converters. 766 767 Immediately stops the current Lua execution and returns to the caller which 768 may be a sample fetch, a converter or an action and returns the specified 769 value (ignored for actions). It is used when the LUA process finishes its 770 work and wants to give back the control to HAProxy without executing the 771 remaining code. It can be seen as a multi-level "return". 772 773.. js:function:: core.yield() 774 775 **context**: task, action, sample-fetch, converter 776 777 Give back the hand at the HAProxy scheduler. It is used when the LUA 778 processing consumes a lot of processing time. 779 780.. js:function:: core.parse_addr(address) 781 782 **context**: body, init, task, action, sample-fetch, converter 783 784 :param network: is a string describing an ipv4 or ipv6 address and optionally 785 its network length, like this: "127.0.0.1/8" or "aaaa::1234/32". 786 :returns: a userdata containing network or nil if an error occurs. 787 788 Parse ipv4 or ipv6 addresses and its facultative associated network. 789 790.. js:function:: core.match_addr(addr1, addr2) 791 792 **context**: body, init, task, action, sample-fetch, converter 793 794 :param addr1: is an address created with "core.parse_addr". 795 :param addr2: is an address created with "core.parse_addr". 796 :returns: boolean, true if the network of the addresses match, else returns 797 false. 798 799 Match two networks. For example "127.0.0.1/32" matches "127.0.0.0/8". The order 800 of network is not important. 801 802.. js:function:: core.tokenize(str, separators [, noblank]) 803 804 **context**: body, init, task, action, sample-fetch, converter 805 806 This function is useful for tokenizing an entry, or splitting some messages. 807 :param string str: The string which will be split. 808 :param string separators: A string containing a list of separators. 809 :param boolean noblank: Ignore empty entries. 810 :returns: an array of string. 811 812 For example: 813 814.. code-block:: lua 815 816 local array = core.tokenize("This function is useful, for tokenizing an entry.", "., ", true) 817 print_r(array) 818.. 819 820 Returns this array: 821 822.. code-block:: text 823 824 (table) table: 0x21c01e0 [ 825 1: (string) "This" 826 2: (string) "function" 827 3: (string) "is" 828 4: (string) "useful" 829 5: (string) "for" 830 6: (string) "tokenizing" 831 7: (string) "an" 832 8: (string) "entry" 833 ] 834.. 835 836.. _proxy_class: 837 838Proxy class 839============ 840 841.. js:class:: Proxy 842 843 This class provides a way for manipulating proxy and retrieving information 844 like statistics. 845 846.. js:attribute:: Proxy.name 847 848 Contain the name of the proxy. 849 850.. js:attribute:: Proxy.uuid 851 852 Contain the unique identifier of the proxy. 853 854.. js:attribute:: Proxy.servers 855 856 Contain a table with the attached servers. The table is indexed by server 857 name, and each server entry is an object of type :ref:`server_class`. 858 859.. js:attribute:: Proxy.stktable 860 861 Contains a stick table object attached to the proxy. 862 863.. js:attribute:: Proxy.listeners 864 865 Contain a table with the attached listeners. The table is indexed by listener 866 name, and each each listeners entry is an object of type 867 :ref:`listener_class`. 868 869.. js:function:: Proxy.pause(px) 870 871 Pause the proxy. See the management socket documentation for more information. 872 873 :param class_proxy px: A :ref:`proxy_class` which indicates the manipulated 874 proxy. 875 876.. js:function:: Proxy.resume(px) 877 878 Resume the proxy. See the management socket documentation for more 879 information. 880 881 :param class_proxy px: A :ref:`proxy_class` which indicates the manipulated 882 proxy. 883 884.. js:function:: Proxy.stop(px) 885 886 Stop the proxy. See the management socket documentation for more information. 887 888 :param class_proxy px: A :ref:`proxy_class` which indicates the manipulated 889 proxy. 890 891.. js:function:: Proxy.shut_bcksess(px) 892 893 Kill the session attached to a backup server. See the management socket 894 documentation for more information. 895 896 :param class_proxy px: A :ref:`proxy_class` which indicates the manipulated 897 proxy. 898 899.. js:function:: Proxy.get_cap(px) 900 901 Returns a string describing the capabilities of the proxy. 902 903 :param class_proxy px: A :ref:`proxy_class` which indicates the manipulated 904 proxy. 905 :returns: a string "frontend", "backend", "proxy" or "ruleset". 906 907.. js:function:: Proxy.get_mode(px) 908 909 Returns a string describing the mode of the current proxy. 910 911 :param class_proxy px: A :ref:`proxy_class` which indicates the manipulated 912 proxy. 913 :returns: a string "tcp", "http", "health" or "unknown" 914 915.. js:function:: Proxy.get_stats(px) 916 917 Returns a table containing the proxy statistics. The statistics returned are 918 not the same if the proxy is frontend or a backend. 919 920 :param class_proxy px: A :ref:`proxy_class` which indicates the manipulated 921 proxy. 922 :returns: a key/value table containing stats 923 924.. _server_class: 925 926Server class 927============ 928 929.. js:class:: Server 930 931 This class provides a way for manipulating servers and retrieving information. 932 933.. js:attribute:: Server.name 934 935 Contain the name of the server. 936 937.. js:attribute:: Server.puid 938 939 Contain the proxy unique identifier of the server. 940 941.. js:function:: Server.is_draining(sv) 942 943 Return true if the server is currently draining sticky connections. 944 945 :param class_server sv: A :ref:`server_class` which indicates the manipulated 946 server. 947 :returns: a boolean 948 949.. js:function:: Server.set_maxconn(sv, weight) 950 951 Dynamically change the maximum connections of the server. See the management 952 socket documentation for more information about the format of the string. 953 954 :param class_server sv: A :ref:`server_class` which indicates the manipulated 955 server. 956 :param string maxconn: A string describing the server maximum connections. 957 958.. js:function:: Server.get_maxconn(sv, weight) 959 960 This function returns an integer representing the server maximum connections. 961 962 :param class_server sv: A :ref:`server_class` which indicates the manipulated 963 server. 964 :returns: an integer. 965 966.. js:function:: Server.set_weight(sv, weight) 967 968 Dynamically change the weight of the server. See the management socket 969 documentation for more information about the format of the string. 970 971 :param class_server sv: A :ref:`server_class` which indicates the manipulated 972 server. 973 :param string weight: A string describing the server weight. 974 975.. js:function:: Server.get_weight(sv) 976 977 This function returns an integer representing the server weight. 978 979 :param class_server sv: A :ref:`server_class` which indicates the manipulated 980 server. 981 :returns: an integer. 982 983.. js:function:: Server.set_addr(sv, addr[, port]) 984 985 Dynamically change the address of the server. See the management socket 986 documentation for more information about the format of the string. 987 988 :param class_server sv: A :ref:`server_class` which indicates the manipulated 989 server. 990 :param string addr: A string describing the server address. 991 992.. js:function:: Server.get_addr(sv) 993 994 Returns a string describing the address of the server. 995 996 :param class_server sv: A :ref:`server_class` which indicates the manipulated 997 server. 998 :returns: A string 999 1000.. js:function:: Server.get_stats(sv) 1001 1002 Returns server statistics. 1003 1004 :param class_server sv: A :ref:`server_class` which indicates the manipulated 1005 server. 1006 :returns: a key/value table containing stats 1007 1008.. js:function:: Server.shut_sess(sv) 1009 1010 Shutdown all the sessions attached to the server. See the management socket 1011 documentation for more information about this function. 1012 1013 :param class_server sv: A :ref:`server_class` which indicates the manipulated 1014 server. 1015 1016.. js:function:: Server.set_drain(sv) 1017 1018 Drain sticky sessions. See the management socket documentation for more 1019 information about this function. 1020 1021 :param class_server sv: A :ref:`server_class` which indicates the manipulated 1022 server. 1023 1024.. js:function:: Server.set_maint(sv) 1025 1026 Set maintenance mode. See the management socket documentation for more 1027 information about this function. 1028 1029 :param class_server sv: A :ref:`server_class` which indicates the manipulated 1030 server. 1031 1032.. js:function:: Server.set_ready(sv) 1033 1034 Set normal mode. See the management socket documentation for more information 1035 about this function. 1036 1037 :param class_server sv: A :ref:`server_class` which indicates the manipulated 1038 server. 1039 1040.. js:function:: Server.check_enable(sv) 1041 1042 Enable health checks. See the management socket documentation for more 1043 information about this function. 1044 1045 :param class_server sv: A :ref:`server_class` which indicates the manipulated 1046 server. 1047 1048.. js:function:: Server.check_disable(sv) 1049 1050 Disable health checks. See the management socket documentation for more 1051 information about this function. 1052 1053 :param class_server sv: A :ref:`server_class` which indicates the manipulated 1054 server. 1055 1056.. js:function:: Server.check_force_up(sv) 1057 1058 Force health-check up. See the management socket documentation for more 1059 information about this function. 1060 1061 :param class_server sv: A :ref:`server_class` which indicates the manipulated 1062 server. 1063 1064.. js:function:: Server.check_force_nolb(sv) 1065 1066 Force health-check nolb mode. See the management socket documentation for more 1067 information about this function. 1068 1069 :param class_server sv: A :ref:`server_class` which indicates the manipulated 1070 server. 1071 1072.. js:function:: Server.check_force_down(sv) 1073 1074 Force health-check down. See the management socket documentation for more 1075 information about this function. 1076 1077 :param class_server sv: A :ref:`server_class` which indicates the manipulated 1078 server. 1079 1080.. js:function:: Server.agent_enable(sv) 1081 1082 Enable agent check. See the management socket documentation for more 1083 information about this function. 1084 1085 :param class_server sv: A :ref:`server_class` which indicates the manipulated 1086 server. 1087 1088.. js:function:: Server.agent_disable(sv) 1089 1090 Disable agent check. See the management socket documentation for more 1091 information about this function. 1092 1093 :param class_server sv: A :ref:`server_class` which indicates the manipulated 1094 server. 1095 1096.. js:function:: Server.agent_force_up(sv) 1097 1098 Force agent check up. See the management socket documentation for more 1099 information about this function. 1100 1101 :param class_server sv: A :ref:`server_class` which indicates the manipulated 1102 server. 1103 1104.. js:function:: Server.agent_force_down(sv) 1105 1106 Force agent check down. See the management socket documentation for more 1107 information about this function. 1108 1109 :param class_server sv: A :ref:`server_class` which indicates the manipulated 1110 server. 1111 1112.. _listener_class: 1113 1114Listener class 1115============== 1116 1117.. js:function:: Listener.get_stats(ls) 1118 1119 Returns server statistics. 1120 1121 :param class_listener ls: A :ref:`listener_class` which indicates the 1122 manipulated listener. 1123 :returns: a key/value table containing stats 1124 1125.. _concat_class: 1126 1127Concat class 1128============ 1129 1130.. js:class:: Concat 1131 1132 This class provides a fast way for string concatenation. The way using native 1133 Lua concatenation like the code below is slow for some reasons. 1134 1135.. code-block:: lua 1136 1137 str = "string1" 1138 str = str .. ", string2" 1139 str = str .. ", string3" 1140.. 1141 1142 For each concatenation, Lua: 1143 * allocate memory for the result, 1144 * catenate the two string copying the strings in the new memory block, 1145 * free the old memory block containing the string which is no longer used. 1146 This process does many memory move, allocation and free. In addition, the 1147 memory is not really freed, it is just mark mark as unused and wait for the 1148 garbage collector. 1149 1150 The Concat class provide an alternative way to concatenate strings. It uses 1151 the internal Lua mechanism (it does not allocate memory), but it doesn't copy 1152 the data more than once. 1153 1154 On my computer, the following loops spends 0.2s for the Concat method and 1155 18.5s for the pure Lua implementation. So, the Concat class is about 1000x 1156 faster than the embedded solution. 1157 1158.. code-block:: lua 1159 1160 for j = 1, 100 do 1161 c = core.concat() 1162 for i = 1, 20000 do 1163 c:add("#####") 1164 end 1165 end 1166.. 1167 1168.. code-block:: lua 1169 1170 for j = 1, 100 do 1171 c = "" 1172 for i = 1, 20000 do 1173 c = c .. "#####" 1174 end 1175 end 1176.. 1177 1178.. js:function:: Concat.add(concat, string) 1179 1180 This function adds a string to the current concatenated string. 1181 1182 :param class_concat concat: A :ref:`concat_class` which contains the currently 1183 built string. 1184 :param string string: A new string to concatenate to the current built 1185 string. 1186 1187.. js:function:: Concat.dump(concat) 1188 1189 This function returns the concatenated string. 1190 1191 :param class_concat concat: A :ref:`concat_class` which contains the currently 1192 built string. 1193 :returns: the concatenated string 1194 1195.. _fetches_class: 1196 1197Fetches class 1198============= 1199 1200.. js:class:: Fetches 1201 1202 This class contains a lot of internal HAProxy sample fetches. See the 1203 HAProxy "configuration.txt" documentation for more information about her 1204 usage. They are the chapters 7.3.2 to 7.3.6. 1205 1206 .. warning:: 1207 some sample fetches are not available in some context. These limitations 1208 are specified in this documentation when they're useful. 1209 1210 :see: :js:attr:`TXN.f` 1211 :see: :js:attr:`TXN.sf` 1212 1213 Fetches are useful for: 1214 1215 * get system time, 1216 * get environment variable, 1217 * get random numbers, 1218 * known backend status like the number of users in queue or the number of 1219 connections established, 1220 * client information like ip source or destination, 1221 * deal with stick tables, 1222 * Established SSL information, 1223 * HTTP information like headers or method. 1224 1225.. code-block:: lua 1226 1227 function action(txn) 1228 -- Get source IP 1229 local clientip = txn.f:src() 1230 end 1231.. 1232 1233.. _converters_class: 1234 1235Converters class 1236================ 1237 1238.. js:class:: Converters 1239 1240 This class contains a lot of internal HAProxy sample converters. See the 1241 HAProxy documentation "configuration.txt" for more information about her 1242 usage. Its the chapter 7.3.1. 1243 1244 :see: :js:attr:`TXN.c` 1245 :see: :js:attr:`TXN.sc` 1246 1247 Converters provides statefull transformation. They are useful for: 1248 1249 * converting input to base64, 1250 * applying hash on input string (djb2, crc32, sdbm, wt6), 1251 * format date, 1252 * json escape, 1253 * extracting preferred language comparing two lists, 1254 * turn to lower or upper chars, 1255 * deal with stick tables. 1256 1257.. _channel_class: 1258 1259Channel class 1260============= 1261 1262.. js:class:: Channel 1263 1264 HAProxy uses two buffers for the processing of the requests. The first one is 1265 used with the request data (from the client to the server) and the second is 1266 used for the response data (from the server to the client). 1267 1268 Each buffer contains two types of data. The first type is the incoming data 1269 waiting for a processing. The second part is the outgoing data already 1270 processed. Usually, the incoming data is processed, after it is tagged as 1271 outgoing data, and finally it is sent. The following functions provides tools 1272 for manipulating these data in a buffer. 1273 1274 The following diagram shows where the channel class function are applied. 1275 1276 **Warning**: It is not possible to read from the response in request action, 1277 and it is not possible to read for the request channel in response action. 1278 1279 **Warning**: It is forbidden to alter the Channels buffer from HTTP contexts. 1280 So only :js:func:`Channel.get_in_length`, :js:func:`Channel.get_out_length` 1281 and :js:func:`Channel.is_full` can be called from an HTTP conetext. 1282 1283.. image:: _static/channel.png 1284 1285.. js:function:: Channel.dup(channel) 1286 1287 This function returns a string that contain the entire buffer. The data is 1288 not remove from the buffer and can be reprocessed later. 1289 1290 If the buffer can't receive more data, a 'nil' value is returned. 1291 1292 :param class_channel channel: The manipulated Channel. 1293 :returns: a string containing all the available data or nil. 1294 1295.. js:function:: Channel.get(channel) 1296 1297 This function returns a string that contain the entire buffer. The data is 1298 consumed from the buffer. 1299 1300 If the buffer can't receive more data, a 'nil' value is returned. 1301 1302 :param class_channel channel: The manipulated Channel. 1303 :returns: a string containing all the available data or nil. 1304 1305.. js:function:: Channel.getline(channel) 1306 1307 This function returns a string that contain the first line of the buffer. The 1308 data is consumed. If the data returned doesn't contains a final '\n' its 1309 assumed than its the last available data in the buffer. 1310 1311 If the buffer can't receive more data, a 'nil' value is returned. 1312 1313 :param class_channel channel: The manipulated Channel. 1314 :returns: a string containing the available line or nil. 1315 1316.. js:function:: Channel.set(channel, string) 1317 1318 This function replace the content of the buffer by the string. The function 1319 returns the copied length, otherwise, it returns -1. 1320 1321 The data set with this function are not send. They wait for the end of 1322 HAProxy processing, so the buffer can be full. 1323 1324 :param class_channel channel: The manipulated Channel. 1325 :param string string: The data which will sent. 1326 :returns: an integer containing the amount of bytes copied or -1. 1327 1328.. js:function:: Channel.append(channel, string) 1329 1330 This function append the string argument to the content of the buffer. The 1331 function returns the copied length, otherwise, it returns -1. 1332 1333 The data set with this function are not send. They wait for the end of 1334 HAProxy processing, so the buffer can be full. 1335 1336 :param class_channel channel: The manipulated Channel. 1337 :param string string: The data which will sent. 1338 :returns: an integer containing the amount of bytes copied or -1. 1339 1340.. js:function:: Channel.send(channel, string) 1341 1342 This function required immediate send of the data. Unless if the connection 1343 is close, the buffer is regularly flushed and all the string can be sent. 1344 1345 :param class_channel channel: The manipulated Channel. 1346 :param string string: The data which will sent. 1347 :returns: an integer containing the amount of bytes copied or -1. 1348 1349.. js:function:: Channel.get_in_length(channel) 1350 1351 This function returns the length of the input part of the buffer. 1352 1353 :param class_channel channel: The manipulated Channel. 1354 :returns: an integer containing the amount of available bytes. 1355 1356.. js:function:: Channel.get_out_length(channel) 1357 1358 This function returns the length of the output part of the buffer. 1359 1360 :param class_channel channel: The manipulated Channel. 1361 :returns: an integer containing the amount of available bytes. 1362 1363.. js:function:: Channel.forward(channel, int) 1364 1365 This function transfer bytes from the input part of the buffer to the output 1366 part. 1367 1368 :param class_channel channel: The manipulated Channel. 1369 :param integer int: The amount of data which will be forwarded. 1370 1371.. js:function:: Channel.is_full(channel) 1372 1373 This function returns true if the buffer channel is full. 1374 1375 :returns: a boolean 1376 1377.. _http_class: 1378 1379HTTP class 1380========== 1381 1382.. js:class:: HTTP 1383 1384 This class contain all the HTTP manipulation functions. 1385 1386.. js:function:: HTTP.req_get_headers(http) 1387 1388 Returns a table containing all the request headers. 1389 1390 :param class_http http: The related http object. 1391 :returns: table of headers. 1392 :see: :js:func:`HTTP.res_get_headers` 1393 1394 This is the form of the returned table: 1395 1396.. code-block:: lua 1397 1398 HTTP:req_get_headers()['<header-name>'][<header-index>] = "<header-value>" 1399 1400 local hdr = HTTP:req_get_headers() 1401 hdr["host"][0] = "www.test.com" 1402 hdr["accept"][0] = "audio/basic q=1" 1403 hdr["accept"][1] = "audio/*, q=0.2" 1404 hdr["accept"][2] = "*/*, q=0.1" 1405.. 1406 1407.. js:function:: HTTP.res_get_headers(http) 1408 1409 Returns a table containing all the response headers. 1410 1411 :param class_http http: The related http object. 1412 :returns: table of headers. 1413 :see: :js:func:`HTTP.req_get_headers` 1414 1415 This is the form of the returned table: 1416 1417.. code-block:: lua 1418 1419 HTTP:res_get_headers()['<header-name>'][<header-index>] = "<header-value>" 1420 1421 local hdr = HTTP:req_get_headers() 1422 hdr["host"][0] = "www.test.com" 1423 hdr["accept"][0] = "audio/basic q=1" 1424 hdr["accept"][1] = "audio/*, q=0.2" 1425 hdr["accept"][2] = "*.*, q=0.1" 1426.. 1427 1428.. js:function:: HTTP.req_add_header(http, name, value) 1429 1430 Appends an HTTP header field in the request whose name is 1431 specified in "name" and whose value is defined in "value". 1432 1433 :param class_http http: The related http object. 1434 :param string name: The header name. 1435 :param string value: The header value. 1436 :see: :js:func:`HTTP.res_add_header` 1437 1438.. js:function:: HTTP.res_add_header(http, name, value) 1439 1440 Appends an HTTP header field in the response whose name is 1441 specified in "name" and whose value is defined in "value". 1442 1443 :param class_http http: The related http object. 1444 :param string name: The header name. 1445 :param string value: The header value. 1446 :see: :js:func:`HTTP.req_add_header` 1447 1448.. js:function:: HTTP.req_del_header(http, name) 1449 1450 Removes all HTTP header fields in the request whose name is 1451 specified in "name". 1452 1453 :param class_http http: The related http object. 1454 :param string name: The header name. 1455 :see: :js:func:`HTTP.res_del_header` 1456 1457.. js:function:: HTTP.res_del_header(http, name) 1458 1459 Removes all HTTP header fields in the response whose name is 1460 specified in "name". 1461 1462 :param class_http http: The related http object. 1463 :param string name: The header name. 1464 :see: :js:func:`HTTP.req_del_header` 1465 1466.. js:function:: HTTP.req_set_header(http, name, value) 1467 1468 This variable replace all occurrence of all header "name", by only 1469 one containing the "value". 1470 1471 :param class_http http: The related http object. 1472 :param string name: The header name. 1473 :param string value: The header value. 1474 :see: :js:func:`HTTP.res_set_header` 1475 1476 This function does the same work as the following code: 1477 1478.. code-block:: lua 1479 1480 function fcn(txn) 1481 TXN.http:req_del_header("header") 1482 TXN.http:req_add_header("header", "value") 1483 end 1484.. 1485 1486.. js:function:: HTTP.res_set_header(http, name, value) 1487 1488 This variable replace all occurrence of all header "name", by only 1489 one containing the "value". 1490 1491 :param class_http http: The related http object. 1492 :param string name: The header name. 1493 :param string value: The header value. 1494 :see: :js:func:`HTTP.req_rep_header()` 1495 1496.. js:function:: HTTP.req_rep_header(http, name, regex, replace) 1497 1498 Matches the regular expression in all occurrences of header field "name" 1499 according to "regex", and replaces them with the "replace" argument. The 1500 replacement value can contain back references like \1, \2, ... This 1501 function works with the request. 1502 1503 :param class_http http: The related http object. 1504 :param string name: The header name. 1505 :param string regex: The match regular expression. 1506 :param string replace: The replacement value. 1507 :see: :js:func:`HTTP.res_rep_header()` 1508 1509.. js:function:: HTTP.res_rep_header(http, name, regex, string) 1510 1511 Matches the regular expression in all occurrences of header field "name" 1512 according to "regex", and replaces them with the "replace" argument. The 1513 replacement value can contain back references like \1, \2, ... This 1514 function works with the request. 1515 1516 :param class_http http: The related http object. 1517 :param string name: The header name. 1518 :param string regex: The match regular expression. 1519 :param string replace: The replacement value. 1520 :see: :js:func:`HTTP.req_rep_header()` 1521 1522.. js:function:: HTTP.req_set_method(http, method) 1523 1524 Rewrites the request method with the parameter "method". 1525 1526 :param class_http http: The related http object. 1527 :param string method: The new method. 1528 1529.. js:function:: HTTP.req_set_path(http, path) 1530 1531 Rewrites the request path with the "path" parameter. 1532 1533 :param class_http http: The related http object. 1534 :param string path: The new path. 1535 1536.. js:function:: HTTP.req_set_query(http, query) 1537 1538 Rewrites the request's query string which appears after the first question 1539 mark ("?") with the parameter "query". 1540 1541 :param class_http http: The related http object. 1542 :param string query: The new query. 1543 1544.. js:function:: HTTP.req_set_uri(http, uri) 1545 1546 Rewrites the request URI with the parameter "uri". 1547 1548 :param class_http http: The related http object. 1549 :param string uri: The new uri. 1550 1551.. js:function:: HTTP.res_set_status(http, status [, reason]) 1552 1553 Rewrites the response status code with the parameter "code". 1554 1555 If no custom reason is provided, it will be generated from the status. 1556 1557 :param class_http http: The related http object. 1558 :param integer status: The new response status code. 1559 :param string reason: The new response reason (optional). 1560 1561.. _txn_class: 1562 1563TXN class 1564========= 1565 1566.. js:class:: TXN 1567 1568 The txn class contain all the functions relative to the http or tcp 1569 transaction (Note than a tcp stream is the same than a tcp transaction, but 1570 an HTTP transaction is not the same than a tcp stream). 1571 1572 The usage of this class permits to retrieve data from the requests, alter it 1573 and forward it. 1574 1575 All the functions provided by this class are available in the context 1576 **sample-fetches** and **actions**. 1577 1578.. js:attribute:: TXN.c 1579 1580 :returns: An :ref:`converters_class`. 1581 1582 This attribute contains a Converters class object. 1583 1584.. js:attribute:: TXN.sc 1585 1586 :returns: An :ref:`converters_class`. 1587 1588 This attribute contains a Converters class object. The functions of 1589 this object returns always a string. 1590 1591.. js:attribute:: TXN.f 1592 1593 :returns: An :ref:`fetches_class`. 1594 1595 This attribute contains a Fetches class object. 1596 1597.. js:attribute:: TXN.sf 1598 1599 :returns: An :ref:`fetches_class`. 1600 1601 This attribute contains a Fetches class object. The functions of 1602 this object returns always a string. 1603 1604.. js:attribute:: TXN.req 1605 1606 :returns: An :ref:`channel_class`. 1607 1608 This attribute contains a channel class object for the request buffer. 1609 1610.. js:attribute:: TXN.res 1611 1612 :returns: An :ref:`channel_class`. 1613 1614 This attribute contains a channel class object for the response buffer. 1615 1616.. js:attribute:: TXN.http 1617 1618 :returns: An :ref:`http_class`. 1619 1620 This attribute contains an HTTP class object. It is available only if the 1621 proxy has the "mode http" enabled. 1622 1623.. js:function:: TXN.log(TXN, loglevel, msg) 1624 1625 This function sends a log. The log is sent, according with the HAProxy 1626 configuration file, on the default syslog server if it is configured and on 1627 the stderr if it is allowed. 1628 1629 :param class_txn txn: The class txn object containing the data. 1630 :param integer loglevel: Is the log level associated with the message. It is a 1631 number between 0 and 7. 1632 :param string msg: The log content. 1633 :see: :js:attr:`core.emerg`, :js:attr:`core.alert`, :js:attr:`core.crit`, 1634 :js:attr:`core.err`, :js:attr:`core.warning`, :js:attr:`core.notice`, 1635 :js:attr:`core.info`, :js:attr:`core.debug` (log level definitions) 1636 :see: :js:func:`TXN.deflog` 1637 :see: :js:func:`TXN.Debug` 1638 :see: :js:func:`TXN.Info` 1639 :see: :js:func:`TXN.Warning` 1640 :see: :js:func:`TXN.Alert` 1641 1642.. js:function:: TXN.deflog(TXN, msg) 1643 1644 Sends a log line with the default loglevel for the proxy associated with the 1645 transaction. 1646 1647 :param class_txn txn: The class txn object containing the data. 1648 :param string msg: The log content. 1649 :see: :js:func:`TXN.log 1650 1651.. js:function:: TXN.Debug(txn, msg) 1652 1653 :param class_txn txn: The class txn object containing the data. 1654 :param string msg: The log content. 1655 :see: :js:func:`TXN.log` 1656 1657 Does the same job than: 1658 1659.. code-block:: lua 1660 1661 function Debug(txn, msg) 1662 TXN.log(txn, core.debug, msg) 1663 end 1664.. 1665 1666.. js:function:: TXN.Info(txn, msg) 1667 1668 :param class_txn txn: The class txn object containing the data. 1669 :param string msg: The log content. 1670 :see: :js:func:`TXN.log` 1671 1672.. code-block:: lua 1673 1674 function Debug(txn, msg) 1675 TXN.log(txn, core.info, msg) 1676 end 1677.. 1678 1679.. js:function:: TXN.Warning(txn, msg) 1680 1681 :param class_txn txn: The class txn object containing the data. 1682 :param string msg: The log content. 1683 :see: :js:func:`TXN.log` 1684 1685.. code-block:: lua 1686 1687 function Debug(txn, msg) 1688 TXN.log(txn, core.warning, msg) 1689 end 1690.. 1691 1692.. js:function:: TXN.Alert(txn, msg) 1693 1694 :param class_txn txn: The class txn object containing the data. 1695 :param string msg: The log content. 1696 :see: :js:func:`TXN.log` 1697 1698.. code-block:: lua 1699 1700 function Debug(txn, msg) 1701 TXN.log(txn, core.alert, msg) 1702 end 1703.. 1704 1705.. js:function:: TXN.get_priv(txn) 1706 1707 Return Lua data stored in the current transaction (with the `TXN.set_priv()`) 1708 function. If no data are stored, it returns a nil value. 1709 1710 :param class_txn txn: The class txn object containing the data. 1711 :returns: the opaque data previously stored, or nil if nothing is 1712 available. 1713 1714.. js:function:: TXN.set_priv(txn, data) 1715 1716 Store any data in the current HAProxy transaction. This action replace the 1717 old stored data. 1718 1719 :param class_txn txn: The class txn object containing the data. 1720 :param opaque data: The data which is stored in the transaction. 1721 1722.. js:function:: TXN.set_var(TXN, var, value[, ifexist]) 1723 1724 Converts a Lua type in a HAProxy type and store it in a variable <var>. 1725 1726 :param class_txn txn: The class txn object containing the data. 1727 :param string var: The variable name according with the HAProxy variable syntax. 1728 :param type value: The value associated to the variable. The type can be string or 1729 integer. 1730 :param boolean ifexist: If this parameter is set to a truthy value the variable 1731 will only be set if it was defined elsewhere (i.e. used 1732 within the configuration). It is highly recommended to 1733 always set this to true. 1734 1735.. js:function:: TXN.unset_var(TXN, var) 1736 1737 Unset the variable <var>. 1738 1739 :param class_txn txn: The class txn object containing the data. 1740 :param string var: The variable name according with the HAProxy variable syntax. 1741 1742.. js:function:: TXN.get_var(TXN, var) 1743 1744 Returns data stored in the variable <var> converter in Lua type. 1745 1746 :param class_txn txn: The class txn object containing the data. 1747 :param string var: The variable name according with the HAProxy variable syntax. 1748 1749.. js:function:: TXN.reply([reply]) 1750 1751 Return a new reply object 1752 1753 :param table reply: A table containing info to initialize the reply fields. 1754 :returns: A :ref:`reply_class` object. 1755 1756 The table used to initialized the reply object may contain following entries : 1757 1758 * status : The reply status code. the code 200 is used by default. 1759 * reason : The reply reason. The reason corresponding to the status code is 1760 used by default. 1761 * headers : An list of headers, indexed by header name. Empty by default. For 1762 a given name, multiple values are possible, stored in an ordered list. 1763 * body : The reply body, empty by default. 1764 1765.. code-block:: lua 1766 1767 local reply = txn:reply{ 1768 status = 400, 1769 reason = "Bad request", 1770 headers = { 1771 ["content-type"] = { "text/html" }, 1772 ["cache-control"] = {"no-cache", "no-store" } 1773 }, 1774 body = "<html><body><h1>invalid request<h1></body></html>" 1775 } 1776.. 1777 :see: :js:class:`Reply` 1778 1779.. js:function:: TXN.done(txn[, reply]) 1780 1781 This function terminates processing of the transaction and the associated 1782 session and optionally reply to the client for HTTP sessions. 1783 1784 :param class_txn txn: The class txn object containing the data. 1785 :param class_reply reply: The class reply object to return to the client. 1786 1787 This functions can be used when a critical error is detected or to terminate 1788 processing after some data have been returned to the client (eg: a redirect). 1789 To do so, a reply may be provided. This object is optional and may contain a 1790 status code, a reason, a header list and a body. All these fields are 1791 optional. When not provided, the default values are used. By default, with an 1792 empty reply object, an empty HTTP 200 response is returned to the client. If 1793 no reply object is provided, the transaction is terminated without any 1794 reply. If a reply object is provided, it must not exceed the buffer size once 1795 converted into the internal HTTP representing. Because for now there is no 1796 easy way to be sure it fits, it is probably better to keep it reasonably 1797 small. 1798 1799 The reply object may be fully created in lua or the class Reply may be used to 1800 create it. 1801 1802.. code-block:: lua 1803 1804 local reply = txn:reply() 1805 reply:set_status(400, "Bad request") 1806 reply:add_header("content-type", "text/html") 1807 reply:add_header("cache-control", "no-cache") 1808 reply:add_header("cache-control", "no-store") 1809 reply:set_body("<html><body><h1>invalid request<h1></body></html>") 1810 txn:done(reply) 1811.. 1812 1813.. code-block:: lua 1814 1815 txn:done{ 1816 status = 400, 1817 reason = "Bad request", 1818 headers = { 1819 ["content-type"] = { "text/html" }, 1820 ["cache-control"] = { "no-cache", "no-store" }, 1821 }, 1822 body = "<html><body><h1>invalid request<h1></body></html>" 1823 } 1824.. 1825 1826 .. warning:: 1827 It not make sense to call this function from sample-fetches. In this case 1828 the behaviour of this one is the same than core.done(): it quit the Lua 1829 execution. The transaction is really aborted only from an action registered 1830 function. 1831 1832 :see: :js:func:`TXN.reply`, :js:class:`Reply` 1833 1834.. js:function:: TXN.set_loglevel(txn, loglevel) 1835 1836 Is used to change the log level of the current request. The "loglevel" must 1837 be an integer between 0 and 7. 1838 1839 :param class_txn txn: The class txn object containing the data. 1840 :param integer loglevel: The required log level. This variable can be one of 1841 :see: :js:attr:`core.emerg`, :js:attr:`core.alert`, :js:attr:`core.crit`, 1842 :js:attr:`core.err`, :js:attr:`core.warning`, :js:attr:`core.notice`, 1843 :js:attr:`core.info`, :js:attr:`core.debug` (log level definitions) 1844 1845.. js:function:: TXN.set_tos(txn, tos) 1846 1847 Is used to set the TOS or DSCP field value of packets sent to the client to 1848 the value passed in "tos" on platforms which support this. 1849 1850 :param class_txn txn: The class txn object containing the data. 1851 :param integer tos: The new TOS os DSCP. 1852 1853.. js:function:: TXN.set_mark(txn, mark) 1854 1855 Is used to set the Netfilter MARK on all packets sent to the client to the 1856 value passed in "mark" on platforms which support it. 1857 1858 :param class_txn txn: The class txn object containing the data. 1859 :param integer mark: The mark value. 1860 1861.. js:function:: TXN.set_priority_class(txn, prio) 1862 1863 This function adjusts the priority class of the transaction. The value should 1864 be within the range -2047..2047. Values outside this range will be 1865 truncated. 1866 1867 See the HAProxy configuration.txt file keyword "http-request" action 1868 "set-priority-class" for details. 1869 1870.. js:function:: TXN.set_priority_offset(txn, prio) 1871 1872 This function adjusts the priority offset of the transaction. The value 1873 should be within the range -524287..524287. Values outside this range will be 1874 truncated. 1875 1876 See the HAProxy configuration.txt file keyword "http-request" action 1877 "set-priority-offset" for details. 1878 1879.. _reply_class: 1880 1881Reply class 1882============ 1883 1884.. js:class:: Reply 1885 1886 **context**: action 1887 1888 This class represents an HTTP response message. It provides some methods to 1889 enrich it. Once converted into the internal HTTP representation, the response 1890 message must not exceed the buffer size. Because for now there is no 1891 easy way to be sure it fits, it is probably better to keep it reasonably 1892 small. 1893 1894 See tune.bufsize in the configuration manual for dettails. 1895 1896.. code-block:: lua 1897 1898 local reply = txn:reply({status = 400}) -- default HTTP 400 reason-phase used 1899 reply:add_header("content-type", "text/html") 1900 reply:add_header("cache-control", "no-cache") 1901 reply:add_header("cache-control", "no-store") 1902 reply:set_body("<html><body><h1>invalid request<h1></body></html>") 1903.. 1904 1905 :see: :js:func:`TXN.reply` 1906 1907.. js:attribute:: Reply.status 1908 1909 The reply status code. By default, the status code is set to 200. 1910 1911 :returns: integer 1912 1913.. js:attribute:: Reply.reason 1914 1915 The reason string describing the status code. 1916 1917 :returns: string 1918 1919.. js:attribute:: Reply.headers 1920 1921 A table indexing all reply headers by name. To each name is associated an 1922 ordered list of values. 1923 1924 :returns: Lua table 1925 1926.. code-block:: lua 1927 1928 { 1929 ["content-type"] = { "text/html" }, 1930 ["cache-control"] = {"no-cache", "no-store" }, 1931 x_header_name = { "value1", "value2", ... } 1932 ... 1933 } 1934.. 1935 1936.. js:attribute:: Reply.body 1937 1938 The reply payload. 1939 1940 :returns: string 1941 1942.. js:function:: Reply.set_status(REPLY, status[, reason]) 1943 1944 Set the reply status code and optionally the reason-phrase. If the reason is 1945 not provided, the default reason corresponding to the status code is used. 1946 1947 :param class_reply reply: The related Reply object. 1948 :param integer status: The reply status code. 1949 :param string reason: The reply status reason (optional). 1950 1951.. js:function:: Reply.add_header(REPLY, name, value) 1952 1953 Add a header to the reply object. If the header does not already exist, a new 1954 entry is created with its name as index and a one-element list containing its 1955 value as value. Otherwise, the header value is appended to the ordered list of 1956 values associated to the header name. 1957 1958 :param class_reply reply: The related Reply object. 1959 :param string name: The header field name. 1960 :param string value: The header field value. 1961 1962.. js:function:: Reply.del_header(REPLY, name) 1963 1964 Remove all occurrences of a header name from the reply object. 1965 1966 :param class_reply reply: The related Reply object. 1967 :param string name: The header field name. 1968 1969.. js:function:: Reply.set_body(REPLY, body) 1970 1971 Set the reply payload. 1972 1973 :param class_reply reply: The related Reply object. 1974 :param string body: The reply payload. 1975 1976.. _socket_class: 1977 1978Socket class 1979============ 1980 1981.. js:class:: Socket 1982 1983 This class must be compatible with the Lua Socket class. Only the 'client' 1984 functions are available. See the Lua Socket documentation: 1985 1986 `http://w3.impa.br/~diego/software/luasocket/tcp.html 1987 <http://w3.impa.br/~diego/software/luasocket/tcp.html>`_ 1988 1989.. js:function:: Socket.close(socket) 1990 1991 Closes a TCP object. The internal socket used by the object is closed and the 1992 local address to which the object was bound is made available to other 1993 applications. No further operations (except for further calls to the close 1994 method) are allowed on a closed Socket. 1995 1996 :param class_socket socket: Is the manipulated Socket. 1997 1998 Note: It is important to close all used sockets once they are not needed, 1999 since, in many systems, each socket uses a file descriptor, which are limited 2000 system resources. Garbage-collected objects are automatically closed before 2001 destruction, though. 2002 2003.. js:function:: Socket.connect(socket, address[, port]) 2004 2005 Attempts to connect a socket object to a remote host. 2006 2007 2008 In case of error, the method returns nil followed by a string describing the 2009 error. In case of success, the method returns 1. 2010 2011 :param class_socket socket: Is the manipulated Socket. 2012 :param string address: can be an IP address or a host name. See below for more 2013 information. 2014 :param integer port: must be an integer number in the range [1..64K]. 2015 :returns: 1 or nil. 2016 2017 An address field extension permits to use the connect() function to connect to 2018 other stream than TCP. The syntax containing a simpleipv4 or ipv6 address is 2019 the basically expected format. This format requires the port. 2020 2021 Other format accepted are a socket path like "/socket/path", it permits to 2022 connect to a socket. Abstract namespaces are supported with the prefix 2023 "abns@", and finally a file descriptor can be passed with the prefix "fd@". 2024 The prefix "ipv4@", "ipv6@" and "unix@" are also supported. The port can be 2025 passed int the string. The syntax "127.0.0.1:1234" is valid. In this case, the 2026 parameter *port* must not be set. 2027 2028.. js:function:: Socket.connect_ssl(socket, address, port) 2029 2030 Same behavior than the function socket:connect, but uses SSL. 2031 2032 :param class_socket socket: Is the manipulated Socket. 2033 :returns: 1 or nil. 2034 2035.. js:function:: Socket.getpeername(socket) 2036 2037 Returns information about the remote side of a connected client object. 2038 2039 Returns a string with the IP address of the peer, followed by the port number 2040 that peer is using for the connection. In case of error, the method returns 2041 nil. 2042 2043 :param class_socket socket: Is the manipulated Socket. 2044 :returns: a string containing the server information. 2045 2046.. js:function:: Socket.getsockname(socket) 2047 2048 Returns the local address information associated to the object. 2049 2050 The method returns a string with local IP address and a number with the port. 2051 In case of error, the method returns nil. 2052 2053 :param class_socket socket: Is the manipulated Socket. 2054 :returns: a string containing the client information. 2055 2056.. js:function:: Socket.receive(socket, [pattern [, prefix]]) 2057 2058 Reads data from a client object, according to the specified read pattern. 2059 Patterns follow the Lua file I/O format, and the difference in performance 2060 between all patterns is negligible. 2061 2062 :param class_socket socket: Is the manipulated Socket. 2063 :param string|integer pattern: Describe what is required (see below). 2064 :param string prefix: A string which will be prefix the returned data. 2065 :returns: a string containing the required data or nil. 2066 2067 Pattern can be any of the following: 2068 2069 * **`*a`**: reads from the socket until the connection is closed. No 2070 end-of-line translation is performed; 2071 2072 * **`*l`**: reads a line of text from the Socket. The line is terminated by a 2073 LF character (ASCII 10), optionally preceded by a CR character 2074 (ASCII 13). The CR and LF characters are not included in the 2075 returned line. In fact, all CR characters are ignored by the 2076 pattern. This is the default pattern. 2077 2078 * **number**: causes the method to read a specified number of bytes from the 2079 Socket. Prefix is an optional string to be concatenated to the 2080 beginning of any received data before return. 2081 2082 * **empty**: If the pattern is left empty, the default option is `*l`. 2083 2084 If successful, the method returns the received pattern. In case of error, the 2085 method returns nil followed by an error message which can be the string 2086 'closed' in case the connection was closed before the transmission was 2087 completed or the string 'timeout' in case there was a timeout during the 2088 operation. Also, after the error message, the function returns the partial 2089 result of the transmission. 2090 2091 Important note: This function was changed severely. It used to support 2092 multiple patterns (but I have never seen this feature used) and now it 2093 doesn't anymore. Partial results used to be returned in the same way as 2094 successful results. This last feature violated the idea that all functions 2095 should return nil on error. Thus it was changed too. 2096 2097.. js:function:: Socket.send(socket, data [, start [, end ]]) 2098 2099 Sends data through client object. 2100 2101 :param class_socket socket: Is the manipulated Socket. 2102 :param string data: The data that will be sent. 2103 :param integer start: The start position in the buffer of the data which will 2104 be sent. 2105 :param integer end: The end position in the buffer of the data which will 2106 be sent. 2107 :returns: see below. 2108 2109 Data is the string to be sent. The optional arguments i and j work exactly 2110 like the standard string.sub Lua function to allow the selection of a 2111 substring to be sent. 2112 2113 If successful, the method returns the index of the last byte within [start, 2114 end] that has been sent. Notice that, if start is 1 or absent, this is 2115 effectively the total number of bytes sent. In case of error, the method 2116 returns nil, followed by an error message, followed by the index of the last 2117 byte within [start, end] that has been sent. You might want to try again from 2118 the byte following that. The error message can be 'closed' in case the 2119 connection was closed before the transmission was completed or the string 2120 'timeout' in case there was a timeout during the operation. 2121 2122 Note: Output is not buffered. For small strings, it is always better to 2123 concatenate them in Lua (with the '..' operator) and send the result in one 2124 call instead of calling the method several times. 2125 2126.. js:function:: Socket.setoption(socket, option [, value]) 2127 2128 Just implemented for compatibility, this cal does nothing. 2129 2130.. js:function:: Socket.settimeout(socket, value [, mode]) 2131 2132 Changes the timeout values for the object. All I/O operations are blocking. 2133 That is, any call to the methods send, receive, and accept will block 2134 indefinitely, until the operation completes. The settimeout method defines a 2135 limit on the amount of time the I/O methods can block. When a timeout time 2136 has elapsed, the affected methods give up and fail with an error code. 2137 2138 The amount of time to wait is specified as the value parameter, in seconds. 2139 2140 The timeout modes are not implemented, the only settable timeout is the 2141 inactivity time waiting for complete the internal buffer send or waiting for 2142 receive data. 2143 2144 :param class_socket socket: Is the manipulated Socket. 2145 :param float value: The timeout value. Use floating point to specify 2146 milliseconds. 2147 2148.. _regex_class: 2149 2150Regex class 2151=========== 2152 2153.. js:class:: Regex 2154 2155 This class allows the usage of HAProxy regexes because classic lua doesn't 2156 provides regexes. This class inherits the HAProxy compilation options, so the 2157 regexes can be libc regex, pcre regex or pcre JIT regex. 2158 2159 The expression matching number is limited to 20 per regex. The only available 2160 option is case sensitive. 2161 2162 Because regexes compilation is a heavy process, it is better to define all 2163 your regexes in the **body context** and use it during the runtime. 2164 2165.. code-block:: lua 2166 2167 -- Create the regex 2168 st, regex = Regex.new("needle (..) (...)", true); 2169 2170 -- Check compilation errors 2171 if st == false then 2172 print "error: " .. regex 2173 end 2174 2175 -- Match the regexes 2176 print(regex:exec("Looking for a needle in the haystack")) -- true 2177 print(regex:exec("Lokking for a cat in the haystack")) -- false 2178 2179 -- Extract words 2180 st, list = regex:match("Looking for a needle in the haystack") 2181 print(st) -- true 2182 print(list[1]) -- needle in the 2183 print(list[2]) -- in 2184 print(list[3]) -- the 2185 2186.. js:function:: Regex.new(regex, case_sensitive) 2187 2188 Create and compile a regex. 2189 2190 :param string regex: The regular expression according with the libc or pcre 2191 standard 2192 :param boolean case_sensitive: Match is case sensitive or not. 2193 :returns: boolean status and :ref:`regex_class` or string containing fail reason. 2194 2195.. js:function:: Regex.exec(regex, str) 2196 2197 Execute the regex. 2198 2199 :param class_regex regex: A :ref:`regex_class` object. 2200 :param string str: The input string will be compared with the compiled regex. 2201 :returns: a boolean status according with the match result. 2202 2203.. js:function:: Regex.match(regex, str) 2204 2205 Execute the regex and return matched expressions. 2206 2207 :param class_map map: A :ref:`regex_class` object. 2208 :param string str: The input string will be compared with the compiled regex. 2209 :returns: a boolean status according with the match result, and 2210 a table containing all the string matched in order of declaration. 2211 2212.. _map_class: 2213 2214Map class 2215========= 2216 2217.. js:class:: Map 2218 2219 This class permits to do some lookup in HAProxy maps. The declared maps can 2220 be modified during the runtime through the HAProxy management socket. 2221 2222.. code-block:: lua 2223 2224 default = "usa" 2225 2226 -- Create and load map 2227 geo = Map.new("geo.map", Map._ip); 2228 2229 -- Create new fetch that returns the user country 2230 core.register_fetches("country", function(txn) 2231 local src; 2232 local loc; 2233 2234 src = txn.f:fhdr("x-forwarded-for"); 2235 if (src == nil) then 2236 src = txn.f:src() 2237 if (src == nil) then 2238 return default; 2239 end 2240 end 2241 2242 -- Perform lookup 2243 loc = geo:lookup(src); 2244 2245 if (loc == nil) then 2246 return default; 2247 end 2248 2249 return loc; 2250 end); 2251 2252.. js:attribute:: Map._int 2253 2254 See the HAProxy configuration.txt file, chapter "Using ACLs and fetching 2255 samples" and subchapter "ACL basics" to understand this pattern matching 2256 method. 2257 2258 Note that :js:attr:`Map.int` is also available for compatibility. 2259 2260.. js:attribute:: Map._ip 2261 2262 See the HAProxy configuration.txt file, chapter "Using ACLs and fetching 2263 samples" and subchapter "ACL basics" to understand this pattern matching 2264 method. 2265 2266 Note that :js:attr:`Map.ip` is also available for compatibility. 2267 2268.. js:attribute:: Map._str 2269 2270 See the HAProxy configuration.txt file, chapter "Using ACLs and fetching 2271 samples" and subchapter "ACL basics" to understand this pattern matching 2272 method. 2273 2274 Note that :js:attr:`Map.str` is also available for compatibility. 2275 2276.. js:attribute:: Map._beg 2277 2278 See the HAProxy configuration.txt file, chapter "Using ACLs and fetching 2279 samples" and subchapter "ACL basics" to understand this pattern matching 2280 method. 2281 2282 Note that :js:attr:`Map.beg` is also available for compatibility. 2283 2284.. js:attribute:: Map._sub 2285 2286 See the HAProxy configuration.txt file, chapter "Using ACLs and fetching 2287 samples" and subchapter "ACL basics" to understand this pattern matching 2288 method. 2289 2290 Note that :js:attr:`Map.sub` is also available for compatibility. 2291 2292.. js:attribute:: Map._dir 2293 2294 See the HAProxy configuration.txt file, chapter "Using ACLs and fetching 2295 samples" and subchapter "ACL basics" to understand this pattern matching 2296 method. 2297 2298 Note that :js:attr:`Map.dir` is also available for compatibility. 2299 2300.. js:attribute:: Map._dom 2301 2302 See the HAProxy configuration.txt file, chapter "Using ACLs and fetching 2303 samples" and subchapter "ACL basics" to understand this pattern matching 2304 method. 2305 2306 Note that :js:attr:`Map.dom` is also available for compatibility. 2307 2308.. js:attribute:: Map._end 2309 2310 See the HAProxy configuration.txt file, chapter "Using ACLs and fetching 2311 samples" and subchapter "ACL basics" to understand this pattern matching 2312 method. 2313 2314.. js:attribute:: Map._reg 2315 2316 See the HAProxy configuration.txt file, chapter "Using ACLs and fetching 2317 samples" and subchapter "ACL basics" to understand this pattern matching 2318 method. 2319 2320 Note that :js:attr:`Map.reg` is also available for compatibility. 2321 2322 2323.. js:function:: Map.new(file, method) 2324 2325 Creates and load a map. 2326 2327 :param string file: Is the file containing the map. 2328 :param integer method: Is the map pattern matching method. See the attributes 2329 of the Map class. 2330 :returns: a class Map object. 2331 :see: The Map attributes: :js:attr:`Map._int`, :js:attr:`Map._ip`, 2332 :js:attr:`Map._str`, :js:attr:`Map._beg`, :js:attr:`Map._sub`, 2333 :js:attr:`Map._dir`, :js:attr:`Map._dom`, :js:attr:`Map._end` and 2334 :js:attr:`Map._reg`. 2335 2336.. js:function:: Map.lookup(map, str) 2337 2338 Perform a lookup in a map. 2339 2340 :param class_map map: Is the class Map object. 2341 :param string str: Is the string used as key. 2342 :returns: a string containing the result or nil if no match. 2343 2344.. js:function:: Map.slookup(map, str) 2345 2346 Perform a lookup in a map. 2347 2348 :param class_map map: Is the class Map object. 2349 :param string str: Is the string used as key. 2350 :returns: a string containing the result or empty string if no match. 2351 2352.. _applethttp_class: 2353 2354AppletHTTP class 2355================ 2356 2357.. js:class:: AppletHTTP 2358 2359 This class is used with applets that requires the 'http' mode. The http applet 2360 can be registered with the *core.register_service()* function. They are used 2361 for processing an http request like a server in back of HAProxy. 2362 2363 This is an hello world sample code: 2364 2365.. code-block:: lua 2366 2367 core.register_service("hello-world", "http", function(applet) 2368 local response = "Hello World !" 2369 applet:set_status(200) 2370 applet:add_header("content-length", string.len(response)) 2371 applet:add_header("content-type", "text/plain") 2372 applet:start_response() 2373 applet:send(response) 2374 end) 2375 2376.. js:attribute:: AppletHTTP.c 2377 2378 :returns: A :ref:`converters_class` 2379 2380 This attribute contains a Converters class object. 2381 2382.. js:attribute:: AppletHTTP.sc 2383 2384 :returns: A :ref:`converters_class` 2385 2386 This attribute contains a Converters class object. The 2387 functions of this object returns always a string. 2388 2389.. js:attribute:: AppletHTTP.f 2390 2391 :returns: A :ref:`fetches_class` 2392 2393 This attribute contains a Fetches class object. Note that the 2394 applet execution place cannot access to a valid HAProxy core HTTP 2395 transaction, so some sample fetches related to the HTTP dependent 2396 values (hdr, path, ...) are not available. 2397 2398.. js:attribute:: AppletHTTP.sf 2399 2400 :returns: A :ref:`fetches_class` 2401 2402 This attribute contains a Fetches class object. The functions of 2403 this object returns always a string. Note that the applet 2404 execution place cannot access to a valid HAProxy core HTTP 2405 transaction, so some sample fetches related to the HTTP dependent 2406 values (hdr, path, ...) are not available. 2407 2408.. js:attribute:: AppletHTTP.method 2409 2410 :returns: string 2411 2412 The attribute method returns a string containing the HTTP 2413 method. 2414 2415.. js:attribute:: AppletHTTP.version 2416 2417 :returns: string 2418 2419 The attribute version, returns a string containing the HTTP 2420 request version. 2421 2422.. js:attribute:: AppletHTTP.path 2423 2424 :returns: string 2425 2426 The attribute path returns a string containing the HTTP 2427 request path. 2428 2429.. js:attribute:: AppletHTTP.qs 2430 2431 :returns: string 2432 2433 The attribute qs returns a string containing the HTTP 2434 request query string. 2435 2436.. js:attribute:: AppletHTTP.length 2437 2438 :returns: integer 2439 2440 The attribute length returns an integer containing the HTTP 2441 body length. 2442 2443.. js:attribute:: AppletHTTP.headers 2444 2445 :returns: table 2446 2447 The attribute headers returns a table containing the HTTP 2448 headers. The header names are always in lower case. As the header name can be 2449 encountered more than once in each request, the value is indexed with 0 as 2450 first index value. The table have this form: 2451 2452.. code-block:: lua 2453 2454 AppletHTTP.headers['<header-name>'][<header-index>] = "<header-value>" 2455 2456 AppletHTTP.headers["host"][0] = "www.test.com" 2457 AppletHTTP.headers["accept"][0] = "audio/basic q=1" 2458 AppletHTTP.headers["accept"][1] = "audio/*, q=0.2" 2459 AppletHTTP.headers["accept"][2] = "*/*, q=0.1" 2460.. 2461 2462.. js:function:: AppletHTTP.set_status(applet, code [, reason]) 2463 2464 This function sets the HTTP status code for the response. The allowed code are 2465 from 100 to 599. 2466 2467 :param class_AppletHTTP applet: An :ref:`applethttp_class` 2468 :param integer code: the status code returned to the client. 2469 :param string reason: the status reason returned to the client (optional). 2470 2471.. js:function:: AppletHTTP.add_header(applet, name, value) 2472 2473 This function add an header in the response. Duplicated headers are not 2474 collapsed. The special header *content-length* is used to determinate the 2475 response length. If it not exists, a *transfer-encoding: chunked* is set, and 2476 all the write from the function *AppletHTTP:send()* become a chunk. 2477 2478 :param class_AppletHTTP applet: An :ref:`applethttp_class` 2479 :param string name: the header name 2480 :param string value: the header value 2481 2482.. js:function:: AppletHTTP.start_response(applet) 2483 2484 This function indicates to the HTTP engine that it can process and send the 2485 response headers. After this called we cannot add headers to the response; We 2486 cannot use the *AppletHTTP:send()* function if the 2487 *AppletHTTP:start_response()* is not called. 2488 2489 :param class_AppletHTTP applet: An :ref:`applethttp_class` 2490 2491.. js:function:: AppletHTTP.getline(applet) 2492 2493 This function returns a string containing one line from the http body. If the 2494 data returned doesn't contains a final '\\n' its assumed than its the last 2495 available data before the end of stream. 2496 2497 :param class_AppletHTTP applet: An :ref:`applethttp_class` 2498 :returns: a string. The string can be empty if we reach the end of the stream. 2499 2500.. js:function:: AppletHTTP.receive(applet, [size]) 2501 2502 Reads data from the HTTP body, according to the specified read *size*. If the 2503 *size* is missing, the function tries to read all the content of the stream 2504 until the end. If the *size* is bigger than the http body, it returns the 2505 amount of data available. 2506 2507 :param class_AppletHTTP applet: An :ref:`applethttp_class` 2508 :param integer size: the required read size. 2509 :returns: always return a string,the string can be empty is the connection is 2510 closed. 2511 2512.. js:function:: AppletHTTP.send(applet, msg) 2513 2514 Send the message *msg* on the http request body. 2515 2516 :param class_AppletHTTP applet: An :ref:`applethttp_class` 2517 :param string msg: the message to send. 2518 2519.. js:function:: AppletHTTP.get_priv(applet) 2520 2521 Return Lua data stored in the current transaction. If no data are stored, 2522 it returns a nil value. 2523 2524 :param class_AppletHTTP applet: An :ref:`applethttp_class` 2525 :returns: the opaque data previously stored, or nil if nothing is 2526 available. 2527 :see: :js:func:`AppletHTTP.set_priv` 2528 2529.. js:function:: AppletHTTP.set_priv(applet, data) 2530 2531 Store any data in the current HAProxy transaction. This action replace the 2532 old stored data. 2533 2534 :param class_AppletHTTP applet: An :ref:`applethttp_class` 2535 :param opaque data: The data which is stored in the transaction. 2536 :see: :js:func:`AppletHTTP.get_priv` 2537 2538.. js:function:: AppletHTTP.set_var(applet, var, value[, ifexist]) 2539 2540 Converts a Lua type in a HAProxy type and store it in a variable <var>. 2541 2542 :param class_AppletHTTP applet: An :ref:`applethttp_class` 2543 :param string var: The variable name according with the HAProxy variable syntax. 2544 :param type value: The value associated to the variable. The type ca be string or 2545 integer. 2546 :param boolean ifexist: If this parameter is set to a truthy value the variable 2547 will only be set if it was defined elsewhere (i.e. used 2548 within the configuration). It is highly recommended to 2549 always set this to true. 2550 :see: :js:func:`AppletHTTP.unset_var` 2551 :see: :js:func:`AppletHTTP.get_var` 2552 2553.. js:function:: AppletHTTP.unset_var(applet, var) 2554 2555 Unset the variable <var>. 2556 2557 :param class_AppletHTTP applet: An :ref:`applethttp_class` 2558 :param string var: The variable name according with the HAProxy variable syntax. 2559 :see: :js:func:`AppletHTTP.set_var` 2560 :see: :js:func:`AppletHTTP.get_var` 2561 2562.. js:function:: AppletHTTP.get_var(applet, var) 2563 2564 Returns data stored in the variable <var> converter in Lua type. 2565 2566 :param class_AppletHTTP applet: An :ref:`applethttp_class` 2567 :param string var: The variable name according with the HAProxy variable syntax. 2568 :see: :js:func:`AppletHTTP.set_var` 2569 :see: :js:func:`AppletHTTP.unset_var` 2570 2571.. _applettcp_class: 2572 2573AppletTCP class 2574=============== 2575 2576.. js:class:: AppletTCP 2577 2578 This class is used with applets that requires the 'tcp' mode. The tcp applet 2579 can be registered with the *core.register_service()* function. They are used 2580 for processing a tcp stream like a server in back of HAProxy. 2581 2582.. js:attribute:: AppletTCP.c 2583 2584 :returns: A :ref:`converters_class` 2585 2586 This attribute contains a Converters class object. 2587 2588.. js:attribute:: AppletTCP.sc 2589 2590 :returns: A :ref:`converters_class` 2591 2592 This attribute contains a Converters class object. The 2593 functions of this object returns always a string. 2594 2595.. js:attribute:: AppletTCP.f 2596 2597 :returns: A :ref:`fetches_class` 2598 2599 This attribute contains a Fetches class object. 2600 2601.. js:attribute:: AppletTCP.sf 2602 2603 :returns: A :ref:`fetches_class` 2604 2605 This attribute contains a Fetches class object. 2606 2607.. js:function:: AppletTCP.getline(applet) 2608 2609 This function returns a string containing one line from the stream. If the 2610 data returned doesn't contains a final '\\n' its assumed than its the last 2611 available data before the end of stream. 2612 2613 :param class_AppletTCP applet: An :ref:`applettcp_class` 2614 :returns: a string. The string can be empty if we reach the end of the stream. 2615 2616.. js:function:: AppletTCP.receive(applet, [size]) 2617 2618 Reads data from the TCP stream, according to the specified read *size*. If the 2619 *size* is missing, the function tries to read all the content of the stream 2620 until the end. 2621 2622 :param class_AppletTCP applet: An :ref:`applettcp_class` 2623 :param integer size: the required read size. 2624 :returns: always return a string,the string can be empty is the connection is 2625 closed. 2626 2627.. js:function:: AppletTCP.send(appletmsg) 2628 2629 Send the message on the stream. 2630 2631 :param class_AppletTCP applet: An :ref:`applettcp_class` 2632 :param string msg: the message to send. 2633 2634.. js:function:: AppletTCP.get_priv(applet) 2635 2636 Return Lua data stored in the current transaction. If no data are stored, 2637 it returns a nil value. 2638 2639 :param class_AppletTCP applet: An :ref:`applettcp_class` 2640 :returns: the opaque data previously stored, or nil if nothing is 2641 available. 2642 :see: :js:func:`AppletTCP.set_priv` 2643 2644.. js:function:: AppletTCP.set_priv(applet, data) 2645 2646 Store any data in the current HAProxy transaction. This action replace the 2647 old stored data. 2648 2649 :param class_AppletTCP applet: An :ref:`applettcp_class` 2650 :param opaque data: The data which is stored in the transaction. 2651 :see: :js:func:`AppletTCP.get_priv` 2652 2653.. js:function:: AppletTCP.set_var(applet, var, value[, ifexist]) 2654 2655 Converts a Lua type in a HAProxy type and stores it in a variable <var>. 2656 2657 :param class_AppletTCP applet: An :ref:`applettcp_class` 2658 :param string var: The variable name according with the HAProxy variable syntax. 2659 :param type value: The value associated to the variable. The type can be string or 2660 integer. 2661 :param boolean ifexist: If this parameter is set to a truthy value the variable 2662 will only be set if it was defined elsewhere (i.e. used 2663 within the configuration). It is highly recommended to 2664 always set this to true. 2665 :see: :js:func:`AppletTCP.unset_var` 2666 :see: :js:func:`AppletTCP.get_var` 2667 2668.. js:function:: AppletTCP.unset_var(applet, var) 2669 2670 Unsets the variable <var>. 2671 2672 :param class_AppletTCP applet: An :ref:`applettcp_class` 2673 :param string var: The variable name according with the HAProxy variable syntax. 2674 :see: :js:func:`AppletTCP.unset_var` 2675 :see: :js:func:`AppletTCP.set_var` 2676 2677.. js:function:: AppletTCP.get_var(applet, var) 2678 2679 Returns data stored in the variable <var> converter in Lua type. 2680 2681 :param class_AppletTCP applet: An :ref:`applettcp_class` 2682 :param string var: The variable name according with the HAProxy variable syntax. 2683 :see: :js:func:`AppletTCP.unset_var` 2684 :see: :js:func:`AppletTCP.set_var` 2685 2686StickTable class 2687================ 2688 2689.. js:class:: StickTable 2690 2691 **context**: task, action, sample-fetch 2692 2693 This class can be used to access the HAProxy stick tables from Lua. 2694 2695.. js:function:: StickTable.info() 2696 2697 Returns stick table attributes as a Lua table. See HAProxy documentation for 2698 "stick-table" for canonical info, or check out example bellow. 2699 2700 :returns: Lua table 2701 2702 Assume our table has IPv4 key and gpc0 and conn_rate "columns": 2703 2704.. code-block:: lua 2705 2706 { 2707 expire=<int>, # Value in ms 2708 size=<int>, # Maximum table size 2709 used=<int>, # Actual number of entries in table 2710 data={ # Data columns, with types as key, and periods as values 2711 (-1 if type is not rate counter) 2712 conn_rate=<int>, 2713 gpc0=-1 2714 }, 2715 length=<int>, # max string length for string table keys, key length 2716 # otherwise 2717 nopurge=<boolean>, # purge oldest entries when table is full 2718 type="ip" # can be "ip", "ipv6", "integer", "string", "binary" 2719 } 2720 2721.. js:function:: StickTable.lookup(key) 2722 2723 Returns stick table entry for given <key> 2724 2725 :param string key: Stick table key (IP addresses and strings are supported) 2726 :returns: Lua table 2727 2728.. js:function:: StickTable.dump([filter]) 2729 2730 Returns all entries in stick table. An optional filter can be used 2731 to extract entries with specific data values. Filter is a table with valid 2732 comparison operators as keys followed by data type name and value pairs. 2733 Check out the HAProxy docs for "show table" for more details. For the 2734 reference, the supported operators are: 2735 "eq", "ne", "le", "lt", "ge", "gt" 2736 2737 For large tables, execution of this function can take a long time (for 2738 HAProxy standards). That's also true when filter is used, so take care and 2739 measure the impact. 2740 2741 :param table filter: Stick table filter 2742 :returns: Stick table entries (table) 2743 2744 See below for example filter, which contains 4 entries (or comparisons). 2745 (Maximum number of filter entries is 4, defined in the source code) 2746 2747.. code-block:: lua 2748 2749 local filter = { 2750 {"gpc0", "gt", 30}, {"gpc1", "gt", 20}}, {"conn_rate", "le", 10} 2751 } 2752 2753.. _action_class: 2754 2755Action class 2756============= 2757 2758.. js:class:: Act 2759 2760 **context**: action 2761 2762 This class contains all return codes an action may return. It is the lua 2763 equivalent to HAProxy "ACT_RET_*" code. 2764 2765.. code-block:: lua 2766 2767 core.register_action("deny", { "http-req" }, function (txn) 2768 return act.DENY 2769 end) 2770.. 2771.. js:attribute:: act.CONTINUE 2772 2773 This attribute is an integer (0). It instructs HAProxy to continue the current 2774 ruleset processing on the message. It is the default return code for a lua 2775 action. 2776 2777 :returns: integer 2778 2779.. js:attribute:: act.STOP 2780 2781 This attribute is an integer (1). It instructs HAProxy to stop the current 2782 ruleset processing on the message. 2783 2784.. js:attribute:: act.YIELD 2785 2786 This attribute is an integer (2). It instructs HAProxy to temporarily pause 2787 the message processing. It will be resumed later on the same rule. The 2788 corresponding lua script is re-executed for the start. 2789 2790.. js:attribute:: act.ERROR 2791 2792 This attribute is an integer (3). It triggers an internal errors The message 2793 processing is stopped and the transaction is terminated. For HTTP streams, an 2794 HTTP 500 error is returned to the client. 2795 2796 :returns: integer 2797 2798.. js:attribute:: act.DONE 2799 2800 This attribute is an integer (4). It instructs HAProxy to stop the message 2801 processing. 2802 2803 :returns: integer 2804 2805.. js:attribute:: act.DENY 2806 2807 This attribute is an integer (5). It denies the current message. The message 2808 processing is stopped and the transaction is terminated. For HTTP streams, an 2809 HTTP 403 error is returned to the client if the deny is returned during the 2810 request analysis. During the response analysis, an HTTP 502 error is returned 2811 and the server response is discarded. 2812 2813 :returns: integer 2814 2815.. js:attribute:: act.ABORT 2816 2817 This attribute is an integer (6). It aborts the current message. The message 2818 processing is stopped and the transaction is terminated. For HTTP streams, 2819 HAproxy assumes a response was already sent to the client. From the Lua 2820 actions point of view, when this code is used, the transaction is terminated 2821 with no reply. 2822 2823 :returns: integer 2824 2825.. js:attribute:: act.INVALID 2826 2827 This attribute is an integer (7). It triggers an internal errors. The message 2828 processing is stopped and the transaction is terminated. For HTTP streams, an 2829 HTTP 400 error is returned to the client if the error is returned during the 2830 request analysis. During the response analysis, an HTTP 502 error is returned 2831 and the server response is discarded. 2832 2833 :returns: integer 2834 2835.. js:function:: act:wake_time(milliseconds) 2836 2837 **context**: action 2838 2839 Set the script pause timeout to the specified time, defined in 2840 milliseconds. 2841 2842 :param integer milliseconds: the required milliseconds. 2843 2844 This function may be used when a lua action returns `act.YIELD`, to force its 2845 wake-up at most after the specified number of milliseconds. 2846 2847External Lua libraries 2848====================== 2849 2850A lot of useful lua libraries can be found here: 2851 2852* `https://lua-toolbox.com/ <https://lua-toolbox.com/>`_ 2853 2854Redis client library: 2855 2856* `https://github.com/nrk/redis-lua <https://github.com/nrk/redis-lua>`_ 2857 2858This is an example about the usage of the Redis library with HAProxy. Note that 2859each call of any function of this library can throw an error if the socket 2860connection fails. 2861 2862.. code-block:: lua 2863 2864 -- load the redis library 2865 local redis = require("redis"); 2866 2867 function do_something(txn) 2868 2869 -- create and connect new tcp socket 2870 local tcp = core.tcp(); 2871 tcp:settimeout(1); 2872 tcp:connect("127.0.0.1", 6379); 2873 2874 -- use the redis library with this new socket 2875 local client = redis.connect({socket=tcp}); 2876 client:ping(); 2877 2878 end 2879 2880OpenSSL: 2881 2882* `http://mkottman.github.io/luacrypto/index.html 2883 <http://mkottman.github.io/luacrypto/index.html>`_ 2884 2885* `https://github.com/brunoos/luasec/wiki 2886 <https://github.com/brunoos/luasec/wiki>`_ 2887