1 // Copyright (C) 2006-2023 CEA, EDF
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.
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.
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
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
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"
33 #include "PyStdout.hxx"
41 #define getpid _getpid
44 #if PY_VERSION_HEX < 0x02050000
45 typedef int Py_ssize_t;
49 #include "YacsTrace.hxx"
51 using namespace YACS::ENGINE;
54 const char PythonEntry::SCRIPT_FOR_SIMPLE_SERIALIZATION[]="import pickle\n"
55 "def pickleForVarSimplePyth2009(val):\n"
56 " return pickle.dumps(val,-1)\n"
59 PyObject *PythonEntry::_pyClsBigObject = nullptr;
61 const char PythonNode::IMPL_NAME[]="Python";
62 const char PythonNode::KIND[]="Python";
64 const char PythonNode::SCRIPT_FOR_SERIALIZATION[]="import pickle\n"
65 "def pickleForDistPyth2009(kws):\n"
66 " return pickle.dumps(((),kws),-1)\n"
68 "def unPickleForDistPyth2009(st):\n"
69 " args=pickle.loads(st)\n"
72 const char PythonNode::REMOTE_NAME[]="remote";
74 const char PythonNode::DPL_INFO_NAME[]="my_dpl_localization";
76 const char PyFuncNode::SCRIPT_FOR_SERIALIZATION[]="import pickle\n"
77 "def pickleForDistPyth2009(*args,**kws):\n"
78 " return pickle.dumps((args,kws),-1)\n"
80 "def unPickleForDistPyth2009(st):\n"
81 " args=pickle.loads(st)\n"
84 static char SCRIPT_FOR_BIGOBJECT[]="import SALOME_PyNode\n"
85 "BigObjectOnDiskBase = SALOME_PyNode.BigObjectOnDiskBase\n";
87 // pickle.load concurrency issue : see https://bugs.python.org/issue12680
88 #if PY_VERSION_HEX < 0x03070000
90 static std::mutex data_mutex;
93 PythonEntry::PythonEntry():_context(0),_pyfuncSer(0),_pyfuncUnser(0),_pyfuncSimpleSer(0)
97 PythonEntry::~PythonEntry()
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);
106 void PythonEntry::loadRemoteContainer(InlineNode *reqNode)
108 DEBTRACE( "---------------PythonEntry::CommonRemoteLoad function---------------" );
109 Container *container(reqNode->getContainer());
110 bool isContAlreadyStarted(false);
115 if(hasImposedResource())
116 container->start(reqNode, _imposedResource, _imposedContainer);
119 isContAlreadyStarted=container->isAlreadyStarted(reqNode);
120 if(!isContAlreadyStarted)
121 container->start(reqNode);
126 reqNode->setErrorDetails(e.what());
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);
139 Engines::Container_var GetContainerObj(InlineNode *reqNode, bool& isStandardCont)
141 isStandardCont = false;
142 Container *container(reqNode->getContainer());
143 Engines::Container_var objContainer(Engines::Container::_nil());
145 throw YACS::Exception("No container specified !");
146 SalomeContainer *containerCast0(dynamic_cast<SalomeContainer *>(container));
147 SalomeHPContainer *containerCast1(dynamic_cast<SalomeHPContainer *>(container));
150 isStandardCont = true;
151 objContainer=containerCast0->getContainerPtr(reqNode);
153 else if(containerCast1)
155 YACS::BASES::AutoCppPtr<SalomeContainerTmpForHP> tmpCont(SalomeContainerTmpForHP::BuildFrom(containerCast1,reqNode));
156 objContainer=tmpCont->getContainerPtr(reqNode);
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 !");
165 Engines::Container_var PythonEntry::loadPythonAdapter(InlineNode *reqNode, bool& isInitializeRequested)
167 bool isStandardCont(true);
168 Engines::Container_var objContainer(GetContainerObj(reqNode,isStandardCont));
169 isInitializeRequested=false;
172 Engines::PyNodeBase_var dftPyScript(retrieveDftRemotePyInterpretorIfAny(objContainer));
173 if(CORBA::is_nil(dftPyScript))
175 isInitializeRequested=!isStandardCont;
176 createRemoteAdaptedPyInterpretor(objContainer);
179 assignRemotePyInterpretor(dftPyScript);
181 catch( const SALOME::SALOME_Exception& ex )
183 std::string msg="Exception on remote python node creation ";
185 msg += ex.details.text.in();
186 reqNode->setErrorDetails(msg);
187 throw Exception(msg);
189 Engines::PyNodeBase_var pynode(getRemoteInterpreterHandle());
190 if(CORBA::is_nil(pynode))
191 throw Exception("In PythonNode the ref in NULL ! ");
195 void PythonEntry::loadRemoteContext(InlineNode *reqNode, Engines::Container_ptr objContainer, bool isInitializeRequested)
197 Container *container(reqNode->getContainer());
198 Engines::PyNodeBase_var pynode(getRemoteInterpreterHandle());
201 #if PY_VERSION_HEX < 0x03070000
202 std::unique_lock<std::mutex> lock(data_mutex);
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)
210 std::string errorDetails;
211 PyObject* new_stderr = newPyStdOut(errorDetails);
212 reqNode->setErrorDetails(errorDetails);
213 PySys_SetObject((char*)"stderr", new_stderr);
215 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
216 Py_DECREF(new_stderr);
217 throw Exception("Error during load");
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 )
226 _pyClsBigObject=PyDict_GetItemString(_context,"BigObjectOnDiskBase");
227 Py_INCREF(_pyClsBigObject);
229 if(_pyfuncSer == NULL)
231 std::string errorDetails;
232 PyObject *new_stderr(newPyStdOut(errorDetails));
233 reqNode->setErrorDetails(errorDetails);
234 PySys_SetObject((char*)"stderr", new_stderr);
236 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
237 Py_DECREF(new_stderr);
238 throw Exception("Error during load");
240 if(_pyfuncUnser == NULL)
242 std::string errorDetails;
243 PyObject *new_stderr(newPyStdOut(errorDetails));
244 reqNode->setErrorDetails(errorDetails);
245 PySys_SetObject((char*)"stderr", new_stderr);
247 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
248 Py_DECREF(new_stderr);
249 throw Exception("Error during load");
251 if(_pyfuncSimpleSer == NULL)
253 std::string errorDetails;
254 PyObject *new_stderr(newPyStdOut(errorDetails));
255 reqNode->setErrorDetails(errorDetails);
256 PySys_SetObject((char*)"stderr", new_stderr);
258 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
259 Py_DECREF(new_stderr);
260 throw Exception("Error during load");
263 if(isInitializeRequested)
264 {//This one is called only once at initialization in the container if an init-script is specified.
267 std::string zeInitScriptKey(container->getProperty(HomogeneousPoolContainer::INITIALIZE_SCRIPT_KEY));
268 if(!zeInitScriptKey.empty())
269 pynode->executeAnotherPieceOfCode(zeInitScriptKey.c_str());
271 catch( const SALOME::SALOME_Exception& ex )
273 std::string msg="Exception on PythonNode::loadRemote python invocation of initializisation py script !";
275 msg += ex.details.text.in();
276 reqNode->setErrorDetails(msg);
277 throw Exception(msg);
279 DEBTRACE( "---------------End PyNode::loadRemote function---------------" );
283 std::string PythonEntry::GetContainerLog(const std::string& mode, Container *container, const Task *askingTask)
291 SalomeContainer *containerCast(dynamic_cast<SalomeContainer *>(container));
292 SalomeHPContainer *objContainer2(dynamic_cast<SalomeHPContainer *>(container));
295 Engines::Container_var objContainer(containerCast->getContainerPtr(askingTask));
296 CORBA::String_var logname = objContainer->logfilename();
299 std::string::size_type pos = msg.find(":");
300 msg=msg.substr(pos+1);
302 else if(objContainer2)
304 msg="Remote PythonNode is on HP Container : no log because no info of the location by definition of HP Container !";
308 msg="Not implemented yet for container log for that type of container !";
313 msg = "Container no longer reachable";
318 void PythonEntry::commonRemoteLoad(InlineNode *reqNode)
320 loadRemoteContainer(reqNode);
321 bool isInitializeRequested;
322 Engines::Container_var objContainer(loadPythonAdapter(reqNode,isInitializeRequested));
323 loadRemoteContext(reqNode,objContainer,isInitializeRequested);
326 bool PythonEntry::hasImposedResource()const
328 return !_imposedResource.empty() && !_imposedContainer.empty();
331 bool PythonEntry::IsProxy( PyObject *ob )
335 if( PyObject_IsInstance( ob, _pyClsBigObject) == 1 )
341 if( PyList_Check( ob ) )
343 auto sz = PyList_Size( ob );
344 for( auto i = 0 ; i < sz ; ++i )
346 PyObject *elt = PyList_GetItem( ob, i );
347 if( PythonEntry::IsProxy(elt) )
355 bool PythonEntry::GetDestroyStatus( PyObject *ob )
359 if( PyObject_IsInstance( ob, _pyClsBigObject) == 1 )
361 AutoPyRef unlinkOnDestructor = PyObject_GetAttrString(ob,"getDestroyStatus");
362 AutoPyRef tmp = PyObject_CallFunctionObjArgs(unlinkOnDestructor,nullptr);
363 if( PyBool_Check(tmp.get()) )
365 return tmp.get() == Py_True;
371 if( PyList_Check( ob ) )
373 auto sz = PyList_Size( ob );
374 for( auto i = 0 ; i < sz ; ++i )
376 PyObject *elt = PyList_GetItem( ob, i );
377 if( PythonEntry::GetDestroyStatus(elt) )
385 void PythonEntry::IfProxyDoSomething( PyObject *ob, const char *meth )
389 if( PyObject_IsInstance( ob, _pyClsBigObject) == 1 )
391 AutoPyRef unlinkOnDestructor = PyObject_GetAttrString(ob,meth);
392 AutoPyRef tmp = PyObject_CallFunctionObjArgs(unlinkOnDestructor,nullptr);
396 if( PyList_Check( ob ) )
398 auto sz = PyList_Size( ob );
399 for( auto i = 0 ; i < sz ; ++i )
401 PyObject *elt = PyList_GetItem( ob, i );
402 PythonEntry::IfProxyDoSomething( elt, meth );
408 void PythonEntry::DoNotTouchFileIfProxy( PyObject *ob )
410 IfProxyDoSomething(ob,"doNotTouchFile");
413 void PythonEntry::UnlinkOnDestructorIfProxy( PyObject *ob )
415 IfProxyDoSomething(ob,"unlinkOnDestructor");
418 PythonNode::PythonNode(const PythonNode& other, ComposedNode *father):
419 InlineNode(other,father),_autoSqueeze(other._autoSqueeze),_nonSqueezableOutputNodes(other._nonSqueezableOutputNodes)
421 _pynode = Engines::PyScriptNode::_nil();
422 _implementation=IMPL_NAME;
425 _context=PyDict_New();
426 if( PyDict_SetItemString( _context, "__builtins__", getSALOMERuntime()->getBuiltins() ))
429 msg << "Impossible to set builtins" << __FILE__ << ":" << __LINE__;
430 _errorDetails=msg.str();
431 throw Exception(msg.str());
436 PythonNode::PythonNode(const std::string& name):InlineNode(name)
438 _pynode = Engines::PyScriptNode::_nil();
439 _implementation=IMPL_NAME;
442 _context=PyDict_New();
443 if( PyDict_SetItemString( _context, "__builtins__", getSALOMERuntime()->getBuiltins() ))
446 msg << "Impossible to set builtins" << __FILE__ << ":" << __LINE__;
447 _errorDetails=msg.str();
448 throw Exception(msg.str());
453 PythonNode::~PythonNode()
458 void PythonNode::checkBasicConsistency() const
460 DEBTRACE("checkBasicConsistency");
461 InlineNode::checkBasicConsistency();
465 res=Py_CompileString(_script.c_str(),getName().c_str(),Py_file_input);
468 std::string error="";
469 PyObject* new_stderr = newPyStdOut(error);
470 PySys_SetObject((char*)"stderr", new_stderr);
472 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
473 Py_DECREF(new_stderr);
474 throw Exception(error);
481 void PythonNode::load()
483 DEBTRACE( "---------------PyNode::load function---------------" );
484 if(_mode==PythonNode::REMOTE_NAME)
490 void PythonNode::loadLocal()
492 DEBTRACE( "---------------PyNode::loadLocal function---------------" );
496 void PythonNode::loadRemote()
498 commonRemoteLoad(this);
501 void PythonNode::execute()
503 if(_mode==PythonNode::REMOTE_NAME)
509 void PythonNode::executeRemote()
511 DEBTRACE( "++++++++++++++ PyNode::executeRemote: " << getName() << " ++++++++++++++++++++" );
513 throw Exception("PythonNode badly loaded");
515 if(dynamic_cast<HomogeneousPoolContainer *>(getContainer()))
518 loadPythonAdapter(this,dummy);
519 _pynode->assignNewCompiledCode(getScript().c_str());
521 // not managed by unique_ptr here because destructed by the order of client.
522 SenderByteImpl *serializationInputCorba = nullptr;
523 AutoPyRef serializationInput;
525 #if PY_VERSION_HEX < 0x03070000
526 std::unique_lock<std::mutex> lock(data_mutex);
529 PyObject *args(0),*ob(0);
530 //===========================================================================
531 // Get inputs in input ports, build a Python dict and pickle it
532 //===========================================================================
534 std::list<InputPort *>::iterator iter2;
536 for(iter2 = _setOfInputPort.begin(); iter2 != _setOfInputPort.end(); ++iter2)
538 InputPyPort *p=(InputPyPort *)*iter2;
540 PyDict_SetItemString(args,p->getName().c_str(),ob);
544 PyObject_Print(args,stderr,Py_PRINT_RAW);
547 serializationInput.set(PyObject_CallFunctionObjArgs(_pyfuncSer,args,nullptr));
549 //The pickled string may contain NULL characters so use PyString_AsStringAndSize
550 char *serializationInputC(nullptr);
552 if (PyBytes_AsStringAndSize(serializationInput, &serializationInputC, &len))
553 throw Exception("DistributedPythonNode problem in python pickle");
554 // no copy here. The C byte array of Python is taken as this into CORBA sequence to avoid copy
555 serializationInputCorba = new SenderByteImpl(serializationInputC,len);
558 //get the list of output argument names
559 std::list<OutputPort *>::iterator iter;
560 Engines::listofstring myseq;
561 myseq.length(getNumberOfOutputPorts());
563 for(iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); ++iter)
565 OutputPyPort *p=(OutputPyPort *)*iter;
566 myseq[pos]=p->getName().c_str();
567 DEBTRACE( "port name: " << p->getName() );
568 DEBTRACE( "port kind: " << p->edGetType()->kind() );
569 DEBTRACE( "port pos : " << pos );
572 //===========================================================================
573 // Execute in remote Python node
574 //===========================================================================
575 DEBTRACE( "-----------------starting remote python invocation-----------------" );
576 std::unique_ptr<SALOME::SenderByteSeq> resultCorba;
579 //pass outargsname and dict serialized
580 SALOME::SenderByte_var serializationInputRef = serializationInputCorba->_this();
581 _pynode->executeFirst(serializationInputRef);
582 //serializationInput and serializationInputCorba are no more needed for server. Release it.
583 serializationInput.set(nullptr);
584 resultCorba.reset( _pynode->executeSecond(myseq) );
586 catch( const SALOME::SALOME_Exception& ex )
588 std::ostringstream msg; msg << "Exception on remote python invocation" << std::endl << ex.details.text.in() << std::endl;
589 msg << "PyScriptNode CORBA ref : ";
591 CORBA::ORB_ptr orb(getSALOMERuntime()->getOrb());
592 if(!CORBA::is_nil(orb))
594 CORBA::String_var IOR(orb->object_to_string(_pynode));
599 _errorDetails=msg.str();
600 throw Exception(msg.str());
602 catch(CORBA::COMM_FAILURE& ex)
604 std::ostringstream msg;
605 msg << "Exception on remote python invocation." << std::endl ;
606 msg << "Caught system exception COMM_FAILURE -- unable to contact the "
607 << "object." << std::endl;
608 _errorDetails=msg.str();
609 throw Exception(msg.str());
611 catch(CORBA::SystemException& ex)
613 std::ostringstream msg;
614 msg << "Exception on remote python invocation." << std::endl ;
615 msg << "Caught a CORBA::SystemException." ;
618 CORBA::TypeCode_var tc = tmp.type();
619 const char *p = tc->name();
625 _errorDetails=msg.str();
626 throw Exception(msg.str());
628 catch(CORBA::Exception& ex)
630 std::ostringstream msg;
631 msg << "Exception on remote python invocation." << std::endl ;
632 msg << "Caught CORBA::Exception. " ;
635 CORBA::TypeCode_var tc = tmp.type();
636 const char *p = tc->name();
642 _errorDetails=msg.str();
643 throw Exception(msg.str());
645 catch(omniORB::fatalException& fe)
647 std::ostringstream msg;
648 msg << "Exception on remote python invocation." << std::endl ;
649 msg << "Caught omniORB::fatalException:" << std::endl;
650 msg << " file: " << fe.file() << std::endl;
651 msg << " line: " << fe.line() << std::endl;
652 msg << " mesg: " << fe.errmsg() << std::endl;
653 _errorDetails=msg.str();
654 throw Exception(msg.str());
656 DEBTRACE( "-----------------end of remote python invocation-----------------" );
657 //===========================================================================
658 // Get results, unpickle and put them in output ports
659 //===========================================================================
661 #if PY_VERSION_HEX < 0x03070000
662 std::unique_lock<std::mutex> lock(data_mutex);
665 DEBTRACE( "-----------------PythonNode::outputs-----------------" );
666 int nres( resultCorba->length() );
668 if(getNumberOfOutputPorts() != nres)
670 std::string msg="Number of output arguments : Mismatch between definition and execution";
672 throw Exception(msg);
677 for(iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); ++iter)
679 OutputPyPort *p=(OutputPyPort *)*iter;
680 DEBTRACE( "port name: " << p->getName() );
681 DEBTRACE( "port kind: " << p->edGetType()->kind() );
682 DEBTRACE( "port pos : " << pos );
683 SALOME::SenderByte_var elt = (*resultCorba)[pos];
684 SeqByteReceiver recv(elt);
685 unsigned long length = 0;
686 char *resultCorbaC = recv.data(length);
688 AutoPyRef resultPython=PyMemoryView_FromMemory(resultCorbaC,length,PyBUF_READ);
689 AutoPyRef args = PyTuple_New(1);
690 PyTuple_SetItem(args,0,resultPython.retn());
691 AutoPyRef ob = PyObject_CallObject(_pyfuncUnser,args);
694 std::stringstream msg;
695 msg << "Conversion with pickle of output ports failed !";
696 msg << " : " << __FILE__ << ":" << __LINE__;
697 _errorDetails=msg.str();
698 throw YACS::ENGINE::ConversionException(msg.str());
700 UnlinkOnDestructorIfProxy(ob);
706 catch(ConversionException& ex)
708 _errorDetails=ex.what();
712 squeezeMemoryRemote();
715 if(!isUsingPythonCache())
719 Engines::Container_var cont(GetContainerObj(this,dummy));
720 cont->removePyScriptNode(getName().c_str());
722 DEBTRACE( "++++++++++++++ ENDOF PyNode::executeRemote: " << getName() << " ++++++++++++++++++++" );
725 void PythonNode::ExecuteLocalInternal(const std::string& codeStr, PyObject *context, std::string& errorDetails)
728 DEBTRACE( "context refcnt: " << context->ob_refcnt );
729 std::ostringstream stream;
730 stream << "/tmp/PythonNode_";
732 AutoPyRef code=Py_CompileString(codeStr.c_str(), stream.str().c_str(), Py_file_input);
736 AutoPyRef new_stderr = newPyStdOut(errorDetails);
737 PySys_SetObject((char*)"stderr", new_stderr);
739 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
740 throw YACS::Exception("Error during execution");
743 AutoPyRef res = PyEval_EvalCode( code, context, context);
745 DEBTRACE( "context refcnt: " << context->ob_refcnt );
748 if(PyErr_Occurred ())
751 AutoPyRef new_stderr = newPyStdOut(errorDetails);
752 PySys_SetObject((char*)"stderr", new_stderr);
753 ofstream errorfile(stream.str().c_str());
754 if (errorfile.is_open())
756 errorfile << codeStr;
760 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
761 throw YACS::Exception("Error during execution");
765 void PythonNode::executeLocalInternal(const std::string& codeStr)
767 ExecuteLocalInternal(codeStr,_context,_errorDetails);
770 void PythonNode::executeLocal()
772 DEBTRACE( "++++++++++++++ PyNode::executeLocal: " << getName() << " ++++++++++++++++++++" );
775 std::ostringstream unpxy; unpxy << "from SALOME_PyNode import UnProxyObjectSimpleLocal" << std::endl;
776 DEBTRACE( "---------------PyNode::inputs---------------" );
777 list<InputPort *>::iterator iter2;
778 for(iter2 = _setOfInputPort.begin(); iter2 != _setOfInputPort.end(); iter2++)
780 InputPyPort *p=(InputPyPort *)*iter2;
781 DEBTRACE( "port name: " << p->getName() );
782 DEBTRACE( "port kind: " << p->edGetType()->kind() );
783 PyObject* ob=p->getPyObj();
784 DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
785 unpxy << p->getName() << " = UnProxyObjectSimpleLocal( " << p->getName() << " )" << std::endl;
787 PyObject_Print(ob,stderr,Py_PRINT_RAW);
790 int ier=PyDict_SetItemString(_context,p->getName().c_str(),ob);
791 DEBTRACE( "after PyDict_SetItemString:ob refcnt: " << ob->ob_refcnt );
794 DEBTRACE( "---------------End PyNode::inputs---------------" );
797 DEBTRACE( "----------------PyNode::calculation---------------" );
799 if( ! getSqueezeStatus() )
800 executeLocalInternal( unpxy.str() );
802 executeLocalInternal( _script );
804 DEBTRACE( "-----------------PyNode::outputs-----------------" );
805 list<OutputPort *>::iterator iter;
808 for(iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); iter++)
810 OutputPyPort *p=(OutputPyPort *)*iter;
811 DEBTRACE( "port name: " << p->getName() );
812 DEBTRACE( "port kind: " << p->edGetType()->kind() );
813 PyObject *ob=PyDict_GetItemString(_context,p->getName().c_str());
816 std::string msg="Error during execution: there is no variable ";
817 msg=msg+p->getName()+" in node context";
819 throw Exception(msg);
821 DEBTRACE( "PyNode::outputs::ob refcnt: " << ob->ob_refcnt );
823 PyObject_Print(ob,stderr,Py_PRINT_RAW);
827 if(!isUsingPythonCache())
828 PyDict_DelItemString(_context,p->getName().c_str());
831 catch(ConversionException& ex)
833 _errorDetails=ex.what();
838 DEBTRACE( "-----------------End PyNode::outputs-----------------" );
839 if(!isUsingPythonCache())
841 for(iter2 = _setOfInputPort.begin(); iter2 != _setOfInputPort.end(); iter2++)
843 AutoPyRef pStr = PyUnicode_FromString( (*iter2)->getName().c_str() );
844 if( PyDict_Contains(_context,pStr) == 1 )
845 { PyDict_DelItem(_context,pStr); }
849 DEBTRACE( "++++++++++++++ End PyNode::execute: " << getName() << " ++++++++++++++++++++" );
854 * \param in squeezeExceptions list on output port name excluded from the squeeze mecanism
856 void PythonNode::setSqueezeStatusWithExceptions(bool sqStatus, const std::vector<std::string>& squeezeExceptions)
858 this->setSqueezeStatus(sqStatus);
859 this->_nonSqueezableOutputNodes = std::set<std::string>(squeezeExceptions.begin(), squeezeExceptions.end());
862 void PythonNode::squeezeMemorySafe()
865 if(_mode==PythonNode::REMOTE_NAME)
866 this->squeezeMemoryRemote();
868 this->squeezeMemory();
871 void PythonNode::squeezeMemory()
873 for(auto p : _setOfInputPort)
875 PyDict_DelItemString(_context,p->getName().c_str());
876 InputPyPort *p2(static_cast<InputPyPort *>(p));
877 if(p2->canSafelySqueezeMemory())
880 for(auto p : _setOfOutputPort)
882 if (!this->_nonSqueezableOutputNodes.empty() && this->_nonSqueezableOutputNodes.find(p->getName()) != this->_nonSqueezableOutputNodes.end())
884 PyDict_DelItemString(_context,p->getName().c_str());
885 OutputPyPort *p2(static_cast<OutputPyPort *>(p));
886 p2->putWithoutForward(Py_None);
890 void PythonNode::squeezeMemoryRemote()
892 for(auto p : _setOfInputPort)
894 InputPyPort *p2(static_cast<InputPyPort *>(p));
895 if(p2->canSafelySqueezeMemory())
898 for(auto p : _setOfOutputPort)
900 if (!this->_nonSqueezableOutputNodes.empty() && this->_nonSqueezableOutputNodes.find(p->getName()) != this->_nonSqueezableOutputNodes.end())
902 OutputPyPort *p2(static_cast<OutputPyPort *>(p));
903 p2->putWithoutForward(Py_None);
907 std::string PythonNode::getContainerLog()
909 return PythonEntry::GetContainerLog(_mode,_container,this);
912 void PythonNode::shutdown(int level)
914 DEBTRACE("PythonNode::shutdown " << level);
915 if(_mode=="local")return;
919 _container->shutdown(level);
923 void PythonNode::imposeResource(const std::string& resource_name,
924 const std::string& container_name)
926 if(!resource_name.empty() && !container_name.empty())
928 _imposedResource = resource_name;
929 _imposedContainer = container_name;
933 bool PythonNode::canAcceptImposedResource()
935 return _container != nullptr && _container->canAcceptImposedResource();
938 bool PythonNode::hasImposedResource()const
940 return PythonEntry::hasImposedResource();
943 std::string PythonNode::pythonEntryName()const
945 if(isUsingPythonCache())
946 return "DEFAULT_NAME_FOR_UNIQUE_PYTHON_NODE_ENTRY";
951 bool PythonNode::isUsingPythonCache()const
955 found = _container->isUsingPythonCache();
959 void PythonNode::freeKernelPynode()
961 if(!CORBA::is_nil(_pynode))
965 _pynode->UnRegister();
969 DEBTRACE("Trouble when pynode->UnRegister!")
971 _pynode = Engines::PyScriptNode::_nil();
975 Node *PythonNode::simpleClone(ComposedNode *father, bool editionOnly) const
977 return new PythonNode(*this,father);
980 void PythonNode::createRemoteAdaptedPyInterpretor(Engines::Container_ptr objContainer)
983 _pynode=objContainer->createPyScriptNode(pythonEntryName().c_str(),getScript().c_str());
987 Engines::PyNodeBase_var PythonNode::retrieveDftRemotePyInterpretorIfAny(Engines::Container_ptr objContainer) const
989 Engines::PyScriptNode_var ret(objContainer->getDefaultPyScriptNode(pythonEntryName().c_str()));
990 if(!CORBA::is_nil(ret))
994 return Engines::PyNodeBase::_narrow(ret);
997 void PythonNode::assignRemotePyInterpretor(Engines::PyNodeBase_var remoteInterp)
999 if(CORBA::is_nil(_pynode))
1000 _pynode=Engines::PyScriptNode::_narrow(remoteInterp);
1003 Engines::PyScriptNode_var tmpp(Engines::PyScriptNode::_narrow(remoteInterp));
1004 if(!_pynode->_is_equivalent(tmpp))
1007 _pynode=Engines::PyScriptNode::_narrow(remoteInterp);
1010 _pynode->assignNewCompiledCode(getScript().c_str());
1013 Engines::PyNodeBase_var PythonNode::getRemoteInterpreterHandle()
1015 return Engines::PyNodeBase::_narrow(_pynode);
1018 //! Create a new node of same type with a given name
1019 PythonNode* PythonNode::cloneNode(const std::string& name)
1021 PythonNode* n=new PythonNode(name);
1022 n->setScript(_script);
1023 list<InputPort *>::iterator iter;
1024 for(iter = _setOfInputPort.begin(); iter != _setOfInputPort.end(); iter++)
1026 InputPyPort *p=(InputPyPort *)*iter;
1027 DEBTRACE( "port name: " << p->getName() );
1028 DEBTRACE( "port kind: " << p->edGetType()->kind() );
1029 n->edAddInputPort(p->getName(),p->edGetType());
1031 list<OutputPort *>::iterator iter2;
1032 for(iter2 = _setOfOutputPort.begin(); iter2 != _setOfOutputPort.end(); iter2++)
1034 OutputPyPort *p=(OutputPyPort *)*iter2;
1035 DEBTRACE( "port name: " << p->getName() );
1036 DEBTRACE( "port kind: " << p->edGetType()->kind() );
1037 n->edAddOutputPort(p->getName(),p->edGetType());
1042 void PythonNode::applyDPLScope(ComposedNode *gfn)
1044 std::vector< std::pair<std::string,int> > ret(getDPLScopeInfo(gfn));
1051 std::size_t sz(ret.size());
1053 for(std::size_t i=0;i<sz;i++)
1055 const std::pair<std::string,int>& p(ret[i]);
1056 PyObject *elt(PyTuple_New(2));
1057 PyTuple_SetItem(elt,0,PyUnicode_FromString(p.first.c_str()));
1058 PyTuple_SetItem(elt,1,PyLong_FromLong(p.second));
1059 PyList_SetItem(ob,i,elt);
1062 if(_mode==REMOTE_NAME)
1064 Engines::pickledArgs_var serializationInputCorba(new Engines::pickledArgs);
1067 PyObject *serializationInput(PyObject_CallFunctionObjArgs(_pyfuncSimpleSer,ob,NULL));
1069 char *serializationInputC(0);
1071 if (PyBytes_AsStringAndSize(serializationInput, &serializationInputC, &len))
1072 throw Exception("DistributedPythonNode problem in python pickle");
1073 serializationInputCorba->length(len);
1074 for(int i=0; i < len ; i++)
1075 serializationInputCorba[i]=serializationInputC[i];
1076 Py_XDECREF(serializationInput);
1078 _pynode->defineNewCustomVar(DPL_INFO_NAME,serializationInputCorba);
1083 PyDict_SetItemString(_context,DPL_INFO_NAME,ob);
1088 PyFuncNode::PyFuncNode(const PyFuncNode& other, ComposedNode *father):InlineFuncNode(other,father),_pyfunc(0)
1090 _implementation = PythonNode::IMPL_NAME;
1093 _context=PyDict_New();
1094 DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
1095 if( PyDict_SetItemString( _context, "__builtins__", getSALOMERuntime()->getBuiltins() ))
1098 msg << "Not possible to set builtins" << __FILE__ << ":" << __LINE__;
1099 _errorDetails=msg.str();
1100 throw Exception(msg.str());
1105 PyFuncNode::PyFuncNode(const std::string& name): InlineFuncNode(name),_pyfunc(0)
1108 _implementation = PythonNode::IMPL_NAME;
1109 DEBTRACE( "PyFuncNode::PyFuncNode " << name );
1112 _context=PyDict_New();
1113 DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
1114 if( PyDict_SetItemString( _context, "__builtins__", getSALOMERuntime()->getBuiltins() ))
1117 msg << "Not possible to set builtins" << __FILE__ << ":" << __LINE__;
1118 _errorDetails=msg.str();
1119 throw Exception(msg.str());
1124 PyFuncNode::~PyFuncNode()
1126 if(!CORBA::is_nil(_pynode))
1128 _pynode->UnRegister();
1132 void PyFuncNode::init(bool start)
1134 initCommonPartWithoutStateManagement(start);
1135 if(_state == YACS::DISABLED)
1137 exDisabledState(); // to refresh propagation of DISABLED state
1140 if(start) //complete initialization
1141 setState(YACS::READY);
1142 else if(_state > YACS::LOADED)// WARNING FuncNode has internal vars (CEA usecase) ! Partial initialization (inside a loop). Exclusivity of funcNode.
1143 setState(YACS::TORECONNECT);
1146 void PyFuncNode::checkBasicConsistency() const
1148 DEBTRACE("checkBasicConsistency");
1149 InlineFuncNode::checkBasicConsistency();
1153 res=Py_CompileString(_script.c_str(),getName().c_str(),Py_file_input);
1156 std::string error="";
1157 PyObject* new_stderr = newPyStdOut(error);
1158 PySys_SetObject((char*)"stderr", new_stderr);
1160 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
1161 Py_DECREF(new_stderr);
1162 throw Exception(error);
1169 void PyFuncNode::load()
1171 DEBTRACE( "---------------PyfuncNode::load function---------------" );
1172 if(_mode==PythonNode::REMOTE_NAME)
1178 void PyFuncNode::loadRemote()
1180 commonRemoteLoad(this);
1183 void PyFuncNode::loadLocal()
1185 DEBTRACE( "---------------PyFuncNode::load function " << getName() << " ---------------" );
1186 DEBTRACE( _script );
1189 list<OutputPort *>::iterator iter;
1190 for(iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); iter++)
1192 OutputPyPort *p=(OutputPyPort *)*iter;
1193 DEBTRACE( "port name: " << p->getName() );
1194 DEBTRACE( "port kind: " << p->edGetType()->kind() );
1200 DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
1202 std::ostringstream stream;
1203 stream << "/tmp/PythonNode_";
1206 PyObject* code=Py_CompileString(_script.c_str(), stream.str().c_str(), Py_file_input);
1210 PyObject* new_stderr = newPyStdOut(_errorDetails);
1211 PySys_SetObject((char*)"stderr", new_stderr);
1213 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
1214 Py_DECREF(new_stderr);
1215 throw Exception("Error during execution");
1217 PyObject *res = PyEval_EvalCode( code, _context, _context);
1221 DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
1222 if(PyErr_Occurred ())
1225 PyObject* new_stderr = newPyStdOut(_errorDetails);
1226 PySys_SetObject((char*)"stderr", new_stderr);
1227 ofstream errorfile(stream.str().c_str());
1228 if (errorfile.is_open())
1230 errorfile << _script;
1234 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
1235 Py_DECREF(new_stderr);
1236 throw Exception("Error during execution");
1239 _pyfunc=PyDict_GetItemString(_context,_fname.c_str());
1240 DEBTRACE( "_pyfunc refcnt: " << _pyfunc->ob_refcnt );
1244 PyObject* new_stderr = newPyStdOut(_errorDetails);
1245 PySys_SetObject((char*)"stderr", new_stderr);
1247 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
1248 Py_DECREF(new_stderr);
1249 throw Exception("Error during execution");
1251 DEBTRACE( "---------------End PyFuncNode::load function---------------" );
1255 void PyFuncNode::execute()
1257 if(_mode==PythonNode::REMOTE_NAME)
1263 void PyFuncNode::executeRemote()
1265 DEBTRACE( "++++++++++++++ PyFuncNode::executeRemote: " << getName() << " ++++++++++++++++++++" );
1267 throw Exception("DistributedPythonNode badly loaded");
1269 if(dynamic_cast<HomogeneousPoolContainer *>(getContainer()))
1272 loadPythonAdapter(this,dummy);
1273 _pynode->executeAnotherPieceOfCode(getScript().c_str());
1276 Engines::pickledArgs_var serializationInputCorba(new Engines::pickledArgs);;
1278 #if PY_VERSION_HEX < 0x03070000
1279 std::unique_lock<std::mutex> lock(data_mutex);
1283 //===========================================================================
1284 // Get inputs in input ports, build a Python tuple and pickle it
1285 //===========================================================================
1286 PyObject *args(PyTuple_New(getNumberOfInputPorts()));
1288 for(std::list<InputPort *>::iterator iter2 = _setOfInputPort.begin(); iter2 != _setOfInputPort.end(); iter2++,pos++)
1290 InputPyPort *p=(InputPyPort *)*iter2;
1293 PyTuple_SetItem(args,pos,ob);
1296 PyObject_Print(args,stderr,Py_PRINT_RAW);
1299 PyObject *serializationInput=PyObject_CallObject(_pyfuncSer,args);
1301 //The pickled string may contain NULL characters so use PyString_AsStringAndSize
1302 char *serializationInputC(0);
1304 if (PyBytes_AsStringAndSize(serializationInput, &serializationInputC, &len))
1305 throw Exception("DistributedPythonNode problem in python pickle");
1307 serializationInputCorba->length(len);
1308 for(int i=0; i < len ; i++)
1309 serializationInputCorba[i]=serializationInputC[i];
1310 Py_DECREF(serializationInput);
1313 //===========================================================================
1314 // Execute in remote Python node
1315 //===========================================================================
1316 DEBTRACE( "-----------------starting remote python invocation-----------------" );
1317 Engines::pickledArgs_var resultCorba;
1320 resultCorba=_pynode->execute(getFname().c_str(),serializationInputCorba);
1322 catch( const SALOME::SALOME_Exception& ex )
1324 std::string msg="Exception on remote python invocation";
1326 msg += ex.details.text.in();
1328 throw Exception(msg);
1330 catch(CORBA::COMM_FAILURE& ex)
1332 std::ostringstream msg;
1333 msg << "Exception on remote python invocation." << std::endl ;
1334 msg << "Caught system exception COMM_FAILURE -- unable to contact the "
1335 << "object." << std::endl;
1336 _errorDetails=msg.str();
1337 throw Exception(msg.str());
1339 catch(CORBA::SystemException& ex)
1341 std::ostringstream msg;
1342 msg << "Exception on remote python invocation." << std::endl ;
1343 msg << "Caught a CORBA::SystemException." ;
1346 CORBA::TypeCode_var tc = tmp.type();
1347 const char *p = tc->name();
1353 _errorDetails=msg.str();
1354 throw Exception(msg.str());
1356 catch(CORBA::Exception& ex)
1358 std::ostringstream msg;
1359 msg << "Exception on remote python invocation." << std::endl ;
1360 msg << "Caught CORBA::Exception. " ;
1363 CORBA::TypeCode_var tc = tmp.type();
1364 const char *p = tc->name();
1370 _errorDetails=msg.str();
1371 throw Exception(msg.str());
1373 catch(omniORB::fatalException& fe)
1375 std::ostringstream msg;
1376 msg << "Exception on remote python invocation." << std::endl ;
1377 msg << "Caught omniORB::fatalException:" << std::endl;
1378 msg << " file: " << fe.file() << std::endl;
1379 msg << " line: " << fe.line() << std::endl;
1380 msg << " mesg: " << fe.errmsg() << std::endl;
1381 _errorDetails=msg.str();
1382 throw Exception(msg.str());
1384 DEBTRACE( "-----------------end of remote python invocation-----------------" );
1385 //===========================================================================
1386 // Get results, unpickle and put them in output ports
1387 //===========================================================================
1388 char *resultCorbaC=new char[resultCorba->length()+1];
1389 resultCorbaC[resultCorba->length()]='\0';
1390 for(int i=0;i<resultCorba->length();i++)
1391 resultCorbaC[i]=resultCorba[i];
1394 #if PY_VERSION_HEX < 0x03070000
1395 std::unique_lock<std::mutex> lock(data_mutex);
1399 PyObject *resultPython(PyBytes_FromStringAndSize(resultCorbaC,resultCorba->length()));
1400 delete [] resultCorbaC;
1401 PyObject *args(PyTuple_New(1)),*ob(0);
1402 PyTuple_SetItem(args,0,resultPython);
1403 PyObject *finalResult=PyObject_CallObject(_pyfuncUnser,args);
1406 DEBTRACE( "-----------------PythonNode::outputs-----------------" );
1408 if(finalResult == Py_None)
1410 else if(PyTuple_Check(finalResult))
1411 nres=PyTuple_Size(finalResult);
1413 if(getNumberOfOutputPorts() != nres)
1415 std::string msg="Number of output arguments : Mismatch between definition and execution";
1416 Py_DECREF(finalResult);
1418 throw Exception(msg);
1424 for(std::list<OutputPort *>::iterator iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); iter++, pos++)
1426 OutputPyPort *p=(OutputPyPort *)*iter;
1427 DEBTRACE( "port name: " << p->getName() );
1428 DEBTRACE( "port kind: " << p->edGetType()->kind() );
1429 DEBTRACE( "port pos : " << pos );
1430 if(PyTuple_Check(finalResult))
1431 ob=PyTuple_GetItem(finalResult,pos) ;
1434 DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
1437 Py_DECREF(finalResult);
1439 catch(ConversionException& ex)
1441 Py_DECREF(finalResult);
1442 _errorDetails=ex.what();
1447 DEBTRACE( "++++++++++++++ ENDOF PyFuncNode::executeRemote: " << getName() << " ++++++++++++++++++++" );
1450 void PyFuncNode::executeLocal()
1452 DEBTRACE( "++++++++++++++ PyFuncNode::execute: " << getName() << " ++++++++++++++++++++" );
1456 if(!_pyfunc)throw Exception("PyFuncNode badly loaded");
1459 DEBTRACE( "---------------PyFuncNode::inputs---------------" );
1460 PyObject* args = PyTuple_New(getNumberOfInputPorts()) ;
1461 list<InputPort *>::iterator iter2;
1462 for(iter2 = _setOfInputPort.begin(); iter2 != _setOfInputPort.end(); iter2++)
1464 InputPyPort *p=(InputPyPort *)*iter2;
1465 DEBTRACE( "port name: " << p->getName() );
1466 DEBTRACE( "port kind: " << p->edGetType()->kind() );
1469 PyObject_Print(ob,stderr,Py_PRINT_RAW);
1472 DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
1474 PyTuple_SetItem(args,pos,ob);
1475 DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
1478 DEBTRACE( "---------------End PyFuncNode::inputs---------------" );
1480 DEBTRACE( "----------------PyFuncNode::calculation---------------" );
1482 PyObject_Print(_pyfunc,stderr,Py_PRINT_RAW);
1484 PyObject_Print(args,stderr,Py_PRINT_RAW);
1487 DEBTRACE( "_pyfunc refcnt: " << _pyfunc->ob_refcnt );
1488 PyObject* result = PyObject_CallObject( _pyfunc , args ) ;
1489 DEBTRACE( "_pyfunc refcnt: " << _pyfunc->ob_refcnt );
1496 PyObject* new_stderr = newPyStdOut(_errorDetails);
1497 PySys_SetObject((char*)"stderr", new_stderr);
1498 std::ostringstream stream;
1499 stream << "/tmp/PythonNode_";
1501 ofstream errorfile(stream.str().c_str());
1502 if (errorfile.is_open())
1504 errorfile << _script;
1508 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
1509 Py_DECREF(new_stderr);
1510 throw Exception("Error during execution");
1512 DEBTRACE( "----------------End PyFuncNode::calculation---------------" );
1514 DEBTRACE( "-----------------PyFuncNode::outputs-----------------" );
1516 if(result == Py_None)
1518 else if(PyTuple_Check(result))
1519 nres=PyTuple_Size(result);
1521 if(getNumberOfOutputPorts() != nres)
1523 std::string msg="Number of output arguments : Mismatch between definition and execution";
1526 throw Exception(msg);
1531 PyObject_Print(result,stderr,Py_PRINT_RAW);
1534 list<OutputPort *>::iterator iter;
1537 for(iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); iter++)
1539 OutputPyPort *p=(OutputPyPort *)*iter;
1540 DEBTRACE( "port name: " << p->getName() );
1541 DEBTRACE( "port kind: " << p->edGetType()->kind() );
1542 DEBTRACE( "port pos : " << pos );
1543 if(PyTuple_Check(result))ob=PyTuple_GetItem(result,pos) ;
1545 DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
1547 PyObject_Print(ob,stderr,Py_PRINT_RAW);
1554 catch(ConversionException& ex)
1557 _errorDetails=ex.what();
1560 DEBTRACE( "-----------------End PyFuncNode::outputs-----------------" );
1563 DEBTRACE( "++++++++++++++ End PyFuncNode::execute: " << getName() << " ++++++++++++++++++++" );
1566 Node *PyFuncNode::simpleClone(ComposedNode *father, bool editionOnly) const
1568 return new PyFuncNode(*this,father);
1571 void PyFuncNode::createRemoteAdaptedPyInterpretor(Engines::Container_ptr objContainer)
1573 if(!CORBA::is_nil(_pynode))
1574 _pynode->UnRegister();
1575 _pynode=objContainer->createPyNode(getName().c_str(),getScript().c_str());
1578 Engines::PyNodeBase_var PyFuncNode::retrieveDftRemotePyInterpretorIfAny(Engines::Container_ptr objContainer) const
1580 Engines::PyNode_var ret(objContainer->getDefaultPyNode(getName().c_str()));
1581 if(!CORBA::is_nil(ret))
1585 return Engines::PyNodeBase::_narrow(ret);
1588 void PyFuncNode::assignRemotePyInterpretor(Engines::PyNodeBase_var remoteInterp)
1590 if(!CORBA::is_nil(_pynode))
1592 Engines::PyNode_var tmpp(Engines::PyNode::_narrow(remoteInterp));
1593 if(_pynode->_is_equivalent(tmpp))
1596 if(!CORBA::is_nil(_pynode))
1597 _pynode->UnRegister();
1598 _pynode=Engines::PyNode::_narrow(remoteInterp);
1601 Engines::PyNodeBase_var PyFuncNode::getRemoteInterpreterHandle()
1603 return Engines::PyNodeBase::_narrow(_pynode);
1606 //! Create a new node of same type with a given name
1607 PyFuncNode* PyFuncNode::cloneNode(const std::string& name)
1609 PyFuncNode* n=new PyFuncNode(name);
1610 n->setScript(_script);
1611 n->setFname(_fname);
1612 list<InputPort *>::iterator iter;
1613 for(iter = _setOfInputPort.begin(); iter != _setOfInputPort.end(); iter++)
1615 InputPyPort *p=(InputPyPort *)*iter;
1616 n->edAddInputPort(p->getName(),p->edGetType());
1618 list<OutputPort *>::iterator iter2;
1619 for(iter2 = _setOfOutputPort.begin(); iter2 != _setOfOutputPort.end(); iter2++)
1621 OutputPyPort *p=(OutputPyPort *)*iter2;
1622 n->edAddOutputPort(p->getName(),p->edGetType());
1627 std::string PyFuncNode::getContainerLog()
1629 return PythonEntry::GetContainerLog(_mode,_container,this);
1632 void PyFuncNode::shutdown(int level)
1634 DEBTRACE("PyFuncNode::shutdown " << level);
1635 if(_mode=="local")return;
1638 if(!CORBA::is_nil(_pynode)) _pynode->UnRegister();
1639 _pynode=Engines::PyNode::_nil();
1640 _container->shutdown(level);
1644 void PyFuncNode::imposeResource(const std::string& resource_name,
1645 const std::string& container_name)
1647 if(!resource_name.empty() && !container_name.empty())
1649 _imposedResource = resource_name;
1650 _imposedContainer = container_name;
1654 bool PyFuncNode::canAcceptImposedResource()
1656 return _container != nullptr && _container->canAcceptImposedResource();
1659 bool PyFuncNode::hasImposedResource()const
1661 return PythonEntry::hasImposedResource();