source: XIOS/dev/dev_trunk_omp/src/client.cpp @ 1680

Last change on this file since 1680 was 1646, checked in by yushan, 5 years ago

branch merged with trunk @1645. arch file (ep&mpi) added for ADA

  • 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: 13.6 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#ifdef _usingEP
15using namespace ep_lib;
16#endif
17
18namespace xios
19{
20
21    MPI_Comm CClient::intraComm ;
22    MPI_Comm CClient::interComm ;
23    std::list<MPI_Comm> *CClient::contextInterComms_ptr = 0;
24    int CClient::serverLeader ;
25    bool CClient::is_MPI_Initialized ;
26    int CClient::rank_ = INVALID_RANK;
27    StdOFStream CClient::m_infoStream;
28    StdOFStream CClient::m_errorStream;
29
30    StdOFStream CClient::array_infoStream[16];
31
32    MPI_Comm& CClient::getInterComm(void)   { return (interComm); }
33
34///---------------------------------------------------------------
35/*!
36 * \fn void CClient::initialize(const string& codeId, MPI_Comm& localComm, MPI_Comm& returnComm)
37 * Function creates intraComm (CClient::intraComm) for client group with id=codeId and interComm (CClient::interComm) between client and server groups.
38 * \param [in] codeId identity of context.
39 * \param [in/out] localComm local communicator.
40 * \param [in/out] returnComm (intra)communicator of client group.
41 */
42
43    void CClient::initialize(const string& codeId, MPI_Comm& localComm, MPI_Comm& returnComm)
44    {
45      int initialized ;
46      MPI_Initialized(&initialized) ;
47      if (initialized) is_MPI_Initialized=true ;
48      else is_MPI_Initialized=false ;
49      int rank ;
50
51// don't use OASIS
52      if (!CXios::usingOasis)
53      {
54// localComm isn't given
55        if (localComm == MPI_COMM_NULL)
56        {
57          if (!is_MPI_Initialized)
58          {
59            MPI_Init(NULL, NULL);
60          }
61          CTimer::get("XIOS").resume() ;
62          CTimer::get("XIOS init/finalize").resume() ;
63          boost::hash<string> hashString ;
64
65          unsigned long hashClient=hashString(codeId) ;
66          unsigned long hashServer=hashString(CXios::xiosCodeId) ;
67          unsigned long* hashAll ;
68          int size ;
69          int myColor ;
70          int i,c ;
71          MPI_Comm newComm ;
72
73          MPI_Comm_size(CXios::globalComm,&size) ;
74          MPI_Comm_rank(CXios::globalComm,&rank_);
75
76          hashAll=new unsigned long[size] ;
77
78          MPI_Allgather(&hashClient,1,MPI_LONG,hashAll,1,MPI_LONG,CXios::globalComm) ;
79
80          map<unsigned long, int> colors ;
81          map<unsigned long, int> leaders ;
82
83          for(i=0,c=0;i<size;i++)
84          {
85            if (colors.find(hashAll[i])==colors.end())
86            {
87              colors[hashAll[i]] =c ;
88              leaders[hashAll[i]]=i ;
89              c++ ;
90            }
91          }
92
93          // Verify whether we are on server mode or not
94          CXios::setNotUsingServer();
95          for (i=0; i < size; ++i)
96          {
97            if (hashServer == hashAll[i])
98            {
99              CXios::setUsingServer();
100              break;
101            }
102          }
103
104          myColor=colors[hashClient];
105          MPI_Comm_split(CXios::globalComm,myColor,rank_,&intraComm) ;
106
107          if (CXios::usingServer)
108          {
109            int clientLeader=leaders[hashClient] ;
110            serverLeader=leaders[hashServer] ;
111            int intraCommSize, intraCommRank ;
112            MPI_Comm_size(intraComm,&intraCommSize) ;
113            MPI_Comm_rank(intraComm,&intraCommRank) ;
114
115            MPI_Intercomm_create(intraComm, 0, CXios::globalComm, serverLeader, 0, &interComm) ;
116            #pragma omp critical (_output)
117            {
118              info(50)<<"intercommCreate::client "<<rank_<<" intraCommSize : "<<intraCommSize
119                   <<" intraCommRank :"<<intraCommRank<<"  clientLeader "<< serverLeader<<endl ;
120            }
121          }
122          else
123          {
124            MPI_Comm_dup(intraComm,&interComm) ;
125          }
126          delete [] hashAll ;
127        }
128        // localComm argument is given
129        else
130        {
131          if (CXios::usingServer)
132          {
133            //ERROR("void CClient::initialize(const string& codeId,MPI_Comm& localComm,MPI_Comm& returnComm)", << " giving a local communictor is not compatible with using server mode") ;
134          }
135          else
136          {
137            MPI_Comm_dup(localComm,&intraComm) ;
138            MPI_Comm_dup(intraComm,&interComm) ;
139          }
140        }
141      }
142      // using OASIS
143      else
144      {
145        // localComm isn't given
146        if (localComm == MPI_COMM_NULL)
147        {
148          if (!is_MPI_Initialized) oasis_init(codeId) ;
149          oasis_get_localcomm(localComm) ;
150        }
151        MPI_Comm_dup(localComm,&intraComm) ;
152
153        CTimer::get("XIOS").resume() ;
154        CTimer::get("XIOS init/finalize").resume() ;
155
156        if (CXios::usingServer)
157        {
158          MPI_Status status ;
159          MPI_Comm_rank(intraComm,&rank_) ;
160
161          oasis_get_intercomm(interComm,CXios::xiosCodeId) ;
162          if (rank_==0) MPI_Recv(&serverLeader,1, MPI_INT, 0, 0, interComm, &status) ;
163          MPI_Bcast(&serverLeader,1,MPI_INT,0,intraComm) ;
164        }
165        else MPI_Comm_dup(intraComm,&interComm) ;
166      }
167
168      MPI_Comm_dup(intraComm,&returnComm) ;
169    }
170
171///---------------------------------------------------------------
172/*!
173 * \fn void CClient::registerContext(const string& id, MPI_Comm contextComm)
174 * \brief Sends a request to create a context to server. Creates client/server contexts.
175 * \param [in] id id of context.
176 * \param [in] contextComm.
177 * Function is only called by client.
178 */
179    void CClient::registerContext(const string& id, MPI_Comm contextComm)
180    {
181      CContext::setCurrent(id) ;
182      CContext* context=CContext::create(id);
183      StdString idServer(id);
184      idServer += "_server";
185
186      if (CXios::isServer && !context->hasServer)
187      // Attached mode
188      {
189        MPI_Comm contextInterComm ;
190        MPI_Comm_dup(contextComm,&contextInterComm) ;
191        CContext* contextServer = CContext::create(idServer);
192
193        // Firstly, initialize context on client side
194        context->initClient(contextComm,contextInterComm, contextServer);
195
196        // Secondly, initialize context on server side
197        contextServer->initServer(contextComm,contextInterComm, context);
198
199        // Finally, we should return current context to context client
200        CContext::setCurrent(id);
201
202        if(contextInterComms_ptr == NULL) contextInterComms_ptr = new std::list<MPI_Comm>;
203        contextInterComms_ptr->push_back(contextInterComm);
204      }
205      else
206      {
207        int size,rank,globalRank ;
208        size_t message_size ;
209        int leaderRank ;
210        MPI_Comm contextInterComm ;
211
212        MPI_Comm_size(contextComm,&size) ;
213        MPI_Comm_rank(contextComm,&rank) ;
214        MPI_Comm_rank(CXios::globalComm,&globalRank) ;
215        if (rank!=0) globalRank=0 ;
216
217        CMessage msg ;
218        msg<<idServer<<size<<globalRank ;
219//        msg<<id<<size<<globalRank ;
220
221        int messageSize=msg.size() ;
222        char * buff = new char[messageSize] ;
223        CBufferOut buffer((void*)buff,messageSize) ;
224        buffer<<msg ;
225
226        MPI_Send((void*)buff,buffer.count(),MPI_CHAR,serverLeader,1,CXios::globalComm) ;
227
228        MPI_Intercomm_create(contextComm,0,CXios::globalComm,serverLeader,10+globalRank,&contextInterComm) ;
229        #pragma omp critical (_output)
230        {
231          info(10)<<"Register new Context : "<<id<<endl ;
232        }
233        MPI_Comm inter ;
234        MPI_Intercomm_merge(contextInterComm,0,&inter) ;
235        MPI_Barrier(inter) ;
236
237        context->initClient(contextComm,contextInterComm) ;
238
239        if(contextInterComms_ptr == NULL) contextInterComms_ptr = new std::list<MPI_Comm>;
240        contextInterComms_ptr->push_back(contextInterComm);
241
242        MPI_Comm_free(&inter);
243        delete [] buff ;
244
245      }
246    }
247
248/*!
249 * \fn void CClient::callOasisEnddef(void)
250 * \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
251 * Function is only called by client.
252 */
253    void CClient::callOasisEnddef(void)
254    {
255      bool oasisEnddef=CXios::getin<bool>("call_oasis_enddef",true) ;
256      if (!oasisEnddef) ERROR("void CClient::callOasisEnddef(void)", <<"Function xios_oasis_enddef called but variable <call_oasis_enddef> is set to false."<<endl
257                                                                     <<"Variable <call_oasis_enddef> must be set to true"<<endl) ;
258      if (CXios::isServer)
259      // Attached mode
260      {
261        // nothing to do   
262      }
263      else
264      {
265        int rank ;
266        int msg=0 ;
267
268        MPI_Comm_rank(intraComm,&rank) ;
269        if (rank==0) 
270        {
271          MPI_Send(&msg,1,MPI_INT,0,5,interComm) ; // tags oasis_endded = 5
272        }
273
274      }
275    }
276
277
278    void CClient::finalize(void)
279    {
280      int rank ;
281      int msg=0 ;
282
283      MPI_Comm_rank(intraComm,&rank) ;
284 
285      if (!CXios::isServer)
286      {
287        MPI_Comm_rank(intraComm,&rank) ;
288        if (rank==0)
289        {
290          MPI_Send(&msg,1,MPI_INT,0,0,interComm) ;
291        }
292      }
293
294      for (std::list<MPI_Comm>::iterator it = contextInterComms_ptr->begin(); it != contextInterComms_ptr->end(); it++)
295        MPI_Comm_free(&(*it));
296      MPI_Comm_free(&interComm);
297      MPI_Comm_free(&intraComm);
298
299      CTimer::get("XIOS init/finalize").suspend() ;
300      CTimer::get("XIOS").suspend() ;
301
302      if (!is_MPI_Initialized)
303      {
304        //if (CXios::usingOasis) oasis_finalize();
305        //else
306        MPI_Finalize() ;
307      }
308      #pragma omp critical (_output)
309      {
310        info(20) << "Client side context is finalized"<<endl ;
311      }
312
313      #pragma omp critical (_output)
314      {
315        report(0) <<" Performance report : Whole time from XIOS init and finalize: "<< CTimer::get("XIOS init/finalize").getCumulatedTime()<<" s"<<endl ;
316        report(0) <<" Performance report : total time spent for XIOS : "<< CTimer::get("XIOS").getCumulatedTime()<<" s"<<endl ;
317        report(0)<< " Performance report : time spent for waiting free buffer : "<< CTimer::get("Blocking time").getCumulatedTime()<<" s"<<endl ;
318        report(0)<< " Performance report : Ratio : "<< CTimer::get("Blocking time").getCumulatedTime()/CTimer::get("XIOS init/finalize").getCumulatedTime()*100.<<" %"<<endl ;
319        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 ;
320//      report(0)<< " Memory report : Current buffer_size : "<<CXios::bufferSize<<endl ;
321        report(0)<< " Memory report : Minimum buffer size required : " << CClientBuffer::maxRequestSize << " bytes" << endl ;
322        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 ;
323        report(0)<<CTimer::getAllCumulatedTime()<<endl ;
324      }
325   }
326
327    /*!
328    * Return global rank without oasis and current rank in model intraComm in case of oasis
329    */
330   int CClient::getRank()
331   {
332     return rank_;
333   }
334
335    /*!
336    * Open a file specified by a suffix and an extension and use it for the given file buffer.
337    * The file name will be suffix+rank+extension.
338    *
339    * \param fileName[in] protype file name
340    * \param ext [in] extension of the file
341    * \param fb [in/out] the file buffer
342    */
343    void CClient::openStream(const StdString& fileName, const StdString& ext, std::filebuf* fb)
344    {
345      StdStringStream fileNameClient;
346      int numDigit = 0;
347      int size = 0;
348      int rank;
349      MPI_Comm_size(CXios::globalComm, &size);
350      while (size)
351      {
352        size /= 10;
353        ++numDigit;
354      }
355
356      if (CXios::usingOasis)
357      {
358        MPI_Comm_rank(CXios::globalComm,&rank);
359        fileNameClient << fileName << "_" << std::setfill('0') << std::setw(numDigit) << rank << ext;
360      }
361      else
362        fileNameClient << fileName << "_" << std::setfill('0') << std::setw(numDigit) << getRank() << ext;
363
364
365      fb->open(fileNameClient.str().c_str(), std::ios::out);
366      if (!fb->is_open())
367        ERROR("void CClient::openStream(const StdString& fileName, const StdString& ext, std::filebuf* fb)",
368              << std::endl << "Can not open <" << fileNameClient.str() << "> file to write the client log(s).");
369    }
370
371    /*!
372    * \brief Open a file stream to write the info logs
373    * Open a file stream with a specific file name suffix+rank
374    * to write the info logs.
375    * \param fileName [in] protype file name
376    */
377    void CClient::openInfoStream(const StdString& fileName)
378    {
379      info_FB[omp_get_thread_num()] = array_infoStream[omp_get_thread_num()].rdbuf();
380         
381      openStream(fileName, ".out", info_FB[omp_get_thread_num()]);
382
383      info.write2File(info_FB[omp_get_thread_num()]);
384      report.write2File(info_FB[omp_get_thread_num()]);
385    }
386
387    //! Write the info logs to standard output
388    void CClient::openInfoStream()
389    {
390      info.write2StdOut();
391      report.write2StdOut();
392    }
393
394    //! Close the info logs file if it opens
395    void CClient::closeInfoStream()
396    {
397      if (m_infoStream.is_open()) m_infoStream.close();
398    }
399
400    /*!
401    * \brief Open a file stream to write the error log
402    * Open a file stream with a specific file name suffix+rank
403    * to write the error log.
404    * \param fileName [in] protype file name
405    */
406    void CClient::openErrorStream(const StdString& fileName)
407    {
408      std::filebuf* fb = m_errorStream.rdbuf();
409      openStream(fileName, ".err", fb);
410
411      error.write2File(fb);
412    }
413
414    //! Write the error log to standard error output
415    void CClient::openErrorStream()
416    {
417      error.write2StdErr();
418    }
419
420    //! Close the error log file if it opens
421    void CClient::closeErrorStream()
422    {
423      if (m_errorStream.is_open()) m_errorStream.close();
424    }
425}
Note: See TracBrowser for help on using the repository browser.