Logo AND Algorithmique Numérique Distribuée

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