source: XIOS/dev/dev_ym/XIOS_SERVICES/src/context_server.cpp @ 1761

Last change on this file since 1761 was 1761, checked in by ymipsl, 5 years ago

implementing first guess for service functionnalities.

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