Logo AND Algorithmique Numérique Distribuée

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