Logo AND Algorithmique Numérique Distribuée

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