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