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 (const std::string& pyContainerClsName,
150 PortableServer::POA_ptr poa,
151 char *containerName ,
152 int argc , char* argv[],
153 SALOME_NamingService_Container_Abstract *ns,
154 bool isServantAloneInProcess
156 _NS(nullptr),_py_container_name(pyContainerClsName),_id(0),_numInstance(0),_isServantAloneInProcess(isServantAloneInProcess)
158 _pid = (long)getpid();
160 if( isServantAloneInProcess )
166 std::string hostname = Kernel_Utils::GetHostname();
168 INFO_MESSAGE("Starting Container servant instance on Hostname :" << hostname << " with PID : " << getpid() ) ;
170 MESSAGE(hostname << " " << _getpid() <<
171 " Engines_Container_i starting argc " << _argc<< " Thread " << pthread_self().p ) ;
173 _isSupervContainer = false;
175 _orb = CORBA::ORB::_duplicate(orb) ;
176 _poa = PortableServer::POA::_duplicate(poa) ;
178 // Pour les containers paralleles: il ne faut pas enregistrer et activer
179 // le container generique, mais le container specialise
182 _id = _poa->activate_object(this);
183 // key point : if ns is nullptr : this servant is alone in its process
184 // if ns is not null : this servant embedded into single process.
185 _NS = ns==nullptr ? new SALOME_NamingService : ns->clone();
186 _NS->init_orb( _orb ) ;
187 CORBA::Object_var obj=_poa->id_to_reference(*_id);
188 Engines::Container_var pCont = Engines::Container::_narrow(obj);
191 _containerName = SALOME_NamingService_Abstract::BuildContainerNameForNS(containerName, hostname.c_str());
194 // import SALOME_Container
195 // pycont = SALOME_Container.SALOME_Container_i(containerIORStr)
197 CORBA::String_var sior = _orb->object_to_string(pCont);
198 std::ostringstream myCommand;
199 myCommand << "pyCont = SALOME_Container." << this->getPyContainerClassName() << "('" << _containerName << "','" << sior << "'," << DFT_TIME_INTERVAL_BTW_MEASURE << ")\n";
200 INFO_MESSAGE("Python command executed : " << myCommand.str());
202 //[RNV]: Comment the PyEval_AcquireLock() and PyEval_ReleaseLock() because this
203 //approach leads to the deadlock of the main thread of the application on Windows platform
204 //in case if cppContainer runs in the standalone mode. The problem with the PyThreadState
205 //described by ABN seems not reproduced, to be checked carefully later...
208 //// [ABN]: using the PyGILState* API here is unstable. omniORB logic is invoked
209 //// by the Python code executed below, and in some (random) cases, the Python code
210 //// execution ends with a PyThreadState which was not the one we have here.
211 //// (TODO: understand why ...)
212 //// To be on the safe side we get and load the thread state ourselves:
213 //PyEval_AcquireLock(); // get GIL
214 //PyThreadState * mainThreadState = PyThreadState_Get();
215 //PyThreadState_Swap(mainThreadState);
218 // mpv: this is temporary solution: there is a unregular crash if not
221 // first element is the path to Registry.dll, but it's wrong
222 PyRun_SimpleString("import sys\n");
223 PyRun_SimpleString("sys.path = sys.path[1:]\n");
225 PyRun_SimpleString("import SALOME_Container\n");
226 PyRun_SimpleString((char*)myCommand.str().c_str());
227 PyObject *mainmod = PyImport_AddModule("__main__");
228 PyObject *globals = PyModule_GetDict(mainmod);
229 _pyCont = PyDict_GetItemString(globals, "pyCont");
230 //PyThreadState_Swap(NULL);
231 //PyEval_ReleaseLock();
233 {// register to NS after python initialization to be sure that client invoke after py constructor execution
234 _NS->Register(pCont, _containerName.c_str());
235 DEBUG_MESSAGE("Container registred in NS as : " << _containerName);
237 fileTransfer_i* aFileTransfer = new fileTransfer_i();
238 CORBA::Object_var obref=aFileTransfer->_this();
239 _fileTransfer = Engines::fileTransfer::_narrow(obref);
240 aFileTransfer->_remove_ref();
244 //=============================================================================
248 //=============================================================================
250 Abstract_Engines_Container_i::~Abstract_Engines_Container_i()
252 MESSAGE("Abstract_Container_i::~Abstract_Container_i()");
260 //=============================================================================
261 //! Get container name
263 * CORBA attribute: Container name (see constructor)
265 //=============================================================================
267 char* Abstract_Engines_Container_i::name()
269 return CORBA::string_dup(_containerName.c_str()) ;
272 //=============================================================================
273 //! Get container working directory
275 * CORBA attribute: Container working directory
277 //=============================================================================
279 char* Abstract_Engines_Container_i::workingdir()
283 return CORBA::string_dup(wd) ;
286 //=============================================================================
287 //! Get container log file name
289 * CORBA attribute: Container log file name
291 //=============================================================================
293 char *Abstract_Engines_Container_i::logfilename()
295 return CORBA::string_dup(_logfilename.c_str()) ;
298 //! Set container log file name
299 void Abstract_Engines_Container_i::logfilename(const char* name)
304 char *Abstract_Engines_Container_i::locallogfilename()
306 return CORBA::string_dup( _localfilename.c_str() );
309 void Abstract_Engines_Container_i::locallogfilename(const char *name)
312 _localfilename = name;
313 AutoPyRef result = PyObject_CallMethod(_pyCont,(char*)"setLogFileName","s",name,nullptr);
314 if (PyErr_Occurred())
316 std::string error("can not set logfilename");
318 THROW_SALOME_CORBA_EXCEPTION(error.c_str(),SALOME::INTERNAL_ERROR);
322 CORBA::Long Abstract_Engines_Container_i::monitoringtimeresms()
325 AutoPyRef result = PyObject_CallMethod(_pyCont,(char*)"monitoringtimeresms",nullptr);
326 if (PyErr_Occurred())
328 std::string error("can not retrieve time interval between 2 measures");
330 THROW_SALOME_CORBA_EXCEPTION(error.c_str(),SALOME::INTERNAL_ERROR);
332 CORBA::Long ret = PyLong_AsLong( result );
336 void Abstract_Engines_Container_i::monitoringtimeresms(CORBA::Long intervalInMs)
339 AutoPyRef result = PyObject_CallMethod(_pyCont,(char*)"SetMonitoringtimeresms","i",intervalInMs,nullptr);
340 if (PyErr_Occurred())
342 std::string error("can not set time interval between 2 measures");
344 THROW_SALOME_CORBA_EXCEPTION(error.c_str(),SALOME::INTERNAL_ERROR);
348 void Abstract_Engines_Container_i::verbosity(bool& activated, CORBA::String_out level)
350 activated = SALOME::VerbosityActivated();
351 level = CORBA::string_dup( SALOME::VerbosityLevelStr().c_str() );
354 void Abstract_Engines_Container_i::setVerbosity(bool activated, const char *level)
356 SALOME::SetVerbosityActivated( activated );
357 SALOME::SetVerbosityLevelStr( level );
360 AutoPyRef res = PyObject_CallMethod(_pyCont,
361 (char*)"positionVerbosityOfLogger",NULL);
366 SALOME::ExceptionStruct es;
367 es.type = SALOME::INTERNAL_ERROR;
368 es.text = "can not create a python node";
369 throw SALOME::SALOME_Exception(es);
374 //=============================================================================
375 //! Get container host name
377 * CORBA method: Get the hostName of the Container (without domain extensions)
379 //=============================================================================
381 char* Abstract_Engines_Container_i::getHostName()
383 std::string s = Kernel_Utils::GetHostname();
384 // MESSAGE("Engines_Container_i::getHostName " << s);
385 return CORBA::string_dup(s.c_str()) ;
388 //=============================================================================
389 //! Get container PID
391 * CORBA method: Get the PID (process identification) of the Container
393 //=============================================================================
395 CORBA::Long Abstract_Engines_Container_i::getPID()
397 return (CORBA::Long)getpid();
400 //=============================================================================
401 //! Ping the servant to check it is still alive
403 * CORBA method: check if servant is still alive
405 //=============================================================================
406 void Abstract_Engines_Container_i::ping()
408 MESSAGE("Engines_Container_i::ping() pid "<< getpid());
411 //=============================================================================
412 //! Get number of CPU cores in the calculation node
414 * CORBA method: get number of CPU cores
416 //=============================================================================
418 CORBA::Long Abstract_Engines_Container_i::getNumberOfCPUCores()
421 PyObject *module = PyImport_ImportModuleNoBlock((char*)"salome_psutil");
422 AutoPyRef result = PyObject_CallMethod(module,
423 (char*)"getNumberOfCPUCores", NULL);
424 int n = PyLong_AsLong(result);
425 return (CORBA::Long)n;
428 //=============================================================================
429 //! Get a load of each CPU core in the calculation node
431 * CORBA method: get a load of each CPU core
433 //=============================================================================
443 PyStdOut_dealloc(PyStdOut *self)
449 PyStdOut_write(PyStdOut* self, PyObject* args)
452 if (!PyArg_ParseTuple(args, "s", &c))
455 *(self->out) = *(self->out) + c;
461 static PyMethodDef PyStdOut_methods[] =
463 {"write", (PyCFunction)PyStdOut_write, METH_VARARGS,
464 PyDoc_STR("write(string) -> None")},
465 {0, 0, 0, 0} /* sentinel */
468 static PyMemberDef PyStdOut_memberlist[] =
470 {(char*)"softspace", T_INT, offsetof(PyStdOut, softspace), 0,
471 (char*)"flag indicating that a space needs to be printed; used by print"},
472 {0, 0, 0, 0, 0} /* sentinel */
475 static PyTypeObject PyStdOut_Type =
477 /* The ob_type field must be initialized in the module init function
478 * to be portable to Windows without using C++. */
479 PyVarObject_HEAD_INIT(NULL, 0)
482 sizeof(PyStdOut), /*tp_basicsize*/
485 (destructor)PyStdOut_dealloc, /*tp_dealloc*/
492 0, /*tp_as_sequence*/
497 PyObject_GenericGetAttr, /*tp_getattro*/
498 /* softspace is writable: we must supply tp_setattro */
499 PyObject_GenericSetAttr, /* tp_setattro */
501 Py_TPFLAGS_DEFAULT, /*tp_flags*/
505 0, /*tp_richcompare*/
506 0, /*tp_weaklistoffset*/
509 PyStdOut_methods, /*tp_methods*/
510 PyStdOut_memberlist, /*tp_members*/
528 0, /*tp_version_tag*/
532 PyObject* newPyStdOut(std::string& out)
534 PyStdOut* self = PyObject_New(PyStdOut, &PyStdOut_Type);
539 return (PyObject*)self;
542 std::string parseException()
545 if (PyErr_Occurred())
547 #ifdef BOS26455_WITH_BOOST_PYTHON
548 PyObject *ptype = nullptr;
549 PyObject *pvalue = nullptr;
550 PyObject *ptraceback = nullptr;
551 PyErr_Fetch(&ptype, &pvalue, &ptraceback);
552 if (ptype == nullptr)
553 return std::string("Null exception type");
554 PyErr_NormalizeException(&ptype, &pvalue, &ptraceback);
555 if (ptraceback != nullptr)
556 PyException_SetTraceback(pvalue, ptraceback);
557 boost::python::handle<> htype(ptype);
558 boost::python::handle<> hvalue(boost::python::allow_null(pvalue));
559 boost::python::handle<> htraceback(boost::python::allow_null(ptraceback));
560 boost::python::object traceback = boost::python::import("traceback");
561 boost::python::object format_exc = traceback.attr("format_exception");
562 boost::python::object formatted = format_exc(htype, hvalue, htraceback);
563 error = boost::python::extract<std::string>(boost::python::str("\n").join(formatted));
565 PyObject* new_stderr = newPyStdOut(error);
566 PyObject* old_stderr = PySys_GetObject((char*)"stderr");
567 Py_INCREF(old_stderr);
568 PySys_SetObject((char*)"stderr", new_stderr);
570 PySys_SetObject((char*)"stderr", old_stderr);
571 Py_DECREF(new_stderr);
578 Engines::vectorOfDouble* Abstract_Engines_Container_i::loadOfCPUCores()
581 PyObject *module = PyImport_ImportModuleNoBlock((char*)"salome_psutil");
582 AutoPyRef result = PyObject_CallMethod(module,
583 (char*)"loadOfCPUCores", "s",
584 _load_script.c_str());
585 if (PyErr_Occurred())
587 std::string error = parseException();
589 SALOME::ExceptionStruct es;
590 es.type = SALOME::INTERNAL_ERROR;
591 es.text = CORBA::string_dup(error.c_str());
592 throw SALOME::SALOME_Exception(es);
595 int n = this->getNumberOfCPUCores();
596 if (!PyList_Check(result) || PyList_Size(result) != n) {
597 // bad number of cores
598 SALOME::ExceptionStruct es;
599 es.type = SALOME::INTERNAL_ERROR;
600 es.text = "wrong number of cores";
601 throw SALOME::SALOME_Exception(es);
604 Engines::vectorOfDouble_var loads = new Engines::vectorOfDouble;
606 for (Py_ssize_t i = 0; i < PyList_Size(result); ++i) {
607 PyObject* item = PyList_GetItem(result, i);
608 double foo = PyFloat_AsDouble(item);
609 if (foo < 0.0 || foo > 1.0)
611 // value not in [0, 1] range
612 SALOME::ExceptionStruct es;
613 es.type = SALOME::INTERNAL_ERROR;
614 es.text = "load not in [0, 1] range";
615 throw SALOME::SALOME_Exception(es);
620 return loads._retn();
623 //=============================================================================
624 //! Set custom script to calculate a load of each CPU core
626 * CORBA method: Set custom script to calculate CPU load
627 * \param script Python script to execute
629 //=============================================================================
631 void Abstract_Engines_Container_i::setPyScriptForCPULoad(const char *script)
633 _load_script = script;
636 //=============================================================================
637 //! Nullify custom script to calculate each CPU core's load
639 * CORBA method: reset script for load calculation to default implementation
641 //=============================================================================
643 void Abstract_Engines_Container_i::resetScriptForCPULoad()
648 //=============================================================================
649 //! Get total physical memory of calculation node, in megabytes
651 * CORBA method: get total physical memory of calculation node
653 //=============================================================================
655 CORBA::Long Abstract_Engines_Container_i::getTotalPhysicalMemory()
658 PyObject *module = PyImport_ImportModuleNoBlock((char*)"salome_psutil");
659 AutoPyRef result = PyObject_CallMethod(module,
660 (char*)"getTotalPhysicalMemory", NULL);
661 int n = PyLong_AsLong(result);
663 return (CORBA::Long)n;
666 //=============================================================================
667 //! Get used physical memory of calculation node, in megabytes
669 * CORBA method: get used physical memory of calculation node
671 //=============================================================================
673 CORBA::Long Abstract_Engines_Container_i::getTotalPhysicalMemoryInUse()
676 PyObject *module = PyImport_ImportModuleNoBlock((char*)"salome_psutil");
677 AutoPyRef result = PyObject_CallMethod(module,
678 (char*)"getTotalPhysicalMemoryInUse", NULL);
679 int n = PyLong_AsLong(result);
681 return (CORBA::Long)n;
684 //=============================================================================
685 //! Obtain physical memory, used by the current process, in megabytes.
687 * CORBA method: get physical memory, used by the current process
689 //=============================================================================
691 CORBA::Long Abstract_Engines_Container_i::getTotalPhysicalMemoryInUseByMe()
694 PyObject *module = PyImport_ImportModuleNoBlock((char*)"salome_psutil");
695 AutoPyRef result = PyObject_CallMethod(module,
696 (char*)"getTotalPhysicalMemoryInUseByMe", NULL);
697 int n = PyLong_AsLong(result);
699 return (CORBA::Long)n;
702 //=============================================================================
703 //! Shutdown the container
705 * CORBA method, oneway: Server shutdown.
706 * - Container name removed from naming service,
707 * - servant deactivation,
708 * - orb shutdown if no other servants in the process
710 //=============================================================================
711 void Abstract_Engines_Container_i::Shutdown()
713 ShutdownCommonPart();
714 if(_isServantAloneInProcess)
716 MESSAGE("Effective Shutdown of container Begins...");
719 if(!CORBA::is_nil(_orb))
725 MESSAGE("Effective Shutdown of container Ends...");
729 void Abstract_Engines_Container_i::ShutdownCommonPart()
731 MESSAGE("Engines_Container_i::Shutdown()");
733 // Clear registered temporary files
734 clearTemporaryFiles();
736 /* For each component contained in this container
737 * tell it to self-destroy
739 std::map<std::string, Engines::EngineComponent_var>::iterator itm;
740 for (itm = _listInstances_map.begin(); itm != _listInstances_map.end(); itm++)
744 itm->second->destroy();
746 catch(const CORBA::Exception&)
748 // ignore this entry and continue
752 // ignore this entry and continue
755 _listInstances_map.clear();
756 MESSAGE("Engines_Container_i::Shutdown() -- step 2");
757 // NS unregistering may throw in SSL mode if master process hosting SALOME_Embedded_NamingService servant has vanished
758 // In this case it's skip it and still continue.
761 _NS->Destroy_FullDirectory(_containerName.c_str());
762 _NS->Destroy_Name(_containerName.c_str());
767 MESSAGE("Engines_Container_i::Shutdown() -- step 3");
770 this->cleanAllPyScripts();
774 AutoPyRef result = PyObject_CallMethod(_pyCont, (char*)"shutdownPy", (char*)"",nullptr);
780 MESSAGE("Engines_Container_i::Shutdown() -- step 4");
783 void Abstract_Engines_Container_i::ShutdownNow()
785 ShutdownCommonPart();if(_isServantAloneInProcess)
788 AutoPyRef result = PyObject_CallMethod(_pyCont, (char*)"killMe", (char*)"",nullptr);
792 //=============================================================================
793 //! load a component implementation
796 * \param componentName component name
797 * \param reason explains error when load fails
798 * \return true if dlopen successful or already done, false otherwise
800 //=============================================================================
802 Abstract_Engines_Container_i::load_component_Library(const char* componentName, CORBA::String_out reason)
805 //=================================================================
806 // --- C++ implementation section
807 //=================================================================
809 if(load_component_CppImplementation(componentName,retso))
811 reason=CORBA::string_dup("");
814 else if(retso != "ImplementationNotFound")
816 reason=CORBA::string_dup(retso.c_str());
821 retso+=componentName;
822 retso+=": Can't find C++ implementation ";
823 retso+=std::string(LIB) + componentName + ENGINESO;
825 //=================================================================
826 // --- Python implementation section
827 //=================================================================
829 if(load_component_PythonImplementation(componentName,retpy))
831 reason=CORBA::string_dup("");
834 else if(retpy != "ImplementationNotFound")
836 reason=CORBA::string_dup(retpy.c_str());
841 retpy+=componentName;
842 retpy+=": Can't find python implementation ";
843 retpy+=componentName;
846 //=================================================================
847 // -- Executable implementation section
848 //=================================================================
850 if(load_component_ExecutableImplementation(componentName,retex))
852 reason=CORBA::string_dup("");
855 else if(retex != "ImplementationNotFound")
857 reason=CORBA::string_dup(retex.c_str());
862 retex+=componentName;
863 retex+=": Can't find executable implementation ";
864 retex+=componentName;
867 std::string ret="Component implementation not found: ";
868 ret += componentName ;
874 std::cerr << ret << std::endl;
875 reason=CORBA::string_dup(ret.c_str());
880 //=============================================================================
881 //! try to load a C++ component implementation
884 * \param componentName the name of the component (COMPONENT, for example)
885 * \param reason explains error when load fails
886 * \return true if loading is successful or already done, false otherwise
888 //=============================================================================
890 Abstract_Engines_Container_i::load_component_CppImplementation(const char* componentName, std::string& reason)
892 std::string aCompName(componentName);
893 std::string impl_name = std::string(LIB) + aCompName + ENGINESO;
896 _numInstanceMutex.lock(); // lock to be alone
897 // (see decInstanceCnt, finalize_removal))
898 if (_toRemove_map.count(impl_name) != 0) _toRemove_map.erase(impl_name);
899 if (_library_map.count(impl_name) != 0)
901 MESSAGE("Library " << impl_name << " already loaded");
902 _numInstanceMutex.unlock();
906 _numInstanceMutex.unlock();
910 handle = dlopen( impl_name.c_str() , RTLD_NOW | RTLD_GLOBAL ) ;
913 //not loadable. Try to find the lib file in LD_LIBRARY_PATH
916 char* p=getenv("DYLD_LIBRARY_PATH");
918 char* p=getenv("LD_LIBRARY_PATH");
921 path=path+SEP+"/usr/lib"+SEP+"/lib";
924 if(findpathof(path, pth, impl_name))
926 //found but not loadable
929 reason+=": C++ implementation found ";
931 reason+=" but it is not loadable. Error:\n";
933 std::cerr << reason << std::endl;
939 //continue with other implementation
940 reason="ImplementationNotFound";
947 std::wstring libToLoad = Kernel_Utils::utf8_decode_s( impl_name );
949 std::string libToLoad = impl_name;
951 handle = LoadLibrary(libToLoad.c_str() );
954 reason="ImplementationNotFound";
960 _numInstanceMutex.lock();
961 _library_map[impl_name] = handle;
962 _numInstanceMutex.unlock();
970 //=============================================================================
971 //! try to load a Python component implementation
974 * \param componentName name of the component
975 * \param reason explains error when load fails
976 * \return true if loading is successful or already done, false otherwise
978 //=============================================================================
980 Abstract_Engines_Container_i::load_component_PythonImplementation(const char* componentName, std::string& reason)
982 std::string aCompName(componentName);
984 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
985 if (_library_map.count(aCompName) != 0)
987 _numInstanceMutex.unlock() ;
989 return true; // Python Component, already imported
991 _numInstanceMutex.unlock() ;
995 AutoPyRef result = PyObject_CallMethod(_pyCont,
996 (char*)"import_component",
997 (char*)"s",componentName);
999 reason=PyUnicode_AsUTF8(result);
1005 //Python component has been loaded (import componentName)
1006 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1007 _library_map[aCompName] = (void *)_pyCont; // any non O value OK
1008 _numInstanceMutex.unlock() ;
1009 MESSAGE("import Python: "<< aCompName <<" OK");
1012 else if(reason=="ImplementationNotFound")
1014 //Python implementation has not been found. Continue with other implementation
1015 reason="ImplementationNotFound";
1019 //Python implementation has been found but loading has failed
1020 std::cerr << reason << std::endl;
1025 //=============================================================================
1026 //! try to load a Executable component implementation
1029 * \param componentName name of the component
1030 * \param reason explains error when load fails
1031 * \return true if loading is successful or already done, false otherwise
1033 //=============================================================================
1035 Abstract_Engines_Container_i::load_component_ExecutableImplementation(const char* componentName, std::string& reason)
1037 std::string aCompName(componentName);
1038 std::string executable=aCompName+".exe";
1043 char* p=getenv("PATH");
1046 if (findpathof(path, pth, executable))
1048 if(checkifexecutable(pth))
1050 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1051 _library_map[executable] = (void *)1; // any non O value OK
1052 _numInstanceMutex.unlock() ;
1053 MESSAGE("import executable: "<< pth <<" OK");
1057 reason="Component ";
1059 reason+=": implementation found ";
1061 reason+=" but it is not executable";
1062 std::cerr << reason << std::endl;
1066 reason="ImplementationNotFound";
1071 //=============================================================================
1072 //! Create a new component instance
1074 * CORBA method: Creates a new servant instance of a component.
1075 * The servant registers itself to naming service and Registry.tdlib
1076 * \param genericRegisterName Name of the component instance to register
1077 * in Registry & Name Service (without _inst_n suffix)
1078 * \return a loaded component
1080 //=============================================================================
1081 Engines::EngineComponent_ptr
1082 Abstract_Engines_Container_i::create_component_instance(const char*genericRegisterName)
1084 Engines::FieldsDict_var env = new Engines::FieldsDict;
1086 Engines::EngineComponent_ptr compo =
1087 create_component_instance_env(genericRegisterName, env, reason);
1088 CORBA::string_free(reason);
1092 void EffectiveOverrideEnvironment( const Engines::FieldsDict& env )
1094 MESSAGE("Positionning environment on container ");
1095 for (CORBA::ULong i=0; i < env.length(); i++)
1097 if (env[i].value.type()->kind() == CORBA::tk_string)
1099 const char *value = nullptr;
1100 env[i].value >>= value;
1101 MESSAGE( env[i].key << " = " << value);
1103 if( setenv(env[i].key,value,1) != 0 )
1106 std::string sErr( strerror( errsv) );
1114 std::vector< std::pair<std::string,std::string> > GetOSEnvironment()
1116 std::vector< std::pair<std::string,std::string> > ret;
1118 char **envPt( environ );
1119 for(;*envPt != nullptr; ++envPt)
1121 std::string s( *envPt );
1122 auto pos = s.find_first_of('=');
1123 std::string k( s.substr(0,pos) ),v( s.substr(pos+1) );
1124 ret.emplace_back( std::pair<std::string,std::string>(k,v) );
1130 void Abstract_Engines_Container_i::override_environment( const Engines::FieldsDict& env )
1132 EffectiveOverrideEnvironment(env);
1135 void Abstract_Engines_Container_i::override_environment_python( const Engines::FieldsDict& env )
1137 constexpr char NODE_NAME[] = "ScriptNodeForEnv";
1138 constexpr char SCRIPT[] = R"foo(
1143 Engines::PyScriptNode_var scriptNode = this->createPyScriptNode(NODE_NAME,SCRIPT);
1144 auto sz = env.length();
1145 Engines::listofstring keys, vals;
1146 keys.length( sz ); vals.length( sz );
1147 for( auto i = 0 ; i < sz ; ++i )
1149 keys[i] = CORBA::string_dup( env[i].key );
1150 const char *value = nullptr;
1151 env[i].value >>= value;
1152 vals[i] = CORBA::string_dup( value );
1154 scriptNode->executeSimple(keys,vals);
1155 this->removePyScriptNode(NODE_NAME);
1158 Engines::FieldsDict *Abstract_Engines_Container_i::get_os_environment()
1160 std::unique_ptr<Engines::FieldsDict> ret( new Engines::FieldsDict );
1161 std::vector< std::pair<std::string,std::string> > retCpp( GetOSEnvironment() );
1162 auto sz = retCpp.size();
1164 for(auto i = 0 ; i < sz ; ++i)
1166 (*ret)[i].key = CORBA::string_dup( retCpp[i].first.c_str() );
1167 (*ret)[i].value <<= CORBA::string_dup( retCpp[i].second.c_str() );
1169 return ret.release();
1172 Engines::vectorOfString_var FromVecStringCppToCORBA( const std::vector<std::string>& group)
1174 Engines::vectorOfString_var ret( new Engines::vectorOfString );
1175 auto sz( group.size() );
1177 for(auto i = 0 ; i < sz ; ++i)
1179 ret[i] = CORBA::string_dup( group[i].c_str() );
1184 std::vector<std::string> FromCORBAVecStringToCpp(const Engines::vectorOfString& groupOfLogFileNames)
1186 auto len = groupOfLogFileNames.length();
1187 std::vector<std::string> ret( len );
1188 for( auto i = 0 ; i < len ; ++i )
1190 ret[i] = groupOfLogFileNames[i];
1195 void Abstract_Engines_Container_i::addLogFileNameGroup(const Engines::vectorOfString& groupOfLogFileNames)
1197 this->_groups_of_log_files.push_back( FromCORBAVecStringToCpp(groupOfLogFileNames) );
1200 Engines::vectorOfVectorOfString *Abstract_Engines_Container_i::getAllLogFileNameGroups()
1202 std::unique_ptr<Engines::vectorOfVectorOfString> ret( new Engines::vectorOfVectorOfString );
1203 auto nbOfGrps = this->_groups_of_log_files.size();
1204 ret->length( nbOfGrps );
1205 for(auto i = 0 ; i < nbOfGrps ; ++i)
1207 (*ret)[i] = FromVecStringCppToCORBA( _groups_of_log_files[i] );
1209 return ret.release();
1212 void Abstract_Engines_Container_i::execute_python_code(const char *code)
1215 if( PyRun_SimpleString( code ) != 0 )
1217 std::string error = parseException();
1218 THROW_SALOME_CORBA_EXCEPTION(error.c_str(),SALOME::INTERNAL_ERROR);
1222 //=============================================================================
1223 //! Create a new component instance with environment variables specified
1225 * CORBA method: Creates a new servant instance of a component.
1226 * The servant registers itself to naming service and Registry.
1227 * \param genericRegisterName Name of the component instance to register
1228 * in Registry & Name Service (without _inst_n suffix)
1229 * \param env dict of env variables
1230 * \param reason explains error when create_component_instance_env fails
1231 * \return a loaded component
1233 //=============================================================================
1234 Engines::EngineComponent_ptr
1235 Abstract_Engines_Container_i::create_component_instance_env(const char*genericRegisterName,
1236 const Engines::FieldsDict& env,
1237 CORBA::String_out reason)
1240 if (_library_map.count(genericRegisterName) != 0)
1242 // It's a Python component
1243 Engines::EngineComponent_ptr compo = createPythonInstance(genericRegisterName, error);
1244 reason=CORBA::string_dup(error.c_str());
1248 std::string impl_name = std::string(LIB) + genericRegisterName + ENGINESO;
1249 if (_library_map.count(impl_name) != 0)
1251 // It's a C++ component
1252 void* handle = _library_map[impl_name];
1253 Engines::EngineComponent_ptr compo = createInstance(genericRegisterName, handle, error);
1254 reason=CORBA::string_dup(error.c_str());
1258 impl_name = std::string(genericRegisterName) + ".exe";
1259 if (_library_map.count(impl_name) != 0)
1261 //It's an executable component
1262 Engines::EngineComponent_ptr compo = createExecutableInstance(genericRegisterName, env, error);
1263 reason=CORBA::string_dup(error.c_str());
1267 error="load_component_Library has probably not been called for component: ";
1268 error += genericRegisterName;
1270 reason=CORBA::string_dup(error.c_str());
1271 return Engines::EngineComponent::_nil() ;
1274 //=============================================================================
1275 //! Create a new component instance (Executable implementation)
1277 * \param CompName Name of the component instance
1278 * \param env dict of env variables
1279 * \param reason explains error when creation fails
1280 * \return a loaded component
1282 * This component is implemented in an executable with name genericRegisterName.exe
1283 * It must register itself in Naming Service. The container waits some time (10 s max)
1284 * it's registration.
1286 //=============================================================================
1287 Engines::EngineComponent_ptr
1288 Abstract_Engines_Container_i::createExecutableInstance(std::string CompName,
1289 const Engines::FieldsDict& env,
1290 std::string& reason)
1292 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1294 _numInstanceMutex.lock() ; // lock on the instance number
1296 int numInstance = _numInstance ;
1297 _numInstanceMutex.unlock() ;
1300 sprintf( aNumI , "%d" , numInstance ) ;
1301 std::string instanceName = CompName + "_inst_" + aNumI ;
1302 std::string component_registerName = _containerName + "/" + instanceName;
1304 //check if an entry exist in naming service
1305 CORBA::Object_var nsobj = _NS->Resolve(component_registerName.c_str());
1306 if ( !CORBA::is_nil(nsobj) )
1308 // unregister the registered component
1309 _NS->Destroy_Name(component_registerName.c_str());
1310 //kill or shutdown it ???
1313 // first arg container ior string
1314 // second arg container name
1315 // third arg instance name
1317 Engines::Container_var pCont= _this();
1318 CORBA::String_var sior = _orb->object_to_string(pCont);
1320 std::string command;
1321 command="mkdir -p ";
1322 command+=instanceName;
1324 command+=instanceName;
1329 command+= sior; // container ior string
1331 command+=_containerName; //container name
1333 command+=instanceName; //instance name
1335 MESSAGE("SALOME_Container::create_component_instance command=" << command);
1338 // use fork/execl instead of system to get finer control on env variables
1341 if(pid == 0) // child
1343 EffectiveOverrideEnvironment(env);
1345 execl("/bin/sh", "sh", "-c", command.c_str() , (char *)0);
1348 else if(pid < 0) // failed to fork
1357 tpid = wait(&status);
1358 } while (tpid != pid);
1361 // launch component with a system call
1362 int status=system(command.c_str());
1367 reason="SALOME_Container::create_component_instance system failed (system command status -1)";
1369 return Engines::EngineComponent::_nil();
1372 else if (WEXITSTATUS(status) == 217)
1374 reason="SALOME_Container::create_component_instance system failed (system command status 217)";
1376 return Engines::EngineComponent::_nil();
1382 if (getenv("TIMEOUT_TO_WAIT_EXE_COMPONENT") != 0)
1384 std::string new_count_str = getenv("TIMEOUT_TO_WAIT_EXE_COMPONENT");
1386 std::istringstream ss(new_count_str);
1387 if (!(ss >> new_count))
1389 INFOS("[Container] TIMEOUT_TO_WAIT_EXE_COMPONENT should be an int");
1394 INFOS("[Container] waiting " << count << " second steps exe component ");
1395 CORBA::Object_var obj = CORBA::Object::_nil() ;
1396 while ( CORBA::is_nil(obj) && count )
1404 MESSAGE( count << ". Waiting for component " << CompName);
1405 obj = _NS->Resolve(component_registerName.c_str());
1408 if(CORBA::is_nil(obj))
1410 reason="SALOME_Container::create_component_instance failed";
1412 return Engines::EngineComponent::_nil();
1416 MESSAGE("SALOME_Container::create_component_instance successful");
1417 iobject = Engines::EngineComponent::_narrow(obj);
1418 _listInstances_map[instanceName] = iobject;
1419 return iobject._retn();
1425 //=============================================================================
1426 //! Create a new component instance (Python implementation)
1428 * \param CompName Name of the component instance
1429 * \param reason explains error when creation fails
1430 * \return a loaded component
1432 //=============================================================================
1433 Engines::EngineComponent_ptr
1434 Abstract_Engines_Container_i::createPythonInstance(std::string CompName,
1435 std::string& reason)
1437 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1439 _numInstanceMutex.lock() ; // lock on the instance number
1441 int numInstance = _numInstance ;
1442 _numInstanceMutex.unlock() ;
1445 sprintf( aNumI , "%d" , numInstance ) ;
1446 std::string instanceName = CompName + "_inst_" + aNumI ;
1447 std::string component_registerName = _containerName + "/" + instanceName;
1451 AutoPyRef result = PyObject_CallMethod(_pyCont,
1452 (char*)"create_component_instance",
1455 instanceName.c_str());
1458 PyArg_ParseTuple(result,"ss", &ior, &error);
1465 CORBA::Object_var obj = _orb->string_to_object(iors.c_str());
1466 iobject = Engines::EngineComponent::_narrow( obj ) ;
1467 _listInstances_map[instanceName] = iobject;
1469 return iobject._retn();
1473 Abstract_Engines_Container_i::create_python_service_instance(const char * CompName,
1474 CORBA::String_out reason)
1476 CORBA::Object_var object = CORBA::Object::_nil();
1478 _numInstanceMutex.lock() ; // lock on the instance number
1480 int numInstance = _numInstance ;
1481 _numInstanceMutex.unlock() ;
1484 sprintf( aNumI , "%d" , numInstance ) ;
1485 std::string instanceName = std::string(CompName) + "_inst_" + aNumI ;
1486 std::string component_registerName = _containerName + "/" + instanceName;
1488 char * _ior = nullptr;
1491 AutoPyRef result = PyObject_CallMethod(_pyCont,
1492 (char*)"create_component_instance",
1495 instanceName.c_str());
1498 PyArg_ParseTuple(result,"ss", &ior, &error);
1499 reason = CORBA::string_dup(error);
1500 _ior = CORBA::string_dup(ior);
1506 //=============================================================================
1507 //! Create a new component instance (C++ implementation)
1509 * C++ method: create a servant instance of a component.
1510 * \param genericRegisterName Name of the component instance to register
1511 * in Registry & Name Service,
1512 * (without _inst_n suffix, like "COMPONENT")
1513 * \param handle loaded library handle
1514 * \param reason explains error when creation fails
1515 * \return a loaded component
1517 * example with names:
1518 * - aGenRegisterName = COMPONENT (= first argument)
1519 * - _containerName = /Containers/cli76ce/FactoryServer
1520 * - factoryName = COMPONENTEngine_factory
1521 * - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
1522 * - instanceName = COMPONENT_inst_1
1523 * - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1525 //=============================================================================
1526 Engines::EngineComponent_ptr
1527 Abstract_Engines_Container_i::createInstance(std::string genericRegisterName,
1529 std::string& reason)
1531 // --- find the factory
1533 std::string aGenRegisterName = genericRegisterName;
1534 std::string factory_name = aGenRegisterName + std::string("Engine_factory");
1535 SCRUTE(factory_name) ;
1537 typedef PortableServer::ObjectId* (*FACTORY_FUNCTION) (CORBA::ORB_ptr,
1538 PortableServer::POA_ptr,
1539 PortableServer::ObjectId *,
1544 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)dlsym( handle, factory_name.c_str() );
1546 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)GetProcAddress( (HINSTANCE)handle, factory_name.c_str() );
1549 if ( !Component_factory )
1551 MESSAGE( "Can't resolve symbol: " + factory_name );
1556 return Engines::EngineComponent::_nil() ;
1559 // --- create instance
1561 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1565 _numInstanceMutex.lock() ; // lock on the instance number
1567 int numInstance = _numInstance ;
1568 _numInstanceMutex.unlock() ;
1571 sprintf( aNumI , "%d" , numInstance ) ;
1572 std::string instanceName = aGenRegisterName + "_inst_" + aNumI ;
1573 std::string component_registerName =
1574 _containerName + "/" + instanceName;
1576 // --- Instantiate required CORBA object
1578 PortableServer::ObjectId *id ; //not owner, do not delete (nore use var)
1579 id = (Component_factory) ( _orb, _poa, _id, instanceName.c_str(),
1580 aGenRegisterName.c_str() ) ;
1583 reason="Can't get ObjectId from factory";
1585 return iobject._retn();
1588 // --- get reference from id
1590 CORBA::Object_var obj = _poa->id_to_reference(*id);
1591 iobject = Engines::EngineComponent::_narrow( obj ) ;
1593 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1594 _listInstances_map[instanceName] = iobject;
1595 _cntInstances_map[aGenRegisterName] += 1;
1596 _numInstanceMutex.unlock() ;
1597 SCRUTE(aGenRegisterName);
1598 SCRUTE(_cntInstances_map[aGenRegisterName]);
1600 // --- register the engine under the name
1601 // containerName(.dir)/instanceName(.object)
1603 _NS->Register( iobject , component_registerName.c_str() ) ;
1604 MESSAGE( component_registerName.c_str() << " bound" ) ;
1608 reason="Container_i::createInstance exception caught";
1611 return iobject._retn();
1614 //=============================================================================
1615 //! Find an existing (in the container) component instance
1617 * CORBA method: Finds a servant instance of a component
1618 * \param registeredName Name of the component in Registry or Name Service,
1619 * without instance suffix number
1620 * \return the first found instance
1622 //=============================================================================
1623 Engines::EngineComponent_ptr
1624 Abstract_Engines_Container_i::find_component_instance( const char* registeredName)
1626 Engines::EngineComponent_var anEngine = Engines::EngineComponent::_nil();
1627 std::map<std::string,Engines::EngineComponent_var>::iterator itm =_listInstances_map.begin();
1628 while (itm != _listInstances_map.end())
1630 std::string instance = (*itm).first;
1632 if (instance.find(registeredName) == 0)
1634 anEngine = (*itm).second;
1635 return anEngine._retn();
1639 return anEngine._retn();
1642 //=============================================================================
1643 //! Remove the component instance from container
1645 * CORBA method: Stops the component servant, and deletes all related objects
1646 * \param component_i Component to be removed
1648 //=============================================================================
1650 void Abstract_Engines_Container_i::remove_impl(Engines::EngineComponent_ptr component_i)
1652 ASSERT(! CORBA::is_nil(component_i));
1653 std::string instanceName = component_i->instanceName() ;
1654 MESSAGE("unload component " << instanceName);
1655 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1656 _listInstances_map.erase(instanceName);
1657 _numInstanceMutex.unlock() ;
1658 component_i->destroy() ;
1659 _NS->Destroy_Name(instanceName.c_str());
1662 //=============================================================================
1663 //! Unload component libraries from the container
1665 * CORBA method: Discharges unused libraries from the container.
1667 //=============================================================================
1668 void Abstract_Engines_Container_i::finalize_removal()
1670 MESSAGE("finalize unload : dlclose");
1671 _numInstanceMutex.lock(); // lock to be alone
1672 // (see decInstanceCnt, load_component_Library)
1673 std::map<std::string, void *>::iterator ith;
1674 for (ith = _toRemove_map.begin(); ith != _toRemove_map.end(); ith++)
1676 void *handle = (*ith).second;
1677 std::string impl_name= (*ith).first;
1682 // dlclose(handle); // SALOME unstable after ...
1683 // _library_map.erase(impl_name);
1686 _toRemove_map.clear();
1687 _numInstanceMutex.unlock();
1690 //=============================================================================
1691 //! Decrement component instance reference count
1695 //=============================================================================
1696 void Abstract_Engines_Container_i::decInstanceCnt(std::string genericRegisterName)
1698 if(_cntInstances_map.count(genericRegisterName)==0)
1700 std::string aGenRegisterName =genericRegisterName;
1701 MESSAGE("Engines_Container_i::decInstanceCnt " << aGenRegisterName);
1702 ASSERT(_cntInstances_map[aGenRegisterName] > 0);
1703 _numInstanceMutex.lock(); // lock to be alone
1704 // (see finalize_removal, load_component_Library)
1705 _cntInstances_map[aGenRegisterName] -= 1;
1706 SCRUTE(_cntInstances_map[aGenRegisterName]);
1707 if (_cntInstances_map[aGenRegisterName] == 0)
1709 std::string impl_name =
1710 Engines_Component_i::GetDynLibraryName(aGenRegisterName.c_str());
1712 void* handle = _library_map[impl_name];
1714 _toRemove_map[impl_name] = handle;
1716 _numInstanceMutex.unlock();
1719 //=============================================================================
1720 //! Find or create a new component instance
1722 * CORBA method: find or create an instance of the component (servant),
1723 * load a new component class (dynamic library) if required,
1725 * ---- FOR COMPATIBILITY WITH 2.2 ----
1727 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
1729 * The servant registers itself to naming service and Registry.
1730 * \param genericRegisterName Name of the component to register
1731 * in Registry & Name Service
1732 * \param componentName Name of the constructed library of the component
1733 * \return a loaded component
1735 //=============================================================================
1737 Engines::EngineComponent_ptr
1738 Abstract_Engines_Container_i::load_impl( const char* genericRegisterName,
1739 const char* /*componentName*/ )
1742 std::string impl_name = std::string(LIB) + genericRegisterName + ENGINESO;
1743 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1744 if (load_component_Library(genericRegisterName,reason))
1745 iobject = find_or_create_instance(genericRegisterName, impl_name);
1746 CORBA::string_free(reason);
1747 return iobject._retn();
1750 Engines::EmbeddedNamingService_ptr Abstract_Engines_Container_i::get_embedded_NS_if_ssl()
1752 SALOME_Embedded_NamingService_Client *nsc(dynamic_cast<SALOME_Embedded_NamingService_Client *>(this->_NS));
1755 Engines::EmbeddedNamingService_var obj = nsc->GetObject();
1756 return Engines::EmbeddedNamingService::_duplicate(obj);
1760 SALOME_Fake_NamingService *fns(dynamic_cast<SALOME_Fake_NamingService *>(this->_NS));
1763 Engines::EmbeddedNamingService_var ret = GetEmbeddedNamingService();
1767 return Engines::EmbeddedNamingService::_nil();
1771 //=============================================================================
1772 //! Finds an already existing component instance or create a new instance
1774 * C++ method: Finds an already existing servant instance of a component, or
1775 * create an instance.
1776 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
1777 * \param genericRegisterName Name of the component instance to register
1778 * in Registry & Name Service,
1779 * (without _inst_n suffix, like "COMPONENT")
1780 * \param componentLibraryName like "libCOMPONENTEngine.so"
1781 * \return a loaded component
1783 * example with names:
1784 * - aGenRegisterName = COMPONENT (= first argument)
1785 * - impl_name = libCOMPONENTEngine.so (= second argument)
1786 * - _containerName = /Containers/cli76ce/FactoryServer
1787 * - factoryName = COMPONENTEngine_factory
1788 * - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
1789 * - instanceName = COMPONENT_inst_1
1790 * - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1792 //=============================================================================
1794 Engines::EngineComponent_ptr
1795 Abstract_Engines_Container_i::find_or_create_instance(std::string genericRegisterName,
1796 std::string componentLibraryName)
1798 std::string aGenRegisterName = genericRegisterName;
1799 std::string impl_name = componentLibraryName;
1800 if (_library_map.count(impl_name) == 0)
1802 INFOS("shared library " << impl_name <<" must be loaded before creating instance");
1803 return Engines::EngineComponent::_nil() ;
1807 // --- find a registered instance in naming service, or create
1809 void* handle = _library_map[impl_name];
1810 std::string component_registerBase =
1811 _containerName + "/" + aGenRegisterName;
1812 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1816 CORBA::Object_var obj =
1817 _NS->ResolveFirst( component_registerBase.c_str());
1818 if ( CORBA::is_nil( obj ) )
1820 iobject = createInstance(genericRegisterName,
1826 iobject = Engines::EngineComponent::_narrow( obj ) ;
1831 INFOS( "Container_i::load_impl caught" ) ;
1833 return iobject._retn();
1837 //=============================================================================
1838 //! Indicate if container is a python one
1840 * Retrieves only with container naming convention if it is a python container
1842 //=============================================================================
1843 bool Abstract_Engines_Container_i::isPythonContainer(const char* ContainerName)
1846 size_t len=strlen(ContainerName);
1848 if(strcmp(ContainerName+len-2,"Py")==0)
1853 //=============================================================================
1854 //! Kill the container
1856 * CORBA method: Kill the container process with exit(0).
1857 * To remove : never returns !
1859 //=============================================================================
1860 bool Abstract_Engines_Container_i::Kill_impl()
1862 MESSAGE("Engines_Container_i::Kill() pid "<< getpid() << " containerName "
1863 << _containerName.c_str() << " machineName "
1864 << Kernel_Utils::GetHostname().c_str());
1865 INFOS("===============================================================");
1866 INFOS("= REMOVE calls to Kill_impl in C++ container =");
1867 INFOS("===============================================================");
1873 //=============================================================================
1877 //=============================================================================
1878 void ActSigIntHandler()
1881 struct sigaction SigIntAct ;
1882 SigIntAct.sa_sigaction = &SigIntHandler ;
1883 sigemptyset(&SigIntAct.sa_mask);
1884 SigIntAct.sa_flags = SA_SIGINFO ;
1887 // DEBUG 03.02.2005 : the first parameter of sigaction is not a mask of signals
1888 // (SIGINT | SIGUSR1) :
1889 // it must be only one signal ===> one call for SIGINT
1890 // and an other one for SIGUSR1
1893 if ( sigaction( SIGINT , &SigIntAct, NULL ) )
1895 perror("SALOME_Container main ") ;
1898 if ( sigaction( SIGUSR1 , &SigIntAct, NULL ) )
1900 perror("SALOME_Container main ") ;
1903 if ( sigaction( SIGUSR2 , &SigIntAct, NULL ) )
1905 perror("SALOME_Container main ") ;
1909 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1910 // use of streams (and so on) should never be used because :
1911 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1912 // A stream operation may be interrupted by a signal and if the Handler use stream we
1913 // may have a "Dead-Lock" ===HangUp
1914 //==INFOS is commented
1915 // INFOS(pthread_self() << "SigIntHandler activated") ;
1918 signal( SIGINT, SigIntHandler );
1919 // legacy code required to supervisor. Commented in order to avoid problems on Windows
1920 // signal( SIGUSR1, SigIntHandler );
1926 void CallCancelThread() ;
1929 void SigIntHandler(int /*what*/ ,
1930 siginfo_t * siginfo ,
1933 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1934 // use of streams (and so on) should never be used because :
1935 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1936 // A stream operation may be interrupted by a signal and if the Handler use stream we
1937 // may have a "Dead-Lock" ===HangUp
1938 //==MESSAGE is commented
1939 // MESSAGE(pthread_self() << "SigIntHandler what " << what << std::endl
1940 // << " si_signo " << siginfo->si_signo << std::endl
1941 // << " si_code " << siginfo->si_code << std::endl
1942 // << " si_pid " << siginfo->si_pid) ;
1947 // MESSAGE("SigIntHandler END sleeping.") ;
1952 ActSigIntHandler() ;
1953 if ( siginfo->si_signo == SIGUSR1 )
1957 else if ( siginfo->si_signo == SIGUSR2 )
1959 CallCancelThread() ;
1964 // MESSAGE("SigIntHandler BEGIN sleeping.") ;
1971 // MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1977 void SigIntHandler( int what )
1980 MESSAGE( pthread_self() << "SigIntHandler what " << what << std::endl );
1982 MESSAGE( "SigIntHandler what " << what << std::endl );
1987 MESSAGE("SigIntHandler END sleeping.") ;
1992 ActSigIntHandler() ;
1993 if ( what == SIGUSR1 )
2000 MESSAGE("SigIntHandler BEGIN sleeping.") ;
2007 MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
2014 //=============================================================================
2015 //! Get or create a file reference object associated to a local file (to transfer it)
2017 * CORBA method: get or create a fileRef object associated to a local file
2018 * (a file on the computer on which runs the container server), which stores
2019 * a list of (machine, localFileName) corresponding to copies already done.
2021 * \param origFileName absolute path for a local file to copy on other
2023 * \return a fileRef object associated to the file.
2025 //=============================================================================
2026 Engines::fileRef_ptr
2027 Abstract_Engines_Container_i::createFileRef(const char* origFileName)
2029 std::string origName(origFileName);
2030 Engines::fileRef_var theFileRef = Engines::fileRef::_nil();
2032 if (origName[0] != '/')
2034 INFOS("path of file to copy must be an absolute path beginning with '/'");
2035 return Engines::fileRef::_nil();
2038 if (CORBA::is_nil(_fileRef_map[origName]))
2040 CORBA::Object_var obj=_poa->id_to_reference(*_id);
2041 Engines::Container_var pCont = Engines::Container::_narrow(obj);
2042 fileRef_i* aFileRef = new fileRef_i(pCont, origFileName);
2043 theFileRef = Engines::fileRef::_narrow(aFileRef->_this());
2044 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
2045 _fileRef_map[origName] = theFileRef;
2046 _numInstanceMutex.unlock() ;
2049 theFileRef = Engines::fileRef::_duplicate(_fileRef_map[origName]);
2050 ASSERT(! CORBA::is_nil(theFileRef));
2051 return theFileRef._retn();
2054 //=============================================================================
2055 //! Get a fileTransfer reference
2058 * \return a reference to the fileTransfer object
2060 //=============================================================================
2061 Engines::fileTransfer_ptr
2062 Abstract_Engines_Container_i::getFileTransfer()
2064 Engines::fileTransfer_var aFileTransfer
2065 = Engines::fileTransfer::_duplicate(_fileTransfer);
2066 return aFileTransfer._retn();
2069 //=============================================================================
2070 //! Create a Salome file
2071 //=============================================================================
2072 Engines::Salome_file_ptr
2073 Abstract_Engines_Container_i::createSalome_file(const char* origFileName)
2075 std::string origName(origFileName);
2076 if (CORBA::is_nil(_Salome_file_map[origName]))
2078 Salome_file_i* aSalome_file = new Salome_file_i();
2079 aSalome_file->setContainer(Engines::Container::_duplicate(this->_this()));
2082 aSalome_file->setLocalFile(origFileName);
2083 aSalome_file->recvFiles();
2085 catch (const SALOME::SALOME_Exception& /*e*/) //!< TODO: unused variable
2087 return Engines::Salome_file::_nil();
2090 Engines::Salome_file_var theSalome_file = Engines::Salome_file::_nil();
2091 theSalome_file = Engines::Salome_file::_narrow(aSalome_file->_this());
2092 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
2093 _Salome_file_map[origName] = theSalome_file;
2094 _numInstanceMutex.unlock() ;
2097 Engines::Salome_file_ptr theSalome_file =
2098 Engines::Salome_file::_duplicate(_Salome_file_map[origName]);
2099 ASSERT(!CORBA::is_nil(theSalome_file));
2100 return theSalome_file;
2103 //=============================================================================
2104 /*! \brief copy a file from a remote host (container) to the local host
2105 * \param container the remote container
2106 * \param remoteFile the file to copy locally from the remote host into localFile
2107 * \param localFile the local file
2109 //=============================================================================
2110 void Abstract_Engines_Container_i::copyFile(Engines::Container_ptr container, const char* remoteFile, const char* localFile)
2112 Engines::fileTransfer_var fileTransfer = container->getFileTransfer();
2115 if ((fp = fopen(localFile,"wb")) == NULL)
2117 INFOS("file " << localFile << " cannot be open for writing");
2121 CORBA::Long fileId = fileTransfer->open(remoteFile);
2124 Engines::fileBlock* aBlock;
2131 aBlock = fileTransfer->getBlock(fileId);
2132 toFollow = aBlock->length();
2134 CORBA::Octet *buf = aBlock->get_buffer();
2135 fwrite(buf, sizeof(CORBA::Octet), toFollow, fp);
2139 MESSAGE("end of transfer");
2140 fileTransfer->close(fileId);
2144 INFOS("open reference file for copy impossible");
2148 //=============================================================================
2149 /*! \brief create a PyNode object to execute remote python code
2150 * \param nodeName the name of the node
2151 * \param code the python code to load
2152 * \return the PyNode
2154 //=============================================================================
2155 Engines::PyNode_ptr Abstract_Engines_Container_i::createPyNode(const char* nodeName, const char* code)
2157 Engines::PyNode_var node= Engines::PyNode::_nil();
2162 PyObject *res = PyObject_CallMethod(_pyCont,
2163 (char*)"create_pynode",
2171 SALOME::ExceptionStruct es;
2172 es.type = SALOME::INTERNAL_ERROR;
2173 es.text = "can not create a python node";
2174 throw SALOME::SALOME_Exception(es);
2176 ierr=PyLong_AsLong(PyTuple_GetItem(res,0));
2177 PyObject* result=PyTuple_GetItem(res,1);
2178 astr = PyUnicode_AsUTF8(result);
2183 Utils_Locker lck(&_mutexForDftPy);
2184 CORBA::Object_var obj=_orb->string_to_object(astr.c_str());
2185 node=Engines::PyNode::_narrow(obj);
2186 std::map<std::string,Engines::PyNode_var>::iterator it(_dftPyNode.find(nodeName));
2187 if(it==_dftPyNode.end())
2189 _dftPyNode[nodeName]=node;
2193 Engines::PyNode_var oldNode((*it).second);
2194 if(!CORBA::is_nil(oldNode))
2195 oldNode->UnRegister();
2198 if(!CORBA::is_nil(node))
2200 return node._retn();
2204 SALOME::ExceptionStruct es;
2205 es.type = SALOME::INTERNAL_ERROR;
2206 es.text = astr.c_str();
2207 throw SALOME::SALOME_Exception(es);
2211 //=============================================================================
2212 /*! \brief Retrieves the last created PyNode instance with createPyNode.
2215 //=============================================================================
2216 Engines::PyNode_ptr Abstract_Engines_Container_i::getDefaultPyNode(const char *nodeName)
2218 Utils_Locker lck(&_mutexForDftPy);
2219 std::map<std::string,Engines::PyNode_var>::iterator it(_dftPyNode.find(nodeName));
2220 if(it==_dftPyNode.end())
2221 return Engines::PyNode::_nil();
2224 Engines::PyNode_var tmpVar((*it).second);
2225 if(!CORBA::is_nil(tmpVar))
2226 return Engines::PyNode::_duplicate(tmpVar);
2228 return Engines::PyNode::_nil();
2232 //=============================================================================
2233 /*! \brief create a PyScriptNode object to execute remote python code
2234 * \param nodeName the name of the node
2235 * \param code the python code to load
2236 * \return the PyScriptNode
2238 //=============================================================================
2239 Engines::PyScriptNode_ptr Abstract_Engines_Container_i::createPyScriptNode(const char* nodeName, const char* code)
2241 Engines::PyScriptNode_var node= Engines::PyScriptNode::_nil();
2246 AutoPyRef res = PyObject_CallMethod(_pyCont,
2247 (char*)"create_pyscriptnode",
2255 SALOME::ExceptionStruct es;
2256 es.type = SALOME::INTERNAL_ERROR;
2257 es.text = "can not create a python node";
2258 throw SALOME::SALOME_Exception(es);
2260 ierr=PyLong_AsLong(PyTuple_GetItem(res,0));
2261 PyObject* result=PyTuple_GetItem(res,1);
2262 astr = PyUnicode_AsUTF8(result);
2267 Utils_Locker lck(&_mutexForDftPy);
2268 CORBA::Object_var obj=_orb->string_to_object(astr.c_str());
2269 node=Engines::PyScriptNode::_narrow(obj);
2270 std::map<std::string,Engines::PyScriptNode_var>::iterator it(_dftPyScriptNode.find(nodeName));
2271 if(it==_dftPyScriptNode.end())
2273 _dftPyScriptNode[nodeName]=node;
2277 Engines::PyScriptNode_var oldNode((*it).second);
2278 if(!CORBA::is_nil(oldNode))
2279 oldNode->UnRegister();
2282 return node._retn();
2286 SALOME::ExceptionStruct es;
2287 es.type = SALOME::INTERNAL_ERROR;
2288 es.text = astr.c_str();
2289 throw SALOME::SALOME_Exception(es);
2293 void Abstract_Engines_Container_i::removePyScriptNode(const char *nodeName)
2295 std::map<std::string,Engines::PyScriptNode_var>::iterator it(_dftPyScriptNode.find(nodeName));
2296 if(it==_dftPyScriptNode.end())
2298 std::ostringstream oss; oss << "Engines_Container_i::removePyScriptNode : node \"" << nodeName << "\" is not map !";
2299 SALOME::ExceptionStruct es;
2300 es.type = SALOME::INTERNAL_ERROR;
2301 es.text = oss.str().c_str();
2302 throw SALOME::SALOME_Exception(es);
2304 (*it).second->UnRegister();
2305 _dftPyScriptNode.erase(it);
2308 void Abstract_Engines_Container_i::cleanAllPyScripts()
2310 for(std::map<std::string,Engines::PyNode_var>::iterator it=_dftPyNode.begin();it!=_dftPyNode.end();it++)
2312 Engines::PyNode_var tmpVar((*it).second);
2313 if(!CORBA::is_nil(tmpVar))
2314 tmpVar->UnRegister();
2317 for(std::map<std::string,Engines::PyScriptNode_var>::iterator it=_dftPyScriptNode.begin();it!=_dftPyScriptNode.end();it++)
2319 Engines::PyScriptNode_var tmpVar((*it).second);
2320 if(!CORBA::is_nil(tmpVar))
2321 tmpVar->UnRegister();
2323 _dftPyScriptNode.clear();
2326 //=============================================================================
2327 /*! \brief Retrieves the last created PyScriptNode instance with createPyScriptNode.
2330 //=============================================================================
2331 Engines::PyScriptNode_ptr Abstract_Engines_Container_i::getDefaultPyScriptNode(const char *nodeName)
2333 Utils_Locker lck(&_mutexForDftPy);
2334 std::map<std::string,Engines::PyScriptNode_var>::iterator it(_dftPyScriptNode.find(nodeName));
2335 if(it==_dftPyScriptNode.end())
2336 return Engines::PyScriptNode::_nil();
2339 Engines::PyScriptNode_var tmpVar((*it).second);
2340 if(!CORBA::is_nil(tmpVar))
2341 return Engines::PyScriptNode::_duplicate(tmpVar);
2343 return Engines::PyScriptNode::_nil();
2347 //=============================================================================
2348 /* int checkifexecutable(const char *filename)
2350 * Return non-zero if the name is an executable file, and
2351 * zero if it is not executable, or if it does not exist.
2353 //=============================================================================
2354 int checkifexecutable(const std::string& filename)
2357 struct stat statinfo;
2359 result = stat(filename.c_str(), &statinfo);
2360 if (result < 0) return 0;
2361 if (!S_ISREG(statinfo.st_mode)) return 0;
2366 if (statinfo.st_uid == geteuid()) return statinfo.st_mode & S_IXUSR;
2367 if (statinfo.st_gid == getegid()) return statinfo.st_mode & S_IXGRP;
2368 return statinfo.st_mode & S_IXOTH;
2373 //=============================================================================
2374 /*! \brief Find a file by searching in a path
2375 * \param filename file name to search
2376 * \param path path to search in
2377 * \param pth the complete file path if found
2378 * \return 1 if found 0 if not
2380 //=============================================================================
2381 int findpathof(const std::string& path, std::string& pth, const std::string& filename)
2383 if ( path.size() == 0 ) return 0;
2385 std::string::size_type offset = 0;
2386 std::string::size_type pos = 0;
2388 struct stat statinfo;
2392 pos = path.find( SEP, offset );
2393 pth = path.substr( offset, pos - offset );
2394 if ( pth.size() > 0 )
2396 if( pth[pth.size()-1] != SLASH ) pth += SLASH;
2398 int result=stat(pth.c_str(), &statinfo);
2399 if(result == 0) found=1;
2401 if (pos == std::string::npos) break;
2407 void Abstract_Engines_Container_i::registerTemporaryFile( const std::string& fileName )
2409 _tmp_files.remove( fileName );
2410 _tmp_files.push_back( fileName );
2413 void Abstract_Engines_Container_i::unregisterTemporaryFile( const std::string& fileName )
2415 _tmp_files.remove( fileName );
2418 void Abstract_Engines_Container_i::clearTemporaryFiles()
2420 std::list<std::string>::const_iterator it;
2421 for ( it = _tmp_files.begin(); it != _tmp_files.end(); ++it ) {
2422 #if defined(WIN32) && defined(UNICODE)
2423 std::wstring aFile = Kernel_Utils::utf8_decode_s(*it);
2424 std::wstring command = (GetFileAttributes(aFile.c_str()) == FILE_ATTRIBUTE_DIRECTORY) ? L"rd /Q \"" : L"del /F /Q \"";
2426 command += L"\" 2>NUL";
2427 _wsystem(command.c_str());
2430 std::string aFile = *it;
2431 std::string command = (GetFileAttributes(aFile.c_str()) == FILE_ATTRIBUTE_DIRECTORY) ? "rd /Q \"" : "del /F /Q \"";
2433 command += "\" 2>NUL";
2435 std::string command = "rm -rf ";
2438 system(command.c_str());
2444 static Engines_Container_SSL_i *_container_singleton_ssl = nullptr;
2446 static Engines::Container_var _container_ref_singleton_ssl;
2448 Abstract_Engines_Container_SSL_i *KERNEL::getContainerSA()
2450 if(!_container_singleton_ssl)
2452 CORBA::ORB_var orb = KERNEL::GetRefToORB();
2453 CORBA::Object_var obj = orb->resolve_initial_references("RootPOA");
2454 PortableServer::POA_var poa = PortableServer::POA::_narrow(obj);
2455 PortableServer::POAManager_var pman = poa->the_POAManager();
2456 CORBA::PolicyList policies;
2459 constexpr int ARGC = 4;
2460 constexpr const char *ARGV[ARGC] = {"Container","FactoryServer","toto",nullptr};
2461 std::unique_ptr<char*[]> argv( new char *[ARGC+1] );
2462 std::vector< std::unique_ptr<char[]> > argvv(ARGC);
2463 argv[ARGC] = nullptr;
2464 for(int i = 0 ; i < ARGC ; ++i)
2468 argvv[i].reset( new char[strlen(ARGV[i])+1] );
2469 strcpy(argvv[i].get(),ARGV[i]);
2470 argv[i] = argvv[i].get();
2475 SALOME_Fake_NamingService ns;
2476 _container_singleton_ssl = new Engines_Container_SSL_i(orb,poa,(char *)"FactoryServer",2,argv.get(),&ns,false);
2477 PortableServer::ObjectId * cont_id = _container_singleton_ssl->getCORBAId();
2479 CORBA::Object_var zeRef = poa->id_to_reference(*cont_id);
2480 _container_ref_singleton_ssl = Engines::Container::_narrow(zeRef);
2482 return _container_singleton_ssl;
2485 Engines::Container_var KERNEL::getContainerRefSA()
2488 return _container_ref_singleton_ssl;