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");
263 char identifier[6 * DATA_MAX_NAME_LEN];
264 FORMAT_VL(identifier, sizeof(identifier), vl);
266 DEBUG("Lua plugin: collectd.dispatch_values(): Received value list \"%s\", "
267 "time %.3f, interval %.3f.",
268 identifier, CDTIME_T_TO_DOUBLE(vl->time),
269 CDTIME_T_TO_DOUBLE(vl->interval));
271 plugin_dispatch_values(vl);
276 } /* }}} lua_cb_dispatch_values */
278 static int lua_cb_register_read(lua_State *L) /* {{{ */
280 int nargs = lua_gettop(L);
283 return luaL_error(L, "Invalid number of arguments (%d != 1)", nargs);
285 luaL_checktype(L, 1, LUA_TFUNCTION);
287 char function_name[DATA_MAX_NAME_LEN];
288 ssnprintf(function_name, sizeof(function_name), "lua/%s", lua_tostring(L, 1));
290 int callback_id = clua_store_callback(L, 1);
292 return luaL_error(L, "%s", "Storing callback function failed");
294 lua_State *thread = lua_newthread(L);
296 return luaL_error(L, "%s", "lua_newthread failed");
297 clua_store_thread(L, -1);
300 clua_callback_data_t *cb = calloc(1, sizeof(*cb));
302 return luaL_error(L, "%s", "calloc failed");
304 cb->lua_state = thread;
305 cb->callback_id = callback_id;
306 cb->lua_function_name = strdup(function_name);
307 pthread_mutex_init(&cb->lock, NULL);
313 int status = plugin_register_complex_read(/* group = */ "lua",
314 /* name = */ function_name,
315 /* callback = */ clua_read,
317 /* user_data = */ &ud);
320 return luaL_error(L, "%s", "plugin_register_complex_read failed");
322 } /* }}} int lua_cb_register_read */
324 static int lua_cb_register_write(lua_State *L) /* {{{ */
326 int nargs = lua_gettop(L);
329 return luaL_error(L, "Invalid number of arguments (%d != 1)", nargs);
331 luaL_checktype(L, 1, LUA_TFUNCTION);
333 char function_name[DATA_MAX_NAME_LEN] = "";
334 ssnprintf(function_name, sizeof(function_name), "lua/%s", lua_tostring(L, 1));
336 int callback_id = clua_store_callback(L, 1);
338 return luaL_error(L, "%s", "Storing callback function failed");
340 lua_State *thread = lua_newthread(L);
342 return luaL_error(L, "%s", "lua_newthread failed");
343 clua_store_thread(L, -1);
346 clua_callback_data_t *cb = calloc(1, sizeof(*cb));
348 return luaL_error(L, "%s", "calloc failed");
350 cb->lua_state = thread;
351 cb->callback_id = callback_id;
352 cb->lua_function_name = strdup(function_name);
353 pthread_mutex_init(&cb->lock, NULL);
359 int status = plugin_register_write(/* name = */ function_name,
360 /* callback = */ clua_write,
361 /* user_data = */ &ud);
364 return luaL_error(L, "%s", "plugin_register_write failed");
366 } /* }}} int lua_cb_register_write */
368 static lua_c_function_t lua_c_functions[] = {
369 {"log_debug", lua_cb_log_debug},
370 {"log_error", lua_cb_log_error},
371 {"log_info", lua_cb_log_info},
372 {"log_notice", lua_cb_log_notice},
373 {"log_warning", lua_cb_log_warning},
374 {"dispatch_values", lua_cb_dispatch_values},
375 {"register_read", lua_cb_register_read},
376 {"register_write", lua_cb_register_write}};
378 static void lua_script_free(lua_script_t *script) /* {{{ */
383 lua_script_t *next = script->next;
385 if (script->lua_state != NULL) {
386 lua_close(script->lua_state);
387 script->lua_state = NULL;
390 sfree(script->script_path);
393 lua_script_free(next);
394 } /* }}} void lua_script_free */
396 static int lua_script_init(lua_script_t *script) /* {{{ */
398 memset(script, 0, sizeof(*script));
400 /* initialize the lua context */
401 script->lua_state = luaL_newstate();
402 if (script->lua_state == NULL) {
403 ERROR("Lua plugin: luaL_newstate() failed.");
407 /* Open up all the standard Lua libraries. */
408 luaL_openlibs(script->lua_state);
410 /* Register all the functions we implement in C */
411 lua_newtable(script->lua_state);
412 for (size_t i = 0; i < STATIC_ARRAY_SIZE(lua_c_functions); i++) {
413 lua_pushcfunction(script->lua_state, lua_c_functions[i].func);
414 lua_setfield(script->lua_state, -2, lua_c_functions[i].name);
416 lua_setglobal(script->lua_state, "collectd");
418 /* Prepend BasePath to package.path */
419 if (base_path[0] != '\0') {
420 lua_getglobal(script->lua_state, "package");
421 lua_getfield(script->lua_state, -1, "path");
423 const char *cur_path = lua_tostring(script->lua_state, -1);
424 char *new_path = ssnprintf_alloc("%s/?.lua;%s", base_path, cur_path);
426 lua_pop(script->lua_state, 1);
427 lua_pushstring(script->lua_state, new_path);
431 lua_setfield(script->lua_state, -2, "path");
432 lua_pop(script->lua_state, 1);
436 } /* }}} int lua_script_init */
438 static int lua_script_load(const char *script_path) /* {{{ */
440 lua_script_t *script = malloc(sizeof(*script));
441 if (script == NULL) {
442 ERROR("Lua plugin: malloc failed.");
446 int status = lua_script_init(script);
448 lua_script_free(script);
452 script->script_path = strdup(script_path);
453 if (script->script_path == NULL) {
454 ERROR("Lua plugin: strdup failed.");
455 lua_script_free(script);
459 status = luaL_loadfile(script->lua_state, script->script_path);
461 ERROR("Lua plugin: luaL_loadfile failed: %s",
462 lua_tostring(script->lua_state, -1));
463 lua_pop(script->lua_state, 1);
464 lua_script_free(script);
468 status = lua_pcall(script->lua_state,
470 /* nresults = */ LUA_MULTRET,
473 const char *errmsg = lua_tostring(script->lua_state, -1);
476 ERROR("Lua plugin: lua_pcall failed with status %i. "
477 "In addition, no error message could be retrieved from the stack.",
480 ERROR("Lua plugin: Executing script \"%s\" failed:\n%s",
481 script->script_path, errmsg);
483 lua_script_free(script);
487 /* Append this script to the global list of scripts. */
489 lua_script_t *last = scripts;
499 } /* }}} int lua_script_load */
501 static int lua_config_base_path(const oconfig_item_t *ci) /* {{{ */
503 int status = cf_util_get_string_buffer(ci, base_path, sizeof(base_path));
507 size_t len = strlen(base_path);
508 while ((len > 0) && (base_path[len - 1] == '/')) {
510 base_path[len] = '\0';
513 DEBUG("Lua plugin: base_path = \"%s\";", base_path);
516 } /* }}} int lua_config_base_path */
518 static int lua_config_script(const oconfig_item_t *ci) /* {{{ */
520 char rel_path[PATH_MAX];
522 int status = cf_util_get_string_buffer(ci, rel_path, sizeof(rel_path));
526 char abs_path[PATH_MAX];
528 if (base_path[0] == '\0')
529 sstrncpy(abs_path, rel_path, sizeof(abs_path));
531 ssnprintf(abs_path, sizeof(abs_path), "%s/%s", base_path, rel_path);
533 DEBUG("Lua plugin: abs_path = \"%s\";", abs_path);
535 status = lua_script_load(abs_path);
539 INFO("Lua plugin: File \"%s\" loaded succesfully", abs_path);
542 } /* }}} int lua_config_script */
547 * Script "script1.lua"
548 * Script "script2.lua"
551 static int lua_config(oconfig_item_t *ci) /* {{{ */
554 for (int i = 0; i < ci->children_num; i++) {
555 oconfig_item_t *child = ci->children + i;
557 if (strcasecmp("BasePath", child->key) == 0) {
558 status = lua_config_base_path(child);
559 } else if (strcasecmp("Script", child->key) == 0) {
560 status = lua_config_script(child);
562 ERROR("Lua plugin: Option `%s' is not allowed here.", child->key);
568 } /* }}} int lua_config */
570 static int lua_shutdown(void) /* {{{ */
572 lua_script_free(scripts);
575 } /* }}} int lua_shutdown */
577 void module_register() {
578 plugin_register_complex_config("lua", lua_config);
579 plugin_register_shutdown("lua", lua_shutdown);
582 /* vim: set sw=2 sts=2 et fdm=marker : */