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 lua_State *simgrid_lua_state;
14 #define TASK_MODULE_NAME "simgrid.Task"
15 #define HOST_MODULE_NAME "simgrid.Host"
16 // Surf ( bypass XML )
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 /* ********************************************************************************* */
23 /* helper functions */
24 /* ********************************************************************************* */
25 static void stackDump(const char *msg, lua_State * L)
30 int top = lua_gettop(L);
33 p += sprintf(p, "STACK(top=%d): ", top);
35 for (i = 1; i <= top; i++) { /* repeat for each level */
36 int t = lua_type(L, i);
39 case LUA_TSTRING: /* strings */
40 p += sprintf(p, "`%s'", lua_tostring(L, i));
43 case LUA_TBOOLEAN: /* booleans */
44 p += sprintf(p, lua_toboolean(L, i) ? "true" : "false");
47 case LUA_TNUMBER: /* numbers */
48 p += sprintf(p, "%g", lua_tonumber(L, i));
52 p += sprintf(p, "Table");
55 default: /* other values */
56 p += sprintf(p, "???");
57 /* if ((ptr = luaL_checkudata(L,i,TASK_MODULE_NAME))) {
60 p+=printf(p,"%s", lua_typename(L, t));
65 p += sprintf(p, " "); /* put a separator */
67 XBT_INFO("%s%s", msg, buff);
70 /** @brief ensures that a userdata on the stack is a task and returns the pointer inside the userdata */
71 static m_task_t checkTask(lua_State * L, int index)
74 luaL_checktype(L, index, LUA_TTABLE);
75 lua_getfield(L, index, "__simgrid_task");
76 pi = (m_task_t *) luaL_checkudata(L, -1, TASK_MODULE_NAME);
78 luaL_typerror(L, index, TASK_MODULE_NAME);
81 luaL_error(L, "null Task");
86 /* ********************************************************************************* */
87 /* wrapper functions */
88 /* ********************************************************************************* */
91 * A task is either something to compute somewhere, or something to exchange between two hosts (or both).
92 * It is defined by a computing amount and a message size.
100 * Construct an new task with the specified processing amount and amount
103 * @param name Task's name
105 * @param computeDuration A value of the processing amount (in flop) needed to process the task.
106 * If 0, then it cannot be executed with the execute() method.
107 * This value has to be >= 0.
109 * @param messageSize A value of amount of data (in bytes) needed to transfert this task.
110 * If 0, then it cannot be transfered with the get() and put() methods.
111 * This value has to be >= 0.
113 static int Task_new(lua_State * L)
115 XBT_DEBUG("Task new...");
116 const char *name = luaL_checkstring(L, 1);
117 int comp_size = luaL_checkint(L, 2);
118 int msg_size = luaL_checkint(L, 3);
119 m_task_t msg_task = MSG_task_create(name, comp_size, msg_size, NULL);
120 lua_newtable(L); /* create a table, put the userdata on top of it */
121 m_task_t *lua_task = (m_task_t *) lua_newuserdata(L, sizeof(m_task_t));
122 *lua_task = msg_task;
123 luaL_getmetatable(L, TASK_MODULE_NAME);
124 lua_setmetatable(L, -2);
125 lua_setfield(L, -2, "__simgrid_task"); /* put the userdata as field of the table */
126 /* remove the args from the stack */
133 static int Task_get_name(lua_State * L)
135 m_task_t tk = checkTask(L, -1);
136 lua_pushstring(L, MSG_task_get_name(tk));
140 static int Task_computation_duration(lua_State * L)
142 m_task_t tk = checkTask(L, -1);
143 lua_pushnumber(L, MSG_task_get_compute_duration(tk));
147 static int Task_execute(lua_State * L)
149 m_task_t tk = checkTask(L, -1);
150 int res = MSG_task_execute(tk);
151 lua_pushnumber(L, res);
155 static int Task_destroy(lua_State * L)
157 m_task_t tk = checkTask(L, -1);
158 int res = MSG_task_destroy(tk);
159 lua_pushnumber(L, res);
163 static int Task_send(lua_State * L)
165 //stackDump("send ",L);
166 m_task_t tk = checkTask(L, 1);
167 const char *mailbox = luaL_checkstring(L, 2);
168 lua_pop(L, 1); // remove the string so that the task is on top of it
169 MSG_task_set_data(tk, L); // Copy my stack into the task, so that the receiver can copy the lua task directly
170 MSG_error_t res = MSG_task_send(tk, mailbox);
171 while (MSG_task_get_data(tk) != NULL) // Don't mess up with my stack: the receiver didn't copy the data yet
172 MSG_process_sleep(0); // yield
177 XBT_ERROR("MSG_task_send failed : Timeout");
179 case MSG_TRANSFER_FAILURE:
180 XBT_ERROR("MSG_task_send failed : Transfer Failure");
182 case MSG_HOST_FAILURE:
183 XBT_ERROR("MSG_task_send failed : Host Failure ");
187 ("MSG_task_send failed : Unexpected error , please report this bug");
193 static int Task_recv(lua_State * L)
196 const char *mailbox = luaL_checkstring(L, -1);
197 MSG_error_t res = MSG_task_receive(&tk, mailbox);
199 lua_State *sender_stack = MSG_task_get_data(tk);
200 lua_xmove(sender_stack, L, 1); // copy the data directly from sender's stack
201 MSG_task_set_data(tk, NULL);
206 XBT_ERROR("MSG_task_receive failed : Timeout");
208 case MSG_TRANSFER_FAILURE:
209 XBT_ERROR("MSG_task_receive failed : Transfer Failure");
211 case MSG_HOST_FAILURE:
212 XBT_ERROR("MSG_task_receive failed : Host Failure ");
216 ("MSG_task_receive failed : Unexpected error , please report this bug");
223 static int Task_recv_with_timeout(lua_State * L)
226 const char *mailbox = luaL_checkstring(L, -2);
227 int timeout = luaL_checknumber(L, -1);
228 MSG_error_t res = MSG_task_receive_with_timeout(&tk, mailbox, timeout);
230 lua_State *sender_stack = MSG_task_get_data(tk);
231 lua_xmove(sender_stack, L, 1); // copy the data directly from sender's stack
232 MSG_task_set_data(tk, NULL);
237 XBT_ERROR("MSG_task_receive failed : Timeout");
239 case MSG_TRANSFER_FAILURE:
240 XBT_ERROR("MSG_task_receive failed : Transfer Failure");
242 case MSG_HOST_FAILURE:
243 XBT_ERROR("MSG_task_receive failed : Host Failure ");
247 ("MSG_task_receive failed : Unexpected error , please report this bug");
254 * Static Binding for the Splay methods : event.sleep :
255 * it use MSG_task_irecv with MSG_comm_wait
257 static int Task_splay_irecv(lua_State *L)
259 m_task_t task = NULL;
260 msg_comm_t comm = NULL; //current communication to receive
261 const char *mailbox = luaL_checkstring(L, -2);
262 double timeout = luaL_checknumber(L, -1);
263 comm = MSG_task_irecv(&task, mailbox);
264 MSG_comm_wait(comm, timeout);
265 if (MSG_comm_get_status(comm) == MSG_OK)
267 XBT_DEBUG("Receiving task : %s",MSG_task_get_name(task));
268 lua_State *sender_stack = MSG_task_get_data(task);
269 lua_xmove(sender_stack, L, 1); // copy the data directly from sender's stack
270 MSG_task_set_data(task, NULL);
272 MSG_comm_destroy(comm);
276 static int Task_splay_isend(lua_State *L)
278 m_task_t tk = checkTask(L, 1);
279 const char *mailbox = luaL_checkstring(L, 2);
280 lua_pop(L, 1); // remove the string so that the task is on top of it
281 MSG_task_set_data(tk, L); // Copy my stack into the task, so that the receiver can copy the lua task directly
282 MSG_task_isend(tk, mailbox);
287 static const luaL_reg Task_methods[] = {
289 {"name", Task_get_name},
290 {"computation_duration", Task_computation_duration},
291 {"execute", Task_execute},
292 {"destroy", Task_destroy},
295 {"recv_timeout",Task_recv_with_timeout},
296 {"splay_recv",Task_splay_irecv},
297 {"iSend",Task_splay_isend},
301 static int Task_gc(lua_State * L)
303 m_task_t tk = checkTask(L, -1);
305 MSG_task_destroy(tk);
309 static int Task_tostring(lua_State * L)
311 lua_pushfstring(L, "Task :%p", lua_touserdata(L, 1));
315 static const luaL_reg Task_meta[] = {
317 {"__tostring", Task_tostring},
324 static m_host_t checkHost(lua_State * L, int index)
327 luaL_checktype(L, index, LUA_TTABLE);
328 lua_getfield(L, index, "__simgrid_host");
329 pi = (m_host_t *) luaL_checkudata(L, -1, HOST_MODULE_NAME);
331 luaL_typerror(L, index, HOST_MODULE_NAME);
334 luaL_error(L, "null Host");
339 static int Host_get_by_name(lua_State * L)
341 const char *name = luaL_checkstring(L, 1);
342 XBT_DEBUG("Getting Host from name...");
343 m_host_t msg_host = MSG_get_host_by_name(name);
345 luaL_error(L, "null Host : MSG_get_host_by_name failed");
347 lua_newtable(L); /* create a table, put the userdata on top of it */
348 m_host_t *lua_host = (m_host_t *) lua_newuserdata(L, sizeof(m_host_t));
349 *lua_host = msg_host;
350 luaL_getmetatable(L, HOST_MODULE_NAME);
351 lua_setmetatable(L, -2);
352 lua_setfield(L, -2, "__simgrid_host"); /* put the userdata as field of the table */
353 /* remove the args from the stack */
359 static int Host_get_name(lua_State * L)
361 m_host_t ht = checkHost(L, -1);
362 lua_pushstring(L, MSG_host_get_name(ht));
366 static int Host_number(lua_State * L)
368 lua_pushnumber(L, MSG_get_host_number());
372 static int Host_at(lua_State * L)
374 int index = luaL_checkinteger(L, 1);
375 m_host_t host = MSG_get_host_table()[index - 1]; // lua indexing start by 1 (lua[1] <=> C[0])
376 lua_newtable(L); /* create a table, put the userdata on top of it */
377 m_host_t *lua_host = (m_host_t *) lua_newuserdata(L, sizeof(m_host_t));
379 luaL_getmetatable(L, HOST_MODULE_NAME);
380 lua_setmetatable(L, -2);
381 lua_setfield(L, -2, "__simgrid_host"); /* put the userdata as field of the table */
386 static int Host_self(lua_State * L)
388 m_host_t host = MSG_host_self();
390 m_host_t *lua_host =(m_host_t *)lua_newuserdata(L,sizeof(m_host_t));
392 luaL_getmetatable(L, HOST_MODULE_NAME);
393 lua_setmetatable(L, -2);
394 lua_setfield(L, -2, "__simgrid_host");
399 static int Host_get_property_value(lua_State * L)
401 m_host_t ht = checkHost(L, -2);
402 const char *prop = luaL_checkstring(L, -1);
403 lua_pushstring(L,MSG_host_get_property_value(ht,prop));
407 static int Host_sleep(lua_State *L)
409 int time = luaL_checknumber(L, -1);
410 MSG_process_sleep(time);
414 static int Host_destroy(lua_State *L)
416 m_host_t ht = checkHost(L, -1);
417 __MSG_host_destroy(ht);
421 /* ********************************************************************************* */
422 /* lua_stub_generator functions */
423 /* ********************************************************************************* */
425 xbt_dict_t process_function_set;
426 xbt_dynar_t process_list;
427 xbt_dict_t machine_set;
428 static s_process_t process;
430 void s_process_free(void *process)
432 s_process_t *p = (s_process_t *) process;
434 for (i = 0; i < p->argc; i++)
440 static int gras_add_process_function(lua_State * L)
443 const char *process_host = luaL_checkstring(L, 1);
444 const char *process_function = luaL_checkstring(L, 2);
446 if (xbt_dict_is_empty(machine_set)
447 || xbt_dict_is_empty(process_function_set)
448 || xbt_dynar_is_empty(process_list)) {
449 process_function_set = xbt_dict_new();
450 process_list = xbt_dynar_new(sizeof(s_process_t), s_process_free);
451 machine_set = xbt_dict_new();
454 xbt_dict_set(machine_set, process_host, NULL, NULL);
455 xbt_dict_set(process_function_set, process_function, NULL, NULL);
458 process.argv = xbt_new(char *, 1);
459 process.argv[0] = xbt_strdup(process_function);
460 process.host = strdup(process_host);
463 while (lua_next(L, 3) != 0) {
464 arg = lua_tostring(L, -1);
467 xbt_realloc(process.argv, (process.argc) * sizeof(char *));
468 process.argv[(process.argc) - 1] = xbt_strdup(arg);
470 XBT_DEBUG("index = %f , arg = %s \n", lua_tonumber(L, -2),
471 lua_tostring(L, -1));
475 //add to the process list
476 xbt_dynar_push(process_list, &process);
481 static int gras_generate(lua_State * L)
483 const char *project_name = luaL_checkstring(L, 1);
484 generate_sim(project_name);
485 generate_rl(project_name);
486 generate_makefile_local(project_name);
490 /***********************************
492 **********************************/
493 static int trace_start(lua_State *L)
501 static int trace_category(lua_State * L)
504 TRACE_category(luaL_checkstring(L, 1));
509 static int trace_set_task_category(lua_State *L)
512 TRACE_msg_set_task_category(checkTask(L, -2), luaL_checkstring(L, -1));
517 static int trace_end(lua_State *L)
524 //***********Register Methods *******************************************//
528 static const luaL_reg Host_methods[] = {
529 {"getByName", Host_get_by_name},
530 {"name", Host_get_name},
531 {"number", Host_number},
534 {"getPropValue", Host_get_property_value},
535 {"sleep", Host_sleep},
536 {"destroy",Host_destroy},
537 // Bypass XML Methods
538 {"setFunction", console_set_function},
539 {"setProperty", console_host_set_property},
543 static int Host_gc(lua_State * L)
545 m_host_t ht = checkHost(L, -1);
551 static int Host_tostring(lua_State * L)
553 lua_pushfstring(L, "Host :%p", lua_touserdata(L, 1));
557 static const luaL_reg Host_meta[] = {
559 {"__tostring", Host_tostring},
566 static const luaL_reg AS_methods[] = {
567 {"new", console_add_AS},
568 {"addHost",console_add_host},
569 {"addLink",console_add_link},
570 {"addRoute",console_add_route},
577 static const luaL_reg Trace_methods[] = {
578 {"start",trace_start},
579 {"category",trace_category},
580 {"setTaskCategory",trace_set_task_category},
581 {"finish",trace_end},
585 * Environment related
588 //extern lua_State *simgrid_lua_state;
590 static int run_lua_code(int argc, char **argv)
592 XBT_DEBUG("Run lua code %s", argv[0]);
593 lua_State *L = lua_newthread(simgrid_lua_state);
594 int ref = luaL_ref(simgrid_lua_state, LUA_REGISTRYINDEX); // protect the thread from being garbage collected
597 /* Start the co-routine */
598 lua_getglobal(L, argv[0]);
599 xbt_assert(lua_isfunction(L, -1),
600 "The lua function %s does not seem to exist", argv[0]);
602 // push arguments onto the stack
604 for (i = 1; i < argc; i++)
605 lua_pushstring(L, argv[i]);
607 // Call the function (in resume)
609 err = lua_pcall(L, argc - 1, 1, 0);
610 xbt_assert(err == 0, "error running function `%s': %s", argv[0],
611 lua_tostring(L, -1));
613 /* retrieve result */
614 if (lua_isnumber(L, -1)) {
615 res = lua_tonumber(L, -1);
616 lua_pop(L, 1); /* pop returned value */
619 luaL_unref(simgrid_lua_state, LUA_REGISTRYINDEX, ref);
620 XBT_DEBUG("Execution of lua code %s is over", (argv ? argv[0] : "(null)"));
624 static int launch_application(lua_State * L)
626 const char *file = luaL_checkstring(L, 1);
627 MSG_function_register_default(run_lua_code);
628 MSG_launch_application(file);
632 #include "simix/simix.h" //FIXME: KILLME when debugging on simix internals become useless
633 static int create_environment(lua_State * L)
635 const char *file = luaL_checkstring(L, 1);
636 XBT_DEBUG("Loading environment file %s", file);
637 MSG_create_environment(file);
640 xbt_dict_t hosts = SIMIX_host_get_dict();
645 xbt_dict_foreach(hosts, c, name, host) {
646 XBT_DEBUG("We have an host %s", SIMIX_host_get_name(host));
653 static int debug(lua_State * L)
655 const char *str = luaL_checkstring(L, 1);
656 XBT_DEBUG("%s", str);
660 static int info(lua_State * L)
662 const char *str = luaL_checkstring(L, 1);
667 static int run(lua_State * L)
673 static int clean(lua_State * L)
680 * Bypass XML Parser (lua console)
684 * Register platform for MSG
686 static int msg_register_platform(lua_State * L)
688 /* Tell Simgrid we dont wanna use its parser */
689 surf_parse = console_parse_platform;
690 surf_parse_reset_callbacks();
691 surf_config_models_setup(NULL);
692 MSG_create_environment(NULL);
697 * Register platform for Simdag
700 static int sd_register_platform(lua_State * L)
702 surf_parse = console_parse_platform_wsL07;
703 surf_parse_reset_callbacks();
704 surf_config_models_setup(NULL);
705 SD_create_environment(NULL);
710 * Register platform for gras
712 static int gras_register_platform(lua_State * L)
714 /* Tell Simgrid we dont wanna use surf parser */
715 surf_parse = console_parse_platform;
716 surf_parse_reset_callbacks();
717 surf_config_models_setup(NULL);
718 gras_create_environment(NULL);
723 * Register applicaiton for MSG
725 static int msg_register_application(lua_State * L)
727 MSG_function_register_default(run_lua_code);
728 surf_parse = console_parse_application;
729 MSG_launch_application(NULL);
734 * Register application for gras
736 static int gras_register_application(lua_State * L)
738 gras_function_register_default(run_lua_code);
739 surf_parse = console_parse_application;
740 gras_launch_application(NULL);
744 static const luaL_Reg simgrid_funcs[] = {
745 {"create_environment", create_environment},
746 {"launch_application", launch_application},
752 {"platform", create_environment},
753 {"application", launch_application},
754 /* methods to bypass XML parser */
755 {"msg_register_platform", msg_register_platform},
756 {"sd_register_platform", sd_register_platform},
757 {"msg_register_application", msg_register_application},
758 {"gras_register_platform", gras_register_platform},
759 {"gras_register_application", gras_register_application},
760 /* gras sub generator method */
761 {"gras_set_process_function", gras_add_process_function},
762 {"gras_generate", gras_generate},
766 /* ********************************************************************************* */
767 /* module management functions */
768 /* ********************************************************************************* */
770 #define LUA_MAX_ARGS_COUNT 10 /* maximum amount of arguments we can get from lua on command line */
772 int luaopen_simgrid(lua_State * L); // Fuck gcc: we don't need that prototype
773 int luaopen_simgrid(lua_State * L)
775 XBT_DEBUG("Luaopen_Simgrid *****");
776 char **argv = malloc(sizeof(char *) * LUA_MAX_ARGS_COUNT);
778 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? */
779 /* Get the command line arguments from the lua interpreter */
780 lua_getglobal(L, "arg");
781 /* if arg is a null value, it means we use lua only as a script to init platform
782 * else it should be a table and then take arg in consideration
784 if (lua_istable(L, -1)) {
788 lua_pushinteger(L, argc - 2);
790 if (lua_isnil(L, -1)) {
793 xbt_assert(lua_isstring(L, -1),
794 "argv[%d] got from lua is no string", argc - 1);
795 xbt_assert(argc < LUA_MAX_ARGS_COUNT,
796 "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",
797 __FILE__, LUA_MAX_ARGS_COUNT - 1);
798 argv[argc - 1] = (char *) luaL_checkstring(L, -1);
800 XBT_DEBUG("Got command line argument %s from lua", argv[argc - 1]);
805 /* Initialize the MSG core */
806 MSG_global_init(&argc, argv);
807 XBT_DEBUG("Still %d arguments on command line", argc); // FIXME: update the lua's arg table to reflect the changes from SimGrid
809 /* register the core C functions to lua */
810 luaL_register(L, "simgrid", simgrid_funcs);
811 /* register the task methods to lua */
812 luaL_openlib(L, TASK_MODULE_NAME, Task_methods, 0); //create methods table,add it to the globals
813 luaL_newmetatable(L, TASK_MODULE_NAME); //create metatable for Task,add it to the Lua registry
814 luaL_openlib(L, 0, Task_meta, 0); // fill metatable
815 lua_pushliteral(L, "__index");
816 lua_pushvalue(L, -3); //dup methods table
817 lua_rawset(L, -3); //matatable.__index = methods
818 lua_pushliteral(L, "__metatable");
819 lua_pushvalue(L, -3); //dup methods table
820 lua_rawset(L, -3); //hide metatable:metatable.__metatable = methods
821 lua_pop(L, 1); //drop metatable
823 /* register the hosts methods to lua */
824 luaL_openlib(L, HOST_MODULE_NAME, Host_methods, 0);
825 luaL_newmetatable(L, HOST_MODULE_NAME);
826 luaL_openlib(L, 0, Host_meta, 0);
827 lua_pushliteral(L, "__index");
828 lua_pushvalue(L, -3);
830 lua_pushliteral(L, "__metatable");
831 lua_pushvalue(L, -3);
835 /* register the links methods to lua */
836 luaL_openlib(L, AS_MODULE_NAME, AS_methods, 0);
837 luaL_newmetatable(L, AS_MODULE_NAME);
842 /*register the Tracing functions to lua */
843 luaL_openlib(L, TRACE_MODULE_NAME, Trace_methods, 0);
844 luaL_newmetatable(L, TRACE_MODULE_NAME);
847 /* Keep the context mechanism informed of our lua world today */
848 simgrid_lua_state = L;