Logo AND Algorithmique Numérique Distribuée

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