source: XIOS/dev/dev_olga/src/server.cpp @ 1054

Last change on this file since 1054 was 1054, checked in by oabramkina, 7 years ago

dev: intermediate commit.

  • 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: 19.8 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"
16
17namespace xios
18{
19    MPI_Comm CServer::intraComm ;
20    list<MPI_Comm> CServer::interCommLeft ;
21    list<MPI_Comm> CServer::interCommRight ;
22//    list<MPI_Comm> CServer::interComm ;
23    std::list<MPI_Comm> CServer::contextInterComms;
24    int CServer::serverLevel = 0 ;
25    int CServer::serverLeader = 0;
26    int CServer::serverSize = 0;
27    int CServer::nbPools = 0;
28    int CServer::poolId = 0;
29    bool CServer::isRoot = false ;
30    int CServer::rank = INVALID_RANK;
31    StdOFStream CServer::m_infoStream;
32    StdOFStream CServer::m_errorStream;
33    map<string,CContext*> CServer::contextList ;
34    bool CServer::finished=false ;
35    bool CServer::is_MPI_Initialized ;
36    CEventScheduler* CServer::eventScheduler = 0;
37
38//---------------------------------------------------------------
39/*!
40 * \fn void CServer::initialize(void)
41 * Creates intraComm for each possible type of servers (classical, primary or secondary).
42 * In case of secondary servers intraComm is created for each secondary server pool.
43 * (For now the assumption is that there is one proc per pool.)
44 * Creates the following lists of interComms:
45 *   classical server -- interCommLeft
46 *   primary server -- interCommLeft and interCommRight
47 *   secondary server -- interComm for each pool.
48 */
49    void CServer::initialize(void)
50    {
51      int initialized ;
52      MPI_Initialized(&initialized) ;
53      if (initialized) is_MPI_Initialized=true ;
54      else is_MPI_Initialized=false ;
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 hashServer1 = hashString(CXios::xiosCodeIdPrm);
68//        unsigned long hashServer2 = hashString(CXios::xiosCodeIdSnd);
69//        unsigned long hashServer = (CXios::serverLevel < 2)  ? hashServer1 : hashServer2;
70        unsigned long hashServer = hashString(CXios::xiosCodeId);
71
72        unsigned long* hashAll ;
73
74//        int rank ;
75        int size ;
76        int myColor ;
77        int i,c ;
78        MPI_Comm newComm, serversComm;
79
80        MPI_Comm_size(CXios::globalComm, &size) ;
81        MPI_Comm_rank(CXios::globalComm, &rank);
82
83        hashAll=new unsigned long[size] ;
84        MPI_Allgather(&hashServer, 1, MPI_LONG, hashAll, 1, MPI_LONG, CXios::globalComm) ;
85
86        map<unsigned long, int> colors ;
87        map<unsigned long, int> leaders ;
88        map<unsigned long, int>::iterator it ;
89
90        for(i=0,c=0;i<size;i++)
91        {
92          if (colors.find(hashAll[i])==colors.end())
93          {
94            colors[hashAll[i]]=c ;
95            leaders[hashAll[i]]=i ;
96            c++ ;
97          }
98        }
99
100        // Setting the number of secondary pools
101        myColor = colors[hashServer];
102        if (CXios::usingServer2)
103        {
104          int serverRank = rank - leaders[hashServer]; // server proc rank starting 0
105          serverSize = size - leaders[hashServer];
106          nbPools = serverSize * CXios::ratioServer2 / 100;
107          if ( serverRank < (serverSize - nbPools) )
108          {
109            serverLevel = 1;
110          }
111          else
112          {
113            serverLevel = 2;
114            poolId = serverRank - serverSize + nbPools;
115            myColor = rank;
116          }
117        }
118
119        MPI_Comm_split(CXios::globalComm, myColor, rank, &intraComm) ;
120
121        if (serverLevel == 0)
122        {
123          int clientLeader;
124          for(it=leaders.begin();it!=leaders.end();it++)
125          {
126            if (it->first!=hashServer)
127            {
128              clientLeader=it->second ;
129              int intraCommSize, intraCommRank ;
130              MPI_Comm_size(intraComm,&intraCommSize) ;
131              MPI_Comm_rank(intraComm,&intraCommRank) ;
132              info(50)<<"intercommCreate::server "<<rank<<" intraCommSize : "<<intraCommSize
133                       <<" intraCommRank :"<<intraCommRank<<"  clientLeader "<< clientLeader<<endl ;
134
135              MPI_Intercomm_create(intraComm, 0, CXios::globalComm, clientLeader, 0, &newComm) ;
136               interCommLeft.push_back(newComm) ;
137            }
138          }
139        }
140        else if (serverLevel == 1)
141        {
142          int clientLeader, srvSndLeader;
143          int srvPrmLeader ;
144          for (it=leaders.begin();it!=leaders.end();it++)
145          {
146            if (it->first != hashServer)
147            {
148              clientLeader=it->second ;
149              int intraCommSize, intraCommRank ;
150              MPI_Comm_size(intraComm, &intraCommSize) ;
151              MPI_Comm_rank(intraComm, &intraCommRank) ;
152              info(50)<<"intercommCreate::server "<<rank<<" intraCommSize : "<<intraCommSize
153                       <<" intraCommRank :"<<intraCommRank<<"  clientLeader "<< clientLeader<<endl ;
154              MPI_Intercomm_create(intraComm, 0, CXios::globalComm, clientLeader, 0, &newComm) ;
155              interCommLeft.push_back(newComm) ;
156            }
157            else
158              serverLeader = it->second;
159          }
160
161          for (int i = 0; i < nbPools; ++i)
162          {
163            srvSndLeader = serverLeader + serverSize - nbPools + i;
164            int intraCommSize, intraCommRank ;
165            MPI_Comm_size(intraComm, &intraCommSize) ;
166            MPI_Comm_rank(intraComm, &intraCommRank) ;
167            info(50)<<"intercommCreate::client "<<rank<<" intraCommSize : "<<intraCommSize
168                <<" intraCommRank :"<<intraCommRank<<"  clientLeader "<< srvSndLeader<<endl ;
169            MPI_Intercomm_create(intraComm, 0, CXios::globalComm, srvSndLeader, 0, &newComm) ;
170            interCommRight.push_back(newComm) ;
171          }
172        } // primary server
173        else
174        {
175          int clientLeader;
176          clientLeader = leaders[hashString(CXios::xiosCodeId)];
177          int intraCommSize, intraCommRank ;
178          MPI_Comm_size(intraComm, &intraCommSize) ;
179          MPI_Comm_rank(intraComm, &intraCommRank) ;
180          info(50)<<"intercommCreate::server "<<rank<<" intraCommSize : "<<intraCommSize
181                   <<" intraCommRank :"<<intraCommRank<<"  clientLeader "<< clientLeader<<endl ;
182
183          MPI_Intercomm_create(intraComm, 0, CXios::globalComm, clientLeader, 0, &newComm) ;
184          interCommLeft.push_back(newComm) ;
185        } // secondary server
186
187        delete [] hashAll ;
188
189      }
190      // using OASIS
191      else
192      {
193//        int rank ,size;
194        int size;
195        if (!is_MPI_Initialized) oasis_init(CXios::xiosCodeId);
196
197        CTimer::get("XIOS").resume() ;
198        MPI_Comm localComm;
199        oasis_get_localcomm(localComm);
200        MPI_Comm_dup(localComm, &intraComm);
201
202        MPI_Comm_rank(intraComm,&rank) ;
203        MPI_Comm_size(intraComm,&size) ;
204        string codesId=CXios::getin<string>("oasis_codes_id") ;
205
206        vector<string> splitted ;
207        boost::split( splitted, codesId, boost::is_any_of(","), boost::token_compress_on ) ;
208        vector<string>::iterator it ;
209
210        MPI_Comm newComm ;
211        int globalRank ;
212        MPI_Comm_rank(CXios::globalComm,&globalRank);
213
214        for(it=splitted.begin();it!=splitted.end();it++)
215        {
216          oasis_get_intercomm(newComm,*it) ;
217          if (rank==0) MPI_Send(&globalRank,1,MPI_INT,0,0,newComm) ;
218          MPI_Comm_remote_size(newComm,&size);
219//          interComm.push_back(newComm) ;
220          interCommLeft.push_back(newComm) ;
221        }
222              oasis_enddef() ;
223      }
224
225      int rankServer;
226      MPI_Comm_rank(intraComm, &rankServer) ;
227      if (rankServer==0) isRoot=true;
228      else isRoot=false;
229     
230      eventScheduler = new CEventScheduler(intraComm) ;
231    }
232
233    void CServer::finalize(void)
234    {
235
236      CTimer::get("XIOS").suspend() ;
237     
238      delete eventScheduler ;
239
240      for (std::list<MPI_Comm>::iterator it = contextInterComms.begin(); it != contextInterComms.end(); it++)
241        MPI_Comm_free(&(*it));
242
243//      for (std::list<MPI_Comm>::iterator it = interComm.begin(); it != interComm.end(); it++)
244//        MPI_Comm_free(&(*it));
245
246        for (std::list<MPI_Comm>::iterator it = interCommLeft.begin(); it != interCommLeft.end(); it++)
247          MPI_Comm_free(&(*it));
248
249        for (std::list<MPI_Comm>::iterator it = interCommRight.begin(); it != interCommRight.end(); it++)
250          MPI_Comm_free(&(*it));
251
252      MPI_Comm_free(&intraComm);
253
254      if (!is_MPI_Initialized)
255      {
256        if (CXios::usingOasis) oasis_finalize();
257        else MPI_Finalize() ;
258      }
259      report(0)<<"Performance report : Time spent for XIOS : "<<CTimer::get("XIOS server").getCumulatedTime()<<endl  ;
260      report(0)<<"Performance report : Time spent in processing events : "<<CTimer::get("Process events").getCumulatedTime()<<endl  ;
261      report(0)<<"Performance report : Ratio : "<<CTimer::get("Process events").getCumulatedTime()/CTimer::get("XIOS server").getCumulatedTime()*100.<<"%"<<endl  ;
262    }
263
264     void CServer::eventLoop(void)
265     {
266       bool stop=false ;
267
268       CTimer::get("XIOS server").resume() ;
269       while(!stop)
270       {
271
272         if (isRoot)
273         {
274           listenContext();
275           if (!finished) listenFinalize() ;
276         }
277         else
278         {
279           listenRootContext();
280           if (!finished) listenRootFinalize() ;
281         }
282
283         contextEventLoop() ;
284//         if (finished && contextList.empty()) stop=true ;
285         if (finished && contextList.empty()) stop=true ;
286         eventScheduler->checkEvent() ;
287
288       }
289       CTimer::get("XIOS server").suspend() ;
290     }
291
292     void CServer::listenFinalize(void)
293     {
294        list<MPI_Comm>::iterator it, itr;
295        int msg ;
296        int flag ;
297
298        for(it=interCommLeft.begin();it!=interCommLeft.end();it++)
299        {
300           MPI_Status status ;
301           traceOff() ;
302           MPI_Iprobe(0,0,*it,&flag,&status) ;
303           traceOn() ;
304           if (flag==true)
305           {
306              MPI_Recv(&msg,1,MPI_INT,0,0,*it,&status) ;
307              info(20)<<" CServer : Receive client finalize"<<endl ;
308              // Sending server finalize message to secondary servers (if any)
309              for(itr=interCommRight.begin();itr!=interCommRight.end();itr++)
310              {
311                MPI_Send(&msg,1,MPI_INT,0,0,*itr) ;
312//                itr = interCommRight.erase(itr) ;
313              }
314              MPI_Comm_free(&(*it));
315              interCommLeft.erase(it) ;
316              break ;
317            }
318         }
319
320         if (interCommLeft.empty())
321         {
322           int i,size ;
323           MPI_Comm_size(intraComm,&size) ;
324           MPI_Request* requests= new MPI_Request[size-1] ;
325           MPI_Status* status= new MPI_Status[size-1] ;
326
327           for(int i=1;i<size;i++) MPI_Isend(&msg,1,MPI_INT,i,4,intraComm,&requests[i-1]) ;
328           MPI_Waitall(size-1,requests,status) ;
329
330           finished=true ;
331           delete [] requests ;
332           delete [] status ;
333         }
334     }
335
336
337     void CServer::listenRootFinalize()
338     {
339        int flag ;
340        MPI_Status status ;
341        int msg ;
342
343        traceOff() ;
344        MPI_Iprobe(0,4,intraComm, &flag, &status) ;
345        traceOn() ;
346        if (flag==true)
347        {
348           MPI_Recv(&msg,1,MPI_INT,0,4,intraComm,&status) ;
349           finished=true ;
350        }
351      }
352
353     void CServer::listenContext(void)
354     {
355
356       MPI_Status status ;
357       int flag ;
358       static void* buffer ;
359       static MPI_Request request ;
360       static bool recept=false ;
361       int rank ;
362       int count ;
363
364       if (recept==false)
365       {
366         traceOff() ;
367         MPI_Iprobe(MPI_ANY_SOURCE,1,CXios::globalComm, &flag, &status) ;
368         traceOn() ;
369         if (flag==true)
370         {
371           rank=status.MPI_SOURCE ;
372           MPI_Get_count(&status,MPI_CHAR,&count) ;
373           buffer=new char[count] ;
374           MPI_Irecv(buffer,count,MPI_CHAR,rank,1,CXios::globalComm,&request) ;
375           recept=true ;
376         }
377       }
378       else
379       {
380         traceOff() ;
381         MPI_Test(&request,&flag,&status) ;
382         traceOn() ;
383         if (flag==true)
384         {
385           rank=status.MPI_SOURCE ;
386           MPI_Get_count(&status,MPI_CHAR,&count) ;
387           recvContextMessage(buffer,count) ;
388           delete [] buffer;
389           recept=false ;
390         }
391       }
392     }
393
394     void CServer::recvContextMessage(void* buff,int count)
395     {
396       static map<string,contextMessage> recvContextId;
397       map<string,contextMessage>::iterator it ;
398       CBufferIn buffer(buff,count) ;
399       string id ;
400       int clientLeader ;
401       int nbMessage ;
402
403       buffer>>id>>nbMessage>>clientLeader ;
404
405       it=recvContextId.find(id) ;
406       if (it==recvContextId.end())
407       {
408         contextMessage msg={0,0} ;
409         pair<map<string,contextMessage>::iterator,bool> ret ;
410         ret=recvContextId.insert(pair<string,contextMessage>(id,msg)) ;
411         it=ret.first ;
412       }
413       it->second.nbRecv+=1 ;
414       it->second.leaderRank+=clientLeader ;
415
416       if (it->second.nbRecv==nbMessage)
417       {
418         int size ;
419         MPI_Comm_size(intraComm,&size) ;
420         MPI_Request* requests= new MPI_Request[size-1] ;
421         MPI_Status* status= new MPI_Status[size-1] ;
422
423         for(int i=1;i<size;i++)
424         {
425            MPI_Isend(buff,count,MPI_CHAR,i,2,intraComm,&requests[i-1]) ;
426         }
427         MPI_Waitall(size-1,requests,status) ;
428         registerContext(buff,count,it->second.leaderRank) ;
429
430         recvContextId.erase(it) ;
431         delete [] requests ;
432         delete [] status ;
433
434       }
435     }
436
437     void CServer::listenRootContext(void)
438     {
439       MPI_Status status ;
440       int flag ;
441       static void* buffer ;
442       static MPI_Request request ;
443       static bool recept=false ;
444       int rank ;
445       int count ;
446       const int root=0 ;
447
448       if (recept==false)
449       {
450         traceOff() ;
451         MPI_Iprobe(root,2,intraComm, &flag, &status) ;
452         traceOn() ;
453         if (flag==true)
454         {
455           MPI_Get_count(&status,MPI_CHAR,&count) ;
456           buffer=new char[count] ;
457           MPI_Irecv(buffer,count,MPI_CHAR,root,2,intraComm,&request) ;
458           recept=true ;
459         }
460       }
461       else
462       {
463         MPI_Test(&request,&flag,&status) ;
464         if (flag==true)
465         {
466           MPI_Get_count(&status,MPI_CHAR,&count) ;
467           registerContext(buffer,count) ;
468           delete [] buffer ;
469           recept=false ;
470         }
471       }
472     }
473
474     void CServer::registerContext(void* buff, int count, int leaderRank)
475     {
476       string contextId;
477       CBufferIn buffer(buff, count);
478       buffer >> contextId;
479       CContext* context;
480
481       info(20) << "CServer : Register new Context : " << contextId << endl;
482
483       if (contextList.find(contextId) != contextList.end())
484         ERROR("void CServer::registerContext(void* buff, int count, int leaderRank)",
485               << "Context '" << contextId << "' has already been registred");
486
487       context=CContext::create(contextId);
488       contextList[contextId]=context;
489
490       // All type of servers initialize its own server (CContextServer)
491       if (serverLevel < 2)
492       {
493         MPI_Comm contextInterComm;
494         MPI_Intercomm_create(intraComm, 0, CXios::globalComm, leaderRank, 10+leaderRank, &contextInterComm);
495         MPI_Comm inter;
496         MPI_Intercomm_merge(contextInterComm,1,&inter);
497         MPI_Barrier(inter);
498         MPI_Comm_free(&inter);
499         context->initServer(intraComm,contextInterComm);
500         contextInterComms.push_back(contextInterComm);
501       }
502       else if (serverLevel == 2)
503       {
504         context->initServer(intraComm, interCommLeft.front());
505       }
506
507       // Primary server: send create context message to secondary servers and initialize its own client (CContextClient)
508       if (serverLevel == 1)
509       {
510         int i = 0, size;
511         CMessage msg;
512         int messageSize;
513         MPI_Comm_size(intraComm, &size) ;
514         for (std::list<MPI_Comm>::iterator it = interCommRight.begin(); it != interCommRight.end(); it++, ++i)
515         {
516           StdString str = contextId +"_server_" + boost::lexical_cast<string>(i);
517           msg<<str<<size<<rank ;
518           messageSize = msg.size() ;
519           buff = new char[messageSize] ;
520           CBufferOut buffer(buff,messageSize) ;
521           buffer<<msg ;
522           int sndServerGloRanks = serverSize-nbPools+serverLeader +i;  // the assumption is that there is only one proc per secondary server pool
523           MPI_Send(buff, buffer.count(), MPI_CHAR, sndServerGloRanks, 1, CXios::globalComm) ;
524           context->initClient(intraComm, *it) ;
525           delete [] buff ;
526         }
527       }
528     }
529
530     void CServer::contextEventLoop(void)
531     {
532       bool finished ;
533
534       map<string,CContext*>::iterator it ;
535
536       for(it=contextList.begin();it!=contextList.end();it++)
537       {
538         finished=it->second->isFinalized();
539         if (finished)
540         {
541           contextList.erase(it) ;
542           break ;
543         }
544         else
545           finished=it->second->checkBuffersAndListen();
546       }
547     }
548
549     //! Get rank of the current process
550     int CServer::getRank()
551     {
552       return rank;
553     }
554
555    /*!
556    * Open a file specified by a suffix and an extension and use it for the given file buffer.
557    * The file name will be suffix+rank+extension.
558    *
559    * \param fileName[in] protype file name
560    * \param ext [in] extension of the file
561    * \param fb [in/out] the file buffer
562    */
563    void CServer::openStream(const StdString& fileName, const StdString& ext, std::filebuf* fb)
564    {
565      StdStringStream fileNameClient;
566      int numDigit = 0;
567      int size = 0;
568      int id;
569      MPI_Comm_size(CXios::globalComm, &size);
570      while (size)
571      {
572        size /= 10;
573        ++numDigit;
574      }
575
576      if (!CXios::usingServer2)
577        id = getRank();
578      else
579      {
580        if (serverLevel == 1)
581          id = rank-serverLeader;
582        else
583          id = poolId;
584      }
585      fileNameClient << fileName << "_" << std::setfill('0') << std::setw(numDigit) << id << ext;
586      fb->open(fileNameClient.str().c_str(), std::ios::out);
587      if (!fb->is_open())
588        ERROR("void CServer::openStream(const StdString& fileName, const StdString& ext, std::filebuf* fb)",
589              << std::endl << "Can not open <" << fileNameClient << "> file to write the server log(s).");
590    }
591
592    /*!
593    * \brief Open a file stream to write the info logs
594    * Open a file stream with a specific file name suffix+rank
595    * to write the info logs.
596    * \param fileName [in] protype file name
597    */
598    void CServer::openInfoStream(const StdString& fileName)
599    {
600      std::filebuf* fb = m_infoStream.rdbuf();
601      openStream(fileName, ".out", fb);
602
603      info.write2File(fb);
604      report.write2File(fb);
605    }
606
607    //! Write the info logs to standard output
608    void CServer::openInfoStream()
609    {
610      info.write2StdOut();
611      report.write2StdOut();
612    }
613
614    //! Close the info logs file if it opens
615    void CServer::closeInfoStream()
616    {
617      if (m_infoStream.is_open()) m_infoStream.close();
618    }
619
620    /*!
621    * \brief Open a file stream to write the error log
622    * Open a file stream with a specific file name suffix+rank
623    * to write the error log.
624    * \param fileName [in] protype file name
625    */
626    void CServer::openErrorStream(const StdString& fileName)
627    {
628      std::filebuf* fb = m_errorStream.rdbuf();
629      openStream(fileName, ".err", fb);
630
631      error.write2File(fb);
632    }
633
634    //! Write the error log to standard error output
635    void CServer::openErrorStream()
636    {
637      error.write2StdErr();
638    }
639
640    //! Close the error log file if it opens
641    void CServer::closeErrorStream()
642    {
643      if (m_errorStream.is_open()) m_errorStream.close();
644    }
645}
Note: See TracBrowser for help on using the repository browser.