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 "PythonCppUtils.hxx"
67 #include "Utils_CorbaException.hxx"
74 #include <structmember.h>
75 #include "Container_init_python.hxx"
76 #ifdef BOS26455_WITH_BOOST_PYTHON
77 #include <boost/python.hpp>
80 bool _Sleeping = false ;
82 // // Needed by multi-threaded Python --- Supervision
86 extern "C" {void ActSigIntHandler() ; }
88 extern "C" {void SigIntHandler(int, siginfo_t *, void *) ; }
90 extern "C" {void SigIntHandler( int ) ; }
96 #define ENGINESO "Engine.dylib"
98 #define ENGINESO "Engine.so"
102 #define ENGINESO "Engine.dll"
113 const int Abstract_Engines_Container_i::DFT_TIME_INTERVAL_BTW_MEASURE = 500;
115 std::map<std::string, int> Abstract_Engines_Container_i::_cntInstances_map;
116 std::map<std::string, void *> Abstract_Engines_Container_i::_library_map;
117 std::map<std::string, void *> Abstract_Engines_Container_i::_toRemove_map;
118 omni_mutex Abstract_Engines_Container_i::_numInstanceMutex ;
120 static PyObject *_pyCont = nullptr;
122 int checkifexecutable(const std::string&);
123 int findpathof(const std::string& path, std::string&, const std::string&);
125 /*! \class Engines_Container_i
126 * \brief C++ implementation of Engines::Container interface
131 //=============================================================================
133 * Default constructor, not for use
135 //=============================================================================
137 Abstract_Engines_Container_i::Abstract_Engines_Container_i () :
138 _NS(nullptr),_id(nullptr),_numInstance(0)
142 //=============================================================================
146 //=============================================================================
148 Abstract_Engines_Container_i::Abstract_Engines_Container_i (CORBA::ORB_ptr orb,
149 PortableServer::POA_ptr poa,
150 char *containerName ,
151 int argc , char* argv[],
152 SALOME_NamingService_Container_Abstract *ns,
153 bool isServantAloneInProcess
155 _NS(nullptr),_id(0),_numInstance(0),_isServantAloneInProcess(isServantAloneInProcess)
157 _pid = (long)getpid();
165 std::string hostname = Kernel_Utils::GetHostname();
167 INFO_MESSAGE("Starting Container servant instance on Hostname :" << hostname << " with PID : " << getpid() ) ;
169 MESSAGE(hostname << " " << _getpid() <<
170 " Engines_Container_i starting argc " << _argc<< " Thread " << pthread_self().p ) ;
172 _isSupervContainer = false;
174 _orb = CORBA::ORB::_duplicate(orb) ;
175 _poa = PortableServer::POA::_duplicate(poa) ;
177 // Pour les containers paralleles: il ne faut pas enregistrer et activer
178 // le container generique, mais le container specialise
181 _id = _poa->activate_object(this);
182 // key point : if ns is nullptr : this servant is alone in its process
183 // if ns is not null : this servant embedded into single process.
184 _NS = ns==nullptr ? new SALOME_NamingService : ns->clone();
185 _NS->init_orb( _orb ) ;
186 CORBA::Object_var obj=_poa->id_to_reference(*_id);
187 Engines::Container_var pCont = Engines::Container::_narrow(obj);
190 _containerName = SALOME_NamingService_Abstract::BuildContainerNameForNS(containerName, hostname.c_str());
193 // import SALOME_Container
194 // pycont = SALOME_Container.SALOME_Container_i(containerIORStr)
196 CORBA::String_var sior = _orb->object_to_string(pCont);
197 std::ostringstream myCommand;
198 myCommand << "pyCont = SALOME_Container.SALOME_Container_i('" << _containerName << "','" << sior << "'," << DFT_TIME_INTERVAL_BTW_MEASURE << ")\n";
199 INFO_MESSAGE("Python command executed : " << myCommand.str());
201 //[RNV]: Comment the PyEval_AcquireLock() and PyEval_ReleaseLock() because this
202 //approach leads to the deadlock of the main thread of the application on Windows platform
203 //in case if cppContainer runs in the standalone mode. The problem with the PyThreadState
204 //described by ABN seems not reproduced, to be checked carefully later...
207 //// [ABN]: using the PyGILState* API here is unstable. omniORB logic is invoked
208 //// by the Python code executed below, and in some (random) cases, the Python code
209 //// execution ends with a PyThreadState which was not the one we have here.
210 //// (TODO: understand why ...)
211 //// To be on the safe side we get and load the thread state ourselves:
212 //PyEval_AcquireLock(); // get GIL
213 //PyThreadState * mainThreadState = PyThreadState_Get();
214 //PyThreadState_Swap(mainThreadState);
217 // mpv: this is temporary solution: there is a unregular crash if not
220 // first element is the path to Registry.dll, but it's wrong
221 PyRun_SimpleString("import sys\n");
222 PyRun_SimpleString("sys.path = sys.path[1:]\n");
224 PyRun_SimpleString("import SALOME_Container\n");
225 PyRun_SimpleString((char*)myCommand.str().c_str());
226 PyObject *mainmod = PyImport_AddModule("__main__");
227 PyObject *globals = PyModule_GetDict(mainmod);
228 _pyCont = PyDict_GetItemString(globals, "pyCont");
229 //PyThreadState_Swap(NULL);
230 //PyEval_ReleaseLock();
232 {// register to NS after python initialization to be sure that client invoke after py constructor execution
233 _NS->Register(pCont, _containerName.c_str());
234 DEBUG_MESSAGE("Container registred in NS as : " << _containerName);
236 fileTransfer_i* aFileTransfer = new fileTransfer_i();
237 CORBA::Object_var obref=aFileTransfer->_this();
238 _fileTransfer = Engines::fileTransfer::_narrow(obref);
239 aFileTransfer->_remove_ref();
243 //=============================================================================
247 //=============================================================================
249 Abstract_Engines_Container_i::~Abstract_Engines_Container_i()
251 MESSAGE("Abstract_Container_i::~Abstract_Container_i()");
259 //=============================================================================
260 //! Get container name
262 * CORBA attribute: Container name (see constructor)
264 //=============================================================================
266 char* Abstract_Engines_Container_i::name()
268 return CORBA::string_dup(_containerName.c_str()) ;
271 //=============================================================================
272 //! Get container working directory
274 * CORBA attribute: Container working directory
276 //=============================================================================
278 char* Abstract_Engines_Container_i::workingdir()
282 return CORBA::string_dup(wd) ;
285 //=============================================================================
286 //! Get container log file name
288 * CORBA attribute: Container log file name
290 //=============================================================================
292 char *Abstract_Engines_Container_i::logfilename()
294 return CORBA::string_dup(_logfilename.c_str()) ;
297 //! Set container log file name
298 void Abstract_Engines_Container_i::logfilename(const char* name)
303 char *Abstract_Engines_Container_i::locallogfilename()
305 return CORBA::string_dup( _localfilename.c_str() );
308 void Abstract_Engines_Container_i::locallogfilename(const char *name)
311 _localfilename = name;
312 AutoPyRef result = PyObject_CallMethod(_pyCont,(char*)"setLogFileName","s",name,nullptr);
313 if (PyErr_Occurred())
315 std::string error("can not set logfilename");
317 THROW_SALOME_CORBA_EXCEPTION(error.c_str(),SALOME::INTERNAL_ERROR);
321 CORBA::Long Abstract_Engines_Container_i::monitoringtimeresms()
324 AutoPyRef result = PyObject_CallMethod(_pyCont,(char*)"monitoringtimeresms",nullptr);
325 if (PyErr_Occurred())
327 std::string error("can not retrieve time interval between 2 measures");
329 THROW_SALOME_CORBA_EXCEPTION(error.c_str(),SALOME::INTERNAL_ERROR);
331 CORBA::Long ret = PyLong_AsLong( result );
335 void Abstract_Engines_Container_i::monitoringtimeresms(CORBA::Long intervalInMs)
338 AutoPyRef result = PyObject_CallMethod(_pyCont,(char*)"SetMonitoringtimeresms","i",intervalInMs,nullptr);
339 if (PyErr_Occurred())
341 std::string error("can not set time interval between 2 measures");
343 THROW_SALOME_CORBA_EXCEPTION(error.c_str(),SALOME::INTERNAL_ERROR);
347 void Abstract_Engines_Container_i::verbosity(bool& activated, CORBA::String_out level)
349 activated = SALOME::VerbosityActivated();
350 level = CORBA::string_dup( SALOME::VerbosityLevelStr().c_str() );
353 void Abstract_Engines_Container_i::setVerbosity(bool activated, const char *level)
355 SALOME::SetVerbosityActivated( activated );
356 SALOME::SetVerbosityLevelStr( level );
359 AutoPyRef res = PyObject_CallMethod(_pyCont,
360 (char*)"positionVerbosityOfLogger",NULL);
365 SALOME::ExceptionStruct es;
366 es.type = SALOME::INTERNAL_ERROR;
367 es.text = "can not create a python node";
368 throw SALOME::SALOME_Exception(es);
373 //=============================================================================
374 //! Get container host name
376 * CORBA method: Get the hostName of the Container (without domain extensions)
378 //=============================================================================
380 char* Abstract_Engines_Container_i::getHostName()
382 std::string s = Kernel_Utils::GetHostname();
383 // MESSAGE("Engines_Container_i::getHostName " << s);
384 return CORBA::string_dup(s.c_str()) ;
387 //=============================================================================
388 //! Get container PID
390 * CORBA method: Get the PID (process identification) of the Container
392 //=============================================================================
394 CORBA::Long Abstract_Engines_Container_i::getPID()
396 return (CORBA::Long)getpid();
399 //=============================================================================
400 //! Ping the servant to check it is still alive
402 * CORBA method: check if servant is still alive
404 //=============================================================================
405 void Abstract_Engines_Container_i::ping()
407 MESSAGE("Engines_Container_i::ping() pid "<< getpid());
410 //=============================================================================
411 //! Get number of CPU cores in the calculation node
413 * CORBA method: get number of CPU cores
415 //=============================================================================
417 CORBA::Long Abstract_Engines_Container_i::getNumberOfCPUCores()
420 PyObject *module = PyImport_ImportModuleNoBlock((char*)"salome_psutil");
421 AutoPyRef result = PyObject_CallMethod(module,
422 (char*)"getNumberOfCPUCores", NULL);
423 int n = PyLong_AsLong(result);
424 return (CORBA::Long)n;
427 //=============================================================================
428 //! Get a load of each CPU core in the calculation node
430 * CORBA method: get a load of each CPU core
432 //=============================================================================
442 PyStdOut_dealloc(PyStdOut *self)
448 PyStdOut_write(PyStdOut* self, PyObject* args)
451 if (!PyArg_ParseTuple(args, "s", &c))
454 *(self->out) = *(self->out) + c;
460 static PyMethodDef PyStdOut_methods[] =
462 {"write", (PyCFunction)PyStdOut_write, METH_VARARGS,
463 PyDoc_STR("write(string) -> None")},
464 {0, 0, 0, 0} /* sentinel */
467 static PyMemberDef PyStdOut_memberlist[] =
469 {(char*)"softspace", T_INT, offsetof(PyStdOut, softspace), 0,
470 (char*)"flag indicating that a space needs to be printed; used by print"},
471 {0, 0, 0, 0, 0} /* sentinel */
474 static PyTypeObject PyStdOut_Type =
476 /* The ob_type field must be initialized in the module init function
477 * to be portable to Windows without using C++. */
478 PyVarObject_HEAD_INIT(NULL, 0)
481 sizeof(PyStdOut), /*tp_basicsize*/
484 (destructor)PyStdOut_dealloc, /*tp_dealloc*/
491 0, /*tp_as_sequence*/
496 PyObject_GenericGetAttr, /*tp_getattro*/
497 /* softspace is writable: we must supply tp_setattro */
498 PyObject_GenericSetAttr, /* tp_setattro */
500 Py_TPFLAGS_DEFAULT, /*tp_flags*/
504 0, /*tp_richcompare*/
505 0, /*tp_weaklistoffset*/
508 PyStdOut_methods, /*tp_methods*/
509 PyStdOut_memberlist, /*tp_members*/
527 0, /*tp_version_tag*/
531 PyObject* newPyStdOut(std::string& out)
533 PyStdOut* self = PyObject_New(PyStdOut, &PyStdOut_Type);
538 return (PyObject*)self;
541 std::string parseException()
544 if (PyErr_Occurred())
546 #ifdef BOS26455_WITH_BOOST_PYTHON
547 PyObject *ptype = nullptr;
548 PyObject *pvalue = nullptr;
549 PyObject *ptraceback = nullptr;
550 PyErr_Fetch(&ptype, &pvalue, &ptraceback);
551 if (ptype == nullptr)
552 return std::string("Null exception type");
553 PyErr_NormalizeException(&ptype, &pvalue, &ptraceback);
554 if (ptraceback != nullptr)
555 PyException_SetTraceback(pvalue, ptraceback);
556 boost::python::handle<> htype(ptype);
557 boost::python::handle<> hvalue(boost::python::allow_null(pvalue));
558 boost::python::handle<> htraceback(boost::python::allow_null(ptraceback));
559 boost::python::object traceback = boost::python::import("traceback");
560 boost::python::object format_exc = traceback.attr("format_exception");
561 boost::python::object formatted = format_exc(htype, hvalue, htraceback);
562 error = boost::python::extract<std::string>(boost::python::str("\n").join(formatted));
564 PyObject* new_stderr = newPyStdOut(error);
565 PyObject* old_stderr = PySys_GetObject((char*)"stderr");
566 Py_INCREF(old_stderr);
567 PySys_SetObject((char*)"stderr", new_stderr);
569 PySys_SetObject((char*)"stderr", old_stderr);
570 Py_DECREF(new_stderr);
577 Engines::vectorOfDouble* Abstract_Engines_Container_i::loadOfCPUCores()
580 PyObject *module = PyImport_ImportModuleNoBlock((char*)"salome_psutil");
581 AutoPyRef result = PyObject_CallMethod(module,
582 (char*)"loadOfCPUCores", "s",
583 _load_script.c_str());
584 if (PyErr_Occurred())
586 std::string error = parseException();
588 SALOME::ExceptionStruct es;
589 es.type = SALOME::INTERNAL_ERROR;
590 es.text = CORBA::string_dup(error.c_str());
591 throw SALOME::SALOME_Exception(es);
594 int n = this->getNumberOfCPUCores();
595 if (!PyList_Check(result) || PyList_Size(result) != n) {
596 // bad number of cores
597 SALOME::ExceptionStruct es;
598 es.type = SALOME::INTERNAL_ERROR;
599 es.text = "wrong number of cores";
600 throw SALOME::SALOME_Exception(es);
603 Engines::vectorOfDouble_var loads = new Engines::vectorOfDouble;
605 for (Py_ssize_t i = 0; i < PyList_Size(result); ++i) {
606 PyObject* item = PyList_GetItem(result, i);
607 double foo = PyFloat_AsDouble(item);
608 if (foo < 0.0 || foo > 1.0)
610 // value not in [0, 1] range
611 SALOME::ExceptionStruct es;
612 es.type = SALOME::INTERNAL_ERROR;
613 es.text = "load not in [0, 1] range";
614 throw SALOME::SALOME_Exception(es);
619 return loads._retn();
622 //=============================================================================
623 //! Set custom script to calculate a load of each CPU core
625 * CORBA method: Set custom script to calculate CPU load
626 * \param script Python script to execute
628 //=============================================================================
630 void Abstract_Engines_Container_i::setPyScriptForCPULoad(const char *script)
632 _load_script = script;
635 //=============================================================================
636 //! Nullify custom script to calculate each CPU core's load
638 * CORBA method: reset script for load calculation to default implementation
640 //=============================================================================
642 void Abstract_Engines_Container_i::resetScriptForCPULoad()
647 //=============================================================================
648 //! Get total physical memory of calculation node, in megabytes
650 * CORBA method: get total physical memory of calculation node
652 //=============================================================================
654 CORBA::Long Abstract_Engines_Container_i::getTotalPhysicalMemory()
657 PyObject *module = PyImport_ImportModuleNoBlock((char*)"salome_psutil");
658 AutoPyRef result = PyObject_CallMethod(module,
659 (char*)"getTotalPhysicalMemory", NULL);
660 int n = PyLong_AsLong(result);
662 return (CORBA::Long)n;
665 //=============================================================================
666 //! Get used physical memory of calculation node, in megabytes
668 * CORBA method: get used physical memory of calculation node
670 //=============================================================================
672 CORBA::Long Abstract_Engines_Container_i::getTotalPhysicalMemoryInUse()
675 PyObject *module = PyImport_ImportModuleNoBlock((char*)"salome_psutil");
676 AutoPyRef result = PyObject_CallMethod(module,
677 (char*)"getTotalPhysicalMemoryInUse", NULL);
678 int n = PyLong_AsLong(result);
680 return (CORBA::Long)n;
683 //=============================================================================
684 //! Obtain physical memory, used by the current process, in megabytes.
686 * CORBA method: get physical memory, used by the current process
688 //=============================================================================
690 CORBA::Long Abstract_Engines_Container_i::getTotalPhysicalMemoryInUseByMe()
693 PyObject *module = PyImport_ImportModuleNoBlock((char*)"salome_psutil");
694 AutoPyRef result = PyObject_CallMethod(module,
695 (char*)"getTotalPhysicalMemoryInUseByMe", NULL);
696 int n = PyLong_AsLong(result);
698 return (CORBA::Long)n;
701 //=============================================================================
702 //! Shutdown the container
704 * CORBA method, oneway: Server shutdown.
705 * - Container name removed from naming service,
706 * - servant deactivation,
707 * - orb shutdown if no other servants in the process
709 //=============================================================================
710 void Abstract_Engines_Container_i::Shutdown()
712 MESSAGE("Engines_Container_i::Shutdown()");
714 // Clear registered temporary files
715 clearTemporaryFiles();
717 /* For each component contained in this container
718 * tell it to self-destroy
720 std::map<std::string, Engines::EngineComponent_var>::iterator itm;
721 for (itm = _listInstances_map.begin(); itm != _listInstances_map.end(); itm++)
725 itm->second->destroy();
727 catch(const CORBA::Exception&)
729 // ignore this entry and continue
733 // ignore this entry and continue
736 _listInstances_map.clear();
738 // NS unregistering may throw in SSL mode if master process hosting SALOME_Embedded_NamingService servant has vanished
739 // In this case it's skip it and still continue.
742 _NS->Destroy_FullDirectory(_containerName.c_str());
743 _NS->Destroy_Name(_containerName.c_str());
749 this->cleanAllPyScripts();
753 AutoPyRef result = PyObject_CallMethod(_pyCont, (char*)"shutdownPy", (char*)"",nullptr);
756 if(_isServantAloneInProcess)
758 MESSAGE("Effective Shutdown of container Begins...");
759 if(!CORBA::is_nil(_orb))
764 //=============================================================================
765 //! load a component implementation
768 * \param componentName component name
769 * \param reason explains error when load fails
770 * \return true if dlopen successful or already done, false otherwise
772 //=============================================================================
774 Abstract_Engines_Container_i::load_component_Library(const char* componentName, CORBA::String_out reason)
777 //=================================================================
778 // --- C++ implementation section
779 //=================================================================
781 if(load_component_CppImplementation(componentName,retso))
783 reason=CORBA::string_dup("");
786 else if(retso != "ImplementationNotFound")
788 reason=CORBA::string_dup(retso.c_str());
793 retso+=componentName;
794 retso+=": Can't find C++ implementation ";
795 retso+=std::string(LIB) + componentName + ENGINESO;
797 //=================================================================
798 // --- Python implementation section
799 //=================================================================
801 if(load_component_PythonImplementation(componentName,retpy))
803 reason=CORBA::string_dup("");
806 else if(retpy != "ImplementationNotFound")
808 reason=CORBA::string_dup(retpy.c_str());
813 retpy+=componentName;
814 retpy+=": Can't find python implementation ";
815 retpy+=componentName;
818 //=================================================================
819 // -- Executable implementation section
820 //=================================================================
822 if(load_component_ExecutableImplementation(componentName,retex))
824 reason=CORBA::string_dup("");
827 else if(retex != "ImplementationNotFound")
829 reason=CORBA::string_dup(retex.c_str());
834 retex+=componentName;
835 retex+=": Can't find executable implementation ";
836 retex+=componentName;
839 std::string ret="Component implementation not found: ";
840 ret += componentName ;
846 std::cerr << ret << std::endl;
847 reason=CORBA::string_dup(ret.c_str());
852 //=============================================================================
853 //! try to load a C++ component implementation
856 * \param componentName the name of the component (COMPONENT, for example)
857 * \param reason explains error when load fails
858 * \return true if loading is successful or already done, false otherwise
860 //=============================================================================
862 Abstract_Engines_Container_i::load_component_CppImplementation(const char* componentName, std::string& reason)
864 std::string aCompName(componentName);
865 std::string impl_name = std::string(LIB) + aCompName + ENGINESO;
868 _numInstanceMutex.lock(); // lock to be alone
869 // (see decInstanceCnt, finalize_removal))
870 if (_toRemove_map.count(impl_name) != 0) _toRemove_map.erase(impl_name);
871 if (_library_map.count(impl_name) != 0)
873 MESSAGE("Library " << impl_name << " already loaded");
874 _numInstanceMutex.unlock();
878 _numInstanceMutex.unlock();
882 handle = dlopen( impl_name.c_str() , RTLD_NOW | RTLD_GLOBAL ) ;
885 //not loadable. Try to find the lib file in LD_LIBRARY_PATH
888 char* p=getenv("DYLD_LIBRARY_PATH");
890 char* p=getenv("LD_LIBRARY_PATH");
893 path=path+SEP+"/usr/lib"+SEP+"/lib";
896 if(findpathof(path, pth, impl_name))
898 //found but not loadable
901 reason+=": C++ implementation found ";
903 reason+=" but it is not loadable. Error:\n";
905 std::cerr << reason << std::endl;
911 //continue with other implementation
912 reason="ImplementationNotFound";
919 std::wstring libToLoad = Kernel_Utils::utf8_decode_s( impl_name );
921 std::string libToLoad = impl_name;
923 handle = LoadLibrary(libToLoad.c_str() );
926 reason="ImplementationNotFound";
932 _numInstanceMutex.lock();
933 _library_map[impl_name] = handle;
934 _numInstanceMutex.unlock();
942 //=============================================================================
943 //! try to load a Python component implementation
946 * \param componentName name of the component
947 * \param reason explains error when load fails
948 * \return true if loading is successful or already done, false otherwise
950 //=============================================================================
952 Abstract_Engines_Container_i::load_component_PythonImplementation(const char* componentName, std::string& reason)
954 std::string aCompName(componentName);
956 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
957 if (_library_map.count(aCompName) != 0)
959 _numInstanceMutex.unlock() ;
961 return true; // Python Component, already imported
963 _numInstanceMutex.unlock() ;
967 AutoPyRef result = PyObject_CallMethod(_pyCont,
968 (char*)"import_component",
969 (char*)"s",componentName);
971 reason=PyUnicode_AsUTF8(result);
977 //Python component has been loaded (import componentName)
978 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
979 _library_map[aCompName] = (void *)_pyCont; // any non O value OK
980 _numInstanceMutex.unlock() ;
981 MESSAGE("import Python: "<< aCompName <<" OK");
984 else if(reason=="ImplementationNotFound")
986 //Python implementation has not been found. Continue with other implementation
987 reason="ImplementationNotFound";
991 //Python implementation has been found but loading has failed
992 std::cerr << reason << std::endl;
997 //=============================================================================
998 //! try to load a Executable component implementation
1001 * \param componentName name of the component
1002 * \param reason explains error when load fails
1003 * \return true if loading is successful or already done, false otherwise
1005 //=============================================================================
1007 Abstract_Engines_Container_i::load_component_ExecutableImplementation(const char* componentName, std::string& reason)
1009 std::string aCompName(componentName);
1010 std::string executable=aCompName+".exe";
1015 char* p=getenv("PATH");
1018 if (findpathof(path, pth, executable))
1020 if(checkifexecutable(pth))
1022 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1023 _library_map[executable] = (void *)1; // any non O value OK
1024 _numInstanceMutex.unlock() ;
1025 MESSAGE("import executable: "<< pth <<" OK");
1029 reason="Component ";
1031 reason+=": implementation found ";
1033 reason+=" but it is not executable";
1034 std::cerr << reason << std::endl;
1038 reason="ImplementationNotFound";
1043 //=============================================================================
1044 //! Create a new component instance
1046 * CORBA method: Creates a new servant instance of a component.
1047 * The servant registers itself to naming service and Registry.tdlib
1048 * \param genericRegisterName Name of the component instance to register
1049 * in Registry & Name Service (without _inst_n suffix)
1050 * \return a loaded component
1052 //=============================================================================
1053 Engines::EngineComponent_ptr
1054 Abstract_Engines_Container_i::create_component_instance(const char*genericRegisterName)
1056 Engines::FieldsDict_var env = new Engines::FieldsDict;
1058 Engines::EngineComponent_ptr compo =
1059 create_component_instance_env(genericRegisterName, env, reason);
1060 CORBA::string_free(reason);
1064 void EffectiveOverrideEnvironment( const Engines::FieldsDict& env )
1066 MESSAGE("Positionning environment on container ");
1067 for (CORBA::ULong i=0; i < env.length(); i++)
1069 if (env[i].value.type()->kind() == CORBA::tk_string)
1071 const char *value = nullptr;
1072 env[i].value >>= value;
1073 MESSAGE( env[i].key << " = " << value);
1075 if( setenv(env[i].key,value,1) != 0 )
1078 std::string sErr( strerror( errsv) );
1086 std::vector< std::pair<std::string,std::string> > GetOSEnvironment()
1088 std::vector< std::pair<std::string,std::string> > ret;
1090 char **envPt( environ );
1091 for(;*envPt != nullptr; ++envPt)
1093 std::string s( *envPt );
1094 auto pos = s.find_first_of('=');
1095 std::string k( s.substr(0,pos) ),v( s.substr(pos+1) );
1096 ret.emplace_back( std::pair<std::string,std::string>(k,v) );
1102 void Abstract_Engines_Container_i::override_environment( const Engines::FieldsDict& env )
1104 EffectiveOverrideEnvironment(env);
1107 void Abstract_Engines_Container_i::override_environment_python( const Engines::FieldsDict& env )
1109 constexpr char NODE_NAME[] = "ScriptNodeForEnv";
1110 constexpr char SCRIPT[] = R"foo(
1115 Engines::PyScriptNode_var scriptNode = this->createPyScriptNode(NODE_NAME,SCRIPT);
1116 auto sz = env.length();
1117 Engines::listofstring keys, vals;
1118 keys.length( sz ); vals.length( sz );
1119 for( auto i = 0 ; i < sz ; ++i )
1121 keys[i] = CORBA::string_dup( env[i].key );
1122 const char *value = nullptr;
1123 env[i].value >>= value;
1124 vals[i] = CORBA::string_dup( value );
1126 scriptNode->executeSimple(keys,vals);
1127 this->removePyScriptNode(NODE_NAME);
1130 Engines::FieldsDict *Abstract_Engines_Container_i::get_os_environment()
1132 std::unique_ptr<Engines::FieldsDict> ret( new Engines::FieldsDict );
1133 std::vector< std::pair<std::string,std::string> > retCpp( GetOSEnvironment() );
1134 auto sz = retCpp.size();
1136 for(auto i = 0 ; i < sz ; ++i)
1138 (*ret)[i].key = CORBA::string_dup( retCpp[i].first.c_str() );
1139 (*ret)[i].value <<= CORBA::string_dup( retCpp[i].second.c_str() );
1141 return ret.release();
1144 void Abstract_Engines_Container_i::execute_python_code(const char *code)
1147 if( PyRun_SimpleString( code ) != 0 )
1149 std::string error = parseException();
1150 THROW_SALOME_CORBA_EXCEPTION(error.c_str(),SALOME::INTERNAL_ERROR);
1154 //=============================================================================
1155 //! Create a new component instance with environment variables specified
1157 * CORBA method: Creates a new servant instance of a component.
1158 * The servant registers itself to naming service and Registry.
1159 * \param genericRegisterName Name of the component instance to register
1160 * in Registry & Name Service (without _inst_n suffix)
1161 * \param env dict of env variables
1162 * \param reason explains error when create_component_instance_env fails
1163 * \return a loaded component
1165 //=============================================================================
1166 Engines::EngineComponent_ptr
1167 Abstract_Engines_Container_i::create_component_instance_env(const char*genericRegisterName,
1168 const Engines::FieldsDict& env,
1169 CORBA::String_out reason)
1172 if (_library_map.count(genericRegisterName) != 0)
1174 // It's a Python component
1175 Engines::EngineComponent_ptr compo = createPythonInstance(genericRegisterName, error);
1176 reason=CORBA::string_dup(error.c_str());
1180 std::string impl_name = std::string(LIB) + genericRegisterName + ENGINESO;
1181 if (_library_map.count(impl_name) != 0)
1183 // It's a C++ component
1184 void* handle = _library_map[impl_name];
1185 Engines::EngineComponent_ptr compo = createInstance(genericRegisterName, handle, error);
1186 reason=CORBA::string_dup(error.c_str());
1190 impl_name = std::string(genericRegisterName) + ".exe";
1191 if (_library_map.count(impl_name) != 0)
1193 //It's an executable component
1194 Engines::EngineComponent_ptr compo = createExecutableInstance(genericRegisterName, env, error);
1195 reason=CORBA::string_dup(error.c_str());
1199 error="load_component_Library has probably not been called for component: ";
1200 error += genericRegisterName;
1202 reason=CORBA::string_dup(error.c_str());
1203 return Engines::EngineComponent::_nil() ;
1206 //=============================================================================
1207 //! Create a new component instance (Executable implementation)
1209 * \param CompName Name of the component instance
1210 * \param env dict of env variables
1211 * \param reason explains error when creation fails
1212 * \return a loaded component
1214 * This component is implemented in an executable with name genericRegisterName.exe
1215 * It must register itself in Naming Service. The container waits some time (10 s max)
1216 * it's registration.
1218 //=============================================================================
1219 Engines::EngineComponent_ptr
1220 Abstract_Engines_Container_i::createExecutableInstance(std::string CompName,
1221 const Engines::FieldsDict& env,
1222 std::string& reason)
1224 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1226 _numInstanceMutex.lock() ; // lock on the instance number
1228 int numInstance = _numInstance ;
1229 _numInstanceMutex.unlock() ;
1232 sprintf( aNumI , "%d" , numInstance ) ;
1233 std::string instanceName = CompName + "_inst_" + aNumI ;
1234 std::string component_registerName = _containerName + "/" + instanceName;
1236 //check if an entry exist in naming service
1237 CORBA::Object_var nsobj = _NS->Resolve(component_registerName.c_str());
1238 if ( !CORBA::is_nil(nsobj) )
1240 // unregister the registered component
1241 _NS->Destroy_Name(component_registerName.c_str());
1242 //kill or shutdown it ???
1245 // first arg container ior string
1246 // second arg container name
1247 // third arg instance name
1249 Engines::Container_var pCont= _this();
1250 CORBA::String_var sior = _orb->object_to_string(pCont);
1252 std::string command;
1253 command="mkdir -p ";
1254 command+=instanceName;
1256 command+=instanceName;
1261 command+= sior; // container ior string
1263 command+=_containerName; //container name
1265 command+=instanceName; //instance name
1267 MESSAGE("SALOME_Container::create_component_instance command=" << command);
1270 // use fork/execl instead of system to get finer control on env variables
1273 if(pid == 0) // child
1275 EffectiveOverrideEnvironment(env);
1277 execl("/bin/sh", "sh", "-c", command.c_str() , (char *)0);
1280 else if(pid < 0) // failed to fork
1289 tpid = wait(&status);
1290 } while (tpid != pid);
1293 // launch component with a system call
1294 int status=system(command.c_str());
1299 reason="SALOME_Container::create_component_instance system failed (system command status -1)";
1301 return Engines::EngineComponent::_nil();
1304 else if (WEXITSTATUS(status) == 217)
1306 reason="SALOME_Container::create_component_instance system failed (system command status 217)";
1308 return Engines::EngineComponent::_nil();
1314 if (getenv("TIMEOUT_TO_WAIT_EXE_COMPONENT") != 0)
1316 std::string new_count_str = getenv("TIMEOUT_TO_WAIT_EXE_COMPONENT");
1318 std::istringstream ss(new_count_str);
1319 if (!(ss >> new_count))
1321 INFOS("[Container] TIMEOUT_TO_WAIT_EXE_COMPONENT should be an int");
1326 INFOS("[Container] waiting " << count << " second steps exe component ");
1327 CORBA::Object_var obj = CORBA::Object::_nil() ;
1328 while ( CORBA::is_nil(obj) && count )
1336 MESSAGE( count << ". Waiting for component " << CompName);
1337 obj = _NS->Resolve(component_registerName.c_str());
1340 if(CORBA::is_nil(obj))
1342 reason="SALOME_Container::create_component_instance failed";
1344 return Engines::EngineComponent::_nil();
1348 MESSAGE("SALOME_Container::create_component_instance successful");
1349 iobject = Engines::EngineComponent::_narrow(obj);
1350 _listInstances_map[instanceName] = iobject;
1351 return iobject._retn();
1357 //=============================================================================
1358 //! Create a new component instance (Python implementation)
1360 * \param CompName Name of the component instance
1361 * \param reason explains error when creation fails
1362 * \return a loaded component
1364 //=============================================================================
1365 Engines::EngineComponent_ptr
1366 Abstract_Engines_Container_i::createPythonInstance(std::string CompName,
1367 std::string& reason)
1369 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1371 _numInstanceMutex.lock() ; // lock on the instance number
1373 int numInstance = _numInstance ;
1374 _numInstanceMutex.unlock() ;
1377 sprintf( aNumI , "%d" , numInstance ) ;
1378 std::string instanceName = CompName + "_inst_" + aNumI ;
1379 std::string component_registerName = _containerName + "/" + instanceName;
1383 AutoPyRef result = PyObject_CallMethod(_pyCont,
1384 (char*)"create_component_instance",
1387 instanceName.c_str());
1390 PyArg_ParseTuple(result,"ss", &ior, &error);
1397 CORBA::Object_var obj = _orb->string_to_object(iors.c_str());
1398 iobject = Engines::EngineComponent::_narrow( obj ) ;
1399 _listInstances_map[instanceName] = iobject;
1401 return iobject._retn();
1405 Abstract_Engines_Container_i::create_python_service_instance(const char * CompName,
1406 CORBA::String_out reason)
1408 CORBA::Object_var object = CORBA::Object::_nil();
1410 _numInstanceMutex.lock() ; // lock on the instance number
1412 int numInstance = _numInstance ;
1413 _numInstanceMutex.unlock() ;
1416 sprintf( aNumI , "%d" , numInstance ) ;
1417 std::string instanceName = std::string(CompName) + "_inst_" + aNumI ;
1418 std::string component_registerName = _containerName + "/" + instanceName;
1420 char * _ior = nullptr;
1423 AutoPyRef result = PyObject_CallMethod(_pyCont,
1424 (char*)"create_component_instance",
1427 instanceName.c_str());
1430 PyArg_ParseTuple(result,"ss", &ior, &error);
1431 reason = CORBA::string_dup(error);
1432 _ior = CORBA::string_dup(ior);
1438 //=============================================================================
1439 //! Create a new component instance (C++ implementation)
1441 * C++ method: create a servant instance of a component.
1442 * \param genericRegisterName Name of the component instance to register
1443 * in Registry & Name Service,
1444 * (without _inst_n suffix, like "COMPONENT")
1445 * \param handle loaded library handle
1446 * \param reason explains error when creation fails
1447 * \return a loaded component
1449 * example with names:
1450 * - aGenRegisterName = COMPONENT (= first argument)
1451 * - _containerName = /Containers/cli76ce/FactoryServer
1452 * - factoryName = COMPONENTEngine_factory
1453 * - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
1454 * - instanceName = COMPONENT_inst_1
1455 * - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1457 //=============================================================================
1458 Engines::EngineComponent_ptr
1459 Abstract_Engines_Container_i::createInstance(std::string genericRegisterName,
1461 std::string& reason)
1463 // --- find the factory
1465 std::string aGenRegisterName = genericRegisterName;
1466 std::string factory_name = aGenRegisterName + std::string("Engine_factory");
1467 SCRUTE(factory_name) ;
1469 typedef PortableServer::ObjectId* (*FACTORY_FUNCTION) (CORBA::ORB_ptr,
1470 PortableServer::POA_ptr,
1471 PortableServer::ObjectId *,
1476 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)dlsym( handle, factory_name.c_str() );
1478 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)GetProcAddress( (HINSTANCE)handle, factory_name.c_str() );
1481 if ( !Component_factory )
1483 MESSAGE( "Can't resolve symbol: " + factory_name );
1488 return Engines::EngineComponent::_nil() ;
1491 // --- create instance
1493 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1497 _numInstanceMutex.lock() ; // lock on the instance number
1499 int numInstance = _numInstance ;
1500 _numInstanceMutex.unlock() ;
1503 sprintf( aNumI , "%d" , numInstance ) ;
1504 std::string instanceName = aGenRegisterName + "_inst_" + aNumI ;
1505 std::string component_registerName =
1506 _containerName + "/" + instanceName;
1508 // --- Instantiate required CORBA object
1510 PortableServer::ObjectId *id ; //not owner, do not delete (nore use var)
1511 id = (Component_factory) ( _orb, _poa, _id, instanceName.c_str(),
1512 aGenRegisterName.c_str() ) ;
1515 reason="Can't get ObjectId from factory";
1517 return iobject._retn();
1520 // --- get reference from id
1522 CORBA::Object_var obj = _poa->id_to_reference(*id);
1523 iobject = Engines::EngineComponent::_narrow( obj ) ;
1525 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1526 _listInstances_map[instanceName] = iobject;
1527 _cntInstances_map[aGenRegisterName] += 1;
1528 _numInstanceMutex.unlock() ;
1529 SCRUTE(aGenRegisterName);
1530 SCRUTE(_cntInstances_map[aGenRegisterName]);
1532 // --- register the engine under the name
1533 // containerName(.dir)/instanceName(.object)
1535 _NS->Register( iobject , component_registerName.c_str() ) ;
1536 MESSAGE( component_registerName.c_str() << " bound" ) ;
1540 reason="Container_i::createInstance exception caught";
1543 return iobject._retn();
1546 //=============================================================================
1547 //! Find an existing (in the container) component instance
1549 * CORBA method: Finds a servant instance of a component
1550 * \param registeredName Name of the component in Registry or Name Service,
1551 * without instance suffix number
1552 * \return the first found instance
1554 //=============================================================================
1555 Engines::EngineComponent_ptr
1556 Abstract_Engines_Container_i::find_component_instance( const char* registeredName)
1558 Engines::EngineComponent_var anEngine = Engines::EngineComponent::_nil();
1559 std::map<std::string,Engines::EngineComponent_var>::iterator itm =_listInstances_map.begin();
1560 while (itm != _listInstances_map.end())
1562 std::string instance = (*itm).first;
1564 if (instance.find(registeredName) == 0)
1566 anEngine = (*itm).second;
1567 return anEngine._retn();
1571 return anEngine._retn();
1574 //=============================================================================
1575 //! Remove the component instance from container
1577 * CORBA method: Stops the component servant, and deletes all related objects
1578 * \param component_i Component to be removed
1580 //=============================================================================
1582 void Abstract_Engines_Container_i::remove_impl(Engines::EngineComponent_ptr component_i)
1584 ASSERT(! CORBA::is_nil(component_i));
1585 std::string instanceName = component_i->instanceName() ;
1586 MESSAGE("unload component " << instanceName);
1587 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1588 _listInstances_map.erase(instanceName);
1589 _numInstanceMutex.unlock() ;
1590 component_i->destroy() ;
1591 _NS->Destroy_Name(instanceName.c_str());
1594 //=============================================================================
1595 //! Unload component libraries from the container
1597 * CORBA method: Discharges unused libraries from the container.
1599 //=============================================================================
1600 void Abstract_Engines_Container_i::finalize_removal()
1602 MESSAGE("finalize unload : dlclose");
1603 _numInstanceMutex.lock(); // lock to be alone
1604 // (see decInstanceCnt, load_component_Library)
1605 std::map<std::string, void *>::iterator ith;
1606 for (ith = _toRemove_map.begin(); ith != _toRemove_map.end(); ith++)
1608 void *handle = (*ith).second;
1609 std::string impl_name= (*ith).first;
1614 // dlclose(handle); // SALOME unstable after ...
1615 // _library_map.erase(impl_name);
1618 _toRemove_map.clear();
1619 _numInstanceMutex.unlock();
1622 //=============================================================================
1623 //! Decrement component instance reference count
1627 //=============================================================================
1628 void Abstract_Engines_Container_i::decInstanceCnt(std::string genericRegisterName)
1630 if(_cntInstances_map.count(genericRegisterName)==0)
1632 std::string aGenRegisterName =genericRegisterName;
1633 MESSAGE("Engines_Container_i::decInstanceCnt " << aGenRegisterName);
1634 ASSERT(_cntInstances_map[aGenRegisterName] > 0);
1635 _numInstanceMutex.lock(); // lock to be alone
1636 // (see finalize_removal, load_component_Library)
1637 _cntInstances_map[aGenRegisterName] -= 1;
1638 SCRUTE(_cntInstances_map[aGenRegisterName]);
1639 if (_cntInstances_map[aGenRegisterName] == 0)
1641 std::string impl_name =
1642 Engines_Component_i::GetDynLibraryName(aGenRegisterName.c_str());
1644 void* handle = _library_map[impl_name];
1646 _toRemove_map[impl_name] = handle;
1648 _numInstanceMutex.unlock();
1651 //=============================================================================
1652 //! Find or create a new component instance
1654 * CORBA method: find or create an instance of the component (servant),
1655 * load a new component class (dynamic library) if required,
1657 * ---- FOR COMPATIBILITY WITH 2.2 ----
1659 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
1661 * The servant registers itself to naming service and Registry.
1662 * \param genericRegisterName Name of the component to register
1663 * in Registry & Name Service
1664 * \param componentName Name of the constructed library of the component
1665 * \return a loaded component
1667 //=============================================================================
1669 Engines::EngineComponent_ptr
1670 Abstract_Engines_Container_i::load_impl( const char* genericRegisterName,
1671 const char* /*componentName*/ )
1674 std::string impl_name = std::string(LIB) + genericRegisterName + ENGINESO;
1675 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1676 if (load_component_Library(genericRegisterName,reason))
1677 iobject = find_or_create_instance(genericRegisterName, impl_name);
1678 CORBA::string_free(reason);
1679 return iobject._retn();
1682 Engines::EmbeddedNamingService_ptr Abstract_Engines_Container_i::get_embedded_NS_if_ssl()
1684 SALOME_Embedded_NamingService_Client *nsc(dynamic_cast<SALOME_Embedded_NamingService_Client *>(this->_NS));
1687 Engines::EmbeddedNamingService_var obj = nsc->GetObject();
1688 return Engines::EmbeddedNamingService::_duplicate(obj);
1692 SALOME_Fake_NamingService *fns(dynamic_cast<SALOME_Fake_NamingService *>(this->_NS));
1695 Engines::EmbeddedNamingService_var ret = GetEmbeddedNamingService();
1699 return Engines::EmbeddedNamingService::_nil();
1703 //=============================================================================
1704 //! Finds an already existing component instance or create a new instance
1706 * C++ method: Finds an already existing servant instance of a component, or
1707 * create an instance.
1708 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
1709 * \param genericRegisterName Name of the component instance to register
1710 * in Registry & Name Service,
1711 * (without _inst_n suffix, like "COMPONENT")
1712 * \param componentLibraryName like "libCOMPONENTEngine.so"
1713 * \return a loaded component
1715 * example with names:
1716 * - aGenRegisterName = COMPONENT (= first argument)
1717 * - impl_name = libCOMPONENTEngine.so (= second argument)
1718 * - _containerName = /Containers/cli76ce/FactoryServer
1719 * - factoryName = COMPONENTEngine_factory
1720 * - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
1721 * - instanceName = COMPONENT_inst_1
1722 * - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1724 //=============================================================================
1726 Engines::EngineComponent_ptr
1727 Abstract_Engines_Container_i::find_or_create_instance(std::string genericRegisterName,
1728 std::string componentLibraryName)
1730 std::string aGenRegisterName = genericRegisterName;
1731 std::string impl_name = componentLibraryName;
1732 if (_library_map.count(impl_name) == 0)
1734 INFOS("shared library " << impl_name <<" must be loaded before creating instance");
1735 return Engines::EngineComponent::_nil() ;
1739 // --- find a registered instance in naming service, or create
1741 void* handle = _library_map[impl_name];
1742 std::string component_registerBase =
1743 _containerName + "/" + aGenRegisterName;
1744 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1748 CORBA::Object_var obj =
1749 _NS->ResolveFirst( component_registerBase.c_str());
1750 if ( CORBA::is_nil( obj ) )
1752 iobject = createInstance(genericRegisterName,
1758 iobject = Engines::EngineComponent::_narrow( obj ) ;
1763 INFOS( "Container_i::load_impl caught" ) ;
1765 return iobject._retn();
1769 //=============================================================================
1770 //! Indicate if container is a python one
1772 * Retrieves only with container naming convention if it is a python container
1774 //=============================================================================
1775 bool Abstract_Engines_Container_i::isPythonContainer(const char* ContainerName)
1778 size_t len=strlen(ContainerName);
1780 if(strcmp(ContainerName+len-2,"Py")==0)
1785 //=============================================================================
1786 //! Kill the container
1788 * CORBA method: Kill the container process with exit(0).
1789 * To remove : never returns !
1791 //=============================================================================
1792 bool Abstract_Engines_Container_i::Kill_impl()
1794 MESSAGE("Engines_Container_i::Kill() pid "<< getpid() << " containerName "
1795 << _containerName.c_str() << " machineName "
1796 << Kernel_Utils::GetHostname().c_str());
1797 INFOS("===============================================================");
1798 INFOS("= REMOVE calls to Kill_impl in C++ container =");
1799 INFOS("===============================================================");
1805 //=============================================================================
1809 //=============================================================================
1810 void ActSigIntHandler()
1813 struct sigaction SigIntAct ;
1814 SigIntAct.sa_sigaction = &SigIntHandler ;
1815 sigemptyset(&SigIntAct.sa_mask);
1816 SigIntAct.sa_flags = SA_SIGINFO ;
1819 // DEBUG 03.02.2005 : the first parameter of sigaction is not a mask of signals
1820 // (SIGINT | SIGUSR1) :
1821 // it must be only one signal ===> one call for SIGINT
1822 // and an other one for SIGUSR1
1825 if ( sigaction( SIGINT , &SigIntAct, NULL ) )
1827 perror("SALOME_Container main ") ;
1830 if ( sigaction( SIGUSR1 , &SigIntAct, NULL ) )
1832 perror("SALOME_Container main ") ;
1835 if ( sigaction( SIGUSR2 , &SigIntAct, NULL ) )
1837 perror("SALOME_Container main ") ;
1841 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1842 // use of streams (and so on) should never be used because :
1843 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1844 // A stream operation may be interrupted by a signal and if the Handler use stream we
1845 // may have a "Dead-Lock" ===HangUp
1846 //==INFOS is commented
1847 // INFOS(pthread_self() << "SigIntHandler activated") ;
1850 signal( SIGINT, SigIntHandler );
1851 // legacy code required to supervisor. Commented in order to avoid problems on Windows
1852 // signal( SIGUSR1, SigIntHandler );
1858 void CallCancelThread() ;
1861 void SigIntHandler(int /*what*/ ,
1862 siginfo_t * siginfo ,
1865 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1866 // use of streams (and so on) should never be used because :
1867 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1868 // A stream operation may be interrupted by a signal and if the Handler use stream we
1869 // may have a "Dead-Lock" ===HangUp
1870 //==MESSAGE is commented
1871 // MESSAGE(pthread_self() << "SigIntHandler what " << what << std::endl
1872 // << " si_signo " << siginfo->si_signo << std::endl
1873 // << " si_code " << siginfo->si_code << std::endl
1874 // << " si_pid " << siginfo->si_pid) ;
1879 // MESSAGE("SigIntHandler END sleeping.") ;
1884 ActSigIntHandler() ;
1885 if ( siginfo->si_signo == SIGUSR1 )
1889 else if ( siginfo->si_signo == SIGUSR2 )
1891 CallCancelThread() ;
1896 // MESSAGE("SigIntHandler BEGIN sleeping.") ;
1903 // MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1909 void SigIntHandler( int what )
1912 MESSAGE( pthread_self() << "SigIntHandler what " << what << std::endl );
1914 MESSAGE( "SigIntHandler what " << what << std::endl );
1919 MESSAGE("SigIntHandler END sleeping.") ;
1924 ActSigIntHandler() ;
1925 if ( what == SIGUSR1 )
1932 MESSAGE("SigIntHandler BEGIN sleeping.") ;
1939 MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1946 //=============================================================================
1947 //! Get or create a file reference object associated to a local file (to transfer it)
1949 * CORBA method: get or create a fileRef object associated to a local file
1950 * (a file on the computer on which runs the container server), which stores
1951 * a list of (machine, localFileName) corresponding to copies already done.
1953 * \param origFileName absolute path for a local file to copy on other
1955 * \return a fileRef object associated to the file.
1957 //=============================================================================
1958 Engines::fileRef_ptr
1959 Abstract_Engines_Container_i::createFileRef(const char* origFileName)
1961 std::string origName(origFileName);
1962 Engines::fileRef_var theFileRef = Engines::fileRef::_nil();
1964 if (origName[0] != '/')
1966 INFOS("path of file to copy must be an absolute path beginning with '/'");
1967 return Engines::fileRef::_nil();
1970 if (CORBA::is_nil(_fileRef_map[origName]))
1972 CORBA::Object_var obj=_poa->id_to_reference(*_id);
1973 Engines::Container_var pCont = Engines::Container::_narrow(obj);
1974 fileRef_i* aFileRef = new fileRef_i(pCont, origFileName);
1975 theFileRef = Engines::fileRef::_narrow(aFileRef->_this());
1976 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1977 _fileRef_map[origName] = theFileRef;
1978 _numInstanceMutex.unlock() ;
1981 theFileRef = Engines::fileRef::_duplicate(_fileRef_map[origName]);
1982 ASSERT(! CORBA::is_nil(theFileRef));
1983 return theFileRef._retn();
1986 //=============================================================================
1987 //! Get a fileTransfer reference
1990 * \return a reference to the fileTransfer object
1992 //=============================================================================
1993 Engines::fileTransfer_ptr
1994 Abstract_Engines_Container_i::getFileTransfer()
1996 Engines::fileTransfer_var aFileTransfer
1997 = Engines::fileTransfer::_duplicate(_fileTransfer);
1998 return aFileTransfer._retn();
2001 //=============================================================================
2002 //! Create a Salome file
2003 //=============================================================================
2004 Engines::Salome_file_ptr
2005 Abstract_Engines_Container_i::createSalome_file(const char* origFileName)
2007 std::string origName(origFileName);
2008 if (CORBA::is_nil(_Salome_file_map[origName]))
2010 Salome_file_i* aSalome_file = new Salome_file_i();
2011 aSalome_file->setContainer(Engines::Container::_duplicate(this->_this()));
2014 aSalome_file->setLocalFile(origFileName);
2015 aSalome_file->recvFiles();
2017 catch (const SALOME::SALOME_Exception& /*e*/) //!< TODO: unused variable
2019 return Engines::Salome_file::_nil();
2022 Engines::Salome_file_var theSalome_file = Engines::Salome_file::_nil();
2023 theSalome_file = Engines::Salome_file::_narrow(aSalome_file->_this());
2024 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
2025 _Salome_file_map[origName] = theSalome_file;
2026 _numInstanceMutex.unlock() ;
2029 Engines::Salome_file_ptr theSalome_file =
2030 Engines::Salome_file::_duplicate(_Salome_file_map[origName]);
2031 ASSERT(!CORBA::is_nil(theSalome_file));
2032 return theSalome_file;
2035 //=============================================================================
2036 /*! \brief copy a file from a remote host (container) to the local host
2037 * \param container the remote container
2038 * \param remoteFile the file to copy locally from the remote host into localFile
2039 * \param localFile the local file
2041 //=============================================================================
2042 void Abstract_Engines_Container_i::copyFile(Engines::Container_ptr container, const char* remoteFile, const char* localFile)
2044 Engines::fileTransfer_var fileTransfer = container->getFileTransfer();
2047 if ((fp = fopen(localFile,"wb")) == NULL)
2049 INFOS("file " << localFile << " cannot be open for writing");
2053 CORBA::Long fileId = fileTransfer->open(remoteFile);
2056 Engines::fileBlock* aBlock;
2063 aBlock = fileTransfer->getBlock(fileId);
2064 toFollow = aBlock->length();
2066 CORBA::Octet *buf = aBlock->get_buffer();
2067 fwrite(buf, sizeof(CORBA::Octet), toFollow, fp);
2071 MESSAGE("end of transfer");
2072 fileTransfer->close(fileId);
2076 INFOS("open reference file for copy impossible");
2080 //=============================================================================
2081 /*! \brief create a PyNode object to execute remote python code
2082 * \param nodeName the name of the node
2083 * \param code the python code to load
2084 * \return the PyNode
2086 //=============================================================================
2087 Engines::PyNode_ptr Abstract_Engines_Container_i::createPyNode(const char* nodeName, const char* code)
2089 Engines::PyNode_var node= Engines::PyNode::_nil();
2094 PyObject *res = PyObject_CallMethod(_pyCont,
2095 (char*)"create_pynode",
2103 SALOME::ExceptionStruct es;
2104 es.type = SALOME::INTERNAL_ERROR;
2105 es.text = "can not create a python node";
2106 throw SALOME::SALOME_Exception(es);
2108 ierr=PyLong_AsLong(PyTuple_GetItem(res,0));
2109 PyObject* result=PyTuple_GetItem(res,1);
2110 astr = PyUnicode_AsUTF8(result);
2115 Utils_Locker lck(&_mutexForDftPy);
2116 CORBA::Object_var obj=_orb->string_to_object(astr.c_str());
2117 node=Engines::PyNode::_narrow(obj);
2118 std::map<std::string,Engines::PyNode_var>::iterator it(_dftPyNode.find(nodeName));
2119 if(it==_dftPyNode.end())
2121 _dftPyNode[nodeName]=node;
2125 Engines::PyNode_var oldNode((*it).second);
2126 if(!CORBA::is_nil(oldNode))
2127 oldNode->UnRegister();
2130 if(!CORBA::is_nil(node))
2132 return node._retn();
2136 SALOME::ExceptionStruct es;
2137 es.type = SALOME::INTERNAL_ERROR;
2138 es.text = astr.c_str();
2139 throw SALOME::SALOME_Exception(es);
2143 //=============================================================================
2144 /*! \brief Retrieves the last created PyNode instance with createPyNode.
2147 //=============================================================================
2148 Engines::PyNode_ptr Abstract_Engines_Container_i::getDefaultPyNode(const char *nodeName)
2150 Utils_Locker lck(&_mutexForDftPy);
2151 std::map<std::string,Engines::PyNode_var>::iterator it(_dftPyNode.find(nodeName));
2152 if(it==_dftPyNode.end())
2153 return Engines::PyNode::_nil();
2156 Engines::PyNode_var tmpVar((*it).second);
2157 if(!CORBA::is_nil(tmpVar))
2158 return Engines::PyNode::_duplicate(tmpVar);
2160 return Engines::PyNode::_nil();
2164 //=============================================================================
2165 /*! \brief create a PyScriptNode object to execute remote python code
2166 * \param nodeName the name of the node
2167 * \param code the python code to load
2168 * \return the PyScriptNode
2170 //=============================================================================
2171 Engines::PyScriptNode_ptr Abstract_Engines_Container_i::createPyScriptNode(const char* nodeName, const char* code)
2173 Engines::PyScriptNode_var node= Engines::PyScriptNode::_nil();
2178 AutoPyRef res = PyObject_CallMethod(_pyCont,
2179 (char*)"create_pyscriptnode",
2187 SALOME::ExceptionStruct es;
2188 es.type = SALOME::INTERNAL_ERROR;
2189 es.text = "can not create a python node";
2190 throw SALOME::SALOME_Exception(es);
2192 ierr=PyLong_AsLong(PyTuple_GetItem(res,0));
2193 PyObject* result=PyTuple_GetItem(res,1);
2194 astr = PyUnicode_AsUTF8(result);
2199 Utils_Locker lck(&_mutexForDftPy);
2200 CORBA::Object_var obj=_orb->string_to_object(astr.c_str());
2201 node=Engines::PyScriptNode::_narrow(obj);
2202 std::map<std::string,Engines::PyScriptNode_var>::iterator it(_dftPyScriptNode.find(nodeName));
2203 if(it==_dftPyScriptNode.end())
2205 _dftPyScriptNode[nodeName]=node;
2209 Engines::PyScriptNode_var oldNode((*it).second);
2210 if(!CORBA::is_nil(oldNode))
2211 oldNode->UnRegister();
2214 return node._retn();
2218 SALOME::ExceptionStruct es;
2219 es.type = SALOME::INTERNAL_ERROR;
2220 es.text = astr.c_str();
2221 throw SALOME::SALOME_Exception(es);
2225 void Abstract_Engines_Container_i::removePyScriptNode(const char *nodeName)
2227 std::map<std::string,Engines::PyScriptNode_var>::iterator it(_dftPyScriptNode.find(nodeName));
2228 if(it==_dftPyScriptNode.end())
2230 std::ostringstream oss; oss << "Engines_Container_i::removePyScriptNode : node \"" << nodeName << "\" is not map !";
2231 SALOME::ExceptionStruct es;
2232 es.type = SALOME::INTERNAL_ERROR;
2233 es.text = oss.str().c_str();
2234 throw SALOME::SALOME_Exception(es);
2236 (*it).second->UnRegister();
2237 _dftPyScriptNode.erase(it);
2240 void Abstract_Engines_Container_i::cleanAllPyScripts()
2242 for(std::map<std::string,Engines::PyNode_var>::iterator it=_dftPyNode.begin();it!=_dftPyNode.end();it++)
2244 Engines::PyNode_var tmpVar((*it).second);
2245 if(!CORBA::is_nil(tmpVar))
2246 tmpVar->UnRegister();
2249 for(std::map<std::string,Engines::PyScriptNode_var>::iterator it=_dftPyScriptNode.begin();it!=_dftPyScriptNode.end();it++)
2251 Engines::PyScriptNode_var tmpVar((*it).second);
2252 if(!CORBA::is_nil(tmpVar))
2253 tmpVar->UnRegister();
2255 _dftPyScriptNode.clear();
2258 //=============================================================================
2259 /*! \brief Retrieves the last created PyScriptNode instance with createPyScriptNode.
2262 //=============================================================================
2263 Engines::PyScriptNode_ptr Abstract_Engines_Container_i::getDefaultPyScriptNode(const char *nodeName)
2265 Utils_Locker lck(&_mutexForDftPy);
2266 std::map<std::string,Engines::PyScriptNode_var>::iterator it(_dftPyScriptNode.find(nodeName));
2267 if(it==_dftPyScriptNode.end())
2268 return Engines::PyScriptNode::_nil();
2271 Engines::PyScriptNode_var tmpVar((*it).second);
2272 if(!CORBA::is_nil(tmpVar))
2273 return Engines::PyScriptNode::_duplicate(tmpVar);
2275 return Engines::PyScriptNode::_nil();
2279 //=============================================================================
2280 /* int checkifexecutable(const char *filename)
2282 * Return non-zero if the name is an executable file, and
2283 * zero if it is not executable, or if it does not exist.
2285 //=============================================================================
2286 int checkifexecutable(const std::string& filename)
2289 struct stat statinfo;
2291 result = stat(filename.c_str(), &statinfo);
2292 if (result < 0) return 0;
2293 if (!S_ISREG(statinfo.st_mode)) return 0;
2298 if (statinfo.st_uid == geteuid()) return statinfo.st_mode & S_IXUSR;
2299 if (statinfo.st_gid == getegid()) return statinfo.st_mode & S_IXGRP;
2300 return statinfo.st_mode & S_IXOTH;
2305 //=============================================================================
2306 /*! \brief Find a file by searching in a path
2307 * \param filename file name to search
2308 * \param path path to search in
2309 * \param pth the complete file path if found
2310 * \return 1 if found 0 if not
2312 //=============================================================================
2313 int findpathof(const std::string& path, std::string& pth, const std::string& filename)
2315 if ( path.size() == 0 ) return 0;
2317 std::string::size_type offset = 0;
2318 std::string::size_type pos = 0;
2320 struct stat statinfo;
2324 pos = path.find( SEP, offset );
2325 pth = path.substr( offset, pos - offset );
2326 if ( pth.size() > 0 )
2328 if( pth[pth.size()-1] != SLASH ) pth += SLASH;
2330 int result=stat(pth.c_str(), &statinfo);
2331 if(result == 0) found=1;
2333 if (pos == std::string::npos) break;
2339 void Abstract_Engines_Container_i::registerTemporaryFile( const std::string& fileName )
2341 _tmp_files.remove( fileName );
2342 _tmp_files.push_back( fileName );
2345 void Abstract_Engines_Container_i::unregisterTemporaryFile( const std::string& fileName )
2347 _tmp_files.remove( fileName );
2350 void Abstract_Engines_Container_i::clearTemporaryFiles()
2352 std::list<std::string>::const_iterator it;
2353 for ( it = _tmp_files.begin(); it != _tmp_files.end(); ++it ) {
2354 #if defined(WIN32) && defined(UNICODE)
2355 std::wstring aFile = Kernel_Utils::utf8_decode_s(*it);
2356 std::wstring command = (GetFileAttributes(aFile.c_str()) == FILE_ATTRIBUTE_DIRECTORY) ? L"rd /Q \"" : L"del /F /Q \"";
2358 command += L"\" 2>NUL";
2359 _wsystem(command.c_str());
2362 std::string aFile = *it;
2363 std::string command = (GetFileAttributes(aFile.c_str()) == FILE_ATTRIBUTE_DIRECTORY) ? "rd /Q \"" : "del /F /Q \"";
2365 command += "\" 2>NUL";
2367 std::string command = "rm -rf ";
2370 system(command.c_str());
2376 static Engines_Container_SSL_i *_container_singleton_ssl = nullptr;
2378 static Engines::Container_var _container_ref_singleton_ssl;
2380 Engines_Container_SSL_i *KERNEL::getContainerSA()
2382 if(!_container_singleton_ssl)
2384 CORBA::ORB_var orb = KERNEL::GetRefToORB();
2385 CORBA::Object_var obj = orb->resolve_initial_references("RootPOA");
2386 PortableServer::POA_var poa = PortableServer::POA::_narrow(obj);
2387 PortableServer::POAManager_var pman = poa->the_POAManager();
2388 CORBA::PolicyList policies;
2391 constexpr int ARGC = 4;
2392 constexpr const char *ARGV[ARGC] = {"Container","FactoryServer","toto",nullptr};
2393 std::unique_ptr<char*[]> argv( new char *[ARGC+1] );
2394 std::vector< std::unique_ptr<char[]> > argvv(ARGC);
2395 argv[ARGC] = nullptr;
2396 for(int i = 0 ; i < ARGC ; ++i)
2400 argvv[i].reset( new char[strlen(ARGV[i])+1] );
2401 strcpy(argvv[i].get(),ARGV[i]);
2402 argv[i] = argvv[i].get();
2407 SALOME_Fake_NamingService ns;
2408 _container_singleton_ssl = new Engines_Container_SSL_i(orb,poa,(char *)"FactoryServer",2,argv.get(),&ns,false);
2409 PortableServer::ObjectId * cont_id = _container_singleton_ssl->getCORBAId();
2411 CORBA::Object_var zeRef = poa->id_to_reference(*cont_id);
2412 _container_ref_singleton_ssl = Engines::Container::_narrow(zeRef);
2414 return _container_singleton_ssl;
2417 Engines::Container_var KERNEL::getContainerRefSA()
2420 return _container_ref_singleton_ssl;