1 // Copyright (C) 2006-2015 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 PythonNode::IMPL_NAME[]="Python";
52 const char PythonNode::KIND[]="Python";
54 const char PythonNode::SCRIPT_FOR_SERIALIZATION[]="import cPickle\n"
55 "def pickleForDistPyth2009(kws):\n"
56 " return cPickle.dumps(((),kws),-1)\n"
58 "def unPickleForDistPyth2009(st):\n"
59 " args=cPickle.loads(st)\n"
62 const char PyFuncNode::SCRIPT_FOR_SERIALIZATION[]="import cPickle\n"
63 "def pickleForDistPyth2009(*args,**kws):\n"
64 " return cPickle.dumps((args,kws),-1)\n"
66 "def unPickleForDistPyth2009(st):\n"
67 " args=cPickle.loads(st)\n"
70 PythonEntry::PythonEntry():_context(0),_pyfuncSer(0),_pyfuncUnser(0)
74 PythonEntry::~PythonEntry()
77 DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
78 // not Py_XDECREF of _pyfuncUnser because it is returned by PyDict_GetItem -> borrowed
79 // not Py_XDECREF of _pyfuncSer because it is returned by PyDict_GetItem -> borrowed
83 void PythonEntry::commonRemoteLoadPart1(InlineNode *reqNode)
85 DEBTRACE( "---------------PythonEntry::CommonRemoteLoad function---------------" );
86 Container *container(reqNode->getContainer());
87 bool isContAlreadyStarted(false);
90 isContAlreadyStarted=container->isAlreadyStarted(reqNode);
91 if(!isContAlreadyStarted)
95 container->start(reqNode);
99 reqNode->setErrorDetails(e.what());
106 std::string what("PythonEntry::CommonRemoteLoad : a load operation requested on \"");
107 what+=reqNode->getName(); what+="\" with no container specified.";
108 reqNode->setErrorDetails(what);
109 throw Exception(what);
113 Engines::Container_var PythonEntry::commonRemoteLoadPart2(InlineNode *reqNode, bool& isInitializeRequested)
115 Container *container(reqNode->getContainer());
116 Engines::Container_var objContainer=Engines::Container::_nil();
118 throw Exception("No container specified !");
119 SalomeContainer *containerCast0(dynamic_cast<SalomeContainer *>(container));
120 SalomeHPContainer *containerCast1(dynamic_cast<SalomeHPContainer *>(container));
122 objContainer=containerCast0->getContainerPtr(reqNode);
123 else if(containerCast1)
125 YACS::BASES::AutoCppPtr<SalomeContainerTmpForHP> tmpCont(SalomeContainerTmpForHP::BuildFrom(containerCast1,reqNode));
126 objContainer=tmpCont->getContainerPtr(reqNode);
129 throw Exception("Unrecognized type of container ! Salome one is expected for PythonNode/PyFuncNode !");
130 if(CORBA::is_nil(objContainer))
131 throw Exception("Container corba pointer is NULL for PythonNode !");
132 isInitializeRequested=false;
137 createRemoteAdaptedPyInterpretor(objContainer);
141 Engines::PyNodeBase_var dftPyScript(retrieveDftRemotePyInterpretorIfAny(objContainer));
142 if(CORBA::is_nil(dftPyScript))
144 isInitializeRequested=true;
145 createRemoteAdaptedPyInterpretor(objContainer);
148 assignRemotePyInterpretor(dftPyScript);
151 catch( const SALOME::SALOME_Exception& ex )
153 std::string msg="Exception on remote python node creation ";
155 msg += ex.details.text.in();
156 reqNode->setErrorDetails(msg);
157 throw Exception(msg);
159 Engines::PyNodeBase_var pynode(getRemoteInterpreterHandle());
160 if(CORBA::is_nil(pynode))
161 throw Exception("In PythonNode the ref in NULL ! ");
165 void PythonEntry::commonRemoteLoadPart3(InlineNode *reqNode, Engines::Container_ptr objContainer, bool isInitializeRequested)
167 Container *container(reqNode->getContainer());
168 Engines::PyNodeBase_var pynode(getRemoteInterpreterHandle());
172 const char *picklizeScript(getSerializationScript());
173 PyObject *res=PyRun_String(picklizeScript,Py_file_input,_context,_context);
176 std::string errorDetails;
177 PyObject* new_stderr = newPyStdOut(errorDetails);
178 reqNode->setErrorDetails(errorDetails);
179 PySys_SetObject((char*)"stderr", new_stderr);
181 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
182 Py_DECREF(new_stderr);
183 throw Exception("Error during load");
186 _pyfuncSer=PyDict_GetItemString(_context,"pickleForDistPyth2009");
187 _pyfuncUnser=PyDict_GetItemString(_context,"unPickleForDistPyth2009");
188 if(_pyfuncSer == NULL)
190 std::string errorDetails;
191 PyObject *new_stderr(newPyStdOut(errorDetails));
192 reqNode->setErrorDetails(errorDetails);
193 PySys_SetObject((char*)"stderr", new_stderr);
195 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
196 Py_DECREF(new_stderr);
197 throw Exception("Error during load");
199 if(_pyfuncUnser == 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");
211 if(isInitializeRequested)
212 {//This one is called only once at initialization in the container if an init-script is specified.
215 std::string zeInitScriptKey(container->getProperty(HomogeneousPoolContainer::INITIALIZE_SCRIPT_KEY));
216 if(!zeInitScriptKey.empty())
217 pynode->executeAnotherPieceOfCode(zeInitScriptKey.c_str());
219 catch( const SALOME::SALOME_Exception& ex )
221 std::string msg="Exception on PythonNode::loadRemote python invocation of initializisation py script !";
223 msg += ex.details.text.in();
224 reqNode->setErrorDetails(msg);
225 throw Exception(msg);
227 DEBTRACE( "---------------End PyNode::loadRemote function---------------" );
231 std::string PythonEntry::GetContainerLog(const std::string& mode, Container *container, const Task *askingTask)
239 SalomeContainer *containerCast(dynamic_cast<SalomeContainer *>(container));
240 SalomeHPContainer *objContainer2(dynamic_cast<SalomeHPContainer *>(container));
243 Engines::Container_var objContainer(containerCast->getContainerPtr(askingTask));
244 CORBA::String_var logname = objContainer->logfilename();
247 std::string::size_type pos = msg.find(":");
248 msg=msg.substr(pos+1);
250 else if(objContainer2)
252 msg="Remote PythonNode is on HP Container : no log because no info of the location by definition of HP Container !";
256 msg="Not implemented yet for container log for that type of container !";
261 msg = "Container no longer reachable";
266 void PythonEntry::commonRemoteLoad(InlineNode *reqNode)
268 commonRemoteLoadPart1(reqNode);
269 bool isInitializeRequested;
270 Engines::Container_var objContainer(commonRemoteLoadPart2(reqNode,isInitializeRequested));
271 commonRemoteLoadPart3(reqNode,objContainer,isInitializeRequested);
274 PythonNode::PythonNode(const PythonNode& other, ComposedNode *father):InlineNode(other,father)
276 _implementation=IMPL_NAME;
279 _context=PyDict_New();
280 if( PyDict_SetItemString( _context, "__builtins__", getSALOMERuntime()->getBuiltins() ))
283 msg << "Impossible to set builtins" << __FILE__ << ":" << __LINE__;
284 _errorDetails=msg.str();
285 throw Exception(msg.str());
290 PythonNode::PythonNode(const std::string& name):InlineNode(name)
292 _implementation=IMPL_NAME;
295 _context=PyDict_New();
296 if( PyDict_SetItemString( _context, "__builtins__", getSALOMERuntime()->getBuiltins() ))
299 msg << "Impossible to set builtins" << __FILE__ << ":" << __LINE__;
300 _errorDetails=msg.str();
301 throw Exception(msg.str());
306 PythonNode::~PythonNode()
308 if(!CORBA::is_nil(_pynode))
310 _pynode->UnRegister();
314 void PythonNode::checkBasicConsistency() const throw(YACS::Exception)
316 DEBTRACE("checkBasicConsistency");
317 InlineNode::checkBasicConsistency();
321 res=Py_CompileString(_script.c_str(),getName().c_str(),Py_file_input);
324 std::string error="";
325 PyObject* new_stderr = newPyStdOut(error);
326 PySys_SetObject((char*)"stderr", new_stderr);
328 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
329 Py_DECREF(new_stderr);
330 throw Exception(error);
337 void PythonNode::load()
339 DEBTRACE( "---------------PyNode::load function---------------" );
346 void PythonNode::loadLocal()
348 DEBTRACE( "---------------PyNode::loadLocal function---------------" );
352 void PythonNode::loadRemote()
354 commonRemoteLoad(this);
357 void PythonNode::execute()
365 void PythonNode::executeRemote()
367 DEBTRACE( "++++++++++++++ PyNode::executeRemote: " << getName() << " ++++++++++++++++++++" );
369 throw Exception("DistributedPythonNode badly loaded");
371 if(dynamic_cast<HomogeneousPoolContainer *>(getContainer()))
374 commonRemoteLoadPart2(this,dummy);
375 _pynode->assignNewCompiledCode(getScript().c_str());
378 Engines::pickledArgs_var serializationInputCorba(new Engines::pickledArgs);
381 PyObject *args(0),*ob(0);
382 //===========================================================================
383 // Get inputs in input ports, build a Python dict and pickle it
384 //===========================================================================
386 std::list<InputPort *>::iterator iter2;
388 for(iter2 = _setOfInputPort.begin(); iter2 != _setOfInputPort.end(); ++iter2)
390 InputPyPort *p=(InputPyPort *)*iter2;
392 PyDict_SetItemString(args,p->getName().c_str(),ob);
396 PyObject_Print(args,stderr,Py_PRINT_RAW);
399 PyObject *serializationInput(PyObject_CallFunctionObjArgs(_pyfuncSer,args,NULL));
401 //The pickled string may contain NULL characters so use PyString_AsStringAndSize
402 char *serializationInputC(0);
404 if (PyString_AsStringAndSize(serializationInput, &serializationInputC, &len))
405 throw Exception("DistributedPythonNode problem in python pickle");
406 serializationInputCorba->length(len);
407 for(int i=0; i < len ; i++)
408 serializationInputCorba[i]=serializationInputC[i];
409 Py_DECREF(serializationInput);
412 //get the list of output argument names
413 std::list<OutputPort *>::iterator iter;
414 Engines::listofstring myseq;
415 myseq.length(getNumberOfOutputPorts());
417 for(iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); ++iter)
419 OutputPyPort *p=(OutputPyPort *)*iter;
420 myseq[pos]=p->getName().c_str();
421 DEBTRACE( "port name: " << p->getName() );
422 DEBTRACE( "port kind: " << p->edGetType()->kind() );
423 DEBTRACE( "port pos : " << pos );
426 //===========================================================================
427 // Execute in remote Python node
428 //===========================================================================
429 DEBTRACE( "-----------------starting remote python invocation-----------------" );
430 Engines::pickledArgs_var resultCorba;
433 //pass outargsname and dict serialized
434 resultCorba=_pynode->execute(myseq,serializationInputCorba);
436 catch( const SALOME::SALOME_Exception& ex )
438 std::string msg="Exception on remote python invocation";
440 msg += ex.details.text.in();
442 throw Exception(msg);
444 DEBTRACE( "-----------------end of remote python invocation-----------------" );
445 //===========================================================================
446 // Get results, unpickle and put them in output ports
447 //===========================================================================
448 char *resultCorbaC=new char[resultCorba->length()+1];
449 resultCorbaC[resultCorba->length()]='\0';
450 for(int i=0;i<resultCorba->length();i++)
451 resultCorbaC[i]=resultCorba[i];
455 PyObject *args(0),*ob(0);
456 PyObject* resultPython=PyString_FromStringAndSize(resultCorbaC,resultCorba->length());
457 delete [] resultCorbaC;
458 args = PyTuple_New(1);
459 PyTuple_SetItem(args,0,resultPython);
460 PyObject *finalResult=PyObject_CallObject(_pyfuncUnser,args);
463 if (finalResult == NULL)
465 std::stringstream msg;
466 msg << "Conversion with pickle of output ports failed !";
467 msg << " : " << __FILE__ << ":" << __LINE__;
468 _errorDetails=msg.str();
469 throw YACS::ENGINE::ConversionException(msg.str());
472 DEBTRACE( "-----------------PythonNode::outputs-----------------" );
474 if(finalResult == Py_None)
476 else if(PyTuple_Check(finalResult))
477 nres=PyTuple_Size(finalResult);
479 if(getNumberOfOutputPorts() != nres)
481 std::string msg="Number of output arguments : Mismatch between definition and execution";
482 Py_DECREF(finalResult);
484 throw Exception(msg);
490 for(iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); ++iter)
492 OutputPyPort *p=(OutputPyPort *)*iter;
493 DEBTRACE( "port name: " << p->getName() );
494 DEBTRACE( "port kind: " << p->edGetType()->kind() );
495 DEBTRACE( "port pos : " << pos );
496 if(PyTuple_Check(finalResult))
497 ob=PyTuple_GetItem(finalResult,pos) ;
500 DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
504 Py_DECREF(finalResult);
506 catch(ConversionException& ex)
508 Py_DECREF(finalResult);
509 _errorDetails=ex.what();
513 DEBTRACE( "++++++++++++++ ENDOF PyNode::executeRemote: " << getName() << " ++++++++++++++++++++" );
516 void PythonNode::executeLocal()
518 DEBTRACE( "++++++++++++++ PyNode::executeLocal: " << getName() << " ++++++++++++++++++++" );
522 DEBTRACE( "---------------PyNode::inputs---------------" );
523 list<InputPort *>::iterator iter2;
524 for(iter2 = _setOfInputPort.begin(); iter2 != _setOfInputPort.end(); iter2++)
526 InputPyPort *p=(InputPyPort *)*iter2;
527 DEBTRACE( "port name: " << p->getName() );
528 DEBTRACE( "port kind: " << p->edGetType()->kind() );
529 PyObject* ob=p->getPyObj();
530 DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
532 PyObject_Print(ob,stderr,Py_PRINT_RAW);
535 int ier=PyDict_SetItemString(_context,p->getName().c_str(),ob);
536 DEBTRACE( "after PyDict_SetItemString:ob refcnt: " << ob->ob_refcnt );
539 DEBTRACE( "---------------End PyNode::inputs---------------" );
542 DEBTRACE( "----------------PyNode::calculation---------------" );
544 DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
546 std::ostringstream stream;
547 stream << "/tmp/PythonNode_";
550 PyObject* code=Py_CompileString(_script.c_str(), stream.str().c_str(), Py_file_input);
554 PyObject* new_stderr = newPyStdOut(_errorDetails);
555 PySys_SetObject((char*)"stderr", new_stderr);
557 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
558 Py_DECREF(new_stderr);
559 throw Exception("Error during execution");
561 PyObject *res = PyEval_EvalCode((PyCodeObject *)code, _context, _context);
565 DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
568 if(PyErr_Occurred ())
571 PyObject* new_stderr = newPyStdOut(_errorDetails);
572 PySys_SetObject((char*)"stderr", new_stderr);
573 ofstream errorfile(stream.str().c_str());
574 if (errorfile.is_open())
576 errorfile << _script;
580 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
581 Py_DECREF(new_stderr);
582 throw Exception("Error during execution");
585 DEBTRACE( "-----------------PyNode::outputs-----------------" );
586 list<OutputPort *>::iterator iter;
589 for(iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); iter++)
591 OutputPyPort *p=(OutputPyPort *)*iter;
592 DEBTRACE( "port name: " << p->getName() );
593 DEBTRACE( "port kind: " << p->edGetType()->kind() );
594 PyObject *ob=PyDict_GetItemString(_context,p->getName().c_str());
597 std::string msg="Error during execution: there is no variable ";
598 msg=msg+p->getName()+" in node context";
600 throw Exception(msg);
602 DEBTRACE( "PyNode::outputs::ob refcnt: " << ob->ob_refcnt );
604 PyObject_Print(ob,stderr,Py_PRINT_RAW);
610 catch(ConversionException& ex)
612 _errorDetails=ex.what();
616 DEBTRACE( "-----------------End PyNode::outputs-----------------" );
618 DEBTRACE( "++++++++++++++ End PyNode::execute: " << getName() << " ++++++++++++++++++++" );
621 std::string PythonNode::getContainerLog()
623 return PythonEntry::GetContainerLog(_mode,_container,this);
626 void PythonNode::shutdown(int level)
628 DEBTRACE("PythonNode::shutdown " << level);
629 if(_mode=="local")return;
632 if(!CORBA::is_nil(_pynode)) _pynode->UnRegister();
633 _pynode=Engines::PyScriptNode::_nil();
634 _container->shutdown(level);
638 Node *PythonNode::simpleClone(ComposedNode *father, bool editionOnly) const
640 return new PythonNode(*this,father);
643 void PythonNode::createRemoteAdaptedPyInterpretor(Engines::Container_ptr objContainer)
645 if(!CORBA::is_nil(_pynode))
646 _pynode->UnRegister();
647 _pynode=objContainer->createPyScriptNode(getName().c_str(),getScript().c_str());
650 Engines::PyNodeBase_var PythonNode::retrieveDftRemotePyInterpretorIfAny(Engines::Container_ptr objContainer) const
652 Engines::PyScriptNode_var ret(objContainer->getDefaultPyScriptNode());
653 if(!CORBA::is_nil(ret))
657 return Engines::PyNodeBase::_narrow(ret);
660 void PythonNode::assignRemotePyInterpretor(Engines::PyNodeBase_var remoteInterp)
662 if(!CORBA::is_nil(_pynode))
664 Engines::PyScriptNode_var tmpp(Engines::PyScriptNode::_narrow(remoteInterp));
665 if(_pynode->_is_equivalent(tmpp))
668 if(!CORBA::is_nil(_pynode))
669 _pynode->UnRegister();
670 _pynode=Engines::PyScriptNode::_narrow(remoteInterp);
673 Engines::PyNodeBase_var PythonNode::getRemoteInterpreterHandle()
675 return Engines::PyNodeBase::_narrow(_pynode);
678 //! Create a new node of same type with a given name
679 PythonNode* PythonNode::cloneNode(const std::string& name)
681 PythonNode* n=new PythonNode(name);
682 n->setScript(_script);
683 list<InputPort *>::iterator iter;
684 for(iter = _setOfInputPort.begin(); iter != _setOfInputPort.end(); iter++)
686 InputPyPort *p=(InputPyPort *)*iter;
687 DEBTRACE( "port name: " << p->getName() );
688 DEBTRACE( "port kind: " << p->edGetType()->kind() );
689 n->edAddInputPort(p->getName(),p->edGetType());
691 list<OutputPort *>::iterator iter2;
692 for(iter2 = _setOfOutputPort.begin(); iter2 != _setOfOutputPort.end(); iter2++)
694 OutputPyPort *p=(OutputPyPort *)*iter2;
695 DEBTRACE( "port name: " << p->getName() );
696 DEBTRACE( "port kind: " << p->edGetType()->kind() );
697 n->edAddOutputPort(p->getName(),p->edGetType());
702 PyFuncNode::PyFuncNode(const PyFuncNode& other, ComposedNode *father):InlineFuncNode(other,father),_pyfunc(0)
704 _implementation = PythonNode::IMPL_NAME;
707 _context=PyDict_New();
708 DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
709 if( PyDict_SetItemString( _context, "__builtins__", getSALOMERuntime()->getBuiltins() ))
712 msg << "Not possible to set builtins" << __FILE__ << ":" << __LINE__;
713 _errorDetails=msg.str();
714 throw Exception(msg.str());
719 PyFuncNode::PyFuncNode(const std::string& name): InlineFuncNode(name),_pyfunc(0)
722 _implementation = PythonNode::IMPL_NAME;
723 DEBTRACE( "PyFuncNode::PyFuncNode " << name );
726 _context=PyDict_New();
727 DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
728 if( PyDict_SetItemString( _context, "__builtins__", getSALOMERuntime()->getBuiltins() ))
731 msg << "Not possible to set builtins" << __FILE__ << ":" << __LINE__;
732 _errorDetails=msg.str();
733 throw Exception(msg.str());
738 PyFuncNode::~PyFuncNode()
740 if(!CORBA::is_nil(_pynode))
742 _pynode->UnRegister();
746 void PyFuncNode::checkBasicConsistency() const throw(YACS::Exception)
748 DEBTRACE("checkBasicConsistency");
749 InlineFuncNode::checkBasicConsistency();
753 res=Py_CompileString(_script.c_str(),getName().c_str(),Py_file_input);
756 std::string error="";
757 PyObject* new_stderr = newPyStdOut(error);
758 PySys_SetObject((char*)"stderr", new_stderr);
760 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
761 Py_DECREF(new_stderr);
762 throw Exception(error);
769 void PyFuncNode::load()
771 DEBTRACE( "---------------PyfuncNode::load function---------------" );
778 void PyFuncNode::loadRemote()
780 commonRemoteLoad(this);
783 void PyFuncNode::loadLocal()
785 DEBTRACE( "---------------PyFuncNode::load function " << getName() << " ---------------" );
789 list<OutputPort *>::iterator iter;
790 for(iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); iter++)
792 OutputPyPort *p=(OutputPyPort *)*iter;
793 DEBTRACE( "port name: " << p->getName() );
794 DEBTRACE( "port kind: " << p->edGetType()->kind() );
800 DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
802 std::ostringstream stream;
803 stream << "/tmp/PythonNode_";
806 PyObject* code=Py_CompileString(_script.c_str(), stream.str().c_str(), Py_file_input);
810 PyObject* new_stderr = newPyStdOut(_errorDetails);
811 PySys_SetObject((char*)"stderr", new_stderr);
813 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
814 Py_DECREF(new_stderr);
815 throw Exception("Error during execution");
817 PyObject *res = PyEval_EvalCode((PyCodeObject *)code, _context, _context);
821 DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
822 if(PyErr_Occurred ())
825 PyObject* new_stderr = newPyStdOut(_errorDetails);
826 PySys_SetObject((char*)"stderr", new_stderr);
827 ofstream errorfile(stream.str().c_str());
828 if (errorfile.is_open())
830 errorfile << _script;
834 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
835 Py_DECREF(new_stderr);
836 throw Exception("Error during execution");
839 _pyfunc=PyDict_GetItemString(_context,_fname.c_str());
840 DEBTRACE( "_pyfunc refcnt: " << _pyfunc->ob_refcnt );
844 PyObject* new_stderr = newPyStdOut(_errorDetails);
845 PySys_SetObject((char*)"stderr", new_stderr);
847 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
848 Py_DECREF(new_stderr);
849 throw Exception("Error during execution");
851 DEBTRACE( "---------------End PyFuncNode::load function---------------" );
855 void PyFuncNode::execute()
863 void PyFuncNode::executeRemote()
865 DEBTRACE( "++++++++++++++ PyFuncNode::executeRemote: " << getName() << " ++++++++++++++++++++" );
867 throw Exception("DistributedPythonNode badly loaded");
869 if(dynamic_cast<HomogeneousPoolContainer *>(getContainer()))
872 commonRemoteLoadPart2(this,dummy);
873 _pynode->executeAnotherPieceOfCode(getScript().c_str());
876 Engines::pickledArgs_var serializationInputCorba(new Engines::pickledArgs);;
880 //===========================================================================
881 // Get inputs in input ports, build a Python tuple and pickle it
882 //===========================================================================
883 PyObject *args(PyTuple_New(getNumberOfInputPorts()));
885 for(std::list<InputPort *>::iterator iter2 = _setOfInputPort.begin(); iter2 != _setOfInputPort.end(); iter2++,pos++)
887 InputPyPort *p=(InputPyPort *)*iter2;
890 PyTuple_SetItem(args,pos,ob);
893 PyObject_Print(args,stderr,Py_PRINT_RAW);
896 PyObject *serializationInput=PyObject_CallObject(_pyfuncSer,args);
898 //The pickled string may contain NULL characters so use PyString_AsStringAndSize
899 char *serializationInputC(0);
901 if (PyString_AsStringAndSize(serializationInput, &serializationInputC, &len))
902 throw Exception("DistributedPythonNode problem in python pickle");
904 serializationInputCorba->length(len);
905 for(int i=0; i < len ; i++)
906 serializationInputCorba[i]=serializationInputC[i];
907 Py_DECREF(serializationInput);
910 //===========================================================================
911 // Execute in remote Python node
912 //===========================================================================
913 DEBTRACE( "-----------------starting remote python invocation-----------------" );
914 Engines::pickledArgs_var resultCorba;
917 resultCorba=_pynode->execute(getFname().c_str(),serializationInputCorba);
919 catch( const SALOME::SALOME_Exception& ex )
921 std::string msg="Exception on remote python invocation";
923 msg += ex.details.text.in();
925 throw Exception(msg);
927 DEBTRACE( "-----------------end of remote python invocation-----------------" );
928 //===========================================================================
929 // Get results, unpickle and put them in output ports
930 //===========================================================================
931 char *resultCorbaC=new char[resultCorba->length()+1];
932 resultCorbaC[resultCorba->length()]='\0';
933 for(int i=0;i<resultCorba->length();i++)
934 resultCorbaC[i]=resultCorba[i];
939 PyObject *resultPython(PyString_FromStringAndSize(resultCorbaC,resultCorba->length()));
940 delete [] resultCorbaC;
941 PyObject *args(PyTuple_New(1)),*ob(0);
942 PyTuple_SetItem(args,0,resultPython);
943 PyObject *finalResult=PyObject_CallObject(_pyfuncUnser,args);
946 DEBTRACE( "-----------------PythonNode::outputs-----------------" );
948 if(finalResult == Py_None)
950 else if(PyTuple_Check(finalResult))
951 nres=PyTuple_Size(finalResult);
953 if(getNumberOfOutputPorts() != nres)
955 std::string msg="Number of output arguments : Mismatch between definition and execution";
956 Py_DECREF(finalResult);
958 throw Exception(msg);
964 for(std::list<OutputPort *>::iterator iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); iter++, pos++)
966 OutputPyPort *p=(OutputPyPort *)*iter;
967 DEBTRACE( "port name: " << p->getName() );
968 DEBTRACE( "port kind: " << p->edGetType()->kind() );
969 DEBTRACE( "port pos : " << pos );
970 if(PyTuple_Check(finalResult))
971 ob=PyTuple_GetItem(finalResult,pos) ;
974 DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
977 Py_DECREF(finalResult);
979 catch(ConversionException& ex)
981 Py_DECREF(finalResult);
982 _errorDetails=ex.what();
987 DEBTRACE( "++++++++++++++ ENDOF PyFuncNode::executeRemote: " << getName() << " ++++++++++++++++++++" );
990 void PyFuncNode::executeLocal()
992 DEBTRACE( "++++++++++++++ PyFuncNode::execute: " << getName() << " ++++++++++++++++++++" );
996 if(!_pyfunc)throw Exception("PyFuncNode badly loaded");
999 DEBTRACE( "---------------PyFuncNode::inputs---------------" );
1000 PyObject* args = PyTuple_New(getNumberOfInputPorts()) ;
1001 list<InputPort *>::iterator iter2;
1002 for(iter2 = _setOfInputPort.begin(); iter2 != _setOfInputPort.end(); iter2++)
1004 InputPyPort *p=(InputPyPort *)*iter2;
1005 DEBTRACE( "port name: " << p->getName() );
1006 DEBTRACE( "port kind: " << p->edGetType()->kind() );
1009 PyObject_Print(ob,stderr,Py_PRINT_RAW);
1012 DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
1014 PyTuple_SetItem(args,pos,ob);
1015 DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
1018 DEBTRACE( "---------------End PyFuncNode::inputs---------------" );
1020 DEBTRACE( "----------------PyFuncNode::calculation---------------" );
1022 PyObject_Print(_pyfunc,stderr,Py_PRINT_RAW);
1024 PyObject_Print(args,stderr,Py_PRINT_RAW);
1027 DEBTRACE( "_pyfunc refcnt: " << _pyfunc->ob_refcnt );
1028 PyObject* result = PyObject_CallObject( _pyfunc , args ) ;
1029 DEBTRACE( "_pyfunc refcnt: " << _pyfunc->ob_refcnt );
1036 PyObject* new_stderr = newPyStdOut(_errorDetails);
1037 PySys_SetObject((char*)"stderr", new_stderr);
1038 std::ostringstream stream;
1039 stream << "/tmp/PythonNode_";
1041 ofstream errorfile(stream.str().c_str());
1042 if (errorfile.is_open())
1044 errorfile << _script;
1048 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
1049 Py_DECREF(new_stderr);
1050 throw Exception("Error during execution");
1052 DEBTRACE( "----------------End PyFuncNode::calculation---------------" );
1054 DEBTRACE( "-----------------PyFuncNode::outputs-----------------" );
1056 if(result == Py_None)
1058 else if(PyTuple_Check(result))
1059 nres=PyTuple_Size(result);
1061 if(getNumberOfOutputPorts() != nres)
1063 std::string msg="Number of output arguments : Mismatch between definition and execution";
1066 throw Exception(msg);
1071 PyObject_Print(result,stderr,Py_PRINT_RAW);
1074 list<OutputPort *>::iterator iter;
1077 for(iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); iter++)
1079 OutputPyPort *p=(OutputPyPort *)*iter;
1080 DEBTRACE( "port name: " << p->getName() );
1081 DEBTRACE( "port kind: " << p->edGetType()->kind() );
1082 DEBTRACE( "port pos : " << pos );
1083 if(PyTuple_Check(result))ob=PyTuple_GetItem(result,pos) ;
1085 DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
1087 PyObject_Print(ob,stderr,Py_PRINT_RAW);
1094 catch(ConversionException& ex)
1097 _errorDetails=ex.what();
1100 DEBTRACE( "-----------------End PyFuncNode::outputs-----------------" );
1103 DEBTRACE( "++++++++++++++ End PyFuncNode::execute: " << getName() << " ++++++++++++++++++++" );
1106 Node *PyFuncNode::simpleClone(ComposedNode *father, bool editionOnly) const
1108 return new PyFuncNode(*this,father);
1111 void PyFuncNode::createRemoteAdaptedPyInterpretor(Engines::Container_ptr objContainer)
1113 if(!CORBA::is_nil(_pynode))
1114 _pynode->UnRegister();
1115 _pynode=objContainer->createPyNode(getName().c_str(),getScript().c_str());
1118 Engines::PyNodeBase_var PyFuncNode::retrieveDftRemotePyInterpretorIfAny(Engines::Container_ptr objContainer) const
1120 Engines::PyNode_var ret(objContainer->getDefaultPyNode());
1121 if(!CORBA::is_nil(ret))
1125 return Engines::PyNodeBase::_narrow(ret);
1128 void PyFuncNode::assignRemotePyInterpretor(Engines::PyNodeBase_var remoteInterp)
1130 if(!CORBA::is_nil(_pynode))
1132 Engines::PyNode_var tmpp(Engines::PyNode::_narrow(remoteInterp));
1133 if(_pynode->_is_equivalent(tmpp))
1136 if(!CORBA::is_nil(_pynode))
1137 _pynode->UnRegister();
1138 _pynode=Engines::PyNode::_narrow(remoteInterp);
1141 Engines::PyNodeBase_var PyFuncNode::getRemoteInterpreterHandle()
1143 return Engines::PyNodeBase::_narrow(_pynode);
1146 //! Create a new node of same type with a given name
1147 PyFuncNode* PyFuncNode::cloneNode(const std::string& name)
1149 PyFuncNode* n=new PyFuncNode(name);
1150 n->setScript(_script);
1151 n->setFname(_fname);
1152 list<InputPort *>::iterator iter;
1153 for(iter = _setOfInputPort.begin(); iter != _setOfInputPort.end(); iter++)
1155 InputPyPort *p=(InputPyPort *)*iter;
1156 n->edAddInputPort(p->getName(),p->edGetType());
1158 list<OutputPort *>::iterator iter2;
1159 for(iter2 = _setOfOutputPort.begin(); iter2 != _setOfOutputPort.end(); iter2++)
1161 OutputPyPort *p=(OutputPyPort *)*iter2;
1162 n->edAddOutputPort(p->getName(),p->edGetType());
1167 std::string PyFuncNode::getContainerLog()
1169 return PythonEntry::GetContainerLog(_mode,_container,this);
1172 void PyFuncNode::shutdown(int level)
1174 DEBTRACE("PyFuncNode::shutdown " << level);
1175 if(_mode=="local")return;
1178 if(!CORBA::is_nil(_pynode)) _pynode->UnRegister();
1179 _pynode=Engines::PyNode::_nil();
1180 _container->shutdown(level);