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 AS_MODULE_NAME "simgrid.AS"
21 #define TRACE_MODULE_NAME "simgrid.Trace"
23 static lua_State* sglua_maestro_state;
25 static void register_c_functions(lua_State *L);
28 * \brief Like luaL_checkudata, with additional debug logs.
29 * \param L a lua state
30 * \param ud index of the userdata to check in the stack
31 * \param tname key of the metatable of this userdata in the registry
33 static void* my_checkudata(lua_State* L, int ud, const char* tname) {
35 XBT_DEBUG("Checking the userdata: ud = %d", ud);
36 sglua_stack_dump("my_checkudata: ", L);
37 void* p = lua_touserdata(L, ud);
38 lua_getfield(L, LUA_REGISTRYINDEX, tname);
39 const void* correct_mt = lua_topointer(L, -1);
41 int has_mt = lua_getmetatable(L, ud);
42 XBT_DEBUG("Checking the userdata: has metatable ? %d", has_mt);
43 const void* actual_mt = NULL;
45 actual_mt = lua_topointer(L, -1);
48 XBT_DEBUG("Checking the task's metatable: expected %p, found %p", correct_mt, actual_mt);
49 sglua_stack_dump("my_checkudata: ", L);
51 if (p == NULL || !lua_getmetatable(L, ud) || !lua_rawequal(L, -1, -2))
52 luaL_typerror(L, ud, tname);
58 * @brief Ensures that a value is a valid task and returns it.
59 * @param L a Lua state
60 * @param index an index in the Lua stack
61 * @return the task at this index
63 static m_task_t checkTask(lua_State* L, int index)
65 sglua_stack_dump("checkTask: ", L);
66 luaL_checktype(L, index, LUA_TTABLE);
68 lua_getfield(L, index, "__simgrid_task");
69 /* ... task ... ctask */
70 m_task_t task = *((m_task_t*) luaL_checkudata(L, -1, TASK_MODULE_NAME));
75 luaL_error(L, "This task was sent to someone else, you cannot access it anymore");
81 /* ********************************************************************************* */
82 /* wrapper functions */
83 /* ********************************************************************************* */
86 * \brief Creates a new task and leaves it onto the stack.
89 * - task name (string)
90 * - computation size (integer)
91 * - communication size (integer)
93 static int Task_new(lua_State* L)
95 XBT_DEBUG("Task new");
96 const char* name = luaL_checkstring(L, 1);
97 int comp_size = luaL_checkint(L, 2);
98 int msg_size = luaL_checkint(L, 3);
102 m_task_t msg_task = MSG_task_create(name, comp_size, msg_size, NULL);
106 m_task_t* lua_task = (m_task_t*) lua_newuserdata(L, sizeof(m_task_t));
108 *lua_task = msg_task;
109 luaL_getmetatable(L, TASK_MODULE_NAME);
111 lua_setmetatable(L, -2);
113 lua_setfield(L, -2, "__simgrid_task");
118 static int Task_get_name(lua_State* L)
120 m_task_t task = checkTask(L, 1);
121 lua_pushstring(L, MSG_task_get_name(task));
125 static int Task_computation_duration(lua_State* L)
127 m_task_t task = checkTask(L, 1);
128 lua_pushnumber(L, MSG_task_get_compute_duration(task));
132 static int Task_execute(lua_State* L)
134 m_task_t task = checkTask(L, 1);
135 int res = MSG_task_execute(task);
136 lua_pushnumber(L, res);
140 static int Task_send(lua_State* L)
142 m_task_t task = checkTask(L, 1);
143 const char* mailbox = luaL_checkstring(L, 2);
147 /* copy my stack into the task, so that the receiver can copy the lua task */
148 MSG_task_set_data(task, L);
149 MSG_error_t res = MSG_task_send(task, mailbox);
150 while (MSG_task_get_data(task) != NULL) {
151 /* don't mess up with my stack: the receiver didn't copy the data yet */
152 MSG_process_sleep(0);
156 /* the receiver is the owner of the task and may destroy it:
157 * remove the C task on my side so that I don't garbage collect it */
158 lua_getfield(L, 1, "__simgrid_task");
160 m_task_t* udata = (m_task_t*) luaL_checkudata(L, -1, TASK_MODULE_NAME);
168 XBT_DEBUG("MSG_task_send failed : Timeout");
170 case MSG_TRANSFER_FAILURE:
171 XBT_DEBUG("MSG_task_send failed : Transfer Failure");
173 case MSG_HOST_FAILURE:
174 XBT_DEBUG("MSG_task_send failed : Host Failure ");
178 ("MSG_task_send failed : Unexpected error , please report this bug");
185 static int Task_recv_with_timeout(lua_State *L)
187 m_task_t task = NULL;
188 const char* mailbox = luaL_checkstring(L, 1);
189 int timeout = luaL_checknumber(L, 2);
190 /* mailbox timeout */
193 MSG_error_t res = MSG_task_receive_with_timeout(&task, mailbox, timeout);
196 /* copy the data directly from sender's stack */
197 lua_State* sender_stack = MSG_task_get_data(task);
198 sglua_copy_value(sender_stack, L);
200 MSG_task_set_data(task, NULL);
205 XBT_DEBUG("MSG_task_receive failed : Timeout");
207 case MSG_TRANSFER_FAILURE:
208 XBT_DEBUG("MSG_task_receive failed : Transfer Failure");
210 case MSG_HOST_FAILURE:
211 XBT_DEBUG("MSG_task_receive failed : Host Failure ");
214 XBT_ERROR("MSG_task_receive failed : Unexpected error , please report this bug");
224 static int Task_recv(lua_State * L)
226 lua_pushnumber(L, -1.0);
227 return Task_recv_with_timeout(L);
230 static const luaL_reg Task_methods[] = {
232 {"name", Task_get_name},
233 {"computation_duration", Task_computation_duration},
234 {"execute", Task_execute},
237 {"recv_timeout", Task_recv_with_timeout},
241 static int Task_gc(lua_State* L)
244 m_task_t task = *((m_task_t*) luaL_checkudata(L, 1, TASK_MODULE_NAME));
245 /* the task is NULL if I sent it to someone else */
247 MSG_task_destroy(task);
252 static int Task_tostring(lua_State* L)
254 m_task_t task = checkTask(L, 1);
255 lua_pushfstring(L, "Task: %p", task);
259 static const luaL_reg Task_meta[] = {
261 {"__tostring", Task_tostring},
268 static m_host_t checkHost(lua_State * L, int index)
271 luaL_checktype(L, index, LUA_TTABLE);
272 lua_getfield(L, index, "__simgrid_host");
273 pi = (m_host_t *) luaL_checkudata(L, lua_gettop(L), HOST_MODULE_NAME);
275 luaL_typerror(L, index, HOST_MODULE_NAME);
278 luaL_error(L, "null Host");
283 static int Host_get_by_name(lua_State * L)
285 const char *name = luaL_checkstring(L, 1);
286 XBT_DEBUG("Getting Host from name...");
287 m_host_t msg_host = MSG_get_host_by_name(name);
289 luaL_error(L, "null Host : MSG_get_host_by_name failed");
291 lua_newtable(L); /* create a table, put the userdata on top of it */
292 m_host_t *lua_host = (m_host_t *) lua_newuserdata(L, sizeof(m_host_t));
293 *lua_host = msg_host;
294 luaL_getmetatable(L, HOST_MODULE_NAME);
295 lua_setmetatable(L, -2);
296 lua_setfield(L, -2, "__simgrid_host"); /* put the userdata as field of the table */
297 /* remove the args from the stack */
302 static int Host_get_name(lua_State * L)
304 m_host_t ht = checkHost(L, -1);
305 lua_pushstring(L, MSG_host_get_name(ht));
309 static int Host_number(lua_State * L)
311 lua_pushnumber(L, MSG_get_host_number());
315 static int Host_at(lua_State * L)
317 int index = luaL_checkinteger(L, 1);
318 m_host_t host = MSG_get_host_table()[index - 1]; // lua indexing start by 1 (lua[1] <=> C[0])
319 lua_newtable(L); /* create a table, put the userdata on top of it */
320 m_host_t *lua_host = (m_host_t *) lua_newuserdata(L, sizeof(m_host_t));
322 luaL_getmetatable(L, HOST_MODULE_NAME);
323 lua_setmetatable(L, -2);
324 lua_setfield(L, -2, "__simgrid_host"); /* put the userdata as field of the table */
329 static int Host_self(lua_State * L)
332 m_host_t host = MSG_host_self();
335 m_host_t* lua_host = (m_host_t*) lua_newuserdata(L, sizeof(m_host_t));
338 luaL_getmetatable(L, HOST_MODULE_NAME);
340 lua_setmetatable(L, -2);
342 lua_setfield(L, -2, "__simgrid_host");
347 static int Host_get_property_value(lua_State * L)
349 m_host_t ht = checkHost(L, -2);
350 const char *prop = luaL_checkstring(L, -1);
351 lua_pushstring(L,MSG_host_get_property_value(ht,prop));
355 static int Host_sleep(lua_State *L)
357 int time = luaL_checknumber(L, -1);
358 MSG_process_sleep(time);
362 static int Host_destroy(lua_State *L)
364 m_host_t ht = checkHost(L, -1);
365 __MSG_host_destroy(ht);
369 /* ********************************************************************************* */
370 /* lua_stub_generator functions */
371 /* ********************************************************************************* */
373 xbt_dict_t process_function_set;
374 xbt_dynar_t process_list;
375 xbt_dict_t machine_set;
376 static s_process_t process;
378 void s_process_free(void *process)
380 s_process_t *p = (s_process_t *) process;
382 for (i = 0; i < p->argc; i++)
388 static int gras_add_process_function(lua_State * L)
391 const char *process_host = luaL_checkstring(L, 1);
392 const char *process_function = luaL_checkstring(L, 2);
394 if (xbt_dict_is_empty(machine_set)
395 || xbt_dict_is_empty(process_function_set)
396 || xbt_dynar_is_empty(process_list)) {
397 process_function_set = xbt_dict_new();
398 process_list = xbt_dynar_new(sizeof(s_process_t), s_process_free);
399 machine_set = xbt_dict_new();
402 xbt_dict_set(machine_set, process_host, NULL, NULL);
403 xbt_dict_set(process_function_set, process_function, NULL, NULL);
406 process.argv = xbt_new(char *, 1);
407 process.argv[0] = xbt_strdup(process_function);
408 process.host = strdup(process_host);
411 while (lua_next(L, 3) != 0) {
412 arg = lua_tostring(L, -1);
415 xbt_realloc(process.argv, (process.argc) * sizeof(char *));
416 process.argv[(process.argc) - 1] = xbt_strdup(arg);
418 XBT_DEBUG("index = %f , arg = %s \n", lua_tonumber(L, -2),
419 lua_tostring(L, -1));
423 //add to the process list
424 xbt_dynar_push(process_list, &process);
429 static int gras_generate(lua_State * L)
431 const char *project_name = luaL_checkstring(L, 1);
432 generate_sim(project_name);
433 generate_rl(project_name);
434 generate_makefile_local(project_name);
438 /***********************************
440 **********************************/
441 static int trace_start(lua_State *L)
449 static int trace_category(lua_State * L)
452 TRACE_category(luaL_checkstring(L, 1));
457 static int trace_set_task_category(lua_State *L)
460 TRACE_msg_set_task_category(checkTask(L, -2), luaL_checkstring(L, -1));
465 static int trace_end(lua_State *L)
473 // *********** Register Methods ******************************************* //
478 static const luaL_reg Host_methods[] = {
479 {"getByName", Host_get_by_name},
480 {"name", Host_get_name},
481 {"number", Host_number},
484 {"getPropValue", Host_get_property_value},
485 {"sleep", Host_sleep},
486 {"destroy", Host_destroy},
487 // Bypass XML Methods
488 {"setFunction", console_set_function},
489 {"setProperty", console_host_set_property},
493 static int Host_gc(lua_State * L)
495 m_host_t ht = checkHost(L, -1);
501 static int Host_tostring(lua_State * L)
503 lua_pushfstring(L, "Host :%p", lua_touserdata(L, 1));
507 static const luaL_reg Host_meta[] = {
509 {"__tostring", Host_tostring},
516 static const luaL_reg AS_methods[] = {
517 {"new", console_add_AS},
518 {"addHost", console_add_host},
519 {"addLink", console_add_link},
520 {"addRoute", console_add_route},
527 static const luaL_reg Trace_methods[] = {
528 {"start", trace_start},
529 {"category", trace_category},
530 {"setTaskCategory", trace_set_task_category},
531 {"finish", trace_end},
536 * Environment related
540 * @brief Runs a Lua function as a new simulated process.
541 * @param argc number of arguments of the function
542 * @param argv name of the Lua function and array of its arguments
543 * @return result of the function
545 static int run_lua_code(int argc, char **argv)
547 XBT_DEBUG("Run lua code %s", argv[0]);
549 lua_State *L = sglua_clone_maestro();
552 /* start the function */
553 lua_getglobal(L, argv[0]);
554 xbt_assert(lua_isfunction(L, -1),
555 "The lua function %s does not seem to exist", argv[0]);
557 /* push arguments onto the stack */
559 for (i = 1; i < argc; i++)
560 lua_pushstring(L, argv[i]);
562 /* call the function */
563 _XBT_GNUC_UNUSED int err;
564 err = lua_pcall(L, argc - 1, 1, 0);
565 xbt_assert(err == 0, "error running function `%s': %s", argv[0],
566 lua_tostring(L, -1));
568 /* retrieve result */
569 if (lua_isnumber(L, -1)) {
570 res = lua_tonumber(L, -1);
571 lua_pop(L, 1); /* pop returned value */
574 XBT_DEBUG("Execution of Lua code %s is over", (argv ? argv[0] : "(null)"));
579 static int launch_application(lua_State * L)
581 const char *file = luaL_checkstring(L, 1);
582 MSG_function_register_default(run_lua_code);
583 MSG_launch_application(file);
587 static int create_environment(lua_State * L)
589 const char *file = luaL_checkstring(L, 1);
590 XBT_DEBUG("Loading environment file %s", file);
591 MSG_create_environment(file);
595 static int debug(lua_State * L)
597 const char *str = luaL_checkstring(L, 1);
598 XBT_DEBUG("%s", str);
602 static int info(lua_State * L)
604 const char *str = luaL_checkstring(L, 1);
609 static int run(lua_State * L)
615 static int clean(lua_State * L)
622 * Bypass XML Parser (lua console)
626 * Register platform for MSG
628 static int msg_register_platform(lua_State * L)
630 /* Tell Simgrid we dont wanna use its parser */
631 surf_parse = console_parse_platform;
632 surf_parse_reset_callbacks();
633 MSG_create_environment(NULL);
638 * Register platform for Simdag
641 static int sd_register_platform(lua_State * L)
643 surf_parse = console_parse_platform_wsL07;
644 surf_parse_reset_callbacks();
645 SD_create_environment(NULL);
650 * Register platform for gras
652 static int gras_register_platform(lua_State * L)
654 /* Tell Simgrid we dont wanna use surf parser */
655 surf_parse = console_parse_platform;
656 surf_parse_reset_callbacks();
657 gras_create_environment(NULL);
662 * Register applicaiton for MSG
664 static int msg_register_application(lua_State * L)
666 MSG_function_register_default(run_lua_code);
667 surf_parse = console_parse_application;
668 MSG_launch_application(NULL);
673 * Register application for gras
675 static int gras_register_application(lua_State * L)
677 gras_function_register_default(run_lua_code);
678 surf_parse = console_parse_application;
679 gras_launch_application(NULL);
683 static const luaL_Reg simgrid_funcs[] = {
684 {"create_environment", create_environment},
685 {"launch_application", launch_application},
691 {"platform", create_environment},
692 {"application", launch_application},
693 /* methods to bypass XML parser */
694 {"msg_register_platform", msg_register_platform},
695 {"sd_register_platform", sd_register_platform},
696 {"msg_register_application", msg_register_application},
697 {"gras_register_platform", gras_register_platform},
698 {"gras_register_application", gras_register_application},
699 /* gras sub generator method */
700 {"gras_set_process_function", gras_add_process_function},
701 {"gras_generate", gras_generate},
705 /* ********************************************************************************* */
706 /* module management functions */
707 /* ********************************************************************************* */
709 #define LUA_MAX_ARGS_COUNT 10 /* maximum amount of arguments we can get from lua on command line */
711 int luaopen_simgrid(lua_State *L); // Fuck gcc: we don't need that prototype
714 * This function is called automatically by the Lua interpreter when some Lua code requires
715 * the "simgrid" module.
716 * @param L the Lua state
718 int luaopen_simgrid(lua_State *L)
720 XBT_DEBUG("luaopen_simgrid *****");
722 /* Get the command line arguments from the lua interpreter */
723 char **argv = malloc(sizeof(char *) * LUA_MAX_ARGS_COUNT);
725 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? */
727 lua_getglobal(L, "arg");
728 /* if arg is a null value, it means we use lua only as a script to init platform
729 * else it should be a table and then take arg in consideration
731 if (lua_istable(L, -1)) {
735 lua_pushinteger(L, argc - 2);
737 if (lua_isnil(L, -1)) {
740 xbt_assert(lua_isstring(L, -1),
741 "argv[%d] got from lua is no string", argc - 1);
742 xbt_assert(argc < LUA_MAX_ARGS_COUNT,
743 "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",
744 __FILE__, LUA_MAX_ARGS_COUNT - 1);
745 argv[argc - 1] = (char *) luaL_checkstring(L, -1);
747 XBT_DEBUG("Got command line argument %s from lua", argv[argc - 1]);
752 /* Initialize the MSG core */
753 MSG_global_init(&argc, argv);
754 XBT_DEBUG("Still %d arguments on command line", argc); // FIXME: update the lua's arg table to reflect the changes from SimGrid
757 /* Keep the context mechanism informed of our lua world today */
758 sglua_maestro_state = L;
760 /* initialize access to my tables by children Lua states */
762 lua_setfield(L, LUA_REGISTRYINDEX, "simgrid.maestro_tables");
764 register_c_functions(L);
770 * @brief Returns whether a Lua state is the maestro state.
771 * @param L a Lua state
772 * @return true if this is maestro
774 int sglua_is_maestro(lua_State* L) {
775 return L == sglua_maestro_state;
779 * @brief Returns the maestro state.
780 * @return true the maestro Lua state
782 lua_State* sglua_get_maestro(void) {
783 return sglua_maestro_state;
787 * Makes the appropriate Simgrid functions available to the Lua world.
788 * @param L a Lua world
790 void register_c_functions(lua_State *L) {
792 /* register the core C functions to lua */
793 luaL_register(L, "simgrid", simgrid_funcs);
795 /* register the task methods to lua */
796 luaL_openlib(L, TASK_MODULE_NAME, Task_methods, 0); // create methods table, add it to the globals
797 luaL_newmetatable(L, TASK_MODULE_NAME); // create metatable for Task, add it to the Lua registry
798 luaL_openlib(L, 0, Task_meta, 0); // fill metatable
799 lua_pushliteral(L, "__index");
800 lua_pushvalue(L, -3); // dup methods table
801 lua_rawset(L, -3); // matatable.__index = methods
802 lua_pushliteral(L, "__metatable");
803 lua_pushvalue(L, -3); // dup methods table
804 lua_rawset(L, -3); // hide metatable:metatable.__metatable = methods
805 lua_pop(L, 1); // drop metatable
807 /* register the hosts methods to lua */
808 luaL_openlib(L, HOST_MODULE_NAME, Host_methods, 0);
809 luaL_newmetatable(L, HOST_MODULE_NAME);
810 luaL_openlib(L, 0, Host_meta, 0);
811 lua_pushliteral(L, "__index");
812 lua_pushvalue(L, -3);
814 lua_pushliteral(L, "__metatable");
815 lua_pushvalue(L, -3);
819 /* register the links methods to lua */
820 luaL_openlib(L, AS_MODULE_NAME, AS_methods, 0);
821 luaL_newmetatable(L, AS_MODULE_NAME);
824 /* register the Tracing functions to lua */
825 luaL_openlib(L, TRACE_MODULE_NAME, Trace_methods, 0);
826 luaL_newmetatable(L, TRACE_MODULE_NAME);