Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
dbc30ef44dbb81099b82cdc6fee674d209e2949b
[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 #include "surf_routing_cluster_torus.hpp"
11 #include "surf_routing_cluster_fat_tree.hpp"
12
13 #include "simgrid/platf_interface.h"    // platform creation API internal interface
14 #include "simgrid/sg_config.h"
15 #include "storage_interface.hpp"
16
17 #include "surf/surfxml_parse_values.h"
18
19 /*************
20  * Callbacks *
21  *************/
22
23 namespace simgrid {
24 namespace surf {
25
26 simgrid::surf::signal<void(simgrid::surf::RoutingEdge*)> routingEdgeCreatedCallbacks;
27 simgrid::surf::signal<void(simgrid::surf::As*)> asCreatedCallbacks;
28
29 }
30 }
31
32 /**
33  * @ingroup SURF_build_api
34  * @brief A library containing all known hosts
35  */
36 xbt_dict_t host_list;
37
38 int SURF_HOST_LEVEL;            //Surf host level
39 int COORD_HOST_LEVEL=0;         //Coordinates level
40 int NS3_HOST_LEVEL;             //host node for ns3
41
42 int MSG_FILE_LEVEL;             //Msg file level
43
44 int SIMIX_STORAGE_LEVEL;        //Simix storage level
45 int MSG_STORAGE_LEVEL;          //Msg storage level
46 int SD_STORAGE_LEVEL;           //Simdag storage level
47
48 xbt_lib_t as_router_lib;
49 int ROUTING_ASR_LEVEL;          //Routing level
50 int COORD_ASR_LEVEL;            //Coordinates level
51 int NS3_ASR_LEVEL;              //host node for ns3
52 int ROUTING_PROP_ASR_LEVEL;     //Where the properties are stored
53
54 static xbt_dict_t random_value = NULL;
55
56
57 /** @brief Retrieve a routing edge from its name
58  *
59  * Routing edges are either host and routers, whatever
60  */
61 simgrid::surf::RoutingEdge *sg_routing_edge_by_name_or_null(const char *name)
62 {
63   sg_host_t h = sg_host_by_name(name);
64   simgrid::surf::RoutingEdge *net_elm = h==NULL?NULL: sg_host_edge(h);
65   if (!net_elm)
66         net_elm = (simgrid::surf::RoutingEdge*) xbt_lib_get_or_null(as_router_lib, name, ROUTING_ASR_LEVEL);
67   return net_elm;
68 }
69
70 /* Global vars */
71 simgrid::surf::RoutingPlatf *routing_platf = NULL;
72
73 /* global parse functions */
74 extern xbt_dynar_t mount_list;
75
76 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(surf_route, surf, "Routing part of surf");
77
78 /** The current AS in the parsing */
79 static simgrid::surf::As *current_routing = NULL;
80 simgrid::surf::As* routing_get_current()
81 {
82   return current_routing;
83 }
84
85 // static void routing_parse_Srandom(void);        /* random bypass */
86
87 static void routing_parse_postparse(void);
88
89 /* this lines are only for replace use like index in the model table */
90 typedef enum {
91   SURF_MODEL_FULL = 0,
92   SURF_MODEL_FLOYD,
93   SURF_MODEL_DIJKSTRA,
94   SURF_MODEL_DIJKSTRACACHE,
95   SURF_MODEL_NONE,
96   SURF_MODEL_VIVALDI,
97   SURF_MODEL_CLUSTER,
98   SURF_MODEL_TORUS_CLUSTER,
99   SURF_MODEL_FAT_TREE_CLUSTER,
100 } e_routing_types;
101
102 struct s_model_type routing_models[] = {
103   {"Full",
104    "Full routing data (fast, large memory requirements, fully expressive)",
105    model_full_create, model_full_end},
106   {"Floyd",
107    "Floyd routing data (slow initialization, fast lookup, lesser memory requirements, shortest path routing only)",
108    model_floyd_create, model_floyd_end},
109   {"Dijkstra",
110    "Dijkstra routing data (fast initialization, slow lookup, small memory requirements, shortest path routing only)",
111    model_dijkstra_create, model_dijkstra_both_end},
112   {"DijkstraCache",
113    "Dijkstra routing data (fast initialization, fast lookup, small memory requirements, shortest path routing only)",
114    model_dijkstracache_create, model_dijkstra_both_end},
115   {"none", "No routing (Unless you know what you are doing, avoid using this mode in combination with a non Constant network model).",
116    model_none_create,  NULL},
117   {"Vivaldi", "Vivaldi routing",
118    model_vivaldi_create, NULL},
119   {"Cluster", "Cluster routing",
120    model_cluster_create, NULL},
121   {"Torus_Cluster", "Torus Cluster routing",
122    model_torus_cluster_create, NULL},
123   {"Fat_Tree_Cluster", "Fat Tree Cluster routing",
124    model_fat_tree_cluster_create, NULL},
125   {NULL, NULL, NULL, NULL}
126 };
127
128 /**
129  * \brief Add a "host_link" to the network element list
130  */
131 void sg_platf_new_host_link(sg_platf_host_link_cbarg_t host)
132 {
133   simgrid::surf::RoutingEdge *info = sg_host_edge(sg_host_by_name(host->id));
134   xbt_assert(info, "Host '%s' not found!", host->id);
135   xbt_assert(current_routing->p_modelDesc == &routing_models[SURF_MODEL_CLUSTER] ||
136       current_routing->p_modelDesc == &routing_models[SURF_MODEL_VIVALDI],
137       "You have to be in model Cluster to use tag host_link!");
138
139   s_surf_parsing_link_up_down_t link_up_down;
140   link_up_down.link_up = Link::byName(host->link_up);
141   link_up_down.link_down = Link::byName(host->link_down);
142
143   xbt_assert(link_up_down.link_up, "Link '%s' not found!",host->link_up);
144   xbt_assert(link_up_down.link_down, "Link '%s' not found!",host->link_down);
145
146   if(!current_routing->p_linkUpDownList)
147     current_routing->p_linkUpDownList = xbt_dynar_new(sizeof(s_surf_parsing_link_up_down_t),NULL);
148
149   // If dynar is is greater than edge id and if the host_link is already defined
150   if((int)xbt_dynar_length(current_routing->p_linkUpDownList) > info->getId() &&
151       xbt_dynar_get_as(current_routing->p_linkUpDownList, info->getId(), void*))
152         surf_parse_error("Host_link for '%s' is already defined!",host->id);
153
154   XBT_DEBUG("Push Host_link for host '%s' to position %d", info->getName(), info->getId());
155   xbt_dynar_set_as(current_routing->p_linkUpDownList, info->getId(), s_surf_parsing_link_up_down_t, link_up_down);
156 }
157
158 /**
159  * \brief Add a "host" to the network element list
160  */
161 simgrid::surf::RoutingEdge *routing_add_host(
162   simgrid::surf::As* current_routing, sg_platf_host_cbarg_t host)
163 {
164   if (current_routing->p_hierarchy == SURF_ROUTING_NULL)
165     current_routing->p_hierarchy = SURF_ROUTING_BASE;
166   xbt_assert(!sg_host_by_name(host->id),
167                      "Reading a host, processing unit \"%s\" already exists", host->id);
168
169   simgrid::surf::RoutingEdge *routingEdge =
170     new simgrid::surf::RoutingEdgeImpl(xbt_strdup(host->id),
171                                                     -1,
172                                                     SURF_NETWORK_ELEMENT_HOST,
173                                                     current_routing);
174   routingEdge->setId(current_routing->parsePU(routingEdge));
175   sg_host_t h = sg_host_by_name_or_create(host->id);
176   sg_host_edge_set(h, routingEdge);
177   XBT_DEBUG("Having set name '%s' id '%d'", host->id, routingEdge->getId());
178   simgrid::surf::routingEdgeCreatedCallbacks(routingEdge);
179
180   if(mount_list){
181     xbt_lib_set(storage_lib, host->id, ROUTING_STORAGE_HOST_LEVEL, (void *) mount_list);
182     mount_list = NULL;
183   }
184
185   if (host->coord && strcmp(host->coord, "")) {
186     unsigned int cursor;
187     char*str;
188
189     if (!COORD_HOST_LEVEL)
190       xbt_die ("To use host coordinates, please add --cfg=network/coordinates:yes to your command line");
191     /* Pre-parse the host coordinates -- FIXME factorize with routers by overloading the routing->parse_PU function*/
192     xbt_dynar_t ctn_str = xbt_str_split_str(host->coord, " ");
193     xbt_dynar_t ctn = xbt_dynar_new(sizeof(double),NULL);
194     xbt_dynar_foreach(ctn_str,cursor, str) {
195       double val = atof(str);
196       xbt_dynar_push(ctn,&val);
197     }
198     xbt_dynar_shrink(ctn, 0);
199     xbt_dynar_free(&ctn_str);
200     h->extension_set(COORD_HOST_LEVEL, (void *) ctn);
201     XBT_DEBUG("Having set host coordinates for '%s'",host->id);
202   }
203
204   return routingEdge;
205 }
206
207 /**
208  * \brief Store the ASroute by calling the set_ASroute function of the current routing component
209  */
210 static void parse_E_ASroute(sg_platf_route_cbarg_t ASroute)
211 {
212   /*FIXME:REMOVE:xbt_assert(current_routing->parse_ASroute,
213              "no defined method \"set_ASroute\" in \"%s\"",
214              current_routing->name);*/
215   current_routing->parseASroute(ASroute);
216 }
217
218 void sg_platf_new_trace(sg_platf_trace_cbarg_t trace)
219 {
220   tmgr_trace_t tmgr_trace;
221   if (!trace->file || strcmp(trace->file, "") != 0) {
222     tmgr_trace = tmgr_trace_new_from_file(trace->file);
223   } else if (strcmp(trace->pc_data, "") == 0) {
224     tmgr_trace = NULL;
225   } else {
226     tmgr_trace =
227           tmgr_trace_new_from_string(trace->id, trace->pc_data,
228                                      trace->periodicity);
229   }
230   xbt_dict_set(traces_set_list, trace->id, (void *) tmgr_trace, NULL);
231 }
232
233 void sg_platf_trace_connect(sg_platf_trace_connect_cbarg_t trace_connect)
234 {
235   xbt_assert(xbt_dict_get_or_null
236               (traces_set_list, trace_connect->trace),
237               "Cannot connect trace %s to %s: trace unknown",
238               trace_connect->trace,
239               trace_connect->element);
240
241   switch (trace_connect->kind) {
242   case SURF_TRACE_CONNECT_KIND_HOST_AVAIL:
243     xbt_dict_set(trace_connect_list_host_avail,
244         trace_connect->trace,
245         xbt_strdup(trace_connect->element), NULL);
246     break;
247   case SURF_TRACE_CONNECT_KIND_POWER:
248     xbt_dict_set(trace_connect_list_power, trace_connect->trace,
249         xbt_strdup(trace_connect->element), NULL);
250     break;
251   case SURF_TRACE_CONNECT_KIND_LINK_AVAIL:
252     xbt_dict_set(trace_connect_list_link_avail,
253         trace_connect->trace,
254         xbt_strdup(trace_connect->element), NULL);
255     break;
256   case SURF_TRACE_CONNECT_KIND_BANDWIDTH:
257     xbt_dict_set(trace_connect_list_bandwidth,
258         trace_connect->trace,
259         xbt_strdup(trace_connect->element), NULL);
260     break;
261   case SURF_TRACE_CONNECT_KIND_LATENCY:
262     xbt_dict_set(trace_connect_list_latency, trace_connect->trace,
263         xbt_strdup(trace_connect->element), NULL);
264     break;
265   default:
266         surf_parse_error("Cannot connect trace %s to %s: kind of trace unknown",
267         trace_connect->trace, trace_connect->element);
268     break;
269   }
270 }
271
272 /**
273  * \brief Make a new routing component to the platform
274  *
275  * Add a new autonomous system to the platform. Any elements (such as host,
276  * router or sub-AS) added after this call and before the corresponding call
277  * to sg_platf_new_AS_close() will be added to this AS.
278  *
279  * Once this function was called, the configuration concerning the used
280  * models cannot be changed anymore.
281  *
282  * @param AS_id name of this autonomous system. Must be unique in the platform
283  * @param wanted_routing_type one of Full, Floyd, Dijkstra or similar. Full list in the variable routing_models, in src/surf/surf_routing.c
284  */
285 void routing_AS_begin(sg_platf_AS_cbarg_t AS)
286 {
287   XBT_DEBUG("routing_AS_begin");
288   routing_model_description_t model = NULL;
289
290   xbt_assert(!xbt_lib_get_or_null
291              (as_router_lib, AS->id, ROUTING_ASR_LEVEL),
292              "The AS \"%s\" already exists", AS->id);
293
294   _sg_cfg_init_status = 2; /* horrible hack: direct access to the global
295                             * controlling the level of configuration to prevent
296                             * any further config */
297
298   /* search the routing model */
299   switch(AS->routing){
300     case A_surfxml_AS_routing_Cluster:               model = &routing_models[SURF_MODEL_CLUSTER];break;
301     case A_surfxml_AS_routing_Cluster___torus:       model = &routing_models[SURF_MODEL_TORUS_CLUSTER];break;
302     case A_surfxml_AS_routing_Cluster___fat___tree:  model = &routing_models[SURF_MODEL_FAT_TREE_CLUSTER];break;
303     case A_surfxml_AS_routing_Dijkstra:              model = &routing_models[SURF_MODEL_DIJKSTRA];break;
304     case A_surfxml_AS_routing_DijkstraCache:         model = &routing_models[SURF_MODEL_DIJKSTRACACHE];break;
305     case A_surfxml_AS_routing_Floyd:                 model = &routing_models[SURF_MODEL_FLOYD];break;
306     case A_surfxml_AS_routing_Full:                  model = &routing_models[SURF_MODEL_FULL];break;
307     case A_surfxml_AS_routing_None:                  model = &routing_models[SURF_MODEL_NONE];break;
308     case A_surfxml_AS_routing_Vivaldi:               model = &routing_models[SURF_MODEL_VIVALDI];break;
309     default: xbt_die("Not a valid model!!!");
310     break;
311   }
312
313   /* make a new routing component */
314   simgrid::surf::As *new_as = model->create();
315
316   new_as->p_modelDesc = model;
317   new_as->p_hierarchy = SURF_ROUTING_NULL;
318   new_as->p_name = xbt_strdup(AS->id);
319
320   simgrid::surf::RoutingEdge *info =
321     new simgrid::surf::RoutingEdgeImpl(xbt_strdup(new_as->p_name),
322                                             -1,
323                                             SURF_NETWORK_ELEMENT_AS,
324                                             current_routing);
325   if (current_routing == NULL && routing_platf->p_root == NULL) {
326
327     /* it is the first one */
328     new_as->p_routingFather = NULL;
329     routing_platf->p_root = new_as;
330     info->setId(-1);
331   } else if (current_routing != NULL && routing_platf->p_root != NULL) {
332
333     xbt_assert(!xbt_dict_get_or_null
334                (current_routing->p_routingSons, AS->id),
335                "The AS \"%s\" already exists", AS->id);
336     /* it is a part of the tree */
337     new_as->p_routingFather = current_routing;
338     /* set the father behavior */
339     if (current_routing->p_hierarchy == SURF_ROUTING_NULL)
340       current_routing->p_hierarchy = SURF_ROUTING_RECURSIVE;
341     /* add to the sons dictionary */
342     xbt_dict_set(current_routing->p_routingSons, AS->id,
343                  (void *) new_as, NULL);
344     /* add to the father element list */
345     info->setId(current_routing->parseAS(info));
346   } else {
347     THROWF(arg_error, 0, "All defined components must belong to a AS");
348   }
349
350   xbt_lib_set(as_router_lib, info->getName(), ROUTING_ASR_LEVEL,
351               (void *) info);
352   XBT_DEBUG("Having set name '%s' id '%d'", new_as->p_name, info->getId());
353
354   /* set the new current component of the tree */
355   current_routing = new_as;
356   current_routing->p_netElem = info;
357
358   simgrid::surf::routingEdgeCreatedCallbacks(info);
359   simgrid::surf::asCreatedCallbacks(new_as);
360 }
361
362 /**
363  * \brief Specify that the current description of AS is finished
364  *
365  * Once you've declared all the content of your AS, you have to close
366  * it with this call. Your AS is not usable until you call this function.
367  *
368  * @fixme: this call is not as robust as wanted: bad things WILL happen
369  * if you call it twice for the same AS, or if you forget calling it, or
370  * even if you add stuff to a closed AS
371  *
372  */
373 void routing_AS_end()
374 {
375
376   if (current_routing == NULL) {
377     THROWF(arg_error, 0, "Close an AS, but none was under construction");
378   } else {
379     if (current_routing->p_modelDesc->end)
380       current_routing->p_modelDesc->end(current_routing);
381     current_routing = current_routing->p_routingFather;
382   }
383 }
384
385 /* Aux Business methods */
386
387 /**
388  * \brief Get the AS father and the first elements of the chain
389  *
390  * \param src the source host name
391  * \param dst the destination host name
392  *
393  * Get the common father of the to processing units, and the first different
394  * father in the chain
395  */
396 static void elements_father(sg_routing_edge_t src, sg_routing_edge_t dst,
397                             AS_t * res_father,
398                             AS_t * res_src,
399                             AS_t * res_dst)
400 {
401   xbt_assert(src && dst, "bad parameters for \"elements_father\" method");
402 #define ELEMENTS_FATHER_MAXDEPTH 16     /* increase if it is not enough */
403   simgrid::surf::As *src_as, *dst_as;
404   simgrid::surf::As *path_src[ELEMENTS_FATHER_MAXDEPTH];
405   simgrid::surf::As *path_dst[ELEMENTS_FATHER_MAXDEPTH];
406   int index_src = 0;
407   int index_dst = 0;
408   simgrid::surf::As *current;
409   simgrid::surf::As *current_src;
410   simgrid::surf::As *current_dst;
411   simgrid::surf::As *father;
412
413   /* (1) find the as where the src and dst are located */
414   sg_routing_edge_t src_data = src;
415   sg_routing_edge_t dst_data = dst;
416   src_as = src_data->getRcComponent();
417   dst_as = dst_data->getRcComponent();
418 #ifndef NDEBUG
419   char* src_name = src_data->getName();
420   char* dst_name = dst_data->getName();
421 #endif
422
423   xbt_assert(src_as && dst_as,
424              "Ask for route \"from\"(%s) or \"to\"(%s) no found", src_name, dst_name);
425
426   /* (2) find the path to the root routing component */
427   for (current = src_as; current != NULL; current = current->p_routingFather) {
428     if (index_src >= ELEMENTS_FATHER_MAXDEPTH)
429       xbt_die("ELEMENTS_FATHER_MAXDEPTH should be increased for path_src");
430     path_src[index_src++] = current;
431   }
432   for (current = dst_as; current != NULL; current = current->p_routingFather) {
433     if (index_dst >= ELEMENTS_FATHER_MAXDEPTH)
434       xbt_die("ELEMENTS_FATHER_MAXDEPTH should be increased for path_dst");
435     path_dst[index_dst++] = current;
436   }
437
438   /* (3) find the common father */
439   do {
440     current_src = path_src[--index_src];
441     current_dst = path_dst[--index_dst];
442   } while (index_src > 0 && index_dst > 0 && current_src == current_dst);
443
444   /* (4) they are not in the same routing component, make the path */
445   if (current_src == current_dst)
446     father = current_src;
447   else
448     father = path_src[index_src + 1];
449
450   /* (5) result generation */
451   *res_father = father;         /* first the common father of src and dst */
452   *res_src = current_src;       /* second the first different father of src */
453   *res_dst = current_dst;       /* three  the first different father of dst */
454
455 #undef ELEMENTS_FATHER_MAXDEPTH
456 }
457
458 /* Global Business methods */
459
460 /**
461  * \brief Recursive function for get_route_latency
462  *
463  * \param src the source host name
464  * \param dst the destination host name
465  * \param *route the route where the links are stored. It is either NULL or a ready to use dynar
466  * \param *latency the latency, if needed
467  *
468  * This function is called by "get_route" and "get_latency". It allows to walk
469  * recursively through the ASes tree.
470  */
471 static void _get_route_and_latency(
472   simgrid::surf::RoutingEdge *src, simgrid::surf::RoutingEdge *dst,
473   xbt_dynar_t * links, double *latency)
474 {
475   s_sg_platf_route_cbarg_t route = SG_PLATF_ROUTE_INITIALIZER;
476   memset(&route,0,sizeof(route));
477
478   xbt_assert(src && dst, "bad parameters for \"_get_route_latency\" method");
479   XBT_DEBUG("Solve route/latency  \"%s\" to \"%s\"", src->getName(), dst->getName());
480
481   /* Find how src and dst are interconnected */
482   simgrid::surf::As *common_father, *src_father, *dst_father;
483   elements_father(src, dst, &common_father, &src_father, &dst_father);
484   XBT_DEBUG("elements_father: common father '%s' src_father '%s' dst_father '%s'",
485       common_father->p_name, src_father->p_name, dst_father->p_name);
486
487   /* Check whether a direct bypass is defined */
488   sg_platf_route_cbarg_t e_route_bypass = NULL;
489   //FIXME:REMOVE:if (common_father->get_bypass_route)
490
491   e_route_bypass = common_father->getBypassRoute(src, dst, latency);
492
493   /* Common ancestor is kind enough to declare a bypass route from src to dst -- use it and bail out */
494   if (e_route_bypass) {
495     xbt_dynar_merge(links, &e_route_bypass->link_list);
496     generic_free_route(e_route_bypass);
497     return;
498   }
499
500   /* If src and dst are in the same AS, life is good */
501   if (src_father == dst_father) {       /* SURF_ROUTING_BASE */
502     route.link_list = *links;
503     common_father->getRouteAndLatency(src, dst, &route, latency);
504     // if vivaldi latency+=vivaldi(src,dst)
505     return;
506   }
507
508   /* Not in the same AS, no bypass. We'll have to find our path between the ASes recursively*/
509
510   route.link_list = xbt_dynar_new(sizeof(sg_routing_link_t), NULL);
511   // Find the net_card corresponding to father
512   simgrid::surf::RoutingEdge *src_father_net_elm = src_father->p_netElem;
513   simgrid::surf::RoutingEdge *dst_father_net_elm = dst_father->p_netElem;
514
515   common_father->getRouteAndLatency(src_father_net_elm, dst_father_net_elm,
516                                     &route, latency);
517
518   xbt_assert((route.gw_src != NULL) && (route.gw_dst != NULL),
519       "bad gateways for route from \"%s\" to \"%s\"", src->getName(), dst->getName());
520
521   sg_routing_edge_t src_gateway_net_elm = route.gw_src;
522   sg_routing_edge_t dst_gateway_net_elm = route.gw_dst;
523
524   /* If source gateway is not our source, we have to recursively find our way up to this point */
525   if (src != src_gateway_net_elm)
526     _get_route_and_latency(src, src_gateway_net_elm, links, latency);
527   xbt_dynar_merge(links, &route.link_list);
528
529   /* If dest gateway is not our destination, we have to recursively find our way from this point */
530   if (dst_gateway_net_elm != dst)
531     _get_route_and_latency(dst_gateway_net_elm, dst, links, latency);
532
533   // if vivaldi latency+=vivaldi(src_gateway,dst_gateway)
534 }
535
536 AS_t surf_platf_get_root(routing_platf_t platf){
537   return platf->p_root;
538 }
539
540 e_surf_network_element_type_t surf_routing_edge_get_rc_type(sg_routing_edge_t edge){
541   return edge->getRcType();
542 }
543
544 namespace simgrid {
545 namespace surf {
546
547 /**
548  * \brief Find a route between hosts
549  *
550  * \param src the network_element_t for src host
551  * \param dst the network_element_t for dst host
552  * \param route where to store the list of links.
553  *              If *route=NULL, create a short lived dynar. Else, fill the provided dynar
554  * \param latency where to store the latency experienced on the path (or NULL if not interested)
555  *                It is the caller responsability to initialize latency to 0 (we add to provided route)
556  * \pre route!=NULL
557  *
558  * walk through the routing components tree and find a route between hosts
559  * by calling the differents "get_route" functions in each routing component.
560  */
561 void RoutingPlatf::getRouteAndLatency(
562   simgrid::surf::RoutingEdge *src, simgrid::surf::RoutingEdge *dst,
563   xbt_dynar_t* route, double *latency)
564 {
565   XBT_DEBUG("routing_get_route_and_latency from %s to %s", src->getName(), dst->getName());
566   if (!*route) {
567     xbt_dynar_reset(routing_platf->p_lastRoute);
568     *route = routing_platf->p_lastRoute;
569   }
570
571   _get_route_and_latency(src, dst, route, latency);
572
573   xbt_assert(!latency || *latency >= 0.0,
574              "negative latency on route between \"%s\" and \"%s\"", src->getName(), dst->getName());
575 }
576
577 xbt_dynar_t RoutingPlatf::getOneLinkRoutes(){
578   return recursiveGetOneLinkRoutes(p_root);
579 }
580
581 xbt_dynar_t RoutingPlatf::recursiveGetOneLinkRoutes(As *rc)
582 {
583   xbt_dynar_t ret = xbt_dynar_new(sizeof(Onelink*), xbt_free_f);
584
585   //adding my one link routes
586   xbt_dynar_t onelink_mine = rc->getOneLinkRoutes();
587   if (onelink_mine)
588     xbt_dynar_merge(&ret,&onelink_mine);
589
590   //recursing
591   char *key;
592   xbt_dict_cursor_t cursor = NULL;
593   AS_t rc_child;
594   xbt_dict_foreach(rc->p_routingSons, cursor, key, rc_child) {
595     xbt_dynar_t onelink_child = recursiveGetOneLinkRoutes(rc_child);
596     if (onelink_child)
597       xbt_dynar_merge(&ret,&onelink_child);
598   }
599   return ret;
600 }
601
602 }
603 }
604
605 e_surf_network_element_type_t routing_get_network_element_type(const char *name)
606 {
607   simgrid::surf::RoutingEdge *rc = sg_routing_edge_by_name_or_null(name);
608   if (rc)
609     return rc->getRcType();
610
611   return SURF_NETWORK_ELEMENT_NULL;
612 }
613
614 /**
615  * \brief Generic method: create the global routing schema
616  *
617  * Make a global routing structure and set all the parsing functions.
618  */
619 void routing_model_create( void *loopback)
620 {
621   /* config the uniq global routing */
622   routing_platf = new simgrid::surf::RoutingPlatf();
623   routing_platf->p_root = NULL;
624   routing_platf->p_loopback = loopback;
625   routing_platf->p_lastRoute = xbt_dynar_new(sizeof(sg_routing_link_t),NULL);
626   /* no current routing at moment */
627   current_routing = NULL;
628 }
629
630
631 /* ************************************************** */
632 /* ********** PATERN FOR NEW ROUTING **************** */
633
634 /* The minimal configuration of a new routing model need the next functions,
635  * also you need to set at the start of the file, the new model in the model
636  * list. Remember keep the null ending of the list.
637  */
638 /*** Routing model structure ***/
639 // typedef struct {
640 //   s_routing_component_t generic_routing;
641 //   /* things that your routing model need */
642 // } s_routing_component_NEW_t,*routing_component_NEW_t;
643
644 /*** Parse routing model functions ***/
645 // static void model_NEW_set_processing_unit(routing_component_t rc, const char* name) {}
646 // static void model_NEW_set_autonomous_system(routing_component_t rc, const char* name) {}
647 // static void model_NEW_set_route(routing_component_t rc, const char* src, const char* dst, route_t route) {}
648 // static void model_NEW_set_ASroute(routing_component_t rc, const char* src, const char* dst, route_extended_t route) {}
649 // static void model_NEW_set_bypassroute(routing_component_t rc, const char* src, const char* dst, route_extended_t e_route) {}
650
651 /*** Business methods ***/
652 // static route_extended_t NEW_get_route(routing_component_t rc, const char* src,const char* dst) {return NULL;}
653 // static route_extended_t NEW_get_bypass_route(routing_component_t rc, const char* src,const char* dst) {return NULL;}
654 // static void NEW_finalize(routing_component_t rc) { xbt_free(rc);}
655
656 /*** Creation routing model functions ***/
657 // static void* model_NEW_create(void) {
658 //   routing_component_NEW_t new_component =  xbt_new0(s_routing_component_NEW_t,1);
659 //   new_component->generic_routing.set_processing_unit = model_NEW_set_processing_unit;
660 //   new_component->generic_routing.set_autonomous_system = model_NEW_set_autonomous_system;
661 //   new_component->generic_routing.set_route = model_NEW_set_route;
662 //   new_component->generic_routing.set_ASroute = model_NEW_set_ASroute;
663 //   new_component->generic_routing.set_bypassroute = model_NEW_set_bypassroute;
664 //   new_component->generic_routing.get_route = NEW_get_route;
665 //   new_component->generic_routing.get_bypass_route = NEW_get_bypass_route;
666 //   new_component->generic_routing.finalize = NEW_finalize;
667 //   /* initialization of internal structures */
668 //   return new_component;
669 // } /* mandatory */
670 // static void  model_NEW_load(void) {}   /* mandatory */
671 // static void  model_NEW_unload(void) {} /* mandatory */
672 // static void  model_NEW_end(void) {}    /* mandatory */
673
674 /* ************************************************************************** */
675 /* ************************* GENERIC PARSE FUNCTIONS ************************ */
676
677 void routing_cluster_add_backbone(void* bb) {
678   xbt_assert(current_routing->p_modelDesc == &routing_models[SURF_MODEL_CLUSTER],
679         "You have to be in model Cluster to use tag backbone!");
680   xbt_assert(!static_cast<simgrid::surf::AsCluster*>(current_routing)->p_backbone, "The backbone link is already defined!");
681   static_cast<simgrid::surf::AsCluster*>(current_routing)->p_backbone =
682     static_cast<simgrid::surf::Link*>(bb);
683   XBT_DEBUG("Add a backbone to AS '%s'", current_routing->p_name);
684 }
685
686 void sg_platf_new_cabinet(sg_platf_cabinet_cbarg_t cabinet)
687 {
688   int start, end, i;
689   char *groups , *host_id , *link_id = NULL;
690   unsigned int iter;
691   xbt_dynar_t radical_elements;
692   xbt_dynar_t radical_ends;
693
694   //Make all hosts
695   radical_elements = xbt_str_split(cabinet->radical, ",");
696   xbt_dynar_foreach(radical_elements, iter, groups) {
697
698     radical_ends = xbt_str_split(groups, "-");
699     start = surf_parse_get_int(xbt_dynar_get_as(radical_ends, 0, char *));
700
701     switch (xbt_dynar_length(radical_ends)) {
702     case 1:
703       end = start;
704       break;
705     case 2:
706       end = surf_parse_get_int(xbt_dynar_get_as(radical_ends, 1, char *));
707       break;
708     default:
709       surf_parse_error("Malformed radical");
710       break;
711     }
712     s_sg_platf_host_cbarg_t host = SG_PLATF_HOST_INITIALIZER;
713     memset(&host, 0, sizeof(host));
714     host.initial_state = SURF_RESOURCE_ON;
715     host.pstate        = 0;
716     host.speed_scale   = 1.0;
717     host.core_amount   = 1;
718
719     s_sg_platf_link_cbarg_t link = SG_PLATF_LINK_INITIALIZER;
720     memset(&link, 0, sizeof(link));
721     link.state     = SURF_RESOURCE_ON;
722     link.policy    = SURF_LINK_FULLDUPLEX;
723     link.latency   = cabinet->lat;
724     link.bandwidth = cabinet->bw;
725
726     s_sg_platf_host_link_cbarg_t host_link = SG_PLATF_HOST_LINK_INITIALIZER;
727     memset(&host_link, 0, sizeof(host_link));
728
729     for (i = start; i <= end; i++) {
730       host_id                      = bprintf("%s%d%s",cabinet->prefix,i,cabinet->suffix);
731       link_id                      = bprintf("link_%s%d%s",cabinet->prefix,i,cabinet->suffix);
732       host.id                      = host_id;
733       link.id                      = link_id;
734       host.speed_peak = xbt_dynar_new(sizeof(double), NULL);
735       xbt_dynar_push(host.speed_peak,&cabinet->speed);
736       sg_platf_new_host(&host);
737       xbt_dynar_free(&host.speed_peak);
738       sg_platf_new_link(&link);
739
740       char* link_up       = bprintf("%s_UP",link_id);
741       char* link_down     = bprintf("%s_DOWN",link_id);
742       host_link.id        = host_id;
743       host_link.link_up   = link_up;
744       host_link.link_down = link_down;
745       sg_platf_new_host_link(&host_link);
746
747       free(host_id);
748       free(link_id);
749       free(link_up);
750       free(link_down);
751     }
752
753     xbt_dynar_free(&radical_ends);
754   }
755   xbt_dynar_free(&radical_elements);
756 }
757
758 void routing_new_cluster(sg_platf_cluster_cbarg_t cluster)
759 {
760   using simgrid::surf::AsCluster;
761   using simgrid::surf::AsClusterTorus;
762   using simgrid::surf::AsClusterFatTree;
763
764   char *host_id, *groups, *link_id = NULL;
765   xbt_dict_t patterns = NULL;
766   int rankId=0;
767
768   s_sg_platf_host_cbarg_t host = SG_PLATF_HOST_INITIALIZER;
769   s_sg_platf_link_cbarg_t link = SG_PLATF_LINK_INITIALIZER;
770
771   unsigned int iter;
772   int start, end, i;
773   xbt_dynar_t radical_elements;
774   xbt_dynar_t radical_ends;
775
776   if ((cluster->availability_trace && strcmp(cluster->availability_trace, ""))
777       || (cluster->state_trace && strcmp(cluster->state_trace, ""))) {
778     patterns = xbt_dict_new_homogeneous(xbt_free_f);
779     xbt_dict_set(patterns, "id", xbt_strdup(cluster->id), NULL);
780     xbt_dict_set(patterns, "prefix", xbt_strdup(cluster->prefix), NULL);
781     xbt_dict_set(patterns, "suffix", xbt_strdup(cluster->suffix), NULL);
782   }
783
784   /* parse the topology attribute. If we are not in a flat cluster,
785    * switch to the right mode and initialize the routing with
786    * the parameters in topo_parameters attribute
787    */
788   s_sg_platf_AS_cbarg_t AS = SG_PLATF_AS_INITIALIZER;
789   AS.id = cluster->id;
790
791   if(cluster->topology == SURF_CLUSTER_TORUS){
792     XBT_DEBUG("<AS id=\"%s\"\trouting=\"Torus_Cluster\">", cluster->id);
793     AS.routing = A_surfxml_AS_routing_Cluster___torus;
794     sg_platf_new_AS_begin(&AS);
795     ((AsClusterTorus*)current_routing)->parse_specific_arguments(cluster);
796   }
797   else if (cluster->topology == SURF_CLUSTER_FAT_TREE) {
798     XBT_DEBUG("<AS id=\"%s\"\trouting=\"Fat_Tree_Cluster\">", cluster->id);
799     AS.routing = A_surfxml_AS_routing_Cluster___fat___tree;
800     sg_platf_new_AS_begin(&AS);
801     ((AsClusterFatTree*)current_routing)->parse_specific_arguments(cluster);
802   }
803
804   else{
805     XBT_DEBUG("<AS id=\"%s\"\trouting=\"Cluster\">", cluster->id);
806     AS.routing = A_surfxml_AS_routing_Cluster;
807     sg_platf_new_AS_begin(&AS);
808   }
809
810   if(cluster->loopback_bw!=0 || cluster->loopback_lat!=0){
811       ((AsCluster*)current_routing)->p_nb_links_per_node++;
812       ((AsCluster*)current_routing)->p_has_loopback=1;
813   }
814
815   if(cluster->limiter_link!=0){
816       ((AsCluster*)current_routing)->p_nb_links_per_node++;
817       ((AsCluster*)current_routing)->p_has_limiter=1;
818   }
819
820
821
822   current_routing->p_linkUpDownList
823             = xbt_dynar_new(sizeof(s_surf_parsing_link_up_down_t),NULL);
824
825   //Make all hosts
826   radical_elements = xbt_str_split(cluster->radical, ",");
827   xbt_dynar_foreach(radical_elements, iter, groups) {
828
829     radical_ends = xbt_str_split(groups, "-");
830     start = surf_parse_get_int(xbt_dynar_get_as(radical_ends, 0, char *));
831
832     switch (xbt_dynar_length(radical_ends)) {
833     case 1:
834       end = start;
835       break;
836     case 2:
837       end = surf_parse_get_int(xbt_dynar_get_as(radical_ends, 1, char *));
838       break;
839     default:
840       surf_parse_error("Malformed radical");
841       break;
842     }
843     for (i = start; i <= end; i++) {
844       host_id =
845           bprintf("%s%d%s", cluster->prefix, i, cluster->suffix);
846       link_id = bprintf("%s_link_%d", cluster->id, i);
847
848       XBT_DEBUG("<host\tid=\"%s\"\tpower=\"%f\">", host_id, cluster->speed);
849
850       memset(&host, 0, sizeof(host));
851       host.id = host_id;
852       if ((cluster->properties != NULL) && (!xbt_dict_is_empty(cluster->properties))) {
853           xbt_dict_cursor_t cursor=NULL;
854           char *key,*data;
855           host.properties = xbt_dict_new();
856
857           xbt_dict_foreach(cluster->properties,cursor,key,data) {
858                   xbt_dict_set(host.properties, key, xbt_strdup(data),free);
859           }
860       }
861       if (cluster->availability_trace && strcmp(cluster->availability_trace, "")) {
862         xbt_dict_set(patterns, "radical", bprintf("%d", i), NULL);
863         char *avail_file = xbt_str_varsubst(cluster->availability_trace, patterns);
864         XBT_DEBUG("\tavailability_file=\"%s\"", avail_file);
865         host.speed_trace = tmgr_trace_new_from_file(avail_file);
866         xbt_free(avail_file);
867       } else {
868         XBT_DEBUG("\tavailability_file=\"\"");
869       }
870
871       if (cluster->state_trace && strcmp(cluster->state_trace, "")) {
872         char *avail_file = xbt_str_varsubst(cluster->state_trace, patterns);
873         XBT_DEBUG("\tstate_file=\"%s\"", avail_file);
874         host.state_trace = tmgr_trace_new_from_file(avail_file);
875         xbt_free(avail_file);
876       } else {
877         XBT_DEBUG("\tstate_file=\"\"");
878       }
879
880       host.speed_peak = xbt_dynar_new(sizeof(double), NULL);
881       xbt_dynar_push(host.speed_peak,&cluster->speed);
882       host.pstate = 0;
883
884       //host.power_peak = cluster->power;
885       host.speed_scale = 1.0;
886       host.core_amount = cluster->core_amount;
887       host.initial_state = SURF_RESOURCE_ON;
888       host.coord = "";
889       sg_platf_new_host(&host);
890       xbt_dynar_free(&host.speed_peak);
891       XBT_DEBUG("</host>");
892
893       XBT_DEBUG("<link\tid=\"%s\"\tbw=\"%f\"\tlat=\"%f\"/>", link_id,
894                 cluster->bw, cluster->lat);
895
896
897       s_surf_parsing_link_up_down_t info_lim, info_loop;
898       // All links are saved in a matrix;
899       // every row describes a single node; every node
900       // may have multiple links.
901       // the first column may store a link from x to x if p_has_loopback is set
902       // the second column may store a limiter link if p_has_limiter is set
903       // other columns are to store one or more link for the node
904
905       //add a loopback link
906       if(cluster->loopback_bw!=0 || cluster->loopback_lat!=0){
907         char *tmp_link = bprintf("%s_loopback", link_id);
908         XBT_DEBUG("<loopback\tid=\"%s\"\tbw=\"%f\"/>", tmp_link,
909                 cluster->limiter_link);
910
911
912         memset(&link, 0, sizeof(link));
913         link.id        = tmp_link;
914         link.bandwidth = cluster->loopback_bw;
915         link.latency   = cluster->loopback_lat;
916         link.state     = SURF_RESOURCE_ON;
917         link.policy    = SURF_LINK_FATPIPE;
918         sg_platf_new_link(&link);
919         info_loop.link_up   = Link::byName(tmp_link);
920         info_loop.link_down = info_loop.link_up;
921         free(tmp_link);
922         xbt_dynar_set(current_routing->p_linkUpDownList,
923           rankId*(static_cast<AsCluster*>(current_routing))->p_nb_links_per_node, &info_loop);
924       }
925
926       //add a limiter link (shared link to account for maximal bandwidth of the node)
927       if(cluster->limiter_link!=0){
928         char *tmp_link = bprintf("%s_limiter", link_id);
929         XBT_DEBUG("<limiter\tid=\"%s\"\tbw=\"%f\"/>", tmp_link,
930                 cluster->limiter_link);
931
932
933         memset(&link, 0, sizeof(link));
934         link.id = tmp_link;
935         link.bandwidth = cluster->limiter_link;
936         link.latency = 0;
937         link.state = SURF_RESOURCE_ON;
938         link.policy = SURF_LINK_SHARED;
939         sg_platf_new_link(&link);
940         info_lim.link_up = Link::byName(tmp_link);
941         info_lim.link_down = info_lim.link_up;
942         free(tmp_link);
943         auto as_cluster = static_cast<AsCluster*>(current_routing);
944         xbt_dynar_set(current_routing->p_linkUpDownList,
945             rankId*(as_cluster)->p_nb_links_per_node + as_cluster->p_has_loopback ,
946             &info_lim);
947
948       }
949
950
951       //call the cluster function that adds the others links
952       if (cluster->topology == SURF_CLUSTER_FAT_TREE) {
953         ((AsClusterFatTree*) current_routing)->addProcessingNode(i);
954       }
955       else {
956       static_cast<AsCluster*>(current_routing)->create_links_for_node(cluster, i, rankId, rankId*
957                   static_cast<AsCluster*>(current_routing)->p_nb_links_per_node
958           + static_cast<AsCluster*>(current_routing)->p_has_loopback
959           + static_cast<AsCluster*>(current_routing)->p_has_limiter );
960       }
961       xbt_free(link_id);
962       xbt_free(host_id);
963       rankId++;
964     }
965
966     xbt_dynar_free(&radical_ends);
967   }
968   xbt_dynar_free(&radical_elements);
969
970   // For fat trees, the links must be created once all nodes have been added
971   if(cluster->topology == SURF_CLUSTER_FAT_TREE) {
972     static_cast<simgrid::surf::AsClusterFatTree*>(current_routing)->create_links();
973   }
974   // Add a router. It is magically used thanks to the way in which surf_routing_cluster is written,
975   // and it's very useful to connect clusters together
976   XBT_DEBUG(" ");
977   XBT_DEBUG("<router id=\"%s\"/>", cluster->router_id);
978   char *newid = NULL;
979   s_sg_platf_router_cbarg_t router = SG_PLATF_ROUTER_INITIALIZER;
980   memset(&router, 0, sizeof(router));
981   router.id = cluster->router_id;
982   router.coord = "";
983   if (!router.id || !strcmp(router.id, ""))
984     router.id = newid =
985         bprintf("%s%s_router%s", cluster->prefix, cluster->id,
986                 cluster->suffix);
987   sg_platf_new_router(&router);
988   ((AsCluster*)current_routing)->p_router = (simgrid::surf::RoutingEdge*) xbt_lib_get_or_null(as_router_lib, router.id, ROUTING_ASR_LEVEL);
989   free(newid);
990
991   //Make the backbone
992   if ((cluster->bb_bw != 0) || (cluster->bb_lat != 0)) {
993     char *link_backbone = bprintf("%s_backbone", cluster->id);
994     XBT_DEBUG("<link\tid=\"%s\" bw=\"%f\" lat=\"%f\"/>", link_backbone,
995               cluster->bb_bw, cluster->bb_lat);
996
997     memset(&link, 0, sizeof(link));
998     link.id        = link_backbone;
999     link.bandwidth = cluster->bb_bw;
1000     link.latency   = cluster->bb_lat;
1001     link.state     = SURF_RESOURCE_ON;
1002     link.policy    = cluster->bb_sharing_policy;
1003
1004     sg_platf_new_link(&link);
1005
1006     routing_cluster_add_backbone(Link::byName(link_backbone));
1007
1008     free(link_backbone);
1009   }
1010
1011   XBT_DEBUG("</AS>");
1012   sg_platf_new_AS_end();
1013   XBT_DEBUG(" ");
1014   xbt_dict_free(&patterns); // no op if it were never set
1015 }
1016
1017 static void routing_parse_postparse(void) {
1018   xbt_dict_free(&random_value);
1019 }
1020
1021 void sg_platf_new_peer(sg_platf_peer_cbarg_t peer)
1022 {
1023   using simgrid::surf::RoutingEdge;
1024   using simgrid::surf::AsCluster;
1025
1026   char *host_id = NULL;
1027   char *link_id = NULL;
1028   char *router_id = NULL;
1029
1030   XBT_DEBUG(" ");
1031   host_id = HOST_PEER(peer->id);
1032   link_id = LINK_PEER(peer->id);
1033   router_id = ROUTER_PEER(peer->id);
1034
1035   XBT_DEBUG("<AS id=\"%s\"\trouting=\"Cluster\">", peer->id);
1036   s_sg_platf_AS_cbarg_t AS = SG_PLATF_AS_INITIALIZER;
1037   AS.id                    = peer->id;
1038   AS.routing               = A_surfxml_AS_routing_Cluster;
1039   sg_platf_new_AS_begin(&AS);
1040
1041   current_routing->p_linkUpDownList = xbt_dynar_new(sizeof(s_surf_parsing_link_up_down_t),NULL);
1042
1043   XBT_DEBUG("<host\tid=\"%s\"\tpower=\"%f\"/>", host_id, peer->speed);
1044   s_sg_platf_host_cbarg_t host = SG_PLATF_HOST_INITIALIZER;
1045   memset(&host, 0, sizeof(host));
1046   host.initial_state = SURF_RESOURCE_ON;
1047   host.id = host_id;
1048
1049   host.speed_peak = xbt_dynar_new(sizeof(double), NULL);
1050   xbt_dynar_push(host.speed_peak,&peer->speed);
1051   host.pstate = 0;
1052   //host.power_peak = peer->power;
1053   host.speed_scale = 1.0;
1054   host.speed_trace = peer->availability_trace;
1055   host.state_trace = peer->state_trace;
1056   host.core_amount = 1;
1057   sg_platf_new_host(&host);
1058   xbt_dynar_free(&host.speed_peak);
1059
1060   s_sg_platf_link_cbarg_t link = SG_PLATF_LINK_INITIALIZER;
1061   memset(&link, 0, sizeof(link));
1062   link.state   = SURF_RESOURCE_ON;
1063   link.policy  = SURF_LINK_SHARED;
1064   link.latency = peer->lat;
1065
1066   char* link_up = bprintf("%s_UP",link_id);
1067   XBT_DEBUG("<link\tid=\"%s\"\tbw=\"%f\"\tlat=\"%f\"/>", link_up,
1068             peer->bw_out, peer->lat);
1069   link.id = link_up;
1070   link.bandwidth = peer->bw_out;
1071   sg_platf_new_link(&link);
1072
1073   char* link_down = bprintf("%s_DOWN",link_id);
1074   XBT_DEBUG("<link\tid=\"%s\"\tbw=\"%f\"\tlat=\"%f\"/>", link_down,
1075             peer->bw_in, peer->lat);
1076   link.id = link_down;
1077   link.bandwidth = peer->bw_in;
1078   sg_platf_new_link(&link);
1079
1080   XBT_DEBUG("<host_link\tid=\"%s\"\tup=\"%s\"\tdown=\"%s\" />", host_id,link_up,link_down);
1081   s_sg_platf_host_link_cbarg_t host_link = SG_PLATF_HOST_LINK_INITIALIZER;
1082   memset(&host_link, 0, sizeof(host_link));
1083   host_link.id        = host_id;
1084   host_link.link_up   = link_up;
1085   host_link.link_down = link_down;
1086   sg_platf_new_host_link(&host_link);
1087
1088   XBT_DEBUG("<router id=\"%s\"/>", router_id);
1089   s_sg_platf_router_cbarg_t router = SG_PLATF_ROUTER_INITIALIZER;
1090   memset(&router, 0, sizeof(router));
1091   router.id = router_id;
1092   router.coord = peer->coord;
1093   sg_platf_new_router(&router);
1094   static_cast<AsCluster*>(current_routing)->p_router = static_cast<RoutingEdge*>(xbt_lib_get_or_null(as_router_lib, router.id, ROUTING_ASR_LEVEL));
1095
1096   XBT_DEBUG("</AS>");
1097   sg_platf_new_AS_end();
1098   XBT_DEBUG(" ");
1099
1100   //xbt_dynar_free(&tab_elements_num);
1101   free(router_id);
1102   free(host_id);
1103   free(link_id);
1104   free(link_up);
1105   free(link_down);
1106 }
1107
1108 // static void routing_parse_Srandom(void)
1109 // {
1110 //   double mean, std, min, max, seed;
1111 //   char *random_id = A_surfxml_random_id;
1112 //   char *random_radical = A_surfxml_random_radical;
1113 //   char *rd_name = NULL;
1114 //   char *rd_value;
1115 //   mean = surf_parse_get_double(A_surfxml_random_mean);
1116 //   std = surf_parse_get_double(A_surfxml_random_std___deviation);
1117 //   min = surf_parse_get_double(A_surfxml_random_min);
1118 //   max = surf_parse_get_double(A_surfxml_random_max);
1119 //   seed = surf_parse_get_double(A_surfxml_random_seed);
1120
1121 //   double res = 0;
1122 //   int i = 0;
1123 //   random_data_t random = xbt_new0(s_random_data_t, 1);
1124 //   char *tmpbuf;
1125
1126 //   xbt_dynar_t radical_elements;
1127 //   unsigned int iter;
1128 //   char *groups;
1129 //   int start, end;
1130 //   xbt_dynar_t radical_ends;
1131
1132 //   switch (A_surfxml_random_generator) {
1133 //   case AU_surfxml_random_generator:
1134 //   case A_surfxml_random_generator_NONE:
1135 //     random->generator = NONE;
1136 //     break;
1137 //   case A_surfxml_random_generator_DRAND48:
1138 //     random->generator = DRAND48;
1139 //     break;
1140 //   case A_surfxml_random_generator_RAND:
1141 //     random->generator = RAND;
1142 //     break;
1143 //   case A_surfxml_random_generator_RNGSTREAM:
1144 //     random->generator = RNGSTREAM;
1145 //     break;
1146 //   default:
1147 //     surf_parse_error("Invalid random generator");
1148 //     break;
1149 //   }
1150 //   random->seed = seed;
1151 //   random->min = min;
1152 //   random->max = max;
1153
1154 //   /* Check user stupidities */
1155 //   if (max < min)
1156 //     THROWF(arg_error, 0, "random->max < random->min (%f < %f)", max, min);
1157 //   if (mean < min)
1158 //     THROWF(arg_error, 0, "random->mean < random->min (%f < %f)", mean, min);
1159 //   if (mean > max)
1160 //     THROWF(arg_error, 0, "random->mean > random->max (%f > %f)", mean, max);
1161
1162 //   /* normalize the mean and standard deviation before storing */
1163 //   random->mean = (mean - min) / (max - min);
1164 //   random->std = std / (max - min);
1165
1166 //   if (random->mean * (1 - random->mean) < random->std * random->std)
1167 //     THROWF(arg_error, 0, "Invalid mean and standard deviation (%f and %f)",
1168 //            random->mean, random->std);
1169
1170 //   XBT_DEBUG
1171 //       ("id = '%s' min = '%f' max = '%f' mean = '%f' std_deviatinon = '%f' generator = '%d' seed = '%ld' radical = '%s'",
1172 //        random_id, random->min, random->max, random->mean, random->std,
1173 //        (int)random->generator, random->seed, random_radical);
1174
1175 //   if (!random_value)
1176 //     random_value = xbt_dict_new_homogeneous(free);
1177
1178 //   if (!strcmp(random_radical, "")) {
1179 //     res = random_generate(random);
1180 //     rd_value = bprintf("%f", res);
1181 //     xbt_dict_set(random_value, random_id, rd_value, NULL);
1182 //   } else {
1183 //     radical_elements = xbt_str_split(random_radical, ",");
1184 //     xbt_dynar_foreach(radical_elements, iter, groups) {
1185 //       radical_ends = xbt_str_split(groups, "-");
1186 //       switch (xbt_dynar_length(radical_ends)) {
1187 //       case 1:
1188 //         xbt_assert(!xbt_dict_get_or_null(random_value, random_id),
1189 //                    "Custom Random '%s' already exists !", random_id);
1190 //         res = random_generate(random);
1191 //         tmpbuf =
1192 //             bprintf("%s%d", random_id,
1193 //                     atoi(xbt_dynar_getfirst_as(radical_ends, char *)));
1194 //         xbt_dict_set(random_value, tmpbuf, bprintf("%f", res), NULL);
1195 //         xbt_free(tmpbuf);
1196 //         break;
1197
1198 //       case 2:
1199 //         start = surf_parse_get_int(xbt_dynar_get_as(radical_ends, 0, char *));
1200 //         end = surf_parse_get_int(xbt_dynar_get_as(radical_ends, 1, char *));
1201 //         for (i = start; i <= end; i++) {
1202 //           xbt_assert(!xbt_dict_get_or_null(random_value, random_id),
1203 //                      "Custom Random '%s' already exists !", bprintf("%s%d",
1204 //                                                                     random_id,
1205 //                                                                     i));
1206 //           res = random_generate(random);
1207 //           tmpbuf = bprintf("%s%d", random_id, i);
1208 //           xbt_dict_set(random_value, tmpbuf, bprintf("%f", res), NULL);
1209 //           xbt_free(tmpbuf);
1210 //         }
1211 //         break;
1212 //       default:
1213 //         XBT_CRITICAL("Malformed radical");
1214 //         break;
1215 //       }
1216 //       res = random_generate(random);
1217 //       rd_name = bprintf("%s_router", random_id);
1218 //       rd_value = bprintf("%f", res);
1219 //       xbt_dict_set(random_value, rd_name, rd_value, NULL);
1220
1221 //       xbt_dynar_free(&radical_ends);
1222 //     }
1223 //     free(rd_name);
1224 //     xbt_dynar_free(&radical_elements);
1225 //   }
1226 // }
1227
1228 static void check_disk_attachment()
1229 {
1230   xbt_lib_cursor_t cursor;
1231   char *key;
1232   void **data;
1233   simgrid::surf::RoutingEdge *host_elm;
1234   xbt_lib_foreach(storage_lib, cursor, key, data) {
1235     if(xbt_lib_get_level(xbt_lib_get_elm_or_null(storage_lib, key), SURF_STORAGE_LEVEL) != NULL) {
1236           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));
1237           host_elm = sg_routing_edge_by_name_or_null(storage->p_attach);
1238           if(!host_elm)
1239                   surf_parse_error("Unable to attach storage %s: host %s doesn't exist.", storage->getName(), storage->p_attach);
1240     }
1241   }
1242 }
1243
1244 void routing_register_callbacks()
1245 {
1246   sg_platf_postparse_add_cb(routing_parse_postparse);
1247   sg_platf_postparse_add_cb(check_disk_attachment);
1248
1249   instr_routing_define_callbacks();
1250 }
1251
1252 /**
1253  * \brief Recursive function for finalize
1254  *
1255  * \param rc the source host name
1256  *
1257  * This fuction is call by "finalize". It allow to finalize the
1258  * AS or routing components. It delete all the structures.
1259  */
1260 static void finalize_rec(simgrid::surf::As *as) {
1261   xbt_dict_cursor_t cursor = NULL;
1262   char *key;
1263   AS_t elem;
1264
1265   xbt_dict_foreach(as->p_routingSons, cursor, key, elem) {
1266     finalize_rec(elem);
1267   }
1268
1269   delete as;;
1270 }
1271
1272 /** \brief Frees all memory allocated by the routing module */
1273 void routing_exit(void) {
1274   delete routing_platf;
1275 }
1276
1277 namespace simgrid {
1278 namespace surf {
1279
1280 RoutingPlatf::~RoutingPlatf()
1281 {
1282         xbt_dynar_free(&p_lastRoute);
1283         finalize_rec(p_root);
1284 }
1285
1286 }
1287 }
1288
1289 AS_t surf_AS_get_routing_root() {
1290   return routing_platf->p_root;
1291 }
1292
1293 const char *surf_AS_get_name(simgrid::surf::As *as) {
1294   return as->p_name;
1295 }
1296
1297 static simgrid::surf::As *surf_AS_recursive_get_by_name(
1298   simgrid::surf::As *current, const char * name)
1299 {
1300   xbt_dict_cursor_t cursor = NULL;
1301   char *key;
1302   AS_t elem;
1303   simgrid::surf::As *tmp = NULL;
1304
1305   if(!strcmp(current->p_name, name))
1306     return current;
1307
1308   xbt_dict_foreach(current->p_routingSons, cursor, key, elem) {
1309     tmp = surf_AS_recursive_get_by_name(elem, name);
1310     if(tmp != NULL ) {
1311         break;
1312     }
1313   }
1314   return tmp;
1315 }
1316
1317 simgrid::surf::As *surf_AS_get_by_name(const char * name)
1318 {
1319   simgrid::surf::As *as = surf_AS_recursive_get_by_name(routing_platf->p_root, name);
1320   if(as == NULL)
1321     XBT_WARN("Impossible to find an AS with name %s, please check your input", name);
1322   return as;
1323 }
1324
1325 xbt_dict_t surf_AS_get_routing_sons(simgrid::surf::As *as)
1326 {
1327   return as->p_routingSons;
1328 }
1329
1330 const char *surf_AS_get_model(simgrid::surf::As *as)
1331 {
1332   return as->p_modelDesc->name;
1333 }
1334
1335 xbt_dynar_t surf_AS_get_hosts(simgrid::surf::As *as)
1336 {
1337   xbt_dynar_t elms = as->p_indexNetworkElm;
1338   int count = xbt_dynar_length(elms);
1339   xbt_dynar_t res =  xbt_dynar_new(sizeof(sg_host_t), NULL);
1340   for (int index = 0; index < count; index++) {
1341      sg_routing_edge_t relm =
1342       xbt_dynar_get_as(elms, index, simgrid::surf::RoutingEdge*);
1343      sg_host_t delm = simgrid::Host::by_name_or_null(relm->getName());
1344      if (delm!=NULL) {
1345        xbt_dynar_push(res, &delm);
1346      }
1347   }
1348   return res;
1349 }
1350
1351 void surf_AS_get_graph(AS_t as, xbt_graph_t graph, xbt_dict_t nodes, xbt_dict_t edges) {
1352   as->getGraph(graph, nodes, edges);
1353 }