source: XIOS/dev/branch_yushan/src/server.cpp @ 1069

Last change on this file since 1069 was 1069, checked in by yushan, 7 years ago

Clean Up

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