Logo AND Algorithmique Numérique Distribuée

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