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_DEBUG("MSG_task_send failed : Timeout");
179 case MSG_TRANSFER_FAILURE:
180 XBT_DEBUG("MSG_task_send failed : Transfer Failure");
182 case MSG_HOST_FAILURE:
183 XBT_DEBUG("MSG_task_send failed : Host Failure ");
187 ("MSG_task_send failed : Unexpected error , please report this bug");
193 static int Task_recv_with_timeout(lua_State *L)
196 const char *mailbox = luaL_checkstring(L, -2);
197 int timeout = luaL_checknumber(L, -1);
198 MSG_error_t res = MSG_task_receive_with_timeout(&tk, mailbox, timeout);
201 lua_State *sender_stack = MSG_task_get_data(tk);
202 lua_xmove(sender_stack, L, 1); // copy the data directly from sender's stack
203 MSG_task_set_data(tk, NULL);
208 XBT_DEBUG("MSG_task_receive failed : Timeout");
210 case MSG_TRANSFER_FAILURE:
211 XBT_DEBUG("MSG_task_receive failed : Transfer Failure");
213 case MSG_HOST_FAILURE:
214 XBT_DEBUG("MSG_task_receive failed : Host Failure ");
217 XBT_ERROR("MSG_task_receive failed : Unexpected error , please report this bug");
225 static int Task_recv(lua_State * L)
227 lua_pushnumber(L, -1.0);
228 return Task_recv_with_timeout(L);
232 * Static Binding for the Splay method event.sleep :
233 * it uses MSG_task_irecv with MSG_comm_wait
235 static int Task_splay_irecv(lua_State *L)
237 m_task_t task = NULL;
238 msg_comm_t comm = NULL; // current communication to receive
239 const char *mailbox = luaL_checkstring(L, -2);
240 double timeout = luaL_checknumber(L, -1);
241 comm = MSG_task_irecv(&task, mailbox);
242 MSG_comm_wait(comm, timeout);
243 if (MSG_comm_get_status(comm) == MSG_OK)
245 XBT_DEBUG("Task_splay_irecv: Received task %s", MSG_task_get_name(task));
246 lua_State *sender_stack = MSG_task_get_data(task);
247 lua_xmove(sender_stack, L, 1); // move the data directly from the sender's stack
248 MSG_task_set_data(task, NULL);
251 XBT_DEBUG("Task_splay_irecv: Timeout!");
254 MSG_comm_destroy(comm);
258 static int Task_splay_isend(lua_State *L)
260 m_task_t tk = checkTask(L, 1);
261 const char *mailbox = luaL_checkstring(L, 2);
262 lua_pop(L, 1); // remove the string from the stack so that the task is on top of it
263 MSG_task_set_data(tk, L); // copy my stack onto the task, so that the receiver can get the lua task directly
264 MSG_task_isend(tk, mailbox);
270 static const luaL_reg Task_methods[] = {
272 {"name", Task_get_name},
273 {"computation_duration", Task_computation_duration},
274 {"execute", Task_execute},
275 {"destroy", Task_destroy},
278 {"recv_timeout", Task_recv_with_timeout},
280 {"splay_recv", Task_splay_irecv},
281 {"iSend", Task_splay_isend},
286 static int Task_gc(lua_State * L)
288 m_task_t tk = checkTask(L, -1);
290 MSG_task_destroy(tk);
294 static int Task_tostring(lua_State * L)
296 lua_pushfstring(L, "Task :%p", lua_touserdata(L, 1));
300 static const luaL_reg Task_meta[] = {
302 {"__tostring", Task_tostring},
309 static m_host_t checkHost(lua_State * L, int index)
312 luaL_checktype(L, index, LUA_TTABLE);
313 lua_getfield(L, index, "__simgrid_host");
314 pi = (m_host_t *) luaL_checkudata(L, -1, HOST_MODULE_NAME);
316 luaL_typerror(L, index, HOST_MODULE_NAME);
319 luaL_error(L, "null Host");
324 static int Host_get_by_name(lua_State * L)
326 const char *name = luaL_checkstring(L, 1);
327 XBT_DEBUG("Getting Host from name...");
328 m_host_t msg_host = MSG_get_host_by_name(name);
330 luaL_error(L, "null Host : MSG_get_host_by_name failed");
332 lua_newtable(L); /* create a table, put the userdata on top of it */
333 m_host_t *lua_host = (m_host_t *) lua_newuserdata(L, sizeof(m_host_t));
334 *lua_host = msg_host;
335 luaL_getmetatable(L, HOST_MODULE_NAME);
336 lua_setmetatable(L, -2);
337 lua_setfield(L, -2, "__simgrid_host"); /* put the userdata as field of the table */
338 /* remove the args from the stack */
344 static int Host_get_name(lua_State * L)
346 m_host_t ht = checkHost(L, -1);
347 lua_pushstring(L, MSG_host_get_name(ht));
351 static int Host_number(lua_State * L)
353 lua_pushnumber(L, MSG_get_host_number());
357 static int Host_at(lua_State * L)
359 int index = luaL_checkinteger(L, 1);
360 m_host_t host = MSG_get_host_table()[index - 1]; // lua indexing start by 1 (lua[1] <=> C[0])
361 lua_newtable(L); /* create a table, put the userdata on top of it */
362 m_host_t *lua_host = (m_host_t *) lua_newuserdata(L, sizeof(m_host_t));
364 luaL_getmetatable(L, HOST_MODULE_NAME);
365 lua_setmetatable(L, -2);
366 lua_setfield(L, -2, "__simgrid_host"); /* put the userdata as field of the table */
371 static int Host_self(lua_State * L)
373 m_host_t host = MSG_host_self();
375 m_host_t *lua_host =(m_host_t *)lua_newuserdata(L,sizeof(m_host_t));
377 luaL_getmetatable(L, HOST_MODULE_NAME);
378 lua_setmetatable(L, -2);
379 lua_setfield(L, -2, "__simgrid_host");
384 static int Host_get_property_value(lua_State * L)
386 m_host_t ht = checkHost(L, -2);
387 const char *prop = luaL_checkstring(L, -1);
388 lua_pushstring(L,MSG_host_get_property_value(ht,prop));
392 static int Host_sleep(lua_State *L)
394 int time = luaL_checknumber(L, -1);
395 MSG_process_sleep(time);
399 static int Host_destroy(lua_State *L)
401 m_host_t ht = checkHost(L, -1);
402 __MSG_host_destroy(ht);
406 /* ********************************************************************************* */
407 /* lua_stub_generator functions */
408 /* ********************************************************************************* */
410 xbt_dict_t process_function_set;
411 xbt_dynar_t process_list;
412 xbt_dict_t machine_set;
413 static s_process_t process;
415 void s_process_free(void *process)
417 s_process_t *p = (s_process_t *) process;
419 for (i = 0; i < p->argc; i++)
425 static int gras_add_process_function(lua_State * L)
428 const char *process_host = luaL_checkstring(L, 1);
429 const char *process_function = luaL_checkstring(L, 2);
431 if (xbt_dict_is_empty(machine_set)
432 || xbt_dict_is_empty(process_function_set)
433 || xbt_dynar_is_empty(process_list)) {
434 process_function_set = xbt_dict_new();
435 process_list = xbt_dynar_new(sizeof(s_process_t), s_process_free);
436 machine_set = xbt_dict_new();
439 xbt_dict_set(machine_set, process_host, NULL, NULL);
440 xbt_dict_set(process_function_set, process_function, NULL, NULL);
443 process.argv = xbt_new(char *, 1);
444 process.argv[0] = xbt_strdup(process_function);
445 process.host = strdup(process_host);
448 while (lua_next(L, 3) != 0) {
449 arg = lua_tostring(L, -1);
452 xbt_realloc(process.argv, (process.argc) * sizeof(char *));
453 process.argv[(process.argc) - 1] = xbt_strdup(arg);
455 XBT_DEBUG("index = %f , arg = %s \n", lua_tonumber(L, -2),
456 lua_tostring(L, -1));
460 //add to the process list
461 xbt_dynar_push(process_list, &process);
466 static int gras_generate(lua_State * L)
468 const char *project_name = luaL_checkstring(L, 1);
469 generate_sim(project_name);
470 generate_rl(project_name);
471 generate_makefile_local(project_name);
475 /***********************************
477 **********************************/
478 static int trace_start(lua_State *L)
486 static int trace_category(lua_State * L)
489 TRACE_category(luaL_checkstring(L, 1));
494 static int trace_set_task_category(lua_State *L)
497 TRACE_msg_set_task_category(checkTask(L, -2), luaL_checkstring(L, -1));
502 static int trace_end(lua_State *L)
509 //***********Register Methods *******************************************//
513 static const luaL_reg Host_methods[] = {
514 {"getByName", Host_get_by_name},
515 {"name", Host_get_name},
516 {"number", Host_number},
519 {"getPropValue", Host_get_property_value},
520 {"sleep", Host_sleep},
521 {"destroy",Host_destroy},
522 // Bypass XML Methods
523 {"setFunction", console_set_function},
524 {"setProperty", console_host_set_property},
528 static int Host_gc(lua_State * L)
530 m_host_t ht = checkHost(L, -1);
536 static int Host_tostring(lua_State * L)
538 lua_pushfstring(L, "Host :%p", lua_touserdata(L, 1));
542 static const luaL_reg Host_meta[] = {
544 {"__tostring", Host_tostring},
551 static const luaL_reg AS_methods[] = {
552 {"new", console_add_AS},
553 {"addHost",console_add_host},
554 {"addLink",console_add_link},
555 {"addRoute",console_add_route},
562 static const luaL_reg Trace_methods[] = {
563 {"start",trace_start},
564 {"category",trace_category},
565 {"setTaskCategory",trace_set_task_category},
566 {"finish",trace_end},
570 * Environment related
573 //extern lua_State *simgrid_lua_state;
575 static int run_lua_code(int argc, char **argv)
577 XBT_DEBUG("Run lua code %s", argv[0]);
578 lua_State *L = lua_newthread(simgrid_lua_state);
579 int ref = luaL_ref(simgrid_lua_state, LUA_REGISTRYINDEX); /* protect the thread from being garbage collected */
582 /* start the co-routine */
583 lua_getglobal(L, argv[0]);
584 xbt_assert(lua_isfunction(L, -1),
585 "The lua function %s does not seem to exist", argv[0]);
587 /* push arguments onto the stack */
589 for (i = 1; i < argc; i++)
590 lua_pushstring(L, argv[i]);
592 /* call the function */
594 err = lua_pcall(L, argc - 1, 1, 0);
595 xbt_assert(err == 0, "error running function `%s': %s", argv[0],
596 lua_tostring(L, -1));
598 /* retrieve result */
599 if (lua_isnumber(L, -1)) {
600 res = lua_tonumber(L, -1);
601 lua_pop(L, 1); /* pop returned value */
605 luaL_unref(simgrid_lua_state, LUA_REGISTRYINDEX, ref);
606 XBT_DEBUG("Execution of lua code %s is over", (argv ? argv[0] : "(null)"));
610 static int launch_application(lua_State * L)
612 const char *file = luaL_checkstring(L, 1);
613 MSG_function_register_default(run_lua_code);
614 MSG_launch_application(file);
618 #include "simix/simix.h" //FIXME: KILLME when debugging on simix internals become useless
619 static int create_environment(lua_State * L)
621 const char *file = luaL_checkstring(L, 1);
622 XBT_DEBUG("Loading environment file %s", file);
623 MSG_create_environment(file);
626 xbt_dict_t hosts = SIMIX_host_get_dict();
631 xbt_dict_foreach(hosts, c, name, host) {
632 XBT_DEBUG("We have an host %s", SIMIX_host_get_name(host));
639 static int debug(lua_State * L)
641 const char *str = luaL_checkstring(L, 1);
642 XBT_DEBUG("%s", str);
646 static int info(lua_State * L)
648 const char *str = luaL_checkstring(L, 1);
653 static int run(lua_State * L)
659 static int clean(lua_State * L)
666 * Bypass XML Parser (lua console)
670 * Register platform for MSG
672 static int msg_register_platform(lua_State * L)
674 /* Tell Simgrid we dont wanna use its parser */
675 surf_parse = console_parse_platform;
676 surf_parse_reset_callbacks();
677 surf_config_models_setup(NULL);
678 MSG_create_environment(NULL);
683 * Register platform for Simdag
686 static int sd_register_platform(lua_State * L)
688 surf_parse = console_parse_platform_wsL07;
689 surf_parse_reset_callbacks();
690 surf_config_models_setup(NULL);
691 SD_create_environment(NULL);
696 * Register platform for gras
698 static int gras_register_platform(lua_State * L)
700 /* Tell Simgrid we dont wanna use surf parser */
701 surf_parse = console_parse_platform;
702 surf_parse_reset_callbacks();
703 surf_config_models_setup(NULL);
704 gras_create_environment(NULL);
709 * Register applicaiton for MSG
711 static int msg_register_application(lua_State * L)
713 MSG_function_register_default(run_lua_code);
714 surf_parse = console_parse_application;
715 MSG_launch_application(NULL);
720 * Register application for gras
722 static int gras_register_application(lua_State * L)
724 gras_function_register_default(run_lua_code);
725 surf_parse = console_parse_application;
726 gras_launch_application(NULL);
730 static const luaL_Reg simgrid_funcs[] = {
731 {"create_environment", create_environment},
732 {"launch_application", launch_application},
738 {"platform", create_environment},
739 {"application", launch_application},
740 /* methods to bypass XML parser */
741 {"msg_register_platform", msg_register_platform},
742 {"sd_register_platform", sd_register_platform},
743 {"msg_register_application", msg_register_application},
744 {"gras_register_platform", gras_register_platform},
745 {"gras_register_application", gras_register_application},
746 /* gras sub generator method */
747 {"gras_set_process_function", gras_add_process_function},
748 {"gras_generate", gras_generate},
752 /* ********************************************************************************* */
753 /* module management functions */
754 /* ********************************************************************************* */
756 #define LUA_MAX_ARGS_COUNT 10 /* maximum amount of arguments we can get from lua on command line */
758 int luaopen_simgrid(lua_State * L); // Fuck gcc: we don't need that prototype
759 int luaopen_simgrid(lua_State * L)
761 XBT_DEBUG("Luaopen_Simgrid *****");
762 char **argv = malloc(sizeof(char *) * LUA_MAX_ARGS_COUNT);
764 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? */
765 /* Get the command line arguments from the lua interpreter */
766 lua_getglobal(L, "arg");
767 /* if arg is a null value, it means we use lua only as a script to init platform
768 * else it should be a table and then take arg in consideration
770 if (lua_istable(L, -1)) {
774 lua_pushinteger(L, argc - 2);
776 if (lua_isnil(L, -1)) {
779 xbt_assert(lua_isstring(L, -1),
780 "argv[%d] got from lua is no string", argc - 1);
781 xbt_assert(argc < LUA_MAX_ARGS_COUNT,
782 "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",
783 __FILE__, LUA_MAX_ARGS_COUNT - 1);
784 argv[argc - 1] = (char *) luaL_checkstring(L, -1);
786 XBT_DEBUG("Got command line argument %s from lua", argv[argc - 1]);
791 /* Initialize the MSG core */
792 MSG_global_init(&argc, argv);
793 XBT_DEBUG("Still %d arguments on command line", argc); // FIXME: update the lua's arg table to reflect the changes from SimGrid
795 /* register the core C functions to lua */
796 luaL_register(L, "simgrid", simgrid_funcs);
797 /* register the task methods to lua */
798 luaL_openlib(L, TASK_MODULE_NAME, Task_methods, 0); //create methods table,add it to the globals
799 luaL_newmetatable(L, TASK_MODULE_NAME); //create metatable for Task,add it to the Lua registry
800 luaL_openlib(L, 0, Task_meta, 0); // fill metatable
801 lua_pushliteral(L, "__index");
802 lua_pushvalue(L, -3); //dup methods table
803 lua_rawset(L, -3); //matatable.__index = methods
804 lua_pushliteral(L, "__metatable");
805 lua_pushvalue(L, -3); //dup methods table
806 lua_rawset(L, -3); //hide metatable:metatable.__metatable = methods
807 lua_pop(L, 1); //drop metatable
809 /* register the hosts methods to lua */
810 luaL_openlib(L, HOST_MODULE_NAME, Host_methods, 0);
811 luaL_newmetatable(L, HOST_MODULE_NAME);
812 luaL_openlib(L, 0, Host_meta, 0);
813 lua_pushliteral(L, "__index");
814 lua_pushvalue(L, -3);
816 lua_pushliteral(L, "__metatable");
817 lua_pushvalue(L, -3);
821 /* register the links methods to lua */
822 luaL_openlib(L, AS_MODULE_NAME, AS_methods, 0);
823 luaL_newmetatable(L, AS_MODULE_NAME);
826 /* register the Tracing functions to lua */
827 luaL_openlib(L, TRACE_MODULE_NAME, Trace_methods, 0);
828 luaL_newmetatable(L, TRACE_MODULE_NAME);
831 /* Keep the context mechanism informed of our lua world today */
832 simgrid_lua_state = L;