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 {"addRouter", console_add_router},
521 {"addRoute", console_add_route},
528 static const luaL_reg Trace_methods[] = {
529 {"start", trace_start},
530 {"category", trace_category},
531 {"setTaskCategory", trace_set_task_category},
532 {"finish", trace_end},
537 * Environment related
541 * @brief Runs a Lua function as a new simulated process.
542 * @param argc number of arguments of the function
543 * @param argv name of the Lua function and array of its arguments
544 * @return result of the function
546 static int run_lua_code(int argc, char **argv)
548 XBT_DEBUG("Run lua code %s", argv[0]);
550 lua_State *L = sglua_clone_maestro();
553 /* start the function */
554 lua_getglobal(L, argv[0]);
555 xbt_assert(lua_isfunction(L, -1),
556 "The lua function %s does not seem to exist", argv[0]);
558 /* push arguments onto the stack */
560 for (i = 1; i < argc; i++)
561 lua_pushstring(L, argv[i]);
563 /* call the function */
564 _XBT_GNUC_UNUSED int err;
565 err = lua_pcall(L, argc - 1, 1, 0);
566 xbt_assert(err == 0, "error running function `%s': %s", argv[0],
567 lua_tostring(L, -1));
569 /* retrieve result */
570 if (lua_isnumber(L, -1)) {
571 res = lua_tonumber(L, -1);
572 lua_pop(L, 1); /* pop returned value */
575 XBT_DEBUG("Execution of Lua code %s is over", (argv ? argv[0] : "(null)"));
580 static int launch_application(lua_State * L)
582 const char *file = luaL_checkstring(L, 1);
583 MSG_function_register_default(run_lua_code);
584 MSG_launch_application(file);
588 static int create_environment(lua_State * L)
590 const char *file = luaL_checkstring(L, 1);
591 XBT_DEBUG("Loading environment file %s", file);
592 MSG_create_environment(file);
596 static int debug(lua_State * L)
598 const char *str = luaL_checkstring(L, 1);
599 XBT_DEBUG("%s", str);
603 static int info(lua_State * L)
605 const char *str = luaL_checkstring(L, 1);
610 static int run(lua_State * L)
616 static int clean(lua_State * L)
623 * Bypass XML Parser (lua console)
627 * Register platform for MSG
629 static int msg_register_platform(lua_State * L)
631 /* Tell Simgrid we dont wanna use its parser */
632 surf_parse = console_parse_platform;
633 surf_parse_reset_callbacks();
634 MSG_create_environment(NULL);
639 * Register platform for Simdag
642 static int sd_register_platform(lua_State * L)
644 surf_parse = console_parse_platform_wsL07;
645 surf_parse_reset_callbacks();
646 SD_create_environment(NULL);
651 * Register platform for gras
653 static int gras_register_platform(lua_State * L)
655 /* Tell Simgrid we dont wanna use surf parser */
656 surf_parse = console_parse_platform;
657 surf_parse_reset_callbacks();
658 gras_create_environment(NULL);
663 * Register applicaiton for MSG
665 static int msg_register_application(lua_State * L)
667 MSG_function_register_default(run_lua_code);
668 surf_parse = console_parse_application;
669 MSG_launch_application(NULL);
674 * Register application for gras
676 static int gras_register_application(lua_State * L)
678 gras_function_register_default(run_lua_code);
679 surf_parse = console_parse_application;
680 gras_launch_application(NULL);
684 static const luaL_Reg simgrid_funcs[] = {
685 {"create_environment", create_environment},
686 {"launch_application", launch_application},
692 {"platform", create_environment},
693 {"application", launch_application},
694 /* methods to bypass XML parser */
695 {"msg_register_platform", msg_register_platform},
696 {"sd_register_platform", sd_register_platform},
697 {"msg_register_application", msg_register_application},
698 {"gras_register_platform", gras_register_platform},
699 {"gras_register_application", gras_register_application},
700 /* gras sub generator method */
701 {"gras_set_process_function", gras_add_process_function},
702 {"gras_generate", gras_generate},
706 /* ********************************************************************************* */
707 /* module management functions */
708 /* ********************************************************************************* */
710 #define LUA_MAX_ARGS_COUNT 10 /* maximum amount of arguments we can get from lua on command line */
712 int luaopen_simgrid(lua_State *L); // Fuck gcc: we don't need that prototype
715 * This function is called automatically by the Lua interpreter when some Lua code requires
716 * the "simgrid" module.
717 * @param L the Lua state
719 int luaopen_simgrid(lua_State *L)
721 XBT_DEBUG("luaopen_simgrid *****");
723 /* Get the command line arguments from the lua interpreter */
724 char **argv = malloc(sizeof(char *) * LUA_MAX_ARGS_COUNT);
726 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? */
728 lua_getglobal(L, "arg");
729 /* if arg is a null value, it means we use lua only as a script to init platform
730 * else it should be a table and then take arg in consideration
732 if (lua_istable(L, -1)) {
736 lua_pushinteger(L, argc - 2);
738 if (lua_isnil(L, -1)) {
741 xbt_assert(lua_isstring(L, -1),
742 "argv[%d] got from lua is no string", argc - 1);
743 xbt_assert(argc < LUA_MAX_ARGS_COUNT,
744 "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",
745 __FILE__, LUA_MAX_ARGS_COUNT - 1);
746 argv[argc - 1] = (char *) luaL_checkstring(L, -1);
748 XBT_DEBUG("Got command line argument %s from lua", argv[argc - 1]);
753 /* Initialize the MSG core */
754 MSG_global_init(&argc, argv);
755 XBT_DEBUG("Still %d arguments on command line", argc); // FIXME: update the lua's arg table to reflect the changes from SimGrid
758 /* Keep the context mechanism informed of our lua world today */
759 sglua_maestro_state = L;
761 /* initialize access to my tables by children Lua states */
763 lua_setfield(L, LUA_REGISTRYINDEX, "simgrid.maestro_tables");
765 register_c_functions(L);
771 * @brief Returns whether a Lua state is the maestro state.
772 * @param L a Lua state
773 * @return true if this is maestro
775 int sglua_is_maestro(lua_State* L) {
776 return L == sglua_maestro_state;
780 * @brief Returns the maestro state.
781 * @return true the maestro Lua state
783 lua_State* sglua_get_maestro(void) {
784 return sglua_maestro_state;
788 * Makes the appropriate Simgrid functions available to the Lua world.
789 * @param L a Lua world
791 void register_c_functions(lua_State *L) {
793 /* register the core C functions to lua */
794 luaL_register(L, "simgrid", simgrid_funcs);
796 /* register the task methods to lua */
797 luaL_openlib(L, TASK_MODULE_NAME, Task_methods, 0); // create methods table, add it to the globals
798 luaL_newmetatable(L, TASK_MODULE_NAME); // create metatable for Task, add it to the Lua registry
799 luaL_openlib(L, 0, Task_meta, 0); // fill metatable
800 lua_pushliteral(L, "__index");
801 lua_pushvalue(L, -3); // dup methods table
802 lua_rawset(L, -3); // matatable.__index = methods
803 lua_pushliteral(L, "__metatable");
804 lua_pushvalue(L, -3); // dup methods table
805 lua_rawset(L, -3); // hide metatable:metatable.__metatable = methods
806 lua_pop(L, 1); // drop metatable
808 /* register the hosts methods to lua */
809 luaL_openlib(L, HOST_MODULE_NAME, Host_methods, 0);
810 luaL_newmetatable(L, HOST_MODULE_NAME);
811 luaL_openlib(L, 0, Host_meta, 0);
812 lua_pushliteral(L, "__index");
813 lua_pushvalue(L, -3);
815 lua_pushliteral(L, "__metatable");
816 lua_pushvalue(L, -3);
820 /* register the links methods to lua */
821 luaL_openlib(L, AS_MODULE_NAME, AS_methods, 0);
822 luaL_newmetatable(L, AS_MODULE_NAME);
825 /* register the Tracing functions to lua */
826 luaL_openlib(L, TRACE_MODULE_NAME, Trace_methods, 0);
827 luaL_newmetatable(L, TRACE_MODULE_NAME);