Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
code simplification: write the recursivity properly
[simgrid.git] / src / kernel / routing / AsImpl.cpp
1 /* Copyright (c) 2006-2016. The SimGrid Team. All rights reserved.          */
2
3 /* This program is free software; you can redistribute it and/or modify it
4  * under the terms of the license (GNU LGPL) which comes with this package. */
5
6 #include "xbt/log.h"
7
8 #include "simgrid/s4u/host.hpp"
9 #include "src/kernel/routing/AsImpl.hpp"
10 #include "src/surf/cpu_interface.hpp"
11 #include "src/surf/network_interface.hpp" // Link FIXME: move to proper header
12
13 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(AsImpl,surf, "Implementation of S4U autonomous systems");
14
15 namespace simgrid {
16   namespace kernel {
17   namespace routing {
18
19   AsImpl::AsImpl(As* father, const char* name) : As(father, name)
20   {
21     xbt_assert(nullptr == xbt_lib_get_or_null(as_router_lib, name, ROUTING_ASR_LEVEL),
22                "Refusing to create a second AS called '%s'.", name);
23
24     netcard_ = new NetCardImpl(name, NetCard::Type::As, static_cast<AsImpl*>(father));
25     xbt_lib_set(as_router_lib, name, ROUTING_ASR_LEVEL, static_cast<void*>(netcard_));
26     XBT_DEBUG("AS '%s' created with the id '%d'", name, netcard_->id());
27   }
28   AsImpl::~AsImpl() = default;
29
30   simgrid::s4u::Host* AsImpl::createHost(const char* name, std::vector<double>* speedPerPstate, int coreAmount)
31   {
32     simgrid::s4u::Host* res = new simgrid::s4u::Host(name);
33
34     if (hierarchy_ == RoutingMode::unset)
35       hierarchy_ = RoutingMode::base;
36
37     res->pimpl_netcard = new NetCardImpl(name, NetCard::Type::Host, this);
38
39     surf_cpu_model_pm->createCpu(res, speedPerPstate, coreAmount);
40
41     return res;
42   }
43
44   void AsImpl::getOneLinkRoutes(std::vector<Onelink*>* accumulator)
45   {
46     // recursing only. I have no route myself :)
47     char* key;
48     xbt_dict_cursor_t cursor = nullptr;
49     AsImpl* rc_child;
50     xbt_dict_foreach (children(), cursor, key, rc_child) {
51       rc_child->getOneLinkRoutes(accumulator);
52     }
53   }
54
55   /** @brief Get the common ancestor and its first children in each line leading to src and dst
56    *
57    * In the recursive case, this sets common_ancestor, src_ancestor and dst_ancestor are set as follows.
58    * @verbatim
59    *         platform root
60    *               |
61    *              ...                <- possibly long path
62    *               |
63    *         common_ancestor
64    *           /        \
65    *          /          \
66    *         /            \          <- direct links
67    *        /              \
68    *       /                \
69    *  src_ancestor     dst_ancestor  <- must be different in the recursive case
70    *      |                   |
71    *     ...                 ...     <-- possibly long pathes (one hop or more)
72    *      |                   |
73    *     src                 dst
74    *  @endverbatim
75    *
76    *  In the base case (when src and dst are in the same AS), things are as follows:
77    *  @verbatim
78    *                  platform root
79    *                        |
80    *                       ...                      <-- possibly long path
81    *                        |
82    * common_ancestor==src_ancestor==dst_ancestor    <-- all the same value
83    *                   /        \
84    *                  /          \                  <-- direct links (exactly one hop)
85    *                 /            \
86    *              src              dst
87    *  @endverbatim
88    *
89    * A specific recursive case occurs when src is the ancestor of dst. In this case,
90    * the base case routing should be used so the common_ancestor is specifically set
91    * to src_ancestor==dst_ancestor.
92    * Naturally, things are completely symmetrical if dst is the ancestor of src.
93    * @verbatim
94    *            platform root
95    *                  |
96    *                 ...                <-- possibly long path
97    *                  |
98    *  src == src_ancestor==dst_ancestor==common_ancestor <-- same value
99    *                  |
100    *                 ...                <-- possibly long path (one hop or more)
101    *                  |
102    *                 dst
103    *  @endverbatim
104    */
105   static void find_common_ancestors(NetCard* src, NetCard* dst,
106                                     /* OUT */ AsImpl** common_ancestor, AsImpl** src_ancestor, AsImpl** dst_ancestor)
107   {
108     /* Deal with the easy base case */
109     if (src->containingAS() == dst->containingAS()) {
110       *common_ancestor = src->containingAS();
111       *src_ancestor    = *common_ancestor;
112       *dst_ancestor    = *common_ancestor;
113       return;
114     }
115
116     /* engage the full recursive search */
117
118     /* (1) find the path to root of src and dst*/
119     AsImpl* src_as = src->containingAS();
120     AsImpl* dst_as = dst->containingAS();
121
122     xbt_assert(src_as, "Host %s must be in an AS", src->name().c_str());
123     xbt_assert(dst_as, "Host %s must be in an AS", dst->name().c_str());
124
125     /* (2) find the path to the root routing component */
126     std::vector<AsImpl*> path_src;
127     AsImpl* current = src->containingAS();
128     while (current != nullptr) {
129       path_src.push_back(current);
130       current = static_cast<AsImpl*>(current->father());
131     }
132     std::vector<AsImpl*> path_dst;
133     current = dst->containingAS();
134     while (current != nullptr) {
135       path_dst.push_back(current);
136       current = static_cast<AsImpl*>(current->father());
137     }
138
139     /* (3) find the common father.
140      * Before that, index_src and index_dst may be different, they both point to nullptr in path_src/path_dst
141      * So we move them down simultaneously as long as they point to the same content.
142      *
143      * This works because all SimGrid platform have a unique root element (that is the last element of both paths).
144      */
145     AsImpl* father = nullptr; // the AS we dropped on the previous loop iteration
146     while (path_src.size() > 1 && path_dst.size() > 1 &&
147            path_src.at(path_src.size() - 1) == path_dst.at(path_dst.size() - 1)) {
148       father = path_src.at(path_src.size() - 1);
149       path_src.pop_back();
150       path_dst.pop_back();
151     }
152
153     /* (4) we found the difference at least. Finalize the returned values */
154     *src_ancestor = path_src.at(path_src.size() - 1); /* the first different father of src */
155     *dst_ancestor = path_dst.at(path_dst.size() - 1); /* the first different father of dst */
156     if (*src_ancestor == *dst_ancestor) {             // src is the ancestor of dst, or the contrary
157       *common_ancestor = *src_ancestor;
158     } else {
159       *common_ancestor = father;
160     }
161   }
162
163   /* PRECONDITION: this is the common ancestor of src and dst */
164   bool AsImpl::getBypassRoute(routing::NetCard* src, routing::NetCard* dst,
165                               /* OUT */ std::vector<surf::Link*>* links, double* latency)
166   {
167     // If never set a bypass route return nullptr without any further computations
168     XBT_DEBUG("generic_get_bypassroute from %s to %s", src->name().c_str(), dst->name().c_str());
169     if (bypassRoutes_.empty())
170       return false;
171
172     /* Base case, no recursion is needed */
173     if (dst->containingAS() == this && src->containingAS() == this) {
174       if (bypassRoutes_.find({src, dst}) != bypassRoutes_.end()) {
175         AsRoute* bypassedRoute = bypassRoutes_.at({src, dst});
176         for (surf::Link* link : bypassedRoute->links) {
177           links->push_back(link);
178           if (latency)
179             *latency += link->latency();
180         }
181         XBT_DEBUG("Found a bypass route with %zu links", bypassedRoute->links.size());
182         return true;
183       }
184       return false;
185     }
186
187     /* Engage recursive search */
188
189
190     /* (1) find the path to the root routing component */
191     std::vector<AsImpl*> path_src;
192     As* current = src->containingAS();
193     while (current != nullptr) {
194       path_src.push_back(static_cast<AsImpl*>(current));
195       current = current->father_;
196     }
197
198     std::vector<AsImpl*> path_dst;
199     current = dst->containingAS();
200     while (current != nullptr) {
201       path_dst.push_back(static_cast<AsImpl*>(current));
202       current = current->father_;
203     }
204
205     /* (2) find the common father */
206     while (path_src.size() > 1 && path_dst.size() > 1 &&
207            path_src.at(path_src.size() - 1) == path_dst.at(path_dst.size() - 1)) {
208       path_src.pop_back();
209       path_dst.pop_back();
210     }
211
212     int max_index_src = path_src.size() - 1;
213     int max_index_dst = path_dst.size() - 1;
214
215     int max_index = std::max(max_index_src, max_index_dst);
216
217     /* (3) Search for a bypass making the path up to the ancestor useless */
218     AsRoute* bypassedRoute = nullptr;
219     std::pair<kernel::routing::NetCard*, kernel::routing::NetCard*> key;
220     for (int max = 0; max <= max_index; max++) {
221       for (int i = 0; i < max; i++) {
222         if (i <= max_index_src && max <= max_index_dst) {
223           key = {path_src.at(i)->netcard_, path_dst.at(max)->netcard_};
224           if (bypassRoutes_.find(key) != bypassRoutes_.end()) {
225             bypassedRoute = bypassRoutes_.at(key);
226             break;
227           }
228         }
229         if (max <= max_index_src && i <= max_index_dst) {
230           key = {path_src.at(max)->netcard_, path_dst.at(i)->netcard_};
231           if (bypassRoutes_.find(key) != bypassRoutes_.end()) {
232             bypassedRoute = bypassRoutes_.at(key);
233             break;
234           }
235         }
236       }
237
238       if (bypassedRoute)
239         break;
240
241       if (max <= max_index_src && max <= max_index_dst) {
242         key = {path_src.at(max)->netcard_, path_dst.at(max)->netcard_};
243         if (bypassRoutes_.find(key) != bypassRoutes_.end()) {
244           bypassedRoute = bypassRoutes_.at(key);
245           break;
246         }
247       }
248     }
249
250     /* (4) If we have the bypass, use it. If not, caller will do the Right Thing. */
251     if (bypassedRoute) {
252       if (src != key.first)
253         getRouteRecursive(src, const_cast<NetCard*>(bypassedRoute->gw_src), links, latency);
254       for (surf::Link* link : bypassedRoute->links) {
255         links->push_back(link);
256         if (latency)
257           *latency += link->latency();
258       }
259       if (dst != key.second)
260         getRouteRecursive(const_cast<NetCard*>(bypassedRoute->gw_dst), dst, links, latency);
261       return true;
262     }
263     return false;
264     }
265
266     /**
267      * \brief Recursive function for getRouteAndLatency
268      *
269      * \param src the source host
270      * \param dst the destination host
271      * \param links Where to store the links and the gw information
272      * \param latency If not nullptr, the latency of all links will be added in it
273      */
274     void AsImpl::getRouteRecursive(routing::NetCard *src, routing::NetCard *dst,
275         /* OUT */ std::vector<surf::Link*> * links, double *latency)
276     {
277       s_sg_platf_route_cbarg_t route;
278       memset(&route,0,sizeof(route));
279
280       XBT_DEBUG("Solve route/latency \"%s\" to \"%s\"", src->name().c_str(), dst->name().c_str());
281
282       /* Find how src and dst are interconnected */
283       AsImpl *common_ancestor, *src_ancestor, *dst_ancestor;
284       find_common_ancestors(src, dst, &common_ancestor, &src_ancestor, &dst_ancestor);
285       XBT_DEBUG("elements_father: common ancestor '%s' src ancestor '%s' dst ancestor '%s'",
286           common_ancestor->name(), src_ancestor->name(), dst_ancestor->name());
287
288       /* Check whether a direct bypass is defined. If so, use it and bail out */
289       if (common_ancestor->getBypassRoute(src, dst, links, latency))
290         return;
291
292       /* If src and dst are in the same AS, life is good */
293       if (src_ancestor == dst_ancestor) {       /* SURF_ROUTING_BASE */
294         route.link_list = links;
295         common_ancestor->getRouteAndLatency(src, dst, &route, latency);
296         return;
297       }
298
299       /* Not in the same AS, no bypass. We'll have to find our path between the ASes recursively*/
300
301       route.link_list = new std::vector<surf::Link*>();
302
303       common_ancestor->getRouteAndLatency(src_ancestor->netcard_, dst_ancestor->netcard_, &route, latency);
304       xbt_assert((route.gw_src != nullptr) && (route.gw_dst != nullptr), "bad gateways for route from \"%s\" to \"%s\"",
305                  src->name().c_str(), dst->name().c_str());
306
307       /* If source gateway is not our source, we have to recursively find our way up to this point */
308       if (src != route.gw_src)
309         getRouteRecursive(src, route.gw_src, links, latency);
310       for (auto link: *route.link_list)
311         links->push_back(link);
312       delete route.link_list;
313
314       /* If dest gateway is not our destination, we have to recursively find our way from this point */
315       if (route.gw_dst != dst)
316         getRouteRecursive(route.gw_dst, dst, links, latency);
317
318     }
319
320 }}} // namespace