source: XIOS/dev/dev_trunk_omp/src/server.cpp @ 1661

Last change on this file since 1661 was 1661, checked in by yushan, 5 years ago

MARK: branch merged with trunk @1660. Test (test_complete, test_remap) on ADA with IntelMPI and _usingEP/_usingMPI as switch.

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