Logo AND Algorithmique Numérique Distribuée

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