Logo AND Algorithmique Numérique Distribuée

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