source: XIOS2/trunk/src/server.cpp @ 2428

Last change on this file since 2428 was 2428, checked in by jderouillat, 17 months ago

Backport the XIOS3 system to log the memory consumption (commit ID [2418-2420,2425-2426])

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