Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
990ae61924477d3d82a1ba15663af9382bbec09a
[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/NetworkModel.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(ker_routing_fat_tree, ker_routing, "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] * this->num_port_lower_level_[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     surf_parse_error(std::string("The number of provided nodes does not fit with the wanted topology.") +
236                      " Please check your platform description (We need " + std::to_string(this->nodes_by_level_[0]) +
237                      "nodes, we got " + std::to_string(this->nodes_.size()));
238   }
239
240   for (unsigned int i = 0; i < this->levels_; i++) {
241     int nodesInThisLevel = 1;
242
243     for (unsigned int j = 0; j <= i; j++)
244       nodesInThisLevel *= this->num_parents_per_node_[j];
245
246     for (unsigned int j = i + 1; j < this->levels_; j++)
247       nodesInThisLevel *= this->num_children_per_node_[j];
248
249     this->nodes_by_level_[i + 1] = nodesInThisLevel;
250   }
251
252   /* get limiter for this router */
253   auto get_limiter = [this, &set_callbacks](unsigned long i, unsigned long j, long id) -> resource::StandardLinkImpl* {
254     kernel::resource::StandardLinkImpl* limiter = nullptr;
255     if (set_callbacks.limiter) {
256       const auto* s4u_link = set_callbacks.limiter(get_iface(), {i + 1, j}, id);
257       if (s4u_link) {
258         limiter = s4u_link->get_impl();
259       }
260     }
261     return limiter;
262   };
263   // Create the switches
264   unsigned long k = 2 * nodes_.size();
265   for (unsigned long i = 0; i < this->levels_; i++) {
266     for (unsigned long j = 0; j < this->nodes_by_level_[i + 1]; j++) {
267       k--;
268       auto newNode = std::make_shared<FatTreeNode>(k, i + 1, j, get_limiter(i, j, k), nullptr);
269       XBT_DEBUG("We create the switch %d(%u,%u)", newNode->id, newNode->level, newNode->position);
270       newNode->children.resize(static_cast<size_t>(this->num_children_per_node_[i]) * this->num_port_lower_level_[i]);
271       if (i != this->levels_ - 1) {
272         newNode->parents.resize(static_cast<size_t>(this->num_parents_per_node_[i + 1]) *
273                                 this->num_port_lower_level_[i + 1]);
274       }
275       newNode->label.resize(this->levels_);
276       this->nodes_.emplace_back(newNode);
277     }
278   }
279 }
280
281 void FatTreeZone::generate_labels()
282 {
283   XBT_DEBUG("Generating labels.");
284   // TODO : check if nodesByLevel and nodes are filled
285   std::vector<int> maxLabel(this->levels_);
286   std::vector<int> currentLabel(this->levels_);
287   unsigned int k = 0;
288   for (unsigned int i = 0; i <= this->levels_; i++) {
289     currentLabel.assign(this->levels_, 0);
290     for (unsigned int j = 0; j < this->levels_; j++) {
291       maxLabel[j] = j + 1 > i ? this->num_children_per_node_[j] : this->num_parents_per_node_[j];
292     }
293
294     for (unsigned int j = 0; j < this->nodes_by_level_[i]; j++) {
295       if (XBT_LOG_ISENABLED(ker_routing_fat_tree, xbt_log_priority_debug)) {
296         std::stringstream msgBuffer;
297
298         msgBuffer << "Assigning label <";
299         for (unsigned int l = 0; l < this->levels_; l++) {
300           msgBuffer << currentLabel[l] << ",";
301         }
302         msgBuffer << "> to " << k << " (" << i << "," << j << ")";
303
304         XBT_DEBUG("%s", msgBuffer.str().c_str());
305       }
306       this->nodes_[k]->label.assign(currentLabel.begin(), currentLabel.end());
307
308       bool remainder   = true;
309       unsigned int pos = 0;
310       while (remainder && pos < this->levels_) {
311         ++currentLabel[pos];
312         if (currentLabel[pos] >= maxLabel[pos]) {
313           currentLabel[pos] = 0;
314           remainder         = true;
315           ++pos;
316         } else {
317           pos       = 0;
318           remainder = false;
319         }
320       }
321       k++;
322     }
323   }
324 }
325
326 int FatTreeZone::get_level_position(const unsigned int level)
327 {
328   xbt_assert(level <= this->levels_, "The impossible did happen. Yet again.");
329   int tempPosition = 0;
330
331   for (unsigned int i = 0; i < level; i++)
332     tempPosition += this->nodes_by_level_[i];
333
334   return tempPosition;
335 }
336
337 void FatTreeZone::add_processing_node(int id, resource::StandardLinkImpl* limiter, resource::StandardLinkImpl* loopback)
338 {
339   using std::make_pair;
340   static int position = 0;
341   auto newNode = std::make_shared<FatTreeNode>(id, 0, position, limiter, loopback);
342   position++;
343   newNode->parents.resize(static_cast<size_t>(this->num_parents_per_node_[0]) * this->num_port_lower_level_[0]);
344   newNode->label.resize(this->levels_);
345   this->compute_nodes_.try_emplace(id, newNode);
346   this->nodes_.emplace_back(newNode);
347 }
348
349 void FatTreeZone::add_link(FatTreeNode* parent, unsigned int parentPort, FatTreeNode* child, unsigned int childPort)
350 {
351   static int uniqueId = 0;
352   const s4u::Link* linkup;
353   const s4u::Link* linkdown;
354   std::string id =
355       "link_from_" + std::to_string(child->id) + "_" + std::to_string(parent->id) + "_" + std::to_string(uniqueId);
356
357   if (get_link_sharing_policy() == s4u::Link::SharingPolicy::SPLITDUPLEX) {
358     linkup   = create_link(id + "_UP", {get_link_bandwidth()})->set_latency(get_link_latency())->seal();
359     linkdown = create_link(id + "_DOWN", {get_link_bandwidth()})->set_latency(get_link_latency())->seal();
360   } else {
361     linkup   = create_link(id, {get_link_bandwidth()})->set_latency(get_link_latency())->seal();
362     linkdown = linkup;
363   }
364   uniqueId++;
365
366   auto newLink = std::make_shared<FatTreeLink>(child, parent, linkup->get_impl(), linkdown->get_impl());
367   XBT_DEBUG("Creating a link between the parent (%u,%u,%u) and the child (%u,%u,%u)", parent->level, parent->position,
368             parentPort, child->level, child->position, childPort);
369   parent->children[parentPort] = newLink;
370   child->parents[childPort]    = newLink;
371
372   this->links_.emplace_back(newLink);
373 }
374
375 void FatTreeZone::check_topology(unsigned int n_levels, const std::vector<unsigned int>& down_links,
376                                  const std::vector<unsigned int>& up_links, const std::vector<unsigned int>& link_count)
377
378 {
379   /* check number of levels */
380   if (n_levels == 0)
381     throw std::invalid_argument("FatTreeZone: invalid number of levels, must be > 0");
382
383   auto check_vector = [&n_levels](const std::vector<unsigned int>& vector, const std::string& var_name) {
384     if (vector.size() != n_levels)
385       throw std::invalid_argument("FatTreeZone: invalid " + var_name + " parameter, vector has " +
386                                   std::to_string(vector.size()) + " elements, must have " + std::to_string(n_levels));
387
388     auto check_zero = [](unsigned int i) { return i == 0; };
389     if (std::any_of(vector.begin(), vector.end(), check_zero))
390       throw std::invalid_argument("FatTreeZone: invalid " + var_name + " parameter, all values must be greater than 0");
391   };
392
393   /* check remaining vectors */
394   check_vector(down_links, "down links");
395   check_vector(up_links, "up links");
396   check_vector(link_count, "link count");
397 }
398
399 void FatTreeZone::set_topology(unsigned int n_levels, const std::vector<unsigned int>& down_links,
400                                const std::vector<unsigned int>& up_links, const std::vector<unsigned int>& link_count)
401 {
402   levels_                = n_levels;
403   num_children_per_node_ = down_links;
404   num_parents_per_node_  = up_links;
405   num_port_lower_level_  = link_count;
406 }
407
408 s4u::FatTreeParams FatTreeZone::parse_topo_parameters(const std::string& topo_parameters)
409 {
410   std::vector<std::string> parameters;
411   std::vector<std::string> tmp;
412   unsigned int n_lev = 0;
413   std::vector<unsigned int> down;
414   std::vector<unsigned int> up;
415   std::vector<unsigned int> count;
416   boost::split(parameters, topo_parameters, boost::is_any_of(";"));
417
418   surf_parse_assert(
419       parameters.size() == 4,
420       "Fat trees are defined by the levels number and 3 vectors, see the documentation for more information.");
421
422   // The first parts of topo_parameters should be the levels number
423   try {
424     n_lev = std::stoi(parameters[0]);
425   } catch (const std::invalid_argument&) {
426     surf_parse_error(std::string("First parameter is not the amount of levels: ") + parameters[0]);
427   }
428
429   // Then, a l-sized vector standing for the children number by level
430   boost::split(tmp, parameters[1], boost::is_any_of(","));
431   surf_parse_assert(tmp.size() == n_lev, std::string("You specified ") + std::to_string(n_lev) +
432                                              " levels but the child count vector (the first one) contains " +
433                                              std::to_string(tmp.size()) + " levels.");
434
435   for (std::string const& level : tmp) {
436     try {
437       down.push_back(std::stoi(level));
438     } catch (const std::invalid_argument&) {
439       surf_parse_error(std::string("Invalid child count: ") + level);
440     }
441   }
442
443   // Then, a l-sized vector standing for the parents number by level
444   boost::split(tmp, parameters[2], boost::is_any_of(","));
445   surf_parse_assert(tmp.size() == n_lev, std::string("You specified ") + std::to_string(n_lev) +
446                                              " levels but the parent count vector (the second one) contains " +
447                                              std::to_string(tmp.size()) + " levels.");
448   for (std::string const& parent : tmp) {
449     try {
450       up.push_back(std::stoi(parent));
451     } catch (const std::invalid_argument&) {
452       surf_parse_error(std::string("Invalid parent count: ") + parent);
453     }
454   }
455
456   // Finally, a l-sized vector standing for the ports number with the lower level
457   boost::split(tmp, parameters[3], boost::is_any_of(","));
458   surf_parse_assert(tmp.size() == n_lev, std::string("You specified ") + std::to_string(n_lev) +
459                                              " levels but the port count vector (the third one) contains " +
460                                              std::to_string(tmp.size()) + " levels.");
461   for (std::string const& port : tmp) {
462     try {
463       count.push_back(std::stoi(port));
464     } catch (const std::invalid_argument&) {
465       throw std::invalid_argument(std::string("Invalid lower level port number:") + port);
466     }
467   }
468   return s4u::FatTreeParams(n_lev, down, up, count);
469 }
470
471 void FatTreeZone::generate_dot_file(const std::string& filename) const
472 {
473   std::ofstream file;
474   file.open(filename, std::ios::out | std::ios::trunc);
475   xbt_assert(file.is_open(), "Unable to open file %s", filename.c_str());
476
477   file << "graph AsClusterFatTree {\n";
478   for (auto const& node : this->nodes_) {
479     file << node->id;
480     if (node->id < 0)
481       file << " [shape=circle];\n";
482     else
483       file << " [shape=hexagon];\n";
484   }
485
486   for (auto const& link : this->links_) {
487     file << link->down_node_->id << " -- " << link->up_node_->id << ";\n";
488   }
489   file << "}";
490   file.close();
491 }
492 } // namespace kernel::routing
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