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>
49 #include "utilities.h"
50 #include <SALOMEconfig.h>
51 #include CORBA_SERVER_HEADER(SALOME_Component)
52 #include CORBA_SERVER_HEADER(SALOME_Exception)
53 #include <pthread.h> // must be before Python.h !
55 #include "SALOME_Container_i.hxx"
56 #include "SALOME_Component_i.hxx"
57 #include "SALOME_FileRef_i.hxx"
58 #include "SALOME_FileTransfer_i.hxx"
59 #include "Salome_file_i.hxx"
60 #include "SALOME_NamingService.hxx"
61 #include "SALOME_Fake_NamingService.hxx"
62 #include "SALOME_Embedded_NamingService_Client.hxx"
63 #include "SALOME_Embedded_NamingService.hxx"
64 #include "Basics_Utils.hxx"
65 #include "PythonCppUtils.hxx"
72 #include <structmember.h>
73 #include "Container_init_python.hxx"
74 #ifdef BOS26455_WITH_BOOST_PYTHON
75 #include <boost/python.hpp>
78 bool _Sleeping = false ;
80 // // Needed by multi-threaded Python --- Supervision
84 extern "C" {void ActSigIntHandler() ; }
86 extern "C" {void SigIntHandler(int, siginfo_t *, void *) ; }
88 extern "C" {void SigIntHandler( int ) ; }
94 #define ENGINESO "Engine.dylib"
96 #define ENGINESO "Engine.so"
100 #define ENGINESO "Engine.dll"
111 std::map<std::string, int> Abstract_Engines_Container_i::_cntInstances_map;
112 std::map<std::string, void *> Abstract_Engines_Container_i::_library_map;
113 std::map<std::string, void *> Abstract_Engines_Container_i::_toRemove_map;
114 omni_mutex Abstract_Engines_Container_i::_numInstanceMutex ;
116 static PyObject* _pyCont;
118 int checkifexecutable(const std::string&);
119 int findpathof(const std::string& path, std::string&, const std::string&);
121 /*! \class Engines_Container_i
122 * \brief C++ implementation of Engines::Container interface
127 //=============================================================================
129 * Default constructor, not for use
131 //=============================================================================
133 Abstract_Engines_Container_i::Abstract_Engines_Container_i () :
134 _NS(nullptr),_id(nullptr),_numInstance(0)
138 //=============================================================================
142 //=============================================================================
144 Abstract_Engines_Container_i::Abstract_Engines_Container_i (CORBA::ORB_ptr orb,
145 PortableServer::POA_ptr poa,
146 char *containerName ,
147 int argc , char* argv[],
148 SALOME_NamingService_Container_Abstract *ns,
149 bool isServantAloneInProcess
151 _NS(nullptr),_id(0),_numInstance(0),_isServantAloneInProcess(isServantAloneInProcess)
153 _pid = (long)getpid();
161 std::string hostname = Kernel_Utils::GetHostname();
163 MESSAGE(hostname << " " << getpid() <<
164 " Engines_Container_i starting argc " <<
165 _argc << " Thread " << pthread_self() ) ;
167 MESSAGE(hostname << " " << _getpid() <<
168 " Engines_Container_i starting argc " << _argc<< " Thread " << pthread_self().p ) ;
174 MESSAGE(" argv" << i << " " << _argv[ i ]) ;
180 INFOS("SALOME_Container usage : SALOME_Container ServerName");
184 _isSupervContainer = false;
186 _orb = CORBA::ORB::_duplicate(orb) ;
187 _poa = PortableServer::POA::_duplicate(poa) ;
189 // Pour les containers paralleles: il ne faut pas enregistrer et activer
190 // le container generique, mais le container specialise
193 _id = _poa->activate_object(this);
194 // key point : if ns is nullptr : this servant is alone in its process
195 // if ns is not null : this servant embedded into single process.
196 _NS = ns==nullptr ? new SALOME_NamingService : ns->clone();
197 _NS->init_orb( _orb ) ;
198 CORBA::Object_var obj=_poa->id_to_reference(*_id);
199 Engines::Container_var pCont = Engines::Container::_narrow(obj);
202 _containerName = SALOME_NamingService_Abstract::BuildContainerNameForNS(containerName, hostname.c_str());
203 SCRUTE(_containerName);
204 _NS->Register(pCont, _containerName.c_str());
205 MESSAGE("Engines_Container_i::Engines_Container_i : Container name " << _containerName);
208 // import SALOME_Container
209 // pycont = SALOME_Container.SALOME_Container_i(containerIORStr)
211 CORBA::String_var sior = _orb->object_to_string(pCont);
212 std::string myCommand="pyCont = SALOME_Container.SALOME_Container_i('";
213 myCommand += _containerName + "','";
218 //[RNV]: Comment the PyEval_AcquireLock() and PyEval_ReleaseLock() because this
219 //approach leads to the deadlock of the main thread of the application on Windows platform
220 //in case if cppContainer runs in the standalone mode. The problem with the PyThreadState
221 //described by ABN seems not reproduced, to be checked carefully later...
224 //// [ABN]: using the PyGILState* API here is unstable. omniORB logic is invoked
225 //// by the Python code executed below, and in some (random) cases, the Python code
226 //// execution ends with a PyThreadState which was not the one we have here.
227 //// (TODO: understand why ...)
228 //// To be on the safe side we get and load the thread state ourselves:
229 //PyEval_AcquireLock(); // get GIL
230 //PyThreadState * mainThreadState = PyThreadState_Get();
231 //PyThreadState_Swap(mainThreadState);
234 // mpv: this is temporary solution: there is a unregular crash if not
237 // first element is the path to Registry.dll, but it's wrong
238 PyRun_SimpleString("import sys\n");
239 PyRun_SimpleString("sys.path = sys.path[1:]\n");
241 PyRun_SimpleString("import SALOME_Container\n");
242 PyRun_SimpleString((char*)myCommand.c_str());
243 PyObject *mainmod = PyImport_AddModule("__main__");
244 PyObject *globals = PyModule_GetDict(mainmod);
245 _pyCont = PyDict_GetItemString(globals, "pyCont");
246 //PyThreadState_Swap(NULL);
247 //PyEval_ReleaseLock();
250 fileTransfer_i* aFileTransfer = new fileTransfer_i();
251 CORBA::Object_var obref=aFileTransfer->_this();
252 _fileTransfer = Engines::fileTransfer::_narrow(obref);
253 aFileTransfer->_remove_ref();
257 //=============================================================================
261 //=============================================================================
263 Abstract_Engines_Container_i::~Abstract_Engines_Container_i()
265 MESSAGE("Abstract_Container_i::~Abstract_Container_i()");
273 //=============================================================================
274 //! Get container name
276 * CORBA attribute: Container name (see constructor)
278 //=============================================================================
280 char* Abstract_Engines_Container_i::name()
282 return CORBA::string_dup(_containerName.c_str()) ;
285 //=============================================================================
286 //! Get container working directory
288 * CORBA attribute: Container working directory
290 //=============================================================================
292 char* Abstract_Engines_Container_i::workingdir()
296 return CORBA::string_dup(wd) ;
299 //=============================================================================
300 //! Get container log file name
302 * CORBA attribute: Container log file name
304 //=============================================================================
306 char* Abstract_Engines_Container_i::logfilename()
308 return CORBA::string_dup(_logfilename.c_str()) ;
311 //! Set container log file name
312 void Abstract_Engines_Container_i::logfilename(const char* name)
317 //=============================================================================
318 //! Get container host name
320 * CORBA method: Get the hostName of the Container (without domain extensions)
322 //=============================================================================
324 char* Abstract_Engines_Container_i::getHostName()
326 std::string s = Kernel_Utils::GetHostname();
327 // MESSAGE("Engines_Container_i::getHostName " << s);
328 return CORBA::string_dup(s.c_str()) ;
331 //=============================================================================
332 //! Get container PID
334 * CORBA method: Get the PID (process identification) of the Container
336 //=============================================================================
338 CORBA::Long Abstract_Engines_Container_i::getPID()
340 return (CORBA::Long)getpid();
343 //=============================================================================
344 //! Ping the servant to check it is still alive
346 * CORBA method: check if servant is still alive
348 //=============================================================================
349 void Abstract_Engines_Container_i::ping()
351 MESSAGE("Engines_Container_i::ping() pid "<< getpid());
354 //=============================================================================
355 //! Get number of CPU cores in the calculation node
357 * CORBA method: get number of CPU cores
359 //=============================================================================
361 CORBA::Long Abstract_Engines_Container_i::getNumberOfCPUCores()
364 PyObject *module = PyImport_ImportModuleNoBlock((char*)"salome_psutil");
365 PyObject *result = PyObject_CallMethod(module,
366 (char*)"getNumberOfCPUCores", NULL);
367 int n = PyLong_AsLong(result);
370 return (CORBA::Long)n;
373 //=============================================================================
374 //! Get a load of each CPU core in the calculation node
376 * CORBA method: get a load of each CPU core
378 //=============================================================================
388 PyStdOut_dealloc(PyStdOut *self)
394 PyStdOut_write(PyStdOut* self, PyObject* args)
397 if (!PyArg_ParseTuple(args, "s", &c))
400 *(self->out) = *(self->out) + c;
406 static PyMethodDef PyStdOut_methods[] =
408 {"write", (PyCFunction)PyStdOut_write, METH_VARARGS,
409 PyDoc_STR("write(string) -> None")},
410 {0, 0, 0, 0} /* sentinel */
413 static PyMemberDef PyStdOut_memberlist[] =
415 {(char*)"softspace", T_INT, offsetof(PyStdOut, softspace), 0,
416 (char*)"flag indicating that a space needs to be printed; used by print"},
417 {0, 0, 0, 0, 0} /* sentinel */
420 static PyTypeObject PyStdOut_Type =
422 /* The ob_type field must be initialized in the module init function
423 * to be portable to Windows without using C++. */
424 PyVarObject_HEAD_INIT(NULL, 0)
427 sizeof(PyStdOut), /*tp_basicsize*/
430 (destructor)PyStdOut_dealloc, /*tp_dealloc*/
437 0, /*tp_as_sequence*/
442 PyObject_GenericGetAttr, /*tp_getattro*/
443 /* softspace is writable: we must supply tp_setattro */
444 PyObject_GenericSetAttr, /* tp_setattro */
446 Py_TPFLAGS_DEFAULT, /*tp_flags*/
450 0, /*tp_richcompare*/
451 0, /*tp_weaklistoffset*/
454 PyStdOut_methods, /*tp_methods*/
455 PyStdOut_memberlist, /*tp_members*/
473 0, /*tp_version_tag*/
477 PyObject* newPyStdOut(std::string& out)
479 PyStdOut* self = PyObject_New(PyStdOut, &PyStdOut_Type);
484 return (PyObject*)self;
487 std::string parseException()
490 if (PyErr_Occurred())
492 #ifdef BOS26455_WITH_BOOST_PYTHON
493 PyObject *ptype = nullptr;
494 PyObject *pvalue = nullptr;
495 PyObject *ptraceback = nullptr;
496 PyErr_Fetch(&ptype, &pvalue, &ptraceback);
497 if (ptype == nullptr)
498 return std::string("Null exception type");
499 PyErr_NormalizeException(&ptype, &pvalue, &ptraceback);
500 if (ptraceback != nullptr)
501 PyException_SetTraceback(pvalue, ptraceback);
502 boost::python::handle<> htype(ptype);
503 boost::python::handle<> hvalue(boost::python::allow_null(pvalue));
504 boost::python::handle<> htraceback(boost::python::allow_null(ptraceback));
505 boost::python::object traceback = boost::python::import("traceback");
506 boost::python::object format_exc = traceback.attr("format_exception");
507 boost::python::object formatted = format_exc(htype, hvalue, htraceback);
508 error = boost::python::extract<std::string>(boost::python::str("\n").join(formatted));
510 PyObject* new_stderr = newPyStdOut(error);
511 PyObject* old_stderr = PySys_GetObject((char*)"stderr");
512 Py_INCREF(old_stderr);
513 PySys_SetObject((char*)"stderr", new_stderr);
515 PySys_SetObject((char*)"stderr", old_stderr);
516 Py_DECREF(new_stderr);
523 Engines::vectorOfDouble* Abstract_Engines_Container_i::loadOfCPUCores()
526 PyObject *module = PyImport_ImportModuleNoBlock((char*)"salome_psutil");
527 PyObject *result = PyObject_CallMethod(module,
528 (char*)"loadOfCPUCores", "s",
529 _load_script.c_str());
530 if (PyErr_Occurred())
532 std::string error = parseException();
534 SALOME::ExceptionStruct es;
535 es.type = SALOME::INTERNAL_ERROR;
536 es.text = CORBA::string_dup(error.c_str());
537 throw SALOME::SALOME_Exception(es);
540 int n = this->getNumberOfCPUCores();
541 if (!PyList_Check(result) || PyList_Size(result) != n) {
542 // bad number of cores
544 SALOME::ExceptionStruct es;
545 es.type = SALOME::INTERNAL_ERROR;
546 es.text = "wrong number of cores";
547 throw SALOME::SALOME_Exception(es);
550 Engines::vectorOfDouble_var loads = new Engines::vectorOfDouble;
552 for (Py_ssize_t i = 0; i < PyList_Size(result); ++i) {
553 PyObject* item = PyList_GetItem(result, i);
554 double foo = PyFloat_AsDouble(item);
555 if (foo < 0.0 || foo > 1.0)
557 // value not in [0, 1] range
559 SALOME::ExceptionStruct es;
560 es.type = SALOME::INTERNAL_ERROR;
561 es.text = "load not in [0, 1] range";
562 throw SALOME::SALOME_Exception(es);
569 return loads._retn();
572 //=============================================================================
573 //! Set custom script to calculate a load of each CPU core
575 * CORBA method: Set custom script to calculate CPU load
576 * \param script Python script to execute
578 //=============================================================================
580 void Abstract_Engines_Container_i::setPyScriptForCPULoad(const char *script)
582 _load_script = script;
585 //=============================================================================
586 //! Nullify custom script to calculate each CPU core's load
588 * CORBA method: reset script for load calculation to default implementation
590 //=============================================================================
592 void Abstract_Engines_Container_i::resetScriptForCPULoad()
597 //=============================================================================
598 //! Get total physical memory of calculation node, in megabytes
600 * CORBA method: get total physical memory of calculation node
602 //=============================================================================
604 CORBA::Long Abstract_Engines_Container_i::getTotalPhysicalMemory()
607 PyObject *module = PyImport_ImportModuleNoBlock((char*)"salome_psutil");
608 PyObject *result = PyObject_CallMethod(module,
609 (char*)"getTotalPhysicalMemory", NULL);
610 int n = PyLong_AsLong(result);
613 return (CORBA::Long)n;
616 //=============================================================================
617 //! Get used physical memory of calculation node, in megabytes
619 * CORBA method: get used physical memory of calculation node
621 //=============================================================================
623 CORBA::Long Abstract_Engines_Container_i::getTotalPhysicalMemoryInUse()
626 PyObject *module = PyImport_ImportModuleNoBlock((char*)"salome_psutil");
627 PyObject *result = PyObject_CallMethod(module,
628 (char*)"getTotalPhysicalMemoryInUse", NULL);
629 int n = PyLong_AsLong(result);
632 return (CORBA::Long)n;
635 //=============================================================================
636 //! Obtain physical memory, used by the current process, in megabytes.
638 * CORBA method: get physical memory, used by the current process
640 //=============================================================================
642 CORBA::Long Abstract_Engines_Container_i::getTotalPhysicalMemoryInUseByMe()
645 PyObject *module = PyImport_ImportModuleNoBlock((char*)"salome_psutil");
646 PyObject *result = PyObject_CallMethod(module,
647 (char*)"getTotalPhysicalMemoryInUseByMe", NULL);
648 int n = PyLong_AsLong(result);
651 return (CORBA::Long)n;
654 //=============================================================================
655 //! Shutdown the container
657 * CORBA method, oneway: Server shutdown.
658 * - Container name removed from naming service,
659 * - servant deactivation,
660 * - orb shutdown if no other servants in the process
662 //=============================================================================
663 void Abstract_Engines_Container_i::Shutdown()
665 MESSAGE("Engines_Container_i::Shutdown()");
667 // Clear registered temporary files
668 clearTemporaryFiles();
670 /* For each component contained in this container
671 * tell it to self-destroy
673 std::map<std::string, Engines::EngineComponent_var>::iterator itm;
674 for (itm = _listInstances_map.begin(); itm != _listInstances_map.end(); itm++)
678 itm->second->destroy();
680 catch(const CORBA::Exception&)
682 // ignore this entry and continue
686 // ignore this entry and continue
689 _listInstances_map.clear();
691 // NS unregistering may throw in SSL mode if master process hosting SALOME_Embedded_NamingService servant has vanished
692 // In this case it's skip it and still continue.
695 _NS->Destroy_FullDirectory(_containerName.c_str());
696 _NS->Destroy_Name(_containerName.c_str());
702 this->cleanAllPyScripts();
704 if(_isServantAloneInProcess)
706 MESSAGE("Effective Shutdown of container Begins...");
707 if(!CORBA::is_nil(_orb))
712 //=============================================================================
713 //! load a component implementation
716 * \param componentName component name
717 * \param reason explains error when load fails
718 * \return true if dlopen successful or already done, false otherwise
720 //=============================================================================
722 Abstract_Engines_Container_i::load_component_Library(const char* componentName, CORBA::String_out reason)
725 //=================================================================
726 // --- C++ implementation section
727 //=================================================================
729 if(load_component_CppImplementation(componentName,retso))
731 reason=CORBA::string_dup("");
734 else if(retso != "ImplementationNotFound")
736 reason=CORBA::string_dup(retso.c_str());
741 retso+=componentName;
742 retso+=": Can't find C++ implementation ";
743 retso+=std::string(LIB) + componentName + ENGINESO;
745 //=================================================================
746 // --- Python implementation section
747 //=================================================================
749 if(load_component_PythonImplementation(componentName,retpy))
751 reason=CORBA::string_dup("");
754 else if(retpy != "ImplementationNotFound")
756 reason=CORBA::string_dup(retpy.c_str());
761 retpy+=componentName;
762 retpy+=": Can't find python implementation ";
763 retpy+=componentName;
766 //=================================================================
767 // -- Executable implementation section
768 //=================================================================
770 if(load_component_ExecutableImplementation(componentName,retex))
772 reason=CORBA::string_dup("");
775 else if(retex != "ImplementationNotFound")
777 reason=CORBA::string_dup(retex.c_str());
782 retex+=componentName;
783 retex+=": Can't find executable implementation ";
784 retex+=componentName;
787 std::string ret="Component implementation not found: ";
788 ret += componentName ;
794 std::cerr << ret << std::endl;
795 reason=CORBA::string_dup(ret.c_str());
800 //=============================================================================
801 //! try to load a C++ component implementation
804 * \param componentName the name of the component (COMPONENT, for example)
805 * \param reason explains error when load fails
806 * \return true if loading is successful or already done, false otherwise
808 //=============================================================================
810 Abstract_Engines_Container_i::load_component_CppImplementation(const char* componentName, std::string& reason)
812 std::string aCompName(componentName);
813 std::string impl_name = std::string(LIB) + aCompName + ENGINESO;
816 _numInstanceMutex.lock(); // lock to be alone
817 // (see decInstanceCnt, finalize_removal))
818 if (_toRemove_map.count(impl_name) != 0) _toRemove_map.erase(impl_name);
819 if (_library_map.count(impl_name) != 0)
821 MESSAGE("Library " << impl_name << " already loaded");
822 _numInstanceMutex.unlock();
826 _numInstanceMutex.unlock();
830 handle = dlopen( impl_name.c_str() , RTLD_NOW | RTLD_GLOBAL ) ;
833 //not loadable. Try to find the lib file in LD_LIBRARY_PATH
836 char* p=getenv("DYLD_LIBRARY_PATH");
838 char* p=getenv("LD_LIBRARY_PATH");
841 path=path+SEP+"/usr/lib"+SEP+"/lib";
844 if(findpathof(path, pth, impl_name))
846 //found but not loadable
849 reason+=": C++ implementation found ";
851 reason+=" but it is not loadable. Error:\n";
853 std::cerr << reason << std::endl;
859 //continue with other implementation
860 reason="ImplementationNotFound";
867 std::wstring libToLoad = Kernel_Utils::utf8_decode_s( impl_name );
869 std::string libToLoad = impl_name;
871 handle = LoadLibrary(libToLoad.c_str() );
874 reason="ImplementationNotFound";
880 _numInstanceMutex.lock();
881 _library_map[impl_name] = handle;
882 _numInstanceMutex.unlock();
890 //=============================================================================
891 //! try to load a Python component implementation
894 * \param componentName name of the component
895 * \param reason explains error when load fails
896 * \return true if loading is successful or already done, false otherwise
898 //=============================================================================
900 Abstract_Engines_Container_i::load_component_PythonImplementation(const char* componentName, std::string& reason)
902 std::string aCompName(componentName);
904 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
905 if (_library_map.count(aCompName) != 0)
907 _numInstanceMutex.unlock() ;
909 return true; // Python Component, already imported
911 _numInstanceMutex.unlock() ;
915 PyObject *result = PyObject_CallMethod(_pyCont,
916 (char*)"import_component",
917 (char*)"s",componentName);
919 reason=PyUnicode_AsUTF8(result);
926 //Python component has been loaded (import componentName)
927 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
928 _library_map[aCompName] = (void *)_pyCont; // any non O value OK
929 _numInstanceMutex.unlock() ;
930 MESSAGE("import Python: "<< aCompName <<" OK");
933 else if(reason=="ImplementationNotFound")
935 //Python implementation has not been found. Continue with other implementation
936 reason="ImplementationNotFound";
940 //Python implementation has been found but loading has failed
941 std::cerr << reason << std::endl;
946 //=============================================================================
947 //! try to load a Executable component implementation
950 * \param componentName name of the component
951 * \param reason explains error when load fails
952 * \return true if loading is successful or already done, false otherwise
954 //=============================================================================
956 Abstract_Engines_Container_i::load_component_ExecutableImplementation(const char* componentName, std::string& reason)
958 std::string aCompName(componentName);
959 std::string executable=aCompName+".exe";
964 char* p=getenv("PATH");
967 if (findpathof(path, pth, executable))
969 if(checkifexecutable(pth))
971 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
972 _library_map[executable] = (void *)1; // any non O value OK
973 _numInstanceMutex.unlock() ;
974 MESSAGE("import executable: "<< pth <<" OK");
980 reason+=": implementation found ";
982 reason+=" but it is not executable";
983 std::cerr << reason << std::endl;
987 reason="ImplementationNotFound";
992 //=============================================================================
993 //! Create a new component instance
995 * CORBA method: Creates a new servant instance of a component.
996 * The servant registers itself to naming service and Registry.tdlib
997 * \param genericRegisterName Name of the component instance to register
998 * in Registry & Name Service (without _inst_n suffix)
999 * \return a loaded component
1001 //=============================================================================
1002 Engines::EngineComponent_ptr
1003 Abstract_Engines_Container_i::create_component_instance(const char*genericRegisterName)
1005 Engines::FieldsDict_var env = new Engines::FieldsDict;
1007 Engines::EngineComponent_ptr compo =
1008 create_component_instance_env(genericRegisterName, env, reason);
1009 CORBA::string_free(reason);
1013 void EffectiveOverrideEnvironment( const Engines::FieldsDict& env )
1015 MESSAGE("Positionning environment on container ");
1016 for (CORBA::ULong i=0; i < env.length(); i++)
1018 if (env[i].value.type()->kind() == CORBA::tk_string)
1021 env[i].value >>= value;
1022 MESSAGE( env[i].key << " = " << value);
1024 if( setenv(env[i].key,value,1) != 0 )
1027 std::string sErr( strerror( errsv) );
1035 std::vector< std::pair<std::string,std::string> > GetOSEnvironment()
1037 std::vector< std::pair<std::string,std::string> > ret;
1039 char **envPt( environ );
1040 for(;*envPt != nullptr; ++envPt)
1042 std::string s( *envPt );
1043 auto pos = s.find_first_of('=');
1044 std::string k( s.substr(0,pos) ),v( s.substr(pos+1) );
1045 ret.emplace_back( std::pair<std::string,std::string>(k,v) );
1051 void Abstract_Engines_Container_i::override_environment( const Engines::FieldsDict& env )
1053 EffectiveOverrideEnvironment(env);
1056 Engines::FieldsDict *Abstract_Engines_Container_i::get_os_environment()
1058 std::unique_ptr<Engines::FieldsDict> ret( new Engines::FieldsDict );
1059 std::vector< std::pair<std::string,std::string> > retCpp( GetOSEnvironment() );
1060 auto sz = retCpp.size();
1062 for(auto i = 0 ; i < sz ; ++i)
1064 (*ret)[i].key = CORBA::string_dup( retCpp[i].first.c_str() );
1065 (*ret)[i].value <<= CORBA::string_dup( retCpp[i].second.c_str() );
1067 return ret.release();
1070 //=============================================================================
1071 //! Create a new component instance with environment variables specified
1073 * CORBA method: Creates a new servant instance of a component.
1074 * The servant registers itself to naming service and Registry.
1075 * \param genericRegisterName Name of the component instance to register
1076 * in Registry & Name Service (without _inst_n suffix)
1077 * \param env dict of env variables
1078 * \param reason explains error when create_component_instance_env fails
1079 * \return a loaded component
1081 //=============================================================================
1082 Engines::EngineComponent_ptr
1083 Abstract_Engines_Container_i::create_component_instance_env(const char*genericRegisterName,
1084 const Engines::FieldsDict& env,
1085 CORBA::String_out reason)
1088 if (_library_map.count(genericRegisterName) != 0)
1090 // It's a Python component
1091 Engines::EngineComponent_ptr compo = createPythonInstance(genericRegisterName, error);
1092 reason=CORBA::string_dup(error.c_str());
1096 std::string impl_name = std::string(LIB) + genericRegisterName + ENGINESO;
1097 if (_library_map.count(impl_name) != 0)
1099 // It's a C++ component
1100 void* handle = _library_map[impl_name];
1101 Engines::EngineComponent_ptr compo = createInstance(genericRegisterName, handle, error);
1102 reason=CORBA::string_dup(error.c_str());
1106 impl_name = std::string(genericRegisterName) + ".exe";
1107 if (_library_map.count(impl_name) != 0)
1109 //It's an executable component
1110 Engines::EngineComponent_ptr compo = createExecutableInstance(genericRegisterName, env, error);
1111 reason=CORBA::string_dup(error.c_str());
1115 error="load_component_Library has probably not been called for component: ";
1116 error += genericRegisterName;
1118 reason=CORBA::string_dup(error.c_str());
1119 return Engines::EngineComponent::_nil() ;
1122 //=============================================================================
1123 //! Create a new component instance (Executable implementation)
1125 * \param CompName Name of the component instance
1126 * \param env dict of env variables
1127 * \param reason explains error when creation fails
1128 * \return a loaded component
1130 * This component is implemented in an executable with name genericRegisterName.exe
1131 * It must register itself in Naming Service. The container waits some time (10 s max)
1132 * it's registration.
1134 //=============================================================================
1135 Engines::EngineComponent_ptr
1136 Abstract_Engines_Container_i::createExecutableInstance(std::string CompName,
1137 const Engines::FieldsDict& env,
1138 std::string& reason)
1140 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1142 _numInstanceMutex.lock() ; // lock on the instance number
1144 int numInstance = _numInstance ;
1145 _numInstanceMutex.unlock() ;
1148 sprintf( aNumI , "%d" , numInstance ) ;
1149 std::string instanceName = CompName + "_inst_" + aNumI ;
1150 std::string component_registerName = _containerName + "/" + instanceName;
1152 //check if an entry exist in naming service
1153 CORBA::Object_var nsobj = _NS->Resolve(component_registerName.c_str());
1154 if ( !CORBA::is_nil(nsobj) )
1156 // unregister the registered component
1157 _NS->Destroy_Name(component_registerName.c_str());
1158 //kill or shutdown it ???
1161 // first arg container ior string
1162 // second arg container name
1163 // third arg instance name
1165 Engines::Container_var pCont= _this();
1166 CORBA::String_var sior = _orb->object_to_string(pCont);
1168 std::string command;
1169 command="mkdir -p ";
1170 command+=instanceName;
1172 command+=instanceName;
1177 command+= sior; // container ior string
1179 command+=_containerName; //container name
1181 command+=instanceName; //instance name
1183 MESSAGE("SALOME_Container::create_component_instance command=" << command);
1186 // use fork/execl instead of system to get finer control on env variables
1189 if(pid == 0) // child
1191 EffectiveOverrideEnvironment(env);
1193 execl("/bin/sh", "sh", "-c", command.c_str() , (char *)0);
1196 else if(pid < 0) // failed to fork
1205 tpid = wait(&status);
1206 } while (tpid != pid);
1209 // launch component with a system call
1210 int status=system(command.c_str());
1215 reason="SALOME_Container::create_component_instance system failed (system command status -1)";
1217 return Engines::EngineComponent::_nil();
1220 else if (WEXITSTATUS(status) == 217)
1222 reason="SALOME_Container::create_component_instance system failed (system command status 217)";
1224 return Engines::EngineComponent::_nil();
1230 if (getenv("TIMEOUT_TO_WAIT_EXE_COMPONENT") != 0)
1232 std::string new_count_str = getenv("TIMEOUT_TO_WAIT_EXE_COMPONENT");
1234 std::istringstream ss(new_count_str);
1235 if (!(ss >> new_count))
1237 INFOS("[Container] TIMEOUT_TO_WAIT_EXE_COMPONENT should be an int");
1242 INFOS("[Container] waiting " << count << " second steps exe component ");
1243 CORBA::Object_var obj = CORBA::Object::_nil() ;
1244 while ( CORBA::is_nil(obj) && count )
1252 MESSAGE( count << ". Waiting for component " << CompName);
1253 obj = _NS->Resolve(component_registerName.c_str());
1256 if(CORBA::is_nil(obj))
1258 reason="SALOME_Container::create_component_instance failed";
1260 return Engines::EngineComponent::_nil();
1264 MESSAGE("SALOME_Container::create_component_instance successful");
1265 iobject = Engines::EngineComponent::_narrow(obj);
1266 _listInstances_map[instanceName] = iobject;
1267 return iobject._retn();
1273 //=============================================================================
1274 //! Create a new component instance (Python implementation)
1276 * \param CompName Name of the component instance
1277 * \param reason explains error when creation fails
1278 * \return a loaded component
1280 //=============================================================================
1281 Engines::EngineComponent_ptr
1282 Abstract_Engines_Container_i::createPythonInstance(std::string CompName,
1283 std::string& reason)
1285 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1287 _numInstanceMutex.lock() ; // lock on the instance number
1289 int numInstance = _numInstance ;
1290 _numInstanceMutex.unlock() ;
1293 sprintf( aNumI , "%d" , numInstance ) ;
1294 std::string instanceName = CompName + "_inst_" + aNumI ;
1295 std::string component_registerName = _containerName + "/" + instanceName;
1299 PyObject *result = PyObject_CallMethod(_pyCont,
1300 (char*)"create_component_instance",
1303 instanceName.c_str());
1306 PyArg_ParseTuple(result,"ss", &ior, &error);
1314 CORBA::Object_var obj = _orb->string_to_object(iors.c_str());
1315 iobject = Engines::EngineComponent::_narrow( obj ) ;
1316 _listInstances_map[instanceName] = iobject;
1318 return iobject._retn();
1322 Abstract_Engines_Container_i::create_python_service_instance(const char * CompName,
1323 CORBA::String_out reason)
1325 CORBA::Object_var object = CORBA::Object::_nil();
1327 _numInstanceMutex.lock() ; // lock on the instance number
1329 int numInstance = _numInstance ;
1330 _numInstanceMutex.unlock() ;
1333 sprintf( aNumI , "%d" , numInstance ) ;
1334 std::string instanceName = std::string(CompName) + "_inst_" + aNumI ;
1335 std::string component_registerName = _containerName + "/" + instanceName;
1337 char * _ior = nullptr;
1340 PyObject *result = PyObject_CallMethod(_pyCont,
1341 (char*)"create_component_instance",
1344 instanceName.c_str());
1347 PyArg_ParseTuple(result,"ss", &ior, &error);
1348 reason = CORBA::string_dup(error);
1349 _ior = CORBA::string_dup(ior);
1356 //=============================================================================
1357 //! Create a new component instance (C++ implementation)
1359 * C++ method: create a servant instance of a component.
1360 * \param genericRegisterName Name of the component instance to register
1361 * in Registry & Name Service,
1362 * (without _inst_n suffix, like "COMPONENT")
1363 * \param handle loaded library handle
1364 * \param reason explains error when creation fails
1365 * \return a loaded component
1367 * example with names:
1368 * - aGenRegisterName = COMPONENT (= first argument)
1369 * - _containerName = /Containers/cli76ce/FactoryServer
1370 * - factoryName = COMPONENTEngine_factory
1371 * - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
1372 * - instanceName = COMPONENT_inst_1
1373 * - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1375 //=============================================================================
1376 Engines::EngineComponent_ptr
1377 Abstract_Engines_Container_i::createInstance(std::string genericRegisterName,
1379 std::string& reason)
1381 // --- find the factory
1383 std::string aGenRegisterName = genericRegisterName;
1384 std::string factory_name = aGenRegisterName + std::string("Engine_factory");
1385 SCRUTE(factory_name) ;
1387 typedef PortableServer::ObjectId* (*FACTORY_FUNCTION) (CORBA::ORB_ptr,
1388 PortableServer::POA_ptr,
1389 PortableServer::ObjectId *,
1394 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)dlsym( handle, factory_name.c_str() );
1396 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)GetProcAddress( (HINSTANCE)handle, factory_name.c_str() );
1399 if ( !Component_factory )
1401 MESSAGE( "Can't resolve symbol: " + factory_name );
1406 return Engines::EngineComponent::_nil() ;
1409 // --- create instance
1411 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1415 _numInstanceMutex.lock() ; // lock on the instance number
1417 int numInstance = _numInstance ;
1418 _numInstanceMutex.unlock() ;
1421 sprintf( aNumI , "%d" , numInstance ) ;
1422 std::string instanceName = aGenRegisterName + "_inst_" + aNumI ;
1423 std::string component_registerName =
1424 _containerName + "/" + instanceName;
1426 // --- Instantiate required CORBA object
1428 PortableServer::ObjectId *id ; //not owner, do not delete (nore use var)
1429 id = (Component_factory) ( _orb, _poa, _id, instanceName.c_str(),
1430 aGenRegisterName.c_str() ) ;
1433 reason="Can't get ObjectId from factory";
1435 return iobject._retn();
1438 // --- get reference from id
1440 CORBA::Object_var obj = _poa->id_to_reference(*id);
1441 iobject = Engines::EngineComponent::_narrow( obj ) ;
1443 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1444 _listInstances_map[instanceName] = iobject;
1445 _cntInstances_map[aGenRegisterName] += 1;
1446 _numInstanceMutex.unlock() ;
1447 SCRUTE(aGenRegisterName);
1448 SCRUTE(_cntInstances_map[aGenRegisterName]);
1450 // --- register the engine under the name
1451 // containerName(.dir)/instanceName(.object)
1453 _NS->Register( iobject , component_registerName.c_str() ) ;
1454 MESSAGE( component_registerName.c_str() << " bound" ) ;
1458 reason="Container_i::createInstance exception caught";
1461 return iobject._retn();
1464 //=============================================================================
1465 //! Find an existing (in the container) component instance
1467 * CORBA method: Finds a servant instance of a component
1468 * \param registeredName Name of the component in Registry or Name Service,
1469 * without instance suffix number
1470 * \return the first found instance
1472 //=============================================================================
1473 Engines::EngineComponent_ptr
1474 Abstract_Engines_Container_i::find_component_instance( const char* registeredName)
1476 Engines::EngineComponent_var anEngine = Engines::EngineComponent::_nil();
1477 std::map<std::string,Engines::EngineComponent_var>::iterator itm =_listInstances_map.begin();
1478 while (itm != _listInstances_map.end())
1480 std::string instance = (*itm).first;
1482 if (instance.find(registeredName) == 0)
1484 anEngine = (*itm).second;
1485 return anEngine._retn();
1489 return anEngine._retn();
1492 //=============================================================================
1493 //! Remove the component instance from container
1495 * CORBA method: Stops the component servant, and deletes all related objects
1496 * \param component_i Component to be removed
1498 //=============================================================================
1500 void Abstract_Engines_Container_i::remove_impl(Engines::EngineComponent_ptr component_i)
1502 ASSERT(! CORBA::is_nil(component_i));
1503 std::string instanceName = component_i->instanceName() ;
1504 MESSAGE("unload component " << instanceName);
1505 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1506 _listInstances_map.erase(instanceName);
1507 _numInstanceMutex.unlock() ;
1508 component_i->destroy() ;
1509 _NS->Destroy_Name(instanceName.c_str());
1512 //=============================================================================
1513 //! Unload component libraries from the container
1515 * CORBA method: Discharges unused libraries from the container.
1517 //=============================================================================
1518 void Abstract_Engines_Container_i::finalize_removal()
1520 MESSAGE("finalize unload : dlclose");
1521 _numInstanceMutex.lock(); // lock to be alone
1522 // (see decInstanceCnt, load_component_Library)
1523 std::map<std::string, void *>::iterator ith;
1524 for (ith = _toRemove_map.begin(); ith != _toRemove_map.end(); ith++)
1526 void *handle = (*ith).second;
1527 std::string impl_name= (*ith).first;
1532 // dlclose(handle); // SALOME unstable after ...
1533 // _library_map.erase(impl_name);
1536 _toRemove_map.clear();
1537 _numInstanceMutex.unlock();
1540 //=============================================================================
1541 //! Decrement component instance reference count
1545 //=============================================================================
1546 void Abstract_Engines_Container_i::decInstanceCnt(std::string genericRegisterName)
1548 if(_cntInstances_map.count(genericRegisterName)==0)
1550 std::string aGenRegisterName =genericRegisterName;
1551 MESSAGE("Engines_Container_i::decInstanceCnt " << aGenRegisterName);
1552 ASSERT(_cntInstances_map[aGenRegisterName] > 0);
1553 _numInstanceMutex.lock(); // lock to be alone
1554 // (see finalize_removal, load_component_Library)
1555 _cntInstances_map[aGenRegisterName] -= 1;
1556 SCRUTE(_cntInstances_map[aGenRegisterName]);
1557 if (_cntInstances_map[aGenRegisterName] == 0)
1559 std::string impl_name =
1560 Engines_Component_i::GetDynLibraryName(aGenRegisterName.c_str());
1562 void* handle = _library_map[impl_name];
1564 _toRemove_map[impl_name] = handle;
1566 _numInstanceMutex.unlock();
1569 //=============================================================================
1570 //! Find or create a new component instance
1572 * CORBA method: find or create an instance of the component (servant),
1573 * load a new component class (dynamic library) if required,
1575 * ---- FOR COMPATIBILITY WITH 2.2 ----
1577 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
1579 * The servant registers itself to naming service and Registry.
1580 * \param genericRegisterName Name of the component to register
1581 * in Registry & Name Service
1582 * \param componentName Name of the constructed library of the component
1583 * \return a loaded component
1585 //=============================================================================
1587 Engines::EngineComponent_ptr
1588 Abstract_Engines_Container_i::load_impl( const char* genericRegisterName,
1589 const char* /*componentName*/ )
1592 std::string impl_name = std::string(LIB) + genericRegisterName + ENGINESO;
1593 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1594 if (load_component_Library(genericRegisterName,reason))
1595 iobject = find_or_create_instance(genericRegisterName, impl_name);
1596 CORBA::string_free(reason);
1597 return iobject._retn();
1600 Engines::EmbeddedNamingService_ptr Abstract_Engines_Container_i::get_embedded_NS_if_ssl()
1602 SALOME_Embedded_NamingService_Client *nsc(dynamic_cast<SALOME_Embedded_NamingService_Client *>(this->_NS));
1605 Engines::EmbeddedNamingService_var obj = nsc->GetObject();
1606 return Engines::EmbeddedNamingService::_duplicate(obj);
1610 SALOME_Fake_NamingService *fns(dynamic_cast<SALOME_Fake_NamingService *>(this->_NS));
1613 Engines::EmbeddedNamingService_var ret = GetEmbeddedNamingService();
1617 return Engines::EmbeddedNamingService::_nil();
1621 //=============================================================================
1622 //! Finds an already existing component instance or create a new instance
1624 * C++ method: Finds an already existing servant instance of a component, or
1625 * create an instance.
1626 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
1627 * \param genericRegisterName Name of the component instance to register
1628 * in Registry & Name Service,
1629 * (without _inst_n suffix, like "COMPONENT")
1630 * \param componentLibraryName like "libCOMPONENTEngine.so"
1631 * \return a loaded component
1633 * example with names:
1634 * - aGenRegisterName = COMPONENT (= first argument)
1635 * - impl_name = libCOMPONENTEngine.so (= second argument)
1636 * - _containerName = /Containers/cli76ce/FactoryServer
1637 * - factoryName = COMPONENTEngine_factory
1638 * - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
1639 * - instanceName = COMPONENT_inst_1
1640 * - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1642 //=============================================================================
1644 Engines::EngineComponent_ptr
1645 Abstract_Engines_Container_i::find_or_create_instance(std::string genericRegisterName,
1646 std::string componentLibraryName)
1648 std::string aGenRegisterName = genericRegisterName;
1649 std::string impl_name = componentLibraryName;
1650 if (_library_map.count(impl_name) == 0)
1652 INFOS("shared library " << impl_name <<" must be loaded before creating instance");
1653 return Engines::EngineComponent::_nil() ;
1657 // --- find a registered instance in naming service, or create
1659 void* handle = _library_map[impl_name];
1660 std::string component_registerBase =
1661 _containerName + "/" + aGenRegisterName;
1662 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1666 CORBA::Object_var obj =
1667 _NS->ResolveFirst( component_registerBase.c_str());
1668 if ( CORBA::is_nil( obj ) )
1670 iobject = createInstance(genericRegisterName,
1676 iobject = Engines::EngineComponent::_narrow( obj ) ;
1681 INFOS( "Container_i::load_impl caught" ) ;
1683 return iobject._retn();
1687 //=============================================================================
1688 //! Indicate if container is a python one
1690 * Retrieves only with container naming convention if it is a python container
1692 //=============================================================================
1693 bool Abstract_Engines_Container_i::isPythonContainer(const char* ContainerName)
1696 size_t len=strlen(ContainerName);
1698 if(strcmp(ContainerName+len-2,"Py")==0)
1703 //=============================================================================
1704 //! Kill the container
1706 * CORBA method: Kill the container process with exit(0).
1707 * To remove : never returns !
1709 //=============================================================================
1710 bool Abstract_Engines_Container_i::Kill_impl()
1712 MESSAGE("Engines_Container_i::Kill() pid "<< getpid() << " containerName "
1713 << _containerName.c_str() << " machineName "
1714 << Kernel_Utils::GetHostname().c_str());
1715 INFOS("===============================================================");
1716 INFOS("= REMOVE calls to Kill_impl in C++ container =");
1717 INFOS("===============================================================");
1723 //=============================================================================
1727 //=============================================================================
1728 void ActSigIntHandler()
1731 struct sigaction SigIntAct ;
1732 SigIntAct.sa_sigaction = &SigIntHandler ;
1733 sigemptyset(&SigIntAct.sa_mask);
1734 SigIntAct.sa_flags = SA_SIGINFO ;
1737 // DEBUG 03.02.2005 : the first parameter of sigaction is not a mask of signals
1738 // (SIGINT | SIGUSR1) :
1739 // it must be only one signal ===> one call for SIGINT
1740 // and an other one for SIGUSR1
1743 if ( sigaction( SIGINT , &SigIntAct, NULL ) )
1745 perror("SALOME_Container main ") ;
1748 if ( sigaction( SIGUSR1 , &SigIntAct, NULL ) )
1750 perror("SALOME_Container main ") ;
1753 if ( sigaction( SIGUSR2 , &SigIntAct, NULL ) )
1755 perror("SALOME_Container main ") ;
1759 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1760 // use of streams (and so on) should never be used because :
1761 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1762 // A stream operation may be interrupted by a signal and if the Handler use stream we
1763 // may have a "Dead-Lock" ===HangUp
1764 //==INFOS is commented
1765 // INFOS(pthread_self() << "SigIntHandler activated") ;
1768 signal( SIGINT, SigIntHandler );
1769 // legacy code required to supervisor. Commented in order to avoid problems on Windows
1770 // signal( SIGUSR1, SigIntHandler );
1776 void CallCancelThread() ;
1779 void SigIntHandler(int /*what*/ ,
1780 siginfo_t * siginfo ,
1783 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1784 // use of streams (and so on) should never be used because :
1785 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1786 // A stream operation may be interrupted by a signal and if the Handler use stream we
1787 // may have a "Dead-Lock" ===HangUp
1788 //==MESSAGE is commented
1789 // MESSAGE(pthread_self() << "SigIntHandler what " << what << std::endl
1790 // << " si_signo " << siginfo->si_signo << std::endl
1791 // << " si_code " << siginfo->si_code << std::endl
1792 // << " si_pid " << siginfo->si_pid) ;
1797 // MESSAGE("SigIntHandler END sleeping.") ;
1802 ActSigIntHandler() ;
1803 if ( siginfo->si_signo == SIGUSR1 )
1807 else if ( siginfo->si_signo == SIGUSR2 )
1809 CallCancelThread() ;
1814 // MESSAGE("SigIntHandler BEGIN sleeping.") ;
1821 // MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1827 void SigIntHandler( int what )
1830 MESSAGE( pthread_self() << "SigIntHandler what " << what << std::endl );
1832 MESSAGE( "SigIntHandler what " << what << std::endl );
1837 MESSAGE("SigIntHandler END sleeping.") ;
1842 ActSigIntHandler() ;
1843 if ( what == SIGUSR1 )
1850 MESSAGE("SigIntHandler BEGIN sleeping.") ;
1857 MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1864 //=============================================================================
1865 //! Get or create a file reference object associated to a local file (to transfer it)
1867 * CORBA method: get or create a fileRef object associated to a local file
1868 * (a file on the computer on which runs the container server), which stores
1869 * a list of (machine, localFileName) corresponding to copies already done.
1871 * \param origFileName absolute path for a local file to copy on other
1873 * \return a fileRef object associated to the file.
1875 //=============================================================================
1876 Engines::fileRef_ptr
1877 Abstract_Engines_Container_i::createFileRef(const char* origFileName)
1879 std::string origName(origFileName);
1880 Engines::fileRef_var theFileRef = Engines::fileRef::_nil();
1882 if (origName[0] != '/')
1884 INFOS("path of file to copy must be an absolute path beginning with '/'");
1885 return Engines::fileRef::_nil();
1888 if (CORBA::is_nil(_fileRef_map[origName]))
1890 CORBA::Object_var obj=_poa->id_to_reference(*_id);
1891 Engines::Container_var pCont = Engines::Container::_narrow(obj);
1892 fileRef_i* aFileRef = new fileRef_i(pCont, origFileName);
1893 theFileRef = Engines::fileRef::_narrow(aFileRef->_this());
1894 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1895 _fileRef_map[origName] = theFileRef;
1896 _numInstanceMutex.unlock() ;
1899 theFileRef = Engines::fileRef::_duplicate(_fileRef_map[origName]);
1900 ASSERT(! CORBA::is_nil(theFileRef));
1901 return theFileRef._retn();
1904 //=============================================================================
1905 //! Get a fileTransfer reference
1908 * \return a reference to the fileTransfer object
1910 //=============================================================================
1911 Engines::fileTransfer_ptr
1912 Abstract_Engines_Container_i::getFileTransfer()
1914 Engines::fileTransfer_var aFileTransfer
1915 = Engines::fileTransfer::_duplicate(_fileTransfer);
1916 return aFileTransfer._retn();
1919 //=============================================================================
1920 //! Create a Salome file
1921 //=============================================================================
1922 Engines::Salome_file_ptr
1923 Abstract_Engines_Container_i::createSalome_file(const char* origFileName)
1925 std::string origName(origFileName);
1926 if (CORBA::is_nil(_Salome_file_map[origName]))
1928 Salome_file_i* aSalome_file = new Salome_file_i();
1929 aSalome_file->setContainer(Engines::Container::_duplicate(this->_this()));
1932 aSalome_file->setLocalFile(origFileName);
1933 aSalome_file->recvFiles();
1935 catch (const SALOME::SALOME_Exception& /*e*/) //!< TODO: unused variable
1937 return Engines::Salome_file::_nil();
1940 Engines::Salome_file_var theSalome_file = Engines::Salome_file::_nil();
1941 theSalome_file = Engines::Salome_file::_narrow(aSalome_file->_this());
1942 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1943 _Salome_file_map[origName] = theSalome_file;
1944 _numInstanceMutex.unlock() ;
1947 Engines::Salome_file_ptr theSalome_file =
1948 Engines::Salome_file::_duplicate(_Salome_file_map[origName]);
1949 ASSERT(!CORBA::is_nil(theSalome_file));
1950 return theSalome_file;
1953 //=============================================================================
1954 /*! \brief copy a file from a remote host (container) to the local host
1955 * \param container the remote container
1956 * \param remoteFile the file to copy locally from the remote host into localFile
1957 * \param localFile the local file
1959 //=============================================================================
1960 void Abstract_Engines_Container_i::copyFile(Engines::Container_ptr container, const char* remoteFile, const char* localFile)
1962 Engines::fileTransfer_var fileTransfer = container->getFileTransfer();
1965 if ((fp = fopen(localFile,"wb")) == NULL)
1967 INFOS("file " << localFile << " cannot be open for writing");
1971 CORBA::Long fileId = fileTransfer->open(remoteFile);
1974 Engines::fileBlock* aBlock;
1981 aBlock = fileTransfer->getBlock(fileId);
1982 toFollow = aBlock->length();
1984 CORBA::Octet *buf = aBlock->get_buffer();
1985 fwrite(buf, sizeof(CORBA::Octet), toFollow, fp);
1989 MESSAGE("end of transfer");
1990 fileTransfer->close(fileId);
1994 INFOS("open reference file for copy impossible");
1998 //=============================================================================
1999 /*! \brief create a PyNode object to execute remote python code
2000 * \param nodeName the name of the node
2001 * \param code the python code to load
2002 * \return the PyNode
2004 //=============================================================================
2005 Engines::PyNode_ptr Abstract_Engines_Container_i::createPyNode(const char* nodeName, const char* code)
2007 Engines::PyNode_var node= Engines::PyNode::_nil();
2012 PyObject *res = PyObject_CallMethod(_pyCont,
2013 (char*)"create_pynode",
2021 SALOME::ExceptionStruct es;
2022 es.type = SALOME::INTERNAL_ERROR;
2023 es.text = "can not create a python node";
2024 throw SALOME::SALOME_Exception(es);
2026 ierr=PyLong_AsLong(PyTuple_GetItem(res,0));
2027 PyObject* result=PyTuple_GetItem(res,1);
2028 astr = PyUnicode_AsUTF8(result);
2033 Utils_Locker lck(&_mutexForDftPy);
2034 CORBA::Object_var obj=_orb->string_to_object(astr.c_str());
2035 node=Engines::PyNode::_narrow(obj);
2036 std::map<std::string,Engines::PyNode_var>::iterator it(_dftPyNode.find(nodeName));
2037 if(it==_dftPyNode.end())
2039 _dftPyNode[nodeName]=node;
2043 Engines::PyNode_var oldNode((*it).second);
2044 if(!CORBA::is_nil(oldNode))
2045 oldNode->UnRegister();
2048 if(!CORBA::is_nil(node))
2050 return node._retn();
2054 SALOME::ExceptionStruct es;
2055 es.type = SALOME::INTERNAL_ERROR;
2056 es.text = astr.c_str();
2057 throw SALOME::SALOME_Exception(es);
2061 //=============================================================================
2062 /*! \brief Retrieves the last created PyNode instance with createPyNode.
2065 //=============================================================================
2066 Engines::PyNode_ptr Abstract_Engines_Container_i::getDefaultPyNode(const char *nodeName)
2068 Utils_Locker lck(&_mutexForDftPy);
2069 std::map<std::string,Engines::PyNode_var>::iterator it(_dftPyNode.find(nodeName));
2070 if(it==_dftPyNode.end())
2071 return Engines::PyNode::_nil();
2074 Engines::PyNode_var tmpVar((*it).second);
2075 if(!CORBA::is_nil(tmpVar))
2076 return Engines::PyNode::_duplicate(tmpVar);
2078 return Engines::PyNode::_nil();
2082 //=============================================================================
2083 /*! \brief create a PyScriptNode object to execute remote python code
2084 * \param nodeName the name of the node
2085 * \param code the python code to load
2086 * \return the PyScriptNode
2088 //=============================================================================
2089 Engines::PyScriptNode_ptr Abstract_Engines_Container_i::createPyScriptNode(const char* nodeName, const char* code)
2091 Engines::PyScriptNode_var node= Engines::PyScriptNode::_nil();
2096 PyObject *res = PyObject_CallMethod(_pyCont,
2097 (char*)"create_pyscriptnode",
2105 SALOME::ExceptionStruct es;
2106 es.type = SALOME::INTERNAL_ERROR;
2107 es.text = "can not create a python node";
2108 throw SALOME::SALOME_Exception(es);
2110 ierr=PyLong_AsLong(PyTuple_GetItem(res,0));
2111 PyObject* result=PyTuple_GetItem(res,1);
2112 astr = PyUnicode_AsUTF8(result);
2118 Utils_Locker lck(&_mutexForDftPy);
2119 CORBA::Object_var obj=_orb->string_to_object(astr.c_str());
2120 node=Engines::PyScriptNode::_narrow(obj);
2121 std::map<std::string,Engines::PyScriptNode_var>::iterator it(_dftPyScriptNode.find(nodeName));
2122 if(it==_dftPyScriptNode.end())
2124 _dftPyScriptNode[nodeName]=node;
2128 Engines::PyScriptNode_var oldNode((*it).second);
2129 if(!CORBA::is_nil(oldNode))
2130 oldNode->UnRegister();
2133 return node._retn();
2137 SALOME::ExceptionStruct es;
2138 es.type = SALOME::INTERNAL_ERROR;
2139 es.text = astr.c_str();
2140 throw SALOME::SALOME_Exception(es);
2144 void Abstract_Engines_Container_i::removePyScriptNode(const char *nodeName)
2146 std::map<std::string,Engines::PyScriptNode_var>::iterator it(_dftPyScriptNode.find(nodeName));
2147 if(it==_dftPyScriptNode.end())
2149 std::ostringstream oss; oss << "Engines_Container_i::removePyScriptNode : node \"" << nodeName << "\" is not map !";
2150 SALOME::ExceptionStruct es;
2151 es.type = SALOME::INTERNAL_ERROR;
2152 es.text = oss.str().c_str();
2153 throw SALOME::SALOME_Exception(es);
2155 (*it).second->UnRegister();
2156 _dftPyScriptNode.erase(it);
2159 void Abstract_Engines_Container_i::cleanAllPyScripts()
2161 for(std::map<std::string,Engines::PyNode_var>::iterator it=_dftPyNode.begin();it!=_dftPyNode.end();it++)
2163 Engines::PyNode_var tmpVar((*it).second);
2164 if(!CORBA::is_nil(tmpVar))
2165 tmpVar->UnRegister();
2168 for(std::map<std::string,Engines::PyScriptNode_var>::iterator it=_dftPyScriptNode.begin();it!=_dftPyScriptNode.end();it++)
2170 Engines::PyScriptNode_var tmpVar((*it).second);
2171 if(!CORBA::is_nil(tmpVar))
2172 tmpVar->UnRegister();
2174 _dftPyScriptNode.clear();
2177 //=============================================================================
2178 /*! \brief Retrieves the last created PyScriptNode instance with createPyScriptNode.
2181 //=============================================================================
2182 Engines::PyScriptNode_ptr Abstract_Engines_Container_i::getDefaultPyScriptNode(const char *nodeName)
2184 Utils_Locker lck(&_mutexForDftPy);
2185 std::map<std::string,Engines::PyScriptNode_var>::iterator it(_dftPyScriptNode.find(nodeName));
2186 if(it==_dftPyScriptNode.end())
2187 return Engines::PyScriptNode::_nil();
2190 Engines::PyScriptNode_var tmpVar((*it).second);
2191 if(!CORBA::is_nil(tmpVar))
2192 return Engines::PyScriptNode::_duplicate(tmpVar);
2194 return Engines::PyScriptNode::_nil();
2198 //=============================================================================
2199 /* int checkifexecutable(const char *filename)
2201 * Return non-zero if the name is an executable file, and
2202 * zero if it is not executable, or if it does not exist.
2204 //=============================================================================
2205 int checkifexecutable(const std::string& filename)
2208 struct stat statinfo;
2210 result = stat(filename.c_str(), &statinfo);
2211 if (result < 0) return 0;
2212 if (!S_ISREG(statinfo.st_mode)) return 0;
2217 if (statinfo.st_uid == geteuid()) return statinfo.st_mode & S_IXUSR;
2218 if (statinfo.st_gid == getegid()) return statinfo.st_mode & S_IXGRP;
2219 return statinfo.st_mode & S_IXOTH;
2224 //=============================================================================
2225 /*! \brief Find a file by searching in a path
2226 * \param filename file name to search
2227 * \param path path to search in
2228 * \param pth the complete file path if found
2229 * \return 1 if found 0 if not
2231 //=============================================================================
2232 int findpathof(const std::string& path, std::string& pth, const std::string& filename)
2234 if ( path.size() == 0 ) return 0;
2236 std::string::size_type offset = 0;
2237 std::string::size_type pos = 0;
2239 struct stat statinfo;
2243 pos = path.find( SEP, offset );
2244 pth = path.substr( offset, pos - offset );
2245 if ( pth.size() > 0 )
2247 if( pth[pth.size()-1] != SLASH ) pth += SLASH;
2249 int result=stat(pth.c_str(), &statinfo);
2250 if(result == 0) found=1;
2252 if (pos == std::string::npos) break;
2258 void Abstract_Engines_Container_i::registerTemporaryFile( const std::string& fileName )
2260 _tmp_files.remove( fileName );
2261 _tmp_files.push_back( fileName );
2264 void Abstract_Engines_Container_i::unregisterTemporaryFile( const std::string& fileName )
2266 _tmp_files.remove( fileName );
2269 void Abstract_Engines_Container_i::clearTemporaryFiles()
2271 std::list<std::string>::const_iterator it;
2272 for ( it = _tmp_files.begin(); it != _tmp_files.end(); ++it ) {
2273 #if defined(WIN32) && defined(UNICODE)
2274 std::wstring aFile = Kernel_Utils::utf8_decode_s(*it);
2275 std::wstring command = (GetFileAttributes(aFile.c_str()) == FILE_ATTRIBUTE_DIRECTORY) ? L"rd /Q \"" : L"del /F /Q \"";
2277 command += L"\" 2>NUL";
2278 _wsystem(command.c_str());
2281 std::string aFile = *it;
2282 std::string command = (GetFileAttributes(aFile.c_str()) == FILE_ATTRIBUTE_DIRECTORY) ? "rd /Q \"" : "del /F /Q \"";
2284 command += "\" 2>NUL";
2286 std::string command = "rm -rf ";
2289 system(command.c_str());
2295 static Engines_Container_SSL_i *_container_singleton_ssl = nullptr;
2297 static Engines::Container_var _container_ref_singleton_ssl;
2299 Engines_Container_SSL_i *KERNEL::getContainerSA()
2301 if(!_container_singleton_ssl)
2303 CORBA::ORB_var orb = KERNEL::GetRefToORB();
2304 CORBA::Object_var obj = orb->resolve_initial_references("RootPOA");
2305 PortableServer::POA_var poa = PortableServer::POA::_narrow(obj);
2306 PortableServer::POAManager_var pman = poa->the_POAManager();
2307 CORBA::PolicyList policies;
2310 char *argv[4] = {"Container","FactoryServer","toto",nullptr};
2311 SALOME_Fake_NamingService ns;
2312 _container_singleton_ssl = new Engines_Container_SSL_i(orb,poa,"FactoryServer",2,argv,&ns,false);
2313 PortableServer::ObjectId * cont_id = _container_singleton_ssl->getCORBAId();
2315 CORBA::Object_var zeRef = poa->id_to_reference(*cont_id);
2316 _container_ref_singleton_ssl = Engines::Container::_narrow(zeRef);
2318 return _container_singleton_ssl;
2321 Engines::Container_var KERNEL::getContainerRefSA()
2324 return _container_ref_singleton_ssl;