Logo AND Algorithmique Numérique Distribuée

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