Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
ad56002aec251e86bbcdda009b63dfb0513cef59
[simgrid.git] / src / kernel / routing / NetZoneImpl.cpp
1 /* Copyright (c) 2006-2022. 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 <simgrid/kernel/routing/NetPoint.hpp>
7 #include <simgrid/kernel/routing/NetZoneImpl.hpp>
8 #include <simgrid/s4u/Engine.hpp>
9 #include <simgrid/s4u/Host.hpp>
10 #include <simgrid/s4u/VirtualMachine.hpp>
11
12 #include "src/include/simgrid/sg_config.hpp"
13 #include "src/kernel/EngineImpl.hpp"
14 #include "src/kernel/resource/CpuImpl.hpp"
15 #include "src/kernel/resource/DiskImpl.hpp"
16 #include "src/kernel/resource/NetworkModel.hpp"
17 #include "src/kernel/resource/SplitDuplexLinkImpl.hpp"
18 #include "src/kernel/resource/StandardLinkImpl.hpp"
19 #include "src/kernel/resource/VirtualMachineImpl.hpp"
20 #include "src/surf/HostImpl.hpp"
21
22 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(ker_routing, kernel, "Kernel routing-related information");
23
24 namespace simgrid::kernel::routing {
25
26 /* Pick the right models for CPU, net and host, and call their model_init_preparse */
27 static void surf_config_models_setup()
28 {
29   std::string host_model_name    = simgrid::config::get_value<std::string>("host/model");
30   std::string network_model_name = simgrid::config::get_value<std::string>("network/model");
31   std::string cpu_model_name     = simgrid::config::get_value<std::string>("cpu/model");
32   std::string disk_model_name    = simgrid::config::get_value<std::string>("disk/model");
33
34   /* The compound host model is needed when using non-default net/cpu models */
35   if ((not simgrid::config::is_default("network/model") || not simgrid::config::is_default("cpu/model")) &&
36       simgrid::config::is_default("host/model")) {
37     host_model_name = "compound";
38     simgrid::config::set_value("host/model", host_model_name);
39   }
40
41   XBT_DEBUG("host model: %s", host_model_name.c_str());
42   if (host_model_name == "compound") {
43     xbt_assert(not cpu_model_name.empty(), "Set a cpu model to use with the 'compound' host model");
44     xbt_assert(not network_model_name.empty(), "Set a network model to use with the 'compound' host model");
45
46     const auto* cpu_model = find_model_description(surf_cpu_model_description, cpu_model_name);
47     cpu_model->model_init_preparse();
48
49     const auto* network_model = find_model_description(surf_network_model_description, network_model_name);
50     network_model->model_init_preparse();
51   }
52
53   XBT_DEBUG("Call host_model_init");
54   const auto* host_model = find_model_description(surf_host_model_description, host_model_name);
55   host_model->model_init_preparse();
56
57   XBT_DEBUG("Call vm_model_init");
58   /* ideally we should get back the pointer to CpuModel from model_init_preparse(), but this
59    * requires changing the declaration of surf_cpu_model_description.
60    * To be reviewed in the future */
61   surf_vm_model_init_HL13(
62       simgrid::s4u::Engine::get_instance()->get_netzone_root()->get_impl()->get_cpu_pm_model().get());
63
64   XBT_DEBUG("Call disk_model_init");
65   const auto* disk_model = find_model_description(surf_disk_model_description, disk_model_name);
66   disk_model->model_init_preparse();
67 }
68
69 xbt::signal<void(bool symmetrical, kernel::routing::NetPoint* src, kernel::routing::NetPoint* dst,
70                  kernel::routing::NetPoint* gw_src, kernel::routing::NetPoint* gw_dst,
71                  std::vector<kernel::resource::StandardLinkImpl*> const& link_list)>
72     NetZoneImpl::on_route_creation;
73
74 NetZoneImpl::NetZoneImpl(const std::string& name) : piface_(this), name_(name)
75 {
76   auto* engine = s4u::Engine::get_instance();
77   /* workaroud: first netzoneImpl will be the root netzone.
78    * Without globals and with current surf_*_model_description init functions, we need
79    * the root netzone to exist when creating the models.
80    * This was usually done at sg_platf.cpp, during XML parsing */
81   if (not engine->get_netzone_root()) {
82     engine->set_netzone_root(&piface_);
83     /* root netzone set, initialize models */
84     simgrid::s4u::Engine::on_platform_creation();
85
86     /* Initialize the surf models. That must be done after we got all config, and before we need the models.
87      * That is, after the last <config> tag, if any, and before the first of cluster|peer|zone|trace|trace_cb
88      *
89      * I'm not sure for <trace> and <trace_cb>, there may be a bug here
90      * (FIXME: check it out by creating a file beginning with one of these tags)
91      * but cluster and peer come down to zone creations, so putting this verification here is correct.
92      */
93     surf_config_models_setup();
94   }
95
96   xbt_assert(nullptr == engine->netpoint_by_name_or_null(get_name()),
97              "Refusing to create a second NetZone called '%s'.", get_cname());
98   netpoint_ = new NetPoint(name_, NetPoint::Type::NetZone);
99   XBT_DEBUG("NetZone '%s' created with the id '%lu'", get_cname(), netpoint_->id());
100   _sg_cfg_init_status = 2; /* HACK: direct access to the global controlling the level of configuration to prevent
101                             * any further config now that we created some real content */
102   simgrid::s4u::NetZone::on_creation(piface_); // notify the signal
103 }
104
105 NetZoneImpl::~NetZoneImpl()
106 {
107   for (auto const& nz : children_)
108     delete nz;
109
110   /* Since hosts_ and links_ are a std::map, the hosts are destroyed in the lexicographic order, which ensures that the
111    * output is reproducible.
112    */
113   for (auto const& [_, host] : hosts_) {
114     host->destroy();
115   }
116   hosts_.clear();
117   for (auto const& [_, link] : links_) {
118     link->destroy();
119   }
120   links_.clear();
121
122   for (auto const& [_, route] : bypass_routes_)
123     delete route;
124
125   s4u::Engine::get_instance()->netpoint_unregister(netpoint_);
126 }
127
128 xbt_node_t NetZoneImpl::new_xbt_graph_node(const s_xbt_graph_t* graph, const char* name,
129                                            std::map<std::string, xbt_node_t, std::less<>>* nodes)
130 {
131   auto [elm, inserted] = nodes->try_emplace(name);
132   if (inserted)
133     elm->second = xbt_graph_new_node(graph, xbt_strdup(name));
134   return elm->second;
135 }
136
137 xbt_edge_t NetZoneImpl::new_xbt_graph_edge(const s_xbt_graph_t* graph, xbt_node_t src, xbt_node_t dst,
138                                            std::map<std::string, xbt_edge_t, std::less<>>* edges)
139 {
140   const auto* src_name = static_cast<const char*>(xbt_graph_node_get_data(src));
141   const auto* dst_name = static_cast<const char*>(xbt_graph_node_get_data(dst));
142
143   auto elm = edges->find(std::string(src_name) + dst_name);
144   if (elm == edges->end()) {
145     bool inserted;
146     std::tie(elm, inserted) = edges->try_emplace(std::string(dst_name) + src_name);
147     if (inserted)
148       elm->second = xbt_graph_new_edge(graph, src, dst, nullptr);
149   }
150
151   return elm->second;
152 }
153
154 void NetZoneImpl::add_child(NetZoneImpl* new_zone)
155 {
156   xbt_assert(not sealed_, "Cannot add a new child to the sealed zone %s", get_cname());
157   /* set the parent behavior */
158   hierarchy_ = RoutingMode::recursive;
159   children_.push_back(new_zone);
160 }
161
162 /** @brief Returns the list of the hosts found in this NetZone (not recursively)
163  *
164  * Only the hosts that are directly contained in this NetZone are retrieved,
165  * not the ones contained in sub-netzones.
166  */
167 std::vector<s4u::Host*> NetZoneImpl::get_all_hosts() const
168 {
169   return s4u::Engine::get_instance()->get_filtered_hosts(
170       [this](const s4u::Host* host) { return host->get_impl()->get_englobing_zone() == this; });
171 }
172 size_t NetZoneImpl::get_host_count() const
173 {
174   return get_all_hosts().size();
175 }
176
177 std::vector<s4u::Link*> NetZoneImpl::get_filtered_links(const std::function<bool(s4u::Link*)>& filter) const
178 {
179   std::vector<s4u::Link*> filtered_list;
180   for (auto const& [_, link] : links_) {
181     s4u::Link* l = link->get_iface();
182     if (filter(l))
183       filtered_list.push_back(l);
184   }
185
186   for (const auto* child : children_) {
187     auto child_links = child->get_filtered_links(filter);
188     filtered_list.insert(filtered_list.end(), std::make_move_iterator(child_links.begin()),
189                          std::make_move_iterator(child_links.end()));
190   }
191   return filtered_list;
192 }
193
194 std::vector<s4u::Link*> NetZoneImpl::get_all_links() const
195 {
196   return get_filtered_links([](const s4u::Link*) { return true; });
197 }
198
199 size_t NetZoneImpl::get_link_count() const
200 {
201   size_t total = links_.size();
202   for (const auto* child : children_) {
203     total += child->get_link_count();
204   }
205   return total;
206 }
207
208 s4u::Host* NetZoneImpl::create_host(const std::string& name, const std::vector<double>& speed_per_pstate)
209 {
210   xbt_assert(cpu_model_pm_,
211              "Impossible to create host: %s. Invalid CPU model: nullptr. Have you set the parent of this NetZone: %s?",
212              name.c_str(), get_cname());
213   xbt_assert(not sealed_, "Impossible to create host: %s. NetZone %s already sealed", name.c_str(), get_cname());
214   auto* host   = (new resource::HostImpl(name))->set_englobing_zone(this);
215   hosts_[name] = host;
216   host->get_iface()->set_netpoint((new NetPoint(name, NetPoint::Type::Host))->set_englobing_zone(this));
217
218   cpu_model_pm_->create_cpu(host->get_iface(), speed_per_pstate);
219
220   return host->get_iface();
221 }
222
223 resource::StandardLinkImpl* NetZoneImpl::do_create_link(const std::string& name, const std::vector<double>& bandwidths)
224 {
225   return network_model_->create_link(name, bandwidths);
226 }
227
228 s4u::Link* NetZoneImpl::create_link(const std::string& name, const std::vector<double>& bandwidths)
229 {
230   xbt_assert(
231       network_model_,
232       "Impossible to create link: %s. Invalid network model: nullptr. Have you set the parent of this NetZone: %s?",
233       name.c_str(), get_cname());
234   xbt_assert(not sealed_, "Impossible to create link: %s. NetZone %s already sealed", name.c_str(), get_cname());
235   links_[name] = do_create_link(name, bandwidths)->set_englobing_zone(this);
236   return links_[name]->get_iface();
237 }
238
239 s4u::SplitDuplexLink* NetZoneImpl::create_split_duplex_link(const std::string& name,
240                                                             const std::vector<double>& bandwidths)
241 {
242   xbt_assert(
243       network_model_,
244       "Impossible to create link: %s. Invalid network model: nullptr. Have you set the parent of this NetZone: %s?",
245       name.c_str(), get_cname());
246   xbt_assert(not sealed_, "Impossible to create link: %s. NetZone %s already sealed", name.c_str(), get_cname());
247
248   auto* link_up             = create_link(name + "_UP", bandwidths)->get_impl()->set_englobing_zone(this);
249   auto* link_down           = create_link(name + "_DOWN", bandwidths)->get_impl()->set_englobing_zone(this);
250   split_duplex_links_[name] = std::make_unique<resource::SplitDuplexLinkImpl>(name, link_up, link_down);
251   return split_duplex_links_[name]->get_iface();
252 }
253
254 s4u::Disk* NetZoneImpl::create_disk(const std::string& name, double read_bandwidth, double write_bandwidth)
255 {
256   xbt_assert(disk_model_,
257              "Impossible to create disk: %s. Invalid disk model: nullptr. Have you set the parent of this NetZone: %s?",
258              name.c_str(), get_cname());
259   xbt_assert(not sealed_, "Impossible to create disk: %s. NetZone %s already sealed", name.c_str(), get_cname());
260   auto* l = disk_model_->create_disk(name, read_bandwidth, write_bandwidth);
261
262   return l->get_iface();
263 }
264
265 NetPoint* NetZoneImpl::create_router(const std::string& name)
266 {
267   xbt_assert(nullptr == s4u::Engine::get_instance()->netpoint_by_name_or_null(name),
268              "Refusing to create a router named '%s': this name already describes a node.", name.c_str());
269   xbt_assert(not sealed_, "Impossible to create router: %s. NetZone %s already sealed", name.c_str(), get_cname());
270
271   return (new NetPoint(name, NetPoint::Type::Router))->set_englobing_zone(this);
272 }
273
274 unsigned long NetZoneImpl::add_component(NetPoint* elm)
275 {
276   vertices_.push_back(elm);
277   return vertices_.size() - 1; // The rank of the newly created object
278 }
279
280 std::vector<resource::StandardLinkImpl*> NetZoneImpl::get_link_list_impl(const std::vector<s4u::LinkInRoute>& link_list,
281                                                                          bool backroute) const
282 {
283   std::vector<resource::StandardLinkImpl*> links;
284
285   for (const auto& link : link_list) {
286     if (link.get_link()->get_sharing_policy() != s4u::Link::SharingPolicy::SPLITDUPLEX) {
287       links.push_back(link.get_link()->get_impl());
288       continue;
289     }
290     // split-duplex links
291     const auto* sd_link = dynamic_cast<const s4u::SplitDuplexLink*>(link.get_link());
292     xbt_assert(sd_link,
293                "Add_route: cast to SpliDuplexLink impossible. This should not happen, please contact SimGrid team");
294     resource::StandardLinkImpl* link_impl;
295     switch (link.get_direction()) {
296       case s4u::LinkInRoute::Direction::UP:
297         if (backroute)
298           link_impl = sd_link->get_link_down()->get_impl();
299         else
300           link_impl = sd_link->get_link_up()->get_impl();
301         break;
302       case s4u::LinkInRoute::Direction::DOWN:
303         if (backroute)
304           link_impl = sd_link->get_link_up()->get_impl();
305         else
306           link_impl = sd_link->get_link_down()->get_impl();
307         break;
308       default:
309         throw std::invalid_argument("Invalid add_route. Split-Duplex link without a direction: " +
310                                     link.get_link()->get_name());
311     }
312     links.push_back(link_impl);
313   }
314   return links;
315 }
316
317 resource::StandardLinkImpl* NetZoneImpl::get_link_by_name_or_null(const std::string& name) const
318 {
319   if (auto link_it = links_.find(name); link_it != links_.end())
320     return link_it->second;
321
322   for (const auto* child : children_) {
323     if (auto* link = child->get_link_by_name_or_null(name))
324       return link;
325   }
326
327   return nullptr;
328 }
329
330 resource::SplitDuplexLinkImpl* NetZoneImpl::get_split_duplex_link_by_name_or_null(const std::string& name) const
331 {
332   if (auto link_it = split_duplex_links_.find(name); link_it != split_duplex_links_.end())
333     return link_it->second.get();
334
335   for (const auto* child : children_) {
336     if (auto* link = child->get_split_duplex_link_by_name_or_null(name))
337       return link;
338   }
339
340   return nullptr;
341 }
342
343 resource::HostImpl* NetZoneImpl::get_host_by_name_or_null(const std::string& name) const
344 {
345
346   auto host_it = hosts_.find(name);
347   if(host_it != hosts_.end())
348          return host_it->second;
349 /*
350   for (auto const& [_, host] : hosts_) {
351     if (host->get_name() == name)
352        return host;
353     / * keep old behavior where host and VMs were saved together on EngineImpl::hosts_
354      * get hosts returns VMs too * /
355     auto* vm = host->get_vm_by_name_or_null(name);
356     if (vm)
357       return vm;
358   }
359 */
360
361   for (const auto* child : children_) {
362     auto* host = child->get_host_by_name_or_null(name);
363     if (host)
364       return host;
365   }
366
367   return nullptr;
368 }
369
370 std::vector<s4u::Host*> NetZoneImpl::get_filtered_hosts(const std::function<bool(s4u::Host*)>& filter) const
371 {
372   std::vector<s4u::Host*> filtered_list;
373   for (auto const& [_, host] : hosts_) {
374     s4u::Host* h = host->get_iface();
375     if (filter(h))
376       filtered_list.push_back(h);
377     /* Engine::get_hosts returns the VMs too */
378     for (auto* vm : h->get_impl()->get_vms()) {
379       if (filter(vm))
380         filtered_list.push_back(vm);
381     }
382   }
383
384   for (const auto* child : children_) {
385     auto child_links = child->get_filtered_hosts(filter);
386     filtered_list.insert(filtered_list.end(), std::make_move_iterator(child_links.begin()),
387                          std::make_move_iterator(child_links.end()));
388   }
389   return filtered_list;
390 }
391
392 void NetZoneImpl::add_route(NetPoint* /*src*/, NetPoint* /*dst*/, NetPoint* /*gw_src*/, NetPoint* /*gw_dst*/,
393                             const std::vector<s4u::LinkInRoute>& /*link_list_*/, bool /*symmetrical*/)
394 {
395   xbt_die("NetZone '%s' does not accept new routes (wrong class).", get_cname());
396 }
397
398 void NetZoneImpl::add_bypass_route(NetPoint* src, NetPoint* dst, NetPoint* gw_src, NetPoint* gw_dst,
399                                    const std::vector<s4u::LinkInRoute>& link_list)
400 {
401   /* Argument validity checks */
402   if (gw_dst) {
403     XBT_DEBUG("Load bypassNetzoneRoute from %s@%s to %s@%s", src->get_cname(), gw_src->get_cname(), dst->get_cname(),
404               gw_dst->get_cname());
405     xbt_assert(not link_list.empty(), "Bypass route between %s@%s and %s@%s cannot be empty.", src->get_cname(),
406                gw_src->get_cname(), dst->get_cname(), gw_dst->get_cname());
407     xbt_assert(bypass_routes_.find({src, dst}) == bypass_routes_.end(),
408                "The bypass route between %s@%s and %s@%s already exists.", src->get_cname(), gw_src->get_cname(),
409                dst->get_cname(), gw_dst->get_cname());
410   } else {
411     XBT_DEBUG("Load bypassRoute from %s to %s", src->get_cname(), dst->get_cname());
412     xbt_assert(not link_list.empty(), "Bypass route between %s and %s cannot be empty.", src->get_cname(),
413                dst->get_cname());
414     xbt_assert(bypass_routes_.find({src, dst}) == bypass_routes_.end(),
415                "The bypass route between %s and %s already exists.", src->get_cname(), dst->get_cname());
416   }
417
418   /* Build a copy that will be stored in the dict */
419   auto* newRoute = new BypassRoute(gw_src, gw_dst);
420   auto converted_list = get_link_list_impl(link_list, false);
421   newRoute->links.insert(newRoute->links.end(), begin(converted_list), end(converted_list));
422
423   /* Store it */
424   bypass_routes_.try_emplace({src, dst}, newRoute);
425 }
426
427 /** @brief Get the common ancestor and its first children in each line leading to src and dst
428  *
429  * In the recursive case, this sets common_ancestor, src_ancestor and dst_ancestor are set as follows.
430  * @verbatim
431  *         platform root
432  *               |
433  *              ...                <- possibly long path
434  *               |
435  *         common_ancestor
436  *           /        \
437  *          /          \
438  *         /            \          <- direct links
439  *        /              \
440  *       /                \
441  *  src_ancestor     dst_ancestor  <- must be different in the recursive case
442  *      |                   |
443  *     ...                 ...     <-- possibly long paths (one hop or more)
444  *      |                   |
445  *     src                 dst
446  *  @endverbatim
447  *
448  *  In the base case (when src and dst are in the same netzone), things are as follows:
449  *  @verbatim
450  *                  platform root
451  *                        |
452  *                       ...                      <-- possibly long path
453  *                        |
454  * common_ancestor==src_ancestor==dst_ancestor    <-- all the same value
455  *                   /        \
456  *                  /          \                  <-- direct links (exactly one hop)
457  *                 /            \
458  *              src              dst
459  *  @endverbatim
460  *
461  * A specific recursive case occurs when src is the ancestor of dst. In this case,
462  * the base case routing should be used so the common_ancestor is specifically set
463  * to src_ancestor==dst_ancestor.
464  * Naturally, things are completely symmetrical if dst is the ancestor of src.
465  * @verbatim
466  *            platform root
467  *                  |
468  *                 ...                <-- possibly long path
469  *                  |
470  *  src == src_ancestor==dst_ancestor==common_ancestor <-- same value
471  *                  |
472  *                 ...                <-- possibly long path (one hop or more)
473  *                  |
474  *                 dst
475  *  @endverbatim
476  */
477 static void find_common_ancestors(const NetPoint* src, const NetPoint* dst,
478                                   /* OUT */ NetZoneImpl** common_ancestor, NetZoneImpl** src_ancestor,
479                                   NetZoneImpl** dst_ancestor)
480 {
481   /* Deal with the easy base case */
482   if (src->get_englobing_zone() == dst->get_englobing_zone()) {
483     *common_ancestor = src->get_englobing_zone();
484     *src_ancestor    = *common_ancestor;
485     *dst_ancestor    = *common_ancestor;
486     return;
487   }
488
489   /* engage the full recursive search */
490
491   /* (1) find the path to root of src and dst*/
492   const NetZoneImpl* src_as = src->get_englobing_zone();
493   const NetZoneImpl* dst_as = dst->get_englobing_zone();
494
495   xbt_assert(src_as, "Host %s must be in a netzone", src->get_cname());
496   xbt_assert(dst_as, "Host %s must be in a netzone", dst->get_cname());
497
498   /* (2) find the path to the root routing component */
499   std::vector<NetZoneImpl*> path_src;
500   NetZoneImpl* current = src->get_englobing_zone();
501   while (current != nullptr) {
502     path_src.push_back(current);
503     current = current->get_parent();
504   }
505   std::vector<NetZoneImpl*> path_dst;
506   current = dst->get_englobing_zone();
507   while (current != nullptr) {
508     path_dst.push_back(current);
509     current = current->get_parent();
510   }
511
512   /* (3) find the common parent.
513    * Before that, index_src and index_dst may be different, they both point to nullptr in path_src/path_dst
514    * So we move them down simultaneously as long as they point to the same content.
515    *
516    * This works because all SimGrid platform have a unique root element (that is the last element of both paths).
517    */
518   NetZoneImpl* parent = nullptr; // the netzone we dropped on the previous loop iteration
519   while (path_src.size() > 1 && path_dst.size() > 1 && path_src.back() == path_dst.back()) {
520     parent = path_src.back();
521     path_src.pop_back();
522     path_dst.pop_back();
523   }
524
525   /* (4) we found the difference at least. Finalize the returned values */
526   *src_ancestor = path_src.back();                  /* the first different parent of src */
527   *dst_ancestor = path_dst.back();                  /* the first different parent of dst */
528   if (*src_ancestor == *dst_ancestor) {             // src is the ancestor of dst, or the contrary
529     *common_ancestor = *src_ancestor;
530   } else {
531     xbt_assert(parent != nullptr);
532     *common_ancestor = parent;
533   }
534 }
535
536 /* PRECONDITION: this is the common ancestor of src and dst */
537 bool NetZoneImpl::get_bypass_route(const NetPoint* src, const NetPoint* dst,
538                                    /* OUT */ std::vector<resource::StandardLinkImpl*>& links, double* latency,
539                                    std::unordered_set<NetZoneImpl*>& netzones)
540 {
541   // If never set a bypass route return nullptr without any further computations
542   if (bypass_routes_.empty())
543     return false;
544
545   /* Base case, no recursion is needed */
546   if (dst->get_englobing_zone() == this && src->get_englobing_zone() == this) {
547     if (bypass_routes_.find({src, dst}) != bypass_routes_.end()) {
548       const BypassRoute* bypassedRoute = bypass_routes_.at({src, dst});
549       add_link_latency(links, bypassedRoute->links, latency);
550       XBT_DEBUG("Found a bypass route from '%s' to '%s' with %zu links", src->get_cname(), dst->get_cname(),
551                 bypassedRoute->links.size());
552       return true;
553     }
554     return false;
555   }
556
557   /* Engage recursive search */
558
559   /* (1) find the path to the root routing component */
560   std::vector<NetZoneImpl*> path_src;
561   NetZoneImpl* current = src->get_englobing_zone();
562   while (current != nullptr) {
563     path_src.push_back(current);
564     current = current->parent_;
565   }
566
567   std::vector<NetZoneImpl*> path_dst;
568   current = dst->get_englobing_zone();
569   while (current != nullptr) {
570     path_dst.push_back(current);
571     current = current->parent_;
572   }
573
574   /* (2) find the common parent */
575   while (path_src.size() > 1 && path_dst.size() > 1 && path_src.back() == path_dst.back()) {
576     path_src.pop_back();
577     path_dst.pop_back();
578   }
579
580   /* (3) Search for a bypass making the path up to the ancestor useless */
581   const BypassRoute* bypassedRoute = nullptr;
582   std::pair<kernel::routing::NetPoint*, kernel::routing::NetPoint*> key;
583   // Search for a bypass with the given indices. Returns true if found. Initialize variables `bypassedRoute' and `key'.
584   auto lookup = [&bypassedRoute, &key, &path_src, &path_dst, this](unsigned src_index, unsigned dst_index) {
585     if (src_index < path_src.size() && dst_index < path_dst.size()) {
586       key      = {path_src[src_index]->netpoint_, path_dst[dst_index]->netpoint_};
587       auto bpr = bypass_routes_.find(key);
588       if (bpr != bypass_routes_.end()) {
589         bypassedRoute = bpr->second;
590         return true;
591       }
592     }
593     return false;
594   };
595
596   for (unsigned max = 0, max_index = std::max(path_src.size(), path_dst.size()); max < max_index; max++) {
597     for (unsigned i = 0; i < max; i++) {
598       if (lookup(i, max) || lookup(max, i))
599         break;
600     }
601     if (bypassedRoute || lookup(max, max))
602       break;
603   }
604
605   /* (4) If we have the bypass, use it. If not, caller will do the Right Thing. */
606   if (bypassedRoute) {
607     XBT_DEBUG("Found a bypass route from '%s' to '%s' with %zu links. We may have to complete it with recursive "
608               "calls to getRoute",
609               src->get_cname(), dst->get_cname(), bypassedRoute->links.size());
610     if (src != key.first)
611       get_global_route_with_netzones(src, bypassedRoute->gw_src, links, latency, netzones);
612     add_link_latency(links, bypassedRoute->links, latency);
613     if (dst != key.second)
614       get_global_route_with_netzones(bypassedRoute->gw_dst, dst, links, latency, netzones);
615     return true;
616   }
617   XBT_DEBUG("No bypass route from '%s' to '%s'.", src->get_cname(), dst->get_cname());
618   return false;
619 }
620
621 void NetZoneImpl::get_global_route(const NetPoint* src, const NetPoint* dst,
622                                    /* OUT */ std::vector<resource::StandardLinkImpl*>& links, double* latency)
623 {
624   std::unordered_set<NetZoneImpl*> netzones;
625   get_global_route_with_netzones(src, dst, links, latency, netzones);
626 }
627
628 void NetZoneImpl::get_global_route_with_netzones(const NetPoint* src, const NetPoint* dst,
629                                                  /* OUT */ std::vector<resource::StandardLinkImpl*>& links,
630                                                  double* latency, std::unordered_set<NetZoneImpl*>& netzones)
631 {
632   Route route;
633
634   XBT_DEBUG("Resolve route from '%s' to '%s'", src->get_cname(), dst->get_cname());
635
636   /* Find how src and dst are interconnected */
637   NetZoneImpl* common_ancestor;
638   NetZoneImpl* src_ancestor;
639   NetZoneImpl* dst_ancestor;
640   find_common_ancestors(src, dst, &common_ancestor, &src_ancestor, &dst_ancestor);
641   XBT_DEBUG("find_common_ancestors: common ancestor '%s' src ancestor '%s' dst ancestor '%s'",
642             common_ancestor->get_cname(), src_ancestor->get_cname(), dst_ancestor->get_cname());
643
644   netzones.insert(src->get_englobing_zone());
645   netzones.insert(dst->get_englobing_zone());
646   netzones.insert(common_ancestor);
647   /* Check whether a direct bypass is defined. If so, use it and bail out */
648   if (common_ancestor->get_bypass_route(src, dst, links, latency, netzones))
649     return;
650
651   /* If src and dst are in the same netzone, life is good */
652   if (src_ancestor == dst_ancestor) { /* SURF_ROUTING_BASE */
653     route.link_list_ = std::move(links);
654     common_ancestor->get_local_route(src, dst, &route, latency);
655     links = std::move(route.link_list_);
656     return;
657   }
658
659   /* Not in the same netzone, no bypass. We'll have to find our path between the netzones recursively */
660   common_ancestor->get_local_route(src_ancestor->netpoint_, dst_ancestor->netpoint_, &route, latency);
661   xbt_assert((route.gw_src_ != nullptr) && (route.gw_dst_ != nullptr), "Bad gateways for route from '%s' to '%s'.",
662              src->get_cname(), dst->get_cname());
663
664   /* If source gateway is not our source, we have to recursively find our way up to this point */
665   if (src != route.gw_src_)
666     get_global_route_with_netzones(src, route.gw_src_, links, latency, netzones);
667   links.insert(links.end(), begin(route.link_list_), end(route.link_list_));
668
669   /* If dest gateway is not our destination, we have to recursively find our way from this point */
670   if (route.gw_dst_ != dst)
671     get_global_route_with_netzones(route.gw_dst_, dst, links, latency, netzones);
672 }
673
674 void NetZoneImpl::get_graph(const s_xbt_graph_t* graph, std::map<std::string, xbt_node_t, std::less<>>* nodes,
675                             std::map<std::string, xbt_edge_t, std::less<>>* edges)
676 {
677   std::vector<NetPoint*> vertices = get_vertices();
678
679   for (auto const& my_src : vertices) {
680     for (auto const& my_dst : vertices) {
681       if (my_src == my_dst)
682         continue;
683
684       Route route;
685
686       get_local_route(my_src, my_dst, &route, nullptr);
687
688       XBT_DEBUG("get_route_and_latency %s -> %s", my_src->get_cname(), my_dst->get_cname());
689
690       xbt_node_t current;
691       xbt_node_t previous;
692       const char* previous_name;
693       const char* current_name;
694
695       if (route.gw_src_) {
696         previous      = new_xbt_graph_node(graph, route.gw_src_->get_cname(), nodes);
697         previous_name = route.gw_src_->get_cname();
698       } else {
699         previous      = new_xbt_graph_node(graph, my_src->get_cname(), nodes);
700         previous_name = my_src->get_cname();
701       }
702
703       for (auto const& link : route.link_list_) {
704         const char* link_name = link->get_cname();
705         current               = new_xbt_graph_node(graph, link_name, nodes);
706         current_name          = link_name;
707         new_xbt_graph_edge(graph, previous, current, edges);
708         XBT_DEBUG("  %s -> %s", previous_name, current_name);
709         previous      = current;
710         previous_name = current_name;
711       }
712
713       if (route.gw_dst_) {
714         current      = new_xbt_graph_node(graph, route.gw_dst_->get_cname(), nodes);
715         current_name = route.gw_dst_->get_cname();
716       } else {
717         current      = new_xbt_graph_node(graph, my_dst->get_cname(), nodes);
718         current_name = my_dst->get_cname();
719       }
720       new_xbt_graph_edge(graph, previous, current, edges);
721       XBT_DEBUG("  %s -> %s", previous_name, current_name);
722     }
723   }
724 }
725
726 void NetZoneImpl::seal()
727 {
728   /* already sealed netzone */
729   if (sealed_)
730     return;
731   do_seal(); // derived class' specific sealing procedure
732
733   /* seals sub-netzones and hosts */
734   for (auto* host : get_all_hosts()) {
735     host->seal();
736   }
737
738   /* sealing links */
739   for (auto const& [_, link] : links_)
740     link->get_iface()->seal();
741
742   for (auto* sub_net : get_children()) {
743     sub_net->seal();
744   }
745   sealed_ = true;
746   s4u::NetZone::on_seal(piface_);
747 }
748
749 void NetZoneImpl::set_parent(NetZoneImpl* parent)
750 {
751   xbt_assert(not sealed_, "Impossible to set parent to an already sealed NetZone(%s)", this->get_cname());
752   parent_ = parent;
753   netpoint_->set_englobing_zone(parent_);
754   if (parent) {
755     /* adding this class as child */
756     parent->add_child(this);
757     /* copying models from parent host, to be reviewed when we allow multi-models */
758     set_network_model(parent->get_network_model());
759     set_cpu_pm_model(parent->get_cpu_pm_model());
760     set_cpu_vm_model(parent->get_cpu_vm_model());
761     set_disk_model(parent->get_disk_model());
762     set_host_model(parent->get_host_model());
763   }
764 }
765
766 void NetZoneImpl::set_network_model(std::shared_ptr<resource::NetworkModel> netmodel)
767 {
768   xbt_assert(not sealed_, "Impossible to set network model to an already sealed NetZone(%s)", this->get_cname());
769   network_model_ = std::move(netmodel);
770 }
771
772 void NetZoneImpl::set_cpu_vm_model(std::shared_ptr<resource::CpuModel> cpu_model)
773 {
774   xbt_assert(not sealed_, "Impossible to set CPU model to an already sealed NetZone(%s)", this->get_cname());
775   cpu_model_vm_ = std::move(cpu_model);
776 }
777
778 void NetZoneImpl::set_cpu_pm_model(std::shared_ptr<resource::CpuModel> cpu_model)
779 {
780   xbt_assert(not sealed_, "Impossible to set CPU model to an already sealed NetZone(%s)", this->get_cname());
781   cpu_model_pm_ = std::move(cpu_model);
782 }
783
784 void NetZoneImpl::set_disk_model(std::shared_ptr<resource::DiskModel> disk_model)
785 {
786   xbt_assert(not sealed_, "Impossible to set disk model to an already sealed NetZone(%s)", this->get_cname());
787   disk_model_ = std::move(disk_model);
788 }
789
790 void NetZoneImpl::set_host_model(std::shared_ptr<resource::HostModel> host_model)
791 {
792   xbt_assert(not sealed_, "Impossible to set host model to an already sealed NetZone(%s)", this->get_cname());
793   host_model_ = std::move(host_model);
794 }
795
796 const NetZoneImpl* NetZoneImpl::get_netzone_recursive(const NetPoint* netpoint) const
797 {
798   xbt_assert(netpoint && netpoint->is_netzone(), "Netpoint %s must be of the type NetZone",
799              netpoint ? netpoint->get_cname() : "nullptr");
800
801   if (netpoint == netpoint_)
802     return this;
803
804   for (const auto* children : children_) {
805     const NetZoneImpl* netzone = children->get_netzone_recursive(netpoint);
806     if (netzone)
807       return netzone;
808   }
809   return nullptr;
810 }
811
812 bool NetZoneImpl::is_component_recursive(const NetPoint* netpoint) const
813 {
814   /* check direct components */
815   if (std::any_of(begin(vertices_), end(vertices_), [netpoint](const auto* elem) { return elem == netpoint; }))
816     return true;
817
818   /* check childrens */
819   return std::any_of(begin(children_), end(children_),
820                      [netpoint](const auto* child) { return child->is_component_recursive(netpoint); });
821 }
822 } // namespace simgrid::kernel::routing