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

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

MARK: branch merged with trunk @1660. Add option --omp to enable multithreading.

  • 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           
669           #ifdef _usingEP
670           rank=status.ep_src;
671           #else
672           rank=status.MPI_SOURCE ;
673           #endif
674           MPI_Get_count(&status,MPI_CHAR,&count) ;
675           buffer=new char[count] ;
676           MPI_Irecv((void*)buffer,count,MPI_CHAR,rank,1,CXios::globalComm,&request) ;
677           recept=true ;
678         }
679       }
680       else
681       {
682         traceOff() ;
683         MPI_Test(&request,&flag,&status) ;
684         traceOn() ;
685         if (flag==true)
686         {
687           
688           #ifdef _usingEP
689           rank=status.ep_src;
690           #else
691           rank=status.MPI_SOURCE ;
692           #endif
693           MPI_Get_count(&status,MPI_CHAR,&count) ;
694           recvContextMessage((void*)buffer,count) ;
695           delete [] buffer ;
696           recept=false ;
697         }
698       }
699     }
700
701     void CServer::recvContextMessage(void* buff,int count)
702     {
703       static map<string,contextMessage> recvContextId;
704       map<string,contextMessage>::iterator it ;
705       CBufferIn buffer(buff,count) ;
706       string id ;
707       int clientLeader ;
708       int nbMessage ;
709
710       buffer>>id>>nbMessage>>clientLeader ;
711
712       it=recvContextId.find(id) ;
713       if (it==recvContextId.end())
714       {
715         contextMessage msg={0,0} ;
716         pair<map<string,contextMessage>::iterator,bool> ret ;
717         ret=recvContextId.insert(pair<string,contextMessage>(id,msg)) ;
718         it=ret.first ;
719       }
720       it->second.nbRecv+=1 ;
721       it->second.leaderRank+=clientLeader ;
722
723       if (it->second.nbRecv==nbMessage)
724       {
725         int size ;
726         MPI_Comm_size(intraComm,&size) ;
727//         MPI_Request* requests= new MPI_Request[size-1] ;
728//         MPI_Status* status= new MPI_Status[size-1] ;
729         MPI_Request* requests= new MPI_Request[size] ;
730         MPI_Status* status= new MPI_Status[size] ;
731
732         CMessage msg ;
733         msg<<id<<it->second.leaderRank;
734         int messageSize=msg.size() ;
735         void * sendBuff = new char[messageSize] ;
736         CBufferOut sendBuffer(sendBuff,messageSize) ;
737         sendBuffer<<msg ;
738
739         // Include root itself in order not to have a divergence
740         for(int i=0; i<size; i++)
741         {
742           MPI_Isend(sendBuff,sendBuffer.count(),MPI_CHAR,i,2,intraComm,&requests[i]) ;
743         }
744
745         recvContextId.erase(it) ;
746         delete [] requests ;
747         delete [] status ;
748
749       }
750     }
751
752     void CServer::listenRootContext(void)
753     {
754       MPI_Status status ;
755       int flag ;
756       static std::vector<void*> buffers;
757       static std::vector<MPI_Request> requests ;
758       static std::vector<int> counts ;
759       static std::vector<bool> isEventRegistered ;
760       static std::vector<bool> isEventQueued ;
761       MPI_Request request;
762
763       int rank ;
764       const int root=0 ;
765       boost::hash<string> hashString;
766       size_t hashId = hashString("RegisterContext");
767
768       // (1) Receive context id from the root, save it into a buffer
769       traceOff() ;
770       MPI_Iprobe(root,2,intraComm, &flag, &status) ;
771       traceOn() ;
772       if (flag==true)
773       {
774         counts.push_back(0);
775         MPI_Get_count(&status,MPI_CHAR,&(counts.back())) ;
776         buffers.push_back(new char[counts.back()]) ;
777         MPI_Irecv((void*)(buffers.back()),counts.back(),MPI_CHAR,root,2,intraComm,&request) ;
778         requests.push_back(request);
779         isEventRegistered.push_back(false);
780         isEventQueued.push_back(false);
781         nbContexts++;
782       }
783
784       for (int ctxNb = 0; ctxNb < nbContexts; ctxNb++ )
785       {
786         // (2) If context id is received, register an event
787         if(!isEventRegistered[ctxNb]) MPI_Test(&requests[ctxNb],&flag,&status) ;
788         if (flag==true && !isEventRegistered[ctxNb])
789         {
790           eventScheduler->registerEvent(ctxNb,hashId);
791           isEventRegistered[ctxNb] = true;
792         }
793         // (3) If event has been scheduled, call register context
794         if (eventScheduler->queryEvent(ctxNb,hashId) && !isEventQueued[ctxNb])
795         {
796           registerContext(buffers[ctxNb],counts[ctxNb]) ;
797           isEventQueued[ctxNb] = true;
798           delete [] buffers[ctxNb] ;
799         }
800       }
801
802     }
803
804     void CServer::registerContext(void* buff, int count, int leaderRank)
805     {
806       string contextId;
807       CBufferIn buffer(buff, count);
808//       buffer >> contextId;
809       buffer >> contextId>>leaderRank;
810       CContext* context;
811
812       #pragma omp critical (_output)
813       {
814         info(20) << "CServer : Register new Context : " << contextId << endl;
815       }
816
817       if (contextList.find(contextId) != contextList.end())
818         ERROR("void CServer::registerContext(void* buff, int count, int leaderRank)",
819               << "Context '" << contextId << "' has already been registred");
820
821       context=CContext::create(contextId);
822       contextList[contextId]=context;
823
824       // Primary or classical server: create communication channel with a client
825       // (1) create interComm (with a client)
826       // (2) initialize client and server (contextClient and contextServer)
827       MPI_Comm inter;
828       if (serverLevel < 2)
829       {
830         MPI_Comm contextInterComm;
831         MPI_Intercomm_create(intraComm, 0, CXios::globalComm, leaderRank, 10+leaderRank, &contextInterComm);
832         MPI_Intercomm_merge(contextInterComm,1,&inter);
833         MPI_Barrier(inter);
834         context->initServer(intraComm,contextInterComm);
835         contextInterComms.push_back(contextInterComm);
836
837         MPI_Comm_free(&inter);
838       }
839       // Secondary server: create communication channel with a primary server
840       // (1) duplicate interComm with a primary server
841       // (2) initialize client and server (contextClient and contextServer)
842       // Remark: in the case of the secondary server there is no need to create an interComm calling MPI_Intercomm_create,
843       //         because interComm of CContext is defined on the same processes as the interComm of CServer.
844       //         So just duplicate it.
845       else if (serverLevel == 2)
846       {
847         MPI_Comm_dup(interCommLeft.front(), &inter);
848         contextInterComms.push_back(inter);
849         context->initServer(intraComm, contextInterComms.back());
850       }
851
852       // Primary server:
853       // (1) send create context message to secondary servers
854       // (2) initialize communication channels with secondary servers (create contextClient and contextServer)
855       if (serverLevel == 1)
856       {
857         int i = 0, size;
858         MPI_Comm_size(intraComm, &size) ;
859         for (std::list<MPI_Comm>::iterator it = interCommRight.begin(); it != interCommRight.end(); it++, ++i)
860         {
861           StdString str = contextId +"_server_" + boost::lexical_cast<string>(i);
862           CMessage msg;
863           int messageSize;
864           msg<<str<<size<<rank_ ;
865           messageSize = msg.size() ;
866           buff = new char[messageSize] ;
867           CBufferOut buffer(buff,messageSize) ;
868           buffer<<msg ;
869           MPI_Send(buff, buffer.count(), MPI_CHAR, sndServerGlobalRanks[i], 1, CXios::globalComm) ;
870           MPI_Comm_dup(*it, &inter);
871           contextInterComms.push_back(inter);
872           MPI_Comm_dup(intraComm, &inter);
873           contextIntraComms.push_back(inter);
874           context->initClient(contextIntraComms.back(), contextInterComms.back()) ;
875           delete [] buff ;
876         }
877       }
878     }
879
880     void CServer::contextEventLoop(bool enableEventsProcessing /*= true*/)
881     {
882       bool isFinalized ;
883       map<string,CContext*>::iterator it ;
884
885       for(it=contextList.begin();it!=contextList.end();it++)
886       {
887         isFinalized=it->second->isFinalized();
888         if (isFinalized)
889         {
890           contextList.erase(it) ;
891           break ;
892         }
893         else
894           it->second->checkBuffersAndListen(enableEventsProcessing);
895       }
896     }
897
898     //! Get rank of the current process in the intraComm
899     int CServer::getRank()
900     {
901       int rank;
902       MPI_Comm_rank(intraComm,&rank);
903       return rank;
904     }
905
906     vector<int>& CServer::getSecondaryServerGlobalRanks()
907     {
908       return sndServerGlobalRanks;
909     }
910
911    /*!
912    * Open a file specified by a suffix and an extension and use it for the given file buffer.
913    * The file name will be suffix+rank+extension.
914    *
915    * \param fileName[in] protype file name
916    * \param ext [in] extension of the file
917    * \param fb [in/out] the file buffer
918    */
919    void CServer::openStream(const StdString& fileName, const StdString& ext, std::filebuf* fb)
920    {
921      StdStringStream fileNameClient;
922      int numDigit = 0;
923      int size = 0;
924      int id;
925      MPI_Comm_size(CXios::globalComm, &size);
926      while (size)
927      {
928        size /= 10;
929        ++numDigit;
930      }
931      id = rank_; //getRank();
932
933      fileNameClient << fileName << "_" << std::setfill('0') << std::setw(numDigit) << id << ext;
934      fb->open(fileNameClient.str().c_str(), std::ios::out);
935      if (!fb->is_open())
936        ERROR("void CServer::openStream(const StdString& fileName, const StdString& ext, std::filebuf* fb)",
937              << std::endl << "Can not open <" << fileNameClient.str() << "> file to write the server log(s).");
938    }
939
940    /*!
941    * \brief Open a file stream to write the info logs
942    * Open a file stream with a specific file name suffix+rank
943    * to write the info logs.
944    * \param fileName [in] protype file name
945    */
946    void CServer::openInfoStream(const StdString& fileName)
947    {
948      std::filebuf* fb = m_infoStream.rdbuf();
949      openStream(fileName, ".out", fb);
950
951      info.write2File(fb);
952      report.write2File(fb);
953    }
954
955    //! Write the info logs to standard output
956    void CServer::openInfoStream()
957    {
958      info.write2StdOut();
959      report.write2StdOut();
960    }
961
962    //! Close the info logs file if it opens
963    void CServer::closeInfoStream()
964    {
965      if (m_infoStream.is_open()) m_infoStream.close();
966    }
967
968    /*!
969    * \brief Open a file stream to write the error log
970    * Open a file stream with a specific file name suffix+rank
971    * to write the error log.
972    * \param fileName [in] protype file name
973    */
974    void CServer::openErrorStream(const StdString& fileName)
975    {
976      std::filebuf* fb = m_errorStream.rdbuf();
977      openStream(fileName, ".err", fb);
978
979      error.write2File(fb);
980    }
981
982    //! Write the error log to standard error output
983    void CServer::openErrorStream()
984    {
985      error.write2StdErr();
986    }
987
988    //! Close the error log file if it opens
989    void CServer::closeErrorStream()
990    {
991      if (m_errorStream.is_open()) m_errorStream.close();
992    }
993}
Note: See TracBrowser for help on using the repository browser.