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 void Abstract_Engines_Container_i::set_number_of_retry(CORBA::Long nbRetry)
1185 SALOME::SetNumberOfRetry( nbRetry );
1188 void Abstract_Engines_Container_i::set_directory_for_replay_files(const char *directory)
1190 SALOME::SetDirectoryForReplayFiles( directory );
1193 void Abstract_Engines_Container_i::set_startup_code(const char *codeAtStartUp)
1195 _code_at_startup = codeAtStartUp;
1198 char *Abstract_Engines_Container_i::get_startup_code()
1200 return CORBA::string_dup( this->_code_at_startup.c_str() );
1203 Engines::vectorOfString_var FromVecStringCppToCORBA( const std::vector<std::string>& group)
1205 Engines::vectorOfString_var ret( new Engines::vectorOfString );
1206 auto sz( group.size() );
1208 for(auto i = 0 ; i < sz ; ++i)
1210 ret[i] = CORBA::string_dup( group[i].c_str() );
1215 std::vector<std::string> FromCORBAVecStringToCpp(const Engines::vectorOfString& groupOfLogFileNames)
1217 auto len = groupOfLogFileNames.length();
1218 std::vector<std::string> ret( len );
1219 for( auto i = 0 ; i < len ; ++i )
1221 ret[i] = groupOfLogFileNames[i];
1226 void Abstract_Engines_Container_i::addLogFileNameGroup(const Engines::vectorOfString& groupOfLogFileNames)
1228 this->_groups_of_log_files.push_back( FromCORBAVecStringToCpp(groupOfLogFileNames) );
1231 Engines::vectorOfVectorOfString *Abstract_Engines_Container_i::getAllLogFileNameGroups()
1233 std::unique_ptr<Engines::vectorOfVectorOfString> ret( new Engines::vectorOfVectorOfString );
1234 auto nbOfGrps = this->_groups_of_log_files.size();
1235 ret->length( nbOfGrps );
1236 for(auto i = 0 ; i < nbOfGrps ; ++i)
1238 (*ret)[i] = FromVecStringCppToCORBA( _groups_of_log_files[i] );
1240 return ret.release();
1243 void Abstract_Engines_Container_i::execute_python_code(const char *code)
1246 if( PyRun_SimpleString( code ) != 0 )
1248 std::string error = parseException();
1249 THROW_SALOME_CORBA_EXCEPTION(error.c_str(),SALOME::INTERNAL_ERROR);
1253 //=============================================================================
1254 //! Create a new component instance with environment variables specified
1256 * CORBA method: Creates a new servant instance of a component.
1257 * The servant registers itself to naming service and Registry.
1258 * \param genericRegisterName Name of the component instance to register
1259 * in Registry & Name Service (without _inst_n suffix)
1260 * \param env dict of env variables
1261 * \param reason explains error when create_component_instance_env fails
1262 * \return a loaded component
1264 //=============================================================================
1265 Engines::EngineComponent_ptr
1266 Abstract_Engines_Container_i::create_component_instance_env(const char*genericRegisterName,
1267 const Engines::FieldsDict& env,
1268 CORBA::String_out reason)
1271 if (_library_map.count(genericRegisterName) != 0)
1273 // It's a Python component
1274 Engines::EngineComponent_ptr compo = createPythonInstance(genericRegisterName, error);
1275 reason=CORBA::string_dup(error.c_str());
1279 std::string impl_name = std::string(LIB) + genericRegisterName + ENGINESO;
1280 if (_library_map.count(impl_name) != 0)
1282 // It's a C++ component
1283 void* handle = _library_map[impl_name];
1284 Engines::EngineComponent_ptr compo = createInstance(genericRegisterName, handle, error);
1285 reason=CORBA::string_dup(error.c_str());
1289 impl_name = std::string(genericRegisterName) + ".exe";
1290 if (_library_map.count(impl_name) != 0)
1292 //It's an executable component
1293 Engines::EngineComponent_ptr compo = createExecutableInstance(genericRegisterName, env, error);
1294 reason=CORBA::string_dup(error.c_str());
1298 error="load_component_Library has probably not been called for component: ";
1299 error += genericRegisterName;
1301 reason=CORBA::string_dup(error.c_str());
1302 return Engines::EngineComponent::_nil() ;
1305 //=============================================================================
1306 //! Create a new component instance (Executable implementation)
1308 * \param CompName Name of the component instance
1309 * \param env dict of env variables
1310 * \param reason explains error when creation fails
1311 * \return a loaded component
1313 * This component is implemented in an executable with name genericRegisterName.exe
1314 * It must register itself in Naming Service. The container waits some time (10 s max)
1315 * it's registration.
1317 //=============================================================================
1318 Engines::EngineComponent_ptr
1319 Abstract_Engines_Container_i::createExecutableInstance(std::string CompName,
1320 const Engines::FieldsDict& env,
1321 std::string& reason)
1323 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1325 _numInstanceMutex.lock() ; // lock on the instance number
1327 int numInstance = _numInstance ;
1328 _numInstanceMutex.unlock() ;
1331 sprintf( aNumI , "%d" , numInstance ) ;
1332 std::string instanceName = CompName + "_inst_" + aNumI ;
1333 std::string component_registerName = _containerName + "/" + instanceName;
1335 //check if an entry exist in naming service
1336 CORBA::Object_var nsobj = _NS->Resolve(component_registerName.c_str());
1337 if ( !CORBA::is_nil(nsobj) )
1339 // unregister the registered component
1340 _NS->Destroy_Name(component_registerName.c_str());
1341 //kill or shutdown it ???
1344 // first arg container ior string
1345 // second arg container name
1346 // third arg instance name
1348 Engines::Container_var pCont= _this();
1349 CORBA::String_var sior = _orb->object_to_string(pCont);
1351 std::string command;
1352 command="mkdir -p ";
1353 command+=instanceName;
1355 command+=instanceName;
1360 command+= sior; // container ior string
1362 command+=_containerName; //container name
1364 command+=instanceName; //instance name
1366 MESSAGE("SALOME_Container::create_component_instance command=" << command);
1369 // use fork/execl instead of system to get finer control on env variables
1372 if(pid == 0) // child
1374 EffectiveOverrideEnvironment(env);
1376 execl("/bin/sh", "sh", "-c", command.c_str() , (char *)0);
1379 else if(pid < 0) // failed to fork
1388 tpid = wait(&status);
1389 } while (tpid != pid);
1392 // launch component with a system call
1393 int status=system(command.c_str());
1398 reason="SALOME_Container::create_component_instance system failed (system command status -1)";
1400 return Engines::EngineComponent::_nil();
1403 else if (WEXITSTATUS(status) == 217)
1405 reason="SALOME_Container::create_component_instance system failed (system command status 217)";
1407 return Engines::EngineComponent::_nil();
1413 if (getenv("TIMEOUT_TO_WAIT_EXE_COMPONENT") != 0)
1415 std::string new_count_str = getenv("TIMEOUT_TO_WAIT_EXE_COMPONENT");
1417 std::istringstream ss(new_count_str);
1418 if (!(ss >> new_count))
1420 INFOS("[Container] TIMEOUT_TO_WAIT_EXE_COMPONENT should be an int");
1425 INFOS("[Container] waiting " << count << " second steps exe component ");
1426 CORBA::Object_var obj = CORBA::Object::_nil() ;
1427 while ( CORBA::is_nil(obj) && count )
1435 MESSAGE( count << ". Waiting for component " << CompName);
1436 obj = _NS->Resolve(component_registerName.c_str());
1439 if(CORBA::is_nil(obj))
1441 reason="SALOME_Container::create_component_instance failed";
1443 return Engines::EngineComponent::_nil();
1447 MESSAGE("SALOME_Container::create_component_instance successful");
1448 iobject = Engines::EngineComponent::_narrow(obj);
1449 _listInstances_map[instanceName] = iobject;
1450 return iobject._retn();
1456 //=============================================================================
1457 //! Create a new component instance (Python implementation)
1459 * \param CompName Name of the component instance
1460 * \param reason explains error when creation fails
1461 * \return a loaded component
1463 //=============================================================================
1464 Engines::EngineComponent_ptr
1465 Abstract_Engines_Container_i::createPythonInstance(std::string CompName,
1466 std::string& reason)
1468 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1470 _numInstanceMutex.lock() ; // lock on the instance number
1472 int numInstance = _numInstance ;
1473 _numInstanceMutex.unlock() ;
1476 sprintf( aNumI , "%d" , numInstance ) ;
1477 std::string instanceName = CompName + "_inst_" + aNumI ;
1478 std::string component_registerName = _containerName + "/" + instanceName;
1482 AutoPyRef result = PyObject_CallMethod(_pyCont,
1483 (char*)"create_component_instance",
1486 instanceName.c_str());
1489 PyArg_ParseTuple(result,"ss", &ior, &error);
1496 CORBA::Object_var obj = _orb->string_to_object(iors.c_str());
1497 iobject = Engines::EngineComponent::_narrow( obj ) ;
1498 _listInstances_map[instanceName] = iobject;
1500 return iobject._retn();
1504 Abstract_Engines_Container_i::create_python_service_instance(const char * CompName,
1505 CORBA::String_out reason)
1507 CORBA::Object_var object = CORBA::Object::_nil();
1509 _numInstanceMutex.lock() ; // lock on the instance number
1511 int numInstance = _numInstance ;
1512 _numInstanceMutex.unlock() ;
1515 sprintf( aNumI , "%d" , numInstance ) ;
1516 std::string instanceName = std::string(CompName) + "_inst_" + aNumI ;
1517 std::string component_registerName = _containerName + "/" + instanceName;
1519 char * _ior = nullptr;
1522 AutoPyRef result = PyObject_CallMethod(_pyCont,
1523 (char*)"create_component_instance",
1526 instanceName.c_str());
1529 PyArg_ParseTuple(result,"ss", &ior, &error);
1530 reason = CORBA::string_dup(error);
1531 _ior = CORBA::string_dup(ior);
1537 //=============================================================================
1538 //! Create a new component instance (C++ implementation)
1540 * C++ method: create a servant instance of a component.
1541 * \param genericRegisterName Name of the component instance to register
1542 * in Registry & Name Service,
1543 * (without _inst_n suffix, like "COMPONENT")
1544 * \param handle loaded library handle
1545 * \param reason explains error when creation fails
1546 * \return a loaded component
1548 * example with names:
1549 * - aGenRegisterName = COMPONENT (= first argument)
1550 * - _containerName = /Containers/cli76ce/FactoryServer
1551 * - factoryName = COMPONENTEngine_factory
1552 * - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
1553 * - instanceName = COMPONENT_inst_1
1554 * - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1556 //=============================================================================
1557 Engines::EngineComponent_ptr
1558 Abstract_Engines_Container_i::createInstance(std::string genericRegisterName,
1560 std::string& reason)
1562 // --- find the factory
1564 std::string aGenRegisterName = genericRegisterName;
1565 std::string factory_name = aGenRegisterName + std::string("Engine_factory");
1566 SCRUTE(factory_name) ;
1568 typedef PortableServer::ObjectId* (*FACTORY_FUNCTION) (CORBA::ORB_ptr,
1569 PortableServer::POA_ptr,
1570 PortableServer::ObjectId *,
1575 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)dlsym( handle, factory_name.c_str() );
1577 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)GetProcAddress( (HINSTANCE)handle, factory_name.c_str() );
1580 if ( !Component_factory )
1582 MESSAGE( "Can't resolve symbol: " + factory_name );
1587 return Engines::EngineComponent::_nil() ;
1590 // --- create instance
1592 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1596 _numInstanceMutex.lock() ; // lock on the instance number
1598 int numInstance = _numInstance ;
1599 _numInstanceMutex.unlock() ;
1602 sprintf( aNumI , "%d" , numInstance ) ;
1603 std::string instanceName = aGenRegisterName + "_inst_" + aNumI ;
1604 std::string component_registerName =
1605 _containerName + "/" + instanceName;
1607 // --- Instantiate required CORBA object
1609 PortableServer::ObjectId *id ; //not owner, do not delete (nore use var)
1610 id = (Component_factory) ( _orb, _poa, _id, instanceName.c_str(),
1611 aGenRegisterName.c_str() ) ;
1614 reason="Can't get ObjectId from factory";
1616 return iobject._retn();
1619 // --- get reference from id
1621 CORBA::Object_var obj = _poa->id_to_reference(*id);
1622 iobject = Engines::EngineComponent::_narrow( obj ) ;
1624 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1625 _listInstances_map[instanceName] = iobject;
1626 _cntInstances_map[aGenRegisterName] += 1;
1627 _numInstanceMutex.unlock() ;
1628 SCRUTE(aGenRegisterName);
1629 SCRUTE(_cntInstances_map[aGenRegisterName]);
1631 // --- register the engine under the name
1632 // containerName(.dir)/instanceName(.object)
1634 _NS->Register( iobject , component_registerName.c_str() ) ;
1635 MESSAGE( component_registerName.c_str() << " bound" ) ;
1639 reason="Container_i::createInstance exception caught";
1642 return iobject._retn();
1645 //=============================================================================
1646 //! Find an existing (in the container) component instance
1648 * CORBA method: Finds a servant instance of a component
1649 * \param registeredName Name of the component in Registry or Name Service,
1650 * without instance suffix number
1651 * \return the first found instance
1653 //=============================================================================
1654 Engines::EngineComponent_ptr
1655 Abstract_Engines_Container_i::find_component_instance( const char* registeredName)
1657 Engines::EngineComponent_var anEngine = Engines::EngineComponent::_nil();
1658 std::map<std::string,Engines::EngineComponent_var>::iterator itm =_listInstances_map.begin();
1659 while (itm != _listInstances_map.end())
1661 std::string instance = (*itm).first;
1663 if (instance.find(registeredName) == 0)
1665 anEngine = (*itm).second;
1666 return anEngine._retn();
1670 return anEngine._retn();
1673 //=============================================================================
1674 //! Remove the component instance from container
1676 * CORBA method: Stops the component servant, and deletes all related objects
1677 * \param component_i Component to be removed
1679 //=============================================================================
1681 void Abstract_Engines_Container_i::remove_impl(Engines::EngineComponent_ptr component_i)
1683 ASSERT(! CORBA::is_nil(component_i));
1684 std::string instanceName = component_i->instanceName() ;
1685 MESSAGE("unload component " << instanceName);
1686 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1687 _listInstances_map.erase(instanceName);
1688 _numInstanceMutex.unlock() ;
1689 component_i->destroy() ;
1690 _NS->Destroy_Name(instanceName.c_str());
1693 //=============================================================================
1694 //! Unload component libraries from the container
1696 * CORBA method: Discharges unused libraries from the container.
1698 //=============================================================================
1699 void Abstract_Engines_Container_i::finalize_removal()
1701 MESSAGE("finalize unload : dlclose");
1702 _numInstanceMutex.lock(); // lock to be alone
1703 // (see decInstanceCnt, load_component_Library)
1704 std::map<std::string, void *>::iterator ith;
1705 for (ith = _toRemove_map.begin(); ith != _toRemove_map.end(); ith++)
1707 void *handle = (*ith).second;
1708 std::string impl_name= (*ith).first;
1713 // dlclose(handle); // SALOME unstable after ...
1714 // _library_map.erase(impl_name);
1717 _toRemove_map.clear();
1718 _numInstanceMutex.unlock();
1721 //=============================================================================
1722 //! Decrement component instance reference count
1726 //=============================================================================
1727 void Abstract_Engines_Container_i::decInstanceCnt(std::string genericRegisterName)
1729 if(_cntInstances_map.count(genericRegisterName)==0)
1731 std::string aGenRegisterName =genericRegisterName;
1732 MESSAGE("Engines_Container_i::decInstanceCnt " << aGenRegisterName);
1733 ASSERT(_cntInstances_map[aGenRegisterName] > 0);
1734 _numInstanceMutex.lock(); // lock to be alone
1735 // (see finalize_removal, load_component_Library)
1736 _cntInstances_map[aGenRegisterName] -= 1;
1737 SCRUTE(_cntInstances_map[aGenRegisterName]);
1738 if (_cntInstances_map[aGenRegisterName] == 0)
1740 std::string impl_name =
1741 Engines_Component_i::GetDynLibraryName(aGenRegisterName.c_str());
1743 void* handle = _library_map[impl_name];
1745 _toRemove_map[impl_name] = handle;
1747 _numInstanceMutex.unlock();
1750 //=============================================================================
1751 //! Find or create a new component instance
1753 * CORBA method: find or create an instance of the component (servant),
1754 * load a new component class (dynamic library) if required,
1756 * ---- FOR COMPATIBILITY WITH 2.2 ----
1758 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
1760 * The servant registers itself to naming service and Registry.
1761 * \param genericRegisterName Name of the component to register
1762 * in Registry & Name Service
1763 * \param componentName Name of the constructed library of the component
1764 * \return a loaded component
1766 //=============================================================================
1768 Engines::EngineComponent_ptr
1769 Abstract_Engines_Container_i::load_impl( const char* genericRegisterName,
1770 const char* /*componentName*/ )
1773 std::string impl_name = std::string(LIB) + genericRegisterName + ENGINESO;
1774 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1775 if (load_component_Library(genericRegisterName,reason))
1776 iobject = find_or_create_instance(genericRegisterName, impl_name);
1777 CORBA::string_free(reason);
1778 return iobject._retn();
1781 Engines::EmbeddedNamingService_ptr Abstract_Engines_Container_i::get_embedded_NS_if_ssl()
1783 SALOME_Embedded_NamingService_Client *nsc(dynamic_cast<SALOME_Embedded_NamingService_Client *>(this->_NS));
1786 Engines::EmbeddedNamingService_var obj = nsc->GetObject();
1787 return Engines::EmbeddedNamingService::_duplicate(obj);
1791 SALOME_Fake_NamingService *fns(dynamic_cast<SALOME_Fake_NamingService *>(this->_NS));
1794 Engines::EmbeddedNamingService_var ret = GetEmbeddedNamingService();
1798 return Engines::EmbeddedNamingService::_nil();
1802 //=============================================================================
1803 //! Finds an already existing component instance or create a new instance
1805 * C++ method: Finds an already existing servant instance of a component, or
1806 * create an instance.
1807 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
1808 * \param genericRegisterName Name of the component instance to register
1809 * in Registry & Name Service,
1810 * (without _inst_n suffix, like "COMPONENT")
1811 * \param componentLibraryName like "libCOMPONENTEngine.so"
1812 * \return a loaded component
1814 * example with names:
1815 * - aGenRegisterName = COMPONENT (= first argument)
1816 * - impl_name = libCOMPONENTEngine.so (= second argument)
1817 * - _containerName = /Containers/cli76ce/FactoryServer
1818 * - factoryName = COMPONENTEngine_factory
1819 * - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
1820 * - instanceName = COMPONENT_inst_1
1821 * - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1823 //=============================================================================
1825 Engines::EngineComponent_ptr
1826 Abstract_Engines_Container_i::find_or_create_instance(std::string genericRegisterName,
1827 std::string componentLibraryName)
1829 std::string aGenRegisterName = genericRegisterName;
1830 std::string impl_name = componentLibraryName;
1831 if (_library_map.count(impl_name) == 0)
1833 INFOS("shared library " << impl_name <<" must be loaded before creating instance");
1834 return Engines::EngineComponent::_nil() ;
1838 // --- find a registered instance in naming service, or create
1840 void* handle = _library_map[impl_name];
1841 std::string component_registerBase =
1842 _containerName + "/" + aGenRegisterName;
1843 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1847 CORBA::Object_var obj =
1848 _NS->ResolveFirst( component_registerBase.c_str());
1849 if ( CORBA::is_nil( obj ) )
1851 iobject = createInstance(genericRegisterName,
1857 iobject = Engines::EngineComponent::_narrow( obj ) ;
1862 INFOS( "Container_i::load_impl caught" ) ;
1864 return iobject._retn();
1868 //=============================================================================
1869 //! Indicate if container is a python one
1871 * Retrieves only with container naming convention if it is a python container
1873 //=============================================================================
1874 bool Abstract_Engines_Container_i::isPythonContainer(const char* ContainerName)
1877 size_t len=strlen(ContainerName);
1879 if(strcmp(ContainerName+len-2,"Py")==0)
1884 //=============================================================================
1885 //! Kill the container
1887 * CORBA method: Kill the container process with exit(0).
1888 * To remove : never returns !
1890 //=============================================================================
1891 bool Abstract_Engines_Container_i::Kill_impl()
1893 MESSAGE("Engines_Container_i::Kill() pid "<< getpid() << " containerName "
1894 << _containerName.c_str() << " machineName "
1895 << Kernel_Utils::GetHostname().c_str());
1896 INFOS("===============================================================");
1897 INFOS("= REMOVE calls to Kill_impl in C++ container =");
1898 INFOS("===============================================================");
1904 //=============================================================================
1908 //=============================================================================
1909 void ActSigIntHandler()
1912 struct sigaction SigIntAct ;
1913 SigIntAct.sa_sigaction = &SigIntHandler ;
1914 sigemptyset(&SigIntAct.sa_mask);
1915 SigIntAct.sa_flags = SA_SIGINFO ;
1918 // DEBUG 03.02.2005 : the first parameter of sigaction is not a mask of signals
1919 // (SIGINT | SIGUSR1) :
1920 // it must be only one signal ===> one call for SIGINT
1921 // and an other one for SIGUSR1
1924 if ( sigaction( SIGINT , &SigIntAct, NULL ) )
1926 perror("SALOME_Container main ") ;
1929 if ( sigaction( SIGUSR1 , &SigIntAct, NULL ) )
1931 perror("SALOME_Container main ") ;
1934 if ( sigaction( SIGUSR2 , &SigIntAct, NULL ) )
1936 perror("SALOME_Container main ") ;
1940 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1941 // use of streams (and so on) should never be used because :
1942 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1943 // A stream operation may be interrupted by a signal and if the Handler use stream we
1944 // may have a "Dead-Lock" ===HangUp
1945 //==INFOS is commented
1946 // INFOS(pthread_self() << "SigIntHandler activated") ;
1949 signal( SIGINT, SigIntHandler );
1950 // legacy code required to supervisor. Commented in order to avoid problems on Windows
1951 // signal( SIGUSR1, SigIntHandler );
1957 void CallCancelThread() ;
1960 void SigIntHandler(int /*what*/ ,
1961 siginfo_t * siginfo ,
1964 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1965 // use of streams (and so on) should never be used because :
1966 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1967 // A stream operation may be interrupted by a signal and if the Handler use stream we
1968 // may have a "Dead-Lock" ===HangUp
1969 //==MESSAGE is commented
1970 // MESSAGE(pthread_self() << "SigIntHandler what " << what << std::endl
1971 // << " si_signo " << siginfo->si_signo << std::endl
1972 // << " si_code " << siginfo->si_code << std::endl
1973 // << " si_pid " << siginfo->si_pid) ;
1978 // MESSAGE("SigIntHandler END sleeping.") ;
1983 ActSigIntHandler() ;
1984 if ( siginfo->si_signo == SIGUSR1 )
1988 else if ( siginfo->si_signo == SIGUSR2 )
1990 CallCancelThread() ;
1995 // MESSAGE("SigIntHandler BEGIN sleeping.") ;
2002 // MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
2008 void SigIntHandler( int what )
2011 MESSAGE( pthread_self() << "SigIntHandler what " << what << std::endl );
2013 MESSAGE( "SigIntHandler what " << what << std::endl );
2018 MESSAGE("SigIntHandler END sleeping.") ;
2023 ActSigIntHandler() ;
2024 if ( what == SIGUSR1 )
2031 MESSAGE("SigIntHandler BEGIN sleeping.") ;
2038 MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
2045 //=============================================================================
2046 //! Get or create a file reference object associated to a local file (to transfer it)
2048 * CORBA method: get or create a fileRef object associated to a local file
2049 * (a file on the computer on which runs the container server), which stores
2050 * a list of (machine, localFileName) corresponding to copies already done.
2052 * \param origFileName absolute path for a local file to copy on other
2054 * \return a fileRef object associated to the file.
2056 //=============================================================================
2057 Engines::fileRef_ptr
2058 Abstract_Engines_Container_i::createFileRef(const char* origFileName)
2060 std::string origName(origFileName);
2061 Engines::fileRef_var theFileRef = Engines::fileRef::_nil();
2063 if (origName[0] != '/')
2065 INFOS("path of file to copy must be an absolute path beginning with '/'");
2066 return Engines::fileRef::_nil();
2069 if (CORBA::is_nil(_fileRef_map[origName]))
2071 CORBA::Object_var obj=_poa->id_to_reference(*_id);
2072 Engines::Container_var pCont = Engines::Container::_narrow(obj);
2073 fileRef_i* aFileRef = new fileRef_i(pCont, origFileName);
2074 theFileRef = Engines::fileRef::_narrow(aFileRef->_this());
2075 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
2076 _fileRef_map[origName] = theFileRef;
2077 _numInstanceMutex.unlock() ;
2080 theFileRef = Engines::fileRef::_duplicate(_fileRef_map[origName]);
2081 ASSERT(! CORBA::is_nil(theFileRef));
2082 return theFileRef._retn();
2085 //=============================================================================
2086 //! Get a fileTransfer reference
2089 * \return a reference to the fileTransfer object
2091 //=============================================================================
2092 Engines::fileTransfer_ptr
2093 Abstract_Engines_Container_i::getFileTransfer()
2095 Engines::fileTransfer_var aFileTransfer
2096 = Engines::fileTransfer::_duplicate(_fileTransfer);
2097 return aFileTransfer._retn();
2100 //=============================================================================
2101 //! Create a Salome file
2102 //=============================================================================
2103 Engines::Salome_file_ptr
2104 Abstract_Engines_Container_i::createSalome_file(const char* origFileName)
2106 std::string origName(origFileName);
2107 if (CORBA::is_nil(_Salome_file_map[origName]))
2109 Salome_file_i* aSalome_file = new Salome_file_i();
2110 aSalome_file->setContainer(Engines::Container::_duplicate(this->_this()));
2113 aSalome_file->setLocalFile(origFileName);
2114 aSalome_file->recvFiles();
2116 catch (const SALOME::SALOME_Exception& /*e*/) //!< TODO: unused variable
2118 return Engines::Salome_file::_nil();
2121 Engines::Salome_file_var theSalome_file = Engines::Salome_file::_nil();
2122 theSalome_file = Engines::Salome_file::_narrow(aSalome_file->_this());
2123 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
2124 _Salome_file_map[origName] = theSalome_file;
2125 _numInstanceMutex.unlock() ;
2128 Engines::Salome_file_ptr theSalome_file =
2129 Engines::Salome_file::_duplicate(_Salome_file_map[origName]);
2130 ASSERT(!CORBA::is_nil(theSalome_file));
2131 return theSalome_file;
2134 //=============================================================================
2135 /*! \brief copy a file from a remote host (container) to the local host
2136 * \param container the remote container
2137 * \param remoteFile the file to copy locally from the remote host into localFile
2138 * \param localFile the local file
2140 //=============================================================================
2141 void Abstract_Engines_Container_i::copyFile(Engines::Container_ptr container, const char* remoteFile, const char* localFile)
2143 Engines::fileTransfer_var fileTransfer = container->getFileTransfer();
2146 if ((fp = fopen(localFile,"wb")) == NULL)
2148 INFOS("file " << localFile << " cannot be open for writing");
2152 CORBA::Long fileId = fileTransfer->open(remoteFile);
2155 Engines::fileBlock* aBlock;
2162 aBlock = fileTransfer->getBlock(fileId);
2163 toFollow = aBlock->length();
2165 CORBA::Octet *buf = aBlock->get_buffer();
2166 fwrite(buf, sizeof(CORBA::Octet), toFollow, fp);
2170 MESSAGE("end of transfer");
2171 fileTransfer->close(fileId);
2175 INFOS("open reference file for copy impossible");
2179 //=============================================================================
2180 /*! \brief create a PyNode object to execute remote python code
2181 * \param nodeName the name of the node
2182 * \param code the python code to load
2183 * \return the PyNode
2185 //=============================================================================
2186 Engines::PyNode_ptr Abstract_Engines_Container_i::createPyNode(const char* nodeName, const char* code)
2188 Engines::PyNode_var node= Engines::PyNode::_nil();
2193 PyObject *res = PyObject_CallMethod(_pyCont,
2194 (char*)"create_pynode",
2202 SALOME::ExceptionStruct es;
2203 es.type = SALOME::INTERNAL_ERROR;
2204 es.text = "can not create a python node";
2205 throw SALOME::SALOME_Exception(es);
2207 ierr=PyLong_AsLong(PyTuple_GetItem(res,0));
2208 PyObject* result=PyTuple_GetItem(res,1);
2209 astr = PyUnicode_AsUTF8(result);
2214 Utils_Locker lck(&_mutexForDftPy);
2215 CORBA::Object_var obj=_orb->string_to_object(astr.c_str());
2216 node=Engines::PyNode::_narrow(obj);
2217 std::map<std::string,Engines::PyNode_var>::iterator it(_dftPyNode.find(nodeName));
2218 if(it==_dftPyNode.end())
2220 _dftPyNode[nodeName]=node;
2224 Engines::PyNode_var oldNode((*it).second);
2225 if(!CORBA::is_nil(oldNode))
2226 oldNode->UnRegister();
2229 if(!CORBA::is_nil(node))
2231 return node._retn();
2235 SALOME::ExceptionStruct es;
2236 es.type = SALOME::INTERNAL_ERROR;
2237 es.text = astr.c_str();
2238 throw SALOME::SALOME_Exception(es);
2242 //=============================================================================
2243 /*! \brief Retrieves the last created PyNode instance with createPyNode.
2246 //=============================================================================
2247 Engines::PyNode_ptr Abstract_Engines_Container_i::getDefaultPyNode(const char *nodeName)
2249 Utils_Locker lck(&_mutexForDftPy);
2250 std::map<std::string,Engines::PyNode_var>::iterator it(_dftPyNode.find(nodeName));
2251 if(it==_dftPyNode.end())
2252 return Engines::PyNode::_nil();
2255 Engines::PyNode_var tmpVar((*it).second);
2256 if(!CORBA::is_nil(tmpVar))
2257 return Engines::PyNode::_duplicate(tmpVar);
2259 return Engines::PyNode::_nil();
2263 //=============================================================================
2264 /*! \brief create a PyScriptNode object to execute remote python code
2265 * \param nodeName the name of the node
2266 * \param code the python code to load
2267 * \return the PyScriptNode
2269 //=============================================================================
2270 Engines::PyScriptNode_ptr Abstract_Engines_Container_i::createPyScriptNode(const char* nodeName, const char* code)
2272 Engines::PyScriptNode_var node= Engines::PyScriptNode::_nil();
2277 AutoPyRef res = PyObject_CallMethod(_pyCont,
2278 (char*)"create_pyscriptnode",
2286 SALOME::ExceptionStruct es;
2287 es.type = SALOME::INTERNAL_ERROR;
2288 es.text = "can not create a python node";
2289 throw SALOME::SALOME_Exception(es);
2291 ierr=PyLong_AsLong(PyTuple_GetItem(res,0));
2292 PyObject* result=PyTuple_GetItem(res,1);
2293 astr = PyUnicode_AsUTF8(result);
2298 Utils_Locker lck(&_mutexForDftPy);
2299 CORBA::Object_var obj=_orb->string_to_object(astr.c_str());
2300 node=Engines::PyScriptNode::_narrow(obj);
2301 std::map<std::string,Engines::PyScriptNode_var>::iterator it(_dftPyScriptNode.find(nodeName));
2302 if(it==_dftPyScriptNode.end())
2304 _dftPyScriptNode[nodeName]=node;
2308 Engines::PyScriptNode_var oldNode((*it).second);
2309 if(!CORBA::is_nil(oldNode))
2310 oldNode->UnRegister();
2313 return node._retn();
2317 SALOME::ExceptionStruct es;
2318 es.type = SALOME::INTERNAL_ERROR;
2319 es.text = astr.c_str();
2320 throw SALOME::SALOME_Exception(es);
2324 void Abstract_Engines_Container_i::removePyScriptNode(const char *nodeName)
2326 std::map<std::string,Engines::PyScriptNode_var>::iterator it(_dftPyScriptNode.find(nodeName));
2327 if(it==_dftPyScriptNode.end())
2329 std::ostringstream oss; oss << "Engines_Container_i::removePyScriptNode : node \"" << nodeName << "\" is not map !";
2330 SALOME::ExceptionStruct es;
2331 es.type = SALOME::INTERNAL_ERROR;
2332 es.text = oss.str().c_str();
2333 throw SALOME::SALOME_Exception(es);
2335 (*it).second->UnRegister();
2336 _dftPyScriptNode.erase(it);
2339 void Abstract_Engines_Container_i::cleanAllPyScripts()
2341 for(std::map<std::string,Engines::PyNode_var>::iterator it=_dftPyNode.begin();it!=_dftPyNode.end();it++)
2343 Engines::PyNode_var tmpVar((*it).second);
2344 if(!CORBA::is_nil(tmpVar))
2345 tmpVar->UnRegister();
2348 for(std::map<std::string,Engines::PyScriptNode_var>::iterator it=_dftPyScriptNode.begin();it!=_dftPyScriptNode.end();it++)
2350 Engines::PyScriptNode_var tmpVar((*it).second);
2351 if(!CORBA::is_nil(tmpVar))
2352 tmpVar->UnRegister();
2354 _dftPyScriptNode.clear();
2357 //=============================================================================
2358 /*! \brief Retrieves the last created PyScriptNode instance with createPyScriptNode.
2361 //=============================================================================
2362 Engines::PyScriptNode_ptr Abstract_Engines_Container_i::getDefaultPyScriptNode(const char *nodeName)
2364 Utils_Locker lck(&_mutexForDftPy);
2365 std::map<std::string,Engines::PyScriptNode_var>::iterator it(_dftPyScriptNode.find(nodeName));
2366 if(it==_dftPyScriptNode.end())
2367 return Engines::PyScriptNode::_nil();
2370 Engines::PyScriptNode_var tmpVar((*it).second);
2371 if(!CORBA::is_nil(tmpVar))
2372 return Engines::PyScriptNode::_duplicate(tmpVar);
2374 return Engines::PyScriptNode::_nil();
2378 //=============================================================================
2379 /* int checkifexecutable(const char *filename)
2381 * Return non-zero if the name is an executable file, and
2382 * zero if it is not executable, or if it does not exist.
2384 //=============================================================================
2385 int checkifexecutable(const std::string& filename)
2388 struct stat statinfo;
2390 result = stat(filename.c_str(), &statinfo);
2391 if (result < 0) return 0;
2392 if (!S_ISREG(statinfo.st_mode)) return 0;
2397 if (statinfo.st_uid == geteuid()) return statinfo.st_mode & S_IXUSR;
2398 if (statinfo.st_gid == getegid()) return statinfo.st_mode & S_IXGRP;
2399 return statinfo.st_mode & S_IXOTH;
2404 //=============================================================================
2405 /*! \brief Find a file by searching in a path
2406 * \param filename file name to search
2407 * \param path path to search in
2408 * \param pth the complete file path if found
2409 * \return 1 if found 0 if not
2411 //=============================================================================
2412 int findpathof(const std::string& path, std::string& pth, const std::string& filename)
2414 if ( path.size() == 0 ) return 0;
2416 std::string::size_type offset = 0;
2417 std::string::size_type pos = 0;
2419 struct stat statinfo;
2423 pos = path.find( SEP, offset );
2424 pth = path.substr( offset, pos - offset );
2425 if ( pth.size() > 0 )
2427 if( pth[pth.size()-1] != SLASH ) pth += SLASH;
2429 int result=stat(pth.c_str(), &statinfo);
2430 if(result == 0) found=1;
2432 if (pos == std::string::npos) break;
2438 void Abstract_Engines_Container_i::registerTemporaryFile( const std::string& fileName )
2440 _tmp_files.remove( fileName );
2441 _tmp_files.push_back( fileName );
2444 void Abstract_Engines_Container_i::unregisterTemporaryFile( const std::string& fileName )
2446 _tmp_files.remove( fileName );
2449 void Abstract_Engines_Container_i::clearTemporaryFiles()
2451 std::list<std::string>::const_iterator it;
2452 for ( it = _tmp_files.begin(); it != _tmp_files.end(); ++it ) {
2453 #if defined(WIN32) && defined(UNICODE)
2454 std::wstring aFile = Kernel_Utils::utf8_decode_s(*it);
2455 std::wstring command = (GetFileAttributes(aFile.c_str()) == FILE_ATTRIBUTE_DIRECTORY) ? L"rd /Q \"" : L"del /F /Q \"";
2457 command += L"\" 2>NUL";
2458 _wsystem(command.c_str());
2461 std::string aFile = *it;
2462 std::string command = (GetFileAttributes(aFile.c_str()) == FILE_ATTRIBUTE_DIRECTORY) ? "rd /Q \"" : "del /F /Q \"";
2464 command += "\" 2>NUL";
2466 std::string command = "rm -rf ";
2469 system(command.c_str());
2475 static Engines_Container_SSL_i *_container_singleton_ssl = nullptr;
2477 static Engines::Container_var _container_ref_singleton_ssl;
2479 Abstract_Engines_Container_SSL_i *KERNEL::getContainerSA()
2481 if(!_container_singleton_ssl)
2483 CORBA::ORB_var orb = KERNEL::GetRefToORB();
2484 CORBA::Object_var obj = orb->resolve_initial_references("RootPOA");
2485 PortableServer::POA_var poa = PortableServer::POA::_narrow(obj);
2486 PortableServer::POAManager_var pman = poa->the_POAManager();
2487 CORBA::PolicyList policies;
2490 constexpr int ARGC = 4;
2491 constexpr const char *ARGV[ARGC] = {"Container","FactoryServer","toto",nullptr};
2492 std::unique_ptr<char*[]> argv( new char *[ARGC+1] );
2493 std::vector< std::unique_ptr<char[]> > argvv(ARGC);
2494 argv[ARGC] = nullptr;
2495 for(int i = 0 ; i < ARGC ; ++i)
2499 argvv[i].reset( new char[strlen(ARGV[i])+1] );
2500 strcpy(argvv[i].get(),ARGV[i]);
2501 argv[i] = argvv[i].get();
2506 SALOME_Fake_NamingService ns;
2507 _container_singleton_ssl = new Engines_Container_SSL_i(orb,poa,(char *)"FactoryServer",2,argv.get(),&ns,false);
2508 PortableServer::ObjectId * cont_id = _container_singleton_ssl->getCORBAId();
2510 CORBA::Object_var zeRef = poa->id_to_reference(*cont_id);
2511 _container_ref_singleton_ssl = Engines::Container::_narrow(zeRef);
2513 return _container_singleton_ssl;
2516 Engines::Container_var KERNEL::getContainerRefSA()
2519 return _container_ref_singleton_ssl;