Salome HOME
GUI update for workload manager.
[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       isContAlreadyStarted=container->isAlreadyStarted(reqNode);
100       if(!isContAlreadyStarted)
101         {
102           try
103           {
104             if(hasImposedResource())
105               container->start(reqNode, _imposedResource, _imposedContainer);
106             else
107               container->start(reqNode);
108           }
109           catch(Exception& e)
110           {
111               reqNode->setErrorDetails(e.what());
112               throw e;
113           }
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("DistributedPythonNode 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(!storeContext())
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 std::string PythonNode::pythonEntryName()const
746 {
747   if(storeContext())
748     return "DEFAULT_NAME_FOR_UNIQUE_PYTHON_NODE_ENTRY";
749   else
750     return getName();
751 }
752
753 bool PythonNode::storeContext()const
754 {
755   bool found = false;
756   if(_container)
757     found = _container->storeContext();
758   return found;
759 }
760
761 Node *PythonNode::simpleClone(ComposedNode *father, bool editionOnly) const
762 {
763   return new PythonNode(*this,father);
764 }
765
766 void PythonNode::createRemoteAdaptedPyInterpretor(Engines::Container_ptr objContainer)
767 {
768   if(!CORBA::is_nil(_pynode))
769     _pynode->UnRegister();
770   _pynode=objContainer->createPyScriptNode(pythonEntryName().c_str(),getScript().c_str());
771   _pynode->Register();
772 }
773
774 Engines::PyNodeBase_var PythonNode::retrieveDftRemotePyInterpretorIfAny(Engines::Container_ptr objContainer) const
775 {
776   Engines::PyScriptNode_var ret(objContainer->getDefaultPyScriptNode(pythonEntryName().c_str()));
777   if(!CORBA::is_nil(ret))
778     {
779       ret->Register();
780     }
781   return Engines::PyNodeBase::_narrow(ret);
782 }
783
784 void PythonNode::assignRemotePyInterpretor(Engines::PyNodeBase_var remoteInterp)
785 {
786   if(CORBA::is_nil(_pynode))
787     _pynode=Engines::PyScriptNode::_narrow(remoteInterp);
788   else
789   {
790     Engines::PyScriptNode_var tmpp(Engines::PyScriptNode::_narrow(remoteInterp));
791     if(!_pynode->_is_equivalent(tmpp))
792     {
793       _pynode->UnRegister();
794       _pynode=Engines::PyScriptNode::_narrow(remoteInterp);
795     }
796   }
797   _pynode->assignNewCompiledCode(getScript().c_str());
798 }
799
800 Engines::PyNodeBase_var PythonNode::getRemoteInterpreterHandle()
801 {
802   return Engines::PyNodeBase::_narrow(_pynode);
803 }
804
805 //! Create a new node of same type with a given name
806 PythonNode* PythonNode::cloneNode(const std::string& name)
807 {
808   PythonNode* n=new PythonNode(name);
809   n->setScript(_script);
810   list<InputPort *>::iterator iter;
811   for(iter = _setOfInputPort.begin(); iter != _setOfInputPort.end(); iter++)
812     {
813       InputPyPort *p=(InputPyPort *)*iter;
814       DEBTRACE( "port name: " << p->getName() );
815       DEBTRACE( "port kind: " << p->edGetType()->kind() );
816       n->edAddInputPort(p->getName(),p->edGetType());
817     }
818   list<OutputPort *>::iterator iter2;
819   for(iter2 = _setOfOutputPort.begin(); iter2 != _setOfOutputPort.end(); iter2++)
820     {
821       OutputPyPort *p=(OutputPyPort *)*iter2;
822       DEBTRACE( "port name: " << p->getName() );
823       DEBTRACE( "port kind: " << p->edGetType()->kind() );
824       n->edAddOutputPort(p->getName(),p->edGetType());
825     }
826   return n;
827 }
828
829 void PythonNode::applyDPLScope(ComposedNode *gfn)
830 {
831   std::vector< std::pair<std::string,int> > ret(getDPLScopeInfo(gfn));
832   if(ret.empty())
833     return ;
834   //
835   PyObject *ob(0);
836   {
837     AutoGIL agil;
838     std::size_t sz(ret.size());
839     ob=PyList_New(sz);
840     for(std::size_t i=0;i<sz;i++)
841       {
842         const std::pair<std::string,int>& p(ret[i]);
843         PyObject *elt(PyTuple_New(2));
844         PyTuple_SetItem(elt,0,PyUnicode_FromString(p.first.c_str()));
845         PyTuple_SetItem(elt,1,PyLong_FromLong(p.second));
846         PyList_SetItem(ob,i,elt);
847       }
848   }
849   if(_mode==REMOTE_NAME)
850     {
851       Engines::pickledArgs_var serializationInputCorba(new Engines::pickledArgs);
852       {
853         AutoGIL agil;
854         PyObject *serializationInput(PyObject_CallFunctionObjArgs(_pyfuncSimpleSer,ob,NULL));
855         Py_XDECREF(ob);
856         char *serializationInputC(0);
857         Py_ssize_t len;
858         if (PyBytes_AsStringAndSize(serializationInput, &serializationInputC, &len))
859           throw Exception("DistributedPythonNode problem in python pickle");
860         serializationInputCorba->length(len);
861         for(int i=0; i < len ; i++)
862           serializationInputCorba[i]=serializationInputC[i];
863         Py_XDECREF(serializationInput);
864       }
865       _pynode->defineNewCustomVar(DPL_INFO_NAME,serializationInputCorba);
866     }
867   else
868     {
869       AutoGIL agil;
870       PyDict_SetItemString(_context,DPL_INFO_NAME,ob);
871       Py_XDECREF(ob);
872     }
873 }
874
875 PyFuncNode::PyFuncNode(const PyFuncNode& other, ComposedNode *father):InlineFuncNode(other,father),_pyfunc(0)
876 {
877   _implementation = PythonNode::IMPL_NAME;
878   {
879     AutoGIL agil;
880     _context=PyDict_New();
881     DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
882     if( PyDict_SetItemString( _context, "__builtins__", getSALOMERuntime()->getBuiltins() ))
883       {
884         stringstream msg;
885         msg << "Not possible to set builtins" << __FILE__ << ":" << __LINE__;
886         _errorDetails=msg.str();
887         throw Exception(msg.str());
888       }
889   }
890 }
891
892 PyFuncNode::PyFuncNode(const std::string& name): InlineFuncNode(name),_pyfunc(0)
893 {
894
895   _implementation = PythonNode::IMPL_NAME;
896   DEBTRACE( "PyFuncNode::PyFuncNode " << name );
897   {
898     AutoGIL agil;
899     _context=PyDict_New();
900     DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
901     if( PyDict_SetItemString( _context, "__builtins__", getSALOMERuntime()->getBuiltins() ))
902       {
903         stringstream msg;
904         msg << "Not possible to set builtins" << __FILE__ << ":" << __LINE__;
905         _errorDetails=msg.str();
906         throw Exception(msg.str());
907       }
908   }
909 }
910
911 PyFuncNode::~PyFuncNode()
912 {
913   if(!CORBA::is_nil(_pynode))
914     {
915       _pynode->UnRegister();
916     }
917 }
918
919 void PyFuncNode::init(bool start)
920 {
921   initCommonPartWithoutStateManagement(start);
922   if(_state == YACS::DISABLED)
923     {
924       exDisabledState(); // to refresh propagation of DISABLED state
925       return ;
926     }
927   if(start) //complete initialization
928     setState(YACS::READY);
929   else if(_state > YACS::LOADED)// WARNING FuncNode has internal vars (CEA usecase) ! Partial initialization (inside a loop). Exclusivity of funcNode.
930     setState(YACS::TORECONNECT);
931 }
932
933 void PyFuncNode::checkBasicConsistency() const 
934 {
935   DEBTRACE("checkBasicConsistency");
936   InlineFuncNode::checkBasicConsistency();
937   {
938     AutoGIL agil;
939     PyObject* res;
940     res=Py_CompileString(_script.c_str(),getName().c_str(),Py_file_input);
941     if(res == NULL)
942       {
943         std::string error="";
944         PyObject* new_stderr = newPyStdOut(error);
945         PySys_SetObject((char*)"stderr", new_stderr);
946         PyErr_Print();
947         PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
948         Py_DECREF(new_stderr);
949         throw Exception(error);
950       }
951     else
952       Py_XDECREF(res);
953   }
954 }
955
956 void PyFuncNode::load()
957 {
958   DEBTRACE( "---------------PyfuncNode::load function---------------" );
959   if(_mode==PythonNode::REMOTE_NAME)
960     loadRemote();
961   else
962     loadLocal();
963 }
964
965 void PyFuncNode::loadRemote()
966 {
967   commonRemoteLoad(this);
968 }
969
970 void PyFuncNode::loadLocal()
971 {
972   DEBTRACE( "---------------PyFuncNode::load function " << getName() << " ---------------" );
973   DEBTRACE(  _script );
974
975 #ifdef _DEVDEBUG_
976   list<OutputPort *>::iterator iter;
977   for(iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); iter++)
978     {
979       OutputPyPort *p=(OutputPyPort *)*iter;
980       DEBTRACE( "port name: " << p->getName() );
981       DEBTRACE( "port kind: " << p->edGetType()->kind() );
982     }
983 #endif
984
985   {
986     AutoGIL agil;
987     DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
988
989     std::ostringstream stream;
990     stream << "/tmp/PythonNode_";
991     stream << getpid();
992
993     PyObject* code=Py_CompileString(_script.c_str(), stream.str().c_str(), Py_file_input);
994     if(code == NULL)
995       {
996         _errorDetails="";
997         PyObject* new_stderr = newPyStdOut(_errorDetails);
998         PySys_SetObject((char*)"stderr", new_stderr);
999         PyErr_Print();
1000         PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
1001         Py_DECREF(new_stderr);
1002         throw Exception("Error during execution");
1003       }
1004     PyObject *res = PyEval_EvalCode( code, _context, _context);
1005     Py_DECREF(code);
1006     Py_XDECREF(res);
1007
1008     DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
1009     if(PyErr_Occurred ())
1010       {
1011         _errorDetails="";
1012         PyObject* new_stderr = newPyStdOut(_errorDetails);
1013         PySys_SetObject((char*)"stderr", new_stderr);
1014         ofstream errorfile(stream.str().c_str());
1015         if (errorfile.is_open())
1016           {
1017             errorfile << _script;
1018             errorfile.close();
1019           }
1020         PyErr_Print();
1021         PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
1022         Py_DECREF(new_stderr);
1023         throw Exception("Error during execution");
1024         return;
1025       }
1026     _pyfunc=PyDict_GetItemString(_context,_fname.c_str());
1027     DEBTRACE( "_pyfunc refcnt: " << _pyfunc->ob_refcnt );
1028     if(_pyfunc == NULL)
1029       {
1030         _errorDetails="";
1031         PyObject* new_stderr = newPyStdOut(_errorDetails);
1032         PySys_SetObject((char*)"stderr", new_stderr);
1033         PyErr_Print();
1034         PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
1035         Py_DECREF(new_stderr);
1036         throw Exception("Error during execution");
1037       }
1038     DEBTRACE( "---------------End PyFuncNode::load function---------------" );
1039   }
1040 }
1041
1042 void PyFuncNode::execute()
1043 {
1044   if(_mode==PythonNode::REMOTE_NAME)
1045     executeRemote();
1046   else
1047     executeLocal();
1048 }
1049
1050 void PyFuncNode::executeRemote()
1051 {
1052   DEBTRACE( "++++++++++++++ PyFuncNode::executeRemote: " << getName() << " ++++++++++++++++++++" );
1053   if(!_pyfuncSer)
1054     throw Exception("DistributedPythonNode badly loaded");
1055   //
1056   if(dynamic_cast<HomogeneousPoolContainer *>(getContainer()))
1057     {
1058       bool dummy;
1059       loadPythonAdapter(this,dummy);
1060       _pynode->executeAnotherPieceOfCode(getScript().c_str());
1061     }
1062   //
1063   Engines::pickledArgs_var serializationInputCorba(new Engines::pickledArgs);;
1064   {
1065       AutoGIL agil;
1066       PyObject *ob(0);
1067       //===========================================================================
1068       // Get inputs in input ports, build a Python tuple and pickle it
1069       //===========================================================================
1070       PyObject *args(PyTuple_New(getNumberOfInputPorts()));
1071       int pos(0);
1072       for(std::list<InputPort *>::iterator iter2 = _setOfInputPort.begin(); iter2 != _setOfInputPort.end(); iter2++,pos++)
1073         {
1074           InputPyPort *p=(InputPyPort *)*iter2;
1075           ob=p->getPyObj();
1076           Py_INCREF(ob);
1077           PyTuple_SetItem(args,pos,ob);
1078         }
1079 #ifdef _DEVDEBUG_
1080       PyObject_Print(args,stderr,Py_PRINT_RAW);
1081       std::cerr << endl;
1082 #endif
1083       PyObject *serializationInput=PyObject_CallObject(_pyfuncSer,args);
1084       Py_DECREF(args);
1085       //The pickled string may contain NULL characters so use PyString_AsStringAndSize
1086       char *serializationInputC(0);
1087       Py_ssize_t len;
1088       if (PyBytes_AsStringAndSize(serializationInput, &serializationInputC, &len))
1089         throw Exception("DistributedPythonNode problem in python pickle");
1090
1091       serializationInputCorba->length(len);
1092       for(int i=0; i < len ; i++)
1093         serializationInputCorba[i]=serializationInputC[i];
1094       Py_DECREF(serializationInput);
1095   }
1096
1097   //===========================================================================
1098   // Execute in remote Python node
1099   //===========================================================================
1100   DEBTRACE( "-----------------starting remote python invocation-----------------" );
1101   Engines::pickledArgs_var resultCorba;
1102   try
1103     {
1104       resultCorba=_pynode->execute(getFname().c_str(),serializationInputCorba);
1105     }
1106   catch( const SALOME::SALOME_Exception& ex )
1107     {
1108       std::string msg="Exception on remote python invocation";
1109       msg += '\n';
1110       msg += ex.details.text.in();
1111       _errorDetails=msg;
1112       throw Exception(msg);
1113     }
1114   DEBTRACE( "-----------------end of remote python invocation-----------------" );
1115   //===========================================================================
1116   // Get results, unpickle and put them in output ports
1117   //===========================================================================
1118   char *resultCorbaC=new char[resultCorba->length()+1];
1119   resultCorbaC[resultCorba->length()]='\0';
1120   for(int i=0;i<resultCorba->length();i++)
1121     resultCorbaC[i]=resultCorba[i];
1122
1123   {
1124       AutoGIL agil;
1125
1126       PyObject *resultPython(PyBytes_FromStringAndSize(resultCorbaC,resultCorba->length()));
1127       delete [] resultCorbaC;
1128       PyObject *args(PyTuple_New(1)),*ob(0);
1129       PyTuple_SetItem(args,0,resultPython);
1130       PyObject *finalResult=PyObject_CallObject(_pyfuncUnser,args);
1131       Py_DECREF(args);
1132
1133       DEBTRACE( "-----------------PythonNode::outputs-----------------" );
1134       int nres=1;
1135       if(finalResult == Py_None)
1136         nres=0;
1137       else if(PyTuple_Check(finalResult))
1138         nres=PyTuple_Size(finalResult);
1139
1140       if(getNumberOfOutputPorts() != nres)
1141         {
1142           std::string msg="Number of output arguments : Mismatch between definition and execution";
1143           Py_DECREF(finalResult);
1144           _errorDetails=msg;
1145           throw Exception(msg);
1146         }
1147
1148       try
1149       {
1150           int pos(0);
1151           for(std::list<OutputPort *>::iterator iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); iter++, pos++)
1152             {
1153               OutputPyPort *p=(OutputPyPort *)*iter;
1154               DEBTRACE( "port name: " << p->getName() );
1155               DEBTRACE( "port kind: " << p->edGetType()->kind() );
1156               DEBTRACE( "port pos : " << pos );
1157               if(PyTuple_Check(finalResult))
1158                 ob=PyTuple_GetItem(finalResult,pos) ;
1159               else
1160                 ob=finalResult;
1161               DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
1162               p->put(ob);
1163             }
1164           Py_DECREF(finalResult);
1165       }
1166       catch(ConversionException& ex)
1167       {
1168           Py_DECREF(finalResult);
1169           _errorDetails=ex.what();
1170           throw;
1171       }
1172   }
1173
1174   DEBTRACE( "++++++++++++++ ENDOF PyFuncNode::executeRemote: " << getName() << " ++++++++++++++++++++" );
1175 }
1176
1177 void PyFuncNode::executeLocal()
1178 {
1179   DEBTRACE( "++++++++++++++ PyFuncNode::execute: " << getName() << " ++++++++++++++++++++" );
1180
1181   int pos=0;
1182   PyObject* ob;
1183   if(!_pyfunc)throw Exception("PyFuncNode badly loaded");
1184   {
1185       AutoGIL agil;
1186       DEBTRACE( "---------------PyFuncNode::inputs---------------" );
1187       PyObject* args = PyTuple_New(getNumberOfInputPorts()) ;
1188       list<InputPort *>::iterator iter2;
1189       for(iter2 = _setOfInputPort.begin(); iter2 != _setOfInputPort.end(); iter2++)
1190         {
1191           InputPyPort *p=(InputPyPort *)*iter2;
1192           DEBTRACE( "port name: " << p->getName() );
1193           DEBTRACE( "port kind: " << p->edGetType()->kind() );
1194           ob=p->getPyObj();
1195 #ifdef _DEVDEBUG_
1196           PyObject_Print(ob,stderr,Py_PRINT_RAW);
1197           cerr << endl;
1198 #endif
1199           DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
1200           Py_INCREF(ob);
1201           PyTuple_SetItem(args,pos,ob);
1202           DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
1203           pos++;
1204         }
1205       DEBTRACE( "---------------End PyFuncNode::inputs---------------" );
1206
1207       DEBTRACE( "----------------PyFuncNode::calculation---------------" );
1208 #ifdef _DEVDEBUG_
1209       PyObject_Print(_pyfunc,stderr,Py_PRINT_RAW);
1210       cerr << endl;
1211       PyObject_Print(args,stderr,Py_PRINT_RAW);
1212       cerr << endl;
1213 #endif
1214       DEBTRACE( "_pyfunc refcnt: " << _pyfunc->ob_refcnt );
1215       PyObject* result = PyObject_CallObject( _pyfunc , args ) ;
1216       DEBTRACE( "_pyfunc refcnt: " << _pyfunc->ob_refcnt );
1217       Py_DECREF(args);
1218       fflush(stdout);
1219       fflush(stderr);
1220       if(result == NULL)
1221         {
1222           _errorDetails="";
1223           PyObject* new_stderr = newPyStdOut(_errorDetails);
1224           PySys_SetObject((char*)"stderr", new_stderr);
1225           std::ostringstream stream;
1226           stream << "/tmp/PythonNode_";
1227           stream << getpid();
1228           ofstream errorfile(stream.str().c_str());
1229           if (errorfile.is_open())
1230             {
1231               errorfile << _script;
1232               errorfile.close();
1233             }
1234           PyErr_Print();
1235           PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
1236           Py_DECREF(new_stderr);
1237           throw Exception("Error during execution");
1238         }
1239       DEBTRACE( "----------------End PyFuncNode::calculation---------------" );
1240
1241       DEBTRACE( "-----------------PyFuncNode::outputs-----------------" );
1242       int nres=1;
1243       if(result == Py_None)
1244         nres=0;
1245       else if(PyTuple_Check(result))
1246         nres=PyTuple_Size(result);
1247
1248       if(getNumberOfOutputPorts() != nres)
1249         {
1250           std::string msg="Number of output arguments : Mismatch between definition and execution";
1251           Py_DECREF(result);
1252           _errorDetails=msg;
1253           throw Exception(msg);
1254         }
1255
1256       pos=0;
1257 #ifdef _DEVDEBUG_
1258       PyObject_Print(result,stderr,Py_PRINT_RAW);
1259       cerr << endl;
1260 #endif
1261       list<OutputPort *>::iterator iter;
1262       try
1263       {
1264           for(iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); iter++)
1265             {
1266               OutputPyPort *p=(OutputPyPort *)*iter;
1267               DEBTRACE( "port name: " << p->getName() );
1268               DEBTRACE( "port kind: " << p->edGetType()->kind() );
1269               DEBTRACE( "port pos : " << pos );
1270               if(PyTuple_Check(result))ob=PyTuple_GetItem(result,pos) ;
1271               else ob=result;
1272               DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
1273 #ifdef _DEVDEBUG_
1274               PyObject_Print(ob,stderr,Py_PRINT_RAW);
1275               cerr << endl;
1276 #endif
1277               p->put(ob);
1278               pos++;
1279             }
1280       }
1281       catch(ConversionException& ex)
1282       {
1283           Py_DECREF(result);
1284           _errorDetails=ex.what();
1285           throw;
1286       }
1287       DEBTRACE( "-----------------End PyFuncNode::outputs-----------------" );
1288       Py_DECREF(result);
1289   }
1290   DEBTRACE( "++++++++++++++ End PyFuncNode::execute: " << getName() << " ++++++++++++++++++++" );
1291 }
1292
1293 Node *PyFuncNode::simpleClone(ComposedNode *father, bool editionOnly) const
1294 {
1295   return new PyFuncNode(*this,father);
1296 }
1297
1298 void PyFuncNode::createRemoteAdaptedPyInterpretor(Engines::Container_ptr objContainer)
1299 {
1300   if(!CORBA::is_nil(_pynode))
1301     _pynode->UnRegister();
1302   _pynode=objContainer->createPyNode(getName().c_str(),getScript().c_str());
1303 }
1304
1305 Engines::PyNodeBase_var PyFuncNode::retrieveDftRemotePyInterpretorIfAny(Engines::Container_ptr objContainer) const
1306 {
1307   Engines::PyNode_var ret(objContainer->getDefaultPyNode(getName().c_str()));
1308   if(!CORBA::is_nil(ret))
1309     {
1310       ret->Register();
1311     }
1312   return Engines::PyNodeBase::_narrow(ret);
1313 }
1314
1315 void PyFuncNode::assignRemotePyInterpretor(Engines::PyNodeBase_var remoteInterp)
1316 {
1317   if(!CORBA::is_nil(_pynode))
1318     {
1319       Engines::PyNode_var tmpp(Engines::PyNode::_narrow(remoteInterp));
1320       if(_pynode->_is_equivalent(tmpp))
1321         return ;
1322     }
1323   if(!CORBA::is_nil(_pynode))
1324     _pynode->UnRegister();
1325   _pynode=Engines::PyNode::_narrow(remoteInterp);
1326 }
1327
1328 Engines::PyNodeBase_var PyFuncNode::getRemoteInterpreterHandle()
1329 {
1330   return Engines::PyNodeBase::_narrow(_pynode);
1331 }
1332
1333 //! Create a new node of same type with a given name
1334 PyFuncNode* PyFuncNode::cloneNode(const std::string& name)
1335 {
1336   PyFuncNode* n=new PyFuncNode(name);
1337   n->setScript(_script);
1338   n->setFname(_fname);
1339   list<InputPort *>::iterator iter;
1340   for(iter = _setOfInputPort.begin(); iter != _setOfInputPort.end(); iter++)
1341     {
1342       InputPyPort *p=(InputPyPort *)*iter;
1343       n->edAddInputPort(p->getName(),p->edGetType());
1344     }
1345   list<OutputPort *>::iterator iter2;
1346   for(iter2 = _setOfOutputPort.begin(); iter2 != _setOfOutputPort.end(); iter2++)
1347     {
1348       OutputPyPort *p=(OutputPyPort *)*iter2;
1349       n->edAddOutputPort(p->getName(),p->edGetType());
1350     }
1351   return n;
1352 }
1353
1354 std::string PyFuncNode::getContainerLog()
1355 {
1356   return PythonEntry::GetContainerLog(_mode,_container,this);
1357 }
1358
1359 void PyFuncNode::shutdown(int level)
1360 {
1361   DEBTRACE("PyFuncNode::shutdown " << level);
1362   if(_mode=="local")return;
1363   if(_container)
1364     {
1365       if(!CORBA::is_nil(_pynode)) _pynode->UnRegister();
1366       _pynode=Engines::PyNode::_nil();
1367       _container->shutdown(level);
1368     }
1369 }
1370
1371 void PyFuncNode::imposeResource(const std::string& resource_name,
1372                                 const std::string& container_name)
1373 {
1374   if(!resource_name.empty() && !container_name.empty())
1375   {
1376     _imposedResource = resource_name;
1377     _imposedContainer = container_name;
1378   }
1379 }
1380
1381 bool PyFuncNode::canAcceptImposedResource()
1382 {
1383   return _container != nullptr && _container->canAcceptImposedResource();
1384 }