Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
3da6df43aaf59d52e767adacc48190e8bd20eb74
[simgrid.git] / src / kernel / routing / FatTreeZone.cpp
1 /* Copyright (c) 2014-2018. 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 <sstream>
8 #include <string>
9
10 #include "simgrid/kernel/routing/FatTreeZone.hpp"
11 #include "simgrid/kernel/routing/NetPoint.hpp"
12 #include "src/surf/network_interface.hpp"
13 #include "src/surf/xml/platf_private.hpp"
14
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(NetZone* father, std::string name) : ClusterZone(father, name)
26 {
27   XBT_DEBUG("Creating a new fat tree.");
28 }
29
30 FatTreeZone::~FatTreeZone()
31 {
32   for (unsigned int i = 0; i < this->nodes_.size(); i++) {
33     delete this->nodes_[i];
34   }
35   for (unsigned int i = 0; i < this->links_.size(); i++) {
36     delete this->links_[i];
37   }
38 }
39
40 bool FatTreeZone::isInSubTree(FatTreeNode* root, FatTreeNode* node)
41 {
42   XBT_DEBUG("Is %d(%u,%u) in the sub tree of %d(%u,%u) ?", node->id, node->level, node->position, root->id, root->level,
43             root->position);
44   if (root->level <= node->level) {
45     return false;
46   }
47   for (unsigned int i = 0; i < node->level; i++) {
48     if (root->label[i] != node->label[i]) {
49       return false;
50     }
51   }
52
53   for (unsigned int i = root->level; i < this->levels_; i++) {
54     if (root->label[i] != node->label[i]) {
55       return false;
56     }
57   }
58   return true;
59 }
60
61 void FatTreeZone::getLocalRoute(NetPoint* src, NetPoint* dst, RouteCreationArgs* into, double* latency)
62 {
63
64   if (dst->isRouter() || src->isRouter())
65     return;
66
67   /* Let's find the source and the destination in our internal structure */
68   auto searchedNode = this->computeNodes_.find(src->id());
69   xbt_assert(searchedNode != this->computeNodes_.end(), "Could not find the source %s [%u] in the fat tree",
70              src->getCname(), src->id());
71   FatTreeNode* source = searchedNode->second;
72
73   searchedNode = this->computeNodes_.find(dst->id());
74   xbt_assert(searchedNode != this->computeNodes_.end(), "Could not find the destination %s [%u] in the fat tree",
75              dst->getCname(), dst->id());
76   FatTreeNode* destination = searchedNode->second;
77
78   XBT_VERB("Get route and latency from '%s' [%u] to '%s' [%u] in a fat tree", src->getCname(), src->id(),
79            dst->getCname(), dst->id());
80
81   /* In case destination is the source, and there is a loopback, let's use it instead of going up to a switch */
82   if (source->id == destination->id && this->hasLoopback_) {
83     into->link_list.push_back(source->loopback);
84     if (latency)
85       *latency += source->loopback->latency();
86     return;
87   }
88
89   FatTreeNode* currentNode = source;
90
91   // up part
92   while (not isInSubTree(currentNode, destination)) {
93     int d = destination->position; // as in d-mod-k
94
95     for (unsigned int i = 0; i < currentNode->level; i++)
96       d /= this->upperLevelNodesNumber_[i];
97
98     int k = this->upperLevelNodesNumber_[currentNode->level];
99     d     = d % k;
100     into->link_list.push_back(currentNode->parents[d]->upLink);
101
102     if (latency)
103       *latency += currentNode->parents[d]->upLink->latency();
104
105     if (this->hasLimiter_)
106       into->link_list.push_back(currentNode->limiterLink);
107     currentNode = currentNode->parents[d]->upNode;
108   }
109
110   XBT_DEBUG("%d(%u,%u) is in the sub tree of %d(%u,%u).", destination->id, destination->level, destination->position,
111             currentNode->id, currentNode->level, currentNode->position);
112
113   // Down part
114   while (currentNode != destination) {
115     for (unsigned int i = 0; i < currentNode->children.size(); i++) {
116       if (i % this->lowerLevelNodesNumber_[currentNode->level - 1] == destination->label[currentNode->level - 1]) {
117         into->link_list.push_back(currentNode->children[i]->downLink);
118         if (latency)
119           *latency += currentNode->children[i]->downLink->latency();
120         currentNode = currentNode->children[i]->downNode;
121         if (this->hasLimiter_)
122           into->link_list.push_back(currentNode->limiterLink);
123         XBT_DEBUG("%d(%u,%u) is accessible through %d(%u,%u)", destination->id, destination->level,
124                   destination->position, currentNode->id, currentNode->level, currentNode->position);
125       }
126     }
127   }
128 }
129
130 /* This function makes the assumption that parse_specific_arguments() and
131  * addNodes() have already been called
132  */
133 void FatTreeZone::seal()
134 {
135   if (this->levels_ == 0) {
136     return;
137   }
138   this->generateSwitches();
139
140   if (XBT_LOG_ISENABLED(surf_route_fat_tree, xbt_log_priority_debug)) {
141     std::stringstream msgBuffer;
142
143     msgBuffer << "We are creating a fat tree of " << this->levels_ << " levels "
144               << "with " << this->nodesByLevel_[0] << " processing nodes";
145     for (unsigned int i = 1; i <= this->levels_; i++) {
146       msgBuffer << ", " << this->nodesByLevel_[i] << " switches at level " << i;
147     }
148     XBT_DEBUG("%s", msgBuffer.str().c_str());
149     msgBuffer.str("");
150     msgBuffer << "Nodes are : ";
151
152     for (unsigned int i = 0; i < this->nodes_.size(); i++) {
153       msgBuffer << this->nodes_[i]->id << "(" << this->nodes_[i]->level << "," << this->nodes_[i]->position << ") ";
154     }
155     XBT_DEBUG("%s", msgBuffer.str().c_str());
156   }
157
158   this->generateLabels();
159
160   unsigned int k = 0;
161   // Nodes are totally ordered, by level and then by position, in this->nodes
162   for (unsigned int i = 0; i < this->levels_; i++) {
163     for (unsigned int j = 0; j < this->nodesByLevel_[i]; j++) {
164       this->connectNodeToParents(this->nodes_[k]);
165       k++;
166     }
167   }
168
169   if (XBT_LOG_ISENABLED(surf_route_fat_tree, xbt_log_priority_debug)) {
170     std::stringstream msgBuffer;
171     msgBuffer << "Links are : ";
172     for (unsigned int i = 0; i < this->links_.size(); i++) {
173       msgBuffer << "(" << this->links_[i]->upNode->id << "," << this->links_[i]->downNode->id << ") ";
174     }
175     XBT_DEBUG("%s", msgBuffer.str().c_str());
176   }
177 }
178
179 int FatTreeZone::connectNodeToParents(FatTreeNode* node)
180 {
181   std::vector<FatTreeNode*>::iterator currentParentNode = this->nodes_.begin();
182   int connectionsNumber                                 = 0;
183   const int level                                       = node->level;
184   XBT_DEBUG("We are connecting node %d(%u,%u) to his parents.", node->id, node->level, node->position);
185   currentParentNode += this->getLevelPosition(level + 1);
186   for (unsigned int i = 0; i < this->nodesByLevel_[level + 1]; i++) {
187     if (this->areRelated(*currentParentNode, node)) {
188       XBT_DEBUG("%d(%u,%u) and %d(%u,%u) are related,"
189                 " with %u links between them.",
190                 node->id, node->level, node->position, (*currentParentNode)->id, (*currentParentNode)->level,
191                 (*currentParentNode)->position, this->lowerLevelPortsNumber_[level]);
192       for (unsigned int j = 0; j < this->lowerLevelPortsNumber_[level]; j++) {
193         this->addLink(*currentParentNode, node->label[level] + j * this->lowerLevelNodesNumber_[level], node,
194                       (*currentParentNode)->label[level] + j * this->upperLevelNodesNumber_[level]);
195       }
196       connectionsNumber++;
197     }
198     ++currentParentNode;
199   }
200   return connectionsNumber;
201 }
202
203 bool FatTreeZone::areRelated(FatTreeNode* parent, FatTreeNode* child)
204 {
205   std::stringstream msgBuffer;
206
207   if (XBT_LOG_ISENABLED(surf_route_fat_tree, xbt_log_priority_debug)) {
208     msgBuffer << "Are " << child->id << "(" << child->level << "," << child->position << ") <";
209
210     for (unsigned int i = 0; i < this->levels_; i++) {
211       msgBuffer << child->label[i] << ",";
212     }
213     msgBuffer << ">";
214
215     msgBuffer << " and " << parent->id << "(" << parent->level << "," << parent->position << ") <";
216     for (unsigned int i = 0; i < this->levels_; i++) {
217       msgBuffer << parent->label[i] << ",";
218     }
219     msgBuffer << ">";
220     msgBuffer << " related ? ";
221     XBT_DEBUG("%s", msgBuffer.str().c_str());
222   }
223   if (parent->level != child->level + 1) {
224     return false;
225   }
226
227   for (unsigned int i = 0; i < this->levels_; i++) {
228     if (parent->label[i] != child->label[i] && i + 1 != parent->level) {
229       return false;
230     }
231   }
232   return true;
233 }
234
235 void FatTreeZone::generateSwitches()
236 {
237   XBT_DEBUG("Generating switches.");
238   this->nodesByLevel_.resize(this->levels_ + 1, 0);
239
240   // Take care of the number of nodes by level
241   this->nodesByLevel_[0] = 1;
242   for (unsigned int i = 0; i < this->levels_; i++)
243     this->nodesByLevel_[0] *= this->lowerLevelNodesNumber_[i];
244
245   if (this->nodesByLevel_[0] != this->nodes_.size()) {
246     surf_parse_error(std::string("The number of provided nodes does not fit with the wanted topology.") +
247                      " Please check your platform description (We need " + std::to_string(this->nodesByLevel_[0]) +
248                      "nodes, we got " + std::to_string(this->nodes_.size()));
249     return;
250   }
251
252   for (unsigned int i = 0; i < this->levels_; i++) {
253     int nodesInThisLevel = 1;
254
255     for (unsigned int j = 0; j <= i; j++)
256       nodesInThisLevel *= this->upperLevelNodesNumber_[j];
257
258     for (unsigned int j = i + 1; j < this->levels_; j++)
259       nodesInThisLevel *= this->lowerLevelNodesNumber_[j];
260
261     this->nodesByLevel_[i + 1] = nodesInThisLevel;
262   }
263
264   // Create the switches
265   int k = 0;
266   for (unsigned int i = 0; i < this->levels_; i++) {
267     for (unsigned int j = 0; j < this->nodesByLevel_[i + 1]; j++) {
268       FatTreeNode* newNode = new FatTreeNode(this->cluster_, --k, i + 1, j);
269       XBT_DEBUG("We create the switch %d(%u,%u)", newNode->id, newNode->level, newNode->position);
270       newNode->children.resize(this->lowerLevelNodesNumber_[i] * this->lowerLevelPortsNumber_[i]);
271       if (i != this->levels_ - 1) {
272         newNode->parents.resize(this->upperLevelNodesNumber_[i + 1] * this->lowerLevelPortsNumber_[i + 1]);
273       }
274       newNode->label.resize(this->levels_);
275       this->nodes_.push_back(newNode);
276     }
277   }
278 }
279
280 void FatTreeZone::generateLabels()
281 {
282   XBT_DEBUG("Generating labels.");
283   // TODO : check if nodesByLevel and nodes are filled
284   std::vector<int> maxLabel(this->levels_);
285   std::vector<int> currentLabel(this->levels_);
286   unsigned int k = 0;
287   for (unsigned int i = 0; i <= this->levels_; i++) {
288     currentLabel.assign(this->levels_, 0);
289     for (unsigned int j = 0; j < this->levels_; j++) {
290       maxLabel[j] = j + 1 > i ? this->lowerLevelNodesNumber_[j] : this->upperLevelNodesNumber_[j];
291     }
292
293     for (unsigned int j = 0; j < this->nodesByLevel_[i]; j++) {
294
295       if (XBT_LOG_ISENABLED(surf_route_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::getLevelPosition(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->nodesByLevel_[i];
333
334   return tempPosition;
335 }
336
337 void FatTreeZone::addProcessingNode(int id)
338 {
339   using std::make_pair;
340   static int position = 0;
341   FatTreeNode* newNode;
342   newNode = new FatTreeNode(this->cluster_, id, 0, position++);
343   newNode->parents.resize(this->upperLevelNodesNumber_[0] * this->lowerLevelPortsNumber_[0]);
344   newNode->label.resize(this->levels_);
345   this->computeNodes_.insert(make_pair(id, newNode));
346   this->nodes_.push_back(newNode);
347 }
348
349 void FatTreeZone::addLink(FatTreeNode* parent, unsigned int parentPort, FatTreeNode* child, unsigned int childPort)
350 {
351   FatTreeLink* newLink;
352   newLink = new FatTreeLink(this->cluster_, child, parent);
353   XBT_DEBUG("Creating a link between the parent (%u,%u,%u) and the child (%u,%u,%u)", parent->level, parent->position,
354             parentPort, child->level, child->position, childPort);
355   parent->children[parentPort] = newLink;
356   child->parents[childPort]    = newLink;
357
358   this->links_.push_back(newLink);
359 }
360
361 void FatTreeZone::parse_specific_arguments(ClusterCreationArgs* cluster)
362 {
363   std::vector<std::string> parameters;
364   std::vector<std::string> tmp;
365   boost::split(parameters, cluster->topo_parameters, boost::is_any_of(";"));
366   const std::string error_msg {"Fat trees are defined by the levels number and 3 vectors, see the documentation for more information"};
367
368   // TODO : we have to check for zeros and negative numbers, or it might crash
369   if (parameters.size() != 4) {
370     surf_parse_error(error_msg);
371   }
372
373   // The first parts of topo_parameters should be the levels number
374   try {
375     this->levels_ = std::stoi(parameters[0]);
376   } catch (std::invalid_argument& ia) {
377     throw std::invalid_argument(std::string("First parameter is not the amount of levels:") + parameters[0]);
378   }
379
380   // Then, a l-sized vector standing for the children number by level
381   boost::split(tmp, parameters[1], boost::is_any_of(","));
382   if (tmp.size() != this->levels_) {
383     surf_parse_error(error_msg);
384   }
385   for (size_t i = 0; i < tmp.size(); i++) {
386     try {
387       this->lowerLevelNodesNumber_.push_back(std::stoi(tmp[i]));
388     } catch (std::invalid_argument& ia) {
389       throw std::invalid_argument(std::string("Invalid lower level node number:") + tmp[i]);
390     }
391   }
392
393   // Then, a l-sized vector standing for the parents number by level
394   boost::split(tmp, parameters[2], boost::is_any_of(","));
395   if (tmp.size() != this->levels_) {
396     surf_parse_error(error_msg);
397   }
398   for (size_t i = 0; i < tmp.size(); i++) {
399     try {
400       this->upperLevelNodesNumber_.push_back(std::stoi(tmp[i]));
401     } catch (std::invalid_argument& ia) {
402       throw std::invalid_argument(std::string("Invalid upper level node number:") + tmp[i]);
403     }
404   }
405
406   // Finally, a l-sized vector standing for the ports number with the lower level
407   boost::split(tmp, parameters[3], boost::is_any_of(","));
408   if (tmp.size() != this->levels_) {
409     surf_parse_error(error_msg);
410   }
411   for (size_t i = 0; i < tmp.size(); i++) {
412     try {
413       this->lowerLevelPortsNumber_.push_back(std::stoi(tmp[i]));
414     } catch (std::invalid_argument& ia) {
415       throw std::invalid_argument(std::string("Invalid lower level port number:") + tmp[i]);
416     }
417   }
418   this->cluster_ = cluster;
419 }
420
421 void FatTreeZone::generateDotFile(const std::string& filename) const
422 {
423   std::ofstream file;
424   file.open(filename, std::ios::out | std::ios::trunc);
425   xbt_assert(file.is_open(), "Unable to open file %s", filename.c_str());
426
427   file << "graph AsClusterFatTree {\n";
428   for (unsigned int i = 0; i < this->nodes_.size(); i++) {
429     file << this->nodes_[i]->id;
430     if (this->nodes_[i]->id < 0)
431       file << " [shape=circle];\n";
432     else
433       file << " [shape=hexagon];\n";
434   }
435
436   for (unsigned int i = 0; i < this->links_.size(); i++) {
437     file << this->links_[i]->downNode->id << " -- " << this->links_[i]->upNode->id << ";\n";
438   }
439   file << "}";
440   file.close();
441 }
442
443 FatTreeNode::FatTreeNode(ClusterCreationArgs* cluster, int id, int level, int position)
444     : id(id), level(level), position(position)
445 {
446   LinkCreationArgs linkTemplate;
447   if (cluster->limiter_link) {
448     linkTemplate.bandwidth = cluster->limiter_link;
449     linkTemplate.latency   = 0;
450     linkTemplate.policy    = SURF_LINK_SHARED;
451     linkTemplate.id        = "limiter_"+std::to_string(id);
452     sg_platf_new_link(&linkTemplate);
453     this->limiterLink = surf::LinkImpl::byName(linkTemplate.id);
454   }
455   if (cluster->loopback_bw || cluster->loopback_lat) {
456     linkTemplate.bandwidth = cluster->loopback_bw;
457     linkTemplate.latency   = cluster->loopback_lat;
458     linkTemplate.policy    = SURF_LINK_FATPIPE;
459     linkTemplate.id        = "loopback_"+ std::to_string(id);
460     sg_platf_new_link(&linkTemplate);
461     this->loopback = surf::LinkImpl::byName(linkTemplate.id);
462   }
463 }
464
465 FatTreeLink::FatTreeLink(ClusterCreationArgs* cluster, FatTreeNode* downNode, FatTreeNode* upNode)
466     : upNode(upNode), downNode(downNode)
467 {
468   static int uniqueId = 0;
469   LinkCreationArgs linkTemplate;
470   linkTemplate.bandwidth = cluster->bw;
471   linkTemplate.latency   = cluster->lat;
472   linkTemplate.policy    = cluster->sharing_policy; // sthg to do with that ?
473   linkTemplate.id =
474       "link_from_" + std::to_string(downNode->id) + "_" + std::to_string(upNode->id) + "_" + std::to_string(uniqueId);
475   sg_platf_new_link(&linkTemplate);
476
477   if (cluster->sharing_policy == SURF_LINK_SPLITDUPLEX) {
478     std::string tmpID = std::string(linkTemplate.id) + "_UP";
479     this->upLink      = surf::LinkImpl::byName(tmpID); // check link?
480     tmpID          = std::string(linkTemplate.id) + "_DOWN";
481     this->downLink    = surf::LinkImpl::byName(tmpID); // check link ?
482   } else {
483     this->upLink   = surf::LinkImpl::byName(linkTemplate.id);
484     this->downLink = this->upLink;
485   }
486   uniqueId++;
487 }
488 }
489 }
490 } // namespace