Logo AND Algorithmique Numérique Distribuée

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