Logo AND Algorithmique Numérique Distribuée

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