Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
tricky way to bypass XML parser and setup the environment from lua code
[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 "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 // Surf ( bypass XML )
20 #define LINK_MODULE_NAME "simgrid.Link"
21 #define ROUTE_MODULE_NAME "simgrid.Route"
22
23 /* ********************************************************************************* */
24 /*                            helper functions                                       */
25 /* ********************************************************************************* */
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 /** @brief leaves a new userdata on top of the stack, sets its metatable, and sets the Task pointer inside the userdata */
87 // NOT USED
88 /*static m_task_t *pushTask (lua_State *L,m_task_t tk) {
89   m_task_t *pi = NULL;
90   pi = (m_task_t*)lua_newuserdata(L,sizeof(m_task_t));
91   *pi=tk;
92   DEBUG1("push lua task with Name : %s \n",MSG_task_get_name(*pi));
93   luaL_getmetatable(L,TASK_MODULE_NAME);
94   lua_setmetatable(L,-2);
95   return pi;
96 }*/
97
98 /* ********************************************************************************* */
99 /*                           wrapper functions                                       */
100 /* ********************************************************************************* */
101
102 /**
103  *  Task
104  */
105
106 static int Task_new(lua_State* L) {
107   const char *name=luaL_checkstring(L,1);
108   int comp_size = luaL_checkint(L,2);
109   int msg_size = luaL_checkint(L,3);
110   INFO0("Creating task");
111   m_task_t msg_task = MSG_task_create(name,comp_size,msg_size,NULL);
112   lua_newtable (L); /* create a table, put the userdata on top of it */
113   m_task_t *lua_task = (m_task_t*)lua_newuserdata(L,sizeof(m_task_t));
114   *lua_task = msg_task;
115   luaL_getmetatable(L,TASK_MODULE_NAME);
116   lua_setmetatable(L,-2);
117   lua_setfield (L, -2, "__simgrid_task"); /* put the userdata as field of the table */
118   /* remove the args from the stack */
119   lua_remove(L,1);
120   lua_remove(L,1);
121   lua_remove(L,1);
122   return 1;
123 }
124
125 static int Task_get_name(lua_State *L) {
126   m_task_t tk = checkTask(L,-1);
127   lua_pushstring(L,MSG_task_get_name(tk));
128   return 1;
129 }
130
131 static int Task_computation_duration(lua_State *L){
132   m_task_t tk = checkTask(L,-1);
133   lua_pushnumber(L,MSG_task_get_compute_duration (tk));
134   return 1;
135 }
136
137 static int Task_execute(lua_State *L){
138   m_task_t tk = checkTask(L,-1);
139   int res = MSG_task_execute(tk);
140   lua_pushnumber(L,res);
141   return 1;
142 }
143
144 static int Task_destroy(lua_State *L) {
145   m_task_t tk = checkTask(L,-1);
146   int res = MSG_task_destroy(tk);
147   lua_pushnumber(L,res);
148   return 1;
149 }
150
151 static int Task_send(lua_State *L)  {
152   //stackDump("send ",L);
153   m_task_t tk = checkTask(L,-2);
154   const char *mailbox = luaL_checkstring(L,-1);
155   lua_pop(L,1); // remove the string so that the task is on top of it
156   MSG_task_set_data(tk,L); // Copy my stack into the task, so that the receiver can copy the lua task directly
157   MSG_error_t res = MSG_task_send(tk,mailbox);
158   while (MSG_task_get_data(tk)!=NULL) // Don't mess up with my stack: the receiver didn't copy the data yet
159     MSG_process_sleep(0); // yield
160
161   if (res != MSG_OK) switch(res) {
162     case MSG_TIMEOUT :
163       ERROR0("MSG_task_send failed : Timeout");
164       break;
165     case MSG_TRANSFER_FAILURE :
166       ERROR0("MSG_task_send failed : Transfer Failure");
167       break;
168     case MSG_HOST_FAILURE :
169       ERROR0("MSG_task_send failed : Host Failure ");
170       break;
171     default :
172       ERROR0("MSG_task_send failed : Unexpected error , please report this bug");
173       break;
174     }
175   return 0;
176 }
177
178 static int Task_recv(lua_State *L)  {
179   m_task_t tk = NULL;
180   const char *mailbox = luaL_checkstring(L,-1);
181   MSG_error_t res = MSG_task_receive(&tk,mailbox);
182
183   lua_State *sender_stack = MSG_task_get_data(tk);
184   lua_xmove(sender_stack,L,1); // copy the data directly from sender's stack
185   MSG_task_set_data(tk,NULL);
186
187   if(res != MSG_OK) switch(res){
188           case MSG_TIMEOUT :
189                   ERROR0("MSG_task_receive failed : Timeout");
190                   break;
191           case MSG_TRANSFER_FAILURE :
192                   ERROR0("MSG_task_receive failed : Transfer Failure");
193                   break;
194           case MSG_HOST_FAILURE :
195                   ERROR0("MSG_task_receive failed : Host Failure ");
196                   break;
197           default :
198                   ERROR0("MSG_task_receive failed : Unexpected error , please report this bug");
199                   break;
200                   }
201
202   return 1;
203 }
204
205 static const luaL_reg Task_methods[] = {
206     {"new",   Task_new},
207     {"name",  Task_get_name},
208     {"computation_duration",  Task_computation_duration},
209     {"execute", Task_execute},
210     {"destroy", Task_destroy},
211     {"send",    Task_send},
212     {"recv",    Task_recv},
213     {0,0}
214 };
215 static int Task_gc(lua_State *L) {
216   m_task_t tk=checkTask(L,-1);
217   if (tk) MSG_task_destroy(tk);
218   return 0;
219 }
220
221 static int Task_tostring(lua_State *L) {
222   lua_pushfstring(L, "Task :%p",lua_touserdata(L,1));
223   return 1;
224 }
225
226 static const luaL_reg Task_meta[] = {
227     {"__gc",  Task_gc},
228     {"__tostring",  Task_tostring},
229     {0,0}
230 };
231
232 /**
233  * Host
234  */
235 static m_host_t checkHost (lua_State *L,int index) {
236   m_host_t *pi,ht;
237   luaL_checktype(L,index,LUA_TTABLE);
238   lua_getfield(L,index,"__simgrid_host");
239   pi = (m_host_t*)luaL_checkudata(L,-1,HOST_MODULE_NAME);
240   if(pi == NULL)
241          luaL_typerror(L,index,HOST_MODULE_NAME);
242   ht = *pi;
243   if(!ht)
244          luaL_error(L,"null Host");
245   lua_pop(L,1);
246   return  ht;
247 }
248
249 static int Host_get_by_name(lua_State *L)
250 {
251         const char *name=luaL_checkstring(L,1);
252         DEBUG0("Getting Host from name...");
253         m_host_t msg_host = MSG_get_host_by_name(name);
254         if (!msg_host)
255                 {
256                 luaL_error(L,"null Host : MSG_get_host_by_name failled");
257                 }
258     lua_newtable (L); /* create a table, put the userdata on top of it */
259         m_host_t *lua_host = (m_host_t*)lua_newuserdata(L,sizeof(m_host_t));
260         *lua_host = msg_host;
261         luaL_getmetatable(L,HOST_MODULE_NAME);
262         lua_setmetatable(L,-2);
263         lua_setfield (L, -2, "__simgrid_host"); /* put the userdata as field of the table */
264         /* remove the args from the stack */
265         lua_remove(L,1);
266         return 1;
267 }
268
269
270 static int Host_get_name(lua_State *L) {
271   m_host_t ht = checkHost(L,-1);
272   lua_pushstring(L,MSG_host_get_name(ht));
273   return 1;
274 }
275
276 static int Host_number(lua_State *L) {
277   lua_pushnumber(L,MSG_get_host_number());
278   return 1;
279 }
280
281 static int Host_at(lua_State *L)
282 {
283         int index = luaL_checkinteger(L,1);
284         m_host_t host = MSG_get_host_table()[index-1]; // lua indexing start by 1 (lua[1] <=> C[0])
285         lua_newtable (L); /* create a table, put the userdata on top of it */
286         m_host_t *lua_host = (m_host_t*)lua_newuserdata(L,sizeof(m_host_t));
287         *lua_host = host;
288         luaL_getmetatable(L,HOST_MODULE_NAME);
289         lua_setmetatable(L,-2);
290         lua_setfield (L, -2, "__simgrid_host"); /* put the userdata as field of the table */
291         return 1;
292
293 }
294
295 /*****************************************************************************************
296                                                              * BYPASS XML SURF Methods *
297                                                                  ***************************
298                                                                  ***************************
299 ******************************************************************************************/
300 #include "surf/surfxml_parse.h" /* to override surf_parse and bypass the parser */
301 typedef struct t_host_attr
302 {
303         //platform attribute
304         const char* id;
305         double power;
306         //deployment attribute
307         const char* function;
308         int args_nb;
309         const char ** args_list;
310 }host_attr,*p_host_attr;
311
312 typedef struct t_link_attr
313 {
314         const char* id;
315         double bandwidth;
316         double latency;
317 }link_attr,*p_link_attr;
318
319 typedef struct t_route_attr
320 {
321         const char *src_id;
322         const char *dest_id;
323         int links_nb;
324         const char **links_id;
325
326 }route_attr,*p_route_attr;
327
328
329 static int host_index = 0;
330 static int link_index = 0;
331 static int route_index = 0;
332
333 static int max_host_number = 0;
334 static int max_link_number = 0;
335 static int max_route_number = 0;
336
337 static p_host_attr* host_list;
338 static p_link_attr* link_list;
339 static p_route_attr* route_list;
340
341 static int Host_set_number(lua_State *L)
342 {
343         max_host_number = luaL_checkint(L,1);
344         host_list = malloc(sizeof(host_attr)*max_host_number);
345         return 0;
346 }
347
348 static int Link_set_number(lua_State *L)
349 {
350         max_link_number = luaL_checkint(L,1);
351         link_list = malloc(sizeof(link_attr)*max_link_number);
352         return 0;
353 }
354
355 static int Route_set_number(lua_State *L)
356 {
357         max_route_number = luaL_checkint(L,1);
358         route_list = malloc(sizeof(route_attr)*max_link_number);
359         return 0;
360 }
361
362 static int Host_new(lua_State *L) //(id,power)
363 {
364         p_host_attr host = malloc(sizeof(host_attr));
365         host->id = luaL_checkstring(L,1);
366         host->power = luaL_checknumber(L,2);
367         if(host_index >= max_host_number)
368                 ERROR1("max host number:%d reached !!!",max_host_number);
369         host_list[host_index] = host;
370         host_list[host_index]->function = NULL;
371         host_index++;
372         return 0;
373 }
374
375 static int Link_new(lua_State *L) // (id,bandwidth,latency)
376 {
377
378         p_link_attr link = malloc(sizeof(link_attr));
379         link->id = luaL_checkstring(L,1);
380         link->bandwidth = luaL_checknumber(L,2);
381         link->latency = luaL_checknumber(L,3);
382         if(link_index >= max_link_number)
383                 ERROR1("max link number: %d reached !!!",max_link_number);
384         link_list[link_index] = link;
385         link_index++;
386         return 0;
387 }
388
389 static int Route_new(lua_State *L) // (src_id,dest_id,links_number,link_table)
390 {
391         int i=0;
392         p_route_attr route = malloc(sizeof(route_attr));
393         route->src_id = luaL_checkstring(L,1);
394         route->dest_id = luaL_checkstring(L,2);
395         route->links_nb = luaL_checkint(L,3);
396         route->links_id = malloc(sizeof(char*)*route->links_nb);
397         lua_pushnil(L);
398         while (lua_next(L,4) != 0) {
399                 if(i >= route->links_nb)
400                         ERROR1("Number of links should be less than %d",route->links_nb+1);
401                 route->links_id[i] = lua_tostring(L, -1);
402             DEBUG2("index = %f , Link_id = %s \n",lua_tonumber(L, -2),lua_tostring(L, -1));
403             i++;
404             lua_pop(L, 1);
405         }
406         lua_pop(L, 1);
407
408         //add route to platform's route list
409         if(route_index >= max_route_number)
410                         ERROR1("max route number: %d reached !!!",max_route_number);
411         route_list[route_index] = route;
412         route_index++;
413         return 0;
414 }
415
416 static int Host_set_function(lua_State *L) //(host,function,nb_args,list_args)
417 {
418         // look for the index of host in host_list
419         const char *host_id = luaL_checkstring(L,1);
420         int i;
421         for(i=0;i< host_index;i++)
422         {
423                 if(host_list[i]->id == host_id)
424                 {
425                         host_list[i]->function = luaL_checkstring(L,2);
426                         host_list[i]->args_nb = luaL_checkint(L,3);
427                         host_list[i]->args_list = malloc(sizeof(char*)*host_list[i]->args_nb);
428                         // fill the args list
429                         lua_pushnil(L);
430                         int j = 0;
431                         while (lua_next(L,4) != 0) {
432                                         if(j >= host_list[i]->args_nb)
433                                                 ERROR1("Number of args should be less than %d",host_list[i]->args_nb+1);
434                                         host_list[i]->args_list[j] = lua_tostring(L, -1);
435                                     DEBUG2("index = %f , Arg_id = %s \n",lua_tonumber(L, -2),lua_tostring(L, -1));
436                                     j++;
437                                     lua_pop(L, 1);
438                                 }
439                         lua_pop(L, 1);
440                         return 0;
441                 }
442         }
443         ERROR1("Host : %s Not Fount !!",host_id);
444         return 1;
445 }
446
447
448
449 /*
450  * surf parse bypass platform
451  */
452 static int surf_parse_bypass_platform()
453 {
454         static int AX_ptr = 0;
455         static int surfxml_bufferstack_size = 2048;
456           /* FIXME allocating memory for the buffer, I think 2kB should be enough */
457         surfxml_bufferstack = xbt_new0(char, surfxml_bufferstack_size);
458           /* <platform> */
459         SURFXML_BUFFER_SET(platform_version, "2");
460         SURFXML_START_TAG(platform);
461         char buffer[22];
462         int i;
463
464         // Add Host
465         for(i=0;i<host_index;i++)
466         {
467                 SURFXML_BUFFER_SET(host_id,host_list[i]->id);
468                 sprintf(buffer, "%f", host_list[i]->power);
469                 SURFXML_BUFFER_SET(host_power,buffer);
470                 SURFXML_BUFFER_SET(host_availability, "1.0");
471                 SURFXML_BUFFER_SET(host_availability_file, "");
472                 A_surfxml_host_state = A_surfxml_host_state_ON;
473                 SURFXML_BUFFER_SET(host_state_file, "");
474                 SURFXML_BUFFER_SET(host_interference_send, "1.0");
475                 SURFXML_BUFFER_SET(host_interference_recv, "1.0");
476                 SURFXML_BUFFER_SET(host_interference_send_recv, "1.0");
477                 SURFXML_BUFFER_SET(host_max_outgoing_rate, "-1.0");
478                 SURFXML_START_TAG(host);
479                 SURFXML_END_TAG(host);
480         }
481
482         //add Host
483         for (i = 0;i<link_index;i++)
484         {
485                 SURFXML_BUFFER_SET(link_id,link_list[i]->id);
486                 sprintf(buffer,"%f",link_list[i]->bandwidth);
487                 SURFXML_BUFFER_SET(link_bandwidth,buffer);
488                 SURFXML_BUFFER_SET(link_bandwidth_file, "");
489                 sprintf(buffer,"%f",link_list[i]->latency);
490                 SURFXML_BUFFER_SET(link_latency,buffer);
491                 SURFXML_BUFFER_SET(link_latency_file, "");
492                 A_surfxml_link_state = A_surfxml_link_state_ON;
493                 SURFXML_BUFFER_SET(link_state_file, "");
494                 A_surfxml_link_sharing_policy = A_surfxml_link_sharing_policy_SHARED;
495                 SURFXML_START_TAG(link);
496                 SURFXML_END_TAG(link);
497         }
498
499         // add route
500
501         for (i = 0;i<route_index;i++)
502         {
503                 SURFXML_BUFFER_SET(route_src,route_list[i]->src_id);
504                 SURFXML_BUFFER_SET(route_dst,route_list[i]->dest_id);
505                 SURFXML_BUFFER_SET(route_impact_on_src, "0.0");
506                 SURFXML_BUFFER_SET(route_impact_on_dst, "0.0");
507                 SURFXML_BUFFER_SET(route_impact_on_src_with_other_recv, "0.0");
508                 SURFXML_BUFFER_SET(route_impact_on_dst_with_other_send, "0.0");
509                 SURFXML_START_TAG(route);
510                 int j;
511
512                 for(j=0; j < route_list[i]->links_nb;j++)
513                 {
514                         SURFXML_BUFFER_SET(link_c_ctn_id,route_list[i]->links_id[j]);
515                         SURFXML_START_TAG(link_c_ctn);
516                         SURFXML_END_TAG(link_c_ctn);
517                 }
518
519                 SURFXML_END_TAG(route);
520         }
521         /* </platform> */
522
523         SURFXML_END_TAG(platform);
524         free(surfxml_bufferstack);
525         return 0; // must return 0 ?!!
526
527 }
528
529 /*
530  * surf parse bypass application
531  */
532 static int surf_parse_bypass_application()
533 {
534           int i;
535           static int AX_ptr;
536           static int surfxml_bufferstack_size = 2048;
537           /* FIXME ( should be manual )allocating memory to the buffer, I think 2MB should be enough */
538           surfxml_bufferstack = xbt_new0(char, surfxml_bufferstack_size);
539           /* <platform> */
540
541           SURFXML_BUFFER_SET(platform_version, "2");
542
543           SURFXML_START_TAG(platform);
544
545           for(i=0 ; i< host_index ;i++)
546           {
547                   if(host_list[i]->function)
548                   {
549                           SURFXML_BUFFER_SET(process_host, host_list[i]->id);
550                           SURFXML_BUFFER_SET(process_function, host_list[i]->function);
551                           SURFXML_BUFFER_SET(process_start_time, "-1.0");
552                           SURFXML_BUFFER_SET(process_kill_time, "-1.0");
553                           SURFXML_START_TAG(process);
554
555                           //args
556                           int j;
557                           for(j=0 ;j<host_list[i]->args_nb;j++)
558                           {
559                                   SURFXML_BUFFER_SET(argument_value, host_list[i]->args_list[j]);
560                                   SURFXML_START_TAG(argument);
561                                   SURFXML_END_TAG(argument);
562                           }
563                           SURFXML_END_TAG(process);
564                   }
565
566           }
567           /* </platform> */
568           SURFXML_END_TAG(platform);
569           free(surfxml_bufferstack);
570           return 0;
571 }
572
573 // Free Allocated Memory
574 static void clean_attr()
575 {
576         // free hosts
577     int i;
578     for(i = 0;i<host_index;i++)
579         free(host_list[i]->args_list);
580
581         free(host_list);
582     free(link_list);
583
584     for(i=0;i<route_index;i++)
585                 free(route_list[i]->links_id);
586
587     free(route_list);
588 }
589 //***********Register Methods *******************************************//
590 /*
591  * Host Methods
592  */
593 static const luaL_reg Host_methods[] = {
594     {"getByName",   Host_get_by_name},
595     {"name",            Host_get_name},
596     {"number",          Host_number},
597     {"at",                      Host_at},
598     // Bypass XML Methods
599     {"new",                     Host_new},
600     {"setNumber",       Host_set_number},
601     {"setFunction",     Host_set_function},
602     {0,0}
603 };
604
605 static int Host_gc(lua_State *L)
606 {
607   m_host_t ht = checkHost(L,-1);
608   if (ht) ht = NULL;
609   return 0;
610 }
611
612 static int Host_tostring(lua_State *L)
613 {
614   lua_pushfstring(L,"Host :%p",lua_touserdata(L,1));
615   return 1;
616 }
617
618 static const luaL_reg Host_meta[] = {
619     {"__gc",  Host_gc},
620     {"__tostring",  Host_tostring},
621     {0,0}
622 };
623
624 /*
625  * Link Methods
626  */
627 static const luaL_reg Link_methods[] = {
628     {"new",Link_new},
629     {"setNumber", Link_set_number },
630     {0,0}
631 };
632 /*
633  * Route Methods
634  */
635 static const luaL_reg Route_methods[] ={
636    {"new",Route_new},
637    {"setNumber",Route_set_number}
638 };
639
640 /*
641  * Environment related
642  */
643
644 extern lua_State *simgrid_lua_state;
645
646 static int run_lua_code(int argc,char **argv) {
647   DEBUG1("Run lua code %s",argv[0]);
648   lua_State *L = lua_newthread(simgrid_lua_state);
649   int ref = luaL_ref(simgrid_lua_state, LUA_REGISTRYINDEX); // protect the thread from being garbage collected
650   int res = 1;
651
652   /* Start the co-routine */
653   lua_getglobal(L,argv[0]);
654   xbt_assert1(lua_isfunction(L,-1),
655       "The lua function %s does not seem to exist",argv[0]);
656
657   // push arguments onto the stack
658   int i;
659   for(i=1;i<argc;i++)
660     lua_pushstring(L,argv[i]);
661
662   // Call the function (in resume)
663   xbt_assert2(lua_pcall(L, argc-1, 1, 0) == 0,
664     "error running function `%s': %s",argv[0], lua_tostring(L, -1));
665
666   /* retrieve result */
667   if (lua_isnumber(L, -1)) {
668     res = lua_tonumber(L, -1);
669     lua_pop(L, 1);  /* pop returned value */
670   }
671
672   // cleanups
673   luaL_unref(simgrid_lua_state,LUA_REGISTRYINDEX,ref );
674   DEBUG1("Execution of lua code %s is over", (argv ? argv[0] : "(null)"));
675   return res;
676 }
677 static int launch_application(lua_State *L) {
678   const char * file = luaL_checkstring(L,1);
679   MSG_function_register_default(run_lua_code);
680   MSG_launch_application(file);
681   return 0;
682 }
683 #include "simix/simix.h" //FIXME: KILLME when debugging on simix internals become useless
684 static int create_environment(lua_State *L) {
685   const char *file = luaL_checkstring(L,1);
686   DEBUG1("Loading environment file %s",file);
687   MSG_create_environment(file);
688   smx_host_t *hosts = SIMIX_host_get_table();
689   int i;
690   for (i=0;i<SIMIX_host_get_number();i++) {
691     DEBUG1("We have an host %s", SIMIX_host_get_name(hosts[i]));
692   }
693
694   return 0;
695 }
696
697 static int debug(lua_State *L) {
698   const char *str = luaL_checkstring(L,1);
699   DEBUG1("%s",str);
700   return 0;
701 }
702 static int info(lua_State *L) {
703   const char *str = luaL_checkstring(L,1);
704   INFO1("%s",str);
705   return 0;
706 }
707 static int run(lua_State *L) {
708   MSG_main();
709   return 0;
710 }
711 static int clean(lua_State *L) {
712   clean_attr(); // in case of using "bypass xml" methods
713   MSG_clean();
714   return 0;
715 }
716
717 /*
718  * Bypass XML Pareser
719  */
720 static int register_platform(lua_State *L)
721 {
722         /* Tell Simgrid we dont wanna use its parser*/
723         surf_parse = surf_parse_bypass_platform;
724         MSG_create_environment(NULL);
725         return 0;
726 }
727
728 static int register_application(lua_State *L)
729 {
730          MSG_function_register_default(run_lua_code);
731          surf_parse = surf_parse_bypass_application;
732          MSG_launch_application(NULL);
733          return 0;
734 }
735
736 static const luaL_Reg simgrid_funcs[] = {
737     { "create_environment", create_environment},
738     { "launch_application", launch_application},
739     { "debug", debug},
740     { "info", info},
741     { "run", run},
742     { "clean", clean},
743     /* short names */
744     { "platform", create_environment},
745     { "application", launch_application},
746     /* methods to bypass XML parser*/
747     { "register_platform",register_platform},
748     { "register_application",register_application},
749     { NULL, NULL }
750 };
751
752 /* ********************************************************************************* */
753 /*                       module management functions                                 */
754 /* ********************************************************************************* */
755
756 extern const char*xbt_ctx_factory_to_use; /*Hack: let msg load directly the right factory */
757
758 #define LUA_MAX_ARGS_COUNT 10 /* maximum amount of arguments we can get from lua on command line */
759
760 int luaopen_simgrid(lua_State* L); // Fuck gcc: we don't need that prototype
761 int luaopen_simgrid(lua_State* L) {
762   //xbt_ctx_factory_to_use = "lua";
763
764   char **argv=malloc(sizeof(char*)*LUA_MAX_ARGS_COUNT);
765   int argc=1;
766   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? */
767   /* Get the command line arguments from the lua interpreter */
768   lua_getglobal(L,"arg");
769   xbt_assert1(lua_istable(L,-1),"arg parameter is not a table but a %s",lua_typename(L,-1));
770   int done=0;
771   while (!done) {
772     argc++;
773     lua_pushinteger(L,argc-2);
774     lua_gettable(L,-2);
775     if (lua_isnil(L,-1)) {
776       done = 1;
777     } else {
778       xbt_assert1(lua_isstring(L,-1),"argv[%d] got from lua is no string",argc-1);
779       xbt_assert2(argc<LUA_MAX_ARGS_COUNT,
780            "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",
781            __FILE__,LUA_MAX_ARGS_COUNT-1);
782       argv[argc-1] = (char*)luaL_checkstring(L,-1);
783       lua_pop(L,1);
784       DEBUG1("Got command line argument %s from lua",argv[argc-1]);
785     }
786   }
787   argv[argc--]=NULL;
788
789   /* Initialize the MSG core */
790   MSG_global_init(&argc,argv);
791   DEBUG1("Still %d arguments on command line",argc); // FIXME: update the lua's arg table to reflect the changes from SimGrid
792
793   /* register the core C functions to lua */
794   luaL_register(L, "simgrid", simgrid_funcs);
795   /* register the task methods to lua */
796   luaL_openlib(L,TASK_MODULE_NAME,Task_methods,0); //create methods table,add it to the globals
797   luaL_newmetatable(L,TASK_MODULE_NAME); //create metatable for Task,add it to the Lua registry
798   luaL_openlib(L,0,Task_meta,0);// fill metatable
799   lua_pushliteral(L,"__index");
800   lua_pushvalue(L,-3);  //dup methods table
801   lua_rawset(L,-3); //matatable.__index = methods
802   lua_pushliteral(L,"__metatable");
803   lua_pushvalue(L,-3);  //dup methods table
804   lua_rawset(L,-3); //hide metatable:metatable.__metatable = methods
805   lua_pop(L,1);   //drop metatable
806
807   /* register the hosts methods to lua*/
808   luaL_openlib(L,HOST_MODULE_NAME,Host_methods,0);
809   luaL_newmetatable(L,HOST_MODULE_NAME);
810   luaL_openlib(L,0,Host_meta,0);
811   lua_pushliteral(L,"__index");
812   lua_pushvalue(L,-3);
813   lua_rawset(L,-3);
814   lua_pushliteral(L,"__metatable");
815   lua_pushvalue(L,-3);
816   lua_rawset(L,-3);
817   lua_pop(L,1);
818
819   /* register the links methods to lua*/
820   luaL_openlib(L,LINK_MODULE_NAME,Link_methods,0);
821   luaL_newmetatable(L,LINK_MODULE_NAME);
822   lua_pop(L,1);
823
824   /*register the routes methods to lua*/
825   luaL_openlib(L,ROUTE_MODULE_NAME,Route_methods,0);
826   luaL_newmetatable(L,LINK_MODULE_NAME);
827   lua_pop(L,1);
828
829   /* Keep the context mechanism informed of our lua world today */
830   simgrid_lua_state = L;
831   return 1;
832 }