Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Split simgrid_lua.c in one source file per module
[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   MSG_clean();
189   return 0;
190 }
191
192 /*
193  * Register platform for MSG
194  */
195 static int msg_register_platform(lua_State * L)
196 {
197   /* Tell Simgrid we dont wanna use its parser */
198   //surf_parse = console_parse_platform;
199   surf_parse_reset_callbacks();
200   MSG_create_environment(NULL);
201   return 0;
202 }
203
204 /*
205  * Register platform for Simdag
206  */
207
208 static int sd_register_platform(lua_State * L)
209 {
210   //surf_parse = console_parse_platform_wsL07;
211   surf_parse_reset_callbacks();
212   SD_create_environment(NULL);
213   return 0;
214 }
215
216 /*
217  * Register platform for gras
218  */
219 static int gras_register_platform(lua_State * L)
220 {
221   //surf_parse = console_parse_platform;
222   surf_parse_reset_callbacks();
223   gras_create_environment(NULL);
224   return 0;
225 }
226
227 /**
228  * Register applicaiton for MSG
229  */
230 static int msg_register_application(lua_State * L)
231 {
232   MSG_function_register_default(run_lua_code);
233   //surf_parse = console_parse_application;
234   MSG_launch_application(NULL);
235   return 0;
236 }
237
238 /*
239  * Register application for gras
240  */
241 static int gras_register_application(lua_State * L)
242 {
243   gras_function_register_default(run_lua_code);
244   //surf_parse = console_parse_application;
245   gras_launch_application(NULL);
246   return 0;
247 }
248
249 static const luaL_Reg simgrid_functions[] = {
250   {"create_environment", create_environment},
251   {"launch_application", launch_application},
252   {"debug", debug},
253   {"info", info},
254   {"run", run},
255   {"get_clock", get_clock},
256   /* short names */
257   {"platform", create_environment},
258   {"application", launch_application},
259   /* methods to bypass XML parser */
260   {"msg_register_platform", msg_register_platform},
261   {"sd_register_platform", sd_register_platform},
262   {"msg_register_application", msg_register_application},
263   {"gras_register_platform", gras_register_platform},
264   {"gras_register_application", gras_register_application},
265   /* gras sub generator method */
266   {"gras_set_process_function", gras_add_process_function},
267   {"gras_generate", gras_generate},
268   {NULL, NULL}
269 };
270
271 /* ********************************************************************************* */
272 /*                           module management functions                             */
273 /* ********************************************************************************* */
274
275 #define LUA_MAX_ARGS_COUNT 10   /* maximum amount of arguments we can get from lua on command line */
276
277 /**
278  * \brief Opens the simgrid Lua module.
279  *
280  * This function is called automatically by the Lua interpreter when some
281  * Lua code requires the "simgrid" module.
282  *
283  * \param L the Lua state
284  */
285 int luaopen_simgrid(lua_State *L)
286 {
287   XBT_DEBUG("luaopen_simgrid *****");
288
289   /* Get the command line arguments from the lua interpreter */
290   char **argv = malloc(sizeof(char *) * LUA_MAX_ARGS_COUNT);
291   int argc = 1;
292   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? */
293
294   lua_getglobal(L, "arg");
295   /* if arg is a null value, it means we use lua only as a script to init platform
296    * else it should be a table and then take arg in consideration
297    */
298   if (lua_istable(L, -1)) {
299     int done = 0;
300     while (!done) {
301       argc++;
302       lua_pushinteger(L, argc - 2);
303       lua_gettable(L, -2);
304       if (lua_isnil(L, -1)) {
305         done = 1;
306       } else {
307         xbt_assert(lua_isstring(L, -1),
308                     "argv[%d] got from lua is no string", argc - 1);
309         xbt_assert(argc < LUA_MAX_ARGS_COUNT,
310                     "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",
311                     __FILE__, LUA_MAX_ARGS_COUNT - 1);
312         argv[argc - 1] = (char *) luaL_checkstring(L, -1);
313         lua_pop(L, 1);
314         XBT_DEBUG("Got command line argument %s from lua", argv[argc - 1]);
315       }
316     }
317     argv[argc--] = NULL;
318
319     /* Initialize the MSG core */
320     MSG_global_init(&argc, argv);
321     XBT_DEBUG("Still %d arguments on command line", argc); // FIXME: update the lua's arg table to reflect the changes from SimGrid
322   }
323
324   /* Keep the context mechanism informed of our lua world today */
325   sglua_maestro_state = L;
326
327   /* initialize access to my tables by children Lua states */
328   lua_newtable(L);
329   lua_setfield(L, LUA_REGISTRYINDEX, "simgrid.maestro_tables");
330
331   sglua_register_c_functions(L);
332
333   return 1;
334 }
335
336 /**
337  * \brief Returns whether a Lua state is the maestro state.
338  * \param L a Lua state
339  * \return true if this is maestro
340  */
341 int sglua_is_maestro(lua_State* L) {
342   return L == sglua_maestro_state;
343 }
344
345 /**
346  * \brief Returns the maestro state.
347  * \return the maestro Lua state
348  */
349 lua_State* sglua_get_maestro(void) {
350   return sglua_maestro_state;
351 }
352
353 /**
354  * \brief Makes the core functions available to the Lua world.
355  * \param L a Lua world
356  */
357 static void sglua_register_core_functions(lua_State *L)
358 {
359   /* register the core C functions to lua */
360   luaL_register(L, "simgrid", simgrid_functions);
361                                   /* simgrid */
362
363   /* set a finalizer that cleans simgrid, by adding to the simgrid module a
364    * dummy userdata whose __gc metamethod calls MSG_clean() */
365   lua_newuserdata(L, sizeof(void*));
366                                   /* simgrid udata */
367   lua_newtable(L);
368                                   /* simgrid udata mt */
369   lua_pushcfunction(L, simgrid_gc);
370                                   /* simgrid udata mt simgrid_gc */
371   lua_setfield(L, -2, "__gc");
372                                   /* simgrid udata mt */
373   lua_setmetatable(L, -2);
374                                   /* simgrid udata */
375   lua_setfield(L, -2, "__simgrid_loaded");
376                                   /* simgrid */
377   lua_pop(L, 1);
378                                   /* -- */
379 }
380
381 /**
382  * \brief Creates the simgrid module and make it available to Lua.
383  * \param L a Lua world
384  */
385 static void sglua_register_c_functions(lua_State *L)
386 {
387   sglua_register_core_functions(L);
388   sglua_register_task_functions(L);
389   sglua_register_comm_functions(L);
390   sglua_register_host_functions(L);
391   sglua_register_process_functions(L);
392   sglua_register_platf_functions(L);
393 }
394
395 /**
396  * \brief Runs a Lua function as a new simulated process.
397  * \param argc number of arguments of the function
398  * \param argv name of the Lua function and array of its arguments
399  * \return result of the function
400  */
401 static int run_lua_code(int argc, char **argv)
402 {
403   XBT_DEBUG("Run lua code %s", argv[0]);
404
405   /* create a new state, getting globals from maestro */
406   lua_State *L = sglua_clone_maestro();
407   MSG_process_set_data(MSG_process_self(), L);
408
409   /* start the function */
410   lua_getglobal(L, argv[0]);
411   xbt_assert(lua_isfunction(L, -1),
412               "There is no Lua function with name `%s'", argv[0]);
413
414   /* push arguments onto the stack */
415   int i;
416   for (i = 1; i < argc; i++)
417     lua_pushstring(L, argv[i]);
418
419   /* call the function */
420   _XBT_GNUC_UNUSED int err;
421   err = lua_pcall(L, argc - 1, 1, 0);
422   xbt_assert(err == 0, "Error running function `%s': %s", argv[0],
423               lua_tostring(L, -1));
424
425   /* retrieve result */
426   int res = 1;
427   if (lua_isnumber(L, -1)) {
428     res = lua_tonumber(L, -1);
429     lua_pop(L, 1);              /* pop returned value */
430   }
431
432   XBT_DEBUG("Execution of Lua code %s is over", (argv ? argv[0] : "(null)"));
433
434   return res;
435 }
436
437 /**
438  * \brief Returns a string corresponding to an MSG error code.
439  * \param err an MSG error code
440  * \return a string describing this error
441  */
442 const char* sglua_get_msg_error(MSG_error_t err) {
443
444   static const char* msg_errors[] = {
445       NULL,
446       "timeout",
447       "transfer failure",
448       "host failure",
449       "task canceled"
450   };
451
452   return msg_errors[err];
453 }