Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
c340e6b9039e4ef920493870846e5418ce110775
[simgrid.git] / src / bindings / lua / simgrid_lua.c
1 /* SimGrid Lua bindings                                                     */
2
3 /* Copyright (c) 2010, the SimGrid team. All right reserved.                */
4
5 /* This program is free software; you can redistribute it and/or modify it
6  * under the terms of the license (GNU LGPL) which comes with this package. */
7
8 #include <stdio.h>
9 #include <lauxlib.h>
10 #include <lualib.h>
11
12 #include "msg/msg.h"
13 #include "xbt.h"
14
15 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(lua,bindings,"Lua Bindings");
16
17 #define TASK_MODULE_NAME "simgrid.Task"
18
19 /* ********************************************************************************* */
20 /*                            helper functions                                       */
21 /* ********************************************************************************* */
22
23 static void stackDump (lua_State *L) {
24   char buff[2048];
25   char *p=buff;
26   int i;
27   int top = lua_gettop(L);
28   void *ptr;
29   fflush(stdout);
30   p+=sprintf(p,"STACK(top=%d): ",top);
31   for (i = 1; i <= top; i++) {  /* repeat for each level */
32     int t = lua_type(L, i);
33     switch (t) {
34
35     case LUA_TSTRING:  /* strings */
36       p+=sprintf(p,"`%s'", lua_tostring(L, i));
37       break;
38
39     case LUA_TBOOLEAN:  /* booleans */
40       p+=sprintf(p,lua_toboolean(L, i) ? "true" : "false");
41       break;
42
43     case LUA_TNUMBER:  /* numbers */
44       p+=sprintf(p,"%g", lua_tonumber(L, i));
45       break;
46
47     default:  /* other values */
48       if ((ptr = luaL_checkudata(L,i,TASK_MODULE_NAME))) {
49         p+=sprintf(p,"task");
50       } else {
51         p+=printf(p,"%s", lua_typename(L, t));
52       }
53       break;
54
55     }
56     p+=sprintf(p,"  ");  /* put a separator */
57   }
58   DEBUG1("%s",buff);
59 }
60
61 /** @brief ensures that a userdata on the stack is a task and returns the pointer inside the userdata */
62 static m_task_t checkTask (lua_State *L,int index) {
63   m_task_t *pi,tk;
64   luaL_checktype(L,index,LUA_TUSERDATA);
65   pi = (m_task_t*)luaL_checkudata(L,index,TASK_MODULE_NAME);
66   if(pi == NULL)
67          luaL_typerror(L,index,TASK_MODULE_NAME);
68   tk = *pi;
69   if(!tk)
70          luaL_error(L,"null Task");
71   return  tk;
72 }
73
74 /** @brief leaves a new userdata on top of the stack, sets its metatable, and sets the Task pointer inside the userdata */
75 static m_task_t *pushTask (lua_State *L,m_task_t tk,int flag) {
76
77   m_task_t *pi = NULL;
78   if ( flag == 0)
79   pi = (m_task_t*)MSG_task_get_data(tk);//(m_task_t*)lua_newuserdata(L,sizeof(m_task_t));
80   else if ( flag == 1)
81   {
82           pi = (m_task_t*)lua_newuserdata(L,sizeof(m_task_t));
83           *pi=tk;
84
85   }
86
87   //*pi=tk;
88   DEBUG1("push lua task with Name : %s \n",MSG_task_get_name(*pi));
89   luaL_getmetatable(L,TASK_MODULE_NAME);
90   lua_setmetatable(L,-2);
91   return pi;
92
93 }
94
95 /* ********************************************************************************* */
96 /*                           wrapper functions                                       */
97 /* ********************************************************************************* */
98
99 static int Task_new(lua_State* L) {
100   const char *name=luaL_checkstring(L,1);
101   int comp_size = luaL_checkint(L,2);
102   int msg_size = luaL_checkint(L,3);
103   // FIXME: data shouldn't be NULL I guess
104   //pushTask(L,MSG_task_create(name,comp_size,msg_size,NULL));
105   m_task_t msg_task = MSG_task_create(name,comp_size,msg_size,NULL);
106   m_task_t *lua_task = (m_task_t*)lua_newuserdata(L,sizeof(m_task_t));
107   *lua_task = msg_task;
108   MSG_task_set_data(msg_task,lua_task);
109   pushTask(L,msg_task,0);
110   INFO0("Created task");
111   return 1;
112 }
113
114 static int Task_get_name(lua_State *L) {
115   m_task_t tk = checkTask(L,1);
116   lua_pushstring(L,MSG_task_get_name(tk));
117   return 1;
118 }
119
120 static int Task_computation_duration(lua_State *L){
121   m_task_t tk = checkTask(L,1);
122   lua_pushnumber(L,MSG_task_get_compute_duration (tk));
123   return 1;
124 }
125
126 static int Task_execute(lua_State *L){
127   m_task_t tk = checkTask(L,1);
128   int res = MSG_task_execute(tk);
129   lua_pushnumber(L,res);
130   return 1;
131 }
132
133 static int Task_destroy(lua_State *L) {
134   m_task_t tk = checkTask(L,1);
135   int res = MSG_task_destroy(tk);
136   lua_pushnumber(L,res);
137   return 1;
138 }
139 static int Task_send(lua_State *L)  {
140   m_task_t tk = checkTask(L,1);
141   const char *mailbox = luaL_checkstring(L,2);
142   MSG_error_t res = MSG_task_send(tk,mailbox);
143   if(res != MSG_OK)
144     {
145           switch(res){
146           case MSG_TIMEOUT :
147                   ERROR0("MSG_task_send failed : Timeout");
148                   break;
149           case MSG_TRANSFER_FAILURE :
150                   ERROR0("MSG_task_send failed : Transfer Failure");
151                   break;
152           case MSG_HOST_FAILURE :
153                   ERROR0("MSG_task_send failed : Host Failure ");
154                   break;
155           default :
156                   ERROR0("MSG_task_send failed : Unexpected error , please report this bug");
157                   break;
158                   }
159     }
160   return 0;
161 }
162 static int Task_recv(lua_State *L)  {
163   m_task_t tk = NULL;
164   const char *mailbox = luaL_checkstring(L,1);
165   MSG_error_t res = MSG_task_receive(&tk,mailbox);
166   if (MSG_task_has_data(tk)) DEBUG1("Receive The Task with Name : %s \n",MSG_task_get_name(tk));
167   MSG_task_ref(tk); //FIXME: kill it once a ctask cannot be in more than one luatask anymore
168   if(res != MSG_OK)
169   {
170           switch(res){
171           case MSG_TIMEOUT :
172                   ERROR0("MSG_task_receive failed : Timeout");
173                   break;
174           case MSG_TRANSFER_FAILURE :
175                   ERROR0("MSG_task_receive failed : Transfer Failure");
176                   break;
177           case MSG_HOST_FAILURE :
178                   ERROR0("MSG_task_receive failed : Host Failure ");
179                   break;
180           default :
181                   ERROR0("MSG_task_receive failed : Unexpected error , please report this bug");
182                   break;
183                   }
184   }
185   DEBUG1("Task Name : >>>%s",MSG_task_get_name(tk));
186   //lua_pushlightuserdata(L,MSG_task_get_data(tk));
187   pushTask(L,tk,1);
188   return 1;
189 }
190
191 static const luaL_reg Task_methods[] = {
192     {"new",   Task_new},
193     {"name",  Task_get_name},
194     {"computation_duration",  Task_computation_duration},
195     {"execute", Task_execute},
196     {"destroy", Task_destroy},
197     {"send",    Task_send},
198     {"recv",    Task_recv},
199     {0,0}
200 };
201 static int Task_gc(lua_State *L) {
202   m_task_t tk=checkTask(L,1);
203   if (tk) MSG_task_destroy(tk);
204   //printf("GoodBye Task(%p)\n",lua_touserdata(L,1));
205   return 0;
206 }
207
208 static int Task_tostring(lua_State *L) {
209   lua_pushfstring(L, "Task :%p",lua_touserdata(L,1));
210   return 1;
211 }
212
213
214 static const luaL_reg Task_meta[] = {
215     {"__gc",  Task_gc},
216     {"__tostring",  Task_tostring},
217     {0,0}
218 };
219
220 /*
221  * Environment related
222  */
223 extern lua_State *simgrid_lua_state;
224
225 static int run_lua_code(int argc,char **argv) {
226   DEBUG1("Run lua code %s",argv[0]);
227 //  fprintf(stderr,"Run lua code %s\n", (argv ? argv[0] : "(null)"));
228   lua_State *L = lua_newthread(simgrid_lua_state);
229   int ref = luaL_ref(simgrid_lua_state, LUA_REGISTRYINDEX); // protect the thread from being garbage collected
230   int res = 1;
231
232   /* Start the co-routine */
233   lua_getglobal(L,argv[0]);
234   xbt_assert1(lua_isfunction(L,-1),
235       "The lua function %s does not seem to exist",argv[0]);
236
237   // push arguments onto the stack
238   int i;
239   for(i=1;i<argc;i++)
240     lua_pushstring(L,argv[i]);
241
242   // Call the function (in resume)
243   xbt_assert2(lua_pcall(L, argc-1, 1, 0) == 0,
244     "error running function `%s': %s",argv[0], lua_tostring(L, -1));
245
246   /* retrieve result */
247   if (lua_isnumber(L, -1)) {
248     res = lua_tonumber(L, -1);
249     lua_pop(L, 1);  /* pop returned value */
250   }
251
252   // cleanups
253   luaL_unref(simgrid_lua_state,LUA_REGISTRYINDEX,ref );
254   DEBUG1("Execution of lua code %s is over", (argv ? argv[0] : "(null)"));
255   return res;
256 }
257 static int launch_application(lua_State *L) {
258   const char * file = luaL_checkstring(L,1);
259   MSG_function_register_default(run_lua_code);
260   MSG_launch_application(file);
261   return 0;
262 }
263 #include "simix/simix.h" //FIXME: KILLME when debugging on simix internals become useless
264 static int create_environment(lua_State *L) {
265   const char *file = luaL_checkstring(L,1);
266   DEBUG1("Loading environment file %s",file);
267   MSG_create_environment(file);
268   smx_host_t *hosts = SIMIX_host_get_table();
269   int i;
270   for (i=0;i<SIMIX_host_get_number();i++) {
271     DEBUG1("We have an host %s", SIMIX_host_get_name(hosts[i]));
272   }
273
274   return 0;
275 }
276 static int debug(lua_State *L) {
277   const char *str = luaL_checkstring(L,1);
278   DEBUG1("%s",str);
279   return 0;
280 }
281 static int info(lua_State *L) {
282   const char *str = luaL_checkstring(L,1);
283   INFO1("%s",str);
284   return 0;
285 }
286 static int run(lua_State *L) {
287   MSG_main();
288   return 0;
289 }
290 static int clean(lua_State *L) {
291   MSG_clean();
292   return 0;
293 }
294 static const luaL_Reg simgrid_funcs[] = {
295     { "create_environment", create_environment},
296     { "launch_application", launch_application},
297     { "debug", debug},
298     { "info", info},
299     { "run", run},
300     { "clean", clean},
301     /* short names */
302     { "platform", create_environment},
303     { "application", launch_application},
304     { NULL, NULL }
305 };
306
307 /* ********************************************************************************* */
308 /*                       module management functions                                 */
309 /* ********************************************************************************* */
310
311 extern const char*xbt_ctx_factory_to_use; /*Hack: let msg load directly the right factory */
312
313 #define LUA_MAX_ARGS_COUNT 10 /* maximum amount of arguments we can get from lua on command line */
314
315 int luaopen_simgrid(lua_State* L); // Fuck gcc: we don't need that prototype
316 int luaopen_simgrid(lua_State* L) {
317   //xbt_ctx_factory_to_use = "lua";
318
319   char **argv=malloc(sizeof(char*)*LUA_MAX_ARGS_COUNT);
320   int argc=1;
321   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? */
322   /* Get the command line arguments from the lua interpreter */
323   lua_getglobal(L,"arg");
324   xbt_assert1(lua_istable(L,-1),"arg parameter is not a table but a %s",lua_typename(L,-1));
325   int done=0;
326   while (!done) {
327     argc++;
328     lua_pushinteger(L,argc-2);
329     lua_gettable(L,-2);
330     if (lua_isnil(L,-1)) {
331       done = 1;
332     } else {
333       xbt_assert1(lua_isstring(L,-1),"argv[%d] got from lua is no string",argc-1);
334       xbt_assert2(argc<LUA_MAX_ARGS_COUNT,
335            "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",
336            __FILE__,LUA_MAX_ARGS_COUNT-1);
337       argv[argc-1] = (char*)luaL_checkstring(L,-1);
338       lua_pop(L,1);
339       DEBUG1("Got command line argument %s from lua",argv[argc-1]);
340     }
341   }
342   argv[argc--]=NULL;
343
344   /* Initialize the MSG core */
345   MSG_global_init(&argc,argv);
346   DEBUG1("Still %d arguments on command line",argc); // FIXME: update the lua's arg table to reflect the changes from SimGrid
347
348   /* register the core C functions to lua */
349   luaL_register(L, "simgrid", simgrid_funcs);
350   /* register the tasks to lua */
351   luaL_openlib(L,TASK_MODULE_NAME,Task_methods,0); //create methods table,add it to the globals
352   luaL_newmetatable(L,TASK_MODULE_NAME); //create metatable for Task,add it to the Lua registry
353   luaL_openlib(L,0,Task_meta,0);// fill metatable
354   lua_pushliteral(L,"__index");
355   lua_pushvalue(L,-3);  //dup methods table
356   lua_rawset(L,-3); //matatable.__index = methods
357   lua_pushliteral(L,"__metatable");
358   lua_pushvalue(L,-3);  //dup methods table
359   lua_rawset(L,-3); //hide metatable:metatable.__metatable = methods
360   lua_pop(L,1);   //drop metatable
361
362   /* Keep the context mechanism informed of our lua world today */
363   simgrid_lua_state = L;
364
365   return 1;
366 }