source: XIOS/dev/dev_ym/XIOS_COUPLING/src/server.cpp @ 2334

Last change on this file since 2334 was 2334, checked in by jderouillat, 2 years ago

Fix after reintroducing oasis_enddef

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