Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'master' of framagit.org:simgrid/simgrid
[simgrid.git] / src / kernel / routing / FatTreeZone.cpp
1 /* Copyright (c) 2014-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/FatTreeZone.hpp>
7 #include <simgrid/kernel/routing/NetPoint.hpp>
8
9 #include "src/kernel/resource/NetworkModel.hpp"
10 #include "src/kernel/xml/platf.hpp" // simgrid_parse_error() and simgrid_parse_assert()
11
12 #include <fstream>
13 #include <numeric>
14 #include <sstream>
15 #include <string>
16
17 #include <boost/algorithm/string/classification.hpp>
18 #include <boost/algorithm/string/split.hpp>
19
20 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(ker_routing_fat_tree, ker_platform, "Kernel Fat-Tree Routing");
21
22 namespace simgrid {
23 namespace kernel::routing {
24
25 bool FatTreeZone::is_in_sub_tree(const FatTreeNode* root, const FatTreeNode* node) const
26 {
27   XBT_DEBUG("Is %d(%u,%u) in the sub tree of %d(%u,%u) ?", node->id, node->level, node->position, root->id, root->level,
28             root->position);
29   if (root->level <= node->level) {
30     return false;
31   }
32   for (unsigned int i = 0; i < node->level; i++) {
33     if (root->label[i] != node->label[i]) {
34       return false;
35     }
36   }
37
38   for (unsigned int i = root->level; i < this->levels_; i++) {
39     if (root->label[i] != node->label[i]) {
40       return false;
41     }
42   }
43   return true;
44 }
45
46 void FatTreeZone::get_local_route(const NetPoint* src, const NetPoint* dst, Route* into, double* latency)
47 {
48   if (dst->is_router() || src->is_router())
49     return;
50
51   /* Let's find the source and the destination in our internal structure */
52   auto searchedNode = this->compute_nodes_.find(src->id());
53   xbt_assert(searchedNode != this->compute_nodes_.end(), "Could not find the source %s [%lu] in the fat tree",
54              src->get_cname(), src->id());
55   const FatTreeNode* source = searchedNode->second.get();
56
57   searchedNode = this->compute_nodes_.find(dst->id());
58   xbt_assert(searchedNode != this->compute_nodes_.end(), "Could not find the destination %s [%lu] in the fat tree",
59              dst->get_cname(), dst->id());
60   const FatTreeNode* destination = searchedNode->second.get();
61
62   XBT_VERB("Get route and latency from '%s' [%lu] to '%s' [%lu] in a fat tree", src->get_cname(), src->id(),
63            dst->get_cname(), dst->id());
64
65   /* In case destination is the source, and there is a loopback, let's use it instead of going up to a switch */
66   if (source->id == destination->id && has_loopback()) {
67     add_link_latency(into->link_list_, source->loopback_, latency);
68     return;
69   }
70
71   const FatTreeNode* currentNode = source;
72
73   // up part
74   while (not is_in_sub_tree(currentNode, destination)) {
75     int d = destination->position; // as in d-mod-k
76
77     for (unsigned int i = 0; i < currentNode->level; i++)
78       d /= this->num_parents_per_node_[i];
79
80     int k = this->num_parents_per_node_[currentNode->level] * this->num_port_lower_level_[currentNode->level];
81     d = d % k;
82
83     if (currentNode->limiter_link_)
84       into->link_list_.push_back(currentNode->limiter_link_);
85
86     add_link_latency(into->link_list_, currentNode->parents[d]->up_link_, latency);
87
88     currentNode = currentNode->parents[d]->up_node_;
89   }
90
91   XBT_DEBUG("%d(%u,%u) is in the sub tree of %d(%u,%u).", destination->id, destination->level, destination->position,
92             currentNode->id, currentNode->level, currentNode->position);
93
94   // Down part
95   while (currentNode != destination) {
96     //pick cable when multiple parallels
97     int d = source->position % this->num_port_lower_level_[currentNode->level - 1];
98     for (unsigned int i = d * this->num_children_per_node_[currentNode->level - 1]; i < currentNode->children.size(); i++) {
99       if (i % this->num_children_per_node_[currentNode->level - 1] == destination->label[currentNode->level - 1]) {
100         add_link_latency(into->link_list_, currentNode->children[i]->down_link_, latency);
101
102         if (currentNode->limiter_link_)
103           into->link_list_.push_back(currentNode->limiter_link_);
104
105         currentNode = currentNode->children[i]->down_node_;
106         XBT_DEBUG("%d(%u,%u) is accessible through %d(%u,%u)", destination->id, destination->level,
107                   destination->position, currentNode->id, currentNode->level, currentNode->position);
108       }
109     }
110   }
111   if (currentNode->limiter_link_) { // limiter for receiver/destination
112     into->link_list_.push_back(currentNode->limiter_link_);
113   }
114   // set gateways (if any)
115   into->gw_src_ = get_gateway(src->id());
116   into->gw_dst_ = get_gateway(dst->id());
117 }
118
119 void FatTreeZone::build_upper_levels(const s4u::ClusterCallbacks& set_callbacks)
120 {
121   generate_switches(set_callbacks);
122   generate_labels();
123
124   unsigned int k = 0;
125   // Nodes are totally ordered, by level and then by position, in this->nodes
126   for (unsigned int i = 0; i < levels_; i++) {
127     for (unsigned int j = 0; j < nodes_by_level_[i]; j++) {
128       connect_node_to_parents(nodes_[k].get());
129       k++;
130     }
131   }
132 }
133
134 void FatTreeZone::do_seal()
135 {
136   if (this->levels_ == 0) {
137     return;
138   }
139   if (not XBT_LOG_ISENABLED(ker_routing_fat_tree, xbt_log_priority_debug)) {
140     return;
141   }
142
143   /* for debugging purpose only, Fat-Tree is already build when seal is called */
144   std::stringstream msgBuffer;
145
146   msgBuffer << "We are creating a fat tree of " << this->levels_ << " levels "
147             << "with " << this->nodes_by_level_[0] << " processing nodes";
148   for (unsigned int i = 1; i <= this->levels_; i++) {
149     msgBuffer << ", " << this->nodes_by_level_[i] << " switches at level " << i;
150   }
151   XBT_DEBUG("%s", msgBuffer.str().c_str());
152   msgBuffer.str("");
153   msgBuffer << "Nodes are : ";
154
155   for (auto const& node : this->nodes_) {
156     msgBuffer << node->id << "(" << node->level << "," << node->position << ") ";
157   }
158   XBT_DEBUG("%s", msgBuffer.str().c_str());
159
160   msgBuffer.clear();
161   msgBuffer << "Links are : ";
162   for (auto const& link : this->links_) {
163     msgBuffer << "(" << link->up_node_->id << "," << link->down_node_->id << ") ";
164   }
165   XBT_DEBUG("%s", msgBuffer.str().c_str());
166 }
167
168 int FatTreeZone::connect_node_to_parents(FatTreeNode* node)
169 {
170   auto currentParentNode = this->nodes_.begin();
171   int connectionsNumber  = 0;
172   const int level        = node->level;
173   XBT_DEBUG("We are connecting node %d(%u,%u) to his parents.", node->id, node->level, node->position);
174   currentParentNode += this->get_level_position(level + 1);
175   for (unsigned int i = 0; i < this->nodes_by_level_[level + 1]; i++) {
176     if (this->are_related(currentParentNode->get(), node)) {
177       XBT_DEBUG("%d(%u,%u) and %d(%u,%u) are related,"
178                 " with %u links between them.",
179                 node->id, node->level, node->position, (*currentParentNode)->id, (*currentParentNode)->level,
180                 (*currentParentNode)->position, this->num_port_lower_level_[level]);
181       for (unsigned int j = 0; j < this->num_port_lower_level_[level]; j++) {
182         this->add_link(currentParentNode->get(), node->label[level] + j * this->num_children_per_node_[level], node,
183                        (*currentParentNode)->label[level] + j * this->num_parents_per_node_[level]);
184       }
185       connectionsNumber++;
186     }
187     ++currentParentNode;
188   }
189   return connectionsNumber;
190 }
191
192 bool FatTreeZone::are_related(FatTreeNode* parent, FatTreeNode* child) const
193 {
194   std::stringstream msgBuffer;
195
196   if (XBT_LOG_ISENABLED(ker_routing_fat_tree, xbt_log_priority_debug)) {
197     msgBuffer << "Are " << child->id << "(" << child->level << "," << child->position << ") <";
198
199     for (unsigned int i = 0; i < this->levels_; i++) {
200       msgBuffer << child->label[i] << ",";
201     }
202     msgBuffer << ">";
203
204     msgBuffer << " and " << parent->id << "(" << parent->level << "," << parent->position << ") <";
205     for (unsigned int i = 0; i < this->levels_; i++) {
206       msgBuffer << parent->label[i] << ",";
207     }
208     msgBuffer << ">";
209     msgBuffer << " related ? ";
210     XBT_DEBUG("%s", msgBuffer.str().c_str());
211   }
212   if (parent->level != child->level + 1) {
213     return false;
214   }
215
216   for (unsigned int i = 0; i < this->levels_; i++) {
217     if (parent->label[i] != child->label[i] && i + 1 != parent->level) {
218       return false;
219     }
220   }
221   return true;
222 }
223
224 void FatTreeZone::generate_switches(const s4u::ClusterCallbacks& set_callbacks)
225 {
226   XBT_DEBUG("Generating switches.");
227   this->nodes_by_level_.resize(this->levels_ + 1, 0);
228
229   // Take care of the number of nodes by level
230   this->nodes_by_level_[0] = 1;
231   for (unsigned int i = 0; i < this->levels_; i++)
232     this->nodes_by_level_[0] *= this->num_children_per_node_[i];
233
234   if (this->nodes_by_level_[0] != this->nodes_.size()) {
235     simgrid_parse_error("The number of provided nodes does not fit with the wanted topology."
236                         " Please check your platform description (We need " +
237                         std::to_string(this->nodes_by_level_[0]) + "nodes, we got " +
238                         std::to_string(this->nodes_.size()));
239   }
240
241   for (unsigned int i = 0; i < this->levels_; i++) {
242     int nodesInThisLevel = 1;
243
244     for (unsigned int j = 0; j <= i; j++)
245       nodesInThisLevel *= this->num_parents_per_node_[j];
246
247     for (unsigned int j = i + 1; j < this->levels_; j++)
248       nodesInThisLevel *= this->num_children_per_node_[j];
249
250     this->nodes_by_level_[i + 1] = nodesInThisLevel;
251   }
252
253   /* get limiter for this router */
254   auto get_limiter = [this, &set_callbacks](unsigned long i, unsigned long j, long id) -> resource::StandardLinkImpl* {
255     kernel::resource::StandardLinkImpl* limiter = nullptr;
256     if (set_callbacks.limiter) {
257       const auto* s4u_link = set_callbacks.limiter(get_iface(), {i + 1, j}, id);
258       if (s4u_link) {
259         limiter = s4u_link->get_impl();
260       }
261     }
262     return limiter;
263   };
264   // Create the switches
265   unsigned long k = 2 * nodes_.size();
266   for (unsigned long i = 0; i < this->levels_; i++) {
267     for (unsigned long j = 0; j < this->nodes_by_level_[i + 1]; j++) {
268       k--;
269       auto newNode = std::make_shared<FatTreeNode>(k, i + 1, j, get_limiter(i, j, k), nullptr);
270       XBT_DEBUG("We create the switch %d(%u,%u)", newNode->id, newNode->level, newNode->position);
271       newNode->children.resize(static_cast<size_t>(this->num_children_per_node_[i]) * this->num_port_lower_level_[i]);
272       if (i != this->levels_ - 1) {
273         newNode->parents.resize(static_cast<size_t>(this->num_parents_per_node_[i + 1]) *
274                                 this->num_port_lower_level_[i + 1]);
275       }
276       newNode->label.resize(this->levels_);
277       this->nodes_.emplace_back(newNode);
278     }
279   }
280 }
281
282 void FatTreeZone::generate_labels()
283 {
284   XBT_DEBUG("Generating labels.");
285   // TODO : check if nodesByLevel and nodes are filled
286   std::vector<int> maxLabel(this->levels_);
287   std::vector<int> currentLabel(this->levels_);
288   unsigned int k = 0;
289   for (unsigned int i = 0; i <= this->levels_; i++) {
290     currentLabel.assign(this->levels_, 0);
291     for (unsigned int j = 0; j < this->levels_; j++) {
292       maxLabel[j] = j + 1 > i ? this->num_children_per_node_[j] : this->num_parents_per_node_[j];
293     }
294
295     for (unsigned int j = 0; j < this->nodes_by_level_[i]; j++) {
296       if (XBT_LOG_ISENABLED(ker_routing_fat_tree, xbt_log_priority_debug)) {
297         std::stringstream msgBuffer;
298
299         msgBuffer << "Assigning label <";
300         for (unsigned int l = 0; l < this->levels_; l++) {
301           msgBuffer << currentLabel[l] << ",";
302         }
303         msgBuffer << "> to " << k << " (" << i << "," << j << ")";
304
305         XBT_DEBUG("%s", msgBuffer.str().c_str());
306       }
307       this->nodes_[k]->label.assign(currentLabel.begin(), currentLabel.end());
308
309       bool remainder   = true;
310       unsigned int pos = 0;
311       while (remainder && pos < this->levels_) {
312         ++currentLabel[pos];
313         if (currentLabel[pos] >= maxLabel[pos]) {
314           currentLabel[pos] = 0;
315           remainder         = true;
316           ++pos;
317         } else {
318           pos       = 0;
319           remainder = false;
320         }
321       }
322       k++;
323     }
324   }
325 }
326
327 int FatTreeZone::get_level_position(const unsigned int level)
328 {
329   xbt_assert(level <= this->levels_, "The impossible did happen. Yet again.");
330   int tempPosition = 0;
331
332   for (unsigned int i = 0; i < level; i++)
333     tempPosition += this->nodes_by_level_[i];
334
335   return tempPosition;
336 }
337
338 void FatTreeZone::add_processing_node(int id, resource::StandardLinkImpl* limiter, resource::StandardLinkImpl* loopback)
339 {
340   using std::make_pair;
341   static int position = 0;
342   auto newNode = std::make_shared<FatTreeNode>(id, 0, position, limiter, loopback);
343   position++;
344   newNode->parents.resize(static_cast<size_t>(this->num_parents_per_node_[0]) * this->num_port_lower_level_[0]);
345   newNode->label.resize(this->levels_);
346   this->compute_nodes_.try_emplace(id, newNode);
347   this->nodes_.emplace_back(newNode);
348 }
349
350 void FatTreeZone::add_link(FatTreeNode* parent, unsigned int parentPort, FatTreeNode* child, unsigned int childPort)
351 {
352   static int uniqueId = 0;
353   const s4u::Link* linkup;
354   const s4u::Link* linkdown;
355   std::string id =
356       "link_from_" + std::to_string(child->id) + "_" + std::to_string(parent->id) + "_" + std::to_string(uniqueId);
357
358   if (get_link_sharing_policy() == s4u::Link::SharingPolicy::SPLITDUPLEX) {
359     linkup   = create_link(id + "_UP", {get_link_bandwidth()})->set_latency(get_link_latency())->seal();
360     linkdown = create_link(id + "_DOWN", {get_link_bandwidth()})->set_latency(get_link_latency())->seal();
361   } else {
362     linkup   = create_link(id, {get_link_bandwidth()})->set_latency(get_link_latency())->seal();
363     linkdown = linkup;
364   }
365   uniqueId++;
366
367   auto newLink = std::make_shared<FatTreeLink>(child, parent, linkup->get_impl(), linkdown->get_impl());
368   XBT_DEBUG("Creating a link between the parent (%u,%u,%u) and the child (%u,%u,%u)", parent->level, parent->position,
369             parentPort, child->level, child->position, childPort);
370   parent->children[parentPort] = newLink;
371   child->parents[childPort]    = newLink;
372
373   this->links_.emplace_back(newLink);
374 }
375
376 void FatTreeZone::check_topology(unsigned int n_levels, const std::vector<unsigned int>& down_links,
377                                  const std::vector<unsigned int>& up_links, const std::vector<unsigned int>& link_count)
378
379 {
380   /* check number of levels */
381   if (n_levels == 0)
382     throw std::invalid_argument("FatTreeZone: invalid number of levels, must be > 0");
383
384   auto check_vector = [&n_levels](const std::vector<unsigned int>& vector, const std::string& var_name) {
385     if (vector.size() != n_levels)
386       throw std::invalid_argument("FatTreeZone: invalid " + var_name + " parameter, vector has " +
387                                   std::to_string(vector.size()) + " elements, must have " + std::to_string(n_levels));
388
389     auto check_zero = [](unsigned int i) { return i == 0; };
390     if (std::any_of(vector.begin(), vector.end(), check_zero))
391       throw std::invalid_argument("FatTreeZone: invalid " + var_name + " parameter, all values must be greater than 0");
392   };
393
394   /* check remaining vectors */
395   check_vector(down_links, "down links");
396   check_vector(up_links, "up links");
397   check_vector(link_count, "link count");
398 }
399
400 void FatTreeZone::set_topology(unsigned int n_levels, const std::vector<unsigned int>& down_links,
401                                const std::vector<unsigned int>& up_links, const std::vector<unsigned int>& link_count)
402 {
403   levels_                = n_levels;
404   num_children_per_node_ = down_links;
405   num_parents_per_node_  = up_links;
406   num_port_lower_level_  = link_count;
407 }
408
409 s4u::FatTreeParams FatTreeZone::parse_topo_parameters(const std::string& topo_parameters)
410 {
411   std::vector<std::string> parameters;
412   std::vector<std::string> tmp;
413   unsigned int n_lev = 0;
414   std::vector<unsigned int> down;
415   std::vector<unsigned int> up;
416   std::vector<unsigned int> count;
417   boost::split(parameters, topo_parameters, boost::is_any_of(";"));
418
419   simgrid_parse_assert(
420       parameters.size() == 4,
421       "Fat trees are defined by the levels number and 3 vectors, see the documentation for more information.");
422
423   // The first parts of topo_parameters should be the levels number
424   try {
425     n_lev = std::stoi(parameters[0]);
426   } catch (const std::invalid_argument&) {
427     simgrid_parse_error("First parameter is not the amount of levels: " + parameters[0]);
428   }
429
430   // Then, a l-sized vector standing for the children number by level
431   boost::split(tmp, parameters[1], boost::is_any_of(","));
432   simgrid_parse_assert(tmp.size() == n_lev, "You specified " + std::to_string(n_lev) +
433                                                 " levels but the child count vector (the first one) contains " +
434                                                 std::to_string(tmp.size()) + " levels.");
435
436   for (std::string const& level : tmp) {
437     try {
438       down.push_back(std::stoi(level));
439     } catch (const std::invalid_argument&) {
440       simgrid_parse_error("Invalid child count: " + level);
441     }
442   }
443
444   // Then, a l-sized vector standing for the parents number by level
445   boost::split(tmp, parameters[2], boost::is_any_of(","));
446   simgrid_parse_assert(tmp.size() == n_lev, "You specified " + std::to_string(n_lev) +
447                                                 " levels but the parent count vector (the second one) contains " +
448                                                 std::to_string(tmp.size()) + " levels.");
449   for (std::string const& parent : tmp) {
450     try {
451       up.push_back(std::stoi(parent));
452     } catch (const std::invalid_argument&) {
453       simgrid_parse_error("Invalid parent count: " + parent);
454     }
455   }
456
457   // Finally, a l-sized vector standing for the ports number with the lower level
458   boost::split(tmp, parameters[3], boost::is_any_of(","));
459   simgrid_parse_assert(tmp.size() == n_lev, "You specified " + std::to_string(n_lev) +
460                                                 " levels but the port count vector (the third one) contains " +
461                                                 std::to_string(tmp.size()) + " levels.");
462   for (std::string const& port : tmp) {
463     try {
464       count.push_back(std::stoi(port));
465     } catch (const std::invalid_argument&) {
466       throw std::invalid_argument("Invalid lower level port number:" + port);
467     }
468   }
469   return s4u::FatTreeParams(n_lev, down, up, count);
470 }
471
472 void FatTreeZone::generate_dot_file(const std::string& filename) const
473 {
474   std::ofstream file;
475   file.open(filename, std::ios::out | std::ios::trunc);
476   xbt_assert(file.is_open(), "Unable to open file %s", filename.c_str());
477
478   file << "graph AsClusterFatTree {\n";
479   for (auto const& node : this->nodes_) {
480     file << node->id;
481     if (node->id < 0)
482       file << " [shape=circle];\n";
483     else
484       file << " [shape=hexagon];\n";
485   }
486
487   for (auto const& link : this->links_) {
488     file << link->down_node_->id << " -- " << link->up_node_->id << ";\n";
489   }
490   file << "}";
491   file.close();
492 }
493 } // namespace kernel::routing
494
495 namespace s4u {
496 FatTreeParams::FatTreeParams(unsigned int n_levels, const std::vector<unsigned int>& down_links,
497                              const std::vector<unsigned int>& up_links, const std::vector<unsigned int>& links_number)
498     : levels(n_levels), down(down_links), up(up_links), number(links_number)
499 {
500   kernel::routing::FatTreeZone::check_topology(levels, down, up, number);
501 }
502
503 NetZone* create_fatTree_zone(const std::string& name, const NetZone* parent, const FatTreeParams& params,
504                              const ClusterCallbacks& set_callbacks, double bandwidth, double latency,
505                              Link::SharingPolicy sharing_policy)
506 {
507   /* initial checks */
508   if (bandwidth <= 0)
509     throw std::invalid_argument("FatTreeZone: incorrect bandwidth for internode communication, bw=" +
510                                 std::to_string(bandwidth));
511   if (latency < 0)
512     throw std::invalid_argument("FatTreeZone: incorrect latency for internode communication, lat=" +
513                                 std::to_string(latency));
514
515   /* creating zone */
516   auto* zone = new kernel::routing::FatTreeZone(name);
517   zone->set_topology(params.levels, params.down, params.up, params.number);
518   if (parent)
519     zone->set_parent(parent->get_impl());
520   zone->set_link_characteristics(bandwidth, latency, sharing_policy);
521
522   /* populating it */
523   unsigned int tot_elements = std::accumulate(params.down.begin(), params.down.end(), 1, std::multiplies<>());
524   for (unsigned int i = 0; i < tot_elements; i++) {
525     kernel::routing::NetPoint* netpoint;
526     Link* limiter;
527     Link* loopback;
528     /* coordinates are based on 2 indexes: number of levels and id */
529     zone->fill_leaf_from_cb(i, {params.levels + 1, tot_elements}, set_callbacks, &netpoint, &loopback, &limiter);
530     zone->add_processing_node(i, limiter ? limiter->get_impl() : nullptr, loopback ? loopback->get_impl() : nullptr);
531   }
532   zone->build_upper_levels(set_callbacks);
533
534   return zone->get_iface();
535 }
536 } // namespace s4u
537
538 } // namespace simgrid