Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Initialize models together with netzone root
[simgrid.git] / src / kernel / routing / NetZoneImpl.cpp
1 /* Copyright (c) 2006-2021. 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/NetZoneImpl.hpp"
7 #include "simgrid/kernel/routing/NetPoint.hpp"
8 #include "simgrid/s4u/Engine.hpp"
9 #include "simgrid/s4u/Host.hpp"
10 #include "src/include/simgrid/sg_config.hpp"
11 #include "src/kernel/EngineImpl.hpp"
12 #include "src/kernel/resource/DiskImpl.hpp"
13 #include "src/surf/HostImpl.hpp"
14 #include "src/surf/cpu_interface.hpp"
15 #include "src/surf/network_interface.hpp"
16 #include "src/surf/xml/platf_private.hpp"
17 #include "surf/surf.hpp"
18
19 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(surf_route);
20
21 namespace simgrid {
22 namespace kernel {
23 namespace routing {
24
25 /* Pick the right models for CPU, net and host, and call their model_init_preparse */
26 static void surf_config_models_setup()
27 {
28   std::string host_model_name    = simgrid::config::get_value<std::string>("host/model");
29   std::string network_model_name = simgrid::config::get_value<std::string>("network/model");
30   std::string cpu_model_name     = simgrid::config::get_value<std::string>("cpu/model");
31   std::string disk_model_name    = simgrid::config::get_value<std::string>("disk/model");
32
33   /* The compound host model is needed when using non-default net/cpu models */
34   if ((not simgrid::config::is_default("network/model") || not simgrid::config::is_default("cpu/model")) &&
35       simgrid::config::is_default("host/model")) {
36     host_model_name = "compound";
37     simgrid::config::set_value("host/model", host_model_name);
38   }
39
40   XBT_DEBUG("host model: %s", host_model_name.c_str());
41   if (host_model_name == "compound") {
42     xbt_assert(not cpu_model_name.empty(), "Set a cpu model to use with the 'compound' host model");
43     xbt_assert(not network_model_name.empty(), "Set a network model to use with the 'compound' host model");
44
45     int cpu_id = find_model_description(surf_cpu_model_description, cpu_model_name);
46     surf_cpu_model_description[cpu_id].model_init_preparse();
47
48     int network_id = find_model_description(surf_network_model_description, network_model_name);
49     surf_network_model_description[network_id].model_init_preparse();
50   }
51
52   XBT_DEBUG("Call host_model_init");
53   int host_id = find_model_description(surf_host_model_description, host_model_name);
54   surf_host_model_description[host_id].model_init_preparse();
55
56   XBT_DEBUG("Call vm_model_init");
57   /* ideally we should get back the pointer to CpuModel from model_init_preparse(), but this
58    * requires changing the declaration of surf_cpu_model_description.
59    * To be reviewed in the future */
60   surf_vm_model_init_HL13(
61       simgrid::s4u::Engine::get_instance()->get_netzone_root()->get_impl()->get_cpu_pm_model().get());
62
63   XBT_DEBUG("Call disk_model_init");
64   int disk_id = find_model_description(surf_disk_model_description, disk_model_name);
65   surf_disk_model_description[disk_id].model_init_preparse();
66 }
67
68 NetZoneImpl::NetZoneImpl(const std::string& name) : piface_(this), name_(name)
69 {
70   /* workaroud: first netzoneImpl will be the root netzone.
71    * Without globals and with current surf_*_model_description init functions, we need
72    * the root netzone to exist when creating the models.
73    * This was usually done at sg_platf.cpp, during XML parsing */
74   if (not s4u::Engine::get_instance()->get_netzone_root()) {
75     s4u::Engine::get_instance()->set_netzone_root(&piface_);
76     /* root netzone set, initialize models */
77     simgrid::s4u::Engine::on_platform_creation();
78
79     /* Initialize the surf models. That must be done after we got all config, and before we need the models.
80      * That is, after the last <config> tag, if any, and before the first of cluster|peer|zone|trace|trace_connect
81      *
82      * I'm not sure for <trace> and <trace_connect>, there may be a bug here
83      * (FIXME: check it out by creating a file beginning with one of these tags)
84      * but cluster and peer come down to zone creations, so putting this verification here is correct.
85      */
86     surf_config_models_setup();
87   }
88
89   xbt_assert(nullptr == s4u::Engine::get_instance()->netpoint_by_name_or_null(get_name()),
90              "Refusing to create a second NetZone called '%s'.", get_cname());
91   netpoint_ = new NetPoint(name_, NetPoint::Type::NetZone);
92   XBT_DEBUG("NetZone '%s' created with the id '%u'", get_cname(), netpoint_->id());
93 }
94
95 NetZoneImpl::~NetZoneImpl()
96 {
97   for (auto const& nz : children_)
98     delete nz;
99
100   for (auto const& kv : bypass_routes_)
101     delete kv.second;
102
103   s4u::Engine::get_instance()->netpoint_unregister(netpoint_);
104 }
105
106 void NetZoneImpl::add_child(NetZoneImpl* new_zone)
107 {
108   xbt_assert(not sealed_, "Cannot add a new child to the sealed zone %s", get_cname());
109   /* set the father behavior */
110   hierarchy_ = RoutingMode::recursive;
111   children_.push_back(new_zone);
112 }
113
114 /** @brief Returns the list of the hosts found in this NetZone (not recursively)
115  *
116  * Only the hosts that are directly contained in this NetZone are retrieved,
117  * not the ones contained in sub-netzones.
118  */
119 std::vector<s4u::Host*> NetZoneImpl::get_all_hosts() const
120 {
121   std::vector<s4u::Host*> res;
122   for (auto const& card : get_vertices()) {
123     s4u::Host* host = s4u::Host::by_name_or_null(card->get_name());
124     if (host != nullptr)
125       res.push_back(host);
126   }
127   return res;
128 }
129 int NetZoneImpl::get_host_count() const
130 {
131   int count = 0;
132   for (auto const& card : get_vertices()) {
133     const s4u::Host* host = s4u::Host::by_name_or_null(card->get_name());
134     if (host != nullptr)
135       count++;
136   }
137   return count;
138 }
139
140 s4u::Host* NetZoneImpl::create_host(const std::string& name, const std::vector<double>& speed_per_pstate)
141 {
142   auto* res = (new surf::HostImpl(name))->get_iface();
143   res->set_netpoint((new NetPoint(name, NetPoint::Type::Host))->set_englobing_zone(this));
144
145   cpu_model_pm_->create_cpu(res, speed_per_pstate);
146
147   return res;
148 }
149
150 s4u::Link* NetZoneImpl::create_link(const std::string& name, const std::vector<double>& bandwidths)
151 {
152   return network_model_->create_link(name, bandwidths)->get_iface();
153 }
154
155 s4u::Disk* NetZoneImpl::create_disk(const std::string& name, double read_bandwidth, double write_bandwidth)
156 {
157   auto* l = disk_model_->create_disk(name, read_bandwidth, write_bandwidth);
158
159   return l->get_iface();
160 }
161
162 NetPoint* NetZoneImpl::create_router(const std::string& name)
163 {
164   xbt_assert(nullptr == s4u::Engine::get_instance()->netpoint_by_name_or_null(name),
165              "Refusing to create a router named '%s': this name already describes a node.", name.c_str());
166
167   return (new NetPoint(name, NetPoint::Type::Router))->set_englobing_zone(this);
168 }
169 int NetZoneImpl::add_component(NetPoint* elm)
170 {
171   vertices_.push_back(elm);
172   return vertices_.size() - 1; // The rank of the newly created object
173 }
174
175 void NetZoneImpl::add_route(NetPoint* /*src*/, NetPoint* /*dst*/, NetPoint* /*gw_src*/, NetPoint* /*gw_dst*/,
176                             const std::vector<resource::LinkImpl*>& /*link_list*/, bool /*symmetrical*/)
177 {
178   xbt_die("NetZone '%s' does not accept new routes (wrong class).", get_cname());
179 }
180
181 void NetZoneImpl::add_bypass_route(NetPoint* src, NetPoint* dst, NetPoint* gw_src, NetPoint* gw_dst,
182                                    std::vector<resource::LinkImpl*>& link_list, bool /* symmetrical */)
183 {
184   /* Argument validity checks */
185   if (gw_dst) {
186     XBT_DEBUG("Load bypassNetzoneRoute from %s@%s to %s@%s", src->get_cname(), gw_src->get_cname(), dst->get_cname(),
187               gw_dst->get_cname());
188     xbt_assert(not link_list.empty(), "Bypass route between %s@%s and %s@%s cannot be empty.", src->get_cname(),
189                gw_src->get_cname(), dst->get_cname(), gw_dst->get_cname());
190     xbt_assert(bypass_routes_.find({src, dst}) == bypass_routes_.end(),
191                "The bypass route between %s@%s and %s@%s already exists.", src->get_cname(), gw_src->get_cname(),
192                dst->get_cname(), gw_dst->get_cname());
193   } else {
194     XBT_DEBUG("Load bypassRoute from %s to %s", src->get_cname(), dst->get_cname());
195     xbt_assert(not link_list.empty(), "Bypass route between %s and %s cannot be empty.", src->get_cname(),
196                dst->get_cname());
197     xbt_assert(bypass_routes_.find({src, dst}) == bypass_routes_.end(),
198                "The bypass route between %s and %s already exists.", src->get_cname(), dst->get_cname());
199   }
200
201   /* Build a copy that will be stored in the dict */
202   auto* newRoute = new BypassRoute(gw_src, gw_dst);
203   for (auto const& link : link_list)
204     newRoute->links.push_back(link);
205
206   /* Store it */
207   bypass_routes_.insert({{src, dst}, newRoute});
208 }
209
210 /** @brief Get the common ancestor and its first children in each line leading to src and dst
211  *
212  * In the recursive case, this sets common_ancestor, src_ancestor and dst_ancestor are set as follows.
213  * @verbatim
214  *         platform root
215  *               |
216  *              ...                <- possibly long path
217  *               |
218  *         common_ancestor
219  *           /        \
220  *          /          \
221  *         /            \          <- direct links
222  *        /              \
223  *       /                \
224  *  src_ancestor     dst_ancestor  <- must be different in the recursive case
225  *      |                   |
226  *     ...                 ...     <-- possibly long paths (one hop or more)
227  *      |                   |
228  *     src                 dst
229  *  @endverbatim
230  *
231  *  In the base case (when src and dst are in the same netzone), things are as follows:
232  *  @verbatim
233  *                  platform root
234  *                        |
235  *                       ...                      <-- possibly long path
236  *                        |
237  * common_ancestor==src_ancestor==dst_ancestor    <-- all the same value
238  *                   /        \
239  *                  /          \                  <-- direct links (exactly one hop)
240  *                 /            \
241  *              src              dst
242  *  @endverbatim
243  *
244  * A specific recursive case occurs when src is the ancestor of dst. In this case,
245  * the base case routing should be used so the common_ancestor is specifically set
246  * to src_ancestor==dst_ancestor.
247  * Naturally, things are completely symmetrical if dst is the ancestor of src.
248  * @verbatim
249  *            platform root
250  *                  |
251  *                 ...                <-- possibly long path
252  *                  |
253  *  src == src_ancestor==dst_ancestor==common_ancestor <-- same value
254  *                  |
255  *                 ...                <-- possibly long path (one hop or more)
256  *                  |
257  *                 dst
258  *  @endverbatim
259  */
260 static void find_common_ancestors(NetPoint* src, NetPoint* dst,
261                                   /* OUT */ NetZoneImpl** common_ancestor, NetZoneImpl** src_ancestor,
262                                   NetZoneImpl** dst_ancestor)
263 {
264   /* Deal with the easy base case */
265   if (src->get_englobing_zone() == dst->get_englobing_zone()) {
266     *common_ancestor = src->get_englobing_zone();
267     *src_ancestor    = *common_ancestor;
268     *dst_ancestor    = *common_ancestor;
269     return;
270   }
271
272   /* engage the full recursive search */
273
274   /* (1) find the path to root of src and dst*/
275   const NetZoneImpl* src_as = src->get_englobing_zone();
276   const NetZoneImpl* dst_as = dst->get_englobing_zone();
277
278   xbt_assert(src_as, "Host %s must be in a netzone", src->get_cname());
279   xbt_assert(dst_as, "Host %s must be in a netzone", dst->get_cname());
280
281   /* (2) find the path to the root routing component */
282   std::vector<NetZoneImpl*> path_src;
283   NetZoneImpl* current = src->get_englobing_zone();
284   while (current != nullptr) {
285     path_src.push_back(current);
286     current = current->get_parent();
287   }
288   std::vector<NetZoneImpl*> path_dst;
289   current = dst->get_englobing_zone();
290   while (current != nullptr) {
291     path_dst.push_back(current);
292     current = current->get_parent();
293   }
294
295   /* (3) find the common father.
296    * Before that, index_src and index_dst may be different, they both point to nullptr in path_src/path_dst
297    * So we move them down simultaneously as long as they point to the same content.
298    *
299    * This works because all SimGrid platform have a unique root element (that is the last element of both paths).
300    */
301   NetZoneImpl* father = nullptr; // the netzone we dropped on the previous loop iteration
302   while (path_src.size() > 1 && path_dst.size() > 1 &&
303          path_src.at(path_src.size() - 1) == path_dst.at(path_dst.size() - 1)) {
304     father = path_src.at(path_src.size() - 1);
305     path_src.pop_back();
306     path_dst.pop_back();
307   }
308
309   /* (4) we found the difference at least. Finalize the returned values */
310   *src_ancestor = path_src.at(path_src.size() - 1); /* the first different father of src */
311   *dst_ancestor = path_dst.at(path_dst.size() - 1); /* the first different father of dst */
312   if (*src_ancestor == *dst_ancestor) {             // src is the ancestor of dst, or the contrary
313     *common_ancestor = *src_ancestor;
314   } else {
315     *common_ancestor = father;
316   }
317 }
318
319 /* PRECONDITION: this is the common ancestor of src and dst */
320 bool NetZoneImpl::get_bypass_route(NetPoint* src, NetPoint* dst,
321                                    /* OUT */ std::vector<resource::LinkImpl*>& links, double* latency)
322 {
323   // If never set a bypass route return nullptr without any further computations
324   if (bypass_routes_.empty())
325     return false;
326
327   /* Base case, no recursion is needed */
328   if (dst->get_englobing_zone() == this && src->get_englobing_zone() == this) {
329     if (bypass_routes_.find({src, dst}) != bypass_routes_.end()) {
330       const BypassRoute* bypassedRoute = bypass_routes_.at({src, dst});
331       for (resource::LinkImpl* const& link : bypassedRoute->links) {
332         links.push_back(link);
333         if (latency)
334           *latency += link->get_latency();
335       }
336       XBT_DEBUG("Found a bypass route from '%s' to '%s' with %zu links", src->get_cname(), dst->get_cname(),
337                 bypassedRoute->links.size());
338       return true;
339     }
340     return false;
341   }
342
343   /* Engage recursive search */
344
345   /* (1) find the path to the root routing component */
346   std::vector<NetZoneImpl*> path_src;
347   NetZoneImpl* current = src->get_englobing_zone();
348   while (current != nullptr) {
349     path_src.push_back(current);
350     current = current->parent_;
351   }
352
353   std::vector<NetZoneImpl*> path_dst;
354   current = dst->get_englobing_zone();
355   while (current != nullptr) {
356     path_dst.push_back(current);
357     current = current->parent_;
358   }
359
360   /* (2) find the common father */
361   while (path_src.size() > 1 && path_dst.size() > 1 &&
362          path_src.at(path_src.size() - 1) == path_dst.at(path_dst.size() - 1)) {
363     path_src.pop_back();
364     path_dst.pop_back();
365   }
366
367   /* (3) Search for a bypass making the path up to the ancestor useless */
368   const BypassRoute* bypassedRoute = nullptr;
369   std::pair<kernel::routing::NetPoint*, kernel::routing::NetPoint*> key;
370   // Search for a bypass with the given indices. Returns true if found. Initialize variables `bypassedRoute' and `key'.
371   auto lookup = [&bypassedRoute, &key, &path_src, &path_dst, this](unsigned src_index, unsigned dst_index) {
372     if (src_index < path_src.size() && dst_index < path_dst.size()) {
373       key      = {path_src[src_index]->netpoint_, path_dst[dst_index]->netpoint_};
374       auto bpr = bypass_routes_.find(key);
375       if (bpr != bypass_routes_.end()) {
376         bypassedRoute = bpr->second;
377         return true;
378       }
379     }
380     return false;
381   };
382
383   for (unsigned max = 0, max_index = std::max(path_src.size(), path_dst.size()); max < max_index; max++) {
384     for (unsigned i = 0; i < max; i++) {
385       if (lookup(i, max) || lookup(max, i))
386         break;
387     }
388     if (bypassedRoute || lookup(max, max))
389       break;
390   }
391
392   /* (4) If we have the bypass, use it. If not, caller will do the Right Thing. */
393   if (bypassedRoute) {
394     XBT_DEBUG("Found a bypass route from '%s' to '%s' with %zu links. We may have to complete it with recursive "
395               "calls to getRoute",
396               src->get_cname(), dst->get_cname(), bypassedRoute->links.size());
397     if (src != key.first)
398       get_global_route(src, bypassedRoute->gw_src, links, latency);
399     for (resource::LinkImpl* const& link : bypassedRoute->links) {
400       links.push_back(link);
401       if (latency)
402         *latency += link->get_latency();
403     }
404     if (dst != key.second)
405       get_global_route(bypassedRoute->gw_dst, dst, links, latency);
406     return true;
407   }
408   XBT_DEBUG("No bypass route from '%s' to '%s'.", src->get_cname(), dst->get_cname());
409   return false;
410 }
411
412 void NetZoneImpl::get_global_route(NetPoint* src, NetPoint* dst,
413                                    /* OUT */ std::vector<resource::LinkImpl*>& links, double* latency)
414 {
415   RouteCreationArgs route;
416
417   XBT_DEBUG("Resolve route from '%s' to '%s'", src->get_cname(), dst->get_cname());
418
419   /* Find how src and dst are interconnected */
420   NetZoneImpl* common_ancestor;
421   NetZoneImpl* src_ancestor;
422   NetZoneImpl* dst_ancestor;
423   find_common_ancestors(src, dst, &common_ancestor, &src_ancestor, &dst_ancestor);
424   XBT_DEBUG("elements_father: common ancestor '%s' src ancestor '%s' dst ancestor '%s'", common_ancestor->get_cname(),
425             src_ancestor->get_cname(), dst_ancestor->get_cname());
426
427   /* Check whether a direct bypass is defined. If so, use it and bail out */
428   if (common_ancestor->get_bypass_route(src, dst, links, latency))
429     return;
430
431   /* If src and dst are in the same netzone, life is good */
432   if (src_ancestor == dst_ancestor) { /* SURF_ROUTING_BASE */
433     route.link_list = std::move(links);
434     common_ancestor->get_local_route(src, dst, &route, latency);
435     links = std::move(route.link_list);
436     return;
437   }
438
439   /* Not in the same netzone, no bypass. We'll have to find our path between the netzones recursively */
440
441   common_ancestor->get_local_route(src_ancestor->netpoint_, dst_ancestor->netpoint_, &route, latency);
442   xbt_assert((route.gw_src != nullptr) && (route.gw_dst != nullptr), "Bad gateways for route from '%s' to '%s'.",
443              src->get_cname(), dst->get_cname());
444
445   /* If source gateway is not our source, we have to recursively find our way up to this point */
446   if (src != route.gw_src)
447     get_global_route(src, route.gw_src, links, latency);
448   links.insert(links.end(), begin(route.link_list), end(route.link_list));
449
450   /* If dest gateway is not our destination, we have to recursively find our way from this point */
451   if (route.gw_dst != dst)
452     get_global_route(route.gw_dst, dst, links, latency);
453 }
454
455 void NetZoneImpl::seal()
456 {
457   /* already sealed netzone */
458   if (sealed_)
459     return;
460   do_seal(); // derived class' specific sealing procedure
461
462   /* seals sub-netzones and hosts */
463   for (auto* host : get_all_hosts()) {
464     host->seal();
465   }
466   for (auto* sub_net : get_children()) {
467     sub_net->seal();
468   }
469   sealed_ = true;
470 }
471
472 void NetZoneImpl::set_parent(NetZoneImpl* parent)
473 {
474   xbt_assert(not sealed_, "Impossible to set parent to an already sealed NetZone(%s)", this->get_cname());
475   parent_ = parent;
476   netpoint_->set_englobing_zone(parent_);
477   if (parent) {
478     /* adding this class as child */
479     parent->add_child(this);
480     /* copying models from parent host, to be reviewed when we allow multi-models */
481     set_network_model(parent->get_network_model());
482     set_cpu_pm_model(parent->get_cpu_pm_model());
483     set_cpu_vm_model(parent->get_cpu_vm_model());
484     set_disk_model(parent->get_disk_model());
485     set_host_model(parent->get_host_model());
486   }
487 }
488
489 void NetZoneImpl::set_network_model(std::shared_ptr<resource::NetworkModel> netmodel)
490 {
491   xbt_assert(not sealed_, "Impossible to set network model to an already sealed NetZone(%s)", this->get_cname());
492   network_model_ = std::move(netmodel);
493 }
494
495 void NetZoneImpl::set_cpu_vm_model(std::shared_ptr<resource::CpuModel> cpu_model)
496 {
497   xbt_assert(not sealed_, "Impossible to set CPU model to an already sealed NetZone(%s)", this->get_cname());
498   cpu_model_vm_ = std::move(cpu_model);
499 }
500
501 void NetZoneImpl::set_cpu_pm_model(std::shared_ptr<resource::CpuModel> cpu_model)
502 {
503   xbt_assert(not sealed_, "Impossible to set CPU model to an already sealed NetZone(%s)", this->get_cname());
504   cpu_model_pm_ = std::move(cpu_model);
505 }
506
507 void NetZoneImpl::set_disk_model(std::shared_ptr<resource::DiskModel> disk_model)
508 {
509   xbt_assert(not sealed_, "Impossible to set disk model to an already sealed NetZone(%s)", this->get_cname());
510   disk_model_ = std::move(disk_model);
511 }
512
513 void NetZoneImpl::set_host_model(std::shared_ptr<surf::HostModel> host_model)
514 {
515   xbt_assert(not sealed_, "Impossible to set host model to an already sealed NetZone(%s)", this->get_cname());
516   host_model_ = std::move(host_model);
517 }
518
519 } // namespace routing
520 } // namespace kernel
521 } // namespace simgrid