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

Last change on this file since 2309 was 2309, checked in by ymipsl, 2 years ago

Bug fix when resizing buffer on server size.

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: 16.9 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,&clientSize_);
49    else  MPI_Comm_size(interComm,&clientSize_);
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    MPI_Comm_dup(intraComm, &processEventBarrier_) ;
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()) MPI_Intercomm_merge(interComm_,true,&interCommMerged_) ;
76    MPI_Comm_split(intraComm_, intraCommRank, intraCommRank, &commSelf_) ; // for windows
77   
78    itLastTimeLine=lastTimeLine.begin() ;
79
80    pureOneSided=CXios::getin<bool>("pure_one_sided",false); // pure one sided communication (for test)
81    if (isAttachedModeEnabled()) pureOneSided=false ; // no one sided in attach mode
82     
83  }
84
85//! Attached mode is used ?
86//! \return true if attached mode is used, false otherwise
87  bool CContextServer::isAttachedModeEnabled() const
88  {
89    return attachedMode ;
90  }
91 
92  void CContextServer::setPendingEvent(void)
93  {
94    pendingEvent=true;
95  }
96
97  bool CContextServer::hasPendingEvent(void)
98  {
99    return pendingEvent;
100  }
101
102  bool CContextServer::hasFinished(void)
103  {
104    return finished;
105  }
106
107  bool CContextServer::eventLoop(bool enableEventsProcessing /*= true*/)
108  {
109    CTimer::get("listen request").resume();
110    listen();
111    CTimer::get("listen request").suspend();
112    CTimer::get("check pending request").resume();
113    checkPendingRequest();
114    checkPendingProbe() ;
115    CTimer::get("check pending request").suspend();
116    CTimer::get("check event process").resume();
117    if (enableEventsProcessing)  processEvents();
118    CTimer::get("check event process").suspend();
119    return finished;
120  }
121
122 void CContextServer::listen(void)
123  {
124    int rank;
125    int flag;
126    int count;
127    char * addr;
128    MPI_Status status;
129    MPI_Message message ;
130    map<int,CServerBuffer*>::iterator it;
131    bool okLoop;
132
133    traceOff();
134    MPI_Improbe(MPI_ANY_SOURCE, 20,interComm,&flag,&message, &status);
135    traceOn();
136    if (flag==true) listenPendingRequest(message, status) ;
137  }
138
139  bool CContextServer::listenPendingRequest( MPI_Message &message, MPI_Status& status)
140  {
141    int count;
142    char * addr;
143    map<int,CServerBuffer*>::iterator it;
144    int rank=status.MPI_SOURCE ;
145
146    it=buffers.find(rank);
147    if (it==buffers.end()) // Receive the buffer size and allocate the buffer
148    {
149      MPI_Aint recvBuff[4] ;
150      MPI_Mrecv(recvBuff, 4, MPI_AINT,  &message, &status);
151      remoteHashId_ = recvBuff[0] ;
152      StdSize buffSize = recvBuff[1];
153      vector<MPI_Aint> winAdress(2) ;
154      winAdress[0]=recvBuff[2] ; winAdress[1]=recvBuff[3] ;
155      mapBufferSize_.insert(std::make_pair(rank, buffSize));
156
157      // create windows dynamically for one-sided
158      if (!isAttachedModeEnabled())
159      { 
160        CTimer::get("create Windows").resume() ;
161        MPI_Comm interComm ;
162        MPI_Intercomm_create(commSelf_, 0, interCommMerged_, rank, 0 , &interComm) ;
163        MPI_Intercomm_merge(interComm, true, &winComm_[rank]) ;
164        windows_[rank].resize(2) ;
165        MPI_Win_create_dynamic(MPI_INFO_NULL, winComm_[rank], &windows_[rank][0]);
166        MPI_Win_create_dynamic(MPI_INFO_NULL, winComm_[rank], &windows_[rank][1]);
167        CTimer::get("create Windows").suspend() ;
168        MPI_Barrier(winComm_[rank]) ;
169      }
170      else
171      {
172        winComm_[rank] = MPI_COMM_NULL ;
173        windows_[rank].resize(2) ;
174        windows_[rank][0] = MPI_WIN_NULL ;
175        windows_[rank][1] = MPI_WIN_NULL ;
176      }   
177
178      it=(buffers.insert(pair<int,CServerBuffer*>(rank,new CServerBuffer(windows_[rank], winAdress, 0, buffSize)))).first;
179      lastTimeLine[rank]=0 ;
180      itLastTimeLine=lastTimeLine.begin() ;
181
182      return true;
183    }
184    else
185    {
186        std::pair<MPI_Message,MPI_Status> mypair(message,status) ;
187        pendingProbe[rank].push_back(mypair) ;
188        return false;
189    }
190  }
191
192  void CContextServer::checkPendingProbe(void)
193  {
194   
195    list<int> recvProbe ;
196    list<int>::iterator itRecv ;
197    map<int, list<std::pair<MPI_Message,MPI_Status> > >::iterator itProbe;
198
199    for(itProbe=pendingProbe.begin();itProbe!=pendingProbe.end();itProbe++)
200    {
201      int rank=itProbe->first ;
202      if (pendingRequest.count(rank)==0)
203      {
204        MPI_Message& message = itProbe->second.front().first ;
205        MPI_Status& status = itProbe->second.front().second ;
206        int count ;
207        MPI_Get_count(&status,MPI_CHAR,&count);
208        map<int,CServerBuffer*>::iterator it = buffers.find(rank);
209        if ( (it->second->isBufferFree(count) && !it->second->isResizing()) // accept new request if buffer is free
210          || (it->second->isResizing() && it->second->isBufferEmpty()) )    // or if resizing wait for buffer is empty
211        {
212          char * addr;
213          addr=(char*)it->second->getBuffer(count);
214          MPI_Imrecv(addr,count,MPI_CHAR, &message, &pendingRequest[rank]);
215          bufferRequest[rank]=addr;
216          recvProbe.push_back(rank) ;
217          itProbe->second.pop_front() ;
218        }
219      }
220    }
221
222    for(itRecv=recvProbe.begin(); itRecv!=recvProbe.end(); itRecv++) if (pendingProbe[*itRecv].empty()) pendingProbe.erase(*itRecv) ;
223  }
224
225
226  void CContextServer::checkPendingRequest(void)
227  {
228    map<int,MPI_Request>::iterator it;
229    list<int> recvRequest;
230    list<int>::iterator itRecv;
231    int rank;
232    int flag;
233    int count;
234    MPI_Status status;
235   
236    if (!pendingRequest.empty()) CTimer::get("receiving requests").resume();
237    else CTimer::get("receiving requests").suspend();
238
239    for(it=pendingRequest.begin();it!=pendingRequest.end();it++)
240    {
241      rank=it->first;
242      traceOff();
243      MPI_Test(& it->second, &flag, &status);
244      traceOn();
245      if (flag==true)
246      {
247        buffers[rank]->updateCurrentWindows() ;
248        recvRequest.push_back(rank);
249        MPI_Get_count(&status,MPI_CHAR,&count);
250        processRequest(rank,bufferRequest[rank],count);
251      }
252    }
253
254    for(itRecv=recvRequest.begin();itRecv!=recvRequest.end();itRecv++)
255    {
256      pendingRequest.erase(*itRecv);
257      bufferRequest.erase(*itRecv);
258    }
259  }
260
261  void CContextServer::getBufferFromClient(size_t timeLine)
262  {
263    CTimer::get("CContextServer::getBufferFromClient").resume() ;
264    if (!isAttachedModeEnabled()) // one sided desactivated in attached mode
265    { 
266      int rank ;
267      char *buffer ;
268      size_t count ; 
269
270      if (itLastTimeLine==lastTimeLine.end()) itLastTimeLine=lastTimeLine.begin() ;
271      for(;itLastTimeLine!=lastTimeLine.end();++itLastTimeLine)
272      {
273        rank=itLastTimeLine->first ;
274        if (itLastTimeLine->second < timeLine &&  pendingRequest.count(rank)==0 && buffers[rank]->isBufferEmpty())
275        {
276          if (buffers[rank]->getBufferFromClient(timeLine, buffer, count)) processRequest(rank, buffer, count);
277          if (count >= 0) ++itLastTimeLine ;
278          break ;
279        }
280      }
281    }
282    CTimer::get("CContextServer::getBufferFromClient").suspend() ;
283  }
284         
285       
286  void CContextServer::processRequest(int rank, char* buff,int count)
287  {
288
289    CBufferIn buffer(buff,count);
290    char* startBuffer,endBuffer;
291    int size, offset;
292    size_t timeLine=0;
293    map<size_t,CEventServer*>::iterator it;
294
295   
296    CTimer::get("Process request").resume();
297    while(count>0)
298    {
299      char* startBuffer=(char*)buffer.ptr();
300      CBufferIn newBuffer(startBuffer,buffer.remain());
301      newBuffer>>size>>timeLine;
302
303      if (timeLine==timelineEventNotifyChangeBufferSize)
304      {
305        buffers[rank]->notifyBufferResizing() ;
306        buffers[rank]->updateCurrentWindows() ;
307        buffers[rank]->popBuffer(count) ;
308        info(100)<<"Context id "<<context->getId()<<" : Receive NotifyChangeBufferSize from client rank "<<rank<<endl
309                 <<"isBufferEmpty ? "<<buffers[rank]->isBufferEmpty()<<"  remaining count : "<<buffers[rank]->getUsed()<<endl;
310      } 
311      else if (timeLine==timelineEventChangeBufferSize)
312      {
313        size_t newSize ;
314        vector<MPI_Aint> winAdress(2) ;
315        newBuffer>>newSize>>winAdress[0]>>winAdress[1] ;
316        buffers[rank]->freeBuffer(count) ;
317        delete buffers[rank] ;
318        buffers[rank] = new CServerBuffer(windows_[rank], winAdress, 0, newSize) ;
319        info(100)<<"Context id "<<context->getId()<<" : Receive ChangeBufferSize from client rank "<<rank
320                 <<"  newSize : "<<newSize<<" Address : "<<winAdress[0]<<" & "<<winAdress[1]<<endl ;
321      }
322      else
323      {
324        info(100)<<"Context id "<<context->getId()<<" : Receive standard event from client rank "<<rank<<"  with timeLine : "<<timeLine<<endl ;
325        it=events.find(timeLine);
326        if (it==events.end()) it=events.insert(pair<int,CEventServer*>(timeLine,new CEventServer(this))).first;
327        it->second->push(rank,buffers[rank],startBuffer,size);
328        if (timeLine>0) lastTimeLine[rank]=timeLine ;
329      }
330      buffer.advance(size);
331      count=buffer.remain();
332    }
333   
334    CTimer::get("Process request").suspend();
335  }
336
337  void CContextServer::processEvents(void)
338  {
339    map<size_t,CEventServer*>::iterator it;
340    CEventServer* event;
341   
342//    if (context->isProcessingEvent()) return ;
343    if (isProcessingEvent_) return ;
344    if (isAttachedModeEnabled())
345      if (!CXios::getDaemonsManager()->isScheduledContext(remoteHashId_)) return ;
346
347    it=events.find(currentTimeLine);
348    if (it!=events.end())
349    {
350      event=it->second;
351
352      if (event->isFull())
353      {
354        if (!scheduled && !isAttachedModeEnabled()) // Skip event scheduling for attached mode and reception on client side
355        {
356          eventScheduler_->registerEvent(currentTimeLine,hashId);
357          scheduled=true;
358        }
359        else if (isAttachedModeEnabled() || eventScheduler_->queryEvent(currentTimeLine,hashId) )
360        {
361
362          if (!eventScheduled_) 
363          {
364            MPI_Ibarrier(processEventBarrier_,&processEventRequest_) ;
365            eventScheduled_=true ;
366            return ;
367          }
368          else 
369          {
370            MPI_Status status ;
371            int flag ;
372            MPI_Test(&processEventRequest_, &flag, &status) ;
373            if (!flag) return ;
374            eventScheduled_=false ;
375          }
376
377          if (!isAttachedModeEnabled()) eventScheduler_->popEvent() ;
378          //MPI_Barrier(intraComm) ;
379         // When using attached mode, synchronise the processes to avoid that differents event be scheduled by differents processes
380         // The best way to properly solve this problem will be to use the event scheduler also in attached mode
381         // for now just set up a MPI barrier
382//ym to be check later
383//         if (!eventScheduler_ && CXios::isServer) MPI_Barrier(intraComm) ;
384
385//         context->setProcessingEvent() ;
386         isProcessingEvent_=true ;
387         CTimer::get("Process events").resume();
388         info(100)<<"Context id "<<context->getId()<<" : Process Event "<<currentTimeLine<<" of class "<<event->classId<<" of type "<<event->type<<endl ;
389         dispatchEvent(*event);
390         CTimer::get("Process events").suspend();
391         isProcessingEvent_=false ;
392//         context->unsetProcessingEvent() ;
393         pendingEvent=false;
394         delete event;
395         events.erase(it);
396         currentTimeLine++;
397         scheduled = false;
398         if (isAttachedModeEnabled()) CXios::getDaemonsManager()->unscheduleContext() ;
399        }
400      }
401      else if (pendingRequest.empty()) getBufferFromClient(currentTimeLine) ;
402    }
403    else if (pendingRequest.empty()) getBufferFromClient(currentTimeLine) ; // if pure one sided check buffer even if no event recorded at current time line
404  }
405
406  CContextServer::~CContextServer()
407  {
408    map<int,CServerBuffer*>::iterator it;
409    for(it=buffers.begin();it!=buffers.end();++it) delete it->second;
410    buffers.clear() ;
411  }
412
413  void CContextServer::releaseBuffers()
414  {
415    //for(auto it=buffers.begin();it!=buffers.end();++it) delete it->second ;
416    //buffers.clear() ;
417    freeWindows() ;
418  }
419
420  void CContextServer::freeWindows()
421  {
422    //if (!isAttachedModeEnabled())
423    //{
424    //  for(auto& it : winComm_)
425    //  {
426    //    int rank = it.first ;
427    //    MPI_Win_free(&windows_[rank][0]);
428    //    MPI_Win_free(&windows_[rank][1]);
429    //    MPI_Comm_free(&winComm_[rank]) ;
430    //  }
431    //}
432  }
433
434  void CContextServer::notifyClientsFinalize(void)
435  {
436    for(auto it=buffers.begin();it!=buffers.end();++it)
437    {
438      it->second->notifyClientFinalize() ;
439    }
440  }
441
442  void CContextServer::dispatchEvent(CEventServer& event)
443  {
444    string contextName;
445    string buff;
446    int MsgSize;
447    int rank;
448    list<CEventServer::SSubEvent>::iterator it;
449    StdString ctxId = context->getId();
450    CContext::setCurrent(ctxId);
451    StdSize totalBuf = 0;
452
453    if (event.classId==CContext::GetType() && event.type==CContext::EVENT_ID_CONTEXT_FINALIZE)
454    {
455      finished=true;
456      info(20)<<" CContextServer: Receive context <"<<context->getId()<<"> finalize."<<endl;
457      notifyClientsFinalize() ;
458      CTimer::get("receiving requests").suspend();
459      context->finalize();
460     
461      std::map<int, StdSize>::const_iterator itbMap = mapBufferSize_.begin(),
462                           iteMap = mapBufferSize_.end(), itMap;
463      for (itMap = itbMap; itMap != iteMap; ++itMap)
464      {
465        rank = itMap->first;
466        report(10)<< " Memory report : Context <"<<ctxId<<"> : server side : memory used for buffer of each connection to client" << endl
467            << "  +) With client of rank " << rank << " : " << itMap->second << " bytes " << endl;
468        totalBuf += itMap->second;
469      }
470      report(0)<< " Memory report : Context <"<<ctxId<<"> : server side : total memory used for buffer "<<totalBuf<<" bytes"<<endl;
471    }
472    else if (event.classId==CContext::GetType()) CContext::dispatchEvent(event);
473    else if (event.classId==CContextGroup::GetType()) CContextGroup::dispatchEvent(event);
474    else if (event.classId==CCalendarWrapper::GetType()) CCalendarWrapper::dispatchEvent(event);
475    else if (event.classId==CDomain::GetType()) CDomain::dispatchEvent(event);
476    else if (event.classId==CDomainGroup::GetType()) CDomainGroup::dispatchEvent(event);
477    else if (event.classId==CAxis::GetType()) CAxis::dispatchEvent(event);
478    else if (event.classId==CAxisGroup::GetType()) CAxisGroup::dispatchEvent(event);
479    else if (event.classId==CScalar::GetType()) CScalar::dispatchEvent(event);
480    else if (event.classId==CScalarGroup::GetType()) CScalarGroup::dispatchEvent(event);
481    else if (event.classId==CGrid::GetType()) CGrid::dispatchEvent(event);
482    else if (event.classId==CGridGroup::GetType()) CGridGroup::dispatchEvent(event);
483    else if (event.classId==CField::GetType()) CField::dispatchEvent(event);
484    else if (event.classId==CFieldGroup::GetType()) CFieldGroup::dispatchEvent(event);
485    else if (event.classId==CFile::GetType()) CFile::dispatchEvent(event);
486    else if (event.classId==CFileGroup::GetType()) CFileGroup::dispatchEvent(event);
487    else if (event.classId==CVariable::GetType()) CVariable::dispatchEvent(event);
488    else
489    {
490      ERROR("void CContextServer::dispatchEvent(CEventServer& event)",<<" Bad event class Id"<<endl);
491    }
492  }
493
494  bool CContextServer::isCollectiveEvent(CEventServer& event)
495  {
496    if (event.classId==CField::GetType()) return CField::isCollectiveEvent(event);
497    else return true ;
498  }
499}
Note: See TracBrowser for help on using the repository browser.