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