1 // Copyright (C) 2006-2020 CEA/DEN, EDF R&D
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 "AutoGIL.hxx"
25 #include "Container.hxx"
26 #include "SalomeContainer.hxx"
27 #include "SalomeHPContainer.hxx"
28 #include "SalomeContainerTmpForHP.hxx"
29 #include "ConversionException.hxx"
31 #include "PyStdout.hxx"
39 #define getpid _getpid
42 #if PY_VERSION_HEX < 0x02050000
43 typedef int Py_ssize_t;
47 #include "YacsTrace.hxx"
49 using namespace YACS::ENGINE;
52 const char PythonEntry::SCRIPT_FOR_SIMPLE_SERIALIZATION[]="import pickle\n"
53 "def pickleForVarSimplePyth2009(val):\n"
54 " return pickle.dumps(val,-1)\n"
57 const char PythonNode::IMPL_NAME[]="Python";
58 const char PythonNode::KIND[]="Python";
60 const char PythonNode::SCRIPT_FOR_SERIALIZATION[]="import pickle\n"
61 "def pickleForDistPyth2009(kws):\n"
62 " return pickle.dumps(((),kws),-1)\n"
64 "def unPickleForDistPyth2009(st):\n"
65 " args=pickle.loads(st)\n"
68 const char PythonNode::REMOTE_NAME[]="remote";
70 const char PythonNode::DPL_INFO_NAME[]="my_dpl_localization";
72 const char PyFuncNode::SCRIPT_FOR_SERIALIZATION[]="import pickle\n"
73 "def pickleForDistPyth2009(*args,**kws):\n"
74 " return pickle.dumps((args,kws),-1)\n"
76 "def unPickleForDistPyth2009(st):\n"
77 " args=pickle.loads(st)\n"
80 PythonEntry::PythonEntry():_context(0),_pyfuncSer(0),_pyfuncUnser(0),_pyfuncSimpleSer(0)
84 PythonEntry::~PythonEntry()
87 DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
88 // not Py_XDECREF of _pyfuncUnser because it is returned by PyDict_GetItem -> borrowed
89 // not Py_XDECREF of _pyfuncSer because it is returned by PyDict_GetItem -> borrowed
93 void PythonEntry::loadRemoteContainer(InlineNode *reqNode)
95 DEBTRACE( "---------------PythonEntry::CommonRemoteLoad function---------------" );
96 Container *container(reqNode->getContainer());
97 bool isContAlreadyStarted(false);
102 if(hasImposedResource())
103 container->start(reqNode, _imposedResource, _imposedContainer);
106 isContAlreadyStarted=container->isAlreadyStarted(reqNode);
107 if(!isContAlreadyStarted)
108 container->start(reqNode);
113 reqNode->setErrorDetails(e.what());
119 std::string what("PythonEntry::CommonRemoteLoad : a load operation requested on \"");
120 what+=reqNode->getName(); what+="\" with no container specified.";
121 reqNode->setErrorDetails(what);
122 throw Exception(what);
126 Engines::Container_var GetContainerObj(InlineNode *reqNode, bool& isStandardCont)
128 isStandardCont = false;
129 Container *container(reqNode->getContainer());
130 Engines::Container_var objContainer(Engines::Container::_nil());
132 throw YACS::Exception("No container specified !");
133 SalomeContainer *containerCast0(dynamic_cast<SalomeContainer *>(container));
134 SalomeHPContainer *containerCast1(dynamic_cast<SalomeHPContainer *>(container));
137 isStandardCont = true;
138 objContainer=containerCast0->getContainerPtr(reqNode);
140 else if(containerCast1)
142 YACS::BASES::AutoCppPtr<SalomeContainerTmpForHP> tmpCont(SalomeContainerTmpForHP::BuildFrom(containerCast1,reqNode));
143 objContainer=tmpCont->getContainerPtr(reqNode);
146 throw YACS::Exception("Unrecognized type of container ! Salome one is expected for PythonNode/PyFuncNode !");
147 if(CORBA::is_nil(objContainer))
148 throw YACS::Exception("Container corba pointer is NULL for PythonNode !");
152 Engines::Container_var PythonEntry::loadPythonAdapter(InlineNode *reqNode, bool& isInitializeRequested)
154 bool isStandardCont(true);
155 Engines::Container_var objContainer(GetContainerObj(reqNode,isStandardCont));
156 isInitializeRequested=false;
159 Engines::PyNodeBase_var dftPyScript(retrieveDftRemotePyInterpretorIfAny(objContainer));
160 if(CORBA::is_nil(dftPyScript))
162 isInitializeRequested=!isStandardCont;
163 createRemoteAdaptedPyInterpretor(objContainer);
166 assignRemotePyInterpretor(dftPyScript);
168 catch( const SALOME::SALOME_Exception& ex )
170 std::string msg="Exception on remote python node creation ";
172 msg += ex.details.text.in();
173 reqNode->setErrorDetails(msg);
174 throw Exception(msg);
176 Engines::PyNodeBase_var pynode(getRemoteInterpreterHandle());
177 if(CORBA::is_nil(pynode))
178 throw Exception("In PythonNode the ref in NULL ! ");
182 void PythonEntry::loadRemoteContext(InlineNode *reqNode, Engines::Container_ptr objContainer, bool isInitializeRequested)
184 Container *container(reqNode->getContainer());
185 Engines::PyNodeBase_var pynode(getRemoteInterpreterHandle());
189 const char *picklizeScript(getSerializationScript());
190 PyObject *res=PyRun_String(picklizeScript,Py_file_input,_context,_context);
191 PyObject *res2(PyRun_String(SCRIPT_FOR_SIMPLE_SERIALIZATION,Py_file_input,_context,_context));
192 if(res == NULL || res2==NULL)
194 std::string errorDetails;
195 PyObject* new_stderr = newPyStdOut(errorDetails);
196 reqNode->setErrorDetails(errorDetails);
197 PySys_SetObject((char*)"stderr", new_stderr);
199 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
200 Py_DECREF(new_stderr);
201 throw Exception("Error during load");
203 Py_DECREF(res); Py_DECREF(res2);
204 _pyfuncSer=PyDict_GetItemString(_context,"pickleForDistPyth2009");
205 _pyfuncUnser=PyDict_GetItemString(_context,"unPickleForDistPyth2009");
206 _pyfuncSimpleSer=PyDict_GetItemString(_context,"pickleForVarSimplePyth2009");
207 if(_pyfuncSer == NULL)
209 std::string errorDetails;
210 PyObject *new_stderr(newPyStdOut(errorDetails));
211 reqNode->setErrorDetails(errorDetails);
212 PySys_SetObject((char*)"stderr", new_stderr);
214 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
215 Py_DECREF(new_stderr);
216 throw Exception("Error during load");
218 if(_pyfuncUnser == NULL)
220 std::string errorDetails;
221 PyObject *new_stderr(newPyStdOut(errorDetails));
222 reqNode->setErrorDetails(errorDetails);
223 PySys_SetObject((char*)"stderr", new_stderr);
225 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
226 Py_DECREF(new_stderr);
227 throw Exception("Error during load");
229 if(_pyfuncSimpleSer == 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");
241 if(isInitializeRequested)
242 {//This one is called only once at initialization in the container if an init-script is specified.
245 std::string zeInitScriptKey(container->getProperty(HomogeneousPoolContainer::INITIALIZE_SCRIPT_KEY));
246 if(!zeInitScriptKey.empty())
247 pynode->executeAnotherPieceOfCode(zeInitScriptKey.c_str());
249 catch( const SALOME::SALOME_Exception& ex )
251 std::string msg="Exception on PythonNode::loadRemote python invocation of initializisation py script !";
253 msg += ex.details.text.in();
254 reqNode->setErrorDetails(msg);
255 throw Exception(msg);
257 DEBTRACE( "---------------End PyNode::loadRemote function---------------" );
261 std::string PythonEntry::GetContainerLog(const std::string& mode, Container *container, const Task *askingTask)
269 SalomeContainer *containerCast(dynamic_cast<SalomeContainer *>(container));
270 SalomeHPContainer *objContainer2(dynamic_cast<SalomeHPContainer *>(container));
273 Engines::Container_var objContainer(containerCast->getContainerPtr(askingTask));
274 CORBA::String_var logname = objContainer->logfilename();
277 std::string::size_type pos = msg.find(":");
278 msg=msg.substr(pos+1);
280 else if(objContainer2)
282 msg="Remote PythonNode is on HP Container : no log because no info of the location by definition of HP Container !";
286 msg="Not implemented yet for container log for that type of container !";
291 msg = "Container no longer reachable";
296 void PythonEntry::commonRemoteLoad(InlineNode *reqNode)
298 loadRemoteContainer(reqNode);
299 bool isInitializeRequested;
300 Engines::Container_var objContainer(loadPythonAdapter(reqNode,isInitializeRequested));
301 loadRemoteContext(reqNode,objContainer,isInitializeRequested);
304 bool PythonEntry::hasImposedResource()const
306 return !_imposedResource.empty() && !_imposedContainer.empty();
309 PythonNode::PythonNode(const PythonNode& other, ComposedNode *father):InlineNode(other,father),_autoSqueeze(other._autoSqueeze)
311 _pynode = Engines::PyScriptNode::_nil();
312 _implementation=IMPL_NAME;
315 _context=PyDict_New();
316 if( PyDict_SetItemString( _context, "__builtins__", getSALOMERuntime()->getBuiltins() ))
319 msg << "Impossible to set builtins" << __FILE__ << ":" << __LINE__;
320 _errorDetails=msg.str();
321 throw Exception(msg.str());
326 PythonNode::PythonNode(const std::string& name):InlineNode(name)
328 _pynode = Engines::PyScriptNode::_nil();
329 _implementation=IMPL_NAME;
332 _context=PyDict_New();
333 if( PyDict_SetItemString( _context, "__builtins__", getSALOMERuntime()->getBuiltins() ))
336 msg << "Impossible to set builtins" << __FILE__ << ":" << __LINE__;
337 _errorDetails=msg.str();
338 throw Exception(msg.str());
343 PythonNode::~PythonNode()
348 void PythonNode::checkBasicConsistency() const
350 DEBTRACE("checkBasicConsistency");
351 InlineNode::checkBasicConsistency();
355 res=Py_CompileString(_script.c_str(),getName().c_str(),Py_file_input);
358 std::string error="";
359 PyObject* new_stderr = newPyStdOut(error);
360 PySys_SetObject((char*)"stderr", new_stderr);
362 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
363 Py_DECREF(new_stderr);
364 throw Exception(error);
371 void PythonNode::load()
373 DEBTRACE( "---------------PyNode::load function---------------" );
374 if(_mode==PythonNode::REMOTE_NAME)
380 void PythonNode::loadLocal()
382 DEBTRACE( "---------------PyNode::loadLocal function---------------" );
386 void PythonNode::loadRemote()
388 commonRemoteLoad(this);
391 void PythonNode::execute()
393 if(_mode==PythonNode::REMOTE_NAME)
399 void PythonNode::executeRemote()
401 DEBTRACE( "++++++++++++++ PyNode::executeRemote: " << getName() << " ++++++++++++++++++++" );
403 throw Exception("PythonNode badly loaded");
405 if(dynamic_cast<HomogeneousPoolContainer *>(getContainer()))
408 loadPythonAdapter(this,dummy);
409 _pynode->assignNewCompiledCode(getScript().c_str());
412 std::unique_ptr<Engines::pickledArgs> serializationInputCorba(new Engines::pickledArgs);
413 AutoPyRef serializationInput;
416 PyObject *args(0),*ob(0);
417 //===========================================================================
418 // Get inputs in input ports, build a Python dict and pickle it
419 //===========================================================================
421 std::list<InputPort *>::iterator iter2;
423 for(iter2 = _setOfInputPort.begin(); iter2 != _setOfInputPort.end(); ++iter2)
425 InputPyPort *p=(InputPyPort *)*iter2;
427 PyDict_SetItemString(args,p->getName().c_str(),ob);
431 PyObject_Print(args,stderr,Py_PRINT_RAW);
434 serializationInput.set(PyObject_CallFunctionObjArgs(_pyfuncSer,args,nullptr));
436 //The pickled string may contain NULL characters so use PyString_AsStringAndSize
437 char *serializationInputC(0);
439 if (PyBytes_AsStringAndSize(serializationInput, &serializationInputC, &len))
440 throw Exception("DistributedPythonNode problem in python pickle");
441 // no copy here. The C byte array of Python is taken as this into CORBA sequence to avoid copy
442 serializationInputCorba.reset(new Engines::pickledArgs(len,len,reinterpret_cast<CORBA::Octet *>(serializationInputC),0));
445 //get the list of output argument names
446 std::list<OutputPort *>::iterator iter;
447 Engines::listofstring myseq;
448 myseq.length(getNumberOfOutputPorts());
450 for(iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); ++iter)
452 OutputPyPort *p=(OutputPyPort *)*iter;
453 myseq[pos]=p->getName().c_str();
454 DEBTRACE( "port name: " << p->getName() );
455 DEBTRACE( "port kind: " << p->edGetType()->kind() );
456 DEBTRACE( "port pos : " << pos );
459 //===========================================================================
460 // Execute in remote Python node
461 //===========================================================================
462 DEBTRACE( "-----------------starting remote python invocation-----------------" );
463 std::unique_ptr<Engines::pickledArgs> resultCorba;
466 //pass outargsname and dict serialized
467 _pynode->executeFirst(*(serializationInputCorba.get()));
468 //serializationInput and serializationInputCorba are no more needed for server. Release it.
469 serializationInputCorba.reset(nullptr); serializationInput.set(nullptr);
470 resultCorba.reset(_pynode->executeSecond(myseq));
472 catch( const SALOME::SALOME_Exception& ex )
474 std::ostringstream msg; msg << "Exception on remote python invocation" << std::endl << ex.details.text.in() << std::endl;
475 msg << "PyScriptNode CORBA ref : ";
477 CORBA::ORB_ptr orb(getSALOMERuntime()->getOrb());
478 if(!CORBA::is_nil(orb))
480 CORBA::String_var IOR(orb->object_to_string(_pynode));
485 _errorDetails=msg.str();
486 throw Exception(msg.str());
488 // if(!CORBA::is_nil(_pynode))
490 // _pynode->UnRegister();
492 // _pynode = Engines::PyScriptNode::_nil();
495 // Engines::Container_var cont(GetContainerObj(this,dummy));
496 // cont->removePyScriptNode(getName().c_str());
497 DEBTRACE( "-----------------end of remote python invocation-----------------" );
498 //===========================================================================
499 // Get results, unpickle and put them in output ports
500 //===========================================================================
501 auto length(resultCorba->length());
502 char *resultCorbaC(reinterpret_cast<char *>(resultCorba->get_buffer()));
505 PyObject *args(0),*ob(0);
506 PyObject* resultPython=PyMemoryView_FromMemory(resultCorbaC,length,PyBUF_READ);
507 args = PyTuple_New(1);
508 PyTuple_SetItem(args,0,resultPython);
509 PyObject *finalResult=PyObject_CallObject(_pyfuncUnser,args);
510 resultCorba.reset(nullptr);
513 if (finalResult == NULL)
515 std::stringstream msg;
516 msg << "Conversion with pickle of output ports failed !";
517 msg << " : " << __FILE__ << ":" << __LINE__;
518 _errorDetails=msg.str();
519 throw YACS::ENGINE::ConversionException(msg.str());
522 DEBTRACE( "-----------------PythonNode::outputs-----------------" );
524 if(finalResult == Py_None)
526 else if(PyTuple_Check(finalResult))
527 nres=PyTuple_Size(finalResult);
529 if(getNumberOfOutputPorts() != nres)
531 std::string msg="Number of output arguments : Mismatch between definition and execution";
532 Py_DECREF(finalResult);
534 throw Exception(msg);
540 for(iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); ++iter)
542 OutputPyPort *p=(OutputPyPort *)*iter;
543 DEBTRACE( "port name: " << p->getName() );
544 DEBTRACE( "port kind: " << p->edGetType()->kind() );
545 DEBTRACE( "port pos : " << pos );
546 if(PyTuple_Check(finalResult))
547 ob=PyTuple_GetItem(finalResult,pos) ;
550 DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
554 Py_DECREF(finalResult);
556 catch(ConversionException& ex)
558 Py_DECREF(finalResult);
559 _errorDetails=ex.what();
563 squeezeMemoryRemote();
566 if(!isUsingPythonCache())
570 Engines::Container_var cont(GetContainerObj(this,dummy));
571 cont->removePyScriptNode(getName().c_str());
573 DEBTRACE( "++++++++++++++ ENDOF PyNode::executeRemote: " << getName() << " ++++++++++++++++++++" );
576 void PythonNode::executeLocal()
578 DEBTRACE( "++++++++++++++ PyNode::executeLocal: " << getName() << " ++++++++++++++++++++" );
582 DEBTRACE( "---------------PyNode::inputs---------------" );
583 list<InputPort *>::iterator iter2;
584 for(iter2 = _setOfInputPort.begin(); iter2 != _setOfInputPort.end(); iter2++)
586 InputPyPort *p=(InputPyPort *)*iter2;
587 DEBTRACE( "port name: " << p->getName() );
588 DEBTRACE( "port kind: " << p->edGetType()->kind() );
589 PyObject* ob=p->getPyObj();
590 DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
592 PyObject_Print(ob,stderr,Py_PRINT_RAW);
595 int ier=PyDict_SetItemString(_context,p->getName().c_str(),ob);
596 DEBTRACE( "after PyDict_SetItemString:ob refcnt: " << ob->ob_refcnt );
599 DEBTRACE( "---------------End PyNode::inputs---------------" );
602 DEBTRACE( "----------------PyNode::calculation---------------" );
604 DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
606 std::ostringstream stream;
607 stream << "/tmp/PythonNode_";
610 PyObject* code=Py_CompileString(_script.c_str(), stream.str().c_str(), Py_file_input);
614 PyObject* new_stderr = newPyStdOut(_errorDetails);
615 PySys_SetObject((char*)"stderr", new_stderr);
617 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
618 Py_DECREF(new_stderr);
619 throw Exception("Error during execution");
621 PyObject *res = PyEval_EvalCode( code, _context, _context);
625 DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
628 if(PyErr_Occurred ())
631 PyObject* new_stderr = newPyStdOut(_errorDetails);
632 PySys_SetObject((char*)"stderr", new_stderr);
633 ofstream errorfile(stream.str().c_str());
634 if (errorfile.is_open())
636 errorfile << _script;
640 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
641 Py_DECREF(new_stderr);
642 throw Exception("Error during execution");
645 DEBTRACE( "-----------------PyNode::outputs-----------------" );
646 list<OutputPort *>::iterator iter;
649 for(iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); iter++)
651 OutputPyPort *p=(OutputPyPort *)*iter;
652 DEBTRACE( "port name: " << p->getName() );
653 DEBTRACE( "port kind: " << p->edGetType()->kind() );
654 PyObject *ob=PyDict_GetItemString(_context,p->getName().c_str());
657 std::string msg="Error during execution: there is no variable ";
658 msg=msg+p->getName()+" in node context";
660 throw Exception(msg);
662 DEBTRACE( "PyNode::outputs::ob refcnt: " << ob->ob_refcnt );
664 PyObject_Print(ob,stderr,Py_PRINT_RAW);
670 catch(ConversionException& ex)
672 _errorDetails=ex.what();
677 DEBTRACE( "-----------------End PyNode::outputs-----------------" );
679 DEBTRACE( "++++++++++++++ End PyNode::execute: " << getName() << " ++++++++++++++++++++" );
682 void PythonNode::squeezeMemorySafe()
685 if(_mode==PythonNode::REMOTE_NAME)
686 this->squeezeMemoryRemote();
688 this->squeezeMemory();
691 void PythonNode::squeezeMemory()
693 for(auto p : _setOfInputPort)
695 PyDict_DelItemString(_context,p->getName().c_str());
696 InputPyPort *p2(static_cast<InputPyPort *>(p));
697 if(p2->canSafelySqueezeMemory())
700 for(auto p : _setOfOutputPort)
702 PyDict_DelItemString(_context,p->getName().c_str());
703 OutputPyPort *p2(static_cast<OutputPyPort *>(p));
704 p2->putWithoutForward(Py_None);
708 void PythonNode::squeezeMemoryRemote()
710 for(auto p : _setOfInputPort)
712 InputPyPort *p2(static_cast<InputPyPort *>(p));
713 if(p2->canSafelySqueezeMemory())
716 for(auto p : _setOfOutputPort)
718 OutputPyPort *p2(static_cast<OutputPyPort *>(p));
719 p2->putWithoutForward(Py_None);
723 std::string PythonNode::getContainerLog()
725 return PythonEntry::GetContainerLog(_mode,_container,this);
728 void PythonNode::shutdown(int level)
730 DEBTRACE("PythonNode::shutdown " << level);
731 if(_mode=="local")return;
735 _container->shutdown(level);
739 void PythonNode::imposeResource(const std::string& resource_name,
740 const std::string& container_name)
742 if(!resource_name.empty() && !container_name.empty())
744 _imposedResource = resource_name;
745 _imposedContainer = container_name;
749 bool PythonNode::canAcceptImposedResource()
751 return _container != nullptr && _container->canAcceptImposedResource();
754 bool PythonNode::hasImposedResource()const
756 return PythonEntry::hasImposedResource();
759 std::string PythonNode::pythonEntryName()const
761 if(isUsingPythonCache())
762 return "DEFAULT_NAME_FOR_UNIQUE_PYTHON_NODE_ENTRY";
767 bool PythonNode::isUsingPythonCache()const
771 found = _container->isUsingPythonCache();
775 void PythonNode::freeKernelPynode()
777 if(!CORBA::is_nil(_pynode))
781 _pynode->UnRegister();
785 DEBTRACE("Trouble when pynode->UnRegister!")
787 _pynode = Engines::PyScriptNode::_nil();
791 Node *PythonNode::simpleClone(ComposedNode *father, bool editionOnly) const
793 return new PythonNode(*this,father);
796 void PythonNode::createRemoteAdaptedPyInterpretor(Engines::Container_ptr objContainer)
799 _pynode=objContainer->createPyScriptNode(pythonEntryName().c_str(),getScript().c_str());
803 Engines::PyNodeBase_var PythonNode::retrieveDftRemotePyInterpretorIfAny(Engines::Container_ptr objContainer) const
805 Engines::PyScriptNode_var ret(objContainer->getDefaultPyScriptNode(pythonEntryName().c_str()));
806 if(!CORBA::is_nil(ret))
810 return Engines::PyNodeBase::_narrow(ret);
813 void PythonNode::assignRemotePyInterpretor(Engines::PyNodeBase_var remoteInterp)
815 if(CORBA::is_nil(_pynode))
816 _pynode=Engines::PyScriptNode::_narrow(remoteInterp);
819 Engines::PyScriptNode_var tmpp(Engines::PyScriptNode::_narrow(remoteInterp));
820 if(!_pynode->_is_equivalent(tmpp))
823 _pynode=Engines::PyScriptNode::_narrow(remoteInterp);
826 _pynode->assignNewCompiledCode(getScript().c_str());
829 Engines::PyNodeBase_var PythonNode::getRemoteInterpreterHandle()
831 return Engines::PyNodeBase::_narrow(_pynode);
834 //! Create a new node of same type with a given name
835 PythonNode* PythonNode::cloneNode(const std::string& name)
837 PythonNode* n=new PythonNode(name);
838 n->setScript(_script);
839 list<InputPort *>::iterator iter;
840 for(iter = _setOfInputPort.begin(); iter != _setOfInputPort.end(); iter++)
842 InputPyPort *p=(InputPyPort *)*iter;
843 DEBTRACE( "port name: " << p->getName() );
844 DEBTRACE( "port kind: " << p->edGetType()->kind() );
845 n->edAddInputPort(p->getName(),p->edGetType());
847 list<OutputPort *>::iterator iter2;
848 for(iter2 = _setOfOutputPort.begin(); iter2 != _setOfOutputPort.end(); iter2++)
850 OutputPyPort *p=(OutputPyPort *)*iter2;
851 DEBTRACE( "port name: " << p->getName() );
852 DEBTRACE( "port kind: " << p->edGetType()->kind() );
853 n->edAddOutputPort(p->getName(),p->edGetType());
858 void PythonNode::applyDPLScope(ComposedNode *gfn)
860 std::vector< std::pair<std::string,int> > ret(getDPLScopeInfo(gfn));
867 std::size_t sz(ret.size());
869 for(std::size_t i=0;i<sz;i++)
871 const std::pair<std::string,int>& p(ret[i]);
872 PyObject *elt(PyTuple_New(2));
873 PyTuple_SetItem(elt,0,PyUnicode_FromString(p.first.c_str()));
874 PyTuple_SetItem(elt,1,PyLong_FromLong(p.second));
875 PyList_SetItem(ob,i,elt);
878 if(_mode==REMOTE_NAME)
880 Engines::pickledArgs_var serializationInputCorba(new Engines::pickledArgs);
883 PyObject *serializationInput(PyObject_CallFunctionObjArgs(_pyfuncSimpleSer,ob,NULL));
885 char *serializationInputC(0);
887 if (PyBytes_AsStringAndSize(serializationInput, &serializationInputC, &len))
888 throw Exception("DistributedPythonNode problem in python pickle");
889 serializationInputCorba->length(len);
890 for(int i=0; i < len ; i++)
891 serializationInputCorba[i]=serializationInputC[i];
892 Py_XDECREF(serializationInput);
894 _pynode->defineNewCustomVar(DPL_INFO_NAME,serializationInputCorba);
899 PyDict_SetItemString(_context,DPL_INFO_NAME,ob);
904 PyFuncNode::PyFuncNode(const PyFuncNode& other, ComposedNode *father):InlineFuncNode(other,father),_pyfunc(0)
906 _implementation = PythonNode::IMPL_NAME;
909 _context=PyDict_New();
910 DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
911 if( PyDict_SetItemString( _context, "__builtins__", getSALOMERuntime()->getBuiltins() ))
914 msg << "Not possible to set builtins" << __FILE__ << ":" << __LINE__;
915 _errorDetails=msg.str();
916 throw Exception(msg.str());
921 PyFuncNode::PyFuncNode(const std::string& name): InlineFuncNode(name),_pyfunc(0)
924 _implementation = PythonNode::IMPL_NAME;
925 DEBTRACE( "PyFuncNode::PyFuncNode " << name );
928 _context=PyDict_New();
929 DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
930 if( PyDict_SetItemString( _context, "__builtins__", getSALOMERuntime()->getBuiltins() ))
933 msg << "Not possible to set builtins" << __FILE__ << ":" << __LINE__;
934 _errorDetails=msg.str();
935 throw Exception(msg.str());
940 PyFuncNode::~PyFuncNode()
942 if(!CORBA::is_nil(_pynode))
944 _pynode->UnRegister();
948 void PyFuncNode::init(bool start)
950 initCommonPartWithoutStateManagement(start);
951 if(_state == YACS::DISABLED)
953 exDisabledState(); // to refresh propagation of DISABLED state
956 if(start) //complete initialization
957 setState(YACS::READY);
958 else if(_state > YACS::LOADED)// WARNING FuncNode has internal vars (CEA usecase) ! Partial initialization (inside a loop). Exclusivity of funcNode.
959 setState(YACS::TORECONNECT);
962 void PyFuncNode::checkBasicConsistency() const
964 DEBTRACE("checkBasicConsistency");
965 InlineFuncNode::checkBasicConsistency();
969 res=Py_CompileString(_script.c_str(),getName().c_str(),Py_file_input);
972 std::string error="";
973 PyObject* new_stderr = newPyStdOut(error);
974 PySys_SetObject((char*)"stderr", new_stderr);
976 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
977 Py_DECREF(new_stderr);
978 throw Exception(error);
985 void PyFuncNode::load()
987 DEBTRACE( "---------------PyfuncNode::load function---------------" );
988 if(_mode==PythonNode::REMOTE_NAME)
994 void PyFuncNode::loadRemote()
996 commonRemoteLoad(this);
999 void PyFuncNode::loadLocal()
1001 DEBTRACE( "---------------PyFuncNode::load function " << getName() << " ---------------" );
1002 DEBTRACE( _script );
1005 list<OutputPort *>::iterator iter;
1006 for(iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); iter++)
1008 OutputPyPort *p=(OutputPyPort *)*iter;
1009 DEBTRACE( "port name: " << p->getName() );
1010 DEBTRACE( "port kind: " << p->edGetType()->kind() );
1016 DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
1018 std::ostringstream stream;
1019 stream << "/tmp/PythonNode_";
1022 PyObject* code=Py_CompileString(_script.c_str(), stream.str().c_str(), Py_file_input);
1026 PyObject* new_stderr = newPyStdOut(_errorDetails);
1027 PySys_SetObject((char*)"stderr", new_stderr);
1029 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
1030 Py_DECREF(new_stderr);
1031 throw Exception("Error during execution");
1033 PyObject *res = PyEval_EvalCode( code, _context, _context);
1037 DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
1038 if(PyErr_Occurred ())
1041 PyObject* new_stderr = newPyStdOut(_errorDetails);
1042 PySys_SetObject((char*)"stderr", new_stderr);
1043 ofstream errorfile(stream.str().c_str());
1044 if (errorfile.is_open())
1046 errorfile << _script;
1050 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
1051 Py_DECREF(new_stderr);
1052 throw Exception("Error during execution");
1055 _pyfunc=PyDict_GetItemString(_context,_fname.c_str());
1056 DEBTRACE( "_pyfunc refcnt: " << _pyfunc->ob_refcnt );
1060 PyObject* new_stderr = newPyStdOut(_errorDetails);
1061 PySys_SetObject((char*)"stderr", new_stderr);
1063 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
1064 Py_DECREF(new_stderr);
1065 throw Exception("Error during execution");
1067 DEBTRACE( "---------------End PyFuncNode::load function---------------" );
1071 void PyFuncNode::execute()
1073 if(_mode==PythonNode::REMOTE_NAME)
1079 void PyFuncNode::executeRemote()
1081 DEBTRACE( "++++++++++++++ PyFuncNode::executeRemote: " << getName() << " ++++++++++++++++++++" );
1083 throw Exception("DistributedPythonNode badly loaded");
1085 if(dynamic_cast<HomogeneousPoolContainer *>(getContainer()))
1088 loadPythonAdapter(this,dummy);
1089 _pynode->executeAnotherPieceOfCode(getScript().c_str());
1092 Engines::pickledArgs_var serializationInputCorba(new Engines::pickledArgs);;
1096 //===========================================================================
1097 // Get inputs in input ports, build a Python tuple and pickle it
1098 //===========================================================================
1099 PyObject *args(PyTuple_New(getNumberOfInputPorts()));
1101 for(std::list<InputPort *>::iterator iter2 = _setOfInputPort.begin(); iter2 != _setOfInputPort.end(); iter2++,pos++)
1103 InputPyPort *p=(InputPyPort *)*iter2;
1106 PyTuple_SetItem(args,pos,ob);
1109 PyObject_Print(args,stderr,Py_PRINT_RAW);
1112 PyObject *serializationInput=PyObject_CallObject(_pyfuncSer,args);
1114 //The pickled string may contain NULL characters so use PyString_AsStringAndSize
1115 char *serializationInputC(0);
1117 if (PyBytes_AsStringAndSize(serializationInput, &serializationInputC, &len))
1118 throw Exception("DistributedPythonNode problem in python pickle");
1120 serializationInputCorba->length(len);
1121 for(int i=0; i < len ; i++)
1122 serializationInputCorba[i]=serializationInputC[i];
1123 Py_DECREF(serializationInput);
1126 //===========================================================================
1127 // Execute in remote Python node
1128 //===========================================================================
1129 DEBTRACE( "-----------------starting remote python invocation-----------------" );
1130 Engines::pickledArgs_var resultCorba;
1133 resultCorba=_pynode->execute(getFname().c_str(),serializationInputCorba);
1135 catch( const SALOME::SALOME_Exception& ex )
1137 std::string msg="Exception on remote python invocation";
1139 msg += ex.details.text.in();
1141 throw Exception(msg);
1143 DEBTRACE( "-----------------end of remote python invocation-----------------" );
1144 //===========================================================================
1145 // Get results, unpickle and put them in output ports
1146 //===========================================================================
1147 char *resultCorbaC=new char[resultCorba->length()+1];
1148 resultCorbaC[resultCorba->length()]='\0';
1149 for(int i=0;i<resultCorba->length();i++)
1150 resultCorbaC[i]=resultCorba[i];
1155 PyObject *resultPython(PyBytes_FromStringAndSize(resultCorbaC,resultCorba->length()));
1156 delete [] resultCorbaC;
1157 PyObject *args(PyTuple_New(1)),*ob(0);
1158 PyTuple_SetItem(args,0,resultPython);
1159 PyObject *finalResult=PyObject_CallObject(_pyfuncUnser,args);
1162 DEBTRACE( "-----------------PythonNode::outputs-----------------" );
1164 if(finalResult == Py_None)
1166 else if(PyTuple_Check(finalResult))
1167 nres=PyTuple_Size(finalResult);
1169 if(getNumberOfOutputPorts() != nres)
1171 std::string msg="Number of output arguments : Mismatch between definition and execution";
1172 Py_DECREF(finalResult);
1174 throw Exception(msg);
1180 for(std::list<OutputPort *>::iterator iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); iter++, pos++)
1182 OutputPyPort *p=(OutputPyPort *)*iter;
1183 DEBTRACE( "port name: " << p->getName() );
1184 DEBTRACE( "port kind: " << p->edGetType()->kind() );
1185 DEBTRACE( "port pos : " << pos );
1186 if(PyTuple_Check(finalResult))
1187 ob=PyTuple_GetItem(finalResult,pos) ;
1190 DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
1193 Py_DECREF(finalResult);
1195 catch(ConversionException& ex)
1197 Py_DECREF(finalResult);
1198 _errorDetails=ex.what();
1203 DEBTRACE( "++++++++++++++ ENDOF PyFuncNode::executeRemote: " << getName() << " ++++++++++++++++++++" );
1206 void PyFuncNode::executeLocal()
1208 DEBTRACE( "++++++++++++++ PyFuncNode::execute: " << getName() << " ++++++++++++++++++++" );
1212 if(!_pyfunc)throw Exception("PyFuncNode badly loaded");
1215 DEBTRACE( "---------------PyFuncNode::inputs---------------" );
1216 PyObject* args = PyTuple_New(getNumberOfInputPorts()) ;
1217 list<InputPort *>::iterator iter2;
1218 for(iter2 = _setOfInputPort.begin(); iter2 != _setOfInputPort.end(); iter2++)
1220 InputPyPort *p=(InputPyPort *)*iter2;
1221 DEBTRACE( "port name: " << p->getName() );
1222 DEBTRACE( "port kind: " << p->edGetType()->kind() );
1225 PyObject_Print(ob,stderr,Py_PRINT_RAW);
1228 DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
1230 PyTuple_SetItem(args,pos,ob);
1231 DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
1234 DEBTRACE( "---------------End PyFuncNode::inputs---------------" );
1236 DEBTRACE( "----------------PyFuncNode::calculation---------------" );
1238 PyObject_Print(_pyfunc,stderr,Py_PRINT_RAW);
1240 PyObject_Print(args,stderr,Py_PRINT_RAW);
1243 DEBTRACE( "_pyfunc refcnt: " << _pyfunc->ob_refcnt );
1244 PyObject* result = PyObject_CallObject( _pyfunc , args ) ;
1245 DEBTRACE( "_pyfunc refcnt: " << _pyfunc->ob_refcnt );
1252 PyObject* new_stderr = newPyStdOut(_errorDetails);
1253 PySys_SetObject((char*)"stderr", new_stderr);
1254 std::ostringstream stream;
1255 stream << "/tmp/PythonNode_";
1257 ofstream errorfile(stream.str().c_str());
1258 if (errorfile.is_open())
1260 errorfile << _script;
1264 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
1265 Py_DECREF(new_stderr);
1266 throw Exception("Error during execution");
1268 DEBTRACE( "----------------End PyFuncNode::calculation---------------" );
1270 DEBTRACE( "-----------------PyFuncNode::outputs-----------------" );
1272 if(result == Py_None)
1274 else if(PyTuple_Check(result))
1275 nres=PyTuple_Size(result);
1277 if(getNumberOfOutputPorts() != nres)
1279 std::string msg="Number of output arguments : Mismatch between definition and execution";
1282 throw Exception(msg);
1287 PyObject_Print(result,stderr,Py_PRINT_RAW);
1290 list<OutputPort *>::iterator iter;
1293 for(iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); iter++)
1295 OutputPyPort *p=(OutputPyPort *)*iter;
1296 DEBTRACE( "port name: " << p->getName() );
1297 DEBTRACE( "port kind: " << p->edGetType()->kind() );
1298 DEBTRACE( "port pos : " << pos );
1299 if(PyTuple_Check(result))ob=PyTuple_GetItem(result,pos) ;
1301 DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
1303 PyObject_Print(ob,stderr,Py_PRINT_RAW);
1310 catch(ConversionException& ex)
1313 _errorDetails=ex.what();
1316 DEBTRACE( "-----------------End PyFuncNode::outputs-----------------" );
1319 DEBTRACE( "++++++++++++++ End PyFuncNode::execute: " << getName() << " ++++++++++++++++++++" );
1322 Node *PyFuncNode::simpleClone(ComposedNode *father, bool editionOnly) const
1324 return new PyFuncNode(*this,father);
1327 void PyFuncNode::createRemoteAdaptedPyInterpretor(Engines::Container_ptr objContainer)
1329 if(!CORBA::is_nil(_pynode))
1330 _pynode->UnRegister();
1331 _pynode=objContainer->createPyNode(getName().c_str(),getScript().c_str());
1334 Engines::PyNodeBase_var PyFuncNode::retrieveDftRemotePyInterpretorIfAny(Engines::Container_ptr objContainer) const
1336 Engines::PyNode_var ret(objContainer->getDefaultPyNode(getName().c_str()));
1337 if(!CORBA::is_nil(ret))
1341 return Engines::PyNodeBase::_narrow(ret);
1344 void PyFuncNode::assignRemotePyInterpretor(Engines::PyNodeBase_var remoteInterp)
1346 if(!CORBA::is_nil(_pynode))
1348 Engines::PyNode_var tmpp(Engines::PyNode::_narrow(remoteInterp));
1349 if(_pynode->_is_equivalent(tmpp))
1352 if(!CORBA::is_nil(_pynode))
1353 _pynode->UnRegister();
1354 _pynode=Engines::PyNode::_narrow(remoteInterp);
1357 Engines::PyNodeBase_var PyFuncNode::getRemoteInterpreterHandle()
1359 return Engines::PyNodeBase::_narrow(_pynode);
1362 //! Create a new node of same type with a given name
1363 PyFuncNode* PyFuncNode::cloneNode(const std::string& name)
1365 PyFuncNode* n=new PyFuncNode(name);
1366 n->setScript(_script);
1367 n->setFname(_fname);
1368 list<InputPort *>::iterator iter;
1369 for(iter = _setOfInputPort.begin(); iter != _setOfInputPort.end(); iter++)
1371 InputPyPort *p=(InputPyPort *)*iter;
1372 n->edAddInputPort(p->getName(),p->edGetType());
1374 list<OutputPort *>::iterator iter2;
1375 for(iter2 = _setOfOutputPort.begin(); iter2 != _setOfOutputPort.end(); iter2++)
1377 OutputPyPort *p=(OutputPyPort *)*iter2;
1378 n->edAddOutputPort(p->getName(),p->edGetType());
1383 std::string PyFuncNode::getContainerLog()
1385 return PythonEntry::GetContainerLog(_mode,_container,this);
1388 void PyFuncNode::shutdown(int level)
1390 DEBTRACE("PyFuncNode::shutdown " << level);
1391 if(_mode=="local")return;
1394 if(!CORBA::is_nil(_pynode)) _pynode->UnRegister();
1395 _pynode=Engines::PyNode::_nil();
1396 _container->shutdown(level);
1400 void PyFuncNode::imposeResource(const std::string& resource_name,
1401 const std::string& container_name)
1403 if(!resource_name.empty() && !container_name.empty())
1405 _imposedResource = resource_name;
1406 _imposedContainer = container_name;
1410 bool PyFuncNode::canAcceptImposedResource()
1412 return _container != nullptr && _container->canAcceptImposedResource();
1415 bool PyFuncNode::hasImposedResource()const
1417 return PythonEntry::hasImposedResource();