1 // Copyright (C) 2006-2016 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"
38 #define getpid _getpid
41 #if PY_VERSION_HEX < 0x02050000
42 typedef int Py_ssize_t;
46 #include "YacsTrace.hxx"
48 using namespace YACS::ENGINE;
51 const char PythonEntry::SCRIPT_FOR_SIMPLE_SERIALIZATION[]="import pickle\n"
52 "def pickleForVarSimplePyth2009(val):\n"
53 " return pickle.dumps(val,-1)\n"
56 const char PythonNode::IMPL_NAME[]="Python";
57 const char PythonNode::KIND[]="Python";
59 const char PythonNode::SCRIPT_FOR_SERIALIZATION[]="import pickle\n"
60 "def pickleForDistPyth2009(kws):\n"
61 " return pickle.dumps(((),kws),-1)\n"
63 "def unPickleForDistPyth2009(st):\n"
64 " args=pickle.loads(st)\n"
67 const char PythonNode::REMOTE_NAME[]="remote";
69 const char PythonNode::DPL_INFO_NAME[]="my_dpl_localization";
71 const char PyFuncNode::SCRIPT_FOR_SERIALIZATION[]="import pickle\n"
72 "def pickleForDistPyth2009(*args,**kws):\n"
73 " return pickle.dumps((args,kws),-1)\n"
75 "def unPickleForDistPyth2009(st):\n"
76 " 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::commonRemoteLoadPart1(InlineNode *reqNode)
95 DEBTRACE( "---------------PythonEntry::CommonRemoteLoad function---------------" );
96 Container *container(reqNode->getContainer());
97 bool isContAlreadyStarted(false);
100 isContAlreadyStarted=container->isAlreadyStarted(reqNode);
101 if(!isContAlreadyStarted)
105 container->start(reqNode);
109 reqNode->setErrorDetails(e.what());
116 std::string what("PythonEntry::CommonRemoteLoad : a load operation requested on \"");
117 what+=reqNode->getName(); what+="\" with no container specified.";
118 reqNode->setErrorDetails(what);
119 throw Exception(what);
123 Engines::Container_var PythonEntry::commonRemoteLoadPart2(InlineNode *reqNode, bool& isInitializeRequested)
125 Container *container(reqNode->getContainer());
126 Engines::Container_var objContainer=Engines::Container::_nil();
128 throw Exception("No container specified !");
129 SalomeContainer *containerCast0(dynamic_cast<SalomeContainer *>(container));
130 SalomeHPContainerBase *containerCast1(dynamic_cast<SalomeHPContainerBase *>(container));
132 objContainer=containerCast0->getContainerPtr(reqNode);
133 else if(containerCast1)
135 objContainer=containerCast1->getContainerPtr(reqNode);
138 throw Exception("Unrecognized type of container ! Salome one is expected for PythonNode/PyFuncNode !");
139 if(CORBA::is_nil(objContainer))
140 throw Exception("Container corba pointer is NULL for PythonNode !");
141 isInitializeRequested=false;
146 createRemoteAdaptedPyInterpretor(objContainer);
150 Engines::PyNodeBase_var dftPyScript(retrieveDftRemotePyInterpretorIfAny(objContainer));
151 if(CORBA::is_nil(dftPyScript))
153 isInitializeRequested=true;
154 createRemoteAdaptedPyInterpretor(objContainer);
157 assignRemotePyInterpretor(dftPyScript);
160 catch( const SALOME::SALOME_Exception& ex )
162 std::string msg="Exception on remote python node creation ";
164 msg += ex.details.text.in();
165 reqNode->setErrorDetails(msg);
166 throw Exception(msg);
168 Engines::PyNodeBase_var pynode(getRemoteInterpreterHandle());
169 if(CORBA::is_nil(pynode))
170 throw Exception("In PythonNode the ref in NULL ! ");
174 void PythonEntry::commonRemoteLoadPart3(InlineNode *reqNode, Engines::Container_ptr objContainer, bool isInitializeRequested)
176 Container *container(reqNode->getContainer());
177 Engines::PyNodeBase_var pynode(getRemoteInterpreterHandle());
181 const char *picklizeScript(getSerializationScript());
182 PyObject *res=PyRun_String(picklizeScript,Py_file_input,_context,_context);
183 PyObject *res2(PyRun_String(SCRIPT_FOR_SIMPLE_SERIALIZATION,Py_file_input,_context,_context));
184 if(res == NULL || res2==NULL)
186 std::string errorDetails;
187 PyObject* new_stderr = newPyStdOut(errorDetails);
188 reqNode->setErrorDetails(errorDetails);
189 PySys_SetObject((char*)"stderr", new_stderr);
191 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
192 Py_DECREF(new_stderr);
193 throw Exception("Error during load");
195 Py_DECREF(res); Py_DECREF(res2);
196 _pyfuncSer=PyDict_GetItemString(_context,"pickleForDistPyth2009");
197 _pyfuncUnser=PyDict_GetItemString(_context,"unPickleForDistPyth2009");
198 _pyfuncSimpleSer=PyDict_GetItemString(_context,"pickleForVarSimplePyth2009");
199 if(_pyfuncSer == NULL)
201 std::string errorDetails;
202 PyObject *new_stderr(newPyStdOut(errorDetails));
203 reqNode->setErrorDetails(errorDetails);
204 PySys_SetObject((char*)"stderr", new_stderr);
206 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
207 Py_DECREF(new_stderr);
208 throw Exception("Error during load");
210 if(_pyfuncUnser == NULL)
212 std::string errorDetails;
213 PyObject *new_stderr(newPyStdOut(errorDetails));
214 reqNode->setErrorDetails(errorDetails);
215 PySys_SetObject((char*)"stderr", new_stderr);
217 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
218 Py_DECREF(new_stderr);
219 throw Exception("Error during load");
221 if(_pyfuncSimpleSer == NULL)
223 std::string errorDetails;
224 PyObject *new_stderr(newPyStdOut(errorDetails));
225 reqNode->setErrorDetails(errorDetails);
226 PySys_SetObject((char*)"stderr", new_stderr);
228 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
229 Py_DECREF(new_stderr);
230 throw Exception("Error during load");
233 if(isInitializeRequested)
234 {//This one is called only once at initialization in the container if an init-script is specified.
237 std::string zeInitScriptKey(container->getProperty(HomogeneousPoolContainer::INITIALIZE_SCRIPT_KEY));
238 if(!zeInitScriptKey.empty())
239 pynode->executeAnotherPieceOfCode(zeInitScriptKey.c_str());
241 catch( const SALOME::SALOME_Exception& ex )
243 std::string msg="Exception on PythonNode::loadRemote python invocation of initializisation py script !";
245 msg += ex.details.text.in();
246 reqNode->setErrorDetails(msg);
247 throw Exception(msg);
249 DEBTRACE( "---------------End PyNode::loadRemote function---------------" );
253 std::string PythonEntry::GetContainerLog(const std::string& mode, Container *container, const Task *askingTask)
261 SalomeContainer *containerCast(dynamic_cast<SalomeContainer *>(container));
262 SalomeHPContainer *objContainer2(dynamic_cast<SalomeHPContainer *>(container));
265 Engines::Container_var objContainer(containerCast->getContainerPtr(askingTask));
266 CORBA::String_var logname = objContainer->logfilename();
269 std::string::size_type pos = msg.find(":");
270 msg=msg.substr(pos+1);
272 else if(objContainer2)
274 msg="Remote PythonNode is on HP Container : no log because no info of the location by definition of HP Container !";
278 msg="Not implemented yet for container log for that type of container !";
283 msg = "Container no longer reachable";
288 void PythonEntry::commonRemoteLoad(InlineNode *reqNode)
290 commonRemoteLoadPart1(reqNode);
291 bool isInitializeRequested;
292 Engines::Container_var objContainer(commonRemoteLoadPart2(reqNode,isInitializeRequested));
293 commonRemoteLoadPart3(reqNode,objContainer,isInitializeRequested);
296 PythonNode::PythonNode(const PythonNode& other, ComposedNode *father):InlineNode(other,father)
298 _implementation=IMPL_NAME;
301 _context=PyDict_New();
302 if( PyDict_SetItemString( _context, "__builtins__", getSALOMERuntime()->getBuiltins() ))
305 msg << "Impossible to set builtins" << __FILE__ << ":" << __LINE__;
306 _errorDetails=msg.str();
307 throw Exception(msg.str());
312 PythonNode::PythonNode(const std::string& name):InlineNode(name)
314 _implementation=IMPL_NAME;
317 _context=PyDict_New();
318 if( PyDict_SetItemString( _context, "__builtins__", getSALOMERuntime()->getBuiltins() ))
321 msg << "Impossible to set builtins" << __FILE__ << ":" << __LINE__;
322 _errorDetails=msg.str();
323 throw Exception(msg.str());
328 PythonNode::~PythonNode()
330 if(!CORBA::is_nil(_pynode))
332 _pynode->UnRegister();
336 void PythonNode::checkBasicConsistency() const throw(YACS::Exception)
338 DEBTRACE("checkBasicConsistency");
339 InlineNode::checkBasicConsistency();
343 res=Py_CompileString(_script.c_str(),getName().c_str(),Py_file_input);
346 std::string error="";
347 PyObject* new_stderr = newPyStdOut(error);
348 PySys_SetObject((char*)"stderr", new_stderr);
350 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
351 Py_DECREF(new_stderr);
352 throw Exception(error);
359 void PythonNode::load()
361 DEBTRACE( "---------------PyNode::load function---------------" );
362 if(_mode==PythonNode::REMOTE_NAME)
368 void PythonNode::loadLocal()
370 DEBTRACE( "---------------PyNode::loadLocal function---------------" );
374 void PythonNode::loadRemote()
376 commonRemoteLoad(this);
379 void PythonNode::execute()
381 if(_mode==PythonNode::REMOTE_NAME)
387 void PythonNode::executeRemote()
389 DEBTRACE( "++++++++++++++ PyNode::executeRemote: " << getName() << " ++++++++++++++++++++" );
391 throw Exception("DistributedPythonNode badly loaded");
393 if(dynamic_cast<HomogeneousPoolContainer *>(getContainer()))
396 commonRemoteLoadPart2(this,dummy);
397 _pynode->assignNewCompiledCode(getScript().c_str());
400 Engines::pickledArgs_var serializationInputCorba(new Engines::pickledArgs);
403 PyObject *args(0),*ob(0);
404 //===========================================================================
405 // Get inputs in input ports, build a Python dict and pickle it
406 //===========================================================================
408 std::list<InputPort *>::iterator iter2;
410 for(iter2 = _setOfInputPort.begin(); iter2 != _setOfInputPort.end(); ++iter2)
412 InputPyPort *p=(InputPyPort *)*iter2;
414 PyDict_SetItemString(args,p->getName().c_str(),ob);
418 PyObject_Print(args,stderr,Py_PRINT_RAW);
421 PyObject *serializationInput(PyObject_CallFunctionObjArgs(_pyfuncSer,args,NULL));
423 //The pickled string may contain NULL characters so use PyString_AsStringAndSize
424 char *serializationInputC(0);
426 if (PyBytes_AsStringAndSize(serializationInput, &serializationInputC, &len))
427 throw Exception("DistributedPythonNode problem in python pickle");
428 serializationInputCorba->length(len);
429 for(int i=0; i < len ; i++)
430 serializationInputCorba[i]=serializationInputC[i];
431 Py_DECREF(serializationInput);
434 //get the list of output argument names
435 std::list<OutputPort *>::iterator iter;
436 Engines::listofstring myseq;
437 myseq.length(getNumberOfOutputPorts());
439 for(iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); ++iter)
441 OutputPyPort *p=(OutputPyPort *)*iter;
442 myseq[pos]=p->getName().c_str();
443 DEBTRACE( "port name: " << p->getName() );
444 DEBTRACE( "port kind: " << p->edGetType()->kind() );
445 DEBTRACE( "port pos : " << pos );
448 //===========================================================================
449 // Execute in remote Python node
450 //===========================================================================
451 DEBTRACE( "-----------------starting remote python invocation-----------------" );
452 Engines::pickledArgs_var resultCorba;
455 //pass outargsname and dict serialized
456 resultCorba=_pynode->execute(myseq,serializationInputCorba);
458 catch( const SALOME::SALOME_Exception& ex )
460 std::string msg="Exception on remote python invocation";
462 msg += ex.details.text.in();
464 throw Exception(msg);
466 DEBTRACE( "-----------------end of remote python invocation-----------------" );
467 //===========================================================================
468 // Get results, unpickle and put them in output ports
469 //===========================================================================
470 char *resultCorbaC=new char[resultCorba->length()+1];
471 resultCorbaC[resultCorba->length()]='\0';
472 for(int i=0;i<resultCorba->length();i++)
473 resultCorbaC[i]=resultCorba[i];
477 PyObject *args(0),*ob(0);
478 PyObject* resultPython=PyBytes_FromStringAndSize(resultCorbaC,resultCorba->length());
479 delete [] resultCorbaC;
480 args = PyTuple_New(1);
481 PyTuple_SetItem(args,0,resultPython);
482 PyObject *finalResult=PyObject_CallObject(_pyfuncUnser,args);
485 if (finalResult == NULL)
487 std::stringstream msg;
488 msg << "Conversion with pickle of output ports failed !";
489 msg << " : " << __FILE__ << ":" << __LINE__;
490 _errorDetails=msg.str();
491 throw YACS::ENGINE::ConversionException(msg.str());
494 DEBTRACE( "-----------------PythonNode::outputs-----------------" );
496 if(finalResult == Py_None)
498 else if(PyTuple_Check(finalResult))
499 nres=PyTuple_Size(finalResult);
501 if(getNumberOfOutputPorts() != nres)
503 std::string msg="Number of output arguments : Mismatch between definition and execution";
504 Py_DECREF(finalResult);
506 throw Exception(msg);
512 for(iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); ++iter)
514 OutputPyPort *p=(OutputPyPort *)*iter;
515 DEBTRACE( "port name: " << p->getName() );
516 DEBTRACE( "port kind: " << p->edGetType()->kind() );
517 DEBTRACE( "port pos : " << pos );
518 if(PyTuple_Check(finalResult))
519 ob=PyTuple_GetItem(finalResult,pos) ;
522 DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
526 Py_DECREF(finalResult);
528 catch(ConversionException& ex)
530 Py_DECREF(finalResult);
531 _errorDetails=ex.what();
535 DEBTRACE( "++++++++++++++ ENDOF PyNode::executeRemote: " << getName() << " ++++++++++++++++++++" );
538 void PythonNode::executeLocal()
540 DEBTRACE( "++++++++++++++ PyNode::executeLocal: " << getName() << " ++++++++++++++++++++" );
544 DEBTRACE( "---------------PyNode::inputs---------------" );
545 list<InputPort *>::iterator iter2;
546 for(iter2 = _setOfInputPort.begin(); iter2 != _setOfInputPort.end(); iter2++)
548 InputPyPort *p=(InputPyPort *)*iter2;
549 DEBTRACE( "port name: " << p->getName() );
550 DEBTRACE( "port kind: " << p->edGetType()->kind() );
551 PyObject* ob=p->getPyObj();
552 DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
554 PyObject_Print(ob,stderr,Py_PRINT_RAW);
557 int ier=PyDict_SetItemString(_context,p->getName().c_str(),ob);
558 DEBTRACE( "after PyDict_SetItemString:ob refcnt: " << ob->ob_refcnt );
561 DEBTRACE( "---------------End PyNode::inputs---------------" );
564 DEBTRACE( "----------------PyNode::calculation---------------" );
566 DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
568 std::ostringstream stream;
569 stream << "/tmp/PythonNode_";
572 PyObject* code=Py_CompileString(_script.c_str(), stream.str().c_str(), Py_file_input);
576 PyObject* new_stderr = newPyStdOut(_errorDetails);
577 PySys_SetObject((char*)"stderr", new_stderr);
579 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
580 Py_DECREF(new_stderr);
581 throw Exception("Error during execution");
583 PyObject *res = PyEval_EvalCode( code, _context, _context);
587 DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
590 if(PyErr_Occurred ())
593 PyObject* new_stderr = newPyStdOut(_errorDetails);
594 PySys_SetObject((char*)"stderr", new_stderr);
595 ofstream errorfile(stream.str().c_str());
596 if (errorfile.is_open())
598 errorfile << _script;
602 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
603 Py_DECREF(new_stderr);
604 throw Exception("Error during execution");
607 DEBTRACE( "-----------------PyNode::outputs-----------------" );
608 list<OutputPort *>::iterator iter;
611 for(iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); iter++)
613 OutputPyPort *p=(OutputPyPort *)*iter;
614 DEBTRACE( "port name: " << p->getName() );
615 DEBTRACE( "port kind: " << p->edGetType()->kind() );
616 PyObject *ob=PyDict_GetItemString(_context,p->getName().c_str());
619 std::string msg="Error during execution: there is no variable ";
620 msg=msg+p->getName()+" in node context";
622 throw Exception(msg);
624 DEBTRACE( "PyNode::outputs::ob refcnt: " << ob->ob_refcnt );
626 PyObject_Print(ob,stderr,Py_PRINT_RAW);
632 catch(ConversionException& ex)
634 _errorDetails=ex.what();
638 DEBTRACE( "-----------------End PyNode::outputs-----------------" );
640 DEBTRACE( "++++++++++++++ End PyNode::execute: " << getName() << " ++++++++++++++++++++" );
643 std::string PythonNode::getContainerLog()
645 return PythonEntry::GetContainerLog(_mode,_container,this);
648 void PythonNode::shutdown(int level)
650 DEBTRACE("PythonNode::shutdown " << level);
651 if(_mode=="local")return;
654 if(!CORBA::is_nil(_pynode)) _pynode->UnRegister();
655 _pynode=Engines::PyScriptNode::_nil();
656 _container->shutdown(level);
660 Node *PythonNode::simpleClone(ComposedNode *father, bool editionOnly) const
662 return new PythonNode(*this,father);
665 void PythonNode::createRemoteAdaptedPyInterpretor(Engines::Container_ptr objContainer)
667 if(!CORBA::is_nil(_pynode))
668 _pynode->UnRegister();
669 _pynode=objContainer->createPyScriptNode(getName().c_str(),getScript().c_str());
672 Engines::PyNodeBase_var PythonNode::retrieveDftRemotePyInterpretorIfAny(Engines::Container_ptr objContainer) const
674 Engines::PyScriptNode_var ret(objContainer->getDefaultPyScriptNode(getName().c_str()));
675 if(!CORBA::is_nil(ret))
679 return Engines::PyNodeBase::_narrow(ret);
682 void PythonNode::assignRemotePyInterpretor(Engines::PyNodeBase_var remoteInterp)
684 if(!CORBA::is_nil(_pynode))
686 Engines::PyScriptNode_var tmpp(Engines::PyScriptNode::_narrow(remoteInterp));
687 if(_pynode->_is_equivalent(tmpp))
690 if(!CORBA::is_nil(_pynode))
691 _pynode->UnRegister();
692 _pynode=Engines::PyScriptNode::_narrow(remoteInterp);
695 Engines::PyNodeBase_var PythonNode::getRemoteInterpreterHandle()
697 return Engines::PyNodeBase::_narrow(_pynode);
700 //! Create a new node of same type with a given name
701 PythonNode* PythonNode::cloneNode(const std::string& name)
703 PythonNode* n=new PythonNode(name);
704 n->setScript(_script);
705 list<InputPort *>::iterator iter;
706 for(iter = _setOfInputPort.begin(); iter != _setOfInputPort.end(); iter++)
708 InputPyPort *p=(InputPyPort *)*iter;
709 DEBTRACE( "port name: " << p->getName() );
710 DEBTRACE( "port kind: " << p->edGetType()->kind() );
711 n->edAddInputPort(p->getName(),p->edGetType());
713 list<OutputPort *>::iterator iter2;
714 for(iter2 = _setOfOutputPort.begin(); iter2 != _setOfOutputPort.end(); iter2++)
716 OutputPyPort *p=(OutputPyPort *)*iter2;
717 DEBTRACE( "port name: " << p->getName() );
718 DEBTRACE( "port kind: " << p->edGetType()->kind() );
719 n->edAddOutputPort(p->getName(),p->edGetType());
724 void PythonNode::applyDPLScope(ComposedNode *gfn)
726 std::vector< std::pair<std::string,int> > ret(getDPLScopeInfo(gfn));
733 std::size_t sz(ret.size());
735 for(std::size_t i=0;i<sz;i++)
737 const std::pair<std::string,int>& p(ret[i]);
738 PyObject *elt(PyTuple_New(2));
739 PyTuple_SetItem(elt,0,PyUnicode_FromString(p.first.c_str()));
740 PyTuple_SetItem(elt,1,PyLong_FromLong(p.second));
741 PyList_SetItem(ob,i,elt);
744 if(_mode==REMOTE_NAME)
746 Engines::pickledArgs_var serializationInputCorba(new Engines::pickledArgs);
749 PyObject *serializationInput(PyObject_CallFunctionObjArgs(_pyfuncSimpleSer,ob,NULL));
751 char *serializationInputC(0);
753 if (PyBytes_AsStringAndSize(serializationInput, &serializationInputC, &len))
754 throw Exception("DistributedPythonNode problem in python pickle");
755 serializationInputCorba->length(len);
756 for(int i=0; i < len ; i++)
757 serializationInputCorba[i]=serializationInputC[i];
758 Py_XDECREF(serializationInput);
760 _pynode->defineNewCustomVar(DPL_INFO_NAME,serializationInputCorba);
765 PyDict_SetItemString(_context,DPL_INFO_NAME,ob);
770 PyFuncNode::PyFuncNode(const PyFuncNode& other, ComposedNode *father):InlineFuncNode(other,father),_pyfunc(0)
772 _implementation = PythonNode::IMPL_NAME;
775 _context=PyDict_New();
776 DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
777 if( PyDict_SetItemString( _context, "__builtins__", getSALOMERuntime()->getBuiltins() ))
780 msg << "Not possible to set builtins" << __FILE__ << ":" << __LINE__;
781 _errorDetails=msg.str();
782 throw Exception(msg.str());
787 PyFuncNode::PyFuncNode(const std::string& name): InlineFuncNode(name),_pyfunc(0)
790 _implementation = PythonNode::IMPL_NAME;
791 DEBTRACE( "PyFuncNode::PyFuncNode " << name );
794 _context=PyDict_New();
795 DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
796 if( PyDict_SetItemString( _context, "__builtins__", getSALOMERuntime()->getBuiltins() ))
799 msg << "Not possible to set builtins" << __FILE__ << ":" << __LINE__;
800 _errorDetails=msg.str();
801 throw Exception(msg.str());
806 PyFuncNode::~PyFuncNode()
808 if(!CORBA::is_nil(_pynode))
810 _pynode->UnRegister();
814 void PyFuncNode::init(bool start)
816 initCommonPartWithoutStateManagement(start);
817 if(_state == YACS::DISABLED)
819 exDisabledState(); // to refresh propagation of DISABLED state
822 if(start) //complete initialization
823 setState(YACS::READY);
824 else if(_state > YACS::LOADED)// WARNING FuncNode has internal vars (CEA usecase) ! Partial initialization (inside a loop). Exclusivity of funcNode.
825 setState(YACS::TORECONNECT);
828 void PyFuncNode::checkBasicConsistency() const throw(YACS::Exception)
830 DEBTRACE("checkBasicConsistency");
831 InlineFuncNode::checkBasicConsistency();
835 res=Py_CompileString(_script.c_str(),getName().c_str(),Py_file_input);
838 std::string error="";
839 PyObject* new_stderr = newPyStdOut(error);
840 PySys_SetObject((char*)"stderr", new_stderr);
842 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
843 Py_DECREF(new_stderr);
844 throw Exception(error);
851 void PyFuncNode::load()
853 DEBTRACE( "---------------PyfuncNode::load function---------------" );
854 if(_mode==PythonNode::REMOTE_NAME)
860 void PyFuncNode::loadRemote()
862 commonRemoteLoad(this);
865 void PyFuncNode::loadLocal()
867 DEBTRACE( "---------------PyFuncNode::load function " << getName() << " ---------------" );
871 list<OutputPort *>::iterator iter;
872 for(iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); iter++)
874 OutputPyPort *p=(OutputPyPort *)*iter;
875 DEBTRACE( "port name: " << p->getName() );
876 DEBTRACE( "port kind: " << p->edGetType()->kind() );
882 DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
884 std::ostringstream stream;
885 stream << "/tmp/PythonNode_";
888 PyObject* code=Py_CompileString(_script.c_str(), stream.str().c_str(), Py_file_input);
892 PyObject* new_stderr = newPyStdOut(_errorDetails);
893 PySys_SetObject((char*)"stderr", new_stderr);
895 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
896 Py_DECREF(new_stderr);
897 throw Exception("Error during execution");
899 PyObject *res = PyEval_EvalCode( code, _context, _context);
903 DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
904 if(PyErr_Occurred ())
907 PyObject* new_stderr = newPyStdOut(_errorDetails);
908 PySys_SetObject((char*)"stderr", new_stderr);
909 ofstream errorfile(stream.str().c_str());
910 if (errorfile.is_open())
912 errorfile << _script;
916 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
917 Py_DECREF(new_stderr);
918 throw Exception("Error during execution");
921 _pyfunc=PyDict_GetItemString(_context,_fname.c_str());
922 DEBTRACE( "_pyfunc refcnt: " << _pyfunc->ob_refcnt );
926 PyObject* new_stderr = newPyStdOut(_errorDetails);
927 PySys_SetObject((char*)"stderr", new_stderr);
929 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
930 Py_DECREF(new_stderr);
931 throw Exception("Error during execution");
933 DEBTRACE( "---------------End PyFuncNode::load function---------------" );
937 void PyFuncNode::execute()
939 if(_mode==PythonNode::REMOTE_NAME)
945 void PyFuncNode::executeRemote()
947 DEBTRACE( "++++++++++++++ PyFuncNode::executeRemote: " << getName() << " ++++++++++++++++++++" );
949 throw Exception("DistributedPythonNode badly loaded");
951 if(dynamic_cast<HomogeneousPoolContainer *>(getContainer()))
954 commonRemoteLoadPart2(this,dummy);
955 _pynode->executeAnotherPieceOfCode(getScript().c_str());
958 Engines::pickledArgs_var serializationInputCorba(new Engines::pickledArgs);;
962 //===========================================================================
963 // Get inputs in input ports, build a Python tuple and pickle it
964 //===========================================================================
965 PyObject *args(PyTuple_New(getNumberOfInputPorts()));
967 for(std::list<InputPort *>::iterator iter2 = _setOfInputPort.begin(); iter2 != _setOfInputPort.end(); iter2++,pos++)
969 InputPyPort *p=(InputPyPort *)*iter2;
972 PyTuple_SetItem(args,pos,ob);
975 PyObject_Print(args,stderr,Py_PRINT_RAW);
978 PyObject *serializationInput=PyObject_CallObject(_pyfuncSer,args);
980 //The pickled string may contain NULL characters so use PyString_AsStringAndSize
981 char *serializationInputC(0);
983 if (PyBytes_AsStringAndSize(serializationInput, &serializationInputC, &len))
984 throw Exception("DistributedPythonNode problem in python pickle");
986 serializationInputCorba->length(len);
987 for(int i=0; i < len ; i++)
988 serializationInputCorba[i]=serializationInputC[i];
989 Py_DECREF(serializationInput);
992 //===========================================================================
993 // Execute in remote Python node
994 //===========================================================================
995 DEBTRACE( "-----------------starting remote python invocation-----------------" );
996 Engines::pickledArgs_var resultCorba;
999 resultCorba=_pynode->execute(getFname().c_str(),serializationInputCorba);
1001 catch( const SALOME::SALOME_Exception& ex )
1003 std::string msg="Exception on remote python invocation";
1005 msg += ex.details.text.in();
1007 throw Exception(msg);
1009 DEBTRACE( "-----------------end of remote python invocation-----------------" );
1010 //===========================================================================
1011 // Get results, unpickle and put them in output ports
1012 //===========================================================================
1013 char *resultCorbaC=new char[resultCorba->length()+1];
1014 resultCorbaC[resultCorba->length()]='\0';
1015 for(int i=0;i<resultCorba->length();i++)
1016 resultCorbaC[i]=resultCorba[i];
1021 PyObject *resultPython(PyBytes_FromStringAndSize(resultCorbaC,resultCorba->length()));
1022 delete [] resultCorbaC;
1023 PyObject *args(PyTuple_New(1)),*ob(0);
1024 PyTuple_SetItem(args,0,resultPython);
1025 PyObject *finalResult=PyObject_CallObject(_pyfuncUnser,args);
1028 DEBTRACE( "-----------------PythonNode::outputs-----------------" );
1030 if(finalResult == Py_None)
1032 else if(PyTuple_Check(finalResult))
1033 nres=PyTuple_Size(finalResult);
1035 if(getNumberOfOutputPorts() != nres)
1037 std::string msg="Number of output arguments : Mismatch between definition and execution";
1038 Py_DECREF(finalResult);
1040 throw Exception(msg);
1046 for(std::list<OutputPort *>::iterator iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); iter++, pos++)
1048 OutputPyPort *p=(OutputPyPort *)*iter;
1049 DEBTRACE( "port name: " << p->getName() );
1050 DEBTRACE( "port kind: " << p->edGetType()->kind() );
1051 DEBTRACE( "port pos : " << pos );
1052 if(PyTuple_Check(finalResult))
1053 ob=PyTuple_GetItem(finalResult,pos) ;
1056 DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
1059 Py_DECREF(finalResult);
1061 catch(ConversionException& ex)
1063 Py_DECREF(finalResult);
1064 _errorDetails=ex.what();
1069 DEBTRACE( "++++++++++++++ ENDOF PyFuncNode::executeRemote: " << getName() << " ++++++++++++++++++++" );
1072 void PyFuncNode::executeLocal()
1074 DEBTRACE( "++++++++++++++ PyFuncNode::execute: " << getName() << " ++++++++++++++++++++" );
1078 if(!_pyfunc)throw Exception("PyFuncNode badly loaded");
1081 DEBTRACE( "---------------PyFuncNode::inputs---------------" );
1082 PyObject* args = PyTuple_New(getNumberOfInputPorts()) ;
1083 list<InputPort *>::iterator iter2;
1084 for(iter2 = _setOfInputPort.begin(); iter2 != _setOfInputPort.end(); iter2++)
1086 InputPyPort *p=(InputPyPort *)*iter2;
1087 DEBTRACE( "port name: " << p->getName() );
1088 DEBTRACE( "port kind: " << p->edGetType()->kind() );
1091 PyObject_Print(ob,stderr,Py_PRINT_RAW);
1094 DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
1096 PyTuple_SetItem(args,pos,ob);
1097 DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
1100 DEBTRACE( "---------------End PyFuncNode::inputs---------------" );
1102 DEBTRACE( "----------------PyFuncNode::calculation---------------" );
1104 PyObject_Print(_pyfunc,stderr,Py_PRINT_RAW);
1106 PyObject_Print(args,stderr,Py_PRINT_RAW);
1109 DEBTRACE( "_pyfunc refcnt: " << _pyfunc->ob_refcnt );
1110 PyObject* result = PyObject_CallObject( _pyfunc , args ) ;
1111 DEBTRACE( "_pyfunc refcnt: " << _pyfunc->ob_refcnt );
1118 PyObject* new_stderr = newPyStdOut(_errorDetails);
1119 PySys_SetObject((char*)"stderr", new_stderr);
1120 std::ostringstream stream;
1121 stream << "/tmp/PythonNode_";
1123 ofstream errorfile(stream.str().c_str());
1124 if (errorfile.is_open())
1126 errorfile << _script;
1130 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
1131 Py_DECREF(new_stderr);
1132 throw Exception("Error during execution");
1134 DEBTRACE( "----------------End PyFuncNode::calculation---------------" );
1136 DEBTRACE( "-----------------PyFuncNode::outputs-----------------" );
1138 if(result == Py_None)
1140 else if(PyTuple_Check(result))
1141 nres=PyTuple_Size(result);
1143 if(getNumberOfOutputPorts() != nres)
1145 std::string msg="Number of output arguments : Mismatch between definition and execution";
1148 throw Exception(msg);
1153 PyObject_Print(result,stderr,Py_PRINT_RAW);
1156 list<OutputPort *>::iterator iter;
1159 for(iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); iter++)
1161 OutputPyPort *p=(OutputPyPort *)*iter;
1162 DEBTRACE( "port name: " << p->getName() );
1163 DEBTRACE( "port kind: " << p->edGetType()->kind() );
1164 DEBTRACE( "port pos : " << pos );
1165 if(PyTuple_Check(result))ob=PyTuple_GetItem(result,pos) ;
1167 DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
1169 PyObject_Print(ob,stderr,Py_PRINT_RAW);
1176 catch(ConversionException& ex)
1179 _errorDetails=ex.what();
1182 DEBTRACE( "-----------------End PyFuncNode::outputs-----------------" );
1185 DEBTRACE( "++++++++++++++ End PyFuncNode::execute: " << getName() << " ++++++++++++++++++++" );
1188 Node *PyFuncNode::simpleClone(ComposedNode *father, bool editionOnly) const
1190 return new PyFuncNode(*this,father);
1193 void PyFuncNode::createRemoteAdaptedPyInterpretor(Engines::Container_ptr objContainer)
1195 if(!CORBA::is_nil(_pynode))
1196 _pynode->UnRegister();
1197 _pynode=objContainer->createPyNode(getName().c_str(),getScript().c_str());
1200 Engines::PyNodeBase_var PyFuncNode::retrieveDftRemotePyInterpretorIfAny(Engines::Container_ptr objContainer) const
1202 Engines::PyNode_var ret(objContainer->getDefaultPyNode(getName().c_str()));
1203 if(!CORBA::is_nil(ret))
1207 return Engines::PyNodeBase::_narrow(ret);
1210 void PyFuncNode::assignRemotePyInterpretor(Engines::PyNodeBase_var remoteInterp)
1212 if(!CORBA::is_nil(_pynode))
1214 Engines::PyNode_var tmpp(Engines::PyNode::_narrow(remoteInterp));
1215 if(_pynode->_is_equivalent(tmpp))
1218 if(!CORBA::is_nil(_pynode))
1219 _pynode->UnRegister();
1220 _pynode=Engines::PyNode::_narrow(remoteInterp);
1223 Engines::PyNodeBase_var PyFuncNode::getRemoteInterpreterHandle()
1225 return Engines::PyNodeBase::_narrow(_pynode);
1228 //! Create a new node of same type with a given name
1229 PyFuncNode* PyFuncNode::cloneNode(const std::string& name)
1231 PyFuncNode* n=new PyFuncNode(name);
1232 n->setScript(_script);
1233 n->setFname(_fname);
1234 list<InputPort *>::iterator iter;
1235 for(iter = _setOfInputPort.begin(); iter != _setOfInputPort.end(); iter++)
1237 InputPyPort *p=(InputPyPort *)*iter;
1238 n->edAddInputPort(p->getName(),p->edGetType());
1240 list<OutputPort *>::iterator iter2;
1241 for(iter2 = _setOfOutputPort.begin(); iter2 != _setOfOutputPort.end(); iter2++)
1243 OutputPyPort *p=(OutputPyPort *)*iter2;
1244 n->edAddOutputPort(p->getName(),p->edGetType());
1249 std::string PyFuncNode::getContainerLog()
1251 return PythonEntry::GetContainerLog(_mode,_container,this);
1254 void PyFuncNode::shutdown(int level)
1256 DEBTRACE("PyFuncNode::shutdown " << level);
1257 if(_mode=="local")return;
1260 if(!CORBA::is_nil(_pynode)) _pynode->UnRegister();
1261 _pynode=Engines::PyNode::_nil();
1262 _container->shutdown(level);