Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'master' of scm.gforge.inria.fr:/gitroot/simgrid/simgrid
[simgrid.git] / src / surf / surf_routing_cluster_fat_tree.cpp
1 #include "surf_routing_cluster_fat_tree.hpp"
2 #include "xbt/lib.h"
3
4 #include <boost/algorithm/string/split.hpp>
5 #include <boost/algorithm/string/classification.hpp>
6 #include <iostream>
7 #include <fstream>
8 #include <sstream>
9
10 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(surf_route_fat_tree, surf, "Routing for fat trees");
11
12 AS_t model_fat_tree_cluster_create(void)
13 {
14   return new AsClusterFatTree();
15 }
16
17 AsClusterFatTree::AsClusterFatTree() : levels(0) {
18   XBT_DEBUG("Creating a new fat tree.");
19 }
20
21 AsClusterFatTree::~AsClusterFatTree() {
22   for (unsigned int i = 0 ; i < this->nodes.size() ; i++) {
23     delete this->nodes[i];
24   }
25 }
26
27 bool AsClusterFatTree::isInSubTree(FatTreeNode *root, FatTreeNode *node) {
28   XBT_DEBUG("Is %d(%u,%u) in the sub tree of %d(%u,%u) ?", node->id,
29             node->level, node->position, root->id, root->level, root->position);
30   if (root->level <= node->level) {
31     return false;
32   }
33   for (unsigned int i = 0 ; i < node->level ; i++) {
34     if(root->label[i] != node->label[i]) {
35       return false;
36     }
37   }
38   
39   for (unsigned int i = root->level ; i < this->levels ; i++) {
40     if(root->label[i] != node->label[i]) {
41       return false;
42     }
43   }
44   return true;
45 }
46
47 void AsClusterFatTree::getRouteAndLatency(RoutingEdgePtr src,
48                                           RoutingEdgePtr dst,
49                                           sg_platf_route_cbarg_t into,
50                                           double *latency) {
51   FatTreeNode *source, *destination, *currentNode;
52
53   std::map<int, FatTreeNode*>::const_iterator tempIter;
54   
55 if (dst->getRcType() == SURF_NETWORK_ELEMENT_ROUTER || src->getRcType() == SURF_NETWORK_ELEMENT_ROUTER) return;
56
57   /* Let's find the source and the destination in our internal structure */
58   tempIter = this->computeNodes.find(src->getId());
59
60   // xbt_die -> assert
61   if (tempIter == this->computeNodes.end()) {
62     xbt_die("Could not find the source %s [%d] in the fat tree", src->getName(),
63             src->getId());
64   }
65   source = tempIter->second;
66   tempIter = this->computeNodes.find(dst->getId());
67   if (tempIter == this->computeNodes.end()) {
68     xbt_die("Could not find the destination %s [%d] in the fat tree",
69             dst->getName(), dst->getId());
70   }
71
72
73   destination = tempIter->second;
74   
75   XBT_VERB("Get route and latency from '%s' [%d] to '%s' [%d] in a fat tree",
76             src->getName(), src->getId(), dst->getName(), dst->getId());
77
78   /* In case destination is the source, and there is a loopback, let's get
79      through it instead of going up to a switch*/
80   if(source->id == destination->id && this->p_has_loopback) {
81     xbt_dynar_push_as(into->link_list, void*, source->loopback);
82     if(latency) {
83       *latency += source->loopback->getLatency();
84     }
85   }
86
87   currentNode = source;
88
89   // up part
90   while (!isInSubTree(currentNode, destination)) {
91     int d, k; // as in d-mod-k
92     d = destination->position;
93
94     for (unsigned int i = 0 ; i < currentNode->level ; i++) {
95       d /= this->upperLevelNodesNumber[i];
96     }
97     k = this->upperLevelNodesNumber[currentNode->level];
98     d = d % k;
99     xbt_dynar_push_as(into->link_list, void*,currentNode->parents[d]->upLink);
100
101     if(latency) {
102       *latency += currentNode->parents[d]->upLink->getLatency();
103     }
104
105     if (this->p_has_limiter) {
106       xbt_dynar_push_as(into->link_list, void*,currentNode->limiterLink);
107     }
108     currentNode = currentNode->parents[d]->upNode;
109   }
110
111   XBT_DEBUG("%d(%u,%u) is in the sub tree of %d(%u,%u).", destination->id,
112             destination->level, destination->position, currentNode->id,
113             currentNode->level, currentNode->position);
114
115   // Down part
116   while(currentNode != destination) {
117     for(unsigned int i = 0 ; i < currentNode->children.size() ; i++) {
118       if(i % this->lowerLevelNodesNumber[currentNode->level - 1] ==
119          destination->label[currentNode->level - 1]) {
120         xbt_dynar_push_as(into->link_list, void*,currentNode->children[i]->downLink);
121         if(latency) {
122           *latency += currentNode->children[i]->downLink->getLatency();
123         }
124         currentNode = currentNode->children[i]->downNode;
125         if (this->p_has_limiter) {
126           xbt_dynar_push_as(into->link_list, void*,currentNode->limiterLink);
127         }
128         XBT_DEBUG("%d(%u,%u) is accessible through %d(%u,%u)", destination->id,
129                   destination->level, destination->position, currentNode->id,
130                   currentNode->level, currentNode->position);
131       }
132     }
133   }
134 }
135
136 /* This function makes the assumption that parse_specific_arguments() and
137  * addNodes() have already been called
138  */
139 void AsClusterFatTree::create_links(){
140   if(this->levels == 0) {
141     return;
142   }
143   this->generateSwitches();
144
145
146   if(XBT_LOG_ISENABLED(surf_route_fat_tree, xbt_log_priority_debug)) {
147     std::stringstream msgBuffer;
148
149     msgBuffer << "We are creating a fat tree of " << this->levels << " levels "
150               << "with " << this->nodesByLevel[0] << " processing nodes";
151     for (unsigned int i = 1 ; i <= this->levels ; i++) {
152       msgBuffer << ", " << this->nodesByLevel[i] << " switches at level " << i;
153     }
154     XBT_DEBUG("%s", msgBuffer.str().c_str());
155     msgBuffer.str("");
156     msgBuffer << "Nodes are : ";
157
158     for (unsigned int i = 0 ;  i < this->nodes.size() ; i++) {
159       msgBuffer << this->nodes[i]->id << "(" << this->nodes[i]->level << ","
160                 << this->nodes[i]->position << ") ";
161     }
162     XBT_DEBUG("%s", msgBuffer.str().c_str());
163   }
164
165
166   this->generateLabels();
167
168   unsigned int k = 0;
169   // Nodes are totally ordered, by level and then by position, in this->nodes
170   for (unsigned int i = 0 ; i < this->levels ; i++) {
171     for (unsigned int j = 0 ; j < this->nodesByLevel[i] ; j++) {
172         this->connectNodeToParents(this->nodes[k]);
173         k++;
174     }
175   }
176   
177   if(XBT_LOG_ISENABLED(surf_route_fat_tree, xbt_log_priority_debug)) {
178     std::stringstream msgBuffer;
179     msgBuffer << "Links are : ";
180     for (unsigned int i = 0 ; i < this->links.size() ; i++) {
181       msgBuffer << "(" << this->links[i]->upNode->id << ","
182                 << this->links[i]->downNode->id << ") ";
183     }
184     XBT_DEBUG("%s", msgBuffer.str().c_str());
185   }
186
187
188 }
189
190 int AsClusterFatTree::connectNodeToParents(FatTreeNode *node) {
191   std::vector<FatTreeNode*>::iterator currentParentNode = this->nodes.begin();
192   int connectionsNumber = 0;
193   const int level = node->level;
194   XBT_DEBUG("We are connecting node %d(%u,%u) to his parents.",
195             node->id, node->level, node->position);
196   currentParentNode += this->getLevelPosition(level + 1);
197   for (unsigned int i = 0 ; i < this->nodesByLevel[level + 1] ; i++ ) {
198     if(this->areRelated(*currentParentNode, node)) {
199       XBT_DEBUG("%d(%u,%u) and %d(%u,%u) are related,"
200                 " with %u links between them.", node->id,
201                 node->level, node->position, (*currentParentNode)->id,
202                 (*currentParentNode)->level, (*currentParentNode)->position, this->lowerLevelPortsNumber[level]);
203       for (unsigned int j = 0 ; j < this->lowerLevelPortsNumber[level] ; j++) {
204       this->addLink(*currentParentNode, node->label[level] +
205                     j * this->lowerLevelNodesNumber[level], node,
206                     (*currentParentNode)->label[level] +
207                     j * this->upperLevelNodesNumber[level]);
208       }
209       connectionsNumber++;
210     }
211     ++currentParentNode;
212   }
213   return connectionsNumber;
214 }
215
216
217 bool AsClusterFatTree::areRelated(FatTreeNode *parent, FatTreeNode *child) {
218   std::stringstream msgBuffer;
219
220   if(XBT_LOG_ISENABLED(surf_route_fat_tree, xbt_log_priority_debug)) {
221     msgBuffer << "Are " << child->id << "(" << child->level << ","
222               << child->position << ") <";
223
224     for (unsigned int i = 0 ; i < this->levels ; i++) {
225       msgBuffer << child->label[i] << ",";
226     }
227     msgBuffer << ">";
228     
229     msgBuffer << " and " << parent->id << "(" << parent->level
230               << "," << parent->position << ") <";
231     for (unsigned int i = 0 ; i < this->levels ; i++) {
232       msgBuffer << parent->label[i] << ",";
233     }
234     msgBuffer << ">";
235     msgBuffer << " related ? ";
236     XBT_DEBUG("%s", msgBuffer.str().c_str());
237     
238   }
239   if (parent->level != child->level + 1) {
240     return false;
241   }
242   
243   for (unsigned int i = 0 ; i < this->levels; i++) {
244     if (parent->label[i] != child->label[i] && i + 1 != parent->level) {
245       return false;
246     }
247   }
248   return true;
249 }
250
251 void AsClusterFatTree::generateSwitches() {
252   XBT_DEBUG("Generating switches.");
253   this->nodesByLevel.resize(this->levels + 1, 0);
254   unsigned int nodesRequired = 0;
255
256   // We take care of the number of nodes by level
257   this->nodesByLevel[0] = 1;
258   for (unsigned int i = 0 ; i < this->levels ; i++) {
259     this->nodesByLevel[0] *= this->lowerLevelNodesNumber[i];
260   }
261
262      
263   if(this->nodesByLevel[0] != this->nodes.size()) {
264     surf_parse_error("The number of provided nodes does not fit with the wanted topology."
265                      " Please check your platform description (We need %d nodes, we got %zu)",
266                      this->nodesByLevel[0], this->nodes.size());
267     return;
268   }
269
270   
271   for (unsigned int i = 0 ; i < this->levels ; i++) {
272     int nodesInThisLevel = 1;
273       
274     for (unsigned int j = 0 ;  j <= i ; j++) {
275       nodesInThisLevel *= this->upperLevelNodesNumber[j];
276     }
277       
278     for (unsigned int j = i+1 ; j < this->levels ; j++) {
279       nodesInThisLevel *= this->lowerLevelNodesNumber[j];
280     }
281
282     this->nodesByLevel[i+1] = nodesInThisLevel;
283     nodesRequired += nodesInThisLevel;
284   }
285
286
287   // If we have to many compute nodes, we ditch them
288   
289
290   // We create the switches
291   int k = 0;
292   for (unsigned int i = 0 ; i < this->levels ; i++) {
293     for (unsigned int j = 0 ; j < this->nodesByLevel[i + 1] ; j++) {
294       FatTreeNode* newNode;
295       newNode = new FatTreeNode(this->cluster, --k, i + 1, j);
296       XBT_DEBUG("We create the switch %d(%d,%d)", newNode->id, newNode->level,
297                 newNode->position);
298       newNode->children.resize(this->lowerLevelNodesNumber[i] *
299                                this->lowerLevelPortsNumber[i]);
300       if (i != this->levels - 1) {
301         newNode->parents.resize(this->upperLevelNodesNumber[i + 1] *
302                                 this->lowerLevelPortsNumber[i + 1]);
303       }
304       newNode->label.resize(this->levels);
305       this->nodes.push_back(newNode);
306     }
307   }
308 }
309
310 void AsClusterFatTree::generateLabels() {
311   XBT_DEBUG("Generating labels.");
312   // TODO : check if nodesByLevel and nodes are filled
313   std::vector<int> maxLabel(this->levels);
314   std::vector<int> currentLabel(this->levels);
315   unsigned int k = 0;
316   for (unsigned int i = 0 ; i <= this->levels ; i++) {
317     currentLabel.assign(this->levels, 0);
318     for (unsigned int j = 0 ; j < this->levels ; j++) {
319       maxLabel[j] = j + 1 > i ?
320         this->lowerLevelNodesNumber[j] : this->upperLevelNodesNumber[j];
321     }
322     
323     for (unsigned int j = 0 ; j < this->nodesByLevel[i] ; j++) {
324
325       if(XBT_LOG_ISENABLED(surf_route_fat_tree, xbt_log_priority_debug )) {
326         std::stringstream msgBuffer;
327
328         msgBuffer << "Assigning label <";
329         for (unsigned int l = 0 ; l < this->levels ; l++) {
330           msgBuffer << currentLabel[l] << ",";
331         }
332         msgBuffer << "> to " << k << " (" << i << "," << j <<")";
333         
334         XBT_DEBUG("%s", msgBuffer.str().c_str());
335       }
336       this->nodes[k]->label.assign(currentLabel.begin(), currentLabel.end());
337
338       bool remainder = true;
339       
340       unsigned int pos = 0;
341       do {
342         std::stringstream msgBuffer;
343
344         ++currentLabel[pos];
345         if (currentLabel[pos] >= maxLabel[pos]) {
346           currentLabel[pos] = 0;
347           remainder = true;
348         }
349         else {
350           remainder = false;
351         }
352         if (!remainder) {
353           pos = 0;
354         }
355         else {
356           ++pos;
357         }
358       }
359       while(remainder && pos < this->levels);
360       k++;
361     }
362   }
363 }
364
365
366 int AsClusterFatTree::getLevelPosition(const unsigned  int level) {
367   if (level > this->levels) {
368     // Well, that should never happen. Maybe should we throw instead.
369     return -1;
370   }
371   int tempPosition = 0;
372
373   for (unsigned int i = 0 ; i < level ; i++) {
374     tempPosition += this->nodesByLevel[i];
375   }
376  return tempPosition;
377 }
378
379 void AsClusterFatTree::addProcessingNode(int id) {
380   using std::make_pair;
381   static int position = 0;
382   FatTreeNode* newNode;
383   newNode = new FatTreeNode(this->cluster, id, 0, position++);
384   newNode->parents.resize(this->upperLevelNodesNumber[0] *
385                           this->lowerLevelPortsNumber[0]);
386   newNode->label.resize(this->levels);
387   this->computeNodes.insert(make_pair(id,newNode));
388   this->nodes.push_back(newNode);
389 }
390
391 void AsClusterFatTree::addLink(FatTreeNode *parent, unsigned int parentPort,
392                                FatTreeNode *child, unsigned int childPort) {
393   FatTreeLink *newLink;
394   newLink = new FatTreeLink(this->cluster, child, parent);
395   XBT_DEBUG("Creating a link between the parent (%d,%d,%u)"
396             " and the child (%d,%d,%u)", parent->level, parent->position,
397             parentPort, child->level, child->position, childPort);
398   parent->children[parentPort] = newLink;
399   child->parents[childPort] = newLink;
400
401   this->links.push_back(newLink);
402
403   
404
405 }
406
407 void AsClusterFatTree::parse_specific_arguments(sg_platf_cluster_cbarg_t 
408                                                 cluster) {
409   std::vector<string> parameters;
410   std::vector<string> tmp;
411   boost::split(parameters, cluster->topo_parameters, boost::is_any_of(";"));
412  
413
414   // TODO : we have to check for zeros and negative numbers, or it might crash
415   if (parameters.size() != 4){
416     surf_parse_error("Fat trees are defined by the levels number and 3 vectors" 
417                      ", see the documentation for more informations");
418     // Well, there's no doc, yet
419   }
420
421   // The first parts of topo_parameters should be the levels number
422   this->levels = std::atoi(parameters[0].c_str()); // stoi() only in C++11...
423   
424   // Then, a l-sized vector standing for the childs number by level
425   boost::split(tmp, parameters[1], boost::is_any_of(","));
426   if(tmp.size() != this->levels) {
427     surf_parse_error("Fat trees are defined by the levels number and 3 vectors" 
428                      ", see the documentation for more informations"); 
429   }
430   for(size_t i = 0 ; i < tmp.size() ; i++){
431     this->lowerLevelNodesNumber.push_back(std::atoi(tmp[i].c_str())); 
432   }
433   
434   // Then, a l-sized vector standing for the parents number by level
435   boost::split(tmp, parameters[2], boost::is_any_of(","));
436   if(tmp.size() != this->levels) {
437     surf_parse_error("Fat trees are defined by the levels number and 3 vectors" 
438                      ", see the documentation for more informations"); 
439   }
440   for(size_t i = 0 ; i < tmp.size() ; i++){
441     this->upperLevelNodesNumber.push_back(std::atoi(tmp[i].c_str())); 
442   }
443   
444   // Finally, a l-sized vector standing for the ports number with the lower level
445   boost::split(tmp, parameters[3], boost::is_any_of(","));
446   if(tmp.size() != this->levels) {
447     surf_parse_error("Fat trees are defined by the levels number and 3 vectors" 
448                      ", see the documentation for more informations"); 
449     
450   }
451   for(size_t i = 0 ; i < tmp.size() ; i++){
452     this->lowerLevelPortsNumber.push_back(std::atoi(tmp[i].c_str())); 
453   }
454   this->cluster = cluster;
455 }
456
457
458 void AsClusterFatTree::generateDotFile(const string& filename) const {
459   ofstream file;
460   /* Maybe should we get directly a char*, as open takes strings only beginning
461    * with C++11...
462    */
463   file.open(filename.c_str(), ios::out | ios::trunc); 
464   
465   if(file.is_open()) {
466     file << "graph AsClusterFatTree {\n";
467     for (unsigned int i = 0 ; i < this->nodes.size() ; i++) {
468       file << this->nodes[i]->id;
469       if(this->nodes[i]->id < 0) {
470         file << " [shape=circle];\n";
471       }
472       else {
473         file << " [shape=hexagon];\n";
474       }
475     }
476
477     for (unsigned int i = 0 ; i < this->links.size() ; i++ ) {
478       file << this->links[i]->downNode->id
479              << " -- "
480            << this->links[i]->upNode->id
481              << ";\n";
482     }
483     file << "}";
484     file.close();
485   }
486   else {
487     XBT_DEBUG("Unable to open file %s", filename.c_str());
488     return;
489   }
490 }
491
492 FatTreeNode::FatTreeNode(sg_platf_cluster_cbarg_t cluster, int id, int level,
493                          int position) : id(id), level(level),
494                                          position(position) {
495   s_sg_platf_link_cbarg_t linkTemplate;
496   if(cluster->limiter_link) {
497     memset(&linkTemplate, 0, sizeof(linkTemplate));
498     linkTemplate.bandwidth = cluster->limiter_link;
499     linkTemplate.latency = 0;
500     linkTemplate.state = SURF_RESOURCE_ON;
501     linkTemplate.policy = SURF_LINK_SHARED;
502     linkTemplate.id = bprintf("limiter_%d", id);
503     sg_platf_new_link(&linkTemplate);
504     this->limiterLink = (NetworkLink*) xbt_lib_get_or_null(link_lib,
505                                                            linkTemplate.id,
506                                                            SURF_LINK_LEVEL);
507     free((void*)linkTemplate.id);
508   }
509   if(cluster->loopback_bw || cluster->loopback_lat) {
510     memset(&linkTemplate, 0, sizeof(linkTemplate));
511     linkTemplate.bandwidth = cluster->loopback_bw;
512     linkTemplate.latency = cluster->loopback_lat;
513     linkTemplate.state = SURF_RESOURCE_ON;
514     linkTemplate.policy = SURF_LINK_FATPIPE;
515     linkTemplate.id = bprintf("loopback_%d", id);
516     sg_platf_new_link(&linkTemplate);
517     this->loopback = (NetworkLink*) xbt_lib_get_or_null(link_lib,
518                                                         linkTemplate.id,
519                                                         SURF_LINK_LEVEL);
520     free((void*)linkTemplate.id);
521   }  
522 }
523
524 FatTreeLink::FatTreeLink(sg_platf_cluster_cbarg_t cluster,
525                          FatTreeNode *downNode,
526                          FatTreeNode *upNode) : upNode(upNode),
527                                                 downNode(downNode) {
528   static int uniqueId = 0;
529   s_sg_platf_link_cbarg_t linkTemplate;
530   memset(&linkTemplate, 0, sizeof(linkTemplate));
531   linkTemplate.bandwidth = cluster->bw;
532   linkTemplate.latency = cluster->lat;
533   linkTemplate.state = SURF_RESOURCE_ON;
534   linkTemplate.policy = cluster->sharing_policy; // sthg to do with that ?
535   linkTemplate.id = bprintf("link_from_%d_to_%d_%d", downNode->id, upNode->id,
536                             uniqueId);
537   sg_platf_new_link(&linkTemplate);
538   NetworkLink* link;
539   std::string tmpID;
540   if (cluster->sharing_policy == SURF_LINK_FULLDUPLEX) {
541     tmpID = std::string(linkTemplate.id) + "_UP";
542     link = (NetworkLink*) xbt_lib_get_or_null(link_lib, tmpID.c_str(),
543                                               SURF_LINK_LEVEL);
544     this->upLink = link; // check link?
545     tmpID = std::string(linkTemplate.id) + "_DOWN";
546     link = (NetworkLink*) xbt_lib_get_or_null(link_lib, tmpID.c_str(),
547                                               SURF_LINK_LEVEL);
548     this->downLink = link; // check link ?
549   }
550   else {
551     link = (NetworkLink*) xbt_lib_get_or_null(link_lib, linkTemplate.id,
552                                               SURF_LINK_LEVEL);
553     this->upLink = link;
554     this->downLink = link;
555   }
556   uniqueId++;
557   free((void*)linkTemplate.id);
558 }