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