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>
33 #include "utils/common/common.h"
34 #include "utils_lua.h"
36 /* Include the Lua API header files. */
44 #define PLUGIN_WRITE 2
46 typedef struct lua_script_s {
48 struct lua_script_s *next;
53 char *lua_function_name;
56 } clua_callback_data_t;
58 static char base_path[PATH_MAX];
59 static lua_script_t *scripts;
61 static int clua_store_callback(lua_State *L, int idx) /* {{{ */
63 /* Copy the function pointer */
64 lua_pushvalue(L, idx);
66 return luaL_ref(L, LUA_REGISTRYINDEX);
67 } /* }}} int clua_store_callback */
69 static int clua_load_callback(lua_State *L, int callback_ref) /* {{{ */
71 lua_rawgeti(L, LUA_REGISTRYINDEX, callback_ref);
73 if (!lua_isfunction(L, -1)) {
79 } /* }}} int clua_load_callback */
81 /* Store the threads in a global variable so they are not cleaned up by the
82 * garbage collector. */
83 static int clua_store_thread(lua_State *L, int idx) /* {{{ */
85 if (!lua_isthread(L, idx)) {
89 /* Copy the thread pointer */
90 lua_pushvalue(L, idx);
92 luaL_ref(L, LUA_REGISTRYINDEX);
94 } /* }}} int clua_store_thread */
96 static int clua_read(user_data_t *ud) /* {{{ */
98 clua_callback_data_t *cb = ud->data;
100 pthread_mutex_lock(&cb->lock);
102 lua_State *L = cb->lua_state;
104 int status = clua_load_callback(L, cb->callback_id);
106 ERROR("Lua plugin: Unable to load callback \"%s\" (id %i).",
107 cb->lua_function_name, cb->callback_id);
108 pthread_mutex_unlock(&cb->lock);
113 status = lua_pcall(L, 0, 1, 0);
115 const char *errmsg = lua_tostring(L, -1);
117 ERROR("Lua plugin: Calling a read callback failed. "
118 "In addition, retrieving the error message failed.");
120 ERROR("Lua plugin: Calling a read callback failed: %s", errmsg);
122 pthread_mutex_unlock(&cb->lock);
126 if (!lua_isnumber(L, -1)) {
127 ERROR("Lua plugin: Read function \"%s\" (id %i) did not return a numeric "
129 cb->lua_function_name, cb->callback_id);
132 status = (int)lua_tointeger(L, -1);
135 /* pop return value and function */
136 lua_pop(L, 1); /* -1 = 0 */
138 pthread_mutex_unlock(&cb->lock);
140 } /* }}} int clua_read */
142 static int clua_write(const data_set_t *ds, const value_list_t *vl, /* {{{ */
144 clua_callback_data_t *cb = ud->data;
146 pthread_mutex_lock(&cb->lock);
148 lua_State *L = cb->lua_state;
150 int status = clua_load_callback(L, cb->callback_id);
152 ERROR("Lua plugin: Unable to load callback \"%s\" (id %i).",
153 cb->lua_function_name, cb->callback_id);
154 pthread_mutex_unlock(&cb->lock);
159 status = luaC_pushvaluelist(L, ds, vl);
161 lua_pop(L, 1); /* -1 = 0 */
162 pthread_mutex_unlock(&cb->lock);
163 ERROR("Lua plugin: luaC_pushvaluelist failed.");
168 status = lua_pcall(L, 1, 1, 0); /* -2+1 = 1 */
170 const char *errmsg = lua_tostring(L, -1);
172 ERROR("Lua plugin: Calling the write callback failed. "
173 "In addition, retrieving the error message failed.");
175 ERROR("Lua plugin: Calling the write callback failed:\n%s", errmsg);
176 lua_pop(L, 1); /* -1 = 0 */
177 pthread_mutex_unlock(&cb->lock);
181 if (!lua_isnumber(L, -1)) {
182 ERROR("Lua plugin: Write function \"%s\" (id %i) did not return a numeric "
184 cb->lua_function_name, cb->callback_id);
187 status = (int)lua_tointeger(L, -1);
190 lua_pop(L, 1); /* -1 = 0 */
191 pthread_mutex_unlock(&cb->lock);
193 } /* }}} int clua_write */
199 static int lua_cb_log_debug(lua_State *L) /* {{{ */
201 const char *msg = luaL_checkstring(L, 1);
202 plugin_log(LOG_DEBUG, "%s", msg);
204 } /* }}} int lua_cb_log_debug */
206 static int lua_cb_log_error(lua_State *L) /* {{{ */
208 const char *msg = luaL_checkstring(L, 1);
209 plugin_log(LOG_ERR, "%s", msg);
211 } /* }}} int lua_cb_log_error */
213 static int lua_cb_log_info(lua_State *L) /* {{{ */
215 const char *msg = luaL_checkstring(L, 1);
216 plugin_log(LOG_INFO, "%s", msg);
218 } /* }}} int lua_cb_log_info */
220 static int lua_cb_log_notice(lua_State *L) /* {{{ */
222 const char *msg = luaL_checkstring(L, 1);
223 plugin_log(LOG_NOTICE, "%s", msg);
225 } /* }}} int lua_cb_log_notice */
227 static int lua_cb_log_warning(lua_State *L) /* {{{ */
229 const char *msg = luaL_checkstring(L, 1);
230 plugin_log(LOG_WARNING, "%s", msg);
232 } /* }}} int lua_cb_log_warning */
234 static int lua_cb_dispatch_values(lua_State *L) /* {{{ */
236 int nargs = lua_gettop(L);
239 return luaL_error(L, "Invalid number of arguments (%d != 1)", nargs);
241 luaL_checktype(L, 1, LUA_TTABLE);
243 value_list_t *vl = luaC_tovaluelist(L, -1);
245 return luaL_error(L, "%s", "luaC_tovaluelist failed");
248 char identifier[6 * DATA_MAX_NAME_LEN];
249 FORMAT_VL(identifier, sizeof(identifier), vl);
251 DEBUG("Lua plugin: collectd.dispatch_values(): Received value list \"%s\", "
252 "time %.3f, interval %.3f.",
253 identifier, CDTIME_T_TO_DOUBLE(vl->time),
254 CDTIME_T_TO_DOUBLE(vl->interval));
257 plugin_dispatch_values(vl);
262 } /* }}} lua_cb_dispatch_values */
264 static void lua_cb_free(void *data) {
265 clua_callback_data_t *cb = data;
266 free(cb->lua_function_name);
267 pthread_mutex_destroy(&cb->lock);
271 static int lua_cb_register_generic(lua_State *L, int type) /* {{{ */
273 int nargs = lua_gettop(L);
276 return luaL_error(L, "Invalid number of arguments (%d != 1)", nargs);
278 char subname[DATA_MAX_NAME_LEN];
279 if (!lua_isfunction(L, 1) && lua_isstring(L, 1)) {
280 const char *fname = lua_tostring(L, 1);
281 ssnprintf(subname, sizeof(subname), "%s()", fname);
283 lua_getglobal(L, fname); // Push function into stack
284 lua_remove(L, 1); // Remove string from stack
285 if (!lua_isfunction(L, -1)) {
286 return luaL_error(L, "Unable to find function '%s'", fname);
289 lua_getfield(L, LUA_REGISTRYINDEX, "collectd:callback_num");
290 int tmp = lua_tointeger(L, -1);
291 ssnprintf(subname, sizeof(subname), "callback_%d", tmp);
292 lua_pop(L, 1); // Remove old value from stack
293 lua_pushinteger(L, tmp + 1);
294 lua_setfield(L, LUA_REGISTRYINDEX, "collectd:callback_num"); // pops value
297 luaL_checktype(L, 1, LUA_TFUNCTION);
299 lua_getfield(L, LUA_REGISTRYINDEX, "collectd:script_path");
300 char function_name[DATA_MAX_NAME_LEN];
301 ssnprintf(function_name, sizeof(function_name), "lua/%s/%s",
302 lua_tostring(L, -1), subname);
305 int callback_id = clua_store_callback(L, 1);
307 return luaL_error(L, "%s", "Storing callback function failed");
309 lua_State *thread = lua_newthread(L);
311 return luaL_error(L, "%s", "lua_newthread failed");
312 clua_store_thread(L, -1);
315 clua_callback_data_t *cb = calloc(1, sizeof(*cb));
317 return luaL_error(L, "%s", "calloc failed");
319 cb->lua_state = thread;
320 cb->callback_id = callback_id;
321 cb->lua_function_name = strdup(function_name);
322 pthread_mutex_init(&cb->lock, NULL);
324 if (PLUGIN_READ == type) {
325 int status = plugin_register_complex_read(/* group = */ "lua",
326 /* name = */ function_name,
327 /* callback = */ clua_read,
331 .free_func = lua_cb_free,
335 return luaL_error(L, "%s", "plugin_register_complex_read failed");
337 } else if (PLUGIN_WRITE == type) {
338 int status = plugin_register_write(/* name = */ function_name,
339 /* callback = */ clua_write,
342 .free_func = lua_cb_free,
346 return luaL_error(L, "%s", "plugin_register_write failed");
349 return luaL_error(L, "%s", "lua_cb_register_generic unsupported type");
351 } /* }}} int lua_cb_register_generic */
353 static int lua_cb_register_read(lua_State *L) {
354 return lua_cb_register_generic(L, PLUGIN_READ);
357 static int lua_cb_register_write(lua_State *L) {
358 return lua_cb_register_generic(L, PLUGIN_WRITE);
361 static const luaL_Reg collectdlib[] = {
362 {"log_debug", lua_cb_log_debug},
363 {"log_error", lua_cb_log_error},
364 {"log_info", lua_cb_log_info},
365 {"log_notice", lua_cb_log_notice},
366 {"log_warning", lua_cb_log_warning},
367 {"dispatch_values", lua_cb_dispatch_values},
368 {"register_read", lua_cb_register_read},
369 {"register_write", lua_cb_register_write},
372 static int open_collectd(lua_State *L) /* {{{ */
374 #if LUA_VERSION_NUM < 502
375 luaL_register(L, "collectd", collectdlib);
377 luaL_newlib(L, collectdlib);
382 static void lua_script_free(lua_script_t *script) /* {{{ */
387 lua_script_t *next = script->next;
389 if (script->lua_state != NULL) {
390 lua_close(script->lua_state);
391 script->lua_state = NULL;
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 status = luaL_loadfile(script->lua_state, script_path);
459 ERROR("Lua plugin: luaL_loadfile failed: %s",
460 lua_tostring(script->lua_state, -1));
461 lua_pop(script->lua_state, 1);
462 lua_script_free(script);
466 lua_pushstring(script->lua_state, script_path);
467 lua_setfield(script->lua_state, LUA_REGISTRYINDEX, "collectd:script_path");
468 lua_pushinteger(script->lua_state, 0);
469 lua_setfield(script->lua_state, LUA_REGISTRYINDEX, "collectd:callback_num");
471 status = lua_pcall(script->lua_state,
473 /* nresults = */ LUA_MULTRET,
476 const char *errmsg = lua_tostring(script->lua_state, -1);
479 ERROR("Lua plugin: lua_pcall failed with status %i. "
480 "In addition, no error message could be retrieved from the stack.",
483 ERROR("Lua plugin: Executing script \"%s\" failed: %s", script_path,
487 /* Append this script to the global list of scripts. */
489 lua_script_t *last = scripts;
502 } /* }}} int lua_script_load */
504 static int lua_config_base_path(const oconfig_item_t *ci) /* {{{ */
506 int status = cf_util_get_string_buffer(ci, base_path, sizeof(base_path));
510 size_t len = strlen(base_path);
511 while ((len > 0) && (base_path[len - 1] == '/')) {
513 base_path[len] = '\0';
516 DEBUG("Lua plugin: base_path = \"%s\";", base_path);
519 } /* }}} int lua_config_base_path */
521 static int lua_config_script(const oconfig_item_t *ci) /* {{{ */
523 char rel_path[PATH_MAX];
525 int status = cf_util_get_string_buffer(ci, rel_path, sizeof(rel_path));
529 char abs_path[PATH_MAX];
531 if (base_path[0] == '\0')
532 sstrncpy(abs_path, rel_path, sizeof(abs_path));
534 ssnprintf(abs_path, sizeof(abs_path), "%s/%s", base_path, rel_path);
536 DEBUG("Lua plugin: abs_path = \"%s\";", abs_path);
538 status = lua_script_load(abs_path);
542 INFO("Lua plugin: File \"%s\" loaded successfully", abs_path);
545 } /* }}} int lua_config_script */
550 * Script "script1.lua"
551 * Script "script2.lua"
554 static int lua_config(oconfig_item_t *ci) /* {{{ */
557 for (int i = 0; i < ci->children_num; i++) {
558 oconfig_item_t *child = ci->children + i;
560 if (strcasecmp("BasePath", child->key) == 0) {
561 status = lua_config_base_path(child);
562 } else if (strcasecmp("Script", child->key) == 0) {
563 status = lua_config_script(child);
565 ERROR("Lua plugin: Option `%s' is not allowed here.", child->key);
571 } /* }}} int lua_config */
573 static int lua_shutdown(void) /* {{{ */
575 lua_script_free(scripts);
578 } /* }}} int lua_shutdown */
580 void module_register(void) {
581 plugin_register_complex_config("lua", lua_config);
582 plugin_register_shutdown("lua", lua_shutdown);