Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
add a test trying to access the properties of a remote host -- it works
[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 COMM_MODULE_NAME "simgrid.comm"
17 #define HOST_MODULE_NAME "simgrid.host"
18 #define PROCESS_MODULE_NAME "simgrid.process"
19 // Surf (bypass XML)
20 #define LINK_MODULE_NAME "simgrid.link"
21 #define ROUTE_MODULE_NAME "simgrid.route"
22 #define PLATF_MODULE_NAME "simgrid.platf"
23
24 static lua_State* sglua_maestro_state;
25
26 static const char* msg_errors[] = {
27     NULL,
28     "timeout",
29     "transfer failure",
30     "host failure",
31     "task canceled"
32 };
33
34 int luaopen_simgrid(lua_State *L);
35 static void register_c_functions(lua_State *L);
36 static int run_lua_code(int argc, char **argv);
37
38 /* ********************************************************************************* */
39 /*                                simgrid.task API                                   */
40 /* ********************************************************************************* */
41
42 /**
43  * \brief Ensures that a value in the stack is a valid task and returns it.
44  * \param L a Lua state
45  * \param index an index in the Lua stack
46  * \return the C task corresponding to this Lua task
47  */
48 static m_task_t sglua_checktask(lua_State* L, int index)
49 {
50   sglua_stack_dump("check task: ", L);
51   luaL_checktype(L, index, LUA_TTABLE);
52                                   /* ... task ... */
53   lua_getfield(L, index, "__simgrid_task");
54                                   /* ... task ... ctask */
55   m_task_t task = *((m_task_t*) luaL_checkudata(L, -1, TASK_MODULE_NAME));
56   lua_pop(L, 1);
57                                   /* ... task ... */
58
59   if (task == NULL) {
60     luaL_error(L, "This task was sent to someone else, you cannot access it anymore");
61   }
62
63   return task;
64 }
65
66 /**
67  * \brief Creates a new task and leaves it onto the stack.
68  * \param L a Lua state
69  * \return number of values returned to Lua
70  *
71  * - Argument 1 (string): name of the task
72  * - Argument 2 (number): computation size
73  * - Argument 3 (number): communication size
74  * - Return value (task): the task created
75  *
76  * A Lua task is a regular table with a full userdata inside, and both share
77  * the same metatable. For the regular table, the metatable allows OO-style
78  * writing such as your_task:send(someone).
79  * For the userdata, the metatable is used to check its type.
80  * TODO: make the task name an optional last parameter
81  */
82 static int l_task_new(lua_State* L)
83 {
84   XBT_DEBUG("Task new");
85   const char* name = luaL_checkstring(L, 1);
86   int comp_size = luaL_checkint(L, 2);
87   int msg_size = luaL_checkint(L, 3);
88                                   /* name comp comm */
89   lua_settop(L, 0);
90                                   /* -- */
91   m_task_t msg_task = MSG_task_create(name, comp_size, msg_size, NULL);
92
93   lua_newtable(L);
94                                   /* task */
95   luaL_getmetatable(L, TASK_MODULE_NAME);
96                                   /* task mt */
97   lua_setmetatable(L, -2);
98                                   /* task */
99   m_task_t* lua_task = (m_task_t*) lua_newuserdata(L, sizeof(m_task_t));
100                                   /* task ctask */
101   *lua_task = msg_task;
102   luaL_getmetatable(L, TASK_MODULE_NAME);
103                                   /* task ctask mt */
104   lua_setmetatable(L, -2);
105                                   /* task ctask */
106   lua_setfield(L, -2, "__simgrid_task");
107                                   /* task */
108   return 1;
109 }
110
111 /**
112  * \brief Returns the name of a task.
113  * \param L a Lua state
114  * \return number of values returned to Lua
115  *
116  * - Argument 1 (task): a task
117  * - Return value (string): name of the task
118  */
119 static int l_task_get_name(lua_State* L)
120 {
121   m_task_t task = sglua_checktask(L, 1);
122   lua_pushstring(L, MSG_task_get_name(task));
123   return 1;
124 }
125
126 /**
127  * \brief Returns the computation duration of a task.
128  * \param L a Lua state
129  * \return number of values returned to Lua
130  *
131  * - Argument 1 (task): a task
132  * - Return value (number): computation duration of this task
133  */
134 static int l_task_get_computation_duration(lua_State* L)
135 {
136   m_task_t task = sglua_checktask(L, 1);
137   lua_pushnumber(L, MSG_task_get_compute_duration(task));
138   return 1;
139 }
140
141 /**
142  * \brief Executes a task.
143  * \param L a Lua state
144  * \return number of values returned to Lua
145  *
146  * - Argument 1 (task): the task to execute
147  * - Return value (nil or string): nil if the task was successfully executed,
148  * or an error string in case of failure, which may be "task canceled" or
149  * "host failure"
150  */
151 static int l_task_execute(lua_State* L)
152 {
153   m_task_t task = sglua_checktask(L, 1);
154   MSG_error_t res = MSG_task_execute(task);
155
156   if (res == MSG_OK) {
157     return 0;
158   }
159   else {
160     lua_pushstring(L, msg_errors[res]);
161     return 1;
162   }
163 }
164
165 /**
166  * \brief Pops the Lua task on top of the stack and registers it so that a
167  * receiver can retrieve it later knowing the C task.
168  *
169  * After calling this function, you can send the C task to someone and he
170  * will be able to also get the corresponding Lua task.
171  *
172  * \param L a lua state
173  */
174 static void task_register(lua_State* L) {
175
176   m_task_t task = sglua_checktask(L, -1);
177                                   /* ... task */
178   /* put in the C task a ref to the lua task so that the receiver finds it */
179   unsigned long ref = luaL_ref(L, LUA_REGISTRYINDEX);
180                                   /* ... */
181   MSG_task_set_data(task, (void*) ref);
182 }
183
184 /**
185  * \brief Pushes onto the stack the Lua task corresponding to a C task.
186  *
187  * The Lua task must have been previously registered with task_register so
188  * that it can be retrieved knowing the C task.
189  *
190  * \param L a lua state
191  * \param task a C task
192  */
193 static void task_unregister(lua_State* L, m_task_t task) {
194
195                                   /* ... */
196   /* the task is in my registry, put it onto my stack */
197   unsigned long ref = (unsigned long) MSG_task_get_data(task);
198   lua_rawgeti(L, LUA_REGISTRYINDEX, ref);
199                                   /* ... task */
200   luaL_unref(L, LUA_REGISTRYINDEX, ref);
201   MSG_task_set_data(task, NULL);
202 }
203
204 /**
205  * \brief When a C task has been received, retrieves the corresponding Lua
206  * task from the sender and pushes it onto the receiver's stack.
207  *
208  * This function should be called from the receiver process.
209  *
210  * \param dst the receiver
211  * \param task the task just received
212  */
213 static void task_copy(lua_State* dst, m_task_t task) {
214
215   m_process_t src_proc = MSG_task_get_sender(task);
216   lua_State* src = MSG_process_get_data(src_proc);
217
218                                   /* src: ...
219                                      dst: ... */
220   task_unregister(src, task);
221                                   /* src: ... task */
222   sglua_copy_value(src, dst);
223                                   /* src: ... task
224                                      dst: ... task */
225
226   /* the receiver is the owner of the task and may destroy it:
227    * make the C task NULL on the sender side so that it doesn't garbage
228    * collect it */
229   lua_getfield(src, -1, "__simgrid_task");
230                                   /* src: ... task ctask */
231   m_task_t* udata = (m_task_t*) luaL_checkudata(src, -1, TASK_MODULE_NAME);
232   *udata = NULL;
233   lua_pop(src, 2);
234                                   /* src: ... */
235 }
236
237 /**
238  * \brief Sends a task to a mailbox and waits for its completion.
239  * \param L a Lua state
240  * \return number of values returned to Lua
241  *
242  * - Argument 1 (task): the task to send
243  * - Argument 2 (string or compatible): mailbox name, as a real string or any
244  * type convertible to string (numbers always are)
245  * - Return values (boolean + string): true if the communication was successful,
246  * or false plus an error string in case of failure, which may be "timeout",
247  * "host failure" or "transfer failure"
248  */
249 static int l_task_send(lua_State* L)
250 {
251   m_task_t task = sglua_checktask(L, 1);
252   const char* mailbox = luaL_checkstring(L, 2);
253                                   /* task mailbox ... */
254   lua_settop(L, 1);
255                                   /* task */
256   task_register(L);
257                                   /* -- */
258   MSG_error_t res = MSG_task_send(task, mailbox);
259
260   if (res == MSG_OK) {
261     lua_pushboolean(L, 1);
262                                   /* true */
263     return 1;
264   }
265   else {
266     /* the communication has failed, I'm still the owner of the task */
267     task_unregister(L, task);
268                                   /* task */
269     lua_pushboolean(L, 0);
270                                   /* task false */
271     lua_pushstring(L, msg_errors[res]);
272                                   /* task false error */
273     return 2;
274   }
275 }
276
277 /**
278  * \brief Sends a task on a mailbox.
279  * \param L a Lua state
280  * \return number of values returned to Lua
281  *
282  * This is a non-blocking function: use simgrid.comm.wait() or
283  * simgrid.comm.test() to end the communication.
284  *
285  * - Argument 1 (task): the task to send
286  * - Argument 2 (string or compatible): mailbox name, as a real string or any
287  * type convertible to string (numbers always are)
288  * - Return value (comm): a communication object to be used later with wait or test
289  */
290 static int l_task_isend(lua_State* L)
291 {
292   m_task_t task = sglua_checktask(L, 1);
293   const char* mailbox = luaL_checkstring(L, 2);
294                                   /* task mailbox ... */
295   lua_settop(L, 1);
296                                   /* task */
297   task_register(L);
298                                   /* -- */
299   msg_comm_t comm = MSG_task_isend(task, mailbox);
300
301   msg_comm_t* userdata = (msg_comm_t*) lua_newuserdata(L, sizeof(msg_comm_t));
302                                   /* comm */
303   *userdata = comm;
304   luaL_getmetatable(L, COMM_MODULE_NAME);
305                                   /* comm mt */
306   lua_setmetatable(L, -2);
307                                   /* comm */
308   return 1;
309 }
310
311 /**
312  * \brief Sends a task on a mailbox on a best effort way (detached send).
313  * \param L a Lua state
314  * \return number of values returned to Lua
315  *
316  * Like simgrid.task.isend, this is a non-blocking function.
317  * You can use this function if you don't care about when the communication
318  * ends and whether it succeeds.
319  * FIXME: isn't this equivalent to calling simgrid.task.isend() and ignoring
320  * the result?
321  *
322  * - Argument 1 (task): the task to send
323  * - Argument 2 (string or compatible): mailbox name, as a real string or any
324  * type convertible to string (numbers always are)
325  */
326 static int l_task_dsend(lua_State* L)
327 {
328   m_task_t task = sglua_checktask(L, 1);
329   const char* mailbox = luaL_checkstring(L, 2);
330                                   /* task mailbox ... */
331   lua_settop(L, 1);
332                                   /* task */
333   task_register(L);
334                                   /* -- */
335   MSG_task_dsend(task, mailbox, NULL);
336   return 0;
337 }
338
339 /**
340  * \brief Receives a task.
341  * \param L a Lua state
342  * \return number of values returned to Lua
343  *
344  * - Argument 1 (string or compatible): mailbox name, as a real string or any
345  * type convertible to string (numbers always are)
346  * - Argument 2 (number, optional): timeout (default is no timeout)
347  * - Return values (task or nil + string): the task received, or nil plus an
348  * error message if the communication has failed
349  */
350 static int l_task_recv(lua_State* L)
351 {
352   m_task_t task = NULL;
353   const char* mailbox = luaL_checkstring(L, 1);
354   int timeout;
355   if (lua_gettop(L) >= 2) {
356                                   /* mailbox timeout ... */
357     timeout = luaL_checknumber(L, 2);
358   }
359   else {
360                                   /* mailbox */
361     timeout = -1;
362     /* no timeout by default */
363   }
364                                   /* mailbox ... */
365   MSG_error_t res = MSG_task_receive_with_timeout(&task, mailbox, timeout);
366
367   if (res == MSG_OK) {
368     task_copy(L, task);
369                                   /* mailbox ... task */
370     return 1;
371   }
372   else {
373     lua_pushnil(L);
374                                   /* mailbox ... nil */
375     lua_pushstring(L, msg_errors[res]);
376                                   /* mailbox ... nil error */
377     return 2;
378   }
379 }
380
381 /**
382  * \brief Asynchronously receives a task on a mailbox.
383  * \param L a Lua state
384  * \return number of values returned to Lua
385  *
386  * This is a non-blocking function: use simgrid.comm.wait() or
387  * simgrid.comm.test() to end the communication and get the task in case of
388  * success.
389  *
390  * - Argument 1 (string or compatible): mailbox name, as a real string or any
391  * type convertible to string (numbers always are)
392  * - Return value (comm): a communication object to be used later with wait or test
393  */
394
395 static int l_task_irecv(lua_State* L)
396 {
397   const char* mailbox = luaL_checkstring(L, 1);
398                                   /* mailbox ... */
399   m_task_t* task = xbt_new0(m_task_t, 1); // FIXME fix this leak
400   msg_comm_t comm = MSG_task_irecv(task, mailbox);
401
402   msg_comm_t* userdata = (msg_comm_t*) lua_newuserdata(L, sizeof(msg_comm_t));
403                                   /* mailbox ... comm */
404   *userdata = comm;
405   luaL_getmetatable(L, COMM_MODULE_NAME);
406                                   /* mailbox ... comm mt */
407   lua_setmetatable(L, -2);
408                                   /* mailbox ... comm */
409   return 1;
410 }
411
412 static const luaL_reg task_functions[] = {
413   {"new", l_task_new},
414   {"get_name", l_task_get_name},
415   {"get_computation_duration", l_task_get_computation_duration},
416   {"execute", l_task_execute},
417   {"send", l_task_send},
418   {"isend", l_task_isend},
419   {"dsend", l_task_dsend},
420   {"recv", l_task_recv},
421   {"irecv", l_task_irecv},
422   {NULL, NULL}
423 };
424
425 /**
426  * \brief Finalizes the userdata of a task.
427  * \param L a Lua state
428  * \return number of values returned to Lua
429  *
430  * - Argument 1 (userdata): a C task, possibly NULL if it was sent to another
431  * Lua state
432  */
433 static int l_task_gc(lua_State* L)
434 {
435                                   /* ctask */
436   m_task_t task = *((m_task_t*) luaL_checkudata(L, 1, TASK_MODULE_NAME));
437   /* the task is NULL if I sent it to someone else */
438   if (task != NULL) {
439     MSG_task_destroy(task);
440   }
441   return 0;
442 }
443
444 /**
445  * \brief Returns a string representation of a C task.
446  * \param L a Lua state
447  * \return number of values returned to Lua
448  *
449  * - Argument 1 (userdata): a task
450  * - Return value (string): a string describing this task
451  */
452 static int l_task_tostring(lua_State* L)
453 {
454   m_task_t task = *((m_task_t*) luaL_checkudata(L, 1, TASK_MODULE_NAME));
455   lua_pushfstring(L, "Task: %p", task);
456   return 1;
457 }
458
459 /**
460  * \brief Metamethods of both a task table and the userdata inside it.
461  */
462 static const luaL_reg task_meta[] = {
463   {"__gc", l_task_gc}, /* will be called only for userdata */
464   {"__tostring", l_task_tostring},
465   {NULL, NULL}
466 };
467
468 /* ********************************************************************************* */
469 /*                                simgrid.comm API                                   */
470 /* ********************************************************************************* */
471
472 /**
473  * \brief Ensures that a value in the stack is a comm and returns it.
474  * \param L a Lua state
475  * \param index an index in the Lua stack
476  * \return the C comm
477  */
478 static msg_comm_t sglua_checkcomm(lua_State* L, int index)
479 {
480   msg_comm_t comm = *((msg_comm_t*) luaL_checkudata(L, index, COMM_MODULE_NAME));
481   return comm;
482 }
483
484 /**
485  * \brief Blocks the current process until a communication is finished.
486  * \param L a Lua state
487  * \return number of values returned to Lua
488  *
489  * - Argument 1 (comm): a comm (previously created by isend or irecv)
490  * - Argument 2 (number, optional): timeout (default is no timeout)
491  * - Return values (task or nil + string): in case of success, returns the task
492  * received if you are the receiver and nil if you are the sender. In case of
493  * failure, returns nil plus an error string.
494  */
495 static int l_comm_wait(lua_State* L) {
496
497   msg_comm_t comm = sglua_checkcomm(L, 1);
498   double timeout = -1;
499   if (lua_gettop(L) >= 2) {
500     timeout = luaL_checknumber(L, 2);
501   }
502                                   /* comm ... */
503   MSG_error_t res = MSG_comm_wait(comm, timeout);
504
505   if (res == MSG_OK) {
506     m_task_t task = MSG_comm_get_task(comm);
507     if (MSG_task_get_sender(task) == MSG_process_self()) {
508       /* I'm the sender */
509       return 0;
510     }
511     else {
512       /* I'm the receiver: copy the Lua task from the sender */
513       task_copy(L, task);
514                                   /* comm ... task */
515       return 1;
516     }
517   }
518   else {
519     /* the communication has failed */
520     lua_pushnil(L);
521                                   /* comm ... nil */
522     lua_pushstring(L, msg_errors[res]);
523                                   /* comm ... nil error */
524     return 2;
525   }
526 }
527
528 /**
529  * @brief Returns whether a communication is finished.
530  *
531  * Unlike wait(), This function always returns immediately.
532  *
533  * - Argument 1 (comm): a comm (previously created by isend or irecv)
534  * - Return values (task/boolean or nil + string): if the communication is not
535  * finished, return false. If the communication is finished and was successful,
536  * returns the task received if you are the receiver or true if you are the
537  * sender. If the communication is finished and has failed, returns nil
538  * plus an error string.
539  */
540 static int l_comm_test(lua_State* L) {
541
542   msg_comm_t comm = sglua_checkcomm(L, 1);
543                                   /* comm ... */
544   if (!MSG_comm_test(comm)) {
545     /* not finished yet */
546     lua_pushboolean(L, 0);
547                                   /* comm ... false */
548     return 1;
549   }
550   else {
551     /* finished but may have failed */
552     MSG_error_t res = MSG_comm_get_status(comm);
553
554     if (res == MSG_OK) {
555       m_task_t task = MSG_comm_get_task(comm);
556       if (MSG_task_get_sender(task) == MSG_process_self()) {
557         /* I'm the sender */
558         lua_pushboolean(L, 1);
559                                   /* comm ... true */
560         return 1;
561       }
562       else {
563         /* I'm the receiver: copy the Lua task from the sender */
564         task_copy(L, task);
565                                   /* comm ... task */
566         return 1;
567       }
568     }
569     else {
570       /* the communication has failed */
571       lua_pushnil(L);
572                                   /* comm ... nil */
573       lua_pushstring(L, msg_errors[res]);
574                                   /* comm ... nil error */
575       return 2;
576     }
577   }
578 }
579
580 static const luaL_reg comm_functions[] = {
581   {"wait", l_comm_wait},
582   {"test", l_comm_test},
583   /* TODO waitany, testany */
584   {NULL, NULL}
585 };
586
587 /**
588  * \brief Finalizes a comm userdata.
589  * \param L a Lua state
590  * \return number of values returned to Lua
591  *
592  * - Argument 1 (userdata): a comm
593  */
594 static int l_comm_gc(lua_State* L)
595 {
596                                   /* ctask */
597   msg_comm_t comm = *((msg_comm_t*) luaL_checkudata(L, 1, COMM_MODULE_NAME));
598   MSG_comm_destroy(comm);
599   return 0;
600 }
601
602 /**
603  * \brief Metamethods of the comm userdata.
604  */
605 static const luaL_reg comm_meta[] = {
606   {"__gc", l_comm_gc},
607   {NULL, NULL}
608 };
609
610 /* ********************************************************************************* */
611 /*                                simgrid.host API                                   */
612 /* ********************************************************************************* */
613
614 /**
615  * \brief Ensures that a value in the stack is a host and returns it.
616  * \param L a Lua state
617  * \param index an index in the Lua stack
618  * \return the C host corresponding to this Lua host
619  */
620 static m_host_t sglua_checkhost(lua_State * L, int index)
621 {
622   m_host_t *pi, ht;
623   luaL_checktype(L, index, LUA_TTABLE);
624   lua_getfield(L, index, "__simgrid_host");
625   pi = (m_host_t *) luaL_checkudata(L, lua_gettop(L), HOST_MODULE_NAME);
626   if (pi == NULL)
627     luaL_typerror(L, index, HOST_MODULE_NAME);
628   ht = *pi;
629   if (!ht)
630     luaL_error(L, "null Host");
631   lua_pop(L, 1);
632   return ht;
633 }
634
635 /**
636  * \brief Returns a host given its name.
637  * \param L a Lua state
638  * \return number of values returned to Lua
639  *
640  * - Argument 1 (string): name of a host
641  * - Return value (host): the corresponding host
642  */
643 static int l_host_get_by_name(lua_State * L)
644 {
645   const char *name = luaL_checkstring(L, 1);
646   XBT_DEBUG("Getting Host from name...");
647   m_host_t msg_host = MSG_get_host_by_name(name);
648   if (!msg_host) {
649     luaL_error(L, "null Host : MSG_get_host_by_name failed");
650   }
651   lua_newtable(L);              /* create a table, put the userdata on top of it */
652   m_host_t *lua_host = (m_host_t *) lua_newuserdata(L, sizeof(m_host_t));
653   *lua_host = msg_host;
654   luaL_getmetatable(L, HOST_MODULE_NAME);
655   lua_setmetatable(L, -2);
656   lua_setfield(L, -2, "__simgrid_host");        /* put the userdata as field of the table */
657   /* remove the args from the stack */
658   lua_remove(L, 1);
659   return 1;
660 }
661
662 /**
663  * \brief Returns the name of a host.
664  * \param L a Lua state
665  * \return number of values returned to Lua
666  *
667  * - Argument 1 (host): a host
668  * - Return value (string): name of this host
669  */
670 static int l_host_get_name(lua_State * L)
671 {
672   m_host_t ht = sglua_checkhost(L, 1);
673   lua_pushstring(L, MSG_host_get_name(ht));
674   return 1;
675 }
676
677 /**
678  * \brief Returns the number of existing hosts.
679  * \param L a Lua state
680  * \return number of values returned to Lua
681  *
682  * - Return value (number): number of hosts
683  */
684 static int l_host_number(lua_State * L)
685 {
686   lua_pushnumber(L, MSG_get_host_number());
687   return 1;
688 }
689
690 /**
691  * \brief Returns the host given its index.
692  * \param L a Lua state
693  * \return number of values returned to Lua
694  *
695  * - Argument 1 (number): an index (1 is the first)
696  * - Return value (host): the host at this index
697  */
698 static int l_host_at(lua_State * L)
699 {
700   int index = luaL_checkinteger(L, 1);
701   m_host_t host = MSG_get_host_table()[index - 1];      // lua indexing start by 1 (lua[1] <=> C[0])
702   lua_newtable(L);              /* create a table, put the userdata on top of it */
703   m_host_t *lua_host = (m_host_t *) lua_newuserdata(L, sizeof(m_host_t));
704   *lua_host = host;
705   luaL_getmetatable(L, HOST_MODULE_NAME);
706   lua_setmetatable(L, -2);
707   lua_setfield(L, -2, "__simgrid_host");        /* put the userdata as field of the table */
708   return 1;
709 }
710
711 /**
712  * \brief Returns the host where the current process is located.
713  * \param L a Lua state
714  * \return number of values returned to Lua
715  *
716  * - Return value (host): the current host
717  */
718 static int l_host_self(lua_State * L)
719 {
720                                   /* -- */
721   m_host_t host = MSG_host_self();
722   lua_newtable(L);
723                                   /* table */
724   m_host_t* lua_host = (m_host_t*) lua_newuserdata(L, sizeof(m_host_t));
725                                   /* table ud */
726   *lua_host = host;
727   luaL_getmetatable(L, HOST_MODULE_NAME);
728                                   /* table ud mt */
729   lua_setmetatable(L, -2);
730                                   /* table ud */
731   lua_setfield(L, -2, "__simgrid_host");
732                                   /* table */
733   return 1;
734 }
735
736 /**
737  * \brief Returns the value of a host property.
738  * \param L a Lua state
739  * \return number of values returned to Lua
740  *
741  * - Argument 1 (host): a host
742  * - Argument 2 (string): name of the property to get
743  * - Return value (string): the value of this property
744  */
745 static int l_host_get_property_value(lua_State * L)
746 {
747   m_host_t ht = sglua_checkhost(L, 1);
748   const char *prop = luaL_checkstring(L, 2);
749   lua_pushstring(L,MSG_host_get_property_value(ht,prop));
750   return 1;
751 }
752
753 /**
754  * \brief Makes the current process sleep for a while.
755  * \param L a Lua state
756  * \return number of values returned to Lua
757  *
758  * - Argument 1 (number): duration of the sleep
759  */
760 static int l_host_sleep(lua_State *L)
761 {
762   int time = luaL_checknumber(L, 1);
763   MSG_process_sleep(time);
764   return 0;
765 }
766
767 /**
768  * \brief Destroys a host.
769  * \param L a Lua state
770  * \return number of values returned to Lua
771  *
772  * - Argument 1 (host): the host to destroy
773  */
774 static int l_host_destroy(lua_State *L)
775 {
776   m_host_t ht = sglua_checkhost(L, 1);
777   __MSG_host_destroy(ht);
778   return 0;
779 }
780
781 static const luaL_reg host_functions[] = {
782   {"get_by_name", l_host_get_by_name},
783   {"name", l_host_get_name},
784   {"number", l_host_number},
785   {"at", l_host_at},
786   {"self", l_host_self},
787   {"get_prop_value", l_host_get_property_value},
788   {"sleep", l_host_sleep},
789   {"destroy", l_host_destroy},
790   // Bypass XML Methods
791   {"set_function", console_set_function},
792   {"set_property", console_host_set_property},
793   {NULL, NULL}
794 };
795
796 /**
797  * \brief Returns a string representation of a host.
798  * \param L a Lua state
799  * \return number of values returned to Lua
800  *
801  * - Argument 1 (userdata): a host
802  * - Return value (string): a string describing this host
803  */
804 static int l_host_tostring(lua_State * L)
805 {
806   lua_pushfstring(L, "Host :%p", lua_touserdata(L, 1));
807   return 1;
808 }
809
810 static const luaL_reg host_meta[] = {
811   {"__tostring", l_host_tostring},
812   {0, 0}
813 };
814
815 /* ********************************************************************************* */
816 /*                              simgrid.process API                                  */
817 /* ********************************************************************************* */
818
819 /**
820  * \brief Makes the current process sleep for a while.
821  * \param L a Lua state
822  * \return number of values returned to Lua
823  *
824  * - Argument 1 (number): duration of the sleep
825  * - Return value (nil or string): nil in everything went ok, or a string error
826  * if case of failure ("host failure")
827  */
828 static int l_process_sleep(lua_State* L)
829 {
830   double duration = luaL_checknumber(L, 1);
831   MSG_error_t res = MSG_process_sleep(duration);
832
833   switch (res) {
834
835   case MSG_OK:
836     return 0;
837
838   case MSG_HOST_FAILURE:
839     lua_pushliteral(L, "host failure");
840     return 1;
841
842   default:
843     xbt_die("Unexpected result of MSG_process_sleep: %d, please report this bug", res);
844   }
845 }
846
847 static const luaL_reg process_functions[] = {
848     {"sleep", l_process_sleep},
849     /* TODO: self, create, kill, suspend, is_suspended, resume, get_name,
850      * get_pid, get_ppid, migrate
851      */
852     {NULL, NULL}
853 };
854
855 /* ********************************************************************************* */
856 /*                           lua_stub_generator functions                            */
857 /* ********************************************************************************* */
858
859 xbt_dict_t process_function_set;
860 xbt_dynar_t process_list;
861 xbt_dict_t machine_set;
862 static s_process_t process;
863
864 void s_process_free(void *process)
865 {
866   s_process_t *p = (s_process_t *) process;
867   int i;
868   for (i = 0; i < p->argc; i++)
869     free(p->argv[i]);
870   free(p->argv);
871   free(p->host);
872 }
873
874 static int gras_add_process_function(lua_State * L)
875 {
876   const char *arg;
877   const char *process_host = luaL_checkstring(L, 1);
878   const char *process_function = luaL_checkstring(L, 2);
879
880   if (xbt_dict_is_empty(machine_set)
881       || xbt_dict_is_empty(process_function_set)
882       || xbt_dynar_is_empty(process_list)) {
883     process_function_set = xbt_dict_new();
884     process_list = xbt_dynar_new(sizeof(s_process_t), s_process_free);
885     machine_set = xbt_dict_new();
886   }
887
888   xbt_dict_set(machine_set, process_host, NULL, NULL);
889   xbt_dict_set(process_function_set, process_function, NULL, NULL);
890
891   process.argc = 1;
892   process.argv = xbt_new(char *, 1);
893   process.argv[0] = xbt_strdup(process_function);
894   process.host = strdup(process_host);
895
896   lua_pushnil(L);
897   while (lua_next(L, 3) != 0) {
898     arg = lua_tostring(L, -1);
899     process.argc++;
900     process.argv =
901         xbt_realloc(process.argv, (process.argc) * sizeof(char *));
902     process.argv[(process.argc) - 1] = xbt_strdup(arg);
903
904     XBT_DEBUG("index = %f , arg = %s \n", lua_tonumber(L, -2),
905            lua_tostring(L, -1));
906     lua_pop(L, 1);
907   }
908   lua_pop(L, 1);
909   //add to the process list
910   xbt_dynar_push(process_list, &process);
911   return 0;
912 }
913
914 static int gras_generate(lua_State * L)
915 {
916   const char *project_name = luaL_checkstring(L, 1);
917   generate_sim(project_name);
918   generate_rl(project_name);
919   generate_makefile_local(project_name);
920   return 0;
921 }
922
923 /* ********************************************************************************* */
924 /*                               simgrid.platf API                                   */
925 /* ********************************************************************************* */
926
927 static const luaL_reg platf_functions[] = {
928     {"open", console_open},
929     {"close", console_close},
930     {"AS_open", console_AS_open},
931     {"AS_close", console_AS_close},
932     {"host_new", console_add_host},
933     {"link_new", console_add_link},
934     {"router_new", console_add_router},
935     {"route_new", console_add_route},
936     {NULL, NULL}
937 };
938
939 /* ********************************************************************************* */
940 /*                                  simgrid API                                      */
941 /* ********************************************************************************* */
942
943 /**
944  * \brief Deploys your application.
945  * \param L a Lua state
946  * \return number of values returned to Lua
947  *
948  * - Argument 1 (string): name of the deployment file to load
949  */
950 static int launch_application(lua_State* L) {
951
952   const char* file = luaL_checkstring(L, 1);
953   MSG_function_register_default(run_lua_code);
954   MSG_launch_application(file);
955   return 0;
956 }
957
958 /**
959  * \brief Creates the platform.
960  * \param L a Lua state
961  * \return number of values returned to Lua
962  *
963  * - Argument 1 (string): name of the platform file to load
964  */
965 static int create_environment(lua_State* L) {
966
967   const char* file = luaL_checkstring(L, 1);
968   XBT_DEBUG("Loading environment file %s", file);
969   MSG_create_environment(file);
970   return 0;
971 }
972
973 /**
974  * \brief Prints a log string with debug level.
975  * \param L a Lua state
976  * \return number of values returned to Lua
977  *
978  * - Argument 1 (string): the text to print
979  */
980 static int debug(lua_State* L) {
981
982   const char* str = luaL_checkstring(L, 1);
983   XBT_DEBUG("%s", str);
984   return 0;
985 }
986
987 /**
988  * \brief Prints a log string with info level.
989  * \param L a Lua state
990  * \return number of values returned to Lua
991  *
992  * - Argument 1 (string): the text to print
993  */
994 static int info(lua_State* L) {
995
996   const char* str = luaL_checkstring(L, 1);
997   XBT_INFO("%s", str);
998   return 0;
999 }
1000
1001 /**
1002  * \brief Runs your application.
1003  * \param L a Lua state
1004  * \return number of values returned to Lua
1005  */
1006 static int run(lua_State*  L) {
1007
1008   MSG_main();
1009   return 0;
1010 }
1011
1012 /**
1013  * \brief Returns the current simulated time.
1014  * \param L a Lua state
1015  * \return number of values returned to Lua
1016  *
1017  * - Return value (number): the simulated time
1018  */
1019 static int get_clock(lua_State* L) {
1020
1021   lua_pushnumber(L, MSG_get_clock());
1022   return 1;
1023 }
1024
1025 /**
1026  * \brief Cleans the simulation.
1027  * \param L a Lua state
1028  * \return number of values returned to Lua
1029  */
1030 static int simgrid_gc(lua_State * L)
1031 {
1032   MSG_clean();
1033   return 0;
1034 }
1035
1036 /*
1037  * Register platform for MSG
1038  */
1039 static int msg_register_platform(lua_State * L)
1040 {
1041   /* Tell Simgrid we dont wanna use its parser */
1042   //surf_parse = console_parse_platform;
1043   surf_parse_reset_callbacks();
1044   MSG_create_environment(NULL);
1045   return 0;
1046 }
1047
1048 /*
1049  * Register platform for Simdag
1050  */
1051
1052 static int sd_register_platform(lua_State * L)
1053 {
1054   //surf_parse = console_parse_platform_wsL07;
1055   surf_parse_reset_callbacks();
1056   SD_create_environment(NULL);
1057   return 0;
1058 }
1059
1060 /*
1061  * Register platform for gras
1062  */
1063 static int gras_register_platform(lua_State * L)
1064 {
1065   //surf_parse = console_parse_platform;
1066   surf_parse_reset_callbacks();
1067   gras_create_environment(NULL);
1068   return 0;
1069 }
1070
1071 /**
1072  * Register applicaiton for MSG
1073  */
1074 static int msg_register_application(lua_State * L)
1075 {
1076   MSG_function_register_default(run_lua_code);
1077   //surf_parse = console_parse_application;
1078   MSG_launch_application(NULL);
1079   return 0;
1080 }
1081
1082 /*
1083  * Register application for gras
1084  */
1085 static int gras_register_application(lua_State * L)
1086 {
1087   gras_function_register_default(run_lua_code);
1088   //surf_parse = console_parse_application;
1089   gras_launch_application(NULL);
1090   return 0;
1091 }
1092
1093 static const luaL_Reg simgrid_functions[] = {
1094   {"create_environment", create_environment},
1095   {"launch_application", launch_application},
1096   {"debug", debug},
1097   {"info", info},
1098   {"run", run},
1099   {"get_clock", get_clock},
1100   /* short names */
1101   {"platform", create_environment},
1102   {"application", launch_application},
1103   /* methods to bypass XML parser */
1104   {"msg_register_platform", msg_register_platform},
1105   {"sd_register_platform", sd_register_platform},
1106   {"msg_register_application", msg_register_application},
1107   {"gras_register_platform", gras_register_platform},
1108   {"gras_register_application", gras_register_application},
1109   /* gras sub generator method */
1110   {"gras_set_process_function", gras_add_process_function},
1111   {"gras_generate", gras_generate},
1112   {NULL, NULL}
1113 };
1114
1115 /* ********************************************************************************* */
1116 /*                           module management functions                             */
1117 /* ********************************************************************************* */
1118
1119 #define LUA_MAX_ARGS_COUNT 10   /* maximum amount of arguments we can get from lua on command line */
1120
1121 /**
1122  * \brief Opens the simgrid Lua module.
1123  *
1124  * This function is called automatically by the Lua interpreter when some
1125  * Lua code requires the "simgrid" module.
1126  *
1127  * \param L the Lua state
1128  */
1129 int luaopen_simgrid(lua_State *L)
1130 {
1131   XBT_DEBUG("luaopen_simgrid *****");
1132
1133   /* Get the command line arguments from the lua interpreter */
1134   char **argv = malloc(sizeof(char *) * LUA_MAX_ARGS_COUNT);
1135   int argc = 1;
1136   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? */
1137
1138   lua_getglobal(L, "arg");
1139   /* if arg is a null value, it means we use lua only as a script to init platform
1140    * else it should be a table and then take arg in consideration
1141    */
1142   if (lua_istable(L, -1)) {
1143     int done = 0;
1144     while (!done) {
1145       argc++;
1146       lua_pushinteger(L, argc - 2);
1147       lua_gettable(L, -2);
1148       if (lua_isnil(L, -1)) {
1149         done = 1;
1150       } else {
1151         xbt_assert(lua_isstring(L, -1),
1152                     "argv[%d] got from lua is no string", argc - 1);
1153         xbt_assert(argc < LUA_MAX_ARGS_COUNT,
1154                     "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",
1155                     __FILE__, LUA_MAX_ARGS_COUNT - 1);
1156         argv[argc - 1] = (char *) luaL_checkstring(L, -1);
1157         lua_pop(L, 1);
1158         XBT_DEBUG("Got command line argument %s from lua", argv[argc - 1]);
1159       }
1160     }
1161     argv[argc--] = NULL;
1162
1163     /* Initialize the MSG core */
1164     MSG_global_init(&argc, argv);
1165     XBT_DEBUG("Still %d arguments on command line", argc); // FIXME: update the lua's arg table to reflect the changes from SimGrid
1166   }
1167
1168   /* Keep the context mechanism informed of our lua world today */
1169   sglua_maestro_state = L;
1170
1171   /* initialize access to my tables by children Lua states */
1172   lua_newtable(L);
1173   lua_setfield(L, LUA_REGISTRYINDEX, "simgrid.maestro_tables");
1174
1175   register_c_functions(L);
1176
1177   return 1;
1178 }
1179
1180 /**
1181  * \brief Returns whether a Lua state is the maestro state.
1182  * \param L a Lua state
1183  * \return true if this is maestro
1184  */
1185 int sglua_is_maestro(lua_State* L) {
1186   return L == sglua_maestro_state;
1187 }
1188
1189 /**
1190  * \brief Returns the maestro state.
1191  * \return the maestro Lua state
1192  */
1193 lua_State* sglua_get_maestro(void) {
1194   return sglua_maestro_state;
1195 }
1196
1197 /**
1198  * \brief Registers the task functions into the table simgrid.task.
1199  *
1200  * Also initialize the metatable of the task userdata type.
1201  *
1202  * \param L a lua state
1203  */
1204 static void register_task_functions(lua_State* L)
1205 {
1206   /* create a table simgrid.task and fill it with task functions */
1207   luaL_openlib(L, TASK_MODULE_NAME, task_functions, 0);
1208                                   /* simgrid.task */
1209
1210   /* create the metatable for tasks, add it to the Lua registry */
1211   luaL_newmetatable(L, TASK_MODULE_NAME);
1212                                   /* simgrid.task mt */
1213   /* fill the metatable */
1214   luaL_openlib(L, NULL, task_meta, 0);
1215                                   /* simgrid.task mt */
1216   lua_pushvalue(L, -2);
1217                                   /* simgrid.task mt simgrid.task */
1218   /* metatable.__index = simgrid.task
1219    * we put the task functions inside the task itself:
1220    * this allows to write my_task:method(args) for
1221    * simgrid.task.method(my_task, args) */
1222   lua_setfield(L, -2, "__index");
1223                                   /* simgrid.task mt */
1224   lua_pop(L, 2);
1225                                   /* -- */
1226 }
1227
1228 /**
1229  * \brief Registers the comm functions into the table simgrid.comm.
1230  *
1231  * Also initialize the metatable of the comm userdata type.
1232  *
1233  * \param L a lua state
1234  */
1235 static void register_comm_functions(lua_State* L)
1236 {
1237   /* create a table simgrid.com and fill it with com functions */
1238   luaL_openlib(L, COMM_MODULE_NAME, comm_functions, 0);
1239                                   /* simgrid.comm */
1240
1241   /* create the metatable for comms, add it to the Lua registry */
1242   luaL_newmetatable(L, COMM_MODULE_NAME);
1243                                   /* simgrid.comm mt */
1244   /* fill the metatable */
1245   luaL_openlib(L, NULL, comm_meta, 0);
1246                                   /* simgrid.comm mt */
1247   lua_pushvalue(L, -2);
1248                                   /* simgrid.comm mt simgrid.comm */
1249   /* metatable.__index = simgrid.comm
1250    * we put the comm functions inside the comm itself:
1251    * this allows to write my_comm:method(args) for
1252    * simgrid.comm.method(my_comm, args) */
1253   lua_setfield(L, -2, "__index");
1254                                   /* simgrid.comm mt */
1255   lua_pop(L, 2);
1256                                   /* -- */
1257 }
1258
1259 /**
1260  * \brief Registers the host functions into the table simgrid.host.
1261  *
1262  * Also initialize the metatable of the host userdata type.
1263  *
1264  * \param L a lua state
1265  */
1266 static void register_host_functions(lua_State* L)
1267 {
1268   /* create a table simgrid.host and fill it with host functions */
1269   luaL_openlib(L, HOST_MODULE_NAME, host_functions, 0);
1270                                   /* simgrid.host */
1271
1272   /* create the metatable for host, add it to the Lua registry */
1273   luaL_newmetatable(L, HOST_MODULE_NAME);
1274                                   /* simgrid.host mt */
1275   /* fill the metatable */
1276   luaL_openlib(L, NULL, host_meta, 0);
1277                                   /* simgrid.host mt */
1278   lua_pushvalue(L, -2);
1279                                   /* simgrid.host mt simgrid.host */
1280   /* metatable.__index = simgrid.host
1281    * we put the host functions inside the host userdata itself:
1282    * this allows to write my_host:method(args) for
1283    * simgrid.host.method(my_host, args) */
1284   lua_setfield(L, -2, "__index");
1285                                   /* simgrid.host mt */
1286   lua_pop(L, 2);
1287                                   /* -- */
1288 }
1289
1290 /**
1291  * \brief Registers the process functions into the table simgrid.process.
1292  * \param L a lua state
1293  */
1294 static void register_process_functions(lua_State* L)
1295 {
1296   luaL_openlib(L, PROCESS_MODULE_NAME, process_functions, 0);
1297                                   /* simgrid.process */
1298   lua_pop(L, 1);
1299 }
1300
1301 /**
1302  * \brief Registers the platform functions into the table simgrid.platf.
1303  * \param L a lua state
1304  */
1305 static void register_platf_functions(lua_State* L)
1306 {
1307   luaL_openlib(L, PLATF_MODULE_NAME, platf_functions, 0);
1308                                   /* simgrid.platf */
1309   lua_pop(L, 1);
1310 }
1311
1312 /**
1313  * \brief Makes the core functions available to the Lua world.
1314  * \param L a Lua world
1315  */
1316 static void register_core_functions(lua_State *L)
1317 {
1318   /* register the core C functions to lua */
1319   luaL_register(L, "simgrid", simgrid_functions);
1320                                   /* simgrid */
1321
1322   /* set a finalizer that cleans simgrid, by adding to the simgrid module a
1323    * dummy userdata whose __gc metamethod calls MSG_clean() */
1324   lua_newuserdata(L, sizeof(void*));
1325                                   /* simgrid udata */
1326   lua_newtable(L);
1327                                   /* simgrid udata mt */
1328   lua_pushcfunction(L, simgrid_gc);
1329                                   /* simgrid udata mt simgrid_gc */
1330   lua_setfield(L, -2, "__gc");
1331                                   /* simgrid udata mt */
1332   lua_setmetatable(L, -2);
1333                                   /* simgrid udata */
1334   lua_setfield(L, -2, "__simgrid_loaded");
1335                                   /* simgrid */
1336   lua_pop(L, 1);
1337                                   /* -- */
1338 }
1339
1340 /**
1341  * \brief Creates the simgrid module and make it available to Lua.
1342  * \param L a Lua world
1343  */
1344 static void register_c_functions(lua_State *L)
1345 {
1346   register_core_functions(L);
1347   register_task_functions(L);
1348   register_comm_functions(L);
1349   register_host_functions(L);
1350   register_process_functions(L);
1351   register_platf_functions(L);
1352 }
1353
1354 /**
1355  * \brief Runs a Lua function as a new simulated process.
1356  * \param argc number of arguments of the function
1357  * \param argv name of the Lua function and array of its arguments
1358  * \return result of the function
1359  */
1360 static int run_lua_code(int argc, char **argv)
1361 {
1362   XBT_DEBUG("Run lua code %s", argv[0]);
1363
1364   /* create a new state, getting globals from maestro */
1365   lua_State *L = sglua_clone_maestro();
1366   MSG_process_set_data(MSG_process_self(), L);
1367
1368   /* start the function */
1369   lua_getglobal(L, argv[0]);
1370   xbt_assert(lua_isfunction(L, -1),
1371               "There is no Lua function with name `%s'", argv[0]);
1372
1373   /* push arguments onto the stack */
1374   int i;
1375   for (i = 1; i < argc; i++)
1376     lua_pushstring(L, argv[i]);
1377
1378   /* call the function */
1379   _XBT_GNUC_UNUSED int err;
1380   err = lua_pcall(L, argc - 1, 1, 0);
1381   xbt_assert(err == 0, "Error running function `%s': %s", argv[0],
1382               lua_tostring(L, -1));
1383
1384   /* retrieve result */
1385   int res = 1;
1386   if (lua_isnumber(L, -1)) {
1387     res = lua_tonumber(L, -1);
1388     lua_pop(L, 1);              /* pop returned value */
1389   }
1390
1391   XBT_DEBUG("Execution of Lua code %s is over", (argv ? argv[0] : "(null)"));
1392
1393   return res;
1394 }