source: XIOS/dev/dev_ym/XIOS_COUPLING/src/client.cpp @ 2230

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

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