]> SALOME platform Git repositories - modules/yacs.git/blob - src/engine/Proc.cxx
Salome HOME
First implementation of evalyfx.
[modules/yacs.git] / src / engine / Proc.cxx
1 // Copyright (C) 2006-2015  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #include "Proc.hxx"
21 #include "ElementaryNode.hxx"
22 #include "Runtime.hxx"
23 #include "Container.hxx"
24 #include "ComponentInstance.hxx"
25 #include "InputPort.hxx"
26 #include "OutputPort.hxx"
27 #include "TypeCode.hxx"
28 #include "Logger.hxx"
29 #include "Visitor.hxx"
30 #include "VisitorSaveSchema.hxx"
31 #include "VisitorSaveState.hxx"
32 #include <sstream>
33 #include <set>
34
35 //#define _DEVDEBUG_
36 #include "YacsTrace.hxx"
37
38 using namespace std;
39 using namespace YACS::ENGINE;
40
41 /*! \class YACS::ENGINE::Proc
42  *  \brief Base class for all schema objects.
43  *
44  * This is an abstract class that must be specialized in runtime.
45  * \ingroup Nodes
46  */
47
48 Proc::Proc(const std::string& name):Bloc(name),_edition(false),_compoinstctr(0)
49 {
50   Runtime *theRuntime=getRuntime();
51   DEBTRACE("theRuntime->_tc_double->ref: " << theRuntime->_tc_double->getRefCnt());
52   DEBTRACE("theRuntime->_tc_int->ref: " << theRuntime->_tc_int->getRefCnt());
53   DEBTRACE("theRuntime->_tc_string->ref: " << theRuntime->_tc_string->getRefCnt());
54   DEBTRACE("theRuntime->_tc_bool->ref: " << theRuntime->_tc_bool->getRefCnt());
55   DEBTRACE("theRuntime->_tc_file->ref: " << theRuntime->_tc_file->getRefCnt());
56   theRuntime->_tc_double->incrRef();
57   theRuntime->_tc_string->incrRef();
58   theRuntime->_tc_int->incrRef();
59   theRuntime->_tc_bool->incrRef();
60   theRuntime->_tc_file->incrRef();
61   typeMap["double"]=theRuntime->_tc_double;
62   typeMap["string"]=theRuntime->_tc_string;
63   typeMap["int"]=theRuntime->_tc_int;
64   typeMap["bool"]=theRuntime->_tc_bool;
65   typeMap["file"]=theRuntime->_tc_file;
66 }
67
68 Proc::~Proc()
69 {
70   DEBTRACE("Proc::~Proc");
71   //for the moment all nodes are owned, so no need to manage their destruction
72   //nodeMap, inlineMap, serviceMap will be cleared automatically
73   //but we need to destroy TypeCodes
74   std::map<std::string, TypeCode *>::iterator pt;
75   for(pt=typeMap.begin();pt!=typeMap.end();pt++)
76     ((*pt).second)->decrRef();
77
78   removeContainers();
79
80   //get rid of loggers in logger map
81   std::map<std::string, Logger*>::const_iterator lt;
82   for(lt=_loggers.begin();lt!=_loggers.end();lt++)
83     delete (*lt).second;
84 }
85
86 void Proc::writeDot(std::ostream &os) const
87 {
88   os << "digraph " << getQualifiedName() << " {\n" ;
89   os << "node [ style=\"filled\" ];\n" ;
90   os << "compound=true;";
91   os << "states [label=< <TABLE> <TR> <TD BGCOLOR=\"pink\" > Ready</TD> <TD BGCOLOR=\"magenta\" > Toload</TD> </TR> <TR> <TD BGCOLOR=\"magenta\" > Loaded</TD> <TD BGCOLOR=\"purple\" > Toactivate</TD> </TR> <TR> <TD BGCOLOR=\"blue\" > Activated</TD> <TD BGCOLOR=\"green\" > Done</TD> </TR> <TR> <TD BGCOLOR=\"red\" > Error</TD> <TD BGCOLOR=\"orange\" > Failed</TD> </TR> <TR> <TD BGCOLOR=\"grey\" > Disabled</TD> <TD BGCOLOR=\"white\" > Pause</TD> </TR> </TABLE>> \n shape = plaintext \n style = invis \n ];\n";
92
93   Bloc::writeDot(os);
94   os << "}\n" ;
95 }
96
97 std::ostream& operator<< (std::ostream& os, const Proc& p)
98 {
99   os << "Proc" ;
100   return os;
101 }
102
103 TypeCode *Proc::createType(const std::string& name, const std::string& kind)
104 {
105   TypeCode* t;
106   if(kind=="double")
107     t=getRuntime()->_tc_double;
108   else if(kind=="string")
109     t=getRuntime()->_tc_string;
110   else if(kind=="int")
111     t=getRuntime()->_tc_int;
112   else if(kind=="bool")
113     t=getRuntime()->_tc_bool;
114   else
115     throw Exception("Unknown kind");
116
117   if(typeMap.count(name)!=0)
118     typeMap[name]->decrRef();
119   t->incrRef();
120   typeMap[name]=t;
121   t->incrRef();
122   return t;
123 }
124
125 //! Create an object reference TypeCode 
126 /*!
127  * \param id: the TypeCode repository id
128  * \param name: the TypeCode name
129  * \param ltc: a liste of object reference TypeCode to use as base types for this type
130  * \return the created TypeCode
131  */
132 TypeCode *Proc::createInterfaceTc(const std::string& id, const std::string& name,
133                                   std::list<TypeCodeObjref *> ltc)
134 {
135   TypeCode* t = TypeCode::interfaceTc(id.c_str(),name.c_str(),ltc);
136   if(typeMap.count(name)!=0)
137     typeMap[name]->decrRef();
138   typeMap[name]=t;
139   t->incrRef();
140   return t;
141 }
142
143 //! Create a sequence TypeCode 
144 /*!
145  * \param id: the TypeCode repository id ("" for normal use)
146  * \param name: the TypeCode name
147  * \param content: the element TypeCode 
148  * \return the created TypeCode
149  */
150 TypeCode * Proc::createSequenceTc (const std::string& id, const std::string& name,
151                                    TypeCode *content)
152 {
153   TypeCode* t = TypeCode::sequenceTc(id.c_str(),name.c_str(),content);
154   if(typeMap.count(name)!=0)
155     typeMap[name]->decrRef();
156   typeMap[name]=t;
157   t->incrRef();
158   return t;
159 }
160
161 TypeCode * Proc::createStructTc (const std::string& id, const std::string& name)
162 {
163   TypeCode* t = TypeCode::structTc(id.c_str(),name.c_str());
164   if(typeMap.count(name)!=0)
165     typeMap[name]->decrRef();
166   typeMap[name]=t;
167   t->incrRef();
168   return t;
169 }
170
171 TypeCode * Proc::getTypeCode (const std::string& name)
172 {
173   TypeCode* aTC=0;
174   if(typeMap.count(name)==0)
175     aTC=getRuntime()->getTypeCode(name);
176   else
177     aTC=typeMap[name];
178
179   if(!aTC)
180     {
181       std::stringstream msg;
182       msg << "Type " << name << " does not exist" ;
183       msg << " (" <<__FILE__ << ":" << __LINE__ << ")";
184       throw Exception(msg.str());
185     }
186
187   return aTC;
188 }
189
190 void Proc::setTypeCode (const std::string& name,TypeCode *t)
191 {
192   if(typeMap.count(name)!=0)
193     typeMap[name]->decrRef();
194   typeMap[name]=t;
195   t->incrRef();
196 }
197
198
199 void Proc::accept(Visitor *visitor)
200 {
201   visitor->visitProc(this);
202 }
203
204 void Proc::setName(const std::string& name)
205 {
206   _name = name;
207 }
208
209 YACS::StatesForNode Proc::getNodeState(int numId)
210 {
211   if(YACS::ENGINE::Node::idMap.count(numId) == 0)
212     {
213       cerr << "Unknown node id " << numId << endl;
214       return YACS::UNDEFINED;
215     }
216   YACS::ENGINE::Node* node = YACS::ENGINE::Node::idMap[numId];
217   YACS::StatesForNode state = node->getEffectiveState();
218   return state;
219 }
220
221 std::string Proc::getNodeProgress(int numId)
222 {
223   std::string progress = "0";
224   if(YACS::ENGINE::Node::idMap.count(numId) == 0)
225     {
226       cerr << "Unknown node id " << numId << endl;
227     }
228   else if (YACS::ENGINE::ComposedNode* node = dynamic_cast<YACS::ENGINE::ComposedNode*>(YACS::ENGINE::Node::idMap[numId]))
229     progress = node->getProgress();
230   return progress;
231 }
232
233 std::string Proc::getXMLState(int numId)
234 {
235   if(YACS::ENGINE::Node::idMap.count(numId) == 0)
236     {
237       cerr << "Unknown node id " << numId << endl;
238       return "<state>unknown</state>";
239     }
240   YACS::ENGINE::Node* node = YACS::ENGINE::Node::idMap[numId];
241   stringstream msg;
242   msg << "<state>" << node->getEffectiveState() << "</state>";
243   msg << "<name>" << node->getQualifiedName() << "</name>";
244   msg << "<id>" << numId << "</id>";
245   return msg.str();
246 }
247
248 std::string Proc::getInPortValue(int nodeNumId, std::string portName)
249 {
250   DEBTRACE("Proc::getInPortValue " << nodeNumId << " " << portName);
251   stringstream msg;
252   if(YACS::ENGINE::Node::idMap.count(nodeNumId) == 0)
253     {
254       msg << "<value><error>unknown node id: " << nodeNumId << "</error></value>";
255       return msg.str();
256     }
257   try
258     {
259       YACS::ENGINE::Node* node = YACS::ENGINE::Node::idMap[nodeNumId];
260       InputPort * inputPort = node->getInputPort(portName);
261       return inputPort->getAsString();
262     }
263   catch(YACS::Exception& ex)
264     {
265       DEBTRACE("Proc::getInPortValue " << ex.what());
266       msg << "<value><error>" << ex.what() << "</error></value>";
267       return msg.str();
268     }
269 }
270
271 std::string Proc::setInPortValue(std::string nodeName, std::string portName, std::string value)
272 {
273   DEBTRACE("Proc::setInPortValue " << nodeName << " " << portName << " " << value);
274
275   try
276     {
277       YACS::ENGINE::Node* node = YACS::ENGINE::Proc::nodeMap[nodeName];
278       YACS::ENGINE::InputPort* inputPort = node->getInputPort(portName);
279
280       switch (inputPort->edGetType()->kind())
281         {
282           case Double:
283             {
284               double val = atof(value.c_str());
285               inputPort->edInit(val);
286             }
287           case Int:
288             {
289               int val = atoi(value.c_str());
290               inputPort->edInit(val);
291             }
292           case String:
293             inputPort->edInit(value.c_str());
294           case Bool:
295             {
296               bool val = (! value.compare("False") ) && (! value.compare("0") );
297               inputPort->edInit(val);
298             }
299           default:
300             DEBTRACE("Proc::setInPortValue: filtered type: " << inputPort->edGetType()->kind());
301         }
302       return value;
303     }
304   catch(YACS::Exception& ex)
305     {
306       DEBTRACE("Proc::setInPortValue " << ex.what());
307       stringstream msg;
308       msg << "<value><error>" << ex.what() << "</error></value>";
309       return msg.str();
310     }
311 }
312
313 std::string Proc::getOutPortValue(int nodeNumId, std::string portName)
314 {
315   DEBTRACE("Proc::getOutPortValue " << nodeNumId << " " << portName);
316   stringstream msg;
317   if(YACS::ENGINE::Node::idMap.count(nodeNumId) == 0)
318     {
319       msg << "<value><error>unknown node id: " << nodeNumId << "</error></value>";
320       return msg.str();
321     }
322   try
323     {
324       YACS::ENGINE::Node* node = YACS::ENGINE::Node::idMap[nodeNumId];
325       OutputPort * outputPort = node->getOutputPort(portName);
326       return outputPort->getAsString();
327     }
328   catch(YACS::Exception& ex)
329     {
330       DEBTRACE("Proc::getOutPortValue " << ex.what());
331       msg << "<value><error>" << ex.what() << "</error></value>";
332       return msg.str();
333     }
334 }
335
336 std::string Proc::getNodeErrorDetails(int nodeNumId)
337 {
338   DEBTRACE("Proc::getNodeErrorDetails " << nodeNumId);
339   stringstream msg;
340   if(YACS::ENGINE::Node::idMap.count(nodeNumId) == 0)
341     {
342       msg << "Unknown node id " << nodeNumId;
343       return msg.str();
344     }
345   YACS::ENGINE::Node* node = YACS::ENGINE::Node::idMap[nodeNumId];
346   return node->getErrorDetails();
347 }
348
349 std::string Proc::getNodeErrorReport(int nodeNumId)
350 {
351   DEBTRACE("Proc::getNodeErrorReport " << nodeNumId);
352   stringstream msg;
353   if(YACS::ENGINE::Node::idMap.count(nodeNumId) == 0)
354     {
355       msg << "Unknown node id " << nodeNumId;
356       return msg.str();
357     }
358   YACS::ENGINE::Node* node = YACS::ENGINE::Node::idMap[nodeNumId];
359   return node->getErrorReport();
360 }
361
362 std::string Proc::getNodeContainerLog(int nodeNumId)
363 {
364   DEBTRACE("Proc::getNodeContainerLog " << nodeNumId);
365   stringstream msg;
366   if(YACS::ENGINE::Node::idMap.count(nodeNumId) == 0)
367     {
368       msg << "Unknown node id " << nodeNumId;
369       return msg.str();
370     }
371   YACS::ENGINE::Node* node = YACS::ENGINE::Node::idMap[nodeNumId];
372   return node->getContainerLog();
373 }
374
375 std::list<int> Proc::getNumIds()
376 {
377   list<YACS::ENGINE::Node *> nodes = getAllRecursiveConstituents();
378   int len = nodes.size();
379   list<int> numids;
380   for( list<YACS::ENGINE::Node *>::const_iterator iter = nodes.begin();
381        iter != nodes.end(); iter++)
382     {
383       numids.push_back((*iter)->getNumId());
384     }
385   numids.push_back(this->getNumId());
386   return numids;
387 }
388
389 std::list<std::string> Proc::getIds()
390 {
391   list<YACS::ENGINE::Node *> nodes = getAllRecursiveConstituents();
392   int len = nodes.size();
393   list<string> ids;
394   for( list<YACS::ENGINE::Node *>::const_iterator iter = nodes.begin();
395        iter != nodes.end(); iter++)
396     {
397       ids.push_back(getChildName(*iter));
398     }
399   ids.push_back("_root_");
400   return ids;
401 }
402
403 Logger *Proc::getLogger(const std::string& name)
404 {
405   Logger* logger;
406   LoggerMap::const_iterator it = _loggers.find(name);
407
408   if (it != _loggers.end())
409   {
410     logger = it->second;
411   }
412   else
413   {
414     logger = new Logger(name);
415     _loggers[name]=logger;
416   }
417   return logger;
418 }
419
420 void Proc::setEdition(bool edition)
421 {
422   DEBTRACE("Proc::setEdition: " << edition);
423   _edition=edition;
424   if(_edition)
425     edUpdateState();
426 }
427 //! Sets Proc in modified state and update state if in edition mode
428 /*!
429  *
430  */
431 void Proc::modified()
432 {
433   DEBTRACE("Proc::modified() " << _edition);
434   _modified=1;
435   if(_edition)
436     edUpdateState();
437 }
438
439 //! Save Proc in XML schema file
440 /*!
441  * \param xmlSchemaFile: the file name
442  */
443 void Proc::saveSchema(const std::string& xmlSchemaFile)
444 {
445   VisitorSaveSchema vss(this);
446   vss.openFileSchema(xmlSchemaFile);
447   accept(&vss);
448   vss.closeFileSchema();
449 }
450
451 //! Save Proc state in XML state file
452 /*!
453  * \param xmlStateFile: the file name
454  */
455 void Proc::saveState(const std::string& xmlStateFile)
456 {
457   VisitorSaveState vst(this);
458   vst.openFileDump(xmlStateFile);
459   accept(&vst);
460   vst.closeFileDump();
461 }
462
463 void Proc::removeContainers()
464 {
465   //get rid of containers in container map
466   std::map<std::string, Container*>::const_iterator it;
467   for(it=containerMap.begin();it!=containerMap.end();it++)
468     ((*it).second)->decrRef();
469   containerMap.clear();
470 }
471
472 //! Create a new Container and store it in containerMap
473 /*!
474  * \param name: the container name and key in containerMap
475  * \param kind: the container kind (depends on runtime)
476  * \return the created Container
477  */
478 Container *Proc::createContainer(const std::string& name, const std::string& kind)
479 {
480   Container *co(getRuntime()->createContainer(kind));
481   co->setName(name);
482   if(containerMap.count(name)!=0)
483     containerMap[name]->decrRef();
484   containerMap[name]=co;
485   co->incrRef();
486   co->setProc(this);
487   return co;
488 }
489
490 //! Add a ComponentInstance into componentInstanceMap
491 /*!
492  * If the name == "", the component instance is automatically named with a unique (in the Proc) name
493  *
494  * \param inst: the component instance
495  * \param name: the component instance name
496  * \param resetCtr: try to reuse instance number previously released, false by default
497  */
498 void Proc::addComponentInstance(ComponentInstance* inst, const std::string& name, bool resetCtr)
499 {
500   if(name != "")
501     {
502       inst->setName(name);
503       inst->setAnonymous(false);
504       if(componentInstanceMap.count(name)!=0)
505         componentInstanceMap[name]->decrRef();
506       componentInstanceMap[name]=inst;
507       inst->incrRef();
508     }
509   else
510     {
511       //automatic naming : componame_<_compoinstctr>
512       std::string instname;
513       std::string componame=inst->getCompoName();
514       if (resetCtr)
515         _compoinstctr = 0;        
516       while(1)
517         {
518           std::ostringstream buffer;
519           buffer << ++_compoinstctr;
520           instname=componame+"_"+buffer.str();
521           if(componentInstanceMap.count(instname)==0)
522             {
523               inst->setName(instname);
524               componentInstanceMap[instname]=inst;
525               inst->incrRef();
526               break;
527             }
528         }
529     }
530 }
531
532 //! Remove a componentInstance from the componentInstanceMap
533 /*!
534  * To be used for a componentInstance with no service nodes referenced.
535  *
536  * \param inst: the component instance
537  */
538 void Proc::removeComponentInstance(ComponentInstance* inst)
539 {
540   if (componentInstanceMap.count(inst->getInstanceName()))
541     {
542       componentInstanceMap.erase(inst->getInstanceName());
543       inst->decrRef();
544     }
545 }
546
547 //! Remove a container from the containerMap
548 /*!
549  * To be used for a container with no componentInstance referenced.
550  *
551  * \param cont: the container
552  */
553 void Proc::removeContainer(Container* cont)
554 {
555   if (containerMap.count(cont->getName()))
556     {
557       containerMap.erase(cont->getName());
558       cont->decrRef();
559     }
560 }
561
562 //! Create a new ComponentInstance and add it into componentInstanceMap
563 /*!
564  * If the name == "", the component instance is automatically named with a unique (in the Proc) name
565  *
566  * \param componame: the component name
567  * \param name: the component instance name
568  * \param kind: the component instance kind (depends on runtime)
569  * \return the created ComponentInstance
570  */
571 ComponentInstance* Proc::createComponentInstance(const std::string& componame, const std::string& name,const std::string& kind)
572 {
573   ComponentInstance* inst=  getRuntime()->createComponentInstance(componame,kind);
574   addComponentInstance(inst,name);
575   return inst;
576 }
577
578 //! Return the proc (this)
579 Proc* Proc::getProc()
580 {
581   return this;
582 }
583
584 //! Return the proc (this)
585 const Proc * Proc::getProc() const
586 {
587   return this;
588 }
589
590 /*!
591  * This method is useful if this has been modified recursively and an update is needed between all the
592  * containers and components refered by children and little children and maps.
593  */
594 void Proc::updateContainersAndComponents()
595 {
596   std::map<std::string, Container*> myContainerMap;
597   std::map<std::string, ComponentInstance*> myComponentInstanceMap;
598   DeploymentTree treeToDup(getDeploymentTree());
599   vector<Container *> conts(treeToDup.getAllContainers());
600   for(vector<Container *>::const_iterator iterCt=conts.begin();iterCt!=conts.end();iterCt++)
601     {
602       Container *tmp(*iterCt);
603       if(tmp)
604         {
605           if(myContainerMap.find(tmp->getName())!=myContainerMap.end())
606             {
607               std::ostringstream oss; oss << "Proc::updateContainersAndComponents : more than one container instance with name \"" << tmp->getName() << "\" !";
608               throw YACS::Exception(oss.str());
609             }
610           myContainerMap[tmp->getName()]=tmp;
611           tmp->incrRef();
612         }
613       vector<ComponentInstance *> comps=treeToDup.getComponentsLinkedToContainer(*iterCt);
614       for(vector<ComponentInstance *>::iterator iterCp=comps.begin();iterCp!=comps.end();iterCp++)
615         {
616           ComponentInstance *tmp2(*iterCp);
617           if(tmp2)
618             {
619               if(myComponentInstanceMap.find(tmp2->getCompoName())!=myComponentInstanceMap.end())
620                 {
621                   std::ostringstream oss; oss << "Proc::updateContainersAndComponents : more than one component instance with name \"" << tmp2->getCompoName() << "\" !";
622                   throw YACS::Exception(oss.str());
623                 }
624             }
625           myComponentInstanceMap[tmp2->getCompoName()]=tmp2;
626           tmp2->incrRef();
627         }
628     }
629   removeContainers();
630   containerMap=myContainerMap;
631   componentInstanceMap=myComponentInstanceMap;
632 }