source: XIOS/dev/dev_ym/XIOS_COUPLING/src/context_server.cpp @ 2130

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

New management of client-server buffers.

  • buffers can grow automatically in intialization phase
  • buffers is evaluated after the close context definition phase and fixed at optimal value.

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: 14.4 KB
Line 
1#include "context_server.hpp"
2#include "buffer_in.hpp"
3#include "type.hpp"
4#include "context.hpp"
5#include "object_template.hpp"
6#include "group_template.hpp"
7#include "attribute_template.hpp"
8#include "domain.hpp"
9#include "field.hpp"
10#include "file.hpp"
11#include "grid.hpp"
12#include "mpi.hpp"
13#include "tracer.hpp"
14#include "timer.hpp"
15#include "cxios.hpp"
16#include "event_scheduler.hpp"
17#include "server.hpp"
18#include "servers_ressource.hpp"
19#include "pool_ressource.hpp"
20#include "services.hpp"
21#include "contexts_manager.hpp"
22#include "timeline_events.hpp"
23
24#include <boost/functional/hash.hpp>
25#include <random>
26#include <chrono>
27
28
29namespace xios
30{
31  using namespace std ;
32
33  CContextServer::CContextServer(CContext* parent,MPI_Comm intraComm_,MPI_Comm interComm_) 
34    : eventScheduler_(nullptr), isProcessingEvent_(false), associatedClient_(nullptr)
35  {
36    context=parent;
37    intraComm=intraComm_;
38    MPI_Comm_size(intraComm,&intraCommSize);
39    MPI_Comm_rank(intraComm,&intraCommRank);
40
41    interComm=interComm_;
42    int flag;
43    MPI_Comm_test_inter(interComm,&flag);
44
45    if (flag) attachedMode=false ;
46    else  attachedMode=true ;
47   
48    if (flag) MPI_Comm_remote_size(interComm,&commSize);
49    else  MPI_Comm_size(interComm,&commSize);
50
51   
52    SRegisterContextInfo contextInfo ;
53    CXios::getContextsManager()->getContextInfo(context->getId(), contextInfo, intraComm) ;
54
55  //  if (contextInfo.serviceType != CServicesManager::CLIENT) // we must have an event scheduler => to be retrieve from the associated services
56  //  {
57      //if (!isAttachedModeEnabled()) eventScheduler_=CXios::getPoolRessource()->getService(contextInfo.serviceId,contextInfo.partitionId)->getEventScheduler() ;
58      eventScheduler_=CXios::getPoolRessource()->getService(contextInfo.serviceId,contextInfo.partitionId)->getEventScheduler() ;
59
60  //  }
61
62
63    currentTimeLine=1;
64    scheduled=false;
65    finished=false;
66
67    // generate unique hash for server
68    auto time=chrono::system_clock::now().time_since_epoch().count() ;
69    std::default_random_engine rd(time); // not reproducible from a run to another
70    std::uniform_int_distribution<size_t> dist;
71    hashId=dist(rd) ;
72    MPI_Bcast(&hashId,1,MPI_SIZE_T,0,intraComm) ; // Bcast to all server of the context
73
74
75    if (!isAttachedModeEnabled())
76    {
77      MPI_Intercomm_merge(interComm_,true,&interCommMerged) ;
78// create windows for one sided comm
79      int interCommMergedRank;
80      MPI_Comm winComm ;
81      MPI_Comm_rank(intraComm, &interCommMergedRank);
82      windows.resize(2) ;
83      for(int rank=commSize; rank<commSize+intraCommSize; rank++)
84      {
85        if (rank==commSize+interCommMergedRank) 
86        {
87          MPI_Comm_split(interCommMerged, interCommMergedRank, rank, &winComm);
88          int myRank ;
89          MPI_Comm_rank(winComm,&myRank);
90          MPI_Win_create_dynamic(MPI_INFO_NULL, winComm, &windows[0]);
91          MPI_Win_create_dynamic(MPI_INFO_NULL, winComm, &windows[1]);     
92        }
93        else MPI_Comm_split(interCommMerged, interCommMergedRank, rank, &winComm);
94        MPI_Comm_free(&winComm) ;
95      }
96    }
97    else 
98    {
99      windows.resize(2) ;
100      windows[0]=MPI_WIN_NULL ;
101      windows[1]=MPI_WIN_NULL ;
102    }
103
104
105   
106    MPI_Comm_split(intraComm_,intraCommRank,intraCommRank, &commSelf) ;
107    itLastTimeLine=lastTimeLine.begin() ;
108
109    pureOneSided=CXios::getin<bool>("pure_one_sided",false); // pure one sided communication (for test)
110    if (isAttachedModeEnabled()) pureOneSided=false ; // no one sided in attach mode
111     
112  }
113
114//! Attached mode is used ?
115//! \return true if attached mode is used, false otherwise
116  bool CContextServer::isAttachedModeEnabled() const
117  {
118    return attachedMode ;
119  }
120 
121  void CContextServer::setPendingEvent(void)
122  {
123    pendingEvent=true;
124  }
125
126  bool CContextServer::hasPendingEvent(void)
127  {
128    return pendingEvent;
129  }
130
131  bool CContextServer::hasFinished(void)
132  {
133    return finished;
134  }
135
136  bool CContextServer::eventLoop(bool enableEventsProcessing /*= true*/)
137  {
138    listen();
139    checkPendingRequest();
140    if (enableEventsProcessing)  processEvents();
141    return finished;
142  }
143
144  void CContextServer::listen(void)
145  {
146    int rank;
147    int flag;
148    int count;
149    char * addr;
150    MPI_Status status;
151    map<int,CServerBuffer*>::iterator it;
152    bool okLoop;
153
154    traceOff();
155    MPI_Iprobe(MPI_ANY_SOURCE, 20,interComm,&flag,&status);
156    traceOn();
157
158    if (flag==true)
159    {
160      rank=status.MPI_SOURCE ;
161      okLoop = true;
162      if (pendingRequest.find(rank)==pendingRequest.end())
163        okLoop = !listenPendingRequest(status) ;
164      if (okLoop)
165      {
166        for(rank=0;rank<commSize;rank++)
167        {
168          if (pendingRequest.find(rank)==pendingRequest.end())
169          {
170
171            traceOff();
172            MPI_Iprobe(rank, 20,interComm,&flag,&status);
173            traceOn();
174            if (flag==true) listenPendingRequest(status) ;
175          }
176        }
177      }
178    }
179  }
180
181  bool CContextServer::listenPendingRequest(MPI_Status& status)
182  {
183    int count;
184    char * addr;
185    map<int,CServerBuffer*>::iterator it;
186    int rank=status.MPI_SOURCE ;
187
188    it=buffers.find(rank);
189    if (it==buffers.end()) // Receive the buffer size and allocate the buffer
190    {
191       MPI_Aint recvBuff[4] ;
192       MPI_Recv(recvBuff, 4, MPI_AINT, rank, 20, interComm, &status);
193       remoteHashId_ = recvBuff[0] ;
194       StdSize buffSize = recvBuff[1];
195       vector<MPI_Aint> winAdress(2) ;
196       winAdress[0]=recvBuff[2] ; winAdress[1]=recvBuff[3] ;
197       mapBufferSize_.insert(std::make_pair(rank, buffSize));
198       it=(buffers.insert(pair<int,CServerBuffer*>(rank,new CServerBuffer(windows, winAdress, rank, buffSize)))).first;
199     
200       lastTimeLine[rank]=0 ;
201       itLastTimeLine=lastTimeLine.begin() ;
202
203       return true;
204    }
205    else
206    {
207      MPI_Get_count(&status,MPI_CHAR,&count);
208      if (it->second->isBufferFree(count))
209      {
210         addr=(char*)it->second->getBuffer(count);
211         MPI_Irecv(addr,count,MPI_CHAR,rank,20,interComm,&pendingRequest[rank]);
212         bufferRequest[rank]=addr;
213         return true;
214       }
215      else
216        return false;
217    }
218  }
219
220
221  void CContextServer::checkPendingRequest(void)
222  {
223    map<int,MPI_Request>::iterator it;
224    list<int> recvRequest;
225    list<int>::iterator itRecv;
226    int rank;
227    int flag;
228    int count;
229    MPI_Status status;
230
231    for(it=pendingRequest.begin();it!=pendingRequest.end();it++)
232    {
233      rank=it->first;
234      traceOff();
235      MPI_Test(& it->second, &flag, &status);
236      traceOn();
237      if (flag==true)
238      {
239        buffers[rank]->updateCurrentWindows() ;
240        recvRequest.push_back(rank);
241        MPI_Get_count(&status,MPI_CHAR,&count);
242        processRequest(rank,bufferRequest[rank],count);
243      }
244    }
245
246    for(itRecv=recvRequest.begin();itRecv!=recvRequest.end();itRecv++)
247    {
248      pendingRequest.erase(*itRecv);
249      bufferRequest.erase(*itRecv);
250    }
251  }
252
253  void CContextServer::getBufferFromClient(size_t timeLine)
254  {
255    if (!isAttachedModeEnabled()) // one sided desactivated in attached mode
256    { 
257      int rank ;
258      char *buffer ;
259      size_t count ; 
260
261      if (itLastTimeLine==lastTimeLine.end()) itLastTimeLine=lastTimeLine.begin() ;
262      for(;itLastTimeLine!=lastTimeLine.end();++itLastTimeLine)
263      {
264        rank=itLastTimeLine->first ;
265        if (itLastTimeLine->second < timeLine &&  pendingRequest.count(rank)==0)
266        {
267          if (buffers[rank]->getBufferFromClient(timeLine, buffer, count))
268          {
269            processRequest(rank, buffer, count);
270            break ;
271          }
272        }
273      }
274    }
275  }
276         
277       
278  void CContextServer::processRequest(int rank, char* buff,int count)
279  {
280
281    CBufferIn buffer(buff,count);
282    char* startBuffer,endBuffer;
283    int size, offset;
284    size_t timeLine=0;
285    map<size_t,CEventServer*>::iterator it;
286
287   
288    CTimer::get("Process request").resume();
289    while(count>0)
290    {
291      char* startBuffer=(char*)buffer.ptr();
292      CBufferIn newBuffer(startBuffer,buffer.remain());
293      newBuffer>>size>>timeLine;
294
295      if (timeLine==timelineEventNotifyChangeBufferSize)
296      {
297        buffers[rank]->notifyBufferResizing() ;
298        buffers[rank]->updateCurrentWindows() ;
299      } 
300      else if (timeLine==timelineEventChangeBufferSize)
301      {
302        size_t newSize ;
303        vector<MPI_Aint> winAdress(2) ;
304        newBuffer>>newSize>>winAdress[0]>>winAdress[1] ;
305        buffers.erase(rank) ;
306        buffers.insert(pair<int,CServerBuffer*>(rank,new CServerBuffer(windows, winAdress, rank, newSize)));
307      }
308      else
309      {
310        it=events.find(timeLine);
311        if (it==events.end()) it=events.insert(pair<int,CEventServer*>(timeLine,new CEventServer(this))).first;
312        it->second->push(rank,buffers[rank],startBuffer,size);
313        if (timeLine>0) lastTimeLine[rank]=timeLine ;
314      }
315      buffer.advance(size);
316      count=buffer.remain();
317    }
318   
319    CTimer::get("Process request").suspend();
320  }
321
322  void CContextServer::processEvents(void)
323  {
324    map<size_t,CEventServer*>::iterator it;
325    CEventServer* event;
326   
327//    if (context->isProcessingEvent()) return ;
328    if (isProcessingEvent_) return ;
329    if (isAttachedModeEnabled())
330      if (!CXios::getDaemonsManager()->isScheduledContext(remoteHashId_)) return ;
331
332    it=events.find(currentTimeLine);
333    if (it!=events.end())
334    {
335      event=it->second;
336
337      if (event->isFull())
338      {
339        if (!scheduled && !isAttachedModeEnabled()) // Skip event scheduling for attached mode and reception on client side
340        {
341          eventScheduler_->registerEvent(currentTimeLine,hashId);
342          scheduled=true;
343        }
344        else if (isAttachedModeEnabled() || eventScheduler_->queryEvent(currentTimeLine,hashId) )
345        {
346          MPI_Request req ;
347          MPI_Status status ;
348
349          MPI_Ibarrier(intraComm,&req) ;
350          int flag=false ;
351          do 
352          {
353            eventScheduler_->checkEvent()  ;
354            MPI_Test(&req,&flag,&status) ;
355          } while (!flag) ;
356
357          //MPI_Barrier(intraComm) ;
358         // When using attached mode, synchronise the processes to avoid that differents event be scheduled by differents processes
359         // The best way to properly solve this problem will be to use the event scheduler also in attached mode
360         // for now just set up a MPI barrier
361//ym to be check later
362//         if (!eventScheduler_ && CXios::isServer) MPI_Barrier(intraComm) ;
363
364//         context->setProcessingEvent() ;
365         isProcessingEvent_=true ;
366         CTimer::get("Process events").resume();
367         info(100)<<"Received Event "<<currentTimeLine<<" of class "<<event->classId<<" of type "<<event->type<<endl ;
368         dispatchEvent(*event);
369         CTimer::get("Process events").suspend();
370         isProcessingEvent_=false ;
371//         context->unsetProcessingEvent() ;
372         pendingEvent=false;
373         delete event;
374         events.erase(it);
375         currentTimeLine++;
376         scheduled = false;
377         if (isAttachedModeEnabled()) CXios::getDaemonsManager()->unscheduleContext() ;
378        }
379      }
380      else getBufferFromClient(currentTimeLine) ;
381    }
382    else if (pureOneSided) getBufferFromClient(currentTimeLine) ; // if pure one sided check buffer even if no event recorded at current time line
383  }
384
385  CContextServer::~CContextServer()
386  {
387    map<int,CServerBuffer*>::iterator it;
388    for(it=buffers.begin();it!=buffers.end();++it) delete it->second;
389  }
390
391  void CContextServer::releaseBuffers()
392  {
393    map<int,CServerBuffer*>::iterator it;
394    bool out ;
395    do
396    {
397      out=true ;
398      for(it=buffers.begin();it!=buffers.end();++it)
399      {
400//        out = out && it->second->freeWindows() ;
401
402      }
403    } while (! out) ; 
404  }
405
406  void CContextServer::notifyClientsFinalize(void)
407  {
408    for(auto it=buffers.begin();it!=buffers.end();++it)
409    {
410      it->second->notifyClientFinalize() ;
411    }
412  }
413
414  void CContextServer::dispatchEvent(CEventServer& event)
415  {
416    string contextName;
417    string buff;
418    int MsgSize;
419    int rank;
420    list<CEventServer::SSubEvent>::iterator it;
421    StdString ctxId = context->getId();
422    CContext::setCurrent(ctxId);
423    StdSize totalBuf = 0;
424
425    if (event.classId==CContext::GetType() && event.type==CContext::EVENT_ID_CONTEXT_FINALIZE)
426    {
427      finished=true;
428      info(20)<<" CContextServer: Receive context <"<<context->getId()<<"> finalize."<<endl;
429//      releaseBuffers() ;
430      notifyClientsFinalize() ;
431      context->finalize();
432
433/* don't know where release windows
434      MPI_Win_free(&windows[0]) ;
435      MPI_Win_free(&windows[1]) ;
436*/     
437      std::map<int, StdSize>::const_iterator itbMap = mapBufferSize_.begin(),
438                           iteMap = mapBufferSize_.end(), itMap;
439      for (itMap = itbMap; itMap != iteMap; ++itMap)
440      {
441        rank = itMap->first;
442        report(10)<< " Memory report : Context <"<<ctxId<<"> : server side : memory used for buffer of each connection to client" << endl
443            << "  +) With client of rank " << rank << " : " << itMap->second << " bytes " << endl;
444        totalBuf += itMap->second;
445      }
446      report(0)<< " Memory report : Context <"<<ctxId<<"> : server side : total memory used for buffer "<<totalBuf<<" bytes"<<endl;
447    }
448    else if (event.classId==CContext::GetType()) CContext::dispatchEvent(event);
449    else if (event.classId==CContextGroup::GetType()) CContextGroup::dispatchEvent(event);
450    else if (event.classId==CCalendarWrapper::GetType()) CCalendarWrapper::dispatchEvent(event);
451    else if (event.classId==CDomain::GetType()) CDomain::dispatchEvent(event);
452    else if (event.classId==CDomainGroup::GetType()) CDomainGroup::dispatchEvent(event);
453    else if (event.classId==CAxis::GetType()) CAxis::dispatchEvent(event);
454    else if (event.classId==CAxisGroup::GetType()) CAxisGroup::dispatchEvent(event);
455    else if (event.classId==CScalar::GetType()) CScalar::dispatchEvent(event);
456    else if (event.classId==CScalarGroup::GetType()) CScalarGroup::dispatchEvent(event);
457    else if (event.classId==CGrid::GetType()) CGrid::dispatchEvent(event);
458    else if (event.classId==CGridGroup::GetType()) CGridGroup::dispatchEvent(event);
459    else if (event.classId==CField::GetType()) CField::dispatchEvent(event);
460    else if (event.classId==CFieldGroup::GetType()) CFieldGroup::dispatchEvent(event);
461    else if (event.classId==CFile::GetType()) CFile::dispatchEvent(event);
462    else if (event.classId==CFileGroup::GetType()) CFileGroup::dispatchEvent(event);
463    else if (event.classId==CVariable::GetType()) CVariable::dispatchEvent(event);
464    else
465    {
466      ERROR("void CContextServer::dispatchEvent(CEventServer& event)",<<" Bad event class Id"<<endl);
467    }
468  }
469}
Note: See TracBrowser for help on using the repository browser.