blob: 666aaf225d438830624e1eb2ccf038b7b5d6d6a3 [file] [log] [blame]
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01001#include <lauxlib.h>
2#include <lua.h>
3#include <lualib.h>
4
Thierry FOURNIER380d0932015-01-23 14:27:52 +01005#include <ebpttree.h>
6
7#include <common/cfgparse.h>
8
9#include <types/hlua.h>
10#include <types/proxy.h>
11
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010012#include <proto/task.h>
13
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010014/* Lua uses longjmp to perform yield or throwing errors. This
15 * macro is used only for identifying the function that can
16 * not return because a longjmp is executed.
17 * __LJMP marks a prototype of hlua file that can use longjmp.
18 * WILL_LJMP() marks an lua function that will use longjmp.
19 * MAY_LJMP() marks an lua function that may use longjmp.
20 */
21#define __LJMP
22#define WILL_LJMP(func) func
23#define MAY_LJMP(func) func
24
Thierry FOURNIER380d0932015-01-23 14:27:52 +010025/* The main Lua execution context. */
26struct hlua gL;
27
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010028/* This is the memory pool containing all the signal structs. These
29 * struct are used to store each requiered signal between two tasks.
30 */
31struct pool_head *pool2_hlua_com;
32
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010033/* List head of the function called at the initialisation time. */
34struct list hlua_init_functions = LIST_HEAD_INIT(hlua_init_functions);
35
Thierry FOURNIER380d0932015-01-23 14:27:52 +010036/* Store the fast lua context for coroutines. This tree uses the
37 * Lua stack pointer value as indexed entry, and store the associated
38 * hlua context.
39 */
40struct eb_root hlua_ctx = EB_ROOT_UNIQUE;
41
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010042/* The following variables contains the reference of the different
43 * Lua classes. These references are useful for identify metadata
44 * associated with an object.
45 */
46static int class_core_ref;
47
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +010048/* Used to check an Lua function type in the stack. It creates and
49 * returns a reference of the function. This function throws an
50 * error if the rgument is not a "function".
51 */
52__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
53{
54 if (!lua_isfunction(L, argno)) {
55 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, -1));
56 WILL_LJMP(luaL_argerror(L, argno, msg));
57 }
58 lua_pushvalue(L, argno);
59 return luaL_ref(L, LUA_REGISTRYINDEX);
60}
61
62/* The three following functions are useful for adding entries
63 * in a table. These functions takes a string and respectively an
64 * integer, a string or a function and add it to the table in the
65 * top of the stack.
66 *
67 * These functions throws an error if no more stack size is
68 * available.
69 */
70__LJMP static inline void hlua_class_const_int(lua_State *L, const char *name,
71 unsigned int value)
72{
73 if (!lua_checkstack(L, 2))
74 WILL_LJMP(luaL_error(L, "full stack"));
75 lua_pushstring(L, name);
76 lua_pushunsigned(L, value);
77 lua_settable(L, -3);
78}
79__LJMP static inline void hlua_class_const_str(lua_State *L, const char *name,
80 const char *value)
81{
82 if (!lua_checkstack(L, 2))
83 WILL_LJMP(luaL_error(L, "full stack"));
84 lua_pushstring(L, name);
85 lua_pushstring(L, value);
86 lua_settable(L, -3);
87}
88__LJMP static inline void hlua_class_function(lua_State *L, const char *name,
89 int (*function)(lua_State *L))
90{
91 if (!lua_checkstack(L, 2))
92 WILL_LJMP(luaL_error(L, "full stack"));
93 lua_pushstring(L, name);
94 lua_pushcclosure(L, function, 0);
95 lua_settable(L, -3);
96}
97
98/* This function check the number of arguments available in the
99 * stack. If the number of arguments available is not the same
100 * then <nb> an error is throwed.
101 */
102__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
103{
104 if (lua_gettop(L) == nb)
105 return;
106 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
107}
108
109/* Return true if the data in stack[<ud>] is an object of
110 * type <class_ref>.
111 */
112static int hlua_udataistype(lua_State *L, int ud, int class_ref)
113{
114 void *p = lua_touserdata(L, ud);
115 if (!p)
116 return 0;
117
118 if (!lua_getmetatable(L, ud))
119 return 0;
120
121 lua_rawgeti(L, LUA_REGISTRYINDEX, class_ref);
122 if (!lua_rawequal(L, -1, -2)) {
123 lua_pop(L, 2);
124 return 0;
125 }
126
127 lua_pop(L, 2);
128 return 1;
129}
130
131/* Return an object of the expected type, or throws an error. */
132__LJMP static void *hlua_checkudata(lua_State *L, int ud, int class_ref)
133{
134 if (!hlua_udataistype(L, ud, class_ref))
135 WILL_LJMP(luaL_argerror(L, 1, NULL));
136 return lua_touserdata(L, ud);
137}
138
139/* This fucntion push an error string prefixed by the file name
140 * and the line number where the error is encountered.
141 */
142static int hlua_pusherror(lua_State *L, const char *fmt, ...)
143{
144 va_list argp;
145 va_start(argp, fmt);
146 luaL_where(L, 1);
147 lua_pushvfstring(L, fmt, argp);
148 va_end(argp);
149 lua_concat(L, 2);
150 return 1;
151}
152
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100153/* This function register a new signal. "lua" is the current lua
154 * execution context. It contains a pointer to the associated task.
155 * "link" is a list head attached to an other task that must be wake
156 * the lua task if an event occurs. This is useful with external
157 * events like TCP I/O or sleep functions. This funcion allocate
158 * memory for the signal.
159 */
160static int hlua_com_new(struct hlua *lua, struct list *link)
161{
162 struct hlua_com *com = pool_alloc2(pool2_hlua_com);
163 if (!com)
164 return 0;
165 LIST_ADDQ(&lua->com, &com->purge_me);
166 LIST_ADDQ(link, &com->wake_me);
167 com->task = lua->task;
168 return 1;
169}
170
171/* This function purge all the pending signals when the LUA execution
172 * is finished. This prevent than a coprocess try to wake a deleted
173 * task. This function remove the memory associated to the signal.
174 */
175static void hlua_com_purge(struct hlua *lua)
176{
177 struct hlua_com *com, *back;
178
179 /* Delete all pending communication signals. */
180 list_for_each_entry_safe(com, back, &lua->com, purge_me) {
181 LIST_DEL(&com->purge_me);
182 LIST_DEL(&com->wake_me);
183 pool_free2(pool2_hlua_com, com);
184 }
185}
186
187/* This function sends signals. It wakes all the tasks attached
188 * to a list head, and remove the signal, and free the used
189 * memory.
190 */
191static void hlua_com_wake(struct list *wake)
192{
193 struct hlua_com *com, *back;
194
195 /* Wake task and delete all pending communication signals. */
196 list_for_each_entry_safe(com, back, wake, wake_me) {
197 LIST_DEL(&com->purge_me);
198 LIST_DEL(&com->wake_me);
199 task_wakeup(com->task, TASK_WOKEN_MSG);
200 pool_free2(pool2_hlua_com, com);
201 }
202}
203
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100204/*
205 * The following functions are used to make correspondance between the the
206 * executed lua pointer and the "struct hlua *" that contain the context.
207 * They run with the tree head "hlua_ctx", they just perform lookup in the
208 * tree.
209 *
210 * - hlua_gethlua : return the hlua context associated with an lua_State.
211 * - hlua_delhlua : remove the association between hlua context and lua_state.
212 * - hlua_sethlua : create the association between hlua context and lua_state.
213 */
214static inline struct hlua *hlua_gethlua(lua_State *L)
215{
216 struct ebpt_node *node;
217
218 node = ebpt_lookup(&hlua_ctx, L);
219 if (!node)
220 return NULL;
221 return ebpt_entry(node, struct hlua, node);
222}
223static inline void hlua_delhlua(struct hlua *hlua)
224{
225 if (hlua->node.key)
226 ebpt_delete(&hlua->node);
227}
228static inline void hlua_sethlua(struct hlua *hlua)
229{
230 hlua->node.key = hlua->T;
231 ebpt_insert(&hlua_ctx, &hlua->node);
232}
233
234/* This function initialises the Lua environment stored in the session.
235 * It must be called at the start of the session. This function creates
236 * an LUA coroutine. It can not be use to crete the main LUA context.
237 */
238int hlua_ctx_init(struct hlua *lua, struct task *task)
239{
240 lua->Mref = LUA_REFNIL;
241 lua->state = HLUA_STOP;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100242 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100243 lua->T = lua_newthread(gL.T);
244 if (!lua->T) {
245 lua->Tref = LUA_REFNIL;
246 return 0;
247 }
248 hlua_sethlua(lua);
249 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
250 lua->task = task;
251 return 1;
252}
253
254/* Used to destroy the Lua coroutine when the attached session or task
255 * is destroyed. The destroy also the memory context. The struct "lua"
256 * is not freed.
257 */
258void hlua_ctx_destroy(struct hlua *lua)
259{
260 /* Remove context. */
261 hlua_delhlua(lua);
262
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100263 /* Purge all the pending signals. */
264 hlua_com_purge(lua);
265
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100266 /* The thread is garbage collected by Lua. */
267 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
268 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
269}
270
271/* This function is used to restore the Lua context when a coroutine
272 * fails. This function copy the common memory between old coroutine
273 * and the new coroutine. The old coroutine is destroyed, and its
274 * replaced by the new coroutine.
275 * If the flag "keep_msg" is set, the last entry of the old is assumed
276 * as string error message and it is copied in the new stack.
277 */
278static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
279{
280 lua_State *T;
281 int new_ref;
282
283 /* Renew the main LUA stack doesn't have sense. */
284 if (lua == &gL)
285 return 0;
286
287 /* Remove context. */
288 hlua_delhlua(lua);
289
290 /* New Lua coroutine. */
291 T = lua_newthread(gL.T);
292 if (!T)
293 return 0;
294
295 /* Copy last error message. */
296 if (keep_msg)
297 lua_xmove(lua->T, T, 1);
298
299 /* Copy data between the coroutines. */
300 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
301 lua_xmove(lua->T, T, 1);
302 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
303
304 /* Destroy old data. */
305 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
306
307 /* The thread is garbage collected by Lua. */
308 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
309
310 /* Fill the struct with the new coroutine values. */
311 lua->Mref = new_ref;
312 lua->T = T;
313 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
314
315 /* Set context. */
316 hlua_sethlua(lua);
317
318 return 1;
319}
320
321/* This function start or resumes the Lua stack execution. If the flag
322 * "yield_allowed" if no set and the LUA stack execution returns a yield
323 * The function return an error.
324 *
325 * The function can returns 4 values:
326 * - HLUA_E_OK : The execution is terminated without any errors.
327 * - HLUA_E_AGAIN : The execution must continue at the next associated
328 * task wakeup.
329 * - HLUA_E_ERRMSG : An error has occured, an error message is set in
330 * the top of the stack.
331 * - HLUA_E_ERR : An error has occured without error message.
332 *
333 * If an error occured, the stack is renewed and it is ready to run new
334 * LUA code.
335 */
336static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
337{
338 int ret;
339 const char *msg;
340
341 lua->state = HLUA_RUN;
342
343 /* Call the function. */
344 ret = lua_resume(lua->T, gL.T, lua->nargs);
345 switch (ret) {
346
347 case LUA_OK:
348 ret = HLUA_E_OK;
349 break;
350
351 case LUA_YIELD:
352 if (!yield_allowed) {
353 lua_settop(lua->T, 0); /* Empty the stack. */
354 if (!lua_checkstack(lua->T, 1)) {
355 ret = HLUA_E_ERR;
356 break;
357 }
358 lua_pushfstring(lua->T, "yield not allowed");
359 ret = HLUA_E_ERRMSG;
360 break;
361 }
362 ret = HLUA_E_AGAIN;
363 break;
364
365 case LUA_ERRRUN:
366 if (!lua_checkstack(lua->T, 1)) {
367 ret = HLUA_E_ERR;
368 break;
369 }
370 msg = lua_tostring(lua->T, -1);
371 lua_settop(lua->T, 0); /* Empty the stack. */
372 lua_pop(lua->T, 1);
373 if (msg)
374 lua_pushfstring(lua->T, "runtime error: %s", msg);
375 else
376 lua_pushfstring(lua->T, "unknown runtime error");
377 ret = HLUA_E_ERRMSG;
378 break;
379
380 case LUA_ERRMEM:
381 lua_settop(lua->T, 0); /* Empty the stack. */
382 if (!lua_checkstack(lua->T, 1)) {
383 ret = HLUA_E_ERR;
384 break;
385 }
386 lua_pushfstring(lua->T, "out of memory error");
387 ret = HLUA_E_ERRMSG;
388 break;
389
390 case LUA_ERRERR:
391 if (!lua_checkstack(lua->T, 1)) {
392 ret = HLUA_E_ERR;
393 break;
394 }
395 msg = lua_tostring(lua->T, -1);
396 lua_settop(lua->T, 0); /* Empty the stack. */
397 lua_pop(lua->T, 1);
398 if (msg)
399 lua_pushfstring(lua->T, "message handler error: %s", msg);
400 else
401 lua_pushfstring(lua->T, "message handler error");
402 ret = HLUA_E_ERRMSG;
403 break;
404
405 default:
406 lua_settop(lua->T, 0); /* Empty the stack. */
407 if (!lua_checkstack(lua->T, 1)) {
408 ret = HLUA_E_ERR;
409 break;
410 }
411 lua_pushfstring(lua->T, "unknonwn error");
412 ret = HLUA_E_ERRMSG;
413 break;
414 }
415
416 switch (ret) {
417 case HLUA_E_AGAIN:
418 break;
419
420 case HLUA_E_ERRMSG:
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100421 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100422 hlua_ctx_renew(lua, 1);
423 lua->state = HLUA_STOP;
424 break;
425
426 case HLUA_E_ERR:
427 lua->state = HLUA_STOP;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100428 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100429 hlua_ctx_renew(lua, 0);
430 break;
431
432 case HLUA_E_OK:
433 lua->state = HLUA_STOP;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100434 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100435 break;
436 }
437
438 return ret;
439}
440
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100441/* This function is an LUA binding that register LUA function to be
442 * executed after the HAProxy configuration parsing and before the
443 * HAProxy scheduler starts. This function expect only one LUA
444 * argument that is a function. This function returns nothing, but
445 * throws if an error is encountered.
446 */
447__LJMP static int hlua_register_init(lua_State *L)
448{
449 struct hlua_init_function *init;
450 int ref;
451
452 MAY_LJMP(check_args(L, 1, "register_init"));
453
454 ref = MAY_LJMP(hlua_checkfunction(L, 1));
455
456 init = malloc(sizeof(*init));
457 if (!init)
458 WILL_LJMP(luaL_error(L, "lua out of memory error."));
459
460 init->function_ref = ref;
461 LIST_ADDQ(&hlua_init_functions, &init->l);
462 return 0;
463}
464
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +0100465/* This function is called by the main configuration key "lua-load". It loads and
466 * execute an lua file during the parsing of the HAProxy configuration file. It is
467 * the main lua entry point.
468 *
469 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
470 * occured, otherwise it returns 0.
471 *
472 * In some error case, LUA set an error message in top of the stack. This function
473 * returns this error message in the HAProxy logs and pop it from the stack.
474 */
475static int hlua_load(char **args, int section_type, struct proxy *curpx,
476 struct proxy *defpx, const char *file, int line,
477 char **err)
478{
479 int error;
480
481 /* Just load and compile the file. */
482 error = luaL_loadfile(gL.T, args[1]);
483 if (error) {
484 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
485 lua_pop(gL.T, 1);
486 return -1;
487 }
488
489 /* If no syntax error where detected, execute the code. */
490 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
491 switch (error) {
492 case LUA_OK:
493 break;
494 case LUA_ERRRUN:
495 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
496 lua_pop(gL.T, 1);
497 return -1;
498 case LUA_ERRMEM:
499 memprintf(err, "lua out of memory error\n");
500 return -1;
501 case LUA_ERRERR:
502 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
503 lua_pop(gL.T, 1);
504 return -1;
505 case LUA_ERRGCMM:
506 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
507 lua_pop(gL.T, 1);
508 return -1;
509 default:
510 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
511 lua_pop(gL.T, 1);
512 return -1;
513 }
514
515 return 0;
516}
517
518/* configuration keywords declaration */
519static struct cfg_kw_list cfg_kws = {{ },{
520 { CFG_GLOBAL, "lua-load", hlua_load },
521 { 0, NULL, NULL },
522}};
523
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100524int hlua_post_init()
525{
526 struct hlua_init_function *init;
527 const char *msg;
528 enum hlua_exec ret;
529
530 list_for_each_entry(init, &hlua_init_functions, l) {
531 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
532 ret = hlua_ctx_resume(&gL, 0);
533 switch (ret) {
534 case HLUA_E_OK:
535 lua_pop(gL.T, -1);
536 return 1;
537 case HLUA_E_AGAIN:
538 Alert("lua init: yield not allowed.\n");
539 return 0;
540 case HLUA_E_ERRMSG:
541 msg = lua_tostring(gL.T, -1);
542 Alert("lua init: %s.\n", msg);
543 return 0;
544 case HLUA_E_ERR:
545 default:
546 Alert("lua init: unknown runtime error.\n");
547 return 0;
548 }
549 }
550 return 1;
551}
552
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +0100553void hlua_init(void)
554{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100555 int i;
556
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100557 /* Initialise com signals pool session. */
558 pool2_hlua_com = create_pool("hlua_com", sizeof(struct hlua_com), MEM_F_SHARED);
559
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +0100560 /* Register configuration keywords. */
561 cfg_register_keywords(&cfg_kws);
562
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100563 /* Init main lua stack. */
564 gL.Mref = LUA_REFNIL;
565 gL.state = HLUA_STOP;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100566 LIST_INIT(&gL.com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100567 gL.T = luaL_newstate();
568 hlua_sethlua(&gL);
569 gL.Tref = LUA_REFNIL;
570 gL.task = NULL;
571
572 /* Initialise lua. */
573 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100574
575 /*
576 *
577 * Create "core" object.
578 *
579 */
580
581 /* This integer entry is just used as base value for the object "core". */
582 lua_pushinteger(gL.T, 0);
583
584 /* Create and fill the metatable. */
585 lua_newtable(gL.T);
586
587 /* Create and fill the __index entry. */
588 lua_pushstring(gL.T, "__index");
589 lua_newtable(gL.T);
590
591 /* Push the loglevel constants. */
592 for (i=0; i<NB_LOG_LEVELS; i++)
593 hlua_class_const_int(gL.T, log_levels[i], i);
594
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100595 /* Register special functions. */
596 hlua_class_function(gL.T, "register_init", hlua_register_init);
597
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100598 /* Store the table __index in the metable. */
599 lua_settable(gL.T, -3);
600
601 /* Register previous table in the registry with named entry. */
602 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
603 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CORE); /* register class session. */
604
605 /* Register previous table in the registry with reference. */
606 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
607 class_core_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
608
609 /* Create new object with class Core. */
610 lua_setmetatable(gL.T, -2);
611 lua_setglobal(gL.T, "core");
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +0100612}