Logo AND Algorithmique Numérique Distribuée

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