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

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

Tracking memory leak : release memory statically alocated

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.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 <cstdio>
22#include "workflow_graph.hpp"
23#include "release_static_allocation.hpp"
24
25
26
27namespace xios
28{
29    MPI_Comm CServer::intraComm ;
30    MPI_Comm CServer::serversComm_ ;
31    std::list<MPI_Comm> CServer::interCommLeft ;
32    std::list<MPI_Comm> CServer::interCommRight ;
33    std::list<MPI_Comm> CServer::contextInterComms;
34    std::list<MPI_Comm> CServer::contextIntraComms;
35    int CServer::serverLevel = 0 ;
36    int CServer::nbContexts = 0;
37    bool CServer::isRoot = false ;
38    int CServer::rank_ = INVALID_RANK;
39    StdOFStream CServer::m_infoStream;
40    StdOFStream CServer::m_errorStream;
41    map<string,CContext*> CServer::contextList ;
42    vector<int> CServer::sndServerGlobalRanks;
43    bool CServer::finished=false ;
44    bool CServer::is_MPI_Initialized ;
45    CEventScheduler* CServer::eventScheduler = 0;
46    CServersRessource* CServer::serversRessource_=nullptr ;
47
48       
49    void CServer::initialize(void)
50    {
51     
52      MPI_Comm serverComm ;
53      int initialized ;
54      MPI_Initialized(&initialized) ;
55      if (initialized) is_MPI_Initialized=true ;
56      else is_MPI_Initialized=false ;
57      MPI_Comm globalComm=CXios::getGlobalComm() ;
58
59      /////////////////////////////////////////
60      ///////////// PART 1 ////////////////////
61      /////////////////////////////////////////
62      CTimer::get("XIOS").resume() ;
63      CTimer::get("XIOS initialize").resume() ;
64      // don't use OASIS
65      if (!CXios::usingOasis)
66      {
67        if (!is_MPI_Initialized) MPI_Init(NULL, NULL);
68       
69        // split the global communicator
70        // get hash from all model to attribute a unique color (int) and then split to get client communicator
71        // every mpi process of globalComm (MPI_COMM_WORLD) must participate
72         
73        int commRank, commSize ;
74        MPI_Comm_rank(globalComm,&commRank) ;
75        MPI_Comm_size(globalComm,&commSize) ;
76
77        std::hash<string> hashString ;
78        size_t hashServer=hashString(CXios::xiosCodeId) ;
79         
80        size_t* hashAll = new size_t[commSize] ;
81        MPI_Allgather(&hashServer,1,MPI_SIZE_T,hashAll,1,MPI_SIZE_T,globalComm) ;
82         
83        int color=0 ;
84        map<size_t,int> listHash ;
85        for(int i=0 ; i<=commSize ; i++) 
86          if (listHash.count(hashAll[i])==0) 
87          {
88            listHash[hashAll[i]]=color ;
89            color=color+1 ;
90          }
91        color=listHash[hashServer] ;
92        delete[] hashAll ;
93
94        MPI_Comm_split(globalComm, color, commRank, &serverComm) ;
95      }
96      else // using OASIS
97      {
98        if (!is_MPI_Initialized) oasis_init(CXios::xiosCodeId);
99
100        oasis_get_localcomm(serverComm);
101      }
102 
103      /////////////////////////////////////////
104      ///////////// PART 2 ////////////////////
105      /////////////////////////////////////////
106     
107
108      // Create the XIOS communicator for every process which is related
109      // to XIOS, as well on client side as on server side
110      MPI_Comm xiosGlobalComm ;
111      string strIds=CXios::getin<string>("clients_code_id","") ;
112      vector<string> clientsCodeId=splitRegex(strIds,"\\s*,\\s*") ;
113      if (strIds.empty())
114      {
115        // no code Ids given, suppose XIOS initialisation is global           
116        int commRank, commGlobalRank, serverLeader, clientLeader,serverRemoteLeader,clientRemoteLeader ;
117        MPI_Comm splitComm,interComm ;
118        MPI_Comm_rank(globalComm,&commGlobalRank) ;
119        MPI_Comm_split(globalComm, 1, commGlobalRank, &splitComm) ;
120        MPI_Comm_rank(splitComm,&commRank) ;
121        if (commRank==0) serverLeader=commGlobalRank ;
122        else serverLeader=0 ;
123        clientLeader=0 ;
124        MPI_Allreduce(&clientLeader,&clientRemoteLeader,1,MPI_INT,MPI_SUM,globalComm) ;
125        MPI_Allreduce(&serverLeader,&serverRemoteLeader,1,MPI_INT,MPI_SUM,globalComm) ;
126        MPI_Intercomm_create(splitComm, 0, globalComm, clientRemoteLeader,1341,&interComm) ;
127        MPI_Intercomm_merge(interComm,false,&xiosGlobalComm) ;
128        CXios::setXiosComm(xiosGlobalComm) ;
129      }
130      else
131      {
132
133        xiosGlobalCommByFileExchange(serverComm) ;
134
135      }
136     
137      /////////////////////////////////////////
138      ///////////// PART 4 ////////////////////
139      //  create servers intra communicator  //
140      /////////////////////////////////////////
141     
142      int commRank ;
143      MPI_Comm_rank(CXios::getXiosComm(), &commRank) ;
144      MPI_Comm_split(CXios::getXiosComm(),true,commRank,&serversComm_) ;
145     
146      CXios::setUsingServer() ;
147
148      /////////////////////////////////////////
149      ///////////// PART 5 ////////////////////
150      //       redirect files output         //
151      /////////////////////////////////////////
152     
153      CServer::openInfoStream(CXios::serverFile);
154      CServer::openErrorStream(CXios::serverFile);
155
156      /////////////////////////////////////////
157      ///////////// PART 4 ////////////////////
158      /////////////////////////////////////////
159
160      CXios::launchDaemonsManager(true) ;
161     
162      /////////////////////////////////////////
163      ///////////// PART 5 ////////////////////
164      /////////////////////////////////////////
165
166      // create the services
167
168      auto ressourcesManager=CXios::getRessourcesManager() ;
169      auto servicesManager=CXios::getServicesManager() ;
170      auto contextsManager=CXios::getContextsManager() ;
171      auto daemonsManager=CXios::getDaemonsManager() ;
172      auto serversRessource=CServer::getServersRessource() ;
173
174      if (serversRessource->isServerLeader())
175      {
176        int nbRessources = ressourcesManager->getRessourcesSize() ;
177        if (!CXios::usingServer2)
178        {
179          ressourcesManager->createPool(CXios::defaultPoolId, nbRessources) ;
180          servicesManager->createServices(CXios::defaultPoolId, CXios::defaultServerId, CServicesManager::IO_SERVER,nbRessources,1) ;
181        }
182        else
183        {
184          int nprocsServer = nbRessources*CXios::ratioServer2/100.;
185          int nprocsGatherer = nbRessources - nprocsServer ;
186         
187          int nbPoolsServer2 = CXios::nbPoolsServer2 ;
188          if (nbPoolsServer2 == 0) nbPoolsServer2 = nprocsServer;
189          ressourcesManager->createPool(CXios::defaultPoolId, nbRessources) ;
190          servicesManager->createServices(CXios::defaultPoolId,  CXios::defaultGathererId, CServicesManager::GATHERER, nprocsGatherer, 1) ;
191          servicesManager->createServices(CXios::defaultPoolId,  CXios::defaultServerId, CServicesManager::OUT_SERVER, nprocsServer, nbPoolsServer2) ;
192        }
193      }
194      CTimer::get("XIOS initialize").suspend() ;
195
196      /////////////////////////////////////////
197      ///////////// PART 5 ////////////////////
198      /////////////////////////////////////////
199      // loop on event loop
200
201      bool finished=false ;
202      CTimer::get("XIOS event loop").resume() ;
203
204      while (!finished)
205      {
206        finished=daemonsManager->eventLoop() ;
207      }
208      CTimer::get("XIOS event loop").suspend() ;
209
210      // Delete CContext
211      //CObjectTemplate<CContext>::cleanStaticDataStructure();
212    }
213
214
215
216
217
218    void  CServer::xiosGlobalCommByFileExchange(MPI_Comm serverComm)
219    {
220       
221      MPI_Comm globalComm=CXios::getGlobalComm() ;
222      MPI_Comm xiosGlobalComm ;
223     
224      string strIds=CXios::getin<string>("clients_code_id","") ;
225      vector<string> clientsCodeId=splitRegex(strIds,"\\s*,\\s*") ;
226     
227      int commRank, globalRank ;
228      MPI_Comm_rank(serverComm, &commRank) ;
229      MPI_Comm_rank(globalComm, &globalRank) ;
230      string serverFileName("__xios_publisher::"+CXios::xiosCodeId+"__to_remove__") ;
231
232      if (commRank==0) // if root process publish name
233      { 
234        std::ofstream ofs (serverFileName, std::ofstream::out);
235        ofs<<globalRank ;
236        ofs.close();
237      }
238       
239      vector<int> clientsRank(clientsCodeId.size()) ;
240      for(int i=0;i<clientsRank.size();i++)
241      {
242        std::ifstream ifs ;
243        string fileName=("__xios_publisher::"+clientsCodeId[i]+"__to_remove__") ;
244        do
245        {
246          ifs.clear() ;
247          ifs.open(fileName, std::ifstream::in) ;
248        } while (ifs.fail()) ;
249        ifs>>clientsRank[i] ;
250        ifs.close() ; 
251      }
252
253      MPI_Comm intraComm ;
254      MPI_Comm_dup(serverComm,&intraComm) ;
255      MPI_Comm interComm ;
256      for(int i=0 ; i<clientsRank.size(); i++)
257      { 
258        MPI_Intercomm_create(intraComm, 0, globalComm, clientsRank[i], 3141, &interComm);
259        MPI_Comm_free(&intraComm) ;
260        MPI_Intercomm_merge(interComm,false, &intraComm ) ;
261      }
262      xiosGlobalComm=intraComm ; 
263      MPI_Barrier(xiosGlobalComm);
264      if (commRank==0) std::remove(serverFileName.c_str()) ;
265      MPI_Barrier(xiosGlobalComm);
266
267      CXios::setXiosComm(xiosGlobalComm) ;
268     
269    }
270
271
272    void  CServer::xiosGlobalCommByPublishing(MPI_Comm serverComm)
273    {
274        // untested, need to be tested on a true MPI-2 compliant library
275
276        // try to discover other client/server
277/*
278        // publish server name
279        char portName[MPI_MAX_PORT_NAME];
280        int ierr ;
281        int commRank ;
282        MPI_Comm_rank(serverComm, &commRank) ;
283       
284        if (commRank==0) // if root process publish name
285        { 
286          MPI_Open_port(MPI_INFO_NULL, portName);
287          MPI_Publish_name(CXios::xiosCodeId.c_str(), MPI_INFO_NULL, portName);
288        }
289
290        MPI_Comm intraComm=serverComm ;
291        MPI_Comm interComm ;
292        for(int i=0 ; i<clientsCodeId.size(); i++)
293        { 
294          MPI_Comm_accept(portName, MPI_INFO_NULL, 0, intraComm, &interComm);
295          MPI_Intercomm_merge(interComm,false, &intraComm ) ;
296        }
297*/     
298    }
299
300
301    void CServer::finalize(void)
302    {
303      CTimer::get("XIOS").suspend() ;
304     
305      delete eventScheduler ;
306
307      for (std::list<MPI_Comm>::iterator it = contextInterComms.begin(); it != contextInterComms.end(); it++)
308        MPI_Comm_free(&(*it));
309
310      for (std::list<MPI_Comm>::iterator it = contextIntraComms.begin(); it != contextIntraComms.end(); it++)
311        MPI_Comm_free(&(*it));
312
313        for (std::list<MPI_Comm>::iterator it = interCommRight.begin(); it != interCommRight.end(); it++)
314          MPI_Comm_free(&(*it));
315
316//      MPI_Comm_free(&intraComm);
317      CXios::finalizeDaemonsManager();
318      finalizeServersRessource();
319     
320      CContext::removeAllContexts() ; // free memory for related context
321         
322      if (!is_MPI_Initialized)
323      {
324        if (CXios::usingOasis) oasis_finalize();
325        else MPI_Finalize() ;
326      }
327      report(0)<<"Performance report : Time spent for XIOS : "<<CTimer::get("XIOS server").getCumulatedTime()<<endl  ;
328      report(0)<<"Performance report : Time spent in processing events : "<<CTimer::get("Process events").getCumulatedTime()<<endl  ;
329      report(0)<<"Performance report : Ratio : "<<CTimer::get("Process events").getCumulatedTime()/CTimer::get("XIOS server").getCumulatedTime()*100.<<"%"<<endl  ;
330      report(100)<<CTimer::getAllCumulatedTime()<<endl ;
331     
332      CWorkflowGraph::drawWorkFlowGraph_server();
333      xios::releaseStaticAllocation() ; // free memory from static allocation
334    }
335
336    /*!
337    * Open a file specified by a suffix and an extension and use it for the given file buffer.
338    * The file name will be suffix+rank+extension.
339    *
340    * \param fileName[in] protype file name
341    * \param ext [in] extension of the file
342    * \param fb [in/out] the file buffer
343    */
344    void CServer::openStream(const StdString& fileName, const StdString& ext, std::filebuf* fb)
345    {
346      StdStringStream fileNameServer;
347      int numDigit = 0;
348      int commSize = 0;
349      int commRank ;
350      int id;
351     
352      MPI_Comm_size(CXios::getGlobalComm(), &commSize);
353      MPI_Comm_rank(CXios::getGlobalComm(), &commRank);
354
355      while (commSize)
356      {
357        commSize /= 10;
358        ++numDigit;
359      }
360      id = commRank;
361
362      fileNameServer << fileName << "_" << std::setfill('0') << std::setw(numDigit) << id << ext;
363      fb->open(fileNameServer.str().c_str(), std::ios::out);
364      if (!fb->is_open())
365        ERROR("void CServer::openStream(const StdString& fileName, const StdString& ext, std::filebuf* fb)",
366              << std::endl << "Can not open <" << fileNameServer.str() << "> file to write the server log(s).");
367    }
368
369    /*!
370    * \brief Open a file stream to write the info logs
371    * Open a file stream with a specific file name suffix+rank
372    * to write the info logs.
373    * \param fileName [in] protype file name
374    */
375    void CServer::openInfoStream(const StdString& fileName)
376    {
377      std::filebuf* fb = m_infoStream.rdbuf();
378      openStream(fileName, ".out", fb);
379
380      info.write2File(fb);
381      report.write2File(fb);
382    }
383
384    //! Write the info logs to standard output
385    void CServer::openInfoStream()
386    {
387      info.write2StdOut();
388      report.write2StdOut();
389    }
390
391    //! Close the info logs file if it opens
392    void CServer::closeInfoStream()
393    {
394      if (m_infoStream.is_open()) m_infoStream.close();
395    }
396
397    /*!
398    * \brief Open a file stream to write the error log
399    * Open a file stream with a specific file name suffix+rank
400    * to write the error log.
401    * \param fileName [in] protype file name
402    */
403    void CServer::openErrorStream(const StdString& fileName)
404    {
405      std::filebuf* fb = m_errorStream.rdbuf();
406      openStream(fileName, ".err", fb);
407
408      error.write2File(fb);
409    }
410
411    //! Write the error log to standard error output
412    void CServer::openErrorStream()
413    {
414      error.write2StdErr();
415    }
416
417    //! Close the error log file if it opens
418    void CServer::closeErrorStream()
419    {
420      if (m_errorStream.is_open()) m_errorStream.close();
421    }
422
423    void CServer::launchServersRessource(MPI_Comm serverComm)
424    {
425      serversRessource_ = new CServersRessource(serverComm) ;
426    }
427
428    void  CServer::finalizeServersRessource(void) 
429    { 
430      delete serversRessource_; serversRessource_=nullptr ;
431    }
432}
Note: See TracBrowser for help on using the repository browser.