1 /* SimGrid Lua bindings */
3 /* Copyright (c) 2010. The SimGrid Team.
4 * All rights reserved. */
6 /* This program is free software; you can redistribute it and/or modify it
7 * under the terms of the license (GNU LGPL) which comes with this package. */
8 #include "simgrid_lua.h"
10 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(lua, bindings, "Lua Bindings");
12 static lua_State *lua_maestro_state;
14 #define TASK_MODULE_NAME "simgrid.Task"
15 #define HOST_MODULE_NAME "simgrid.Host"
17 #define LINK_MODULE_NAME "simgrid.Link"
18 #define ROUTE_MODULE_NAME "simgrid.Route"
19 #define AS_MODULE_NAME "simgrid.AS"
20 #define TRACE_MODULE_NAME "simgrid.Trace"
22 static void stack_dump(const char *msg, lua_State *L);
23 static m_task_t check_task(lua_State *L, int index);
24 static void register_c_functions(lua_State *L);
26 /* ********************************************************************************* */
27 /* helper functions */
28 /* ********************************************************************************* */
31 * @brief Dumps the Lua stack
32 * @param msg a message to print
33 * @param L a Lua state
35 static void stack_dump(const char *msg, lua_State *L)
40 int top = lua_gettop(L);
43 p += sprintf(p, "STACK(top=%d): ", top);
45 for (i = 1; i <= top; i++) { /* repeat for each level */
46 int t = lua_type(L, i);
49 case LUA_TSTRING: /* strings */
50 p += sprintf(p, "`%s'", lua_tostring(L, i));
53 case LUA_TBOOLEAN: /* booleans */
54 p += sprintf(p, lua_toboolean(L, i) ? "true" : "false");
57 case LUA_TNUMBER: /* numbers */
58 p += sprintf(p, "%g", lua_tonumber(L, i));
62 p += sprintf(p, "Table");
65 default: /* other values */
66 p += sprintf(p, "???");
67 /* if ((ptr = luaL_checkudata(L,i,TASK_MODULE_NAME))) {
70 p+=printf(p,"%s", lua_typename(L, t));
75 p += sprintf(p, " "); /* put a separator */
77 XBT_INFO("%s%s", msg, buff);
81 * @brief Ensures that a userdata on the stack is a task
82 * and returns the pointer inside the userdata.
83 * @param L a Lua state
84 * @param index an index in the Lua stack
85 * @return the task at this index
87 static m_task_t checkTask(lua_State * L, int index)
90 luaL_checktype(L, index, LUA_TTABLE);
91 lua_getfield(L, index, "__simgrid_task");
92 pi = (m_task_t *) luaL_checkudata(L, -1, TASK_MODULE_NAME);
94 luaL_typerror(L, index, TASK_MODULE_NAME);
97 luaL_error(L, "null Task");
102 /* ********************************************************************************* */
103 /* wrapper functions */
104 /* ********************************************************************************* */
107 * A task is either something to compute somewhere, or something to exchange between two hosts (or both).
108 * It is defined by a computing amount and a message size.
117 * @brief Constructs a new task with the specified processing amount and amount
120 * @param name Task's name
122 * @param computeDuration A value of the processing amount (in flop) needed to process the task.
123 * If 0, then it cannot be executed with the execute() method.
124 * This value has to be >= 0.
126 * @param messageSize A value of amount of data (in bytes) needed to transfert this task.
127 * If 0, then it cannot be transfered with the get() and put() methods.
128 * This value has to be >= 0.
130 static int Task_new(lua_State * L)
132 XBT_DEBUG("Task new...");
133 const char *name = luaL_checkstring(L, 1);
134 int comp_size = luaL_checkint(L, 2);
135 int msg_size = luaL_checkint(L, 3);
136 m_task_t msg_task = MSG_task_create(name, comp_size, msg_size, NULL);
137 lua_newtable(L); /* create a table, put the userdata on top of it */
138 m_task_t *lua_task = (m_task_t *) lua_newuserdata(L, sizeof(m_task_t));
139 *lua_task = msg_task;
140 luaL_getmetatable(L, TASK_MODULE_NAME);
141 lua_setmetatable(L, -2);
142 lua_setfield(L, -2, "__simgrid_task"); /* put the userdata as field of the table */
143 /* remove the args from the stack */
150 static int Task_get_name(lua_State * L)
152 m_task_t tk = checkTask(L, -1);
153 lua_pushstring(L, MSG_task_get_name(tk));
157 static int Task_computation_duration(lua_State * L)
159 m_task_t tk = checkTask(L, -1);
160 lua_pushnumber(L, MSG_task_get_compute_duration(tk));
164 static int Task_execute(lua_State * L)
166 m_task_t tk = checkTask(L, -1);
167 int res = MSG_task_execute(tk);
168 lua_pushnumber(L, res);
172 static int Task_destroy(lua_State * L)
174 m_task_t tk = checkTask(L, -1);
175 int res = MSG_task_destroy(tk);
176 lua_pushnumber(L, res);
180 static int Task_send(lua_State * L)
182 //stackDump("send ",L);
183 m_task_t tk = checkTask(L, 1);
184 const char *mailbox = luaL_checkstring(L, 2);
185 lua_pop(L, 1); // remove the string so that the task is on top of it
186 MSG_task_set_data(tk, L); // Copy my stack into the task, so that the receiver can copy the lua task directly
187 MSG_error_t res = MSG_task_send(tk, mailbox);
188 while (MSG_task_get_data(tk) != NULL) // Don't mess up with my stack: the receiver didn't copy the data yet
189 MSG_process_sleep(0); // yield
194 XBT_DEBUG("MSG_task_send failed : Timeout");
196 case MSG_TRANSFER_FAILURE:
197 XBT_DEBUG("MSG_task_send failed : Transfer Failure");
199 case MSG_HOST_FAILURE:
200 XBT_DEBUG("MSG_task_send failed : Host Failure ");
204 ("MSG_task_send failed : Unexpected error , please report this bug");
210 static int Task_recv_with_timeout(lua_State *L)
213 const char *mailbox = luaL_checkstring(L, -2);
214 int timeout = luaL_checknumber(L, -1);
215 MSG_error_t res = MSG_task_receive_with_timeout(&tk, mailbox, timeout);
218 lua_State *sender_stack = MSG_task_get_data(tk);
219 lua_xmove(sender_stack, L, 1); // copy the data directly from sender's stack
220 MSG_task_set_data(tk, NULL);
225 XBT_DEBUG("MSG_task_receive failed : Timeout");
227 case MSG_TRANSFER_FAILURE:
228 XBT_DEBUG("MSG_task_receive failed : Transfer Failure");
230 case MSG_HOST_FAILURE:
231 XBT_DEBUG("MSG_task_receive failed : Host Failure ");
234 XBT_ERROR("MSG_task_receive failed : Unexpected error , please report this bug");
242 static int Task_recv(lua_State * L)
244 lua_pushnumber(L, -1.0);
245 return Task_recv_with_timeout(L);
248 static const luaL_reg Task_methods[] = {
250 {"name", Task_get_name},
251 {"computation_duration", Task_computation_duration},
252 {"execute", Task_execute},
253 {"destroy", Task_destroy},
256 {"recv_timeout", Task_recv_with_timeout},
260 static int Task_gc(lua_State * L)
262 m_task_t tk = checkTask(L, -1);
264 MSG_task_destroy(tk);
268 static int Task_tostring(lua_State * L)
270 lua_pushfstring(L, "Task :%p", lua_touserdata(L, 1));
274 static const luaL_reg Task_meta[] = {
276 {"__tostring", Task_tostring},
283 static m_host_t checkHost(lua_State * L, int index)
286 luaL_checktype(L, index, LUA_TTABLE);
287 lua_getfield(L, index, "__simgrid_host");
288 pi = (m_host_t *) luaL_checkudata(L, -1, HOST_MODULE_NAME);
290 luaL_typerror(L, index, HOST_MODULE_NAME);
293 luaL_error(L, "null Host");
298 static int Host_get_by_name(lua_State * L)
300 const char *name = luaL_checkstring(L, 1);
301 XBT_DEBUG("Getting Host from name...");
302 m_host_t msg_host = MSG_get_host_by_name(name);
304 luaL_error(L, "null Host : MSG_get_host_by_name failed");
306 lua_newtable(L); /* create a table, put the userdata on top of it */
307 m_host_t *lua_host = (m_host_t *) lua_newuserdata(L, sizeof(m_host_t));
308 *lua_host = msg_host;
309 luaL_getmetatable(L, HOST_MODULE_NAME);
310 lua_setmetatable(L, -2);
311 lua_setfield(L, -2, "__simgrid_host"); /* put the userdata as field of the table */
312 /* remove the args from the stack */
317 static int Host_get_name(lua_State * L)
319 m_host_t ht = checkHost(L, -1);
320 lua_pushstring(L, MSG_host_get_name(ht));
324 static int Host_number(lua_State * L)
326 lua_pushnumber(L, MSG_get_host_number());
330 static int Host_at(lua_State * L)
332 int index = luaL_checkinteger(L, 1);
333 m_host_t host = MSG_get_host_table()[index - 1]; // lua indexing start by 1 (lua[1] <=> C[0])
334 lua_newtable(L); /* create a table, put the userdata on top of it */
335 m_host_t *lua_host = (m_host_t *) lua_newuserdata(L, sizeof(m_host_t));
337 luaL_getmetatable(L, HOST_MODULE_NAME);
338 lua_setmetatable(L, -2);
339 lua_setfield(L, -2, "__simgrid_host"); /* put the userdata as field of the table */
344 static int Host_self(lua_State * L)
346 m_host_t host = MSG_host_self();
348 m_host_t *lua_host =(m_host_t *)lua_newuserdata(L,sizeof(m_host_t));
350 luaL_getmetatable(L, HOST_MODULE_NAME);
351 lua_setmetatable(L, -2);
352 lua_setfield(L, -2, "__simgrid_host");
356 static int Host_get_property_value(lua_State * L)
358 m_host_t ht = checkHost(L, -2);
359 const char *prop = luaL_checkstring(L, -1);
360 lua_pushstring(L,MSG_host_get_property_value(ht,prop));
364 static int Host_sleep(lua_State *L)
366 int time = luaL_checknumber(L, -1);
367 MSG_process_sleep(time);
371 static int Host_destroy(lua_State *L)
373 m_host_t ht = checkHost(L, -1);
374 __MSG_host_destroy(ht);
378 /* ********************************************************************************* */
379 /* lua_stub_generator functions */
380 /* ********************************************************************************* */
382 xbt_dict_t process_function_set;
383 xbt_dynar_t process_list;
384 xbt_dict_t machine_set;
385 static s_process_t process;
387 void s_process_free(void *process)
389 s_process_t *p = (s_process_t *) process;
391 for (i = 0; i < p->argc; i++)
397 static int gras_add_process_function(lua_State * L)
400 const char *process_host = luaL_checkstring(L, 1);
401 const char *process_function = luaL_checkstring(L, 2);
403 if (xbt_dict_is_empty(machine_set)
404 || xbt_dict_is_empty(process_function_set)
405 || xbt_dynar_is_empty(process_list)) {
406 process_function_set = xbt_dict_new();
407 process_list = xbt_dynar_new(sizeof(s_process_t), s_process_free);
408 machine_set = xbt_dict_new();
411 xbt_dict_set(machine_set, process_host, NULL, NULL);
412 xbt_dict_set(process_function_set, process_function, NULL, NULL);
415 process.argv = xbt_new(char *, 1);
416 process.argv[0] = xbt_strdup(process_function);
417 process.host = strdup(process_host);
420 while (lua_next(L, 3) != 0) {
421 arg = lua_tostring(L, -1);
424 xbt_realloc(process.argv, (process.argc) * sizeof(char *));
425 process.argv[(process.argc) - 1] = xbt_strdup(arg);
427 XBT_DEBUG("index = %f , arg = %s \n", lua_tonumber(L, -2),
428 lua_tostring(L, -1));
432 //add to the process list
433 xbt_dynar_push(process_list, &process);
438 static int gras_generate(lua_State * L)
440 const char *project_name = luaL_checkstring(L, 1);
441 generate_sim(project_name);
442 generate_rl(project_name);
443 generate_makefile_local(project_name);
447 /***********************************
449 **********************************/
450 static int trace_start(lua_State *L)
458 static int trace_category(lua_State * L)
461 TRACE_category(luaL_checkstring(L, 1));
466 static int trace_set_task_category(lua_State *L)
469 TRACE_msg_set_task_category(checkTask(L, -2), luaL_checkstring(L, -1));
474 static int trace_end(lua_State *L)
482 // *********** Register Methods ******************************************* //
487 static const luaL_reg Host_methods[] = {
488 {"getByName", Host_get_by_name},
489 {"name", Host_get_name},
490 {"number", Host_number},
493 {"getPropValue", Host_get_property_value},
494 {"sleep", Host_sleep},
495 {"destroy", Host_destroy},
496 // Bypass XML Methods
497 {"setFunction", console_set_function},
498 {"setProperty", console_host_set_property},
502 static int Host_gc(lua_State * L)
504 m_host_t ht = checkHost(L, -1);
510 static int Host_tostring(lua_State * L)
512 lua_pushfstring(L, "Host :%p", lua_touserdata(L, 1));
516 static const luaL_reg Host_meta[] = {
518 {"__tostring", Host_tostring},
525 static const luaL_reg AS_methods[] = {
526 {"new", console_add_AS},
527 {"addHost", console_add_host},
528 {"addLink", console_add_link},
529 {"addRoute", console_add_route},
536 static const luaL_reg Trace_methods[] = {
537 {"start", trace_start},
538 {"category", trace_category},
539 {"setTaskCategory", trace_set_task_category},
540 {"finish", trace_end},
545 * Environment related
549 * @brief Runs a Lua function as a new simulated process.
550 * @param argc number of arguments of the function
551 * @param argv name of the Lua function and array of its arguments
552 * @return result of the function
554 static int run_lua_code(int argc, char **argv)
556 XBT_DEBUG("Run lua code %s", argv[0]);
558 lua_State *L = lua_newthread(lua_maestro_state);
559 int ref = luaL_ref(lua_maestro_state, LUA_REGISTRYINDEX); /* protect the thread from being garbage collected */
562 /* start the co-routine */
563 lua_getglobal(L, argv[0]);
564 xbt_assert(lua_isfunction(L, -1),
565 "The lua function %s does not seem to exist", argv[0]);
567 /* push arguments onto the stack */
569 for (i = 1; i < argc; i++)
570 lua_pushstring(L, argv[i]);
572 /* call the function */
574 err = lua_pcall(L, argc - 1, 1, 0);
575 xbt_assert(err == 0, "error running function `%s': %s", argv[0],
576 lua_tostring(L, -1));
578 /* retrieve result */
579 if (lua_isnumber(L, -1)) {
580 res = lua_tonumber(L, -1);
581 lua_pop(L, 1); /* pop returned value */
585 luaL_unref(lua_maestro_state, LUA_REGISTRYINDEX, ref);
586 XBT_DEBUG("Execution of Lua code %s is over", (argv ? argv[0] : "(null)"));
591 static int launch_application(lua_State * L)
593 const char *file = luaL_checkstring(L, 1);
594 MSG_function_register_default(run_lua_code);
595 MSG_launch_application(file);
599 static int create_environment(lua_State * L)
601 const char *file = luaL_checkstring(L, 1);
602 XBT_DEBUG("Loading environment file %s", file);
603 MSG_create_environment(file);
607 static int debug(lua_State * L)
609 const char *str = luaL_checkstring(L, 1);
610 XBT_DEBUG("%s", str);
614 static int info(lua_State * L)
616 const char *str = luaL_checkstring(L, 1);
621 static int run(lua_State * L)
627 static int clean(lua_State * L)
634 * Bypass XML Parser (lua console)
638 * Register platform for MSG
640 static int msg_register_platform(lua_State * L)
642 /* Tell Simgrid we dont wanna use its parser */
643 surf_parse = console_parse_platform;
644 surf_parse_reset_callbacks();
645 surf_config_models_setup(NULL);
646 MSG_create_environment(NULL);
651 * Register platform for Simdag
654 static int sd_register_platform(lua_State * L)
656 surf_parse = console_parse_platform_wsL07;
657 surf_parse_reset_callbacks();
658 surf_config_models_setup(NULL);
659 SD_create_environment(NULL);
664 * Register platform for gras
666 static int gras_register_platform(lua_State * L)
668 /* Tell Simgrid we dont wanna use surf parser */
669 surf_parse = console_parse_platform;
670 surf_parse_reset_callbacks();
671 surf_config_models_setup(NULL);
672 gras_create_environment(NULL);
677 * Register applicaiton for MSG
679 static int msg_register_application(lua_State * L)
681 MSG_function_register_default(run_lua_code);
682 surf_parse = console_parse_application;
683 MSG_launch_application(NULL);
688 * Register application for gras
690 static int gras_register_application(lua_State * L)
692 gras_function_register_default(run_lua_code);
693 surf_parse = console_parse_application;
694 gras_launch_application(NULL);
698 static const luaL_Reg simgrid_funcs[] = {
699 {"create_environment", create_environment},
700 {"launch_application", launch_application},
706 {"platform", create_environment},
707 {"application", launch_application},
708 /* methods to bypass XML parser */
709 {"msg_register_platform", msg_register_platform},
710 {"sd_register_platform", sd_register_platform},
711 {"msg_register_application", msg_register_application},
712 {"gras_register_platform", gras_register_platform},
713 {"gras_register_application", gras_register_application},
714 /* gras sub generator method */
715 {"gras_set_process_function", gras_add_process_function},
716 {"gras_generate", gras_generate},
720 /* ********************************************************************************* */
721 /* module management functions */
722 /* ********************************************************************************* */
724 #define LUA_MAX_ARGS_COUNT 10 /* maximum amount of arguments we can get from lua on command line */
726 int luaopen_simgrid(lua_State *L); // Fuck gcc: we don't need that prototype
729 * This function is called automatically by the Lua interpreter when some Lua code requires
730 * the "simgrid" module.
731 * @param L the Lua state
733 int luaopen_simgrid(lua_State *L)
735 XBT_DEBUG("luaopen_simgrid *****");
737 /* Get the command line arguments from the lua interpreter */
738 char **argv = malloc(sizeof(char *) * LUA_MAX_ARGS_COUNT);
740 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? */
742 lua_getglobal(L, "arg");
743 /* if arg is a null value, it means we use lua only as a script to init platform
744 * else it should be a table and then take arg in consideration
746 if (lua_istable(L, -1)) {
750 lua_pushinteger(L, argc - 2);
752 if (lua_isnil(L, -1)) {
755 xbt_assert(lua_isstring(L, -1),
756 "argv[%d] got from lua is no string", argc - 1);
757 xbt_assert(argc < LUA_MAX_ARGS_COUNT,
758 "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",
759 __FILE__, LUA_MAX_ARGS_COUNT - 1);
760 argv[argc - 1] = (char *) luaL_checkstring(L, -1);
762 XBT_DEBUG("Got command line argument %s from lua", argv[argc - 1]);
767 /* Initialize the MSG core */
768 MSG_global_init(&argc, argv);
769 XBT_DEBUG("Still %d arguments on command line", argc); // FIXME: update the lua's arg table to reflect the changes from SimGrid
772 /* Keep the context mechanism informed of our lua world today */
773 lua_maestro_state = L;
775 register_c_functions(L);
781 * Makes the appropriate Simgrid functions available to the Lua world.
782 * @param L a Lua world
784 void register_c_functions(lua_State *L) {
786 /* register the core C functions to lua */
787 luaL_register(L, "simgrid", simgrid_funcs);
789 /* register the task methods to lua */
790 luaL_openlib(L, TASK_MODULE_NAME, Task_methods, 0); // create methods table, add it to the globals
791 luaL_newmetatable(L, TASK_MODULE_NAME); // create metatable for Task, add it to the Lua registry
792 luaL_openlib(L, 0, Task_meta, 0); // fill metatable
793 lua_pushliteral(L, "__index");
794 lua_pushvalue(L, -3); // dup methods table
795 lua_rawset(L, -3); // matatable.__index = methods
796 lua_pushliteral(L, "__metatable");
797 lua_pushvalue(L, -3); // dup methods table
798 lua_rawset(L, -3); // hide metatable:metatable.__metatable = methods
799 lua_pop(L, 1); // drop metatable
801 /* register the hosts methods to lua */
802 luaL_openlib(L, HOST_MODULE_NAME, Host_methods, 0);
803 luaL_newmetatable(L, HOST_MODULE_NAME);
804 luaL_openlib(L, 0, Host_meta, 0);
805 lua_pushliteral(L, "__index");
806 lua_pushvalue(L, -3);
808 lua_pushliteral(L, "__metatable");
809 lua_pushvalue(L, -3);
813 /* register the links methods to lua */
814 luaL_openlib(L, AS_MODULE_NAME, AS_methods, 0);
815 luaL_newmetatable(L, AS_MODULE_NAME);
818 /* register the Tracing functions to lua */
819 luaL_openlib(L, TRACE_MODULE_NAME, Trace_methods, 0);
820 luaL_newmetatable(L, TRACE_MODULE_NAME);