source: XIOS/dev/branch_openmp/src/server.cpp @ 1465

Last change on this file since 1465 was 1465, checked in by yushan, 6 years ago

Unify the MPI_Finalize in different tests.

  • Property copyright set to
    Software name : XIOS (Xml I/O Server)
    http://forge.ipsl.jussieu.fr/ioserver
    Creation date : January 2009
    Licence : CeCCIL version2
    see license file in root directory : Licence_CeCILL_V2-en.txt
    or http://www.cecill.info/licences/Licence_CeCILL_V2-en.html
    Holder : CEA/LSCE (Laboratoire des Sciences du CLimat et de l'Environnement)
    CNRS/IPSL (Institut Pierre Simon Laplace)
    Project Manager : Yann Meurdesoif
    yann.meurdesoif@cea.fr
  • Property svn:eol-style set to native
File size: 29.6 KB
Line 
1#include "globalScopeData.hpp"
2#include "xios_spl.hpp"
3#include "cxios.hpp"
4#include "server.hpp"
5#include "client.hpp"
6#include "type.hpp"
7#include "context.hpp"
8#include "object_template.hpp"
9#include "oasis_cinterface.hpp"
10#include <boost/functional/hash.hpp>
11#include <boost/algorithm/string.hpp>
12#include "mpi.hpp"
13#include "tracer.hpp"
14#include "timer.hpp"
15#include "event_scheduler.hpp"
16using namespace ep_lib;
17
18namespace xios
19{
20    MPI_Comm CServer::intraComm ;
21    std::list<MPI_Comm> CServer::interCommLeft ;
22    std::list<MPI_Comm> CServer::interCommRight ;
23    std::list<MPI_Comm> CServer::contextInterComms;
24    std::list<MPI_Comm> CServer::contextIntraComms;
25    int CServer::serverLevel = 0 ;
26    int CServer::nbContexts = 0;
27    bool CServer::isRoot = false ;
28    int CServer::rank_ = INVALID_RANK;
29    StdOFStream CServer::m_infoStream;
30    StdOFStream CServer::m_errorStream;
31    map<string,CContext*> CServer::contextList ;
32    vector<int> CServer::sndServerGlobalRanks;
33    bool CServer::finished=false ;
34    bool CServer::is_MPI_Initialized ;
35    CEventScheduler* CServer::eventScheduler = 0;
36
37//---------------------------------------------------------------
38/*!
39 * \fn void CServer::initialize(void)
40 * Creates intraComm for each possible type of servers (classical, primary or secondary).
41 * (For now the assumption is that there is one proc per secondary server pool.)
42 * Creates interComm and stores them into the following lists:
43 *   classical server -- interCommLeft
44 *   primary server -- interCommLeft and interCommRight
45 *   secondary server -- interCommLeft for each pool.
46 *   IMPORTANT: CXios::usingServer2 should NOT be used beyond this function. Use CServer::serverLevel instead.
47 */
48    void CServer::initialize(void)
49    {
50      //int initialized ;
51      //MPI_Initialized(&initialized) ;
52      //if (initialized) is_MPI_Initialized=true ;
53      //else is_MPI_Initialized=false ;
54      int rank ;
55
56      // Not using OASIS
57      if (!CXios::usingOasis)
58      {
59
60        //if (!is_MPI_Initialized)
61        //{
62        //  MPI_Init(NULL, NULL);
63        //}
64        CTimer::get("XIOS").resume() ;
65
66        boost::hash<string> hashString ;
67        unsigned long hashServer = hashString(CXios::xiosCodeId);
68
69        unsigned long* hashAll ;
70        unsigned long* srvLevelAll ;
71
72        int size ;
73        int myColor ;
74        int i,c ;
75        MPI_Comm newComm;
76
77        MPI_Comm_size(CXios::globalComm, &size) ;
78        MPI_Comm_rank(CXios::globalComm, &rank_);
79
80        hashAll=new unsigned long[size] ;
81        MPI_Allgather(&hashServer, 1, MPI_LONG, hashAll, 1, MPI_LONG, CXios::globalComm) ;
82
83        map<unsigned long, int> colors ;
84        map<unsigned long, int> leaders ;
85        map<unsigned long, int>::iterator it ;
86
87        // (1) Establish client leaders, distribute processes between two server levels
88        std::vector<int> srvRanks;
89        for(i=0,c=0;i<size;i++)
90        {
91          if (colors.find(hashAll[i])==colors.end())
92          {
93            colors[hashAll[i]]=c ;
94            leaders[hashAll[i]]=i ;
95            c++ ;
96          }
97          if (CXios::usingServer2)
98            if (hashAll[i] == hashServer)
99              srvRanks.push_back(i);
100        }
101
102        if (CXios::usingServer2)
103        {
104          int reqNbProc = srvRanks.size()*CXios::ratioServer2/100.;
105          if (reqNbProc<1 || reqNbProc==srvRanks.size())
106          {
107            error(0)<<"WARNING: void CServer::initialize(void)"<<endl
108                << "It is impossible to dedicate the requested number of processes = "<<reqNbProc
109                <<" to secondary server. XIOS will run in the classical server mode."<<endl;
110          }
111          else
112          {
113            int firstSndSrvRank = srvRanks.size()*(100.-CXios::ratioServer2)/100. ;
114            int poolLeader = firstSndSrvRank;
115//*********** (1) Comment out the line below to set one process per pool
116//            sndServerGlobalRanks.push_back(srvRanks[poolLeader]);
117            int nbPools = CXios::nbPoolsServer2;
118            if ( nbPools > reqNbProc || nbPools < 1)
119            {
120              error(0)<<"WARNING: void CServer::initialize(void)"<<endl
121                  << "It is impossible to allocate the requested number of pools = "<<nbPools
122                  <<" on the secondary server. It will be set so that there is one process per pool."<<endl;
123              nbPools = reqNbProc;
124            }
125            int remainder = ((int) (srvRanks.size()*CXios::ratioServer2/100.)) % nbPools;
126            int procsPerPool = ((int) (srvRanks.size()*CXios::ratioServer2/100.)) / nbPools;
127            for (i=0; i<srvRanks.size(); i++)
128            {
129              if (i >= firstSndSrvRank)
130              {
131                if (rank_ == srvRanks[i])
132                {
133                  serverLevel=2;
134                }
135                poolLeader += procsPerPool;
136                if (remainder != 0)
137                {
138                  ++poolLeader;
139                  --remainder;
140                }
141//*********** (2) Comment out the two lines below to set one process per pool
142//                if (poolLeader < srvRanks.size())
143//                  sndServerGlobalRanks.push_back(srvRanks[poolLeader]);
144//*********** (3) Uncomment the line below to set one process per pool
145                sndServerGlobalRanks.push_back(srvRanks[i]);
146              }
147              else
148              {
149                if (rank_ == srvRanks[i]) serverLevel=1;
150              }
151            }
152            if (serverLevel==2)
153            {
154              #pragma omp critical (_output)
155              info(50)<<"The number of secondary server pools is "<< sndServerGlobalRanks.size() <<endl ;
156              for (i=0; i<sndServerGlobalRanks.size(); i++)
157              {
158                if (rank_>= sndServerGlobalRanks[i])
159                {
160                  if ( i == sndServerGlobalRanks.size()-1)
161                  {
162                    myColor = colors.size() + sndServerGlobalRanks[i];
163                  }
164                  else if (rank_< sndServerGlobalRanks[i+1])
165                  {
166                    myColor = colors.size() + sndServerGlobalRanks[i];
167                    break;
168                  }
169                }
170              }
171            }
172          }
173        }
174
175        // (2) Create intraComm
176        if (serverLevel != 2) myColor=colors[hashServer];
177        MPI_Comm_split(CXios::globalComm, myColor, rank_, &intraComm) ;
178
179        // (3) Create interComm
180        if (serverLevel == 0)
181        {
182          int clientLeader;
183          for(it=leaders.begin();it!=leaders.end();it++)
184          {
185            if (it->first!=hashServer)
186            {
187              clientLeader=it->second ;
188              int intraCommSize, intraCommRank ;
189              MPI_Comm_size(intraComm,&intraCommSize) ;
190              MPI_Comm_rank(intraComm,&intraCommRank) ;
191              #pragma omp critical (_output)
192              {
193                info(50)<<"intercommCreate::server (classical mode) "<<rank_<<" intraCommSize : "<<intraCommSize
194                       <<" intraCommRank :"<<intraCommRank<<"  clientLeader "<< clientLeader<<endl ;
195              }
196
197              MPI_Intercomm_create(intraComm, 0, CXios::globalComm, clientLeader, 0, &newComm) ;
198              interCommLeft.push_back(newComm) ;
199            }
200          }
201        }
202        else if (serverLevel == 1)
203        {
204          int clientLeader, srvSndLeader;
205          int srvPrmLeader ;
206
207          for (it=leaders.begin();it!=leaders.end();it++)
208          {
209            if (it->first != hashServer)
210            {
211              clientLeader=it->second ;
212              int intraCommSize, intraCommRank ;
213              MPI_Comm_size(intraComm, &intraCommSize) ;
214              MPI_Comm_rank(intraComm, &intraCommRank) ;
215              #pragma omp critical (_output)
216              {
217                info(50)<<"intercommCreate::server (server level 1) "<<rank_<<" intraCommSize : "<<intraCommSize
218                       <<" intraCommRank :"<<intraCommRank<<"  clientLeader "<< clientLeader<<endl ;
219              }
220              MPI_Intercomm_create(intraComm, 0, CXios::globalComm, clientLeader, 0, &newComm) ;
221              interCommLeft.push_back(newComm) ;
222            }
223          }
224
225          for (int i = 0; i < sndServerGlobalRanks.size(); ++i)
226          {
227            int intraCommSize, intraCommRank ;
228            MPI_Comm_size(intraComm, &intraCommSize) ;
229            MPI_Comm_rank(intraComm, &intraCommRank) ;
230            #pragma omp critical (_output)
231            {
232              info(50)<<"intercommCreate::client (server level 1) "<<rank_<<" intraCommSize : "<<intraCommSize
233                <<" intraCommRank :"<<intraCommRank<<"  clientLeader "<< sndServerGlobalRanks[i]<<endl ;
234            }
235            MPI_Intercomm_create(intraComm, 0, CXios::globalComm, sndServerGlobalRanks[i], 1, &newComm) ;
236            interCommRight.push_back(newComm) ;
237          }
238        }
239        else
240        {
241          int clientLeader;
242          clientLeader = leaders[hashString(CXios::xiosCodeId)];
243          int intraCommSize, intraCommRank ;
244          MPI_Comm_size(intraComm, &intraCommSize) ;
245          MPI_Comm_rank(intraComm, &intraCommRank) ;
246          #pragma omp critical (_output)
247          {
248            info(50)<<"intercommCreate::server (server level 2) "<<rank_<<" intraCommSize : "<<intraCommSize
249                   <<" intraCommRank :"<<intraCommRank<<"  clientLeader "<< clientLeader<<endl ;
250          }
251
252          MPI_Intercomm_create(intraComm, 0, CXios::globalComm, clientLeader, 1, &newComm) ;
253          interCommLeft.push_back(newComm) ;
254        }
255
256        delete [] hashAll ;
257
258      }
259      // using OASIS
260      else
261      {
262        int size;
263        int myColor;
264        int* srvGlobalRanks;
265        if (!is_MPI_Initialized) oasis_init(CXios::xiosCodeId);
266
267        CTimer::get("XIOS").resume() ;
268        MPI_Comm localComm;
269        oasis_get_localcomm(localComm);
270        MPI_Comm_rank(localComm,&rank_) ;
271
272//      (1) Create server intraComm
273        if (!CXios::usingServer2)
274        {
275          MPI_Comm_dup(localComm, &intraComm);
276        }
277        else
278        {
279          int globalRank;
280          MPI_Comm_size(localComm,&size) ;
281          MPI_Comm_rank(CXios::globalComm,&globalRank) ;
282          srvGlobalRanks = new int[size] ;
283          MPI_Allgather(&globalRank, 1, MPI_INT, srvGlobalRanks, 1, MPI_INT, localComm) ;
284
285          int reqNbProc = size*CXios::ratioServer2/100.;
286          if (reqNbProc < 1 || reqNbProc == size)
287          {
288            error(0)<<"WARNING: void CServer::initialize(void)"<<endl
289                << "It is impossible to dedicate the requested number of processes = "<<reqNbProc
290                <<" to secondary server. XIOS will run in the classical server mode."<<endl;
291            MPI_Comm_dup(localComm, &intraComm);
292          }
293          else
294          {
295            int firstSndSrvRank = size*(100.-CXios::ratioServer2)/100. ;
296            int poolLeader = firstSndSrvRank;
297//*********** (1) Comment out the line below to set one process per pool
298//            sndServerGlobalRanks.push_back(srvGlobalRanks[poolLeader]);
299            int nbPools = CXios::nbPoolsServer2;
300            if ( nbPools > reqNbProc || nbPools < 1)
301            {
302              error(0)<<"WARNING: void CServer::initialize(void)"<<endl
303                  << "It is impossible to allocate the requested number of pools = "<<nbPools
304                  <<" on the secondary server. It will be set so that there is one process per pool."<<endl;
305              nbPools = reqNbProc;
306            }
307            int remainder = ((int) (size*CXios::ratioServer2/100.)) % nbPools;
308            int procsPerPool = ((int) (size*CXios::ratioServer2/100.)) / nbPools;
309            for (int i=0; i<size; i++)
310            {
311              if (i >= firstSndSrvRank)
312              {
313                if (globalRank == srvGlobalRanks[i])
314                {
315                  serverLevel=2;
316                }
317                poolLeader += procsPerPool;
318                if (remainder != 0)
319                {
320                  ++poolLeader;
321                  --remainder;
322                }
323//*********** (2) Comment out the two lines below to set one process per pool
324//                if (poolLeader < size)
325//                  sndServerGlobalRanks.push_back(srvGlobalRanks[poolLeader]);
326//*********** (3) Uncomment the line below to set one process per pool
327                sndServerGlobalRanks.push_back(srvGlobalRanks[i]);
328              }
329              else
330              {
331                if (globalRank == srvGlobalRanks[i]) serverLevel=1;
332              }
333            }
334            if (serverLevel==2)
335            {
336              info(50)<<"The number of secondary server pools is "<< sndServerGlobalRanks.size() <<endl ;
337              for (int i=0; i<sndServerGlobalRanks.size(); i++)
338              {
339                if (globalRank>= sndServerGlobalRanks[i])
340                {
341                  if (i == sndServerGlobalRanks.size()-1)
342                  {
343                    myColor = sndServerGlobalRanks[i];
344                  }
345                  else if (globalRank< sndServerGlobalRanks[i+1])
346                  {
347                    myColor = sndServerGlobalRanks[i];
348                    break;
349                  }
350                }
351              }
352            }
353            if (serverLevel != 2) myColor=0;
354            MPI_Comm_split(localComm, myColor, rank_, &intraComm) ;
355          }
356        }
357
358        string codesId=CXios::getin<string>("oasis_codes_id") ;
359        vector<string> splitted ;
360        boost::split( splitted, codesId, boost::is_any_of(","), boost::token_compress_on ) ;
361        vector<string>::iterator it ;
362
363        MPI_Comm newComm ;
364        int globalRank ;
365        MPI_Comm_rank(CXios::globalComm,&globalRank);
366
367//      (2) Create interComms with models
368        for(it=splitted.begin();it!=splitted.end();it++)
369        {
370          oasis_get_intercomm(newComm,*it) ;
371          if ( serverLevel == 0 || serverLevel == 1)
372          {
373            interCommLeft.push_back(newComm) ;
374            if (rank_==0) MPI_Send(&globalRank,1,MPI_INT,0,0,newComm) ;
375          }
376        }
377
378//      (3) Create interComms between primary and secondary servers
379        int intraCommSize, intraCommRank ;
380        MPI_Comm_size(intraComm,&intraCommSize) ;
381        MPI_Comm_rank(intraComm, &intraCommRank) ;
382
383        if (serverLevel == 1)
384        {
385          for (int i = 0; i < sndServerGlobalRanks.size(); ++i)
386          {
387            int srvSndLeader = sndServerGlobalRanks[i];
388            info(50)<<"intercommCreate::client (server level 1) "<<globalRank<<" intraCommSize : "<<intraCommSize
389                <<" intraCommRank :"<<intraCommRank<<"  clientLeader "<< srvSndLeader<<endl ;
390            MPI_Intercomm_create(intraComm, 0, CXios::globalComm, srvSndLeader, 0, &newComm) ;
391            interCommRight.push_back(newComm) ;
392          }
393        }
394        else if (serverLevel == 2)
395        {
396          info(50)<<"intercommCreate::server (server level 2)"<<globalRank<<" intraCommSize : "<<intraCommSize
397                   <<" intraCommRank :"<<intraCommRank<<"  clientLeader "<< srvGlobalRanks[0] <<endl ;
398          MPI_Intercomm_create(intraComm, 0, CXios::globalComm, srvGlobalRanks[0], 0, &newComm) ;
399          interCommLeft.push_back(newComm) ;
400        }
401        if (CXios::usingServer2) delete [] srvGlobalRanks ;
402        oasis_enddef() ;
403      }
404
405
406      MPI_Comm_rank(intraComm, &rank) ;
407      if (rank==0) isRoot=true;
408      else isRoot=false;
409     
410      eventScheduler = new CEventScheduler(intraComm) ;
411    }
412
413    void CServer::finalize(void)
414    {
415      CTimer::get("XIOS").suspend() ;
416     
417      delete eventScheduler ;
418
419      for (std::list<MPI_Comm>::iterator it = contextInterComms.begin(); it != contextInterComms.end(); it++)
420        MPI_Comm_free(&(*it));
421
422      for (std::list<MPI_Comm>::iterator it = contextIntraComms.begin(); it != contextIntraComms.end(); it++)
423        MPI_Comm_free(&(*it));
424
425//      for (std::list<MPI_Comm>::iterator it = interComm.begin(); it != interComm.end(); it++)
426//        MPI_Comm_free(&(*it));
427
428//        for (std::list<MPI_Comm>::iterator it = interCommLeft.begin(); it != interCommLeft.end(); it++)
429//          MPI_Comm_free(&(*it));
430
431        for (std::list<MPI_Comm>::iterator it = interCommRight.begin(); it != interCommRight.end(); it++)
432          MPI_Comm_free(&(*it));
433
434      MPI_Comm_free(&intraComm);
435
436      if (!is_MPI_Initialized)
437      {
438        if (CXios::usingOasis) oasis_finalize();
439        //else MPI_Finalize() ;
440      }
441
442      //MPI_Finalize();
443
444      report(0)<<"Performance report : Time spent for XIOS : "<<CTimer::get("XIOS server").getCumulatedTime()<<endl  ;
445      report(0)<<"Performance report : Time spent in processing events : "<<CTimer::get("Process events").getCumulatedTime()<<endl  ;
446      report(0)<<"Performance report : Ratio : "<<CTimer::get("Process events").getCumulatedTime()/CTimer::get("XIOS server").getCumulatedTime()*100.<<"%"<<endl  ;
447      report(100)<<CTimer::getAllCumulatedTime()<<endl ;
448    }
449
450     void CServer::eventLoop(void)
451     {
452       bool stop=false ;
453
454       CTimer::get("XIOS server").resume() ;
455       while(!stop)
456       {
457         if (isRoot)
458         {
459           listenContext();
460           listenRootContext();
461           if (!finished) listenFinalize() ;
462         }
463         else
464         {
465           listenRootContext();
466           if (!finished) listenRootFinalize() ;
467         }
468
469         contextEventLoop() ;
470         if (finished && contextList.empty()) stop=true ;
471         eventScheduler->checkEvent() ;
472       }
473       CTimer::get("XIOS server").suspend() ;
474     }
475
476     void CServer::listenFinalize(void)
477     {
478        list<MPI_Comm>::iterator it, itr;
479        int msg ;
480        int flag ;
481
482        for(it=interCommLeft.begin();it!=interCommLeft.end();it++)
483        {
484           MPI_Status status ;
485           traceOff() ;
486           MPI_Iprobe(0,0,*it,&flag,&status) ;
487           traceOn() ;
488           if (flag==true)
489           {
490              MPI_Recv(&msg,1,MPI_INT,0,0,*it,&status) ;
491              info(20)<<" CServer : Receive client finalize"<<endl ;
492              // Sending server finalize message to secondary servers (if any)
493              for(itr=interCommRight.begin();itr!=interCommRight.end();itr++)
494              {
495                MPI_Send(&msg,1,MPI_INT,0,0,*itr) ;
496              }
497              MPI_Comm_free(&(*it));
498              interCommLeft.erase(it) ;
499              break ;
500            }
501         }
502
503         if (interCommLeft.empty())
504         {
505           int i,size ;
506           MPI_Comm_size(intraComm,&size) ;
507           MPI_Request* requests= new MPI_Request[size-1] ;
508           MPI_Status* status= new MPI_Status[size-1] ;
509
510           for(int i=1;i<size;i++) MPI_Isend(&msg,1,MPI_INT,i,4,intraComm,&requests[i-1]) ;
511           MPI_Waitall(size-1,requests,status) ;
512
513           finished=true ;
514           delete [] requests ;
515           delete [] status ;
516         }
517     }
518
519
520     void CServer::listenRootFinalize()
521     {
522        int flag ;
523        MPI_Status status ;
524        int msg ;
525
526        traceOff() ;
527        MPI_Iprobe(0,4,intraComm, &flag, &status) ;
528        traceOn() ;
529        if (flag==true)
530        {
531           MPI_Recv(&msg,1,MPI_INT,0,4,intraComm,&status) ;
532           finished=true ;
533        }
534      }
535
536     void CServer::listenContext(void)
537     {
538
539       MPI_Status status ;
540       int flag ;
541       static char* buffer ;
542       static MPI_Request request ;
543       static bool recept=false ;
544       int rank ;
545       int count ;
546
547       if (recept==false)
548       {
549         traceOff() ;
550         MPI_Iprobe(-2,1,CXios::globalComm, &flag, &status) ;
551         traceOn() ;
552         if (flag==true)
553         {
554           #ifdef _usingMPI
555           rank=status.MPI_SOURCE ;
556           #elif _usingEP
557           rank=status.ep_src;
558           #endif
559           MPI_Get_count(&status,MPI_CHAR,&count) ;
560           buffer=new char[count] ;
561           MPI_Irecv((void*)buffer,count,MPI_CHAR,rank,1,CXios::globalComm,&request) ;
562           recept=true ;
563         }
564       }
565       else
566       {
567         traceOff() ;
568         MPI_Test(&request,&flag,&status) ;
569         traceOn() ;
570         if (flag==true)
571         {
572           #ifdef _usingMPI
573           rank=status.MPI_SOURCE ;
574           #elif _usingEP
575           rank=status.ep_src;
576           #endif
577           MPI_Get_count(&status,MPI_CHAR,&count) ;
578           recvContextMessage((void*)buffer,count) ;
579           delete [] buffer ;
580           recept=false ;
581         }
582       }
583     }
584
585     void CServer::recvContextMessage(void* buff,int count)
586     {
587       static map<string,contextMessage> recvContextId;
588       map<string,contextMessage>::iterator it ;
589       CBufferIn buffer(buff,count) ;
590       string id ;
591       int clientLeader ;
592       int nbMessage ;
593
594       buffer>>id>>nbMessage>>clientLeader ;
595
596       it=recvContextId.find(id) ;
597       if (it==recvContextId.end())
598       {
599         contextMessage msg={0,0} ;
600         pair<map<string,contextMessage>::iterator,bool> ret ;
601         ret=recvContextId.insert(pair<string,contextMessage>(id,msg)) ;
602         it=ret.first ;
603       }
604       it->second.nbRecv+=1 ;
605       it->second.leaderRank+=clientLeader ;
606
607       if (it->second.nbRecv==nbMessage)
608       {
609         int size ;
610         MPI_Comm_size(intraComm,&size) ;
611//         MPI_Request* requests= new MPI_Request[size-1] ;
612//         MPI_Status* status= new MPI_Status[size-1] ;
613         MPI_Request* requests= new MPI_Request[size] ;
614         MPI_Status* status= new MPI_Status[size] ;
615
616         CMessage msg ;
617         msg<<id<<it->second.leaderRank;
618         int messageSize=msg.size() ;
619         void * sendBuff = new char[messageSize] ;
620         CBufferOut sendBuffer(sendBuff,messageSize) ;
621         sendBuffer<<msg ;
622
623         // Include root itself in order not to have a divergence
624         for(int i=0; i<size; i++)
625         {
626           MPI_Isend(sendBuff,sendBuffer.count(),MPI_CHAR,i,2,intraComm,&requests[i]) ;
627         }
628
629         recvContextId.erase(it) ;
630         delete [] requests ;
631         delete [] status ;
632
633       }
634     }
635
636     void CServer::listenRootContext(void)
637     {
638       MPI_Status status ;
639       int flag ;
640       static std::vector<void*> buffers;
641       static std::vector<MPI_Request> requests ;
642       static std::vector<int> counts ;
643       static std::vector<bool> isEventRegistered ;
644       static std::vector<bool> isEventQueued ;
645       MPI_Request request;
646
647       int rank ;
648       const int root=0 ;
649       boost::hash<string> hashString;
650       size_t hashId = hashString("RegisterContext");
651
652       // (1) Receive context id from the root, save it into a buffer
653       traceOff() ;
654       MPI_Iprobe(root,2,intraComm, &flag, &status) ;
655       traceOn() ;
656       if (flag==true)
657       {
658         counts.push_back(0);
659         MPI_Get_count(&status,MPI_CHAR,&(counts.back())) ;
660         buffers.push_back(new char[counts.back()]) ;
661         requests.push_back(request);
662         MPI_Irecv((void*)(buffers.back()),counts.back(),MPI_CHAR,root,2,intraComm,&(requests.back())) ;
663         isEventRegistered.push_back(false);
664         isEventQueued.push_back(false);
665         nbContexts++;
666       }
667
668       for (int ctxNb = 0; ctxNb < nbContexts; ctxNb++ )
669       {
670         // (2) If context id is received, register an event
671         MPI_Test(&requests[ctxNb],&flag,&status) ;
672         if (flag==true && !isEventRegistered[ctxNb])
673         {
674           eventScheduler->registerEvent(ctxNb,hashId);
675           isEventRegistered[ctxNb] = true;
676         }
677         // (3) If event has been scheduled, call register context
678         if (eventScheduler->queryEvent(ctxNb,hashId) && !isEventQueued[ctxNb])
679         {
680           registerContext(buffers[ctxNb],counts[ctxNb]) ;
681           isEventQueued[ctxNb] = true;
682           delete [] buffers[ctxNb] ;
683         }
684       }
685
686     }
687
688     void CServer::registerContext(void* buff, int count, int leaderRank)
689     {
690       string contextId;
691       CBufferIn buffer(buff, count);
692//       buffer >> contextId;
693       buffer >> contextId>>leaderRank;
694       CContext* context;
695
696       info(20) << "CServer : Register new Context : " << contextId << endl;
697
698       if (contextList.find(contextId) != contextList.end())
699         ERROR("void CServer::registerContext(void* buff, int count, int leaderRank)",
700               << "Context '" << contextId << "' has already been registred");
701
702       context=CContext::create(contextId);
703       contextList[contextId]=context;
704
705       // Primary or classical server: create communication channel with a client
706       // (1) create interComm (with a client)
707       // (2) initialize client and server (contextClient and contextServer)
708       MPI_Comm inter;
709       if (serverLevel < 2)
710       {
711         MPI_Comm contextInterComm;
712         MPI_Intercomm_create(intraComm, 0, CXios::globalComm, leaderRank, 10+leaderRank, &contextInterComm);
713         MPI_Intercomm_merge(contextInterComm,1,&inter);
714         MPI_Barrier(inter);
715         context->initServer(intraComm,contextInterComm);
716         contextInterComms.push_back(contextInterComm);
717
718         MPI_Comm_free(&inter);
719       }
720       // Secondary server: create communication channel with a primary server
721       // (1) duplicate interComm with a primary server
722       // (2) initialize client and server (contextClient and contextServer)
723       // Remark: in the case of the secondary server there is no need to create an interComm calling MPI_Intercomm_create,
724       //         because interComm of CContext is defined on the same processes as the interComm of CServer.
725       //         So just duplicate it.
726       else if (serverLevel == 2)
727       {
728         MPI_Comm_dup(interCommLeft.front(), &inter);
729         contextInterComms.push_back(inter);
730         context->initServer(intraComm, contextInterComms.back());
731       }
732
733       // Primary server:
734       // (1) send create context message to secondary servers
735       // (2) initialize communication channels with secondary servers (create contextClient and contextServer)
736       if (serverLevel == 1)
737       {
738         int i = 0, size;
739         MPI_Comm_size(intraComm, &size) ;
740         for (std::list<MPI_Comm>::iterator it = interCommRight.begin(); it != interCommRight.end(); it++, ++i)
741         {
742           StdString str = contextId +"_server_" + boost::lexical_cast<string>(i);
743           CMessage msg;
744           int messageSize;
745           msg<<str<<size<<rank_ ;
746           messageSize = msg.size() ;
747           buff = new char[messageSize] ;
748           CBufferOut buffer(buff,messageSize) ;
749           buffer<<msg ;
750           MPI_Send(buff, buffer.count(), MPI_CHAR, sndServerGlobalRanks[i], 1, CXios::globalComm) ;
751           MPI_Comm_dup(*it, &inter);
752           contextInterComms.push_back(inter);
753           MPI_Comm_dup(intraComm, &inter);
754           contextIntraComms.push_back(inter);
755           context->initClient(contextIntraComms.back(), contextInterComms.back()) ;
756           delete [] buff ;
757         }
758       }
759     }
760
761     void CServer::contextEventLoop(bool enableEventsProcessing /*= true*/)
762     {
763       bool isFinalized ;
764       map<string,CContext*>::iterator it ;
765
766       for(it=contextList.begin();it!=contextList.end();it++)
767       {
768         isFinalized=it->second->isFinalized();
769         if (isFinalized)
770         {
771           contextList.erase(it) ;
772           break ;
773         }
774         else
775           it->second->checkBuffersAndListen(enableEventsProcessing);
776       }
777     }
778
779     //! Get rank of the current process in the intraComm
780     int CServer::getRank()
781     {
782       int rank;
783       MPI_Comm_rank(intraComm,&rank);
784       return rank;
785     }
786
787     vector<int>& CServer::getSecondaryServerGlobalRanks()
788     {
789       return sndServerGlobalRanks;
790     }
791
792    /*!
793    * Open a file specified by a suffix and an extension and use it for the given file buffer.
794    * The file name will be suffix+rank+extension.
795    *
796    * \param fileName[in] protype file name
797    * \param ext [in] extension of the file
798    * \param fb [in/out] the file buffer
799    */
800    void CServer::openStream(const StdString& fileName, const StdString& ext, std::filebuf* fb)
801    {
802      StdStringStream fileNameClient;
803      int numDigit = 0;
804      int size = 0;
805      int id;
806      MPI_Comm_size(CXios::globalComm, &size);
807      while (size)
808      {
809        size /= 10;
810        ++numDigit;
811      }
812      id = rank_; //getRank();
813
814      fileNameClient << fileName << "_" << std::setfill('0') << std::setw(numDigit) << id << ext;
815      fb->open(fileNameClient.str().c_str(), std::ios::out);
816      if (!fb->is_open())
817        ERROR("void CServer::openStream(const StdString& fileName, const StdString& ext, std::filebuf* fb)",
818              << std::endl << "Can not open <" << fileNameClient << "> file to write the server log(s).");
819    }
820
821    /*!
822    * \brief Open a file stream to write the info logs
823    * Open a file stream with a specific file name suffix+rank
824    * to write the info logs.
825    * \param fileName [in] protype file name
826    */
827    void CServer::openInfoStream(const StdString& fileName)
828    {
829      std::filebuf* fb = m_infoStream.rdbuf();
830      openStream(fileName, ".out", fb);
831
832      info.write2File(fb);
833      report.write2File(fb);
834    }
835
836    //! Write the info logs to standard output
837    void CServer::openInfoStream()
838    {
839      info.write2StdOut();
840      report.write2StdOut();
841    }
842
843    //! Close the info logs file if it opens
844    void CServer::closeInfoStream()
845    {
846      if (m_infoStream.is_open()) m_infoStream.close();
847    }
848
849    /*!
850    * \brief Open a file stream to write the error log
851    * Open a file stream with a specific file name suffix+rank
852    * to write the error log.
853    * \param fileName [in] protype file name
854    */
855    void CServer::openErrorStream(const StdString& fileName)
856    {
857      std::filebuf* fb = m_errorStream.rdbuf();
858      openStream(fileName, ".err", fb);
859
860      error.write2File(fb);
861    }
862
863    //! Write the error log to standard error output
864    void CServer::openErrorStream()
865    {
866      error.write2StdErr();
867    }
868
869    //! Close the error log file if it opens
870    void CServer::closeErrorStream()
871    {
872      if (m_errorStream.is_open()) m_errorStream.close();
873    }
874}
Note: See TracBrowser for help on using the repository browser.