Logo AND Algorithmique Numérique Distribuée

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