Salome HOME
Manage initnode and finalizenode in the foreachloop progress bar.
[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 int Proc::getGlobalProgressPercent()
234 {
235   list<ProgressWeight> weightList = getProgressWeight();
236   int weightDone = 0;
237   int weightTotal = 0;
238   int progressPercent = 0;
239   for(list<ProgressWeight>::const_iterator iter=weightList.begin();iter!=weightList.end();iter++)
240     {
241       weightDone += (*iter).weightDone;
242       weightTotal += (*iter).weightTotal;
243     }
244   if (weightTotal > 0)
245     progressPercent = int(float(weightDone) / float(weightTotal) * 100);
246   return progressPercent;
247 }
248
249 std::string Proc::getXMLState(int numId)
250 {
251   if(YACS::ENGINE::Node::idMap.count(numId) == 0)
252     {
253       cerr << "Unknown node id " << numId << endl;
254       return "<state>unknown</state>";
255     }
256   YACS::ENGINE::Node* node = YACS::ENGINE::Node::idMap[numId];
257   stringstream msg;
258   msg << "<state>" << node->getEffectiveState() << "</state>";
259   msg << "<name>" << node->getQualifiedName() << "</name>";
260   msg << "<id>" << numId << "</id>";
261   return msg.str();
262 }
263
264 std::string Proc::getInPortValue(int nodeNumId, std::string portName)
265 {
266   DEBTRACE("Proc::getInPortValue " << nodeNumId << " " << portName);
267   stringstream msg;
268   if(YACS::ENGINE::Node::idMap.count(nodeNumId) == 0)
269     {
270       msg << "<value><error>unknown node id: " << nodeNumId << "</error></value>";
271       return msg.str();
272     }
273   try
274     {
275       YACS::ENGINE::Node* node = YACS::ENGINE::Node::idMap[nodeNumId];
276       InputPort * inputPort = node->getInputPort(portName);
277       return inputPort->getAsString();
278     }
279   catch(YACS::Exception& ex)
280     {
281       DEBTRACE("Proc::getInPortValue " << ex.what());
282       msg << "<value><error>" << ex.what() << "</error></value>";
283       return msg.str();
284     }
285 }
286
287 std::string Proc::setInPortValue(std::string nodeName, std::string portName, std::string value)
288 {
289   DEBTRACE("Proc::setInPortValue " << nodeName << " " << portName << " " << value);
290
291   try
292     {
293       YACS::ENGINE::Node* node = YACS::ENGINE::Proc::nodeMap[nodeName];
294       YACS::ENGINE::InputPort* inputPort = node->getInputPort(portName);
295
296       switch (inputPort->edGetType()->kind())
297         {
298           case Double:
299             {
300               double val = atof(value.c_str());
301               inputPort->edInit(val);
302             }
303           case Int:
304             {
305               int val = atoi(value.c_str());
306               inputPort->edInit(val);
307             }
308           case String:
309             inputPort->edInit(value.c_str());
310           case Bool:
311             {
312               bool val = (! value.compare("False") ) && (! value.compare("0") );
313               inputPort->edInit(val);
314             }
315           default:
316             DEBTRACE("Proc::setInPortValue: filtered type: " << inputPort->edGetType()->kind());
317         }
318       return value;
319     }
320   catch(YACS::Exception& ex)
321     {
322       DEBTRACE("Proc::setInPortValue " << ex.what());
323       stringstream msg;
324       msg << "<value><error>" << ex.what() << "</error></value>";
325       return msg.str();
326     }
327 }
328
329 std::string Proc::getOutPortValue(int nodeNumId, std::string portName)
330 {
331   DEBTRACE("Proc::getOutPortValue " << nodeNumId << " " << portName);
332   stringstream msg;
333   if(YACS::ENGINE::Node::idMap.count(nodeNumId) == 0)
334     {
335       msg << "<value><error>unknown node id: " << nodeNumId << "</error></value>";
336       return msg.str();
337     }
338   try
339     {
340       YACS::ENGINE::Node* node = YACS::ENGINE::Node::idMap[nodeNumId];
341       OutputPort * outputPort = node->getOutputPort(portName);
342       return outputPort->getAsString();
343     }
344   catch(YACS::Exception& ex)
345     {
346       DEBTRACE("Proc::getOutPortValue " << ex.what());
347       msg << "<value><error>" << ex.what() << "</error></value>";
348       return msg.str();
349     }
350 }
351
352 std::string Proc::getNodeErrorDetails(int nodeNumId)
353 {
354   DEBTRACE("Proc::getNodeErrorDetails " << nodeNumId);
355   stringstream msg;
356   if(YACS::ENGINE::Node::idMap.count(nodeNumId) == 0)
357     {
358       msg << "Unknown node id " << nodeNumId;
359       return msg.str();
360     }
361   YACS::ENGINE::Node* node = YACS::ENGINE::Node::idMap[nodeNumId];
362   return node->getErrorDetails();
363 }
364
365 std::string Proc::getNodeErrorReport(int nodeNumId)
366 {
367   DEBTRACE("Proc::getNodeErrorReport " << nodeNumId);
368   stringstream msg;
369   if(YACS::ENGINE::Node::idMap.count(nodeNumId) == 0)
370     {
371       msg << "Unknown node id " << nodeNumId;
372       return msg.str();
373     }
374   YACS::ENGINE::Node* node = YACS::ENGINE::Node::idMap[nodeNumId];
375   return node->getErrorReport();
376 }
377
378 std::string Proc::getNodeContainerLog(int nodeNumId)
379 {
380   DEBTRACE("Proc::getNodeContainerLog " << nodeNumId);
381   stringstream msg;
382   if(YACS::ENGINE::Node::idMap.count(nodeNumId) == 0)
383     {
384       msg << "Unknown node id " << nodeNumId;
385       return msg.str();
386     }
387   YACS::ENGINE::Node* node = YACS::ENGINE::Node::idMap[nodeNumId];
388   return node->getContainerLog();
389 }
390
391 std::list<int> Proc::getNumIds()
392 {
393   list<YACS::ENGINE::Node *> nodes = getAllRecursiveConstituents();
394   int len = nodes.size();
395   list<int> numids;
396   for( list<YACS::ENGINE::Node *>::const_iterator iter = nodes.begin();
397        iter != nodes.end(); iter++)
398     {
399       numids.push_back((*iter)->getNumId());
400     }
401   numids.push_back(this->getNumId());
402   return numids;
403 }
404
405 std::list<std::string> Proc::getIds()
406 {
407   list<YACS::ENGINE::Node *> nodes = getAllRecursiveConstituents();
408   int len = nodes.size();
409   list<string> ids;
410   for( list<YACS::ENGINE::Node *>::const_iterator iter = nodes.begin();
411        iter != nodes.end(); iter++)
412     {
413       ids.push_back(getChildName(*iter));
414     }
415   ids.push_back("_root_");
416   return ids;
417 }
418
419 Logger *Proc::getLogger(const std::string& name)
420 {
421   Logger* logger;
422   LoggerMap::const_iterator it = _loggers.find(name);
423
424   if (it != _loggers.end())
425   {
426     logger = it->second;
427   }
428   else
429   {
430     logger = new Logger(name);
431     _loggers[name]=logger;
432   }
433   return logger;
434 }
435
436 void Proc::setEdition(bool edition)
437 {
438   DEBTRACE("Proc::setEdition: " << edition);
439   _edition=edition;
440   if(_edition)
441     edUpdateState();
442 }
443 //! Sets Proc in modified state and update state if in edition mode
444 /*!
445  *
446  */
447 void Proc::modified()
448 {
449   DEBTRACE("Proc::modified() " << _edition);
450   _modified=1;
451   if(_edition)
452     edUpdateState();
453 }
454
455 //! Save Proc in XML schema file
456 /*!
457  * \param xmlSchemaFile: the file name
458  */
459 void Proc::saveSchema(const std::string& xmlSchemaFile)
460 {
461   VisitorSaveSchema vss(this);
462   vss.openFileSchema(xmlSchemaFile);
463   accept(&vss);
464   vss.closeFileSchema();
465 }
466
467 //! Save Proc state in XML state file
468 /*!
469  * \param xmlStateFile: the file name
470  */
471 void Proc::saveState(const std::string& xmlStateFile)
472 {
473   VisitorSaveState vst(this);
474   vst.openFileDump(xmlStateFile);
475   accept(&vst);
476   vst.closeFileDump();
477 }
478
479 void Proc::removeContainers()
480 {
481   //get rid of containers in container map
482   std::map<std::string, Container*>::const_iterator it;
483   for(it=containerMap.begin();it!=containerMap.end();it++)
484     ((*it).second)->decrRef();
485   containerMap.clear();
486 }
487
488 //! Create a new Container and store it in containerMap
489 /*!
490  * \param name: the container name and key in containerMap
491  * \param kind: the container kind (depends on runtime)
492  * \return the created Container
493  */
494 Container *Proc::createContainer(const std::string& name, const std::string& kind)
495 {
496   Container *co(getRuntime()->createContainer(kind));
497   co->setName(name);
498   if(containerMap.count(name)!=0)
499     containerMap[name]->decrRef();
500   containerMap[name]=co;
501   co->incrRef();
502   co->setProc(this);
503   return co;
504 }
505
506 //! Add a ComponentInstance into componentInstanceMap
507 /*!
508  * If the name == "", the component instance is automatically named with a unique (in the Proc) name
509  *
510  * \param inst: the component instance
511  * \param name: the component instance name
512  * \param resetCtr: try to reuse instance number previously released, false by default
513  */
514 void Proc::addComponentInstance(ComponentInstance* inst, const std::string& name, bool resetCtr)
515 {
516   if(name != "")
517     {
518       inst->setName(name);
519       inst->setAnonymous(false);
520       if(componentInstanceMap.count(name)!=0)
521         componentInstanceMap[name]->decrRef();
522       componentInstanceMap[name]=inst;
523       inst->incrRef();
524     }
525   else
526     {
527       //automatic naming : componame_<_compoinstctr>
528       std::string instname;
529       std::string componame=inst->getCompoName();
530       if (resetCtr)
531         _compoinstctr = 0;        
532       while(1)
533         {
534           std::ostringstream buffer;
535           buffer << ++_compoinstctr;
536           instname=componame+"_"+buffer.str();
537           if(componentInstanceMap.count(instname)==0)
538             {
539               inst->setName(instname);
540               componentInstanceMap[instname]=inst;
541               inst->incrRef();
542               break;
543             }
544         }
545     }
546 }
547
548 //! Remove a componentInstance from the componentInstanceMap
549 /*!
550  * To be used for a componentInstance with no service nodes referenced.
551  *
552  * \param inst: the component instance
553  */
554 void Proc::removeComponentInstance(ComponentInstance* inst)
555 {
556   if (componentInstanceMap.count(inst->getInstanceName()))
557     {
558       componentInstanceMap.erase(inst->getInstanceName());
559       inst->decrRef();
560     }
561 }
562
563 //! Remove a container from the containerMap
564 /*!
565  * To be used for a container with no componentInstance referenced.
566  *
567  * \param cont: the container
568  */
569 void Proc::removeContainer(Container* cont)
570 {
571   if (containerMap.count(cont->getName()))
572     {
573       containerMap.erase(cont->getName());
574       cont->decrRef();
575     }
576 }
577
578 //! Create a new ComponentInstance and add it into componentInstanceMap
579 /*!
580  * If the name == "", the component instance is automatically named with a unique (in the Proc) name
581  *
582  * \param componame: the component name
583  * \param name: the component instance name
584  * \param kind: the component instance kind (depends on runtime)
585  * \return the created ComponentInstance
586  */
587 ComponentInstance* Proc::createComponentInstance(const std::string& componame, const std::string& name,const std::string& kind)
588 {
589   ComponentInstance* inst=  getRuntime()->createComponentInstance(componame,kind);
590   addComponentInstance(inst,name);
591   return inst;
592 }
593
594 //! Return the proc (this)
595 Proc* Proc::getProc()
596 {
597   return this;
598 }
599
600 //! Return the proc (this)
601 const Proc * Proc::getProc() const
602 {
603   return this;
604 }
605
606 /*!
607  * This method is useful if this has been modified recursively and an update is needed between all the
608  * containers and components refered by children and little children and maps.
609  */
610 void Proc::updateContainersAndComponents()
611 {
612   std::map<std::string, Container*> myContainerMap;
613   std::map<std::string, ComponentInstance*> myComponentInstanceMap;
614   DeploymentTree treeToDup(getDeploymentTree());
615   vector<Container *> conts(treeToDup.getAllContainers());
616   for(vector<Container *>::const_iterator iterCt=conts.begin();iterCt!=conts.end();iterCt++)
617     {
618       Container *tmp(*iterCt);
619       if(tmp)
620         {
621           if(myContainerMap.find(tmp->getName())!=myContainerMap.end())
622             {
623               std::ostringstream oss; oss << "Proc::updateContainersAndComponents : more than one container instance with name \"" << tmp->getName() << "\" !";
624               throw YACS::Exception(oss.str());
625             }
626           myContainerMap[tmp->getName()]=tmp;
627           tmp->incrRef();
628         }
629       vector<ComponentInstance *> comps=treeToDup.getComponentsLinkedToContainer(*iterCt);
630       for(vector<ComponentInstance *>::iterator iterCp=comps.begin();iterCp!=comps.end();iterCp++)
631         {
632           ComponentInstance *tmp2(*iterCp);
633           if(tmp2)
634             {
635               if(myComponentInstanceMap.find(tmp2->getCompoName())!=myComponentInstanceMap.end())
636                 {
637                   std::ostringstream oss; oss << "Proc::updateContainersAndComponents : more than one component instance with name \"" << tmp2->getCompoName() << "\" !";
638                   throw YACS::Exception(oss.str());
639                 }
640             }
641           myComponentInstanceMap[tmp2->getCompoName()]=tmp2;
642           tmp2->incrRef();
643         }
644     }
645   removeContainers();
646   containerMap=myContainerMap;
647   componentInstanceMap=myComponentInstanceMap;
648 }