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

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

branch merged with trunk @1200

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