1 // Copyright (C) 2007-2024 CEA, EDF, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 // SALOME Container : implementation of container and engine for Kernel
24 // File : Container_i.cxx
25 // Author : Paul RASCLE, EDF - MARC TAJCHMAN, CEA
28 //#define private public
33 #include <sys/types.h>
50 #include "utilities.h"
51 #include <SALOMEconfig.h>
52 #include CORBA_SERVER_HEADER(SALOME_Component)
53 #include CORBA_SERVER_HEADER(SALOME_Exception)
54 #include <pthread.h> // must be before Python.h !
56 #include "SALOME_Container_i.hxx"
57 #include "SALOME_Component_i.hxx"
58 #include "SALOME_FileRef_i.hxx"
59 #include "SALOME_FileTransfer_i.hxx"
60 #include "Salome_file_i.hxx"
61 #include "SALOME_NamingService.hxx"
62 #include "SALOME_Fake_NamingService.hxx"
63 #include "SALOME_Embedded_NamingService_Client.hxx"
64 #include "SALOME_Embedded_NamingService.hxx"
65 #include "Basics_Utils.hxx"
66 #include "KernelBasis.hxx"
67 #include "PythonCppUtils.hxx"
68 #include "Utils_CorbaException.hxx"
75 #include <structmember.h>
76 #include "Container_init_python.hxx"
77 #ifdef BOS26455_WITH_BOOST_PYTHON
78 #include <boost/python.hpp>
81 bool _Sleeping = false ;
83 // // Needed by multi-threaded Python --- Supervision
87 extern "C" {void ActSigIntHandler() ; }
89 extern "C" {void SigIntHandler(int, siginfo_t *, void *) ; }
91 extern "C" {void SigIntHandler( int ) ; }
97 #define ENGINESO "Engine.dylib"
99 #define ENGINESO "Engine.so"
103 #define ENGINESO "Engine.dll"
114 const int Abstract_Engines_Container_i::DFT_TIME_INTERVAL_BTW_MEASURE = 500;
116 std::map<std::string, int> Abstract_Engines_Container_i::_cntInstances_map;
117 std::map<std::string, void *> Abstract_Engines_Container_i::_library_map;
118 std::map<std::string, void *> Abstract_Engines_Container_i::_toRemove_map;
119 omni_mutex Abstract_Engines_Container_i::_numInstanceMutex ;
121 static PyObject *_pyCont = nullptr;
123 int checkifexecutable(const std::string&);
124 int findpathof(const std::string& path, std::string&, const std::string&);
126 /*! \class Engines_Container_i
127 * \brief C++ implementation of Engines::Container interface
132 //=============================================================================
134 * Default constructor, not for use
136 //=============================================================================
138 Abstract_Engines_Container_i::Abstract_Engines_Container_i () :
139 _NS(nullptr),_id(nullptr),_numInstance(0)
143 //=============================================================================
147 //=============================================================================
149 Abstract_Engines_Container_i::Abstract_Engines_Container_i (const std::string& pyContainerClsName,
151 PortableServer::POA_ptr poa,
152 char *containerName ,
153 int argc , char* argv[],
154 SALOME_NamingService_Container_Abstract *ns,
155 bool isServantAloneInProcess
157 _NS(nullptr),_py_container_name(pyContainerClsName),_id(0),_numInstance(0),_isServantAloneInProcess(isServantAloneInProcess)
159 _pid = (long)getpid();
161 if( isServantAloneInProcess )
167 std::string hostname = Kernel_Utils::GetHostname();
169 INFO_MESSAGE("Starting Container servant instance on Hostname :" << hostname << " with PID : " << getpid() ) ;
171 MESSAGE(hostname << " " << _getpid() <<
172 " Engines_Container_i starting argc " << _argc<< " Thread " << pthread_self().p ) ;
174 _isSupervContainer = false;
176 _orb = CORBA::ORB::_duplicate(orb) ;
177 _poa = PortableServer::POA::_duplicate(poa) ;
179 // Pour les containers paralleles: il ne faut pas enregistrer et activer
180 // le container generique, mais le container specialise
183 _id = _poa->activate_object(this);
184 // key point : if ns is nullptr : this servant is alone in its process
185 // if ns is not null : this servant embedded into single process.
186 _NS = ns==nullptr ? new SALOME_NamingService : ns->clone();
187 _NS->init_orb( _orb ) ;
188 CORBA::Object_var obj=_poa->id_to_reference(*_id);
189 Engines::Container_var pCont = Engines::Container::_narrow(obj);
192 _containerName = SALOME_NamingService_Abstract::BuildContainerNameForNS(containerName, hostname.c_str());
195 // import SALOME_Container
196 // pycont = SALOME_Container.SALOME_Container_i(containerIORStr)
198 CORBA::String_var sior = _orb->object_to_string(pCont);
199 std::ostringstream myCommand;
200 myCommand << "pyCont = SALOME_Container." << this->getPyContainerClassName() << "('" << _containerName << "','" << sior << "'," << DFT_TIME_INTERVAL_BTW_MEASURE << ")\n";
201 INFO_MESSAGE("Python command executed : " << myCommand.str());
203 //[RNV]: Comment the PyEval_AcquireLock() and PyEval_ReleaseLock() because this
204 //approach leads to the deadlock of the main thread of the application on Windows platform
205 //in case if cppContainer runs in the standalone mode. The problem with the PyThreadState
206 //described by ABN seems not reproduced, to be checked carefully later...
209 //// [ABN]: using the PyGILState* API here is unstable. omniORB logic is invoked
210 //// by the Python code executed below, and in some (random) cases, the Python code
211 //// execution ends with a PyThreadState which was not the one we have here.
212 //// (TODO: understand why ...)
213 //// To be on the safe side we get and load the thread state ourselves:
214 //PyEval_AcquireLock(); // get GIL
215 //PyThreadState * mainThreadState = PyThreadState_Get();
216 //PyThreadState_Swap(mainThreadState);
219 // mpv: this is temporary solution: there is a unregular crash if not
222 // first element is the path to Registry.dll, but it's wrong
223 PyRun_SimpleString("import sys\n");
224 PyRun_SimpleString("sys.path = sys.path[1:]\n");
226 PyRun_SimpleString("import SALOME_Container\n");
227 PyRun_SimpleString((char*)myCommand.str().c_str());
228 PyObject *mainmod = PyImport_AddModule("__main__");
229 PyObject *globals = PyModule_GetDict(mainmod);
230 _pyCont = PyDict_GetItemString(globals, "pyCont");
231 //PyThreadState_Swap(NULL);
232 //PyEval_ReleaseLock();
234 {// register to NS after python initialization to be sure that client invoke after py constructor execution
235 _NS->Register(pCont, _containerName.c_str());
236 DEBUG_MESSAGE("Container registred in NS as : " << _containerName);
238 fileTransfer_i* aFileTransfer = new fileTransfer_i();
239 CORBA::Object_var obref=aFileTransfer->_this();
240 _fileTransfer = Engines::fileTransfer::_narrow(obref);
241 aFileTransfer->_remove_ref();
245 //=============================================================================
249 //=============================================================================
251 Abstract_Engines_Container_i::~Abstract_Engines_Container_i()
253 MESSAGE("Abstract_Container_i::~Abstract_Container_i()");
261 //=============================================================================
262 //! Get container name
264 * CORBA attribute: Container name (see constructor)
266 //=============================================================================
268 char* Abstract_Engines_Container_i::name()
270 return CORBA::string_dup(_containerName.c_str()) ;
273 //=============================================================================
274 //! Get container working directory
276 * CORBA attribute: Container working directory
278 //=============================================================================
280 char* Abstract_Engines_Container_i::workingdir()
284 return CORBA::string_dup(wd) ;
287 //=============================================================================
288 //! Get container log file name
290 * CORBA attribute: Container log file name
292 //=============================================================================
294 char *Abstract_Engines_Container_i::logfilename()
296 return CORBA::string_dup(_logfilename.c_str()) ;
299 //! Set container log file name
300 void Abstract_Engines_Container_i::logfilename(const char* name)
305 char *Abstract_Engines_Container_i::locallogfilename()
307 return CORBA::string_dup( _localfilename.c_str() );
310 void Abstract_Engines_Container_i::locallogfilename(const char *name)
313 _localfilename = name;
314 AutoPyRef result = PyObject_CallMethod(_pyCont,(char*)"setLogFileName","s",name,nullptr);
315 if (PyErr_Occurred())
317 std::string error("can not set logfilename");
319 THROW_SALOME_CORBA_EXCEPTION(error.c_str(),SALOME::INTERNAL_ERROR);
323 CORBA::Long Abstract_Engines_Container_i::monitoringtimeresms()
326 AutoPyRef result = PyObject_CallMethod(_pyCont,(char*)"monitoringtimeresms",nullptr);
327 if (PyErr_Occurred())
329 std::string error("can not retrieve time interval between 2 measures");
331 THROW_SALOME_CORBA_EXCEPTION(error.c_str(),SALOME::INTERNAL_ERROR);
333 CORBA::Long ret = PyLong_AsLong( result );
337 void Abstract_Engines_Container_i::monitoringtimeresms(CORBA::Long intervalInMs)
340 AutoPyRef result = PyObject_CallMethod(_pyCont,(char*)"SetMonitoringtimeresms","i",intervalInMs,nullptr);
341 if (PyErr_Occurred())
343 std::string error("can not set time interval between 2 measures");
345 THROW_SALOME_CORBA_EXCEPTION(error.c_str(),SALOME::INTERNAL_ERROR);
349 void Abstract_Engines_Container_i::verbosity(bool& activated, CORBA::String_out level)
351 activated = SALOME::VerbosityActivated();
352 level = CORBA::string_dup( SALOME::VerbosityLevelStr().c_str() );
355 void Abstract_Engines_Container_i::setVerbosity(bool activated, const char *level)
357 SALOME::SetVerbosityActivated( activated );
358 SALOME::SetVerbosityLevelStr( level );
361 AutoPyRef res = PyObject_CallMethod(_pyCont,
362 (char*)"positionVerbosityOfLogger",NULL);
367 SALOME::ExceptionStruct es;
368 es.type = SALOME::INTERNAL_ERROR;
369 es.text = "can not create a python node";
370 throw SALOME::SALOME_Exception(es);
375 //=============================================================================
376 //! Get container host name
378 * CORBA method: Get the hostName of the Container (without domain extensions)
380 //=============================================================================
382 char* Abstract_Engines_Container_i::getHostName()
384 std::string s = Kernel_Utils::GetHostname();
385 // MESSAGE("Engines_Container_i::getHostName " << s);
386 return CORBA::string_dup(s.c_str()) ;
389 //=============================================================================
390 //! Get container PID
392 * CORBA method: Get the PID (process identification) of the Container
394 //=============================================================================
396 CORBA::Long Abstract_Engines_Container_i::getPID()
398 return (CORBA::Long)getpid();
401 //=============================================================================
402 //! Ping the servant to check it is still alive
404 * CORBA method: check if servant is still alive
406 //=============================================================================
407 void Abstract_Engines_Container_i::ping()
409 MESSAGE("Engines_Container_i::ping() pid "<< getpid());
412 //=============================================================================
413 //! Get number of CPU cores in the calculation node
415 * CORBA method: get number of CPU cores
417 //=============================================================================
419 CORBA::Long Abstract_Engines_Container_i::getNumberOfCPUCores()
422 PyObject *module = PyImport_ImportModuleNoBlock((char*)"salome_psutil");
423 AutoPyRef result = PyObject_CallMethod(module,
424 (char*)"getNumberOfCPUCores", NULL);
425 int n = PyLong_AsLong(result);
426 return (CORBA::Long)n;
429 //=============================================================================
430 //! Get a load of each CPU core in the calculation node
432 * CORBA method: get a load of each CPU core
434 //=============================================================================
444 PyStdOut_dealloc(PyStdOut *self)
450 PyStdOut_write(PyStdOut* self, PyObject* args)
453 if (!PyArg_ParseTuple(args, "s", &c))
456 *(self->out) = *(self->out) + c;
462 static PyMethodDef PyStdOut_methods[] =
464 {"write", (PyCFunction)PyStdOut_write, METH_VARARGS,
465 PyDoc_STR("write(string) -> None")},
466 {0, 0, 0, 0} /* sentinel */
469 static PyMemberDef PyStdOut_memberlist[] =
471 {(char*)"softspace", T_INT, offsetof(PyStdOut, softspace), 0,
472 (char*)"flag indicating that a space needs to be printed; used by print"},
473 {0, 0, 0, 0, 0} /* sentinel */
476 static PyTypeObject PyStdOut_Type =
478 /* The ob_type field must be initialized in the module init function
479 * to be portable to Windows without using C++. */
480 PyVarObject_HEAD_INIT(NULL, 0)
483 sizeof(PyStdOut), /*tp_basicsize*/
486 (destructor)PyStdOut_dealloc, /*tp_dealloc*/
493 0, /*tp_as_sequence*/
498 PyObject_GenericGetAttr, /*tp_getattro*/
499 /* softspace is writable: we must supply tp_setattro */
500 PyObject_GenericSetAttr, /* tp_setattro */
502 Py_TPFLAGS_DEFAULT, /*tp_flags*/
506 0, /*tp_richcompare*/
507 0, /*tp_weaklistoffset*/
510 PyStdOut_methods, /*tp_methods*/
511 PyStdOut_memberlist, /*tp_members*/
529 0, /*tp_version_tag*/
533 PyObject* newPyStdOut(std::string& out)
535 PyStdOut* self = PyObject_New(PyStdOut, &PyStdOut_Type);
540 return (PyObject*)self;
543 std::string parseException()
546 if (PyErr_Occurred())
548 #ifdef BOS26455_WITH_BOOST_PYTHON
549 PyObject *ptype = nullptr;
550 PyObject *pvalue = nullptr;
551 PyObject *ptraceback = nullptr;
552 PyErr_Fetch(&ptype, &pvalue, &ptraceback);
553 if (ptype == nullptr)
554 return std::string("Null exception type");
555 PyErr_NormalizeException(&ptype, &pvalue, &ptraceback);
556 if (ptraceback != nullptr)
557 PyException_SetTraceback(pvalue, ptraceback);
558 boost::python::handle<> htype(ptype);
559 boost::python::handle<> hvalue(boost::python::allow_null(pvalue));
560 boost::python::handle<> htraceback(boost::python::allow_null(ptraceback));
561 boost::python::object traceback = boost::python::import("traceback");
562 boost::python::object format_exc = traceback.attr("format_exception");
563 boost::python::object formatted = format_exc(htype, hvalue, htraceback);
564 error = boost::python::extract<std::string>(boost::python::str("\n").join(formatted));
566 PyObject* new_stderr = newPyStdOut(error);
567 PyObject* old_stderr = PySys_GetObject((char*)"stderr");
568 Py_INCREF(old_stderr);
569 PySys_SetObject((char*)"stderr", new_stderr);
571 PySys_SetObject((char*)"stderr", old_stderr);
572 Py_DECREF(new_stderr);
579 Engines::vectorOfDouble* Abstract_Engines_Container_i::loadOfCPUCores()
582 PyObject *module = PyImport_ImportModuleNoBlock((char*)"salome_psutil");
583 AutoPyRef result = PyObject_CallMethod(module,
584 (char*)"loadOfCPUCores", "s",
585 _load_script.c_str());
586 if (PyErr_Occurred())
588 std::string error = parseException();
590 SALOME::ExceptionStruct es;
591 es.type = SALOME::INTERNAL_ERROR;
592 es.text = CORBA::string_dup(error.c_str());
593 throw SALOME::SALOME_Exception(es);
596 int n = this->getNumberOfCPUCores();
597 if (!PyList_Check(result) || PyList_Size(result) != n) {
598 // bad number of cores
599 SALOME::ExceptionStruct es;
600 es.type = SALOME::INTERNAL_ERROR;
601 es.text = "wrong number of cores";
602 throw SALOME::SALOME_Exception(es);
605 Engines::vectorOfDouble_var loads = new Engines::vectorOfDouble;
607 for (Py_ssize_t i = 0; i < PyList_Size(result); ++i) {
608 PyObject* item = PyList_GetItem(result, i);
609 double foo = PyFloat_AsDouble(item);
610 if (foo < 0.0 || foo > 1.0)
612 // value not in [0, 1] range
613 SALOME::ExceptionStruct es;
614 es.type = SALOME::INTERNAL_ERROR;
615 es.text = "load not in [0, 1] range";
616 throw SALOME::SALOME_Exception(es);
621 return loads._retn();
624 //=============================================================================
625 //! Set custom script to calculate a load of each CPU core
627 * CORBA method: Set custom script to calculate CPU load
628 * \param script Python script to execute
630 //=============================================================================
632 void Abstract_Engines_Container_i::setPyScriptForCPULoad(const char *script)
634 _load_script = script;
637 //=============================================================================
638 //! Nullify custom script to calculate each CPU core's load
640 * CORBA method: reset script for load calculation to default implementation
642 //=============================================================================
644 void Abstract_Engines_Container_i::resetScriptForCPULoad()
649 //=============================================================================
650 //! Get total physical memory of calculation node, in megabytes
652 * CORBA method: get total physical memory of calculation node
654 //=============================================================================
656 CORBA::Long Abstract_Engines_Container_i::getTotalPhysicalMemory()
659 PyObject *module = PyImport_ImportModuleNoBlock((char*)"salome_psutil");
660 AutoPyRef result = PyObject_CallMethod(module,
661 (char*)"getTotalPhysicalMemory", NULL);
662 int n = PyLong_AsLong(result);
664 return (CORBA::Long)n;
667 //=============================================================================
668 //! Get used physical memory of calculation node, in megabytes
670 * CORBA method: get used physical memory of calculation node
672 //=============================================================================
674 CORBA::Long Abstract_Engines_Container_i::getTotalPhysicalMemoryInUse()
677 PyObject *module = PyImport_ImportModuleNoBlock((char*)"salome_psutil");
678 AutoPyRef result = PyObject_CallMethod(module,
679 (char*)"getTotalPhysicalMemoryInUse", NULL);
680 int n = PyLong_AsLong(result);
682 return (CORBA::Long)n;
685 //=============================================================================
686 //! Obtain physical memory, used by the current process, in megabytes.
688 * CORBA method: get physical memory, used by the current process
690 //=============================================================================
692 CORBA::Long Abstract_Engines_Container_i::getTotalPhysicalMemoryInUseByMe()
695 PyObject *module = PyImport_ImportModuleNoBlock((char*)"salome_psutil");
696 AutoPyRef result = PyObject_CallMethod(module,
697 (char*)"getTotalPhysicalMemoryInUseByMe", NULL);
698 int n = PyLong_AsLong(result);
700 return (CORBA::Long)n;
703 //=============================================================================
704 //! Shutdown the container
706 * CORBA method, oneway: Server shutdown.
707 * - Container name removed from naming service,
708 * - servant deactivation,
709 * - orb shutdown if no other servants in the process
711 //=============================================================================
712 void Abstract_Engines_Container_i::Shutdown()
714 ShutdownCommonPart();
715 if(_isServantAloneInProcess)
717 MESSAGE("Effective Shutdown of container Begins...");
720 if(!CORBA::is_nil(_orb))
726 MESSAGE("Effective Shutdown of container Ends...");
730 void Abstract_Engines_Container_i::ShutdownCommonPart()
732 MESSAGE("Engines_Container_i::Shutdown()");
734 // Clear registered temporary files
735 clearTemporaryFiles();
737 /* For each component contained in this container
738 * tell it to self-destroy
740 std::map<std::string, Engines::EngineComponent_var>::iterator itm;
741 for (itm = _listInstances_map.begin(); itm != _listInstances_map.end(); itm++)
745 itm->second->destroy();
747 catch(const CORBA::Exception&)
749 // ignore this entry and continue
753 // ignore this entry and continue
756 _listInstances_map.clear();
757 MESSAGE("Engines_Container_i::Shutdown() -- step 2");
758 // NS unregistering may throw in SSL mode if master process hosting SALOME_Embedded_NamingService servant has vanished
759 // In this case it's skip it and still continue.
762 _NS->Destroy_FullDirectory(_containerName.c_str());
763 _NS->Destroy_Name(_containerName.c_str());
768 MESSAGE("Engines_Container_i::Shutdown() -- step 3");
771 this->cleanAllPyScripts();
775 AutoPyRef result = PyObject_CallMethod(_pyCont, (char*)"shutdownPy", (char*)"",nullptr);
781 MESSAGE("Engines_Container_i::Shutdown() -- step 4");
784 void Abstract_Engines_Container_i::ShutdownNow()
786 ShutdownCommonPart();if(_isServantAloneInProcess)
789 AutoPyRef result = PyObject_CallMethod(_pyCont, (char*)"killMe", (char*)"",nullptr);
793 //=============================================================================
794 //! load a component implementation
797 * \param componentName component name
798 * \param reason explains error when load fails
799 * \return true if dlopen successful or already done, false otherwise
801 //=============================================================================
803 Abstract_Engines_Container_i::load_component_Library(const char* componentName, CORBA::String_out reason)
806 //=================================================================
807 // --- C++ implementation section
808 //=================================================================
810 if(load_component_CppImplementation(componentName,retso))
812 reason=CORBA::string_dup("");
815 else if(retso != "ImplementationNotFound")
817 reason=CORBA::string_dup(retso.c_str());
822 retso+=componentName;
823 retso+=": Can't find C++ implementation ";
824 retso+=std::string(LIB) + componentName + ENGINESO;
826 //=================================================================
827 // --- Python implementation section
828 //=================================================================
830 if(load_component_PythonImplementation(componentName,retpy))
832 reason=CORBA::string_dup("");
835 else if(retpy != "ImplementationNotFound")
837 reason=CORBA::string_dup(retpy.c_str());
842 retpy+=componentName;
843 retpy+=": Can't find python implementation ";
844 retpy+=componentName;
847 //=================================================================
848 // -- Executable implementation section
849 //=================================================================
851 if(load_component_ExecutableImplementation(componentName,retex))
853 reason=CORBA::string_dup("");
856 else if(retex != "ImplementationNotFound")
858 reason=CORBA::string_dup(retex.c_str());
863 retex+=componentName;
864 retex+=": Can't find executable implementation ";
865 retex+=componentName;
868 std::string ret="Component implementation not found: ";
869 ret += componentName ;
875 std::cerr << ret << std::endl;
876 reason=CORBA::string_dup(ret.c_str());
881 //=============================================================================
882 //! try to load a C++ component implementation
885 * \param componentName the name of the component (COMPONENT, for example)
886 * \param reason explains error when load fails
887 * \return true if loading is successful or already done, false otherwise
889 //=============================================================================
891 Abstract_Engines_Container_i::load_component_CppImplementation(const char* componentName, std::string& reason)
893 std::string aCompName(componentName);
894 std::string impl_name = std::string(LIB) + aCompName + ENGINESO;
897 _numInstanceMutex.lock(); // lock to be alone
898 // (see decInstanceCnt, finalize_removal))
899 if (_toRemove_map.count(impl_name) != 0) _toRemove_map.erase(impl_name);
900 if (_library_map.count(impl_name) != 0)
902 MESSAGE("Library " << impl_name << " already loaded");
903 _numInstanceMutex.unlock();
907 _numInstanceMutex.unlock();
911 handle = dlopen( impl_name.c_str() , RTLD_NOW | RTLD_GLOBAL ) ;
914 //not loadable. Try to find the lib file in LD_LIBRARY_PATH
917 char* p=getenv("DYLD_LIBRARY_PATH");
919 char* p=getenv("LD_LIBRARY_PATH");
922 path=path+SEP+"/usr/lib"+SEP+"/lib";
925 if(findpathof(path, pth, impl_name))
927 //found but not loadable
930 reason+=": C++ implementation found ";
932 reason+=" but it is not loadable. Error:\n";
934 std::cerr << reason << std::endl;
940 //continue with other implementation
941 reason="ImplementationNotFound";
948 std::wstring libToLoad = Kernel_Utils::utf8_decode_s( impl_name );
950 std::string libToLoad = impl_name;
952 handle = LoadLibrary(libToLoad.c_str() );
955 reason="ImplementationNotFound";
961 _numInstanceMutex.lock();
962 _library_map[impl_name] = handle;
963 _numInstanceMutex.unlock();
971 //=============================================================================
972 //! try to load a Python component implementation
975 * \param componentName name of the component
976 * \param reason explains error when load fails
977 * \return true if loading is successful or already done, false otherwise
979 //=============================================================================
981 Abstract_Engines_Container_i::load_component_PythonImplementation(const char* componentName, std::string& reason)
983 std::string aCompName(componentName);
985 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
986 if (_library_map.count(aCompName) != 0)
988 _numInstanceMutex.unlock() ;
990 return true; // Python Component, already imported
992 _numInstanceMutex.unlock() ;
996 AutoPyRef result = PyObject_CallMethod(_pyCont,
997 (char*)"import_component",
998 (char*)"s",componentName);
1000 reason=PyUnicode_AsUTF8(result);
1006 //Python component has been loaded (import componentName)
1007 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1008 _library_map[aCompName] = (void *)_pyCont; // any non O value OK
1009 _numInstanceMutex.unlock() ;
1010 MESSAGE("import Python: "<< aCompName <<" OK");
1013 else if(reason=="ImplementationNotFound")
1015 //Python implementation has not been found. Continue with other implementation
1016 reason="ImplementationNotFound";
1020 //Python implementation has been found but loading has failed
1021 std::cerr << reason << std::endl;
1026 //=============================================================================
1027 //! try to load a Executable component implementation
1030 * \param componentName name of the component
1031 * \param reason explains error when load fails
1032 * \return true if loading is successful or already done, false otherwise
1034 //=============================================================================
1036 Abstract_Engines_Container_i::load_component_ExecutableImplementation(const char* componentName, std::string& reason)
1038 std::string aCompName(componentName);
1039 std::string executable=aCompName+".exe";
1044 char* p=getenv("PATH");
1047 if (findpathof(path, pth, executable))
1049 if(checkifexecutable(pth))
1051 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1052 _library_map[executable] = (void *)1; // any non O value OK
1053 _numInstanceMutex.unlock() ;
1054 MESSAGE("import executable: "<< pth <<" OK");
1058 reason="Component ";
1060 reason+=": implementation found ";
1062 reason+=" but it is not executable";
1063 std::cerr << reason << std::endl;
1067 reason="ImplementationNotFound";
1072 //=============================================================================
1073 //! Create a new component instance
1075 * CORBA method: Creates a new servant instance of a component.
1076 * The servant registers itself to naming service and Registry.tdlib
1077 * \param genericRegisterName Name of the component instance to register
1078 * in Registry & Name Service (without _inst_n suffix)
1079 * \return a loaded component
1081 //=============================================================================
1082 Engines::EngineComponent_ptr
1083 Abstract_Engines_Container_i::create_component_instance(const char*genericRegisterName)
1085 Engines::FieldsDict_var env = new Engines::FieldsDict;
1087 Engines::EngineComponent_ptr compo =
1088 create_component_instance_env(genericRegisterName, env, reason);
1089 CORBA::string_free(reason);
1093 void EffectiveOverrideEnvironment( const Engines::FieldsDict& env )
1095 MESSAGE("Positionning environment on container ");
1096 for (CORBA::ULong i=0; i < env.length(); i++)
1098 if (env[i].value.type()->kind() == CORBA::tk_string)
1100 const char *value = nullptr;
1101 env[i].value >>= value;
1102 MESSAGE( env[i].key << " = " << value);
1104 if( setenv(env[i].key,value,1) != 0 )
1107 std::string sErr( strerror( errsv) );
1115 std::vector< std::pair<std::string,std::string> > GetOSEnvironment()
1117 std::vector< std::pair<std::string,std::string> > ret;
1119 char **envPt( environ );
1120 for(;*envPt != nullptr; ++envPt)
1122 std::string s( *envPt );
1123 auto pos = s.find_first_of('=');
1124 std::string k( s.substr(0,pos) ),v( s.substr(pos+1) );
1125 ret.emplace_back( std::pair<std::string,std::string>(k,v) );
1131 void Abstract_Engines_Container_i::override_environment( const Engines::FieldsDict& env )
1133 EffectiveOverrideEnvironment(env);
1136 void Abstract_Engines_Container_i::override_environment_python( const Engines::FieldsDict& env )
1138 constexpr char NODE_NAME[] = "ScriptNodeForEnv";
1139 constexpr char SCRIPT[] = R"foo(
1144 Engines::PyScriptNode_var scriptNode = this->createPyScriptNode(NODE_NAME,SCRIPT);
1145 auto sz = env.length();
1146 Engines::listofstring keys, vals;
1147 keys.length( sz ); vals.length( sz );
1148 for( auto i = 0 ; i < sz ; ++i )
1150 keys[i] = CORBA::string_dup( env[i].key );
1151 const char *value = nullptr;
1152 env[i].value >>= value;
1153 vals[i] = CORBA::string_dup( value );
1155 scriptNode->executeSimple(keys,vals);
1156 this->removePyScriptNode(NODE_NAME);
1159 Engines::FieldsDict *Abstract_Engines_Container_i::get_os_environment()
1161 std::unique_ptr<Engines::FieldsDict> ret( new Engines::FieldsDict );
1162 std::vector< std::pair<std::string,std::string> > retCpp( GetOSEnvironment() );
1163 auto sz = retCpp.size();
1165 for(auto i = 0 ; i < sz ; ++i)
1167 (*ret)[i].key = CORBA::string_dup( retCpp[i].first.c_str() );
1168 (*ret)[i].value <<= CORBA::string_dup( retCpp[i].second.c_str() );
1170 return ret.release();
1173 void Abstract_Engines_Container_i::set_big_obj_on_disk_threshold(CORBA::Long thresholdInByte)
1175 SALOME::SetBigObjOnDiskThreshold(thresholdInByte);
1178 void Abstract_Engines_Container_i::set_big_obj_on_disk_directory(const char *directory)
1180 SALOME::SetBigObjOnDiskDirectory(directory);
1183 Engines::vectorOfString_var FromVecStringCppToCORBA( const std::vector<std::string>& group)
1185 Engines::vectorOfString_var ret( new Engines::vectorOfString );
1186 auto sz( group.size() );
1188 for(auto i = 0 ; i < sz ; ++i)
1190 ret[i] = CORBA::string_dup( group[i].c_str() );
1195 std::vector<std::string> FromCORBAVecStringToCpp(const Engines::vectorOfString& groupOfLogFileNames)
1197 auto len = groupOfLogFileNames.length();
1198 std::vector<std::string> ret( len );
1199 for( auto i = 0 ; i < len ; ++i )
1201 ret[i] = groupOfLogFileNames[i];
1206 void Abstract_Engines_Container_i::addLogFileNameGroup(const Engines::vectorOfString& groupOfLogFileNames)
1208 this->_groups_of_log_files.push_back( FromCORBAVecStringToCpp(groupOfLogFileNames) );
1211 Engines::vectorOfVectorOfString *Abstract_Engines_Container_i::getAllLogFileNameGroups()
1213 std::unique_ptr<Engines::vectorOfVectorOfString> ret( new Engines::vectorOfVectorOfString );
1214 auto nbOfGrps = this->_groups_of_log_files.size();
1215 ret->length( nbOfGrps );
1216 for(auto i = 0 ; i < nbOfGrps ; ++i)
1218 (*ret)[i] = FromVecStringCppToCORBA( _groups_of_log_files[i] );
1220 return ret.release();
1223 void Abstract_Engines_Container_i::execute_python_code(const char *code)
1226 if( PyRun_SimpleString( code ) != 0 )
1228 std::string error = parseException();
1229 THROW_SALOME_CORBA_EXCEPTION(error.c_str(),SALOME::INTERNAL_ERROR);
1233 //=============================================================================
1234 //! Create a new component instance with environment variables specified
1236 * CORBA method: Creates a new servant instance of a component.
1237 * The servant registers itself to naming service and Registry.
1238 * \param genericRegisterName Name of the component instance to register
1239 * in Registry & Name Service (without _inst_n suffix)
1240 * \param env dict of env variables
1241 * \param reason explains error when create_component_instance_env fails
1242 * \return a loaded component
1244 //=============================================================================
1245 Engines::EngineComponent_ptr
1246 Abstract_Engines_Container_i::create_component_instance_env(const char*genericRegisterName,
1247 const Engines::FieldsDict& env,
1248 CORBA::String_out reason)
1251 if (_library_map.count(genericRegisterName) != 0)
1253 // It's a Python component
1254 Engines::EngineComponent_ptr compo = createPythonInstance(genericRegisterName, error);
1255 reason=CORBA::string_dup(error.c_str());
1259 std::string impl_name = std::string(LIB) + genericRegisterName + ENGINESO;
1260 if (_library_map.count(impl_name) != 0)
1262 // It's a C++ component
1263 void* handle = _library_map[impl_name];
1264 Engines::EngineComponent_ptr compo = createInstance(genericRegisterName, handle, error);
1265 reason=CORBA::string_dup(error.c_str());
1269 impl_name = std::string(genericRegisterName) + ".exe";
1270 if (_library_map.count(impl_name) != 0)
1272 //It's an executable component
1273 Engines::EngineComponent_ptr compo = createExecutableInstance(genericRegisterName, env, error);
1274 reason=CORBA::string_dup(error.c_str());
1278 error="load_component_Library has probably not been called for component: ";
1279 error += genericRegisterName;
1281 reason=CORBA::string_dup(error.c_str());
1282 return Engines::EngineComponent::_nil() ;
1285 //=============================================================================
1286 //! Create a new component instance (Executable implementation)
1288 * \param CompName Name of the component instance
1289 * \param env dict of env variables
1290 * \param reason explains error when creation fails
1291 * \return a loaded component
1293 * This component is implemented in an executable with name genericRegisterName.exe
1294 * It must register itself in Naming Service. The container waits some time (10 s max)
1295 * it's registration.
1297 //=============================================================================
1298 Engines::EngineComponent_ptr
1299 Abstract_Engines_Container_i::createExecutableInstance(std::string CompName,
1300 const Engines::FieldsDict& env,
1301 std::string& reason)
1303 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1305 _numInstanceMutex.lock() ; // lock on the instance number
1307 int numInstance = _numInstance ;
1308 _numInstanceMutex.unlock() ;
1311 sprintf( aNumI , "%d" , numInstance ) ;
1312 std::string instanceName = CompName + "_inst_" + aNumI ;
1313 std::string component_registerName = _containerName + "/" + instanceName;
1315 //check if an entry exist in naming service
1316 CORBA::Object_var nsobj = _NS->Resolve(component_registerName.c_str());
1317 if ( !CORBA::is_nil(nsobj) )
1319 // unregister the registered component
1320 _NS->Destroy_Name(component_registerName.c_str());
1321 //kill or shutdown it ???
1324 // first arg container ior string
1325 // second arg container name
1326 // third arg instance name
1328 Engines::Container_var pCont= _this();
1329 CORBA::String_var sior = _orb->object_to_string(pCont);
1331 std::string command;
1332 command="mkdir -p ";
1333 command+=instanceName;
1335 command+=instanceName;
1340 command+= sior; // container ior string
1342 command+=_containerName; //container name
1344 command+=instanceName; //instance name
1346 MESSAGE("SALOME_Container::create_component_instance command=" << command);
1349 // use fork/execl instead of system to get finer control on env variables
1352 if(pid == 0) // child
1354 EffectiveOverrideEnvironment(env);
1356 execl("/bin/sh", "sh", "-c", command.c_str() , (char *)0);
1359 else if(pid < 0) // failed to fork
1368 tpid = wait(&status);
1369 } while (tpid != pid);
1372 // launch component with a system call
1373 int status=system(command.c_str());
1378 reason="SALOME_Container::create_component_instance system failed (system command status -1)";
1380 return Engines::EngineComponent::_nil();
1383 else if (WEXITSTATUS(status) == 217)
1385 reason="SALOME_Container::create_component_instance system failed (system command status 217)";
1387 return Engines::EngineComponent::_nil();
1393 if (getenv("TIMEOUT_TO_WAIT_EXE_COMPONENT") != 0)
1395 std::string new_count_str = getenv("TIMEOUT_TO_WAIT_EXE_COMPONENT");
1397 std::istringstream ss(new_count_str);
1398 if (!(ss >> new_count))
1400 INFOS("[Container] TIMEOUT_TO_WAIT_EXE_COMPONENT should be an int");
1405 INFOS("[Container] waiting " << count << " second steps exe component ");
1406 CORBA::Object_var obj = CORBA::Object::_nil() ;
1407 while ( CORBA::is_nil(obj) && count )
1415 MESSAGE( count << ". Waiting for component " << CompName);
1416 obj = _NS->Resolve(component_registerName.c_str());
1419 if(CORBA::is_nil(obj))
1421 reason="SALOME_Container::create_component_instance failed";
1423 return Engines::EngineComponent::_nil();
1427 MESSAGE("SALOME_Container::create_component_instance successful");
1428 iobject = Engines::EngineComponent::_narrow(obj);
1429 _listInstances_map[instanceName] = iobject;
1430 return iobject._retn();
1436 //=============================================================================
1437 //! Create a new component instance (Python implementation)
1439 * \param CompName Name of the component instance
1440 * \param reason explains error when creation fails
1441 * \return a loaded component
1443 //=============================================================================
1444 Engines::EngineComponent_ptr
1445 Abstract_Engines_Container_i::createPythonInstance(std::string CompName,
1446 std::string& reason)
1448 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1450 _numInstanceMutex.lock() ; // lock on the instance number
1452 int numInstance = _numInstance ;
1453 _numInstanceMutex.unlock() ;
1456 sprintf( aNumI , "%d" , numInstance ) ;
1457 std::string instanceName = CompName + "_inst_" + aNumI ;
1458 std::string component_registerName = _containerName + "/" + instanceName;
1462 AutoPyRef result = PyObject_CallMethod(_pyCont,
1463 (char*)"create_component_instance",
1466 instanceName.c_str());
1469 PyArg_ParseTuple(result,"ss", &ior, &error);
1476 CORBA::Object_var obj = _orb->string_to_object(iors.c_str());
1477 iobject = Engines::EngineComponent::_narrow( obj ) ;
1478 _listInstances_map[instanceName] = iobject;
1480 return iobject._retn();
1484 Abstract_Engines_Container_i::create_python_service_instance(const char * CompName,
1485 CORBA::String_out reason)
1487 CORBA::Object_var object = CORBA::Object::_nil();
1489 _numInstanceMutex.lock() ; // lock on the instance number
1491 int numInstance = _numInstance ;
1492 _numInstanceMutex.unlock() ;
1495 sprintf( aNumI , "%d" , numInstance ) ;
1496 std::string instanceName = std::string(CompName) + "_inst_" + aNumI ;
1497 std::string component_registerName = _containerName + "/" + instanceName;
1499 char * _ior = nullptr;
1502 AutoPyRef result = PyObject_CallMethod(_pyCont,
1503 (char*)"create_component_instance",
1506 instanceName.c_str());
1509 PyArg_ParseTuple(result,"ss", &ior, &error);
1510 reason = CORBA::string_dup(error);
1511 _ior = CORBA::string_dup(ior);
1517 //=============================================================================
1518 //! Create a new component instance (C++ implementation)
1520 * C++ method: create a servant instance of a component.
1521 * \param genericRegisterName Name of the component instance to register
1522 * in Registry & Name Service,
1523 * (without _inst_n suffix, like "COMPONENT")
1524 * \param handle loaded library handle
1525 * \param reason explains error when creation fails
1526 * \return a loaded component
1528 * example with names:
1529 * - aGenRegisterName = COMPONENT (= first argument)
1530 * - _containerName = /Containers/cli76ce/FactoryServer
1531 * - factoryName = COMPONENTEngine_factory
1532 * - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
1533 * - instanceName = COMPONENT_inst_1
1534 * - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1536 //=============================================================================
1537 Engines::EngineComponent_ptr
1538 Abstract_Engines_Container_i::createInstance(std::string genericRegisterName,
1540 std::string& reason)
1542 // --- find the factory
1544 std::string aGenRegisterName = genericRegisterName;
1545 std::string factory_name = aGenRegisterName + std::string("Engine_factory");
1546 SCRUTE(factory_name) ;
1548 typedef PortableServer::ObjectId* (*FACTORY_FUNCTION) (CORBA::ORB_ptr,
1549 PortableServer::POA_ptr,
1550 PortableServer::ObjectId *,
1555 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)dlsym( handle, factory_name.c_str() );
1557 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)GetProcAddress( (HINSTANCE)handle, factory_name.c_str() );
1560 if ( !Component_factory )
1562 MESSAGE( "Can't resolve symbol: " + factory_name );
1567 return Engines::EngineComponent::_nil() ;
1570 // --- create instance
1572 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1576 _numInstanceMutex.lock() ; // lock on the instance number
1578 int numInstance = _numInstance ;
1579 _numInstanceMutex.unlock() ;
1582 sprintf( aNumI , "%d" , numInstance ) ;
1583 std::string instanceName = aGenRegisterName + "_inst_" + aNumI ;
1584 std::string component_registerName =
1585 _containerName + "/" + instanceName;
1587 // --- Instantiate required CORBA object
1589 PortableServer::ObjectId *id ; //not owner, do not delete (nore use var)
1590 id = (Component_factory) ( _orb, _poa, _id, instanceName.c_str(),
1591 aGenRegisterName.c_str() ) ;
1594 reason="Can't get ObjectId from factory";
1596 return iobject._retn();
1599 // --- get reference from id
1601 CORBA::Object_var obj = _poa->id_to_reference(*id);
1602 iobject = Engines::EngineComponent::_narrow( obj ) ;
1604 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1605 _listInstances_map[instanceName] = iobject;
1606 _cntInstances_map[aGenRegisterName] += 1;
1607 _numInstanceMutex.unlock() ;
1608 SCRUTE(aGenRegisterName);
1609 SCRUTE(_cntInstances_map[aGenRegisterName]);
1611 // --- register the engine under the name
1612 // containerName(.dir)/instanceName(.object)
1614 _NS->Register( iobject , component_registerName.c_str() ) ;
1615 MESSAGE( component_registerName.c_str() << " bound" ) ;
1619 reason="Container_i::createInstance exception caught";
1622 return iobject._retn();
1625 //=============================================================================
1626 //! Find an existing (in the container) component instance
1628 * CORBA method: Finds a servant instance of a component
1629 * \param registeredName Name of the component in Registry or Name Service,
1630 * without instance suffix number
1631 * \return the first found instance
1633 //=============================================================================
1634 Engines::EngineComponent_ptr
1635 Abstract_Engines_Container_i::find_component_instance( const char* registeredName)
1637 Engines::EngineComponent_var anEngine = Engines::EngineComponent::_nil();
1638 std::map<std::string,Engines::EngineComponent_var>::iterator itm =_listInstances_map.begin();
1639 while (itm != _listInstances_map.end())
1641 std::string instance = (*itm).first;
1643 if (instance.find(registeredName) == 0)
1645 anEngine = (*itm).second;
1646 return anEngine._retn();
1650 return anEngine._retn();
1653 //=============================================================================
1654 //! Remove the component instance from container
1656 * CORBA method: Stops the component servant, and deletes all related objects
1657 * \param component_i Component to be removed
1659 //=============================================================================
1661 void Abstract_Engines_Container_i::remove_impl(Engines::EngineComponent_ptr component_i)
1663 ASSERT(! CORBA::is_nil(component_i));
1664 std::string instanceName = component_i->instanceName() ;
1665 MESSAGE("unload component " << instanceName);
1666 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1667 _listInstances_map.erase(instanceName);
1668 _numInstanceMutex.unlock() ;
1669 component_i->destroy() ;
1670 _NS->Destroy_Name(instanceName.c_str());
1673 //=============================================================================
1674 //! Unload component libraries from the container
1676 * CORBA method: Discharges unused libraries from the container.
1678 //=============================================================================
1679 void Abstract_Engines_Container_i::finalize_removal()
1681 MESSAGE("finalize unload : dlclose");
1682 _numInstanceMutex.lock(); // lock to be alone
1683 // (see decInstanceCnt, load_component_Library)
1684 std::map<std::string, void *>::iterator ith;
1685 for (ith = _toRemove_map.begin(); ith != _toRemove_map.end(); ith++)
1687 void *handle = (*ith).second;
1688 std::string impl_name= (*ith).first;
1693 // dlclose(handle); // SALOME unstable after ...
1694 // _library_map.erase(impl_name);
1697 _toRemove_map.clear();
1698 _numInstanceMutex.unlock();
1701 //=============================================================================
1702 //! Decrement component instance reference count
1706 //=============================================================================
1707 void Abstract_Engines_Container_i::decInstanceCnt(std::string genericRegisterName)
1709 if(_cntInstances_map.count(genericRegisterName)==0)
1711 std::string aGenRegisterName =genericRegisterName;
1712 MESSAGE("Engines_Container_i::decInstanceCnt " << aGenRegisterName);
1713 ASSERT(_cntInstances_map[aGenRegisterName] > 0);
1714 _numInstanceMutex.lock(); // lock to be alone
1715 // (see finalize_removal, load_component_Library)
1716 _cntInstances_map[aGenRegisterName] -= 1;
1717 SCRUTE(_cntInstances_map[aGenRegisterName]);
1718 if (_cntInstances_map[aGenRegisterName] == 0)
1720 std::string impl_name =
1721 Engines_Component_i::GetDynLibraryName(aGenRegisterName.c_str());
1723 void* handle = _library_map[impl_name];
1725 _toRemove_map[impl_name] = handle;
1727 _numInstanceMutex.unlock();
1730 //=============================================================================
1731 //! Find or create a new component instance
1733 * CORBA method: find or create an instance of the component (servant),
1734 * load a new component class (dynamic library) if required,
1736 * ---- FOR COMPATIBILITY WITH 2.2 ----
1738 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
1740 * The servant registers itself to naming service and Registry.
1741 * \param genericRegisterName Name of the component to register
1742 * in Registry & Name Service
1743 * \param componentName Name of the constructed library of the component
1744 * \return a loaded component
1746 //=============================================================================
1748 Engines::EngineComponent_ptr
1749 Abstract_Engines_Container_i::load_impl( const char* genericRegisterName,
1750 const char* /*componentName*/ )
1753 std::string impl_name = std::string(LIB) + genericRegisterName + ENGINESO;
1754 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1755 if (load_component_Library(genericRegisterName,reason))
1756 iobject = find_or_create_instance(genericRegisterName, impl_name);
1757 CORBA::string_free(reason);
1758 return iobject._retn();
1761 Engines::EmbeddedNamingService_ptr Abstract_Engines_Container_i::get_embedded_NS_if_ssl()
1763 SALOME_Embedded_NamingService_Client *nsc(dynamic_cast<SALOME_Embedded_NamingService_Client *>(this->_NS));
1766 Engines::EmbeddedNamingService_var obj = nsc->GetObject();
1767 return Engines::EmbeddedNamingService::_duplicate(obj);
1771 SALOME_Fake_NamingService *fns(dynamic_cast<SALOME_Fake_NamingService *>(this->_NS));
1774 Engines::EmbeddedNamingService_var ret = GetEmbeddedNamingService();
1778 return Engines::EmbeddedNamingService::_nil();
1782 //=============================================================================
1783 //! Finds an already existing component instance or create a new instance
1785 * C++ method: Finds an already existing servant instance of a component, or
1786 * create an instance.
1787 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
1788 * \param genericRegisterName Name of the component instance to register
1789 * in Registry & Name Service,
1790 * (without _inst_n suffix, like "COMPONENT")
1791 * \param componentLibraryName like "libCOMPONENTEngine.so"
1792 * \return a loaded component
1794 * example with names:
1795 * - aGenRegisterName = COMPONENT (= first argument)
1796 * - impl_name = libCOMPONENTEngine.so (= second argument)
1797 * - _containerName = /Containers/cli76ce/FactoryServer
1798 * - factoryName = COMPONENTEngine_factory
1799 * - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
1800 * - instanceName = COMPONENT_inst_1
1801 * - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1803 //=============================================================================
1805 Engines::EngineComponent_ptr
1806 Abstract_Engines_Container_i::find_or_create_instance(std::string genericRegisterName,
1807 std::string componentLibraryName)
1809 std::string aGenRegisterName = genericRegisterName;
1810 std::string impl_name = componentLibraryName;
1811 if (_library_map.count(impl_name) == 0)
1813 INFOS("shared library " << impl_name <<" must be loaded before creating instance");
1814 return Engines::EngineComponent::_nil() ;
1818 // --- find a registered instance in naming service, or create
1820 void* handle = _library_map[impl_name];
1821 std::string component_registerBase =
1822 _containerName + "/" + aGenRegisterName;
1823 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1827 CORBA::Object_var obj =
1828 _NS->ResolveFirst( component_registerBase.c_str());
1829 if ( CORBA::is_nil( obj ) )
1831 iobject = createInstance(genericRegisterName,
1837 iobject = Engines::EngineComponent::_narrow( obj ) ;
1842 INFOS( "Container_i::load_impl caught" ) ;
1844 return iobject._retn();
1848 //=============================================================================
1849 //! Indicate if container is a python one
1851 * Retrieves only with container naming convention if it is a python container
1853 //=============================================================================
1854 bool Abstract_Engines_Container_i::isPythonContainer(const char* ContainerName)
1857 size_t len=strlen(ContainerName);
1859 if(strcmp(ContainerName+len-2,"Py")==0)
1864 //=============================================================================
1865 //! Kill the container
1867 * CORBA method: Kill the container process with exit(0).
1868 * To remove : never returns !
1870 //=============================================================================
1871 bool Abstract_Engines_Container_i::Kill_impl()
1873 MESSAGE("Engines_Container_i::Kill() pid "<< getpid() << " containerName "
1874 << _containerName.c_str() << " machineName "
1875 << Kernel_Utils::GetHostname().c_str());
1876 INFOS("===============================================================");
1877 INFOS("= REMOVE calls to Kill_impl in C++ container =");
1878 INFOS("===============================================================");
1884 //=============================================================================
1888 //=============================================================================
1889 void ActSigIntHandler()
1892 struct sigaction SigIntAct ;
1893 SigIntAct.sa_sigaction = &SigIntHandler ;
1894 sigemptyset(&SigIntAct.sa_mask);
1895 SigIntAct.sa_flags = SA_SIGINFO ;
1898 // DEBUG 03.02.2005 : the first parameter of sigaction is not a mask of signals
1899 // (SIGINT | SIGUSR1) :
1900 // it must be only one signal ===> one call for SIGINT
1901 // and an other one for SIGUSR1
1904 if ( sigaction( SIGINT , &SigIntAct, NULL ) )
1906 perror("SALOME_Container main ") ;
1909 if ( sigaction( SIGUSR1 , &SigIntAct, NULL ) )
1911 perror("SALOME_Container main ") ;
1914 if ( sigaction( SIGUSR2 , &SigIntAct, NULL ) )
1916 perror("SALOME_Container main ") ;
1920 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1921 // use of streams (and so on) should never be used because :
1922 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1923 // A stream operation may be interrupted by a signal and if the Handler use stream we
1924 // may have a "Dead-Lock" ===HangUp
1925 //==INFOS is commented
1926 // INFOS(pthread_self() << "SigIntHandler activated") ;
1929 signal( SIGINT, SigIntHandler );
1930 // legacy code required to supervisor. Commented in order to avoid problems on Windows
1931 // signal( SIGUSR1, SigIntHandler );
1937 void CallCancelThread() ;
1940 void SigIntHandler(int /*what*/ ,
1941 siginfo_t * siginfo ,
1944 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1945 // use of streams (and so on) should never be used because :
1946 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1947 // A stream operation may be interrupted by a signal and if the Handler use stream we
1948 // may have a "Dead-Lock" ===HangUp
1949 //==MESSAGE is commented
1950 // MESSAGE(pthread_self() << "SigIntHandler what " << what << std::endl
1951 // << " si_signo " << siginfo->si_signo << std::endl
1952 // << " si_code " << siginfo->si_code << std::endl
1953 // << " si_pid " << siginfo->si_pid) ;
1958 // MESSAGE("SigIntHandler END sleeping.") ;
1963 ActSigIntHandler() ;
1964 if ( siginfo->si_signo == SIGUSR1 )
1968 else if ( siginfo->si_signo == SIGUSR2 )
1970 CallCancelThread() ;
1975 // MESSAGE("SigIntHandler BEGIN sleeping.") ;
1982 // MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1988 void SigIntHandler( int what )
1991 MESSAGE( pthread_self() << "SigIntHandler what " << what << std::endl );
1993 MESSAGE( "SigIntHandler what " << what << std::endl );
1998 MESSAGE("SigIntHandler END sleeping.") ;
2003 ActSigIntHandler() ;
2004 if ( what == SIGUSR1 )
2011 MESSAGE("SigIntHandler BEGIN sleeping.") ;
2018 MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
2025 //=============================================================================
2026 //! Get or create a file reference object associated to a local file (to transfer it)
2028 * CORBA method: get or create a fileRef object associated to a local file
2029 * (a file on the computer on which runs the container server), which stores
2030 * a list of (machine, localFileName) corresponding to copies already done.
2032 * \param origFileName absolute path for a local file to copy on other
2034 * \return a fileRef object associated to the file.
2036 //=============================================================================
2037 Engines::fileRef_ptr
2038 Abstract_Engines_Container_i::createFileRef(const char* origFileName)
2040 std::string origName(origFileName);
2041 Engines::fileRef_var theFileRef = Engines::fileRef::_nil();
2043 if (origName[0] != '/')
2045 INFOS("path of file to copy must be an absolute path beginning with '/'");
2046 return Engines::fileRef::_nil();
2049 if (CORBA::is_nil(_fileRef_map[origName]))
2051 CORBA::Object_var obj=_poa->id_to_reference(*_id);
2052 Engines::Container_var pCont = Engines::Container::_narrow(obj);
2053 fileRef_i* aFileRef = new fileRef_i(pCont, origFileName);
2054 theFileRef = Engines::fileRef::_narrow(aFileRef->_this());
2055 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
2056 _fileRef_map[origName] = theFileRef;
2057 _numInstanceMutex.unlock() ;
2060 theFileRef = Engines::fileRef::_duplicate(_fileRef_map[origName]);
2061 ASSERT(! CORBA::is_nil(theFileRef));
2062 return theFileRef._retn();
2065 //=============================================================================
2066 //! Get a fileTransfer reference
2069 * \return a reference to the fileTransfer object
2071 //=============================================================================
2072 Engines::fileTransfer_ptr
2073 Abstract_Engines_Container_i::getFileTransfer()
2075 Engines::fileTransfer_var aFileTransfer
2076 = Engines::fileTransfer::_duplicate(_fileTransfer);
2077 return aFileTransfer._retn();
2080 //=============================================================================
2081 //! Create a Salome file
2082 //=============================================================================
2083 Engines::Salome_file_ptr
2084 Abstract_Engines_Container_i::createSalome_file(const char* origFileName)
2086 std::string origName(origFileName);
2087 if (CORBA::is_nil(_Salome_file_map[origName]))
2089 Salome_file_i* aSalome_file = new Salome_file_i();
2090 aSalome_file->setContainer(Engines::Container::_duplicate(this->_this()));
2093 aSalome_file->setLocalFile(origFileName);
2094 aSalome_file->recvFiles();
2096 catch (const SALOME::SALOME_Exception& /*e*/) //!< TODO: unused variable
2098 return Engines::Salome_file::_nil();
2101 Engines::Salome_file_var theSalome_file = Engines::Salome_file::_nil();
2102 theSalome_file = Engines::Salome_file::_narrow(aSalome_file->_this());
2103 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
2104 _Salome_file_map[origName] = theSalome_file;
2105 _numInstanceMutex.unlock() ;
2108 Engines::Salome_file_ptr theSalome_file =
2109 Engines::Salome_file::_duplicate(_Salome_file_map[origName]);
2110 ASSERT(!CORBA::is_nil(theSalome_file));
2111 return theSalome_file;
2114 //=============================================================================
2115 /*! \brief copy a file from a remote host (container) to the local host
2116 * \param container the remote container
2117 * \param remoteFile the file to copy locally from the remote host into localFile
2118 * \param localFile the local file
2120 //=============================================================================
2121 void Abstract_Engines_Container_i::copyFile(Engines::Container_ptr container, const char* remoteFile, const char* localFile)
2123 Engines::fileTransfer_var fileTransfer = container->getFileTransfer();
2126 if ((fp = fopen(localFile,"wb")) == NULL)
2128 INFOS("file " << localFile << " cannot be open for writing");
2132 CORBA::Long fileId = fileTransfer->open(remoteFile);
2135 Engines::fileBlock* aBlock;
2142 aBlock = fileTransfer->getBlock(fileId);
2143 toFollow = aBlock->length();
2145 CORBA::Octet *buf = aBlock->get_buffer();
2146 fwrite(buf, sizeof(CORBA::Octet), toFollow, fp);
2150 MESSAGE("end of transfer");
2151 fileTransfer->close(fileId);
2155 INFOS("open reference file for copy impossible");
2159 //=============================================================================
2160 /*! \brief create a PyNode object to execute remote python code
2161 * \param nodeName the name of the node
2162 * \param code the python code to load
2163 * \return the PyNode
2165 //=============================================================================
2166 Engines::PyNode_ptr Abstract_Engines_Container_i::createPyNode(const char* nodeName, const char* code)
2168 Engines::PyNode_var node= Engines::PyNode::_nil();
2173 PyObject *res = PyObject_CallMethod(_pyCont,
2174 (char*)"create_pynode",
2182 SALOME::ExceptionStruct es;
2183 es.type = SALOME::INTERNAL_ERROR;
2184 es.text = "can not create a python node";
2185 throw SALOME::SALOME_Exception(es);
2187 ierr=PyLong_AsLong(PyTuple_GetItem(res,0));
2188 PyObject* result=PyTuple_GetItem(res,1);
2189 astr = PyUnicode_AsUTF8(result);
2194 Utils_Locker lck(&_mutexForDftPy);
2195 CORBA::Object_var obj=_orb->string_to_object(astr.c_str());
2196 node=Engines::PyNode::_narrow(obj);
2197 std::map<std::string,Engines::PyNode_var>::iterator it(_dftPyNode.find(nodeName));
2198 if(it==_dftPyNode.end())
2200 _dftPyNode[nodeName]=node;
2204 Engines::PyNode_var oldNode((*it).second);
2205 if(!CORBA::is_nil(oldNode))
2206 oldNode->UnRegister();
2209 if(!CORBA::is_nil(node))
2211 return node._retn();
2215 SALOME::ExceptionStruct es;
2216 es.type = SALOME::INTERNAL_ERROR;
2217 es.text = astr.c_str();
2218 throw SALOME::SALOME_Exception(es);
2222 //=============================================================================
2223 /*! \brief Retrieves the last created PyNode instance with createPyNode.
2226 //=============================================================================
2227 Engines::PyNode_ptr Abstract_Engines_Container_i::getDefaultPyNode(const char *nodeName)
2229 Utils_Locker lck(&_mutexForDftPy);
2230 std::map<std::string,Engines::PyNode_var>::iterator it(_dftPyNode.find(nodeName));
2231 if(it==_dftPyNode.end())
2232 return Engines::PyNode::_nil();
2235 Engines::PyNode_var tmpVar((*it).second);
2236 if(!CORBA::is_nil(tmpVar))
2237 return Engines::PyNode::_duplicate(tmpVar);
2239 return Engines::PyNode::_nil();
2243 //=============================================================================
2244 /*! \brief create a PyScriptNode object to execute remote python code
2245 * \param nodeName the name of the node
2246 * \param code the python code to load
2247 * \return the PyScriptNode
2249 //=============================================================================
2250 Engines::PyScriptNode_ptr Abstract_Engines_Container_i::createPyScriptNode(const char* nodeName, const char* code)
2252 Engines::PyScriptNode_var node= Engines::PyScriptNode::_nil();
2257 AutoPyRef res = PyObject_CallMethod(_pyCont,
2258 (char*)"create_pyscriptnode",
2266 SALOME::ExceptionStruct es;
2267 es.type = SALOME::INTERNAL_ERROR;
2268 es.text = "can not create a python node";
2269 throw SALOME::SALOME_Exception(es);
2271 ierr=PyLong_AsLong(PyTuple_GetItem(res,0));
2272 PyObject* result=PyTuple_GetItem(res,1);
2273 astr = PyUnicode_AsUTF8(result);
2278 Utils_Locker lck(&_mutexForDftPy);
2279 CORBA::Object_var obj=_orb->string_to_object(astr.c_str());
2280 node=Engines::PyScriptNode::_narrow(obj);
2281 std::map<std::string,Engines::PyScriptNode_var>::iterator it(_dftPyScriptNode.find(nodeName));
2282 if(it==_dftPyScriptNode.end())
2284 _dftPyScriptNode[nodeName]=node;
2288 Engines::PyScriptNode_var oldNode((*it).second);
2289 if(!CORBA::is_nil(oldNode))
2290 oldNode->UnRegister();
2293 return node._retn();
2297 SALOME::ExceptionStruct es;
2298 es.type = SALOME::INTERNAL_ERROR;
2299 es.text = astr.c_str();
2300 throw SALOME::SALOME_Exception(es);
2304 void Abstract_Engines_Container_i::removePyScriptNode(const char *nodeName)
2306 std::map<std::string,Engines::PyScriptNode_var>::iterator it(_dftPyScriptNode.find(nodeName));
2307 if(it==_dftPyScriptNode.end())
2309 std::ostringstream oss; oss << "Engines_Container_i::removePyScriptNode : node \"" << nodeName << "\" is not map !";
2310 SALOME::ExceptionStruct es;
2311 es.type = SALOME::INTERNAL_ERROR;
2312 es.text = oss.str().c_str();
2313 throw SALOME::SALOME_Exception(es);
2315 (*it).second->UnRegister();
2316 _dftPyScriptNode.erase(it);
2319 void Abstract_Engines_Container_i::cleanAllPyScripts()
2321 for(std::map<std::string,Engines::PyNode_var>::iterator it=_dftPyNode.begin();it!=_dftPyNode.end();it++)
2323 Engines::PyNode_var tmpVar((*it).second);
2324 if(!CORBA::is_nil(tmpVar))
2325 tmpVar->UnRegister();
2328 for(std::map<std::string,Engines::PyScriptNode_var>::iterator it=_dftPyScriptNode.begin();it!=_dftPyScriptNode.end();it++)
2330 Engines::PyScriptNode_var tmpVar((*it).second);
2331 if(!CORBA::is_nil(tmpVar))
2332 tmpVar->UnRegister();
2334 _dftPyScriptNode.clear();
2337 //=============================================================================
2338 /*! \brief Retrieves the last created PyScriptNode instance with createPyScriptNode.
2341 //=============================================================================
2342 Engines::PyScriptNode_ptr Abstract_Engines_Container_i::getDefaultPyScriptNode(const char *nodeName)
2344 Utils_Locker lck(&_mutexForDftPy);
2345 std::map<std::string,Engines::PyScriptNode_var>::iterator it(_dftPyScriptNode.find(nodeName));
2346 if(it==_dftPyScriptNode.end())
2347 return Engines::PyScriptNode::_nil();
2350 Engines::PyScriptNode_var tmpVar((*it).second);
2351 if(!CORBA::is_nil(tmpVar))
2352 return Engines::PyScriptNode::_duplicate(tmpVar);
2354 return Engines::PyScriptNode::_nil();
2358 //=============================================================================
2359 /* int checkifexecutable(const char *filename)
2361 * Return non-zero if the name is an executable file, and
2362 * zero if it is not executable, or if it does not exist.
2364 //=============================================================================
2365 int checkifexecutable(const std::string& filename)
2368 struct stat statinfo;
2370 result = stat(filename.c_str(), &statinfo);
2371 if (result < 0) return 0;
2372 if (!S_ISREG(statinfo.st_mode)) return 0;
2377 if (statinfo.st_uid == geteuid()) return statinfo.st_mode & S_IXUSR;
2378 if (statinfo.st_gid == getegid()) return statinfo.st_mode & S_IXGRP;
2379 return statinfo.st_mode & S_IXOTH;
2384 //=============================================================================
2385 /*! \brief Find a file by searching in a path
2386 * \param filename file name to search
2387 * \param path path to search in
2388 * \param pth the complete file path if found
2389 * \return 1 if found 0 if not
2391 //=============================================================================
2392 int findpathof(const std::string& path, std::string& pth, const std::string& filename)
2394 if ( path.size() == 0 ) return 0;
2396 std::string::size_type offset = 0;
2397 std::string::size_type pos = 0;
2399 struct stat statinfo;
2403 pos = path.find( SEP, offset );
2404 pth = path.substr( offset, pos - offset );
2405 if ( pth.size() > 0 )
2407 if( pth[pth.size()-1] != SLASH ) pth += SLASH;
2409 int result=stat(pth.c_str(), &statinfo);
2410 if(result == 0) found=1;
2412 if (pos == std::string::npos) break;
2418 void Abstract_Engines_Container_i::registerTemporaryFile( const std::string& fileName )
2420 _tmp_files.remove( fileName );
2421 _tmp_files.push_back( fileName );
2424 void Abstract_Engines_Container_i::unregisterTemporaryFile( const std::string& fileName )
2426 _tmp_files.remove( fileName );
2429 void Abstract_Engines_Container_i::clearTemporaryFiles()
2431 std::list<std::string>::const_iterator it;
2432 for ( it = _tmp_files.begin(); it != _tmp_files.end(); ++it ) {
2433 #if defined(WIN32) && defined(UNICODE)
2434 std::wstring aFile = Kernel_Utils::utf8_decode_s(*it);
2435 std::wstring command = (GetFileAttributes(aFile.c_str()) == FILE_ATTRIBUTE_DIRECTORY) ? L"rd /Q \"" : L"del /F /Q \"";
2437 command += L"\" 2>NUL";
2438 _wsystem(command.c_str());
2441 std::string aFile = *it;
2442 std::string command = (GetFileAttributes(aFile.c_str()) == FILE_ATTRIBUTE_DIRECTORY) ? "rd /Q \"" : "del /F /Q \"";
2444 command += "\" 2>NUL";
2446 std::string command = "rm -rf ";
2449 system(command.c_str());
2455 static Engines_Container_SSL_i *_container_singleton_ssl = nullptr;
2457 static Engines::Container_var _container_ref_singleton_ssl;
2459 Abstract_Engines_Container_SSL_i *KERNEL::getContainerSA()
2461 if(!_container_singleton_ssl)
2463 CORBA::ORB_var orb = KERNEL::GetRefToORB();
2464 CORBA::Object_var obj = orb->resolve_initial_references("RootPOA");
2465 PortableServer::POA_var poa = PortableServer::POA::_narrow(obj);
2466 PortableServer::POAManager_var pman = poa->the_POAManager();
2467 CORBA::PolicyList policies;
2470 constexpr int ARGC = 4;
2471 constexpr const char *ARGV[ARGC] = {"Container","FactoryServer","toto",nullptr};
2472 std::unique_ptr<char*[]> argv( new char *[ARGC+1] );
2473 std::vector< std::unique_ptr<char[]> > argvv(ARGC);
2474 argv[ARGC] = nullptr;
2475 for(int i = 0 ; i < ARGC ; ++i)
2479 argvv[i].reset( new char[strlen(ARGV[i])+1] );
2480 strcpy(argvv[i].get(),ARGV[i]);
2481 argv[i] = argvv[i].get();
2486 SALOME_Fake_NamingService ns;
2487 _container_singleton_ssl = new Engines_Container_SSL_i(orb,poa,(char *)"FactoryServer",2,argv.get(),&ns,false);
2488 PortableServer::ObjectId * cont_id = _container_singleton_ssl->getCORBAId();
2490 CORBA::Object_var zeRef = poa->id_to_reference(*cont_id);
2491 _container_ref_singleton_ssl = Engines::Container::_narrow(zeRef);
2493 return _container_singleton_ssl;
2496 Engines::Container_var KERNEL::getContainerRefSA()
2499 return _container_ref_singleton_ssl;