1 // Copyright (C) 2006-2024 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 DEBUG_YACSTRACE("Before execute first of " << getId());
582 _pynode->executeFirst(serializationInputRef);
583 //serializationInput and serializationInputCorba are no more needed for server. Release it.
584 serializationInput.set(nullptr);
585 resultCorba.reset( _pynode->executeSecond(myseq) );
586 DEBUG_YACSTRACE("After execute second of " << getId());
588 catch( const SALOME::SALOME_Exception& ex )
590 std::ostringstream msg; msg << "Exception on remote python invocation" << std::endl << ex.details.text.in() << std::endl;
591 msg << "PyScriptNode CORBA ref : ";
593 CORBA::ORB_ptr orb(getSALOMERuntime()->getOrb());
594 if(!CORBA::is_nil(orb))
596 CORBA::String_var IOR(orb->object_to_string(_pynode));
601 _errorDetails=msg.str();
602 throw Exception(msg.str());
604 catch(CORBA::COMM_FAILURE& ex)
606 std::ostringstream msg;
607 msg << "Exception on remote python invocation." << std::endl ;
608 msg << "Caught system exception COMM_FAILURE -- unable to contact the "
609 << "object." << std::endl;
610 _errorDetails=msg.str();
611 throw Exception(msg.str());
613 catch(CORBA::SystemException& ex)
615 std::ostringstream msg;
616 msg << "Exception on remote python invocation." << std::endl ;
617 msg << "Caught a CORBA::SystemException." ;
620 CORBA::TypeCode_var tc = tmp.type();
621 const char *p = tc->name();
627 _errorDetails=msg.str();
628 throw Exception(msg.str());
630 catch(CORBA::Exception& ex)
632 std::ostringstream msg;
633 msg << "Exception on remote python invocation." << std::endl ;
634 msg << "Caught CORBA::Exception. " ;
637 CORBA::TypeCode_var tc = tmp.type();
638 const char *p = tc->name();
644 _errorDetails=msg.str();
645 throw Exception(msg.str());
647 catch(omniORB::fatalException& fe)
649 std::ostringstream msg;
650 msg << "Exception on remote python invocation." << std::endl ;
651 msg << "Caught omniORB::fatalException:" << std::endl;
652 msg << " file: " << fe.file() << std::endl;
653 msg << " line: " << fe.line() << std::endl;
654 msg << " mesg: " << fe.errmsg() << std::endl;
655 _errorDetails=msg.str();
656 throw Exception(msg.str());
658 DEBTRACE( "-----------------end of remote python invocation-----------------" );
659 //===========================================================================
660 // Get results, unpickle and put them in output ports
661 //===========================================================================
663 #if PY_VERSION_HEX < 0x03070000
664 std::unique_lock<std::mutex> lock(data_mutex);
667 DEBTRACE( "-----------------PythonNode::outputs-----------------" );
668 int nres( resultCorba->length() );
670 if(getNumberOfOutputPorts() != nres)
672 std::string msg="Number of output arguments : Mismatch between definition and execution";
674 throw Exception(msg);
679 for(iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); ++iter)
681 OutputPyPort *p=(OutputPyPort *)*iter;
682 DEBUG_YACSTRACE("Start of dealing with output " << p->getName() << " of "<< getId());
683 DEBTRACE( "port name: " << p->getName() );
684 DEBTRACE( "port kind: " << p->edGetType()->kind() );
685 DEBTRACE( "port pos : " << pos );
686 SALOME::SenderByte_var elt = (*resultCorba)[pos];
687 SeqByteReceiver recv(elt);
688 unsigned long length = 0;
689 char *resultCorbaC = recv.data(length);
691 AutoPyRef resultPython=PyMemoryView_FromMemory(resultCorbaC,length,PyBUF_READ);
692 AutoPyRef args = PyTuple_New(1);
693 PyTuple_SetItem(args,0,resultPython.retn());
694 AutoPyRef ob = PyObject_CallObject(_pyfuncUnser,args);
697 std::stringstream msg;
698 msg << "Conversion with pickle of output ports failed !";
699 msg << " : " << __FILE__ << ":" << __LINE__;
700 _errorDetails=msg.str();
701 throw YACS::ENGINE::ConversionException(msg.str());
703 UnlinkOnDestructorIfProxy(ob);
704 DEBUG_YACSTRACE("Assign PyObj output " << p->getName() << " of "<< getId());
706 DEBUG_YACSTRACE("End of assign PyObj output " << p->getName() << " of "<< getId());
711 catch(ConversionException& ex)
713 _errorDetails=ex.what();
717 squeezeMemoryRemote();
720 if(!isUsingPythonCache())
724 Engines::Container_var cont(GetContainerObj(this,dummy));
725 cont->removePyScriptNode(getId().c_str());
727 DEBTRACE( "++++++++++++++ ENDOF PyNode::executeRemote: " << getName() << " ++++++++++++++++++++" );
730 void PythonNode::ExecuteLocalInternal(const std::string& codeStr, PyObject *context, std::string& errorDetails)
733 DEBTRACE( "context refcnt: " << context->ob_refcnt );
734 std::ostringstream stream;
735 stream << "/tmp/PythonNode_";
737 AutoPyRef code=Py_CompileString(codeStr.c_str(), stream.str().c_str(), Py_file_input);
741 AutoPyRef new_stderr = newPyStdOut(errorDetails);
742 PySys_SetObject((char*)"stderr", new_stderr);
744 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
745 throw YACS::Exception("Error during execution");
748 AutoPyRef res = PyEval_EvalCode( code, context, context);
750 DEBTRACE( "context refcnt: " << context->ob_refcnt );
753 if(PyErr_Occurred ())
756 AutoPyRef new_stderr = newPyStdOut(errorDetails);
757 PySys_SetObject((char*)"stderr", new_stderr);
758 ofstream errorfile(stream.str().c_str());
759 if (errorfile.is_open())
761 errorfile << codeStr;
765 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
766 throw YACS::Exception("Error during execution");
770 void PythonNode::executeLocalInternal(const std::string& codeStr)
772 ExecuteLocalInternal(codeStr,_context,_errorDetails);
775 void PythonNode::executeLocal()
777 DEBTRACE( "++++++++++++++ PyNode::executeLocal: " << getName() << " ++++++++++++++++++++" );
780 std::ostringstream unpxy; unpxy << "from SALOME_PyNode import UnProxyObjectSimpleLocal" << std::endl;
781 DEBTRACE( "---------------PyNode::inputs---------------" );
782 list<InputPort *>::iterator iter2;
783 for(iter2 = _setOfInputPort.begin(); iter2 != _setOfInputPort.end(); iter2++)
785 InputPyPort *p=(InputPyPort *)*iter2;
786 DEBTRACE( "port name: " << p->getName() );
787 DEBTRACE( "port kind: " << p->edGetType()->kind() );
788 PyObject* ob=p->getPyObj();
789 DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
790 unpxy << p->getName() << " = UnProxyObjectSimpleLocal( " << p->getName() << " )" << std::endl;
792 PyObject_Print(ob,stderr,Py_PRINT_RAW);
795 int ier=PyDict_SetItemString(_context,p->getName().c_str(),ob);
796 DEBTRACE( "after PyDict_SetItemString:ob refcnt: " << ob->ob_refcnt );
799 DEBTRACE( "---------------End PyNode::inputs---------------" );
802 DEBTRACE( "----------------PyNode::calculation---------------" );
804 if( ! getSqueezeStatus() )
805 executeLocalInternal( unpxy.str() );
807 executeLocalInternal( _script );
809 DEBTRACE( "-----------------PyNode::outputs-----------------" );
810 list<OutputPort *>::iterator iter;
813 for(iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); iter++)
815 OutputPyPort *p=(OutputPyPort *)*iter;
816 DEBTRACE( "port name: " << p->getName() );
817 DEBTRACE( "port kind: " << p->edGetType()->kind() );
818 PyObject *ob=PyDict_GetItemString(_context,p->getName().c_str());
821 std::string msg="Error during execution: there is no variable ";
822 msg=msg+p->getName()+" in node context";
824 throw Exception(msg);
826 DEBTRACE( "PyNode::outputs::ob refcnt: " << ob->ob_refcnt );
828 PyObject_Print(ob,stderr,Py_PRINT_RAW);
832 if(!isUsingPythonCache())
833 PyDict_DelItemString(_context,p->getName().c_str());
836 catch(ConversionException& ex)
838 _errorDetails=ex.what();
843 DEBTRACE( "-----------------End PyNode::outputs-----------------" );
844 if(!isUsingPythonCache())
846 for(iter2 = _setOfInputPort.begin(); iter2 != _setOfInputPort.end(); iter2++)
848 AutoPyRef pStr = PyUnicode_FromString( (*iter2)->getName().c_str() );
849 if( PyDict_Contains(_context,pStr) == 1 )
850 { PyDict_DelItem(_context,pStr); }
854 DEBTRACE( "++++++++++++++ End PyNode::execute: " << getName() << " ++++++++++++++++++++" );
859 * \param in squeezeExceptions list on output port name excluded from the squeeze mecanism
861 void PythonNode::setSqueezeStatusWithExceptions(bool sqStatus, const std::vector<std::string>& squeezeExceptions)
863 this->setSqueezeStatus(sqStatus);
864 this->_nonSqueezableOutputNodes = std::set<std::string>(squeezeExceptions.begin(), squeezeExceptions.end());
867 void PythonNode::squeezeMemorySafe()
870 if(_mode==PythonNode::REMOTE_NAME)
871 this->squeezeMemoryRemote();
873 this->squeezeMemory();
876 void PythonNode::squeezeMemory()
878 for(auto p : _setOfInputPort)
880 PyDict_DelItemString(_context,p->getName().c_str());
881 InputPyPort *p2(static_cast<InputPyPort *>(p));
882 if(p2->canSafelySqueezeMemory())
885 for(auto p : _setOfOutputPort)
887 if (!this->_nonSqueezableOutputNodes.empty() && this->_nonSqueezableOutputNodes.find(p->getName()) != this->_nonSqueezableOutputNodes.end())
889 PyDict_DelItemString(_context,p->getName().c_str());
890 OutputPyPort *p2(static_cast<OutputPyPort *>(p));
891 p2->putWithoutForward(Py_None);
895 void PythonNode::squeezeMemoryRemote()
897 for(auto p : _setOfInputPort)
899 InputPyPort *p2(static_cast<InputPyPort *>(p));
900 if(p2->canSafelySqueezeMemory())
903 for(auto p : _setOfOutputPort)
905 if (!this->_nonSqueezableOutputNodes.empty() && this->_nonSqueezableOutputNodes.find(p->getName()) != this->_nonSqueezableOutputNodes.end())
907 OutputPyPort *p2(static_cast<OutputPyPort *>(p));
908 p2->putWithoutForward(Py_None);
912 std::string PythonNode::getContainerLog()
914 return PythonEntry::GetContainerLog(_mode,_container,this);
917 void PythonNode::shutdown(int level)
919 DEBTRACE("PythonNode::shutdown " << level);
920 if(_mode=="local")return;
924 _container->shutdown(level);
928 void PythonNode::imposeResource(const std::string& resource_name,
929 const std::string& container_name)
931 if(!resource_name.empty() && !container_name.empty())
933 _imposedResource = resource_name;
934 _imposedContainer = container_name;
938 bool PythonNode::canAcceptImposedResource()
940 return _container != nullptr && _container->canAcceptImposedResource();
943 bool PythonNode::hasImposedResource()const
945 return PythonEntry::hasImposedResource();
948 std::string PythonNode::pythonEntryName()const
950 if(isUsingPythonCache())
951 return "DEFAULT_NAME_FOR_UNIQUE_PYTHON_NODE_ENTRY";
956 bool PythonNode::isUsingPythonCache()const
960 found = _container->isUsingPythonCache();
964 void PythonNode::freeKernelPynode()
966 if(!CORBA::is_nil(_pynode))
970 _pynode->UnRegister();
974 DEBTRACE("Trouble when pynode->UnRegister!")
976 _pynode = Engines::PyScriptNode::_nil();
980 Node *PythonNode::simpleClone(ComposedNode *father, bool editionOnly) const
982 return new PythonNode(*this,father);
985 void PythonNode::createRemoteAdaptedPyInterpretor(Engines::Container_ptr objContainer)
988 _pynode=objContainer->createPyScriptNode(pythonEntryName().c_str(),getScript().c_str());
992 Engines::PyNodeBase_var PythonNode::retrieveDftRemotePyInterpretorIfAny(Engines::Container_ptr objContainer) const
994 Engines::PyScriptNode_var ret(objContainer->getDefaultPyScriptNode(pythonEntryName().c_str()));
995 if(!CORBA::is_nil(ret))
999 return Engines::PyNodeBase::_narrow(ret);
1002 void PythonNode::assignRemotePyInterpretor(Engines::PyNodeBase_var remoteInterp)
1004 if(CORBA::is_nil(_pynode))
1005 _pynode=Engines::PyScriptNode::_narrow(remoteInterp);
1008 Engines::PyScriptNode_var tmpp(Engines::PyScriptNode::_narrow(remoteInterp));
1009 if(!_pynode->_is_equivalent(tmpp))
1012 _pynode=Engines::PyScriptNode::_narrow(remoteInterp);
1015 _pynode->assignNewCompiledCode(getScript().c_str());
1018 Engines::PyNodeBase_var PythonNode::getRemoteInterpreterHandle()
1020 return Engines::PyNodeBase::_narrow(_pynode);
1023 //! Create a new node of same type with a given name
1024 PythonNode* PythonNode::cloneNode(const std::string& name)
1026 PythonNode* n=new PythonNode(name);
1027 n->setScript(_script);
1028 list<InputPort *>::iterator iter;
1029 for(iter = _setOfInputPort.begin(); iter != _setOfInputPort.end(); iter++)
1031 InputPyPort *p=(InputPyPort *)*iter;
1032 DEBTRACE( "port name: " << p->getName() );
1033 DEBTRACE( "port kind: " << p->edGetType()->kind() );
1034 n->edAddInputPort(p->getName(),p->edGetType());
1036 list<OutputPort *>::iterator iter2;
1037 for(iter2 = _setOfOutputPort.begin(); iter2 != _setOfOutputPort.end(); iter2++)
1039 OutputPyPort *p=(OutputPyPort *)*iter2;
1040 DEBTRACE( "port name: " << p->getName() );
1041 DEBTRACE( "port kind: " << p->edGetType()->kind() );
1042 n->edAddOutputPort(p->getName(),p->edGetType());
1047 void PythonNode::applyDPLScope(ComposedNode *gfn)
1049 std::vector< std::pair<std::string,int> > ret(getDPLScopeInfo(gfn));
1056 std::size_t sz(ret.size());
1058 for(std::size_t i=0;i<sz;i++)
1060 const std::pair<std::string,int>& p(ret[i]);
1061 PyObject *elt(PyTuple_New(2));
1062 PyTuple_SetItem(elt,0,PyUnicode_FromString(p.first.c_str()));
1063 PyTuple_SetItem(elt,1,PyLong_FromLong(p.second));
1064 PyList_SetItem(ob,i,elt);
1067 if(_mode==REMOTE_NAME)
1069 Engines::pickledArgs_var serializationInputCorba(new Engines::pickledArgs);
1072 PyObject *serializationInput(PyObject_CallFunctionObjArgs(_pyfuncSimpleSer,ob,NULL));
1074 char *serializationInputC(0);
1076 if (PyBytes_AsStringAndSize(serializationInput, &serializationInputC, &len))
1077 throw Exception("DistributedPythonNode problem in python pickle");
1078 serializationInputCorba->length(len);
1079 for(int i=0; i < len ; i++)
1080 serializationInputCorba[i]=serializationInputC[i];
1081 Py_XDECREF(serializationInput);
1083 _pynode->defineNewCustomVar(DPL_INFO_NAME,serializationInputCorba);
1088 PyDict_SetItemString(_context,DPL_INFO_NAME,ob);
1093 PyFuncNode::PyFuncNode(const PyFuncNode& other, ComposedNode *father):InlineFuncNode(other,father),_pyfunc(0)
1095 _implementation = PythonNode::IMPL_NAME;
1098 _context=PyDict_New();
1099 DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
1100 if( PyDict_SetItemString( _context, "__builtins__", getSALOMERuntime()->getBuiltins() ))
1103 msg << "Not possible to set builtins" << __FILE__ << ":" << __LINE__;
1104 _errorDetails=msg.str();
1105 throw Exception(msg.str());
1110 PyFuncNode::PyFuncNode(const std::string& name): InlineFuncNode(name),_pyfunc(0)
1113 _implementation = PythonNode::IMPL_NAME;
1114 DEBTRACE( "PyFuncNode::PyFuncNode " << name );
1117 _context=PyDict_New();
1118 DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
1119 if( PyDict_SetItemString( _context, "__builtins__", getSALOMERuntime()->getBuiltins() ))
1122 msg << "Not possible to set builtins" << __FILE__ << ":" << __LINE__;
1123 _errorDetails=msg.str();
1124 throw Exception(msg.str());
1129 PyFuncNode::~PyFuncNode()
1131 if(!CORBA::is_nil(_pynode))
1133 _pynode->UnRegister();
1137 void PyFuncNode::init(bool start)
1139 initCommonPartWithoutStateManagement(start);
1140 if(_state == YACS::DISABLED)
1142 exDisabledState(); // to refresh propagation of DISABLED state
1145 if(start) //complete initialization
1146 setState(YACS::READY);
1147 else if(_state > YACS::LOADED)// WARNING FuncNode has internal vars (CEA usecase) ! Partial initialization (inside a loop). Exclusivity of funcNode.
1148 setState(YACS::TORECONNECT);
1151 void PyFuncNode::checkBasicConsistency() const
1153 DEBTRACE("checkBasicConsistency");
1154 InlineFuncNode::checkBasicConsistency();
1158 res=Py_CompileString(_script.c_str(),getName().c_str(),Py_file_input);
1161 std::string error="";
1162 PyObject* new_stderr = newPyStdOut(error);
1163 PySys_SetObject((char*)"stderr", new_stderr);
1165 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
1166 Py_DECREF(new_stderr);
1167 throw Exception(error);
1174 void PyFuncNode::load()
1176 DEBTRACE( "---------------PyfuncNode::load function---------------" );
1177 if(_mode==PythonNode::REMOTE_NAME)
1183 void PyFuncNode::loadRemote()
1185 commonRemoteLoad(this);
1188 void PyFuncNode::loadLocal()
1190 DEBTRACE( "---------------PyFuncNode::load function " << getName() << " ---------------" );
1191 DEBTRACE( _script );
1194 list<OutputPort *>::iterator iter;
1195 for(iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); iter++)
1197 OutputPyPort *p=(OutputPyPort *)*iter;
1198 DEBTRACE( "port name: " << p->getName() );
1199 DEBTRACE( "port kind: " << p->edGetType()->kind() );
1205 DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
1207 std::ostringstream stream;
1208 stream << "/tmp/PythonNode_";
1211 PyObject* code=Py_CompileString(_script.c_str(), stream.str().c_str(), Py_file_input);
1215 PyObject* new_stderr = newPyStdOut(_errorDetails);
1216 PySys_SetObject((char*)"stderr", new_stderr);
1218 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
1219 Py_DECREF(new_stderr);
1220 throw Exception("Error during execution");
1222 PyObject *res = PyEval_EvalCode( code, _context, _context);
1226 DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
1227 if(PyErr_Occurred ())
1230 PyObject* new_stderr = newPyStdOut(_errorDetails);
1231 PySys_SetObject((char*)"stderr", new_stderr);
1232 ofstream errorfile(stream.str().c_str());
1233 if (errorfile.is_open())
1235 errorfile << _script;
1239 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
1240 Py_DECREF(new_stderr);
1241 throw Exception("Error during execution");
1244 _pyfunc=PyDict_GetItemString(_context,_fname.c_str());
1245 DEBTRACE( "_pyfunc refcnt: " << _pyfunc->ob_refcnt );
1249 PyObject* new_stderr = newPyStdOut(_errorDetails);
1250 PySys_SetObject((char*)"stderr", new_stderr);
1252 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
1253 Py_DECREF(new_stderr);
1254 throw Exception("Error during execution");
1256 DEBTRACE( "---------------End PyFuncNode::load function---------------" );
1260 void PyFuncNode::execute()
1262 if(_mode==PythonNode::REMOTE_NAME)
1268 void PyFuncNode::executeRemote()
1270 DEBTRACE( "++++++++++++++ PyFuncNode::executeRemote: " << getName() << " ++++++++++++++++++++" );
1272 throw Exception("DistributedPythonNode badly loaded");
1274 if(dynamic_cast<HomogeneousPoolContainer *>(getContainer()))
1277 loadPythonAdapter(this,dummy);
1278 _pynode->executeAnotherPieceOfCode(getScript().c_str());
1281 Engines::pickledArgs_var serializationInputCorba(new Engines::pickledArgs);;
1283 #if PY_VERSION_HEX < 0x03070000
1284 std::unique_lock<std::mutex> lock(data_mutex);
1288 //===========================================================================
1289 // Get inputs in input ports, build a Python tuple and pickle it
1290 //===========================================================================
1291 PyObject *args(PyTuple_New(getNumberOfInputPorts()));
1293 for(std::list<InputPort *>::iterator iter2 = _setOfInputPort.begin(); iter2 != _setOfInputPort.end(); iter2++,pos++)
1295 InputPyPort *p=(InputPyPort *)*iter2;
1298 PyTuple_SetItem(args,pos,ob);
1301 PyObject_Print(args,stderr,Py_PRINT_RAW);
1304 PyObject *serializationInput=PyObject_CallObject(_pyfuncSer,args);
1306 //The pickled string may contain NULL characters so use PyString_AsStringAndSize
1307 char *serializationInputC(0);
1309 if (PyBytes_AsStringAndSize(serializationInput, &serializationInputC, &len))
1310 throw Exception("DistributedPythonNode problem in python pickle");
1312 serializationInputCorba->length(len);
1313 for(int i=0; i < len ; i++)
1314 serializationInputCorba[i]=serializationInputC[i];
1315 Py_DECREF(serializationInput);
1318 //===========================================================================
1319 // Execute in remote Python node
1320 //===========================================================================
1321 DEBTRACE( "-----------------starting remote python invocation-----------------" );
1322 Engines::pickledArgs_var resultCorba;
1325 resultCorba=_pynode->execute(getFname().c_str(),serializationInputCorba);
1327 catch( const SALOME::SALOME_Exception& ex )
1329 std::string msg="Exception on remote python invocation";
1331 msg += ex.details.text.in();
1333 throw Exception(msg);
1335 catch(CORBA::COMM_FAILURE& ex)
1337 std::ostringstream msg;
1338 msg << "Exception on remote python invocation." << std::endl ;
1339 msg << "Caught system exception COMM_FAILURE -- unable to contact the "
1340 << "object." << std::endl;
1341 _errorDetails=msg.str();
1342 throw Exception(msg.str());
1344 catch(CORBA::SystemException& ex)
1346 std::ostringstream msg;
1347 msg << "Exception on remote python invocation." << std::endl ;
1348 msg << "Caught a CORBA::SystemException." ;
1351 CORBA::TypeCode_var tc = tmp.type();
1352 const char *p = tc->name();
1358 _errorDetails=msg.str();
1359 throw Exception(msg.str());
1361 catch(CORBA::Exception& ex)
1363 std::ostringstream msg;
1364 msg << "Exception on remote python invocation." << std::endl ;
1365 msg << "Caught CORBA::Exception. " ;
1368 CORBA::TypeCode_var tc = tmp.type();
1369 const char *p = tc->name();
1375 _errorDetails=msg.str();
1376 throw Exception(msg.str());
1378 catch(omniORB::fatalException& fe)
1380 std::ostringstream msg;
1381 msg << "Exception on remote python invocation." << std::endl ;
1382 msg << "Caught omniORB::fatalException:" << std::endl;
1383 msg << " file: " << fe.file() << std::endl;
1384 msg << " line: " << fe.line() << std::endl;
1385 msg << " mesg: " << fe.errmsg() << std::endl;
1386 _errorDetails=msg.str();
1387 throw Exception(msg.str());
1389 DEBTRACE( "-----------------end of remote python invocation-----------------" );
1390 //===========================================================================
1391 // Get results, unpickle and put them in output ports
1392 //===========================================================================
1393 char *resultCorbaC=new char[resultCorba->length()+1];
1394 resultCorbaC[resultCorba->length()]='\0';
1395 for(int i=0;i<resultCorba->length();i++)
1396 resultCorbaC[i]=resultCorba[i];
1399 #if PY_VERSION_HEX < 0x03070000
1400 std::unique_lock<std::mutex> lock(data_mutex);
1404 PyObject *resultPython(PyBytes_FromStringAndSize(resultCorbaC,resultCorba->length()));
1405 delete [] resultCorbaC;
1406 PyObject *args(PyTuple_New(1)),*ob(0);
1407 PyTuple_SetItem(args,0,resultPython);
1408 PyObject *finalResult=PyObject_CallObject(_pyfuncUnser,args);
1411 DEBTRACE( "-----------------PythonNode::outputs-----------------" );
1413 if(finalResult == Py_None)
1415 else if(PyTuple_Check(finalResult))
1416 nres=PyTuple_Size(finalResult);
1418 if(getNumberOfOutputPorts() != nres)
1420 std::string msg="Number of output arguments : Mismatch between definition and execution";
1421 Py_DECREF(finalResult);
1423 throw Exception(msg);
1429 for(std::list<OutputPort *>::iterator iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); iter++, pos++)
1431 OutputPyPort *p=(OutputPyPort *)*iter;
1432 DEBTRACE( "port name: " << p->getName() );
1433 DEBTRACE( "port kind: " << p->edGetType()->kind() );
1434 DEBTRACE( "port pos : " << pos );
1435 if(PyTuple_Check(finalResult))
1436 ob=PyTuple_GetItem(finalResult,pos) ;
1439 DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
1442 Py_DECREF(finalResult);
1444 catch(ConversionException& ex)
1446 Py_DECREF(finalResult);
1447 _errorDetails=ex.what();
1452 DEBTRACE( "++++++++++++++ ENDOF PyFuncNode::executeRemote: " << getName() << " ++++++++++++++++++++" );
1455 void PyFuncNode::executeLocal()
1457 DEBTRACE( "++++++++++++++ PyFuncNode::execute: " << getName() << " ++++++++++++++++++++" );
1461 if(!_pyfunc)throw Exception("PyFuncNode badly loaded");
1464 DEBTRACE( "---------------PyFuncNode::inputs---------------" );
1465 PyObject* args = PyTuple_New(getNumberOfInputPorts()) ;
1466 list<InputPort *>::iterator iter2;
1467 for(iter2 = _setOfInputPort.begin(); iter2 != _setOfInputPort.end(); iter2++)
1469 InputPyPort *p=(InputPyPort *)*iter2;
1470 DEBTRACE( "port name: " << p->getName() );
1471 DEBTRACE( "port kind: " << p->edGetType()->kind() );
1474 PyObject_Print(ob,stderr,Py_PRINT_RAW);
1477 DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
1479 PyTuple_SetItem(args,pos,ob);
1480 DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
1483 DEBTRACE( "---------------End PyFuncNode::inputs---------------" );
1485 DEBTRACE( "----------------PyFuncNode::calculation---------------" );
1487 PyObject_Print(_pyfunc,stderr,Py_PRINT_RAW);
1489 PyObject_Print(args,stderr,Py_PRINT_RAW);
1492 DEBTRACE( "_pyfunc refcnt: " << _pyfunc->ob_refcnt );
1493 PyObject* result = PyObject_CallObject( _pyfunc , args ) ;
1494 DEBTRACE( "_pyfunc refcnt: " << _pyfunc->ob_refcnt );
1501 PyObject* new_stderr = newPyStdOut(_errorDetails);
1502 PySys_SetObject((char*)"stderr", new_stderr);
1503 std::ostringstream stream;
1504 stream << "/tmp/PythonNode_";
1506 ofstream errorfile(stream.str().c_str());
1507 if (errorfile.is_open())
1509 errorfile << _script;
1513 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
1514 Py_DECREF(new_stderr);
1515 throw Exception("Error during execution");
1517 DEBTRACE( "----------------End PyFuncNode::calculation---------------" );
1519 DEBTRACE( "-----------------PyFuncNode::outputs-----------------" );
1521 if(result == Py_None)
1523 else if(PyTuple_Check(result))
1524 nres=PyTuple_Size(result);
1526 if(getNumberOfOutputPorts() != nres)
1528 std::string msg="Number of output arguments : Mismatch between definition and execution";
1531 throw Exception(msg);
1536 PyObject_Print(result,stderr,Py_PRINT_RAW);
1539 list<OutputPort *>::iterator iter;
1542 for(iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); iter++)
1544 OutputPyPort *p=(OutputPyPort *)*iter;
1545 DEBTRACE( "port name: " << p->getName() );
1546 DEBTRACE( "port kind: " << p->edGetType()->kind() );
1547 DEBTRACE( "port pos : " << pos );
1548 if(PyTuple_Check(result))ob=PyTuple_GetItem(result,pos) ;
1550 DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
1552 PyObject_Print(ob,stderr,Py_PRINT_RAW);
1559 catch(ConversionException& ex)
1562 _errorDetails=ex.what();
1565 DEBTRACE( "-----------------End PyFuncNode::outputs-----------------" );
1568 DEBTRACE( "++++++++++++++ End PyFuncNode::execute: " << getName() << " ++++++++++++++++++++" );
1571 Node *PyFuncNode::simpleClone(ComposedNode *father, bool editionOnly) const
1573 return new PyFuncNode(*this,father);
1576 void PyFuncNode::createRemoteAdaptedPyInterpretor(Engines::Container_ptr objContainer)
1578 if(!CORBA::is_nil(_pynode))
1579 _pynode->UnRegister();
1580 _pynode=objContainer->createPyNode(getName().c_str(),getScript().c_str());
1583 Engines::PyNodeBase_var PyFuncNode::retrieveDftRemotePyInterpretorIfAny(Engines::Container_ptr objContainer) const
1585 Engines::PyNode_var ret(objContainer->getDefaultPyNode(getName().c_str()));
1586 if(!CORBA::is_nil(ret))
1590 return Engines::PyNodeBase::_narrow(ret);
1593 void PyFuncNode::assignRemotePyInterpretor(Engines::PyNodeBase_var remoteInterp)
1595 if(!CORBA::is_nil(_pynode))
1597 Engines::PyNode_var tmpp(Engines::PyNode::_narrow(remoteInterp));
1598 if(_pynode->_is_equivalent(tmpp))
1601 if(!CORBA::is_nil(_pynode))
1602 _pynode->UnRegister();
1603 _pynode=Engines::PyNode::_narrow(remoteInterp);
1606 Engines::PyNodeBase_var PyFuncNode::getRemoteInterpreterHandle()
1608 return Engines::PyNodeBase::_narrow(_pynode);
1611 //! Create a new node of same type with a given name
1612 PyFuncNode* PyFuncNode::cloneNode(const std::string& name)
1614 PyFuncNode* n=new PyFuncNode(name);
1615 n->setScript(_script);
1616 n->setFname(_fname);
1617 list<InputPort *>::iterator iter;
1618 for(iter = _setOfInputPort.begin(); iter != _setOfInputPort.end(); iter++)
1620 InputPyPort *p=(InputPyPort *)*iter;
1621 n->edAddInputPort(p->getName(),p->edGetType());
1623 list<OutputPort *>::iterator iter2;
1624 for(iter2 = _setOfOutputPort.begin(); iter2 != _setOfOutputPort.end(); iter2++)
1626 OutputPyPort *p=(OutputPyPort *)*iter2;
1627 n->edAddOutputPort(p->getName(),p->edGetType());
1632 std::string PyFuncNode::getContainerLog()
1634 return PythonEntry::GetContainerLog(_mode,_container,this);
1637 void PyFuncNode::shutdown(int level)
1639 DEBTRACE("PyFuncNode::shutdown " << level);
1640 if(_mode=="local")return;
1643 if(!CORBA::is_nil(_pynode)) _pynode->UnRegister();
1644 _pynode=Engines::PyNode::_nil();
1645 _container->shutdown(level);
1649 void PyFuncNode::imposeResource(const std::string& resource_name,
1650 const std::string& container_name)
1652 if(!resource_name.empty() && !container_name.empty())
1654 _imposedResource = resource_name;
1655 _imposedContainer = container_name;
1659 bool PyFuncNode::canAcceptImposedResource()
1661 return _container != nullptr && _container->canAcceptImposedResource();
1664 bool PyFuncNode::hasImposedResource()const
1666 return PythonEntry::hasImposedResource();