Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
move e_surf_link_sharing_policy_t structure to surf.h and fix the way to create link...
[simgrid.git] / src / bindings / lua / simgrid_lua.c
1 /* SimGrid Lua bindings                                                     */
2
3 /* Copyright (c) 2010. The SimGrid Team.
4  * All rights reserved.                                                     */
5
6 /* This program is free software; you can redistribute it and/or modify it
7  * under the terms of the license (GNU LGPL) which comes with this package. */
8
9 #include <stdio.h>
10 #include <lauxlib.h>
11 #include <lualib.h>
12 #include "msg/msg.h"
13 #include "simdag/simdag.h"
14 #include <gras.h>
15 #include "xbt.h"
16 #include "lua_stub_generator.h"
17
18 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(lua,bindings,"Lua Bindings");
19
20 #define TASK_MODULE_NAME "simgrid.Task"
21 #define HOST_MODULE_NAME "simgrid.Host"
22 // Surf ( bypass XML )
23 #define LINK_MODULE_NAME "simgrid.Link"
24 #define ROUTE_MODULE_NAME "simgrid.Route"
25
26 /* ********************************************************************************* */
27 /*                            helper functions                                       */
28 /* ********************************************************************************* */
29 static void stackDump (const char *msg, lua_State *L) {
30   char buff[2048];
31   char *p=buff;
32   int i;
33   int top = lua_gettop(L);
34
35   fflush(stdout);
36   p+=sprintf(p,"STACK(top=%d): ",top);
37
38   for (i = 1; i <= top; i++) {  /* repeat for each level */
39     int t = lua_type(L, i);
40     switch (t) {
41
42     case LUA_TSTRING:  /* strings */
43       p+=sprintf(p,"`%s'", lua_tostring(L, i));
44       break;
45
46     case LUA_TBOOLEAN:  /* booleans */
47       p+=sprintf(p,lua_toboolean(L, i) ? "true" : "false");
48       break;
49
50     case LUA_TNUMBER:  /* numbers */
51       p+=sprintf(p,"%g", lua_tonumber(L, i));
52       break;
53
54     case LUA_TTABLE:
55       p+=sprintf(p, "Table");
56       break;
57
58     default:  /* other values */
59       p+=sprintf(p, "???");
60 /*      if ((ptr = luaL_checkudata(L,i,TASK_MODULE_NAME))) {
61         p+=sprintf(p,"task");
62       } else {
63         p+=printf(p,"%s", lua_typename(L, t));
64       }*/
65       break;
66
67     }
68     p+=sprintf(p,"  ");  /* put a separator */
69   }
70   INFO2("%s%s",msg,buff);
71 }
72
73 /** @brief ensures that a userdata on the stack is a task and returns the pointer inside the userdata */
74 static m_task_t checkTask (lua_State *L,int index) {
75   m_task_t *pi,tk;
76   luaL_checktype(L,index,LUA_TTABLE);
77   lua_getfield(L,index,"__simgrid_task");
78   pi = (m_task_t*)luaL_checkudata(L,-1,TASK_MODULE_NAME);
79   if(pi == NULL)
80          luaL_typerror(L,index,TASK_MODULE_NAME);
81   tk = *pi;
82   if(!tk)
83          luaL_error(L,"null Task");
84   lua_pop(L,1);
85   return  tk;
86 }
87 /* ********************************************************************************* */
88 /*                           wrapper functions                                       */
89 /* ********************************************************************************* */
90
91 /**
92  * A task is either something to compute somewhere, or something to exchange between two hosts (or both).
93  * It is defined by a computing amount and a message size.
94  *
95  */
96
97 /* *              * *
98  * * Constructors * *
99  * *              * */
100 /**
101  * Construct an new task with the specified processing amount and amount
102  * of data needed.
103  *
104  * @param name  Task's name
105  *
106  * @param computeDuration       A value of the processing amount (in flop) needed to process the task.
107  *                              If 0, then it cannot be executed with the execute() method.
108  *                              This value has to be >= 0.
109  *
110  * @param messageSize           A value of amount of data (in bytes) needed to transfert this task.
111  *                              If 0, then it cannot be transfered with the get() and put() methods.
112  *                              This value has to be >= 0.
113  */
114 static int Task_new(lua_State* L) {
115           const char *name=luaL_checkstring(L,1);
116           int comp_size = luaL_checkint(L,2);
117           int msg_size = luaL_checkint(L,3);
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         // Mandatory attributes
313         const char* id;
314         double power_peak;
315         // Optional attributes
316         double power_scale;
317         const char *power_trace;
318         int state_initial;
319         const char *state_trace;
320         //deployment attribute
321         const char* function;
322         xbt_dynar_t args_list;
323 }host_attr,*p_host_attr;
324
325 typedef struct t_link_attr
326 {
327         //mandatory attributes
328         const char* id;
329         double bandwidth;
330         double latency;
331         // Optional attributes
332         const char* bandwidth_trace;
333         const char* latency_trace;
334         const char*     state_trace;
335         int state_initial;
336         int policy;
337 }link_attr,*p_link_attr;
338
339 typedef struct t_route_attr
340 {
341         const char *src_id;
342         const char *dest_id;
343         xbt_dynar_t links_id;
344
345 }route_attr,*p_route_attr;
346
347 //using xbt_dynar_t :
348 static xbt_dynar_t host_list_d ;
349 static xbt_dynar_t link_list_d ;
350 static xbt_dynar_t route_list_d ;
351
352
353 /**
354  * create host resource via CPU model [for MSG]
355  */
356
357 static void create_host(const char* id,double power_peak,double power_sc,
358                                                 const char* power_tr,int state_init,
359                                                 const char* state_tr)
360 {
361
362         double power_scale = 1.0;
363         tmgr_trace_t power_trace = NULL;
364         e_surf_resource_state_t state_initial;
365         tmgr_trace_t state_trace;
366         if(power_sc) // !=0
367                 power_scale = power_sc;
368         if (state_init == -1)
369                 state_initial = SURF_RESOURCE_OFF;
370         else
371                 state_initial = SURF_RESOURCE_ON;
372         if(power_tr)
373                 power_trace = tmgr_trace_new(power_tr);
374         else
375                 power_trace = tmgr_trace_new("");
376         if(state_tr)
377                 state_trace = tmgr_trace_new(state_tr);
378         else
379                 state_trace = tmgr_trace_new("");
380         current_property_set = xbt_dict_new();
381         surf_host_create_resource(xbt_strdup(id), power_peak, power_scale,
382                                                power_trace, state_initial, state_trace, current_property_set);
383
384 }
385
386 /**
387  * create link resource via network model
388  */
389 static void create_link(const char *name,
390         double bw_initial,const char *trace,double lat_initial,
391         const char* latency_trace,int state_init, const char* state_trace,int policy)
392 {
393         tmgr_trace_t bw_trace;
394         tmgr_trace_t lat_trace;
395         e_surf_resource_state_t state_initial_link = SURF_RESOURCE_ON;
396         e_surf_link_sharing_policy_t policy_initial_link = SURF_LINK_SHARED;
397         tmgr_trace_t st_trace;
398         if(trace)
399                 bw_trace = tmgr_trace_new(trace);
400         else
401                 bw_trace = tmgr_trace_new("");
402
403         if(latency_trace)
404                 lat_trace = tmgr_trace_new(latency_trace);
405         else
406                 lat_trace = tmgr_trace_new("");
407
408         if(state_trace)
409                 st_trace = tmgr_trace_new(state_trace);
410         else
411                 st_trace = tmgr_trace_new("");
412
413         if(state_init == -1)
414                 state_initial_link = SURF_RESOURCE_OFF;
415         if(policy == -1)
416                 policy_initial_link = SURF_LINK_FATPIPE;
417
418         surf_link_create_resource(xbt_strdup(name), bw_initial, bw_trace,
419                    lat_initial, lat_trace, state_initial_link, st_trace,
420                    policy_initial_link, xbt_dict_new());
421 }
422
423
424 /*
425  *create host resource via workstation_ptask_L07 model [for SimDag]
426  */
427 static void create_host_wsL07(const char* id,double power_peak,double power_sc,
428                                                 const char* power_tr,int state_init,
429                                                 const char* state_tr)
430 {
431         double power_scale = 1.0;
432         tmgr_trace_t power_trace = NULL;
433         e_surf_resource_state_t state_initial;
434         tmgr_trace_t state_trace;
435         if(power_sc) // !=0
436                 power_scale = power_sc;
437         if (state_init == -1)
438                 state_initial = SURF_RESOURCE_OFF;
439         else
440                 state_initial = SURF_RESOURCE_ON;
441         if(power_tr)
442                 power_trace = tmgr_trace_new(power_tr);
443         else
444                 power_trace = tmgr_trace_new("");
445         if(state_tr)
446                 state_trace = tmgr_trace_new(state_tr);
447         else
448                 state_trace = tmgr_trace_new("");
449         current_property_set = xbt_dict_new();
450         surf_wsL07_host_create_resource(xbt_strdup(id), power_peak, power_scale,
451                                                power_trace, state_initial, state_trace, current_property_set);
452
453 }
454 /*
455  * add new host to platform hosts list
456  */
457 static int Host_new(lua_State *L)
458 {
459
460         if(xbt_dynar_is_empty(host_list_d))
461                 host_list_d = xbt_dynar_new(sizeof(p_host_attr), &xbt_free_ref);
462
463         p_host_attr host;
464         const char * id;
465         const char *power_trace;
466         const char *state_trace;
467         double power,power_scale;
468         int state_initial;
469         //get values from the table passed as argument
470     if (lua_istable(L,-1)) {
471
472             // get Id Value
473             lua_pushstring(L,"id");
474             lua_gettable(L, -2 );
475             id = lua_tostring(L,-1);
476             lua_pop(L,1);
477
478             // get power value
479             lua_pushstring(L,"power");
480             lua_gettable(L, -2 );
481             power = lua_tonumber(L,-1);
482             lua_pop(L,1);
483
484             //get power_scale
485             lua_pushstring(L,"power_scale");
486             lua_gettable(L, -2 );
487             power_scale = lua_tonumber(L,-1);
488             lua_pop(L,1);
489
490             //get power_trace
491             lua_pushstring(L,"power_trace");
492             lua_gettable(L, -2 );
493             power_trace = lua_tostring(L,-1);
494             lua_pop(L,1);
495
496             //get state initial
497             lua_pushstring(L,"state_initial");
498             lua_gettable(L, -2 );
499             state_initial = lua_tonumber(L,-1);
500             lua_pop(L,1);
501
502             //get trace state
503             lua_pushstring(L,"state_trace");
504             lua_gettable(L, -2 );
505             state_trace = lua_tostring(L,-1);
506             lua_pop(L,1);
507
508     } else {
509             ERROR0("Bad Arguments to create host, Should be a table with named arguments");
510             return -1;
511     }
512
513             host = malloc(sizeof(host_attr));
514                 host->id = id;
515                 host->power_peak = power;
516                 host->power_scale = power_scale;
517                 host->power_trace = power_trace;
518                 host->state_initial = state_initial;
519                 host->state_trace = state_trace;
520                 host->function = NULL;
521                 xbt_dynar_push(host_list_d, &host);
522
523     return 0;
524 }
525
526 /**
527  * add link to platform links list
528  */
529 static int Link_new(lua_State *L) // (id,bandwidth,latency)
530 {
531         if(xbt_dynar_is_empty(link_list_d))
532                 link_list_d = xbt_dynar_new(sizeof(p_link_attr), &xbt_free_ref);
533
534         const char* id;
535         double bandwidth,latency;
536         const char* bandwidth_trace;
537         const char* latency_trace;
538         const char* state_trace;
539         int state_initial,policy;
540
541         //get values from the table passed as argument
542         if (lua_istable(L,-1)) {
543                     // get Id Value
544                     lua_pushstring(L,"id");
545                     lua_gettable(L, -2 );
546                     id = lua_tostring(L,-1);
547                     lua_pop(L,1);
548
549                     // get bandwidth value
550                     lua_pushstring(L,"bandwidth");
551                     lua_gettable(L, -2 );
552                     bandwidth = lua_tonumber(L,-1);
553                     lua_pop(L,1);
554
555                     //get latency value
556                     lua_pushstring(L,"latency");
557                     lua_gettable(L, -2 );
558                     latency = lua_tonumber(L,-1);
559                     lua_pop(L,1);
560
561                     /*Optional Arguments  */
562
563                     //get bandwidth_trace value
564                     lua_pushstring(L,"bandwidth_trace");
565                     lua_gettable(L, -2 );
566                     bandwidth_trace = lua_tostring(L,-1);
567                     lua_pop(L,1);
568
569                     //get latency_trace value
570                     lua_pushstring(L,"latency_trace");
571                     lua_gettable(L, -2 );
572                     latency_trace = lua_tostring(L,-1);
573                     lua_pop(L,1);
574
575                     //get state_trace value
576                     lua_pushstring(L,"state_trace");
577                     lua_gettable(L, -2 );
578                     state_trace = lua_tostring(L,-1);
579                     lua_pop(L,1);
580
581                                 //get state_initial value
582                     lua_pushstring(L,"state_initial");
583                     lua_gettable(L, -2 );
584                     state_initial = lua_tonumber(L,-1);
585                     lua_pop(L,1);
586
587
588                                 //get policy value
589                     lua_pushstring(L,"policy");
590                     lua_gettable(L, -2 );
591                     policy = lua_tonumber(L,-1);
592                     lua_pop(L,1);
593
594             } else {
595                     ERROR0("Bad Arguments to create link, Should be a table with named arguments");
596                     return -1;
597             }
598
599         p_link_attr link = malloc(sizeof(link_attr));
600         link->id = id;
601         link->bandwidth = bandwidth;
602         link->latency = latency;
603         link->bandwidth_trace = bandwidth_trace;
604         link->latency_trace = latency_trace;
605         link->state_trace = state_trace;
606         link->state_initial= state_initial;
607         link->policy = policy;
608         xbt_dynar_push(link_list_d,&link);
609         return 0;
610 }
611
612 /**
613  * add route to platform routes list
614  */
615 static int Route_new(lua_State *L) // (src_id,dest_id,links_number,link_table)
616 {
617         if(xbt_dynar_is_empty(route_list_d))
618                 route_list_d = xbt_dynar_new(sizeof(p_route_attr), &xbt_free_ref);
619         const char * link_id;
620         p_route_attr route = malloc(sizeof(route_attr));
621         route->src_id = luaL_checkstring(L,1);
622         route->dest_id = luaL_checkstring(L,2);
623         route->links_id = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
624         lua_pushnil(L);
625         while (lua_next(L,3) != 0) {
626                 link_id = lua_tostring(L, -1);
627                 xbt_dynar_push(route->links_id, &link_id);
628             DEBUG2("index = %f , Link_id = %s \n",lua_tonumber(L, -2),lua_tostring(L, -1));
629             lua_pop(L, 1);
630         }
631         lua_pop(L, 1);
632
633         //add route to platform's route list
634         xbt_dynar_push(route_list_d,&route);
635         return 0;
636 }
637
638 /**
639  * set function to process
640  */
641 static int Host_set_function(lua_State *L) //(host,function,nb_args,list_args)
642 {
643         // look for the index of host in host_list
644         const char *host_id = luaL_checkstring(L,1);
645         const char* argument;
646         unsigned int i;
647         p_host_attr p_host;
648
649         xbt_dynar_foreach(host_list_d,i,p_host)
650         {
651                 if(p_host->id == host_id)
652                 {
653                         p_host->function = luaL_checkstring(L,2);
654                         if(lua_istable(L,3))
655                         {
656                                 p_host->args_list = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
657                                 // fill the args list
658                                 lua_pushnil(L);
659                                 int j = 0;
660                                 while (lua_next(L,3) != 0) {
661                                                 argument = lua_tostring(L, -1);
662                                                 xbt_dynar_push(p_host->args_list, &argument);
663                                                 DEBUG2("index = %f , Arg_id = %s \n",lua_tonumber(L, -2),lua_tostring(L, -1));
664                                                 j++;
665                                                 lua_pop(L, 1);
666                                         }
667                         }
668                         lua_pop(L, 1);
669                         return 0;
670                 }
671         }
672         ERROR1("Host : %s Not Fount !!",host_id);
673         return 1;
674 }
675
676 /*
677  * surf parse bypass platform
678  * through CPU/network Models
679  */
680
681 static int surf_parse_bypass_platform()
682 {
683         unsigned int i;
684         p_host_attr p_host;
685         p_link_attr p_link;
686         p_route_attr p_route;
687
688         // Add Hosts
689         xbt_dynar_foreach(host_list_d,i,p_host)
690         {
691                 create_host(p_host->id,p_host->power_peak,p_host->power_scale,p_host->power_trace,
692                                         p_host->state_initial,p_host->state_trace);
693                 //add to routing model host list
694                 surf_route_add_host((char*)p_host->id);
695         }
696
697         //add Links
698         xbt_dynar_foreach(link_list_d,i,p_link)
699         {
700                 /*(const char *name,
701         double bw_initial,const char *trace,double lat_initial,
702         const char* latency_trace,int state_init, const char* state_trace,int policy)*/
703                 create_link(p_link->id,p_link->bandwidth,p_link->bandwidth_trace,p_link->latency,
704                                 p_link->latency_trace,p_link->state_initial,p_link->state_trace,p_link->policy);
705         }
706         // add route
707         xbt_dynar_foreach(route_list_d,i,p_route)
708         {
709                 surf_route_set_resource((char*)p_route->src_id,(char*)p_route->dest_id,p_route->links_id,0);
710         }
711         /* </platform> */
712
713         surf_add_host_traces();
714         surf_set_routes();
715         surf_add_link_traces();
716
717         return 0; // must return 0 ?!!
718
719 }
720
721 /**
722  *
723  * surf parse bypass platform
724  * through workstation_ptask_L07 Model
725  */
726
727
728 static int surf_wsL07_parse_bypass_platform()
729 {
730         unsigned int i;
731         p_host_attr p_host;
732         p_link_attr p_link;
733         p_route_attr p_route;
734
735         // Add Hosts
736         xbt_dynar_foreach(host_list_d,i,p_host)
737         {
738                 create_host_wsL07(p_host->id,p_host->power_peak,p_host->power_scale,p_host->power_trace,
739                                         p_host->state_initial,p_host->state_trace);
740                 //add to routing model host list
741                 surf_route_add_host((char*)p_host->id);
742         }
743
744         //add Links
745         xbt_dynar_foreach(link_list_d,i,p_link)
746         {
747                 surf_wsL07_link_create_resource((char*)p_link->id,p_link->bandwidth,p_link->latency);
748         }
749         // add route
750         xbt_dynar_foreach(route_list_d,i,p_route)
751         {
752                 surf_route_set_resource((char*)p_route->src_id,(char*)p_route->dest_id,p_route->links_id,0);
753         }
754         /* </platform> */
755
756         surf_wsL07_add_traces();
757         surf_set_routes();
758
759         return 0;
760
761 }
762 /*
763  * surf parse bypass application for MSG Module
764  */
765 static int surf_parse_bypass_application()
766 {
767           unsigned int i;
768           p_host_attr p_host;
769           xbt_dynar_foreach(host_list_d,i,p_host)
770                   {
771                   if(p_host->function)
772                           MSG_set_function(p_host->id,p_host->function,p_host->args_list);
773                   }
774           return 0;
775 }
776
777
778 /**
779  *  Generate Gras Templates File from lua
780  */
781
782 xbt_dict_t process_function_set;
783 xbt_dynar_t process_list;
784 xbt_dict_t machine_set;
785 static s_process_t process;
786
787 void s_process_free(void *process)
788 {
789   s_process_t *p = (s_process_t *) process;
790   int i;
791   for (i = 0; i < p->argc; i++)
792     free(p->argv[i]);
793   free(p->argv);
794   free(p->host);
795 }
796
797 static int gras_add_process_function(lua_State *L)
798 {
799         const char * arg;
800         const char* process_host = luaL_checkstring(L,1);
801         const char *process_function = luaL_checkstring(L,2);
802
803         if(xbt_dict_is_empty(machine_set) || xbt_dict_is_empty(process_function_set)
804                         || xbt_dynar_is_empty(process_list))
805                 {
806                   process_function_set = xbt_dict_new();
807                   process_list = xbt_dynar_new(sizeof(s_process_t), s_process_free);
808                   machine_set = xbt_dict_new();
809                 }
810
811         xbt_dict_set(machine_set,process_host, NULL, NULL);
812         xbt_dict_set(process_function_set,process_function, NULL, NULL);
813
814         process.argc = 1;
815         process.argv = xbt_new(char *, 1);
816         process.argv[0] = xbt_strdup(process_function);
817         process.host = strdup(process_host);
818
819         lua_pushnil(L);
820         while (lua_next(L,3) != 0) {
821                 arg = lua_tostring(L, -1);
822                 process.argc++;
823                 process.argv = xbt_realloc(process.argv, (process.argc) * sizeof(char *));
824                 process.argv[(process.argc) - 1] = xbt_strdup(arg);
825
826                 DEBUG2("index = %f , arg = %s \n",lua_tonumber(L, -2),lua_tostring(L, -1));
827                 lua_pop(L, 1);
828                 }
829         lua_pop(L, 1);
830         //add to the process list
831         xbt_dynar_push(process_list, &process);
832
833         return 0;
834
835 }
836
837
838 static int gras_generate(lua_State *L)
839 {
840   const char *project_name = luaL_checkstring(L,1);
841   generate_sim(project_name);
842   generate_rl(project_name);
843   generate_makefile_local(project_name);
844
845   return 0;
846 }
847
848 //***********Register Methods *******************************************//
849 /*
850  * Host Methods
851  */
852 static const luaL_reg Host_methods[] = {
853     {"getByName",   Host_get_by_name},
854     {"name",            Host_get_name},
855     {"number",          Host_number},
856     {"at",                      Host_at},
857     // Bypass XML Methods
858     {"new",                     Host_new},
859     {"setFunction",     Host_set_function},
860     {0,0}
861 };
862
863 static int Host_gc(lua_State *L)
864 {
865   m_host_t ht = checkHost(L,-1);
866   if (ht) ht = NULL;
867   return 0;
868 }
869
870 static int Host_tostring(lua_State *L)
871 {
872   lua_pushfstring(L,"Host :%p",lua_touserdata(L,1));
873   return 1;
874 }
875
876 static const luaL_reg Host_meta[] = {
877     {"__gc",  Host_gc},
878     {"__tostring",  Host_tostring},
879     {0,0}
880 };
881
882 /*
883  * Link Methods
884  */
885 static const luaL_reg Link_methods[] = {
886     {"new",Link_new},
887     {0,0}
888 };
889 /*
890  * Route Methods
891  */
892 static const luaL_reg Route_methods[] ={
893    {"new",Route_new},
894    {0,0}
895 };
896
897 /*
898  * Environment related
899  */
900
901 extern lua_State *simgrid_lua_state;
902
903 static int run_lua_code(int argc,char **argv) {
904   DEBUG1("Run lua code %s",argv[0]);
905   lua_State *L = lua_newthread(simgrid_lua_state);
906   int ref = luaL_ref(simgrid_lua_state, LUA_REGISTRYINDEX); // protect the thread from being garbage collected
907   int res = 1;
908
909   /* Start the co-routine */
910   lua_getglobal(L,argv[0]);
911   xbt_assert1(lua_isfunction(L,-1),
912       "The lua function %s does not seem to exist",argv[0]);
913
914   // push arguments onto the stack
915   int i;
916   for(i=1;i<argc;i++)
917     lua_pushstring(L,argv[i]);
918
919   // Call the function (in resume)
920   xbt_assert2(lua_pcall(L, argc-1, 1, 0) == 0,
921     "error running function `%s': %s",argv[0], lua_tostring(L, -1));
922
923   /* retrieve result */
924   if (lua_isnumber(L, -1)) {
925     res = lua_tonumber(L, -1);
926     lua_pop(L, 1);  /* pop returned value */
927   }
928   // cleanups
929   luaL_unref(simgrid_lua_state,LUA_REGISTRYINDEX,ref );
930   DEBUG1("Execution of lua code %s is over", (argv ? argv[0] : "(null)"));
931   return res;
932 }
933 static int launch_application(lua_State *L) {
934   const char * file = luaL_checkstring(L,1);
935   MSG_function_register_default(run_lua_code);
936   MSG_launch_application(file);
937   return 0;
938 }
939 #include "simix/simix.h" //FIXME: KILLME when debugging on simix internals become useless
940 static int create_environment(lua_State *L) {
941   const char *file = luaL_checkstring(L,1);
942   DEBUG1("Loading environment file %s",file);
943   MSG_create_environment(file);
944   smx_host_t *hosts = SIMIX_host_get_table();
945   int i;
946   for (i=0;i<SIMIX_host_get_number();i++) {
947     DEBUG1("We have an host %s", SIMIX_host_get_name(hosts[i]));
948   }
949
950   return 0;
951 }
952
953 static int debug(lua_State *L) {
954   const char *str = luaL_checkstring(L,1);
955   DEBUG1("%s",str);
956   return 0;
957 }
958 static int info(lua_State *L) {
959   const char *str = luaL_checkstring(L,1);
960   INFO1("%s",str);
961   return 0;
962 }
963 static int run(lua_State *L) {
964   MSG_main();
965   return 0;
966 }
967 static int clean(lua_State *L) {
968   MSG_clean();
969   return 0;
970 }
971
972 /*
973  * Bypass XML Parser
974  */
975
976 /*
977  * Register platform for MSG
978  */
979 static int msg_register_platform(lua_State *L)
980 {
981         /* Tell Simgrid we dont wanna use its parser*/
982         surf_parse = surf_parse_bypass_platform;
983         MSG_create_environment(NULL);
984         return 0;
985 }
986
987 /*
988  * Register platform for Simdag
989  */
990
991 static int sd_register_platform(lua_State *L)
992 {
993         surf_parse = surf_wsL07_parse_bypass_platform;
994         SD_create_environment(NULL);
995         return 0;
996 }
997 /*
998  * Register platform for gras
999  */
1000 static int gras_register_platform(lua_State *L)
1001 {
1002         /* Tell Simgrid we dont wanna use surf parser*/
1003         surf_parse = surf_parse_bypass_platform;
1004         gras_create_environment(NULL);
1005         return 0;
1006 }
1007
1008 /**
1009  * Register applicaiton for MSG
1010  */
1011 static int msg_register_application(lua_State *L)
1012 {
1013          MSG_function_register_default(run_lua_code);
1014          surf_parse = surf_parse_bypass_application;
1015          MSG_launch_application(NULL);
1016          return 0;
1017 }
1018
1019 /*
1020  * Register application for gras
1021  */
1022 static int gras_register_application(lua_State *L)
1023 {
1024         gras_function_register_default(run_lua_code);
1025         surf_parse = surf_parse_bypass_application;
1026         gras_launch_application(NULL);
1027         return 0;
1028 }
1029 static const luaL_Reg simgrid_funcs[] = {
1030     { "create_environment", create_environment},
1031     { "launch_application", launch_application},
1032     { "debug", debug},
1033     { "info", info},
1034     { "run", run},
1035     { "clean", clean},
1036     /* short names */
1037     { "platform", create_environment},
1038     { "application", launch_application},
1039     /* methods to bypass XML parser*/
1040     { "msg_register_platform",msg_register_platform},
1041     { "sd_register_platform",sd_register_platform},
1042     { "msg_register_application",msg_register_application},
1043     { "gras_register_platform",gras_register_platform},
1044     { "gras_register_application",gras_register_application},
1045     /* gras sub generator method*/
1046     {"gras_set_process_function",gras_add_process_function},
1047     {"gras_generate",gras_generate},
1048     { NULL, NULL }
1049 };
1050
1051 /* ********************************************************************************* */
1052 /*                       module management functions                                 */
1053 /* ********************************************************************************* */
1054
1055 extern const char*xbt_ctx_factory_to_use; /*Hack: let msg load directly the right factory */
1056
1057 #define LUA_MAX_ARGS_COUNT 10 /* maximum amount of arguments we can get from lua on command line */
1058 #define TEST
1059 int luaopen_simgrid(lua_State* L); // Fuck gcc: we don't need that prototype
1060 int luaopen_simgrid(lua_State* L) {
1061
1062   //xbt_ctx_factory_to_use = "lua";
1063   char **argv=malloc(sizeof(char*)*LUA_MAX_ARGS_COUNT);
1064   int argc=1;
1065   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? */
1066   /* Get the command line arguments from the lua interpreter */
1067   lua_getglobal(L,"arg");
1068   /* if arg is a null value, it means we use lua only as a script to init platform
1069    * else it should be a table and then take arg in consideration
1070    */
1071   if(lua_istable(L,-1))
1072   {
1073           int done=0;
1074           while (!done) {
1075                 argc++;
1076                 lua_pushinteger(L,argc-2);
1077                 lua_gettable(L,-2);
1078                 if (lua_isnil(L,-1)) {
1079                   done = 1;
1080                 } else {
1081                   xbt_assert1(lua_isstring(L,-1),"argv[%d] got from lua is no string",argc-1);
1082                   xbt_assert2(argc<LUA_MAX_ARGS_COUNT,
1083                            "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",
1084                            __FILE__,LUA_MAX_ARGS_COUNT-1);
1085                   argv[argc-1] = (char*)luaL_checkstring(L,-1);
1086                   lua_pop(L,1);
1087                   DEBUG1("Got command line argument %s from lua",argv[argc-1]);
1088                 }
1089           }
1090           argv[argc--]=NULL;
1091
1092           /* Initialize the MSG core */
1093           MSG_global_init(&argc,argv);
1094           DEBUG1("Still %d arguments on command line",argc); // FIXME: update the lua's arg table to reflect the changes from SimGrid
1095  }
1096   /* register the core C functions to lua */
1097   luaL_register(L, "simgrid", simgrid_funcs);
1098   /* register the task methods to lua */
1099   luaL_openlib(L,TASK_MODULE_NAME,Task_methods,0); //create methods table,add it to the globals
1100   luaL_newmetatable(L,TASK_MODULE_NAME); //create metatable for Task,add it to the Lua registry
1101   luaL_openlib(L,0,Task_meta,0);// fill metatable
1102   lua_pushliteral(L,"__index");
1103   lua_pushvalue(L,-3);  //dup methods table
1104   lua_rawset(L,-3); //matatable.__index = methods
1105   lua_pushliteral(L,"__metatable");
1106   lua_pushvalue(L,-3);  //dup methods table
1107   lua_rawset(L,-3); //hide metatable:metatable.__metatable = methods
1108   lua_pop(L,1);   //drop metatable
1109
1110   /* register the hosts methods to lua*/
1111   luaL_openlib(L,HOST_MODULE_NAME,Host_methods,0);
1112   luaL_newmetatable(L,HOST_MODULE_NAME);
1113   luaL_openlib(L,0,Host_meta,0);
1114   lua_pushliteral(L,"__index");
1115   lua_pushvalue(L,-3);
1116   lua_rawset(L,-3);
1117   lua_pushliteral(L,"__metatable");
1118   lua_pushvalue(L,-3);
1119   lua_rawset(L,-3);
1120   lua_pop(L,1);
1121
1122   /* register the links methods to lua*/
1123   luaL_openlib(L,LINK_MODULE_NAME,Link_methods,0);
1124   luaL_newmetatable(L,LINK_MODULE_NAME);
1125   lua_pop(L,1);
1126
1127   /*register the routes methods to lua*/
1128   luaL_openlib(L,ROUTE_MODULE_NAME,Route_methods,0);
1129   luaL_newmetatable(L,LINK_MODULE_NAME);
1130   lua_pop(L,1);
1131
1132   /* Keep the context mechanism informed of our lua world today */
1133   simgrid_lua_state = L;
1134   return 1;
1135 }