3 * Copyright (C) 2010 Julien Ammous
4 * Copyright (C) 2010 Florian Forster
5 * Copyright (C) 2016 Ruben Kerkhof
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:
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
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
27 * Florian Forster <octo at collectd.org>
28 * Ruben Kerkhof <ruben at rubenkerkhof.com>
31 /* <lua5.1/luaconf.h> defines a macro using "sprintf". Although not used here,
32 * GCC will complain about the macro definition. */
33 #define DONT_POISON_SPRINTF_YET
39 /* Include the Lua API header files. */
43 #include "utils_lua.h"
47 #if COLLECT_DEBUG && __GNUC__
49 #pragma GCC poison sprintf
52 typedef struct lua_script_s {
55 struct lua_script_s *next;
60 const char *lua_function_name;
63 } clua_callback_data_t;
65 static char base_path[PATH_MAX];
66 static lua_script_t *scripts;
68 static int clua_store_callback(lua_State *L, int idx) /* {{{ */
70 /* Copy the function pointer */
71 lua_pushvalue(L, idx);
73 return luaL_ref(L, LUA_REGISTRYINDEX);
74 } /* }}} int clua_store_callback */
76 static int clua_load_callback(lua_State *L, int callback_ref) /* {{{ */
78 lua_rawgeti(L, LUA_REGISTRYINDEX, callback_ref);
80 if (!lua_isfunction(L, -1)) {
86 } /* }}} int clua_load_callback */
88 /* Store the threads in a global variable so they are not cleaned up by the
89 * garbage collector. */
90 static int clua_store_thread(lua_State *L, int idx) /* {{{ */
93 idx += lua_gettop(L) + 1;
95 /* Copy the thread pointer */
96 lua_pushvalue(L, idx); /* +1 = 3 */
97 if (!lua_isthread(L, -1)) {
98 lua_pop(L, 3); /* -3 = 0 */
102 luaL_ref(L, LUA_REGISTRYINDEX);
103 lua_pop(L, 1); /* -1 = 0 */
105 } /* }}} int clua_store_thread */
107 static int clua_read(user_data_t *ud) /* {{{ */
109 clua_callback_data_t *cb = ud->data;
111 pthread_mutex_lock(&cb->lock);
113 lua_State *L = cb->lua_state;
115 int status = clua_load_callback(L, cb->callback_id);
117 ERROR("Lua plugin: Unable to load callback \"%s\" (id %i).",
118 cb->lua_function_name, cb->callback_id);
119 pthread_mutex_unlock(&cb->lock);
124 status = lua_pcall(L, 0, 1, 0);
126 const char *errmsg = lua_tostring(L, -1);
128 ERROR("Lua plugin: Calling a read callback failed. "
129 "In addition, retrieving the error message failed.");
131 ERROR("Lua plugin: Calling a read callback failed: %s", errmsg);
133 pthread_mutex_unlock(&cb->lock);
137 if (!lua_isnumber(L, -1)) {
138 ERROR("Lua plugin: Read function \"%s\" (id %i) did not return a numeric "
140 cb->lua_function_name, cb->callback_id);
143 status = (int)lua_tointeger(L, -1);
146 /* pop return value and function */
147 lua_pop(L, 1); /* -1 = 0 */
149 pthread_mutex_unlock(&cb->lock);
151 } /* }}} int clua_read */
153 static int clua_write(const data_set_t *ds, const value_list_t *vl, /* {{{ */
155 clua_callback_data_t *cb = ud->data;
157 pthread_mutex_lock(&cb->lock);
159 lua_State *L = cb->lua_state;
161 int status = clua_load_callback(L, cb->callback_id);
163 ERROR("Lua plugin: Unable to load callback \"%s\" (id %i).",
164 cb->lua_function_name, cb->callback_id);
165 pthread_mutex_unlock(&cb->lock);
170 status = luaC_pushvaluelist(L, ds, vl);
172 lua_pop(L, 1); /* -1 = 0 */
173 pthread_mutex_unlock(&cb->lock);
174 ERROR("Lua plugin: luaC_pushvaluelist failed.");
179 status = lua_pcall(L, 1, 1, 0); /* -2+1 = 1 */
181 const char *errmsg = lua_tostring(L, -1);
183 ERROR("Lua plugin: Calling the write callback failed. "
184 "In addition, retrieving the error message failed.");
186 ERROR("Lua plugin: Calling the write callback failed:\n%s", errmsg);
187 lua_pop(L, 1); /* -1 = 0 */
188 pthread_mutex_unlock(&cb->lock);
192 if (!lua_isnumber(L, -1)) {
193 ERROR("Lua plugin: Write function \"%s\" (id %i) did not return a numeric "
195 cb->lua_function_name, cb->callback_id);
198 status = (int)lua_tointeger(L, -1);
201 lua_pop(L, 1); /* -1 = 0 */
202 pthread_mutex_unlock(&cb->lock);
204 } /* }}} int clua_write */
210 static int lua_cb_log_debug(lua_State *L) /* {{{ */
212 const char *msg = luaL_checkstring(L, 1);
213 plugin_log(LOG_DEBUG, "%s", msg);
215 } /* }}} int lua_cb_log_debug */
217 static int lua_cb_log_error(lua_State *L) /* {{{ */
219 const char *msg = luaL_checkstring(L, 1);
220 plugin_log(LOG_ERR, "%s", msg);
222 } /* }}} int lua_cb_log_error */
224 static int lua_cb_log_info(lua_State *L) /* {{{ */
226 const char *msg = luaL_checkstring(L, 1);
227 plugin_log(LOG_INFO, "%s", msg);
229 } /* }}} int lua_cb_log_info */
231 static int lua_cb_log_notice(lua_State *L) /* {{{ */
233 const char *msg = luaL_checkstring(L, 1);
234 plugin_log(LOG_NOTICE, "%s", msg);
236 } /* }}} int lua_cb_log_notice */
238 static int lua_cb_log_warning(lua_State *L) /* {{{ */
240 const char *msg = luaL_checkstring(L, 1);
241 plugin_log(LOG_WARNING, "%s", msg);
243 } /* }}} int lua_cb_log_warning */
245 static int lua_cb_dispatch_values(lua_State *L) /* {{{ */
247 int nargs = lua_gettop(L);
250 return luaL_error(L, "Invalid number of arguments (%d != 1)", nargs);
252 luaL_checktype(L, 1, LUA_TTABLE);
254 value_list_t *vl = luaC_tovaluelist(L, -1);
256 return luaL_error(L, "%s", "luaC_tovaluelist failed");
259 char identifier[6 * DATA_MAX_NAME_LEN];
260 FORMAT_VL(identifier, sizeof(identifier), vl);
262 DEBUG("Lua plugin: collectd.dispatch_values(): Received value list \"%s\", "
263 "time %.3f, interval %.3f.",
264 identifier, CDTIME_T_TO_DOUBLE(vl->time),
265 CDTIME_T_TO_DOUBLE(vl->interval));
268 plugin_dispatch_values(vl);
273 } /* }}} lua_cb_dispatch_values */
275 static int lua_cb_register_read(lua_State *L) /* {{{ */
277 int nargs = lua_gettop(L);
280 return luaL_error(L, "Invalid number of arguments (%d != 1)", nargs);
282 luaL_checktype(L, 1, LUA_TFUNCTION);
284 char function_name[DATA_MAX_NAME_LEN];
285 ssnprintf(function_name, sizeof(function_name), "lua/%s", lua_tostring(L, 1));
287 int callback_id = clua_store_callback(L, 1);
289 return luaL_error(L, "%s", "Storing callback function failed");
291 lua_State *thread = lua_newthread(L);
293 return luaL_error(L, "%s", "lua_newthread failed");
294 clua_store_thread(L, -1);
297 clua_callback_data_t *cb = calloc(1, sizeof(*cb));
299 return luaL_error(L, "%s", "calloc failed");
301 cb->lua_state = thread;
302 cb->callback_id = callback_id;
303 cb->lua_function_name = strdup(function_name);
304 pthread_mutex_init(&cb->lock, NULL);
306 int status = plugin_register_complex_read(/* group = */ "lua",
307 /* name = */ function_name,
308 /* callback = */ clua_read,
309 /* interval = */ 0, &(user_data_t){
314 return luaL_error(L, "%s", "plugin_register_complex_read failed");
316 } /* }}} int lua_cb_register_read */
318 static int lua_cb_register_write(lua_State *L) /* {{{ */
320 int nargs = lua_gettop(L);
323 return luaL_error(L, "Invalid number of arguments (%d != 1)", nargs);
325 luaL_checktype(L, 1, LUA_TFUNCTION);
327 char function_name[DATA_MAX_NAME_LEN] = "";
328 ssnprintf(function_name, sizeof(function_name), "lua/%s", lua_tostring(L, 1));
330 int callback_id = clua_store_callback(L, 1);
332 return luaL_error(L, "%s", "Storing callback function failed");
334 lua_State *thread = lua_newthread(L);
336 return luaL_error(L, "%s", "lua_newthread failed");
337 clua_store_thread(L, -1);
340 clua_callback_data_t *cb = calloc(1, sizeof(*cb));
342 return luaL_error(L, "%s", "calloc failed");
344 cb->lua_state = thread;
345 cb->callback_id = callback_id;
346 cb->lua_function_name = strdup(function_name);
347 pthread_mutex_init(&cb->lock, NULL);
350 plugin_register_write(/* name = */ function_name,
351 /* callback = */ clua_write, &(user_data_t){
356 return luaL_error(L, "%s", "plugin_register_write failed");
358 } /* }}} int lua_cb_register_write */
360 static const luaL_Reg collectdlib[] = {
361 {"log_debug", lua_cb_log_debug},
362 {"log_error", lua_cb_log_error},
363 {"log_info", lua_cb_log_info},
364 {"log_notice", lua_cb_log_notice},
365 {"log_warning", lua_cb_log_warning},
366 {"dispatch_values", lua_cb_dispatch_values},
367 {"register_read", lua_cb_register_read},
368 {"register_write", lua_cb_register_write},
371 static int open_collectd(lua_State *L) /* {{{ */
373 #if LUA_VERSION_NUM < 502
374 luaL_register(L, "collectd", collectdlib);
376 luaL_newlib(L, collectdlib);
381 static void lua_script_free(lua_script_t *script) /* {{{ */
386 lua_script_t *next = script->next;
388 if (script->lua_state != NULL) {
389 lua_close(script->lua_state);
390 script->lua_state = NULL;
393 sfree(script->script_path);
396 lua_script_free(next);
397 } /* }}} void lua_script_free */
399 static int lua_script_init(lua_script_t *script) /* {{{ */
401 memset(script, 0, sizeof(*script));
403 /* initialize the lua context */
404 script->lua_state = luaL_newstate();
405 if (script->lua_state == NULL) {
406 ERROR("Lua plugin: luaL_newstate() failed.");
410 /* Open up all the standard Lua libraries. */
411 luaL_openlibs(script->lua_state);
413 /* Load the 'collectd' library */
414 #if LUA_VERSION_NUM < 502
415 lua_pushcfunction(script->lua_state, open_collectd);
416 lua_pushstring(script->lua_state, "collectd");
417 lua_call(script->lua_state, 1, 0);
419 luaL_requiref(script->lua_state, "collectd", open_collectd, 1);
420 lua_pop(script->lua_state, 1);
423 /* Prepend BasePath to package.path */
424 if (base_path[0] != '\0') {
425 lua_getglobal(script->lua_state, "package");
426 lua_getfield(script->lua_state, -1, "path");
428 const char *cur_path = lua_tostring(script->lua_state, -1);
429 char *new_path = ssnprintf_alloc("%s/?.lua;%s", base_path, cur_path);
431 lua_pop(script->lua_state, 1);
432 lua_pushstring(script->lua_state, new_path);
436 lua_setfield(script->lua_state, -2, "path");
437 lua_pop(script->lua_state, 1);
441 } /* }}} int lua_script_init */
443 static int lua_script_load(const char *script_path) /* {{{ */
445 lua_script_t *script = malloc(sizeof(*script));
446 if (script == NULL) {
447 ERROR("Lua plugin: malloc failed.");
451 int status = lua_script_init(script);
453 lua_script_free(script);
457 script->script_path = strdup(script_path);
458 if (script->script_path == NULL) {
459 ERROR("Lua plugin: strdup failed.");
460 lua_script_free(script);
464 status = luaL_loadfile(script->lua_state, script->script_path);
466 ERROR("Lua plugin: luaL_loadfile failed: %s",
467 lua_tostring(script->lua_state, -1));
468 lua_pop(script->lua_state, 1);
469 lua_script_free(script);
473 status = lua_pcall(script->lua_state,
475 /* nresults = */ LUA_MULTRET,
478 const char *errmsg = lua_tostring(script->lua_state, -1);
481 ERROR("Lua plugin: lua_pcall failed with status %i. "
482 "In addition, no error message could be retrieved from the stack.",
485 ERROR("Lua plugin: Executing script \"%s\" failed:\n%s",
486 script->script_path, errmsg);
488 lua_script_free(script);
492 /* Append this script to the global list of scripts. */
494 lua_script_t *last = scripts;
504 } /* }}} int lua_script_load */
506 static int lua_config_base_path(const oconfig_item_t *ci) /* {{{ */
508 int status = cf_util_get_string_buffer(ci, base_path, sizeof(base_path));
512 size_t len = strlen(base_path);
513 while ((len > 0) && (base_path[len - 1] == '/')) {
515 base_path[len] = '\0';
518 DEBUG("Lua plugin: base_path = \"%s\";", base_path);
521 } /* }}} int lua_config_base_path */
523 static int lua_config_script(const oconfig_item_t *ci) /* {{{ */
525 char rel_path[PATH_MAX];
527 int status = cf_util_get_string_buffer(ci, rel_path, sizeof(rel_path));
531 char abs_path[PATH_MAX];
533 if (base_path[0] == '\0')
534 sstrncpy(abs_path, rel_path, sizeof(abs_path));
536 ssnprintf(abs_path, sizeof(abs_path), "%s/%s", base_path, rel_path);
538 DEBUG("Lua plugin: abs_path = \"%s\";", abs_path);
540 status = lua_script_load(abs_path);
544 INFO("Lua plugin: File \"%s\" loaded successfully", abs_path);
547 } /* }}} int lua_config_script */
552 * Script "script1.lua"
553 * Script "script2.lua"
556 static int lua_config(oconfig_item_t *ci) /* {{{ */
559 for (int i = 0; i < ci->children_num; i++) {
560 oconfig_item_t *child = ci->children + i;
562 if (strcasecmp("BasePath", child->key) == 0) {
563 status = lua_config_base_path(child);
564 } else if (strcasecmp("Script", child->key) == 0) {
565 status = lua_config_script(child);
567 ERROR("Lua plugin: Option `%s' is not allowed here.", child->key);
573 } /* }}} int lua_config */
575 static int lua_shutdown(void) /* {{{ */
577 lua_script_free(scripts);
580 } /* }}} int lua_shutdown */
582 void module_register(void) {
583 plugin_register_complex_config("lua", lua_config);
584 plugin_register_shutdown("lua", lua_shutdown);