source: XIOS2/trunk/src/server.cpp

Last change on this file was 2503, checked in by jderouillat, 14 months ago

Add an option called memory_report (in the xios context, default is true) to activate the memory reporting operated at each xios routine call from models

  • 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.8 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      if (CXios::reportMemory)
437      {
438        report(100)<<CMemChecker::getAllCumulatedMem()<<endl ;
439      }
440
441    }
442
443     void CServer::eventLoop(void)
444     {
445       bool stop=false ;
446
447       CTimer::get("XIOS server").resume() ;
448       while(!stop)
449       {
450         if (isRoot)
451         {
452           listenContext();
453           listenRootContext();
454           listenOasisEnddef() ;
455           listenRootOasisEnddef() ;
456           if (!finished) listenFinalize() ;
457         }
458         else
459         {
460           listenRootContext();
461           listenRootOasisEnddef() ;
462           if (!finished) listenRootFinalize() ;
463         }
464
465         contextEventLoop() ;
466         if (finished && contextList.empty()) stop=true ;
467         eventScheduler->checkEvent() ;
468       }
469       CTimer::get("XIOS server").suspend() ;
470     }
471
472     void CServer::listenFinalize(void)
473     {
474        list<MPI_Comm>::iterator it, itr;
475        int msg ;
476        int flag ;
477
478        for(it=interCommLeft.begin();it!=interCommLeft.end();it++)
479        {
480           MPI_Status status ;
481           traceOff() ;
482           MPI_Iprobe(0,0,*it,&flag,&status) ;
483           traceOn() ;
484           if (flag==true)
485           {
486              MPI_Recv(&msg,1,MPI_INT,0,0,*it,&status) ;
487              info(20)<<" CServer : Receive client finalize"<<endl ;
488              // Sending server finalize message to secondary servers (if any)
489              for(itr=interCommRight.begin();itr!=interCommRight.end();itr++)
490              {
491                MPI_Send(&msg,1,MPI_INT,0,0,*itr) ;
492              }
493              /* MPI_Comm_free(&(*it)); */ // WARNING remove freeing communicator !! --> deadlock raised, to be checked
494              interCommLeft.erase(it) ;
495              break ;
496            }
497         }
498
499         if (interCommLeft.empty())
500         {
501           int i,size ;
502           MPI_Comm_size(intraComm,&size) ;
503           MPI_Request* requests= new MPI_Request[size-1] ;
504           MPI_Status* status= new MPI_Status[size-1] ;
505
506           for(int i=1;i<size;i++) MPI_Isend(&msg,1,MPI_INT,i,4,intraComm,&requests[i-1]) ;
507           MPI_Waitall(size-1,requests,status) ;
508
509           finished=true ;
510           delete [] requests ;
511           delete [] status ;
512         }
513     }
514
515
516     void CServer::listenRootFinalize()
517     {
518        int flag ;
519        MPI_Status status ;
520        int msg ;
521
522        traceOff() ;
523        MPI_Iprobe(0,4,intraComm, &flag, &status) ;
524        traceOn() ;
525        if (flag==true)
526        {
527           MPI_Recv(&msg,1,MPI_INT,0,4,intraComm,&status) ;
528           finished=true ;
529        }
530      }
531
532
533   /*!
534    * Root process is listening for an order sent by client to call "oasis_enddef".
535    * The root client of a compound send the order (tag 5). It is probed and received.
536    * 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).
537    * After, it also inform (asynchronous call) other processes of the communicator that the oasis_enddef call must be done
538    */
539   
540     void CServer::listenOasisEnddef(void)
541     {
542        int flag ;
543        MPI_Status status ;
544        list<MPI_Comm>::iterator it;
545        int msg ;
546        static int nbCompound=0 ;
547        int size ;
548        static bool sent=false ;
549        static MPI_Request* allRequests ;
550        static MPI_Status* allStatus ;
551
552
553        if (sent)
554        {
555          MPI_Comm_size(intraComm,&size) ;
556          MPI_Testall(size,allRequests, &flag, allStatus) ;
557          if (flag==true)
558          {
559            delete [] allRequests ;
560            delete [] allStatus ;
561            sent=false ;
562          }
563        }
564       
565
566        for(it=interCommLeft.begin();it!=interCommLeft.end();it++)
567        {
568           MPI_Status status ;
569           traceOff() ;
570           MPI_Iprobe(0,5,*it,&flag,&status) ;  // tags oasis_endded = 5
571           traceOn() ;
572           if (flag==true)
573           {
574              MPI_Recv(&msg,1,MPI_INT,0,5,*it,&status) ; // tags oasis_endded = 5
575              nbCompound++ ;
576              if (nbCompound==interCommLeft.size())
577              {
578                for (std::list<MPI_Comm>::iterator it = interCommRight.begin(); it != interCommRight.end(); it++)
579                {
580                   MPI_Send(&msg,1,MPI_INT,0,5,*it) ; // tags oasis_endded = 5
581                }
582                MPI_Comm_size(intraComm,&size) ;
583                allRequests= new MPI_Request[size] ;
584                allStatus= new MPI_Status[size] ;
585                for(int i=0;i<size;i++) MPI_Isend(&msg,1,MPI_INT,i,5,intraComm,&allRequests[i]) ; // tags oasis_endded = 5
586                sent=true ;
587              }
588           }
589        }
590     }
591     
592   /*!
593    * Processes probes message from root process if oasis_enddef call must be done.
594    * When the order is received it is scheduled to be treated in a synchronized way by all server processes of the communicator
595    */
596     void CServer::listenRootOasisEnddef(void)
597     {
598       int flag ;
599       MPI_Status status ;
600       const int root=0 ;
601       int msg ;
602       static bool eventSent=false ;
603
604       if (eventSent)
605       {
606         boost::hash<string> hashString;
607         size_t hashId = hashString("oasis_enddef");
608         if (eventScheduler->queryEvent(0,hashId))
609         {
610           oasis_enddef() ;
611           eventSent=false ;
612         }
613       }
614         
615       traceOff() ;
616       MPI_Iprobe(root,5,intraComm, &flag, &status) ;
617       traceOn() ;
618       if (flag==true)
619       {
620         MPI_Recv(&msg,1,MPI_INT,root,5,intraComm,&status) ; // tags oasis_endded = 5
621         boost::hash<string> hashString;
622         size_t hashId = hashString("oasis_enddef");
623         eventScheduler->registerEvent(0,hashId);
624         eventSent=true ;
625       }
626     }
627
628
629
630     
631
632     void CServer::listenContext(void)
633     {
634
635       MPI_Status status ;
636       int flag ;
637       static char* buffer ;
638       static MPI_Request request ;
639       static bool recept=false ;
640       int rank ;
641       int count ;
642
643       if (recept==false)
644       {
645         traceOff() ;
646         MPI_Iprobe(MPI_ANY_SOURCE,1,CXios::globalComm, &flag, &status) ;
647         traceOn() ;
648         if (flag==true)
649         {
650           rank=status.MPI_SOURCE ;
651           MPI_Get_count(&status,MPI_CHAR,&count) ;
652           buffer=new char[count] ;
653           MPI_Irecv((void*)buffer,count,MPI_CHAR,rank,1,CXios::globalComm,&request) ;
654           recept=true ;
655         }
656       }
657       else
658       {
659         traceOff() ;
660         MPI_Test(&request,&flag,&status) ;
661         traceOn() ;
662         if (flag==true)
663         {
664           rank=status.MPI_SOURCE ;
665           MPI_Get_count(&status,MPI_CHAR,&count) ;
666           recvContextMessage((void*)buffer,count) ;
667           delete [] buffer ;
668           recept=false ;
669         }
670       }
671     }
672
673     void CServer::recvContextMessage(void* buff,int count)
674     {
675       static map<string,contextMessage> recvContextId;
676       map<string,contextMessage>::iterator it ;
677       CBufferIn buffer(buff,count) ;
678       string id ;
679       int clientLeader ;
680       int nbMessage ;
681
682       buffer>>id>>nbMessage>>clientLeader ;
683
684       it=recvContextId.find(id) ;
685       if (it==recvContextId.end())
686       {
687         contextMessage msg={0,0} ;
688         pair<map<string,contextMessage>::iterator,bool> ret ;
689         ret=recvContextId.insert(pair<string,contextMessage>(id,msg)) ;
690         it=ret.first ;
691       }
692       it->second.nbRecv+=1 ;
693       it->second.leaderRank+=clientLeader ;
694
695       if (it->second.nbRecv==nbMessage)
696       {
697         int size ;
698         MPI_Comm_size(intraComm,&size) ;
699//         MPI_Request* requests= new MPI_Request[size-1] ;
700//         MPI_Status* status= new MPI_Status[size-1] ;
701         MPI_Request* requests= new MPI_Request[size] ;
702         MPI_Status* status= new MPI_Status[size] ;
703
704         CMessage msg ;
705         msg<<id<<it->second.leaderRank;
706         int messageSize=msg.size() ;
707         void * sendBuff = new char[messageSize] ;
708         CBufferOut sendBuffer(sendBuff,messageSize) ;
709         sendBuffer<<msg ;
710
711         // Include root itself in order not to have a divergence
712         for(int i=0; i<size; i++)
713         {
714           MPI_Isend(sendBuff,sendBuffer.count(),MPI_CHAR,i,2,intraComm,&requests[i]) ;
715         }
716
717         recvContextId.erase(it) ;
718         delete [] requests ;
719         delete [] status ;
720
721       }
722     }
723
724     void CServer::listenRootContext(void)
725     {
726       MPI_Status status ;
727       int flag ;
728       static std::vector<void*> buffers;
729       static std::vector<MPI_Request> requests ;
730       static std::vector<int> counts ;
731       static std::vector<bool> isEventRegistered ;
732       static std::vector<bool> isEventQueued ;
733       MPI_Request request;
734
735       int rank ;
736       const int root=0 ;
737       boost::hash<string> hashString;
738       size_t hashId = hashString("RegisterContext");
739
740       // (1) Receive context id from the root, save it into a buffer
741       traceOff() ;
742       MPI_Iprobe(root,2,intraComm, &flag, &status) ;
743       traceOn() ;
744       if (flag==true)
745       {
746         counts.push_back(0);
747         MPI_Get_count(&status,MPI_CHAR,&(counts.back())) ;
748         buffers.push_back(new char[counts.back()]) ;
749         requests.push_back(request);
750         MPI_Irecv((void*)(buffers.back()),counts.back(),MPI_CHAR,root,2,intraComm,&(requests.back())) ;
751         isEventRegistered.push_back(false);
752         isEventQueued.push_back(false);
753         nbContexts++;
754       }
755
756       for (int ctxNb = 0; ctxNb < nbContexts; ctxNb++ )
757       {
758         // (2) If context id is received, register an event
759         MPI_Test(&requests[ctxNb],&flag,&status) ;
760         if (flag==true && !isEventRegistered[ctxNb])
761         {
762           eventScheduler->registerEvent(ctxNb,hashId);
763           isEventRegistered[ctxNb] = true;
764         }
765         // (3) If event has been scheduled, call register context
766         if (eventScheduler->queryEvent(ctxNb,hashId) && !isEventQueued[ctxNb])
767         {
768           registerContext(buffers[ctxNb],counts[ctxNb]) ;
769           isEventQueued[ctxNb] = true;
770           delete [] buffers[ctxNb] ;
771         }
772       }
773
774     }
775
776     void CServer::registerContext(void* buff, int count, int leaderRank)
777     {
778       string contextId;
779       CBufferIn buffer(buff, count);
780//       buffer >> contextId;
781       buffer >> contextId>>leaderRank;
782       CContext* context;
783
784       info(20) << "CServer : Register new Context : " << contextId << endl;
785
786       if (contextList.find(contextId) != contextList.end())
787         ERROR("void CServer::registerContext(void* buff, int count, int leaderRank)",
788               << "Context '" << contextId << "' has already been registred");
789
790       context=CContext::create(contextId);
791       contextList[contextId]=context;
792
793       // Primary or classical server: create communication channel with a client
794       // (1) create interComm (with a client)
795       // (2) initialize client and server (contextClient and contextServer)
796       MPI_Comm inter;
797       if (serverLevel < 2)
798       {
799         MPI_Comm contextInterComm;
800         MPI_Intercomm_create(intraComm, 0, CXios::globalComm, leaderRank, 10+leaderRank, &contextInterComm);
801         MPI_Intercomm_merge(contextInterComm,1,&inter);
802         MPI_Barrier(inter);
803         MPI_Comm_free(&inter);
804         context->initServer(intraComm,contextInterComm);
805         contextInterComms.push_back(contextInterComm);
806
807       }
808       // Secondary server: create communication channel with a primary server
809       // (1) duplicate interComm with a primary server
810       // (2) initialize client and server (contextClient and contextServer)
811       // Remark: in the case of the secondary server there is no need to create an interComm calling MPI_Intercomm_create,
812       //         because interComm of CContext is defined on the same processes as the interComm of CServer.
813       //         So just duplicate it.
814       else if (serverLevel == 2)
815       {
816         MPI_Comm_dup(interCommLeft.front(), &inter);
817         contextInterComms.push_back(inter);
818         context->initServer(intraComm, contextInterComms.back());
819       }
820
821       // Primary server:
822       // (1) send create context message to secondary servers
823       // (2) initialize communication channels with secondary servers (create contextClient and contextServer)
824       if (serverLevel == 1)
825       {
826         int i = 0, size;
827         MPI_Comm_size(intraComm, &size) ;
828         for (std::list<MPI_Comm>::iterator it = interCommRight.begin(); it != interCommRight.end(); it++, ++i)
829         {
830           StdString str = contextId +"_server_" + boost::lexical_cast<string>(i);
831           CMessage msg;
832           int messageSize;
833           msg<<str<<size<<rank_ ;
834           messageSize = msg.size() ;
835           buff = new char[messageSize] ;
836           CBufferOut buffer(buff,messageSize) ;
837           buffer<<msg ;
838           MPI_Send(buff, buffer.count(), MPI_CHAR, sndServerGlobalRanks[i], 1, CXios::globalComm) ;
839           MPI_Comm_dup(*it, &inter);
840           contextInterComms.push_back(inter);
841           MPI_Comm_dup(intraComm, &inter);
842           contextIntraComms.push_back(inter);
843           context->initClient(contextIntraComms.back(), contextInterComms.back()) ;
844           delete [] buff ;
845         }
846       }
847     }
848
849     void CServer::contextEventLoop(bool enableEventsProcessing /*= true*/)
850     {
851       bool isFinalized ;
852       map<string,CContext*>::iterator it ;
853
854       for(it=contextList.begin();it!=contextList.end();it++)
855       {
856         isFinalized=it->second->isFinalized();
857         if (isFinalized)
858         {
859           contextList.erase(it) ;
860           break ;
861         }
862         else
863           it->second->checkBuffersAndListen(enableEventsProcessing);
864       }
865     }
866
867     //! Get rank of the current process in the intraComm
868     int CServer::getRank()
869     {
870       int rank;
871       MPI_Comm_rank(intraComm,&rank);
872       return rank;
873     }
874
875     vector<int>& CServer::getSecondaryServerGlobalRanks()
876     {
877       return sndServerGlobalRanks;
878     }
879
880    /*!
881    * Open a file specified by a suffix and an extension and use it for the given file buffer.
882    * The file name will be suffix+rank+extension.
883    *
884    * \param fileName[in] protype file name
885    * \param ext [in] extension of the file
886    * \param fb [in/out] the file buffer
887    */
888    void CServer::openStream(const StdString& fileName, const StdString& ext, std::filebuf* fb)
889    {
890      StdStringStream fileNameClient;
891      int numDigit = 0;
892      int size = 0;
893      int id;
894      MPI_Comm_size(CXios::globalComm, &size);
895      while (size)
896      {
897        size /= 10;
898        ++numDigit;
899      }
900      id = rank_; //getRank();
901
902      fileNameClient << fileName << "_" << std::setfill('0') << std::setw(numDigit) << id << ext;
903      fb->open(fileNameClient.str().c_str(), std::ios::out);
904      if (!fb->is_open())
905        ERROR("void CServer::openStream(const StdString& fileName, const StdString& ext, std::filebuf* fb)",
906              << std::endl << "Can not open <" << fileNameClient.str() << "> file to write the server log(s).");
907    }
908
909    /*!
910    * \brief Open a file stream to write the info logs
911    * Open a file stream with a specific file name suffix+rank
912    * to write the info logs.
913    * \param fileName [in] protype file name
914    */
915    void CServer::openInfoStream(const StdString& fileName)
916    {
917      std::filebuf* fb = m_infoStream.rdbuf();
918      openStream(fileName, ".out", fb);
919
920      info.write2File(fb);
921      report.write2File(fb);
922    }
923
924    //! Write the info logs to standard output
925    void CServer::openInfoStream()
926    {
927      info.write2StdOut();
928      report.write2StdOut();
929    }
930
931    //! Close the info logs file if it opens
932    void CServer::closeInfoStream()
933    {
934      if (m_infoStream.is_open()) m_infoStream.close();
935    }
936
937    /*!
938    * \brief Open a file stream to write the error log
939    * Open a file stream with a specific file name suffix+rank
940    * to write the error log.
941    * \param fileName [in] protype file name
942    */
943    void CServer::openErrorStream(const StdString& fileName)
944    {
945      std::filebuf* fb = m_errorStream.rdbuf();
946      openStream(fileName, ".err", fb);
947
948      error.write2File(fb);
949    }
950
951    //! Write the error log to standard error output
952    void CServer::openErrorStream()
953    {
954      error.write2StdErr();
955    }
956
957    //! Close the error log file if it opens
958    void CServer::closeErrorStream()
959    {
960      if (m_errorStream.is_open()) m_errorStream.close();
961    }
962}
Note: See TracBrowser for help on using the repository browser.