Stop poisoning function in debug mode
[collectd.git] / src / lua.c
1 /**
2  * collectd - src/lua.c
3  * Copyright (C) 2010       Julien Ammous
4  * Copyright (C) 2010       Florian Forster
5  * Copyright (C) 2016       Ruben Kerkhof
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a copy
8  * of this software and associated documentation files (the "Software"), to deal
9  * in the Software without restriction, including without limitation the rights
10  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11  * copies of the Software, and to permit persons to whom the Software is
12  * furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included in
15  * all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23  * SOFTWARE.
24  *
25  * Authors:
26  *   Julien Ammous
27  *   Florian Forster <octo at collectd.org>
28  *   Ruben Kerkhof <ruben at rubenkerkhof.com>
29  **/
30
31 #include "collectd.h"
32 #include "common.h"
33 #include "plugin.h"
34 #include "utils_lua.h"
35
36 /* Include the Lua API header files. */
37 #include <lauxlib.h>
38 #include <lua.h>
39 #include <lualib.h>
40
41 #include <pthread.h>
42
43 typedef struct lua_script_s {
44   char *script_path;
45   lua_State *lua_state;
46   struct lua_script_s *next;
47 } lua_script_t;
48
49 typedef struct {
50   lua_State *lua_state;
51   const char *lua_function_name;
52   pthread_mutex_t lock;
53   int callback_id;
54 } clua_callback_data_t;
55
56 static char base_path[PATH_MAX];
57 static lua_script_t *scripts;
58
59 static int clua_store_callback(lua_State *L, int idx) /* {{{ */
60 {
61   /* Copy the function pointer */
62   lua_pushvalue(L, idx);
63
64   return luaL_ref(L, LUA_REGISTRYINDEX);
65 } /* }}} int clua_store_callback */
66
67 static int clua_load_callback(lua_State *L, int callback_ref) /* {{{ */
68 {
69   lua_rawgeti(L, LUA_REGISTRYINDEX, callback_ref);
70
71   if (!lua_isfunction(L, -1)) {
72     lua_pop(L, 1);
73     return -1;
74   }
75
76   return 0;
77 } /* }}} int clua_load_callback */
78
79 /* Store the threads in a global variable so they are not cleaned up by the
80  * garbage collector. */
81 static int clua_store_thread(lua_State *L, int idx) /* {{{ */
82 {
83   if (idx < 0)
84     idx += lua_gettop(L) + 1;
85
86   /* Copy the thread pointer */
87   lua_pushvalue(L, idx); /* +1 = 3 */
88   if (!lua_isthread(L, -1)) {
89     lua_pop(L, 3); /* -3 = 0 */
90     return -1;
91   }
92
93   luaL_ref(L, LUA_REGISTRYINDEX);
94   lua_pop(L, 1); /* -1 = 0 */
95   return 0;
96 } /* }}} int clua_store_thread */
97
98 static int clua_read(user_data_t *ud) /* {{{ */
99 {
100   clua_callback_data_t *cb = ud->data;
101
102   pthread_mutex_lock(&cb->lock);
103
104   lua_State *L = cb->lua_state;
105
106   int status = clua_load_callback(L, cb->callback_id);
107   if (status != 0) {
108     ERROR("Lua plugin: Unable to load callback \"%s\" (id %i).",
109           cb->lua_function_name, cb->callback_id);
110     pthread_mutex_unlock(&cb->lock);
111     return -1;
112   }
113   /* +1 = 1 */
114
115   status = lua_pcall(L, 0, 1, 0);
116   if (status != 0) {
117     const char *errmsg = lua_tostring(L, -1);
118     if (errmsg == NULL)
119       ERROR("Lua plugin: Calling a read callback failed. "
120             "In addition, retrieving the error message failed.");
121     else
122       ERROR("Lua plugin: Calling a read callback failed: %s", errmsg);
123     lua_pop(L, 1);
124     pthread_mutex_unlock(&cb->lock);
125     return -1;
126   }
127
128   if (!lua_isnumber(L, -1)) {
129     ERROR("Lua plugin: Read function \"%s\" (id %i) did not return a numeric "
130           "status.",
131           cb->lua_function_name, cb->callback_id);
132     status = -1;
133   } else {
134     status = (int)lua_tointeger(L, -1);
135   }
136
137   /* pop return value and function */
138   lua_pop(L, 1); /* -1 = 0 */
139
140   pthread_mutex_unlock(&cb->lock);
141   return status;
142 } /* }}} int clua_read */
143
144 static int clua_write(const data_set_t *ds, const value_list_t *vl, /* {{{ */
145                       user_data_t *ud) {
146   clua_callback_data_t *cb = ud->data;
147
148   pthread_mutex_lock(&cb->lock);
149
150   lua_State *L = cb->lua_state;
151
152   int status = clua_load_callback(L, cb->callback_id);
153   if (status != 0) {
154     ERROR("Lua plugin: Unable to load callback \"%s\" (id %i).",
155           cb->lua_function_name, cb->callback_id);
156     pthread_mutex_unlock(&cb->lock);
157     return -1;
158   }
159   /* +1 = 1 */
160
161   status = luaC_pushvaluelist(L, ds, vl);
162   if (status != 0) {
163     lua_pop(L, 1); /* -1 = 0 */
164     pthread_mutex_unlock(&cb->lock);
165     ERROR("Lua plugin: luaC_pushvaluelist failed.");
166     return -1;
167   }
168   /* +1 = 2 */
169
170   status = lua_pcall(L, 1, 1, 0); /* -2+1 = 1 */
171   if (status != 0) {
172     const char *errmsg = lua_tostring(L, -1);
173     if (errmsg == NULL)
174       ERROR("Lua plugin: Calling the write callback failed. "
175             "In addition, retrieving the error message failed.");
176     else
177       ERROR("Lua plugin: Calling the write callback failed:\n%s", errmsg);
178     lua_pop(L, 1); /* -1 = 0 */
179     pthread_mutex_unlock(&cb->lock);
180     return -1;
181   }
182
183   if (!lua_isnumber(L, -1)) {
184     ERROR("Lua plugin: Write function \"%s\" (id %i) did not return a numeric "
185           "value.",
186           cb->lua_function_name, cb->callback_id);
187     status = -1;
188   } else {
189     status = (int)lua_tointeger(L, -1);
190   }
191
192   lua_pop(L, 1); /* -1 = 0 */
193   pthread_mutex_unlock(&cb->lock);
194   return status;
195 } /* }}} int clua_write */
196
197 /*
198  * Exported functions
199  */
200
201 static int lua_cb_log_debug(lua_State *L) /* {{{ */
202 {
203   const char *msg = luaL_checkstring(L, 1);
204   plugin_log(LOG_DEBUG, "%s", msg);
205   return 0;
206 } /* }}} int lua_cb_log_debug */
207
208 static int lua_cb_log_error(lua_State *L) /* {{{ */
209 {
210   const char *msg = luaL_checkstring(L, 1);
211   plugin_log(LOG_ERR, "%s", msg);
212   return 0;
213 } /* }}} int lua_cb_log_error */
214
215 static int lua_cb_log_info(lua_State *L) /* {{{ */
216 {
217   const char *msg = luaL_checkstring(L, 1);
218   plugin_log(LOG_INFO, "%s", msg);
219   return 0;
220 } /* }}} int lua_cb_log_info */
221
222 static int lua_cb_log_notice(lua_State *L) /* {{{ */
223 {
224   const char *msg = luaL_checkstring(L, 1);
225   plugin_log(LOG_NOTICE, "%s", msg);
226   return 0;
227 } /* }}} int lua_cb_log_notice */
228
229 static int lua_cb_log_warning(lua_State *L) /* {{{ */
230 {
231   const char *msg = luaL_checkstring(L, 1);
232   plugin_log(LOG_WARNING, "%s", msg);
233   return 0;
234 } /* }}} int lua_cb_log_warning */
235
236 static int lua_cb_dispatch_values(lua_State *L) /* {{{ */
237 {
238   int nargs = lua_gettop(L);
239
240   if (nargs != 1)
241     return luaL_error(L, "Invalid number of arguments (%d != 1)", nargs);
242
243   luaL_checktype(L, 1, LUA_TTABLE);
244
245   value_list_t *vl = luaC_tovaluelist(L, -1);
246   if (vl == NULL)
247     return luaL_error(L, "%s", "luaC_tovaluelist failed");
248
249 #if COLLECT_DEBUG
250   char identifier[6 * DATA_MAX_NAME_LEN];
251   FORMAT_VL(identifier, sizeof(identifier), vl);
252
253   DEBUG("Lua plugin: collectd.dispatch_values(): Received value list \"%s\", "
254         "time %.3f, interval %.3f.",
255         identifier, CDTIME_T_TO_DOUBLE(vl->time),
256         CDTIME_T_TO_DOUBLE(vl->interval));
257 #endif
258
259   plugin_dispatch_values(vl);
260
261   sfree(vl->values);
262   sfree(vl);
263   return 0;
264 } /* }}} lua_cb_dispatch_values */
265
266 static int lua_cb_register_read(lua_State *L) /* {{{ */
267 {
268   int nargs = lua_gettop(L);
269
270   if (nargs != 1)
271     return luaL_error(L, "Invalid number of arguments (%d != 1)", nargs);
272
273   luaL_checktype(L, 1, LUA_TFUNCTION);
274
275   char function_name[DATA_MAX_NAME_LEN];
276   snprintf(function_name, sizeof(function_name), "lua/%s", lua_tostring(L, 1));
277
278   int callback_id = clua_store_callback(L, 1);
279   if (callback_id < 0)
280     return luaL_error(L, "%s", "Storing callback function failed");
281
282   lua_State *thread = lua_newthread(L);
283   if (thread == NULL)
284     return luaL_error(L, "%s", "lua_newthread failed");
285   clua_store_thread(L, -1);
286   lua_pop(L, 1);
287
288   clua_callback_data_t *cb = calloc(1, sizeof(*cb));
289   if (cb == NULL)
290     return luaL_error(L, "%s", "calloc failed");
291
292   cb->lua_state = thread;
293   cb->callback_id = callback_id;
294   cb->lua_function_name = strdup(function_name);
295   pthread_mutex_init(&cb->lock, NULL);
296
297   int status = plugin_register_complex_read(/* group = */ "lua",
298                                             /* name      = */ function_name,
299                                             /* callback  = */ clua_read,
300                                             /* interval  = */ 0,
301                                             &(user_data_t){
302                                                 .data = cb,
303                                             });
304
305   if (status != 0)
306     return luaL_error(L, "%s", "plugin_register_complex_read failed");
307   return 0;
308 } /* }}} int lua_cb_register_read */
309
310 static int lua_cb_register_write(lua_State *L) /* {{{ */
311 {
312   int nargs = lua_gettop(L);
313
314   if (nargs != 1)
315     return luaL_error(L, "Invalid number of arguments (%d != 1)", nargs);
316
317   luaL_checktype(L, 1, LUA_TFUNCTION);
318
319   char function_name[DATA_MAX_NAME_LEN] = "";
320   snprintf(function_name, sizeof(function_name), "lua/%s", lua_tostring(L, 1));
321
322   int callback_id = clua_store_callback(L, 1);
323   if (callback_id < 0)
324     return luaL_error(L, "%s", "Storing callback function failed");
325
326   lua_State *thread = lua_newthread(L);
327   if (thread == NULL)
328     return luaL_error(L, "%s", "lua_newthread failed");
329   clua_store_thread(L, -1);
330   lua_pop(L, 1);
331
332   clua_callback_data_t *cb = calloc(1, sizeof(*cb));
333   if (cb == NULL)
334     return luaL_error(L, "%s", "calloc failed");
335
336   cb->lua_state = thread;
337   cb->callback_id = callback_id;
338   cb->lua_function_name = strdup(function_name);
339   pthread_mutex_init(&cb->lock, NULL);
340
341   int status = plugin_register_write(/* name = */ function_name,
342                                      /* callback  = */ clua_write,
343                                      &(user_data_t){
344                                          .data = cb,
345                                      });
346
347   if (status != 0)
348     return luaL_error(L, "%s", "plugin_register_write failed");
349   return 0;
350 } /* }}} int lua_cb_register_write */
351
352 static const luaL_Reg collectdlib[] = {
353     {"log_debug", lua_cb_log_debug},
354     {"log_error", lua_cb_log_error},
355     {"log_info", lua_cb_log_info},
356     {"log_notice", lua_cb_log_notice},
357     {"log_warning", lua_cb_log_warning},
358     {"dispatch_values", lua_cb_dispatch_values},
359     {"register_read", lua_cb_register_read},
360     {"register_write", lua_cb_register_write},
361     {NULL, NULL}};
362
363 static int open_collectd(lua_State *L) /* {{{ */
364 {
365 #if LUA_VERSION_NUM < 502
366   luaL_register(L, "collectd", collectdlib);
367 #else
368   luaL_newlib(L, collectdlib);
369 #endif
370   return 1;
371 } /* }}} */
372
373 static void lua_script_free(lua_script_t *script) /* {{{ */
374 {
375   if (script == NULL)
376     return;
377
378   lua_script_t *next = script->next;
379
380   if (script->lua_state != NULL) {
381     lua_close(script->lua_state);
382     script->lua_state = NULL;
383   }
384
385   sfree(script->script_path);
386   sfree(script);
387
388   lua_script_free(next);
389 } /* }}} void lua_script_free */
390
391 static int lua_script_init(lua_script_t *script) /* {{{ */
392 {
393   memset(script, 0, sizeof(*script));
394
395   /* initialize the lua context */
396   script->lua_state = luaL_newstate();
397   if (script->lua_state == NULL) {
398     ERROR("Lua plugin: luaL_newstate() failed.");
399     return -1;
400   }
401
402   /* Open up all the standard Lua libraries. */
403   luaL_openlibs(script->lua_state);
404
405 /* Load the 'collectd' library */
406 #if LUA_VERSION_NUM < 502
407   lua_pushcfunction(script->lua_state, open_collectd);
408   lua_pushstring(script->lua_state, "collectd");
409   lua_call(script->lua_state, 1, 0);
410 #else
411   luaL_requiref(script->lua_state, "collectd", open_collectd, 1);
412   lua_pop(script->lua_state, 1);
413 #endif
414
415   /* Prepend BasePath to package.path */
416   if (base_path[0] != '\0') {
417     lua_getglobal(script->lua_state, "package");
418     lua_getfield(script->lua_state, -1, "path");
419
420     const char *cur_path = lua_tostring(script->lua_state, -1);
421     char *new_path = ssnprintf_alloc("%s/?.lua;%s", base_path, cur_path);
422
423     lua_pop(script->lua_state, 1);
424     lua_pushstring(script->lua_state, new_path);
425
426     free(new_path);
427
428     lua_setfield(script->lua_state, -2, "path");
429     lua_pop(script->lua_state, 1);
430   }
431
432   return 0;
433 } /* }}} int lua_script_init */
434
435 static int lua_script_load(const char *script_path) /* {{{ */
436 {
437   lua_script_t *script = malloc(sizeof(*script));
438   if (script == NULL) {
439     ERROR("Lua plugin: malloc failed.");
440     return -1;
441   }
442
443   int status = lua_script_init(script);
444   if (status != 0) {
445     lua_script_free(script);
446     return status;
447   }
448
449   script->script_path = strdup(script_path);
450   if (script->script_path == NULL) {
451     ERROR("Lua plugin: strdup failed.");
452     lua_script_free(script);
453     return -1;
454   }
455
456   status = luaL_loadfile(script->lua_state, script->script_path);
457   if (status != 0) {
458     ERROR("Lua plugin: luaL_loadfile failed: %s",
459           lua_tostring(script->lua_state, -1));
460     lua_pop(script->lua_state, 1);
461     lua_script_free(script);
462     return -1;
463   }
464
465   status = lua_pcall(script->lua_state,
466                      /* nargs = */ 0,
467                      /* nresults = */ LUA_MULTRET,
468                      /* errfunc = */ 0);
469   if (status != 0) {
470     const char *errmsg = lua_tostring(script->lua_state, -1);
471
472     if (errmsg == NULL)
473       ERROR("Lua plugin: lua_pcall failed with status %i. "
474             "In addition, no error message could be retrieved from the stack.",
475             status);
476     else
477       ERROR("Lua plugin: Executing script \"%s\" failed:\n%s",
478             script->script_path, errmsg);
479
480     lua_script_free(script);
481     return -1;
482   }
483
484   /* Append this script to the global list of scripts. */
485   if (scripts) {
486     lua_script_t *last = scripts;
487     while (last->next)
488       last = last->next;
489
490     last->next = script;
491   } else {
492     scripts = script;
493   }
494
495   return 0;
496 } /* }}} int lua_script_load */
497
498 static int lua_config_base_path(const oconfig_item_t *ci) /* {{{ */
499 {
500   int status = cf_util_get_string_buffer(ci, base_path, sizeof(base_path));
501   if (status != 0)
502     return status;
503
504   size_t len = strlen(base_path);
505   while ((len > 0) && (base_path[len - 1] == '/')) {
506     len--;
507     base_path[len] = '\0';
508   }
509
510   DEBUG("Lua plugin: base_path = \"%s\";", base_path);
511
512   return 0;
513 } /* }}} int lua_config_base_path */
514
515 static int lua_config_script(const oconfig_item_t *ci) /* {{{ */
516 {
517   char rel_path[PATH_MAX];
518
519   int status = cf_util_get_string_buffer(ci, rel_path, sizeof(rel_path));
520   if (status != 0)
521     return status;
522
523   char abs_path[PATH_MAX];
524
525   if (base_path[0] == '\0')
526     sstrncpy(abs_path, rel_path, sizeof(abs_path));
527   else
528     snprintf(abs_path, sizeof(abs_path), "%s/%s", base_path, rel_path);
529
530   DEBUG("Lua plugin: abs_path = \"%s\";", abs_path);
531
532   status = lua_script_load(abs_path);
533   if (status != 0)
534     return status;
535
536   INFO("Lua plugin: File \"%s\" loaded successfully", abs_path);
537
538   return 0;
539 } /* }}} int lua_config_script */
540
541 /*
542  * <Plugin lua>
543  *   BasePath "/"
544  *   Script "script1.lua"
545  *   Script "script2.lua"
546  * </Plugin>
547  */
548 static int lua_config(oconfig_item_t *ci) /* {{{ */
549 {
550   int status = 0;
551   for (int i = 0; i < ci->children_num; i++) {
552     oconfig_item_t *child = ci->children + i;
553
554     if (strcasecmp("BasePath", child->key) == 0) {
555       status = lua_config_base_path(child);
556     } else if (strcasecmp("Script", child->key) == 0) {
557       status = lua_config_script(child);
558     } else {
559       ERROR("Lua plugin: Option `%s' is not allowed here.", child->key);
560       status = 1;
561     }
562   }
563
564   return status;
565 } /* }}} int lua_config */
566
567 static int lua_shutdown(void) /* {{{ */
568 {
569   lua_script_free(scripts);
570
571   return 0;
572 } /* }}} int lua_shutdown */
573
574 void module_register(void) {
575   plugin_register_complex_config("lua", lua_config);
576   plugin_register_shutdown("lua", lua_shutdown);
577 }