source: CONFIG_DEVT/IPSLCM6.5_work_ENSEMBLES/modeles/XIOS/src/server.cpp @ 5861

Last change on this file since 5861 was 5861, checked in by ymipsl, 3 years ago
  • Adapt XIOS sources to manage ensemble runs, using new version of oasis

YM

File size: 34.2 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#include "string_tools.hpp"
17
18namespace xios
19{
20    MPI_Comm CServer::intraComm ;
21    std::list<MPI_Comm> CServer::interCommLeft ;
22    std::list<MPI_Comm> CServer::interCommRight ;
23    std::list<MPI_Comm> CServer::contextInterComms;
24    std::list<MPI_Comm> CServer::contextIntraComms;
25    int CServer::serverLevel = 0 ;
26    int CServer::nbContexts = 0;
27    bool CServer::isRoot = false ;
28    int CServer::rank_ = INVALID_RANK;
29    StdOFStream CServer::m_infoStream;
30    StdOFStream CServer::m_errorStream;
31    map<string,CContext*> CServer::contextList ;
32    vector<int> CServer::sndServerGlobalRanks;
33    bool CServer::finished=false ;
34    bool CServer::is_MPI_Initialized ;
35    CEventScheduler* CServer::eventScheduler = 0;
36
37//---------------------------------------------------------------
38/*!
39 * \fn void CServer::initialize(void)
40 * Creates intraComm for each possible type of servers (classical, primary or secondary).
41 * Creates interComm and stores them into the following lists:
42 *   classical server -- interCommLeft
43 *   primary server -- interCommLeft and interCommRight
44 *   secondary server -- interCommLeft for each pool.
45 *   IMPORTANT: CXios::usingServer2 should NOT be used beyond this function. Use CServer::serverLevel instead.
46 */
47    void CServer::initialize(void)
48    {
49      int initialized ;
50      MPI_Initialized(&initialized) ;
51      if (initialized) is_MPI_Initialized=true ;
52      else is_MPI_Initialized=false ;
53      int rank ;
54
55      // Not using OASIS
56      if (!CXios::usingOasis)
57      {
58
59        if (!is_MPI_Initialized)
60        {
61          MPI_Init(NULL, NULL);
62        }
63        CTimer::get("XIOS").resume() ;
64
65        boost::hash<string> hashString ;
66        unsigned long hashServer = hashString(CXios::xiosCodeId);
67
68        unsigned long* hashAll ;
69        unsigned long* srvLevelAll ;
70
71        int size ;
72        int myColor ;
73        int i,c ;
74        MPI_Comm newComm;
75
76        MPI_Comm_size(CXios::globalComm, &size) ;
77        MPI_Comm_rank(CXios::globalComm, &rank_);
78
79        hashAll=new unsigned long[size] ;
80        MPI_Allgather(&hashServer, 1, MPI_LONG, hashAll, 1, MPI_LONG, CXios::globalComm) ;
81
82        map<unsigned long, int> colors ;
83        map<unsigned long, int> leaders ;
84        map<unsigned long, int>::iterator it ;
85
86        // (1) Establish client leaders, distribute processes between two server levels
87        std::vector<int> srvRanks;
88        for(i=0,c=0;i<size;i++)
89        {
90          if (colors.find(hashAll[i])==colors.end())
91          {
92            colors[hashAll[i]]=c ;
93            leaders[hashAll[i]]=i ;
94            c++ ;
95          }
96          if (CXios::usingServer2)
97            if (hashAll[i] == hashServer)
98              srvRanks.push_back(i);
99        }
100
101        if (CXios::usingServer2)
102        {
103          int reqNbProc = srvRanks.size()*CXios::ratioServer2/100.;
104          if (reqNbProc<1 || reqNbProc==srvRanks.size())
105          {
106            error(0)<<"WARNING: void CServer::initialize(void)"<<endl
107                << "It is impossible to dedicate the requested number of processes = "<<reqNbProc
108                <<" to secondary server. XIOS will run in the classical server mode."<<endl;
109          }
110          else
111          {
112            if (CXios::nbPoolsServer2 == 0) CXios::nbPoolsServer2 = reqNbProc;
113            int firstSndSrvRank = srvRanks.size()*(100.-CXios::ratioServer2)/100. ;
114            int poolLeader = firstSndSrvRank;
115//*********** (1) Comment out the line below to set one process per pool
116            sndServerGlobalRanks.push_back(srvRanks[poolLeader]);
117            int nbPools = CXios::nbPoolsServer2;
118            if ( nbPools > reqNbProc || nbPools < 1)
119            {
120              error(0)<<"WARNING: void CServer::initialize(void)"<<endl
121                  << "It is impossible to allocate the requested number of pools = "<<nbPools
122                  <<" on the secondary server. It will be set so that there is one process per pool."<<endl;
123              nbPools = reqNbProc;
124            }
125            int remainder = ((int) (srvRanks.size()*CXios::ratioServer2/100.)) % nbPools;
126            int procsPerPool = ((int) (srvRanks.size()*CXios::ratioServer2/100.)) / nbPools;
127            for (i=0; i<srvRanks.size(); i++)
128            {
129              if (i >= firstSndSrvRank)
130              {
131                if (rank_ == srvRanks[i])
132                {
133                  serverLevel=2;
134                }
135                poolLeader += procsPerPool;
136                if (remainder != 0)
137                {
138                  ++poolLeader;
139                  --remainder;
140                }
141//*********** (2) Comment out the two lines below to set one process per pool
142                if (poolLeader < srvRanks.size())
143                  sndServerGlobalRanks.push_back(srvRanks[poolLeader]);
144//*********** (3) Uncomment the line below to set one process per pool
145//                sndServerGlobalRanks.push_back(srvRanks[i]);
146              }
147              else
148              {
149                if (rank_ == srvRanks[i]) serverLevel=1;
150              }
151            }
152            if (serverLevel==2)
153            {
154              info(50)<<"The number of secondary server pools is "<< sndServerGlobalRanks.size() <<endl ;
155              for (i=0; i<sndServerGlobalRanks.size(); i++)
156              {
157                if (rank_>= sndServerGlobalRanks[i])
158                {
159                  if ( i == sndServerGlobalRanks.size()-1)
160                  {
161                    myColor = colors.size() + sndServerGlobalRanks[i];
162                  }
163                  else if (rank_< sndServerGlobalRanks[i+1])
164                  {
165                    myColor = colors.size() + sndServerGlobalRanks[i];
166                    break;
167                  }
168                }
169              }
170            }
171          }
172        }
173
174        // (2) Create intraComm
175        if (serverLevel != 2) myColor=colors[hashServer];
176        MPI_Comm_split(CXios::globalComm, myColor, rank_, &intraComm) ;
177
178        // (3) Create interComm
179        if (serverLevel == 0)
180        {
181          int clientLeader;
182          for(it=leaders.begin();it!=leaders.end();it++)
183          {
184            if (it->first!=hashServer)
185            {
186              clientLeader=it->second ;
187              int intraCommSize, intraCommRank ;
188              MPI_Comm_size(intraComm,&intraCommSize) ;
189              MPI_Comm_rank(intraComm,&intraCommRank) ;
190              info(50)<<"intercommCreate::server (classical mode) "<<rank_<<" intraCommSize : "<<intraCommSize
191                       <<" intraCommRank :"<<intraCommRank<<"  clientLeader "<< clientLeader<<endl ;
192
193              MPI_Intercomm_create(intraComm, 0, CXios::globalComm, clientLeader, 0, &newComm) ;
194              interCommLeft.push_back(newComm) ;
195            }
196          }
197        }
198        else if (serverLevel == 1)
199        {
200          int clientLeader, srvSndLeader;
201          int srvPrmLeader ;
202
203          for (it=leaders.begin();it!=leaders.end();it++)
204          {
205            if (it->first != hashServer)
206            {
207              clientLeader=it->second ;
208              int intraCommSize, intraCommRank ;
209              MPI_Comm_size(intraComm, &intraCommSize) ;
210              MPI_Comm_rank(intraComm, &intraCommRank) ;
211              info(50)<<"intercommCreate::server (server level 1) "<<rank_<<" intraCommSize : "<<intraCommSize
212                       <<" intraCommRank :"<<intraCommRank<<"  clientLeader "<< clientLeader<<endl ;
213              MPI_Intercomm_create(intraComm, 0, CXios::globalComm, clientLeader, 0, &newComm) ;
214              interCommLeft.push_back(newComm) ;
215            }
216          }
217
218          for (int i = 0; i < sndServerGlobalRanks.size(); ++i)
219          {
220            int intraCommSize, intraCommRank ;
221            MPI_Comm_size(intraComm, &intraCommSize) ;
222            MPI_Comm_rank(intraComm, &intraCommRank) ;
223            info(50)<<"intercommCreate::client (server level 1) "<<rank_<<" intraCommSize : "<<intraCommSize
224                <<" intraCommRank :"<<intraCommRank<<"  clientLeader "<< sndServerGlobalRanks[i]<<endl ;
225            MPI_Intercomm_create(intraComm, 0, CXios::globalComm, sndServerGlobalRanks[i], 1, &newComm) ;
226            interCommRight.push_back(newComm) ;
227          }
228        }
229        else
230        {
231          int clientLeader;
232          clientLeader = leaders[hashString(CXios::xiosCodeId)];
233          int intraCommSize, intraCommRank ;
234          MPI_Comm_size(intraComm, &intraCommSize) ;
235          MPI_Comm_rank(intraComm, &intraCommRank) ;
236          info(50)<<"intercommCreate::server (server level 2) "<<rank_<<" intraCommSize : "<<intraCommSize
237                   <<" intraCommRank :"<<intraCommRank<<"  clientLeader "<< clientLeader<<endl ;
238
239          MPI_Intercomm_create(intraComm, 0, CXios::globalComm, clientLeader, 1, &newComm) ;
240          interCommLeft.push_back(newComm) ;
241        }
242
243        delete [] hashAll ;
244
245      }
246      // using OASIS
247      else
248      {
249        int size;
250        int myColor;
251        int* srvGlobalRanks;
252        if (!is_MPI_Initialized) oasis_init(CXios::xiosCodeId);
253
254        CTimer::get("XIOS").resume() ;
255        MPI_Comm localComm;
256        oasis_get_localcomm(localComm);
257        MPI_Comm_rank(localComm,&rank_) ;
258
259//      (1) Create server intraComm
260        if (!CXios::usingServer2)
261        {
262          MPI_Comm_dup(localComm, &intraComm);
263        }
264        else
265        {
266          int globalRank;
267          MPI_Comm_size(localComm,&size) ;
268          MPI_Comm_rank(CXios::globalComm,&globalRank) ;
269          srvGlobalRanks = new int[size] ;
270          MPI_Allgather(&globalRank, 1, MPI_INT, srvGlobalRanks, 1, MPI_INT, localComm) ;
271
272          int reqNbProc = size*CXios::ratioServer2/100.;
273          if (reqNbProc < 1 || reqNbProc == size)
274          {
275            error(0)<<"WARNING: void CServer::initialize(void)"<<endl
276                << "It is impossible to dedicate the requested number of processes = "<<reqNbProc
277                <<" to secondary server. XIOS will run in the classical server mode."<<endl;
278            MPI_Comm_dup(localComm, &intraComm);
279          }
280          else
281          {
282            int firstSndSrvRank = size*(100.-CXios::ratioServer2)/100. ;
283            int poolLeader = firstSndSrvRank;
284//*********** (1) Comment out the line below to set one process per pool
285//            sndServerGlobalRanks.push_back(srvGlobalRanks[poolLeader]);
286            int nbPools = CXios::nbPoolsServer2;
287            if ( nbPools > reqNbProc || nbPools < 1)
288            {
289              error(0)<<"WARNING: void CServer::initialize(void)"<<endl
290                  << "It is impossible to allocate the requested number of pools = "<<nbPools
291                  <<" on the secondary server. It will be set so that there is one process per pool."<<endl;
292              nbPools = reqNbProc;
293            }
294            int remainder = ((int) (size*CXios::ratioServer2/100.)) % nbPools;
295            int procsPerPool = ((int) (size*CXios::ratioServer2/100.)) / nbPools;
296            for (int i=0; i<size; i++)
297            {
298              if (i >= firstSndSrvRank)
299              {
300                if (globalRank == srvGlobalRanks[i])
301                {
302                  serverLevel=2;
303                }
304                poolLeader += procsPerPool;
305                if (remainder != 0)
306                {
307                  ++poolLeader;
308                  --remainder;
309                }
310//*********** (2) Comment out the two lines below to set one process per pool
311//                if (poolLeader < size)
312//                  sndServerGlobalRanks.push_back(srvGlobalRanks[poolLeader]);
313//*********** (3) Uncomment the line below to set one process per pool
314                sndServerGlobalRanks.push_back(srvGlobalRanks[i]);
315              }
316              else
317              {
318                if (globalRank == srvGlobalRanks[i]) serverLevel=1;
319              }
320            }
321            if (serverLevel==2)
322            {
323              info(50)<<"The number of secondary server pools is "<< sndServerGlobalRanks.size() <<endl ;
324              for (int i=0; i<sndServerGlobalRanks.size(); i++)
325              {
326                if (globalRank>= sndServerGlobalRanks[i])
327                {
328                  if (i == sndServerGlobalRanks.size()-1)
329                  {
330                    myColor = sndServerGlobalRanks[i];
331                  }
332                  else if (globalRank< sndServerGlobalRanks[i+1])
333                  {
334                    myColor = sndServerGlobalRanks[i];
335                    break;
336                  }
337                }
338              }
339            }
340            if (serverLevel != 2) myColor=0;
341            MPI_Comm_split(localComm, myColor, rank_, &intraComm) ;
342          }
343        }
344
345        string codesId=CXios::getin<string>("oasis_codes_id") ;
346        vector<string> oasisCodeId=splitRegex(codesId,"\\s*,\\s*") ;
347 
348        vector<string>::iterator it ;
349
350        MPI_Comm newComm ;
351        int globalRank ;
352        MPI_Comm_rank(CXios::globalComm,&globalRank);
353
354// (1.5) check ensemble management
355        vector<string> baseOasisCodeId(oasisCodeId.size()) ;
356        vector<int> ensembleSize(oasisCodeId.size()) ;
357        vector<bool> ensembleManagement(oasisCodeId.size()) ;
358       
359        for(int i=0 ; i<oasisCodeId.size() ;i++)
360        {
361          vector<string> splittedOasisCodeId = splitRegex(oasisCodeId[i],"\\s*:\\s*") ;
362          baseOasisCodeId[i]=splittedOasisCodeId[0] ;
363          if (splittedOasisCodeId.size()==1) 
364          {
365            ensembleManagement[i]=false ;
366            ensembleSize[i]=1 ;
367          }
368          else if (splittedOasisCodeId.size()==2)
369          {
370           
371            try
372            { 
373              ensembleSize[i] = stoi(splittedOasisCodeId[1]) ;
374            }
375            catch(...) 
376            { 
377              ERROR("void CServer::initialize(void)",<<"OasisCodeId is badly formed "<<oasisCodeId[i]) ;
378            }
379           
380            ensembleManagement[i] = true ;
381          }
382          else ERROR("void CServer::initialize(void)",<<"OasisCodeId is badly formed "<<oasisCodeId[i]) ;
383        }
384
385//      (2) Create interComms with models
386        for(int i=0; i<baseOasisCodeId.size();i++)
387        {
388          if (ensembleManagement[i]==false) oasis_get_intercomm(newComm,baseOasisCodeId[i]) ;
389          else
390          {
391            vector<string> intraCommStr(ensembleSize[i]+1) ;
392            vector<int>    rootRanks ;
393            for(int j=0;j<ensembleSize[i];j++) intraCommStr[j]=baseOasisCodeId[i]+":"+std::to_string(j) ;
394            intraCommStr[ensembleSize[i]] = CXios::xiosCodeId ;
395            oasis_get_multi_intracomm(localComm, intraCommStr, rootRanks) ;
396   
397            int myColor= 1 ; // 0:client 1:server
398            int myrank ;
399            MPI_Comm splittedComm ;
400            MPI_Comm_rank(localComm,&myrank) ;
401            MPI_Comm_split(localComm,myColor,myrank, &splittedComm) ;
402            MPI_Intercomm_create(splittedComm,0,localComm,rootRanks[0],10,&newComm) ;
403          }
404         
405          if ( serverLevel == 0 || serverLevel == 1)
406          {
407            interCommLeft.push_back(newComm) ;
408            if (rank_==0) MPI_Send(&globalRank,1,MPI_INT,0,0,newComm) ;
409          }
410        }
411
412//      (3) Create interComms between primary and secondary servers
413        int intraCommSize, intraCommRank ;
414        MPI_Comm_size(intraComm,&intraCommSize) ;
415        MPI_Comm_rank(intraComm, &intraCommRank) ;
416
417        if (serverLevel == 1)
418        {
419          for (int i = 0; i < sndServerGlobalRanks.size(); ++i)
420          {
421            int srvSndLeader = sndServerGlobalRanks[i];
422            info(50)<<"intercommCreate::client (server level 1) "<<globalRank<<" intraCommSize : "<<intraCommSize
423                <<" intraCommRank :"<<intraCommRank<<"  clientLeader "<< srvSndLeader<<endl ;
424            MPI_Intercomm_create(intraComm, 0, CXios::globalComm, srvSndLeader, 0, &newComm) ;
425            interCommRight.push_back(newComm) ;
426          }
427        }
428        else if (serverLevel == 2)
429        {
430          info(50)<<"intercommCreate::server (server level 2)"<<globalRank<<" intraCommSize : "<<intraCommSize
431                   <<" intraCommRank :"<<intraCommRank<<"  clientLeader "<< srvGlobalRanks[0] <<endl ;
432          MPI_Intercomm_create(intraComm, 0, CXios::globalComm, srvGlobalRanks[0], 0, &newComm) ;
433          interCommLeft.push_back(newComm) ;
434        }
435        if (CXios::usingServer2) delete [] srvGlobalRanks ;
436
437        bool oasisEnddef=CXios::getin<bool>("call_oasis_enddef",true) ;
438        if (!oasisEnddef) oasis_enddef() ;
439      }
440
441
442      MPI_Comm_rank(intraComm, &rank) ;
443      if (rank==0) isRoot=true;
444      else isRoot=false;
445     
446      eventScheduler = new CEventScheduler(intraComm) ;
447    }
448
449    void CServer::finalize(void)
450    {
451      CTimer::get("XIOS").suspend() ;
452     
453      delete eventScheduler ;
454
455      for (std::list<MPI_Comm>::iterator it = contextInterComms.begin(); it != contextInterComms.end(); it++)
456        MPI_Comm_free(&(*it));
457
458      for (std::list<MPI_Comm>::iterator it = contextIntraComms.begin(); it != contextIntraComms.end(); it++)
459        MPI_Comm_free(&(*it));
460
461//      for (std::list<MPI_Comm>::iterator it = interComm.begin(); it != interComm.end(); it++)
462//        MPI_Comm_free(&(*it));
463
464//        for (std::list<MPI_Comm>::iterator it = interCommLeft.begin(); it != interCommLeft.end(); it++)
465//          MPI_Comm_free(&(*it));
466
467        for (std::list<MPI_Comm>::iterator it = interCommRight.begin(); it != interCommRight.end(); it++)
468          MPI_Comm_free(&(*it));
469
470      MPI_Comm_free(&intraComm);
471
472      if (!is_MPI_Initialized)
473      {
474        if (CXios::usingOasis) oasis_finalize();
475        else MPI_Finalize() ;
476      }
477      report(0)<<"Performance report : Time spent for XIOS : "<<CTimer::get("XIOS server").getCumulatedTime()<<endl  ;
478      report(0)<<"Performance report : Time spent in processing events : "<<CTimer::get("Process events").getCumulatedTime()<<endl  ;
479      report(0)<<"Performance report : Ratio : "<<CTimer::get("Process events").getCumulatedTime()/CTimer::get("XIOS server").getCumulatedTime()*100.<<"%"<<endl  ;
480      report(100)<<CTimer::getAllCumulatedTime()<<endl ;
481    }
482
483     void CServer::eventLoop(void)
484     {
485       bool stop=false ;
486
487       CTimer::get("XIOS server").resume() ;
488       while(!stop)
489       {
490         if (isRoot)
491         {
492           listenContext();
493           listenRootContext();
494           listenOasisEnddef() ;
495           listenRootOasisEnddef() ;
496           if (!finished) listenFinalize() ;
497         }
498         else
499         {
500           listenRootContext();
501           listenRootOasisEnddef() ;
502           if (!finished) listenRootFinalize() ;
503         }
504
505         contextEventLoop() ;
506         if (finished && contextList.empty()) stop=true ;
507         eventScheduler->checkEvent() ;
508       }
509       CTimer::get("XIOS server").suspend() ;
510     }
511
512     void CServer::listenFinalize(void)
513     {
514        list<MPI_Comm>::iterator it, itr;
515        int msg ;
516        int flag ;
517
518        for(it=interCommLeft.begin();it!=interCommLeft.end();it++)
519        {
520           MPI_Status status ;
521           traceOff() ;
522           MPI_Iprobe(0,0,*it,&flag,&status) ;
523           traceOn() ;
524           if (flag==true)
525           {
526              MPI_Recv(&msg,1,MPI_INT,0,0,*it,&status) ;
527              info(20)<<" CServer : Receive client finalize"<<endl ;
528              // Sending server finalize message to secondary servers (if any)
529              for(itr=interCommRight.begin();itr!=interCommRight.end();itr++)
530              {
531                MPI_Send(&msg,1,MPI_INT,0,0,*itr) ;
532              }
533              MPI_Comm_free(&(*it));
534              interCommLeft.erase(it) ;
535              break ;
536            }
537         }
538
539         if (interCommLeft.empty())
540         {
541           int i,size ;
542           MPI_Comm_size(intraComm,&size) ;
543           MPI_Request* requests= new MPI_Request[size-1] ;
544           MPI_Status* status= new MPI_Status[size-1] ;
545
546           for(int i=1;i<size;i++) MPI_Isend(&msg,1,MPI_INT,i,4,intraComm,&requests[i-1]) ;
547           MPI_Waitall(size-1,requests,status) ;
548
549           finished=true ;
550           delete [] requests ;
551           delete [] status ;
552         }
553     }
554
555
556     void CServer::listenRootFinalize()
557     {
558        int flag ;
559        MPI_Status status ;
560        int msg ;
561
562        traceOff() ;
563        MPI_Iprobe(0,4,intraComm, &flag, &status) ;
564        traceOn() ;
565        if (flag==true)
566        {
567           MPI_Recv(&msg,1,MPI_INT,0,4,intraComm,&status) ;
568           finished=true ;
569        }
570      }
571
572
573   /*!
574    * Root process is listening for an order sent by client to call "oasis_enddef".
575    * The root client of a compound send the order (tag 5). It is probed and received.
576    * When the order has been received from each coumpound, the server root process ping the order to the root processes of the secondary levels of servers (if any).
577    * After, it also inform (asynchronous call) other processes of the communicator that the oasis_enddef call must be done
578    */
579   
580     void CServer::listenOasisEnddef(void)
581     {
582        int flag ;
583        MPI_Status status ;
584        list<MPI_Comm>::iterator it;
585        int msg ;
586        static int nbCompound=0 ;
587        int size ;
588        static bool sent=false ;
589        static MPI_Request* allRequests ;
590        static MPI_Status* allStatus ;
591
592
593        if (sent)
594        {
595          MPI_Comm_size(intraComm,&size) ;
596          MPI_Testall(size,allRequests, &flag, allStatus) ;
597          if (flag==true)
598          {
599            delete [] allRequests ;
600            delete [] allStatus ;
601            sent=false ;
602          }
603        }
604       
605
606        for(it=interCommLeft.begin();it!=interCommLeft.end();it++)
607        {
608           MPI_Status status ;
609           traceOff() ;
610           MPI_Iprobe(0,5,*it,&flag,&status) ;  // tags oasis_endded = 5
611           traceOn() ;
612           if (flag==true)
613           {
614              MPI_Recv(&msg,1,MPI_INT,0,5,*it,&status) ; // tags oasis_endded = 5
615              nbCompound++ ;
616              if (nbCompound==interCommLeft.size())
617              {
618                for (std::list<MPI_Comm>::iterator it = interCommRight.begin(); it != interCommRight.end(); it++)
619                {
620                   MPI_Send(&msg,1,MPI_INT,0,5,*it) ; // tags oasis_endded = 5
621                }
622                MPI_Comm_size(intraComm,&size) ;
623                allRequests= new MPI_Request[size] ;
624                allStatus= new MPI_Status[size] ;
625                for(int i=0;i<size;i++) MPI_Isend(&msg,1,MPI_INT,i,5,intraComm,&allRequests[i]) ; // tags oasis_endded = 5
626                sent=true ;
627              }
628           }
629        }
630     }
631     
632   /*!
633    * Processes probes message from root process if oasis_enddef call must be done.
634    * When the order is received it is scheduled to be treated in a synchronized way by all server processes of the communicator
635    */
636     void CServer::listenRootOasisEnddef(void)
637     {
638       int flag ;
639       MPI_Status status ;
640       const int root=0 ;
641       int msg ;
642       static bool eventSent=false ;
643
644       if (eventSent)
645       {
646         boost::hash<string> hashString;
647         size_t hashId = hashString("oasis_enddef");
648         if (eventScheduler->queryEvent(0,hashId))
649         {
650           oasis_enddef() ;
651           eventSent=false ;
652         }
653       }
654         
655       traceOff() ;
656       MPI_Iprobe(root,5,intraComm, &flag, &status) ;
657       traceOn() ;
658       if (flag==true)
659       {
660         MPI_Recv(&msg,1,MPI_INT,root,5,intraComm,&status) ; // tags oasis_endded = 5
661         boost::hash<string> hashString;
662         size_t hashId = hashString("oasis_enddef");
663         eventScheduler->registerEvent(0,hashId);
664         eventSent=true ;
665       }
666     }
667
668
669
670     
671
672     void CServer::listenContext(void)
673     {
674
675       MPI_Status status ;
676       int flag ;
677       static char* buffer ;
678       static MPI_Request request ;
679       static bool recept=false ;
680       int rank ;
681       int count ;
682
683       if (recept==false)
684       {
685         traceOff() ;
686         MPI_Iprobe(MPI_ANY_SOURCE,1,CXios::globalComm, &flag, &status) ;
687         traceOn() ;
688         if (flag==true)
689         {
690           rank=status.MPI_SOURCE ;
691           MPI_Get_count(&status,MPI_CHAR,&count) ;
692           buffer=new char[count] ;
693           MPI_Irecv((void*)buffer,count,MPI_CHAR,rank,1,CXios::globalComm,&request) ;
694           recept=true ;
695         }
696       }
697       else
698       {
699         traceOff() ;
700         MPI_Test(&request,&flag,&status) ;
701         traceOn() ;
702         if (flag==true)
703         {
704           rank=status.MPI_SOURCE ;
705           MPI_Get_count(&status,MPI_CHAR,&count) ;
706           recvContextMessage((void*)buffer,count) ;
707           delete [] buffer ;
708           recept=false ;
709         }
710       }
711     }
712
713     void CServer::recvContextMessage(void* buff,int count)
714     {
715       static map<string,contextMessage> recvContextId;
716       map<string,contextMessage>::iterator it ;
717       CBufferIn buffer(buff,count) ;
718       string id ;
719       int clientLeader ;
720       int nbMessage ;
721
722       buffer>>id>>nbMessage>>clientLeader ;
723
724       it=recvContextId.find(id) ;
725       if (it==recvContextId.end())
726       {
727         contextMessage msg={0,0} ;
728         pair<map<string,contextMessage>::iterator,bool> ret ;
729         ret=recvContextId.insert(pair<string,contextMessage>(id,msg)) ;
730         it=ret.first ;
731       }
732       it->second.nbRecv+=1 ;
733       it->second.leaderRank+=clientLeader ;
734
735       if (it->second.nbRecv==nbMessage)
736       {
737         int size ;
738         MPI_Comm_size(intraComm,&size) ;
739//         MPI_Request* requests= new MPI_Request[size-1] ;
740//         MPI_Status* status= new MPI_Status[size-1] ;
741         MPI_Request* requests= new MPI_Request[size] ;
742         MPI_Status* status= new MPI_Status[size] ;
743
744         CMessage msg ;
745         msg<<id<<it->second.leaderRank;
746         int messageSize=msg.size() ;
747         void * sendBuff = new char[messageSize] ;
748         CBufferOut sendBuffer(sendBuff,messageSize) ;
749         sendBuffer<<msg ;
750
751         // Include root itself in order not to have a divergence
752         for(int i=0; i<size; i++)
753         {
754           MPI_Isend(sendBuff,sendBuffer.count(),MPI_CHAR,i,2,intraComm,&requests[i]) ;
755         }
756
757         recvContextId.erase(it) ;
758         delete [] requests ;
759         delete [] status ;
760
761       }
762     }
763
764     void CServer::listenRootContext(void)
765     {
766       MPI_Status status ;
767       int flag ;
768       static std::vector<void*> buffers;
769       static std::vector<MPI_Request> requests ;
770       static std::vector<int> counts ;
771       static std::vector<bool> isEventRegistered ;
772       static std::vector<bool> isEventQueued ;
773       MPI_Request request;
774
775       int rank ;
776       const int root=0 ;
777       boost::hash<string> hashString;
778       size_t hashId = hashString("RegisterContext");
779
780       // (1) Receive context id from the root, save it into a buffer
781       traceOff() ;
782       MPI_Iprobe(root,2,intraComm, &flag, &status) ;
783       traceOn() ;
784       if (flag==true)
785       {
786         counts.push_back(0);
787         MPI_Get_count(&status,MPI_CHAR,&(counts.back())) ;
788         buffers.push_back(new char[counts.back()]) ;
789         requests.push_back(request);
790         MPI_Irecv((void*)(buffers.back()),counts.back(),MPI_CHAR,root,2,intraComm,&(requests.back())) ;
791         isEventRegistered.push_back(false);
792         isEventQueued.push_back(false);
793         nbContexts++;
794       }
795
796       for (int ctxNb = 0; ctxNb < nbContexts; ctxNb++ )
797       {
798         // (2) If context id is received, register an event
799         MPI_Test(&requests[ctxNb],&flag,&status) ;
800         if (flag==true && !isEventRegistered[ctxNb])
801         {
802           eventScheduler->registerEvent(ctxNb,hashId);
803           isEventRegistered[ctxNb] = true;
804         }
805         // (3) If event has been scheduled, call register context
806         if (eventScheduler->queryEvent(ctxNb,hashId) && !isEventQueued[ctxNb])
807         {
808           registerContext(buffers[ctxNb],counts[ctxNb]) ;
809           isEventQueued[ctxNb] = true;
810           delete [] buffers[ctxNb] ;
811         }
812       }
813
814     }
815
816     void CServer::registerContext(void* buff, int count, int leaderRank)
817     {
818       string contextId;
819       CBufferIn buffer(buff, count);
820//       buffer >> contextId;
821       buffer >> contextId>>leaderRank;
822       CContext* context;
823
824       info(20) << "CServer : Register new Context : " << contextId << endl;
825
826       if (contextList.find(contextId) != contextList.end())
827         ERROR("void CServer::registerContext(void* buff, int count, int leaderRank)",
828               << "Context '" << contextId << "' has already been registred");
829
830       context=CContext::create(contextId);
831       contextList[contextId]=context;
832
833       // Primary or classical server: create communication channel with a client
834       // (1) create interComm (with a client)
835       // (2) initialize client and server (contextClient and contextServer)
836       MPI_Comm inter;
837       if (serverLevel < 2)
838       {
839         MPI_Comm contextInterComm;
840         MPI_Intercomm_create(intraComm, 0, CXios::globalComm, leaderRank, 10+leaderRank, &contextInterComm);
841         MPI_Intercomm_merge(contextInterComm,1,&inter);
842         MPI_Barrier(inter);
843         MPI_Comm_free(&inter);
844         context->initServer(intraComm,contextInterComm);
845         contextInterComms.push_back(contextInterComm);
846
847       }
848       // Secondary server: create communication channel with a primary server
849       // (1) duplicate interComm with a primary server
850       // (2) initialize client and server (contextClient and contextServer)
851       // Remark: in the case of the secondary server there is no need to create an interComm calling MPI_Intercomm_create,
852       //         because interComm of CContext is defined on the same processes as the interComm of CServer.
853       //         So just duplicate it.
854       else if (serverLevel == 2)
855       {
856         MPI_Comm_dup(interCommLeft.front(), &inter);
857         contextInterComms.push_back(inter);
858         context->initServer(intraComm, contextInterComms.back());
859       }
860
861       // Primary server:
862       // (1) send create context message to secondary servers
863       // (2) initialize communication channels with secondary servers (create contextClient and contextServer)
864       if (serverLevel == 1)
865       {
866         int i = 0, size;
867         MPI_Comm_size(intraComm, &size) ;
868         for (std::list<MPI_Comm>::iterator it = interCommRight.begin(); it != interCommRight.end(); it++, ++i)
869         {
870           StdString str = contextId +"_server_" + boost::lexical_cast<string>(i);
871           CMessage msg;
872           int messageSize;
873           msg<<str<<size<<rank_ ;
874           messageSize = msg.size() ;
875           buff = new char[messageSize] ;
876           CBufferOut buffer(buff,messageSize) ;
877           buffer<<msg ;
878           MPI_Send(buff, buffer.count(), MPI_CHAR, sndServerGlobalRanks[i], 1, CXios::globalComm) ;
879           MPI_Comm_dup(*it, &inter);
880           contextInterComms.push_back(inter);
881           MPI_Comm_dup(intraComm, &inter);
882           contextIntraComms.push_back(inter);
883           context->initClient(contextIntraComms.back(), contextInterComms.back()) ;
884           delete [] buff ;
885         }
886       }
887     }
888
889     void CServer::contextEventLoop(bool enableEventsProcessing /*= true*/)
890     {
891       bool isFinalized ;
892       map<string,CContext*>::iterator it ;
893
894       for(it=contextList.begin();it!=contextList.end();it++)
895       {
896         isFinalized=it->second->isFinalized();
897         if (isFinalized)
898         {
899           contextList.erase(it) ;
900           break ;
901         }
902         else
903           it->second->checkBuffersAndListen(enableEventsProcessing);
904       }
905     }
906
907     //! Get rank of the current process in the intraComm
908     int CServer::getRank()
909     {
910       int rank;
911       MPI_Comm_rank(intraComm,&rank);
912       return rank;
913     }
914
915     vector<int>& CServer::getSecondaryServerGlobalRanks()
916     {
917       return sndServerGlobalRanks;
918     }
919
920    /*!
921    * Open a file specified by a suffix and an extension and use it for the given file buffer.
922    * The file name will be suffix+rank+extension.
923    *
924    * \param fileName[in] protype file name
925    * \param ext [in] extension of the file
926    * \param fb [in/out] the file buffer
927    */
928    void CServer::openStream(const StdString& fileName, const StdString& ext, std::filebuf* fb)
929    {
930      StdStringStream fileNameClient;
931      int numDigit = 0;
932      int size = 0;
933      int id;
934      MPI_Comm_size(CXios::globalComm, &size);
935      while (size)
936      {
937        size /= 10;
938        ++numDigit;
939      }
940      id = rank_; //getRank();
941
942      fileNameClient << fileName << "_" << std::setfill('0') << std::setw(numDigit) << id << ext;
943      fb->open(fileNameClient.str().c_str(), std::ios::out);
944      if (!fb->is_open())
945        ERROR("void CServer::openStream(const StdString& fileName, const StdString& ext, std::filebuf* fb)",
946              << std::endl << "Can not open <" << fileNameClient.str() << "> file to write the server log(s).");
947    }
948
949    /*!
950    * \brief Open a file stream to write the info logs
951    * Open a file stream with a specific file name suffix+rank
952    * to write the info logs.
953    * \param fileName [in] protype file name
954    */
955    void CServer::openInfoStream(const StdString& fileName)
956    {
957      std::filebuf* fb = m_infoStream.rdbuf();
958      openStream(fileName, ".out", fb);
959
960      info.write2File(fb);
961      report.write2File(fb);
962    }
963
964    //! Write the info logs to standard output
965    void CServer::openInfoStream()
966    {
967      info.write2StdOut();
968      report.write2StdOut();
969    }
970
971    //! Close the info logs file if it opens
972    void CServer::closeInfoStream()
973    {
974      if (m_infoStream.is_open()) m_infoStream.close();
975    }
976
977    /*!
978    * \brief Open a file stream to write the error log
979    * Open a file stream with a specific file name suffix+rank
980    * to write the error log.
981    * \param fileName [in] protype file name
982    */
983    void CServer::openErrorStream(const StdString& fileName)
984    {
985      std::filebuf* fb = m_errorStream.rdbuf();
986      openStream(fileName, ".err", fb);
987
988      error.write2File(fb);
989    }
990
991    //! Write the error log to standard error output
992    void CServer::openErrorStream()
993    {
994      error.write2StdErr();
995    }
996
997    //! Close the error log file if it opens
998    void CServer::closeErrorStream()
999    {
1000      if (m_errorStream.is_open()) m_errorStream.close();
1001    }
1002}
Note: See TracBrowser for help on using the repository browser.