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. */
40 #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;
70 static char base_path[PATH_MAX];
71 static lua_script_t *scripts;
73 static int clua_store_callback(lua_State *L, int idx) /* {{{ */
75 /* Copy the function pointer */
76 lua_pushvalue(L, idx);
78 return luaL_ref(L, LUA_REGISTRYINDEX);
79 } /* }}} int clua_store_callback */
81 static int clua_load_callback(lua_State *L, int callback_ref) /* {{{ */
83 lua_rawgeti(L, LUA_REGISTRYINDEX, callback_ref);
85 if (!lua_isfunction(L, -1)) {
91 } /* }}} int clua_load_callback */
93 /* Store the threads in a global variable so they are not cleaned up by the
94 * garbage collector. */
95 static int clua_store_thread(lua_State *L, int idx) /* {{{ */
98 idx += lua_gettop(L) + 1;
100 /* Copy the thread pointer */
101 lua_pushvalue(L, idx); /* +1 = 3 */
102 if (!lua_isthread(L, -1)) {
103 lua_pop(L, 3); /* -3 = 0 */
107 luaL_ref(L, LUA_REGISTRYINDEX);
108 lua_pop(L, 1); /* -1 = 0 */
110 } /* }}} int clua_store_thread */
112 static int clua_read(user_data_t *ud) /* {{{ */
114 clua_callback_data_t *cb = ud->data;
116 pthread_mutex_lock(&cb->lock);
118 lua_State *L = cb->lua_state;
120 int status = clua_load_callback(L, cb->callback_id);
122 ERROR("Lua plugin: Unable to load callback \"%s\" (id %i).",
123 cb->lua_function_name, cb->callback_id);
124 pthread_mutex_unlock(&cb->lock);
129 status = lua_pcall(L, 0, 1, 0);
131 const char *errmsg = lua_tostring(L, -1);
133 ERROR("Lua plugin: Calling a read callback failed. "
134 "In addition, retrieving the error message failed.");
136 ERROR("Lua plugin: Calling a read callback failed: %s", errmsg);
138 pthread_mutex_unlock(&cb->lock);
142 if (!lua_isnumber(L, -1)) {
143 ERROR("Lua plugin: Read function \"%s\" (id %i) did not return a numeric "
145 cb->lua_function_name, cb->callback_id);
148 status = (int)lua_tointeger(L, -1);
151 /* pop return value and function */
152 lua_pop(L, 1); /* -1 = 0 */
154 pthread_mutex_unlock(&cb->lock);
156 } /* }}} int clua_read */
158 static int clua_write(const data_set_t *ds, const value_list_t *vl, /* {{{ */
160 clua_callback_data_t *cb = ud->data;
162 pthread_mutex_lock(&cb->lock);
164 lua_State *L = cb->lua_state;
166 int status = clua_load_callback(L, cb->callback_id);
168 ERROR("Lua plugin: Unable to load callback \"%s\" (id %i).",
169 cb->lua_function_name, cb->callback_id);
170 pthread_mutex_unlock(&cb->lock);
175 status = luaC_pushvaluelist(L, ds, vl);
177 lua_pop(L, 1); /* -1 = 0 */
178 pthread_mutex_unlock(&cb->lock);
179 ERROR("Lua plugin: luaC_pushvaluelist failed.");
184 status = lua_pcall(L, 1, 1, 0); /* -2+1 = 1 */
186 const char *errmsg = lua_tostring(L, -1);
188 ERROR("Lua plugin: Calling the write callback failed. "
189 "In addition, retrieving the error message failed.");
191 ERROR("Lua plugin: Calling the write callback failed:\n%s", errmsg);
192 lua_pop(L, 1); /* -1 = 0 */
193 pthread_mutex_unlock(&cb->lock);
197 if (!lua_isnumber(L, -1)) {
198 ERROR("Lua plugin: Write function \"%s\" (id %i) did not return a numeric "
200 cb->lua_function_name, cb->callback_id);
203 status = (int)lua_tointeger(L, -1);
206 lua_pop(L, 1); /* -1 = 0 */
207 pthread_mutex_unlock(&cb->lock);
209 } /* }}} int clua_write */
215 static int lua_cb_log_debug(lua_State *L) /* {{{ */
217 const char *msg = luaL_checkstring(L, 1);
218 plugin_log(LOG_DEBUG, "%s", msg);
220 } /* }}} int lua_cb_log_debug */
222 static int lua_cb_log_error(lua_State *L) /* {{{ */
224 const char *msg = luaL_checkstring(L, 1);
225 plugin_log(LOG_ERR, "%s", msg);
227 } /* }}} int lua_cb_log_error */
229 static int lua_cb_log_info(lua_State *L) /* {{{ */
231 const char *msg = luaL_checkstring(L, 1);
232 plugin_log(LOG_INFO, "%s", msg);
234 } /* }}} int lua_cb_log_info */
236 static int lua_cb_log_notice(lua_State *L) /* {{{ */
238 const char *msg = luaL_checkstring(L, 1);
239 plugin_log(LOG_NOTICE, "%s", msg);
241 } /* }}} int lua_cb_log_notice */
243 static int lua_cb_log_warning(lua_State *L) /* {{{ */
245 const char *msg = luaL_checkstring(L, 1);
246 plugin_log(LOG_WARNING, "%s", msg);
248 } /* }}} int lua_cb_log_warning */
250 static int lua_cb_dispatch_values(lua_State *L) /* {{{ */
252 int nargs = lua_gettop(L);
255 return luaL_error(L, "Invalid number of arguments (%d != 1)", nargs);
257 luaL_checktype(L, 1, LUA_TTABLE);
259 value_list_t *vl = luaC_tovaluelist(L, -1);
261 return luaL_error(L, "%s", "luaC_tovaluelist failed");
264 char identifier[6 * DATA_MAX_NAME_LEN];
265 FORMAT_VL(identifier, sizeof(identifier), vl);
267 DEBUG("Lua plugin: collectd.dispatch_values(): Received value list \"%s\", "
268 "time %.3f, interval %.3f.",
269 identifier, CDTIME_T_TO_DOUBLE(vl->time),
270 CDTIME_T_TO_DOUBLE(vl->interval));
273 plugin_dispatch_values(vl);
278 } /* }}} lua_cb_dispatch_values */
280 static int lua_cb_register_read(lua_State *L) /* {{{ */
282 int nargs = lua_gettop(L);
285 return luaL_error(L, "Invalid number of arguments (%d != 1)", nargs);
287 luaL_checktype(L, 1, LUA_TFUNCTION);
289 char function_name[DATA_MAX_NAME_LEN];
290 ssnprintf(function_name, sizeof(function_name), "lua/%s", lua_tostring(L, 1));
292 int callback_id = clua_store_callback(L, 1);
294 return luaL_error(L, "%s", "Storing callback function failed");
296 lua_State *thread = lua_newthread(L);
298 return luaL_error(L, "%s", "lua_newthread failed");
299 clua_store_thread(L, -1);
302 clua_callback_data_t *cb = calloc(1, sizeof(*cb));
304 return luaL_error(L, "%s", "calloc failed");
306 cb->lua_state = thread;
307 cb->callback_id = callback_id;
308 cb->lua_function_name = strdup(function_name);
309 pthread_mutex_init(&cb->lock, NULL);
315 int status = plugin_register_complex_read(/* group = */ "lua",
316 /* name = */ function_name,
317 /* callback = */ clua_read,
319 /* user_data = */ &ud);
322 return luaL_error(L, "%s", "plugin_register_complex_read failed");
324 } /* }}} int lua_cb_register_read */
326 static int lua_cb_register_write(lua_State *L) /* {{{ */
328 int nargs = lua_gettop(L);
331 return luaL_error(L, "Invalid number of arguments (%d != 1)", nargs);
333 luaL_checktype(L, 1, LUA_TFUNCTION);
335 char function_name[DATA_MAX_NAME_LEN] = "";
336 ssnprintf(function_name, sizeof(function_name), "lua/%s", lua_tostring(L, 1));
338 int callback_id = clua_store_callback(L, 1);
340 return luaL_error(L, "%s", "Storing callback function failed");
342 lua_State *thread = lua_newthread(L);
344 return luaL_error(L, "%s", "lua_newthread failed");
345 clua_store_thread(L, -1);
348 clua_callback_data_t *cb = calloc(1, sizeof(*cb));
350 return luaL_error(L, "%s", "calloc failed");
352 cb->lua_state = thread;
353 cb->callback_id = callback_id;
354 cb->lua_function_name = strdup(function_name);
355 pthread_mutex_init(&cb->lock, NULL);
361 int status = plugin_register_write(/* name = */ function_name,
362 /* callback = */ clua_write,
363 /* user_data = */ &ud);
366 return luaL_error(L, "%s", "plugin_register_write failed");
368 } /* }}} int lua_cb_register_write */
370 static lua_c_function_t lua_c_functions[] = {
371 {"log_debug", lua_cb_log_debug},
372 {"log_error", lua_cb_log_error},
373 {"log_info", lua_cb_log_info},
374 {"log_notice", lua_cb_log_notice},
375 {"log_warning", lua_cb_log_warning},
376 {"dispatch_values", lua_cb_dispatch_values},
377 {"register_read", lua_cb_register_read},
378 {"register_write", lua_cb_register_write}};
380 static void lua_script_free(lua_script_t *script) /* {{{ */
385 lua_script_t *next = script->next;
387 if (script->lua_state != NULL) {
388 lua_close(script->lua_state);
389 script->lua_state = NULL;
392 sfree(script->script_path);
395 lua_script_free(next);
396 } /* }}} void lua_script_free */
398 static int lua_script_init(lua_script_t *script) /* {{{ */
400 memset(script, 0, sizeof(*script));
402 /* initialize the lua context */
403 script->lua_state = luaL_newstate();
404 if (script->lua_state == NULL) {
405 ERROR("Lua plugin: luaL_newstate() failed.");
409 /* Open up all the standard Lua libraries. */
410 luaL_openlibs(script->lua_state);
412 /* Register all the functions we implement in C */
413 lua_newtable(script->lua_state);
414 for (size_t i = 0; i < STATIC_ARRAY_SIZE(lua_c_functions); i++) {
415 lua_pushcfunction(script->lua_state, lua_c_functions[i].func);
416 lua_setfield(script->lua_state, -2, lua_c_functions[i].name);
418 lua_setglobal(script->lua_state, "collectd");
420 /* Prepend BasePath to package.path */
421 if (base_path[0] != '\0') {
422 lua_getglobal(script->lua_state, "package");
423 lua_getfield(script->lua_state, -1, "path");
425 const char *cur_path = lua_tostring(script->lua_state, -1);
426 char *new_path = ssnprintf_alloc("%s/?.lua;%s", base_path, cur_path);
428 lua_pop(script->lua_state, 1);
429 lua_pushstring(script->lua_state, new_path);
433 lua_setfield(script->lua_state, -2, "path");
434 lua_pop(script->lua_state, 1);
438 } /* }}} int lua_script_init */
440 static int lua_script_load(const char *script_path) /* {{{ */
442 lua_script_t *script = malloc(sizeof(*script));
443 if (script == NULL) {
444 ERROR("Lua plugin: malloc failed.");
448 int status = lua_script_init(script);
450 lua_script_free(script);
454 script->script_path = strdup(script_path);
455 if (script->script_path == NULL) {
456 ERROR("Lua plugin: strdup failed.");
457 lua_script_free(script);
461 status = luaL_loadfile(script->lua_state, script->script_path);
463 ERROR("Lua plugin: luaL_loadfile failed: %s",
464 lua_tostring(script->lua_state, -1));
465 lua_pop(script->lua_state, 1);
466 lua_script_free(script);
470 status = lua_pcall(script->lua_state,
472 /* nresults = */ LUA_MULTRET,
475 const char *errmsg = lua_tostring(script->lua_state, -1);
478 ERROR("Lua plugin: lua_pcall failed with status %i. "
479 "In addition, no error message could be retrieved from the stack.",
482 ERROR("Lua plugin: Executing script \"%s\" failed:\n%s",
483 script->script_path, errmsg);
485 lua_script_free(script);
489 /* Append this script to the global list of scripts. */
491 lua_script_t *last = scripts;
501 } /* }}} int lua_script_load */
503 static int lua_config_base_path(const oconfig_item_t *ci) /* {{{ */
505 int status = cf_util_get_string_buffer(ci, base_path, sizeof(base_path));
509 size_t len = strlen(base_path);
510 while ((len > 0) && (base_path[len - 1] == '/')) {
512 base_path[len] = '\0';
515 DEBUG("Lua plugin: base_path = \"%s\";", base_path);
518 } /* }}} int lua_config_base_path */
520 static int lua_config_script(const oconfig_item_t *ci) /* {{{ */
522 char rel_path[PATH_MAX];
524 int status = cf_util_get_string_buffer(ci, rel_path, sizeof(rel_path));
528 char abs_path[PATH_MAX];
530 if (base_path[0] == '\0')
531 sstrncpy(abs_path, rel_path, sizeof(abs_path));
533 ssnprintf(abs_path, sizeof(abs_path), "%s/%s", base_path, rel_path);
535 DEBUG("Lua plugin: abs_path = \"%s\";", abs_path);
537 status = lua_script_load(abs_path);
541 INFO("Lua plugin: File \"%s\" loaded succesfully", abs_path);
544 } /* }}} int lua_config_script */
549 * Script "script1.lua"
550 * Script "script2.lua"
553 static int lua_config(oconfig_item_t *ci) /* {{{ */
556 for (int i = 0; i < ci->children_num; i++) {
557 oconfig_item_t *child = ci->children + i;
559 if (strcasecmp("BasePath", child->key) == 0) {
560 status = lua_config_base_path(child);
561 } else if (strcasecmp("Script", child->key) == 0) {
562 status = lua_config_script(child);
564 ERROR("Lua plugin: Option `%s' is not allowed here.", child->key);
570 } /* }}} int lua_config */
572 static int lua_shutdown(void) /* {{{ */
574 lua_script_free(scripts);
577 } /* }}} int lua_shutdown */
579 void module_register() {
580 plugin_register_complex_config("lua", lua_config);
581 plugin_register_shutdown("lua", lua_shutdown);
584 /* vim: set sw=2 sts=2 et fdm=marker : */