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_CATEGORY(lua, "Lua Bindings");
15 static lua_State *lua_maestro_state;
17 #define TASK_MODULE_NAME "simgrid.Task"
18 #define HOST_MODULE_NAME "simgrid.Host"
20 #define LINK_MODULE_NAME "simgrid.Link"
21 #define ROUTE_MODULE_NAME "simgrid.Route"
22 #define AS_MODULE_NAME "simgrid.AS"
23 #define TRACE_MODULE_NAME "simgrid.Trace"
25 static void register_c_functions(lua_State *L);
27 static void *my_checkudata (lua_State *L, int ud, const char *tname) {
29 XBT_DEBUG("Checking the task: ud = %d", ud);
30 sglua_stack_dump("my_checkudata: ", L);
31 void *p = lua_touserdata(L, ud);
32 lua_getfield(L, LUA_REGISTRYINDEX, tname);
33 const void* correct_mt = lua_topointer(L, -1);
35 int has_mt = lua_getmetatable(L, ud);
36 XBT_DEBUG("Checking the task: has metatable ? %d", has_mt);
37 const void* actual_mt = NULL;
38 if (has_mt) { actual_mt = lua_topointer(L, -1); lua_pop(L, 1); }
39 XBT_DEBUG("Checking the task's metatable: expected %p, found %p", correct_mt, actual_mt);
40 sglua_stack_dump("my_checkudata: ", L);
42 if (p == NULL || !lua_getmetatable(L, ud) || !lua_rawequal(L, -1, -2))
43 luaL_typerror(L, ud, tname);
49 * @brief Ensures that a userdata on the stack is a task
50 * and returns the pointer inside the userdata.
51 * @param L a Lua state
52 * @param index an index in the Lua stack
53 * @return the task at this index
55 static m_task_t checkTask(lua_State * L, int index)
58 XBT_DEBUG("Lua task: %s", sglua_tostring(L, index));
59 luaL_checktype(L, index, LUA_TTABLE);
60 lua_getfield(L, index, "__simgrid_task");
62 pi = (m_task_t *) luaL_checkudata(L, lua_gettop(L), TASK_MODULE_NAME);
65 luaL_typerror(L, index, TASK_MODULE_NAME);
68 luaL_error(L, "null Task");
73 /* ********************************************************************************* */
74 /* wrapper functions */
75 /* ********************************************************************************* */
78 * A task is either something to compute somewhere, or something to exchange between two hosts (or both).
79 * It is defined by a computing amount and a message size.
88 * @brief Constructs a new task with the specified processing amount and amount
91 * @param name Task's name
93 * @param computeDuration A value of the processing amount (in flop) needed to process the task.
94 * If 0, then it cannot be executed with the execute() method.
95 * This value has to be >= 0.
97 * @param messageSize A value of amount of data (in bytes) needed to transfert this task.
98 * If 0, then it cannot be transfered with the get() and put() methods.
99 * This value has to be >= 0.
101 static int Task_new(lua_State * L)
103 XBT_DEBUG("Task new...");
104 const char *name = luaL_checkstring(L, 1);
105 int comp_size = luaL_checkint(L, 2);
106 int msg_size = luaL_checkint(L, 3);
107 m_task_t msg_task = MSG_task_create(name, comp_size, msg_size, NULL);
108 lua_newtable(L); /* create a table, put the userdata on top of it */
109 m_task_t *lua_task = (m_task_t *) lua_newuserdata(L, sizeof(m_task_t));
110 *lua_task = msg_task;
111 luaL_getmetatable(L, TASK_MODULE_NAME);
112 lua_setmetatable(L, -2);
113 lua_setfield(L, -2, "__simgrid_task"); /* put the userdata as field of the table */
114 /* remove the args from the stack */
121 static int Task_get_name(lua_State * L)
123 m_task_t tk = checkTask(L, -1);
124 lua_pushstring(L, MSG_task_get_name(tk));
128 static int Task_computation_duration(lua_State * L)
130 m_task_t tk = checkTask(L, -1);
131 lua_pushnumber(L, MSG_task_get_compute_duration(tk));
135 static int Task_execute(lua_State * L)
137 m_task_t tk = checkTask(L, -1);
138 int res = MSG_task_execute(tk);
139 lua_pushnumber(L, res);
143 static int Task_destroy(lua_State * L)
145 m_task_t tk = checkTask(L, -1);
146 int res = MSG_task_destroy(tk);
147 lua_pushnumber(L, res);
151 static int Task_send(lua_State * L)
153 //stack_dump("send ", L);
154 m_task_t tk = checkTask(L, 1);
155 const char *mailbox = luaL_checkstring(L, 2);
156 lua_pop(L, 1); // remove the string so that the task is on top of it
157 MSG_task_set_data(tk, L); // Copy my stack into the task, so that the receiver can copy the lua task directly
158 MSG_error_t res = MSG_task_send(tk, mailbox);
159 while (MSG_task_get_data(tk) != NULL) // Don't mess up with my stack: the receiver didn't copy the data yet
160 MSG_process_sleep(0); // yield
165 XBT_DEBUG("MSG_task_send failed : Timeout");
167 case MSG_TRANSFER_FAILURE:
168 XBT_DEBUG("MSG_task_send failed : Transfer Failure");
170 case MSG_HOST_FAILURE:
171 XBT_DEBUG("MSG_task_send failed : Host Failure ");
175 ("MSG_task_send failed : Unexpected error , please report this bug");
181 static int Task_recv_with_timeout(lua_State *L)
184 const char *mailbox = luaL_checkstring(L, -2);
185 int timeout = luaL_checknumber(L, -1);
186 MSG_error_t res = MSG_task_receive_with_timeout(&tk, mailbox, timeout);
189 lua_State *sender_stack = MSG_task_get_data(tk);
190 sglua_move_value(sender_stack, L); // copy the data directly from sender's stack
191 MSG_task_set_data(tk, NULL);
196 XBT_DEBUG("MSG_task_receive failed : Timeout");
198 case MSG_TRANSFER_FAILURE:
199 XBT_DEBUG("MSG_task_receive failed : Transfer Failure");
201 case MSG_HOST_FAILURE:
202 XBT_DEBUG("MSG_task_receive failed : Host Failure ");
205 XBT_ERROR("MSG_task_receive failed : Unexpected error , please report this bug");
213 static int Task_recv(lua_State * L)
215 lua_pushnumber(L, -1.0);
216 return Task_recv_with_timeout(L);
219 static const luaL_reg Task_methods[] = {
221 {"name", Task_get_name},
222 {"computation_duration", Task_computation_duration},
223 {"execute", Task_execute},
224 {"destroy", Task_destroy},
227 {"recv_timeout", Task_recv_with_timeout},
231 static int Task_gc(lua_State * L)
233 m_task_t tk = checkTask(L, -1);
235 MSG_task_destroy(tk);
239 static int Task_tostring(lua_State * L)
241 lua_pushfstring(L, "Task :%p", lua_touserdata(L, 1));
245 static const luaL_reg Task_meta[] = {
247 {"__tostring", Task_tostring},
254 static m_host_t checkHost(lua_State * L, int index)
257 luaL_checktype(L, index, LUA_TTABLE);
258 lua_getfield(L, index, "__simgrid_host");
259 pi = (m_host_t *) luaL_checkudata(L, lua_gettop(L), HOST_MODULE_NAME);
261 luaL_typerror(L, index, HOST_MODULE_NAME);
264 luaL_error(L, "null Host");
269 static int Host_get_by_name(lua_State * L)
271 const char *name = luaL_checkstring(L, 1);
272 XBT_DEBUG("Getting Host from name...");
273 m_host_t msg_host = MSG_get_host_by_name(name);
275 luaL_error(L, "null Host : MSG_get_host_by_name failed");
277 lua_newtable(L); /* create a table, put the userdata on top of it */
278 m_host_t *lua_host = (m_host_t *) lua_newuserdata(L, sizeof(m_host_t));
279 *lua_host = msg_host;
280 luaL_getmetatable(L, HOST_MODULE_NAME);
281 lua_setmetatable(L, -2);
282 lua_setfield(L, -2, "__simgrid_host"); /* put the userdata as field of the table */
283 /* remove the args from the stack */
288 static int Host_get_name(lua_State * L)
290 m_host_t ht = checkHost(L, -1);
291 lua_pushstring(L, MSG_host_get_name(ht));
295 static int Host_number(lua_State * L)
297 lua_pushnumber(L, MSG_get_host_number());
301 static int Host_at(lua_State * L)
303 int index = luaL_checkinteger(L, 1);
304 m_host_t host = MSG_get_host_table()[index - 1]; // lua indexing start by 1 (lua[1] <=> C[0])
305 lua_newtable(L); /* create a table, put the userdata on top of it */
306 m_host_t *lua_host = (m_host_t *) lua_newuserdata(L, sizeof(m_host_t));
308 luaL_getmetatable(L, HOST_MODULE_NAME);
309 lua_setmetatable(L, -2);
310 lua_setfield(L, -2, "__simgrid_host"); /* put the userdata as field of the table */
315 static int Host_self(lua_State * L)
317 m_host_t host = MSG_host_self();
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");
327 static int Host_get_property_value(lua_State * L)
329 m_host_t ht = checkHost(L, -2);
330 const char *prop = luaL_checkstring(L, -1);
331 lua_pushstring(L,MSG_host_get_property_value(ht,prop));
335 static int Host_sleep(lua_State *L)
337 int time = luaL_checknumber(L, -1);
338 MSG_process_sleep(time);
342 static int Host_destroy(lua_State *L)
344 m_host_t ht = checkHost(L, -1);
345 __MSG_host_destroy(ht);
349 /* ********************************************************************************* */
350 /* lua_stub_generator functions */
351 /* ********************************************************************************* */
353 xbt_dict_t process_function_set;
354 xbt_dynar_t process_list;
355 xbt_dict_t machine_set;
356 static s_process_t process;
358 void s_process_free(void *process)
360 s_process_t *p = (s_process_t *) process;
362 for (i = 0; i < p->argc; i++)
368 static int gras_add_process_function(lua_State * L)
371 const char *process_host = luaL_checkstring(L, 1);
372 const char *process_function = luaL_checkstring(L, 2);
374 if (xbt_dict_is_empty(machine_set)
375 || xbt_dict_is_empty(process_function_set)
376 || xbt_dynar_is_empty(process_list)) {
377 process_function_set = xbt_dict_new();
378 process_list = xbt_dynar_new(sizeof(s_process_t), s_process_free);
379 machine_set = xbt_dict_new();
382 xbt_dict_set(machine_set, process_host, NULL, NULL);
383 xbt_dict_set(process_function_set, process_function, NULL, NULL);
386 process.argv = xbt_new(char *, 1);
387 process.argv[0] = xbt_strdup(process_function);
388 process.host = strdup(process_host);
391 while (lua_next(L, 3) != 0) {
392 arg = lua_tostring(L, -1);
395 xbt_realloc(process.argv, (process.argc) * sizeof(char *));
396 process.argv[(process.argc) - 1] = xbt_strdup(arg);
398 XBT_DEBUG("index = %f , arg = %s \n", lua_tonumber(L, -2),
399 lua_tostring(L, -1));
403 //add to the process list
404 xbt_dynar_push(process_list, &process);
409 static int gras_generate(lua_State * L)
411 const char *project_name = luaL_checkstring(L, 1);
412 generate_sim(project_name);
413 generate_rl(project_name);
414 generate_makefile_local(project_name);
418 /***********************************
420 **********************************/
421 static int trace_start(lua_State *L)
429 static int trace_category(lua_State * L)
432 TRACE_category(luaL_checkstring(L, 1));
437 static int trace_set_task_category(lua_State *L)
440 TRACE_msg_set_task_category(checkTask(L, -2), luaL_checkstring(L, -1));
445 static int trace_end(lua_State *L)
453 // *********** Register Methods ******************************************* //
458 static const luaL_reg Host_methods[] = {
459 {"getByName", Host_get_by_name},
460 {"name", Host_get_name},
461 {"number", Host_number},
464 {"getPropValue", Host_get_property_value},
465 {"sleep", Host_sleep},
466 {"destroy", Host_destroy},
467 // Bypass XML Methods
468 {"setFunction", console_set_function},
469 {"setProperty", console_host_set_property},
473 static int Host_gc(lua_State * L)
475 m_host_t ht = checkHost(L, -1);
481 static int Host_tostring(lua_State * L)
483 lua_pushfstring(L, "Host :%p", lua_touserdata(L, 1));
487 static const luaL_reg Host_meta[] = {
489 {"__tostring", Host_tostring},
496 static const luaL_reg AS_methods[] = {
497 {"new", console_add_AS},
498 {"addHost", console_add_host},
499 {"addLink", console_add_link},
500 {"addRoute", console_add_route},
507 static const luaL_reg Trace_methods[] = {
508 {"start", trace_start},
509 {"category", trace_category},
510 {"setTaskCategory", trace_set_task_category},
511 {"finish", trace_end},
516 * Environment related
520 * @brief Runs a Lua function as a new simulated process.
521 * @param argc number of arguments of the function
522 * @param argv name of the Lua function and array of its arguments
523 * @return result of the function
525 static int run_lua_code(int argc, char **argv)
527 XBT_DEBUG("Run lua code %s", argv[0]);
529 lua_State *L = sglua_clone_maestro();
532 /* start the function */
533 lua_getglobal(L, argv[0]);
534 xbt_assert(lua_isfunction(L, -1),
535 "The lua function %s does not seem to exist", argv[0]);
537 /* push arguments onto the stack */
539 for (i = 1; i < argc; i++)
540 lua_pushstring(L, argv[i]);
542 /* call the function */
544 err = lua_pcall(L, argc - 1, 1, 0);
545 xbt_assert(err == 0, "error running function `%s': %s", argv[0],
546 lua_tostring(L, -1));
548 /* retrieve result */
549 if (lua_isnumber(L, -1)) {
550 res = lua_tonumber(L, -1);
551 lua_pop(L, 1); /* pop returned value */
554 XBT_DEBUG("Execution of Lua code %s is over", (argv ? argv[0] : "(null)"));
559 static int launch_application(lua_State * L)
561 const char *file = luaL_checkstring(L, 1);
562 MSG_function_register_default(run_lua_code);
563 MSG_launch_application(file);
567 static int create_environment(lua_State * L)
569 const char *file = luaL_checkstring(L, 1);
570 XBT_DEBUG("Loading environment file %s", file);
571 MSG_create_environment(file);
575 static int debug(lua_State * L)
577 const char *str = luaL_checkstring(L, 1);
578 XBT_DEBUG("%s", str);
582 static int info(lua_State * L)
584 const char *str = luaL_checkstring(L, 1);
589 static int run(lua_State * L)
595 static int clean(lua_State * L)
602 * Bypass XML Parser (lua console)
606 * Register platform for MSG
608 static int msg_register_platform(lua_State * L)
610 /* Tell Simgrid we dont wanna use its parser */
611 surf_parse = console_parse_platform;
612 surf_parse_reset_callbacks();
613 surf_config_models_setup(NULL);
614 MSG_create_environment(NULL);
619 * Register platform for Simdag
622 static int sd_register_platform(lua_State * L)
624 surf_parse = console_parse_platform_wsL07;
625 surf_parse_reset_callbacks();
626 surf_config_models_setup(NULL);
627 SD_create_environment(NULL);
632 * Register platform for gras
634 static int gras_register_platform(lua_State * L)
636 /* Tell Simgrid we dont wanna use surf parser */
637 surf_parse = console_parse_platform;
638 surf_parse_reset_callbacks();
639 surf_config_models_setup(NULL);
640 gras_create_environment(NULL);
645 * Register applicaiton for MSG
647 static int msg_register_application(lua_State * L)
649 MSG_function_register_default(run_lua_code);
650 surf_parse = console_parse_application;
651 MSG_launch_application(NULL);
656 * Register application for gras
658 static int gras_register_application(lua_State * L)
660 gras_function_register_default(run_lua_code);
661 surf_parse = console_parse_application;
662 gras_launch_application(NULL);
666 static const luaL_Reg simgrid_funcs[] = {
667 {"create_environment", create_environment},
668 {"launch_application", launch_application},
674 {"platform", create_environment},
675 {"application", launch_application},
676 /* methods to bypass XML parser */
677 {"msg_register_platform", msg_register_platform},
678 {"sd_register_platform", sd_register_platform},
679 {"msg_register_application", msg_register_application},
680 {"gras_register_platform", gras_register_platform},
681 {"gras_register_application", gras_register_application},
682 /* gras sub generator method */
683 {"gras_set_process_function", gras_add_process_function},
684 {"gras_generate", gras_generate},
688 /* ********************************************************************************* */
689 /* module management functions */
690 /* ********************************************************************************* */
692 #define LUA_MAX_ARGS_COUNT 10 /* maximum amount of arguments we can get from lua on command line */
694 int luaopen_simgrid(lua_State *L); // Fuck gcc: we don't need that prototype
697 * This function is called automatically by the Lua interpreter when some Lua code requires
698 * the "simgrid" module.
699 * @param L the Lua state
701 int luaopen_simgrid(lua_State *L)
703 XBT_DEBUG("luaopen_simgrid *****");
705 /* Get the command line arguments from the lua interpreter */
706 char **argv = malloc(sizeof(char *) * LUA_MAX_ARGS_COUNT);
708 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? */
710 lua_getglobal(L, "arg");
711 /* if arg is a null value, it means we use lua only as a script to init platform
712 * else it should be a table and then take arg in consideration
714 if (lua_istable(L, -1)) {
718 lua_pushinteger(L, argc - 2);
720 if (lua_isnil(L, -1)) {
723 xbt_assert(lua_isstring(L, -1),
724 "argv[%d] got from lua is no string", argc - 1);
725 xbt_assert(argc < LUA_MAX_ARGS_COUNT,
726 "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",
727 __FILE__, LUA_MAX_ARGS_COUNT - 1);
728 argv[argc - 1] = (char *) luaL_checkstring(L, -1);
730 XBT_DEBUG("Got command line argument %s from lua", argv[argc - 1]);
735 /* Initialize the MSG core */
736 MSG_global_init(&argc, argv);
737 XBT_DEBUG("Still %d arguments on command line", argc); // FIXME: update the lua's arg table to reflect the changes from SimGrid
740 /* Keep the context mechanism informed of our lua world today */
741 lua_maestro_state = L;
743 /* initialize access to my tables by children Lua states */
745 lua_setfield(L, LUA_REGISTRYINDEX, "simgrid.maestro_tables");
747 register_c_functions(L);
753 * @brief Returns whether a Lua state is the maestro state.
754 * @param L a Lua state
755 * @return true if this is maestro
757 int sglua_is_maestro(lua_State* L) {
758 return L == lua_maestro_state;
762 * @brief Returns the maestro state.
763 * @return true the maestro Lua state
765 lua_State* sglua_get_maestro(void) {
766 return lua_maestro_state;
770 * Makes the appropriate Simgrid functions available to the Lua world.
771 * @param L a Lua world
773 void register_c_functions(lua_State *L) {
775 /* register the core C functions to lua */
776 luaL_register(L, "simgrid", simgrid_funcs);
778 /* register the task methods to lua */
779 luaL_openlib(L, TASK_MODULE_NAME, Task_methods, 0); // create methods table, add it to the globals
780 luaL_newmetatable(L, TASK_MODULE_NAME); // create metatable for Task, add it to the Lua registry
781 luaL_openlib(L, 0, Task_meta, 0); // fill metatable
782 lua_pushliteral(L, "__index");
783 lua_pushvalue(L, -3); // dup methods table
784 lua_rawset(L, -3); // matatable.__index = methods
785 lua_pushliteral(L, "__metatable");
786 lua_pushvalue(L, -3); // dup methods table
787 lua_rawset(L, -3); // hide metatable:metatable.__metatable = methods
788 lua_pop(L, 1); // drop metatable
790 /* register the hosts methods to lua */
791 luaL_openlib(L, HOST_MODULE_NAME, Host_methods, 0);
792 luaL_newmetatable(L, HOST_MODULE_NAME);
793 luaL_openlib(L, 0, Host_meta, 0);
794 lua_pushliteral(L, "__index");
795 lua_pushvalue(L, -3);
797 lua_pushliteral(L, "__metatable");
798 lua_pushvalue(L, -3);
802 /* register the links methods to lua */
803 luaL_openlib(L, AS_MODULE_NAME, AS_methods, 0);
804 luaL_newmetatable(L, AS_MODULE_NAME);
807 /* register the Tracing functions to lua */
808 luaL_openlib(L, TRACE_MODULE_NAME, Trace_methods, 0);
809 luaL_newmetatable(L, TRACE_MODULE_NAME);