1 // Copyright (C) 2006-2014 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::commonRemoteLoad(InlineNode *reqNode)
167 commonRemoteLoadPart1(reqNode);
168 Container *container(reqNode->getContainer());
169 bool isInitializeRequested;
170 Engines::Container_var objContainer(commonRemoteLoadPart2(reqNode,isInitializeRequested));
171 Engines::PyNodeBase_var pynode(getRemoteInterpreterHandle());
175 const char *picklizeScript(getSerializationScript());
176 PyObject *res=PyRun_String(picklizeScript,Py_file_input,_context,_context);
179 std::string errorDetails;
180 PyObject* new_stderr = newPyStdOut(errorDetails);
181 reqNode->setErrorDetails(errorDetails);
182 PySys_SetObject((char*)"stderr", new_stderr);
184 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
185 Py_DECREF(new_stderr);
186 throw Exception("Error during load");
189 _pyfuncSer=PyDict_GetItemString(_context,"pickleForDistPyth2009");
190 _pyfuncUnser=PyDict_GetItemString(_context,"unPickleForDistPyth2009");
191 if(_pyfuncSer == NULL)
193 std::string errorDetails;
194 PyObject *new_stderr(newPyStdOut(errorDetails));
195 reqNode->setErrorDetails(errorDetails);
196 PySys_SetObject((char*)"stderr", new_stderr);
198 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
199 Py_DECREF(new_stderr);
200 throw Exception("Error during load");
202 if(_pyfuncUnser == NULL)
204 std::string errorDetails;
205 PyObject *new_stderr(newPyStdOut(errorDetails));
206 reqNode->setErrorDetails(errorDetails);
207 PySys_SetObject((char*)"stderr", new_stderr);
209 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
210 Py_DECREF(new_stderr);
211 throw Exception("Error during load");
213 if(isInitializeRequested)
214 {//This one is called only once at initialization in the container if an init-script is specified.
217 std::string zeInitScriptKey(container->getProperty(HomogeneousPoolContainer::INITIALIZE_SCRIPT_KEY));
218 if(!zeInitScriptKey.empty())
219 pynode->executeAnotherPieceOfCode(zeInitScriptKey.c_str());
221 catch( const SALOME::SALOME_Exception& ex )
223 std::string msg="Exception on PythonNode::loadRemote python invocation of initializisation py script !";
225 msg += ex.details.text.in();
226 reqNode->setErrorDetails(msg);
227 throw Exception(msg);
230 DEBTRACE( "---------------End PyNode::loadRemote function---------------" );
234 PythonNode::PythonNode(const PythonNode& other, ComposedNode *father):InlineNode(other,father)
236 _implementation=IMPL_NAME;
239 _context=PyDict_New();
240 if( PyDict_SetItemString( _context, "__builtins__", getSALOMERuntime()->getBuiltins() ))
243 msg << "Impossible to set builtins" << __FILE__ << ":" << __LINE__;
244 _errorDetails=msg.str();
245 throw Exception(msg.str());
250 PythonNode::PythonNode(const std::string& name):InlineNode(name)
252 _implementation=IMPL_NAME;
255 _context=PyDict_New();
256 if( PyDict_SetItemString( _context, "__builtins__", getSALOMERuntime()->getBuiltins() ))
259 msg << "Impossible to set builtins" << __FILE__ << ":" << __LINE__;
260 _errorDetails=msg.str();
261 throw Exception(msg.str());
266 PythonNode::~PythonNode()
268 if(!CORBA::is_nil(_pynode))
270 _pynode->UnRegister();
274 void PythonNode::checkBasicConsistency() const throw(YACS::Exception)
276 DEBTRACE("checkBasicConsistency");
277 InlineNode::checkBasicConsistency();
281 res=Py_CompileString(_script.c_str(),getName().c_str(),Py_file_input);
284 std::string error="";
285 PyObject* new_stderr = newPyStdOut(error);
286 PySys_SetObject((char*)"stderr", new_stderr);
288 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
289 Py_DECREF(new_stderr);
290 throw Exception(error);
297 void PythonNode::load()
299 DEBTRACE( "---------------PyNode::load function---------------" );
306 void PythonNode::loadLocal()
308 DEBTRACE( "---------------PyNode::loadLocal function---------------" );
312 void PythonNode::loadRemote()
314 commonRemoteLoad(this);
317 void PythonNode::execute()
325 void PythonNode::executeRemote()
327 DEBTRACE( "++++++++++++++ PyNode::executeRemote: " << getName() << " ++++++++++++++++++++" );
329 throw Exception("DistributedPythonNode badly loaded");
332 if(dynamic_cast<HomogeneousPoolContainer *>(getContainer()))
335 commonRemoteLoadPart2(this,dummy);
338 Engines::pickledArgs_var serializationInputCorba(new Engines::pickledArgs);
341 PyObject *args(0),*ob(0);
342 //===========================================================================
343 // Get inputs in input ports, build a Python dict and pickle it
344 //===========================================================================
346 std::list<InputPort *>::iterator iter2;
348 for(iter2 = _setOfInputPort.begin(); iter2 != _setOfInputPort.end(); ++iter2)
350 InputPyPort *p=(InputPyPort *)*iter2;
352 PyDict_SetItemString(args,p->getName().c_str(),ob);
356 PyObject_Print(args,stderr,Py_PRINT_RAW);
359 PyObject *serializationInput(PyObject_CallFunctionObjArgs(_pyfuncSer,args,NULL));
361 //The pickled string may contain NULL characters so use PyString_AsStringAndSize
362 char *serializationInputC(0);
364 if (PyString_AsStringAndSize(serializationInput, &serializationInputC, &len))
365 throw Exception("DistributedPythonNode problem in python pickle");
366 serializationInputCorba->length(len);
367 for(int i=0; i < len ; i++)
368 serializationInputCorba[i]=serializationInputC[i];
369 Py_DECREF(serializationInput);
372 //get the list of output argument names
373 std::list<OutputPort *>::iterator iter;
374 Engines::listofstring myseq;
375 myseq.length(getNumberOfOutputPorts());
377 for(iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); ++iter)
379 OutputPyPort *p=(OutputPyPort *)*iter;
380 myseq[pos]=p->getName().c_str();
381 DEBTRACE( "port name: " << p->getName() );
382 DEBTRACE( "port kind: " << p->edGetType()->kind() );
383 DEBTRACE( "port pos : " << pos );
386 //===========================================================================
387 // Execute in remote Python node
388 //===========================================================================
389 DEBTRACE( "-----------------starting remote python invocation-----------------" );
390 Engines::pickledArgs_var resultCorba;
393 //pass outargsname and dict serialized
394 resultCorba=_pynode->execute(myseq,serializationInputCorba);
396 catch( const SALOME::SALOME_Exception& ex )
398 std::string msg="Exception on remote python invocation";
400 msg += ex.details.text.in();
402 throw Exception(msg);
404 DEBTRACE( "-----------------end of remote python invocation-----------------" );
405 //===========================================================================
406 // Get results, unpickle and put them in output ports
407 //===========================================================================
408 char *resultCorbaC=new char[resultCorba->length()+1];
409 resultCorbaC[resultCorba->length()]='\0';
410 for(int i=0;i<resultCorba->length();i++)
411 resultCorbaC[i]=resultCorba[i];
415 PyObject *args(0),*ob(0);
416 PyObject* resultPython=PyString_FromStringAndSize(resultCorbaC,resultCorba->length());
417 delete [] resultCorbaC;
418 args = PyTuple_New(1);
419 PyTuple_SetItem(args,0,resultPython);
420 PyObject *finalResult=PyObject_CallObject(_pyfuncUnser,args);
423 if (finalResult == NULL)
425 std::stringstream msg;
426 msg << "Conversion with pickle of output ports failed !";
427 msg << " : " << __FILE__ << ":" << __LINE__;
428 _errorDetails=msg.str();
429 throw YACS::ENGINE::ConversionException(msg.str());
432 DEBTRACE( "-----------------PythonNode::outputs-----------------" );
434 if(finalResult == Py_None)
436 else if(PyTuple_Check(finalResult))
437 nres=PyTuple_Size(finalResult);
439 if(getNumberOfOutputPorts() != nres)
441 std::string msg="Number of output arguments : Mismatch between definition and execution";
442 Py_DECREF(finalResult);
444 throw Exception(msg);
450 for(iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); ++iter)
452 OutputPyPort *p=(OutputPyPort *)*iter;
453 DEBTRACE( "port name: " << p->getName() );
454 DEBTRACE( "port kind: " << p->edGetType()->kind() );
455 DEBTRACE( "port pos : " << pos );
456 if(PyTuple_Check(finalResult))
457 ob=PyTuple_GetItem(finalResult,pos) ;
460 DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
464 Py_DECREF(finalResult);
466 catch(ConversionException& ex)
468 Py_DECREF(finalResult);
469 _errorDetails=ex.what();
473 DEBTRACE( "++++++++++++++ ENDOF PyNode::executeRemote: " << getName() << " ++++++++++++++++++++" );
476 void PythonNode::executeLocal()
478 DEBTRACE( "++++++++++++++ PyNode::executeLocal: " << getName() << " ++++++++++++++++++++" );
482 DEBTRACE( "---------------PyNode::inputs---------------" );
483 list<InputPort *>::iterator iter2;
484 for(iter2 = _setOfInputPort.begin(); iter2 != _setOfInputPort.end(); iter2++)
486 InputPyPort *p=(InputPyPort *)*iter2;
487 DEBTRACE( "port name: " << p->getName() );
488 DEBTRACE( "port kind: " << p->edGetType()->kind() );
489 PyObject* ob=p->getPyObj();
490 DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
492 PyObject_Print(ob,stderr,Py_PRINT_RAW);
495 int ier=PyDict_SetItemString(_context,p->getName().c_str(),ob);
496 DEBTRACE( "after PyDict_SetItemString:ob refcnt: " << ob->ob_refcnt );
499 DEBTRACE( "---------------End PyNode::inputs---------------" );
502 DEBTRACE( "----------------PyNode::calculation---------------" );
504 DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
506 std::ostringstream stream;
507 stream << "/tmp/PythonNode_";
510 PyObject* code=Py_CompileString(_script.c_str(), stream.str().c_str(), Py_file_input);
514 PyObject* new_stderr = newPyStdOut(_errorDetails);
515 PySys_SetObject((char*)"stderr", new_stderr);
517 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
518 Py_DECREF(new_stderr);
519 throw Exception("Error during execution");
521 PyObject *res = PyEval_EvalCode((PyCodeObject *)code, _context, _context);
525 DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
528 if(PyErr_Occurred ())
531 PyObject* new_stderr = newPyStdOut(_errorDetails);
532 PySys_SetObject((char*)"stderr", new_stderr);
533 ofstream errorfile(stream.str().c_str());
534 if (errorfile.is_open())
536 errorfile << _script;
540 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
541 Py_DECREF(new_stderr);
542 throw Exception("Error during execution");
545 DEBTRACE( "-----------------PyNode::outputs-----------------" );
546 list<OutputPort *>::iterator iter;
549 for(iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); iter++)
551 OutputPyPort *p=(OutputPyPort *)*iter;
552 DEBTRACE( "port name: " << p->getName() );
553 DEBTRACE( "port kind: " << p->edGetType()->kind() );
554 PyObject *ob=PyDict_GetItemString(_context,p->getName().c_str());
557 std::string msg="Error during execution: there is no variable ";
558 msg=msg+p->getName()+" in node context";
560 throw Exception(msg);
562 DEBTRACE( "PyNode::outputs::ob refcnt: " << ob->ob_refcnt );
564 PyObject_Print(ob,stderr,Py_PRINT_RAW);
570 catch(ConversionException& ex)
572 _errorDetails=ex.what();
576 DEBTRACE( "-----------------End PyNode::outputs-----------------" );
578 DEBTRACE( "++++++++++++++ End PyNode::execute: " << getName() << " ++++++++++++++++++++" );
581 std::string PythonNode::getContainerLog()
583 if(_mode=="local")return "";
588 Engines::Container_var objContainer=((SalomeContainer*)_container)->getContainerPtr(this);
589 CORBA::String_var logname = objContainer->logfilename();
592 std::string::size_type pos = msg.find(":");
593 msg=msg.substr(pos+1);
597 msg = "Container no longer reachable";
602 void PythonNode::shutdown(int level)
604 DEBTRACE("PythonNode::shutdown " << level);
605 if(_mode=="local")return;
608 if(!CORBA::is_nil(_pynode)) _pynode->UnRegister();
609 _pynode=Engines::PyScriptNode::_nil();
610 _container->shutdown(level);
614 Node *PythonNode::simpleClone(ComposedNode *father, bool editionOnly) const
616 return new PythonNode(*this,father);
619 void PythonNode::createRemoteAdaptedPyInterpretor(Engines::Container_ptr objContainer)
621 if(!CORBA::is_nil(_pynode))
622 _pynode->UnRegister();
623 _pynode=objContainer->createPyScriptNode(getName().c_str(),getScript().c_str());
626 Engines::PyNodeBase_var PythonNode::retrieveDftRemotePyInterpretorIfAny(Engines::Container_ptr objContainer) const
628 Engines::PyScriptNode_var ret(objContainer->getDefaultPyScriptNode());
629 if(!CORBA::is_nil(ret))
633 return Engines::PyNodeBase::_narrow(ret);
636 void PythonNode::assignRemotePyInterpretor(Engines::PyNodeBase_var remoteInterp)
638 if(!CORBA::is_nil(_pynode))
640 Engines::PyScriptNode_var tmpp(Engines::PyScriptNode::_narrow(remoteInterp));
641 if(_pynode->_is_equivalent(tmpp))
644 if(!CORBA::is_nil(_pynode))
645 _pynode->UnRegister();
646 _pynode=Engines::PyScriptNode::_narrow(remoteInterp);
649 Engines::PyNodeBase_var PythonNode::getRemoteInterpreterHandle()
651 return Engines::PyNodeBase::_narrow(_pynode);
654 //! Create a new node of same type with a given name
655 PythonNode* PythonNode::cloneNode(const std::string& name)
657 PythonNode* n=new PythonNode(name);
658 n->setScript(_script);
659 list<InputPort *>::iterator iter;
660 for(iter = _setOfInputPort.begin(); iter != _setOfInputPort.end(); iter++)
662 InputPyPort *p=(InputPyPort *)*iter;
663 DEBTRACE( "port name: " << p->getName() );
664 DEBTRACE( "port kind: " << p->edGetType()->kind() );
665 n->edAddInputPort(p->getName(),p->edGetType());
667 list<OutputPort *>::iterator iter2;
668 for(iter2 = _setOfOutputPort.begin(); iter2 != _setOfOutputPort.end(); iter2++)
670 OutputPyPort *p=(OutputPyPort *)*iter2;
671 DEBTRACE( "port name: " << p->getName() );
672 DEBTRACE( "port kind: " << p->edGetType()->kind() );
673 n->edAddOutputPort(p->getName(),p->edGetType());
678 PyFuncNode::PyFuncNode(const PyFuncNode& other, ComposedNode *father):InlineFuncNode(other,father),_pyfunc(0)
680 _implementation = PythonNode::IMPL_NAME;
683 _context=PyDict_New();
684 DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
685 if( PyDict_SetItemString( _context, "__builtins__", getSALOMERuntime()->getBuiltins() ))
688 msg << "Not possible to set builtins" << __FILE__ << ":" << __LINE__;
689 _errorDetails=msg.str();
690 throw Exception(msg.str());
695 PyFuncNode::PyFuncNode(const std::string& name): InlineFuncNode(name),_pyfunc(0)
698 _implementation = PythonNode::IMPL_NAME;
699 DEBTRACE( "PyFuncNode::PyFuncNode " << name );
702 _context=PyDict_New();
703 DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
704 if( PyDict_SetItemString( _context, "__builtins__", getSALOMERuntime()->getBuiltins() ))
707 msg << "Not possible to set builtins" << __FILE__ << ":" << __LINE__;
708 _errorDetails=msg.str();
709 throw Exception(msg.str());
714 PyFuncNode::~PyFuncNode()
716 if(!CORBA::is_nil(_pynode))
718 _pynode->UnRegister();
722 void PyFuncNode::checkBasicConsistency() const throw(YACS::Exception)
724 DEBTRACE("checkBasicConsistency");
725 InlineFuncNode::checkBasicConsistency();
729 res=Py_CompileString(_script.c_str(),getName().c_str(),Py_file_input);
732 std::string error="";
733 PyObject* new_stderr = newPyStdOut(error);
734 PySys_SetObject((char*)"stderr", new_stderr);
736 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
737 Py_DECREF(new_stderr);
738 throw Exception(error);
745 void PyFuncNode::load()
747 DEBTRACE( "---------------PyfuncNode::load function---------------" );
754 void PyFuncNode::loadRemote()
756 commonRemoteLoad(this);
759 void PyFuncNode::loadLocal()
761 DEBTRACE( "---------------PyFuncNode::load function " << getName() << " ---------------" );
765 list<OutputPort *>::iterator iter;
766 for(iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); iter++)
768 OutputPyPort *p=(OutputPyPort *)*iter;
769 DEBTRACE( "port name: " << p->getName() );
770 DEBTRACE( "port kind: " << p->edGetType()->kind() );
776 DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
778 std::ostringstream stream;
779 stream << "/tmp/PythonNode_";
782 PyObject* code=Py_CompileString(_script.c_str(), stream.str().c_str(), Py_file_input);
786 PyObject* new_stderr = newPyStdOut(_errorDetails);
787 PySys_SetObject((char*)"stderr", new_stderr);
789 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
790 Py_DECREF(new_stderr);
791 throw Exception("Error during execution");
793 PyObject *res = PyEval_EvalCode((PyCodeObject *)code, _context, _context);
797 DEBTRACE( "_context refcnt: " << _context->ob_refcnt );
798 if(PyErr_Occurred ())
801 PyObject* new_stderr = newPyStdOut(_errorDetails);
802 PySys_SetObject((char*)"stderr", new_stderr);
803 ofstream errorfile(stream.str().c_str());
804 if (errorfile.is_open())
806 errorfile << _script;
810 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
811 Py_DECREF(new_stderr);
812 throw Exception("Error during execution");
815 _pyfunc=PyDict_GetItemString(_context,_fname.c_str());
816 DEBTRACE( "_pyfunc refcnt: " << _pyfunc->ob_refcnt );
820 PyObject* new_stderr = newPyStdOut(_errorDetails);
821 PySys_SetObject((char*)"stderr", new_stderr);
823 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
824 Py_DECREF(new_stderr);
825 throw Exception("Error during execution");
827 DEBTRACE( "---------------End PyFuncNode::load function---------------" );
831 void PyFuncNode::execute()
839 void PyFuncNode::executeRemote()
841 DEBTRACE( "++++++++++++++ PyFuncNode::executeRemote: " << getName() << " ++++++++++++++++++++" );
843 throw Exception("DistributedPythonNode badly loaded");
845 if(dynamic_cast<HomogeneousPoolContainer *>(getContainer()))
848 commonRemoteLoadPart2(this,dummy);
851 Engines::pickledArgs_var serializationInputCorba(new Engines::pickledArgs);;
855 //===========================================================================
856 // Get inputs in input ports, build a Python tuple and pickle it
857 //===========================================================================
858 PyObject *args(PyTuple_New(getNumberOfInputPorts()));
860 for(std::list<InputPort *>::iterator iter2 = _setOfInputPort.begin(); iter2 != _setOfInputPort.end(); iter2++,pos++)
862 InputPyPort *p=(InputPyPort *)*iter2;
865 PyTuple_SetItem(args,pos,ob);
868 PyObject_Print(args,stderr,Py_PRINT_RAW);
871 PyObject *serializationInput=PyObject_CallObject(_pyfuncSer,args);
873 //The pickled string may contain NULL characters so use PyString_AsStringAndSize
874 char *serializationInputC(0);
876 if (PyString_AsStringAndSize(serializationInput, &serializationInputC, &len))
877 throw Exception("DistributedPythonNode problem in python pickle");
879 serializationInputCorba->length(len);
880 for(int i=0; i < len ; i++)
881 serializationInputCorba[i]=serializationInputC[i];
882 Py_DECREF(serializationInput);
885 //===========================================================================
886 // Execute in remote Python node
887 //===========================================================================
888 DEBTRACE( "-----------------starting remote python invocation-----------------" );
889 Engines::pickledArgs_var resultCorba;
892 resultCorba=_pynode->execute(getFname().c_str(),serializationInputCorba);
894 catch( const SALOME::SALOME_Exception& ex )
896 std::string msg="Exception on remote python invocation";
898 msg += ex.details.text.in();
900 throw Exception(msg);
902 DEBTRACE( "-----------------end of remote python invocation-----------------" );
903 //===========================================================================
904 // Get results, unpickle and put them in output ports
905 //===========================================================================
906 char *resultCorbaC=new char[resultCorba->length()+1];
907 resultCorbaC[resultCorba->length()]='\0';
908 for(int i=0;i<resultCorba->length();i++)
909 resultCorbaC[i]=resultCorba[i];
914 PyObject *resultPython(PyString_FromStringAndSize(resultCorbaC,resultCorba->length()));
915 delete [] resultCorbaC;
916 PyObject *args(PyTuple_New(1)),*ob(0);
917 PyTuple_SetItem(args,0,resultPython);
918 PyObject *finalResult=PyObject_CallObject(_pyfuncUnser,args);
921 DEBTRACE( "-----------------PythonNode::outputs-----------------" );
923 if(finalResult == Py_None)
925 else if(PyTuple_Check(finalResult))
926 nres=PyTuple_Size(finalResult);
928 if(getNumberOfOutputPorts() != nres)
930 std::string msg="Number of output arguments : Mismatch between definition and execution";
931 Py_DECREF(finalResult);
933 throw Exception(msg);
939 for(std::list<OutputPort *>::iterator iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); iter++, pos++)
941 OutputPyPort *p=(OutputPyPort *)*iter;
942 DEBTRACE( "port name: " << p->getName() );
943 DEBTRACE( "port kind: " << p->edGetType()->kind() );
944 DEBTRACE( "port pos : " << pos );
945 if(PyTuple_Check(finalResult))
946 ob=PyTuple_GetItem(finalResult,pos) ;
949 DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
952 Py_DECREF(finalResult);
954 catch(ConversionException& ex)
956 Py_DECREF(finalResult);
957 _errorDetails=ex.what();
962 DEBTRACE( "++++++++++++++ ENDOF PyFuncNode::executeRemote: " << getName() << " ++++++++++++++++++++" );
965 void PyFuncNode::executeLocal()
967 DEBTRACE( "++++++++++++++ PyFuncNode::execute: " << getName() << " ++++++++++++++++++++" );
971 if(!_pyfunc)throw Exception("PyFuncNode badly loaded");
974 DEBTRACE( "---------------PyFuncNode::inputs---------------" );
975 PyObject* args = PyTuple_New(getNumberOfInputPorts()) ;
976 list<InputPort *>::iterator iter2;
977 for(iter2 = _setOfInputPort.begin(); iter2 != _setOfInputPort.end(); iter2++)
979 InputPyPort *p=(InputPyPort *)*iter2;
980 DEBTRACE( "port name: " << p->getName() );
981 DEBTRACE( "port kind: " << p->edGetType()->kind() );
984 PyObject_Print(ob,stderr,Py_PRINT_RAW);
987 DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
989 PyTuple_SetItem(args,pos,ob);
990 DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
993 DEBTRACE( "---------------End PyFuncNode::inputs---------------" );
995 DEBTRACE( "----------------PyFuncNode::calculation---------------" );
997 PyObject_Print(_pyfunc,stderr,Py_PRINT_RAW);
999 PyObject_Print(args,stderr,Py_PRINT_RAW);
1002 DEBTRACE( "_pyfunc refcnt: " << _pyfunc->ob_refcnt );
1003 PyObject* result = PyObject_CallObject( _pyfunc , args ) ;
1004 DEBTRACE( "_pyfunc refcnt: " << _pyfunc->ob_refcnt );
1011 PyObject* new_stderr = newPyStdOut(_errorDetails);
1012 PySys_SetObject((char*)"stderr", new_stderr);
1013 std::ostringstream stream;
1014 stream << "/tmp/PythonNode_";
1016 ofstream errorfile(stream.str().c_str());
1017 if (errorfile.is_open())
1019 errorfile << _script;
1023 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
1024 Py_DECREF(new_stderr);
1025 throw Exception("Error during execution");
1027 DEBTRACE( "----------------End PyFuncNode::calculation---------------" );
1029 DEBTRACE( "-----------------PyFuncNode::outputs-----------------" );
1031 if(result == Py_None)
1033 else if(PyTuple_Check(result))
1034 nres=PyTuple_Size(result);
1036 if(getNumberOfOutputPorts() != nres)
1038 std::string msg="Number of output arguments : Mismatch between definition and execution";
1041 throw Exception(msg);
1046 PyObject_Print(result,stderr,Py_PRINT_RAW);
1049 list<OutputPort *>::iterator iter;
1052 for(iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); iter++)
1054 OutputPyPort *p=(OutputPyPort *)*iter;
1055 DEBTRACE( "port name: " << p->getName() );
1056 DEBTRACE( "port kind: " << p->edGetType()->kind() );
1057 DEBTRACE( "port pos : " << pos );
1058 if(PyTuple_Check(result))ob=PyTuple_GetItem(result,pos) ;
1060 DEBTRACE( "ob refcnt: " << ob->ob_refcnt );
1062 PyObject_Print(ob,stderr,Py_PRINT_RAW);
1069 catch(ConversionException& ex)
1072 _errorDetails=ex.what();
1075 DEBTRACE( "-----------------End PyFuncNode::outputs-----------------" );
1078 DEBTRACE( "++++++++++++++ End PyFuncNode::execute: " << getName() << " ++++++++++++++++++++" );
1081 Node *PyFuncNode::simpleClone(ComposedNode *father, bool editionOnly) const
1083 return new PyFuncNode(*this,father);
1086 void PyFuncNode::createRemoteAdaptedPyInterpretor(Engines::Container_ptr objContainer)
1088 if(!CORBA::is_nil(_pynode))
1089 _pynode->UnRegister();
1090 _pynode=objContainer->createPyNode(getName().c_str(),getScript().c_str());
1093 Engines::PyNodeBase_var PyFuncNode::retrieveDftRemotePyInterpretorIfAny(Engines::Container_ptr objContainer) const
1095 Engines::PyNode_var ret(objContainer->getDefaultPyNode());
1096 if(!CORBA::is_nil(ret))
1100 return Engines::PyNodeBase::_narrow(ret);
1103 void PyFuncNode::assignRemotePyInterpretor(Engines::PyNodeBase_var remoteInterp)
1105 if(!CORBA::is_nil(_pynode))
1107 Engines::PyNode_var tmpp(Engines::PyNode::_narrow(remoteInterp));
1108 if(_pynode->_is_equivalent(tmpp))
1111 if(!CORBA::is_nil(_pynode))
1112 _pynode->UnRegister();
1113 _pynode=Engines::PyNode::_narrow(remoteInterp);
1116 Engines::PyNodeBase_var PyFuncNode::getRemoteInterpreterHandle()
1118 return Engines::PyNodeBase::_narrow(_pynode);
1121 //! Create a new node of same type with a given name
1122 PyFuncNode* PyFuncNode::cloneNode(const std::string& name)
1124 PyFuncNode* n=new PyFuncNode(name);
1125 n->setScript(_script);
1126 n->setFname(_fname);
1127 list<InputPort *>::iterator iter;
1128 for(iter = _setOfInputPort.begin(); iter != _setOfInputPort.end(); iter++)
1130 InputPyPort *p=(InputPyPort *)*iter;
1131 n->edAddInputPort(p->getName(),p->edGetType());
1133 list<OutputPort *>::iterator iter2;
1134 for(iter2 = _setOfOutputPort.begin(); iter2 != _setOfOutputPort.end(); iter2++)
1136 OutputPyPort *p=(OutputPyPort *)*iter2;
1137 n->edAddOutputPort(p->getName(),p->edGetType());
1142 std::string PyFuncNode::getContainerLog()
1144 if(_mode=="local")return "";
1149 Engines::Container_var objContainer=((SalomeContainer*)_container)->getContainerPtr(this);
1150 CORBA::String_var logname = objContainer->logfilename();
1153 std::string::size_type pos = msg.find(":");
1154 msg=msg.substr(pos+1);
1158 msg = "Container no longer reachable";
1163 void PyFuncNode::shutdown(int level)
1165 DEBTRACE("PyFuncNode::shutdown " << level);
1166 if(_mode=="local")return;
1169 if(!CORBA::is_nil(_pynode)) _pynode->UnRegister();
1170 _pynode=Engines::PyNode::_nil();
1171 _container->shutdown(level);