Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Lua: copy the Lua task right after the C task using an MSG callback
[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 from the stack and registers it so that the
167  * process can retrieve it later knowing the C task.
168  * \param L a lua state
169  */
170 static void task_register(lua_State* L) {
171
172   m_task_t task = sglua_checktask(L, -1);
173                                   /* ... task */
174   /* put in the C task a ref to the lua task so that the receiver finds it */
175   unsigned long ref = luaL_ref(L, LUA_REGISTRYINDEX);
176                                   /* ... */
177   MSG_task_set_data(task, (void*) ref);
178 }
179
180 /**
181  * \brief Pushes onto the stack the Lua task corresponding to a C task.
182  *
183  * The Lua task must have been previously registered with task_register so
184  * that it can be retrieved knowing the C task.
185  *
186  * \param L a lua state
187  * \param task a C task
188  */
189 static void task_unregister(lua_State* L, m_task_t task) {
190
191                                   /* ... */
192   /* the task is in my registry, put it onto my stack */
193   unsigned long ref = (unsigned long) MSG_task_get_data(task);
194   lua_rawgeti(L, LUA_REGISTRYINDEX, ref);
195                                   /* ... task */
196   luaL_unref(L, LUA_REGISTRYINDEX, ref);
197   MSG_task_set_data(task, NULL);
198 }
199
200 /**
201  * \brief This function is called when a C task has just been copied.
202  *
203  * This callback is used to copy the corresponding Lua task.
204  *
205  * \param task the task copied
206  * \param src_process the sender
207  * \param dst_process the receiver
208  */
209 static void task_copy_callback(m_task_t task, m_process_t src_process,
210     m_process_t dst_process) {
211
212   lua_State* src = MSG_process_get_data(src_process);
213   lua_State* dst = MSG_process_get_data(dst_process);
214
215                                   /* src: ...
216                                      dst: ... */
217   task_unregister(src, task);
218                                   /* src: ... task */
219   sglua_copy_value(src, dst);
220                                   /* src: ... task
221                                      dst: ... task */
222   task_register(dst);             /* dst: ... */
223
224   /* the receiver is now the owner of the task and may destroy it:
225    * make the sender forget the C task so that it doesn't garbage */
226   lua_getfield(src, -1, "__simgrid_task");
227                                   /* src: ... task ctask */
228   m_task_t* udata = (m_task_t*) luaL_checkudata(src, -1, TASK_MODULE_NAME);
229   *udata = NULL;
230   lua_pop(src, 2);
231                                   /* src: ... */
232 }
233
234 /**
235  * \brief Sends a task to a mailbox and waits for its completion.
236  * \param L a Lua state
237  * \return number of values returned to Lua
238  *
239  * - Argument 1 (task): the task to send
240  * - Argument 2 (string or compatible): mailbox name, as a real string or any
241  * type convertible to string (numbers always are)
242  * - Return values (boolean + string): true if the communication was successful,
243  * or false plus an error string in case of failure, which may be "timeout",
244  * "host failure" or "transfer failure"
245  */
246 static int l_task_send(lua_State* L)
247 {
248   m_task_t task = sglua_checktask(L, 1);
249   const char* mailbox = luaL_checkstring(L, 2);
250                                   /* task mailbox ... */
251   lua_settop(L, 1);
252                                   /* task */
253   task_register(L);
254                                   /* -- */
255   MSG_error_t res = MSG_task_send(task, mailbox);
256
257   if (res == MSG_OK) {
258     lua_pushboolean(L, 1);
259                                   /* true */
260     return 1;
261   }
262   else {
263     /* the communication has failed, I'm still the owner of the task */
264     task_unregister(L, task);
265                                   /* task */
266     lua_pushboolean(L, 0);
267                                   /* task false */
268     lua_pushstring(L, msg_errors[res]);
269                                   /* task false error */
270     return 2;
271   }
272 }
273
274 /**
275  * \brief Sends a task on a mailbox.
276  * \param L a Lua state
277  * \return number of values returned to Lua
278  *
279  * This is a non-blocking function: use simgrid.comm.wait() or
280  * simgrid.comm.test() to end the communication.
281  *
282  * - Argument 1 (task): the task to send
283  * - Argument 2 (string or compatible): mailbox name, as a real string or any
284  * type convertible to string (numbers always are)
285  * - Return value (comm): a communication object to be used later with wait or test
286  */
287 static int l_task_isend(lua_State* L)
288 {
289   m_task_t task = sglua_checktask(L, 1);
290   const char* mailbox = luaL_checkstring(L, 2);
291                                   /* task mailbox ... */
292   lua_settop(L, 1);
293                                   /* task */
294   task_register(L);
295                                   /* -- */
296   msg_comm_t comm = MSG_task_isend(task, mailbox);
297
298   msg_comm_t* userdata = (msg_comm_t*) lua_newuserdata(L, sizeof(msg_comm_t));
299                                   /* comm */
300   *userdata = comm;
301   luaL_getmetatable(L, COMM_MODULE_NAME);
302                                   /* comm mt */
303   lua_setmetatable(L, -2);
304                                   /* comm */
305   return 1;
306 }
307
308 /**
309  * \brief Sends a task on a mailbox on a best effort way (detached send).
310  * \param L a Lua state
311  * \return number of values returned to Lua
312  *
313  * Like simgrid.task.isend, this is a non-blocking function.
314  * You can use this function if you don't care about when the communication
315  * ends and whether it succeeds.
316  * FIXME: isn't this equivalent to calling simgrid.task.isend() and ignoring
317  * the result?
318  *
319  * - Argument 1 (task): the task to send
320  * - Argument 2 (string or compatible): mailbox name, as a real string or any
321  * type convertible to string (numbers always are)
322  */
323 static int l_task_dsend(lua_State* L)
324 {
325   m_task_t task = sglua_checktask(L, 1);
326   const char* mailbox = luaL_checkstring(L, 2);
327                                   /* task mailbox ... */
328   lua_settop(L, 1);
329                                   /* task */
330   task_register(L);
331                                   /* -- */
332   MSG_task_dsend(task, mailbox, NULL);
333   return 0;
334 }
335
336 /**
337  * \brief Receives a task.
338  * \param L a Lua state
339  * \return number of values returned to Lua
340  *
341  * - Argument 1 (string or compatible): mailbox name, as a real string or any
342  * type convertible to string (numbers always are)
343  * - Argument 2 (number, optional): timeout (default is no timeout)
344  * - Return values (task or nil + string): the task received, or nil plus an
345  * error message if the communication has failed
346  */
347 static int l_task_recv(lua_State* L)
348 {
349   m_task_t task = NULL;
350   const char* mailbox = luaL_checkstring(L, 1);
351   int timeout;
352   if (lua_gettop(L) >= 2) {
353                                   /* mailbox timeout ... */
354     timeout = luaL_checknumber(L, 2);
355   }
356   else {
357                                   /* mailbox */
358     timeout = -1;
359     /* no timeout by default */
360   }
361                                   /* mailbox ... */
362   MSG_error_t res = MSG_task_receive_with_timeout(&task, mailbox, timeout);
363
364   if (res == MSG_OK) {
365     task_unregister(L, task);
366                                   /* mailbox ... task */
367     return 1;
368   }
369   else {
370     lua_pushnil(L);
371                                   /* mailbox ... nil */
372     lua_pushstring(L, msg_errors[res]);
373                                   /* mailbox ... nil error */
374     return 2;
375   }
376 }
377
378 /**
379  * \brief Asynchronously receives a task on a mailbox.
380  * \param L a Lua state
381  * \return number of values returned to Lua
382  *
383  * This is a non-blocking function: use simgrid.comm.wait() or
384  * simgrid.comm.test() to end the communication and get the task in case of
385  * success.
386  *
387  * - Argument 1 (string or compatible): mailbox name, as a real string or any
388  * type convertible to string (numbers always are)
389  * - Return value (comm): a communication object to be used later with wait or test
390  */
391
392 static int l_task_irecv(lua_State* L)
393 {
394   const char* mailbox = luaL_checkstring(L, 1);
395                                   /* mailbox ... */
396   m_task_t* task = xbt_new0(m_task_t, 1); // FIXME fix this leak
397   msg_comm_t comm = MSG_task_irecv(task, mailbox);
398
399   msg_comm_t* userdata = (msg_comm_t*) lua_newuserdata(L, sizeof(msg_comm_t));
400                                   /* mailbox ... comm */
401   *userdata = comm;
402   luaL_getmetatable(L, COMM_MODULE_NAME);
403                                   /* mailbox ... comm mt */
404   lua_setmetatable(L, -2);
405                                   /* mailbox ... comm */
406   return 1;
407 }
408
409 static const luaL_reg task_functions[] = {
410   {"new", l_task_new},
411   {"get_name", l_task_get_name},
412   {"get_computation_duration", l_task_get_computation_duration},
413   {"execute", l_task_execute},
414   {"send", l_task_send},
415   {"isend", l_task_isend},
416   {"dsend", l_task_dsend},
417   {"recv", l_task_recv},
418   {"irecv", l_task_irecv},
419   {NULL, NULL}
420 };
421
422 /**
423  * \brief Finalizes the userdata of a task.
424  * \param L a Lua state
425  * \return number of values returned to Lua
426  *
427  * - Argument 1 (userdata): a C task, possibly NULL if it was sent to another
428  * Lua state
429  */
430 static int l_task_gc(lua_State* L)
431 {
432                                   /* ctask */
433   m_task_t task = *((m_task_t*) luaL_checkudata(L, 1, TASK_MODULE_NAME));
434   /* the task is NULL if I sent it to someone else */
435   if (task != NULL) {
436     MSG_task_destroy(task);
437   }
438   return 0;
439 }
440
441 /**
442  * \brief Returns a string representation of a C task.
443  * \param L a Lua state
444  * \return number of values returned to Lua
445  *
446  * - Argument 1 (userdata): a task
447  * - Return value (string): a string describing this task
448  */
449 static int l_task_tostring(lua_State* L)
450 {
451   m_task_t task = *((m_task_t*) luaL_checkudata(L, 1, TASK_MODULE_NAME));
452   lua_pushfstring(L, "Task: %p", task);
453   return 1;
454 }
455
456 /**
457  * \brief Metamethods of both a task table and the userdata inside it.
458  */
459 static const luaL_reg task_meta[] = {
460   {"__gc", l_task_gc}, /* will be called only for userdata */
461   {"__tostring", l_task_tostring},
462   {NULL, NULL}
463 };
464
465 /* ********************************************************************************* */
466 /*                                simgrid.comm API                                   */
467 /* ********************************************************************************* */
468
469 /**
470  * \brief Ensures that a value in the stack is a comm and returns it.
471  * \param L a Lua state
472  * \param index an index in the Lua stack
473  * \return the C comm
474  */
475 static msg_comm_t sglua_checkcomm(lua_State* L, int index)
476 {
477   msg_comm_t comm = *((msg_comm_t*) luaL_checkudata(L, index, COMM_MODULE_NAME));
478   return comm;
479 }
480
481 /**
482  * \brief Blocks the current process until a communication is finished.
483  * \param L a Lua state
484  * \return number of values returned to Lua
485  *
486  * - Argument 1 (comm): a comm (previously created by isend or irecv)
487  * - Argument 2 (number, optional): timeout (default is no timeout)
488  * - Return values (task or nil + string): in case of success, returns the task
489  * received if you are the receiver and nil if you are the sender. In case of
490  * failure, returns nil plus an error string.
491  */
492 static int l_comm_wait(lua_State* L) {
493
494   msg_comm_t comm = sglua_checkcomm(L, 1);
495   double timeout = -1;
496   if (lua_gettop(L) >= 2) {
497     timeout = luaL_checknumber(L, 2);
498   }
499                                   /* comm ... */
500   MSG_error_t res = MSG_comm_wait(comm, timeout);
501
502   if (res == MSG_OK) {
503     m_task_t task = MSG_comm_get_task(comm);
504     if (MSG_task_get_sender(task) == MSG_process_self()) {
505       /* I'm the sender */
506       return 0;
507     }
508     else {
509       /* I'm the receiver: find the Lua task from the C task */
510       task_unregister(L, task);
511                                   /* comm ... task */
512       return 1;
513     }
514   }
515   else {
516     /* the communication has failed */
517     lua_pushnil(L);
518                                   /* comm ... nil */
519     lua_pushstring(L, msg_errors[res]);
520                                   /* comm ... nil error */
521     return 2;
522   }
523 }
524
525 /**
526  * @brief Returns whether a communication is finished.
527  *
528  * Unlike wait(), This function always returns immediately.
529  *
530  * - Argument 1 (comm): a comm (previously created by isend or irecv)
531  * - Return values (task/boolean or nil + string): if the communication is not
532  * finished, return false. If the communication is finished and was successful,
533  * returns the task received if you are the receiver or true if you are the
534  * sender. If the communication is finished and has failed, returns nil
535  * plus an error string.
536  */
537 static int l_comm_test(lua_State* L) {
538
539   msg_comm_t comm = sglua_checkcomm(L, 1);
540                                   /* comm ... */
541   if (!MSG_comm_test(comm)) {
542     /* not finished yet */
543     lua_pushboolean(L, 0);
544                                   /* comm ... false */
545     return 1;
546   }
547   else {
548     /* finished but may have failed */
549     MSG_error_t res = MSG_comm_get_status(comm);
550
551     if (res == MSG_OK) {
552       m_task_t task = MSG_comm_get_task(comm);
553       if (MSG_task_get_sender(task) == MSG_process_self()) {
554         /* I'm the sender */
555         lua_pushboolean(L, 1);
556                                   /* comm ... true */
557         return 1;
558       }
559       else {
560         /* I'm the receiver: find the Lua task from the C task*/
561         task_unregister(L, task);
562                                   /* comm ... task */
563         return 1;
564       }
565     }
566     else {
567       /* the communication has failed */
568       lua_pushnil(L);
569                                   /* comm ... nil */
570       lua_pushstring(L, msg_errors[res]);
571                                   /* comm ... nil error */
572       return 2;
573     }
574   }
575 }
576
577 static const luaL_reg comm_functions[] = {
578   {"wait", l_comm_wait},
579   {"test", l_comm_test},
580   /* TODO waitany, testany */
581   {NULL, NULL}
582 };
583
584 /**
585  * \brief Finalizes a comm userdata.
586  * \param L a Lua state
587  * \return number of values returned to Lua
588  *
589  * - Argument 1 (userdata): a comm
590  */
591 static int l_comm_gc(lua_State* L)
592 {
593                                   /* ctask */
594   msg_comm_t comm = *((msg_comm_t*) luaL_checkudata(L, 1, COMM_MODULE_NAME));
595   MSG_comm_destroy(comm);
596   return 0;
597 }
598
599 /**
600  * \brief Metamethods of the comm userdata.
601  */
602 static const luaL_reg comm_meta[] = {
603   {"__gc", l_comm_gc},
604   {NULL, NULL}
605 };
606
607 /* ********************************************************************************* */
608 /*                                simgrid.host API                                   */
609 /* ********************************************************************************* */
610
611 /**
612  * \brief Ensures that a value in the stack is a host and returns it.
613  * \param L a Lua state
614  * \param index an index in the Lua stack
615  * \return the C host corresponding to this Lua host
616  */
617 static m_host_t sglua_checkhost(lua_State * L, int index)
618 {
619   m_host_t *pi, ht;
620   luaL_checktype(L, index, LUA_TTABLE);
621   lua_getfield(L, index, "__simgrid_host");
622   pi = (m_host_t *) luaL_checkudata(L, lua_gettop(L), HOST_MODULE_NAME);
623   if (pi == NULL)
624     luaL_typerror(L, index, HOST_MODULE_NAME);
625   ht = *pi;
626   if (!ht)
627     luaL_error(L, "null Host");
628   lua_pop(L, 1);
629   return ht;
630 }
631
632 /**
633  * \brief Returns a host given its name.
634  * \param L a Lua state
635  * \return number of values returned to Lua
636  *
637  * - Argument 1 (string): name of a host
638  * - Return value (host): the corresponding host
639  */
640 static int l_host_get_by_name(lua_State * L)
641 {
642   const char *name = luaL_checkstring(L, 1);
643   XBT_DEBUG("Getting Host from name...");
644   m_host_t msg_host = MSG_get_host_by_name(name);
645   if (!msg_host) {
646     luaL_error(L, "null Host : MSG_get_host_by_name failed");
647   }
648   lua_newtable(L);              /* create a table, put the userdata on top of it */
649   m_host_t *lua_host = (m_host_t *) lua_newuserdata(L, sizeof(m_host_t));
650   *lua_host = msg_host;
651   luaL_getmetatable(L, HOST_MODULE_NAME);
652   lua_setmetatable(L, -2);
653   lua_setfield(L, -2, "__simgrid_host");        /* put the userdata as field of the table */
654   /* remove the args from the stack */
655   lua_remove(L, 1);
656   return 1;
657 }
658
659 /**
660  * \brief Returns the name of a host.
661  * \param L a Lua state
662  * \return number of values returned to Lua
663  *
664  * - Argument 1 (host): a host
665  * - Return value (string): name of this host
666  */
667 static int l_host_get_name(lua_State * L)
668 {
669   m_host_t ht = sglua_checkhost(L, 1);
670   lua_pushstring(L, MSG_host_get_name(ht));
671   return 1;
672 }
673
674 /**
675  * \brief Returns the number of existing hosts.
676  * \param L a Lua state
677  * \return number of values returned to Lua
678  *
679  * - Return value (number): number of hosts
680  */
681 static int l_host_number(lua_State * L)
682 {
683   lua_pushnumber(L, MSG_get_host_number());
684   return 1;
685 }
686
687 /**
688  * \brief Returns the host given its index.
689  * \param L a Lua state
690  * \return number of values returned to Lua
691  *
692  * - Argument 1 (number): an index (1 is the first)
693  * - Return value (host): the host at this index
694  */
695 static int l_host_at(lua_State * L)
696 {
697   int index = luaL_checkinteger(L, 1);
698   m_host_t host = MSG_get_host_table()[index - 1];      // lua indexing start by 1 (lua[1] <=> C[0])
699   lua_newtable(L);              /* create a table, put the userdata on top of it */
700   m_host_t *lua_host = (m_host_t *) lua_newuserdata(L, sizeof(m_host_t));
701   *lua_host = host;
702   luaL_getmetatable(L, HOST_MODULE_NAME);
703   lua_setmetatable(L, -2);
704   lua_setfield(L, -2, "__simgrid_host");        /* put the userdata as field of the table */
705   return 1;
706 }
707
708 /**
709  * \brief Returns the host where the current process is located.
710  * \param L a Lua state
711  * \return number of values returned to Lua
712  *
713  * - Return value (host): the current host
714  */
715 static int l_host_self(lua_State * L)
716 {
717                                   /* -- */
718   m_host_t host = MSG_host_self();
719   lua_newtable(L);
720                                   /* table */
721   m_host_t* lua_host = (m_host_t*) lua_newuserdata(L, sizeof(m_host_t));
722                                   /* table ud */
723   *lua_host = host;
724   luaL_getmetatable(L, HOST_MODULE_NAME);
725                                   /* table ud mt */
726   lua_setmetatable(L, -2);
727                                   /* table ud */
728   lua_setfield(L, -2, "__simgrid_host");
729                                   /* table */
730   return 1;
731 }
732
733 /**
734  * \brief Returns the value of a host property.
735  * \param L a Lua state
736  * \return number of values returned to Lua
737  *
738  * - Argument 1 (host): a host
739  * - Argument 2 (string): name of the property to get
740  * - Return value (string): the value of this property
741  */
742 static int l_host_get_property_value(lua_State * L)
743 {
744   m_host_t ht = sglua_checkhost(L, 1);
745   const char *prop = luaL_checkstring(L, 2);
746   lua_pushstring(L,MSG_host_get_property_value(ht,prop));
747   return 1;
748 }
749
750 /**
751  * \brief Makes the current process sleep for a while.
752  * \param L a Lua state
753  * \return number of values returned to Lua
754  *
755  * - Argument 1 (number): duration of the sleep
756  */
757 static int l_host_sleep(lua_State *L)
758 {
759   int time = luaL_checknumber(L, 1);
760   MSG_process_sleep(time);
761   return 0;
762 }
763
764 /**
765  * \brief Destroys a host.
766  * \param L a Lua state
767  * \return number of values returned to Lua
768  *
769  * - Argument 1 (host): the host to destroy
770  */
771 static int l_host_destroy(lua_State *L)
772 {
773   m_host_t ht = sglua_checkhost(L, 1);
774   __MSG_host_destroy(ht);
775   return 0;
776 }
777
778 static const luaL_reg host_functions[] = {
779   {"get_by_name", l_host_get_by_name},
780   {"name", l_host_get_name},
781   {"number", l_host_number},
782   {"at", l_host_at},
783   {"self", l_host_self},
784   {"get_prop_value", l_host_get_property_value},
785   {"sleep", l_host_sleep},
786   {"destroy", l_host_destroy},
787   // Bypass XML Methods
788   {"set_function", console_set_function},
789   {"set_property", console_host_set_property},
790   {NULL, NULL}
791 };
792
793 /**
794  * \brief Returns a string representation of a host.
795  * \param L a Lua state
796  * \return number of values returned to Lua
797  *
798  * - Argument 1 (userdata): a host
799  * - Return value (string): a string describing this host
800  */
801 static int l_host_tostring(lua_State * L)
802 {
803   lua_pushfstring(L, "Host :%p", lua_touserdata(L, 1));
804   return 1;
805 }
806
807 static const luaL_reg host_meta[] = {
808   {"__tostring", l_host_tostring},
809   {0, 0}
810 };
811
812 /* ********************************************************************************* */
813 /*                              simgrid.process API                                  */
814 /* ********************************************************************************* */
815
816 /**
817  * \brief Makes the current process sleep for a while.
818  * \param L a Lua state
819  * \return number of values returned to Lua
820  *
821  * - Argument 1 (number): duration of the sleep
822  * - Return value (nil or string): nil in everything went ok, or a string error
823  * if case of failure ("host failure")
824  */
825 static int l_process_sleep(lua_State* L)
826 {
827   double duration = luaL_checknumber(L, 1);
828   MSG_error_t res = MSG_process_sleep(duration);
829
830   switch (res) {
831
832   case MSG_OK:
833     return 0;
834
835   case MSG_HOST_FAILURE:
836     lua_pushliteral(L, "host failure");
837     return 1;
838
839   default:
840     xbt_die("Unexpected result of MSG_process_sleep: %d, please report this bug", res);
841   }
842 }
843
844 static const luaL_reg process_functions[] = {
845     {"sleep", l_process_sleep},
846     /* TODO: self, create, kill, suspend, is_suspended, resume, get_name,
847      * get_pid, get_ppid, migrate
848      */
849     {NULL, NULL}
850 };
851
852 /* ********************************************************************************* */
853 /*                           lua_stub_generator functions                            */
854 /* ********************************************************************************* */
855
856 xbt_dict_t process_function_set;
857 xbt_dynar_t process_list;
858 xbt_dict_t machine_set;
859 static s_process_t process;
860
861 void s_process_free(void *process)
862 {
863   s_process_t *p = (s_process_t *) process;
864   int i;
865   for (i = 0; i < p->argc; i++)
866     free(p->argv[i]);
867   free(p->argv);
868   free(p->host);
869 }
870
871 static int gras_add_process_function(lua_State * L)
872 {
873   const char *arg;
874   const char *process_host = luaL_checkstring(L, 1);
875   const char *process_function = luaL_checkstring(L, 2);
876
877   if (xbt_dict_is_empty(machine_set)
878       || xbt_dict_is_empty(process_function_set)
879       || xbt_dynar_is_empty(process_list)) {
880     process_function_set = xbt_dict_new_homogeneous(NULL);
881     process_list = xbt_dynar_new(sizeof(s_process_t), s_process_free);
882     machine_set = xbt_dict_new_homogeneous(NULL);
883   }
884
885   xbt_dict_set(machine_set, process_host, NULL, NULL);
886   xbt_dict_set(process_function_set, process_function, NULL, NULL);
887
888   process.argc = 1;
889   process.argv = xbt_new(char *, 1);
890   process.argv[0] = xbt_strdup(process_function);
891   process.host = strdup(process_host);
892
893   lua_pushnil(L);
894   while (lua_next(L, 3) != 0) {
895     arg = lua_tostring(L, -1);
896     process.argc++;
897     process.argv =
898         xbt_realloc(process.argv, (process.argc) * sizeof(char *));
899     process.argv[(process.argc) - 1] = xbt_strdup(arg);
900
901     XBT_DEBUG("index = %f , arg = %s \n", lua_tonumber(L, -2),
902            lua_tostring(L, -1));
903     lua_pop(L, 1);
904   }
905   lua_pop(L, 1);
906   //add to the process list
907   xbt_dynar_push(process_list, &process);
908   return 0;
909 }
910
911 static int gras_generate(lua_State * L)
912 {
913   const char *project_name = luaL_checkstring(L, 1);
914   generate_sim(project_name);
915   generate_rl(project_name);
916   generate_makefile_local(project_name);
917   return 0;
918 }
919
920 /* ********************************************************************************* */
921 /*                               simgrid.platf API                                   */
922 /* ********************************************************************************* */
923
924 static const luaL_reg platf_functions[] = {
925     {"open", console_open},
926     {"close", console_close},
927     {"AS_open", console_AS_open},
928     {"AS_close", console_AS_close},
929     {"host_new", console_add_host},
930     {"link_new", console_add_link},
931     {"router_new", console_add_router},
932     {"route_new", console_add_route},
933     {NULL, NULL}
934 };
935
936 /* ********************************************************************************* */
937 /*                                  simgrid API                                      */
938 /* ********************************************************************************* */
939
940 /**
941  * \brief Deploys your application.
942  * \param L a Lua state
943  * \return number of values returned to Lua
944  *
945  * - Argument 1 (string): name of the deployment file to load
946  */
947 static int launch_application(lua_State* L) {
948
949   const char* file = luaL_checkstring(L, 1);
950   MSG_function_register_default(run_lua_code);
951   MSG_launch_application(file);
952   return 0;
953 }
954
955 /**
956  * \brief Creates the platform.
957  * \param L a Lua state
958  * \return number of values returned to Lua
959  *
960  * - Argument 1 (string): name of the platform file to load
961  */
962 static int create_environment(lua_State* L) {
963
964   const char* file = luaL_checkstring(L, 1);
965   XBT_DEBUG("Loading environment file %s", file);
966   MSG_create_environment(file);
967   return 0;
968 }
969
970 /**
971  * \brief Prints a log string with debug level.
972  * \param L a Lua state
973  * \return number of values returned to Lua
974  *
975  * - Argument 1 (string): the text to print
976  */
977 static int debug(lua_State* L) {
978
979   const char* str = luaL_checkstring(L, 1);
980   XBT_DEBUG("%s", str);
981   return 0;
982 }
983
984 /**
985  * \brief Prints a log string with info level.
986  * \param L a Lua state
987  * \return number of values returned to Lua
988  *
989  * - Argument 1 (string): the text to print
990  */
991 static int info(lua_State* L) {
992
993   const char* str = luaL_checkstring(L, 1);
994   XBT_INFO("%s", str);
995   return 0;
996 }
997
998 /**
999  * \brief Runs your application.
1000  * \param L a Lua state
1001  * \return number of values returned to Lua
1002  */
1003 static int run(lua_State*  L) {
1004
1005   MSG_main();
1006   return 0;
1007 }
1008
1009 /**
1010  * \brief Returns the current simulated time.
1011  * \param L a Lua state
1012  * \return number of values returned to Lua
1013  *
1014  * - Return value (number): the simulated time
1015  */
1016 static int get_clock(lua_State* L) {
1017
1018   lua_pushnumber(L, MSG_get_clock());
1019   return 1;
1020 }
1021
1022 /**
1023  * \brief Cleans the simulation.
1024  * \param L a Lua state
1025  * \return number of values returned to Lua
1026  */
1027 static int simgrid_gc(lua_State * L)
1028 {
1029   MSG_clean();
1030   return 0;
1031 }
1032
1033 /*
1034  * Register platform for MSG
1035  */
1036 static int msg_register_platform(lua_State * L)
1037 {
1038   /* Tell Simgrid we dont wanna use its parser */
1039   //surf_parse = console_parse_platform;
1040   surf_parse_reset_callbacks();
1041   MSG_create_environment(NULL);
1042   return 0;
1043 }
1044
1045 /*
1046  * Register platform for Simdag
1047  */
1048
1049 static int sd_register_platform(lua_State * L)
1050 {
1051   //surf_parse = console_parse_platform_wsL07;
1052   surf_parse_reset_callbacks();
1053   SD_create_environment(NULL);
1054   return 0;
1055 }
1056
1057 /*
1058  * Register platform for gras
1059  */
1060 static int gras_register_platform(lua_State * L)
1061 {
1062   //surf_parse = console_parse_platform;
1063   surf_parse_reset_callbacks();
1064   gras_create_environment(NULL);
1065   return 0;
1066 }
1067
1068 /**
1069  * Register applicaiton for MSG
1070  */
1071 static int msg_register_application(lua_State * L)
1072 {
1073   MSG_function_register_default(run_lua_code);
1074   //surf_parse = console_parse_application;
1075   MSG_launch_application(NULL);
1076   return 0;
1077 }
1078
1079 /*
1080  * Register application for gras
1081  */
1082 static int gras_register_application(lua_State * L)
1083 {
1084   gras_function_register_default(run_lua_code);
1085   //surf_parse = console_parse_application;
1086   gras_launch_application(NULL);
1087   return 0;
1088 }
1089
1090 static const luaL_Reg simgrid_functions[] = {
1091   {"create_environment", create_environment},
1092   {"launch_application", launch_application},
1093   {"debug", debug},
1094   {"info", info},
1095   {"run", run},
1096   {"get_clock", get_clock},
1097   /* short names */
1098   {"platform", create_environment},
1099   {"application", launch_application},
1100   /* methods to bypass XML parser */
1101   {"msg_register_platform", msg_register_platform},
1102   {"sd_register_platform", sd_register_platform},
1103   {"msg_register_application", msg_register_application},
1104   {"gras_register_platform", gras_register_platform},
1105   {"gras_register_application", gras_register_application},
1106   /* gras sub generator method */
1107   {"gras_set_process_function", gras_add_process_function},
1108   {"gras_generate", gras_generate},
1109   {NULL, NULL}
1110 };
1111
1112 /* ********************************************************************************* */
1113 /*                           module management functions                             */
1114 /* ********************************************************************************* */
1115
1116 #define LUA_MAX_ARGS_COUNT 10   /* maximum amount of arguments we can get from lua on command line */
1117
1118 /**
1119  * \brief Opens the simgrid Lua module.
1120  *
1121  * This function is called automatically by the Lua interpreter when some
1122  * Lua code requires the "simgrid" module.
1123  *
1124  * \param L the Lua state
1125  */
1126 int luaopen_simgrid(lua_State *L)
1127 {
1128   XBT_DEBUG("luaopen_simgrid *****");
1129
1130   /* Get the command line arguments from the lua interpreter */
1131   char **argv = malloc(sizeof(char *) * LUA_MAX_ARGS_COUNT);
1132   int argc = 1;
1133   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? */
1134
1135   lua_getglobal(L, "arg");
1136   /* if arg is a null value, it means we use lua only as a script to init platform
1137    * else it should be a table and then take arg in consideration
1138    */
1139   if (lua_istable(L, -1)) {
1140     int done = 0;
1141     while (!done) {
1142       argc++;
1143       lua_pushinteger(L, argc - 2);
1144       lua_gettable(L, -2);
1145       if (lua_isnil(L, -1)) {
1146         done = 1;
1147       } else {
1148         xbt_assert(lua_isstring(L, -1),
1149                     "argv[%d] got from lua is no string", argc - 1);
1150         xbt_assert(argc < LUA_MAX_ARGS_COUNT,
1151                     "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",
1152                     __FILE__, LUA_MAX_ARGS_COUNT - 1);
1153         argv[argc - 1] = (char *) luaL_checkstring(L, -1);
1154         lua_pop(L, 1);
1155         XBT_DEBUG("Got command line argument %s from lua", argv[argc - 1]);
1156       }
1157     }
1158     argv[argc--] = NULL;
1159
1160     /* Initialize the MSG core */
1161     MSG_global_init(&argc, argv);
1162     XBT_DEBUG("Still %d arguments on command line", argc); // FIXME: update the lua's arg table to reflect the changes from SimGrid
1163   }
1164
1165   /* Keep the context mechanism informed of our lua world today */
1166   sglua_maestro_state = L;
1167
1168   /* initialize access to my tables by children Lua states */
1169   lua_newtable(L);
1170   lua_setfield(L, LUA_REGISTRYINDEX, "simgrid.maestro_tables");
1171
1172   register_c_functions(L);
1173
1174   return 1;
1175 }
1176
1177 /**
1178  * \brief Returns whether a Lua state is the maestro state.
1179  * \param L a Lua state
1180  * \return true if this is maestro
1181  */
1182 int sglua_is_maestro(lua_State* L) {
1183   return L == sglua_maestro_state;
1184 }
1185
1186 /**
1187  * \brief Returns the maestro state.
1188  * \return the maestro Lua state
1189  */
1190 lua_State* sglua_get_maestro(void) {
1191   return sglua_maestro_state;
1192 }
1193
1194 /**
1195  * \brief Registers the task functions into the table simgrid.task.
1196  *
1197  * Also initialize the metatable of the task userdata type.
1198  *
1199  * \param L a lua state
1200  */
1201 static void register_task_functions(lua_State* L)
1202 {
1203   /* create a table simgrid.task and fill it with task functions */
1204   luaL_openlib(L, TASK_MODULE_NAME, task_functions, 0);
1205                                   /* simgrid.task */
1206
1207   /* create the metatable for tasks, add it to the Lua registry */
1208   luaL_newmetatable(L, TASK_MODULE_NAME);
1209                                   /* simgrid.task mt */
1210   /* fill the metatable */
1211   luaL_openlib(L, NULL, task_meta, 0);
1212                                   /* simgrid.task mt */
1213   lua_pushvalue(L, -2);
1214                                   /* simgrid.task mt simgrid.task */
1215   /* metatable.__index = simgrid.task
1216    * we put the task functions inside the task itself:
1217    * this allows to write my_task:method(args) for
1218    * simgrid.task.method(my_task, args) */
1219   lua_setfield(L, -2, "__index");
1220                                   /* simgrid.task mt */
1221   lua_pop(L, 2);
1222                                   /* -- */
1223
1224   /* set up MSG to copy Lua tasks between states */
1225   MSG_task_set_copy_callback(task_copy_callback);
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 }