Salome HOME
Merge branch 'omu/testpy3' into agy/optim_fe_0_2
[modules/yacs.git] / src / runtime / PythonNode.cxx
1 // Copyright (C) 2006-2019  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 "RuntimeSALOME.hxx"
21 #include "PythonNode.hxx"
22 #include "PythonPorts.hxx"
23 #include "TypeCode.hxx"
24 #include "AutoGIL.hxx"
25 #include "Container.hxx"
26 #include "SalomeContainer.hxx"
27 #include "SalomeHPContainer.hxx"
28 #include "SalomeContainerTmpForHP.hxx"
29 #include "ConversionException.hxx"
30
31 #include "PyStdout.hxx"
32 #include <iostream>
33 #include <sstream>
34 #include <fstream>
35
36 #ifdef WIN32
37 #include <process.h>
38 #define getpid _getpid
39 #endif
40
41 #if PY_VERSION_HEX < 0x02050000 
42 typedef int Py_ssize_t;
43 #endif
44
45 //#define _DEVDEBUG_
46 #include "YacsTrace.hxx"
47
48 using namespace YACS::ENGINE;
49 using namespace std;
50
51 const char PythonEntry::SCRIPT_FOR_SIMPLE_SERIALIZATION[]="import pickle\n"
52     "def pickleForVarSimplePyth2009(val):\n"
53     "  return pickle.dumps(val,-1)\n"
54     "\n";
55
56 const char PythonNode::IMPL_NAME[]="Python";
57 const char PythonNode::KIND[]="Python";
58
59 const char PythonNode::SCRIPT_FOR_SERIALIZATION[]="import pickle\n"
60     "def pickleForDistPyth2009(kws):\n"
61     "  return pickle.dumps(((),kws),-1)\n"
62     "\n"
63     "def unPickleForDistPyth2009(st):\n"
64     "  args=pickle.loads(st)\n"
65     "  return args\n";
66
67 const char PythonNode::REMOTE_NAME[]="remote";
68
69 const char PythonNode::DPL_INFO_NAME[]="my_dpl_localization";
70
71 const char PyFuncNode::SCRIPT_FOR_SERIALIZATION[]="import pickle\n"
72     "def pickleForDistPyth2009(*args,**kws):\n"
73     "  return pickle.dumps((args,kws),-1)\n"
74     "\n"
75     "def unPickleForDistPyth2009(st):\n"
76     "  args=pickle.loads(st)\n"
77     "  return args\n";
78
79
80 PythonEntry::PythonEntry():_context(0),_pyfuncSer(0),_pyfuncUnser(0),_pyfuncSimpleSer(0)
81 {
82 }
83
84 PythonEntry::~PythonEntry()
85 {
86   AutoGIL agil;
87   DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
88   // not Py_XDECREF of _pyfuncUnser because it is returned by PyDict_GetItem -> borrowed
89   // not Py_XDECREF of _pyfuncSer because it is returned by PyDict_GetItem -> borrowed
90   Py_XDECREF(_context);
91 }
92
93 void PythonEntry::commonRemoteLoadPart1(InlineNode *reqNode)
94 {
95   DEBTRACE( "---------------PythonEntry::CommonRemoteLoad function---------------" );
96   Container *container(reqNode->getContainer());
97   bool isContAlreadyStarted(false);
98   if(container)
99     {
100       isContAlreadyStarted=container->isAlreadyStarted(reqNode);
101       if(!isContAlreadyStarted)
102         {
103           try
104           {
105               container->start(reqNode);
106           }
107           catch(Exception& e)
108           {
109               reqNode->setErrorDetails(e.what());
110               throw e;
111           }
112         }
113     }
114   else
115     {
116       std::string what("PythonEntry::CommonRemoteLoad : a load operation requested on \"");
117       what+=reqNode->getName(); what+="\" with no container specified.";
118       reqNode->setErrorDetails(what);
119       throw Exception(what);
120     }
121 }
122
123 Engines::Container_var GetContainerObj(InlineNode *reqNode, bool& isStandardCont)
124 {
125   isStandardCont = false;
126   Container *container(reqNode->getContainer());
127   Engines::Container_var objContainer(Engines::Container::_nil());
128   if(!container)
129     throw YACS::Exception("No container specified !");
130   SalomeContainer *containerCast0(dynamic_cast<SalomeContainer *>(container));
131   SalomeHPContainer *containerCast1(dynamic_cast<SalomeHPContainer *>(container));
132   if(containerCast0)
133     {
134       isStandardCont = true;
135       objContainer=containerCast0->getContainerPtr(reqNode);
136     }
137   else if(containerCast1)
138     {
139       YACS::BASES::AutoCppPtr<SalomeContainerTmpForHP> tmpCont(SalomeContainerTmpForHP::BuildFrom(containerCast1,reqNode));
140       objContainer=tmpCont->getContainerPtr(reqNode);
141     }
142   else
143     throw YACS::Exception("Unrecognized type of container ! Salome one is expected for PythonNode/PyFuncNode !");
144   if(CORBA::is_nil(objContainer))
145     throw YACS::Exception("Container corba pointer is NULL for PythonNode !");
146   return objContainer;
147 }
148
149 Engines::Container_var PythonEntry::commonRemoteLoadPart2(InlineNode *reqNode, bool& isInitializeRequested)
150 {
151   bool isStandardCont(true);
152   Engines::Container_var objContainer(GetContainerObj(reqNode,isStandardCont));
153   isInitializeRequested=false;
154   try
155   {
156       if(isStandardCont)
157         {
158           createRemoteAdaptedPyInterpretor(objContainer);
159         }
160       else
161         {
162           Engines::PyNodeBase_var dftPyScript(retrieveDftRemotePyInterpretorIfAny(objContainer));
163           if(CORBA::is_nil(dftPyScript))
164             {
165               isInitializeRequested=true;
166               createRemoteAdaptedPyInterpretor(objContainer);
167             }
168           else
169             assignRemotePyInterpretor(dftPyScript);
170         }
171   }
172   catch( const SALOME::SALOME_Exception& ex )
173   {
174       std::string msg="Exception on remote python node creation ";
175       msg += '\n';
176       msg += ex.details.text.in();
177       reqNode->setErrorDetails(msg);
178       throw Exception(msg);
179   }
180   Engines::PyNodeBase_var pynode(getRemoteInterpreterHandle());
181   if(CORBA::is_nil(pynode))
182     throw Exception("In PythonNode the ref in NULL ! ");
183   return objContainer;
184 }
185
186 void PythonEntry::commonRemoteLoadPart3(InlineNode *reqNode, Engines::Container_ptr objContainer, bool isInitializeRequested)
187 {
188   Container *container(reqNode->getContainer());
189   Engines::PyNodeBase_var pynode(getRemoteInterpreterHandle());
190   ///
191   {
192     AutoGIL agil;
193     const char *picklizeScript(getSerializationScript());
194     PyObject *res=PyRun_String(picklizeScript,Py_file_input,_context,_context);
195     PyObject *res2(PyRun_String(SCRIPT_FOR_SIMPLE_SERIALIZATION,Py_file_input,_context,_context));
196     if(res == NULL || res2==NULL)
197       {
198         std::string errorDetails;
199         PyObject* new_stderr = newPyStdOut(errorDetails);
200         reqNode->setErrorDetails(errorDetails);
201         PySys_SetObject((char*)"stderr", new_stderr);
202         PyErr_Print();
203         PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
204         Py_DECREF(new_stderr);
205         throw Exception("Error during load");
206       }
207     Py_DECREF(res); Py_DECREF(res2);
208     _pyfuncSer=PyDict_GetItemString(_context,"pickleForDistPyth2009");
209     _pyfuncUnser=PyDict_GetItemString(_context,"unPickleForDistPyth2009");
210     _pyfuncSimpleSer=PyDict_GetItemString(_context,"pickleForVarSimplePyth2009");
211     if(_pyfuncSer == NULL)
212       {
213         std::string errorDetails;
214         PyObject *new_stderr(newPyStdOut(errorDetails));
215         reqNode->setErrorDetails(errorDetails);
216         PySys_SetObject((char*)"stderr", new_stderr);
217         PyErr_Print();
218         PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
219         Py_DECREF(new_stderr);
220         throw Exception("Error during load");
221       }
222     if(_pyfuncUnser == NULL)
223       {
224         std::string errorDetails;
225         PyObject *new_stderr(newPyStdOut(errorDetails));
226         reqNode->setErrorDetails(errorDetails);
227         PySys_SetObject((char*)"stderr", new_stderr);
228         PyErr_Print();
229         PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
230         Py_DECREF(new_stderr);
231         throw Exception("Error during load");
232       }
233     if(_pyfuncSimpleSer == NULL)
234       {
235         std::string errorDetails;
236         PyObject *new_stderr(newPyStdOut(errorDetails));
237         reqNode->setErrorDetails(errorDetails);
238         PySys_SetObject((char*)"stderr", new_stderr);
239         PyErr_Print();
240         PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
241         Py_DECREF(new_stderr);
242         throw Exception("Error during load");
243       }
244   }
245   if(isInitializeRequested)
246     {//This one is called only once at initialization in the container if an init-script is specified.
247       try
248       {
249           std::string zeInitScriptKey(container->getProperty(HomogeneousPoolContainer::INITIALIZE_SCRIPT_KEY));
250           if(!zeInitScriptKey.empty())
251             pynode->executeAnotherPieceOfCode(zeInitScriptKey.c_str());
252       }
253       catch( const SALOME::SALOME_Exception& ex )
254       {
255           std::string msg="Exception on PythonNode::loadRemote python invocation of initializisation py script !";
256           msg += '\n';
257           msg += ex.details.text.in();
258           reqNode->setErrorDetails(msg);
259           throw Exception(msg);
260       }
261       DEBTRACE( "---------------End PyNode::loadRemote function---------------" );
262     }
263 }
264
265 std::string PythonEntry::GetContainerLog(const std::string& mode, Container *container, const Task *askingTask)
266 {
267   if(mode=="local")
268     return "";
269
270   std::string msg;
271   try
272   {
273       SalomeContainer *containerCast(dynamic_cast<SalomeContainer *>(container));
274       SalomeHPContainer *objContainer2(dynamic_cast<SalomeHPContainer *>(container));
275       if(containerCast)
276         {
277           Engines::Container_var objContainer(containerCast->getContainerPtr(askingTask));
278           CORBA::String_var logname = objContainer->logfilename();
279           DEBTRACE(logname);
280           msg=logname;
281           std::string::size_type pos = msg.find(":");
282           msg=msg.substr(pos+1);
283         }
284       else if(objContainer2)
285         {
286           msg="Remote PythonNode is on HP Container : no log because no info of the location by definition of HP Container !";
287         }
288       else
289         {
290           msg="Not implemented yet for container log for that type of container !";
291         }
292   }
293   catch(...)
294   {
295       msg = "Container no longer reachable";
296   }
297   return msg;
298 }
299
300 void PythonEntry::commonRemoteLoad(InlineNode *reqNode)
301 {
302   commonRemoteLoadPart1(reqNode);
303   bool isInitializeRequested;
304   Engines::Container_var objContainer(commonRemoteLoadPart2(reqNode,isInitializeRequested));
305   commonRemoteLoadPart3(reqNode,objContainer,isInitializeRequested);
306 }
307
308 PythonNode::PythonNode(const PythonNode& other, ComposedNode *father):InlineNode(other,father),_autoSqueeze(other._autoSqueeze)
309 {
310   _implementation=IMPL_NAME;
311   {
312     AutoGIL agil;
313     _context=PyDict_New();
314     if( PyDict_SetItemString( _context, "__builtins__", getSALOMERuntime()->getBuiltins() ))
315       {
316         stringstream msg;
317         msg << "Impossible to set builtins" << __FILE__ << ":" << __LINE__;
318         _errorDetails=msg.str();
319         throw Exception(msg.str());
320       }
321   }
322 }
323
324 PythonNode::PythonNode(const std::string& name):InlineNode(name)
325 {
326   _implementation=IMPL_NAME;
327   {
328     AutoGIL agil;
329     _context=PyDict_New();
330     if( PyDict_SetItemString( _context, "__builtins__", getSALOMERuntime()->getBuiltins() ))
331       {
332         stringstream msg;
333         msg << "Impossible to set builtins" << __FILE__ << ":" << __LINE__;
334         _errorDetails=msg.str();
335         throw Exception(msg.str());
336       }
337   }
338 }
339
340 PythonNode::~PythonNode()
341 {
342   if(!CORBA::is_nil(_pynode))
343     {
344       _pynode->UnRegister();
345     }
346 }
347
348 void PythonNode::checkBasicConsistency() const throw(YACS::Exception)
349 {
350   DEBTRACE("checkBasicConsistency");
351   InlineNode::checkBasicConsistency();
352   {
353     AutoGIL agil;
354     PyObject* res;
355     res=Py_CompileString(_script.c_str(),getName().c_str(),Py_file_input);
356     if(res == NULL)
357       {
358         std::string error="";
359         PyObject* new_stderr = newPyStdOut(error);
360         PySys_SetObject((char*)"stderr", new_stderr);
361         PyErr_Print();
362         PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
363         Py_DECREF(new_stderr);
364         throw Exception(error);
365       }
366     else
367       Py_XDECREF(res);
368   }
369 }
370
371 void PythonNode::load()
372 {
373   DEBTRACE( "---------------PyNode::load function---------------" );
374   if(_mode==PythonNode::REMOTE_NAME)
375     loadRemote();
376   else
377     loadLocal();
378 }
379
380 void PythonNode::loadLocal()
381 {
382   DEBTRACE( "---------------PyNode::loadLocal function---------------" );
383   // do nothing
384 }
385
386 void PythonNode::loadRemote()
387 {
388   commonRemoteLoad(this);
389 }
390
391 void PythonNode::execute()
392 {
393   if(_mode==PythonNode::REMOTE_NAME)
394     executeRemote();
395   else
396     executeLocal();
397 }
398
399 void PythonNode::executeRemote()
400 {
401   DEBTRACE( "++++++++++++++ PyNode::executeRemote: " << getName() << " ++++++++++++++++++++" );
402   if(!_pyfuncSer)
403     throw Exception("DistributedPythonNode badly loaded");
404   //
405   if(dynamic_cast<HomogeneousPoolContainer *>(getContainer()))
406     {
407       bool dummy;
408       commonRemoteLoadPart2(this,dummy);
409       _pynode->assignNewCompiledCode(getScript().c_str());
410     }
411   //
412   Engines::pickledArgs_var serializationInputCorba(new Engines::pickledArgs);
413   {
414       AutoGIL agil;
415       PyObject *args(0),*ob(0);
416       //===========================================================================
417       // Get inputs in input ports, build a Python dict and pickle it
418       //===========================================================================
419       args = PyDict_New();
420       std::list<InputPort *>::iterator iter2;
421       int pos(0);
422       for(iter2 = _setOfInputPort.begin(); iter2 != _setOfInputPort.end(); ++iter2)
423         {
424           InputPyPort *p=(InputPyPort *)*iter2;
425           ob=p->getPyObj();
426           PyDict_SetItemString(args,p->getName().c_str(),ob);
427           pos++;
428         }
429 #ifdef _DEVDEBUG_
430       PyObject_Print(args,stderr,Py_PRINT_RAW);
431       std::cerr << endl;
432 #endif
433       PyObject *serializationInput(PyObject_CallFunctionObjArgs(_pyfuncSer,args,NULL));
434       Py_DECREF(args);
435       //The pickled string may contain NULL characters so use PyString_AsStringAndSize
436       char *serializationInputC(0);
437       Py_ssize_t len;
438       if (PyBytes_AsStringAndSize(serializationInput, &serializationInputC, &len))
439         throw Exception("DistributedPythonNode problem in python pickle");
440       serializationInputCorba->length(len);
441       for(int i=0; i < len ; i++)
442         serializationInputCorba[i]=serializationInputC[i];
443       Py_DECREF(serializationInput);
444   }
445
446   //get the list of output argument names
447   std::list<OutputPort *>::iterator iter;
448   Engines::listofstring myseq;
449   myseq.length(getNumberOfOutputPorts());
450   int pos=0;
451   for(iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); ++iter)
452     {
453       OutputPyPort *p=(OutputPyPort *)*iter;
454       myseq[pos]=p->getName().c_str();
455       DEBTRACE( "port name: " << p->getName() );
456       DEBTRACE( "port kind: " << p->edGetType()->kind() );
457       DEBTRACE( "port pos : " << pos );
458       pos++;
459     }
460   //===========================================================================
461   // Execute in remote Python node
462   //===========================================================================
463   DEBTRACE( "-----------------starting remote python invocation-----------------" );
464   Engines::pickledArgs_var resultCorba;
465   try
466     {
467       //pass outargsname and dict serialized
468       resultCorba=_pynode->execute(myseq,serializationInputCorba);
469     }
470   catch( const SALOME::SALOME_Exception& ex )
471     {
472       std::string msg="Exception on remote python invocation";
473       msg += '\n';
474       msg += ex.details.text.in();
475       _errorDetails=msg;
476       throw Exception(msg);
477     }
478   DEBTRACE( "-----------------end of remote python invocation-----------------" );
479   //===========================================================================
480   // Get results, unpickle and put them in output ports
481   //===========================================================================
482   char *resultCorbaC=new char[resultCorba->length()+1];
483   resultCorbaC[resultCorba->length()]='\0';
484   for(int i=0;i<resultCorba->length();i++)
485     resultCorbaC[i]=resultCorba[i];
486
487   {
488       AutoGIL agil;
489       PyObject *args(0),*ob(0);
490       PyObject* resultPython=PyBytes_FromStringAndSize(resultCorbaC,resultCorba->length());
491       delete [] resultCorbaC;
492       args = PyTuple_New(1);
493       PyTuple_SetItem(args,0,resultPython);
494       PyObject *finalResult=PyObject_CallObject(_pyfuncUnser,args);
495       Py_DECREF(args);
496
497       if (finalResult == NULL)
498         {
499           std::stringstream msg;
500           msg << "Conversion with pickle of output ports failed !";
501           msg << " : " << __FILE__ << ":" << __LINE__;
502           _errorDetails=msg.str();
503           throw YACS::ENGINE::ConversionException(msg.str());
504         }
505
506       DEBTRACE( "-----------------PythonNode::outputs-----------------" );
507       int nres=1;
508       if(finalResult == Py_None)
509         nres=0;
510       else if(PyTuple_Check(finalResult))
511         nres=PyTuple_Size(finalResult);
512
513       if(getNumberOfOutputPorts() != nres)
514         {
515           std::string msg="Number of output arguments : Mismatch between definition and execution";
516           Py_DECREF(finalResult);
517           _errorDetails=msg;
518           throw Exception(msg);
519         }
520
521       pos=0;
522       try
523       {
524           for(iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); ++iter)
525             {
526               OutputPyPort *p=(OutputPyPort *)*iter;
527               DEBTRACE( "port name: " << p->getName() );
528               DEBTRACE( "port kind: " << p->edGetType()->kind() );
529               DEBTRACE( "port pos : " << pos );
530               if(PyTuple_Check(finalResult))
531                 ob=PyTuple_GetItem(finalResult,pos) ;
532               else
533                 ob=finalResult;
534               DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
535               p->put(ob);
536               pos++;
537             }
538           Py_DECREF(finalResult);
539       }
540       catch(ConversionException& ex)
541       {
542           Py_DECREF(finalResult);
543           _errorDetails=ex.what();
544           throw;
545       }
546       if(_autoSqueeze)
547         squeezeMemoryRemote();
548   }
549   //
550   if(!CORBA::is_nil(_pynode))
551     {
552       _pynode->UnRegister();
553     }
554   _pynode = Engines::PyScriptNode::_nil();
555   bool dummy;
556   Engines::Container_var cont(GetContainerObj(this,dummy));
557   cont->removePyScriptNode(getName().c_str());
558   DEBTRACE( "++++++++++++++ ENDOF PyNode::executeRemote: " << getName() << " ++++++++++++++++++++" );
559 }
560
561 void PythonNode::executeLocal()
562 {
563   DEBTRACE( "++++++++++++++ PyNode::executeLocal: " << getName() << " ++++++++++++++++++++" );
564   {
565     AutoGIL agil;
566
567     DEBTRACE( "---------------PyNode::inputs---------------" );
568     list<InputPort *>::iterator iter2;
569     for(iter2 = _setOfInputPort.begin(); iter2 != _setOfInputPort.end(); iter2++)
570       {
571         InputPyPort *p=(InputPyPort *)*iter2;
572         DEBTRACE( "port name: " << p->getName() );
573         DEBTRACE( "port kind: " << p->edGetType()->kind() );
574         PyObject* ob=p->getPyObj();
575         DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
576 #ifdef _DEVDEBUG_
577         PyObject_Print(ob,stderr,Py_PRINT_RAW);
578         cerr << endl;
579 #endif
580         int ier=PyDict_SetItemString(_context,p->getName().c_str(),ob);
581         DEBTRACE( "after PyDict_SetItemString:ob refcnt: " << ob->ob_refcnt );
582       }
583
584     DEBTRACE( "---------------End PyNode::inputs---------------" );
585
586     //calculation
587     DEBTRACE( "----------------PyNode::calculation---------------" );
588     DEBTRACE(  _script );
589     DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
590
591     std::ostringstream stream;
592     stream << "/tmp/PythonNode_";
593     stream << getpid();
594
595     PyObject* code=Py_CompileString(_script.c_str(), stream.str().c_str(), Py_file_input);
596     if(code == NULL)
597       {
598         _errorDetails=""; 
599         PyObject* new_stderr = newPyStdOut(_errorDetails);
600         PySys_SetObject((char*)"stderr", new_stderr);
601         PyErr_Print();
602         PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
603         Py_DECREF(new_stderr);
604         throw Exception("Error during execution");
605       }
606     PyObject *res = PyEval_EvalCode(  code, _context, _context);
607
608     Py_DECREF(code);
609     Py_XDECREF(res);
610     DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
611     fflush(stdout);
612     fflush(stderr);
613     if(PyErr_Occurred ())
614       {
615         _errorDetails="";
616         PyObject* new_stderr = newPyStdOut(_errorDetails);
617         PySys_SetObject((char*)"stderr", new_stderr);
618         ofstream errorfile(stream.str().c_str());
619         if (errorfile.is_open())
620           {
621             errorfile << _script;
622             errorfile.close();
623           }
624         PyErr_Print();
625         PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
626         Py_DECREF(new_stderr);
627         throw Exception("Error during execution");
628       }
629
630     DEBTRACE( "-----------------PyNode::outputs-----------------" );
631     list<OutputPort *>::iterator iter;
632     try
633     {
634         for(iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); iter++)
635           {
636             OutputPyPort *p=(OutputPyPort *)*iter;
637             DEBTRACE( "port name: " << p->getName() );
638             DEBTRACE( "port kind: " << p->edGetType()->kind() );
639             PyObject *ob=PyDict_GetItemString(_context,p->getName().c_str());
640             if(ob==NULL)
641               {
642                 std::string msg="Error during execution: there is no variable ";
643                 msg=msg+p->getName()+" in node context";
644                 _errorDetails=msg;
645                 throw Exception(msg);
646               }
647             DEBTRACE( "PyNode::outputs::ob refcnt: " << ob->ob_refcnt );
648 #ifdef _DEVDEBUG_
649             PyObject_Print(ob,stderr,Py_PRINT_RAW);
650             cerr << endl;
651 #endif
652             p->put(ob);
653           }
654     }
655     catch(ConversionException& ex)
656     {
657         _errorDetails=ex.what();
658         throw;
659     }
660     if(_autoSqueeze)
661       squeezeMemory();
662     DEBTRACE( "-----------------End PyNode::outputs-----------------" );
663   }
664   DEBTRACE( "++++++++++++++ End PyNode::execute: " << getName() << " ++++++++++++++++++++" );
665 }
666
667 void PythonNode::squeezeMemorySafe()
668 {
669   AutoGIL agil;
670   if(_mode==PythonNode::REMOTE_NAME)
671     this->squeezeMemoryRemote();
672   else
673     this->squeezeMemory();
674 }
675   
676 void PythonNode::squeezeMemory()
677 {
678   for(auto p : _setOfInputPort)
679     {
680       PyDict_DelItemString(_context,p->getName().c_str());
681       InputPyPort *p2(static_cast<InputPyPort *>(p));
682       if(p2->canSafelySqueezeMemory())
683         p2->put(Py_None);
684     }
685   for(auto p : _setOfOutputPort)
686     {
687       PyDict_DelItemString(_context,p->getName().c_str());
688       OutputPyPort *p2(static_cast<OutputPyPort *>(p));
689       p2->putWithoutForward(Py_None);
690     }
691 }
692
693 void PythonNode::squeezeMemoryRemote()
694 {
695   for(auto p : _setOfInputPort)
696     {
697       InputPyPort *p2(static_cast<InputPyPort *>(p));
698       if(p2->canSafelySqueezeMemory())
699         p2->put(Py_None);
700     }
701   for(auto p : _setOfOutputPort)
702     {
703       OutputPyPort *p2(static_cast<OutputPyPort *>(p));
704       p2->putWithoutForward(Py_None);
705     }
706 }
707
708 std::string PythonNode::getContainerLog()
709 {
710   return PythonEntry::GetContainerLog(_mode,_container,this);
711 }
712
713 void PythonNode::shutdown(int level)
714 {
715   DEBTRACE("PythonNode::shutdown " << level);
716   if(_mode=="local")return;
717   if(_container)
718     {
719       if(!CORBA::is_nil(_pynode)) _pynode->UnRegister();
720       _pynode=Engines::PyScriptNode::_nil();
721       _container->shutdown(level);
722     }
723 }
724
725 Node *PythonNode::simpleClone(ComposedNode *father, bool editionOnly) const
726 {
727   return new PythonNode(*this,father);
728 }
729
730 void PythonNode::createRemoteAdaptedPyInterpretor(Engines::Container_ptr objContainer)
731 {
732   if(!CORBA::is_nil(_pynode))
733     _pynode->UnRegister();
734   _pynode=objContainer->createPyScriptNode(getName().c_str(),getScript().c_str());
735   _pynode->Register();
736 }
737
738 Engines::PyNodeBase_var PythonNode::retrieveDftRemotePyInterpretorIfAny(Engines::Container_ptr objContainer) const
739 {
740   Engines::PyScriptNode_var ret(objContainer->getDefaultPyScriptNode(getName().c_str()));
741   if(!CORBA::is_nil(ret))
742     {
743       ret->Register();
744     }
745   return Engines::PyNodeBase::_narrow(ret);
746 }
747
748 void PythonNode::assignRemotePyInterpretor(Engines::PyNodeBase_var remoteInterp)
749 {
750   if(!CORBA::is_nil(_pynode))
751     {
752       Engines::PyScriptNode_var tmpp(Engines::PyScriptNode::_narrow(remoteInterp));
753       if(_pynode->_is_equivalent(tmpp))
754         {
755           _pynode->UnRegister();
756           return ;
757         }
758     }
759   if(!CORBA::is_nil(_pynode))
760     _pynode->UnRegister();
761   _pynode=Engines::PyScriptNode::_narrow(remoteInterp);
762 }
763
764 Engines::PyNodeBase_var PythonNode::getRemoteInterpreterHandle()
765 {
766   return Engines::PyNodeBase::_narrow(_pynode);
767 }
768
769 //! Create a new node of same type with a given name
770 PythonNode* PythonNode::cloneNode(const std::string& name)
771 {
772   PythonNode* n=new PythonNode(name);
773   n->setScript(_script);
774   list<InputPort *>::iterator iter;
775   for(iter = _setOfInputPort.begin(); iter != _setOfInputPort.end(); iter++)
776     {
777       InputPyPort *p=(InputPyPort *)*iter;
778       DEBTRACE( "port name: " << p->getName() );
779       DEBTRACE( "port kind: " << p->edGetType()->kind() );
780       n->edAddInputPort(p->getName(),p->edGetType());
781     }
782   list<OutputPort *>::iterator iter2;
783   for(iter2 = _setOfOutputPort.begin(); iter2 != _setOfOutputPort.end(); iter2++)
784     {
785       OutputPyPort *p=(OutputPyPort *)*iter2;
786       DEBTRACE( "port name: " << p->getName() );
787       DEBTRACE( "port kind: " << p->edGetType()->kind() );
788       n->edAddOutputPort(p->getName(),p->edGetType());
789     }
790   return n;
791 }
792
793 void PythonNode::applyDPLScope(ComposedNode *gfn)
794 {
795   std::vector< std::pair<std::string,int> > ret(getDPLScopeInfo(gfn));
796   if(ret.empty())
797     return ;
798   //
799   PyObject *ob(0);
800   {
801     AutoGIL agil;
802     std::size_t sz(ret.size());
803     ob=PyList_New(sz);
804     for(std::size_t i=0;i<sz;i++)
805       {
806         const std::pair<std::string,int>& p(ret[i]);
807         PyObject *elt(PyTuple_New(2));
808         PyTuple_SetItem(elt,0,PyUnicode_FromString(p.first.c_str()));
809         PyTuple_SetItem(elt,1,PyLong_FromLong(p.second));
810         PyList_SetItem(ob,i,elt);
811       }
812   }
813   if(_mode==REMOTE_NAME)
814     {
815       Engines::pickledArgs_var serializationInputCorba(new Engines::pickledArgs);
816       {
817         AutoGIL agil;
818         PyObject *serializationInput(PyObject_CallFunctionObjArgs(_pyfuncSimpleSer,ob,NULL));
819         Py_XDECREF(ob);
820         char *serializationInputC(0);
821         Py_ssize_t len;
822         if (PyBytes_AsStringAndSize(serializationInput, &serializationInputC, &len))
823           throw Exception("DistributedPythonNode problem in python pickle");
824         serializationInputCorba->length(len);
825         for(int i=0; i < len ; i++)
826           serializationInputCorba[i]=serializationInputC[i];
827         Py_XDECREF(serializationInput);
828       }
829       _pynode->defineNewCustomVar(DPL_INFO_NAME,serializationInputCorba);
830     }
831   else
832     {
833       AutoGIL agil;
834       PyDict_SetItemString(_context,DPL_INFO_NAME,ob);
835       Py_XDECREF(ob);
836     }
837 }
838
839 PyFuncNode::PyFuncNode(const PyFuncNode& other, ComposedNode *father):InlineFuncNode(other,father),_pyfunc(0)
840 {
841   _implementation = PythonNode::IMPL_NAME;
842   {
843     AutoGIL agil;
844     _context=PyDict_New();
845     DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
846     if( PyDict_SetItemString( _context, "__builtins__", getSALOMERuntime()->getBuiltins() ))
847       {
848         stringstream msg;
849         msg << "Not possible to set builtins" << __FILE__ << ":" << __LINE__;
850         _errorDetails=msg.str();
851         throw Exception(msg.str());
852       }
853   }
854 }
855
856 PyFuncNode::PyFuncNode(const std::string& name): InlineFuncNode(name),_pyfunc(0)
857 {
858
859   _implementation = PythonNode::IMPL_NAME;
860   DEBTRACE( "PyFuncNode::PyFuncNode " << name );
861   {
862     AutoGIL agil;
863     _context=PyDict_New();
864     DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
865     if( PyDict_SetItemString( _context, "__builtins__", getSALOMERuntime()->getBuiltins() ))
866       {
867         stringstream msg;
868         msg << "Not possible to set builtins" << __FILE__ << ":" << __LINE__;
869         _errorDetails=msg.str();
870         throw Exception(msg.str());
871       }
872   }
873 }
874
875 PyFuncNode::~PyFuncNode()
876 {
877   if(!CORBA::is_nil(_pynode))
878     {
879       _pynode->UnRegister();
880     }
881 }
882
883 void PyFuncNode::init(bool start)
884 {
885   initCommonPartWithoutStateManagement(start);
886   if(_state == YACS::DISABLED)
887     {
888       exDisabledState(); // to refresh propagation of DISABLED state
889       return ;
890     }
891   if(start) //complete initialization
892     setState(YACS::READY);
893   else if(_state > YACS::LOADED)// WARNING FuncNode has internal vars (CEA usecase) ! Partial initialization (inside a loop). Exclusivity of funcNode.
894     setState(YACS::TORECONNECT);
895 }
896
897 void PyFuncNode::checkBasicConsistency() const throw(YACS::Exception)
898 {
899   DEBTRACE("checkBasicConsistency");
900   InlineFuncNode::checkBasicConsistency();
901   {
902     AutoGIL agil;
903     PyObject* res;
904     res=Py_CompileString(_script.c_str(),getName().c_str(),Py_file_input);
905     if(res == NULL)
906       {
907         std::string error="";
908         PyObject* new_stderr = newPyStdOut(error);
909         PySys_SetObject((char*)"stderr", new_stderr);
910         PyErr_Print();
911         PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
912         Py_DECREF(new_stderr);
913         throw Exception(error);
914       }
915     else
916       Py_XDECREF(res);
917   }
918 }
919
920 void PyFuncNode::load()
921 {
922   DEBTRACE( "---------------PyfuncNode::load function---------------" );
923   if(_mode==PythonNode::REMOTE_NAME)
924     loadRemote();
925   else
926     loadLocal();
927 }
928
929 void PyFuncNode::loadRemote()
930 {
931   commonRemoteLoad(this);
932 }
933
934 void PyFuncNode::loadLocal()
935 {
936   DEBTRACE( "---------------PyFuncNode::load function " << getName() << " ---------------" );
937   DEBTRACE(  _script );
938
939 #ifdef _DEVDEBUG_
940   list<OutputPort *>::iterator iter;
941   for(iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); iter++)
942     {
943       OutputPyPort *p=(OutputPyPort *)*iter;
944       DEBTRACE( "port name: " << p->getName() );
945       DEBTRACE( "port kind: " << p->edGetType()->kind() );
946     }
947 #endif
948
949   {
950     AutoGIL agil;
951     DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
952
953     std::ostringstream stream;
954     stream << "/tmp/PythonNode_";
955     stream << getpid();
956
957     PyObject* code=Py_CompileString(_script.c_str(), stream.str().c_str(), Py_file_input);
958     if(code == NULL)
959       {
960         _errorDetails="";
961         PyObject* new_stderr = newPyStdOut(_errorDetails);
962         PySys_SetObject((char*)"stderr", new_stderr);
963         PyErr_Print();
964         PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
965         Py_DECREF(new_stderr);
966         throw Exception("Error during execution");
967       }
968     PyObject *res = PyEval_EvalCode( code, _context, _context);
969     Py_DECREF(code);
970     Py_XDECREF(res);
971
972     DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
973     if(PyErr_Occurred ())
974       {
975         _errorDetails="";
976         PyObject* new_stderr = newPyStdOut(_errorDetails);
977         PySys_SetObject((char*)"stderr", new_stderr);
978         ofstream errorfile(stream.str().c_str());
979         if (errorfile.is_open())
980           {
981             errorfile << _script;
982             errorfile.close();
983           }
984         PyErr_Print();
985         PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
986         Py_DECREF(new_stderr);
987         throw Exception("Error during execution");
988         return;
989       }
990     _pyfunc=PyDict_GetItemString(_context,_fname.c_str());
991     DEBTRACE( "_pyfunc refcnt: " << _pyfunc->ob_refcnt );
992     if(_pyfunc == NULL)
993       {
994         _errorDetails="";
995         PyObject* new_stderr = newPyStdOut(_errorDetails);
996         PySys_SetObject((char*)"stderr", new_stderr);
997         PyErr_Print();
998         PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
999         Py_DECREF(new_stderr);
1000         throw Exception("Error during execution");
1001       }
1002     DEBTRACE( "---------------End PyFuncNode::load function---------------" );
1003   }
1004 }
1005
1006 void PyFuncNode::execute()
1007 {
1008   if(_mode==PythonNode::REMOTE_NAME)
1009     executeRemote();
1010   else
1011     executeLocal();
1012 }
1013
1014 void PyFuncNode::executeRemote()
1015 {
1016   DEBTRACE( "++++++++++++++ PyFuncNode::executeRemote: " << getName() << " ++++++++++++++++++++" );
1017   if(!_pyfuncSer)
1018     throw Exception("DistributedPythonNode badly loaded");
1019   //
1020   if(dynamic_cast<HomogeneousPoolContainer *>(getContainer()))
1021     {
1022       bool dummy;
1023       commonRemoteLoadPart2(this,dummy);
1024       _pynode->executeAnotherPieceOfCode(getScript().c_str());
1025     }
1026   //
1027   Engines::pickledArgs_var serializationInputCorba(new Engines::pickledArgs);;
1028   {
1029       AutoGIL agil;
1030       PyObject *ob(0);
1031       //===========================================================================
1032       // Get inputs in input ports, build a Python tuple and pickle it
1033       //===========================================================================
1034       PyObject *args(PyTuple_New(getNumberOfInputPorts()));
1035       int pos(0);
1036       for(std::list<InputPort *>::iterator iter2 = _setOfInputPort.begin(); iter2 != _setOfInputPort.end(); iter2++,pos++)
1037         {
1038           InputPyPort *p=(InputPyPort *)*iter2;
1039           ob=p->getPyObj();
1040           Py_INCREF(ob);
1041           PyTuple_SetItem(args,pos,ob);
1042         }
1043 #ifdef _DEVDEBUG_
1044       PyObject_Print(args,stderr,Py_PRINT_RAW);
1045       std::cerr << endl;
1046 #endif
1047       PyObject *serializationInput=PyObject_CallObject(_pyfuncSer,args);
1048       Py_DECREF(args);
1049       //The pickled string may contain NULL characters so use PyString_AsStringAndSize
1050       char *serializationInputC(0);
1051       Py_ssize_t len;
1052       if (PyBytes_AsStringAndSize(serializationInput, &serializationInputC, &len))
1053         throw Exception("DistributedPythonNode problem in python pickle");
1054
1055       serializationInputCorba->length(len);
1056       for(int i=0; i < len ; i++)
1057         serializationInputCorba[i]=serializationInputC[i];
1058       Py_DECREF(serializationInput);
1059   }
1060
1061   //===========================================================================
1062   // Execute in remote Python node
1063   //===========================================================================
1064   DEBTRACE( "-----------------starting remote python invocation-----------------" );
1065   Engines::pickledArgs_var resultCorba;
1066   try
1067     {
1068       resultCorba=_pynode->execute(getFname().c_str(),serializationInputCorba);
1069     }
1070   catch( const SALOME::SALOME_Exception& ex )
1071     {
1072       std::string msg="Exception on remote python invocation";
1073       msg += '\n';
1074       msg += ex.details.text.in();
1075       _errorDetails=msg;
1076       throw Exception(msg);
1077     }
1078   DEBTRACE( "-----------------end of remote python invocation-----------------" );
1079   //===========================================================================
1080   // Get results, unpickle and put them in output ports
1081   //===========================================================================
1082   char *resultCorbaC=new char[resultCorba->length()+1];
1083   resultCorbaC[resultCorba->length()]='\0';
1084   for(int i=0;i<resultCorba->length();i++)
1085     resultCorbaC[i]=resultCorba[i];
1086
1087   {
1088       AutoGIL agil;
1089
1090       PyObject *resultPython(PyBytes_FromStringAndSize(resultCorbaC,resultCorba->length()));
1091       delete [] resultCorbaC;
1092       PyObject *args(PyTuple_New(1)),*ob(0);
1093       PyTuple_SetItem(args,0,resultPython);
1094       PyObject *finalResult=PyObject_CallObject(_pyfuncUnser,args);
1095       Py_DECREF(args);
1096
1097       DEBTRACE( "-----------------PythonNode::outputs-----------------" );
1098       int nres=1;
1099       if(finalResult == Py_None)
1100         nres=0;
1101       else if(PyTuple_Check(finalResult))
1102         nres=PyTuple_Size(finalResult);
1103
1104       if(getNumberOfOutputPorts() != nres)
1105         {
1106           std::string msg="Number of output arguments : Mismatch between definition and execution";
1107           Py_DECREF(finalResult);
1108           _errorDetails=msg;
1109           throw Exception(msg);
1110         }
1111
1112       try
1113       {
1114           int pos(0);
1115           for(std::list<OutputPort *>::iterator iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); iter++, pos++)
1116             {
1117               OutputPyPort *p=(OutputPyPort *)*iter;
1118               DEBTRACE( "port name: " << p->getName() );
1119               DEBTRACE( "port kind: " << p->edGetType()->kind() );
1120               DEBTRACE( "port pos : " << pos );
1121               if(PyTuple_Check(finalResult))
1122                 ob=PyTuple_GetItem(finalResult,pos) ;
1123               else
1124                 ob=finalResult;
1125               DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
1126               p->put(ob);
1127             }
1128           Py_DECREF(finalResult);
1129       }
1130       catch(ConversionException& ex)
1131       {
1132           Py_DECREF(finalResult);
1133           _errorDetails=ex.what();
1134           throw;
1135       }
1136   }
1137
1138   DEBTRACE( "++++++++++++++ ENDOF PyFuncNode::executeRemote: " << getName() << " ++++++++++++++++++++" );
1139 }
1140
1141 void PyFuncNode::executeLocal()
1142 {
1143   DEBTRACE( "++++++++++++++ PyFuncNode::execute: " << getName() << " ++++++++++++++++++++" );
1144
1145   int pos=0;
1146   PyObject* ob;
1147   if(!_pyfunc)throw Exception("PyFuncNode badly loaded");
1148   {
1149       AutoGIL agil;
1150       DEBTRACE( "---------------PyFuncNode::inputs---------------" );
1151       PyObject* args = PyTuple_New(getNumberOfInputPorts()) ;
1152       list<InputPort *>::iterator iter2;
1153       for(iter2 = _setOfInputPort.begin(); iter2 != _setOfInputPort.end(); iter2++)
1154         {
1155           InputPyPort *p=(InputPyPort *)*iter2;
1156           DEBTRACE( "port name: " << p->getName() );
1157           DEBTRACE( "port kind: " << p->edGetType()->kind() );
1158           ob=p->getPyObj();
1159 #ifdef _DEVDEBUG_
1160           PyObject_Print(ob,stderr,Py_PRINT_RAW);
1161           cerr << endl;
1162 #endif
1163           DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
1164           Py_INCREF(ob);
1165           PyTuple_SetItem(args,pos,ob);
1166           DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
1167           pos++;
1168         }
1169       DEBTRACE( "---------------End PyFuncNode::inputs---------------" );
1170
1171       DEBTRACE( "----------------PyFuncNode::calculation---------------" );
1172 #ifdef _DEVDEBUG_
1173       PyObject_Print(_pyfunc,stderr,Py_PRINT_RAW);
1174       cerr << endl;
1175       PyObject_Print(args,stderr,Py_PRINT_RAW);
1176       cerr << endl;
1177 #endif
1178       DEBTRACE( "_pyfunc refcnt: " << _pyfunc->ob_refcnt );
1179       PyObject* result = PyObject_CallObject( _pyfunc , args ) ;
1180       DEBTRACE( "_pyfunc refcnt: " << _pyfunc->ob_refcnt );
1181       Py_DECREF(args);
1182       fflush(stdout);
1183       fflush(stderr);
1184       if(result == NULL)
1185         {
1186           _errorDetails="";
1187           PyObject* new_stderr = newPyStdOut(_errorDetails);
1188           PySys_SetObject((char*)"stderr", new_stderr);
1189           std::ostringstream stream;
1190           stream << "/tmp/PythonNode_";
1191           stream << getpid();
1192           ofstream errorfile(stream.str().c_str());
1193           if (errorfile.is_open())
1194             {
1195               errorfile << _script;
1196               errorfile.close();
1197             }
1198           PyErr_Print();
1199           PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
1200           Py_DECREF(new_stderr);
1201           throw Exception("Error during execution");
1202         }
1203       DEBTRACE( "----------------End PyFuncNode::calculation---------------" );
1204
1205       DEBTRACE( "-----------------PyFuncNode::outputs-----------------" );
1206       int nres=1;
1207       if(result == Py_None)
1208         nres=0;
1209       else if(PyTuple_Check(result))
1210         nres=PyTuple_Size(result);
1211
1212       if(getNumberOfOutputPorts() != nres)
1213         {
1214           std::string msg="Number of output arguments : Mismatch between definition and execution";
1215           Py_DECREF(result);
1216           _errorDetails=msg;
1217           throw Exception(msg);
1218         }
1219
1220       pos=0;
1221 #ifdef _DEVDEBUG_
1222       PyObject_Print(result,stderr,Py_PRINT_RAW);
1223       cerr << endl;
1224 #endif
1225       list<OutputPort *>::iterator iter;
1226       try
1227       {
1228           for(iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); iter++)
1229             {
1230               OutputPyPort *p=(OutputPyPort *)*iter;
1231               DEBTRACE( "port name: " << p->getName() );
1232               DEBTRACE( "port kind: " << p->edGetType()->kind() );
1233               DEBTRACE( "port pos : " << pos );
1234               if(PyTuple_Check(result))ob=PyTuple_GetItem(result,pos) ;
1235               else ob=result;
1236               DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
1237 #ifdef _DEVDEBUG_
1238               PyObject_Print(ob,stderr,Py_PRINT_RAW);
1239               cerr << endl;
1240 #endif
1241               p->put(ob);
1242               pos++;
1243             }
1244       }
1245       catch(ConversionException& ex)
1246       {
1247           Py_DECREF(result);
1248           _errorDetails=ex.what();
1249           throw;
1250       }
1251       DEBTRACE( "-----------------End PyFuncNode::outputs-----------------" );
1252       Py_DECREF(result);
1253   }
1254   DEBTRACE( "++++++++++++++ End PyFuncNode::execute: " << getName() << " ++++++++++++++++++++" );
1255 }
1256
1257 Node *PyFuncNode::simpleClone(ComposedNode *father, bool editionOnly) const
1258 {
1259   return new PyFuncNode(*this,father);
1260 }
1261
1262 void PyFuncNode::createRemoteAdaptedPyInterpretor(Engines::Container_ptr objContainer)
1263 {
1264   if(!CORBA::is_nil(_pynode))
1265     _pynode->UnRegister();
1266   _pynode=objContainer->createPyNode(getName().c_str(),getScript().c_str());
1267 }
1268
1269 Engines::PyNodeBase_var PyFuncNode::retrieveDftRemotePyInterpretorIfAny(Engines::Container_ptr objContainer) const
1270 {
1271   Engines::PyNode_var ret(objContainer->getDefaultPyNode(getName().c_str()));
1272   if(!CORBA::is_nil(ret))
1273     {
1274       ret->Register();
1275     }
1276   return Engines::PyNodeBase::_narrow(ret);
1277 }
1278
1279 void PyFuncNode::assignRemotePyInterpretor(Engines::PyNodeBase_var remoteInterp)
1280 {
1281   if(!CORBA::is_nil(_pynode))
1282     {
1283       Engines::PyNode_var tmpp(Engines::PyNode::_narrow(remoteInterp));
1284       if(_pynode->_is_equivalent(tmpp))
1285         return ;
1286     }
1287   if(!CORBA::is_nil(_pynode))
1288     _pynode->UnRegister();
1289   _pynode=Engines::PyNode::_narrow(remoteInterp);
1290 }
1291
1292 Engines::PyNodeBase_var PyFuncNode::getRemoteInterpreterHandle()
1293 {
1294   return Engines::PyNodeBase::_narrow(_pynode);
1295 }
1296
1297 //! Create a new node of same type with a given name
1298 PyFuncNode* PyFuncNode::cloneNode(const std::string& name)
1299 {
1300   PyFuncNode* n=new PyFuncNode(name);
1301   n->setScript(_script);
1302   n->setFname(_fname);
1303   list<InputPort *>::iterator iter;
1304   for(iter = _setOfInputPort.begin(); iter != _setOfInputPort.end(); iter++)
1305     {
1306       InputPyPort *p=(InputPyPort *)*iter;
1307       n->edAddInputPort(p->getName(),p->edGetType());
1308     }
1309   list<OutputPort *>::iterator iter2;
1310   for(iter2 = _setOfOutputPort.begin(); iter2 != _setOfOutputPort.end(); iter2++)
1311     {
1312       OutputPyPort *p=(OutputPyPort *)*iter2;
1313       n->edAddOutputPort(p->getName(),p->edGetType());
1314     }
1315   return n;
1316 }
1317
1318 std::string PyFuncNode::getContainerLog()
1319 {
1320   return PythonEntry::GetContainerLog(_mode,_container,this);
1321 }
1322
1323 void PyFuncNode::shutdown(int level)
1324 {
1325   DEBTRACE("PyFuncNode::shutdown " << level);
1326   if(_mode=="local")return;
1327   if(_container)
1328     {
1329       if(!CORBA::is_nil(_pynode)) _pynode->UnRegister();
1330       _pynode=Engines::PyNode::_nil();
1331       _container->shutdown(level);
1332     }
1333 }
1334