1 // Copyright (C) 2007-2023 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 std::map<std::string, int> Abstract_Engines_Container_i::_cntInstances_map;
114 std::map<std::string, void *> Abstract_Engines_Container_i::_library_map;
115 std::map<std::string, void *> Abstract_Engines_Container_i::_toRemove_map;
116 omni_mutex Abstract_Engines_Container_i::_numInstanceMutex ;
118 static PyObject* _pyCont;
120 int checkifexecutable(const std::string&);
121 int findpathof(const std::string& path, std::string&, const std::string&);
123 /*! \class Engines_Container_i
124 * \brief C++ implementation of Engines::Container interface
129 //=============================================================================
131 * Default constructor, not for use
133 //=============================================================================
135 Abstract_Engines_Container_i::Abstract_Engines_Container_i () :
136 _NS(nullptr),_id(nullptr),_numInstance(0)
140 //=============================================================================
144 //=============================================================================
146 Abstract_Engines_Container_i::Abstract_Engines_Container_i (CORBA::ORB_ptr orb,
147 PortableServer::POA_ptr poa,
148 char *containerName ,
149 int argc , char* argv[],
150 SALOME_NamingService_Container_Abstract *ns,
151 bool isServantAloneInProcess
153 _NS(nullptr),_id(0),_numInstance(0),_isServantAloneInProcess(isServantAloneInProcess)
155 _pid = (long)getpid();
163 std::string hostname = Kernel_Utils::GetHostname();
165 MESSAGE(hostname << " " << getpid() <<
166 " Engines_Container_i starting argc " <<
167 _argc << " Thread " << pthread_self() ) ;
169 MESSAGE(hostname << " " << _getpid() <<
170 " Engines_Container_i starting argc " << _argc<< " Thread " << pthread_self().p ) ;
176 MESSAGE(" argv" << i << " " << _argv[ i ]) ;
182 INFOS("SALOME_Container usage : SALOME_Container ServerName");
186 _isSupervContainer = false;
188 _orb = CORBA::ORB::_duplicate(orb) ;
189 _poa = PortableServer::POA::_duplicate(poa) ;
191 // Pour les containers paralleles: il ne faut pas enregistrer et activer
192 // le container generique, mais le container specialise
195 _id = _poa->activate_object(this);
196 // key point : if ns is nullptr : this servant is alone in its process
197 // if ns is not null : this servant embedded into single process.
198 _NS = ns==nullptr ? new SALOME_NamingService : ns->clone();
199 _NS->init_orb( _orb ) ;
200 CORBA::Object_var obj=_poa->id_to_reference(*_id);
201 Engines::Container_var pCont = Engines::Container::_narrow(obj);
204 _containerName = SALOME_NamingService_Abstract::BuildContainerNameForNS(containerName, hostname.c_str());
205 SCRUTE(_containerName);
206 _NS->Register(pCont, _containerName.c_str());
207 MESSAGE("Engines_Container_i::Engines_Container_i : Container name " << _containerName);
210 // import SALOME_Container
211 // pycont = SALOME_Container.SALOME_Container_i(containerIORStr)
213 CORBA::String_var sior = _orb->object_to_string(pCont);
214 std::string myCommand="pyCont = SALOME_Container.SALOME_Container_i('";
215 myCommand += _containerName + "','";
220 //[RNV]: Comment the PyEval_AcquireLock() and PyEval_ReleaseLock() because this
221 //approach leads to the deadlock of the main thread of the application on Windows platform
222 //in case if cppContainer runs in the standalone mode. The problem with the PyThreadState
223 //described by ABN seems not reproduced, to be checked carefully later...
226 //// [ABN]: using the PyGILState* API here is unstable. omniORB logic is invoked
227 //// by the Python code executed below, and in some (random) cases, the Python code
228 //// execution ends with a PyThreadState which was not the one we have here.
229 //// (TODO: understand why ...)
230 //// To be on the safe side we get and load the thread state ourselves:
231 //PyEval_AcquireLock(); // get GIL
232 //PyThreadState * mainThreadState = PyThreadState_Get();
233 //PyThreadState_Swap(mainThreadState);
236 // mpv: this is temporary solution: there is a unregular crash if not
239 // first element is the path to Registry.dll, but it's wrong
240 PyRun_SimpleString("import sys\n");
241 PyRun_SimpleString("sys.path = sys.path[1:]\n");
243 PyRun_SimpleString("import SALOME_Container\n");
244 PyRun_SimpleString((char*)myCommand.c_str());
245 PyObject *mainmod = PyImport_AddModule("__main__");
246 PyObject *globals = PyModule_GetDict(mainmod);
247 _pyCont = PyDict_GetItemString(globals, "pyCont");
248 //PyThreadState_Swap(NULL);
249 //PyEval_ReleaseLock();
252 fileTransfer_i* aFileTransfer = new fileTransfer_i();
253 CORBA::Object_var obref=aFileTransfer->_this();
254 _fileTransfer = Engines::fileTransfer::_narrow(obref);
255 aFileTransfer->_remove_ref();
259 //=============================================================================
263 //=============================================================================
265 Abstract_Engines_Container_i::~Abstract_Engines_Container_i()
267 MESSAGE("Abstract_Container_i::~Abstract_Container_i()");
275 //=============================================================================
276 //! Get container name
278 * CORBA attribute: Container name (see constructor)
280 //=============================================================================
282 char* Abstract_Engines_Container_i::name()
284 return CORBA::string_dup(_containerName.c_str()) ;
287 //=============================================================================
288 //! Get container working directory
290 * CORBA attribute: Container working directory
292 //=============================================================================
294 char* Abstract_Engines_Container_i::workingdir()
298 return CORBA::string_dup(wd) ;
301 //=============================================================================
302 //! Get container log file name
304 * CORBA attribute: Container log file name
306 //=============================================================================
308 char* Abstract_Engines_Container_i::logfilename()
310 return CORBA::string_dup(_logfilename.c_str()) ;
313 //! Set container log file name
314 void Abstract_Engines_Container_i::logfilename(const char* name)
319 //=============================================================================
320 //! Get container host name
322 * CORBA method: Get the hostName of the Container (without domain extensions)
324 //=============================================================================
326 char* Abstract_Engines_Container_i::getHostName()
328 std::string s = Kernel_Utils::GetHostname();
329 // MESSAGE("Engines_Container_i::getHostName " << s);
330 return CORBA::string_dup(s.c_str()) ;
333 //=============================================================================
334 //! Get container PID
336 * CORBA method: Get the PID (process identification) of the Container
338 //=============================================================================
340 CORBA::Long Abstract_Engines_Container_i::getPID()
342 return (CORBA::Long)getpid();
345 //=============================================================================
346 //! Ping the servant to check it is still alive
348 * CORBA method: check if servant is still alive
350 //=============================================================================
351 void Abstract_Engines_Container_i::ping()
353 MESSAGE("Engines_Container_i::ping() pid "<< getpid());
356 //=============================================================================
357 //! Get number of CPU cores in the calculation node
359 * CORBA method: get number of CPU cores
361 //=============================================================================
363 CORBA::Long Abstract_Engines_Container_i::getNumberOfCPUCores()
366 PyObject *module = PyImport_ImportModuleNoBlock((char*)"salome_psutil");
367 PyObject *result = PyObject_CallMethod(module,
368 (char*)"getNumberOfCPUCores", NULL);
369 int n = PyLong_AsLong(result);
372 return (CORBA::Long)n;
375 //=============================================================================
376 //! Get a load of each CPU core in the calculation node
378 * CORBA method: get a load of each CPU core
380 //=============================================================================
390 PyStdOut_dealloc(PyStdOut *self)
396 PyStdOut_write(PyStdOut* self, PyObject* args)
399 if (!PyArg_ParseTuple(args, "s", &c))
402 *(self->out) = *(self->out) + c;
408 static PyMethodDef PyStdOut_methods[] =
410 {"write", (PyCFunction)PyStdOut_write, METH_VARARGS,
411 PyDoc_STR("write(string) -> None")},
412 {0, 0, 0, 0} /* sentinel */
415 static PyMemberDef PyStdOut_memberlist[] =
417 {(char*)"softspace", T_INT, offsetof(PyStdOut, softspace), 0,
418 (char*)"flag indicating that a space needs to be printed; used by print"},
419 {0, 0, 0, 0, 0} /* sentinel */
422 static PyTypeObject PyStdOut_Type =
424 /* The ob_type field must be initialized in the module init function
425 * to be portable to Windows without using C++. */
426 PyVarObject_HEAD_INIT(NULL, 0)
429 sizeof(PyStdOut), /*tp_basicsize*/
432 (destructor)PyStdOut_dealloc, /*tp_dealloc*/
439 0, /*tp_as_sequence*/
444 PyObject_GenericGetAttr, /*tp_getattro*/
445 /* softspace is writable: we must supply tp_setattro */
446 PyObject_GenericSetAttr, /* tp_setattro */
448 Py_TPFLAGS_DEFAULT, /*tp_flags*/
452 0, /*tp_richcompare*/
453 0, /*tp_weaklistoffset*/
456 PyStdOut_methods, /*tp_methods*/
457 PyStdOut_memberlist, /*tp_members*/
475 0, /*tp_version_tag*/
479 PyObject* newPyStdOut(std::string& out)
481 PyStdOut* self = PyObject_New(PyStdOut, &PyStdOut_Type);
486 return (PyObject*)self;
489 std::string parseException()
492 if (PyErr_Occurred())
494 #ifdef BOS26455_WITH_BOOST_PYTHON
495 PyObject *ptype = nullptr;
496 PyObject *pvalue = nullptr;
497 PyObject *ptraceback = nullptr;
498 PyErr_Fetch(&ptype, &pvalue, &ptraceback);
499 if (ptype == nullptr)
500 return std::string("Null exception type");
501 PyErr_NormalizeException(&ptype, &pvalue, &ptraceback);
502 if (ptraceback != nullptr)
503 PyException_SetTraceback(pvalue, ptraceback);
504 boost::python::handle<> htype(ptype);
505 boost::python::handle<> hvalue(boost::python::allow_null(pvalue));
506 boost::python::handle<> htraceback(boost::python::allow_null(ptraceback));
507 boost::python::object traceback = boost::python::import("traceback");
508 boost::python::object format_exc = traceback.attr("format_exception");
509 boost::python::object formatted = format_exc(htype, hvalue, htraceback);
510 error = boost::python::extract<std::string>(boost::python::str("\n").join(formatted));
512 PyObject* new_stderr = newPyStdOut(error);
513 PyObject* old_stderr = PySys_GetObject((char*)"stderr");
514 Py_INCREF(old_stderr);
515 PySys_SetObject((char*)"stderr", new_stderr);
517 PySys_SetObject((char*)"stderr", old_stderr);
518 Py_DECREF(new_stderr);
525 Engines::vectorOfDouble* Abstract_Engines_Container_i::loadOfCPUCores()
528 PyObject *module = PyImport_ImportModuleNoBlock((char*)"salome_psutil");
529 PyObject *result = PyObject_CallMethod(module,
530 (char*)"loadOfCPUCores", "s",
531 _load_script.c_str());
532 if (PyErr_Occurred())
534 std::string error = parseException();
536 SALOME::ExceptionStruct es;
537 es.type = SALOME::INTERNAL_ERROR;
538 es.text = CORBA::string_dup(error.c_str());
539 throw SALOME::SALOME_Exception(es);
542 int n = this->getNumberOfCPUCores();
543 if (!PyList_Check(result) || PyList_Size(result) != n) {
544 // bad number of cores
546 SALOME::ExceptionStruct es;
547 es.type = SALOME::INTERNAL_ERROR;
548 es.text = "wrong number of cores";
549 throw SALOME::SALOME_Exception(es);
552 Engines::vectorOfDouble_var loads = new Engines::vectorOfDouble;
554 for (Py_ssize_t i = 0; i < PyList_Size(result); ++i) {
555 PyObject* item = PyList_GetItem(result, i);
556 double foo = PyFloat_AsDouble(item);
557 if (foo < 0.0 || foo > 1.0)
559 // value not in [0, 1] range
561 SALOME::ExceptionStruct es;
562 es.type = SALOME::INTERNAL_ERROR;
563 es.text = "load not in [0, 1] range";
564 throw SALOME::SALOME_Exception(es);
571 return loads._retn();
574 //=============================================================================
575 //! Set custom script to calculate a load of each CPU core
577 * CORBA method: Set custom script to calculate CPU load
578 * \param script Python script to execute
580 //=============================================================================
582 void Abstract_Engines_Container_i::setPyScriptForCPULoad(const char *script)
584 _load_script = script;
587 //=============================================================================
588 //! Nullify custom script to calculate each CPU core's load
590 * CORBA method: reset script for load calculation to default implementation
592 //=============================================================================
594 void Abstract_Engines_Container_i::resetScriptForCPULoad()
599 //=============================================================================
600 //! Get total physical memory of calculation node, in megabytes
602 * CORBA method: get total physical memory of calculation node
604 //=============================================================================
606 CORBA::Long Abstract_Engines_Container_i::getTotalPhysicalMemory()
609 PyObject *module = PyImport_ImportModuleNoBlock((char*)"salome_psutil");
610 PyObject *result = PyObject_CallMethod(module,
611 (char*)"getTotalPhysicalMemory", NULL);
612 int n = PyLong_AsLong(result);
615 return (CORBA::Long)n;
618 //=============================================================================
619 //! Get used physical memory of calculation node, in megabytes
621 * CORBA method: get used physical memory of calculation node
623 //=============================================================================
625 CORBA::Long Abstract_Engines_Container_i::getTotalPhysicalMemoryInUse()
628 PyObject *module = PyImport_ImportModuleNoBlock((char*)"salome_psutil");
629 PyObject *result = PyObject_CallMethod(module,
630 (char*)"getTotalPhysicalMemoryInUse", NULL);
631 int n = PyLong_AsLong(result);
634 return (CORBA::Long)n;
637 //=============================================================================
638 //! Obtain physical memory, used by the current process, in megabytes.
640 * CORBA method: get physical memory, used by the current process
642 //=============================================================================
644 CORBA::Long Abstract_Engines_Container_i::getTotalPhysicalMemoryInUseByMe()
647 PyObject *module = PyImport_ImportModuleNoBlock((char*)"salome_psutil");
648 PyObject *result = PyObject_CallMethod(module,
649 (char*)"getTotalPhysicalMemoryInUseByMe", NULL);
650 int n = PyLong_AsLong(result);
653 return (CORBA::Long)n;
656 //=============================================================================
657 //! Shutdown the container
659 * CORBA method, oneway: Server shutdown.
660 * - Container name removed from naming service,
661 * - servant deactivation,
662 * - orb shutdown if no other servants in the process
664 //=============================================================================
665 void Abstract_Engines_Container_i::Shutdown()
667 MESSAGE("Engines_Container_i::Shutdown()");
669 // Clear registered temporary files
670 clearTemporaryFiles();
672 /* For each component contained in this container
673 * tell it to self-destroy
675 std::map<std::string, Engines::EngineComponent_var>::iterator itm;
676 for (itm = _listInstances_map.begin(); itm != _listInstances_map.end(); itm++)
680 itm->second->destroy();
682 catch(const CORBA::Exception&)
684 // ignore this entry and continue
688 // ignore this entry and continue
691 _listInstances_map.clear();
693 // NS unregistering may throw in SSL mode if master process hosting SALOME_Embedded_NamingService servant has vanished
694 // In this case it's skip it and still continue.
697 _NS->Destroy_FullDirectory(_containerName.c_str());
698 _NS->Destroy_Name(_containerName.c_str());
704 this->cleanAllPyScripts();
706 if(_isServantAloneInProcess)
708 MESSAGE("Effective Shutdown of container Begins...");
709 if(!CORBA::is_nil(_orb))
714 //=============================================================================
715 //! load a component implementation
718 * \param componentName component name
719 * \param reason explains error when load fails
720 * \return true if dlopen successful or already done, false otherwise
722 //=============================================================================
724 Abstract_Engines_Container_i::load_component_Library(const char* componentName, CORBA::String_out reason)
727 //=================================================================
728 // --- C++ implementation section
729 //=================================================================
731 if(load_component_CppImplementation(componentName,retso))
733 reason=CORBA::string_dup("");
736 else if(retso != "ImplementationNotFound")
738 reason=CORBA::string_dup(retso.c_str());
743 retso+=componentName;
744 retso+=": Can't find C++ implementation ";
745 retso+=std::string(LIB) + componentName + ENGINESO;
747 //=================================================================
748 // --- Python implementation section
749 //=================================================================
751 if(load_component_PythonImplementation(componentName,retpy))
753 reason=CORBA::string_dup("");
756 else if(retpy != "ImplementationNotFound")
758 reason=CORBA::string_dup(retpy.c_str());
763 retpy+=componentName;
764 retpy+=": Can't find python implementation ";
765 retpy+=componentName;
768 //=================================================================
769 // -- Executable implementation section
770 //=================================================================
772 if(load_component_ExecutableImplementation(componentName,retex))
774 reason=CORBA::string_dup("");
777 else if(retex != "ImplementationNotFound")
779 reason=CORBA::string_dup(retex.c_str());
784 retex+=componentName;
785 retex+=": Can't find executable implementation ";
786 retex+=componentName;
789 std::string ret="Component implementation not found: ";
790 ret += componentName ;
796 std::cerr << ret << std::endl;
797 reason=CORBA::string_dup(ret.c_str());
802 //=============================================================================
803 //! try to load a C++ component implementation
806 * \param componentName the name of the component (COMPONENT, for example)
807 * \param reason explains error when load fails
808 * \return true if loading is successful or already done, false otherwise
810 //=============================================================================
812 Abstract_Engines_Container_i::load_component_CppImplementation(const char* componentName, std::string& reason)
814 std::string aCompName(componentName);
815 std::string impl_name = std::string(LIB) + aCompName + ENGINESO;
818 _numInstanceMutex.lock(); // lock to be alone
819 // (see decInstanceCnt, finalize_removal))
820 if (_toRemove_map.count(impl_name) != 0) _toRemove_map.erase(impl_name);
821 if (_library_map.count(impl_name) != 0)
823 MESSAGE("Library " << impl_name << " already loaded");
824 _numInstanceMutex.unlock();
828 _numInstanceMutex.unlock();
832 handle = dlopen( impl_name.c_str() , RTLD_NOW | RTLD_GLOBAL ) ;
835 //not loadable. Try to find the lib file in LD_LIBRARY_PATH
838 char* p=getenv("DYLD_LIBRARY_PATH");
840 char* p=getenv("LD_LIBRARY_PATH");
843 path=path+SEP+"/usr/lib"+SEP+"/lib";
846 if(findpathof(path, pth, impl_name))
848 //found but not loadable
851 reason+=": C++ implementation found ";
853 reason+=" but it is not loadable. Error:\n";
855 std::cerr << reason << std::endl;
861 //continue with other implementation
862 reason="ImplementationNotFound";
869 std::wstring libToLoad = Kernel_Utils::utf8_decode_s( impl_name );
871 std::string libToLoad = impl_name;
873 handle = LoadLibrary(libToLoad.c_str() );
876 reason="ImplementationNotFound";
882 _numInstanceMutex.lock();
883 _library_map[impl_name] = handle;
884 _numInstanceMutex.unlock();
892 //=============================================================================
893 //! try to load a Python component implementation
896 * \param componentName name of the component
897 * \param reason explains error when load fails
898 * \return true if loading is successful or already done, false otherwise
900 //=============================================================================
902 Abstract_Engines_Container_i::load_component_PythonImplementation(const char* componentName, std::string& reason)
904 std::string aCompName(componentName);
906 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
907 if (_library_map.count(aCompName) != 0)
909 _numInstanceMutex.unlock() ;
911 return true; // Python Component, already imported
913 _numInstanceMutex.unlock() ;
917 PyObject *result = PyObject_CallMethod(_pyCont,
918 (char*)"import_component",
919 (char*)"s",componentName);
921 reason=PyUnicode_AsUTF8(result);
928 //Python component has been loaded (import componentName)
929 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
930 _library_map[aCompName] = (void *)_pyCont; // any non O value OK
931 _numInstanceMutex.unlock() ;
932 MESSAGE("import Python: "<< aCompName <<" OK");
935 else if(reason=="ImplementationNotFound")
937 //Python implementation has not been found. Continue with other implementation
938 reason="ImplementationNotFound";
942 //Python implementation has been found but loading has failed
943 std::cerr << reason << std::endl;
948 //=============================================================================
949 //! try to load a Executable component implementation
952 * \param componentName name of the component
953 * \param reason explains error when load fails
954 * \return true if loading is successful or already done, false otherwise
956 //=============================================================================
958 Abstract_Engines_Container_i::load_component_ExecutableImplementation(const char* componentName, std::string& reason)
960 std::string aCompName(componentName);
961 std::string executable=aCompName+".exe";
966 char* p=getenv("PATH");
969 if (findpathof(path, pth, executable))
971 if(checkifexecutable(pth))
973 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
974 _library_map[executable] = (void *)1; // any non O value OK
975 _numInstanceMutex.unlock() ;
976 MESSAGE("import executable: "<< pth <<" OK");
982 reason+=": implementation found ";
984 reason+=" but it is not executable";
985 std::cerr << reason << std::endl;
989 reason="ImplementationNotFound";
994 //=============================================================================
995 //! Create a new component instance
997 * CORBA method: Creates a new servant instance of a component.
998 * The servant registers itself to naming service and Registry.tdlib
999 * \param genericRegisterName Name of the component instance to register
1000 * in Registry & Name Service (without _inst_n suffix)
1001 * \return a loaded component
1003 //=============================================================================
1004 Engines::EngineComponent_ptr
1005 Abstract_Engines_Container_i::create_component_instance(const char*genericRegisterName)
1007 Engines::FieldsDict_var env = new Engines::FieldsDict;
1009 Engines::EngineComponent_ptr compo =
1010 create_component_instance_env(genericRegisterName, env, reason);
1011 CORBA::string_free(reason);
1015 void EffectiveOverrideEnvironment( const Engines::FieldsDict& env )
1017 MESSAGE("Positionning environment on container ");
1018 for (CORBA::ULong i=0; i < env.length(); i++)
1020 if (env[i].value.type()->kind() == CORBA::tk_string)
1022 const char *value = nullptr;
1023 env[i].value >>= value;
1024 MESSAGE( env[i].key << " = " << value);
1026 if( setenv(env[i].key,value,1) != 0 )
1029 std::string sErr( strerror( errsv) );
1037 std::vector< std::pair<std::string,std::string> > GetOSEnvironment()
1039 std::vector< std::pair<std::string,std::string> > ret;
1041 char **envPt( environ );
1042 for(;*envPt != nullptr; ++envPt)
1044 std::string s( *envPt );
1045 auto pos = s.find_first_of('=');
1046 std::string k( s.substr(0,pos) ),v( s.substr(pos+1) );
1047 ret.emplace_back( std::pair<std::string,std::string>(k,v) );
1053 void Abstract_Engines_Container_i::override_environment( const Engines::FieldsDict& env )
1055 EffectiveOverrideEnvironment(env);
1058 void Abstract_Engines_Container_i::override_environment_python( const Engines::FieldsDict& env )
1060 constexpr char NODE_NAME[] = "ScriptNodeForEnv";
1061 constexpr char SCRIPT[] = R"foo(
1066 Engines::PyScriptNode_var scriptNode = this->createPyScriptNode(NODE_NAME,SCRIPT);
1067 auto sz = env.length();
1068 Engines::listofstring keys, vals;
1069 keys.length( sz ); vals.length( sz );
1070 for( auto i = 0 ; i < sz ; ++i )
1072 keys[i] = CORBA::string_dup( env[i].key );
1073 const char *value = nullptr;
1074 env[i].value >>= value;
1075 vals[i] = CORBA::string_dup( value );
1077 scriptNode->executeSimple(keys,vals);
1078 this->removePyScriptNode(NODE_NAME);
1081 Engines::FieldsDict *Abstract_Engines_Container_i::get_os_environment()
1083 std::unique_ptr<Engines::FieldsDict> ret( new Engines::FieldsDict );
1084 std::vector< std::pair<std::string,std::string> > retCpp( GetOSEnvironment() );
1085 auto sz = retCpp.size();
1087 for(auto i = 0 ; i < sz ; ++i)
1089 (*ret)[i].key = CORBA::string_dup( retCpp[i].first.c_str() );
1090 (*ret)[i].value <<= CORBA::string_dup( retCpp[i].second.c_str() );
1092 return ret.release();
1095 void Abstract_Engines_Container_i::execute_python_code(const char *code)
1098 if( PyRun_SimpleString( code ) != 0 )
1100 std::string error = parseException();
1101 THROW_SALOME_CORBA_EXCEPTION(error.c_str(),SALOME::INTERNAL_ERROR);
1105 //=============================================================================
1106 //! Create a new component instance with environment variables specified
1108 * CORBA method: Creates a new servant instance of a component.
1109 * The servant registers itself to naming service and Registry.
1110 * \param genericRegisterName Name of the component instance to register
1111 * in Registry & Name Service (without _inst_n suffix)
1112 * \param env dict of env variables
1113 * \param reason explains error when create_component_instance_env fails
1114 * \return a loaded component
1116 //=============================================================================
1117 Engines::EngineComponent_ptr
1118 Abstract_Engines_Container_i::create_component_instance_env(const char*genericRegisterName,
1119 const Engines::FieldsDict& env,
1120 CORBA::String_out reason)
1123 if (_library_map.count(genericRegisterName) != 0)
1125 // It's a Python component
1126 Engines::EngineComponent_ptr compo = createPythonInstance(genericRegisterName, error);
1127 reason=CORBA::string_dup(error.c_str());
1131 std::string impl_name = std::string(LIB) + genericRegisterName + ENGINESO;
1132 if (_library_map.count(impl_name) != 0)
1134 // It's a C++ component
1135 void* handle = _library_map[impl_name];
1136 Engines::EngineComponent_ptr compo = createInstance(genericRegisterName, handle, error);
1137 reason=CORBA::string_dup(error.c_str());
1141 impl_name = std::string(genericRegisterName) + ".exe";
1142 if (_library_map.count(impl_name) != 0)
1144 //It's an executable component
1145 Engines::EngineComponent_ptr compo = createExecutableInstance(genericRegisterName, env, error);
1146 reason=CORBA::string_dup(error.c_str());
1150 error="load_component_Library has probably not been called for component: ";
1151 error += genericRegisterName;
1153 reason=CORBA::string_dup(error.c_str());
1154 return Engines::EngineComponent::_nil() ;
1157 //=============================================================================
1158 //! Create a new component instance (Executable implementation)
1160 * \param CompName Name of the component instance
1161 * \param env dict of env variables
1162 * \param reason explains error when creation fails
1163 * \return a loaded component
1165 * This component is implemented in an executable with name genericRegisterName.exe
1166 * It must register itself in Naming Service. The container waits some time (10 s max)
1167 * it's registration.
1169 //=============================================================================
1170 Engines::EngineComponent_ptr
1171 Abstract_Engines_Container_i::createExecutableInstance(std::string CompName,
1172 const Engines::FieldsDict& env,
1173 std::string& reason)
1175 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1177 _numInstanceMutex.lock() ; // lock on the instance number
1179 int numInstance = _numInstance ;
1180 _numInstanceMutex.unlock() ;
1183 sprintf( aNumI , "%d" , numInstance ) ;
1184 std::string instanceName = CompName + "_inst_" + aNumI ;
1185 std::string component_registerName = _containerName + "/" + instanceName;
1187 //check if an entry exist in naming service
1188 CORBA::Object_var nsobj = _NS->Resolve(component_registerName.c_str());
1189 if ( !CORBA::is_nil(nsobj) )
1191 // unregister the registered component
1192 _NS->Destroy_Name(component_registerName.c_str());
1193 //kill or shutdown it ???
1196 // first arg container ior string
1197 // second arg container name
1198 // third arg instance name
1200 Engines::Container_var pCont= _this();
1201 CORBA::String_var sior = _orb->object_to_string(pCont);
1203 std::string command;
1204 command="mkdir -p ";
1205 command+=instanceName;
1207 command+=instanceName;
1212 command+= sior; // container ior string
1214 command+=_containerName; //container name
1216 command+=instanceName; //instance name
1218 MESSAGE("SALOME_Container::create_component_instance command=" << command);
1221 // use fork/execl instead of system to get finer control on env variables
1224 if(pid == 0) // child
1226 EffectiveOverrideEnvironment(env);
1228 execl("/bin/sh", "sh", "-c", command.c_str() , (char *)0);
1231 else if(pid < 0) // failed to fork
1240 tpid = wait(&status);
1241 } while (tpid != pid);
1244 // launch component with a system call
1245 int status=system(command.c_str());
1250 reason="SALOME_Container::create_component_instance system failed (system command status -1)";
1252 return Engines::EngineComponent::_nil();
1255 else if (WEXITSTATUS(status) == 217)
1257 reason="SALOME_Container::create_component_instance system failed (system command status 217)";
1259 return Engines::EngineComponent::_nil();
1265 if (getenv("TIMEOUT_TO_WAIT_EXE_COMPONENT") != 0)
1267 std::string new_count_str = getenv("TIMEOUT_TO_WAIT_EXE_COMPONENT");
1269 std::istringstream ss(new_count_str);
1270 if (!(ss >> new_count))
1272 INFOS("[Container] TIMEOUT_TO_WAIT_EXE_COMPONENT should be an int");
1277 INFOS("[Container] waiting " << count << " second steps exe component ");
1278 CORBA::Object_var obj = CORBA::Object::_nil() ;
1279 while ( CORBA::is_nil(obj) && count )
1287 MESSAGE( count << ". Waiting for component " << CompName);
1288 obj = _NS->Resolve(component_registerName.c_str());
1291 if(CORBA::is_nil(obj))
1293 reason="SALOME_Container::create_component_instance failed";
1295 return Engines::EngineComponent::_nil();
1299 MESSAGE("SALOME_Container::create_component_instance successful");
1300 iobject = Engines::EngineComponent::_narrow(obj);
1301 _listInstances_map[instanceName] = iobject;
1302 return iobject._retn();
1308 //=============================================================================
1309 //! Create a new component instance (Python implementation)
1311 * \param CompName Name of the component instance
1312 * \param reason explains error when creation fails
1313 * \return a loaded component
1315 //=============================================================================
1316 Engines::EngineComponent_ptr
1317 Abstract_Engines_Container_i::createPythonInstance(std::string CompName,
1318 std::string& reason)
1320 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1322 _numInstanceMutex.lock() ; // lock on the instance number
1324 int numInstance = _numInstance ;
1325 _numInstanceMutex.unlock() ;
1328 sprintf( aNumI , "%d" , numInstance ) ;
1329 std::string instanceName = CompName + "_inst_" + aNumI ;
1330 std::string component_registerName = _containerName + "/" + instanceName;
1334 PyObject *result = PyObject_CallMethod(_pyCont,
1335 (char*)"create_component_instance",
1338 instanceName.c_str());
1341 PyArg_ParseTuple(result,"ss", &ior, &error);
1349 CORBA::Object_var obj = _orb->string_to_object(iors.c_str());
1350 iobject = Engines::EngineComponent::_narrow( obj ) ;
1351 _listInstances_map[instanceName] = iobject;
1353 return iobject._retn();
1357 Abstract_Engines_Container_i::create_python_service_instance(const char * CompName,
1358 CORBA::String_out reason)
1360 CORBA::Object_var object = CORBA::Object::_nil();
1362 _numInstanceMutex.lock() ; // lock on the instance number
1364 int numInstance = _numInstance ;
1365 _numInstanceMutex.unlock() ;
1368 sprintf( aNumI , "%d" , numInstance ) ;
1369 std::string instanceName = std::string(CompName) + "_inst_" + aNumI ;
1370 std::string component_registerName = _containerName + "/" + instanceName;
1372 char * _ior = nullptr;
1375 PyObject *result = PyObject_CallMethod(_pyCont,
1376 (char*)"create_component_instance",
1379 instanceName.c_str());
1382 PyArg_ParseTuple(result,"ss", &ior, &error);
1383 reason = CORBA::string_dup(error);
1384 _ior = CORBA::string_dup(ior);
1391 //=============================================================================
1392 //! Create a new component instance (C++ implementation)
1394 * C++ method: create a servant instance of a component.
1395 * \param genericRegisterName Name of the component instance to register
1396 * in Registry & Name Service,
1397 * (without _inst_n suffix, like "COMPONENT")
1398 * \param handle loaded library handle
1399 * \param reason explains error when creation fails
1400 * \return a loaded component
1402 * example with names:
1403 * - aGenRegisterName = COMPONENT (= first argument)
1404 * - _containerName = /Containers/cli76ce/FactoryServer
1405 * - factoryName = COMPONENTEngine_factory
1406 * - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
1407 * - instanceName = COMPONENT_inst_1
1408 * - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1410 //=============================================================================
1411 Engines::EngineComponent_ptr
1412 Abstract_Engines_Container_i::createInstance(std::string genericRegisterName,
1414 std::string& reason)
1416 // --- find the factory
1418 std::string aGenRegisterName = genericRegisterName;
1419 std::string factory_name = aGenRegisterName + std::string("Engine_factory");
1420 SCRUTE(factory_name) ;
1422 typedef PortableServer::ObjectId* (*FACTORY_FUNCTION) (CORBA::ORB_ptr,
1423 PortableServer::POA_ptr,
1424 PortableServer::ObjectId *,
1429 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)dlsym( handle, factory_name.c_str() );
1431 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)GetProcAddress( (HINSTANCE)handle, factory_name.c_str() );
1434 if ( !Component_factory )
1436 MESSAGE( "Can't resolve symbol: " + factory_name );
1441 return Engines::EngineComponent::_nil() ;
1444 // --- create instance
1446 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1450 _numInstanceMutex.lock() ; // lock on the instance number
1452 int numInstance = _numInstance ;
1453 _numInstanceMutex.unlock() ;
1456 sprintf( aNumI , "%d" , numInstance ) ;
1457 std::string instanceName = aGenRegisterName + "_inst_" + aNumI ;
1458 std::string component_registerName =
1459 _containerName + "/" + instanceName;
1461 // --- Instantiate required CORBA object
1463 PortableServer::ObjectId *id ; //not owner, do not delete (nore use var)
1464 id = (Component_factory) ( _orb, _poa, _id, instanceName.c_str(),
1465 aGenRegisterName.c_str() ) ;
1468 reason="Can't get ObjectId from factory";
1470 return iobject._retn();
1473 // --- get reference from id
1475 CORBA::Object_var obj = _poa->id_to_reference(*id);
1476 iobject = Engines::EngineComponent::_narrow( obj ) ;
1478 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1479 _listInstances_map[instanceName] = iobject;
1480 _cntInstances_map[aGenRegisterName] += 1;
1481 _numInstanceMutex.unlock() ;
1482 SCRUTE(aGenRegisterName);
1483 SCRUTE(_cntInstances_map[aGenRegisterName]);
1485 // --- register the engine under the name
1486 // containerName(.dir)/instanceName(.object)
1488 _NS->Register( iobject , component_registerName.c_str() ) ;
1489 MESSAGE( component_registerName.c_str() << " bound" ) ;
1493 reason="Container_i::createInstance exception caught";
1496 return iobject._retn();
1499 //=============================================================================
1500 //! Find an existing (in the container) component instance
1502 * CORBA method: Finds a servant instance of a component
1503 * \param registeredName Name of the component in Registry or Name Service,
1504 * without instance suffix number
1505 * \return the first found instance
1507 //=============================================================================
1508 Engines::EngineComponent_ptr
1509 Abstract_Engines_Container_i::find_component_instance( const char* registeredName)
1511 Engines::EngineComponent_var anEngine = Engines::EngineComponent::_nil();
1512 std::map<std::string,Engines::EngineComponent_var>::iterator itm =_listInstances_map.begin();
1513 while (itm != _listInstances_map.end())
1515 std::string instance = (*itm).first;
1517 if (instance.find(registeredName) == 0)
1519 anEngine = (*itm).second;
1520 return anEngine._retn();
1524 return anEngine._retn();
1527 //=============================================================================
1528 //! Remove the component instance from container
1530 * CORBA method: Stops the component servant, and deletes all related objects
1531 * \param component_i Component to be removed
1533 //=============================================================================
1535 void Abstract_Engines_Container_i::remove_impl(Engines::EngineComponent_ptr component_i)
1537 ASSERT(! CORBA::is_nil(component_i));
1538 std::string instanceName = component_i->instanceName() ;
1539 MESSAGE("unload component " << instanceName);
1540 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1541 _listInstances_map.erase(instanceName);
1542 _numInstanceMutex.unlock() ;
1543 component_i->destroy() ;
1544 _NS->Destroy_Name(instanceName.c_str());
1547 //=============================================================================
1548 //! Unload component libraries from the container
1550 * CORBA method: Discharges unused libraries from the container.
1552 //=============================================================================
1553 void Abstract_Engines_Container_i::finalize_removal()
1555 MESSAGE("finalize unload : dlclose");
1556 _numInstanceMutex.lock(); // lock to be alone
1557 // (see decInstanceCnt, load_component_Library)
1558 std::map<std::string, void *>::iterator ith;
1559 for (ith = _toRemove_map.begin(); ith != _toRemove_map.end(); ith++)
1561 void *handle = (*ith).second;
1562 std::string impl_name= (*ith).first;
1567 // dlclose(handle); // SALOME unstable after ...
1568 // _library_map.erase(impl_name);
1571 _toRemove_map.clear();
1572 _numInstanceMutex.unlock();
1575 //=============================================================================
1576 //! Decrement component instance reference count
1580 //=============================================================================
1581 void Abstract_Engines_Container_i::decInstanceCnt(std::string genericRegisterName)
1583 if(_cntInstances_map.count(genericRegisterName)==0)
1585 std::string aGenRegisterName =genericRegisterName;
1586 MESSAGE("Engines_Container_i::decInstanceCnt " << aGenRegisterName);
1587 ASSERT(_cntInstances_map[aGenRegisterName] > 0);
1588 _numInstanceMutex.lock(); // lock to be alone
1589 // (see finalize_removal, load_component_Library)
1590 _cntInstances_map[aGenRegisterName] -= 1;
1591 SCRUTE(_cntInstances_map[aGenRegisterName]);
1592 if (_cntInstances_map[aGenRegisterName] == 0)
1594 std::string impl_name =
1595 Engines_Component_i::GetDynLibraryName(aGenRegisterName.c_str());
1597 void* handle = _library_map[impl_name];
1599 _toRemove_map[impl_name] = handle;
1601 _numInstanceMutex.unlock();
1604 //=============================================================================
1605 //! Find or create a new component instance
1607 * CORBA method: find or create an instance of the component (servant),
1608 * load a new component class (dynamic library) if required,
1610 * ---- FOR COMPATIBILITY WITH 2.2 ----
1612 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
1614 * The servant registers itself to naming service and Registry.
1615 * \param genericRegisterName Name of the component to register
1616 * in Registry & Name Service
1617 * \param componentName Name of the constructed library of the component
1618 * \return a loaded component
1620 //=============================================================================
1622 Engines::EngineComponent_ptr
1623 Abstract_Engines_Container_i::load_impl( const char* genericRegisterName,
1624 const char* /*componentName*/ )
1627 std::string impl_name = std::string(LIB) + genericRegisterName + ENGINESO;
1628 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1629 if (load_component_Library(genericRegisterName,reason))
1630 iobject = find_or_create_instance(genericRegisterName, impl_name);
1631 CORBA::string_free(reason);
1632 return iobject._retn();
1635 Engines::EmbeddedNamingService_ptr Abstract_Engines_Container_i::get_embedded_NS_if_ssl()
1637 SALOME_Embedded_NamingService_Client *nsc(dynamic_cast<SALOME_Embedded_NamingService_Client *>(this->_NS));
1640 Engines::EmbeddedNamingService_var obj = nsc->GetObject();
1641 return Engines::EmbeddedNamingService::_duplicate(obj);
1645 SALOME_Fake_NamingService *fns(dynamic_cast<SALOME_Fake_NamingService *>(this->_NS));
1648 Engines::EmbeddedNamingService_var ret = GetEmbeddedNamingService();
1652 return Engines::EmbeddedNamingService::_nil();
1656 //=============================================================================
1657 //! Finds an already existing component instance or create a new instance
1659 * C++ method: Finds an already existing servant instance of a component, or
1660 * create an instance.
1661 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
1662 * \param genericRegisterName Name of the component instance to register
1663 * in Registry & Name Service,
1664 * (without _inst_n suffix, like "COMPONENT")
1665 * \param componentLibraryName like "libCOMPONENTEngine.so"
1666 * \return a loaded component
1668 * example with names:
1669 * - aGenRegisterName = COMPONENT (= first argument)
1670 * - impl_name = libCOMPONENTEngine.so (= second argument)
1671 * - _containerName = /Containers/cli76ce/FactoryServer
1672 * - factoryName = COMPONENTEngine_factory
1673 * - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
1674 * - instanceName = COMPONENT_inst_1
1675 * - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1677 //=============================================================================
1679 Engines::EngineComponent_ptr
1680 Abstract_Engines_Container_i::find_or_create_instance(std::string genericRegisterName,
1681 std::string componentLibraryName)
1683 std::string aGenRegisterName = genericRegisterName;
1684 std::string impl_name = componentLibraryName;
1685 if (_library_map.count(impl_name) == 0)
1687 INFOS("shared library " << impl_name <<" must be loaded before creating instance");
1688 return Engines::EngineComponent::_nil() ;
1692 // --- find a registered instance in naming service, or create
1694 void* handle = _library_map[impl_name];
1695 std::string component_registerBase =
1696 _containerName + "/" + aGenRegisterName;
1697 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1701 CORBA::Object_var obj =
1702 _NS->ResolveFirst( component_registerBase.c_str());
1703 if ( CORBA::is_nil( obj ) )
1705 iobject = createInstance(genericRegisterName,
1711 iobject = Engines::EngineComponent::_narrow( obj ) ;
1716 INFOS( "Container_i::load_impl caught" ) ;
1718 return iobject._retn();
1722 //=============================================================================
1723 //! Indicate if container is a python one
1725 * Retrieves only with container naming convention if it is a python container
1727 //=============================================================================
1728 bool Abstract_Engines_Container_i::isPythonContainer(const char* ContainerName)
1731 size_t len=strlen(ContainerName);
1733 if(strcmp(ContainerName+len-2,"Py")==0)
1738 //=============================================================================
1739 //! Kill the container
1741 * CORBA method: Kill the container process with exit(0).
1742 * To remove : never returns !
1744 //=============================================================================
1745 bool Abstract_Engines_Container_i::Kill_impl()
1747 MESSAGE("Engines_Container_i::Kill() pid "<< getpid() << " containerName "
1748 << _containerName.c_str() << " machineName "
1749 << Kernel_Utils::GetHostname().c_str());
1750 INFOS("===============================================================");
1751 INFOS("= REMOVE calls to Kill_impl in C++ container =");
1752 INFOS("===============================================================");
1758 //=============================================================================
1762 //=============================================================================
1763 void ActSigIntHandler()
1766 struct sigaction SigIntAct ;
1767 SigIntAct.sa_sigaction = &SigIntHandler ;
1768 sigemptyset(&SigIntAct.sa_mask);
1769 SigIntAct.sa_flags = SA_SIGINFO ;
1772 // DEBUG 03.02.2005 : the first parameter of sigaction is not a mask of signals
1773 // (SIGINT | SIGUSR1) :
1774 // it must be only one signal ===> one call for SIGINT
1775 // and an other one for SIGUSR1
1778 if ( sigaction( SIGINT , &SigIntAct, NULL ) )
1780 perror("SALOME_Container main ") ;
1783 if ( sigaction( SIGUSR1 , &SigIntAct, NULL ) )
1785 perror("SALOME_Container main ") ;
1788 if ( sigaction( SIGUSR2 , &SigIntAct, NULL ) )
1790 perror("SALOME_Container main ") ;
1794 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1795 // use of streams (and so on) should never be used because :
1796 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1797 // A stream operation may be interrupted by a signal and if the Handler use stream we
1798 // may have a "Dead-Lock" ===HangUp
1799 //==INFOS is commented
1800 // INFOS(pthread_self() << "SigIntHandler activated") ;
1803 signal( SIGINT, SigIntHandler );
1804 // legacy code required to supervisor. Commented in order to avoid problems on Windows
1805 // signal( SIGUSR1, SigIntHandler );
1811 void CallCancelThread() ;
1814 void SigIntHandler(int /*what*/ ,
1815 siginfo_t * siginfo ,
1818 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1819 // use of streams (and so on) should never be used because :
1820 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1821 // A stream operation may be interrupted by a signal and if the Handler use stream we
1822 // may have a "Dead-Lock" ===HangUp
1823 //==MESSAGE is commented
1824 // MESSAGE(pthread_self() << "SigIntHandler what " << what << std::endl
1825 // << " si_signo " << siginfo->si_signo << std::endl
1826 // << " si_code " << siginfo->si_code << std::endl
1827 // << " si_pid " << siginfo->si_pid) ;
1832 // MESSAGE("SigIntHandler END sleeping.") ;
1837 ActSigIntHandler() ;
1838 if ( siginfo->si_signo == SIGUSR1 )
1842 else if ( siginfo->si_signo == SIGUSR2 )
1844 CallCancelThread() ;
1849 // MESSAGE("SigIntHandler BEGIN sleeping.") ;
1856 // MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1862 void SigIntHandler( int what )
1865 MESSAGE( pthread_self() << "SigIntHandler what " << what << std::endl );
1867 MESSAGE( "SigIntHandler what " << what << std::endl );
1872 MESSAGE("SigIntHandler END sleeping.") ;
1877 ActSigIntHandler() ;
1878 if ( what == SIGUSR1 )
1885 MESSAGE("SigIntHandler BEGIN sleeping.") ;
1892 MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1899 //=============================================================================
1900 //! Get or create a file reference object associated to a local file (to transfer it)
1902 * CORBA method: get or create a fileRef object associated to a local file
1903 * (a file on the computer on which runs the container server), which stores
1904 * a list of (machine, localFileName) corresponding to copies already done.
1906 * \param origFileName absolute path for a local file to copy on other
1908 * \return a fileRef object associated to the file.
1910 //=============================================================================
1911 Engines::fileRef_ptr
1912 Abstract_Engines_Container_i::createFileRef(const char* origFileName)
1914 std::string origName(origFileName);
1915 Engines::fileRef_var theFileRef = Engines::fileRef::_nil();
1917 if (origName[0] != '/')
1919 INFOS("path of file to copy must be an absolute path beginning with '/'");
1920 return Engines::fileRef::_nil();
1923 if (CORBA::is_nil(_fileRef_map[origName]))
1925 CORBA::Object_var obj=_poa->id_to_reference(*_id);
1926 Engines::Container_var pCont = Engines::Container::_narrow(obj);
1927 fileRef_i* aFileRef = new fileRef_i(pCont, origFileName);
1928 theFileRef = Engines::fileRef::_narrow(aFileRef->_this());
1929 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1930 _fileRef_map[origName] = theFileRef;
1931 _numInstanceMutex.unlock() ;
1934 theFileRef = Engines::fileRef::_duplicate(_fileRef_map[origName]);
1935 ASSERT(! CORBA::is_nil(theFileRef));
1936 return theFileRef._retn();
1939 //=============================================================================
1940 //! Get a fileTransfer reference
1943 * \return a reference to the fileTransfer object
1945 //=============================================================================
1946 Engines::fileTransfer_ptr
1947 Abstract_Engines_Container_i::getFileTransfer()
1949 Engines::fileTransfer_var aFileTransfer
1950 = Engines::fileTransfer::_duplicate(_fileTransfer);
1951 return aFileTransfer._retn();
1954 //=============================================================================
1955 //! Create a Salome file
1956 //=============================================================================
1957 Engines::Salome_file_ptr
1958 Abstract_Engines_Container_i::createSalome_file(const char* origFileName)
1960 std::string origName(origFileName);
1961 if (CORBA::is_nil(_Salome_file_map[origName]))
1963 Salome_file_i* aSalome_file = new Salome_file_i();
1964 aSalome_file->setContainer(Engines::Container::_duplicate(this->_this()));
1967 aSalome_file->setLocalFile(origFileName);
1968 aSalome_file->recvFiles();
1970 catch (const SALOME::SALOME_Exception& /*e*/) //!< TODO: unused variable
1972 return Engines::Salome_file::_nil();
1975 Engines::Salome_file_var theSalome_file = Engines::Salome_file::_nil();
1976 theSalome_file = Engines::Salome_file::_narrow(aSalome_file->_this());
1977 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1978 _Salome_file_map[origName] = theSalome_file;
1979 _numInstanceMutex.unlock() ;
1982 Engines::Salome_file_ptr theSalome_file =
1983 Engines::Salome_file::_duplicate(_Salome_file_map[origName]);
1984 ASSERT(!CORBA::is_nil(theSalome_file));
1985 return theSalome_file;
1988 //=============================================================================
1989 /*! \brief copy a file from a remote host (container) to the local host
1990 * \param container the remote container
1991 * \param remoteFile the file to copy locally from the remote host into localFile
1992 * \param localFile the local file
1994 //=============================================================================
1995 void Abstract_Engines_Container_i::copyFile(Engines::Container_ptr container, const char* remoteFile, const char* localFile)
1997 Engines::fileTransfer_var fileTransfer = container->getFileTransfer();
2000 if ((fp = fopen(localFile,"wb")) == NULL)
2002 INFOS("file " << localFile << " cannot be open for writing");
2006 CORBA::Long fileId = fileTransfer->open(remoteFile);
2009 Engines::fileBlock* aBlock;
2016 aBlock = fileTransfer->getBlock(fileId);
2017 toFollow = aBlock->length();
2019 CORBA::Octet *buf = aBlock->get_buffer();
2020 fwrite(buf, sizeof(CORBA::Octet), toFollow, fp);
2024 MESSAGE("end of transfer");
2025 fileTransfer->close(fileId);
2029 INFOS("open reference file for copy impossible");
2033 //=============================================================================
2034 /*! \brief create a PyNode object to execute remote python code
2035 * \param nodeName the name of the node
2036 * \param code the python code to load
2037 * \return the PyNode
2039 //=============================================================================
2040 Engines::PyNode_ptr Abstract_Engines_Container_i::createPyNode(const char* nodeName, const char* code)
2042 Engines::PyNode_var node= Engines::PyNode::_nil();
2047 PyObject *res = PyObject_CallMethod(_pyCont,
2048 (char*)"create_pynode",
2056 SALOME::ExceptionStruct es;
2057 es.type = SALOME::INTERNAL_ERROR;
2058 es.text = "can not create a python node";
2059 throw SALOME::SALOME_Exception(es);
2061 ierr=PyLong_AsLong(PyTuple_GetItem(res,0));
2062 PyObject* result=PyTuple_GetItem(res,1);
2063 astr = PyUnicode_AsUTF8(result);
2068 Utils_Locker lck(&_mutexForDftPy);
2069 CORBA::Object_var obj=_orb->string_to_object(astr.c_str());
2070 node=Engines::PyNode::_narrow(obj);
2071 std::map<std::string,Engines::PyNode_var>::iterator it(_dftPyNode.find(nodeName));
2072 if(it==_dftPyNode.end())
2074 _dftPyNode[nodeName]=node;
2078 Engines::PyNode_var oldNode((*it).second);
2079 if(!CORBA::is_nil(oldNode))
2080 oldNode->UnRegister();
2083 if(!CORBA::is_nil(node))
2085 return node._retn();
2089 SALOME::ExceptionStruct es;
2090 es.type = SALOME::INTERNAL_ERROR;
2091 es.text = astr.c_str();
2092 throw SALOME::SALOME_Exception(es);
2096 //=============================================================================
2097 /*! \brief Retrieves the last created PyNode instance with createPyNode.
2100 //=============================================================================
2101 Engines::PyNode_ptr Abstract_Engines_Container_i::getDefaultPyNode(const char *nodeName)
2103 Utils_Locker lck(&_mutexForDftPy);
2104 std::map<std::string,Engines::PyNode_var>::iterator it(_dftPyNode.find(nodeName));
2105 if(it==_dftPyNode.end())
2106 return Engines::PyNode::_nil();
2109 Engines::PyNode_var tmpVar((*it).second);
2110 if(!CORBA::is_nil(tmpVar))
2111 return Engines::PyNode::_duplicate(tmpVar);
2113 return Engines::PyNode::_nil();
2117 //=============================================================================
2118 /*! \brief create a PyScriptNode object to execute remote python code
2119 * \param nodeName the name of the node
2120 * \param code the python code to load
2121 * \return the PyScriptNode
2123 //=============================================================================
2124 Engines::PyScriptNode_ptr Abstract_Engines_Container_i::createPyScriptNode(const char* nodeName, const char* code)
2126 Engines::PyScriptNode_var node= Engines::PyScriptNode::_nil();
2131 PyObject *res = PyObject_CallMethod(_pyCont,
2132 (char*)"create_pyscriptnode",
2140 SALOME::ExceptionStruct es;
2141 es.type = SALOME::INTERNAL_ERROR;
2142 es.text = "can not create a python node";
2143 throw SALOME::SALOME_Exception(es);
2145 ierr=PyLong_AsLong(PyTuple_GetItem(res,0));
2146 PyObject* result=PyTuple_GetItem(res,1);
2147 astr = PyUnicode_AsUTF8(result);
2153 Utils_Locker lck(&_mutexForDftPy);
2154 CORBA::Object_var obj=_orb->string_to_object(astr.c_str());
2155 node=Engines::PyScriptNode::_narrow(obj);
2156 std::map<std::string,Engines::PyScriptNode_var>::iterator it(_dftPyScriptNode.find(nodeName));
2157 if(it==_dftPyScriptNode.end())
2159 _dftPyScriptNode[nodeName]=node;
2163 Engines::PyScriptNode_var oldNode((*it).second);
2164 if(!CORBA::is_nil(oldNode))
2165 oldNode->UnRegister();
2168 return node._retn();
2172 SALOME::ExceptionStruct es;
2173 es.type = SALOME::INTERNAL_ERROR;
2174 es.text = astr.c_str();
2175 throw SALOME::SALOME_Exception(es);
2179 void Abstract_Engines_Container_i::removePyScriptNode(const char *nodeName)
2181 std::map<std::string,Engines::PyScriptNode_var>::iterator it(_dftPyScriptNode.find(nodeName));
2182 if(it==_dftPyScriptNode.end())
2184 std::ostringstream oss; oss << "Engines_Container_i::removePyScriptNode : node \"" << nodeName << "\" is not map !";
2185 SALOME::ExceptionStruct es;
2186 es.type = SALOME::INTERNAL_ERROR;
2187 es.text = oss.str().c_str();
2188 throw SALOME::SALOME_Exception(es);
2190 (*it).second->UnRegister();
2191 _dftPyScriptNode.erase(it);
2194 void Abstract_Engines_Container_i::cleanAllPyScripts()
2196 for(std::map<std::string,Engines::PyNode_var>::iterator it=_dftPyNode.begin();it!=_dftPyNode.end();it++)
2198 Engines::PyNode_var tmpVar((*it).second);
2199 if(!CORBA::is_nil(tmpVar))
2200 tmpVar->UnRegister();
2203 for(std::map<std::string,Engines::PyScriptNode_var>::iterator it=_dftPyScriptNode.begin();it!=_dftPyScriptNode.end();it++)
2205 Engines::PyScriptNode_var tmpVar((*it).second);
2206 if(!CORBA::is_nil(tmpVar))
2207 tmpVar->UnRegister();
2209 _dftPyScriptNode.clear();
2212 //=============================================================================
2213 /*! \brief Retrieves the last created PyScriptNode instance with createPyScriptNode.
2216 //=============================================================================
2217 Engines::PyScriptNode_ptr Abstract_Engines_Container_i::getDefaultPyScriptNode(const char *nodeName)
2219 Utils_Locker lck(&_mutexForDftPy);
2220 std::map<std::string,Engines::PyScriptNode_var>::iterator it(_dftPyScriptNode.find(nodeName));
2221 if(it==_dftPyScriptNode.end())
2222 return Engines::PyScriptNode::_nil();
2225 Engines::PyScriptNode_var tmpVar((*it).second);
2226 if(!CORBA::is_nil(tmpVar))
2227 return Engines::PyScriptNode::_duplicate(tmpVar);
2229 return Engines::PyScriptNode::_nil();
2233 //=============================================================================
2234 /* int checkifexecutable(const char *filename)
2236 * Return non-zero if the name is an executable file, and
2237 * zero if it is not executable, or if it does not exist.
2239 //=============================================================================
2240 int checkifexecutable(const std::string& filename)
2243 struct stat statinfo;
2245 result = stat(filename.c_str(), &statinfo);
2246 if (result < 0) return 0;
2247 if (!S_ISREG(statinfo.st_mode)) return 0;
2252 if (statinfo.st_uid == geteuid()) return statinfo.st_mode & S_IXUSR;
2253 if (statinfo.st_gid == getegid()) return statinfo.st_mode & S_IXGRP;
2254 return statinfo.st_mode & S_IXOTH;
2259 //=============================================================================
2260 /*! \brief Find a file by searching in a path
2261 * \param filename file name to search
2262 * \param path path to search in
2263 * \param pth the complete file path if found
2264 * \return 1 if found 0 if not
2266 //=============================================================================
2267 int findpathof(const std::string& path, std::string& pth, const std::string& filename)
2269 if ( path.size() == 0 ) return 0;
2271 std::string::size_type offset = 0;
2272 std::string::size_type pos = 0;
2274 struct stat statinfo;
2278 pos = path.find( SEP, offset );
2279 pth = path.substr( offset, pos - offset );
2280 if ( pth.size() > 0 )
2282 if( pth[pth.size()-1] != SLASH ) pth += SLASH;
2284 int result=stat(pth.c_str(), &statinfo);
2285 if(result == 0) found=1;
2287 if (pos == std::string::npos) break;
2293 void Abstract_Engines_Container_i::registerTemporaryFile( const std::string& fileName )
2295 _tmp_files.remove( fileName );
2296 _tmp_files.push_back( fileName );
2299 void Abstract_Engines_Container_i::unregisterTemporaryFile( const std::string& fileName )
2301 _tmp_files.remove( fileName );
2304 void Abstract_Engines_Container_i::clearTemporaryFiles()
2306 std::list<std::string>::const_iterator it;
2307 for ( it = _tmp_files.begin(); it != _tmp_files.end(); ++it ) {
2308 #if defined(WIN32) && defined(UNICODE)
2309 std::wstring aFile = Kernel_Utils::utf8_decode_s(*it);
2310 std::wstring command = (GetFileAttributes(aFile.c_str()) == FILE_ATTRIBUTE_DIRECTORY) ? L"rd /Q \"" : L"del /F /Q \"";
2312 command += L"\" 2>NUL";
2313 _wsystem(command.c_str());
2316 std::string aFile = *it;
2317 std::string command = (GetFileAttributes(aFile.c_str()) == FILE_ATTRIBUTE_DIRECTORY) ? "rd /Q \"" : "del /F /Q \"";
2319 command += "\" 2>NUL";
2321 std::string command = "rm -rf ";
2324 system(command.c_str());
2330 static Engines_Container_SSL_i *_container_singleton_ssl = nullptr;
2332 static Engines::Container_var _container_ref_singleton_ssl;
2334 Engines_Container_SSL_i *KERNEL::getContainerSA()
2336 if(!_container_singleton_ssl)
2338 CORBA::ORB_var orb = KERNEL::GetRefToORB();
2339 CORBA::Object_var obj = orb->resolve_initial_references("RootPOA");
2340 PortableServer::POA_var poa = PortableServer::POA::_narrow(obj);
2341 PortableServer::POAManager_var pman = poa->the_POAManager();
2342 CORBA::PolicyList policies;
2345 constexpr int ARGC = 4;
2346 constexpr const char *ARGV[ARGC] = {"Container","FactoryServer","toto",nullptr};
2347 std::unique_ptr<char*[]> argv( new char *[ARGC+1] );
2348 std::vector< std::unique_ptr<char[]> > argvv(ARGC);
2349 argv[ARGC] = nullptr;
2350 for(int i = 0 ; i < ARGC ; ++i)
2354 argvv[i].reset( new char[strlen(ARGV[i])+1] );
2355 strcpy(argvv[i].get(),ARGV[i]);
2356 argv[i] = argvv[i].get();
2361 SALOME_Fake_NamingService ns;
2362 _container_singleton_ssl = new Engines_Container_SSL_i(orb,poa,(char *)"FactoryServer",2,argv.get(),&ns,false);
2363 PortableServer::ObjectId * cont_id = _container_singleton_ssl->getCORBAId();
2365 CORBA::Object_var zeRef = poa->id_to_reference(*cont_id);
2366 _container_ref_singleton_ssl = Engines::Container::_narrow(zeRef);
2368 return _container_singleton_ssl;
2371 Engines::Container_var KERNEL::getContainerRefSA()
2374 return _container_ref_singleton_ssl;