Logo AND Algorithmique Numérique Distribuée

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