Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Use new API to create Torus/Dragonfly/Fat-Tree clusters from XML.
[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, RouteCreationArgs* 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     into->link_list.push_back(currentNode->parents[d]->up_link_);
93
94     if (latency)
95       *latency += currentNode->parents[d]->up_link_->get_latency();
96
97     if (currentNode->limiter_link_)
98       into->link_list.push_back(currentNode->limiter_link_);
99     currentNode = currentNode->parents[d]->up_node_;
100   }
101
102   XBT_DEBUG("%d(%u,%u) is in the sub tree of %d(%u,%u).", destination->id, destination->level, destination->position,
103             currentNode->id, currentNode->level, currentNode->position);
104
105   // Down part
106   while (currentNode != destination) {
107     for (unsigned int i = 0; i < currentNode->children.size(); i++) {
108       if (i % this->num_children_per_node_[currentNode->level - 1] == destination->label[currentNode->level - 1]) {
109         into->link_list.push_back(currentNode->children[i]->down_link_);
110         if (latency)
111           *latency += currentNode->children[i]->down_link_->get_latency();
112         currentNode = currentNode->children[i]->down_node_;
113         if (currentNode->limiter_link_)
114           into->link_list.push_back(currentNode->limiter_link_);
115         XBT_DEBUG("%d(%u,%u) is accessible through %d(%u,%u)", destination->id, destination->level,
116                   destination->position, currentNode->id, currentNode->level, currentNode->position);
117       }
118     }
119   }
120   // set gateways (if any)
121   into->gw_src = get_gateway(src->id());
122   into->gw_dst = get_gateway(dst->id());
123 }
124
125 /* This function makes the assumption that parse_specific_arguments() and
126  * addNodes() have already been called
127  */
128 void FatTreeZone::do_seal()
129 {
130   if (this->levels_ == 0) {
131     return;
132   }
133   this->generate_switches();
134
135   if (XBT_LOG_ISENABLED(surf_route_fat_tree, xbt_log_priority_debug)) {
136     std::stringstream msgBuffer;
137
138     msgBuffer << "We are creating a fat tree of " << this->levels_ << " levels "
139               << "with " << this->nodes_by_level_[0] << " processing nodes";
140     for (unsigned int i = 1; i <= this->levels_; i++) {
141       msgBuffer << ", " << this->nodes_by_level_[i] << " switches at level " << i;
142     }
143     XBT_DEBUG("%s", msgBuffer.str().c_str());
144     msgBuffer.str("");
145     msgBuffer << "Nodes are : ";
146
147     for (FatTreeNode const* node : this->nodes_) {
148       msgBuffer << node->id << "(" << node->level << "," << node->position << ") ";
149     }
150     XBT_DEBUG("%s", msgBuffer.str().c_str());
151   }
152
153   this->generate_labels();
154
155   unsigned int k = 0;
156   // Nodes are totally ordered, by level and then by position, in this->nodes
157   for (unsigned int i = 0; i < this->levels_; i++) {
158     for (unsigned int j = 0; j < this->nodes_by_level_[i]; j++) {
159       this->connect_node_to_parents(this->nodes_[k]);
160       k++;
161     }
162   }
163
164   if (XBT_LOG_ISENABLED(surf_route_fat_tree, xbt_log_priority_debug)) {
165     std::stringstream msgBuffer;
166     msgBuffer << "Links are : ";
167     for (FatTreeLink 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
174 int FatTreeZone::connect_node_to_parents(FatTreeNode* node)
175 {
176   auto currentParentNode = this->nodes_.begin();
177   int connectionsNumber  = 0;
178   const int level        = node->level;
179   XBT_DEBUG("We are connecting node %d(%u,%u) to his parents.", node->id, node->level, node->position);
180   currentParentNode += this->get_level_position(level + 1);
181   for (unsigned int i = 0; i < this->nodes_by_level_[level + 1]; i++) {
182     if (this->are_related(*currentParentNode, node)) {
183       XBT_DEBUG("%d(%u,%u) and %d(%u,%u) are related,"
184                 " with %u links between them.",
185                 node->id, node->level, node->position, (*currentParentNode)->id, (*currentParentNode)->level,
186                 (*currentParentNode)->position, this->num_port_lower_level_[level]);
187       for (unsigned int j = 0; j < this->num_port_lower_level_[level]; j++) {
188         this->add_link(*currentParentNode, node->label[level] + j * this->num_children_per_node_[level], node,
189                        (*currentParentNode)->label[level] + j * this->num_parents_per_node_[level]);
190       }
191       connectionsNumber++;
192     }
193     ++currentParentNode;
194   }
195   return connectionsNumber;
196 }
197
198 bool FatTreeZone::are_related(FatTreeNode* parent, FatTreeNode* child) const
199 {
200   std::stringstream msgBuffer;
201
202   if (XBT_LOG_ISENABLED(surf_route_fat_tree, xbt_log_priority_debug)) {
203     msgBuffer << "Are " << child->id << "(" << child->level << "," << child->position << ") <";
204
205     for (unsigned int i = 0; i < this->levels_; i++) {
206       msgBuffer << child->label[i] << ",";
207     }
208     msgBuffer << ">";
209
210     msgBuffer << " and " << parent->id << "(" << parent->level << "," << parent->position << ") <";
211     for (unsigned int i = 0; i < this->levels_; i++) {
212       msgBuffer << parent->label[i] << ",";
213     }
214     msgBuffer << ">";
215     msgBuffer << " related ? ";
216     XBT_DEBUG("%s", msgBuffer.str().c_str());
217   }
218   if (parent->level != child->level + 1) {
219     return false;
220   }
221
222   for (unsigned int i = 0; i < this->levels_; i++) {
223     if (parent->label[i] != child->label[i] && i + 1 != parent->level) {
224       return false;
225     }
226   }
227   return true;
228 }
229
230 void FatTreeZone::generate_switches()
231 {
232   XBT_DEBUG("Generating switches.");
233   this->nodes_by_level_.resize(this->levels_ + 1, 0);
234
235   // Take care of the number of nodes by level
236   this->nodes_by_level_[0] = 1;
237   for (unsigned int i = 0; i < this->levels_; i++)
238     this->nodes_by_level_[0] *= this->num_children_per_node_[i];
239
240   if (this->nodes_by_level_[0] != this->nodes_.size()) {
241     surf_parse_error(std::string("The number of provided nodes does not fit with the wanted topology.") +
242                      " Please check your platform description (We need " + std::to_string(this->nodes_by_level_[0]) +
243                      "nodes, we got " + std::to_string(this->nodes_.size()));
244   }
245
246   for (unsigned int i = 0; i < this->levels_; i++) {
247     int nodesInThisLevel = 1;
248
249     for (unsigned int j = 0; j <= i; j++)
250       nodesInThisLevel *= this->num_parents_per_node_[j];
251
252     for (unsigned int j = i + 1; j < this->levels_; j++)
253       nodesInThisLevel *= this->num_children_per_node_[j];
254
255     this->nodes_by_level_[i + 1] = nodesInThisLevel;
256   }
257
258   // Create the switches
259   int k = 0;
260   for (unsigned int i = 0; i < this->levels_; i++) {
261     for (unsigned int j = 0; j < this->nodes_by_level_[i + 1]; j++) {
262       auto* newNode = new FatTreeNode(--k, i + 1, j, nullptr, nullptr);
263       XBT_DEBUG("We create the switch %d(%u,%u)", newNode->id, newNode->level, newNode->position);
264       newNode->children.resize(this->num_children_per_node_[i] * this->num_port_lower_level_[i]);
265       if (i != this->levels_ - 1) {
266         newNode->parents.resize(this->num_parents_per_node_[i + 1] * this->num_port_lower_level_[i + 1]);
267       }
268       newNode->label.resize(this->levels_);
269       this->nodes_.push_back(newNode);
270     }
271   }
272 }
273
274 void FatTreeZone::generate_labels()
275 {
276   XBT_DEBUG("Generating labels.");
277   // TODO : check if nodesByLevel and nodes are filled
278   std::vector<int> maxLabel(this->levels_);
279   std::vector<int> currentLabel(this->levels_);
280   unsigned int k = 0;
281   for (unsigned int i = 0; i <= this->levels_; i++) {
282     currentLabel.assign(this->levels_, 0);
283     for (unsigned int j = 0; j < this->levels_; j++) {
284       maxLabel[j] = j + 1 > i ? this->num_children_per_node_[j] : this->num_parents_per_node_[j];
285     }
286
287     for (unsigned int j = 0; j < this->nodes_by_level_[i]; j++) {
288       if (XBT_LOG_ISENABLED(surf_route_fat_tree, xbt_log_priority_debug)) {
289         std::stringstream msgBuffer;
290
291         msgBuffer << "Assigning label <";
292         for (unsigned int l = 0; l < this->levels_; l++) {
293           msgBuffer << currentLabel[l] << ",";
294         }
295         msgBuffer << "> to " << k << " (" << i << "," << j << ")";
296
297         XBT_DEBUG("%s", msgBuffer.str().c_str());
298       }
299       this->nodes_[k]->label.assign(currentLabel.begin(), currentLabel.end());
300
301       bool remainder   = true;
302       unsigned int pos = 0;
303       while (remainder && pos < this->levels_) {
304         ++currentLabel[pos];
305         if (currentLabel[pos] >= maxLabel[pos]) {
306           currentLabel[pos] = 0;
307           remainder         = true;
308           ++pos;
309         } else {
310           pos       = 0;
311           remainder = false;
312         }
313       }
314       k++;
315     }
316   }
317 }
318
319 int FatTreeZone::get_level_position(const unsigned int level)
320 {
321   xbt_assert(level <= this->levels_, "The impossible did happen. Yet again.");
322   int tempPosition = 0;
323
324   for (unsigned int i = 0; i < level; i++)
325     tempPosition += this->nodes_by_level_[i];
326
327   return tempPosition;
328 }
329
330 void FatTreeZone::add_processing_node(int id, resource::LinkImpl* limiter, resource::LinkImpl* loopback)
331 {
332   using std::make_pair;
333   static int position = 0;
334   auto* newNode       = new FatTreeNode(id, 0, position++, limiter, loopback);
335   newNode->parents.resize(this->num_parents_per_node_[0] * this->num_port_lower_level_[0]);
336   newNode->label.resize(this->levels_);
337   this->compute_nodes_.insert(make_pair(id, newNode));
338   this->nodes_.push_back(newNode);
339 }
340
341 void FatTreeZone::add_link(FatTreeNode* parent, unsigned int parentPort, FatTreeNode* child, unsigned int childPort)
342 {
343   static int uniqueId = 0;
344   const s4u::Link* linkup;
345   const s4u::Link* linkdown;
346   std::string id =
347       "link_from_" + std::to_string(child->id) + "_" + std::to_string(parent->id) + "_" + std::to_string(uniqueId);
348
349   if (link_sharing_policy_ == s4u::Link::SharingPolicy::SPLITDUPLEX) {
350     linkup   = create_link(id + "_UP", std::vector<double>{link_bw_})->set_latency(link_lat_)->seal();
351     linkdown = create_link(id + "_DOWN", std::vector<double>{link_bw_})->set_latency(link_lat_)->seal();
352   } else {
353     linkup   = create_link(id, std::vector<double>{link_bw_})->set_latency(link_lat_)->seal();
354     linkdown = linkup;
355   }
356   uniqueId++;
357
358   auto* newLink = new FatTreeLink(child, parent, linkup->get_impl(), linkdown->get_impl());
359   XBT_DEBUG("Creating a link between the parent (%u,%u,%u) and the child (%u,%u,%u)", parent->level, parent->position,
360             parentPort, child->level, child->position, childPort);
361   parent->children[parentPort] = newLink;
362   child->parents[childPort]    = newLink;
363
364   this->links_.push_back(newLink);
365 }
366
367 void FatTreeZone::check_topology(unsigned int n_levels, const std::vector<unsigned int>& down_links,
368                                  const std::vector<unsigned int>& up_links, const std::vector<unsigned int>& link_count)
369
370 {
371   /* check number of levels */
372   if (n_levels == 0)
373     throw std::invalid_argument("FatTreeZone: invalid number of levels, must be > 0");
374
375   auto check_vector = [&n_levels](const std::vector<unsigned int>& vector, const std::string& var_name) {
376     if (vector.size() != n_levels)
377       throw std::invalid_argument("FatTreeZone: invalid " + var_name + " parameter, vector has " +
378                                   std::to_string(vector.size()) + " elements, must have " + std::to_string(n_levels));
379
380     auto check_zero = [](unsigned int i) { return i == 0; };
381     if (std::any_of(vector.begin(), vector.end(), check_zero))
382       throw std::invalid_argument("FatTreeZone: invalid " + var_name + " parameter, all values must be greater than 0");
383   };
384
385   /* check remaining vectors */
386   check_vector(down_links, "down links");
387   check_vector(up_links, "up links");
388   check_vector(link_count, "link count");
389 }
390
391 void FatTreeZone::set_link_characteristics(double bw, double lat, s4u::Link::SharingPolicy sharing_policy)
392 {
393   link_sharing_policy_ = sharing_policy;
394   link_bw_             = bw;
395   link_lat_            = lat;
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 (FatTreeNode 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 (FatTreeLink 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                              double bandwidth, double latency, Link::SharingPolicy sharing_policy,
504                              const std::function<ClusterNetPointCb>& set_netpoint,
505                              const std::function<ClusterLinkCb>& set_loopback,
506                              const std::function<ClusterLinkCb>& set_limiter)
507 {
508   /* initial checks */
509   if (bandwidth <= 0)
510     throw std::invalid_argument("FatTreeZone: incorrect bandwidth for internode communication, bw=" +
511                                 std::to_string(bandwidth));
512   if (latency < 0)
513     throw std::invalid_argument("FatTreeZone: incorrect latency for internode communication, lat=" +
514                                 std::to_string(latency));
515
516   /* creating zone */
517   auto* zone = new kernel::routing::FatTreeZone(name);
518   zone->set_topology(params.levels, params.down, params.up, params.number);
519   if (parent)
520     zone->set_parent(parent->get_impl());
521   zone->set_link_characteristics(bandwidth, latency, sharing_policy);
522
523   /* populating it */
524   int tot_elements = std::accumulate(params.down.begin(), params.down.end(), 1, std::multiplies<>());
525   for (int i = 0; i < tot_elements; i++) {
526     kernel::routing::NetPoint* netpoint;
527     Link* limiter;
528     Link* loopback;
529     zone->fill_leaf_from_cb(i, params.down, set_netpoint, set_loopback, set_limiter, &netpoint, &loopback, &limiter);
530     zone->add_processing_node(i, limiter ? limiter->get_impl() : nullptr, loopback ? loopback->get_impl() : nullptr);
531   }
532
533   return zone->get_iface();
534 }
535 } // namespace s4u
536
537 } // namespace simgrid