Logo AND Algorithmique Numérique Distribuée

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