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

Last change on this file since 2189 was 2189, checked in by jderouillat, 3 years ago

Fixes for some more strict compilers (gcc 8.3 at TGCC)

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