Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
4578350a26e61cad2b35688a91d7d7abea8f2404
[simgrid.git] / src / surf / surf_routing.cpp
1 /* Copyright (c) 2009-2011, 2013-2015. The SimGrid Team.
2  * All rights reserved.                                                     */
3
4 /* This program is free software; you can redistribute it and/or modify it
5  * under the terms of the license (GNU LGPL) which comes with this package. */
6
7 #include "surf_routing.hpp"
8 #include "surf_routing_private.hpp"
9 #include "surf_routing_cluster.hpp"
10
11 #include "simgrid/platf_interface.h"    // platform creation API internal interface
12 #include "simgrid/sg_config.h"
13 #include "storage_interface.hpp"
14 #include "src/surf/platform.hpp"
15 #include "surf/surfxml_parse_values.h"
16
17 /*************
18  * Callbacks *
19  *************/
20
21 namespace simgrid {
22 namespace surf {
23
24 simgrid::xbt::signal<void(simgrid::surf::NetCard*)> netcardCreatedCallbacks;
25 simgrid::xbt::signal<void(simgrid::surf::As*)> asCreatedCallbacks;
26
27 }
28 }
29
30 /**
31  * @ingroup SURF_build_api
32  * @brief A library containing all known hosts
33  */
34 xbt_dict_t host_list;
35
36 int COORD_HOST_LEVEL=0;         //Coordinates level
37
38 int MSG_FILE_LEVEL;             //Msg file level
39
40 int SIMIX_STORAGE_LEVEL;        //Simix storage level
41 int MSG_STORAGE_LEVEL;          //Msg storage level
42
43 xbt_lib_t as_router_lib;
44 int ROUTING_ASR_LEVEL;          //Routing level
45 int COORD_ASR_LEVEL;            //Coordinates level
46 int NS3_ASR_LEVEL;              //host node for ns3
47 int ROUTING_PROP_ASR_LEVEL;     //Where the properties are stored
48
49 /** @brief Retrieve a netcard from its name
50  *
51  * Netcards are the thing that connect host or routers to the network
52  */
53 simgrid::surf::NetCard *sg_netcard_by_name_or_null(const char *name)
54 {
55   sg_host_t h = sg_host_by_name(name);
56   simgrid::surf::NetCard *net_elm = h==NULL?NULL: h->pimpl_netcard;
57   if (!net_elm)
58     net_elm = (simgrid::surf::NetCard*) xbt_lib_get_or_null(as_router_lib, name, ROUTING_ASR_LEVEL);
59   return net_elm;
60 }
61
62 /* Global vars */
63 simgrid::surf::RoutingPlatf *routing_platf = NULL;
64
65 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(surf_route, surf, "Routing part of surf");
66
67 /** The current AS in the parsing */
68 static simgrid::surf::As *current_routing = NULL;
69 simgrid::surf::As* routing_get_current()
70 {
71   return current_routing;
72 }
73
74 /* this lines are only for replace use like index in the model table */
75 typedef enum {
76   SURF_MODEL_FULL = 0,
77   SURF_MODEL_FLOYD,
78   SURF_MODEL_DIJKSTRA,
79   SURF_MODEL_DIJKSTRACACHE,
80   SURF_MODEL_NONE,
81   SURF_MODEL_VIVALDI,
82   SURF_MODEL_CLUSTER,
83   SURF_MODEL_TORUS_CLUSTER,
84   SURF_MODEL_FAT_TREE_CLUSTER,
85 } e_routing_types;
86
87 struct s_model_type routing_models[] = {
88   {"Full",
89    "Full routing data (fast, large memory requirements, fully expressive)",
90    model_full_create, model_full_end},
91   {"Floyd",
92    "Floyd routing data (slow initialization, fast lookup, lesser memory requirements, shortest path routing only)",
93    model_floyd_create, model_floyd_end},
94   {"Dijkstra",
95    "Dijkstra routing data (fast initialization, slow lookup, small memory requirements, shortest path routing only)",
96    model_dijkstra_create, model_dijkstra_both_end},
97   {"DijkstraCache",
98    "Dijkstra routing data (fast initialization, fast lookup, small memory requirements, shortest path routing only)",
99    model_dijkstracache_create, model_dijkstra_both_end},
100   {"none", "No routing (Unless you know what you are doing, avoid using this mode in combination with a non Constant network model).",
101    model_none_create,  NULL},
102   {"Vivaldi", "Vivaldi routing",
103    model_vivaldi_create, NULL},
104   {"Cluster", "Cluster routing",
105    model_cluster_create, NULL},
106   {"Torus_Cluster", "Torus Cluster routing",
107    model_torus_cluster_create, NULL},
108   {"Fat_Tree_Cluster", "Fat Tree Cluster routing",
109    model_fat_tree_cluster_create, NULL},
110   {NULL, NULL, NULL, NULL}
111 };
112
113 /**
114  * \brief Add a netcard connecting an host to the network element list
115  * FIXME: integrate into host constructor
116  */
117 void sg_platf_new_netcard(sg_platf_host_link_cbarg_t netcard)
118 {
119   simgrid::surf::NetCard *info = sg_host_by_name(netcard->id)->pimpl_netcard;
120   xbt_assert(info, "Host '%s' not found!", netcard->id);
121   xbt_assert(current_routing->p_modelDesc == &routing_models[SURF_MODEL_CLUSTER] ||
122       current_routing->p_modelDesc == &routing_models[SURF_MODEL_VIVALDI],
123       "You have to be in model Cluster to use tag host_link!");
124
125   s_surf_parsing_link_up_down_t link_up_down;
126   link_up_down.link_up = Link::byName(netcard->link_up);
127   link_up_down.link_down = Link::byName(netcard->link_down);
128
129   xbt_assert(link_up_down.link_up, "Link '%s' not found!",netcard->link_up);
130   xbt_assert(link_up_down.link_down, "Link '%s' not found!",netcard->link_down);
131
132   if(!current_routing->p_linkUpDownList)
133     current_routing->p_linkUpDownList = xbt_dynar_new(sizeof(s_surf_parsing_link_up_down_t),NULL);
134
135   // If dynar is is greater than netcard id and if the host_link is already defined
136   if((int)xbt_dynar_length(current_routing->p_linkUpDownList) > info->getId() &&
137       xbt_dynar_get_as(current_routing->p_linkUpDownList, info->getId(), void*))
138   surf_parse_error("Host_link for '%s' is already defined!",netcard->id);
139
140   XBT_DEBUG("Push Host_link for host '%s' to position %d", info->getName(), info->getId());
141   xbt_dynar_set_as(current_routing->p_linkUpDownList, info->getId(), s_surf_parsing_link_up_down_t, link_up_down);
142 }
143
144 void sg_platf_new_trace(sg_platf_trace_cbarg_t trace)
145 {
146   tmgr_trace_t tmgr_trace;
147   if (!trace->file || strcmp(trace->file, "") != 0) {
148     tmgr_trace = tmgr_trace_new_from_file(trace->file);
149   } else {
150     xbt_assert(strcmp(trace->pc_data, ""),
151         "Trace '%s' must have either a content, or point to a file on disk.",trace->id);
152     tmgr_trace = tmgr_trace_new_from_string(trace->id, trace->pc_data, trace->periodicity);
153   }
154   xbt_dict_set(traces_set_list, trace->id, (void *) tmgr_trace, NULL);
155 }
156
157 /**
158  * \brief Make a new routing component to the platform
159  *
160  * Add a new autonomous system to the platform. Any elements (such as host,
161  * router or sub-AS) added after this call and before the corresponding call
162  * to sg_platf_new_AS_close() will be added to this AS.
163  *
164  * Once this function was called, the configuration concerning the used
165  * models cannot be changed anymore.
166  *
167  * @param AS_id name of this autonomous system. Must be unique in the platform
168  * @param wanted_routing_type one of Full, Floyd, Dijkstra or similar. Full list in the variable routing_models, in src/surf/surf_routing.c
169  */
170 void routing_AS_begin(sg_platf_AS_cbarg_t AS)
171 {
172   XBT_DEBUG("routing_AS_begin");
173   routing_model_description_t model = NULL;
174
175   xbt_assert(!xbt_lib_get_or_null
176              (as_router_lib, AS->id, ROUTING_ASR_LEVEL),
177              "The AS \"%s\" already exists", AS->id);
178
179   _sg_cfg_init_status = 2; /* horrible hack: direct access to the global
180                             * controlling the level of configuration to prevent
181                             * any further config */
182
183   /* search the routing model */
184   switch(AS->routing){
185     case A_surfxml_AS_routing_Cluster:               model = &routing_models[SURF_MODEL_CLUSTER];break;
186     case A_surfxml_AS_routing_Cluster___torus:       model = &routing_models[SURF_MODEL_TORUS_CLUSTER];break;
187     case A_surfxml_AS_routing_Cluster___fat___tree:  model = &routing_models[SURF_MODEL_FAT_TREE_CLUSTER];break;
188     case A_surfxml_AS_routing_Dijkstra:              model = &routing_models[SURF_MODEL_DIJKSTRA];break;
189     case A_surfxml_AS_routing_DijkstraCache:         model = &routing_models[SURF_MODEL_DIJKSTRACACHE];break;
190     case A_surfxml_AS_routing_Floyd:                 model = &routing_models[SURF_MODEL_FLOYD];break;
191     case A_surfxml_AS_routing_Full:                  model = &routing_models[SURF_MODEL_FULL];break;
192     case A_surfxml_AS_routing_None:                  model = &routing_models[SURF_MODEL_NONE];break;
193     case A_surfxml_AS_routing_Vivaldi:               model = &routing_models[SURF_MODEL_VIVALDI];break;
194     default: xbt_die("Not a valid model!!!");
195     break;
196   }
197
198   /* make a new routing component */
199   simgrid::surf::As *new_as = model->create();
200
201   new_as->p_modelDesc = model;
202   new_as->p_hierarchy = SURF_ROUTING_NULL;
203   new_as->p_name = xbt_strdup(AS->id);
204
205   simgrid::surf::NetCard *info =
206     new simgrid::surf::NetCardImpl(xbt_strdup(new_as->p_name),
207                                             -1,
208                                             SURF_NETWORK_ELEMENT_AS,
209                                             current_routing);
210   if (current_routing == NULL && routing_platf->p_root == NULL) {
211
212     /* it is the first one */
213     new_as->p_routingFather = NULL;
214     routing_platf->p_root = new_as;
215     info->setId(-1);
216   } else if (current_routing != NULL && routing_platf->p_root != NULL) {
217
218     xbt_assert(!xbt_dict_get_or_null
219                (current_routing->p_routingSons, AS->id),
220                "The AS \"%s\" already exists", AS->id);
221     /* it is a part of the tree */
222     new_as->p_routingFather = current_routing;
223     /* set the father behavior */
224     if (current_routing->p_hierarchy == SURF_ROUTING_NULL)
225       current_routing->p_hierarchy = SURF_ROUTING_RECURSIVE;
226     /* add to the sons dictionary */
227     xbt_dict_set(current_routing->p_routingSons, AS->id,
228                  (void *) new_as, NULL);
229     /* add to the father element list */
230     info->setId(current_routing->parseAS(info));
231   } else {
232     THROWF(arg_error, 0, "All defined components must belong to a AS");
233   }
234
235   xbt_lib_set(as_router_lib, info->getName(), ROUTING_ASR_LEVEL,
236               (void *) info);
237   XBT_DEBUG("Having set name '%s' id '%d'", new_as->p_name, info->getId());
238
239   /* set the new current component of the tree */
240   current_routing = new_as;
241   current_routing->p_netcard = info;
242
243   simgrid::surf::netcardCreatedCallbacks(info);
244   simgrid::surf::asCreatedCallbacks(new_as);
245 }
246
247 /**
248  * \brief Specify that the current description of AS is finished
249  *
250  * Once you've declared all the content of your AS, you have to close
251  * it with this call. Your AS is not usable until you call this function.
252  *
253  * @fixme: this call is not as robust as wanted: bad things WILL happen
254  * if you call it twice for the same AS, or if you forget calling it, or
255  * even if you add stuff to a closed AS
256  *
257  */
258 void routing_AS_end()
259 {
260
261   if (current_routing == NULL) {
262     THROWF(arg_error, 0, "Close an AS, but none was under construction");
263   } else {
264     if (current_routing->p_modelDesc->end)
265       current_routing->p_modelDesc->end(current_routing);
266     current_routing = current_routing->p_routingFather;
267   }
268 }
269
270 /* Aux Business methods */
271
272 /**
273  * \brief Get the AS father and the first elements of the chain
274  *
275  * \param src the source host name
276  * \param dst the destination host name
277  *
278  * Get the common father of the to processing units, and the first different
279  * father in the chain
280  */
281 static void elements_father(sg_netcard_t src, sg_netcard_t dst,
282                             AS_t * res_father,
283                             AS_t * res_src,
284                             AS_t * res_dst)
285 {
286   xbt_assert(src && dst, "bad parameters for \"elements_father\" method");
287 #define ELEMENTS_FATHER_MAXDEPTH 16     /* increase if it is not enough */
288   simgrid::surf::As *src_as, *dst_as;
289   simgrid::surf::As *path_src[ELEMENTS_FATHER_MAXDEPTH];
290   simgrid::surf::As *path_dst[ELEMENTS_FATHER_MAXDEPTH];
291   int index_src = 0;
292   int index_dst = 0;
293   simgrid::surf::As *current;
294   simgrid::surf::As *current_src;
295   simgrid::surf::As *current_dst;
296   simgrid::surf::As *father;
297
298   /* (1) find the as where the src and dst are located */
299   sg_netcard_t src_data = src;
300   sg_netcard_t dst_data = dst;
301   src_as = src_data->getRcComponent();
302   dst_as = dst_data->getRcComponent();
303 #ifndef NDEBUG
304   char* src_name = src_data->getName();
305   char* dst_name = dst_data->getName();
306 #endif
307
308   xbt_assert(src_as && dst_as,
309              "Ask for route \"from\"(%s) or \"to\"(%s) no found", src_name, dst_name);
310
311   /* (2) find the path to the root routing component */
312   for (current = src_as; current != NULL; current = current->p_routingFather) {
313     if (index_src >= ELEMENTS_FATHER_MAXDEPTH)
314       xbt_die("ELEMENTS_FATHER_MAXDEPTH should be increased for path_src");
315     path_src[index_src++] = current;
316   }
317   for (current = dst_as; current != NULL; current = current->p_routingFather) {
318     if (index_dst >= ELEMENTS_FATHER_MAXDEPTH)
319       xbt_die("ELEMENTS_FATHER_MAXDEPTH should be increased for path_dst");
320     path_dst[index_dst++] = current;
321   }
322
323   /* (3) find the common father */
324   do {
325     current_src = path_src[--index_src];
326     current_dst = path_dst[--index_dst];
327   } while (index_src > 0 && index_dst > 0 && current_src == current_dst);
328
329   /* (4) they are not in the same routing component, make the path */
330   if (current_src == current_dst)
331     father = current_src;
332   else
333     father = path_src[index_src + 1];
334
335   /* (5) result generation */
336   *res_father = father;         /* first the common father of src and dst */
337   *res_src = current_src;       /* second the first different father of src */
338   *res_dst = current_dst;       /* three  the first different father of dst */
339
340 #undef ELEMENTS_FATHER_MAXDEPTH
341 }
342
343 /* Global Business methods */
344
345 /**
346  * \brief Recursive function for get_route_latency
347  *
348  * \param src the source host name
349  * \param dst the destination host name
350  * \param *route the route where the links are stored. It is either NULL or a ready to use dynar
351  * \param *latency the latency, if needed
352  *
353  * This function is called by "get_route" and "get_latency". It allows to walk
354  * recursively through the ASes tree.
355  */
356 static void _get_route_and_latency(
357   simgrid::surf::NetCard *src, simgrid::surf::NetCard *dst,
358   xbt_dynar_t * links, double *latency)
359 {
360   s_sg_platf_route_cbarg_t route = SG_PLATF_ROUTE_INITIALIZER;
361   memset(&route,0,sizeof(route));
362
363   xbt_assert(src && dst, "bad parameters for \"_get_route_latency\" method");
364   XBT_DEBUG("Solve route/latency  \"%s\" to \"%s\"", src->getName(), dst->getName());
365
366   /* Find how src and dst are interconnected */
367   simgrid::surf::As *common_father, *src_father, *dst_father;
368   elements_father(src, dst, &common_father, &src_father, &dst_father);
369   XBT_DEBUG("elements_father: common father '%s' src_father '%s' dst_father '%s'",
370       common_father->p_name, src_father->p_name, dst_father->p_name);
371
372   /* Check whether a direct bypass is defined */
373   sg_platf_route_cbarg_t e_route_bypass = NULL;
374   //FIXME:REMOVE:if (common_father->get_bypass_route)
375
376   e_route_bypass = common_father->getBypassRoute(src, dst, latency);
377
378   /* Common ancestor is kind enough to declare a bypass route from src to dst -- use it and bail out */
379   if (e_route_bypass) {
380     xbt_dynar_merge(links, &e_route_bypass->link_list);
381     routing_route_free(e_route_bypass);
382     return;
383   }
384
385   /* If src and dst are in the same AS, life is good */
386   if (src_father == dst_father) {       /* SURF_ROUTING_BASE */
387     route.link_list = *links;
388     common_father->getRouteAndLatency(src, dst, &route, latency);
389     // if vivaldi latency+=vivaldi(src,dst)
390     return;
391   }
392
393   /* Not in the same AS, no bypass. We'll have to find our path between the ASes recursively*/
394
395   route.link_list = xbt_dynar_new(sizeof(sg_routing_link_t), NULL);
396   // Find the net_card corresponding to father
397   simgrid::surf::NetCard *src_father_netcard = src_father->p_netcard;
398   simgrid::surf::NetCard *dst_father_netcard = dst_father->p_netcard;
399
400   common_father->getRouteAndLatency(src_father_netcard, dst_father_netcard,
401                                     &route, latency);
402
403   xbt_assert((route.gw_src != NULL) && (route.gw_dst != NULL),
404       "bad gateways for route from \"%s\" to \"%s\"", src->getName(), dst->getName());
405
406   sg_netcard_t src_gateway_net_elm = route.gw_src;
407   sg_netcard_t dst_gateway_net_elm = route.gw_dst;
408
409   /* If source gateway is not our source, we have to recursively find our way up to this point */
410   if (src != src_gateway_net_elm)
411     _get_route_and_latency(src, src_gateway_net_elm, links, latency);
412   xbt_dynar_merge(links, &route.link_list);
413
414   /* If dest gateway is not our destination, we have to recursively find our way from this point */
415   if (dst_gateway_net_elm != dst)
416     _get_route_and_latency(dst_gateway_net_elm, dst, links, latency);
417
418 }
419
420 AS_t surf_platf_get_root(routing_platf_t platf){
421   return platf->p_root;
422 }
423
424 e_surf_network_element_type_t surf_routing_edge_get_rc_type(sg_netcard_t netcard){
425   return netcard->getRcType();
426 }
427
428 namespace simgrid {
429 namespace surf {
430
431 /**
432  * \brief Find a route between hosts
433  *
434  * \param src the network_element_t for src host
435  * \param dst the network_element_t for dst host
436  * \param route where to store the list of links.
437  *              If *route=NULL, create a short lived dynar. Else, fill the provided dynar
438  * \param latency where to store the latency experienced on the path (or NULL if not interested)
439  *                It is the caller responsability to initialize latency to 0 (we add to provided route)
440  * \pre route!=NULL
441  *
442  * walk through the routing components tree and find a route between hosts
443  * by calling each "get_route" function in each routing component.
444  */
445 void RoutingPlatf::getRouteAndLatency(NetCard *src, NetCard *dst, xbt_dynar_t* route, double *latency)
446 {
447   XBT_DEBUG("getRouteAndLatency from %s to %s", src->getName(), dst->getName());
448   if (NULL == *route) {
449     xbt_dynar_reset(routing_platf->p_lastRoute);
450     *route = routing_platf->p_lastRoute;
451   }
452
453   _get_route_and_latency(src, dst, route, latency);
454
455   xbt_assert(!latency || *latency >= 0.0,
456              "negative latency on route between \"%s\" and \"%s\"", src->getName(), dst->getName());
457 }
458
459 xbt_dynar_t RoutingPlatf::getOneLinkRoutes(){
460   return recursiveGetOneLinkRoutes(p_root);
461 }
462
463 xbt_dynar_t RoutingPlatf::recursiveGetOneLinkRoutes(As *rc)
464 {
465   xbt_dynar_t ret = xbt_dynar_new(sizeof(Onelink*), xbt_free_f);
466
467   //adding my one link routes
468   xbt_dynar_t onelink_mine = rc->getOneLinkRoutes();
469   if (onelink_mine)
470     xbt_dynar_merge(&ret,&onelink_mine);
471
472   //recursing
473   char *key;
474   xbt_dict_cursor_t cursor = NULL;
475   AS_t rc_child;
476   xbt_dict_foreach(rc->p_routingSons, cursor, key, rc_child) {
477     xbt_dynar_t onelink_child = recursiveGetOneLinkRoutes(rc_child);
478     if (onelink_child)
479       xbt_dynar_merge(&ret,&onelink_child);
480   }
481   return ret;
482 }
483
484 }
485 }
486
487 e_surf_network_element_type_t routing_get_network_element_type(const char *name)
488 {
489   simgrid::surf::NetCard *rc = sg_netcard_by_name_or_null(name);
490   if (rc)
491     return rc->getRcType();
492
493   return SURF_NETWORK_ELEMENT_NULL;
494 }
495
496 /** @brief create the root AS */
497 void routing_model_create( void *loopback)
498 {
499   routing_platf = new simgrid::surf::RoutingPlatf(loopback);
500 }
501
502 /* ************************************************************************** */
503 /* ************************* GENERIC PARSE FUNCTIONS ************************ */
504
505 void routing_cluster_add_backbone(void* bb) {
506   xbt_assert(current_routing->p_modelDesc == &routing_models[SURF_MODEL_CLUSTER],
507         "You have to be in model Cluster to use tag backbone!");
508   xbt_assert(!static_cast<simgrid::surf::AsCluster*>(current_routing)->p_backbone, "The backbone link is already defined!");
509   static_cast<simgrid::surf::AsCluster*>(current_routing)->p_backbone =
510     static_cast<simgrid::surf::Link*>(bb);
511   XBT_DEBUG("Add a backbone to AS '%s'", current_routing->p_name);
512 }
513
514 void sg_platf_new_cabinet(sg_platf_cabinet_cbarg_t cabinet)
515 {
516   int start, end, i;
517   char *groups , *host_id , *link_id = NULL;
518   unsigned int iter;
519   xbt_dynar_t radical_elements;
520   xbt_dynar_t radical_ends;
521
522   //Make all hosts
523   radical_elements = xbt_str_split(cabinet->radical, ",");
524   xbt_dynar_foreach(radical_elements, iter, groups) {
525
526     radical_ends = xbt_str_split(groups, "-");
527     start = surf_parse_get_int(xbt_dynar_get_as(radical_ends, 0, char *));
528
529     switch (xbt_dynar_length(radical_ends)) {
530     case 1:
531       end = start;
532       break;
533     case 2:
534       end = surf_parse_get_int(xbt_dynar_get_as(radical_ends, 1, char *));
535       break;
536     default:
537       surf_parse_error("Malformed radical");
538       break;
539     }
540     s_sg_platf_host_cbarg_t host = SG_PLATF_HOST_INITIALIZER;
541     memset(&host, 0, sizeof(host));
542     host.initiallyOn   = 1;
543     host.pstate        = 0;
544     host.speed_scale   = 1.0;
545     host.core_amount   = 1;
546
547     s_sg_platf_link_cbarg_t link = SG_PLATF_LINK_INITIALIZER;
548     memset(&link, 0, sizeof(link));
549     link.initiallyOn = 1;
550     link.policy    = SURF_LINK_FULLDUPLEX;
551     link.latency   = cabinet->lat;
552     link.bandwidth = cabinet->bw;
553
554     s_sg_platf_host_link_cbarg_t host_link = SG_PLATF_HOST_LINK_INITIALIZER;
555     memset(&host_link, 0, sizeof(host_link));
556
557     for (i = start; i <= end; i++) {
558       host_id                      = bprintf("%s%d%s",cabinet->prefix,i,cabinet->suffix);
559       link_id                      = bprintf("link_%s%d%s",cabinet->prefix,i,cabinet->suffix);
560       host.id                      = host_id;
561       link.id                      = link_id;
562       host.speed_peak = xbt_dynar_new(sizeof(double), NULL);
563       xbt_dynar_push(host.speed_peak,&cabinet->speed);
564       sg_platf_new_host(&host);
565       xbt_dynar_free(&host.speed_peak);
566       sg_platf_new_link(&link);
567
568       char* link_up       = bprintf("%s_UP",link_id);
569       char* link_down     = bprintf("%s_DOWN",link_id);
570       host_link.id        = host_id;
571       host_link.link_up   = link_up;
572       host_link.link_down = link_down;
573       sg_platf_new_netcard(&host_link);
574
575       free(host_id);
576       free(link_id);
577       free(link_up);
578       free(link_down);
579     }
580
581     xbt_dynar_free(&radical_ends);
582   }
583   xbt_dynar_free(&radical_elements);
584 }
585
586 void sg_platf_new_peer(sg_platf_peer_cbarg_t peer)
587 {
588   using simgrid::surf::NetCard;
589   using simgrid::surf::AsCluster;
590
591   char *host_id = NULL;
592   char *link_id = NULL;
593   char *router_id = NULL;
594
595   XBT_DEBUG(" ");
596   host_id = HOST_PEER(peer->id);
597   link_id = LINK_PEER(peer->id);
598   router_id = ROUTER_PEER(peer->id);
599
600   XBT_DEBUG("<AS id=\"%s\"\trouting=\"Cluster\">", peer->id);
601   s_sg_platf_AS_cbarg_t AS = SG_PLATF_AS_INITIALIZER;
602   AS.id                    = peer->id;
603   AS.routing               = A_surfxml_AS_routing_Cluster;
604   sg_platf_new_AS_begin(&AS);
605
606   current_routing->p_linkUpDownList = xbt_dynar_new(sizeof(s_surf_parsing_link_up_down_t),NULL);
607
608   XBT_DEBUG("<host\tid=\"%s\"\tpower=\"%f\"/>", host_id, peer->speed);
609   s_sg_platf_host_cbarg_t host = SG_PLATF_HOST_INITIALIZER;
610   memset(&host, 0, sizeof(host));
611   host.initiallyOn = 1;
612   host.id = host_id;
613
614   host.speed_peak = xbt_dynar_new(sizeof(double), NULL);
615   xbt_dynar_push(host.speed_peak,&peer->speed);
616   host.pstate = 0;
617   //host.power_peak = peer->power;
618   host.speed_scale = 1.0;
619   host.speed_trace = peer->availability_trace;
620   host.state_trace = peer->state_trace;
621   host.core_amount = 1;
622   sg_platf_new_host(&host);
623   xbt_dynar_free(&host.speed_peak);
624
625   s_sg_platf_link_cbarg_t link = SG_PLATF_LINK_INITIALIZER;
626   memset(&link, 0, sizeof(link));
627   link.initiallyOn = 1;
628   link.policy  = SURF_LINK_SHARED;
629   link.latency = peer->lat;
630
631   char* link_up = bprintf("%s_UP",link_id);
632   XBT_DEBUG("<link\tid=\"%s\"\tbw=\"%f\"\tlat=\"%f\"/>", link_up,
633             peer->bw_out, peer->lat);
634   link.id = link_up;
635   link.bandwidth = peer->bw_out;
636   sg_platf_new_link(&link);
637
638   char* link_down = bprintf("%s_DOWN",link_id);
639   XBT_DEBUG("<link\tid=\"%s\"\tbw=\"%f\"\tlat=\"%f\"/>", link_down,
640             peer->bw_in, peer->lat);
641   link.id = link_down;
642   link.bandwidth = peer->bw_in;
643   sg_platf_new_link(&link);
644
645   XBT_DEBUG("<host_link\tid=\"%s\"\tup=\"%s\"\tdown=\"%s\" />", host_id,link_up,link_down);
646   s_sg_platf_host_link_cbarg_t host_link = SG_PLATF_HOST_LINK_INITIALIZER;
647   memset(&host_link, 0, sizeof(host_link));
648   host_link.id        = host_id;
649   host_link.link_up   = link_up;
650   host_link.link_down = link_down;
651   sg_platf_new_netcard(&host_link);
652
653   XBT_DEBUG("<router id=\"%s\"/>", router_id);
654   s_sg_platf_router_cbarg_t router = SG_PLATF_ROUTER_INITIALIZER;
655   memset(&router, 0, sizeof(router));
656   router.id = router_id;
657   router.coord = peer->coord;
658   sg_platf_new_router(&router);
659   static_cast<AsCluster*>(current_routing)->p_router = static_cast<NetCard*>(xbt_lib_get_or_null(as_router_lib, router.id, ROUTING_ASR_LEVEL));
660
661   XBT_DEBUG("</AS>");
662   sg_platf_new_AS_end();
663   XBT_DEBUG(" ");
664
665   //xbt_dynar_free(&tab_elements_num);
666   free(router_id);
667   free(host_id);
668   free(link_id);
669   free(link_up);
670   free(link_down);
671 }
672
673 // static void routing_parse_Srandom(void)
674 // {
675 //   double mean, std, min, max, seed;
676 //   char *random_id = A_surfxml_random_id;
677 //   char *random_radical = A_surfxml_random_radical;
678 //   char *rd_name = NULL;
679 //   char *rd_value;
680 //   mean = surf_parse_get_double(A_surfxml_random_mean);
681 //   std = surf_parse_get_double(A_surfxml_random_std___deviation);
682 //   min = surf_parse_get_double(A_surfxml_random_min);
683 //   max = surf_parse_get_double(A_surfxml_random_max);
684 //   seed = surf_parse_get_double(A_surfxml_random_seed);
685
686 //   double res = 0;
687 //   int i = 0;
688 //   random_data_t random = xbt_new0(s_random_data_t, 1);
689 //   char *tmpbuf;
690
691 //   xbt_dynar_t radical_elements;
692 //   unsigned int iter;
693 //   char *groups;
694 //   int start, end;
695 //   xbt_dynar_t radical_ends;
696
697 //   switch (A_surfxml_random_generator) {
698 //   case AU_surfxml_random_generator:
699 //   case A_surfxml_random_generator_NONE:
700 //     random->generator = NONE;
701 //     break;
702 //   case A_surfxml_random_generator_DRAND48:
703 //     random->generator = DRAND48;
704 //     break;
705 //   case A_surfxml_random_generator_RAND:
706 //     random->generator = RAND;
707 //     break;
708 //   case A_surfxml_random_generator_RNGSTREAM:
709 //     random->generator = RNGSTREAM;
710 //     break;
711 //   default:
712 //     surf_parse_error("Invalid random generator");
713 //     break;
714 //   }
715 //   random->seed = seed;
716 //   random->min = min;
717 //   random->max = max;
718
719 //   /* Check user stupidities */
720 //   if (max < min)
721 //     THROWF(arg_error, 0, "random->max < random->min (%f < %f)", max, min);
722 //   if (mean < min)
723 //     THROWF(arg_error, 0, "random->mean < random->min (%f < %f)", mean, min);
724 //   if (mean > max)
725 //     THROWF(arg_error, 0, "random->mean > random->max (%f > %f)", mean, max);
726
727 //   /* normalize the mean and standard deviation before storing */
728 //   random->mean = (mean - min) / (max - min);
729 //   random->std = std / (max - min);
730
731 //   if (random->mean * (1 - random->mean) < random->std * random->std)
732 //     THROWF(arg_error, 0, "Invalid mean and standard deviation (%f and %f)",
733 //            random->mean, random->std);
734
735 //   XBT_DEBUG
736 //       ("id = '%s' min = '%f' max = '%f' mean = '%f' std_deviatinon = '%f' generator = '%d' seed = '%ld' radical = '%s'",
737 //        random_id, random->min, random->max, random->mean, random->std,
738 //        (int)random->generator, random->seed, random_radical);
739
740 //   if (!random_value)
741 //     random_value = xbt_dict_new_homogeneous(free);
742
743 //   if (!strcmp(random_radical, "")) {
744 //     res = random_generate(random);
745 //     rd_value = bprintf("%f", res);
746 //     xbt_dict_set(random_value, random_id, rd_value, NULL);
747 //   } else {
748 //     radical_elements = xbt_str_split(random_radical, ",");
749 //     xbt_dynar_foreach(radical_elements, iter, groups) {
750 //       radical_ends = xbt_str_split(groups, "-");
751 //       switch (xbt_dynar_length(radical_ends)) {
752 //       case 1:
753 //         xbt_assert(!xbt_dict_get_or_null(random_value, random_id),
754 //                    "Custom Random '%s' already exists !", random_id);
755 //         res = random_generate(random);
756 //         tmpbuf =
757 //             bprintf("%s%d", random_id,
758 //                     atoi(xbt_dynar_getfirst_as(radical_ends, char *)));
759 //         xbt_dict_set(random_value, tmpbuf, bprintf("%f", res), NULL);
760 //         xbt_free(tmpbuf);
761 //         break;
762
763 //       case 2:
764 //         start = surf_parse_get_int(xbt_dynar_get_as(radical_ends, 0, char *));
765 //         end = surf_parse_get_int(xbt_dynar_get_as(radical_ends, 1, char *));
766 //         for (i = start; i <= end; i++) {
767 //           xbt_assert(!xbt_dict_get_or_null(random_value, random_id),
768 //                      "Custom Random '%s' already exists !", bprintf("%s%d",
769 //                                                                     random_id,
770 //                                                                     i));
771 //           res = random_generate(random);
772 //           tmpbuf = bprintf("%s%d", random_id, i);
773 //           xbt_dict_set(random_value, tmpbuf, bprintf("%f", res), NULL);
774 //           xbt_free(tmpbuf);
775 //         }
776 //         break;
777 //       default:
778 //         XBT_CRITICAL("Malformed radical");
779 //         break;
780 //       }
781 //       res = random_generate(random);
782 //       rd_name = bprintf("%s_router", random_id);
783 //       rd_value = bprintf("%f", res);
784 //       xbt_dict_set(random_value, rd_name, rd_value, NULL);
785
786 //       xbt_dynar_free(&radical_ends);
787 //     }
788 //     free(rd_name);
789 //     xbt_dynar_free(&radical_elements);
790 //   }
791 // }
792
793 static void check_disk_attachment()
794 {
795   xbt_lib_cursor_t cursor;
796   char *key;
797   void **data;
798   simgrid::surf::NetCard *host_elm;
799   xbt_lib_foreach(storage_lib, cursor, key, data) {
800     if(xbt_lib_get_level(xbt_lib_get_elm_or_null(storage_lib, key), SURF_STORAGE_LEVEL) != NULL) {
801     simgrid::surf::Storage *storage = static_cast<simgrid::surf::Storage*>(xbt_lib_get_level(xbt_lib_get_elm_or_null(storage_lib, key), SURF_STORAGE_LEVEL));
802     host_elm = sg_netcard_by_name_or_null(storage->p_attach);
803     if(!host_elm)
804       surf_parse_error("Unable to attach storage %s: host %s doesn't exist.", storage->getName(), storage->p_attach);
805     }
806   }
807 }
808
809 void routing_register_callbacks()
810 {
811   simgrid::surf::on_postparse.connect(check_disk_attachment);
812
813   instr_routing_define_callbacks();
814 }
815
816 /**
817  * \brief Recursive function for finalize
818  *
819  * \param rc the source host name
820  *
821  * This fuction is call by "finalize". It allow to finalize the
822  * AS or routing components. It delete all the structures.
823  */
824 static void finalize_rec(simgrid::surf::As *as) {
825   xbt_dict_cursor_t cursor = NULL;
826   char *key;
827   AS_t elem;
828
829   xbt_dict_foreach(as->p_routingSons, cursor, key, elem) {
830     finalize_rec(elem);
831   }
832
833   delete as;;
834 }
835
836 /** \brief Frees all memory allocated by the routing module */
837 void routing_exit(void) {
838   delete routing_platf;
839 }
840
841 namespace simgrid {
842 namespace surf {
843
844   RoutingPlatf::RoutingPlatf(void *loopback)
845   : p_loopback(loopback)
846   {
847   }
848   RoutingPlatf::~RoutingPlatf()
849   {
850     xbt_dynar_free(&p_lastRoute);
851     finalize_rec(p_root);
852   }
853
854 }
855 }
856
857 AS_t surf_AS_get_routing_root() {
858   return routing_platf->p_root;
859 }
860
861 const char *surf_AS_get_name(simgrid::surf::As *as) {
862   return as->p_name;
863 }
864
865 static simgrid::surf::As *surf_AS_recursive_get_by_name(
866   simgrid::surf::As *current, const char * name)
867 {
868   xbt_dict_cursor_t cursor = NULL;
869   char *key;
870   AS_t elem;
871   simgrid::surf::As *tmp = NULL;
872
873   if(!strcmp(current->p_name, name))
874     return current;
875
876   xbt_dict_foreach(current->p_routingSons, cursor, key, elem) {
877     tmp = surf_AS_recursive_get_by_name(elem, name);
878     if(tmp != NULL ) {
879         break;
880     }
881   }
882   return tmp;
883 }
884
885 simgrid::surf::As *surf_AS_get_by_name(const char * name)
886 {
887   simgrid::surf::As *as = surf_AS_recursive_get_by_name(routing_platf->p_root, name);
888   if(as == NULL)
889     XBT_WARN("Impossible to find an AS with name %s, please check your input", name);
890   return as;
891 }
892
893 xbt_dict_t surf_AS_get_routing_sons(simgrid::surf::As *as)
894 {
895   return as->p_routingSons;
896 }
897
898 const char *surf_AS_get_model(simgrid::surf::As *as)
899 {
900   return as->p_modelDesc->name;
901 }
902
903 xbt_dynar_t surf_AS_get_hosts(simgrid::surf::As *as)
904 {
905   xbt_dynar_t elms = as->p_indexNetworkElm;
906   int count = xbt_dynar_length(elms);
907   xbt_dynar_t res =  xbt_dynar_new(sizeof(sg_host_t), NULL);
908   for (int index = 0; index < count; index++) {
909      sg_netcard_t relm =
910       xbt_dynar_get_as(elms, index, simgrid::surf::NetCard*);
911      sg_host_t delm = simgrid::s4u::Host::by_name_or_null(relm->getName());
912      if (delm!=NULL) {
913        xbt_dynar_push(res, &delm);
914      }
915   }
916   return res;
917 }
918
919 void surf_AS_get_graph(AS_t as, xbt_graph_t graph, xbt_dict_t nodes, xbt_dict_t edges) {
920   as->getGraph(graph, nodes, edges);
921 }