Logo AND Algorithmique Numérique Distribuée

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