source: XIOS/dev/dev_ym/XIOS_COUPLING/src/context_client.cpp @ 2291

Last change on this file since 2291 was 2287, checked in by jderouillat, 2 years ago

Fix for second level servers usage (nomenclature and recomment MPI_Win_free)

  • 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: 18.4 KB
RevLine 
[591]1#include "xios_spl.hpp"
[300]2#include "context_client.hpp"
3#include "context_server.hpp"
4#include "event_client.hpp"
5#include "buffer_out.hpp"
6#include "buffer_client.hpp"
7#include "type.hpp"
8#include "event_client.hpp"
9#include "context.hpp"
[382]10#include "mpi.hpp"
[347]11#include "timer.hpp"
[401]12#include "cxios.hpp"
[1130]13#include "server.hpp"
[2130]14#include "services.hpp"
15#include <boost/functional/hash.hpp>
16#include <random>
17#include <chrono>
[300]18
[335]19namespace xios
[300]20{
[512]21    /*!
22    \param [in] parent Pointer to context on client side
23    \param [in] intraComm_ communicator of group client
24    \param [in] interComm_ communicator of group server
[983]25    \cxtSer [in] cxtSer Pointer to context of server side. (It is only used in case of attached mode).
[512]26    */
[1639]27    CContextClient::CContextClient(CContext* parent, MPI_Comm intraComm_, MPI_Comm interComm_, CContext* cxtSer)
[1853]28     : mapBufferSize_(), parentServer(cxtSer), maxBufferedEvents(4), associatedServer_(nullptr)
[300]29    {
[1757]30     
[2130]31      context_ = parent;
[595]32      intraComm = intraComm_;
33      interComm = interComm_;
[1639]34      MPI_Comm_rank(intraComm, &clientRank);
35      MPI_Comm_size(intraComm, &clientSize);
[509]36
[595]37      int flag;
[1639]38      MPI_Comm_test_inter(interComm, &flag);
[1761]39      if (flag) isAttached_=false ;
40      else  isAttached_=true ;
41
42      pureOneSided=CXios::getin<bool>("pure_one_sided",false); // pure one sided communication (for test)
43      if (isAttachedModeEnabled()) pureOneSided=false ; // no one sided in attach mode
44     
45
46
[1639]47      if (flag) MPI_Comm_remote_size(interComm, &serverSize);
48      else  MPI_Comm_size(interComm, &serverSize);
[509]49
[1232]50      computeLeader(clientRank, clientSize, serverSize, ranksServerLeader, ranksServerNotLeader);
51
[2259]52      if (flag) MPI_Intercomm_merge(interComm_,false, &interCommMerged_) ;
[1757]53     
[2259]54      MPI_Comm_split(intraComm_,clientRank,clientRank, &commSelf_) ; // for windows
[2246]55
[2130]56      auto time=chrono::system_clock::now().time_since_epoch().count() ;
57      std::default_random_engine rd(time); // not reproducible from a run to another
58      std::uniform_int_distribution<size_t> dist;
59      hashId_=dist(rd) ;
60      MPI_Bcast(&hashId_,1,MPI_SIZE_T,0,intraComm) ; // Bcast to all server of the context
61
[1757]62      timeLine = 1;
[1232]63    }
64
65    void CContextClient::computeLeader(int clientRank, int clientSize, int serverSize,
66                                       std::list<int>& rankRecvLeader,
67                                       std::list<int>& rankRecvNotLeader)
68    {
69      if ((0 == clientSize) || (0 == serverSize)) return;
70
[595]71      if (clientSize < serverSize)
72      {
73        int serverByClient = serverSize / clientSize;
74        int remain = serverSize % clientSize;
75        int rankStart = serverByClient * clientRank;
[300]76
[595]77        if (clientRank < remain)
78        {
79          serverByClient++;
80          rankStart += clientRank;
81        }
82        else
83          rankStart += remain;
84
85        for (int i = 0; i < serverByClient; i++)
[1232]86          rankRecvLeader.push_back(rankStart + i);
[1021]87
[1232]88        rankRecvNotLeader.resize(0);
[1158]89      }
[595]90      else
91      {
92        int clientByServer = clientSize / serverSize;
93        int remain = clientSize % serverSize;
94
95        if (clientRank < (clientByServer + 1) * remain)
96        {
97          if (clientRank % (clientByServer + 1) == 0)
[1232]98            rankRecvLeader.push_back(clientRank / (clientByServer + 1));
[1021]99          else
[1232]100            rankRecvNotLeader.push_back(clientRank / (clientByServer + 1));
[595]101        }
102        else
103        {
104          int rank = clientRank - (clientByServer + 1) * remain;
105          if (rank % clientByServer == 0)
[1232]106            rankRecvLeader.push_back(remain + rank / clientByServer);
[1021]107          else
[1232]108            rankRecvNotLeader.push_back(remain + rank / clientByServer);
[595]109        }
110      }
[300]111    }
112
[512]113    /*!
114    In case of attached mode, the current context must be reset to context for client
115    \param [in] event Event sent to server
116    */
[300]117    void CContextClient::sendEvent(CEventClient& event)
118    {
[731]119      list<int> ranks = event.getRanks();
[2260]120 
121//      ostringstream str ;
122//      for(auto& rank : ranks) str<<rank<<" ; " ;
123//      info(100)<<"Event "<<timeLine<<" of context "<<context_->getId()<<"  for ranks : "<<str.str()<<endl ;
124
[1377]125      if (CXios::checkEventSync)
126      {
[2189]127        int typeId, classId, typeId_in, classId_in;
128        long long timeLine_out;
129        long long timeLine_in( timeLine );
[1377]130        typeId_in=event.getTypeId() ;
131        classId_in=event.getClassId() ;
[1475]132//        MPI_Allreduce(&timeLine,&timeLine_out, 1, MPI_UINT64_T, MPI_SUM, intraComm) ; // MPI_UINT64_T standardized by MPI 3
[2189]133        MPI_Allreduce(&timeLine_in,&timeLine_out, 1, MPI_LONG_LONG_INT, MPI_SUM, intraComm) ; 
[1639]134        MPI_Allreduce(&typeId_in,&typeId, 1, MPI_INT, MPI_SUM, intraComm) ;
135        MPI_Allreduce(&classId_in,&classId, 1, MPI_INT, MPI_SUM, intraComm) ;
[1377]136        if (typeId/clientSize!=event.getTypeId() || classId/clientSize!=event.getClassId() || timeLine_out/clientSize!=timeLine)
137        {
138           ERROR("void CContextClient::sendEvent(CEventClient& event)",
[2229]139               << "Event are not coherent between client for timeline = "<<timeLine);
[1377]140        }
[2229]141       
142        vector<int> servers(serverSize,0) ;
143        auto ranks=event.getRanks() ;
144        for(auto& rank : ranks) servers[rank]=1 ;
145        MPI_Allreduce(MPI_IN_PLACE, servers.data(), serverSize,MPI_INT,MPI_SUM,intraComm) ;
146        ostringstream osstr ;
147        for(int i=0;i<serverSize;i++)  if (servers[i]==0) osstr<<i<<" , " ;
148        if (!osstr.str().empty())
149        {
150          ERROR("void CContextClient::sendEvent(CEventClient& event)",
151                 <<" Some servers will not receive the message for timeline = "<<timeLine<<endl
152                 <<"Servers are : "<<osstr.str()) ;
153        }
154
155
[1377]156      }
157
[595]158      if (!event.isEmpty())
[300]159      {
[731]160        list<int> sizes = event.getSizes();
[300]161
[1757]162         // We force the getBuffers call to be non-blocking on classical servers
[1054]163        list<CBufferOut*> buffList;
[1757]164        getBuffers(timeLine, ranks, sizes, buffList) ;
[509]165
[1757]166        event.send(timeLine, sizes, buffList);
167       
168        //for (auto itRank = ranks.begin(); itRank != ranks.end(); itRank++) buffers[*itRank]->infoBuffer() ;
[731]169
[1757]170        unlockBuffers(ranks) ;
171        checkBuffers(ranks);
[2260]172       
[300]173      }
[1761]174     
175      if (isAttachedModeEnabled()) // couldBuffer is always true in attached mode
176      {
[2130]177        while (checkBuffers(ranks)) context_->globalEventLoop() ;
178     
179        CXios::getDaemonsManager()->scheduleContext(hashId_) ;
180        while (CXios::getDaemonsManager()->isScheduledContext(hashId_)) context_->globalEventLoop() ;
[1761]181      }
182     
[1054]183      timeLine++;
184    }
185
186    /*!
[512]187    If client is also server (attached mode), after sending event, it should process right away
188    the incoming event.
189    \param [in] ranks list rank of server connected this client
190    */
[300]191    void CContextClient::waitEvent(list<int>& ranks)
192    {
[1761]193      while (checkBuffers(ranks))
194      {
[2130]195        context_->eventLoop() ;
[1761]196      }
197
198      MPI_Request req ;
199      MPI_Status status ;
200
201      MPI_Ibarrier(intraComm,&req) ;
202      int flag=false ;
203
204      do 
205      {
206        CXios::getDaemonsManager()->eventLoop() ;
207        MPI_Test(&req,&flag,&status) ;
208      } while (!flag) ;
209
210
211    }
212
213
214    void CContextClient::waitEvent_old(list<int>& ranks)
215    {
[595]216      parentServer->server->setPendingEvent();
217      while (checkBuffers(ranks))
[300]218      {
[595]219        parentServer->server->listen();
220        parentServer->server->checkPendingRequest();
[300]221      }
[386]222
[595]223      while (parentServer->server->hasPendingEvent())
[386]224      {
[595]225       parentServer->server->eventLoop();
[386]226      }
[300]227    }
228
[512]229    /*!
[1054]230     * Get buffers for each connection to the servers. This function blocks until there is enough room in the buffers unless
231     * it is explicitly requested to be non-blocking.
232     *
[1757]233     *
234     * \param [in] timeLine time line of the event which will be sent to servers
[1054]235     * \param [in] serverList list of rank of connected server
236     * \param [in] sizeList size of message corresponding to each connection
237     * \param [out] retBuffers list of buffers that can be used to store an event
238     * \param [in] nonBlocking whether this function should be non-blocking
239     * \return whether the already allocated buffers could be used
[512]240    */
[1757]241    bool CContextClient::getBuffers(const size_t timeLine, const list<int>& serverList, const list<int>& sizeList, list<CBufferOut*>& retBuffers,
[1071]242                                    bool nonBlocking /*= false*/)
[300]243    {
[1054]244      list<int>::const_iterator itServer, itSize;
[595]245      list<CClientBuffer*> bufferList;
[1054]246      map<int,CClientBuffer*>::const_iterator it;
[595]247      list<CClientBuffer*>::iterator itBuffer;
[884]248      bool areBuffersFree;
[300]249
[595]250      for (itServer = serverList.begin(); itServer != serverList.end(); itServer++)
[300]251      {
[595]252        it = buffers.find(*itServer);
253        if (it == buffers.end())
[300]254        {
[595]255          newBuffer(*itServer);
256          it = buffers.find(*itServer);
[509]257        }
[595]258        bufferList.push_back(it->second);
[300]259      }
[347]260
[2246]261      double lastTimeBuffersNotFree=0. ;
262      double time ;
263      bool doUnlockBuffers ;
[347]264      CTimer::get("Blocking time").resume();
[884]265      do
[300]266      {
[884]267        areBuffersFree = true;
[2246]268        doUnlockBuffers=false ;
269        time=MPI_Wtime() ;
270        if (time-lastTimeBuffersNotFree > latency_)
[1757]271        {
[2246]272          for (itBuffer = bufferList.begin(), itSize = sizeList.begin(); itBuffer != bufferList.end(); itBuffer++, itSize++)
273          {
274            areBuffersFree &= (*itBuffer)->isBufferFree(*itSize);
275          }
276          if (!areBuffersFree)
277          {
278            lastTimeBuffersNotFree = time ;
279            doUnlockBuffers=true ;
280          }         
[1757]281        }
[2246]282        else areBuffersFree = false ;
[884]283
284        if (!areBuffersFree)
[300]285        {
[2246]286          if (doUnlockBuffers) for (itBuffer = bufferList.begin(); itBuffer != bufferList.end(); itBuffer++) (*itBuffer)->unlockBuffer();
[884]287          checkBuffers();
[1761]288
[2246]289          context_->globalEventLoop() ;
[2130]290        }
[1130]291
[1054]292      } while (!areBuffersFree && !nonBlocking);
[347]293      CTimer::get("Blocking time").suspend();
294
[1054]295      if (areBuffersFree)
[300]296      {
[1054]297        for (itBuffer = bufferList.begin(), itSize = sizeList.begin(); itBuffer != bufferList.end(); itBuffer++, itSize++)
[1757]298          retBuffers.push_back((*itBuffer)->getBuffer(timeLine, *itSize));
[300]299      }
[1054]300      return areBuffersFree;
[300]301   }
[509]302
[512]303   /*!
304   Make a new buffer for a certain connection to server with specific rank
305   \param [in] rank rank of connected server
306   */
[300]307   void CContextClient::newBuffer(int rank)
308   {
[1201]309      if (!mapBufferSize_.count(rank))
310      {
311        error(0) << "WARNING: Unexpected request for buffer to communicate with server " << rank << std::endl;
312        mapBufferSize_[rank] = CXios::minBufferSize;
313        maxEventSizes[rank] = CXios::minBufferSize;
314      }
[1757]315     
[2259]316      CClientBuffer* buffer = buffers[rank] = new CClientBuffer(interComm, rank, mapBufferSize_[rank], maxEventSizes[rank]);
[2130]317      if (isGrowableBuffer_) buffer->setGrowableBuffer(1.2) ;
318      else buffer->fixBuffer() ;
[1201]319      // Notify the server
[2130]320      CBufferOut* bufOut = buffer->getBuffer(0, 4*sizeof(MPI_Aint));
321      MPI_Aint sendBuff[4] ;
322      sendBuff[0]=hashId_;
323      sendBuff[1]=mapBufferSize_[rank];
324      sendBuff[2]=buffers[rank]->getWinAddress(0); 
325      sendBuff[3]=buffers[rank]->getWinAddress(1); 
[1757]326      info(100)<<"CContextClient::newBuffer : rank "<<rank<<" winAdress[0] "<<buffers[rank]->getWinAddress(0)<<" winAdress[1] "<<buffers[rank]->getWinAddress(1)<<endl;
[2130]327      bufOut->put(sendBuff, 4); 
[1757]328      buffer->checkBuffer(true);
[2259]329     
330       // create windows dynamically for one-sided
331      if (!isAttachedModeEnabled())
332      { 
333        CTimer::get("create Windows").resume() ;
334        MPI_Comm interComm ;
335        MPI_Intercomm_create(commSelf_, 0, interCommMerged_, clientSize+rank, 0, &interComm) ;
336        MPI_Intercomm_merge(interComm, false, &winComm_[rank]) ;
337        MPI_Comm_free(&interComm) ;
338        windows_[rank].resize(2) ;
339        MPI_Win_create_dynamic(MPI_INFO_NULL, winComm_[rank], &windows_[rank][0]);
340        MPI_Win_create_dynamic(MPI_INFO_NULL, winComm_[rank], &windows_[rank][1]);   
341        CTimer::get("create Windows").suspend() ;
342      }
343      else
344      {
345        winComm_[rank] = MPI_COMM_NULL ;
346        windows_[rank].resize(2) ;
347        windows_[rank][0] = MPI_WIN_NULL ;
348        windows_[rank][1] = MPI_WIN_NULL ;
349      }
350      buffer->attachWindows(windows_[rank]) ;
[2260]351      if (!isAttachedModeEnabled()) MPI_Barrier(winComm_[rank]) ;
352       
[509]353   }
[300]354
[512]355   /*!
356   Verify state of buffers. Buffer is under pending state if there is no message on it
357   \return state of buffers, pending(true), ready(false)
358   */
[300]359   bool CContextClient::checkBuffers(void)
360   {
[595]361      map<int,CClientBuffer*>::iterator itBuff;
362      bool pending = false;
[1130]363      for (itBuff = buffers.begin(); itBuff != buffers.end(); itBuff++)
[1757]364        pending |= itBuff->second->checkBuffer(!pureOneSided);
[595]365      return pending;
[509]366   }
[300]367
[512]368   //! Release all buffers
[1071]369   void CContextClient::releaseBuffers()
[300]370   {
[2276]371      map<int,CClientBuffer*>::iterator itBuff;
372      for (itBuff = buffers.begin(); itBuff != buffers.end(); itBuff++)
373      {
374         delete itBuff->second;
375      }
376      buffers.clear();
[1757]377
[2240]378// don't know when release windows
[1757]379
[2287]380      //if (!isAttachedModeEnabled())
381      //{ 
382      //  for(auto& it : winComm_)
383      //  {
384      //    int rank = it.first ;
385      //    MPI_Win_free(&windows_[rank][0]);
386      //    MPI_Win_free(&windows_[rank][1]);
387      //    MPI_Comm_free(&winComm_[rank]) ;
388      //  }
389      //}
[509]390   }
[1761]391
[1757]392     
393  /*!
394   Lock the buffers for one sided communications
395   \param [in] ranks list rank of server to which client connects to
396   */
397   void CContextClient::lockBuffers(list<int>& ranks)
398   {
399      list<int>::iterator it;
400      for (it = ranks.begin(); it != ranks.end(); it++) buffers[*it]->lockBuffer();
401   }
[300]402
[1757]403  /*!
404   Unlock the buffers for one sided communications
405   \param [in] ranks list rank of server to which client connects to
406   */
407   void CContextClient::unlockBuffers(list<int>& ranks)
408   {
409      list<int>::iterator it;
410      for (it = ranks.begin(); it != ranks.end(); it++) buffers[*it]->unlockBuffer();
411   }
412     
[512]413   /*!
414   Verify state of buffers corresponding to a connection
415   \param [in] ranks list rank of server to which client connects to
416   \return state of buffers, pending(true), ready(false)
417   */
[300]418   bool CContextClient::checkBuffers(list<int>& ranks)
419   {
[595]420      list<int>::iterator it;
421      bool pending = false;
[1757]422      for (it = ranks.begin(); it != ranks.end(); it++) pending |= buffers[*it]->checkBuffer(!pureOneSided);
[595]423      return pending;
[509]424   }
[300]425
[512]426   /*!
[917]427    * Set the buffer size for each connection. Warning: This function is collective.
428    *
429    * \param [in] mapSize maps the rank of the connected servers to the size of the correspoinding buffer
430    * \param [in] maxEventSize maps the rank of the connected servers to the size of the biggest event
[512]431   */
[2130]432   void CContextClient::setBufferSize(const std::map<int,StdSize>& mapSize)
[509]433   {
[2176]434     for(auto& it : mapSize) 
435      buffers[it.first]->fixBufferSize(std::max(CXios::minBufferSize*1.0,std::min(it.second*CXios::bufferSizeFactor*1.01,CXios::maxBufferSize*1.0)));
[509]436   }
437
[1158]438  /*!
439  Get leading server in the group of connected server
440  \return ranks of leading servers
441  */
442  const std::list<int>& CContextClient::getRanksServerNotLeader(void) const
443  {
444    return ranksServerNotLeader;
445  }
[1021]446
[1158]447  /*!
448  Check if client connects to leading server
449  \return connected(true), not connected (false)
450  */
451  bool CContextClient::isServerNotLeader(void) const
452  {
453    return !ranksServerNotLeader.empty();
454  }
[1021]455
[595]456  /*!
457  Get leading server in the group of connected server
458  \return ranks of leading servers
459  */
460  const std::list<int>& CContextClient::getRanksServerLeader(void) const
461  {
462    return ranksServerLeader;
463  }
[509]464
[595]465  /*!
466  Check if client connects to leading server
467  \return connected(true), not connected (false)
468  */
469  bool CContextClient::isServerLeader(void) const
470  {
471    return !ranksServerLeader.empty();
472  }
[300]473
[512]474   /*!
[1130]475   * Finalize context client and do some reports. Function is non-blocking.
[512]476   */
[1130]477  void CContextClient::finalize(void)
[1054]478  {
479    map<int,CClientBuffer*>::iterator itBuff;
[1757]480    std::list<int>::iterator ItServerLeader; 
481   
[1054]482    bool stop = false;
[731]483
[1757]484    int* nbServerConnectionLocal  = new int[serverSize] ;
485    int* nbServerConnectionGlobal  = new int[serverSize] ;
486    for(int i=0;i<serverSize;++i) nbServerConnectionLocal[i]=0 ;
487    for (itBuff = buffers.begin(); itBuff != buffers.end(); itBuff++)  nbServerConnectionLocal[itBuff->first]=1 ;
488    for (ItServerLeader = ranksServerLeader.begin(); ItServerLeader != ranksServerLeader.end(); ItServerLeader++)  nbServerConnectionLocal[*ItServerLeader]=1 ;
489   
490    MPI_Allreduce(nbServerConnectionLocal, nbServerConnectionGlobal, serverSize, MPI_INT, MPI_SUM, intraComm);
491   
492    CEventClient event(CContext::GetType(), CContext::EVENT_ID_CONTEXT_FINALIZE);
493    CMessage msg;
[509]494
[1757]495    for (int i=0;i<serverSize;++i) if (nbServerConnectionLocal[i]==1) event.push(i, nbServerConnectionGlobal[i], msg) ;
496    sendEvent(event);
497
498    delete[] nbServerConnectionLocal ;
499    delete[] nbServerConnectionGlobal ;
[509]500
[1765]501
[1054]502    CTimer::get("Blocking time").resume();
[1757]503    checkBuffers();
[1054]504    CTimer::get("Blocking time").suspend();
505
506    std::map<int,StdSize>::const_iterator itbMap = mapBufferSize_.begin(),
507                                          iteMap = mapBufferSize_.end(), itMap;
[1071]508
[1054]509    StdSize totalBuf = 0;
510    for (itMap = itbMap; itMap != iteMap; ++itMap)
511    {
[2130]512      report(10) << " Memory report : Context <" << context_->getId() << "> : client side : memory used for buffer of each connection to server" << endl
[1054]513                 << "  +) To server with rank " << itMap->first << " : " << itMap->second << " bytes " << endl;
514      totalBuf += itMap->second;
515    }
[2130]516    report(0) << " Memory report : Context <" << context_->getId() << "> : client side : total memory used for buffer " << totalBuf << " bytes" << endl;
[1054]517
518  }
[1130]519
[1139]520
521  /*!
522  */
[1130]523  bool CContextClient::havePendingRequests(void)
524  {
525    bool pending = false;
526    map<int,CClientBuffer*>::iterator itBuff;
527    for (itBuff = buffers.begin(); itBuff != buffers.end(); itBuff++)
528      pending |= itBuff->second->hasPendingRequest();
529    return pending;
530  }
[1757]531 
[2260]532  bool CContextClient::havePendingRequests(list<int>& ranks)
533  {
534      list<int>::iterator it;
535      bool pending = false;
536      for (it = ranks.begin(); it != ranks.end(); it++) pending |= buffers[*it]->hasPendingRequest();
537      return pending;
538  }
539
[1757]540  bool CContextClient::isNotifiedFinalized(void)
541  {
542    if (isAttachedModeEnabled()) return true ;
[1130]543
[1757]544    bool finalized = true;
545    map<int,CClientBuffer*>::iterator itBuff;
546    for (itBuff = buffers.begin(); itBuff != buffers.end(); itBuff++)
547      finalized &= itBuff->second->isNotifiedFinalized();
548    return finalized;
549  }
[1130]550
[509]551}
Note: See TracBrowser for help on using the repository browser.