Logo AND Algorithmique Numérique Distribuée

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