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

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

dev omp from Ada

  • 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: 14.3 KB
Line 
1#include "globalScopeData.hpp"
2#include "xios_spl.hpp"
3#include "cxios.hpp"
4#include "server.hpp"
5#include "type.hpp"
6#include "context.hpp"
7#include "object_template.hpp"
8#include "oasis_cinterface.hpp"
9#include <boost/functional/hash.hpp>
10#include <boost/algorithm/string.hpp>
11#include "mpi.hpp"
12#include "tracer.hpp"
13#include "timer.hpp"
14#include "event_scheduler.hpp"
15using namespace ep_lib;
16
17namespace xios
18{
19    MPI_Comm CServer::intraComm ;
20    list<MPI_Comm> CServer::interComm ;
21    std::list<MPI_Comm> CServer::contextInterComms;
22    bool CServer::isRoot ;
23    int CServer::rank = INVALID_RANK;
24    StdOFStream CServer::m_infoStream;
25    StdOFStream CServer::m_errorStream;
26    map<string,CContext*> CServer::contextList ;
27    bool CServer::finished=false ;
28    bool CServer::is_MPI_Initialized ;
29    CEventScheduler* CServer::eventScheduler = 0;
30   
31    void CServer::initialize(void)
32    {
33     // int initialized ;
34     // MPI_Initialized(&initialized) ;
35     // if (initialized) is_MPI_Initialized=true ;
36     // else is_MPI_Initialized=false ;
37
38      // Not using OASIS
39      if (!CXios::usingOasis)
40      {
41
42       // if (!is_MPI_Initialized)
43       // {
44       //   MPI_Init(NULL, NULL);
45       // }
46        CTimer::get("XIOS").resume() ;
47
48        boost::hash<string> hashString ;
49
50        unsigned long hashServer=hashString(CXios::xiosCodeId) ;
51        unsigned long* hashAll ;
52
53//        int rank ;
54        int size ;
55        int myColor ;
56        int i,c ;
57        MPI_Comm newComm ;
58
59        MPI_Comm_size(CXios::globalComm,&size) ;
60        MPI_Comm_rank(CXios::globalComm,&rank);
61        hashAll=new unsigned long[size] ;
62
63        MPI_Allgather(&hashServer,1,MPI_LONG,hashAll,1,MPI_LONG,CXios::globalComm) ;
64
65        map<unsigned long, int> colors ;
66        map<unsigned long, int> leaders ;
67        map<unsigned long, int>::iterator it ;
68
69        for(i=0,c=0;i<size;i++)
70        {
71          if (colors.find(hashAll[i])==colors.end())
72          {
73            colors[hashAll[i]]=c ;
74            leaders[hashAll[i]]=i ;
75            c++ ;
76          }
77        }
78
79        myColor=colors[hashServer] ;
80        MPI_Comm_split(CXios::globalComm,myColor,rank,&intraComm) ;
81
82        int serverLeader=leaders[hashServer] ;
83        int clientLeader;
84
85         serverLeader=leaders[hashServer] ;
86         for(it=leaders.begin();it!=leaders.end();it++)
87         {
88           if (it->first!=hashServer)
89           {
90             clientLeader=it->second ;
91             int intraCommSize, intraCommRank ;
92             MPI_Comm_size(intraComm,&intraCommSize) ;
93             MPI_Comm_rank(intraComm,&intraCommRank) ;
94             #pragma omp critical (_output)
95             {
96               info(50)<<"intercommCreate::server "<<rank<<" intraCommSize : "<<intraCommSize
97                       <<" intraCommRank :"<<intraCommRank<<"  clientLeader "<< clientLeader<<endl ;
98             }
99             MPI_Intercomm_create(intraComm,0,CXios::globalComm,clientLeader,0,&newComm) ;
100             interComm.push_back(newComm) ;
101           }
102         }
103
104         delete [] hashAll ;
105      }
106      // using OASIS
107/*      else
108      {
109        int rank ,size;
110        int size;
111        if (!is_MPI_Initialized) oasis_init(CXios::xiosCodeId);
112
113        CTimer::get("XIOS").resume() ;
114        MPI_Comm localComm;
115        oasis_get_localcomm(localComm);
116        MPI_Comm_dup(localComm, &intraComm);
117
118        MPI_Comm_rank(intraComm,&rank) ;
119        MPI_Comm_size(intraComm,&size) ;
120        string codesId=CXios::getin<string>("oasis_codes_id") ;
121
122        vector<string> splitted ;
123        boost::split( splitted, codesId, boost::is_any_of(","), boost::token_compress_on ) ;
124        vector<string>::iterator it ;
125
126        MPI_Comm newComm ;
127        int globalRank ;
128        MPI_Comm_rank(CXios::globalComm,&globalRank);
129
130        for(it=splitted.begin();it!=splitted.end();it++)
131        {
132          oasis_get_intercomm(newComm,*it) ;
133          if (rank==0) MPI_Send(&globalRank,1,MPI_INT,0,0,newComm) ;
134          MPI_Comm_remote_size(newComm,&size);
135          interComm.push_back(newComm) ;
136        }
137              oasis_enddef() ;
138      }
139*/
140//      int rank;
141      MPI_Comm_rank(intraComm,&rank) ;
142      if (rank==0) isRoot=true;
143      else isRoot=false;
144     
145      eventScheduler = new CEventScheduler(intraComm) ;
146    }
147
148    void CServer::finalize(void)
149    {
150      CTimer::get("XIOS").suspend() ;
151     
152      delete eventScheduler ;
153
154      for (std::list<MPI_Comm>::iterator it = contextInterComms.begin(); it != contextInterComms.end(); it++)
155        MPI_Comm_free(&(*it));
156      for (std::list<MPI_Comm>::iterator it = interComm.begin(); it != interComm.end(); it++)
157        MPI_Comm_free(&(*it));
158      MPI_Comm_free(&intraComm);
159
160      if (!is_MPI_Initialized)
161      {
162        if (CXios::usingOasis) oasis_finalize();
163        //else MPI_Finalize() ;
164      }
165      report(0)<<"Performance report : Time spent for XIOS : "<<CTimer::get("XIOS server").getCumulatedTime()<<endl  ;
166      report(0)<<"Performance report : Time spent in processing events : "<<CTimer::get("Process events").getCumulatedTime()<<endl  ;
167      report(0)<<"Performance report : Ratio : "<<CTimer::get("Process events").getCumulatedTime()/CTimer::get("XIOS server").getCumulatedTime()*100.<<"%"<<endl  ;
168      report(100)<<CTimer::getAllCumulatedTime()<<endl ;
169    }
170
171     void CServer::eventLoop(void)
172     {
173       bool stop=false ;
174
175       CTimer::get("XIOS server").resume() ;
176       while(!stop)
177       {
178         if (isRoot)
179         {
180           listenContext();
181           if (!finished) listenFinalize() ;
182         }
183         else
184         {
185           listenRootContext();
186           if (!finished) listenRootFinalize() ;
187         }
188
189         contextEventLoop() ;
190         if (finished && contextList.empty()) stop=true ;
191         eventScheduler->checkEvent() ;
192       }
193       CTimer::get("XIOS server").suspend() ;
194     }
195
196     void CServer::listenFinalize(void)
197     {
198        list<MPI_Comm>::iterator it;
199        int msg ;
200        int flag ;
201
202        for(it=interComm.begin();it!=interComm.end();it++)
203        {
204           MPI_Status status ;
205           traceOff() ;
206           MPI_Iprobe(0,0,*it,&flag,&status) ;
207           traceOn() ;
208           if (flag==true)
209           {
210              MPI_Recv(&msg,1,MPI_INT,0,0,*it,&status) ;
211              info(20)<<" CServer : Receive client finalize"<<endl ;
212              MPI_Comm_free(&(*it));
213              interComm.erase(it) ;
214              break ;
215            }
216         }
217
218         if (interComm.empty())
219         {
220           int i,size ;
221           MPI_Comm_size(intraComm,&size) ;
222           MPI_Request* requests= new MPI_Request[size-1] ;
223           MPI_Status* status= new MPI_Status[size-1] ;
224
225           for(int i=1;i<size;i++) MPI_Isend(&msg,1,MPI_INT,i,4,intraComm,&requests[i-1]) ;
226           MPI_Waitall(size-1,requests,status) ;
227
228           finished=true ;
229           delete [] requests ;
230           delete [] status ;
231         }
232     }
233
234
235     void CServer::listenRootFinalize()
236     {
237        int flag ;
238        MPI_Status status ;
239        int msg ;
240
241        traceOff() ;
242        MPI_Iprobe(0,4,intraComm, &flag, &status) ;
243        traceOn() ;
244        if (flag==true)
245        {
246           MPI_Recv(&msg,1,MPI_INT,0,4,intraComm,&status) ;
247           finished=true ;
248        }
249      }
250
251     void CServer::listenContext(void)
252     {
253
254       MPI_Status status ;
255       int flag ;
256       static char* buffer ;
257       static MPI_Request request ;
258       static bool recept=false ;
259       int rank ;
260       int count ;
261
262       if (recept==false)
263       {
264         traceOff() ;
265         MPI_Iprobe(-2,1,CXios::globalComm, &flag, &status) ;
266         traceOn() ;
267         if (flag==true)
268         {
269           #ifdef _usingMPI
270           rank=status.MPI_SOURCE ;
271           #elif _usingEP
272           rank=status.ep_src;
273           #endif
274           MPI_Get_count(&status,MPI_CHAR,&count) ;
275           buffer=new char[count] ;
276           MPI_Irecv((void*)buffer,count,MPI_CHAR,rank,1,CXios::globalComm,&request) ;
277           recept=true ;
278         }
279       }
280       else
281       {
282         traceOff() ;
283         MPI_Test(&request,&flag,&status) ;
284         traceOn() ;
285         if (flag==true)
286         {
287           #ifdef _usingMPI
288           rank=status.MPI_SOURCE ;
289           #elif _usingEP
290           rank=status.ep_src;
291           #endif
292           MPI_Get_count(&status,MPI_CHAR,&count) ;
293           recvContextMessage((void*)buffer,count) ;
294           delete [] buffer ;
295           recept=false ;
296         }
297       }
298     }
299
300     void CServer::recvContextMessage(void* buff,int count)
301     {
302       static map<string,contextMessage> recvContextId ;
303       map<string,contextMessage>::iterator it ;
304
305       CBufferIn buffer(buff,count) ;
306       string id ;
307       int clientLeader ;
308       int nbMessage ;
309
310       buffer>>id>>nbMessage>>clientLeader ;
311
312       it=recvContextId.find(id) ;
313       if (it==recvContextId.end())
314       {
315         contextMessage msg={0,0} ;
316         pair<map<string,contextMessage>::iterator,bool> ret ;
317         ret=recvContextId.insert(pair<string,contextMessage>(id,msg)) ;
318         it=ret.first ;
319       }
320       it->second.nbRecv+=1 ;
321       it->second.leaderRank+=clientLeader ;
322
323       if (it->second.nbRecv==nbMessage)
324       {
325         int size ;
326         MPI_Comm_size(intraComm,&size) ;
327         MPI_Request* requests= new MPI_Request[size-1] ;
328         MPI_Status* status= new MPI_Status[size-1] ;
329
330         for(int i=1;i<size;i++)
331         {
332            MPI_Isend(buff,count,MPI_CHAR,i,2,intraComm,&requests[i-1]) ;
333         }
334         MPI_Waitall(size-1,requests,status) ;
335         registerContext(buff,count,it->second.leaderRank) ;
336
337         recvContextId.erase(it) ;
338         delete [] requests ;
339         delete [] status ;
340
341       }
342     }
343
344     void CServer::listenRootContext(void)
345     {
346
347       MPI_Status status ;
348       int flag ;
349       static char* buffer ;
350       static MPI_Request request ;
351       static bool recept=false ;
352       int rank ;
353       int count ;
354       const int root=0 ;
355
356       if (recept==false)
357       {
358         traceOff() ;
359         MPI_Iprobe(root,2,intraComm, &flag, &status) ;
360         traceOn() ;
361         if (flag==true)
362         {
363           MPI_Get_count(&status,MPI_CHAR,&count) ;
364           buffer=new char[count] ;
365           MPI_Irecv((void*)buffer,count,MPI_CHAR,root,2,intraComm,&request) ;
366           recept=true ;
367         }
368       }
369       else
370       {
371         MPI_Test(&request,&flag,&status) ;
372         if (flag==true)
373         {
374           MPI_Get_count(&status,MPI_CHAR,&count) ;
375           registerContext((void*)buffer,count) ;
376           delete [] buffer ;
377           recept=false ;
378         }
379       }
380     }
381
382     void CServer::registerContext(void* buff, int count, int leaderRank)
383     {
384       string contextId;
385       CBufferIn buffer(buff, count);
386       buffer >> contextId;
387
388       info(20) << "CServer : Register new Context : " << contextId << endl;
389
390       if (contextList.find(contextId) != contextList.end())
391         ERROR("void CServer::registerContext(void* buff, int count, int leaderRank)",
392               << "Context '" << contextId << "' has already been registred");
393
394       MPI_Comm contextIntercomm;
395       //MPI_Barrier(CXios::globalComm);
396       
397       MPI_Intercomm_create(intraComm,0,CXios::globalComm,leaderRank,10+leaderRank,&contextIntercomm);
398
399       MPI_Comm inter;
400       MPI_Intercomm_merge(contextIntercomm,1,&inter);
401       MPI_Barrier(inter);
402
403       CContext* context=CContext::create(contextId);
404       contextList[contextId]=context;
405       context->initServer(intraComm,contextIntercomm);
406
407       contextInterComms.push_back(contextIntercomm);
408       MPI_Comm_free(&inter);
409     }
410
411     void CServer::contextEventLoop(void)
412     {
413       bool finished ;
414       map<string,CContext*>::iterator it ;
415       for(it=contextList.begin();it!=contextList.end();it++)
416       {
417         finished=it->second->checkBuffersAndListen();
418         if (finished)
419         {
420           contextList.erase(it) ;
421           break ;
422         }
423       }
424
425     }
426
427     //! Get rank of the current process
428     int CServer::getRank()
429     {
430       return rank;
431     }
432
433    /*!
434    * Open a file specified by a suffix and an extension and use it for the given file buffer.
435    * The file name will be suffix+rank+extension.
436    *
437    * \param fileName[in] protype file name
438    * \param ext [in] extension of the file
439    * \param fb [in/out] the file buffer
440    */
441    void CServer::openStream(const StdString& fileName, const StdString& ext, std::filebuf* fb)
442    {
443      StdStringStream fileNameClient;
444      int numDigit = 0;
445      int size = 0;
446      MPI_Comm_size(CXios::globalComm, &size);
447      while (size)
448      {
449        size /= 10;
450        ++numDigit;
451      }
452
453      fileNameClient << fileName << "_" << std::setfill('0') << std::setw(numDigit) << getRank() << ext;
454      fb->open(fileNameClient.str().c_str(), std::ios::out);
455      if (!fb->is_open())
456        ERROR("void CServer::openStream(const StdString& fileName, const StdString& ext, std::filebuf* fb)",
457              << std::endl << "Can not open <" << fileNameClient << "> file to write the server log(s).");
458    }
459
460    /*!
461    * \brief Open a file stream to write the info logs
462    * Open a file stream with a specific file name suffix+rank
463    * to write the info logs.
464    * \param fileName [in] protype file name
465    */
466    void CServer::openInfoStream(const StdString& fileName)
467    {
468      std::filebuf* fb = m_infoStream.rdbuf();
469      openStream(fileName, ".out", fb);
470
471      info.write2File(fb);
472      report.write2File(fb);
473    }
474
475    //! Write the info logs to standard output
476    void CServer::openInfoStream()
477    {
478      info.write2StdOut();
479      report.write2StdOut();
480    }
481
482    //! Close the info logs file if it opens
483    void CServer::closeInfoStream()
484    {
485      if (m_infoStream.is_open()) m_infoStream.close();
486    }
487
488    /*!
489    * \brief Open a file stream to write the error log
490    * Open a file stream with a specific file name suffix+rank
491    * to write the error log.
492    * \param fileName [in] protype file name
493    */
494    void CServer::openErrorStream(const StdString& fileName)
495    {
496      std::filebuf* fb = m_errorStream.rdbuf();
497      openStream(fileName, ".err", fb);
498
499      error.write2File(fb);
500    }
501
502    //! Write the error log to standard error output
503    void CServer::openErrorStream()
504    {
505      error.write2StdErr();
506    }
507
508    //! Close the error log file if it opens
509    void CServer::closeErrorStream()
510    {
511      if (m_errorStream.is_open()) m_errorStream.close();
512    }
513}
Note: See TracBrowser for help on using the repository browser.