source: XIOS3/trunk/src/server.cpp @ 2404

Last change on this file since 2404 was 2404, checked in by ymipsl, 21 months ago

Add the possibility to launch a service on same ressource than an other.
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.2 KB
Line 
1#include "globalScopeData.hpp"
2#include "xios_spl.hpp"
3#include "cxios.hpp"
4#include "server.hpp"
5#include "client.hpp"
6#include "type.hpp"
7#include "context.hpp"
8#include "object_template.hpp"
9#include "oasis_cinterface.hpp"
10#include <boost/functional/hash.hpp>
11#include <boost/algorithm/string.hpp>
12#include "mpi.hpp"
13#include "tracer.hpp"
14#include "timer.hpp"
15#include "event_scheduler.hpp"
16#include "string_tools.hpp"
17#include "ressources_manager.hpp"
18#include "services_manager.hpp"
19#include "contexts_manager.hpp"
20#include "servers_ressource.hpp"
21#include "services.hpp"
22#include <cstdio>
23#include "workflow_graph.hpp"
24#include "release_static_allocation.hpp"
25#include <sys/stat.h>
26#include <unistd.h>
27
28
29
30namespace xios
31{
32    MPI_Comm CServer::intraComm_ ;
33    MPI_Comm CServer::serversComm_ ;
34    std::list<MPI_Comm> CServer::interCommLeft ;
35    std::list<MPI_Comm> CServer::interCommRight ;
36    std::list<MPI_Comm> CServer::contextInterComms;
37    std::list<MPI_Comm> CServer::contextIntraComms;
38    int CServer::serverLevel = 0 ;
39    int CServer::nbContexts = 0;
40    bool CServer::isRoot = false ;
41    int CServer::rank_ = INVALID_RANK;
42    StdOFStream CServer::m_infoStream;
43    StdOFStream CServer::m_errorStream;
44    map<string,CContext*> CServer::contextList ;
45    vector<int> CServer::sndServerGlobalRanks;
46    bool CServer::finished=false ;
47    bool CServer::is_MPI_Initialized ;
48    CEventScheduler* CServer::eventScheduler = 0;
49    CServersRessource* CServer::serversRessource_=nullptr ;
50    CThirdPartyDriver* CServer::driver_ =nullptr ;
51
52       
53    void CServer::initialize(void)
54    {
55     
56      MPI_Comm serverComm ;
57      int initialized ;
58      MPI_Initialized(&initialized) ;
59      if (initialized) is_MPI_Initialized=true ;
60      else is_MPI_Initialized=false ;
61      MPI_Comm globalComm=CXios::getGlobalComm() ;
62      CTimer::get("XIOS server").resume() ;
63      /////////////////////////////////////////
64      ///////////// PART 1 ////////////////////
65      /////////////////////////////////////////
66      // don't use OASIS
67      if (!CXios::usingOasis)
68      {
69        if (!is_MPI_Initialized) MPI_Init(NULL, NULL);
70       
71        // split the global communicator
72        // get hash from all model to attribute a unique color (int) and then split to get client communicator
73        // every mpi process of globalComm (MPI_COMM_WORLD) must participate
74         
75        int commRank, commSize ;
76        MPI_Comm_rank(globalComm,&commRank) ;
77        MPI_Comm_size(globalComm,&commSize) ;
78
79        std::hash<string> hashString ;
80        size_t hashServer=hashString(CXios::xiosCodeId) ;
81         
82        size_t* hashAll = new size_t[commSize] ;
83        MPI_Allgather(&hashServer,1,MPI_SIZE_T,hashAll,1,MPI_SIZE_T,globalComm) ;
84         
85        int color=0 ;
86        map<size_t,int> listHash ;
87        for(int i=0 ; i<=commSize ; i++) 
88          if (listHash.count(hashAll[i])==0) 
89          {
90            listHash[hashAll[i]]=color ;
91            color=color+1 ;
92          }
93        color=listHash[hashServer] ;
94        delete[] hashAll ;
95
96        MPI_Comm_split(globalComm, color, commRank, &serverComm) ;
97      }
98      else // using OASIS
99      {
100        if (!is_MPI_Initialized) driver_ = new CThirdPartyDriver();
101
102        driver_->getComponentCommunicator( serverComm );
103      }
104      MPI_Comm_dup(serverComm, &intraComm_);
105     
106      CTimer::get("XIOS").resume() ;
107      CTimer::get("XIOS initialize").resume() ;
108 
109      /////////////////////////////////////////
110      ///////////// PART 2 ////////////////////
111      /////////////////////////////////////////
112     
113
114      // Create the XIOS communicator for every process which is related
115      // to XIOS, as well on client side as on server side
116      MPI_Comm xiosGlobalComm ;
117      string strIds=CXios::getin<string>("clients_code_id","") ;
118      vector<string> clientsCodeId=splitRegex(strIds,"\\s*,\\s*") ;
119      if (strIds.empty())
120      {
121        // no code Ids given, suppose XIOS initialisation is global           
122        int commRank, commGlobalRank, serverLeader, clientLeader,serverRemoteLeader,clientRemoteLeader ;
123        MPI_Comm splitComm,interComm ;
124        MPI_Comm_rank(globalComm,&commGlobalRank) ;
125        MPI_Comm_split(globalComm, 1, commGlobalRank, &splitComm) ;
126        MPI_Comm_rank(splitComm,&commRank) ;
127        if (commRank==0) serverLeader=commGlobalRank ;
128        else serverLeader=0 ;
129        clientLeader=0 ;
130        MPI_Allreduce(&clientLeader,&clientRemoteLeader,1,MPI_INT,MPI_SUM,globalComm) ;
131        MPI_Allreduce(&serverLeader,&serverRemoteLeader,1,MPI_INT,MPI_SUM,globalComm) ;
132        MPI_Intercomm_create(splitComm, 0, globalComm, clientRemoteLeader,1341,&interComm) ;
133        MPI_Intercomm_merge(interComm,false,&xiosGlobalComm) ;
134        CXios::setXiosComm(xiosGlobalComm) ;
135      }
136      else
137      {
138
139        xiosGlobalCommByFileExchange(serverComm) ;
140
141      }
142     
143      /////////////////////////////////////////
144      ///////////// PART 4 ////////////////////
145      //  create servers intra communicator  //
146      /////////////////////////////////////////
147     
148      int commRank ;
149      MPI_Comm_rank(CXios::getXiosComm(), &commRank) ;
150      MPI_Comm_split(CXios::getXiosComm(),true,commRank,&serversComm_) ;
151     
152      CXios::setUsingServer() ;
153
154      /////////////////////////////////////////
155      ///////////// PART 5 ////////////////////
156      //       redirect files output         //
157      /////////////////////////////////////////
158     
159      CServer::openInfoStream(CXios::serverFile);
160      CServer::openErrorStream(CXios::serverFile);
161
162      /////////////////////////////////////////
163      ///////////// PART 4 ////////////////////
164      /////////////////////////////////////////
165
166      CXios::launchDaemonsManager(true) ;
167     
168      /////////////////////////////////////////
169      ///////////// PART 5 ////////////////////
170      /////////////////////////////////////////
171
172      // create the services
173
174      auto ressourcesManager=CXios::getRessourcesManager() ;
175      auto servicesManager=CXios::getServicesManager() ;
176      auto contextsManager=CXios::getContextsManager() ;
177      auto daemonsManager=CXios::getDaemonsManager() ;
178      auto serversRessource=CServer::getServersRessource() ;
179
180      int rank;
181      MPI_Comm_rank(intraComm_, &rank) ;
182      if (rank==0) isRoot=true;
183      else isRoot=false;
184
185      if (serversRessource->isServerLeader())
186      {
187        int nbRessources = ressourcesManager->getRessourcesSize() ;
188        if (!CXios::usingServer2)
189        {
190          ressourcesManager->createPool(CXios::defaultPoolId, nbRessources) ;
191          servicesManager->createServices(CXios::defaultPoolId, CXios::defaultServerId, CServicesManager::IO_SERVER,nbRessources,1) ;
192          servicesManager->createServicesOnto(CXios::defaultPoolId, "default_reader", CServicesManager::READER, CXios::defaultServerId) ;
193        }
194        else
195        {
196          int nprocsServer = nbRessources*CXios::ratioServer2/100.;
197          int nprocsGatherer = nbRessources - nprocsServer ;
198         
199          int nbPoolsServer2 = CXios::nbPoolsServer2 ;
200          if (nbPoolsServer2 == 0) nbPoolsServer2 = nprocsServer;
201          ressourcesManager->createPool(CXios::defaultPoolId, nbRessources) ;
202          servicesManager->createServices(CXios::defaultPoolId,  CXios::defaultGathererId, CServicesManager::GATHERER, nprocsGatherer, 1) ;
203          servicesManager->createServices(CXios::defaultPoolId,  CXios::defaultServerId, CServicesManager::OUT_SERVER, nprocsServer, nbPoolsServer2) ;
204
205
206        }
207        servicesManager->createServices(CXios::defaultPoolId,  CXios::defaultServicesId, CServicesManager::ALL_SERVICES, nbRessources, 1) ;
208      }
209      CTimer::get("XIOS initialize").suspend() ;
210
211      /////////////////////////////////////////
212      ///////////// PART 5 ////////////////////
213      /////////////////////////////////////////
214      // loop on event loop
215
216      bool finished=false ;
217      CTimer::get("XIOS event loop").resume() ;
218
219      while (!finished)
220      {
221        finished=daemonsManager->eventLoop() ;
222      }
223      CTimer::get("XIOS event loop").suspend() ;
224
225      // Delete CContext
226      //CObjectTemplate<CContext>::cleanStaticDataStructure();
227    }
228
229
230
231
232
233    void  CServer::xiosGlobalCommByFileExchange(MPI_Comm serverComm)
234    {
235       
236      MPI_Comm globalComm=CXios::getGlobalComm() ;
237      MPI_Comm xiosGlobalComm ;
238     
239      string strIds=CXios::getin<string>("clients_code_id","") ;
240      vector<string> clientsCodeId=splitRegex(strIds,"\\s*,\\s*") ;
241     
242      int commRank, globalRank ;
243      MPI_Comm_rank(serverComm, &commRank) ;
244      MPI_Comm_rank(globalComm, &globalRank) ;
245      string serverFileName("__xios_publisher::"+CXios::xiosCodeId+"__to_remove__") ;
246
247      if (commRank==0) // if root process publish name
248      { 
249        std::ofstream ofs (serverFileName, std::ofstream::out);
250        ofs<<globalRank ;
251        ofs.close();
252      }
253       
254      vector<int> clientsRank(clientsCodeId.size()) ;
255      for(int i=0;i<clientsRank.size();i++)
256      {
257        std::ifstream ifs ;
258        string fileName=("__xios_publisher::"+clientsCodeId[i]+"__to_remove__") ;
259        struct stat buffer;
260        do {
261        } while( stat(fileName.c_str(), &buffer) != 0 );
262        sleep(1);
263        ifs.open(fileName, ifstream::in) ;
264        ifs>>clientsRank[i] ;
265        //cout <<  "\t\t read: " << clientsRank[i] << " in " << fileName << endl;
266        ifs.close() ; 
267      }
268
269      MPI_Comm intraComm ;
270      MPI_Comm_dup(serverComm,&intraComm) ;
271      MPI_Comm interComm ;
272      for(int i=0 ; i<clientsRank.size(); i++)
273      { 
274        MPI_Intercomm_create(intraComm, 0, globalComm, clientsRank[i], 3141, &interComm);
275        interCommLeft.push_back(interComm) ;
276        MPI_Comm_free(&intraComm) ;
277        MPI_Intercomm_merge(interComm,false, &intraComm ) ;
278      }
279      xiosGlobalComm=intraComm ; 
280      MPI_Barrier(xiosGlobalComm);
281      if (commRank==0) std::remove(serverFileName.c_str()) ;
282      MPI_Barrier(xiosGlobalComm);
283
284      CXios::setXiosComm(xiosGlobalComm) ;
285     
286    }
287
288
289    void  CServer::xiosGlobalCommByPublishing(MPI_Comm serverComm)
290    {
291        // untested, need to be tested on a true MPI-2 compliant library
292
293        // try to discover other client/server
294/*
295        // publish server name
296        char portName[MPI_MAX_PORT_NAME];
297        int ierr ;
298        int commRank ;
299        MPI_Comm_rank(serverComm, &commRank) ;
300       
301        if (commRank==0) // if root process publish name
302        { 
303          MPI_Open_port(MPI_INFO_NULL, portName);
304          MPI_Publish_name(CXios::xiosCodeId.c_str(), MPI_INFO_NULL, portName);
305        }
306
307        MPI_Comm intraComm=serverComm ;
308        MPI_Comm interComm ;
309        for(int i=0 ; i<clientsCodeId.size(); i++)
310        { 
311          MPI_Comm_accept(portName, MPI_INFO_NULL, 0, intraComm, &interComm);
312          MPI_Intercomm_merge(interComm,false, &intraComm ) ;
313        }
314*/     
315    }
316
317   /*!
318    * Root process is listening for an order sent by client to call "oasis_enddef".
319    * The root client of a compound send the order (tag 5). It is probed and received.
320    * When the order has been received from each coumpound, the server root process ping the order to the root processes of the secondary levels of servers (if any).
321    * After, it also inform (asynchronous call) other processes of the communicator that the oasis_enddef call must be done
322    */
323   
324     void CServer::listenOasisEnddef(void)
325     {
326        int flag ;
327        MPI_Status status ;
328        list<MPI_Comm>::iterator it;
329        int msg ;
330        static int nbCompound=0 ;
331        int size ;
332        static bool sent=false ;
333        static MPI_Request* allRequests ;
334        static MPI_Status* allStatus ;
335
336
337        if (sent)
338        {
339          MPI_Comm_size(intraComm_,&size) ;
340          MPI_Testall(size,allRequests, &flag, allStatus) ;
341          if (flag==true)
342          {
343            delete [] allRequests ;
344            delete [] allStatus ;
345            sent=false ;
346          }
347        }
348       
349
350        for(it=interCommLeft.begin();it!=interCommLeft.end();it++)
351        {
352           MPI_Status status ;
353           traceOff() ;
354           MPI_Iprobe(0,5,*it,&flag,&status) ;  // tags oasis_endded = 5
355           traceOn() ;
356           if (flag==true)
357           {
358              MPI_Recv(&msg,1,MPI_INT,0,5,*it,&status) ; // tags oasis_endded = 5
359              nbCompound++ ;
360              if (nbCompound==interCommLeft.size())
361              {
362                MPI_Comm_size(intraComm_,&size) ;
363                allRequests= new MPI_Request[size] ;
364                allStatus= new MPI_Status[size] ;
365                for(int i=0;i<size;i++) MPI_Isend(&msg,1,MPI_INT,i,5,intraComm_,&allRequests[i]) ; // tags oasis_endded = 5
366                sent=true ;
367              }
368           }
369        }
370}
371     
372   /*!
373    * Processes probes message from root process if oasis_enddef call must be done.
374    * When the order is received it is scheduled to be treated in a synchronized way by all server processes of the communicator
375    */
376     void CServer::listenRootOasisEnddef(void)
377     {
378       int flag ;
379       MPI_Status status ;
380       const int root=0 ;
381       int msg ;
382       static bool eventSent=false ;
383
384       if (eventSent)
385       {
386         boost::hash<string> hashString;
387         size_t hashId = hashString("oasis_enddef");
388         if (CXios::getPoolRessource()->getService(CXios::defaultServicesId,0)->getEventScheduler()->queryEvent(0,hashId))
389         {
390           CXios::getPoolRessource()->getService(CXios::defaultServicesId,0)->getEventScheduler()->popEvent() ;
391           driver_->endSynchronizedDefinition() ;
392           eventSent=false ;
393         }
394       }
395         
396       traceOff() ;
397       MPI_Iprobe(root,5,intraComm_, &flag, &status) ;
398       traceOn() ;
399       if (flag==true)
400       {
401           MPI_Recv(&msg,1,MPI_INT,root,5,intraComm_,&status) ; // tags oasis_endded = 5
402           boost::hash<string> hashString;
403           size_t hashId = hashString("oasis_enddef");
404           CXios::getPoolRessource()->getService(CXios::defaultServicesId,0)->getEventScheduler()->registerEvent(0,hashId);
405           eventSent=true ;
406       }
407     }
408
409    void CServer::finalize(void)
410    {
411      CTimer::get("XIOS").suspend() ;
412      CTimer::get("XIOS server").suspend() ;
413      delete eventScheduler ;
414
415      for (std::list<MPI_Comm>::iterator it = contextInterComms.begin(); it != contextInterComms.end(); it++)
416        MPI_Comm_free(&(*it));
417
418      for (std::list<MPI_Comm>::iterator it = contextIntraComms.begin(); it != contextIntraComms.end(); it++)
419        MPI_Comm_free(&(*it));
420
421        for (std::list<MPI_Comm>::iterator it = interCommRight.begin(); it != interCommRight.end(); it++)
422          MPI_Comm_free(&(*it));
423
424//      MPI_Comm_free(&intraComm);
425      CXios::finalizeDaemonsManager();
426      finalizeServersRessource();
427     
428      CContext::removeAllContexts() ; // free memory for related context
429         
430      CXios::getMpiGarbageCollector().release() ; // release unfree MPI ressources
431
432      if (!is_MPI_Initialized)
433      {
434        if (CXios::usingOasis) delete driver_;
435        else MPI_Finalize() ;
436      }
437      report(0)<<"Performance report : Time spent for XIOS : "<<CTimer::get("XIOS server").getCumulatedTime()<<endl  ;
438      report(0)<<"Performance report : Time spent in processing events : "<<CTimer::get("Process events").getCumulatedTime()<<endl  ;
439      report(0)<<"Performance report : Ratio : "<<CTimer::get("Process events").getCumulatedTime()/CTimer::get("XIOS server").getCumulatedTime()*100.<<"%"<<endl  ;
440      report(100)<<CTimer::getAllCumulatedTime()<<endl ;
441     
442      CWorkflowGraph::drawWorkFlowGraph_server();
443      xios::releaseStaticAllocation() ; // free memory from static allocation
444    }
445
446    /*!
447    * Open a file specified by a suffix and an extension and use it for the given file buffer.
448    * The file name will be suffix+rank+extension.
449    *
450    * \param fileName[in] protype file name
451    * \param ext [in] extension of the file
452    * \param fb [in/out] the file buffer
453    */
454    void CServer::openStream(const StdString& fileName, const StdString& ext, std::filebuf* fb)
455    {
456      StdStringStream fileNameServer;
457      int numDigit = 0;
458      int commSize = 0;
459      int commRank ;
460      int id;
461     
462      MPI_Comm_size(CXios::getGlobalComm(), &commSize);
463      MPI_Comm_rank(CXios::getGlobalComm(), &commRank);
464
465      while (commSize)
466      {
467        commSize /= 10;
468        ++numDigit;
469      }
470      id = commRank;
471
472      fileNameServer << fileName << "_" << std::setfill('0') << std::setw(numDigit) << id << ext;
473      fb->open(fileNameServer.str().c_str(), std::ios::out);
474      if (!fb->is_open())
475        ERROR("void CServer::openStream(const StdString& fileName, const StdString& ext, std::filebuf* fb)",
476              << std::endl << "Can not open <" << fileNameServer.str() << "> file to write the server log(s).");
477    }
478
479    /*!
480    * \brief Open a file stream to write the info logs
481    * Open a file stream with a specific file name suffix+rank
482    * to write the info logs.
483    * \param fileName [in] protype file name
484    */
485    void CServer::openInfoStream(const StdString& fileName)
486    {
487      std::filebuf* fb = m_infoStream.rdbuf();
488      openStream(fileName, ".out", fb);
489
490      info.write2File(fb);
491      report.write2File(fb);
492    }
493
494    //! Write the info logs to standard output
495    void CServer::openInfoStream()
496    {
497      info.write2StdOut();
498      report.write2StdOut();
499    }
500
501    //! Close the info logs file if it opens
502    void CServer::closeInfoStream()
503    {
504      if (m_infoStream.is_open()) m_infoStream.close();
505    }
506
507    /*!
508    * \brief Open a file stream to write the error log
509    * Open a file stream with a specific file name suffix+rank
510    * to write the error log.
511    * \param fileName [in] protype file name
512    */
513    void CServer::openErrorStream(const StdString& fileName)
514    {
515      std::filebuf* fb = m_errorStream.rdbuf();
516      openStream(fileName, ".err", fb);
517
518      error.write2File(fb);
519    }
520
521    //! Write the error log to standard error output
522    void CServer::openErrorStream()
523    {
524      error.write2StdErr();
525    }
526
527    //! Close the error log file if it opens
528    void CServer::closeErrorStream()
529    {
530      if (m_errorStream.is_open()) m_errorStream.close();
531    }
532
533    void CServer::launchServersRessource(MPI_Comm serverComm)
534    {
535      serversRessource_ = new CServersRessource(serverComm) ;
536    }
537
538    void  CServer::finalizeServersRessource(void) 
539    { 
540      delete serversRessource_; serversRessource_=nullptr ;
541    }
542}
Note: See TracBrowser for help on using the repository browser.