Logo AND Algorithmique Numérique Distribuée

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