Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Use msg_error_t instead of MSG_error_t
[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 "lua_private.h"
10 #include "lua_state_cloner.h"
11 #include "lua_utils.h"
12 #include "xbt.h"
13 #include "msg/msg.h"
14 #include "simdag/simdag.h"
15 #include "surf/surfxml_parse.h"
16 #include "gras.h"
17 #include <lauxlib.h>
18
19 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(lua, bindings, "Lua Bindings");
20
21 static lua_State* sglua_maestro_state;
22
23 int luaopen_simgrid(lua_State *L);
24 static void sglua_register_c_functions(lua_State *L);
25 static int run_lua_code(int argc, char **argv);
26
27 /* ********************************************************************************* */
28 /*                           lua_stub_generator functions                            */
29 /* ********************************************************************************* */
30
31 xbt_dict_t process_function_set;
32 xbt_dynar_t process_list;
33 xbt_dict_t machine_set;
34 static s_process_t process;
35
36 void s_process_free(void *process)
37 {
38   s_process_t *p = (s_process_t *) process;
39   int i;
40   for (i = 0; i < p->argc; i++)
41     free(p->argv[i]);
42   free(p->argv);
43   free(p->host);
44 }
45
46 static int gras_add_process_function(lua_State * L)
47 {
48   const char *arg;
49   const char *process_host = luaL_checkstring(L, 1);
50   const char *process_function = luaL_checkstring(L, 2);
51
52   if (xbt_dict_is_empty(machine_set)
53       || xbt_dict_is_empty(process_function_set)
54       || xbt_dynar_is_empty(process_list)) {
55     process_function_set = xbt_dict_new_homogeneous(NULL);
56     process_list = xbt_dynar_new(sizeof(s_process_t), s_process_free);
57     machine_set = xbt_dict_new_homogeneous(NULL);
58   }
59
60   xbt_dict_set(machine_set, process_host, NULL, NULL);
61   xbt_dict_set(process_function_set, process_function, NULL, NULL);
62
63   process.argc = 1;
64   process.argv = xbt_new(char *, 1);
65   process.argv[0] = xbt_strdup(process_function);
66   process.host = strdup(process_host);
67
68   lua_pushnil(L);
69   while (lua_next(L, 3) != 0) {
70     arg = lua_tostring(L, -1);
71     process.argc++;
72     process.argv =
73         xbt_realloc(process.argv, (process.argc) * sizeof(char *));
74     process.argv[(process.argc) - 1] = xbt_strdup(arg);
75
76     XBT_DEBUG("index = %f , arg = %s \n", lua_tonumber(L, -2),
77            lua_tostring(L, -1));
78     lua_pop(L, 1);
79   }
80   lua_pop(L, 1);
81   //add to the process list
82   xbt_dynar_push(process_list, &process);
83   return 0;
84 }
85
86 static int gras_generate(lua_State * L)
87 {
88   const char *project_name = luaL_checkstring(L, 1);
89   generate_sim(project_name);
90   generate_rl(project_name);
91   generate_makefile_local(project_name);
92   return 0;
93 }
94
95 /* ********************************************************************************* */
96 /*                                  simgrid API                                      */
97 /* ********************************************************************************* */
98
99 /**
100  * \brief Deploys your application.
101  * \param L a Lua state
102  * \return number of values returned to Lua
103  *
104  * - Argument 1 (string): name of the deployment file to load
105  */
106 static int launch_application(lua_State* L) {
107
108   const char* file = luaL_checkstring(L, 1);
109   MSG_function_register_default(run_lua_code);
110   MSG_launch_application(file);
111   return 0;
112 }
113
114 /**
115  * \brief Creates the platform.
116  * \param L a Lua state
117  * \return number of values returned to Lua
118  *
119  * - Argument 1 (string): name of the platform file to load
120  */
121 static int create_environment(lua_State* L) {
122
123   const char* file = luaL_checkstring(L, 1);
124   XBT_DEBUG("Loading environment file %s", file);
125   MSG_create_environment(file);
126   return 0;
127 }
128
129 /**
130  * \brief Prints a log string with debug level.
131  * \param L a Lua state
132  * \return number of values returned to Lua
133  *
134  * - Argument 1 (string): the text to print
135  */
136 static int debug(lua_State* L) {
137
138   const char* str = luaL_checkstring(L, 1);
139   XBT_DEBUG("%s", str);
140   return 0;
141 }
142
143 /**
144  * \brief Prints a log string with info level.
145  * \param L a Lua state
146  * \return number of values returned to Lua
147  *
148  * - Argument 1 (string): the text to print
149  */
150 static int info(lua_State* L) {
151
152   const char* str = luaL_checkstring(L, 1);
153   XBT_INFO("%s", str);
154   return 0;
155 }
156
157 /**
158  * \brief Runs your application.
159  * \param L a Lua state
160  * \return number of values returned to Lua
161  */
162 static int run(lua_State*  L) {
163
164   MSG_main();
165   return 0;
166 }
167
168 /**
169  * \brief Returns the current simulated time.
170  * \param L a Lua state
171  * \return number of values returned to Lua
172  *
173  * - Return value (number): the simulated time
174  */
175 static int get_clock(lua_State* L) {
176
177   lua_pushnumber(L, MSG_get_clock());
178   return 1;
179 }
180
181 /**
182  * \brief Cleans the simulation.
183  * \param L a Lua state
184  * \return number of values returned to Lua
185  */
186 static int simgrid_gc(lua_State * L)
187 {
188   if (sglua_is_maestro(L)) {
189     MSG_clean();
190   }
191   return 0;
192 }
193
194 /*
195  * Register platform for MSG
196  */
197 static int msg_register_platform(lua_State * L)
198 {
199   /* Tell Simgrid we don't wanna use its parser */
200   //surf_parse = console_parse_platform;
201   surf_parse_reset_callbacks();
202   MSG_create_environment(NULL);
203   return 0;
204 }
205
206 /*
207  * Register platform for Simdag
208  */
209 static int sd_register_platform(lua_State * L)
210 {
211   //surf_parse = console_parse_platform_wsL07;
212   surf_parse_reset_callbacks();
213   SD_create_environment(NULL);
214   return 0;
215 }
216
217 /*
218  * Register platform for gras
219  */
220 static int gras_register_platform(lua_State * L)
221 {
222   //surf_parse = console_parse_platform;
223   surf_parse_reset_callbacks();
224   gras_create_environment(NULL);
225   return 0;
226 }
227
228 /**
229  * Register applicaiton for MSG
230  */
231 static int msg_register_application(lua_State * L)
232 {
233   MSG_function_register_default(run_lua_code);
234   //surf_parse = console_parse_application;
235   MSG_launch_application(NULL);
236   return 0;
237 }
238
239 /*
240  * Register application for gras
241  */
242 static int gras_register_application(lua_State * L)
243 {
244   gras_function_register_default(run_lua_code);
245   //surf_parse = console_parse_application;
246   gras_launch_application(NULL);
247   return 0;
248 }
249
250 static const luaL_Reg simgrid_functions[] = {
251   {"create_environment", create_environment},
252   {"launch_application", launch_application},
253   {"debug", debug},
254   {"info", info},
255   {"run", run},
256   {"get_clock", get_clock},
257   /* short names */
258   {"platform", create_environment},
259   {"application", launch_application},
260   /* methods to bypass XML parser */
261   {"msg_register_platform", msg_register_platform},
262   {"sd_register_platform", sd_register_platform},
263   {"msg_register_application", msg_register_application},
264   {"gras_register_platform", gras_register_platform},
265   {"gras_register_application", gras_register_application},
266   /* gras sub generator method */
267   {"gras_set_process_function", gras_add_process_function},
268   {"gras_generate", gras_generate},
269   {NULL, NULL}
270 };
271
272 /* ********************************************************************************* */
273 /*                           module management functions                             */
274 /* ********************************************************************************* */
275
276 #define LUA_MAX_ARGS_COUNT 10   /* maximum amount of arguments we can get from lua on command line */
277
278 /**
279  * \brief Opens the simgrid Lua module.
280  *
281  * This function is called automatically by the Lua interpreter when some
282  * Lua code requires the "simgrid" module.
283  *
284  * \param L the Lua state
285  */
286 int luaopen_simgrid(lua_State *L)
287 {
288   XBT_DEBUG("luaopen_simgrid *****");
289
290   /* Get the command line arguments from the lua interpreter */
291   char **argv = malloc(sizeof(char *) * LUA_MAX_ARGS_COUNT);
292   int argc = 1;
293   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? */
294
295   lua_getglobal(L, "arg");
296   /* if arg is a null value, it means we use lua only as a script to init platform
297    * else it should be a table and then take arg in consideration
298    */
299   if (lua_istable(L, -1)) {
300     int done = 0;
301     while (!done) {
302       argc++;
303       lua_pushinteger(L, argc - 2);
304       lua_gettable(L, -2);
305       if (lua_isnil(L, -1)) {
306         done = 1;
307       } else {
308         xbt_assert(lua_isstring(L, -1),
309                     "argv[%d] got from lua is no string", argc - 1);
310         xbt_assert(argc < LUA_MAX_ARGS_COUNT,
311                     "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",
312                     __FILE__, LUA_MAX_ARGS_COUNT - 1);
313         argv[argc - 1] = (char *) luaL_checkstring(L, -1);
314         lua_pop(L, 1);
315         XBT_DEBUG("Got command line argument %s from lua", argv[argc - 1]);
316       }
317     }
318     argv[argc--] = NULL;
319
320     /* Initialize the MSG core */
321     MSG_init(&argc, argv);
322     MSG_process_set_data_cleanup((void_f_pvoid_t) lua_close);
323     XBT_DEBUG("Still %d arguments on command line", argc); // FIXME: update the lua's arg table to reflect the changes from SimGrid
324   }
325
326   /* Keep the context mechanism informed of our lua world today */
327   sglua_maestro_state = L;
328
329   /* initialize access to my tables by children Lua states */
330   lua_newtable(L);
331   lua_setfield(L, LUA_REGISTRYINDEX, "simgrid.maestro_tables");
332
333   sglua_register_c_functions(L);
334
335   return 1;
336 }
337
338 /**
339  * \brief Returns whether a Lua state is the maestro state.
340  * \param L a Lua state
341  * \return true if this is maestro
342  */
343 int sglua_is_maestro(lua_State* L) {
344   return L == sglua_maestro_state;
345 }
346
347 /**
348  * \brief Returns the maestro state.
349  * \return the maestro Lua state
350  */
351 lua_State* sglua_get_maestro(void) {
352   return sglua_maestro_state;
353 }
354
355 /**
356  * \brief Makes the core functions available to the Lua world.
357  * \param L a Lua world
358  */
359 static void sglua_register_core_functions(lua_State *L)
360 {
361   /* register the core C functions to lua */
362   luaL_register(L, "simgrid", simgrid_functions);
363                                   /* simgrid */
364
365   /* set a finalizer that cleans simgrid, by adding to the simgrid module a
366    * dummy userdata whose __gc metamethod calls MSG_clean() */
367   lua_newuserdata(L, sizeof(void*));
368                                   /* simgrid udata */
369   lua_newtable(L);
370                                   /* simgrid udata mt */
371   lua_pushcfunction(L, simgrid_gc);
372                                   /* simgrid udata mt simgrid_gc */
373   lua_setfield(L, -2, "__gc");
374                                   /* simgrid udata mt */
375   lua_setmetatable(L, -2);
376                                   /* simgrid udata */
377   lua_setfield(L, -2, "__simgrid_loaded");
378                                   /* simgrid */
379   lua_pop(L, 1);
380                                   /* -- */
381 }
382
383 /**
384  * \brief Creates the simgrid module and make it available to Lua.
385  * \param L a Lua world
386  */
387 static void sglua_register_c_functions(lua_State *L)
388 {
389   sglua_register_core_functions(L);
390   sglua_register_task_functions(L);
391   sglua_register_comm_functions(L);
392   sglua_register_host_functions(L);
393   sglua_register_process_functions(L);
394   sglua_register_platf_functions(L);
395 }
396
397 /**
398  * \brief Runs a Lua function as a new simulated process.
399  * \param argc number of arguments of the function
400  * \param argv name of the Lua function and array of its arguments
401  * \return result of the function
402  */
403 static int run_lua_code(int argc, char **argv)
404 {
405   XBT_DEBUG("Run lua code %s", argv[0]);
406
407   /* create a new state, getting globals from maestro */
408   lua_State *L = sglua_clone_maestro();
409   MSG_process_set_data(MSG_process_self(), L);
410
411   /* start the function */
412   lua_getglobal(L, argv[0]);
413   xbt_assert(lua_isfunction(L, -1),
414               "There is no Lua function with name `%s'", argv[0]);
415
416   /* push arguments onto the stack */
417   int i;
418   for (i = 1; i < argc; i++)
419     lua_pushstring(L, argv[i]);
420
421   /* call the function */
422   _XBT_GNUC_UNUSED int err;
423   err = lua_pcall(L, argc - 1, 1, 0);
424   xbt_assert(err == 0, "Error running function `%s': %s", argv[0],
425               lua_tostring(L, -1));
426
427   /* retrieve result */
428   int res = 1;
429   if (lua_isnumber(L, -1)) {
430     res = lua_tonumber(L, -1);
431     lua_pop(L, 1);              /* pop returned value */
432   }
433
434   XBT_DEBUG("Execution of Lua code %s is over", (argv ? argv[0] : "(null)"));
435
436   return res;
437 }
438
439 /**
440  * \brief Returns a string corresponding to an MSG error code.
441  * \param err an MSG error code
442  * \return a string describing this error
443  */
444 const char* sglua_get_msg_error(msg_error_t err) {
445
446   static const char* msg_errors[] = {
447       NULL,
448       "timeout",
449       "transfer failure",
450       "host failure",
451       "task canceled"
452   };
453
454   return msg_errors[err];
455 }