Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
updating ChangeLog with tracing modifications
[simgrid.git] / src / bindings / lua / simgrid_lua.c
1 /* SimGrid Lua bindings                                                     */
2
3 /* Copyright (c) 2010. The SimGrid Team.
4  * All rights reserved.                                                     */
5
6 /* This program is free software; you can redistribute it and/or modify it
7  * under the terms of the license (GNU LGPL) which comes with this package. */
8
9 #include <stdio.h>
10 #include <lauxlib.h>
11 #include <lualib.h>
12 #include "msg/msg.h"
13 #include "simdag/simdag.h"
14 #include <gras.h>
15 #include "xbt.h"
16
17 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(lua,bindings,"Lua Bindings");
18
19 #define TASK_MODULE_NAME "simgrid.Task"
20 #define HOST_MODULE_NAME "simgrid.Host"
21 // Surf ( bypass XML )
22 #define LINK_MODULE_NAME "simgrid.Link"
23 #define ROUTE_MODULE_NAME "simgrid.Route"
24
25 /* ********************************************************************************* */
26 /*                            helper functions                                       */
27 /* ********************************************************************************* */
28 static void stackDump (const char *msg, lua_State *L) {
29   char buff[2048];
30   char *p=buff;
31   int i;
32   int top = lua_gettop(L);
33
34   fflush(stdout);
35   p+=sprintf(p,"STACK(top=%d): ",top);
36
37   for (i = 1; i <= top; i++) {  /* repeat for each level */
38     int t = lua_type(L, i);
39     switch (t) {
40
41     case LUA_TSTRING:  /* strings */
42       p+=sprintf(p,"`%s'", lua_tostring(L, i));
43       break;
44
45     case LUA_TBOOLEAN:  /* booleans */
46       p+=sprintf(p,lua_toboolean(L, i) ? "true" : "false");
47       break;
48
49     case LUA_TNUMBER:  /* numbers */
50       p+=sprintf(p,"%g", lua_tonumber(L, i));
51       break;
52
53     case LUA_TTABLE:
54       p+=sprintf(p, "Table");
55       break;
56
57     default:  /* other values */
58       p+=sprintf(p, "???");
59 /*      if ((ptr = luaL_checkudata(L,i,TASK_MODULE_NAME))) {
60         p+=sprintf(p,"task");
61       } else {
62         p+=printf(p,"%s", lua_typename(L, t));
63       }*/
64       break;
65
66     }
67     p+=sprintf(p,"  ");  /* put a separator */
68   }
69   INFO2("%s%s",msg,buff);
70 }
71
72 /** @brief ensures that a userdata on the stack is a task and returns the pointer inside the userdata */
73 static m_task_t checkTask (lua_State *L,int index) {
74   m_task_t *pi,tk;
75   luaL_checktype(L,index,LUA_TTABLE);
76   lua_getfield(L,index,"__simgrid_task");
77   pi = (m_task_t*)luaL_checkudata(L,-1,TASK_MODULE_NAME);
78   if(pi == NULL)
79          luaL_typerror(L,index,TASK_MODULE_NAME);
80   tk = *pi;
81   if(!tk)
82          luaL_error(L,"null Task");
83   lua_pop(L,1);
84   return  tk;
85 }
86 /* ********************************************************************************* */
87 /*                           wrapper functions                                       */
88 /* ********************************************************************************* */
89
90 /**
91  * A task is either something to compute somewhere, or something to exchange between two hosts (or both).
92  * It is defined by a computing amount and a message size.
93  *
94  */
95
96 /* *              * *
97  * * Constructors * *
98  * *              * */
99 /**
100  * Construct an new task with the specified processing amount and amount
101  * of data needed.
102  *
103  * @param name  Task's name
104  *
105  * @param computeDuration       A value of the processing amount (in flop) needed to process the task.
106  *                              If 0, then it cannot be executed with the execute() method.
107  *                              This value has to be >= 0.
108  *
109  * @param messageSize           A value of amount of data (in bytes) needed to transfert this task.
110  *                              If 0, then it cannot be transfered with the get() and put() methods.
111  *                              This value has to be >= 0.
112  */
113 static int Task_new(lua_State* L) {
114           const char *name=luaL_checkstring(L,1);
115           int comp_size = luaL_checkint(L,2);
116           int msg_size = luaL_checkint(L,3);
117           m_task_t msg_task = MSG_task_create(name,comp_size,msg_size,NULL);
118           lua_newtable (L); /* create a table, put the userdata on top of it */
119           m_task_t *lua_task = (m_task_t*)lua_newuserdata(L,sizeof(m_task_t));
120           *lua_task = msg_task;
121           luaL_getmetatable(L,TASK_MODULE_NAME);
122           lua_setmetatable(L,-2);
123           lua_setfield (L, -2, "__simgrid_task"); /* put the userdata as field of the table */
124           /* remove the args from the stack */
125           lua_remove(L,1);
126           lua_remove(L,1);
127           lua_remove(L,1);
128           return 1;
129 }
130
131 static int Task_get_name(lua_State *L) {
132   m_task_t tk = checkTask(L,-1);
133   lua_pushstring(L,MSG_task_get_name(tk));
134   return 1;
135 }
136
137 static int Task_computation_duration(lua_State *L){
138   m_task_t tk = checkTask(L,-1);
139   lua_pushnumber(L,MSG_task_get_compute_duration (tk));
140   return 1;
141 }
142
143 static int Task_execute(lua_State *L){
144   m_task_t tk = checkTask(L,-1);
145   int res = MSG_task_execute(tk);
146   lua_pushnumber(L,res);
147   return 1;
148 }
149
150 static int Task_destroy(lua_State *L) {
151   m_task_t tk = checkTask(L,-1);
152   int res = MSG_task_destroy(tk);
153   lua_pushnumber(L,res);
154   return 1;
155 }
156
157 static int Task_send(lua_State *L)  {
158   //stackDump("send ",L);
159   m_task_t tk = checkTask(L,-2);
160   const char *mailbox = luaL_checkstring(L,-1);
161   lua_pop(L,1); // remove the string so that the task is on top of it
162   MSG_task_set_data(tk,L); // Copy my stack into the task, so that the receiver can copy the lua task directly
163   MSG_error_t res = MSG_task_send(tk,mailbox);
164   while (MSG_task_get_data(tk)!=NULL) // Don't mess up with my stack: the receiver didn't copy the data yet
165     MSG_process_sleep(0); // yield
166
167   if (res != MSG_OK) switch(res) {
168     case MSG_TIMEOUT :
169       ERROR0("MSG_task_send failed : Timeout");
170       break;
171     case MSG_TRANSFER_FAILURE :
172       ERROR0("MSG_task_send failed : Transfer Failure");
173       break;
174     case MSG_HOST_FAILURE :
175       ERROR0("MSG_task_send failed : Host Failure ");
176       break;
177     default :
178       ERROR0("MSG_task_send failed : Unexpected error , please report this bug");
179       break;
180     }
181   return 0;
182 }
183
184 static int Task_recv(lua_State *L)  {
185   m_task_t tk = NULL;
186   const char *mailbox = luaL_checkstring(L,-1);
187   MSG_error_t res = MSG_task_receive(&tk,mailbox);
188
189   lua_State *sender_stack = MSG_task_get_data(tk);
190   lua_xmove(sender_stack,L,1); // copy the data directly from sender's stack
191   MSG_task_set_data(tk,NULL);
192
193   if(res != MSG_OK) switch(res){
194           case MSG_TIMEOUT :
195                   ERROR0("MSG_task_receive failed : Timeout");
196                   break;
197           case MSG_TRANSFER_FAILURE :
198                   ERROR0("MSG_task_receive failed : Transfer Failure");
199                   break;
200           case MSG_HOST_FAILURE :
201                   ERROR0("MSG_task_receive failed : Host Failure ");
202                   break;
203           default :
204                   ERROR0("MSG_task_receive failed : Unexpected error , please report this bug");
205                   break;
206                   }
207
208   return 1;
209 }
210
211 static const luaL_reg Task_methods[] = {
212     {"new",   Task_new},
213     {"name",  Task_get_name},
214     {"computation_duration",  Task_computation_duration},
215     {"execute", Task_execute},
216     {"destroy", Task_destroy},
217     {"send",    Task_send},
218     {"recv",    Task_recv},
219     {0,0}
220 };
221 static int Task_gc(lua_State *L) {
222   m_task_t tk=checkTask(L,-1);
223   if (tk) MSG_task_destroy(tk);
224   return 0;
225 }
226
227 static int Task_tostring(lua_State *L) {
228   lua_pushfstring(L, "Task :%p",lua_touserdata(L,1));
229   return 1;
230 }
231
232 static const luaL_reg Task_meta[] = {
233     {"__gc",  Task_gc},
234     {"__tostring",  Task_tostring},
235     {0,0}
236 };
237
238 /**
239  * Host
240  */
241 static m_host_t checkHost (lua_State *L,int index) {
242   m_host_t *pi,ht;
243   luaL_checktype(L,index,LUA_TTABLE);
244   lua_getfield(L,index,"__simgrid_host");
245   pi = (m_host_t*)luaL_checkudata(L,-1,HOST_MODULE_NAME);
246   if(pi == NULL)
247          luaL_typerror(L,index,HOST_MODULE_NAME);
248   ht = *pi;
249   if(!ht)
250          luaL_error(L,"null Host");
251   lua_pop(L,1);
252   return  ht;
253 }
254
255 static int Host_get_by_name(lua_State *L)
256 {
257         const char *name=luaL_checkstring(L,1);
258         DEBUG0("Getting Host from name...");
259         m_host_t msg_host = MSG_get_host_by_name(name);
260         if (!msg_host)
261                 {
262                 luaL_error(L,"null Host : MSG_get_host_by_name failled");
263                 }
264     lua_newtable (L); /* create a table, put the userdata on top of it */
265         m_host_t *lua_host = (m_host_t*)lua_newuserdata(L,sizeof(m_host_t));
266         *lua_host = msg_host;
267         luaL_getmetatable(L,HOST_MODULE_NAME);
268         lua_setmetatable(L,-2);
269         lua_setfield (L, -2, "__simgrid_host"); /* put the userdata as field of the table */
270         /* remove the args from the stack */
271         lua_remove(L,1);
272         return 1;
273 }
274
275
276 static int Host_get_name(lua_State *L) {
277   m_host_t ht = checkHost(L,-1);
278   lua_pushstring(L,MSG_host_get_name(ht));
279   return 1;
280 }
281
282 static int Host_number(lua_State *L) {
283   lua_pushnumber(L,MSG_get_host_number());
284   return 1;
285 }
286
287 static int Host_at(lua_State *L)
288 {
289         int index = luaL_checkinteger(L,1);
290         m_host_t host = MSG_get_host_table()[index-1]; // lua indexing start by 1 (lua[1] <=> C[0])
291         lua_newtable (L); /* create a table, put the userdata on top of it */
292         m_host_t *lua_host = (m_host_t*)lua_newuserdata(L,sizeof(m_host_t));
293         *lua_host = host;
294         luaL_getmetatable(L,HOST_MODULE_NAME);
295         lua_setmetatable(L,-2);
296         lua_setfield (L, -2, "__simgrid_host"); /* put the userdata as field of the table */
297         return 1;
298
299 }
300
301 /*****************************************************************************************
302                                                              * BYPASS XML SURF Methods *
303                                                                  ***************************
304                                                                  ***************************
305 ******************************************************************************************/
306 #include "surf/surfxml_parse.h" /* to override surf_parse and bypass the parser */
307 #include "surf/surf_private.h"
308 typedef struct t_host_attr
309 {
310         //platform attribute
311         // Mandatory attributes
312         const char* id;
313         double power_peak;
314         // Optional attributes
315         double power_scale;
316         const char *power_trace;
317         int state_initial;
318         const char *state_trace;
319         //deployment attribute
320         const char* function;
321         xbt_dynar_t args_list;
322 }host_attr,*p_host_attr;
323
324 typedef struct t_link_attr
325 {
326         const char* id;
327         double bandwidth;
328         double latency;
329 }link_attr,*p_link_attr;
330
331 typedef struct t_route_attr
332 {
333         const char *src_id;
334         const char *dest_id;
335         xbt_dynar_t links_id;
336
337 }route_attr,*p_route_attr;
338
339 //using xbt_dynar_t :
340 static xbt_dynar_t host_list_d ;
341 static xbt_dynar_t link_list_d ;
342 static xbt_dynar_t route_list_d ;
343
344
345 /**
346  * create host resource via CPU model [for MSG]
347  */
348
349 static void create_host(const char* id,double power_peak,double power_sc,
350                                                 const char* power_tr,int state_init,
351                                                 const char* state_tr)
352 {
353
354         double power_scale = 1.0;
355         tmgr_trace_t power_trace = NULL;
356         e_surf_resource_state_t state_initial;
357         tmgr_trace_t state_trace;
358         if(power_sc) // !=0
359                 power_scale = power_sc;
360         if (state_init == -1)
361                 state_initial = SURF_RESOURCE_OFF;
362         else
363                 state_initial = SURF_RESOURCE_ON;
364         if(power_tr)
365                 power_trace = tmgr_trace_new(power_tr);
366         else
367                 power_trace = tmgr_trace_new("");
368         if(state_tr)
369                 state_trace = tmgr_trace_new(state_tr);
370         else
371                 state_trace = tmgr_trace_new("");
372         current_property_set = xbt_dict_new();
373         surf_host_create_resource(xbt_strdup(id), power_peak, power_scale,
374                                                power_trace, state_initial, state_trace, current_property_set);
375
376 }
377
378 /*
379  *create host resource via workstation_ptask_L07 model [for SimDag]
380  */
381 static void create_host_wsL07(const char* id,double power_peak,double power_sc,
382                                                 const char* power_tr,int state_init,
383                                                 const char* state_tr)
384 {
385         double power_scale = 1.0;
386         tmgr_trace_t power_trace = NULL;
387         e_surf_resource_state_t state_initial;
388         tmgr_trace_t state_trace;
389         if(power_sc) // !=0
390                 power_scale = power_sc;
391         if (state_init == -1)
392                 state_initial = SURF_RESOURCE_OFF;
393         else
394                 state_initial = SURF_RESOURCE_ON;
395         if(power_tr)
396                 power_trace = tmgr_trace_new(power_tr);
397         else
398                 power_trace = tmgr_trace_new("");
399         if(state_tr)
400                 state_trace = tmgr_trace_new(state_tr);
401         else
402                 state_trace = tmgr_trace_new("");
403         current_property_set = xbt_dict_new();
404         surf_wsL07_host_create_resource(xbt_strdup(id), power_peak, power_scale,
405                                                power_trace, state_initial, state_trace, current_property_set);
406
407 }
408 /*
409  * add new host to platform hosts list
410  */
411 static int Host_new(lua_State *L)
412 {
413
414         if(xbt_dynar_is_empty(host_list_d))
415                 host_list_d = xbt_dynar_new(sizeof(p_host_attr), &xbt_free_ref);
416
417         p_host_attr host;
418         const char * id;
419         const char *power_trace;
420         const char *state_trace;
421         double power,power_scale;
422         int state_initial;
423         //get values from the table passed as argument
424     if (lua_istable(L,-1)) {
425
426             // get Id Value
427             lua_pushstring(L,"id");
428             lua_gettable(L, -2 );
429             id = lua_tostring(L,-1);
430             lua_pop(L,1);
431
432             // get power value
433             lua_pushstring(L,"power");
434             lua_gettable(L, -2 );
435             power = lua_tonumber(L,-1);
436             lua_pop(L,1);
437
438             //get power_scale
439             lua_pushstring(L,"power_scale");
440             lua_gettable(L, -2 );
441             power_scale = lua_tonumber(L,-1);
442             lua_pop(L,1);
443
444             //get power_trace
445             lua_pushstring(L,"power_trace");
446             lua_gettable(L, -2 );
447             power_trace = lua_tostring(L,-1);
448             lua_pop(L,1);
449
450             //get state initial
451             lua_pushstring(L,"state_initial");
452             lua_gettable(L, -2 );
453             state_initial = lua_tonumber(L,-1);
454             lua_pop(L,1);
455
456             //get trace state
457             lua_pushstring(L,"state_trace");
458             lua_gettable(L, -2 );
459             state_trace = lua_tostring(L,-1);
460             lua_pop(L,1);
461
462     } else {
463             ERROR0("Bad Arguments to create host, Should be a table with named arguments");
464             return -1;
465     }
466
467             host = malloc(sizeof(host_attr));
468                 host->id = id;
469                 host->power_peak = power;
470                 host->power_scale = power_scale;
471                 host->power_trace = power_trace;
472                 host->state_initial = state_initial;
473                 host->state_trace = state_trace;
474                 host->function = NULL;
475                 xbt_dynar_push(host_list_d, &host);
476
477     return 0;
478 }
479
480 /**
481  * add link to platform links list
482  */
483 static int Link_new(lua_State *L) // (id,bandwidth,latency)
484 {
485         if(xbt_dynar_is_empty(link_list_d))
486                 link_list_d = xbt_dynar_new(sizeof(p_link_attr), &xbt_free_ref);
487
488         const char* id;
489         double bandwidth,latency;
490         //get values from the table passed as argument
491         if (lua_istable(L,-1)) {
492                     // get Id Value
493                     lua_pushstring(L,"id");
494                     lua_gettable(L, -2 );
495                     id = lua_tostring(L,-1);
496                     lua_pop(L,1);
497
498                     // get bandwidth value
499                     lua_pushstring(L,"bandwidth");
500                     lua_gettable(L, -2 );
501                     bandwidth = lua_tonumber(L,-1);
502                     lua_pop(L,1);
503
504                     //get latency value
505                     lua_pushstring(L,"latency");
506                     lua_gettable(L, -2 );
507                     latency = lua_tonumber(L,-1);
508                     lua_pop(L,1);
509
510             } else {
511                     ERROR0("Bad Arguments to create link, Should be a table with named arguments");
512                     return -1;
513             }
514
515         p_link_attr link = malloc(sizeof(link_attr));
516         link->id = id;
517         link->bandwidth = bandwidth;
518         link->latency = latency;
519         xbt_dynar_push(link_list_d,&link);
520         return 0;
521 }
522
523 /**
524  * add route to platform routes list
525  */
526 static int Route_new(lua_State *L) // (src_id,dest_id,links_number,link_table)
527 {
528         if(xbt_dynar_is_empty(route_list_d))
529                 route_list_d = xbt_dynar_new(sizeof(p_route_attr), &xbt_free_ref);
530         const char * link_id;
531         p_route_attr route = malloc(sizeof(route_attr));
532         route->src_id = luaL_checkstring(L,1);
533         route->dest_id = luaL_checkstring(L,2);
534         route->links_id = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
535         lua_pushnil(L);
536         while (lua_next(L,3) != 0) {
537                 link_id = lua_tostring(L, -1);
538                 xbt_dynar_push(route->links_id, &link_id);
539             DEBUG2("index = %f , Link_id = %s \n",lua_tonumber(L, -2),lua_tostring(L, -1));
540             lua_pop(L, 1);
541         }
542         lua_pop(L, 1);
543
544         //add route to platform's route list
545         xbt_dynar_push(route_list_d,&route);
546         return 0;
547 }
548
549 /**
550  * set function to process
551  */
552 static int Host_set_function(lua_State *L) //(host,function,nb_args,list_args)
553 {
554         // look for the index of host in host_list
555         const char *host_id = luaL_checkstring(L,1);
556         const char* argument;
557         unsigned int i;
558         p_host_attr p_host;
559
560         xbt_dynar_foreach(host_list_d,i,p_host)
561         {
562                 if(p_host->id == host_id)
563                 {
564                         p_host->function = luaL_checkstring(L,2);
565                         if(lua_istable(L,3))
566                         {
567                                 p_host->args_list = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
568                                 // fill the args list
569                                 lua_pushnil(L);
570                                 int j = 0;
571                                 while (lua_next(L,3) != 0) {
572                                                 argument = lua_tostring(L, -1);
573                                                 xbt_dynar_push(p_host->args_list, &argument);
574                                                 DEBUG2("index = %f , Arg_id = %s \n",lua_tonumber(L, -2),lua_tostring(L, -1));
575                                                 j++;
576                                                 lua_pop(L, 1);
577                                         }
578                         }
579                         lua_pop(L, 1);
580                         return 0;
581                 }
582         }
583         ERROR1("Host : %s Not Fount !!",host_id);
584         return 1;
585 }
586
587 /*
588  * surf parse bypass platform
589  * through CPU/network Models
590  */
591
592 static int surf_parse_bypass_platform()
593 {
594         unsigned int i;
595         p_host_attr p_host;
596         p_link_attr p_link;
597         p_route_attr p_route;
598
599         // Add Hosts
600         xbt_dynar_foreach(host_list_d,i,p_host)
601         {
602                 create_host(p_host->id,p_host->power_peak,p_host->power_scale,p_host->power_trace,
603                                         p_host->state_initial,p_host->state_trace);
604                 //add to routing model host list
605                 surf_route_add_host((char*)p_host->id);
606         }
607
608         //add Links
609         xbt_dynar_foreach(link_list_d,i,p_link)
610         {
611                 surf_link_create_resource((char*)p_link->id,p_link->bandwidth,p_link->latency);
612         }
613         // add route
614         xbt_dynar_foreach(route_list_d,i,p_route)
615         {
616                 surf_route_set_resource((char*)p_route->src_id,(char*)p_route->dest_id,p_route->links_id,0);
617         }
618         /* </platform> */
619
620         surf_add_host_traces();
621         surf_set_routes();
622         surf_add_link_traces();
623
624         return 0; // must return 0 ?!!
625
626 }
627
628 /**
629  *
630  * surf parse bypass platform
631  * through workstation_ptask_L07 Model
632  */
633
634
635 static int surf_wsL07_parse_bypass_platform()
636 {
637         unsigned int i;
638         p_host_attr p_host;
639         p_link_attr p_link;
640         p_route_attr p_route;
641
642         // Add Hosts
643         xbt_dynar_foreach(host_list_d,i,p_host)
644         {
645                 create_host_wsL07(p_host->id,p_host->power_peak,p_host->power_scale,p_host->power_trace,
646                                         p_host->state_initial,p_host->state_trace);
647                 //add to routing model host list
648                 surf_route_add_host((char*)p_host->id);
649         }
650
651         //add Links
652         xbt_dynar_foreach(link_list_d,i,p_link)
653         {
654                 surf_wsL07_link_create_resource((char*)p_link->id,p_link->bandwidth,p_link->latency);
655         }
656         // add route
657         xbt_dynar_foreach(route_list_d,i,p_route)
658         {
659                 surf_route_set_resource((char*)p_route->src_id,(char*)p_route->dest_id,p_route->links_id,0);
660         }
661         /* </platform> */
662
663         surf_wsL07_add_traces();
664         surf_set_routes();
665
666         return 0;
667
668 }
669 /*
670  * surf parse bypass application for MSG Module
671  */
672 static int surf_parse_bypass_application()
673 {
674           unsigned int i;
675           p_host_attr p_host;
676           xbt_dynar_foreach(host_list_d,i,p_host)
677                   {
678                   if(p_host->function)
679                           MSG_set_function(p_host->id,p_host->function,p_host->args_list);
680                   }
681           return 0;
682 }
683
684 //***********Register Methods *******************************************//
685 /*
686  * Host Methods
687  */
688 static const luaL_reg Host_methods[] = {
689     {"getByName",   Host_get_by_name},
690     {"name",            Host_get_name},
691     {"number",          Host_number},
692     {"at",                      Host_at},
693     // Bypass XML Methods
694     {"new",                     Host_new},
695     {"setFunction",     Host_set_function},
696     {0,0}
697 };
698
699 static int Host_gc(lua_State *L)
700 {
701   m_host_t ht = checkHost(L,-1);
702   if (ht) ht = NULL;
703   return 0;
704 }
705
706 static int Host_tostring(lua_State *L)
707 {
708   lua_pushfstring(L,"Host :%p",lua_touserdata(L,1));
709   return 1;
710 }
711
712 static const luaL_reg Host_meta[] = {
713     {"__gc",  Host_gc},
714     {"__tostring",  Host_tostring},
715     {0,0}
716 };
717
718 /*
719  * Link Methods
720  */
721 static const luaL_reg Link_methods[] = {
722     {"new",Link_new},
723     {0,0}
724 };
725 /*
726  * Route Methods
727  */
728 static const luaL_reg Route_methods[] ={
729    {"new",Route_new},
730    {0,0}
731 };
732
733 /*
734  * Environment related
735  */
736
737 extern lua_State *simgrid_lua_state;
738
739 static int run_lua_code(int argc,char **argv) {
740   DEBUG1("Run lua code %s",argv[0]);
741   lua_State *L = lua_newthread(simgrid_lua_state);
742   int ref = luaL_ref(simgrid_lua_state, LUA_REGISTRYINDEX); // protect the thread from being garbage collected
743   int res = 1;
744
745   /* Start the co-routine */
746   lua_getglobal(L,argv[0]);
747   xbt_assert1(lua_isfunction(L,-1),
748       "The lua function %s does not seem to exist",argv[0]);
749
750   // push arguments onto the stack
751   int i;
752   for(i=1;i<argc;i++)
753     lua_pushstring(L,argv[i]);
754
755   // Call the function (in resume)
756   xbt_assert2(lua_pcall(L, argc-1, 1, 0) == 0,
757     "error running function `%s': %s",argv[0], lua_tostring(L, -1));
758
759   /* retrieve result */
760   if (lua_isnumber(L, -1)) {
761     res = lua_tonumber(L, -1);
762     lua_pop(L, 1);  /* pop returned value */
763   }
764   // cleanups
765   luaL_unref(simgrid_lua_state,LUA_REGISTRYINDEX,ref );
766   DEBUG1("Execution of lua code %s is over", (argv ? argv[0] : "(null)"));
767   return res;
768 }
769 static int launch_application(lua_State *L) {
770   const char * file = luaL_checkstring(L,1);
771   MSG_function_register_default(run_lua_code);
772   MSG_launch_application(file);
773   return 0;
774 }
775 #include "simix/simix.h" //FIXME: KILLME when debugging on simix internals become useless
776 static int create_environment(lua_State *L) {
777   const char *file = luaL_checkstring(L,1);
778   DEBUG1("Loading environment file %s",file);
779   MSG_create_environment(file);
780   smx_host_t *hosts = SIMIX_host_get_table();
781   int i;
782   for (i=0;i<SIMIX_host_get_number();i++) {
783     DEBUG1("We have an host %s", SIMIX_host_get_name(hosts[i]));
784   }
785
786   return 0;
787 }
788
789 static int debug(lua_State *L) {
790   const char *str = luaL_checkstring(L,1);
791   DEBUG1("%s",str);
792   return 0;
793 }
794 static int info(lua_State *L) {
795   const char *str = luaL_checkstring(L,1);
796   INFO1("%s",str);
797   return 0;
798 }
799 static int run(lua_State *L) {
800   MSG_main();
801   return 0;
802 }
803 static int clean(lua_State *L) {
804   MSG_clean();
805   return 0;
806 }
807
808 /*
809  * Bypass XML Parser
810  */
811
812 /*
813  * Register platform for MSG
814  */
815 static int msg_register_platform(lua_State *L)
816 {
817         /* Tell Simgrid we dont wanna use its parser*/
818         surf_parse = surf_parse_bypass_platform;
819         MSG_create_environment(NULL);
820         return 0;
821 }
822
823 /*
824  * Register platform for Simdag
825  */
826
827 static int sd_register_platform(lua_State *L)
828 {
829         surf_parse = surf_wsL07_parse_bypass_platform;
830         SD_create_environment(NULL);
831         return 0;
832 }
833 /*
834  * Register platform for gras
835  */
836 static int gras_register_platform(lua_State *L)
837 {
838         /* Tell Simgrid we dont wanna use its parser*/
839         surf_parse = surf_parse_bypass_platform;
840         gras_create_environment(NULL);
841         return 0;
842 }
843
844 /**
845  * Register applicaiton for MSG
846  */
847 static int msg_register_application(lua_State *L)
848 {
849          MSG_function_register_default(run_lua_code);
850          surf_parse = surf_parse_bypass_application;
851          MSG_launch_application(NULL);
852          return 0;
853 }
854
855 /*
856  * Register application for gras
857  */
858 static int gras_register_application(lua_State *L)
859 {
860         gras_function_register_default(run_lua_code);
861         surf_parse = surf_parse_bypass_application;
862         gras_launch_application(NULL);
863         return 0;
864 }
865 static const luaL_Reg simgrid_funcs[] = {
866     { "create_environment", create_environment},
867     { "launch_application", launch_application},
868     { "debug", debug},
869     { "info", info},
870     { "run", run},
871     { "clean", clean},
872     /* short names */
873     { "platform", create_environment},
874     { "application", launch_application},
875     /* methods to bypass XML parser*/
876     { "msg_register_platform",msg_register_platform},
877     { "sd_register_platform",sd_register_platform},
878     { "msg_register_application",msg_register_application},
879     { "gras_register_platform",gras_register_platform},
880     { "gras_register_application",gras_register_application},
881     { NULL, NULL }
882 };
883
884 /* ********************************************************************************* */
885 /*                       module management functions                                 */
886 /* ********************************************************************************* */
887
888 extern const char*xbt_ctx_factory_to_use; /*Hack: let msg load directly the right factory */
889
890 #define LUA_MAX_ARGS_COUNT 10 /* maximum amount of arguments we can get from lua on command line */
891 #define TEST
892 int luaopen_simgrid(lua_State* L); // Fuck gcc: we don't need that prototype
893 int luaopen_simgrid(lua_State* L) {
894
895   //xbt_ctx_factory_to_use = "lua";
896   char **argv=malloc(sizeof(char*)*LUA_MAX_ARGS_COUNT);
897   int argc=1;
898   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? */
899   /* Get the command line arguments from the lua interpreter */
900   lua_getglobal(L,"arg");
901   /* if arg is a null value, it means we use lua only as a script to init platform
902    * else it should be a table and then take arg in consideration
903    */
904   if(lua_istable(L,-1))
905   {
906           int done=0;
907           while (!done) {
908                 argc++;
909                 lua_pushinteger(L,argc-2);
910                 lua_gettable(L,-2);
911                 if (lua_isnil(L,-1)) {
912                   done = 1;
913                 } else {
914                   xbt_assert1(lua_isstring(L,-1),"argv[%d] got from lua is no string",argc-1);
915                   xbt_assert2(argc<LUA_MAX_ARGS_COUNT,
916                            "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",
917                            __FILE__,LUA_MAX_ARGS_COUNT-1);
918                   argv[argc-1] = (char*)luaL_checkstring(L,-1);
919                   lua_pop(L,1);
920                   DEBUG1("Got command line argument %s from lua",argv[argc-1]);
921                 }
922           }
923           argv[argc--]=NULL;
924
925           /* Initialize the MSG core */
926           MSG_global_init(&argc,argv);
927           DEBUG1("Still %d arguments on command line",argc); // FIXME: update the lua's arg table to reflect the changes from SimGrid
928  }
929   /* register the core C functions to lua */
930   luaL_register(L, "simgrid", simgrid_funcs);
931   /* register the task methods to lua */
932   luaL_openlib(L,TASK_MODULE_NAME,Task_methods,0); //create methods table,add it to the globals
933   luaL_newmetatable(L,TASK_MODULE_NAME); //create metatable for Task,add it to the Lua registry
934   luaL_openlib(L,0,Task_meta,0);// fill metatable
935   lua_pushliteral(L,"__index");
936   lua_pushvalue(L,-3);  //dup methods table
937   lua_rawset(L,-3); //matatable.__index = methods
938   lua_pushliteral(L,"__metatable");
939   lua_pushvalue(L,-3);  //dup methods table
940   lua_rawset(L,-3); //hide metatable:metatable.__metatable = methods
941   lua_pop(L,1);   //drop metatable
942
943   /* register the hosts methods to lua*/
944   luaL_openlib(L,HOST_MODULE_NAME,Host_methods,0);
945   luaL_newmetatable(L,HOST_MODULE_NAME);
946   luaL_openlib(L,0,Host_meta,0);
947   lua_pushliteral(L,"__index");
948   lua_pushvalue(L,-3);
949   lua_rawset(L,-3);
950   lua_pushliteral(L,"__metatable");
951   lua_pushvalue(L,-3);
952   lua_rawset(L,-3);
953   lua_pop(L,1);
954
955   /* register the links methods to lua*/
956   luaL_openlib(L,LINK_MODULE_NAME,Link_methods,0);
957   luaL_newmetatable(L,LINK_MODULE_NAME);
958   lua_pop(L,1);
959
960   /*register the routes methods to lua*/
961   luaL_openlib(L,ROUTE_MODULE_NAME,Route_methods,0);
962   luaL_newmetatable(L,LINK_MODULE_NAME);
963   lua_pop(L,1);
964
965   /* Keep the context mechanism informed of our lua world today */
966   simgrid_lua_state = L;
967   return 1;
968 }