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

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

dev: test for secondary servers added.

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