Logo AND Algorithmique Numérique Distribuée

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