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_current_directory(const char *cwd)
1191 AutoPyRef result = PyObject_CallMethod(_pyCont,(char*)"setCurrentDirectory","s",cwd,nullptr);
1192 if (PyErr_Occurred())
1194 std::string error("can not set logfilename");
1196 THROW_SALOME_CORBA_EXCEPTION(error.c_str(),SALOME::INTERNAL_ERROR);
1200 void Abstract_Engines_Container_i::set_directory_for_replay_files(const char *directory)
1202 SALOME::SetDirectoryForReplayFiles( directory );
1205 void Abstract_Engines_Container_i::set_startup_code(const char *codeAtStartUp)
1207 _code_at_startup = codeAtStartUp;
1210 char *Abstract_Engines_Container_i::get_startup_code()
1212 return CORBA::string_dup( this->_code_at_startup.c_str() );
1215 Engines::vectorOfString_var FromVecStringCppToCORBA( const std::vector<std::string>& group)
1217 Engines::vectorOfString_var ret( new Engines::vectorOfString );
1218 auto sz( group.size() );
1220 for(auto i = 0 ; i < sz ; ++i)
1222 ret[i] = CORBA::string_dup( group[i].c_str() );
1227 std::vector<std::string> FromCORBAVecStringToCpp(const Engines::vectorOfString& groupOfLogFileNames)
1229 auto len = groupOfLogFileNames.length();
1230 std::vector<std::string> ret( len );
1231 for( auto i = 0 ; i < len ; ++i )
1233 ret[i] = groupOfLogFileNames[i];
1238 void Abstract_Engines_Container_i::addLogFileNameGroup(const Engines::vectorOfString& groupOfLogFileNames)
1240 this->_groups_of_log_files.push_back( FromCORBAVecStringToCpp(groupOfLogFileNames) );
1243 Engines::vectorOfVectorOfString *Abstract_Engines_Container_i::getAllLogFileNameGroups()
1245 std::unique_ptr<Engines::vectorOfVectorOfString> ret( new Engines::vectorOfVectorOfString );
1246 auto nbOfGrps = this->_groups_of_log_files.size();
1247 ret->length( nbOfGrps );
1248 for(auto i = 0 ; i < nbOfGrps ; ++i)
1250 (*ret)[i] = FromVecStringCppToCORBA( _groups_of_log_files[i] );
1252 return ret.release();
1255 void Abstract_Engines_Container_i::execute_python_code(const char *code)
1258 if( PyRun_SimpleString( code ) != 0 )
1260 std::string error = parseException();
1261 THROW_SALOME_CORBA_EXCEPTION(error.c_str(),SALOME::INTERNAL_ERROR);
1265 //=============================================================================
1266 //! Create a new component instance with environment variables specified
1268 * CORBA method: Creates a new servant instance of a component.
1269 * The servant registers itself to naming service and Registry.
1270 * \param genericRegisterName Name of the component instance to register
1271 * in Registry & Name Service (without _inst_n suffix)
1272 * \param env dict of env variables
1273 * \param reason explains error when create_component_instance_env fails
1274 * \return a loaded component
1276 //=============================================================================
1277 Engines::EngineComponent_ptr
1278 Abstract_Engines_Container_i::create_component_instance_env(const char*genericRegisterName,
1279 const Engines::FieldsDict& env,
1280 CORBA::String_out reason)
1283 if (_library_map.count(genericRegisterName) != 0)
1285 // It's a Python component
1286 Engines::EngineComponent_ptr compo = createPythonInstance(genericRegisterName, error);
1287 reason=CORBA::string_dup(error.c_str());
1291 std::string impl_name = std::string(LIB) + genericRegisterName + ENGINESO;
1292 if (_library_map.count(impl_name) != 0)
1294 // It's a C++ component
1295 void* handle = _library_map[impl_name];
1296 Engines::EngineComponent_ptr compo = createInstance(genericRegisterName, handle, error);
1297 reason=CORBA::string_dup(error.c_str());
1301 impl_name = std::string(genericRegisterName) + ".exe";
1302 if (_library_map.count(impl_name) != 0)
1304 //It's an executable component
1305 Engines::EngineComponent_ptr compo = createExecutableInstance(genericRegisterName, env, error);
1306 reason=CORBA::string_dup(error.c_str());
1310 error="load_component_Library has probably not been called for component: ";
1311 error += genericRegisterName;
1313 reason=CORBA::string_dup(error.c_str());
1314 return Engines::EngineComponent::_nil() ;
1317 //=============================================================================
1318 //! Create a new component instance (Executable implementation)
1320 * \param CompName Name of the component instance
1321 * \param env dict of env variables
1322 * \param reason explains error when creation fails
1323 * \return a loaded component
1325 * This component is implemented in an executable with name genericRegisterName.exe
1326 * It must register itself in Naming Service. The container waits some time (10 s max)
1327 * it's registration.
1329 //=============================================================================
1330 Engines::EngineComponent_ptr
1331 Abstract_Engines_Container_i::createExecutableInstance(std::string CompName,
1332 const Engines::FieldsDict& env,
1333 std::string& reason)
1335 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1337 _numInstanceMutex.lock() ; // lock on the instance number
1339 int numInstance = _numInstance ;
1340 _numInstanceMutex.unlock() ;
1343 sprintf( aNumI , "%d" , numInstance ) ;
1344 std::string instanceName = CompName + "_inst_" + aNumI ;
1345 std::string component_registerName = _containerName + "/" + instanceName;
1347 //check if an entry exist in naming service
1348 CORBA::Object_var nsobj = _NS->Resolve(component_registerName.c_str());
1349 if ( !CORBA::is_nil(nsobj) )
1351 // unregister the registered component
1352 _NS->Destroy_Name(component_registerName.c_str());
1353 //kill or shutdown it ???
1356 // first arg container ior string
1357 // second arg container name
1358 // third arg instance name
1360 Engines::Container_var pCont= _this();
1361 CORBA::String_var sior = _orb->object_to_string(pCont);
1363 std::string command;
1364 command="mkdir -p ";
1365 command+=instanceName;
1367 command+=instanceName;
1372 command+= sior; // container ior string
1374 command+=_containerName; //container name
1376 command+=instanceName; //instance name
1378 MESSAGE("SALOME_Container::create_component_instance command=" << command);
1381 // use fork/execl instead of system to get finer control on env variables
1384 if(pid == 0) // child
1386 EffectiveOverrideEnvironment(env);
1388 execl("/bin/sh", "sh", "-c", command.c_str() , (char *)0);
1391 else if(pid < 0) // failed to fork
1400 tpid = wait(&status);
1401 } while (tpid != pid);
1404 // launch component with a system call
1405 int status=system(command.c_str());
1410 reason="SALOME_Container::create_component_instance system failed (system command status -1)";
1412 return Engines::EngineComponent::_nil();
1415 else if (WEXITSTATUS(status) == 217)
1417 reason="SALOME_Container::create_component_instance system failed (system command status 217)";
1419 return Engines::EngineComponent::_nil();
1425 if (getenv("TIMEOUT_TO_WAIT_EXE_COMPONENT") != 0)
1427 std::string new_count_str = getenv("TIMEOUT_TO_WAIT_EXE_COMPONENT");
1429 std::istringstream ss(new_count_str);
1430 if (!(ss >> new_count))
1432 INFOS("[Container] TIMEOUT_TO_WAIT_EXE_COMPONENT should be an int");
1437 INFOS("[Container] waiting " << count << " second steps exe component ");
1438 CORBA::Object_var obj = CORBA::Object::_nil() ;
1439 while ( CORBA::is_nil(obj) && count )
1447 MESSAGE( count << ". Waiting for component " << CompName);
1448 obj = _NS->Resolve(component_registerName.c_str());
1451 if(CORBA::is_nil(obj))
1453 reason="SALOME_Container::create_component_instance failed";
1455 return Engines::EngineComponent::_nil();
1459 MESSAGE("SALOME_Container::create_component_instance successful");
1460 iobject = Engines::EngineComponent::_narrow(obj);
1461 _listInstances_map[instanceName] = iobject;
1462 return iobject._retn();
1468 //=============================================================================
1469 //! Create a new component instance (Python implementation)
1471 * \param CompName Name of the component instance
1472 * \param reason explains error when creation fails
1473 * \return a loaded component
1475 //=============================================================================
1476 Engines::EngineComponent_ptr
1477 Abstract_Engines_Container_i::createPythonInstance(std::string CompName,
1478 std::string& reason)
1480 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1482 _numInstanceMutex.lock() ; // lock on the instance number
1484 int numInstance = _numInstance ;
1485 _numInstanceMutex.unlock() ;
1488 sprintf( aNumI , "%d" , numInstance ) ;
1489 std::string instanceName = CompName + "_inst_" + aNumI ;
1490 std::string component_registerName = _containerName + "/" + instanceName;
1494 AutoPyRef result = PyObject_CallMethod(_pyCont,
1495 (char*)"create_component_instance",
1498 instanceName.c_str());
1501 PyArg_ParseTuple(result,"ss", &ior, &error);
1508 CORBA::Object_var obj = _orb->string_to_object(iors.c_str());
1509 iobject = Engines::EngineComponent::_narrow( obj ) ;
1510 _listInstances_map[instanceName] = iobject;
1512 return iobject._retn();
1516 Abstract_Engines_Container_i::create_python_service_instance(const char * CompName,
1517 CORBA::String_out reason)
1519 CORBA::Object_var object = CORBA::Object::_nil();
1521 _numInstanceMutex.lock() ; // lock on the instance number
1523 int numInstance = _numInstance ;
1524 _numInstanceMutex.unlock() ;
1527 sprintf( aNumI , "%d" , numInstance ) ;
1528 std::string instanceName = std::string(CompName) + "_inst_" + aNumI ;
1529 std::string component_registerName = _containerName + "/" + instanceName;
1531 char * _ior = nullptr;
1534 AutoPyRef result = PyObject_CallMethod(_pyCont,
1535 (char*)"create_component_instance",
1538 instanceName.c_str());
1541 PyArg_ParseTuple(result,"ss", &ior, &error);
1542 reason = CORBA::string_dup(error);
1543 _ior = CORBA::string_dup(ior);
1549 //=============================================================================
1550 //! Create a new component instance (C++ implementation)
1552 * C++ method: create a servant instance of a component.
1553 * \param genericRegisterName Name of the component instance to register
1554 * in Registry & Name Service,
1555 * (without _inst_n suffix, like "COMPONENT")
1556 * \param handle loaded library handle
1557 * \param reason explains error when creation fails
1558 * \return a loaded component
1560 * example with names:
1561 * - aGenRegisterName = COMPONENT (= first argument)
1562 * - _containerName = /Containers/cli76ce/FactoryServer
1563 * - factoryName = COMPONENTEngine_factory
1564 * - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
1565 * - instanceName = COMPONENT_inst_1
1566 * - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1568 //=============================================================================
1569 Engines::EngineComponent_ptr
1570 Abstract_Engines_Container_i::createInstance(std::string genericRegisterName,
1572 std::string& reason)
1574 // --- find the factory
1576 std::string aGenRegisterName = genericRegisterName;
1577 std::string factory_name = aGenRegisterName + std::string("Engine_factory");
1578 SCRUTE(factory_name) ;
1580 typedef PortableServer::ObjectId* (*FACTORY_FUNCTION) (CORBA::ORB_ptr,
1581 PortableServer::POA_ptr,
1582 PortableServer::ObjectId *,
1587 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)dlsym( handle, factory_name.c_str() );
1589 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)GetProcAddress( (HINSTANCE)handle, factory_name.c_str() );
1592 if ( !Component_factory )
1594 MESSAGE( "Can't resolve symbol: " + factory_name );
1599 return Engines::EngineComponent::_nil() ;
1602 // --- create instance
1604 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1608 _numInstanceMutex.lock() ; // lock on the instance number
1610 int numInstance = _numInstance ;
1611 _numInstanceMutex.unlock() ;
1614 sprintf( aNumI , "%d" , numInstance ) ;
1615 std::string instanceName = aGenRegisterName + "_inst_" + aNumI ;
1616 std::string component_registerName =
1617 _containerName + "/" + instanceName;
1619 // --- Instantiate required CORBA object
1621 PortableServer::ObjectId *id ; //not owner, do not delete (nore use var)
1622 id = (Component_factory) ( _orb, _poa, _id, instanceName.c_str(),
1623 aGenRegisterName.c_str() ) ;
1626 reason="Can't get ObjectId from factory";
1628 return iobject._retn();
1631 // --- get reference from id
1633 CORBA::Object_var obj = _poa->id_to_reference(*id);
1634 iobject = Engines::EngineComponent::_narrow( obj ) ;
1636 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1637 _listInstances_map[instanceName] = iobject;
1638 _cntInstances_map[aGenRegisterName] += 1;
1639 _numInstanceMutex.unlock() ;
1640 SCRUTE(aGenRegisterName);
1641 SCRUTE(_cntInstances_map[aGenRegisterName]);
1643 // --- register the engine under the name
1644 // containerName(.dir)/instanceName(.object)
1646 _NS->Register( iobject , component_registerName.c_str() ) ;
1647 MESSAGE( component_registerName.c_str() << " bound" ) ;
1651 reason="Container_i::createInstance exception caught";
1654 return iobject._retn();
1657 //=============================================================================
1658 //! Find an existing (in the container) component instance
1660 * CORBA method: Finds a servant instance of a component
1661 * \param registeredName Name of the component in Registry or Name Service,
1662 * without instance suffix number
1663 * \return the first found instance
1665 //=============================================================================
1666 Engines::EngineComponent_ptr
1667 Abstract_Engines_Container_i::find_component_instance( const char* registeredName)
1669 Engines::EngineComponent_var anEngine = Engines::EngineComponent::_nil();
1670 std::map<std::string,Engines::EngineComponent_var>::iterator itm =_listInstances_map.begin();
1671 while (itm != _listInstances_map.end())
1673 std::string instance = (*itm).first;
1675 if (instance.find(registeredName) == 0)
1677 anEngine = (*itm).second;
1678 return anEngine._retn();
1682 return anEngine._retn();
1685 //=============================================================================
1686 //! Remove the component instance from container
1688 * CORBA method: Stops the component servant, and deletes all related objects
1689 * \param component_i Component to be removed
1691 //=============================================================================
1693 void Abstract_Engines_Container_i::remove_impl(Engines::EngineComponent_ptr component_i)
1695 ASSERT(! CORBA::is_nil(component_i));
1696 std::string instanceName = component_i->instanceName() ;
1697 MESSAGE("unload component " << instanceName);
1698 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1699 _listInstances_map.erase(instanceName);
1700 _numInstanceMutex.unlock() ;
1701 component_i->destroy() ;
1702 _NS->Destroy_Name(instanceName.c_str());
1705 //=============================================================================
1706 //! Unload component libraries from the container
1708 * CORBA method: Discharges unused libraries from the container.
1710 //=============================================================================
1711 void Abstract_Engines_Container_i::finalize_removal()
1713 MESSAGE("finalize unload : dlclose");
1714 _numInstanceMutex.lock(); // lock to be alone
1715 // (see decInstanceCnt, load_component_Library)
1716 std::map<std::string, void *>::iterator ith;
1717 for (ith = _toRemove_map.begin(); ith != _toRemove_map.end(); ith++)
1719 void *handle = (*ith).second;
1720 std::string impl_name= (*ith).first;
1725 // dlclose(handle); // SALOME unstable after ...
1726 // _library_map.erase(impl_name);
1729 _toRemove_map.clear();
1730 _numInstanceMutex.unlock();
1733 //=============================================================================
1734 //! Decrement component instance reference count
1738 //=============================================================================
1739 void Abstract_Engines_Container_i::decInstanceCnt(std::string genericRegisterName)
1741 if(_cntInstances_map.count(genericRegisterName)==0)
1743 std::string aGenRegisterName =genericRegisterName;
1744 MESSAGE("Engines_Container_i::decInstanceCnt " << aGenRegisterName);
1745 ASSERT(_cntInstances_map[aGenRegisterName] > 0);
1746 _numInstanceMutex.lock(); // lock to be alone
1747 // (see finalize_removal, load_component_Library)
1748 _cntInstances_map[aGenRegisterName] -= 1;
1749 SCRUTE(_cntInstances_map[aGenRegisterName]);
1750 if (_cntInstances_map[aGenRegisterName] == 0)
1752 std::string impl_name =
1753 Engines_Component_i::GetDynLibraryName(aGenRegisterName.c_str());
1755 void* handle = _library_map[impl_name];
1757 _toRemove_map[impl_name] = handle;
1759 _numInstanceMutex.unlock();
1762 //=============================================================================
1763 //! Find or create a new component instance
1765 * CORBA method: find or create an instance of the component (servant),
1766 * load a new component class (dynamic library) if required,
1768 * ---- FOR COMPATIBILITY WITH 2.2 ----
1770 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
1772 * The servant registers itself to naming service and Registry.
1773 * \param genericRegisterName Name of the component to register
1774 * in Registry & Name Service
1775 * \param componentName Name of the constructed library of the component
1776 * \return a loaded component
1778 //=============================================================================
1780 Engines::EngineComponent_ptr
1781 Abstract_Engines_Container_i::load_impl( const char* genericRegisterName,
1782 const char* /*componentName*/ )
1785 std::string impl_name = std::string(LIB) + genericRegisterName + ENGINESO;
1786 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1787 if (load_component_Library(genericRegisterName,reason))
1788 iobject = find_or_create_instance(genericRegisterName, impl_name);
1789 CORBA::string_free(reason);
1790 return iobject._retn();
1793 Engines::EmbeddedNamingService_ptr Abstract_Engines_Container_i::get_embedded_NS_if_ssl()
1795 SALOME_Embedded_NamingService_Client *nsc(dynamic_cast<SALOME_Embedded_NamingService_Client *>(this->_NS));
1798 Engines::EmbeddedNamingService_var obj = nsc->GetObject();
1799 return Engines::EmbeddedNamingService::_duplicate(obj);
1803 SALOME_Fake_NamingService *fns(dynamic_cast<SALOME_Fake_NamingService *>(this->_NS));
1806 Engines::EmbeddedNamingService_var ret = GetEmbeddedNamingService();
1810 return Engines::EmbeddedNamingService::_nil();
1814 //=============================================================================
1815 //! Finds an already existing component instance or create a new instance
1817 * C++ method: Finds an already existing servant instance of a component, or
1818 * create an instance.
1819 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
1820 * \param genericRegisterName Name of the component instance to register
1821 * in Registry & Name Service,
1822 * (without _inst_n suffix, like "COMPONENT")
1823 * \param componentLibraryName like "libCOMPONENTEngine.so"
1824 * \return a loaded component
1826 * example with names:
1827 * - aGenRegisterName = COMPONENT (= first argument)
1828 * - impl_name = libCOMPONENTEngine.so (= second argument)
1829 * - _containerName = /Containers/cli76ce/FactoryServer
1830 * - factoryName = COMPONENTEngine_factory
1831 * - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
1832 * - instanceName = COMPONENT_inst_1
1833 * - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1835 //=============================================================================
1837 Engines::EngineComponent_ptr
1838 Abstract_Engines_Container_i::find_or_create_instance(std::string genericRegisterName,
1839 std::string componentLibraryName)
1841 std::string aGenRegisterName = genericRegisterName;
1842 std::string impl_name = componentLibraryName;
1843 if (_library_map.count(impl_name) == 0)
1845 INFOS("shared library " << impl_name <<" must be loaded before creating instance");
1846 return Engines::EngineComponent::_nil() ;
1850 // --- find a registered instance in naming service, or create
1852 void* handle = _library_map[impl_name];
1853 std::string component_registerBase =
1854 _containerName + "/" + aGenRegisterName;
1855 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1859 CORBA::Object_var obj =
1860 _NS->ResolveFirst( component_registerBase.c_str());
1861 if ( CORBA::is_nil( obj ) )
1863 iobject = createInstance(genericRegisterName,
1869 iobject = Engines::EngineComponent::_narrow( obj ) ;
1874 INFOS( "Container_i::load_impl caught" ) ;
1876 return iobject._retn();
1880 //=============================================================================
1881 //! Indicate if container is a python one
1883 * Retrieves only with container naming convention if it is a python container
1885 //=============================================================================
1886 bool Abstract_Engines_Container_i::isPythonContainer(const char* ContainerName)
1889 size_t len=strlen(ContainerName);
1891 if(strcmp(ContainerName+len-2,"Py")==0)
1896 //=============================================================================
1897 //! Kill the container
1899 * CORBA method: Kill the container process with exit(0).
1900 * To remove : never returns !
1902 //=============================================================================
1903 bool Abstract_Engines_Container_i::Kill_impl()
1905 MESSAGE("Engines_Container_i::Kill() pid "<< getpid() << " containerName "
1906 << _containerName.c_str() << " machineName "
1907 << Kernel_Utils::GetHostname().c_str());
1908 INFOS("===============================================================");
1909 INFOS("= REMOVE calls to Kill_impl in C++ container =");
1910 INFOS("===============================================================");
1916 //=============================================================================
1920 //=============================================================================
1921 void ActSigIntHandler()
1924 struct sigaction SigIntAct ;
1925 SigIntAct.sa_sigaction = &SigIntHandler ;
1926 sigemptyset(&SigIntAct.sa_mask);
1927 SigIntAct.sa_flags = SA_SIGINFO ;
1930 // DEBUG 03.02.2005 : the first parameter of sigaction is not a mask of signals
1931 // (SIGINT | SIGUSR1) :
1932 // it must be only one signal ===> one call for SIGINT
1933 // and an other one for SIGUSR1
1936 if ( sigaction( SIGINT , &SigIntAct, NULL ) )
1938 perror("SALOME_Container main ") ;
1941 if ( sigaction( SIGUSR1 , &SigIntAct, NULL ) )
1943 perror("SALOME_Container main ") ;
1946 if ( sigaction( SIGUSR2 , &SigIntAct, NULL ) )
1948 perror("SALOME_Container main ") ;
1952 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1953 // use of streams (and so on) should never be used because :
1954 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1955 // A stream operation may be interrupted by a signal and if the Handler use stream we
1956 // may have a "Dead-Lock" ===HangUp
1957 //==INFOS is commented
1958 // INFOS(pthread_self() << "SigIntHandler activated") ;
1961 signal( SIGINT, SigIntHandler );
1962 // legacy code required to supervisor. Commented in order to avoid problems on Windows
1963 // signal( SIGUSR1, SigIntHandler );
1969 void CallCancelThread() ;
1972 void SigIntHandler(int /*what*/ ,
1973 siginfo_t * siginfo ,
1976 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1977 // use of streams (and so on) should never be used because :
1978 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1979 // A stream operation may be interrupted by a signal and if the Handler use stream we
1980 // may have a "Dead-Lock" ===HangUp
1981 //==MESSAGE is commented
1982 // MESSAGE(pthread_self() << "SigIntHandler what " << what << std::endl
1983 // << " si_signo " << siginfo->si_signo << std::endl
1984 // << " si_code " << siginfo->si_code << std::endl
1985 // << " si_pid " << siginfo->si_pid) ;
1990 // MESSAGE("SigIntHandler END sleeping.") ;
1995 ActSigIntHandler() ;
1996 if ( siginfo->si_signo == SIGUSR1 )
2000 else if ( siginfo->si_signo == SIGUSR2 )
2002 CallCancelThread() ;
2007 // MESSAGE("SigIntHandler BEGIN sleeping.") ;
2014 // MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
2020 void SigIntHandler( int what )
2023 MESSAGE( pthread_self() << "SigIntHandler what " << what << std::endl );
2025 MESSAGE( "SigIntHandler what " << what << std::endl );
2030 MESSAGE("SigIntHandler END sleeping.") ;
2035 ActSigIntHandler() ;
2036 if ( what == SIGUSR1 )
2043 MESSAGE("SigIntHandler BEGIN sleeping.") ;
2050 MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
2057 //=============================================================================
2058 //! Get or create a file reference object associated to a local file (to transfer it)
2060 * CORBA method: get or create a fileRef object associated to a local file
2061 * (a file on the computer on which runs the container server), which stores
2062 * a list of (machine, localFileName) corresponding to copies already done.
2064 * \param origFileName absolute path for a local file to copy on other
2066 * \return a fileRef object associated to the file.
2068 //=============================================================================
2069 Engines::fileRef_ptr
2070 Abstract_Engines_Container_i::createFileRef(const char* origFileName)
2072 std::string origName(origFileName);
2073 Engines::fileRef_var theFileRef = Engines::fileRef::_nil();
2075 if (origName[0] != '/')
2077 INFOS("path of file to copy must be an absolute path beginning with '/'");
2078 return Engines::fileRef::_nil();
2081 if (CORBA::is_nil(_fileRef_map[origName]))
2083 CORBA::Object_var obj=_poa->id_to_reference(*_id);
2084 Engines::Container_var pCont = Engines::Container::_narrow(obj);
2085 fileRef_i* aFileRef = new fileRef_i(pCont, origFileName);
2086 theFileRef = Engines::fileRef::_narrow(aFileRef->_this());
2087 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
2088 _fileRef_map[origName] = theFileRef;
2089 _numInstanceMutex.unlock() ;
2092 theFileRef = Engines::fileRef::_duplicate(_fileRef_map[origName]);
2093 ASSERT(! CORBA::is_nil(theFileRef));
2094 return theFileRef._retn();
2097 //=============================================================================
2098 //! Get a fileTransfer reference
2101 * \return a reference to the fileTransfer object
2103 //=============================================================================
2104 Engines::fileTransfer_ptr
2105 Abstract_Engines_Container_i::getFileTransfer()
2107 Engines::fileTransfer_var aFileTransfer
2108 = Engines::fileTransfer::_duplicate(_fileTransfer);
2109 return aFileTransfer._retn();
2112 //=============================================================================
2113 //! Create a Salome file
2114 //=============================================================================
2115 Engines::Salome_file_ptr
2116 Abstract_Engines_Container_i::createSalome_file(const char* origFileName)
2118 std::string origName(origFileName);
2119 if (CORBA::is_nil(_Salome_file_map[origName]))
2121 Salome_file_i* aSalome_file = new Salome_file_i();
2122 aSalome_file->setContainer(Engines::Container::_duplicate(this->_this()));
2125 aSalome_file->setLocalFile(origFileName);
2126 aSalome_file->recvFiles();
2128 catch (const SALOME::SALOME_Exception& /*e*/) //!< TODO: unused variable
2130 return Engines::Salome_file::_nil();
2133 Engines::Salome_file_var theSalome_file = Engines::Salome_file::_nil();
2134 theSalome_file = Engines::Salome_file::_narrow(aSalome_file->_this());
2135 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
2136 _Salome_file_map[origName] = theSalome_file;
2137 _numInstanceMutex.unlock() ;
2140 Engines::Salome_file_ptr theSalome_file =
2141 Engines::Salome_file::_duplicate(_Salome_file_map[origName]);
2142 ASSERT(!CORBA::is_nil(theSalome_file));
2143 return theSalome_file;
2146 //=============================================================================
2147 /*! \brief copy a file from a remote host (container) to the local host
2148 * \param container the remote container
2149 * \param remoteFile the file to copy locally from the remote host into localFile
2150 * \param localFile the local file
2152 //=============================================================================
2153 void Abstract_Engines_Container_i::copyFile(Engines::Container_ptr container, const char* remoteFile, const char* localFile)
2155 Engines::fileTransfer_var fileTransfer = container->getFileTransfer();
2158 if ((fp = fopen(localFile,"wb")) == NULL)
2160 INFOS("file " << localFile << " cannot be open for writing");
2164 CORBA::Long fileId = fileTransfer->open(remoteFile);
2167 Engines::fileBlock* aBlock;
2174 aBlock = fileTransfer->getBlock(fileId);
2175 toFollow = aBlock->length();
2177 CORBA::Octet *buf = aBlock->get_buffer();
2178 fwrite(buf, sizeof(CORBA::Octet), toFollow, fp);
2182 MESSAGE("end of transfer");
2183 fileTransfer->close(fileId);
2187 INFOS("open reference file for copy impossible");
2191 //=============================================================================
2192 /*! \brief create a PyNode object to execute remote python code
2193 * \param nodeName the name of the node
2194 * \param code the python code to load
2195 * \return the PyNode
2197 //=============================================================================
2198 Engines::PyNode_ptr Abstract_Engines_Container_i::createPyNode(const char* nodeName, const char* code)
2200 Engines::PyNode_var node= Engines::PyNode::_nil();
2205 PyObject *res = PyObject_CallMethod(_pyCont,
2206 (char*)"create_pynode",
2214 SALOME::ExceptionStruct es;
2215 es.type = SALOME::INTERNAL_ERROR;
2216 es.text = "can not create a python node";
2217 throw SALOME::SALOME_Exception(es);
2219 ierr=PyLong_AsLong(PyTuple_GetItem(res,0));
2220 PyObject* result=PyTuple_GetItem(res,1);
2221 astr = PyUnicode_AsUTF8(result);
2226 Utils_Locker lck(&_mutexForDftPy);
2227 CORBA::Object_var obj=_orb->string_to_object(astr.c_str());
2228 node=Engines::PyNode::_narrow(obj);
2229 std::map<std::string,Engines::PyNode_var>::iterator it(_dftPyNode.find(nodeName));
2230 if(it==_dftPyNode.end())
2232 _dftPyNode[nodeName]=node;
2236 Engines::PyNode_var oldNode((*it).second);
2237 if(!CORBA::is_nil(oldNode))
2238 oldNode->UnRegister();
2241 if(!CORBA::is_nil(node))
2243 return node._retn();
2247 SALOME::ExceptionStruct es;
2248 es.type = SALOME::INTERNAL_ERROR;
2249 es.text = astr.c_str();
2250 throw SALOME::SALOME_Exception(es);
2254 //=============================================================================
2255 /*! \brief Retrieves the last created PyNode instance with createPyNode.
2258 //=============================================================================
2259 Engines::PyNode_ptr Abstract_Engines_Container_i::getDefaultPyNode(const char *nodeName)
2261 Utils_Locker lck(&_mutexForDftPy);
2262 std::map<std::string,Engines::PyNode_var>::iterator it(_dftPyNode.find(nodeName));
2263 if(it==_dftPyNode.end())
2264 return Engines::PyNode::_nil();
2267 Engines::PyNode_var tmpVar((*it).second);
2268 if(!CORBA::is_nil(tmpVar))
2269 return Engines::PyNode::_duplicate(tmpVar);
2271 return Engines::PyNode::_nil();
2275 //=============================================================================
2276 /*! \brief create a PyScriptNode object to execute remote python code
2277 * \param nodeName the name of the node
2278 * \param code the python code to load
2279 * \return the PyScriptNode
2281 //=============================================================================
2282 Engines::PyScriptNode_ptr Abstract_Engines_Container_i::createPyScriptNode(const char* nodeName, const char* code)
2284 Engines::PyScriptNode_var node= Engines::PyScriptNode::_nil();
2289 AutoPyRef res = PyObject_CallMethod(_pyCont,
2290 (char*)"create_pyscriptnode",
2298 SALOME::ExceptionStruct es;
2299 es.type = SALOME::INTERNAL_ERROR;
2300 es.text = "can not create a python node";
2301 throw SALOME::SALOME_Exception(es);
2303 ierr=PyLong_AsLong(PyTuple_GetItem(res,0));
2304 PyObject* result=PyTuple_GetItem(res,1);
2305 astr = PyUnicode_AsUTF8(result);
2310 Utils_Locker lck(&_mutexForDftPy);
2311 CORBA::Object_var obj=_orb->string_to_object(astr.c_str());
2312 node=Engines::PyScriptNode::_narrow(obj);
2313 std::map<std::string,Engines::PyScriptNode_var>::iterator it(_dftPyScriptNode.find(nodeName));
2314 if(it==_dftPyScriptNode.end())
2316 _dftPyScriptNode[nodeName]=node;
2320 Engines::PyScriptNode_var oldNode((*it).second);
2321 if(!CORBA::is_nil(oldNode))
2322 oldNode->UnRegister();
2325 return node._retn();
2329 SALOME::ExceptionStruct es;
2330 es.type = SALOME::INTERNAL_ERROR;
2331 es.text = astr.c_str();
2332 throw SALOME::SALOME_Exception(es);
2336 void Abstract_Engines_Container_i::removePyScriptNode(const char *nodeName)
2338 std::map<std::string,Engines::PyScriptNode_var>::iterator it(_dftPyScriptNode.find(nodeName));
2339 if(it==_dftPyScriptNode.end())
2341 std::ostringstream oss; oss << "Engines_Container_i::removePyScriptNode : node \"" << nodeName << "\" is not map !";
2342 SALOME::ExceptionStruct es;
2343 es.type = SALOME::INTERNAL_ERROR;
2344 es.text = oss.str().c_str();
2345 throw SALOME::SALOME_Exception(es);
2347 (*it).second->UnRegister();
2348 _dftPyScriptNode.erase(it);
2351 void Abstract_Engines_Container_i::cleanAllPyScripts()
2353 for(std::map<std::string,Engines::PyNode_var>::iterator it=_dftPyNode.begin();it!=_dftPyNode.end();it++)
2355 Engines::PyNode_var tmpVar((*it).second);
2356 if(!CORBA::is_nil(tmpVar))
2357 tmpVar->UnRegister();
2360 for(std::map<std::string,Engines::PyScriptNode_var>::iterator it=_dftPyScriptNode.begin();it!=_dftPyScriptNode.end();it++)
2362 Engines::PyScriptNode_var tmpVar((*it).second);
2363 if(!CORBA::is_nil(tmpVar))
2364 tmpVar->UnRegister();
2366 _dftPyScriptNode.clear();
2369 //=============================================================================
2370 /*! \brief Retrieves the last created PyScriptNode instance with createPyScriptNode.
2373 //=============================================================================
2374 Engines::PyScriptNode_ptr Abstract_Engines_Container_i::getDefaultPyScriptNode(const char *nodeName)
2376 Utils_Locker lck(&_mutexForDftPy);
2377 std::map<std::string,Engines::PyScriptNode_var>::iterator it(_dftPyScriptNode.find(nodeName));
2378 if(it==_dftPyScriptNode.end())
2379 return Engines::PyScriptNode::_nil();
2382 Engines::PyScriptNode_var tmpVar((*it).second);
2383 if(!CORBA::is_nil(tmpVar))
2384 return Engines::PyScriptNode::_duplicate(tmpVar);
2386 return Engines::PyScriptNode::_nil();
2390 //=============================================================================
2391 /* int checkifexecutable(const char *filename)
2393 * Return non-zero if the name is an executable file, and
2394 * zero if it is not executable, or if it does not exist.
2396 //=============================================================================
2397 int checkifexecutable(const std::string& filename)
2400 struct stat statinfo;
2402 result = stat(filename.c_str(), &statinfo);
2403 if (result < 0) return 0;
2404 if (!S_ISREG(statinfo.st_mode)) return 0;
2409 if (statinfo.st_uid == geteuid()) return statinfo.st_mode & S_IXUSR;
2410 if (statinfo.st_gid == getegid()) return statinfo.st_mode & S_IXGRP;
2411 return statinfo.st_mode & S_IXOTH;
2416 //=============================================================================
2417 /*! \brief Find a file by searching in a path
2418 * \param filename file name to search
2419 * \param path path to search in
2420 * \param pth the complete file path if found
2421 * \return 1 if found 0 if not
2423 //=============================================================================
2424 int findpathof(const std::string& path, std::string& pth, const std::string& filename)
2426 if ( path.size() == 0 ) return 0;
2428 std::string::size_type offset = 0;
2429 std::string::size_type pos = 0;
2431 struct stat statinfo;
2435 pos = path.find( SEP, offset );
2436 pth = path.substr( offset, pos - offset );
2437 if ( pth.size() > 0 )
2439 if( pth[pth.size()-1] != SLASH ) pth += SLASH;
2441 int result=stat(pth.c_str(), &statinfo);
2442 if(result == 0) found=1;
2444 if (pos == std::string::npos) break;
2450 void Abstract_Engines_Container_i::registerTemporaryFile( const std::string& fileName )
2452 _tmp_files.remove( fileName );
2453 _tmp_files.push_back( fileName );
2456 void Abstract_Engines_Container_i::unregisterTemporaryFile( const std::string& fileName )
2458 _tmp_files.remove( fileName );
2461 void Abstract_Engines_Container_i::clearTemporaryFiles()
2463 std::list<std::string>::const_iterator it;
2464 for ( it = _tmp_files.begin(); it != _tmp_files.end(); ++it ) {
2465 #if defined(WIN32) && defined(UNICODE)
2466 std::wstring aFile = Kernel_Utils::utf8_decode_s(*it);
2467 std::wstring command = (GetFileAttributes(aFile.c_str()) == FILE_ATTRIBUTE_DIRECTORY) ? L"rd /Q \"" : L"del /F /Q \"";
2469 command += L"\" 2>NUL";
2470 _wsystem(command.c_str());
2473 std::string aFile = *it;
2474 std::string command = (GetFileAttributes(aFile.c_str()) == FILE_ATTRIBUTE_DIRECTORY) ? "rd /Q \"" : "del /F /Q \"";
2476 command += "\" 2>NUL";
2478 std::string command = "rm -rf ";
2481 system(command.c_str());
2487 static Engines_Container_SSL_i *_container_singleton_ssl = nullptr;
2489 static Engines::Container_var _container_ref_singleton_ssl;
2491 Abstract_Engines_Container_SSL_i *KERNEL::getContainerSA()
2493 if(!_container_singleton_ssl)
2495 CORBA::ORB_var orb = KERNEL::GetRefToORB();
2496 CORBA::Object_var obj = orb->resolve_initial_references("RootPOA");
2497 PortableServer::POA_var poa = PortableServer::POA::_narrow(obj);
2498 PortableServer::POAManager_var pman = poa->the_POAManager();
2499 CORBA::PolicyList policies;
2502 constexpr int ARGC = 4;
2503 constexpr const char *ARGV[ARGC] = {"Container","FactoryServer","toto",nullptr};
2504 std::unique_ptr<char*[]> argv( new char *[ARGC+1] );
2505 std::vector< std::unique_ptr<char[]> > argvv(ARGC);
2506 argv[ARGC] = nullptr;
2507 for(int i = 0 ; i < ARGC ; ++i)
2511 argvv[i].reset( new char[strlen(ARGV[i])+1] );
2512 strcpy(argvv[i].get(),ARGV[i]);
2513 argv[i] = argvv[i].get();
2518 SALOME_Fake_NamingService ns;
2519 _container_singleton_ssl = new Engines_Container_SSL_i(orb,poa,(char *)"FactoryServer",2,argv.get(),&ns,false);
2520 PortableServer::ObjectId * cont_id = _container_singleton_ssl->getCORBAId();
2522 CORBA::Object_var zeRef = poa->id_to_reference(*cont_id);
2523 _container_ref_singleton_ssl = Engines::Container::_narrow(zeRef);
2525 return _container_singleton_ssl;
2528 Engines::Container_var KERNEL::getContainerRefSA()
2531 return _container_ref_singleton_ssl;