Logo AND Algorithmique Numérique Distribuée

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