1 /* Copyright (c) 2010. The SimGrid Team.
2 * All rights reserved. */
4 /* This program is free software; you can redistribute it and/or modify it
5 * under the terms of the license (GNU LGPL) which comes with this package. */
7 /* SimGrid Lua bindings */
9 #include "simgrid_lua.h"
10 #include "lua_state_cloner.h"
11 #include "lua_utils.h"
13 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(lua, bindings, "Lua Bindings");
15 #define TASK_MODULE_NAME "simgrid.Task"
16 #define HOST_MODULE_NAME "simgrid.Host"
18 #define LINK_MODULE_NAME "simgrid.Link"
19 #define ROUTE_MODULE_NAME "simgrid.Route"
20 #define PLATF_MODULE_NAME "simgrid.platf"
22 static lua_State* sglua_maestro_state;
24 static void register_c_functions(lua_State *L);
27 * \brief Like luaL_checkudata, with additional debug logs.
28 * \param L a lua state
29 * \param ud index of the userdata to check in the stack
30 * \param tname key of the metatable of this userdata in the registry
32 static void* my_checkudata(lua_State* L, int ud, const char* tname) {
34 XBT_DEBUG("Checking the userdata: ud = %d", ud);
35 sglua_stack_dump("my_checkudata: ", L);
36 void* p = lua_touserdata(L, ud);
37 lua_getfield(L, LUA_REGISTRYINDEX, tname);
38 const void* correct_mt = lua_topointer(L, -1);
40 int has_mt = lua_getmetatable(L, ud);
41 XBT_DEBUG("Checking the userdata: has metatable ? %d", has_mt);
42 const void* actual_mt = NULL;
44 actual_mt = lua_topointer(L, -1);
47 XBT_DEBUG("Checking the task's metatable: expected %p, found %p", correct_mt, actual_mt);
48 sglua_stack_dump("my_checkudata: ", L);
50 if (p == NULL || !lua_getmetatable(L, ud) || !lua_rawequal(L, -1, -2))
51 luaL_typerror(L, ud, tname);
57 * @brief Ensures that a value is a valid task and returns it.
58 * @param L a Lua state
59 * @param index an index in the Lua stack
60 * @return the task at this index
62 static m_task_t checkTask(lua_State* L, int index)
64 sglua_stack_dump("checkTask: ", L);
65 luaL_checktype(L, index, LUA_TTABLE);
67 lua_getfield(L, index, "__simgrid_task");
68 /* ... task ... ctask */
69 m_task_t task = *((m_task_t*) luaL_checkudata(L, -1, TASK_MODULE_NAME));
74 luaL_error(L, "This task was sent to someone else, you cannot access it anymore");
80 /* ********************************************************************************* */
81 /* wrapper functions */
82 /* ********************************************************************************* */
85 * \brief Creates a new task and leaves it onto the stack.
88 * - task name (string)
89 * - computation size (integer)
90 * - communication size (integer)
92 static int Task_new(lua_State* L)
94 XBT_DEBUG("Task new");
95 const char* name = luaL_checkstring(L, 1);
96 int comp_size = luaL_checkint(L, 2);
97 int msg_size = luaL_checkint(L, 3);
101 m_task_t msg_task = MSG_task_create(name, comp_size, msg_size, NULL);
105 m_task_t* lua_task = (m_task_t*) lua_newuserdata(L, sizeof(m_task_t));
107 *lua_task = msg_task;
108 luaL_getmetatable(L, TASK_MODULE_NAME);
110 lua_setmetatable(L, -2);
112 lua_setfield(L, -2, "__simgrid_task");
117 static int Task_get_name(lua_State* L)
119 m_task_t task = checkTask(L, 1);
120 lua_pushstring(L, MSG_task_get_name(task));
124 static int Task_computation_duration(lua_State* L)
126 m_task_t task = checkTask(L, 1);
127 lua_pushnumber(L, MSG_task_get_compute_duration(task));
131 static int Task_execute(lua_State* L)
133 m_task_t task = checkTask(L, 1);
134 int res = MSG_task_execute(task);
135 lua_pushnumber(L, res);
139 static int Task_send(lua_State* L)
141 m_task_t task = checkTask(L, 1);
142 const char* mailbox = luaL_checkstring(L, 2);
146 /* copy my stack into the task, so that the receiver can copy the lua task */
147 MSG_task_set_data(task, L);
148 MSG_error_t res = MSG_task_send(task, mailbox);
149 while (MSG_task_get_data(task) != NULL) {
150 /* don't mess up with my stack: the receiver didn't copy the data yet */
151 MSG_process_sleep(0);
155 /* the receiver is the owner of the task and may destroy it:
156 * remove the C task on my side so that I don't garbage collect it */
157 lua_getfield(L, 1, "__simgrid_task");
159 m_task_t* udata = (m_task_t*) luaL_checkudata(L, -1, TASK_MODULE_NAME);
167 XBT_DEBUG("MSG_task_send failed : Timeout");
169 case MSG_TRANSFER_FAILURE:
170 XBT_DEBUG("MSG_task_send failed : Transfer Failure");
172 case MSG_HOST_FAILURE:
173 XBT_DEBUG("MSG_task_send failed : Host Failure ");
177 ("MSG_task_send failed : Unexpected error , please report this bug");
184 static int Task_recv_with_timeout(lua_State *L)
186 m_task_t task = NULL;
187 const char* mailbox = luaL_checkstring(L, 1);
188 int timeout = luaL_checknumber(L, 2);
189 /* mailbox timeout */
192 MSG_error_t res = MSG_task_receive_with_timeout(&task, mailbox, timeout);
195 /* copy the data directly from sender's stack */
196 lua_State* sender_stack = MSG_task_get_data(task);
197 sglua_copy_value(sender_stack, L);
199 MSG_task_set_data(task, NULL);
204 XBT_DEBUG("MSG_task_receive failed : Timeout");
206 case MSG_TRANSFER_FAILURE:
207 XBT_DEBUG("MSG_task_receive failed : Transfer Failure");
209 case MSG_HOST_FAILURE:
210 XBT_DEBUG("MSG_task_receive failed : Host Failure ");
213 XBT_ERROR("MSG_task_receive failed : Unexpected error , please report this bug");
223 static int Task_recv(lua_State * L)
225 lua_pushnumber(L, -1.0);
226 return Task_recv_with_timeout(L);
229 static const luaL_reg Task_methods[] = {
231 {"name", Task_get_name},
232 {"computation_duration", Task_computation_duration},
233 {"execute", Task_execute},
236 {"recv_timeout", Task_recv_with_timeout},
240 static int Task_gc(lua_State* L)
243 m_task_t task = *((m_task_t*) luaL_checkudata(L, 1, TASK_MODULE_NAME));
244 /* the task is NULL if I sent it to someone else */
246 MSG_task_destroy(task);
251 static int Task_tostring(lua_State* L)
253 m_task_t task = checkTask(L, 1);
254 lua_pushfstring(L, "Task: %p", task);
258 static const luaL_reg Task_meta[] = {
260 {"__tostring", Task_tostring},
267 static m_host_t checkHost(lua_State * L, int index)
270 luaL_checktype(L, index, LUA_TTABLE);
271 lua_getfield(L, index, "__simgrid_host");
272 pi = (m_host_t *) luaL_checkudata(L, lua_gettop(L), HOST_MODULE_NAME);
274 luaL_typerror(L, index, HOST_MODULE_NAME);
277 luaL_error(L, "null Host");
282 static int Host_get_by_name(lua_State * L)
284 const char *name = luaL_checkstring(L, 1);
285 XBT_DEBUG("Getting Host from name...");
286 m_host_t msg_host = MSG_get_host_by_name(name);
288 luaL_error(L, "null Host : MSG_get_host_by_name failed");
290 lua_newtable(L); /* create a table, put the userdata on top of it */
291 m_host_t *lua_host = (m_host_t *) lua_newuserdata(L, sizeof(m_host_t));
292 *lua_host = msg_host;
293 luaL_getmetatable(L, HOST_MODULE_NAME);
294 lua_setmetatable(L, -2);
295 lua_setfield(L, -2, "__simgrid_host"); /* put the userdata as field of the table */
296 /* remove the args from the stack */
301 static int Host_get_name(lua_State * L)
303 m_host_t ht = checkHost(L, -1);
304 lua_pushstring(L, MSG_host_get_name(ht));
308 static int Host_number(lua_State * L)
310 lua_pushnumber(L, MSG_get_host_number());
314 static int Host_at(lua_State * L)
316 int index = luaL_checkinteger(L, 1);
317 m_host_t host = MSG_get_host_table()[index - 1]; // lua indexing start by 1 (lua[1] <=> C[0])
318 lua_newtable(L); /* create a table, put the userdata on top of it */
319 m_host_t *lua_host = (m_host_t *) lua_newuserdata(L, sizeof(m_host_t));
321 luaL_getmetatable(L, HOST_MODULE_NAME);
322 lua_setmetatable(L, -2);
323 lua_setfield(L, -2, "__simgrid_host"); /* put the userdata as field of the table */
328 static int Host_self(lua_State * L)
331 m_host_t host = MSG_host_self();
334 m_host_t* lua_host = (m_host_t*) lua_newuserdata(L, sizeof(m_host_t));
337 luaL_getmetatable(L, HOST_MODULE_NAME);
339 lua_setmetatable(L, -2);
341 lua_setfield(L, -2, "__simgrid_host");
346 static int Host_get_property_value(lua_State * L)
348 m_host_t ht = checkHost(L, -2);
349 const char *prop = luaL_checkstring(L, -1);
350 lua_pushstring(L,MSG_host_get_property_value(ht,prop));
354 static int Host_sleep(lua_State *L)
356 int time = luaL_checknumber(L, -1);
357 MSG_process_sleep(time);
361 static int Host_destroy(lua_State *L)
363 m_host_t ht = checkHost(L, -1);
364 __MSG_host_destroy(ht);
368 /* ********************************************************************************* */
369 /* lua_stub_generator functions */
370 /* ********************************************************************************* */
372 xbt_dict_t process_function_set;
373 xbt_dynar_t process_list;
374 xbt_dict_t machine_set;
375 static s_process_t process;
377 void s_process_free(void *process)
379 s_process_t *p = (s_process_t *) process;
381 for (i = 0; i < p->argc; i++)
387 static int gras_add_process_function(lua_State * L)
390 const char *process_host = luaL_checkstring(L, 1);
391 const char *process_function = luaL_checkstring(L, 2);
393 if (xbt_dict_is_empty(machine_set)
394 || xbt_dict_is_empty(process_function_set)
395 || xbt_dynar_is_empty(process_list)) {
396 process_function_set = xbt_dict_new();
397 process_list = xbt_dynar_new(sizeof(s_process_t), s_process_free);
398 machine_set = xbt_dict_new();
401 xbt_dict_set(machine_set, process_host, NULL, NULL);
402 xbt_dict_set(process_function_set, process_function, NULL, NULL);
405 process.argv = xbt_new(char *, 1);
406 process.argv[0] = xbt_strdup(process_function);
407 process.host = strdup(process_host);
410 while (lua_next(L, 3) != 0) {
411 arg = lua_tostring(L, -1);
414 xbt_realloc(process.argv, (process.argc) * sizeof(char *));
415 process.argv[(process.argc) - 1] = xbt_strdup(arg);
417 XBT_DEBUG("index = %f , arg = %s \n", lua_tonumber(L, -2),
418 lua_tostring(L, -1));
422 //add to the process list
423 xbt_dynar_push(process_list, &process);
428 static int gras_generate(lua_State * L)
430 const char *project_name = luaL_checkstring(L, 1);
431 generate_sim(project_name);
432 generate_rl(project_name);
433 generate_makefile_local(project_name);
438 // *********** Register Methods ******************************************* //
443 static const luaL_reg Host_methods[] = {
444 {"getByName", Host_get_by_name},
445 {"name", Host_get_name},
446 {"number", Host_number},
449 {"getPropValue", Host_get_property_value},
450 {"sleep", Host_sleep},
451 {"destroy", Host_destroy},
452 // Bypass XML Methods
453 {"setFunction", console_set_function},
454 {"setProperty", console_host_set_property},
458 static int Host_gc(lua_State * L)
460 m_host_t ht = checkHost(L, -1);
466 static int Host_tostring(lua_State * L)
468 lua_pushfstring(L, "Host :%p", lua_touserdata(L, 1));
472 static const luaL_reg Host_meta[] = {
474 {"__tostring", Host_tostring},
481 static const luaL_reg platf_methods[] = {
482 {"open", console_open},
483 {"close", console_close},
484 {"AS_open", console_AS_open},
485 {"AS_close", console_AS_close},
486 {"host_new", console_add_host},
487 {"link_new", console_add_link},
488 {"router_new", console_add_router},
489 {"route_new", console_add_route},
494 * Environment related
498 * @brief Runs a Lua function as a new simulated process.
499 * @param argc number of arguments of the function
500 * @param argv name of the Lua function and array of its arguments
501 * @return result of the function
503 static int run_lua_code(int argc, char **argv)
505 XBT_DEBUG("Run lua code %s", argv[0]);
507 lua_State *L = sglua_clone_maestro();
510 /* start the function */
511 lua_getglobal(L, argv[0]);
512 xbt_assert(lua_isfunction(L, -1),
513 "The lua function %s does not seem to exist", argv[0]);
515 /* push arguments onto the stack */
517 for (i = 1; i < argc; i++)
518 lua_pushstring(L, argv[i]);
520 /* call the function */
521 _XBT_GNUC_UNUSED int err;
522 err = lua_pcall(L, argc - 1, 1, 0);
523 xbt_assert(err == 0, "error running function `%s': %s", argv[0],
524 lua_tostring(L, -1));
526 /* retrieve result */
527 if (lua_isnumber(L, -1)) {
528 res = lua_tonumber(L, -1);
529 lua_pop(L, 1); /* pop returned value */
532 XBT_DEBUG("Execution of Lua code %s is over", (argv ? argv[0] : "(null)"));
537 static int launch_application(lua_State * L)
539 const char *file = luaL_checkstring(L, 1);
540 MSG_function_register_default(run_lua_code);
541 MSG_launch_application(file);
545 static int create_environment(lua_State * L)
547 const char *file = luaL_checkstring(L, 1);
548 XBT_DEBUG("Loading environment file %s", file);
549 MSG_create_environment(file);
553 static int debug(lua_State * L)
555 const char *str = luaL_checkstring(L, 1);
556 XBT_DEBUG("%s", str);
560 static int info(lua_State * L)
562 const char *str = luaL_checkstring(L, 1);
567 static int run(lua_State * L)
573 static int clean(lua_State * L)
580 * Bypass XML Parser (lua console)
584 * Register platform for MSG
586 static int msg_register_platform(lua_State * L)
588 /* Tell Simgrid we dont wanna use its parser */
589 //surf_parse = console_parse_platform;
590 surf_parse_reset_callbacks();
591 MSG_create_environment(NULL);
596 * Register platform for Simdag
599 static int sd_register_platform(lua_State * L)
601 //surf_parse = console_parse_platform_wsL07;
602 surf_parse_reset_callbacks();
603 SD_create_environment(NULL);
608 * Register platform for gras
610 static int gras_register_platform(lua_State * L)
612 //surf_parse = console_parse_platform;
613 surf_parse_reset_callbacks();
614 gras_create_environment(NULL);
619 * Register applicaiton for MSG
621 static int msg_register_application(lua_State * L)
623 MSG_function_register_default(run_lua_code);
624 //surf_parse = console_parse_application;
625 MSG_launch_application(NULL);
630 * Register application for gras
632 static int gras_register_application(lua_State * L)
634 gras_function_register_default(run_lua_code);
635 //surf_parse = console_parse_application;
636 gras_launch_application(NULL);
640 static const luaL_Reg simgrid_funcs[] = {
641 {"create_environment", create_environment},
642 {"launch_application", launch_application},
648 {"platform", create_environment},
649 {"application", launch_application},
650 /* methods to bypass XML parser */
651 {"msg_register_platform", msg_register_platform},
652 {"sd_register_platform", sd_register_platform},
653 {"msg_register_application", msg_register_application},
654 {"gras_register_platform", gras_register_platform},
655 {"gras_register_application", gras_register_application},
656 /* gras sub generator method */
657 {"gras_set_process_function", gras_add_process_function},
658 {"gras_generate", gras_generate},
662 /* ********************************************************************************* */
663 /* module management functions */
664 /* ********************************************************************************* */
666 #define LUA_MAX_ARGS_COUNT 10 /* maximum amount of arguments we can get from lua on command line */
668 int luaopen_simgrid(lua_State *L); // Fuck gcc: we don't need that prototype
671 * This function is called automatically by the Lua interpreter when some Lua code requires
672 * the "simgrid" module.
673 * @param L the Lua state
675 int luaopen_simgrid(lua_State *L)
677 XBT_DEBUG("luaopen_simgrid *****");
679 /* Get the command line arguments from the lua interpreter */
680 char **argv = malloc(sizeof(char *) * LUA_MAX_ARGS_COUNT);
682 argv[0] = (char *) "/usr/bin/lua"; /* Lie on the argv[0] so that the stack dumping facilities find the right binary. FIXME: what if lua is not in that location? */
684 lua_getglobal(L, "arg");
685 /* if arg is a null value, it means we use lua only as a script to init platform
686 * else it should be a table and then take arg in consideration
688 if (lua_istable(L, -1)) {
692 lua_pushinteger(L, argc - 2);
694 if (lua_isnil(L, -1)) {
697 xbt_assert(lua_isstring(L, -1),
698 "argv[%d] got from lua is no string", argc - 1);
699 xbt_assert(argc < LUA_MAX_ARGS_COUNT,
700 "Too many arguments, please increase LUA_MAX_ARGS_COUNT in %s before recompiling SimGrid if you insist on having more than %d args on command line",
701 __FILE__, LUA_MAX_ARGS_COUNT - 1);
702 argv[argc - 1] = (char *) luaL_checkstring(L, -1);
704 XBT_DEBUG("Got command line argument %s from lua", argv[argc - 1]);
709 /* Initialize the MSG core */
710 MSG_global_init(&argc, argv);
711 XBT_DEBUG("Still %d arguments on command line", argc); // FIXME: update the lua's arg table to reflect the changes from SimGrid
714 /* Keep the context mechanism informed of our lua world today */
715 sglua_maestro_state = L;
717 /* initialize access to my tables by children Lua states */
719 lua_setfield(L, LUA_REGISTRYINDEX, "simgrid.maestro_tables");
721 register_c_functions(L);
727 * @brief Returns whether a Lua state is the maestro state.
728 * @param L a Lua state
729 * @return true if this is maestro
731 int sglua_is_maestro(lua_State* L) {
732 return L == sglua_maestro_state;
736 * @brief Returns the maestro state.
737 * @return true the maestro Lua state
739 lua_State* sglua_get_maestro(void) {
740 return sglua_maestro_state;
744 * Makes the appropriate Simgrid functions available to the Lua world.
745 * @param L a Lua world
747 void register_c_functions(lua_State *L) {
749 /* register the core C functions to lua */
750 luaL_register(L, "simgrid", simgrid_funcs);
752 /* register the task methods to lua */
753 luaL_openlib(L, TASK_MODULE_NAME, Task_methods, 0); // create methods table, add it to the globals
754 luaL_newmetatable(L, TASK_MODULE_NAME); // create metatable for Task, add it to the Lua registry
755 luaL_openlib(L, 0, Task_meta, 0); // fill metatable
756 lua_pushliteral(L, "__index");
757 lua_pushvalue(L, -3); // dup methods table
758 lua_rawset(L, -3); // matatable.__index = methods
759 lua_pushliteral(L, "__metatable");
760 lua_pushvalue(L, -3); // dup methods table
761 lua_rawset(L, -3); // hide metatable:metatable.__metatable = methods
762 lua_pop(L, 1); // drop metatable
764 /* register the hosts methods to lua */
765 luaL_openlib(L, HOST_MODULE_NAME, Host_methods, 0);
766 luaL_newmetatable(L, HOST_MODULE_NAME);
767 luaL_openlib(L, 0, Host_meta, 0);
768 lua_pushliteral(L, "__index");
769 lua_pushvalue(L, -3);
771 lua_pushliteral(L, "__metatable");
772 lua_pushvalue(L, -3);
776 /* register the links methods to lua */
777 luaL_openlib(L, PLATF_MODULE_NAME, platf_methods, 0);
778 luaL_newmetatable(L, PLATF_MODULE_NAME);