Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
plug some more memleaks. aint bad anymore
[simgrid.git] / src / surf / surf_routing.c
1 /* Copyright (c) 2009, 2010, 2011. 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 <pcre.h>               /* regular expression library */
8
9 #include "simgrid/platf_interface.h"    // platform creation API internal interface
10
11 #include "surf_routing_private.h"
12 #include "surf/surf_routing.h"
13 #include "surf/surfxml_parse_values.h"
14
15 xbt_lib_t host_lib;
16 int ROUTING_HOST_LEVEL;         //Routing level
17 int SURF_CPU_LEVEL;             //Surf cpu level
18 int SURF_WKS_LEVEL;             //Surf workstation level
19 int SIMIX_HOST_LEVEL;           //Simix level
20 int MSG_HOST_LEVEL;             //Msg level
21 int SD_HOST_LEVEL;              //Simdag level
22 int COORD_HOST_LEVEL=0;         //Coordinates level
23 int NS3_HOST_LEVEL;             //host node for ns3
24
25 xbt_lib_t link_lib;
26 int SD_LINK_LEVEL;              //Simdag level
27 int SURF_LINK_LEVEL;            //Surf level
28 int NS3_LINK_LEVEL;             //link for ns3
29
30 xbt_lib_t as_router_lib;
31 int ROUTING_ASR_LEVEL;          //Routing level
32 int COORD_ASR_LEVEL;            //Coordinates level
33 int NS3_ASR_LEVEL;              //host node for ns3
34
35 static xbt_dict_t random_value = NULL;
36
37 /* Global vars */
38 routing_global_t global_routing = NULL;
39 AS_t current_routing = NULL;
40
41 /* global parse functions */
42 xbt_dynar_t parsed_link_list = NULL;   /* temporary store of current list link of a route */
43 static const char *src = NULL;  /* temporary store the source name of a route */
44 static const char *dst = NULL;  /* temporary store the destination name of a route */
45 static char *gw_src = NULL;     /* temporary store the gateway source name of a route */
46 static char *gw_dst = NULL;     /* temporary store the gateway destination name of a route */
47
48 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(surf_route, surf, "Routing part of surf");
49
50 static void routing_parse_peer(sg_platf_peer_cbarg_t peer);     /* peer bypass */
51 static void routing_parse_Srandom(void);        /* random bypass */
52
53 static void routing_parse_postparse(void);
54
55 /* this lines are only for replace use like index in the model table */
56 typedef enum {
57   SURF_MODEL_FULL = 0,
58   SURF_MODEL_FLOYD,
59   SURF_MODEL_DIJKSTRA,
60   SURF_MODEL_DIJKSTRACACHE,
61   SURF_MODEL_NONE,
62   SURF_MODEL_RULEBASED,
63   SURF_MODEL_VIVALDI,
64   SURF_MODEL_CLUSTER
65 } e_routing_types;
66
67 struct s_model_type routing_models[] = {
68   {"Full",
69    "Full routing data (fast, large memory requirements, fully expressive)",
70    model_full_create, model_full_end},
71   {"Floyd",
72    "Floyd routing data (slow initialization, fast lookup, lesser memory requirements, shortest path routing only)",
73    model_floyd_create, model_floyd_end},
74   {"Dijkstra",
75    "Dijkstra routing data (fast initialization, slow lookup, small memory requirements, shortest path routing only)",
76    model_dijkstra_create, model_dijkstra_both_end},
77   {"DijkstraCache",
78    "Dijkstra routing data (fast initialization, fast lookup, small memory requirements, shortest path routing only)",
79    model_dijkstracache_create, model_dijkstra_both_end},
80   {"none", "No routing (usable with Constant network only)",
81    model_none_create,  NULL},
82   {"RuleBased", "Rule-Based routing data (...)",
83    model_rulebased_create, NULL},
84   {"Vivaldi", "Vivaldi routing",
85    model_vivaldi_create, NULL},
86   {"Cluster", "Cluster routing",
87    model_cluster_create, NULL},
88   {NULL, NULL, NULL, NULL}
89 };
90
91 /**
92  * \brief Add a "host" to the network element list
93  */
94 static void parse_S_host(sg_platf_host_cbarg_t host)
95 {
96   network_element_info_t info = NULL;
97   if (current_routing->hierarchy == SURF_ROUTING_NULL)
98     current_routing->hierarchy = SURF_ROUTING_BASE;
99   xbt_assert(!xbt_lib_get_or_null(host_lib, host->id, ROUTING_HOST_LEVEL),
100              "Reading a host, processing unit \"%s\" already exists", host->id);
101
102   current_routing->parse_PU(current_routing, host->id);
103   info = xbt_new0(s_network_element_info_t, 1);
104   info->rc_component = current_routing;
105   info->rc_type = SURF_NETWORK_ELEMENT_HOST;
106   xbt_lib_set(host_lib, host->id, ROUTING_HOST_LEVEL, (void *) info);
107   if (host->coord && strcmp(host->coord, "")) {
108     unsigned int cursor;
109     char*str;
110
111     if (!COORD_HOST_LEVEL)
112       xbt_die ("To use host coordinates, please add --cfg=coordinates:yes to your command line");
113
114     /* Pre-parse the host coordinates -- FIXME factorize with routers by overloading the routing->parse_PU function*/
115     xbt_dynar_t ctn_str = xbt_str_split_str(host->coord, " ");
116     xbt_dynar_t ctn = xbt_dynar_new(sizeof(double),NULL);
117     xbt_dynar_foreach(ctn_str,cursor, str) {
118       double val = atof(str);
119       xbt_dynar_push(ctn,&val);
120     }
121     xbt_dynar_shrink(ctn, 0);
122     xbt_dynar_free(&ctn_str);
123     xbt_lib_set(host_lib, host->id, COORD_HOST_LEVEL, (void *) ctn);
124   }
125 }
126
127 /**
128  * \brief Add a "router" to the network element list
129  */
130 static void parse_S_router(sg_platf_router_cbarg_t router)
131 {
132   network_element_info_t info = NULL;
133   if (current_routing->hierarchy == SURF_ROUTING_NULL)
134     current_routing->hierarchy = SURF_ROUTING_BASE;
135   xbt_assert(!xbt_lib_get_or_null(as_router_lib, router->id, ROUTING_ASR_LEVEL),
136              "Reading a router, processing unit \"%s\" already exists",
137              router->id);
138
139   current_routing->parse_PU(current_routing, router->id);
140   info = xbt_new0(s_network_element_info_t, 1);
141   info->rc_component = current_routing;
142   info->rc_type = SURF_NETWORK_ELEMENT_ROUTER;
143
144   xbt_lib_set(as_router_lib, router->id, ROUTING_ASR_LEVEL, (void *) info);
145   if (strcmp(router->coord, "")) {
146     unsigned int cursor;
147     char*str;
148
149     if (!COORD_ASR_LEVEL)
150       xbt_die ("To use host coordinates, please add --cfg=coordinates:yes to your command line");
151
152     /* Pre-parse the host coordinates */
153     xbt_dynar_t ctn_str = xbt_str_split_str(router->coord, " ");
154     xbt_dynar_t ctn = xbt_dynar_new(sizeof(double),NULL);
155     xbt_dynar_foreach(ctn_str,cursor, str) {
156       double val = atof(str);
157       xbt_dynar_push(ctn,&val);
158     }
159     xbt_dynar_shrink(ctn, 0);
160     xbt_dynar_free(&ctn_str);
161     xbt_lib_set(as_router_lib, router->id, COORD_ASR_LEVEL, (void *) ctn);
162   }
163 }
164
165
166 /**
167  * \brief Set the end points for a route
168  */
169 static void routing_parse_S_route(void)
170 {
171   if (src != NULL && dst != NULL && parsed_link_list != NULL)
172     THROWF(arg_error, 0, "Route between %s to %s can not be defined",
173            A_surfxml_route_src, A_surfxml_route_dst);
174   src = A_surfxml_route_src;
175   dst = A_surfxml_route_dst;
176   xbt_assert(strlen(src) > 0 || strlen(dst) > 0,
177              "Some limits are null in the route between \"%s\" and \"%s\"",
178              src, dst);
179   parsed_link_list = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
180 }
181
182 /**
183  * \brief Set the end points and gateways for a ASroute
184  */
185 static void routing_parse_S_ASroute(void)
186 {
187   if (src != NULL && dst != NULL && parsed_link_list != NULL)
188     THROWF(arg_error, 0, "Route between %s to %s can not be defined",
189            A_surfxml_ASroute_src, A_surfxml_ASroute_dst);
190   src = A_surfxml_ASroute_src;
191   dst = A_surfxml_ASroute_dst;
192   gw_src = A_surfxml_ASroute_gw_src;
193   gw_dst = A_surfxml_ASroute_gw_dst;
194   xbt_assert(strlen(src) > 0 || strlen(dst) > 0 || strlen(gw_src) > 0
195              || strlen(gw_dst) > 0,
196              "Some limits are null in the route between \"%s\" and \"%s\"",
197              src, dst);
198   parsed_link_list = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
199 }
200
201 /**
202  * \brief Set the end points for a bypassRoute
203  */
204 static void routing_parse_S_bypassRoute(void)
205 {
206   if (src != NULL && dst != NULL && parsed_link_list != NULL)
207     THROWF(arg_error, 0,
208            "Bypass Route between %s to %s can not be defined",
209            A_surfxml_bypassRoute_src, A_surfxml_bypassRoute_dst);
210   src = A_surfxml_bypassRoute_src;
211   dst = A_surfxml_bypassRoute_dst;
212   gw_src = A_surfxml_bypassRoute_gw_src;
213   gw_dst = A_surfxml_bypassRoute_gw_dst;
214   xbt_assert(strlen(src) > 0 || strlen(dst) > 0 || strlen(gw_src) > 0
215              || strlen(gw_dst) > 0,
216              "Some limits are null in the route between \"%s\" and \"%s\"",
217              src, dst);
218   parsed_link_list = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
219 }
220
221 /**
222  * \brief Set a new link on the actual list of link for a route or ASroute from XML
223  */
224
225 static void routing_parse_link_ctn(void)
226 {
227   char *link_id;
228   switch (A_surfxml_link_ctn_direction) {
229   case AU_surfxml_link_ctn_direction:
230   case A_surfxml_link_ctn_direction_NONE:
231     link_id = xbt_strdup(A_surfxml_link_ctn_id);
232     break;
233   case A_surfxml_link_ctn_direction_UP:
234     link_id = bprintf("%s_UP", A_surfxml_link_ctn_id);
235     break;
236   case A_surfxml_link_ctn_direction_DOWN:
237     link_id = bprintf("%s_DOWN", A_surfxml_link_ctn_id);
238     break;
239   }
240   xbt_dynar_push(parsed_link_list, &link_id);
241 }
242
243 /**
244  * \brief Store the route by calling the set_route function of the current routing component
245  */
246 static void routing_parse_E_route(void)
247 {
248   route_t route = xbt_new0(s_route_t, 1);
249   route->link_list = parsed_link_list;
250   xbt_assert(current_routing->parse_route,
251              "no defined method \"set_route\" in \"%s\"",
252              current_routing->name);
253   current_routing->parse_route(current_routing, src, dst, route);
254   generic_free_route(route);
255   parsed_link_list = NULL;
256   src = NULL;
257   dst = NULL;
258 }
259
260 /**
261  * \brief Store the ASroute by calling the set_ASroute function of the current routing component
262  */
263 static void routing_parse_E_ASroute(void)
264 {
265   route_t e_route = xbt_new0(s_route_t, 1);
266   e_route->link_list = parsed_link_list;
267   e_route->src_gateway = xbt_strdup(gw_src);
268   e_route->dst_gateway = xbt_strdup(gw_dst);
269   xbt_assert(current_routing->parse_ASroute,
270              "no defined method \"set_ASroute\" in \"%s\"",
271              current_routing->name);
272   current_routing->parse_ASroute(current_routing, src, dst, e_route);
273   generic_free_route(e_route);
274   parsed_link_list = NULL;
275   src = NULL;
276   dst = NULL;
277   gw_src = NULL;
278   gw_dst = NULL;
279 }
280
281 /**
282  * \brief Store the bypass route by calling the set_bypassroute function of the current routing component
283  */
284 static void routing_parse_E_bypassRoute(void)
285 {
286   route_t e_route = xbt_new0(s_route_t, 1);
287   e_route->link_list = parsed_link_list;
288   e_route->src_gateway = xbt_strdup(gw_src);
289   e_route->dst_gateway = xbt_strdup(gw_dst);
290   xbt_assert(current_routing->parse_bypassroute,
291              "Bypassing mechanism not implemented by routing '%s'",
292              current_routing->name);
293   current_routing->parse_bypassroute(current_routing, src, dst, e_route);
294   parsed_link_list = NULL;
295   src = NULL;
296   dst = NULL;
297   gw_src = NULL;
298   gw_dst = NULL;
299 }
300
301 /**
302  * \brief Make a new routing component to the platform
303  *
304  * Add a new autonomous system to the platform. Any elements (such as host,
305  * router or sub-AS) added after this call and before the corresponding call
306  * to sg_platf_new_AS_close() will be added to this AS.
307  *
308  * Once this function was called, the configuration concerning the used
309  * models cannot be changed anymore.
310  *
311  * @param AS_id name of this autonomous system. Must be unique in the platform
312  * @param wanted_routing_type one of Full, Floyd, Dijkstra or similar. Full list in the variable routing_models, in src/surf/surf_routing.c
313  */
314 void routing_AS_begin(const char *AS_id, const char *wanted_routing_type)
315 {
316   AS_t new_as;
317   routing_model_description_t model = NULL;
318   int cpt;
319
320   /* search the routing model */
321   for (cpt = 0; routing_models[cpt].name; cpt++)
322     if (!strcmp(wanted_routing_type, routing_models[cpt].name))
323       model = &routing_models[cpt];
324   /* if its not exist, error */
325   if (model == NULL) {
326     fprintf(stderr, "Routing model %s not found. Existing models:\n",
327             wanted_routing_type);
328     for (cpt = 0; routing_models[cpt].name; cpt++)
329       fprintf(stderr, "   %s: %s\n", routing_models[cpt].name,
330               routing_models[cpt].desc);
331     xbt_die(NULL);
332   }
333
334   /* make a new routing component */
335   new_as = (AS_t) model->create();
336   new_as->model_desc = model;
337   new_as->hierarchy = SURF_ROUTING_NULL;
338   new_as->name = xbt_strdup(AS_id);
339
340   if (current_routing == NULL && global_routing->root == NULL) {
341
342     /* it is the first one */
343     new_as->routing_father = NULL;
344     global_routing->root = new_as;
345
346   } else if (current_routing != NULL && global_routing->root != NULL) {
347
348     xbt_assert(!xbt_dict_get_or_null
349                (current_routing->routing_sons, AS_id),
350                "The AS \"%s\" already exists", AS_id);
351     /* it is a part of the tree */
352     new_as->routing_father = current_routing;
353     /* set the father behavior */
354     if (current_routing->hierarchy == SURF_ROUTING_NULL)
355       current_routing->hierarchy = SURF_ROUTING_RECURSIVE;
356     /* add to the sons dictionary */
357     xbt_dict_set(current_routing->routing_sons, AS_id,
358                  (void *) new_as, NULL);
359     /* add to the father element list */
360     current_routing->parse_AS(current_routing, AS_id);
361   } else {
362     THROWF(arg_error, 0, "All defined components must be belong to a AS");
363   }
364   /* set the new current component of the tree */
365   current_routing = new_as;
366 }
367
368 /**
369  * \brief Specify that the current description of AS is finished
370  *
371  * Once you've declared all the content of your AS, you have to close
372  * it with this call. Your AS is not usable until you call this function.
373  *
374  * @fixme: this call is not as robust as wanted: bad things WILL happen
375  * if you call it twice for the same AS, or if you forget calling it, or
376  * even if you add stuff to a closed AS
377  *
378  */
379 void routing_AS_end()
380 {
381
382   if (current_routing == NULL) {
383     THROWF(arg_error, 0, "Close an AS, but none was under construction");
384   } else {
385     network_element_info_t info = NULL;
386     xbt_assert(!xbt_lib_get_or_null
387                (as_router_lib, current_routing->name, ROUTING_ASR_LEVEL),
388                "The AS \"%s\" already exists", current_routing->name);
389     info = xbt_new0(s_network_element_info_t, 1);
390     info->rc_component = current_routing->routing_father;
391     info->rc_type = SURF_NETWORK_ELEMENT_AS;
392     xbt_lib_set(as_router_lib, current_routing->name, ROUTING_ASR_LEVEL,
393                 (void *) info);
394
395     if (current_routing->model_desc->end)
396       current_routing->model_desc->end(current_routing);
397     current_routing = current_routing->routing_father;
398   }
399 }
400
401 /* Aux Business methods */
402
403 /**
404  * \brief Get the AS father and the first elements of the chain
405  *
406  * \param src the source host name 
407  * \param dst the destination host name
408  * 
409  * Get the common father of the to processing units, and the first different 
410  * father in the chain
411  */
412 static void elements_father(const char *src, const char *dst,
413                             AS_t * res_father,
414                             AS_t * res_src,
415                             AS_t * res_dst)
416 {
417   xbt_assert(src && dst, "bad parameters for \"elements_father\" method");
418 #define ELEMENTS_FATHER_MAXDEPTH 16     /* increase if it is not enough */
419   AS_t src_as, dst_as;
420   AS_t path_src[ELEMENTS_FATHER_MAXDEPTH];
421   AS_t path_dst[ELEMENTS_FATHER_MAXDEPTH];
422   int index_src = 0;
423   int index_dst = 0;
424   AS_t current;
425   AS_t current_src;
426   AS_t current_dst;
427   AS_t father;
428
429   /* (1) find the as where the src and dst are located */
430   network_element_info_t src_data = xbt_lib_get_or_null(host_lib, src,
431                                                         ROUTING_HOST_LEVEL);
432   network_element_info_t dst_data = xbt_lib_get_or_null(host_lib, dst,
433                                                         ROUTING_HOST_LEVEL);
434   if (!src_data)
435     src_data = xbt_lib_get_or_null(as_router_lib, src, ROUTING_ASR_LEVEL);
436   if (!dst_data)
437     dst_data = xbt_lib_get_or_null(as_router_lib, dst, ROUTING_ASR_LEVEL);
438   src_as = src_data->rc_component;
439   dst_as = dst_data->rc_component;
440
441   xbt_assert(src_as && dst_as,
442              "Ask for route \"from\"(%s) or \"to\"(%s) no found", src, dst);
443
444   /* (2) find the path to the root routing component */
445   for (current = src_as; current != NULL; current = current->routing_father) {
446     if (index_src >= ELEMENTS_FATHER_MAXDEPTH)
447       xbt_die("ELEMENTS_FATHER_MAXDEPTH should be increased for path_src");
448     path_src[index_src++] = current;
449   }
450   for (current = dst_as; current != NULL; current = current->routing_father) {
451     if (index_dst >= ELEMENTS_FATHER_MAXDEPTH)
452       xbt_die("ELEMENTS_FATHER_MAXDEPTH should be increased for path_dst");
453     path_dst[index_dst++] = current;
454   }
455
456   /* (3) find the common father */
457   do {
458     current_src = path_src[--index_src];
459     current_dst = path_dst[--index_dst];
460   } while (index_src > 0 && index_dst > 0 && current_src == current_dst);
461
462   /* (4) they are not in the same routing component, make the path */
463   if (current_src == current_dst)
464     father = current_src;
465   else
466     father = path_src[index_src + 1];
467
468   /* (5) result generation */
469   *res_father = father;         /* first the common father of src and dst */
470   *res_src = current_src;       /* second the first different father of src */
471   *res_dst = current_dst;       /* three  the first different father of dst */
472
473 #undef ELEMENTS_FATHER_MAXDEPTH
474 }
475
476 /* Global Business methods */
477
478 /**
479  * \brief Recursive function for get_route_latency
480  *
481  * \param src the source host name 
482  * \param dst the destination host name
483  * \param *route the route where the links are stored. It is either NULL or a ready to use dynar
484  * \param *latency the latency, if needed
485  * 
486  * This function is called by "get_route" and "get_latency". It allows to walk
487  * recursively through the ASes tree.
488  */
489 static void _get_route_and_latency(const char *src, const char *dst,
490                                    xbt_dynar_t * links, double *latency)
491 {
492   void *link;
493   unsigned int cpt;
494   s_route_t route;
495   memset(&route,0,sizeof(route));
496
497   XBT_DEBUG("Solve route/latency  \"%s\" to \"%s\"", src, dst);
498   xbt_assert(src && dst, "bad parameters for \"_get_route_latency\" method");
499
500   /* Find how src and dst are interconnected */
501   AS_t common_father, src_father, dst_father;
502   elements_father(src, dst, &common_father, &src_father, &dst_father);
503
504   /* If src and dst are in the same AS, life is good */
505   if (src_father == dst_father) {       /* SURF_ROUTING_BASE */
506
507     route.link_list = *links;
508
509     common_father->get_route_and_latency(common_father, src, dst, &route,latency);
510
511     xbt_free(route.src_gateway);
512     xbt_free(route.dst_gateway);
513     return;
514   }
515
516   /* If we are here, src and dst are not in the same AS; check whether a direct bypass is defined */
517
518   route_t e_route_bypass = NULL;
519   if (common_father->get_bypass_route)
520     e_route_bypass = common_father->get_bypass_route(common_father, src, dst);
521
522   if (e_route_bypass) { /* Common ancestor is kind enough to declare a bypass route from src to dst -- use it and bail out */
523     if (latency)
524       xbt_die("Bypass cannot work yet with get_latency"); // FIXME: get_bypass_route should update the latency itself, just like get_route
525
526     // FIXME this path is never tested. I need examples to check the bypass mechanism...
527     THROW_UNIMPLEMENTED; // let's warn the users of the problem
528     xbt_dynar_foreach(e_route_bypass->link_list, cpt, link) {
529       xbt_dynar_push(*links, &link);
530     }
531
532     generic_free_route(e_route_bypass);
533     return;
534   }
535
536
537   /* Not in the same AS, no bypass. We'll have to find our path between the ASes recursively*/
538
539   route.link_list = xbt_dynar_new(global_routing->size_of_link, NULL);
540   common_father->get_route_and_latency(common_father, src_father->name, dst_father->name, &route,latency);
541
542   xbt_assert((route.src_gateway != NULL) && (route.dst_gateway != NULL),
543       "bad gateways for route from \"%s\" to \"%s\"", src, dst);
544
545   char*src_gateway = route.src_gateway;
546   char*dst_gateway = route.dst_gateway;
547
548   /* If source gateway is not our source, we have to recursively find our way up to this point */
549   if (strcmp(src, src_gateway))
550     _get_route_and_latency(src, src_gateway, links, latency);
551
552   xbt_dynar_foreach(route.link_list, cpt, link) {
553     xbt_dynar_push(*links, &link);
554   }
555
556   /* If dest gateway is not our destination, we have to recursively find our way from this point */
557   // FIXME why can't I factorize it the same way than [src;src_gw] without breaking the examples??
558   if (strcmp(dst_gateway, dst)) {
559     xbt_dynar_t route_dst = xbt_dynar_new(global_routing->size_of_link,NULL);
560
561     _get_route_and_latency(dst_gateway, dst, &route_dst, latency);
562
563     xbt_dynar_foreach(route_dst, cpt, link) {
564       xbt_dynar_push(*links, &link);
565     }
566     xbt_dynar_free(&route_dst);
567   }
568
569   xbt_free(src_gateway);
570   xbt_free_f(dst_gateway);
571   xbt_dynar_free(&route.link_list);
572 }
573
574 /**
575  * \brief Find a route between hosts
576  *
577  * \param src the source host name
578  * \param dst the destination host name
579  * \param route where to store the list of links.
580  *              If *route=NULL, create a short lived dynar. Else, fill the provided dynar
581  * \param latency where to store the latency experienced on the path (or NULL if not interested)
582  *                It is the caller responsability to initialize latency to 0 (we add to provided route)
583  * \pre route!=NULL
584  *
585  * walk through the routing components tree and find a route between hosts
586  * by calling the differents "get_route" functions in each routing component.
587  */
588 void routing_get_route_and_latency(const char *src, const char *dst,
589                                    xbt_dynar_t * route, double *latency)
590 {
591   static xbt_dynar_t last_route = NULL;
592
593   int need_cleanup = !(*route);
594
595   if (need_cleanup) {
596     xbt_dynar_free(&last_route);
597     last_route = *route = xbt_dynar_new(global_routing->size_of_link,NULL);
598   }
599
600   _get_route_and_latency(src, dst, route, latency);
601
602   xbt_assert(!latency || *latency >= 0.0,
603              "negative latency on route between \"%s\" and \"%s\"", src, dst);
604 }
605
606 static xbt_dynar_t recursive_get_onelink_routes(AS_t rc)
607 {
608   xbt_dynar_t ret = xbt_dynar_new(sizeof(onelink_t), xbt_free);
609
610   //adding my one link routes
611   unsigned int cpt;
612   void *link;
613   xbt_dynar_t onelink_mine = rc->get_onelink_routes(rc);
614   if (onelink_mine) {
615     xbt_dynar_foreach(onelink_mine, cpt, link) {
616       xbt_dynar_push(ret, &link);
617     }
618   }
619   //recursing
620   char *key;
621   xbt_dict_cursor_t cursor = NULL;
622   AS_t rc_child;
623   xbt_dict_foreach(rc->routing_sons, cursor, key, rc_child) {
624     xbt_dynar_t onelink_child = recursive_get_onelink_routes(rc_child);
625     if (onelink_child) {
626       xbt_dynar_foreach(onelink_child, cpt, link) {
627         xbt_dynar_push(ret, &link);
628       }
629     }
630   }
631   return ret;
632 }
633
634 static xbt_dynar_t get_onelink_routes(void)
635 {
636   return recursive_get_onelink_routes(global_routing->root);
637 }
638
639 e_surf_network_element_type_t routing_get_network_element_type(const char *name)
640 {
641   network_element_info_t rc = NULL;
642
643   rc = xbt_lib_get_or_null(host_lib, name, ROUTING_HOST_LEVEL);
644   if (rc)
645     return rc->rc_type;
646
647   rc = xbt_lib_get_or_null(as_router_lib, name, ROUTING_ASR_LEVEL);
648   if (rc)
649     return rc->rc_type;
650
651   return SURF_NETWORK_ELEMENT_NULL;
652 }
653
654 /**
655  * \brief Generic method: create the global routing schema
656  * 
657  * Make a global routing structure and set all the parsing functions.
658  */
659 void routing_model_create(size_t size_of_links, void *loopback)
660 {
661   /* config the uniq global routing */
662   global_routing = xbt_new0(s_routing_global_t, 1);
663   global_routing->root = NULL;
664   global_routing->get_onelink_routes = get_onelink_routes;
665   global_routing->loopback = loopback;
666   global_routing->size_of_link = size_of_links;
667   /* no current routing at moment */
668   current_routing = NULL;
669 }
670
671
672 /* ************************************************** */
673 /* ********** PATERN FOR NEW ROUTING **************** */
674
675 /* The minimal configuration of a new routing model need the next functions,
676  * also you need to set at the start of the file, the new model in the model
677  * list. Remember keep the null ending of the list.
678  */
679 /*** Routing model structure ***/
680 // typedef struct {
681 //   s_routing_component_t generic_routing;
682 //   /* things that your routing model need */
683 // } s_routing_component_NEW_t,*routing_component_NEW_t;
684
685 /*** Parse routing model functions ***/
686 // static void model_NEW_set_processing_unit(routing_component_t rc, const char* name) {}
687 // static void model_NEW_set_autonomous_system(routing_component_t rc, const char* name) {}
688 // static void model_NEW_set_route(routing_component_t rc, const char* src, const char* dst, route_t route) {}
689 // static void model_NEW_set_ASroute(routing_component_t rc, const char* src, const char* dst, route_extended_t route) {}
690 // static void model_NEW_set_bypassroute(routing_component_t rc, const char* src, const char* dst, route_extended_t e_route) {}
691
692 /*** Business methods ***/
693 // static route_extended_t NEW_get_route(routing_component_t rc, const char* src,const char* dst) {return NULL;}
694 // static route_extended_t NEW_get_bypass_route(routing_component_t rc, const char* src,const char* dst) {return NULL;}
695 // static void NEW_finalize(routing_component_t rc) { xbt_free(rc);}
696
697 /*** Creation routing model functions ***/
698 // static void* model_NEW_create(void) {
699 //   routing_component_NEW_t new_component =  xbt_new0(s_routing_component_NEW_t,1);
700 //   new_component->generic_routing.set_processing_unit = model_NEW_set_processing_unit;
701 //   new_component->generic_routing.set_autonomous_system = model_NEW_set_autonomous_system;
702 //   new_component->generic_routing.set_route = model_NEW_set_route;
703 //   new_component->generic_routing.set_ASroute = model_NEW_set_ASroute;
704 //   new_component->generic_routing.set_bypassroute = model_NEW_set_bypassroute;
705 //   new_component->generic_routing.get_route = NEW_get_route;
706 //   new_component->generic_routing.get_bypass_route = NEW_get_bypass_route;
707 //   new_component->generic_routing.finalize = NEW_finalize;
708 //   /* initialization of internal structures */
709 //   return new_component;
710 // } /* mandatory */
711 // static void  model_NEW_load(void) {}   /* mandatory */
712 // static void  model_NEW_unload(void) {} /* mandatory */
713 // static void  model_NEW_end(void) {}    /* mandatory */
714
715 /* ************************************************************************** */
716 /* ************************* GENERIC PARSE FUNCTIONS ************************ */
717
718
719 static void routing_parse_cluster(sg_platf_cluster_cbarg_t cluster)
720 {
721   char *host_id, *groups, *link_id = NULL;
722   xbt_dict_t patterns = NULL;
723
724   s_sg_platf_host_cbarg_t host;
725   s_sg_platf_link_cbarg_t link;
726
727   unsigned int iter;
728   int start, end, i;
729   xbt_dynar_t radical_elements;
730   xbt_dynar_t radical_ends;
731
732   if (strcmp(cluster->availability_trace, "")
733       || strcmp(cluster->state_trace, "")) {
734     patterns = xbt_dict_new();
735     xbt_dict_set(patterns, "id", xbt_strdup(cluster->id), free);
736     xbt_dict_set(patterns, "prefix", xbt_strdup(cluster->prefix), free);
737     xbt_dict_set(patterns, "suffix", xbt_strdup(cluster->suffix), free);
738   }
739
740
741   XBT_DEBUG("<AS id=\"%s\"\trouting=\"Cluster\">", cluster->id);
742   sg_platf_new_AS_begin(cluster->id, "Cluster");
743
744   //Make all hosts
745   radical_elements = xbt_str_split(cluster->radical, ",");
746   xbt_dynar_foreach(radical_elements, iter, groups) {
747
748     radical_ends = xbt_str_split(groups, "-");
749     start = surf_parse_get_int(xbt_dynar_get_as(radical_ends, 0, char *));
750
751     switch (xbt_dynar_length(radical_ends)) {
752     case 1:
753       end = start;
754       break;
755     case 2:
756       end = surf_parse_get_int(xbt_dynar_get_as(radical_ends, 1, char *));
757       break;
758     default:
759       surf_parse_error("Malformed radical");
760       break;
761     }
762     for (i = start; i <= end; i++) {
763       host_id =
764           bprintf("%s%d%s", cluster->prefix, i, cluster->suffix);
765       link_id = bprintf("%s_link_%d", cluster->id, i);
766
767       XBT_DEBUG("<host\tid=\"%s\"\tpower=\"%f\">", host_id, cluster->power);
768
769       memset(&host, 0, sizeof(host));
770       host.id = host_id;
771       if (strcmp(cluster->availability_trace, "")) {
772         xbt_dict_set(patterns, "radical", bprintf("%d", i), xbt_free);
773         char *avail_file = xbt_str_varsubst(cluster->availability_trace, patterns);
774         XBT_DEBUG("\tavailability_file=\"%s\"", avail_file);
775         host.power_trace = tmgr_trace_new(avail_file);
776         xbt_free(avail_file);
777       } else {
778         XBT_DEBUG("\tavailability_file=\"\"");
779       }
780
781       if (strcmp(cluster->state_trace, "")) {
782         char *avail_file = xbt_str_varsubst(cluster->state_trace, patterns);
783         XBT_DEBUG("\tstate_file=\"%s\"", avail_file);
784         host.state_trace = tmgr_trace_new(avail_file);
785         xbt_free(avail_file);
786       } else {
787         XBT_DEBUG("\tstate_file=\"\"");
788       }
789
790       host.power_peak = cluster->power;
791       host.power_scale = 1.0;
792       host.core_amount = cluster->core_amount;
793       host.initial_state = SURF_RESOURCE_ON;
794       host.coord = "";
795       sg_platf_new_host(&host);
796       XBT_DEBUG("</host>");
797
798       XBT_DEBUG("<link\tid=\"%s\"\tbw=\"%f\"\tlat=\"%f\"/>", link_id,
799                 cluster->bw, cluster->lat);
800
801       memset(&link, 0, sizeof(link));
802       link.id = link_id;
803       link.bandwidth = cluster->bw;
804       link.latency = cluster->lat;
805       link.state = SURF_RESOURCE_ON;
806       link.policy = cluster->sharing_policy;
807       sg_platf_new_link(&link);
808
809       surf_parsing_link_up_down_t info =
810           xbt_new0(s_surf_parsing_link_up_down_t, 1);
811       if (link.policy == SURF_LINK_FULLDUPLEX) {
812         char *tmp_link = bprintf("%s_UP", link_id);
813         info->link_up =
814             xbt_lib_get_or_null(link_lib, tmp_link, SURF_LINK_LEVEL);
815         free(tmp_link);
816         tmp_link = bprintf("%s_DOWN", link_id);
817         info->link_down =
818             xbt_lib_get_or_null(link_lib, tmp_link, SURF_LINK_LEVEL);
819         free(tmp_link);
820       } else {
821         info->link_up = xbt_lib_get_or_null(link_lib, link_id, SURF_LINK_LEVEL);
822         info->link_down = info->link_up;
823       }
824       surf_routing_cluster_add_link(host_id, info);
825
826       xbt_free(link_id);
827       xbt_free(host_id);
828     }
829
830     xbt_dynar_free(&radical_ends);
831   }
832   xbt_dynar_free(&radical_elements);
833
834   // Add a router. It is magically used thanks to the way in which surf_routing_cluster is written,
835   // and it's very useful to connect clusters together
836   XBT_DEBUG(" ");
837   XBT_DEBUG("<router id=\"%s\"/>", cluster->router_id);
838   char *newid = NULL;
839   s_sg_platf_router_cbarg_t router;
840   memset(&router, 0, sizeof(router));
841   router.id = cluster->router_id;
842   router.coord = "";
843   if (!router.id || !strcmp(router.id, ""))
844     router.id = newid =
845         bprintf("%s%s_router%s", cluster->prefix, cluster->id,
846                 cluster->suffix);
847   sg_platf_new_router(&router);
848   free(newid);
849
850   //Make the backbone
851   if ((cluster->bb_bw != 0) && (cluster->bb_lat != 0)) {
852     char *link_backbone = bprintf("%s_backbone", cluster->id);
853     XBT_DEBUG("<link\tid=\"%s\" bw=\"%f\" lat=\"%f\"/>", link_backbone,
854               cluster->bb_bw, cluster->bb_lat);
855
856     memset(&link, 0, sizeof(link));
857     link.id = link_backbone;
858     link.bandwidth = cluster->bb_bw;
859     link.latency = cluster->bb_lat;
860     link.state = SURF_RESOURCE_ON;
861     link.policy = cluster->bb_sharing_policy;
862
863     sg_platf_new_link(&link);
864
865     surf_routing_cluster_add_backbone(current_routing, xbt_lib_get_or_null(link_lib, link_backbone, SURF_LINK_LEVEL));
866
867     free(link_backbone);
868   }
869
870   XBT_DEBUG("</AS>");
871   sg_platf_new_AS_end();
872   XBT_DEBUG(" ");
873   xbt_dict_free(&patterns); // no op if it were never set
874 }
875
876 static void routing_parse_postparse(void) {
877   xbt_dict_free(&random_value);
878 }
879
880 static void routing_parse_peer(sg_platf_peer_cbarg_t peer)
881 {
882   static int AX_ptr = 0;
883   char *host_id = NULL;
884   char *router_id, *link_router, *link_backbone, *link_id_up, *link_id_down;
885
886   static unsigned int surfxml_buffer_stack_stack_ptr = 1;
887   static unsigned int surfxml_buffer_stack_stack[1024];
888
889   surfxml_buffer_stack_stack[0] = 0;
890
891   surfxml_bufferstack_push(1);
892
893   XBT_DEBUG("<AS id=\"%s\"\trouting=\"Full\">", peer->id);
894   sg_platf_new_AS_begin(peer->id, "Full");
895
896   XBT_DEBUG(" ");
897   host_id = HOST_PEER(peer->id);
898   router_id = ROUTER_PEER(peer->id);
899   link_id_up = LINK_UP_PEER(peer->id);
900   link_id_down = LINK_DOWN_PEER(peer->id);
901
902   link_router = bprintf("%s_link_router", peer->id);
903   link_backbone = bprintf("%s_backbone", peer->id);
904
905   XBT_DEBUG("<host\tid=\"%s\"\tpower=\"%f\"/>", host_id, peer->power);
906   s_sg_platf_host_cbarg_t host;
907   memset(&host, 0, sizeof(host));
908   host.initial_state = SURF_RESOURCE_ON;
909   host.id = host_id;
910   host.power_peak = peer->power;
911   host.power_scale = 1.0;
912   host.power_trace = peer->availability_trace;
913   host.state_trace = peer->state_trace;
914   host.core_amount = 1;
915   host.coord = peer->coord;
916   sg_platf_new_host(&host);
917
918
919   XBT_DEBUG("<router id=\"%s\"\tcoordinates=\"%s\"/>", router_id, peer->coord);
920   s_sg_platf_router_cbarg_t router;
921   memset(&router, 0, sizeof(router));
922   router.id = router_id;
923   router.coord = peer->coord;
924   sg_platf_new_router(&router);
925
926   XBT_DEBUG("<link\tid=\"%s\"\tbw=\"%f\"\tlat=\"%f\"/>", link_id_up,
927             peer->bw_in, peer->lat);
928   s_sg_platf_link_cbarg_t link;
929   memset(&link, 0, sizeof(link));
930   link.state = SURF_RESOURCE_ON;
931   link.policy = SURF_LINK_SHARED;
932   link.id = link_id_up;
933   link.bandwidth = peer->bw_in;
934   link.latency = peer->lat;
935   sg_platf_new_link(&link);
936
937   // FIXME: dealing with full duplex is not the role of this piece of code, I'd say [Mt]
938   // Instead, it should be created fullduplex, and the models will do what's needed in this case
939   XBT_DEBUG("<link\tid=\"%s\"\tbw=\"%f\"\tlat=\"%f\"/>", link_id_down,
940             peer->bw_out, peer->lat);
941   link.id = link_id_down;
942   sg_platf_new_link(&link);
943
944   XBT_DEBUG(" ");
945
946   // begin here
947   XBT_DEBUG("<route\tsrc=\"%s\"\tdst=\"%s\"", host_id, router_id);
948   XBT_DEBUG("symmetrical=\"NO\">");
949   SURFXML_BUFFER_SET(route_src, host_id);
950   SURFXML_BUFFER_SET(route_dst, router_id);
951   A_surfxml_route_symmetrical = A_surfxml_route_symmetrical_NO;
952   SURFXML_START_TAG(route);
953
954   XBT_DEBUG("<link_ctn\tid=\"%s\"/>", link_id_up);
955   SURFXML_BUFFER_SET(link_ctn_id, link_id_up);
956   A_surfxml_link_ctn_direction = A_surfxml_link_ctn_direction_NONE;
957   SURFXML_START_TAG(link_ctn);
958   SURFXML_END_TAG(link_ctn);
959
960   XBT_DEBUG("</route>");
961   SURFXML_END_TAG(route);
962
963   //Opposite Route
964   XBT_DEBUG("<route\tsrc=\"%s\"\tdst=\"%s\"", router_id, host_id);
965   XBT_DEBUG("symmetrical=\"NO\">");
966   SURFXML_BUFFER_SET(route_src, router_id);
967   SURFXML_BUFFER_SET(route_dst, host_id);
968   A_surfxml_route_symmetrical = A_surfxml_route_symmetrical_NO;
969   SURFXML_START_TAG(route);
970
971   XBT_DEBUG("<link_ctn\tid=\"%s\"/>", link_id_down);
972   SURFXML_BUFFER_SET(link_ctn_id, link_id_down);
973   A_surfxml_link_ctn_direction = A_surfxml_link_ctn_direction_NONE;
974   SURFXML_START_TAG(link_ctn);
975   SURFXML_END_TAG(link_ctn);
976
977   XBT_DEBUG("</route>");
978   SURFXML_END_TAG(route);
979
980   XBT_DEBUG("</AS>");
981   sg_platf_new_AS_end();
982   XBT_DEBUG(" ");
983
984   //xbt_dynar_free(&tab_elements_num);
985   free(host_id);
986   free(router_id);
987   free(link_router);
988   free(link_backbone);
989   free(link_id_up);
990   free(link_id_down);
991   surfxml_bufferstack_pop(1);
992 }
993
994 static void routing_parse_Srandom(void)
995 {
996   double mean, std, min, max, seed;
997   char *random_id = A_surfxml_random_id;
998   char *random_radical = A_surfxml_random_radical;
999   char *rd_name = NULL;
1000   char *rd_value;
1001   mean = surf_parse_get_double(A_surfxml_random_mean);
1002   std = surf_parse_get_double(A_surfxml_random_std_deviation);
1003   min = surf_parse_get_double(A_surfxml_random_min);
1004   max = surf_parse_get_double(A_surfxml_random_max);
1005   seed = surf_parse_get_double(A_surfxml_random_seed);
1006
1007   double res = 0;
1008   int i = 0;
1009   random_data_t random = xbt_new0(s_random_data_t, 1);
1010   char *tmpbuf;
1011
1012   xbt_dynar_t radical_elements;
1013   unsigned int iter;
1014   char *groups;
1015   int start, end;
1016   xbt_dynar_t radical_ends;
1017
1018   random->generator = A_surfxml_random_generator;
1019   random->seed = seed;
1020   random->min = min;
1021   random->max = max;
1022
1023   /* Check user stupidities */
1024   if (max < min)
1025     THROWF(arg_error, 0, "random->max < random->min (%f < %f)", max, min);
1026   if (mean < min)
1027     THROWF(arg_error, 0, "random->mean < random->min (%f < %f)", mean, min);
1028   if (mean > max)
1029     THROWF(arg_error, 0, "random->mean > random->max (%f > %f)", mean, max);
1030
1031   /* normalize the mean and standard deviation before storing */
1032   random->mean = (mean - min) / (max - min);
1033   random->std = std / (max - min);
1034
1035   if (random->mean * (1 - random->mean) < random->std * random->std)
1036     THROWF(arg_error, 0, "Invalid mean and standard deviation (%f and %f)",
1037            random->mean, random->std);
1038
1039   XBT_DEBUG
1040       ("id = '%s' min = '%f' max = '%f' mean = '%f' std_deviatinon = '%f' generator = '%d' seed = '%ld' radical = '%s'",
1041        random_id, random->min, random->max, random->mean, random->std,
1042        random->generator, random->seed, random_radical);
1043
1044   if (!random_value)
1045     random_value = xbt_dict_new();
1046
1047   if (!strcmp(random_radical, "")) {
1048     res = random_generate(random);
1049     rd_value = bprintf("%f", res);
1050     xbt_dict_set(random_value, random_id, rd_value, free);
1051   } else {
1052     radical_elements = xbt_str_split(random_radical, ",");
1053     xbt_dynar_foreach(radical_elements, iter, groups) {
1054       radical_ends = xbt_str_split(groups, "-");
1055       switch (xbt_dynar_length(radical_ends)) {
1056       case 1:
1057         xbt_assert(!xbt_dict_get_or_null(random_value, random_id),
1058                    "Custom Random '%s' already exists !", random_id);
1059         res = random_generate(random);
1060         tmpbuf =
1061             bprintf("%s%d", random_id,
1062                     atoi(xbt_dynar_getfirst_as(radical_ends, char *)));
1063         xbt_dict_set(random_value, tmpbuf, bprintf("%f", res), free);
1064         xbt_free(tmpbuf);
1065         break;
1066
1067       case 2:
1068         start = surf_parse_get_int(xbt_dynar_get_as(radical_ends, 0, char *));
1069         end = surf_parse_get_int(xbt_dynar_get_as(radical_ends, 1, char *));
1070         for (i = start; i <= end; i++) {
1071           xbt_assert(!xbt_dict_get_or_null(random_value, random_id),
1072                      "Custom Random '%s' already exists !", bprintf("%s%d",
1073                                                                     random_id,
1074                                                                     i));
1075           res = random_generate(random);
1076           tmpbuf = bprintf("%s%d", random_id, i);
1077           xbt_dict_set(random_value, tmpbuf, bprintf("%f", res), free);
1078           xbt_free(tmpbuf);
1079         }
1080         break;
1081       default:
1082         XBT_CRITICAL("Malformed radical");
1083         break;
1084       }
1085       res = random_generate(random);
1086       rd_name = bprintf("%s_router", random_id);
1087       rd_value = bprintf("%f", res);
1088       xbt_dict_set(random_value, rd_name, rd_value, free);
1089
1090       xbt_dynar_free(&radical_ends);
1091     }
1092     free(rd_name);
1093     xbt_dynar_free(&radical_elements);
1094   }
1095 }
1096
1097 void routing_register_callbacks()
1098 {
1099   sg_platf_host_add_cb(parse_S_host);
1100   sg_platf_router_add_cb(parse_S_router);
1101
1102   surfxml_add_callback(STag_surfxml_random_cb_list, &routing_parse_Srandom);
1103
1104   surfxml_add_callback(STag_surfxml_route_cb_list, &routing_parse_S_route);
1105   surfxml_add_callback(STag_surfxml_ASroute_cb_list, &routing_parse_S_ASroute);
1106   surfxml_add_callback(STag_surfxml_bypassRoute_cb_list,
1107                        &routing_parse_S_bypassRoute);
1108
1109   surfxml_add_callback(ETag_surfxml_link_ctn_cb_list, &routing_parse_link_ctn);
1110
1111   surfxml_add_callback(ETag_surfxml_route_cb_list, &routing_parse_E_route);
1112   surfxml_add_callback(ETag_surfxml_ASroute_cb_list, &routing_parse_E_ASroute);
1113   surfxml_add_callback(ETag_surfxml_bypassRoute_cb_list,
1114                        &routing_parse_E_bypassRoute);
1115
1116   sg_platf_cluster_add_cb(routing_parse_cluster);
1117
1118   sg_platf_peer_add_cb(routing_parse_peer);
1119   sg_platf_postparse_add_cb(routing_parse_postparse);
1120
1121 #ifdef HAVE_TRACING
1122   instr_routing_define_callbacks();
1123 #endif
1124 }
1125
1126 /**
1127  * \brief Recursive function for finalize
1128  *
1129  * \param rc the source host name
1130  *
1131  * This fuction is call by "finalize". It allow to finalize the
1132  * AS or routing components. It delete all the structures.
1133  */
1134 static void finalize_rec(AS_t as) {
1135   xbt_dict_cursor_t cursor = NULL;
1136   char *key;
1137   AS_t elem;
1138
1139   xbt_dict_foreach(as->routing_sons, cursor, key, elem) {
1140     finalize_rec(elem);
1141   }
1142
1143   as->finalize(as);
1144 }
1145
1146 /** \brief Frees all memory allocated by the routing module */
1147 void routing_exit(void) {
1148   if (!global_routing)
1149     return;
1150   finalize_rec(global_routing->root);
1151   xbt_free(global_routing);
1152 }