source: XIOS/trunk/src/node/context.cpp @ 461

Last change on this file since 461 was 461, checked in by ymipsl, 10 years ago

New function available form fortran interface : LOGICAL xios_context_is_initialized("context_id")
Return .true. if the context "context_id" has been initialized before.

YM

File size: 16.2 KB
Line 
1#include "context.hpp"
2#include "attribute_template.hpp"
3#include "object_template.hpp"
4#include "group_template.hpp"
5
6#include "calendar_type.hpp"
7#include "duration.hpp"
8
9#include "context_client.hpp"
10#include "context_server.hpp"
11#include "nc4_data_output.hpp"
12#include "node_type.hpp"
13#include "message.hpp"
14#include "type.hpp"
15#include "xmlioserver_spl.hpp"
16
17namespace xios {
18 
19  shared_ptr<CContextGroup> CContext::root ;
20   
21   /// ////////////////////// Définitions ////////////////////// ///
22
23   CContext::CContext(void)
24      : CObjectTemplate<CContext>(), CContextAttributes()
25      , calendar(),hasClient(false),hasServer(false)
26   { /* Ne rien faire de plus */ }
27
28   CContext::CContext(const StdString & id)
29      : CObjectTemplate<CContext>(id), CContextAttributes()
30      , calendar(),hasClient(false),hasServer(false)
31   { /* Ne rien faire de plus */ }
32
33   CContext::~CContext(void)
34   { 
35     if (hasClient) delete client ;
36     if (hasServer) delete server ;
37   }
38
39   //----------------------------------------------------------------
40
41   StdString CContext::GetName(void)   { return (StdString("context")); }
42   StdString CContext::GetDefName(void){ return (CContext::GetName()); }
43   ENodeType CContext::GetType(void)   { return (eContext); }
44
45   //----------------------------------------------------------------
46
47   CContextGroup* CContext::getRoot(void)
48   { 
49      if (root.get()==NULL) root=shared_ptr<CContextGroup>(new CContextGroup(xml::CXMLNode::GetRootName())) ;
50      return root.get(); 
51   }
52   
53
54   //----------------------------------------------------------------
55
56   boost::shared_ptr<CCalendar> CContext::getCalendar(void) const
57   {
58      return (this->calendar);
59   }
60   
61   //----------------------------------------------------------------
62   
63   void CContext::setCalendar(boost::shared_ptr<CCalendar> newCalendar)
64   {
65      this->calendar = newCalendar;
66      calendar_type.setValue(this->calendar->getId());
67      start_date.setValue(this->calendar->getInitDate().toString());
68   }
69   
70   //----------------------------------------------------------------
71
72   void CContext::solveCalendar(void)
73   {
74      if (this->calendar.get() != NULL) return;
75      if (calendar_type.isEmpty() || start_date.isEmpty())
76         ERROR(" CContext::solveCalendar(void)",
77               << "[ context id = " << this->getId() << " ] "
78               << "Impossible to define a calendar (an attribute is missing).");
79
80#define DECLARE_CALENDAR(MType  , mtype)                              \
81   if (calendar_type.getValue().compare(#mtype) == 0)                 \
82   {                                                                  \
83      if (time_origin.isEmpty())                                       \
84        this->calendar =  boost::shared_ptr<CCalendar>          \
85           (new C##MType##Calendar(start_date.getValue()));     \
86      else this->calendar =  boost::shared_ptr<CCalendar>       \
87           (new C##MType##Calendar(start_date.getValue(),time_origin.getValue()));     \
88      if (!this->timestep.isEmpty())                                  \
89       this->calendar->setTimeStep                                    \
90          (CDuration::FromString(this->timestep.getValue()));   \
91      return;                                                         \
92   }
93#include "calendar_type.conf"
94
95      ERROR("CContext::solveCalendar(void)",
96            << "[ calendar_type = " << calendar_type.getValue() << " ] "
97            << "The calendar is not defined !");
98   }
99   
100   //----------------------------------------------------------------
101
102   void CContext::parse(xml::CXMLNode & node)
103   {
104      CContext::SuperClass::parse(node);
105
106      // PARSING POUR GESTION DES ENFANTS
107      xml::THashAttributes attributes = node.getAttributes();
108
109      if (attributes.end() != attributes.find("src"))
110      {
111         StdIFStream ifs ( attributes["src"].c_str() , StdIFStream::in );
112         if (!ifs.good())
113            ERROR("CContext::parse(xml::CXMLNode & node)",
114                  << "[ filename = " << attributes["src"] << " ] Bad xml stream !");
115         xml::CXMLParser::ParseInclude(ifs, *this);
116      }
117
118      if (node.getElementName().compare(CContext::GetName()))
119         DEBUG("Le noeud is wrong defined but will be considered as a context !");
120
121      if (!(node.goToChildElement()))
122      {
123         DEBUG("Le context ne contient pas d'enfant !");
124      }
125      else
126      {
127         do { // Parcours des contextes pour traitement.
128
129            StdString name = node.getElementName();
130            attributes.clear();
131            attributes = node.getAttributes();
132
133            if (attributes.end() != attributes.find("id"))
134            { DEBUG(<< "Definition node has an id,"
135                    << "it will not be taking account !"); }
136
137#define DECLARE_NODE(Name_, name_)    \
138   if (name.compare(C##Name_##Definition::GetDefName()) == 0) \
139   { C##Name_##Definition::create(C##Name_##Definition::GetDefName()) -> parse(node) ; continue; }
140#define DECLARE_NODE_PAR(Name_, name_)
141#include "node_type.conf"
142
143            DEBUG(<< "The element \'"     << name
144                  << "\' in the context \'" << CContext::getCurrent()->getId()
145                  << "\' is not a definition !");
146
147         } while (node.goToNextElement());
148
149         node.goToParentElement(); // Retour au parent
150      }
151   }
152
153   //----------------------------------------------------------------
154
155   void CContext::ShowTree(StdOStream & out)
156   {
157      StdString currentContextId = CContext::getCurrent() -> getId() ;
158      std::vector<CContext*> def_vector =
159         CContext::getRoot()->getChildList();
160      std::vector<CContext*>::iterator
161         it = def_vector.begin(), end = def_vector.end();
162
163      out << "<? xml version=\"1.0\" ?>" << std::endl;
164      out << "<"  << xml::CXMLNode::GetRootName() << " >" << std::endl;
165     
166      for (; it != end; it++)
167      {
168         CContext* context = *it;         
169         CContext::setCurrent(context->getId());         
170         out << *context << std::endl;
171      }
172     
173      out << "</" << xml::CXMLNode::GetRootName() << " >" << std::endl;
174      CContext::setCurrent(currentContextId); 
175   }
176   
177
178   //----------------------------------------------------------------
179
180   StdString CContext::toString(void) const
181   {
182      StdOStringStream oss;
183      oss << "<" << CContext::GetName()
184          << " id=\"" << this->getId() << "\" "
185          << SuperClassAttribute::toString() << ">" << std::endl;
186      if (!this->hasChild())
187      {
188         //oss << "<!-- No definition -->" << std::endl; // fait planter l'incrémentation
189      }
190      else
191      {
192
193#define DECLARE_NODE(Name_, name_)    \
194   if (C##Name_##Definition::has(C##Name_##Definition::GetDefName())) \
195   oss << * C##Name_##Definition::get(C##Name_##Definition::GetDefName()) << std::endl;
196#define DECLARE_NODE_PAR(Name_, name_)
197#include "node_type.conf"
198
199      }
200
201      oss << "</" << CContext::GetName() << " >";
202
203      return (oss.str());
204   }
205
206   //----------------------------------------------------------------
207
208   void CContext::solveDescInheritance(bool apply, const CAttributeMap * const UNUSED(parent))
209   {
210#define DECLARE_NODE(Name_, name_)    \
211   if (C##Name_##Definition::has(C##Name_##Definition::GetDefName())) \
212     C##Name_##Definition::get(C##Name_##Definition::GetDefName())->solveDescInheritance(apply);
213#define DECLARE_NODE_PAR(Name_, name_)
214#include "node_type.conf"
215   }
216
217   //----------------------------------------------------------------
218
219   bool CContext::hasChild(void) const
220   {
221      return (
222#define DECLARE_NODE(Name_, name_)    \
223   C##Name_##Definition::has(C##Name_##Definition::GetDefName())   ||
224#define DECLARE_NODE_PAR(Name_, name_)
225#include "node_type.conf"
226      false);
227}
228
229   //----------------------------------------------------------------
230
231   void CContext::solveFieldRefInheritance(bool apply)
232   {
233      if (!this->hasId()) return;
234      vector<CField*> allField = CField::getAll() ;
235//              = CObjectTemplate<CField>::GetAllVectobject(this->getId());
236      std::vector<CField*>::iterator
237         it = allField.begin(), end = allField.end();
238           
239      for (; it != end; it++)
240      {
241         CField* field = *it;
242         field->solveRefInheritance(apply);
243      }
244   }
245
246   //----------------------------------------------------------------
247
248   void CContext::CleanTree(void)
249   {
250#define DECLARE_NODE(Name_, name_) C##Name_##Group::ClearAllAttributes();
251#define DECLARE_NODE_PAR(Name_, name_)
252#include "node_type.conf"
253   }
254   ///---------------------------------------------------------------
255   
256   void CContext::initClient(MPI_Comm intraComm, MPI_Comm interComm)
257   {
258     hasClient=true ;
259     client = new CContextClient(this,intraComm, interComm) ;
260   } 
261
262   bool CContext::isInitialized(void)
263   {
264     return hasClient ;
265   }
266   
267   void CContext::initServer(MPI_Comm intraComm,MPI_Comm interComm)
268   {
269     hasServer=true ;
270     server = new CContextServer(this,intraComm,interComm) ;
271   } 
272
273   bool CContext::eventLoop(void)
274   {
275     return server->eventLoop() ;
276   } 
277   
278   void CContext::finalize(void)
279   {
280      if (hasClient && !hasServer)
281      {
282         client->finalize() ;
283      }
284      if (hasServer)
285      {
286        closeAllFile() ;
287      }
288   }
289       
290       
291 
292   
293   void CContext::closeDefinition(void)
294   {
295      if (hasClient && !hasServer) sendCloseDefinition() ;
296     
297      solveCalendar();         
298         
299      // Résolution des héritages pour le context actuel.
300      this->solveAllInheritance();
301
302      //Initialisation du vecteur 'enabledFiles' contenant la liste des fichiers à sortir.
303      this->findEnabledFiles();
304
305       
306      this->processEnabledFiles() ;
307
308/*       
309      //Recherche des champs à sortir (enable à true + niveau de sortie correct)
310      // pour chaque fichier précédemment listé.
311      this->findAllEnabledFields();
312
313      // Résolution des références de grilles pour chacun des champs.
314      this->solveAllGridRef();
315
316      // Traitement des opérations.
317      this->solveAllOperation();
318
319      // Traitement des expressions.
320      this->solveAllExpression();
321*/
322      // Nettoyage de l'arborescence
323      CleanTree();
324      if (hasClient) sendCreateFileHeader() ;
325   }
326   
327   void CContext::findAllEnabledFields(void)
328   {
329     for (unsigned int i = 0; i < this->enabledFiles.size(); i++)
330     (void)this->enabledFiles[i]->getEnabledFields();
331   }
332   
333    void CContext::processEnabledFiles(void)
334   {
335     for (unsigned int i = 0; i < this->enabledFiles.size(); i++)
336     this->enabledFiles[i]->processEnabledFile();
337   }
338 
339
340   void CContext::solveAllGridRef(void)
341   {
342     for (unsigned int i = 0; i < this->enabledFiles.size(); i++)
343     this->enabledFiles[i]->solveEFGridRef();
344   }
345
346   void CContext::solveAllOperation(void)
347   {
348      for (unsigned int i = 0; i < this->enabledFiles.size(); i++)
349      this->enabledFiles[i]->solveEFOperation();
350   }
351
352   void CContext::solveAllExpression(void)
353   {
354      for (unsigned int i = 0; i < this->enabledFiles.size(); i++)
355      this->enabledFiles[i]->solveEFExpression();
356   }
357   
358   void CContext::solveAllInheritance(bool apply)
359   {
360     // Résolution des héritages descendants (càd des héritages de groupes)
361     // pour chacun des contextes.
362      solveDescInheritance(apply);
363
364     // Résolution des héritages par référence au niveau des fichiers.
365      const vector<CFile*> allFiles=CFile::getAll() ;
366
367      for (unsigned int i = 0; i < allFiles.size(); i++)
368         allFiles[i]->solveFieldRefInheritance(apply);
369   }
370
371   void CContext::findEnabledFiles(void)
372   {
373      const std::vector<CFile*> allFiles = CFile::getAll();
374
375      for (unsigned int i = 0; i < allFiles.size(); i++)
376         if (!allFiles[i]->enabled.isEmpty()) // Si l'attribut 'enabled' est défini.
377         {
378            if (allFiles[i]->enabled.getValue()) // Si l'attribut 'enabled' est fixé à vrai.
379               enabledFiles.push_back(allFiles[i]);
380         }
381         else enabledFiles.push_back(allFiles[i]); // otherwise true by default
382               
383
384      if (enabledFiles.size() == 0)
385         DEBUG(<<"Aucun fichier ne va être sorti dans le contexte nommé \""
386               << getId() << "\" !");
387   }
388
389   void CContext::closeAllFile(void)
390   {
391     std::vector<CFile*>::const_iterator
392            it = this->enabledFiles.begin(), end = this->enabledFiles.end();
393         
394     for (; it != end; it++)
395     {
396       info(30)<<"Closing File : "<<(*it)->getId()<<endl;
397       (*it)->close();
398     }
399   }
400   
401   bool CContext::dispatchEvent(CEventServer& event)
402   {
403     
404      if (SuperClass::dispatchEvent(event)) return true ;
405      else
406      {
407        switch(event.type)
408        {
409           case EVENT_ID_CLOSE_DEFINITION :
410             recvCloseDefinition(event) ;
411             return true ;
412             break ;
413           case EVENT_ID_UPDATE_CALENDAR :
414             recvUpdateCalendar(event) ;
415             return true ;
416             break ;
417           case EVENT_ID_CREATE_FILE_HEADER :
418             recvCreateFileHeader(event) ;
419             return true ;
420             break ;
421           default :
422             ERROR("bool CContext::dispatchEvent(CEventServer& event)",
423                    <<"Unknown Event") ;
424           return false ;
425         }
426      }
427   }
428   
429   void CContext::sendCloseDefinition(void)
430   {
431
432     CEventClient event(getType(),EVENT_ID_CLOSE_DEFINITION) ;   
433     if (client->isServerLeader())
434     {
435       CMessage msg ;
436       msg<<this->getId() ;
437       event.push(client->getServerLeader(),1,msg) ;
438       client->sendEvent(event) ;
439     }
440     else client->sendEvent(event) ;
441   }
442   
443   void CContext::recvCloseDefinition(CEventServer& event)
444   {
445     
446      CBufferIn* buffer=event.subEvents.begin()->buffer;
447      string id;
448      *buffer>>id ;
449      get(id)->closeDefinition() ;
450   }
451   
452   void CContext::sendUpdateCalendar(int step)
453   {
454     if (!hasServer)
455     {
456       CEventClient event(getType(),EVENT_ID_UPDATE_CALENDAR) ;   
457       if (client->isServerLeader())
458       {
459         CMessage msg ;
460         msg<<this->getId()<<step ;
461         event.push(client->getServerLeader(),1,msg) ;
462         client->sendEvent(event) ;
463       }
464       else client->sendEvent(event) ;
465     }
466   }
467   
468   void CContext::recvUpdateCalendar(CEventServer& event)
469   {
470     
471      CBufferIn* buffer=event.subEvents.begin()->buffer;
472      string id;
473      *buffer>>id ;
474      get(id)->recvUpdateCalendar(*buffer) ;
475   }
476   
477   void CContext::recvUpdateCalendar(CBufferIn& buffer)
478   {
479      int step ;
480      buffer>>step ;
481      updateCalendar(step) ;
482   }
483   
484   void CContext::sendCreateFileHeader(void)
485   {
486
487     CEventClient event(getType(),EVENT_ID_CREATE_FILE_HEADER) ;   
488     if (client->isServerLeader())
489     {
490       CMessage msg ;
491       msg<<this->getId() ;
492       event.push(client->getServerLeader(),1,msg) ;
493       client->sendEvent(event) ;
494     }
495     else client->sendEvent(event) ;
496   }
497   
498   void CContext::recvCreateFileHeader(CEventServer& event)
499   {
500     
501      CBufferIn* buffer=event.subEvents.begin()->buffer;
502      string id;
503      *buffer>>id ;
504      get(id)->recvCreateFileHeader(*buffer) ;
505   }
506   
507   void CContext::recvCreateFileHeader(CBufferIn& buffer)
508   {
509      createFileHeader() ;
510   }
511   
512   void CContext::updateCalendar(int step)
513   {
514      info(50)<<"updateCalendar : before : "<<calendar->getCurrentDate()<<endl ;
515      calendar->update(step) ;
516      info(50)<<"updateCalendar : after : "<<calendar->getCurrentDate()<<endl ;
517   }
518 
519   void CContext::createFileHeader(void )
520   {
521      vector<CFile*>::const_iterator it ;
522         
523      for (it=enabledFiles.begin(); it != enabledFiles.end(); it++)
524      {
525         (*it)->initFile();
526      }
527   } 
528   
529   CContext* CContext::getCurrent(void)
530   {
531     return CObjectFactory::GetObject<CContext>(CObjectFactory::GetCurrentContextId()).get() ;
532   }
533   
534   void CContext::setCurrent(const string& id)
535   {
536     CObjectFactory::SetCurrentContextId(id);
537     CGroupFactory::SetCurrentContextId(id);
538   }
539   
540  CContext* CContext::create(const StdString& id)
541  {
542    CContext::setCurrent(id) ;
543 
544    bool hasctxt = CContext::has(id);
545    CContext* context = CObjectFactory::CreateObject<CContext>(id).get();
546    getRoot() ;
547    if (!hasctxt) CGroupFactory::AddChild(root, context->getShared());
548
549#define DECLARE_NODE(Name_, name_) \
550    C##Name_##Definition::create(C##Name_##Definition::GetDefName());
551#define DECLARE_NODE_PAR(Name_, name_)
552#include "node_type.conf"
553
554    return (context);
555  }
556} // namespace xios
Note: See TracBrowser for help on using the repository browser.