Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
reimplement lua bingdings code to support the new platforms format
[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 #define AS_MODULE_NAME "simgrid.AS"
26
27 /* ********************************************************************************* */
28 /*                            helper functions                                       */
29 /* ********************************************************************************* */
30 static void stackDump (const char *msg, lua_State *L) {
31   char buff[2048];
32   char *p=buff;
33   int i;
34   int top = lua_gettop(L);
35
36   fflush(stdout);
37   p+=sprintf(p,"STACK(top=%d): ",top);
38
39   for (i = 1; i <= top; i++) {  /* repeat for each level */
40     int t = lua_type(L, i);
41     switch (t) {
42
43     case LUA_TSTRING:  /* strings */
44       p+=sprintf(p,"`%s'", lua_tostring(L, i));
45       break;
46
47     case LUA_TBOOLEAN:  /* booleans */
48       p+=sprintf(p,lua_toboolean(L, i) ? "true" : "false");
49       break;
50
51     case LUA_TNUMBER:  /* numbers */
52       p+=sprintf(p,"%g", lua_tonumber(L, i));
53       break;
54
55     case LUA_TTABLE:
56       p+=sprintf(p, "Table");
57       break;
58
59     default:  /* other values */
60       p+=sprintf(p, "???");
61 /*      if ((ptr = luaL_checkudata(L,i,TASK_MODULE_NAME))) {
62         p+=sprintf(p,"task");
63       } else {
64         p+=printf(p,"%s", lua_typename(L, t));
65       }*/
66       break;
67
68     }
69     p+=sprintf(p,"  ");  /* put a separator */
70   }
71   INFO2("%s%s",msg,buff);
72 }
73
74 /** @brief ensures that a userdata on the stack is a task and returns the pointer inside the userdata */
75 static m_task_t checkTask (lua_State *L,int index) {
76   m_task_t *pi,tk;
77   luaL_checktype(L,index,LUA_TTABLE);
78   lua_getfield(L,index,"__simgrid_task");
79   pi = (m_task_t*)luaL_checkudata(L,-1,TASK_MODULE_NAME);
80   if(pi == NULL)
81          luaL_typerror(L,index,TASK_MODULE_NAME);
82   tk = *pi;
83   if(!tk)
84          luaL_error(L,"null Task");
85   lua_pop(L,1);
86   return  tk;
87 }
88 /* ********************************************************************************* */
89 /*                           wrapper functions                                       */
90 /* ********************************************************************************* */
91
92 /**
93  * A task is either something to compute somewhere, or something to exchange between two hosts (or both).
94  * It is defined by a computing amount and a message size.
95  *
96  */
97
98 /* *              * *
99  * * Constructors * *
100  * *              * */
101 /**
102  * Construct an new task with the specified processing amount and amount
103  * of data needed.
104  *
105  * @param name  Task's name
106  *
107  * @param computeDuration       A value of the processing amount (in flop) needed to process the task.
108  *                              If 0, then it cannot be executed with the execute() method.
109  *                              This value has to be >= 0.
110  *
111  * @param messageSize           A value of amount of data (in bytes) needed to transfert this task.
112  *                              If 0, then it cannot be transfered with the get() and put() methods.
113  *                              This value has to be >= 0.
114  */
115 static int Task_new(lua_State* L) {
116           const char *name=luaL_checkstring(L,1);
117           int comp_size = luaL_checkint(L,2);
118           int msg_size = luaL_checkint(L,3);
119           m_task_t msg_task = MSG_task_create(name,comp_size,msg_size,NULL);
120           lua_newtable (L); /* create a table, put the userdata on top of it */
121           m_task_t *lua_task = (m_task_t*)lua_newuserdata(L,sizeof(m_task_t));
122           *lua_task = msg_task;
123           luaL_getmetatable(L,TASK_MODULE_NAME);
124           lua_setmetatable(L,-2);
125           lua_setfield (L, -2, "__simgrid_task"); /* put the userdata as field of the table */
126           /* remove the args from the stack */
127           lua_remove(L,1);
128           lua_remove(L,1);
129           lua_remove(L,1);
130           return 1;
131 }
132
133 static int Task_get_name(lua_State *L) {
134   m_task_t tk = checkTask(L,-1);
135   lua_pushstring(L,MSG_task_get_name(tk));
136   return 1;
137 }
138
139 static int Task_computation_duration(lua_State *L){
140   m_task_t tk = checkTask(L,-1);
141   lua_pushnumber(L,MSG_task_get_compute_duration (tk));
142   return 1;
143 }
144
145 static int Task_execute(lua_State *L){
146   m_task_t tk = checkTask(L,-1);
147   int res = MSG_task_execute(tk);
148   lua_pushnumber(L,res);
149   return 1;
150 }
151
152 static int Task_destroy(lua_State *L) {
153   m_task_t tk = checkTask(L,-1);
154   int res = MSG_task_destroy(tk);
155   lua_pushnumber(L,res);
156   return 1;
157 }
158
159 static int Task_send(lua_State *L)  {
160   //stackDump("send ",L);
161   m_task_t tk = checkTask(L,-2);
162   const char *mailbox = luaL_checkstring(L,-1);
163   lua_pop(L,1); // remove the string so that the task is on top of it
164   MSG_task_set_data(tk,L); // Copy my stack into the task, so that the receiver can copy the lua task directly
165   MSG_error_t res = MSG_task_send(tk,mailbox);
166   while (MSG_task_get_data(tk)!=NULL) // Don't mess up with my stack: the receiver didn't copy the data yet
167     MSG_process_sleep(0); // yield
168
169   if (res != MSG_OK) switch(res) {
170     case MSG_TIMEOUT :
171       ERROR0("MSG_task_send failed : Timeout");
172       break;
173     case MSG_TRANSFER_FAILURE :
174       ERROR0("MSG_task_send failed : Transfer Failure");
175       break;
176     case MSG_HOST_FAILURE :
177       ERROR0("MSG_task_send failed : Host Failure ");
178       break;
179     default :
180       ERROR0("MSG_task_send failed : Unexpected error , please report this bug");
181       break;
182     }
183   return 0;
184 }
185
186 static int Task_recv(lua_State *L)  {
187   m_task_t tk = NULL;
188   const char *mailbox = luaL_checkstring(L,-1);
189   MSG_error_t res = MSG_task_receive(&tk,mailbox);
190
191   lua_State *sender_stack = MSG_task_get_data(tk);
192   lua_xmove(sender_stack,L,1); // copy the data directly from sender's stack
193   MSG_task_set_data(tk,NULL);
194
195   if(res != MSG_OK) switch(res){
196           case MSG_TIMEOUT :
197                   ERROR0("MSG_task_receive failed : Timeout");
198                   break;
199           case MSG_TRANSFER_FAILURE :
200                   ERROR0("MSG_task_receive failed : Transfer Failure");
201                   break;
202           case MSG_HOST_FAILURE :
203                   ERROR0("MSG_task_receive failed : Host Failure ");
204                   break;
205           default :
206                   ERROR0("MSG_task_receive failed : Unexpected error , please report this bug");
207                   break;
208                   }
209
210   return 1;
211 }
212
213 static const luaL_reg Task_methods[] = {
214     {"new",   Task_new},
215     {"name",  Task_get_name},
216     {"computation_duration",  Task_computation_duration},
217     {"execute", Task_execute},
218     {"destroy", Task_destroy},
219     {"send",    Task_send},
220     {"recv",    Task_recv},
221     {0,0}
222 };
223 static int Task_gc(lua_State *L) {
224   m_task_t tk=checkTask(L,-1);
225   if (tk) MSG_task_destroy(tk);
226   return 0;
227 }
228
229 static int Task_tostring(lua_State *L) {
230   lua_pushfstring(L, "Task :%p",lua_touserdata(L,1));
231   return 1;
232 }
233
234 static const luaL_reg Task_meta[] = {
235     {"__gc",  Task_gc},
236     {"__tostring",  Task_tostring},
237     {0,0}
238 };
239
240 /**
241  * Host
242  */
243 static m_host_t checkHost (lua_State *L,int index) {
244   m_host_t *pi,ht;
245   luaL_checktype(L,index,LUA_TTABLE);
246   lua_getfield(L,index,"__simgrid_host");
247   pi = (m_host_t*)luaL_checkudata(L,-1,HOST_MODULE_NAME);
248   if(pi == NULL)
249          luaL_typerror(L,index,HOST_MODULE_NAME);
250   ht = *pi;
251   if(!ht)
252          luaL_error(L,"null Host");
253   lua_pop(L,1);
254   return  ht;
255 }
256
257 static int Host_get_by_name(lua_State *L)
258 {
259         const char *name=luaL_checkstring(L,1);
260         DEBUG0("Getting Host from name...");
261         m_host_t msg_host = MSG_get_host_by_name(name);
262         if (!msg_host)
263                 {
264                 luaL_error(L,"null Host : MSG_get_host_by_name failled");
265                 }
266     lua_newtable (L); /* create a table, put the userdata on top of it */
267         m_host_t *lua_host = (m_host_t*)lua_newuserdata(L,sizeof(m_host_t));
268         *lua_host = msg_host;
269         luaL_getmetatable(L,HOST_MODULE_NAME);
270         lua_setmetatable(L,-2);
271         lua_setfield (L, -2, "__simgrid_host"); /* put the userdata as field of the table */
272         /* remove the args from the stack */
273         lua_remove(L,1);
274         return 1;
275 }
276
277
278 static int Host_get_name(lua_State *L) {
279   m_host_t ht = checkHost(L,-1);
280   lua_pushstring(L,MSG_host_get_name(ht));
281   return 1;
282 }
283
284 static int Host_number(lua_State *L) {
285   lua_pushnumber(L,MSG_get_host_number());
286   return 1;
287 }
288
289 static int Host_at(lua_State *L)
290 {
291         int index = luaL_checkinteger(L,1);
292         m_host_t host = MSG_get_host_table()[index-1]; // lua indexing start by 1 (lua[1] <=> C[0])
293         lua_newtable (L); /* create a table, put the userdata on top of it */
294         m_host_t *lua_host = (m_host_t*)lua_newuserdata(L,sizeof(m_host_t));
295         *lua_host = host;
296         luaL_getmetatable(L,HOST_MODULE_NAME);
297         lua_setmetatable(L,-2);
298         lua_setfield (L, -2, "__simgrid_host"); /* put the userdata as field of the table */
299         return 1;
300
301 }
302
303 /*****************************************************************************************
304                                                              * BYPASS XML SURF Methods *
305                                                                  ***************************
306                                                                  ***************************
307 ******************************************************************************************/
308 #include "surf/surfxml_parse.h" /* to override surf_parse and bypass the parser */
309 #include "surf/surf_private.h"
310
311 typedef struct t_AS_attr
312 {
313         const char* id;
314         const char *mode;
315 }AS_attr,*p_AS_attr;
316
317 typedef struct t_host_attr
318 {
319         //platform attribute
320         // Mandatory attributes
321         const char* id;
322         double power_peak;
323         // Optional attributes
324         double power_scale;
325         const char *power_trace;
326         int state_initial;
327         const char *state_trace;
328         //deployment attribute
329         const char* function;
330         xbt_dynar_t args_list;
331 }host_attr,*p_host_attr;
332
333 typedef struct t_link_attr
334 {
335         //mandatory attributes
336         const char* id;
337         double bandwidth;
338         double latency;
339         // Optional attributes
340         const char* bandwidth_trace;
341         const char* latency_trace;
342         const char*     state_trace;
343         int state_initial;
344         int policy;
345 }link_attr,*p_link_attr;
346
347 typedef struct t_route_attr
348 {
349         const char *src_id;
350         const char *dest_id;
351         xbt_dynar_t links_id;
352
353 }route_attr,*p_route_attr;
354
355 //AS : One struct needed
356 static p_AS_attr AS;
357
358 //using xbt_dynar_t :
359 static xbt_dynar_t host_list_d ;
360 static xbt_dynar_t link_list_d ;
361 static xbt_dynar_t route_list_d ;
362
363
364 /*
365  * Initialize platform model routing
366  */
367 static void create_AS(const char* id,const char * mode)
368 {
369         surf_AS_new(id,mode);
370 }
371
372 /**
373  * create host resource via CPU model [for MSG]
374  */
375
376 static void create_host(const char* id,double power_peak,double power_sc,
377                                                 const char* power_tr,int state_init,
378                                                 const char* state_tr)
379 {
380
381         double power_scale = 1.0;
382         tmgr_trace_t power_trace = NULL;
383         e_surf_resource_state_t state_initial;
384         tmgr_trace_t state_trace;
385         if(power_sc) // !=0
386                 power_scale = power_sc;
387         if (state_init == -1)
388                 state_initial = SURF_RESOURCE_OFF;
389         else
390                 state_initial = SURF_RESOURCE_ON;
391         if(power_tr)
392                 power_trace = tmgr_trace_new(power_tr);
393         else
394                 power_trace = tmgr_trace_new("");
395         if(state_tr)
396                 state_trace = tmgr_trace_new(state_tr);
397         else
398                 state_trace = tmgr_trace_new("");
399         current_property_set = xbt_dict_new();
400         surf_host_create_resource(xbt_strdup(id), power_peak, power_scale,
401                                                power_trace, state_initial, state_trace, current_property_set);
402
403 }
404
405 /**
406  * create link resource via network model
407  */
408 static void create_link(const char *name,
409         double bw_initial,const char *trace,double lat_initial,
410         const char* latency_trace,int state_init, const char* state_trace,int policy)
411 {
412         tmgr_trace_t bw_trace;
413         tmgr_trace_t lat_trace;
414         e_surf_resource_state_t state_initial_link = SURF_RESOURCE_ON;
415         e_surf_link_sharing_policy_t policy_initial_link = SURF_LINK_SHARED;
416         tmgr_trace_t st_trace;
417         if(trace)
418                 bw_trace = tmgr_trace_new(trace);
419         else
420                 bw_trace = tmgr_trace_new("");
421
422         if(latency_trace)
423                 lat_trace = tmgr_trace_new(latency_trace);
424         else
425                 lat_trace = tmgr_trace_new("");
426
427         if(state_trace)
428                 st_trace = tmgr_trace_new(state_trace);
429         else
430                 st_trace = tmgr_trace_new("");
431
432         if(state_init == -1)
433                 state_initial_link = SURF_RESOURCE_OFF;
434         if(policy == -1)
435                 policy_initial_link = SURF_LINK_FATPIPE;
436
437         surf_link_create_resource(xbt_strdup(name), bw_initial, bw_trace,
438                    lat_initial, lat_trace, state_initial_link, st_trace,
439                    policy_initial_link, xbt_dict_new());
440 }
441
442
443 /*
444  *create host resource via workstation_ptask_L07 model [for SimDag]
445  */
446 static void create_host_wsL07(const char* id,double power_peak,double power_sc,
447                                                 const char* power_tr,int state_init,
448                                                 const char* state_tr)
449 {
450         double power_scale = 1.0;
451         tmgr_trace_t power_trace = NULL;
452         e_surf_resource_state_t state_initial;
453         tmgr_trace_t state_trace;
454         if(power_sc) // !=0
455                 power_scale = power_sc;
456         if (state_init == -1)
457                 state_initial = SURF_RESOURCE_OFF;
458         else
459                 state_initial = SURF_RESOURCE_ON;
460         if(power_tr)
461                 power_trace = tmgr_trace_new(power_tr);
462         else
463                 power_trace = tmgr_trace_new("");
464         if(state_tr)
465                 state_trace = tmgr_trace_new(state_tr);
466         else
467                 state_trace = tmgr_trace_new("");
468         current_property_set = xbt_dict_new();
469         surf_wsL07_host_create_resource(xbt_strdup(id), power_peak, power_scale,
470                                                power_trace, state_initial, state_trace, current_property_set);
471
472 }
473
474 /**
475  * create link resource via workstation_ptask_L07 model [for SimDag]
476  */
477
478 static void create_link_wsL07(const char *name,
479         double bw_initial,const char *trace,double lat_initial,
480         const char* latency_trace,int state_init, const char* state_trace,int policy)
481 {
482         tmgr_trace_t bw_trace;
483         tmgr_trace_t lat_trace;
484         e_surf_resource_state_t state_initial_link = SURF_RESOURCE_ON;
485         e_surf_link_sharing_policy_t policy_initial_link = SURF_LINK_SHARED;
486         tmgr_trace_t st_trace;
487         if(trace)
488                 bw_trace = tmgr_trace_new(trace);
489         else
490                 bw_trace = tmgr_trace_new("");
491
492         if(latency_trace)
493                 lat_trace = tmgr_trace_new(latency_trace);
494         else
495                 lat_trace = tmgr_trace_new("");
496
497         if(state_trace)
498                 st_trace = tmgr_trace_new(state_trace);
499         else
500                 st_trace = tmgr_trace_new("");
501
502         if(state_init == -1)
503                 state_initial_link = SURF_RESOURCE_OFF;
504         if(policy == -1)
505                 policy_initial_link = SURF_LINK_FATPIPE;
506
507         surf_wsL07_link_create_resource(xbt_strdup(name), bw_initial, bw_trace,
508                    lat_initial, lat_trace, state_initial_link, st_trace,
509                    policy_initial_link, xbt_dict_new());
510 }
511
512
513 /*
514  * init AS
515  */
516
517 static int AS_new(lua_State *L)
518 {
519         const char *id;
520         const char *mode;
521         if(lua_istable(L,1))
522         {
523                 lua_pushstring(L,"id");
524                 lua_gettable(L,-2);
525                 id = lua_tostring(L,-1);
526                 lua_pop(L,1);
527
528                 lua_pushstring(L,"mode");
529                 lua_gettable(L,-2);
530                 mode = lua_tostring(L,-1);
531                 lua_pop(L,1);
532         }
533         else {
534         ERROR0("Bad Arguments to AS.new, Should be a table with named arguments");
535         return -1;
536                 }
537         AS = malloc(sizeof(AS_attr));
538         AS->id = id;
539         AS->mode = mode;
540
541         return 0;
542 }
543
544 /*
545  * add new host to platform hosts list
546  */
547 static int Host_new(lua_State *L)
548 {
549
550         if(xbt_dynar_is_empty(host_list_d))
551                 host_list_d = xbt_dynar_new(sizeof(p_host_attr), &xbt_free_ref);
552
553         p_host_attr host;
554         const char * id;
555         const char *power_trace;
556         const char *state_trace;
557         double power,power_scale;
558         int state_initial;
559         //get values from the table passed as argument
560     if (lua_istable(L,-1)) {
561
562             // get Id Value
563             lua_pushstring(L,"id");
564             lua_gettable(L, -2 );
565             id = lua_tostring(L,-1);
566             lua_pop(L,1);
567
568             // get power value
569             lua_pushstring(L,"power");
570             lua_gettable(L, -2 );
571             power = lua_tonumber(L,-1);
572             lua_pop(L,1);
573
574             //get power_scale
575             lua_pushstring(L,"power_scale");
576             lua_gettable(L, -2 );
577             power_scale = lua_tonumber(L,-1);
578             lua_pop(L,1);
579
580             //get power_trace
581             lua_pushstring(L,"power_trace");
582             lua_gettable(L, -2 );
583             power_trace = lua_tostring(L,-1);
584             lua_pop(L,1);
585
586             //get state initial
587             lua_pushstring(L,"state_initial");
588             lua_gettable(L, -2 );
589             state_initial = lua_tonumber(L,-1);
590             lua_pop(L,1);
591
592             //get trace state
593             lua_pushstring(L,"state_trace");
594             lua_gettable(L, -2 );
595             state_trace = lua_tostring(L,-1);
596             lua_pop(L,1);
597
598     } else {
599             ERROR0("Bad Arguments to create host, Should be a table with named arguments");
600             return -1;
601     }
602
603             host = malloc(sizeof(host_attr));
604                 host->id = id;
605                 host->power_peak = power;
606                 host->power_scale = power_scale;
607                 host->power_trace = power_trace;
608                 host->state_initial = state_initial;
609                 host->state_trace = state_trace;
610                 host->function = NULL;
611                 xbt_dynar_push(host_list_d, &host);
612
613     return 0;
614 }
615
616 /**
617  * add link to platform links list
618  */
619 static int Link_new(lua_State *L) // (id,bandwidth,latency)
620 {
621         if(xbt_dynar_is_empty(link_list_d))
622                 link_list_d = xbt_dynar_new(sizeof(p_link_attr), &xbt_free_ref);
623
624         const char* id;
625         double bandwidth,latency;
626         const char* bandwidth_trace;
627         const char* latency_trace;
628         const char* state_trace;
629         int state_initial,policy;
630
631         //get values from the table passed as argument
632         if (lua_istable(L,-1)) {
633                     // get Id Value
634                     lua_pushstring(L,"id");
635                     lua_gettable(L, -2 );
636                     id = lua_tostring(L,-1);
637                     lua_pop(L,1);
638
639                     // get bandwidth value
640                     lua_pushstring(L,"bandwidth");
641                     lua_gettable(L, -2 );
642                     bandwidth = lua_tonumber(L,-1);
643                     lua_pop(L,1);
644
645                     //get latency value
646                     lua_pushstring(L,"latency");
647                     lua_gettable(L, -2 );
648                     latency = lua_tonumber(L,-1);
649                     lua_pop(L,1);
650
651                     /*Optional Arguments  */
652
653                     //get bandwidth_trace value
654                     lua_pushstring(L,"bandwidth_trace");
655                     lua_gettable(L, -2 );
656                     bandwidth_trace = lua_tostring(L,-1);
657                     lua_pop(L,1);
658
659                     //get latency_trace value
660                     lua_pushstring(L,"latency_trace");
661                     lua_gettable(L, -2 );
662                     latency_trace = lua_tostring(L,-1);
663                     lua_pop(L,1);
664
665                     //get state_trace value
666                     lua_pushstring(L,"state_trace");
667                     lua_gettable(L, -2 );
668                     state_trace = lua_tostring(L,-1);
669                     lua_pop(L,1);
670
671                                 //get state_initial value
672                     lua_pushstring(L,"state_initial");
673                     lua_gettable(L, -2 );
674                     state_initial = lua_tonumber(L,-1);
675                     lua_pop(L,1);
676
677
678                                 //get policy value
679                     lua_pushstring(L,"policy");
680                     lua_gettable(L, -2 );
681                     policy = lua_tonumber(L,-1);
682                     lua_pop(L,1);
683
684             } else {
685                     ERROR0("Bad Arguments to create link, Should be a table with named arguments");
686                     return -1;
687             }
688
689         p_link_attr link = malloc(sizeof(link_attr));
690         link->id = id;
691         link->bandwidth = bandwidth;
692         link->latency = latency;
693         link->bandwidth_trace = bandwidth_trace;
694         link->latency_trace = latency_trace;
695         link->state_trace = state_trace;
696         link->state_initial= state_initial;
697         link->policy = policy;
698         xbt_dynar_push(link_list_d,&link);
699         return 0;
700 }
701
702 /**
703  * add route to platform routes list
704  */
705 static int Route_new(lua_State *L) // (src_id,dest_id,links_number,link_table)
706 {
707         if(xbt_dynar_is_empty(route_list_d))
708                 route_list_d = xbt_dynar_new(sizeof(p_route_attr), &xbt_free_ref);
709         const char * link_id;
710         p_route_attr route = malloc(sizeof(route_attr));
711         route->src_id = luaL_checkstring(L,1);
712         route->dest_id = luaL_checkstring(L,2);
713         route->links_id = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
714         lua_pushnil(L);
715         while (lua_next(L,3) != 0) {
716                 link_id = lua_tostring(L, -1);
717                 xbt_dynar_push(route->links_id, &link_id);
718             DEBUG2("index = %f , Link_id = %s \n",lua_tonumber(L, -2),lua_tostring(L, -1));
719             lua_pop(L, 1);
720         }
721         lua_pop(L, 1);
722
723         //add route to platform's route list
724         xbt_dynar_push(route_list_d,&route);
725         return 0;
726 }
727
728 /**
729  * set function to process
730  */
731 static int Host_set_function(lua_State *L) //(host,function,nb_args,list_args)
732 {
733         // look for the index of host in host_list
734         const char *host_id = luaL_checkstring(L,1);
735         const char* argument;
736         unsigned int i;
737         p_host_attr p_host;
738
739         xbt_dynar_foreach(host_list_d,i,p_host)
740         {
741                 if(p_host->id == host_id)
742                 {
743                         p_host->function = luaL_checkstring(L,2);
744                         if(lua_istable(L,3))
745                         {
746                                 p_host->args_list = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
747                                 // fill the args list
748                                 lua_pushnil(L);
749                                 int j = 0;
750                                 while (lua_next(L,3) != 0) {
751                                                 argument = lua_tostring(L, -1);
752                                                 xbt_dynar_push(p_host->args_list, &argument);
753                                                 DEBUG2("index = %f , Arg_id = %s \n",lua_tonumber(L, -2),lua_tostring(L, -1));
754                                                 j++;
755                                                 lua_pop(L, 1);
756                                         }
757                         }
758                         lua_pop(L, 1);
759                         return 0;
760                 }
761         }
762         ERROR1("Host : %s Not Found !!",host_id);
763         return 1;
764 }
765
766 /*
767  * surf parse bypass platform
768  * through CPU/network Models
769  */
770
771 static int surf_parse_bypass_platform()
772 {
773         unsigned int i;
774         p_host_attr p_host;
775         p_link_attr p_link;
776         p_route_attr p_route;
777
778         // Init routing mode
779         create_AS(AS->id,AS->mode);
780
781
782         // Add Hosts
783         xbt_dynar_foreach(host_list_d,i,p_host)
784         {
785                 create_host(p_host->id,p_host->power_peak,p_host->power_scale,p_host->power_trace,
786                                         p_host->state_initial,p_host->state_trace);
787                 //add to routing model host list
788                 surf_route_add_host((char*)p_host->id);
789
790         }
791
792         //add Links
793         xbt_dynar_foreach(link_list_d,i,p_link)
794         {
795                 create_link(p_link->id,p_link->bandwidth,p_link->bandwidth_trace,p_link->latency,
796                                 p_link->latency_trace,p_link->state_initial,p_link->state_trace,p_link->policy);
797         }
798         // add route
799         xbt_dynar_foreach(route_list_d,i,p_route)
800         {
801                 surf_routing_add_route((char*)p_route->src_id,(char*)p_route->dest_id,p_route->links_id);
802         }
803         /* </platform> */
804
805         // Finalize AS
806         surf_AS_finalize(AS->id);
807
808         // add traces
809         surf_add_host_traces();
810         //surf_set_routes();
811         surf_add_link_traces();
812
813         return 0; // must return 0 ?!!
814
815 }
816
817 /**
818  *
819  * surf parse bypass platform
820  * through workstation_ptask_L07 Model
821  */
822
823
824 static int surf_wsL07_parse_bypass_platform()
825 {
826         unsigned int i;
827         p_host_attr p_host;
828         p_link_attr p_link;
829         p_route_attr p_route;
830
831         // Add Hosts
832         xbt_dynar_foreach(host_list_d,i,p_host)
833         {
834                 create_host_wsL07(p_host->id,p_host->power_peak,p_host->power_scale,p_host->power_trace,
835                                         p_host->state_initial,p_host->state_trace);
836                 //add to routing model host list
837                 surf_route_add_host((char*)p_host->id);
838         }
839
840         //add Links
841         xbt_dynar_foreach(link_list_d,i,p_link)
842         {
843                 create_link_wsL07(p_link->id,p_link->bandwidth,p_link->bandwidth_trace,p_link->latency,
844                                                 p_link->latency_trace,p_link->state_initial,p_link->state_trace,p_link->policy);
845         }
846         // add route
847         xbt_dynar_foreach(route_list_d,i,p_route)
848         {
849                 //surf_routing_add_route((char*)p_route->src_id,(char*)p_route->dest_id,p_route->links_id);
850         }
851         /* </platform> */
852
853         surf_wsL07_add_traces();
854         //surf_set_routes();
855
856         return 0;
857
858 }
859 /*
860  * surf parse bypass application for MSG Module
861  */
862 static int surf_parse_bypass_application()
863 {
864           unsigned int i;
865           p_host_attr p_host;
866           xbt_dynar_foreach(host_list_d,i,p_host)
867                   {
868                   if(p_host->function)
869                           MSG_set_function(p_host->id,p_host->function,p_host->args_list);
870                   }
871           return 0;
872 }
873
874
875 /**
876  *  Generate Gras Templates File from lua
877  */
878
879 xbt_dict_t process_function_set;
880 xbt_dynar_t process_list;
881 xbt_dict_t machine_set;
882 static s_process_t process;
883
884 void s_process_free(void *process)
885 {
886   s_process_t *p = (s_process_t *) process;
887   int i;
888   for (i = 0; i < p->argc; i++)
889     free(p->argv[i]);
890   free(p->argv);
891   free(p->host);
892 }
893
894 static int gras_add_process_function(lua_State *L)
895 {
896         const char * arg;
897         const char* process_host = luaL_checkstring(L,1);
898         const char *process_function = luaL_checkstring(L,2);
899
900         if(xbt_dict_is_empty(machine_set) || xbt_dict_is_empty(process_function_set)
901                         || xbt_dynar_is_empty(process_list))
902                 {
903                   process_function_set = xbt_dict_new();
904                   process_list = xbt_dynar_new(sizeof(s_process_t), s_process_free);
905                   machine_set = xbt_dict_new();
906                 }
907
908         xbt_dict_set(machine_set,process_host, NULL, NULL);
909         xbt_dict_set(process_function_set,process_function, NULL, NULL);
910
911         process.argc = 1;
912         process.argv = xbt_new(char *, 1);
913         process.argv[0] = xbt_strdup(process_function);
914         process.host = strdup(process_host);
915
916         lua_pushnil(L);
917         while (lua_next(L,3) != 0) {
918                 arg = lua_tostring(L, -1);
919                 process.argc++;
920                 process.argv = xbt_realloc(process.argv, (process.argc) * sizeof(char *));
921                 process.argv[(process.argc) - 1] = xbt_strdup(arg);
922
923                 DEBUG2("index = %f , arg = %s \n",lua_tonumber(L, -2),lua_tostring(L, -1));
924                 lua_pop(L, 1);
925                 }
926         lua_pop(L, 1);
927         //add to the process list
928         xbt_dynar_push(process_list, &process);
929
930         return 0;
931
932 }
933
934
935 static int gras_generate(lua_State *L)
936 {
937   const char *project_name = luaL_checkstring(L,1);
938   generate_sim(project_name);
939   generate_rl(project_name);
940   generate_makefile_local(project_name);
941
942   return 0;
943 }
944
945 //***********Register Methods *******************************************//
946 /*
947  * Host Methods
948  */
949 static const luaL_reg Host_methods[] = {
950     {"getByName",   Host_get_by_name},
951     {"name",            Host_get_name},
952     {"number",          Host_number},
953     {"at",                      Host_at},
954     // Bypass XML Methods
955     {"new",                     Host_new},
956     {"setFunction",     Host_set_function},
957     {0,0}
958 };
959
960 static int Host_gc(lua_State *L)
961 {
962   m_host_t ht = checkHost(L,-1);
963   if (ht) ht = NULL;
964   return 0;
965 }
966
967 static int Host_tostring(lua_State *L)
968 {
969   lua_pushfstring(L,"Host :%p",lua_touserdata(L,1));
970   return 1;
971 }
972
973 static const luaL_reg Host_meta[] = {
974     {"__gc",  Host_gc},
975     {"__tostring",  Host_tostring},
976     {0,0}
977 };
978
979 /*
980  * AS Methods
981  */
982 static const luaL_reg AS_methods[] = {
983     {"new",AS_new},
984     {0,0}
985 };
986
987
988 /*
989  * Link Methods
990  */
991 static const luaL_reg Link_methods[] = {
992     {"new",Link_new},
993     {0,0}
994 };
995 /*
996  * Route Methods
997  */
998 static const luaL_reg Route_methods[] ={
999    {"new",Route_new},
1000    {0,0}
1001 };
1002
1003 /*
1004  * Environment related
1005  */
1006
1007 extern lua_State *simgrid_lua_state;
1008
1009 static int run_lua_code(int argc,char **argv) {
1010   DEBUG1("Run lua code %s",argv[0]);
1011   lua_State *L = lua_newthread(simgrid_lua_state);
1012   int ref = luaL_ref(simgrid_lua_state, LUA_REGISTRYINDEX); // protect the thread from being garbage collected
1013   int res = 1;
1014
1015   /* Start the co-routine */
1016   lua_getglobal(L,argv[0]);
1017   xbt_assert1(lua_isfunction(L,-1),
1018       "The lua function %s does not seem to exist",argv[0]);
1019
1020   // push arguments onto the stack
1021   int i;
1022   for(i=1;i<argc;i++)
1023     lua_pushstring(L,argv[i]);
1024
1025   // Call the function (in resume)
1026   xbt_assert2(lua_pcall(L, argc-1, 1, 0) == 0,
1027     "error running function `%s': %s",argv[0], lua_tostring(L, -1));
1028
1029   /* retrieve result */
1030   if (lua_isnumber(L, -1)) {
1031     res = lua_tonumber(L, -1);
1032     lua_pop(L, 1);  /* pop returned value */
1033   }
1034   // cleanups
1035   luaL_unref(simgrid_lua_state,LUA_REGISTRYINDEX,ref );
1036   DEBUG1("Execution of lua code %s is over", (argv ? argv[0] : "(null)"));
1037   return res;
1038 }
1039 static int launch_application(lua_State *L) {
1040   const char * file = luaL_checkstring(L,1);
1041   MSG_function_register_default(run_lua_code);
1042   MSG_launch_application(file);
1043   return 0;
1044 }
1045 #include "simix/simix.h" //FIXME: KILLME when debugging on simix internals become useless
1046 static int create_environment(lua_State *L) {
1047   const char *file = luaL_checkstring(L,1);
1048   DEBUG1("Loading environment file %s",file);
1049   MSG_create_environment(file);
1050   smx_host_t *hosts = SIMIX_host_get_table();
1051   int i;
1052   for (i=0;i<SIMIX_host_get_number();i++) {
1053     DEBUG1("We have an host %s", SIMIX_host_get_name(hosts[i]));
1054   }
1055
1056   return 0;
1057 }
1058
1059 static int debug(lua_State *L) {
1060   const char *str = luaL_checkstring(L,1);
1061   DEBUG1("%s",str);
1062   return 0;
1063 }
1064 static int info(lua_State *L) {
1065   const char *str = luaL_checkstring(L,1);
1066   INFO1("%s",str);
1067   return 0;
1068 }
1069 static int run(lua_State *L) {
1070   MSG_main();
1071   return 0;
1072 }
1073 static int clean(lua_State *L) {
1074   MSG_clean();
1075   return 0;
1076 }
1077
1078 /*
1079  * Bypass XML Parser
1080  */
1081
1082 /*
1083  * Register platform for MSG
1084  */
1085 static int msg_register_platform(lua_State *L)
1086 {
1087         /* Tell Simgrid we dont wanna use its parser*/
1088         surf_parse = surf_parse_bypass_platform;
1089         MSG_create_environment(NULL);
1090         return 0;
1091 }
1092
1093 /*
1094  * Register platform for Simdag
1095  */
1096
1097 static int sd_register_platform(lua_State *L)
1098 {
1099         surf_parse = surf_wsL07_parse_bypass_platform;
1100         SD_create_environment(NULL);
1101         return 0;
1102 }
1103 /*
1104  * Register platform for gras
1105  */
1106 static int gras_register_platform(lua_State *L)
1107 {
1108         /* Tell Simgrid we dont wanna use surf parser*/
1109         surf_parse = surf_parse_bypass_platform;
1110         gras_create_environment(NULL);
1111         return 0;
1112 }
1113
1114 /**
1115  * Register applicaiton for MSG
1116  */
1117 static int msg_register_application(lua_State *L)
1118 {
1119          MSG_function_register_default(run_lua_code);
1120          surf_parse = surf_parse_bypass_application;
1121          MSG_launch_application(NULL);
1122          return 0;
1123 }
1124
1125 /*
1126  * Register application for gras
1127  */
1128 static int gras_register_application(lua_State *L)
1129 {
1130         gras_function_register_default(run_lua_code);
1131         surf_parse = surf_parse_bypass_application;
1132         gras_launch_application(NULL);
1133         return 0;
1134 }
1135 static const luaL_Reg simgrid_funcs[] = {
1136     { "create_environment", create_environment},
1137     { "launch_application", launch_application},
1138     { "debug", debug},
1139     { "info", info},
1140     { "run", run},
1141     { "clean", clean},
1142     /* short names */
1143     { "platform", create_environment},
1144     { "application", launch_application},
1145     /* methods to bypass XML parser*/
1146     { "msg_register_platform",msg_register_platform},
1147     { "sd_register_platform",sd_register_platform},
1148     { "msg_register_application",msg_register_application},
1149     { "gras_register_platform",gras_register_platform},
1150     { "gras_register_application",gras_register_application},
1151     /* gras sub generator method*/
1152     {"gras_set_process_function",gras_add_process_function},
1153     {"gras_generate",gras_generate},
1154     { NULL, NULL }
1155 };
1156
1157 /* ********************************************************************************* */
1158 /*                       module management functions                                 */
1159 /* ********************************************************************************* */
1160
1161 extern const char*xbt_ctx_factory_to_use; /*Hack: let msg load directly the right factory */
1162
1163 #define LUA_MAX_ARGS_COUNT 10 /* maximum amount of arguments we can get from lua on command line */
1164 #define TEST
1165 int luaopen_simgrid(lua_State* L); // Fuck gcc: we don't need that prototype
1166 int luaopen_simgrid(lua_State* L) {
1167
1168   //xbt_ctx_factory_to_use = "lua";
1169   char **argv=malloc(sizeof(char*)*LUA_MAX_ARGS_COUNT);
1170   int argc=1;
1171   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? */
1172   /* Get the command line arguments from the lua interpreter */
1173   lua_getglobal(L,"arg");
1174   /* if arg is a null value, it means we use lua only as a script to init platform
1175    * else it should be a table and then take arg in consideration
1176    */
1177   if(lua_istable(L,-1))
1178   {
1179           int done=0;
1180           while (!done) {
1181                 argc++;
1182                 lua_pushinteger(L,argc-2);
1183                 lua_gettable(L,-2);
1184                 if (lua_isnil(L,-1)) {
1185                   done = 1;
1186                 } else {
1187                   xbt_assert1(lua_isstring(L,-1),"argv[%d] got from lua is no string",argc-1);
1188                   xbt_assert2(argc<LUA_MAX_ARGS_COUNT,
1189                            "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",
1190                            __FILE__,LUA_MAX_ARGS_COUNT-1);
1191                   argv[argc-1] = (char*)luaL_checkstring(L,-1);
1192                   lua_pop(L,1);
1193                   DEBUG1("Got command line argument %s from lua",argv[argc-1]);
1194                 }
1195           }
1196           argv[argc--]=NULL;
1197
1198           /* Initialize the MSG core */
1199           MSG_global_init(&argc,argv);
1200           DEBUG1("Still %d arguments on command line",argc); // FIXME: update the lua's arg table to reflect the changes from SimGrid
1201  }
1202   /* register the core C functions to lua */
1203   luaL_register(L, "simgrid", simgrid_funcs);
1204   /* register the task methods to lua */
1205   luaL_openlib(L,TASK_MODULE_NAME,Task_methods,0); //create methods table,add it to the globals
1206   luaL_newmetatable(L,TASK_MODULE_NAME); //create metatable for Task,add it to the Lua registry
1207   luaL_openlib(L,0,Task_meta,0);// fill metatable
1208   lua_pushliteral(L,"__index");
1209   lua_pushvalue(L,-3);  //dup methods table
1210   lua_rawset(L,-3); //matatable.__index = methods
1211   lua_pushliteral(L,"__metatable");
1212   lua_pushvalue(L,-3);  //dup methods table
1213   lua_rawset(L,-3); //hide metatable:metatable.__metatable = methods
1214   lua_pop(L,1);   //drop metatable
1215
1216   /* register the hosts methods to lua*/
1217   luaL_openlib(L,HOST_MODULE_NAME,Host_methods,0);
1218   luaL_newmetatable(L,HOST_MODULE_NAME);
1219   luaL_openlib(L,0,Host_meta,0);
1220   lua_pushliteral(L,"__index");
1221   lua_pushvalue(L,-3);
1222   lua_rawset(L,-3);
1223   lua_pushliteral(L,"__metatable");
1224   lua_pushvalue(L,-3);
1225   lua_rawset(L,-3);
1226   lua_pop(L,1);
1227
1228   /* register the links methods to lua*/
1229   luaL_openlib(L,AS_MODULE_NAME,AS_methods,0);
1230   luaL_newmetatable(L,AS_MODULE_NAME);
1231   lua_pop(L,1);
1232
1233   /* register the links methods to lua*/
1234   luaL_openlib(L,LINK_MODULE_NAME,Link_methods,0);
1235   luaL_newmetatable(L,LINK_MODULE_NAME);
1236   lua_pop(L,1);
1237
1238   /*register the routes methods to lua*/
1239   luaL_openlib(L,ROUTE_MODULE_NAME,Route_methods,0);
1240   luaL_newmetatable(L,LINK_MODULE_NAME);
1241   lua_pop(L,1);
1242
1243   /* Keep the context mechanism informed of our lua world today */
1244   simgrid_lua_state = L;
1245   return 1;
1246 }