Logo AND Algorithmique Numérique Distribuée

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