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

Last change on this file since 2260 was 2260, checked in by ymipsl, 3 years ago

Improvment of one sided protocol

  • removed latency
  • solve dead-lock

YM

  • 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
Line 
1#include "xios_spl.hpp"
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"
10#include "mpi.hpp"
11#include "timer.hpp"
12#include "cxios.hpp"
13#include "server.hpp"
14#include "services.hpp"
15#include <boost/functional/hash.hpp>
16#include <random>
17#include <chrono>
18
19namespace xios
20{
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
25    \cxtSer [in] cxtSer Pointer to context of server side. (It is only used in case of attached mode).
26    */
27    CContextClient::CContextClient(CContext* parent, MPI_Comm intraComm_, MPI_Comm interComm_, CContext* cxtSer)
28     : mapBufferSize_(), parentServer(cxtSer), maxBufferedEvents(4), associatedServer_(nullptr)
29    {
30     
31      context_ = parent;
32      intraComm = intraComm_;
33      interComm = interComm_;
34      MPI_Comm_rank(intraComm, &clientRank);
35      MPI_Comm_size(intraComm, &clientSize);
36
37      int flag;
38      MPI_Comm_test_inter(interComm, &flag);
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
47      if (flag) MPI_Comm_remote_size(interComm, &serverSize);
48      else  MPI_Comm_size(interComm, &serverSize);
49
50      computeLeader(clientRank, clientSize, serverSize, ranksServerLeader, ranksServerNotLeader);
51
52      if (flag) MPI_Intercomm_merge(interComm_,false, &interCommMerged_) ;
53     
54      MPI_Comm_split(intraComm_,clientRank,clientRank, &commSelf_) ; // for windows
55
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
62      timeLine = 1;
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
71      if (clientSize < serverSize)
72      {
73        int serverByClient = serverSize / clientSize;
74        int remain = serverSize % clientSize;
75        int rankStart = serverByClient * clientRank;
76
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++)
86          rankRecvLeader.push_back(rankStart + i);
87
88        rankRecvNotLeader.resize(0);
89      }
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)
98            rankRecvLeader.push_back(clientRank / (clientByServer + 1));
99          else
100            rankRecvNotLeader.push_back(clientRank / (clientByServer + 1));
101        }
102        else
103        {
104          int rank = clientRank - (clientByServer + 1) * remain;
105          if (rank % clientByServer == 0)
106            rankRecvLeader.push_back(remain + rank / clientByServer);
107          else
108            rankRecvNotLeader.push_back(remain + rank / clientByServer);
109        }
110      }
111    }
112
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    */
117    void CContextClient::sendEvent(CEventClient& event)
118    {
119      list<int> ranks = event.getRanks();
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
125      if (CXios::checkEventSync)
126      {
127        int typeId, classId, typeId_in, classId_in;
128        long long timeLine_out;
129        long long timeLine_in( timeLine );
130        typeId_in=event.getTypeId() ;
131        classId_in=event.getClassId() ;
132//        MPI_Allreduce(&timeLine,&timeLine_out, 1, MPI_UINT64_T, MPI_SUM, intraComm) ; // MPI_UINT64_T standardized by MPI 3
133        MPI_Allreduce(&timeLine_in,&timeLine_out, 1, MPI_LONG_LONG_INT, MPI_SUM, intraComm) ; 
134        MPI_Allreduce(&typeId_in,&typeId, 1, MPI_INT, MPI_SUM, intraComm) ;
135        MPI_Allreduce(&classId_in,&classId, 1, MPI_INT, MPI_SUM, intraComm) ;
136        if (typeId/clientSize!=event.getTypeId() || classId/clientSize!=event.getClassId() || timeLine_out/clientSize!=timeLine)
137        {
138           ERROR("void CContextClient::sendEvent(CEventClient& event)",
139               << "Event are not coherent between client for timeline = "<<timeLine);
140        }
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
156      }
157
158      if (!event.isEmpty())
159      {
160        list<int> sizes = event.getSizes();
161
162         // We force the getBuffers call to be non-blocking on classical servers
163        list<CBufferOut*> buffList;
164        getBuffers(timeLine, ranks, sizes, buffList) ;
165
166        event.send(timeLine, sizes, buffList);
167       
168        //for (auto itRank = ranks.begin(); itRank != ranks.end(); itRank++) buffers[*itRank]->infoBuffer() ;
169
170        unlockBuffers(ranks) ;
171        checkBuffers(ranks);
172       
173      }
174     
175      if (isAttachedModeEnabled()) // couldBuffer is always true in attached mode
176      {
177        while (checkBuffers(ranks)) context_->globalEventLoop() ;
178     
179        CXios::getDaemonsManager()->scheduleContext(hashId_) ;
180        while (CXios::getDaemonsManager()->isScheduledContext(hashId_)) context_->globalEventLoop() ;
181      }
182     
183      timeLine++;
184    }
185
186    /*!
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    */
191    void CContextClient::waitEvent(list<int>& ranks)
192    {
193      while (checkBuffers(ranks))
194      {
195        context_->eventLoop() ;
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    {
216      parentServer->server->setPendingEvent();
217      while (checkBuffers(ranks))
218      {
219        parentServer->server->listen();
220        parentServer->server->checkPendingRequest();
221      }
222
223      while (parentServer->server->hasPendingEvent())
224      {
225       parentServer->server->eventLoop();
226      }
227    }
228
229    /*!
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     *
233     *
234     * \param [in] timeLine time line of the event which will be sent to servers
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
240    */
241    bool CContextClient::getBuffers(const size_t timeLine, const list<int>& serverList, const list<int>& sizeList, list<CBufferOut*>& retBuffers,
242                                    bool nonBlocking /*= false*/)
243    {
244      list<int>::const_iterator itServer, itSize;
245      list<CClientBuffer*> bufferList;
246      map<int,CClientBuffer*>::const_iterator it;
247      list<CClientBuffer*>::iterator itBuffer;
248      bool areBuffersFree;
249
250      for (itServer = serverList.begin(); itServer != serverList.end(); itServer++)
251      {
252        it = buffers.find(*itServer);
253        if (it == buffers.end())
254        {
255          newBuffer(*itServer);
256          it = buffers.find(*itServer);
257        }
258        bufferList.push_back(it->second);
259      }
260
261      double lastTimeBuffersNotFree=0. ;
262      double time ;
263      bool doUnlockBuffers ;
264      CTimer::get("Blocking time").resume();
265      do
266      {
267        areBuffersFree = true;
268        doUnlockBuffers=false ;
269        time=MPI_Wtime() ;
270        if (time-lastTimeBuffersNotFree > latency_)
271        {
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          }         
281        }
282        else areBuffersFree = false ;
283
284        if (!areBuffersFree)
285        {
286          if (doUnlockBuffers) for (itBuffer = bufferList.begin(); itBuffer != bufferList.end(); itBuffer++) (*itBuffer)->unlockBuffer();
287          checkBuffers();
288
289          context_->globalEventLoop() ;
290        }
291
292      } while (!areBuffersFree && !nonBlocking);
293      CTimer::get("Blocking time").suspend();
294
295      if (areBuffersFree)
296      {
297        for (itBuffer = bufferList.begin(), itSize = sizeList.begin(); itBuffer != bufferList.end(); itBuffer++, itSize++)
298          retBuffers.push_back((*itBuffer)->getBuffer(timeLine, *itSize));
299      }
300      return areBuffersFree;
301   }
302
303   /*!
304   Make a new buffer for a certain connection to server with specific rank
305   \param [in] rank rank of connected server
306   */
307   void CContextClient::newBuffer(int rank)
308   {
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      }
315     
316      CClientBuffer* buffer = buffers[rank] = new CClientBuffer(interComm, rank, mapBufferSize_[rank], maxEventSizes[rank]);
317      if (isGrowableBuffer_) buffer->setGrowableBuffer(1.2) ;
318      else buffer->fixBuffer() ;
319      // Notify the server
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); 
326      info(100)<<"CContextClient::newBuffer : rank "<<rank<<" winAdress[0] "<<buffers[rank]->getWinAddress(0)<<" winAdress[1] "<<buffers[rank]->getWinAddress(1)<<endl;
327      bufOut->put(sendBuff, 4); 
328      buffer->checkBuffer(true);
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]) ;
351      if (!isAttachedModeEnabled()) MPI_Barrier(winComm_[rank]) ;
352       
353   }
354
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   */
359   bool CContextClient::checkBuffers(void)
360   {
361      map<int,CClientBuffer*>::iterator itBuff;
362      bool pending = false;
363      for (itBuff = buffers.begin(); itBuff != buffers.end(); itBuff++)
364        pending |= itBuff->second->checkBuffer(!pureOneSided);
365      return pending;
366   }
367
368   //! Release all buffers
369   void CContextClient::releaseBuffers()
370   {
371      map<int,CClientBuffer*>::iterator itBuff;
372      for (itBuff = buffers.begin(); itBuff != buffers.end(); itBuff++)
373      {
374         delete itBuff->second;
375      }
376      buffers.clear();
377
378// don't know when release windows
379
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      } 
390   }
391
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   }
402
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     
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   */
418   bool CContextClient::checkBuffers(list<int>& ranks)
419   {
420      list<int>::iterator it;
421      bool pending = false;
422      for (it = ranks.begin(); it != ranks.end(); it++) pending |= buffers[*it]->checkBuffer(!pureOneSided);
423      return pending;
424   }
425
426   /*!
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
431   */
432   void CContextClient::setBufferSize(const std::map<int,StdSize>& mapSize)
433   {
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)));
436   }
437
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  }
446
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  }
455
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  }
464
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  }
473
474   /*!
475   * Finalize context client and do some reports. Function is non-blocking.
476   */
477  void CContextClient::finalize(void)
478  {
479    map<int,CClientBuffer*>::iterator itBuff;
480    std::list<int>::iterator ItServerLeader; 
481   
482    bool stop = false;
483
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;
494
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 ;
500
501
502    CTimer::get("Blocking time").resume();
503    checkBuffers();
504    CTimer::get("Blocking time").suspend();
505
506    std::map<int,StdSize>::const_iterator itbMap = mapBufferSize_.begin(),
507                                          iteMap = mapBufferSize_.end(), itMap;
508
509    StdSize totalBuf = 0;
510    for (itMap = itbMap; itMap != iteMap; ++itMap)
511    {
512      report(10) << " Memory report : Context <" << context_->getId() << "> : client side : memory used for buffer of each connection to server" << endl
513                 << "  +) To server with rank " << itMap->first << " : " << itMap->second << " bytes " << endl;
514      totalBuf += itMap->second;
515    }
516    report(0) << " Memory report : Context <" << context_->getId() << "> : client side : total memory used for buffer " << totalBuf << " bytes" << endl;
517
518  }
519
520
521  /*!
522  */
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  }
531 
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
540  bool CContextClient::isNotifiedFinalized(void)
541  {
542    if (isAttachedModeEnabled()) return true ;
543
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  }
550
551}
Note: See TracBrowser for help on using the repository browser.