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