source: XIOS3/branches/xios-3.0-beta/src/client.cpp @ 2427

Last change on this file since 2427 was 2427, checked in by jderouillat, 17 months ago

Backport the system to log the memory consumption (commit ID [2418-2420,2425-2426])

  • 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: 20.9 KB
Line 
1#include "globalScopeData.hpp"
2#include "xios_spl.hpp"
3#include "cxios.hpp"
4#include "client.hpp"
5#include <boost/functional/hash.hpp>
6#include "type.hpp"
7#include "context.hpp"
8#include "context_client.hpp"
9#include "oasis_cinterface.hpp"
10#include "mpi.hpp"
11#include "timer.hpp"
12#include "buffer_client.hpp"
13#include "string_tools.hpp"
14#include "ressources_manager.hpp"
15#include "services_manager.hpp"
16#include <functional>
17#include <cstdio>
18#include "workflow_graph.hpp"
19#include "release_static_allocation.hpp"
20#include "mem_checker.hpp"
21
22namespace xios
23{
24
25    const double serverPublishDefaultTimeout=10;
26
27    MPI_Comm CClient::intraComm_ ;
28    MPI_Comm CClient::interComm_ ;
29    MPI_Comm CClient::clientsComm_ ;
30
31    std::list<MPI_Comm> CClient::contextInterComms;
32    int CClient::serverLeader ;
33    bool CClient::is_MPI_Initialized ;
34    int CClient::rank_ = INVALID_RANK;
35    StdOFStream CClient::m_infoStream;
36    StdOFStream CClient::m_errorStream;
37    CPoolRessource* CClient::poolRessource_=nullptr ;
38
39    MPI_Comm& CClient::getInterComm(void)   { return (interComm_); }
40     
41///---------------------------------------------------------------
42/*!
43 * \fn void CClient::initialize(const string& codeId, MPI_Comm& localComm, MPI_Comm& returnComm)
44 * Function creates intraComm (CClient::intraComm) for client group with id=codeId and interComm (CClient::interComm) between client and server groups.
45 * \param [in] codeId identity of context.
46 * \param [in/out] localComm local communicator.
47 * \param [in/out] returnComm (intra)communicator of client group.
48 */
49
50    void CClient::initialize(const string& codeId, MPI_Comm& localComm, MPI_Comm& returnComm)
51    {
52   
53       MPI_Comm clientComm ;
54      // initialize MPI if not initialized
55      int initialized ;
56      MPI_Initialized(&initialized) ;
57      if (initialized) is_MPI_Initialized=true ;
58      else is_MPI_Initialized=false ;
59     
60      MPI_Comm globalComm=CXios::getGlobalComm() ;
61
62      /////////////////////////////////////////
63      ///////////// PART 1 ////////////////////
64      /////////////////////////////////////////
65     
66
67      // localComm isn't given
68      if (localComm == MPI_COMM_NULL)
69      {
70         
71        // don't use OASIS
72        if (!CXios::usingOasis)
73        {
74
75          if (!is_MPI_Initialized)
76          {
77            MPI_Init(NULL, NULL);
78          }
79          CTimer::get("XIOS").resume() ;
80          CTimer::get("XIOS init/finalize",false).resume() ;
81         
82          // split the global communicator
83          // get hash from all model to attribute a unique color (int) and then split to get client communicator
84          // every mpi process of globalComm (MPI_COMM_WORLD) must participate
85
86          int commRank, commSize ;
87          MPI_Comm_rank(globalComm,&commRank) ;
88          MPI_Comm_size(globalComm,&commSize) ;
89
90          std::hash<string> hashString ;
91          size_t hashClient=hashString(codeId) ;
92         
93          size_t* hashAll = new size_t[commSize] ;
94          MPI_Allgather(&hashClient,1,MPI_SIZE_T,hashAll,1,MPI_SIZE_T,globalComm) ;
95         
96          int color=0 ;
97          map<size_t,int> listHash ;
98          for(int i=0 ; i<=commSize ; i++) 
99            if (listHash.count(hashAll[i])==0) 
100            {
101              listHash[hashAll[i]]=color ;
102              color=color+1 ;
103            }
104            color=listHash[hashClient] ;
105          delete[] hashAll ;
106
107          MPI_Comm_split(globalComm, color, commRank, &clientComm) ;
108        }
109        else
110        {
111          ERROR("void CClient::initialize(const string& codeId, MPI_Comm& localComm, MPI_Comm& returnComm)", <<"OASIS usage is set. In these conditions, XIOS initialization needs the local_comm created by OASIS."<<endl) ;
112        }
113      }
114      else // localComm is given
115      {
116        MPI_Comm_dup(localComm,&clientComm) ;
117        MPI_Comm_dup(localComm,&intraComm_) ;
118
119        if (CXios::usingServer)
120        {
121          MPI_Comm_rank(intraComm_,&rank_) ;
122        }
123
124      }
125     
126     
127      /////////////////////////////////////////
128      ///////////// PART 2 ////////////////////
129      /////////////////////////////////////////
130     
131
132      // Create the XIOS communicator for every process which is related
133      // to XIOS, as well on client side as on server side
134     
135      MPI_Comm xiosGlobalComm ;
136      string strIds=CXios::getin<string>("clients_code_id","") ;
137      vector<string> clientsCodeId=splitRegex(strIds,"\\s*,\\s*") ;
138      if (strIds.empty())
139      {
140         // no code Ids given, suppose XIOS initialisation is global           
141         int commRank, commGlobalRank, serverLeader, clientLeader,serverRemoteLeader,clientRemoteLeader ;
142         MPI_Comm splitComm,interComm ;
143         MPI_Comm_rank(globalComm,&commGlobalRank) ;
144         MPI_Comm_split(globalComm, 0, commGlobalRank, &splitComm) ;
145         int splitCommSize, globalCommSize ;
146       
147         MPI_Comm_size(splitComm,&splitCommSize) ;
148         MPI_Comm_size(globalComm,&globalCommSize) ;
149         if (splitCommSize==globalCommSize) // no server
150         {
151           MPI_Comm_dup(globalComm,&xiosGlobalComm) ;
152           CXios::setXiosComm(xiosGlobalComm) ;
153         }
154         else
155         {
156           MPI_Comm_rank(splitComm,&commRank) ;
157           if (commRank==0) clientLeader=commGlobalRank ;
158           else clientLeader=0 ;
159           serverLeader=0 ;
160           MPI_Allreduce(&clientLeader,&clientRemoteLeader,1,MPI_INT,MPI_SUM,globalComm) ;
161           MPI_Allreduce(&serverLeader,&serverRemoteLeader,1,MPI_INT,MPI_SUM,globalComm) ;
162           MPI_Intercomm_create(splitComm, 0, globalComm, serverRemoteLeader,1341,&interComm) ;
163           MPI_Intercomm_merge(interComm,true,&xiosGlobalComm) ;
164           CXios::setXiosComm(xiosGlobalComm) ;
165         }
166      }
167      else
168      {
169
170        xiosGlobalCommByFileExchange(clientComm, codeId) ;
171     
172      }
173
174      int commRank ;
175      MPI_Comm_rank(CXios::getXiosComm(), &commRank) ;
176      MPI_Comm_split(CXios::getXiosComm(),false,commRank, &clientsComm_) ;
177     
178      // is using server or not ?
179      int xiosCommSize, clientsCommSize ; 
180      MPI_Comm_size(CXios::getXiosComm(), &xiosCommSize) ;
181      MPI_Comm_size(clientsComm_, &clientsCommSize) ;
182      if (xiosCommSize==clientsCommSize) CXios::setUsingServer() ;
183      else CXios::setNotUsingServer() ;
184
185      /////////////////////////////////////////
186      ///////////// PART 3 ////////////////////
187      /////////////////////////////////////////
188     
189      CXios::launchDaemonsManager(false) ;
190      poolRessource_ = new CPoolRessource(clientComm, codeId) ;
191
192      /////////////////////////////////////////
193      ///////////// PART 4 ////////////////////
194      /////////////////////////////////////////     
195     
196      returnComm = clientComm ;
197    }
198
199
200    void CClient::xiosGlobalCommByFileExchange(MPI_Comm clientComm, const string& codeId)
201    {
202 
203      MPI_Comm globalComm=CXios::getGlobalComm() ;
204      MPI_Comm xiosGlobalComm ;
205
206      string strIds=CXios::getin<string>("clients_code_id","") ;
207      vector<string> clientsCodeId=splitRegex(strIds,"\\s*,\\s*") ;
208
209      int commRank, globalRank, clientRank, serverRank ;
210      MPI_Comm_rank(clientComm, &commRank) ;
211      MPI_Comm_rank(globalComm, &globalRank) ;
212      string clientFileName("__xios_publisher::"+codeId+"__to_remove__") ;
213           
214      int error ;
215
216      if (commRank==0) // if root process publish name
217      { 
218        std::ofstream ofs (clientFileName, std::ofstream::out);
219        ofs<<globalRank ;
220        ofs.close();
221       
222  // get server root rank
223
224        std::ifstream ifs ;
225        string fileName=("__xios_publisher::"+CXios::xiosCodeId+"__to_remove__") ;
226     
227        double timeout = CXios::getin<double>("server_puplish_timeout",serverPublishDefaultTimeout) ;
228        double time ;
229         
230        do
231        {
232          CTimer::get("server_publish_timeout").resume() ; 
233          ifs.clear() ;
234          ifs.open(fileName, std::ifstream::in) ;
235          CTimer::get("server_publish_timeout").suspend() ;
236        } while (ifs.fail() && CTimer::get("server_publish_timeout").getCumulatedTime()<timeout) ;
237       
238        if (CTimer::get("server_publish_timeout").getCumulatedTime()>=timeout || ifs.fail())
239        {
240          ifs.clear() ;
241          ifs.close() ;
242          ifs.clear() ;
243          error=true ;           
244        }
245        else 
246        {
247          ifs>>serverRank ;
248          ifs.close() ;
249          error=false ;
250        } 
251
252      } 
253      MPI_Bcast(&error,1,MPI_INT,0,clientComm) ;
254     
255      if (error==false)  // you have a server
256      {
257        MPI_Comm intraComm ;
258        MPI_Comm_dup(clientComm,&intraComm) ;
259        MPI_Comm interComm ;
260       
261        int pos=0 ;
262        for(int i=0 ; codeId!=clientsCodeId[i]; i++) pos=pos+1 ;
263
264        bool high=true ;
265        for(int i=pos ; i<clientsCodeId.size(); i++)
266        { 
267          MPI_Intercomm_create(intraComm, 0, globalComm, serverRank, 3141, &interComm);
268          MPI_Comm_free(&intraComm) ;
269          MPI_Intercomm_merge(interComm,high, &intraComm ) ;
270          high=false ;
271          if (i==pos) {
272            interComm_=interComm ;
273          }
274        }
275        xiosGlobalComm=intraComm ;
276      }
277      else  // no server detected
278      {
279        vector<int> clientsRank(clientsCodeId.size()) ;
280       
281        if (commRank==0)
282        { 
283          for(int i=0;i<clientsRank.size();i++)
284          {
285            std::ifstream ifs ;
286            string fileName=("__xios_publisher::"+clientsCodeId[i]+"__to_remove__") ;
287            do
288            {
289              ifs.clear() ;
290              ifs.open(fileName, std::ifstream::in) ;
291            } while (ifs.fail()) ;
292            ifs>>clientsRank[i] ;
293            ifs.close() ;
294          }
295        }
296         
297        int client ;
298        MPI_Comm intraComm ;
299        MPI_Comm_dup(clientComm,&intraComm) ;
300        MPI_Comm interComm ;
301       
302        int pos=0 ;
303        for(int i=0 ; codeId!=clientsCodeId[i]; i++) pos=pos+1 ;
304       
305        bool high=true ;
306        for(int i=pos+1 ; i<clientsCodeId.size(); i++)
307        { 
308          if (codeId==clientsCodeId[0])   // first model play the server rule
309          {         
310            MPI_Intercomm_create(intraComm, 0, globalComm, clientsRank[i], 3141, &interComm);
311            MPI_Intercomm_merge(interComm,false, &intraComm ) ;
312          }
313          else
314          {         
315            MPI_Intercomm_create(intraComm, 0, globalComm, clientsRank[0], 3141, &interComm);
316            MPI_Intercomm_merge(interComm,high, &intraComm ) ;
317            high=false ;
318          }
319          if (i==pos) {
320            interComm_=interComm ; // NOT TESTED !
321          }
322        }
323        xiosGlobalComm=intraComm ;
324      }
325
326      MPI_Barrier(xiosGlobalComm);
327      if (commRank==0) std::remove(clientFileName.c_str()) ;         
328      MPI_Barrier(xiosGlobalComm);
329 
330      CXios::setXiosComm(xiosGlobalComm) ;
331
332      MPI_Comm commUnfree ;
333      MPI_Comm_dup(clientComm, &commUnfree ) ;
334 
335    }
336
337// to check on other architecture
338    void CClient::xiosGlobalCommByPublishing(MPI_Comm clientComm, const string& codeId)
339    {
340
341      // untested. need to be developped an a true MPI compliant library
342
343/*
344        // try to discover other client/server
345        // do you have a xios server ?
346        char portName[MPI_MAX_PORT_NAME];
347        int ierr ;
348        int commRank ;
349        MPI_Comm_rank(clientComm,&commRank) ;
350
351        MPI_Barrier(globalComm) ;
352        if (commRank==0)
353        {
354             
355          MPI_Comm_set_errhandler(MPI_COMM_WORLD, MPI_ERRORS_RETURN );
356          const char* serviceName=CXios::xiosCodeId.c_str() ;
357          ierr=MPI_Lookup_name(CXios::xiosCodeId.c_str(), MPI_INFO_NULL, portName);
358          MPI_Comm_set_errhandler(MPI_COMM_WORLD, MPI_ERRORS_ARE_FATAL );
359        }
360        ierr=MPI_SUCCESS ;
361        MPI_Bcast(&ierr,1,MPI_INT,0,clientComm) ;
362
363        if (ierr==MPI_SUCCESS) // you have a server
364        { 
365          MPI_Comm intraComm=clientComm ;
366          MPI_Comm interComm ;
367          for(int i=0 ; i<clientsCodeId.size(); i++)
368          { 
369            MPI_Comm_connect(portName, MPI_INFO_NULL, 0, intraComm, &interComm);
370            MPI_Intercomm_merge(interComm, true, &intraComm ) ;
371          }
372          xiosGlobalComm=intraComm ;
373        }
374        else  // you don't have any server
375        {
376          if (codeId==clientsCodeId[0]) // first code will publish his name
377          {
378
379            if (commRank==0) // if root process publish name
380            { 
381              MPI_Open_port(MPI_INFO_NULL, portName);
382              MPI_Publish_name(CXios::xiosCodeId.c_str(), MPI_INFO_NULL, portName);
383            }
384
385            MPI_Comm intraComm=clientComm ;
386            MPI_Comm interComm ;
387            for(int i=0 ; i<clientsCodeId.size()-1; i++)
388            { 
389              MPI_Comm_accept(portName, MPI_INFO_NULL, 0, intraComm, &interComm);
390              MPI_Intercomm_merge(interComm,false, &intraComm ) ;
391            }
392          }
393          else  // other clients are connecting to the first one
394          {
395            if (commRank==0)
396            {
397
398              MPI_Comm_set_errhandler(MPI_COMM_WORLD, MPI_ERRORS_RETURN );
399              ierr=MPI_Lookup_name(CXios::xiosCodeId.c_str(), MPI_INFO_NULL, portName);
400              MPI_Comm_set_errhandler(MPI_COMM_WORLD, MPI_ERRORS_ARE_FATAL );
401             }
402
403            MPI_Bcast(&ierr,1,MPI_INT,0,clientComm) ;
404
405            if (ierr==MPI_SUCCESS) // you can connect
406            { 
407              MPI_Comm intraComm=clientComm ;
408              MPI_Comm interComm ;
409              for(int i=0 ; i<clientsCodeId.size()-1; i++)
410              { 
411                MPI_Comm_connect(portName, MPI_INFO_NULL, 0, intraComm, &interComm);
412                MPI_Intercomm_merge(interComm, true, &intraComm ) ;
413              }
414              xiosGlobalComm=intraComm ;
415            }
416          }
417        } 
418      */
419    }
420
421
422///---------------------------------------------------------------
423/*!
424 * \fn void CClient::registerContext(const string& id, MPI_Comm contextComm)
425 * \brief Sends a request to create a context to server. Creates client/server contexts.
426 * \param [in] id id of context.
427 * \param [in] contextComm.
428 * Function is only called by client.
429 */
430    void CClient::registerContext(const string& id, MPI_Comm contextComm)
431    {
432      int commRank, commSize ;
433      MPI_Comm_rank(contextComm,&commRank) ;
434      MPI_Comm_size(contextComm,&commSize) ;
435
436      getPoolRessource()->createService(contextComm, id, 0, CServicesManager::CLIENT, 1) ;
437      getPoolRessource()->createService(contextComm, id+"_"+CXios::defaultServerId, 0, CServicesManager::IO_SERVER, 1) ;
438
439      if (commRank==0) while (!CXios::getServicesManager()->hasService(getPoolRessource()->getId(), id, 0)) { CXios::getDaemonsManager()->eventLoop();}
440
441      if (commRank==0) CXios::getContextsManager()->createServerContext(getPoolRessource()->getId(), id, 0, id) ;
442      int type=CServicesManager::CLIENT ;
443      string name = CXios::getContextsManager()->getServerContextName(getPoolRessource()->getId(), id, 0, type, id) ;
444      double time ;
445      double lastTime=0 ;
446      double latency=0 ;
447      bool out=false ;
448      while (!out)
449      {
450        time=MPI_Wtime() ;
451        if (time-lastTime > latency) 
452        {
453          out=CXios::getContextsManager()->hasContext(name, contextComm);
454          lastTime=time ;
455        }
456        if (!out) CXios::getDaemonsManager()->eventLoop() ;
457      }
458
459    }
460
461
462
463/*!
464 * \fn void CClient::callOasisEnddef(void)
465 * \brief Send the order to the servers to call "oasis_enddef". It must be done by each compound of models before calling oasis_enddef on client side
466 * Function is only called by client.
467 */
468    void CClient::callOasisEnddef(void)
469    {
470      bool oasisEnddef=CXios::getin<bool>("call_oasis_enddef",true) ;
471      if (!oasisEnddef) ERROR("void CClient::callOasisEnddef(void)", <<"Function xios_oasis_enddef called but variable <call_oasis_enddef> is set to false."<<endl
472                                                                     <<"Variable <call_oasis_enddef> must be set to true"<<endl) ;
473      if (!CXios::isClient) // != isServer (change recently )
474      // Attached mode
475      {
476        // nothing to do   
477      }
478      else
479      {
480        int rank ;
481        int msg=0 ;
482
483        MPI_Comm_rank(intraComm_,&rank) ;
484        if (rank==0) 
485        {
486          MPI_Send(&msg,1,MPI_INT,0,5,interComm_) ; // tags oasis_endded = 5
487        }
488
489      }
490    }
491
492    void CClient::finalize(void)
493    {
494     
495      MPI_Barrier(clientsComm_) ;
496      int commRank ;
497      MPI_Comm_rank(clientsComm_, &commRank) ;
498      if (commRank==0) CXios::getRessourcesManager()->finalize() ;
499     
500      CTimer::get("XIOS init/finalize",false).suspend() ;
501      CTimer::get("XIOS").suspend() ;
502      CXios::finalizeDaemonsManager() ;
503      finalizePoolRessource() ;
504      CContext::removeAllContexts() ; // free memory for related context
505
506      CXios::getMpiGarbageCollector().release() ; // release unfree MPI ressources
507      if (!is_MPI_Initialized)
508      {
509        if (!CXios::usingOasis) MPI_Finalize() ;
510      }
511     
512      info(20) << "Client side context is finalized"<<endl ;
513      report(0) <<" Performance report : Whole time from XIOS init and finalize: "<< CTimer::get("XIOS init/finalize").getCumulatedTime()<<" s"<<endl ;
514      report(0) <<" Performance report : total time spent for XIOS : "<< CTimer::get("XIOS").getCumulatedTime()<<" s"<<endl ;
515      report(0)<< " Performance report : time spent for waiting free buffer : "<< CTimer::get("Blocking time").getCumulatedTime()<<" s"<<endl ;
516      report(0)<< " Performance report : Ratio : "<< CTimer::get("Blocking time").getCumulatedTime()/CTimer::get("XIOS init/finalize").getCumulatedTime()*100.<<" %"<<endl ;
517      report(0)<< " Performance report : This ratio must be close to zero. Otherwise it may be usefull to increase buffer size or numbers of server"<<endl ;
518//      report(0)<< " Memory report : Current buffer_size : "<<CXios::bufferSize<<endl ;
519      report(0)<< " Memory report : Minimum buffer size required : " << CClientBuffer::maxRequestSize << " bytes" << endl ;
520      report(0)<< " Memory report : increasing it by a factor will increase performance, depending of the volume of data wrote in file at each time step of the file"<<endl ;
521      report(100)<<CTimer::getAllCumulatedTime()<<endl ;
522      report(100)<<CMemChecker::getAllCumulatedMem()<<endl ;
523      CWorkflowGraph::drawWorkFlowGraph_client();
524
525      xios::releaseStaticAllocation() ;
526
527    }
528   
529    void CClient::finalizePoolRessource() 
530    { 
531      delete poolRessource_ ; poolRessource_=nullptr ;
532    }
533
534    /*!
535    * Return global rank without oasis and current rank in model intraComm in case of oasis
536    */
537   int CClient::getRank()
538   {
539     return rank_;
540   }
541
542    /*!
543    * Open a file specified by a suffix and an extension and use it for the given file buffer.
544    * The file name will be suffix+rank+extension.
545    *
546    * \param fileName[in] protype file name
547    * \param ext [in] extension of the file
548    * \param fb [in/out] the file buffer
549    */
550    void CClient::openStream(const StdString& fileName, const StdString& ext, std::filebuf* fb)
551    {
552      StdStringStream fileNameClient;
553      int numDigit = 0;
554      int size = 0;
555      int rank;
556      MPI_Comm_size(CXios::getGlobalComm(), &size);
557      MPI_Comm_rank(CXios::getGlobalComm(),&rank);
558      while (size)
559      {
560        size /= 10;
561        ++numDigit;
562      }
563
564      fileNameClient << fileName << "_" << std::setfill('0') << std::setw(numDigit) << rank << ext;
565
566      fb->open(fileNameClient.str().c_str(), std::ios::out);
567      if (!fb->is_open())
568        ERROR("void CClient::openStream(const StdString& fileName, const StdString& ext, std::filebuf* fb)",
569              << std::endl << "Can not open <" << fileNameClient.str() << "> file to write the client log(s).");
570    }
571
572    /*!
573    * \brief Open a file stream to write the info logs
574    * Open a file stream with a specific file name suffix+rank
575    * to write the info logs.
576    * \param fileName [in] protype file name
577    */
578    void CClient::openInfoStream(const StdString& fileName)
579    {
580      std::filebuf* fb = m_infoStream.rdbuf();
581      openStream(fileName, ".out", fb);
582
583      info.write2File(fb);
584      report.write2File(fb);
585    }
586
587    //! Write the info logs to standard output
588    void CClient::openInfoStream()
589    {
590      info.write2StdOut();
591      report.write2StdOut();
592    }
593
594    //! Close the info logs file if it opens
595    void CClient::closeInfoStream()
596    {
597      if (m_infoStream.is_open()) m_infoStream.close();
598    }
599
600    /*!
601    * \brief Open a file stream to write the error log
602    * Open a file stream with a specific file name suffix+rank
603    * to write the error log.
604    * \param fileName [in] protype file name
605    */
606    void CClient::openErrorStream(const StdString& fileName)
607    {
608      std::filebuf* fb = m_errorStream.rdbuf();
609      openStream(fileName, ".err", fb);
610
611      error.write2File(fb);
612    }
613
614    //! Write the error log to standard error output
615    void CClient::openErrorStream()
616    {
617      error.write2StdErr();
618    }
619
620    //! Close the error log file if it opens
621    void CClient::closeErrorStream()
622    {
623      if (m_errorStream.is_open()) m_errorStream.close();
624    }
625}
Note: See TracBrowser for help on using the repository browser.