Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Lua: return errors from execute/send/recv, or nil in case of success
[simgrid.git] / src / bindings / lua / simgrid_lua.c
1 /* Copyright (c) 2010. The SimGrid Team.
2  * All rights reserved.                                                     */
3
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. */
6
7 /* SimGrid Lua bindings                                                     */
8
9 #include "simgrid_lua.h"
10 #include "lua_state_cloner.h"
11 #include "lua_utils.h"
12
13 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(lua, bindings, "Lua Bindings");
14
15 #define TASK_MODULE_NAME "simgrid.task"
16 #define HOST_MODULE_NAME "simgrid.host"
17 // Surf (bypass XML)
18 #define LINK_MODULE_NAME "simgrid.link"
19 #define ROUTE_MODULE_NAME "simgrid.route"
20 #define PLATF_MODULE_NAME "simgrid.platf"
21
22 static lua_State* sglua_maestro_state;
23
24 int luaopen_simgrid(lua_State *L);
25 static void register_c_functions(lua_State *L);
26 static int run_lua_code(int argc, char **argv);
27
28 /* ********************************************************************************* */
29 /*                                simgrid.task API                                   */
30 /* ********************************************************************************* */
31
32 /**
33  * \brief Ensures that a value in the stack is a valid task and returns it.
34  * \param L a Lua state
35  * \param index an index in the Lua stack
36  * \return the C task corresponding to this Lua task
37  */
38 static m_task_t sglua_checktask(lua_State* L, int index)
39 {
40   sglua_stack_dump("check task: ", L);
41   luaL_checktype(L, index, LUA_TTABLE);
42                                   /* ... task ... */
43   lua_getfield(L, index, "__simgrid_task");
44                                   /* ... task ... ctask */
45   m_task_t task = *((m_task_t*) luaL_checkudata(L, -1, TASK_MODULE_NAME));
46   lua_pop(L, 1);
47                                   /* ... task ... */
48
49   if (task == NULL) {
50     luaL_error(L, "This task was sent to someone else, you cannot access it anymore");
51   }
52
53   return task;
54 }
55
56 /**
57  * \brief Creates a new task and leaves it onto the stack.
58  * \param L a Lua state
59  * \return number of values returned to Lua
60  *
61  * - Argument 1 (string): name of the task
62  * - Argument 2 (number): computation size
63  * - Argument 3 (number): communication size
64  * - Return value (task): the task created
65  *
66  * A Lua task is a regular table with a full userdata inside, and both share
67  * the same metatable. For the regular table, the metatable allows OO-style
68  * writing such as your_task:send(someone).
69  * For the userdata, the metatable is used to check its type.
70  */
71 static int l_task_new(lua_State* L)
72 {
73   XBT_DEBUG("Task new");
74   const char* name = luaL_checkstring(L, 1);
75   int comp_size = luaL_checkint(L, 2);
76   int msg_size = luaL_checkint(L, 3);
77                                   /* name comp comm */
78   lua_settop(L, 0);
79                                   /* -- */
80   m_task_t msg_task = MSG_task_create(name, comp_size, msg_size, NULL);
81
82   lua_newtable(L);
83                                   /* task */
84   luaL_getmetatable(L, TASK_MODULE_NAME);
85                                   /* task mt */
86   lua_setmetatable(L, -2);
87                                   /* task */
88   m_task_t* lua_task = (m_task_t*) lua_newuserdata(L, sizeof(m_task_t));
89                                   /* task ctask */
90   *lua_task = msg_task;
91   luaL_getmetatable(L, TASK_MODULE_NAME);
92                                   /* task ctask mt */
93   lua_setmetatable(L, -2);
94                                   /* task ctask */
95   lua_setfield(L, -2, "__simgrid_task");
96                                   /* task */
97   return 1;
98 }
99
100 /**
101  * \brief Returns the name of a task.
102  * \param L a Lua state
103  * \return number of values returned to Lua
104  *
105  * - Argument 1 (task): a task
106  * - Return value (string): name of the task
107  */
108 static int l_task_get_name(lua_State* L)
109 {
110   m_task_t task = sglua_checktask(L, 1);
111   lua_pushstring(L, MSG_task_get_name(task));
112   return 1;
113 }
114
115 /**
116  * \brief Returns the computation duration of a task.
117  * \param L a Lua state
118  * \return number of values returned to Lua
119  *
120  * - Argument 1 (task): a task
121  * - Return value (number): computation duration of this task
122  */
123 static int l_task_get_computation_duration(lua_State* L)
124 {
125   m_task_t task = sglua_checktask(L, 1);
126   lua_pushnumber(L, MSG_task_get_compute_duration(task));
127   return 1;
128 }
129
130 /**
131  * \brief Executes a task.
132  * \param L a Lua state
133  * \return number of values returned to Lua
134  *
135  * - Argument 1 (task): the task to execute
136  * - Return value (nil / error): none if the task was successfully executed, or an error
137  * string in case of failure, which may be "task canceled" or "host failure"
138  */
139 static int l_task_execute(lua_State* L)
140 {
141   m_task_t task = sglua_checktask(L, 1);
142   MSG_error_t res = MSG_task_execute(task);
143
144   switch (res) {
145
146     case MSG_OK:
147       return 0;
148
149     case MSG_TASK_CANCELED:
150       lua_pushliteral(L, "task canceled");
151       return 1;
152
153     case MSG_HOST_FAILURE:
154       lua_pushliteral(L, "host failure");
155       return 1;
156
157     default:
158       xbt_die("Unexpected result of MSG_task_execute(): %d, please report this bug", res);
159   }
160 }
161
162 /**
163  * \brief Sends a task to a mailbox and waits for its completion.
164  * \param L a Lua state
165  * \return number of values returned to Lua
166  *
167  * - Argument 1 (task): the task to send
168  * - Argument 2 (string): mailbox
169  * - Return value (nil / error): none if the communication was successful, or an error string
170  * in case of failure, which may be "timeout", "host failure" or
171  * "transfer failure"
172  */
173 static int l_task_send(lua_State* L)
174 {
175   m_task_t task = sglua_checktask(L, 1);
176   const char* mailbox = luaL_checkstring(L, 2);
177                                   /* task mailbox */
178   lua_settop(L, 1);
179                                   /* task */
180   /* copy my stack into the task, so that the receiver can copy the lua task */
181   MSG_task_set_data(task, L);
182   MSG_error_t res = MSG_task_send(task, mailbox);
183   while (MSG_task_get_data(task) != NULL) {
184     /* don't mess up with my stack: the receiver didn't copy the data yet */
185     MSG_process_sleep(0);
186   }
187
188   switch (res) {
189
190   case MSG_OK:
191     /* the receiver is the owner of the task and may destroy it:
192      * remove the C task on my side so that I don't garbage collect it */
193     lua_getfield(L, 1, "__simgrid_task");
194                                   /* task ctask */
195     m_task_t* udata = (m_task_t*) luaL_checkudata(L, -1, TASK_MODULE_NAME);
196     *udata = NULL;
197     return 0;
198
199   case MSG_TIMEOUT:
200     XBT_DEBUG("MSG_task_send failed: timeout");
201     lua_settop(L, 0);
202     lua_pushliteral(L, "timeout");
203     return 1;
204
205   case MSG_TRANSFER_FAILURE:
206     XBT_DEBUG("MSG_task_send failed: transfer failure");
207     lua_settop(L, 0);
208     lua_pushliteral(L, "transfer failure");
209     return 1;
210
211   case MSG_HOST_FAILURE:
212     XBT_DEBUG("MSG_task_send failed: host failure");
213     lua_settop(L, 0);
214     lua_pushliteral(L, "host failure");
215     return 1;
216
217   default:
218     xbt_die("Unexpected result of MSG_task_send: %d, please report this bug", res);
219   }
220 }
221
222 /**
223  * \brief Receives a task.
224  * \param L a Lua state
225  * \return number of values returned to Lua
226  *
227  * - Argument 1 (string): mailbox
228  * - Argument 2 (number, optional): timeout (default is no timeout)
229  * - Return value (task / nil+err): the task received, or nil plus an error message if
230  * the communication has failed
231  */
232 static int l_task_recv(lua_State *L)
233 {
234   m_task_t task = NULL;
235   const char* mailbox = luaL_checkstring(L, 1);
236   int timeout;
237   if (lua_gettop(L) >= 2) {
238                                   /* mailbox timeout */
239     timeout = luaL_checknumber(L, 2);
240   }
241   else {
242                                   /* mailbox */
243     timeout = -1;
244     /* no timeout by default */
245   }
246   lua_settop(L, 0);
247                                   /* -- */
248   MSG_error_t res = MSG_task_receive_with_timeout(&task, mailbox, timeout);
249
250   switch (res) {
251
252   case MSG_OK:
253     /* copy the data directly from sender's stack */
254   {
255     lua_State* sender_stack = MSG_task_get_data(task);
256     sglua_copy_value(sender_stack, L);
257                                   /* task */
258     MSG_task_set_data(task, NULL);
259     return 1;
260   }
261
262   case MSG_TIMEOUT:
263     XBT_DEBUG("MSG_task_send failed: timeout");
264     lua_pushnil(L);
265     lua_pushliteral(L, "timeout");
266     return 2;
267
268   case MSG_TRANSFER_FAILURE:
269     XBT_DEBUG("MSG_task_send failed: transfer failure");
270     lua_pushnil(L);
271     lua_pushliteral(L, "transfer failure");
272     return 2;
273
274   case MSG_HOST_FAILURE:
275     XBT_DEBUG("MSG_task_send failed: host failure");
276     lua_pushnil(L);
277     lua_pushliteral(L, "host failure");
278     return 2;
279
280   default:
281     xbt_die("Unexpected result of MSG_task_recv: %d, please report this bug", res);
282   }
283 }
284
285 static const luaL_reg task_functions[] = {
286   {"new", l_task_new},
287   {"get_name", l_task_get_name},
288   {"get_computation_duration", l_task_get_computation_duration},
289   {"execute", l_task_execute},
290   {"send", l_task_send},
291   {"recv", l_task_recv},
292   {NULL, NULL}
293 };
294
295 /**
296  * \brief Finalizes the userdata of a task.
297  * \param L a Lua state
298  * \return number of values returned to Lua
299  *
300  * - Argument 1 (userdata): a C task, possibly NULL if it was sent to another
301  * Lua state
302  */
303 static int l_task_gc(lua_State* L)
304 {
305                                   /* ctask */
306   m_task_t task = *((m_task_t*) luaL_checkudata(L, 1, TASK_MODULE_NAME));
307   /* the task is NULL if I sent it to someone else */
308   if (task != NULL) {
309     MSG_task_destroy(task);
310   }
311   return 0;
312 }
313
314 /**
315  * \brief Returns a string representation of a C task.
316  * \param L a Lua state
317  * \return number of values returned to Lua
318  *
319  * - Argument 1 (userdata): a task
320  * - Return value (string): a string describing this task
321  */
322 static int l_task_tostring(lua_State* L)
323 {
324   m_task_t task = *((m_task_t*) luaL_checkudata(L, 1, TASK_MODULE_NAME));
325   lua_pushfstring(L, "Task: %p", task);
326   return 1;
327 }
328
329 /**
330  * \brief Metamethods of both a task table and the userdata inside it.
331  */
332 static const luaL_reg task_meta[] = {
333   {"__gc", l_task_gc}, /* will be called only for userdata */
334   {"__tostring", l_task_tostring},
335   {NULL, NULL}
336 };
337
338 /* ********************************************************************************* */
339 /*                                simgrid.host API                                   */
340 /* ********************************************************************************* */
341
342 /**
343  * \brief Ensures that a value in the stack is a host and returns it.
344  * \param L a Lua state
345  * \param index an index in the Lua stack
346  * \return the C host corresponding to this Lua host
347  */
348 static m_host_t sglua_checkhost(lua_State * L, int index)
349 {
350   m_host_t *pi, ht;
351   luaL_checktype(L, index, LUA_TTABLE);
352   lua_getfield(L, index, "__simgrid_host");
353   pi = (m_host_t *) luaL_checkudata(L, lua_gettop(L), HOST_MODULE_NAME);
354   if (pi == NULL)
355     luaL_typerror(L, index, HOST_MODULE_NAME);
356   ht = *pi;
357   if (!ht)
358     luaL_error(L, "null Host");
359   lua_pop(L, 1);
360   return ht;
361 }
362
363 /**
364  * \brief Returns a host given its name.
365  * \param L a Lua state
366  * \return number of values returned to Lua
367  *
368  * - Argument 1 (string): name of a host
369  * - Return value (host): the corresponding host
370  */
371 static int l_host_get_by_name(lua_State * L)
372 {
373   const char *name = luaL_checkstring(L, 1);
374   XBT_DEBUG("Getting Host from name...");
375   m_host_t msg_host = MSG_get_host_by_name(name);
376   if (!msg_host) {
377     luaL_error(L, "null Host : MSG_get_host_by_name failed");
378   }
379   lua_newtable(L);              /* create a table, put the userdata on top of it */
380   m_host_t *lua_host = (m_host_t *) lua_newuserdata(L, sizeof(m_host_t));
381   *lua_host = msg_host;
382   luaL_getmetatable(L, HOST_MODULE_NAME);
383   lua_setmetatable(L, -2);
384   lua_setfield(L, -2, "__simgrid_host");        /* put the userdata as field of the table */
385   /* remove the args from the stack */
386   lua_remove(L, 1);
387   return 1;
388 }
389
390 /**
391  * \brief Returns the name of a host.
392  * \param L a Lua state
393  * \return number of values returned to Lua
394  *
395  * - Argument 1 (host): a host
396  * - Return value (string): name of this host
397  */
398 static int l_host_get_name(lua_State * L)
399 {
400   m_host_t ht = sglua_checkhost(L, 1);
401   lua_pushstring(L, MSG_host_get_name(ht));
402   return 1;
403 }
404
405 /**
406  * \brief Returns the number of existing hosts.
407  * \param L a Lua state
408  * \return number of values returned to Lua
409  *
410  * - Return value (number): number of hosts
411  */
412 static int l_host_number(lua_State * L)
413 {
414   lua_pushnumber(L, MSG_get_host_number());
415   return 1;
416 }
417
418 /**
419  * \brief Returns the host given its index.
420  * \param L a Lua state
421  * \return number of values returned to Lua
422  *
423  * - Argument 1 (number): an index (1 is the first)
424  * - Return value (host): the host at this index
425  */
426 static int l_host_at(lua_State * L)
427 {
428   int index = luaL_checkinteger(L, 1);
429   m_host_t host = MSG_get_host_table()[index - 1];      // lua indexing start by 1 (lua[1] <=> C[0])
430   lua_newtable(L);              /* create a table, put the userdata on top of it */
431   m_host_t *lua_host = (m_host_t *) lua_newuserdata(L, sizeof(m_host_t));
432   *lua_host = host;
433   luaL_getmetatable(L, HOST_MODULE_NAME);
434   lua_setmetatable(L, -2);
435   lua_setfield(L, -2, "__simgrid_host");        /* put the userdata as field of the table */
436   return 1;
437 }
438
439 /**
440  * \brief Returns the host where the current process is located.
441  * \param L a Lua state
442  * \return number of values returned to Lua
443  *
444  * - Return value (host): the current host
445  */
446 static int l_host_self(lua_State * L)
447 {
448                                   /* -- */
449   m_host_t host = MSG_host_self();
450   lua_newtable(L);
451                                   /* table */
452   m_host_t* lua_host = (m_host_t*) lua_newuserdata(L, sizeof(m_host_t));
453                                   /* table ud */
454   *lua_host = host;
455   luaL_getmetatable(L, HOST_MODULE_NAME);
456                                   /* table ud mt */
457   lua_setmetatable(L, -2);
458                                   /* table ud */
459   lua_setfield(L, -2, "__simgrid_host");
460                                   /* table */
461   return 1;
462 }
463
464 /**
465  * \brief Returns the value of a host property.
466  * \param L a Lua state
467  * \return number of values returned to Lua
468  *
469  * - Argument 1 (host): a host
470  * - Argument 2 (string): name of the property to get
471  * - Return value (string): the value of this property
472  */
473 static int l_host_get_property_value(lua_State * L)
474 {
475   m_host_t ht = sglua_checkhost(L, 1);
476   const char *prop = luaL_checkstring(L, 2);
477   lua_pushstring(L,MSG_host_get_property_value(ht,prop));
478   return 1;
479 }
480
481 /**
482  * \brief Makes the current process sleep for a while.
483  * \param L a Lua state
484  * \return number of values returned to Lua
485  *
486  * - Argument 1 (number): duration of the sleep
487  */
488 static int l_host_sleep(lua_State *L)
489 {
490   int time = luaL_checknumber(L, 1);
491   MSG_process_sleep(time);
492   return 0;
493 }
494
495 /**
496  * \brief Destroys a host.
497  * \param L a Lua state
498  * \return number of values returned to Lua
499  *
500  * - Argument 1 (host): the host to destroy
501  */
502 static int l_host_destroy(lua_State *L)
503 {
504   m_host_t ht = sglua_checkhost(L, 1);
505   __MSG_host_destroy(ht);
506   return 0;
507 }
508
509 static const luaL_reg host_functions[] = {
510   {"get_by_name", l_host_get_by_name},
511   {"name", l_host_get_name},
512   {"number", l_host_number},
513   {"at", l_host_at},
514   {"self", l_host_self},
515   {"get_prop_value", l_host_get_property_value},
516   {"sleep", l_host_sleep},
517   {"destroy", l_host_destroy},
518   // Bypass XML Methods
519   {"set_function", console_set_function},
520   {"set_property", console_host_set_property},
521   {NULL, NULL}
522 };
523
524 /**
525  * \brief Returns a string representation of a host.
526  * \param L a Lua state
527  * \return number of values returned to Lua
528  *
529  * - Argument 1 (userdata): a host
530  * - Return value (string): a string describing this host
531  */
532 static int l_host_tostring(lua_State * L)
533 {
534   lua_pushfstring(L, "Host :%p", lua_touserdata(L, 1));
535   return 1;
536 }
537
538 static const luaL_reg host_meta[] = {
539   {"__tostring", l_host_tostring},
540   {0, 0}
541 };
542
543 /* ********************************************************************************* */
544 /*                           lua_stub_generator functions                            */
545 /* ********************************************************************************* */
546
547 xbt_dict_t process_function_set;
548 xbt_dynar_t process_list;
549 xbt_dict_t machine_set;
550 static s_process_t process;
551
552 void s_process_free(void *process)
553 {
554   s_process_t *p = (s_process_t *) process;
555   int i;
556   for (i = 0; i < p->argc; i++)
557     free(p->argv[i]);
558   free(p->argv);
559   free(p->host);
560 }
561
562 static int gras_add_process_function(lua_State * L)
563 {
564   const char *arg;
565   const char *process_host = luaL_checkstring(L, 1);
566   const char *process_function = luaL_checkstring(L, 2);
567
568   if (xbt_dict_is_empty(machine_set)
569       || xbt_dict_is_empty(process_function_set)
570       || xbt_dynar_is_empty(process_list)) {
571     process_function_set = xbt_dict_new();
572     process_list = xbt_dynar_new(sizeof(s_process_t), s_process_free);
573     machine_set = xbt_dict_new();
574   }
575
576   xbt_dict_set(machine_set, process_host, NULL, NULL);
577   xbt_dict_set(process_function_set, process_function, NULL, NULL);
578
579   process.argc = 1;
580   process.argv = xbt_new(char *, 1);
581   process.argv[0] = xbt_strdup(process_function);
582   process.host = strdup(process_host);
583
584   lua_pushnil(L);
585   while (lua_next(L, 3) != 0) {
586     arg = lua_tostring(L, -1);
587     process.argc++;
588     process.argv =
589         xbt_realloc(process.argv, (process.argc) * sizeof(char *));
590     process.argv[(process.argc) - 1] = xbt_strdup(arg);
591
592     XBT_DEBUG("index = %f , arg = %s \n", lua_tonumber(L, -2),
593            lua_tostring(L, -1));
594     lua_pop(L, 1);
595   }
596   lua_pop(L, 1);
597   //add to the process list
598   xbt_dynar_push(process_list, &process);
599   return 0;
600 }
601
602 static int gras_generate(lua_State * L)
603 {
604   const char *project_name = luaL_checkstring(L, 1);
605   generate_sim(project_name);
606   generate_rl(project_name);
607   generate_makefile_local(project_name);
608   return 0;
609 }
610
611 /* ********************************************************************************* */
612 /*                               simgrid.platf API                                   */
613 /* ********************************************************************************* */
614
615 static const luaL_reg platf_functions[] = {
616     {"open", console_open},
617     {"close", console_close},
618     {"AS_open", console_AS_open},
619     {"AS_close", console_AS_close},
620     {"host_new", console_add_host},
621     {"link_new", console_add_link},
622     {"router_new", console_add_router},
623     {"route_new", console_add_route},
624     {NULL, NULL}
625 };
626
627 /* ********************************************************************************* */
628 /*                                  simgrid API                                      */
629 /* ********************************************************************************* */
630
631 /**
632  * \brief Deploys your application.
633  * \param L a Lua state
634  * \return number of values returned to Lua
635  *
636  * - Argument 1 (string): name of the deployment file to load
637  */
638 static int launch_application(lua_State * L)
639 {
640   const char *file = luaL_checkstring(L, 1);
641   MSG_function_register_default(run_lua_code);
642   MSG_launch_application(file);
643   return 0;
644 }
645
646 /**
647  * \brief Creates the platform.
648  * \param L a Lua state
649  * \return number of values returned to Lua
650  *
651  * - Argument 1 (string): name of the platform file to load
652  */
653 static int create_environment(lua_State * L)
654 {
655   const char *file = luaL_checkstring(L, 1);
656   XBT_DEBUG("Loading environment file %s", file);
657   MSG_create_environment(file);
658   return 0;
659 }
660
661 /**
662  * \brief Prints a log string with debug level.
663  * \param L a Lua state
664  * \return number of values returned to Lua
665  *
666  * - Argument 1 (string): the text to print
667  */
668 static int debug(lua_State * L)
669 {
670   const char *str = luaL_checkstring(L, 1);
671   XBT_DEBUG("%s", str);
672   return 0;
673 }
674
675 /**
676  * \brief Prints a log string with info level.
677  * \param L a Lua state
678  * \return number of values returned to Lua
679  *
680  * - Argument 1 (string): the text to print
681  */
682 static int info(lua_State * L)
683 {
684   const char *str = luaL_checkstring(L, 1);
685   XBT_INFO("%s", str);
686   return 0;
687 }
688
689 /**
690  * \brief Runs your application.
691  * \param L a Lua state
692  * \return number of values returned to Lua
693  */
694 static int run(lua_State * L)
695 {
696   MSG_main();
697   return 0;
698 }
699
700 /**
701  * \brief Cleans the simulation.
702  * \param L a Lua state
703  * \return number of values returned to Lua
704  */
705 static int simgrid_gc(lua_State * L)
706 {
707   MSG_clean();
708   return 0;
709 }
710
711 /*
712  * Register platform for MSG
713  */
714 static int msg_register_platform(lua_State * L)
715 {
716   /* Tell Simgrid we dont wanna use its parser */
717   //surf_parse = console_parse_platform;
718   surf_parse_reset_callbacks();
719   MSG_create_environment(NULL);
720   return 0;
721 }
722
723 /*
724  * Register platform for Simdag
725  */
726
727 static int sd_register_platform(lua_State * L)
728 {
729   //surf_parse = console_parse_platform_wsL07;
730   surf_parse_reset_callbacks();
731   SD_create_environment(NULL);
732   return 0;
733 }
734
735 /*
736  * Register platform for gras
737  */
738 static int gras_register_platform(lua_State * L)
739 {
740   //surf_parse = console_parse_platform;
741   surf_parse_reset_callbacks();
742   gras_create_environment(NULL);
743   return 0;
744 }
745
746 /**
747  * Register applicaiton for MSG
748  */
749 static int msg_register_application(lua_State * L)
750 {
751   MSG_function_register_default(run_lua_code);
752   //surf_parse = console_parse_application;
753   MSG_launch_application(NULL);
754   return 0;
755 }
756
757 /*
758  * Register application for gras
759  */
760 static int gras_register_application(lua_State * L)
761 {
762   gras_function_register_default(run_lua_code);
763   //surf_parse = console_parse_application;
764   gras_launch_application(NULL);
765   return 0;
766 }
767
768 static const luaL_Reg simgrid_functions[] = {
769   {"create_environment", create_environment},
770   {"launch_application", launch_application},
771   {"debug", debug},
772   {"info", info},
773   {"run", run},
774   /* short names */
775   {"platform", create_environment},
776   {"application", launch_application},
777   /* methods to bypass XML parser */
778   {"msg_register_platform", msg_register_platform},
779   {"sd_register_platform", sd_register_platform},
780   {"msg_register_application", msg_register_application},
781   {"gras_register_platform", gras_register_platform},
782   {"gras_register_application", gras_register_application},
783   /* gras sub generator method */
784   {"gras_set_process_function", gras_add_process_function},
785   {"gras_generate", gras_generate},
786   {NULL, NULL}
787 };
788
789 /* ********************************************************************************* */
790 /*                           module management functions                             */
791 /* ********************************************************************************* */
792
793 #define LUA_MAX_ARGS_COUNT 10   /* maximum amount of arguments we can get from lua on command line */
794
795 /**
796  * \brief Opens the simgrid Lua module.
797  *
798  * This function is called automatically by the Lua interpreter when some
799  * Lua code requires the "simgrid" module.
800  *
801  * \param L the Lua state
802  */
803 int luaopen_simgrid(lua_State *L)
804 {
805   XBT_DEBUG("luaopen_simgrid *****");
806
807   /* Get the command line arguments from the lua interpreter */
808   char **argv = malloc(sizeof(char *) * LUA_MAX_ARGS_COUNT);
809   int argc = 1;
810   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? */
811
812   lua_getglobal(L, "arg");
813   /* if arg is a null value, it means we use lua only as a script to init platform
814    * else it should be a table and then take arg in consideration
815    */
816   if (lua_istable(L, -1)) {
817     int done = 0;
818     while (!done) {
819       argc++;
820       lua_pushinteger(L, argc - 2);
821       lua_gettable(L, -2);
822       if (lua_isnil(L, -1)) {
823         done = 1;
824       } else {
825         xbt_assert(lua_isstring(L, -1),
826                     "argv[%d] got from lua is no string", argc - 1);
827         xbt_assert(argc < LUA_MAX_ARGS_COUNT,
828                     "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",
829                     __FILE__, LUA_MAX_ARGS_COUNT - 1);
830         argv[argc - 1] = (char *) luaL_checkstring(L, -1);
831         lua_pop(L, 1);
832         XBT_DEBUG("Got command line argument %s from lua", argv[argc - 1]);
833       }
834     }
835     argv[argc--] = NULL;
836
837     /* Initialize the MSG core */
838     MSG_global_init(&argc, argv);
839     XBT_DEBUG("Still %d arguments on command line", argc); // FIXME: update the lua's arg table to reflect the changes from SimGrid
840   }
841
842   /* Keep the context mechanism informed of our lua world today */
843   sglua_maestro_state = L;
844
845   /* initialize access to my tables by children Lua states */
846   lua_newtable(L);
847   lua_setfield(L, LUA_REGISTRYINDEX, "simgrid.maestro_tables");
848
849   register_c_functions(L);
850
851   return 1;
852 }
853
854 /**
855  * \brief Returns whether a Lua state is the maestro state.
856  * \param L a Lua state
857  * \return true if this is maestro
858  */
859 int sglua_is_maestro(lua_State* L) {
860   return L == sglua_maestro_state;
861 }
862
863 /**
864  * \brief Returns the maestro state.
865  * \return the maestro Lua state
866  */
867 lua_State* sglua_get_maestro(void) {
868   return sglua_maestro_state;
869 }
870
871 /**
872  * \brief Registers the task functions into the table simgrid.task.
873  *
874  * Also initialize the metatable of the task userdata type.
875  *
876  * \param L a lua state
877  */
878 static void register_task_functions(lua_State* L)
879 {
880   /* create a table simgrid.task and fill it with task functions */
881   luaL_openlib(L, TASK_MODULE_NAME, task_functions, 0);
882                                   /* simgrid.task */
883
884   /* create the metatable for tasks, add it to the Lua registry */
885   luaL_newmetatable(L, TASK_MODULE_NAME);
886                                   /* simgrid.task mt */
887   /* fill the metatable */
888   luaL_openlib(L, NULL, task_meta, 0);
889                                   /* simgrid.task mt */
890   lua_pushvalue(L, -2);
891                                   /* simgrid.task mt simgrid.task */
892   /* metatable.__index = simgrid.task
893    * we put the task functions inside the task itself:
894    * this allows to write task:method(args) for
895    * simgrid.task.method(task, args) */
896   lua_setfield(L, -2, "__index");
897                                   /* simgrid.task mt */
898   lua_pop(L, 2);
899                                   /* -- */
900 }
901
902 /**
903  * \brief Registers the host functions into the table simgrid.host.
904  *
905  * Also initialize the metatable of the host userdata type.
906  *
907  * \param L a lua state
908  */
909 static void register_host_functions(lua_State* L)
910 {
911   /* create a table simgrid.host and fill it with host functions */
912   luaL_openlib(L, HOST_MODULE_NAME, host_functions, 0);
913                                   /* simgrid.host */
914
915   /* create the metatable for host, add it to the Lua registry */
916   luaL_newmetatable(L, HOST_MODULE_NAME);
917                                   /* simgrid.host mt */
918   /* fill the metatable */
919   luaL_openlib(L, NULL, host_meta, 0);
920                                   /* simgrid.host mt */
921   lua_pushvalue(L, -2);
922                                   /* simgrid.host mt simgrid.host */
923   /* metatable.__index = simgrid.host
924    * we put the host functions inside the host userdata itself:
925    * this allows to write host(args) for
926    * simgrid.host.method(host, args) */
927   // FIXME: cannot work currently, same problem as tasks
928   lua_setfield(L, -2, "__index");
929                                   /* simgrid.host mt */
930   lua_pop(L, 2);
931                                   /* -- */
932 }
933
934 /**
935  * \brief Registers the platform functions into the table simgrid.platf.
936  * \param L a lua state
937  */
938 static void register_platf_functions(lua_State* L)
939 {
940   luaL_openlib(L, PLATF_MODULE_NAME, platf_functions, 0);
941                                   /* simgrid.platf */
942   lua_pop(L, 1);
943 }
944
945 /**
946  * \brief Makes the core functions available to the Lua world.
947  * \param L a Lua world
948  */
949 static void register_core_functions(lua_State *L)
950 {
951   /* register the core C functions to lua */
952   luaL_register(L, "simgrid", simgrid_functions);
953                                   /* simgrid */
954
955   /* set a finalizer that cleans simgrid, by adding to the simgrid module a
956    * dummy userdata whose __gc metamethod calls MSG_clean() */
957   lua_newuserdata(L, sizeof(void*));
958                                   /* simgrid udata */
959   lua_newtable(L);
960                                   /* simgrid udata mt */
961   lua_pushcfunction(L, simgrid_gc);
962                                   /* simgrid udata mt simgrid_gc */
963   lua_setfield(L, -2, "__gc");
964                                   /* simgrid udata mt */
965   lua_setmetatable(L, -2);
966                                   /* simgrid udata */
967   lua_setfield(L, -2, "__simgrid_loaded");
968                                   /* simgrid */
969   lua_pop(L, 1);
970                                   /* -- */
971 }
972
973 /**
974  * \brief Creates the simgrid module and make it available to Lua.
975  * \param L a Lua world
976  */
977 static void register_c_functions(lua_State *L)
978 {
979   register_core_functions(L);
980   register_task_functions(L);
981   register_host_functions(L);
982   register_platf_functions(L);
983 }
984
985 /**
986  * \brief Runs a Lua function as a new simulated process.
987  * \param argc number of arguments of the function
988  * \param argv name of the Lua function and array of its arguments
989  * \return result of the function
990  */
991 static int run_lua_code(int argc, char **argv)
992 {
993   XBT_DEBUG("Run lua code %s", argv[0]);
994
995   /* create a new state, getting globals from maestro */
996   lua_State *L = sglua_clone_maestro();
997   int res = 1;
998
999   /* start the function */
1000   lua_getglobal(L, argv[0]);
1001   xbt_assert(lua_isfunction(L, -1),
1002               "There is no Lua function with name `%s'", argv[0]);
1003
1004   /* push arguments onto the stack */
1005   int i;
1006   for (i = 1; i < argc; i++)
1007     lua_pushstring(L, argv[i]);
1008
1009   /* call the function */
1010   _XBT_GNUC_UNUSED int err;
1011   err = lua_pcall(L, argc - 1, 1, 0);
1012   xbt_assert(err == 0, "Error running function `%s': %s", argv[0],
1013               lua_tostring(L, -1));
1014
1015   /* retrieve result */
1016   if (lua_isnumber(L, -1)) {
1017     res = lua_tonumber(L, -1);
1018     lua_pop(L, 1);              /* pop returned value */
1019   }
1020
1021   XBT_DEBUG("Execution of Lua code %s is over", (argv ? argv[0] : "(null)"));
1022
1023   return res;
1024 }