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

Last change on this file since 2520 was 2503, checked in by jderouillat, 15 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
RevLine 
[490]1#include "globalScopeData.hpp"
[591]2#include "xios_spl.hpp"
[300]3#include "cxios.hpp"
[342]4#include "server.hpp"
[983]5#include "client.hpp"
[300]6#include "type.hpp"
7#include "context.hpp"
[352]8#include "object_template.hpp"
[300]9#include "oasis_cinterface.hpp"
10#include <boost/functional/hash.hpp>
11#include <boost/algorithm/string.hpp>
[382]12#include "mpi.hpp"
[347]13#include "tracer.hpp"
14#include "timer.hpp"
[2428]15#include "mem_checker.hpp"
[492]16#include "event_scheduler.hpp"
[1587]17#include "string_tools.hpp"
[300]18
[335]19namespace xios
[490]20{
[1639]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;
[1021]26    int CServer::serverLevel = 0 ;
[1148]27    int CServer::nbContexts = 0;
[983]28    bool CServer::isRoot = false ;
[1077]29    int CServer::rank_ = INVALID_RANK;
[490]30    StdOFStream CServer::m_infoStream;
[523]31    StdOFStream CServer::m_errorStream;
[490]32    map<string,CContext*> CServer::contextList ;
[1152]33    vector<int> CServer::sndServerGlobalRanks;
[300]34    bool CServer::finished=false ;
35    bool CServer::is_MPI_Initialized ;
[597]36    CEventScheduler* CServer::eventScheduler = 0;
[983]37
38//---------------------------------------------------------------
39/*!
40 * \fn void CServer::initialize(void)
[1054]41 * Creates intraComm for each possible type of servers (classical, primary or secondary).
[1148]42 * Creates interComm and stores them into the following lists:
[1054]43 *   classical server -- interCommLeft
44 *   primary server -- interCommLeft and interCommRight
[1148]45 *   secondary server -- interCommLeft for each pool.
[1234]46 *   IMPORTANT: CXios::usingServer2 should NOT be used beyond this function. Use CServer::serverLevel instead.
[983]47 */
[300]48    void CServer::initialize(void)
49    {
50      int initialized ;
[1639]51      MPI_Initialized(&initialized) ;
[300]52      if (initialized) is_MPI_Initialized=true ;
53      else is_MPI_Initialized=false ;
[1152]54      int rank ;
[490]55
[300]56      // Not using OASIS
57      if (!CXios::usingOasis)
58      {
[490]59
60        if (!is_MPI_Initialized)
[300]61        {
[1639]62          MPI_Init(NULL, NULL);
[300]63        }
[359]64        CTimer::get("XIOS").resume() ;
[490]65
66        boost::hash<string> hashString ;
[1021]67        unsigned long hashServer = hashString(CXios::xiosCodeId);
[490]68
[300]69        unsigned long* hashAll ;
[1152]70        unsigned long* srvLevelAll ;
[490]71
[300]72        int size ;
73        int myColor ;
74        int i,c ;
[1639]75        MPI_Comm newComm;
[490]76
[1639]77        MPI_Comm_size(CXios::globalComm, &size) ;
78        MPI_Comm_rank(CXios::globalComm, &rank_);
[1009]79
[300]80        hashAll=new unsigned long[size] ;
[1639]81        MPI_Allgather(&hashServer, 1, MPI_LONG, hashAll, 1, MPI_LONG, CXios::globalComm) ;
[490]82
[1021]83        map<unsigned long, int> colors ;
[300]84        map<unsigned long, int> leaders ;
85        map<unsigned long, int>::iterator it ;
[490]86
[1152]87        // (1) Establish client leaders, distribute processes between two server levels
[1234]88        std::vector<int> srvRanks;
[300]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          }
[1152]97          if (CXios::usingServer2)
[1180]98            if (hashAll[i] == hashServer)
99              srvRanks.push_back(i);
100        }
[1234]101
102        if (CXios::usingServer2)
[1180]103        {
[1234]104          int reqNbProc = srvRanks.size()*CXios::ratioServer2/100.;
105          if (reqNbProc<1 || reqNbProc==srvRanks.size())
[1152]106          {
[1234]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;
[1152]110          }
[1180]111          else
112          {
[1519]113            if (CXios::nbPoolsServer2 == 0) CXios::nbPoolsServer2 = reqNbProc;
[1243]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
[1519]117            sndServerGlobalRanks.push_back(srvRanks[poolLeader]);
[1243]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;
[1234]128            for (i=0; i<srvRanks.size(); i++)
129            {
[1243]130              if (i >= firstSndSrvRank)
[1234]131              {
[1243]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
[1519]143                if (poolLeader < srvRanks.size())
144                  sndServerGlobalRanks.push_back(srvRanks[poolLeader]);
[1243]145//*********** (3) Uncomment the line below to set one process per pool
[1519]146//                sndServerGlobalRanks.push_back(srvRanks[i]);
[1234]147              }
148              else
149              {
150                if (rank_ == srvRanks[i]) serverLevel=1;
151              }
152            }
[1243]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            }
[1180]172          }
[300]173        }
[1243]174
[1152]175        // (2) Create intraComm
[1243]176        if (serverLevel != 2) myColor=colors[hashServer];
[1639]177        MPI_Comm_split(CXios::globalComm, myColor, rank_, &intraComm) ;
[1152]178
179        // (3) Create interComm
[1021]180        if (serverLevel == 0)
[983]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 ;
[1639]189              MPI_Comm_size(intraComm,&intraCommSize) ;
190              MPI_Comm_rank(intraComm,&intraCommRank) ;
[1142]191              info(50)<<"intercommCreate::server (classical mode) "<<rank_<<" intraCommSize : "<<intraCommSize
[983]192                       <<" intraCommRank :"<<intraCommRank<<"  clientLeader "<< clientLeader<<endl ;
[490]193
[1639]194              MPI_Intercomm_create(intraComm, 0, CXios::globalComm, clientLeader, 0, &newComm) ;
[1180]195              interCommLeft.push_back(newComm) ;
[983]196            }
197          }
198        }
[1021]199        else if (serverLevel == 1)
[983]200        {
[1054]201          int clientLeader, srvSndLeader;
202          int srvPrmLeader ;
[1152]203
[1021]204          for (it=leaders.begin();it!=leaders.end();it++)
[983]205          {
[1021]206            if (it->first != hashServer)
[983]207            {
[1021]208              clientLeader=it->second ;
209              int intraCommSize, intraCommRank ;
[1639]210              MPI_Comm_size(intraComm, &intraCommSize) ;
211              MPI_Comm_rank(intraComm, &intraCommRank) ;
[1142]212              info(50)<<"intercommCreate::server (server level 1) "<<rank_<<" intraCommSize : "<<intraCommSize
[1021]213                       <<" intraCommRank :"<<intraCommRank<<"  clientLeader "<< clientLeader<<endl ;
[1639]214              MPI_Intercomm_create(intraComm, 0, CXios::globalComm, clientLeader, 0, &newComm) ;
[1021]215              interCommLeft.push_back(newComm) ;
[983]216            }
[1021]217          }
[1009]218
[1152]219          for (int i = 0; i < sndServerGlobalRanks.size(); ++i)
[983]220          {
[1054]221            int intraCommSize, intraCommRank ;
[1639]222            MPI_Comm_size(intraComm, &intraCommSize) ;
223            MPI_Comm_rank(intraComm, &intraCommRank) ;
[1142]224            info(50)<<"intercommCreate::client (server level 1) "<<rank_<<" intraCommSize : "<<intraCommSize
[1152]225                <<" intraCommRank :"<<intraCommRank<<"  clientLeader "<< sndServerGlobalRanks[i]<<endl ;
[1639]226            MPI_Intercomm_create(intraComm, 0, CXios::globalComm, sndServerGlobalRanks[i], 1, &newComm) ;
[1054]227            interCommRight.push_back(newComm) ;
[1021]228          }
[1168]229        }
[1021]230        else
231        {
232          int clientLeader;
233          clientLeader = leaders[hashString(CXios::xiosCodeId)];
234          int intraCommSize, intraCommRank ;
[1639]235          MPI_Comm_size(intraComm, &intraCommSize) ;
236          MPI_Comm_rank(intraComm, &intraCommRank) ;
[1142]237          info(50)<<"intercommCreate::server (server level 2) "<<rank_<<" intraCommSize : "<<intraCommSize
[1021]238                   <<" intraCommRank :"<<intraCommRank<<"  clientLeader "<< clientLeader<<endl ;
[983]239
[1639]240          MPI_Intercomm_create(intraComm, 0, CXios::globalComm, clientLeader, 1, &newComm) ;
[1021]241          interCommLeft.push_back(newComm) ;
[1168]242        }
[983]243
244        delete [] hashAll ;
245
[300]246      }
247      // using OASIS
248      else
249      {
[1152]250        int size;
[1130]251        int myColor;
[1234]252        int* srvGlobalRanks;
[490]253        if (!is_MPI_Initialized) oasis_init(CXios::xiosCodeId);
254
[359]255        CTimer::get("XIOS").resume() ;
[1639]256        MPI_Comm localComm;
[655]257        oasis_get_localcomm(localComm);
[1639]258        MPI_Comm_rank(localComm,&rank_) ;
[655]259
[1234]260//      (1) Create server intraComm
[1130]261        if (!CXios::usingServer2)
[1167]262        {
[1639]263          MPI_Comm_dup(localComm, &intraComm);
[1167]264        }
[1130]265        else
266        {
[1180]267          int globalRank;
[1639]268          MPI_Comm_size(localComm,&size) ;
269          MPI_Comm_rank(CXios::globalComm,&globalRank) ;
[1234]270          srvGlobalRanks = new int[size] ;
[1639]271          MPI_Allgather(&globalRank, 1, MPI_INT, srvGlobalRanks, 1, MPI_INT, localComm) ;
[1152]272
[1234]273          int reqNbProc = size*CXios::ratioServer2/100.;
274          if (reqNbProc < 1 || reqNbProc == size)
[1130]275          {
[1234]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;
[1639]279            MPI_Comm_dup(localComm, &intraComm);
[1130]280          }
281          else
282          {
[1243]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;
[1234]297            for (int i=0; i<size; i++)
298            {
[1243]299              if (i >= firstSndSrvRank)
[1234]300              {
[1243]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
[1234]315                sndServerGlobalRanks.push_back(srvGlobalRanks[i]);
316              }
317              else
318              {
319                if (globalRank == srvGlobalRanks[i]) serverLevel=1;
320              }
321            }
[1243]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;
[1639]342            MPI_Comm_split(localComm, myColor, rank_, &intraComm) ;
[1130]343          }
[1234]344        }
[1130]345
[300]346        string codesId=CXios::getin<string>("oasis_codes_id") ;
[1587]347        vector<string> oasisCodeId=splitRegex(codesId,"\\s*,\\s*") ;
348 
[300]349        vector<string>::iterator it ;
350
[1639]351        MPI_Comm newComm ;
[300]352        int globalRank ;
[1639]353        MPI_Comm_rank(CXios::globalComm,&globalRank);
[490]354
[1234]355//      (2) Create interComms with models
[1587]356        for(it=oasisCodeId.begin();it!=oasisCodeId.end();it++)
[300]357        {
358          oasis_get_intercomm(newComm,*it) ;
[1234]359          if ( serverLevel == 0 || serverLevel == 1)
[1150]360          {
[1130]361            interCommLeft.push_back(newComm) ;
[1639]362            if (rank_==0) MPI_Send(&globalRank,1,MPI_INT,0,0,newComm) ;
[1150]363          }
[1180]364        }
365
[1234]366//      (3) Create interComms between primary and secondary servers
[1243]367        int intraCommSize, intraCommRank ;
[1639]368        MPI_Comm_size(intraComm,&intraCommSize) ;
369        MPI_Comm_rank(intraComm, &intraCommRank) ;
[1243]370
[1180]371        if (serverLevel == 1)
372        {
373          for (int i = 0; i < sndServerGlobalRanks.size(); ++i)
[1130]374          {
[1180]375            int srvSndLeader = sndServerGlobalRanks[i];
[1243]376            info(50)<<"intercommCreate::client (server level 1) "<<globalRank<<" intraCommSize : "<<intraCommSize
377                <<" intraCommRank :"<<intraCommRank<<"  clientLeader "<< srvSndLeader<<endl ;
[1639]378            MPI_Intercomm_create(intraComm, 0, CXios::globalComm, srvSndLeader, 0, &newComm) ;
[1180]379            interCommRight.push_back(newComm) ;
[1130]380          }
[300]381        }
[1180]382        else if (serverLevel == 2)
383        {
[1244]384          info(50)<<"intercommCreate::server (server level 2)"<<globalRank<<" intraCommSize : "<<intraCommSize
[1243]385                   <<" intraCommRank :"<<intraCommRank<<"  clientLeader "<< srvGlobalRanks[0] <<endl ;
[1639]386          MPI_Intercomm_create(intraComm, 0, CXios::globalComm, srvGlobalRanks[0], 0, &newComm) ;
[1180]387          interCommLeft.push_back(newComm) ;
388        }
[1184]389        if (CXios::usingServer2) delete [] srvGlobalRanks ;
[1587]390
391        bool oasisEnddef=CXios::getin<bool>("call_oasis_enddef",true) ;
392        if (!oasisEnddef) oasis_enddef() ;
[300]393      }
[490]394
[1184]395
[1639]396      MPI_Comm_rank(intraComm, &rank) ;
[1152]397      if (rank==0) isRoot=true;
[490]398      else isRoot=false;
[492]399     
400      eventScheduler = new CEventScheduler(intraComm) ;
[300]401    }
[490]402
[300]403    void CServer::finalize(void)
404    {
[361]405      CTimer::get("XIOS").suspend() ;
[697]406     
[492]407      delete eventScheduler ;
[655]408
[1639]409      for (std::list<MPI_Comm>::iterator it = contextInterComms.begin(); it != contextInterComms.end(); it++)
[2029]410        /* MPI_Comm_free(&(*it)) */; // WARNING remove freeing communicator !! --> deadlock raised, to be checked
[983]411
[1639]412      for (std::list<MPI_Comm>::iterator it = contextIntraComms.begin(); it != contextIntraComms.end(); it++)
413        MPI_Comm_free(&(*it));
[1071]414
[992]415//      for (std::list<MPI_Comm>::iterator it = interComm.begin(); it != interComm.end(); it++)
416//        MPI_Comm_free(&(*it));
417
[1077]418//        for (std::list<MPI_Comm>::iterator it = interCommLeft.begin(); it != interCommLeft.end(); it++)
419//          MPI_Comm_free(&(*it));
[983]420
[1639]421        for (std::list<MPI_Comm>::iterator it = interCommRight.begin(); it != interCommRight.end(); it++)
[2029]422          /* MPI_Comm_free(&(*it)) */ ; // WARNING remove freeing communicator !! --> deadlock raised, to be checked
[992]423
[1639]424      MPI_Comm_free(&intraComm);
[655]425
[2428]426      CMemChecker::logMem( "CServer::finalize", true );
[300]427      if (!is_MPI_Initialized)
[490]428      {
[300]429        if (CXios::usingOasis) oasis_finalize();
[1639]430        else MPI_Finalize() ;
[300]431      }
[347]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  ;
[1158]435      report(100)<<CTimer::getAllCumulatedTime()<<endl ;
[2503]436      if (CXios::reportMemory)
437      {
438        report(100)<<CMemChecker::getAllCumulatedMem()<<endl ;
439      }
440
[300]441    }
[490]442
[300]443     void CServer::eventLoop(void)
444     {
445       bool stop=false ;
[490]446
[347]447       CTimer::get("XIOS server").resume() ;
[300]448       while(!stop)
449       {
450         if (isRoot)
451         {
452           listenContext();
[1148]453           listenRootContext();
[1587]454           listenOasisEnddef() ;
455           listenRootOasisEnddef() ;
[300]456           if (!finished) listenFinalize() ;
457         }
458         else
459         {
460           listenRootContext();
[1587]461           listenRootOasisEnddef() ;
[300]462           if (!finished) listenRootFinalize() ;
463         }
[490]464
[300]465         contextEventLoop() ;
466         if (finished && contextList.empty()) stop=true ;
[956]467         eventScheduler->checkEvent() ;
[300]468       }
[347]469       CTimer::get("XIOS server").suspend() ;
[300]470     }
[490]471
[300]472     void CServer::listenFinalize(void)
473     {
[1639]474        list<MPI_Comm>::iterator it, itr;
[300]475        int msg ;
476        int flag ;
[490]477
[992]478        for(it=interCommLeft.begin();it!=interCommLeft.end();it++)
[300]479        {
[1639]480           MPI_Status status ;
[347]481           traceOff() ;
[1639]482           MPI_Iprobe(0,0,*it,&flag,&status) ;
[347]483           traceOn() ;
[300]484           if (flag==true)
485           {
[1639]486              MPI_Recv(&msg,1,MPI_INT,0,0,*it,&status) ;
[1054]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              {
[1639]491                MPI_Send(&msg,1,MPI_INT,0,0,*itr) ;
[1054]492              }
[2029]493              /* MPI_Comm_free(&(*it)); */ // WARNING remove freeing communicator !! --> deadlock raised, to be checked
[992]494              interCommLeft.erase(it) ;
[300]495              break ;
496            }
497         }
[490]498
[1054]499         if (interCommLeft.empty())
[300]500         {
501           int i,size ;
[1639]502           MPI_Comm_size(intraComm,&size) ;
503           MPI_Request* requests= new MPI_Request[size-1] ;
504           MPI_Status* status= new MPI_Status[size-1] ;
[490]505
[1639]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) ;
[300]508
509           finished=true ;
510           delete [] requests ;
511           delete [] status ;
512         }
513     }
[490]514
515
[300]516     void CServer::listenRootFinalize()
517     {
518        int flag ;
[1639]519        MPI_Status status ;
[300]520        int msg ;
[490]521
[347]522        traceOff() ;
[1639]523        MPI_Iprobe(0,4,intraComm, &flag, &status) ;
[347]524        traceOn() ;
[300]525        if (flag==true)
526        {
[1639]527           MPI_Recv(&msg,1,MPI_INT,0,4,intraComm,&status) ;
[300]528           finished=true ;
529        }
530      }
[490]531
[1587]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 ;
[1639]543        MPI_Status status ;
544        list<MPI_Comm>::iterator it;
[1587]545        int msg ;
546        static int nbCompound=0 ;
547        int size ;
548        static bool sent=false ;
[1639]549        static MPI_Request* allRequests ;
550        static MPI_Status* allStatus ;
[1587]551
552
553        if (sent)
554        {
[1639]555          MPI_Comm_size(intraComm,&size) ;
556          MPI_Testall(size,allRequests, &flag, allStatus) ;
[1587]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        {
[1639]568           MPI_Status status ;
[1587]569           traceOff() ;
[1639]570           MPI_Iprobe(0,5,*it,&flag,&status) ;  // tags oasis_endded = 5
[1587]571           traceOn() ;
572           if (flag==true)
573           {
[1639]574              MPI_Recv(&msg,1,MPI_INT,0,5,*it,&status) ; // tags oasis_endded = 5
[1587]575              nbCompound++ ;
576              if (nbCompound==interCommLeft.size())
577              {
[1639]578                for (std::list<MPI_Comm>::iterator it = interCommRight.begin(); it != interCommRight.end(); it++)
[1587]579                {
[1639]580                   MPI_Send(&msg,1,MPI_INT,0,5,*it) ; // tags oasis_endded = 5
[1587]581                }
[1639]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
[1587]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 ;
[1639]599       MPI_Status status ;
[1587]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() ;
[1639]616       MPI_Iprobe(root,5,intraComm, &flag, &status) ;
[1587]617       traceOn() ;
618       if (flag==true)
619       {
[1639]620         MPI_Recv(&msg,1,MPI_INT,root,5,intraComm,&status) ; // tags oasis_endded = 5
[1587]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
[300]632     void CServer::listenContext(void)
633     {
[490]634
[1639]635       MPI_Status status ;
[300]636       int flag ;
[1158]637       static char* buffer ;
[1639]638       static MPI_Request request ;
[300]639       static bool recept=false ;
640       int rank ;
641       int count ;
[490]642
[300]643       if (recept==false)
644       {
[347]645         traceOff() ;
[1639]646         MPI_Iprobe(MPI_ANY_SOURCE,1,CXios::globalComm, &flag, &status) ;
[347]647         traceOn() ;
[490]648         if (flag==true)
[300]649         {
650           rank=status.MPI_SOURCE ;
[1639]651           MPI_Get_count(&status,MPI_CHAR,&count) ;
[300]652           buffer=new char[count] ;
[1639]653           MPI_Irecv((void*)buffer,count,MPI_CHAR,rank,1,CXios::globalComm,&request) ;
[490]654           recept=true ;
[300]655         }
656       }
657       else
658       {
[347]659         traceOff() ;
[1639]660         MPI_Test(&request,&flag,&status) ;
[347]661         traceOn() ;
[300]662         if (flag==true)
663         {
664           rank=status.MPI_SOURCE ;
[1639]665           MPI_Get_count(&status,MPI_CHAR,&count) ;
[1158]666           recvContextMessage((void*)buffer,count) ;
667           delete [] buffer ;
[490]668           recept=false ;
[300]669         }
670       }
671     }
[490]672
[300]673     void CServer::recvContextMessage(void* buff,int count)
674     {
[983]675       static map<string,contextMessage> recvContextId;
[300]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 ;
[490]683
[300]684       it=recvContextId.find(id) ;
685       if (it==recvContextId.end())
[490]686       {
[300]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 ;
[490]691       }
[300]692       it->second.nbRecv+=1 ;
693       it->second.leaderRank+=clientLeader ;
[490]694
[300]695       if (it->second.nbRecv==nbMessage)
[490]696       {
[300]697         int size ;
[1639]698         MPI_Comm_size(intraComm,&size) ;
[1148]699//         MPI_Request* requests= new MPI_Request[size-1] ;
700//         MPI_Status* status= new MPI_Status[size-1] ;
[1639]701         MPI_Request* requests= new MPI_Request[size] ;
702         MPI_Status* status= new MPI_Status[size] ;
[490]703
[1148]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++)
[300]713         {
[1639]714           MPI_Isend(sendBuff,sendBuffer.count(),MPI_CHAR,i,2,intraComm,&requests[i]) ;
[300]715         }
716
717         recvContextId.erase(it) ;
718         delete [] requests ;
719         delete [] status ;
720
721       }
[490]722     }
723
[300]724     void CServer::listenRootContext(void)
725     {
[1639]726       MPI_Status status ;
[300]727       int flag ;
[1270]728       static std::vector<void*> buffers;
[1639]729       static std::vector<MPI_Request> requests ;
[1270]730       static std::vector<int> counts ;
[1271]731       static std::vector<bool> isEventRegistered ;
[1323]732       static std::vector<bool> isEventQueued ;
[1639]733       MPI_Request request;
[1270]734
[300]735       int rank ;
736       const int root=0 ;
[1148]737       boost::hash<string> hashString;
738       size_t hashId = hashString("RegisterContext");
[490]739
[1270]740       // (1) Receive context id from the root, save it into a buffer
[1271]741       traceOff() ;
[1639]742       MPI_Iprobe(root,2,intraComm, &flag, &status) ;
[1271]743       traceOn() ;
744       if (flag==true)
[300]745       {
[1271]746         counts.push_back(0);
[1639]747         MPI_Get_count(&status,MPI_CHAR,&(counts.back())) ;
[1271]748         buffers.push_back(new char[counts.back()]) ;
749         requests.push_back(request);
[1639]750         MPI_Irecv((void*)(buffers.back()),counts.back(),MPI_CHAR,root,2,intraComm,&(requests.back())) ;
[1271]751         isEventRegistered.push_back(false);
[1323]752         isEventQueued.push_back(false);
[1271]753         nbContexts++;
[300]754       }
[1271]755
756       for (int ctxNb = 0; ctxNb < nbContexts; ctxNb++ )
[300]757       {
[1271]758         // (2) If context id is received, register an event
[1639]759         MPI_Test(&requests[ctxNb],&flag,&status) ;
[1271]760         if (flag==true && !isEventRegistered[ctxNb])
[300]761         {
[1271]762           eventScheduler->registerEvent(ctxNb,hashId);
763           isEventRegistered[ctxNb] = true;
[300]764         }
[1271]765         // (3) If event has been scheduled, call register context
[1323]766         if (eventScheduler->queryEvent(ctxNb,hashId) && !isEventQueued[ctxNb])
[1271]767         {
768           registerContext(buffers[ctxNb],counts[ctxNb]) ;
[1323]769           isEventQueued[ctxNb] = true;
[1271]770           delete [] buffers[ctxNb] ;
771         }
[300]772       }
[1271]773
[490]774     }
775
[655]776     void CServer::registerContext(void* buff, int count, int leaderRank)
[300]777     {
778       string contextId;
[655]779       CBufferIn buffer(buff, count);
[1148]780//       buffer >> contextId;
781       buffer >> contextId>>leaderRank;
[983]782       CContext* context;
[300]783
[680]784       info(20) << "CServer : Register new Context : " << contextId << endl;
[490]785
[680]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");
[490]789
[983]790       context=CContext::create(contextId);
[655]791       contextList[contextId]=context;
792
[1148]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)
[1639]796       MPI_Comm inter;
[1054]797       if (serverLevel < 2)
798       {
[1639]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);
[1054]804         context->initServer(intraComm,contextInterComm);
805         contextInterComms.push_back(contextInterComm);
[1071]806
[1054]807       }
[1148]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.
[1054]814       else if (serverLevel == 2)
815       {
[1639]816         MPI_Comm_dup(interCommLeft.front(), &inter);
[1071]817         contextInterComms.push_back(inter);
818         context->initServer(intraComm, contextInterComms.back());
[1054]819       }
820
[1148]821       // Primary server:
822       // (1) send create context message to secondary servers
823       // (2) initialize communication channels with secondary servers (create contextClient and contextServer)
[1021]824       if (serverLevel == 1)
[983]825       {
[1054]826         int i = 0, size;
[1639]827         MPI_Comm_size(intraComm, &size) ;
828         for (std::list<MPI_Comm>::iterator it = interCommRight.begin(); it != interCommRight.end(); it++, ++i)
[1054]829         {
830           StdString str = contextId +"_server_" + boost::lexical_cast<string>(i);
[1352]831           CMessage msg;
832           int messageSize;
[1077]833           msg<<str<<size<<rank_ ;
[1054]834           messageSize = msg.size() ;
835           buff = new char[messageSize] ;
836           CBufferOut buffer(buff,messageSize) ;
837           buffer<<msg ;
[1639]838           MPI_Send(buff, buffer.count(), MPI_CHAR, sndServerGlobalRanks[i], 1, CXios::globalComm) ;
839           MPI_Comm_dup(*it, &inter);
[1071]840           contextInterComms.push_back(inter);
[1639]841           MPI_Comm_dup(intraComm, &inter);
[1071]842           contextIntraComms.push_back(inter);
843           context->initClient(contextIntraComms.back(), contextInterComms.back()) ;
[1054]844           delete [] buff ;
845         }
[983]846       }
[490]847     }
848
[1377]849     void CServer::contextEventLoop(bool enableEventsProcessing /*= true*/)
[300]850     {
[1130]851       bool isFinalized ;
[300]852       map<string,CContext*>::iterator it ;
[983]853
[490]854       for(it=contextList.begin();it!=contextList.end();it++)
[300]855       {
[1130]856         isFinalized=it->second->isFinalized();
857         if (isFinalized)
[300]858         {
859           contextList.erase(it) ;
860           break ;
861         }
[1054]862         else
[1377]863           it->second->checkBuffersAndListen(enableEventsProcessing);
[300]864       }
865     }
[490]866
[1148]867     //! Get rank of the current process in the intraComm
[490]868     int CServer::getRank()
869     {
[1167]870       int rank;
[1639]871       MPI_Comm_rank(intraComm,&rank);
[1167]872       return rank;
[490]873     }
874
[1168]875     vector<int>& CServer::getSecondaryServerGlobalRanks()
876     {
877       return sndServerGlobalRanks;
878     }
879
[523]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;
[1021]893      int id;
[1639]894      MPI_Comm_size(CXios::globalComm, &size);
[523]895      while (size)
896      {
897        size /= 10;
898        ++numDigit;
899      }
[1167]900      id = rank_; //getRank();
[497]901
[1021]902      fileNameClient << fileName << "_" << std::setfill('0') << std::setw(numDigit) << id << ext;
[523]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)",
[1542]906              << std::endl << "Can not open <" << fileNameClient.str() << "> file to write the server log(s).");
[523]907    }
[490]908
[523]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);
[490]919
[523]920      info.write2File(fb);
921      report.write2File(fb);
922    }
[490]923
[523]924    //! Write the info logs to standard output
925    void CServer::openInfoStream()
926    {
927      info.write2StdOut();
928      report.write2StdOut();
929    }
[490]930
[523]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    }
[300]962}
Note: See TracBrowser for help on using the repository browser.