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>
46 #include "utilities.h"
47 #include <SALOMEconfig.h>
48 #include CORBA_SERVER_HEADER(SALOME_Component)
49 #include CORBA_SERVER_HEADER(SALOME_Exception)
50 #include <pthread.h> // must be before Python.h !
52 #include "SALOME_Container_i.hxx"
53 #include "SALOME_Component_i.hxx"
54 #include "SALOME_FileRef_i.hxx"
55 #include "SALOME_FileTransfer_i.hxx"
56 #include "Salome_file_i.hxx"
57 #include "SALOME_NamingService.hxx"
58 #include "SALOME_Fake_NamingService.hxx"
59 #include "SALOME_Embedded_NamingService_Client.hxx"
60 #include "SALOME_Embedded_NamingService.hxx"
61 #include "Basics_Utils.hxx"
68 #include <structmember.h>
69 #include "Container_init_python.hxx"
70 #ifdef BOS26455_WITH_BOOST_PYTHON
71 #include <boost/python.hpp>
74 bool _Sleeping = false ;
76 // // Needed by multi-threaded Python --- Supervision
80 extern "C" {void ActSigIntHandler() ; }
82 extern "C" {void SigIntHandler(int, siginfo_t *, void *) ; }
84 extern "C" {void SigIntHandler( int ) ; }
90 #define ENGINESO "Engine.dylib"
92 #define ENGINESO "Engine.so"
96 #define ENGINESO "Engine.dll"
107 std::map<std::string, int> Abstract_Engines_Container_i::_cntInstances_map;
108 std::map<std::string, void *> Abstract_Engines_Container_i::_library_map;
109 std::map<std::string, void *> Abstract_Engines_Container_i::_toRemove_map;
110 omni_mutex Abstract_Engines_Container_i::_numInstanceMutex ;
112 static PyObject* _pyCont;
114 int checkifexecutable(const std::string&);
115 int findpathof(const std::string& path, std::string&, const std::string&);
117 /*! \class Engines_Container_i
118 * \brief C++ implementation of Engines::Container interface
123 //=============================================================================
125 * Default constructor, not for use
127 //=============================================================================
129 Abstract_Engines_Container_i::Abstract_Engines_Container_i () :
130 _NS(nullptr),_id(nullptr),_numInstance(0)
134 //=============================================================================
138 //=============================================================================
140 Abstract_Engines_Container_i::Abstract_Engines_Container_i (CORBA::ORB_ptr orb,
141 PortableServer::POA_ptr poa,
142 char *containerName ,
143 int argc , char* argv[],
144 SALOME_NamingService_Container_Abstract *ns,
145 bool isServantAloneInProcess
147 _NS(nullptr),_id(0),_numInstance(0),_isServantAloneInProcess(isServantAloneInProcess)
149 _pid = (long)getpid();
157 std::string hostname = Kernel_Utils::GetHostname();
159 MESSAGE(hostname << " " << getpid() <<
160 " Engines_Container_i starting argc " <<
161 _argc << " Thread " << pthread_self() ) ;
163 MESSAGE(hostname << " " << _getpid() <<
164 " Engines_Container_i starting argc " << _argc<< " Thread " << pthread_self().p ) ;
170 MESSAGE(" argv" << i << " " << _argv[ i ]) ;
176 INFOS("SALOME_Container usage : SALOME_Container ServerName");
180 _isSupervContainer = false;
182 _orb = CORBA::ORB::_duplicate(orb) ;
183 _poa = PortableServer::POA::_duplicate(poa) ;
185 // Pour les containers paralleles: il ne faut pas enregistrer et activer
186 // le container generique, mais le container specialise
189 _id = _poa->activate_object(this);
190 // key point : if ns is nullptr : this servant is alone in its process
191 // if ns is not null : this servant embedded into single process.
192 _NS = ns==nullptr ? new SALOME_NamingService : ns->clone();
193 _NS->init_orb( _orb ) ;
194 CORBA::Object_var obj=_poa->id_to_reference(*_id);
195 Engines::Container_var pCont = Engines::Container::_narrow(obj);
198 _containerName = SALOME_NamingService_Abstract::BuildContainerNameForNS(containerName, hostname.c_str());
199 SCRUTE(_containerName);
200 _NS->Register(pCont, _containerName.c_str());
201 MESSAGE("Engines_Container_i::Engines_Container_i : Container name " << _containerName);
204 // import SALOME_Container
205 // pycont = SALOME_Container.SALOME_Container_i(containerIORStr)
207 CORBA::String_var sior = _orb->object_to_string(pCont);
208 std::string myCommand="pyCont = SALOME_Container.SALOME_Container_i('";
209 myCommand += _containerName + "','";
214 //[RNV]: Comment the PyEval_AcquireLock() and PyEval_ReleaseLock() because this
215 //approach leads to the deadlock of the main thread of the application on Windows platform
216 //in case if cppContainer runs in the standalone mode. The problem with the PyThreadState
217 //described by ABN seems not reproduced, to be checked carefully later...
218 PyGILState_STATE gstate = PyGILState_Ensure();
220 //// [ABN]: using the PyGILState* API here is unstable. omniORB logic is invoked
221 //// by the Python code executed below, and in some (random) cases, the Python code
222 //// execution ends with a PyThreadState which was not the one we have here.
223 //// (TODO: understand why ...)
224 //// To be on the safe side we get and load the thread state ourselves:
225 //PyEval_AcquireLock(); // get GIL
226 //PyThreadState * mainThreadState = PyThreadState_Get();
227 //PyThreadState_Swap(mainThreadState);
230 // mpv: this is temporary solution: there is a unregular crash if not
233 // first element is the path to Registry.dll, but it's wrong
234 PyRun_SimpleString("import sys\n");
235 PyRun_SimpleString("sys.path = sys.path[1:]\n");
237 PyRun_SimpleString("import SALOME_Container\n");
238 PyRun_SimpleString((char*)myCommand.c_str());
239 PyObject *mainmod = PyImport_AddModule("__main__");
240 PyObject *globals = PyModule_GetDict(mainmod);
241 _pyCont = PyDict_GetItemString(globals, "pyCont");
243 //PyThreadState_Swap(NULL);
244 //PyEval_ReleaseLock();
245 PyGILState_Release(gstate);
247 fileTransfer_i* aFileTransfer = new fileTransfer_i();
248 CORBA::Object_var obref=aFileTransfer->_this();
249 _fileTransfer = Engines::fileTransfer::_narrow(obref);
250 aFileTransfer->_remove_ref();
254 //=============================================================================
258 //=============================================================================
260 Abstract_Engines_Container_i::~Abstract_Engines_Container_i()
262 MESSAGE("Abstract_Container_i::~Abstract_Container_i()");
270 //=============================================================================
271 //! Get container name
273 * CORBA attribute: Container name (see constructor)
275 //=============================================================================
277 char* Abstract_Engines_Container_i::name()
279 return CORBA::string_dup(_containerName.c_str()) ;
282 //=============================================================================
283 //! Get container working directory
285 * CORBA attribute: Container working directory
287 //=============================================================================
289 char* Abstract_Engines_Container_i::workingdir()
293 return CORBA::string_dup(wd) ;
296 //=============================================================================
297 //! Get container log file name
299 * CORBA attribute: Container log file name
301 //=============================================================================
303 char* Abstract_Engines_Container_i::logfilename()
305 return CORBA::string_dup(_logfilename.c_str()) ;
308 //! Set container log file name
309 void Abstract_Engines_Container_i::logfilename(const char* name)
314 //=============================================================================
315 //! Get container host name
317 * CORBA method: Get the hostName of the Container (without domain extensions)
319 //=============================================================================
321 char* Abstract_Engines_Container_i::getHostName()
323 std::string s = Kernel_Utils::GetHostname();
324 // MESSAGE("Engines_Container_i::getHostName " << s);
325 return CORBA::string_dup(s.c_str()) ;
328 //=============================================================================
329 //! Get container PID
331 * CORBA method: Get the PID (process identification) of the Container
333 //=============================================================================
335 CORBA::Long Abstract_Engines_Container_i::getPID()
337 return (CORBA::Long)getpid();
340 //=============================================================================
341 //! Ping the servant to check it is still alive
343 * CORBA method: check if servant is still alive
345 //=============================================================================
346 void Abstract_Engines_Container_i::ping()
348 MESSAGE("Engines_Container_i::ping() pid "<< getpid());
351 //=============================================================================
352 //! Get number of CPU cores in the calculation node
354 * CORBA method: get number of CPU cores
356 //=============================================================================
358 CORBA::Long Abstract_Engines_Container_i::getNumberOfCPUCores()
360 PyGILState_STATE gstate = PyGILState_Ensure();
361 PyObject *module = PyImport_ImportModuleNoBlock((char*)"salome_psutil");
362 PyObject *result = PyObject_CallMethod(module,
363 (char*)"getNumberOfCPUCores", NULL);
364 int n = PyLong_AsLong(result);
366 PyGILState_Release(gstate);
368 return (CORBA::Long)n;
371 //=============================================================================
372 //! Get a load of each CPU core in the calculation node
374 * CORBA method: get a load of each CPU core
376 //=============================================================================
386 PyStdOut_dealloc(PyStdOut *self)
392 PyStdOut_write(PyStdOut* self, PyObject* args)
395 if (!PyArg_ParseTuple(args, "s", &c))
398 *(self->out) = *(self->out) + c;
404 static PyMethodDef PyStdOut_methods[] =
406 {"write", (PyCFunction)PyStdOut_write, METH_VARARGS,
407 PyDoc_STR("write(string) -> None")},
408 {0, 0, 0, 0} /* sentinel */
411 static PyMemberDef PyStdOut_memberlist[] =
413 {(char*)"softspace", T_INT, offsetof(PyStdOut, softspace), 0,
414 (char*)"flag indicating that a space needs to be printed; used by print"},
415 {0, 0, 0, 0, 0} /* sentinel */
418 static PyTypeObject PyStdOut_Type =
420 /* The ob_type field must be initialized in the module init function
421 * to be portable to Windows without using C++. */
422 PyVarObject_HEAD_INIT(NULL, 0)
425 sizeof(PyStdOut), /*tp_basicsize*/
428 (destructor)PyStdOut_dealloc, /*tp_dealloc*/
435 0, /*tp_as_sequence*/
440 PyObject_GenericGetAttr, /*tp_getattro*/
441 /* softspace is writable: we must supply tp_setattro */
442 PyObject_GenericSetAttr, /* tp_setattro */
444 Py_TPFLAGS_DEFAULT, /*tp_flags*/
448 0, /*tp_richcompare*/
449 0, /*tp_weaklistoffset*/
452 PyStdOut_methods, /*tp_methods*/
453 PyStdOut_memberlist, /*tp_members*/
471 0, /*tp_version_tag*/
475 PyObject* newPyStdOut(std::string& out)
477 PyStdOut* self = PyObject_New(PyStdOut, &PyStdOut_Type);
482 return (PyObject*)self;
485 std::string parseException()
488 if (PyErr_Occurred())
490 #ifdef BOS26455_WITH_BOOST_PYTHON
491 PyObject *ptype = nullptr;
492 PyObject *pvalue = nullptr;
493 PyObject *ptraceback = nullptr;
494 PyErr_Fetch(&ptype, &pvalue, &ptraceback);
495 if (ptype == nullptr)
496 return std::string("Null exception type");
497 PyErr_NormalizeException(&ptype, &pvalue, &ptraceback);
498 if (ptraceback != nullptr)
499 PyException_SetTraceback(pvalue, ptraceback);
500 boost::python::handle<> htype(ptype);
501 boost::python::handle<> hvalue(boost::python::allow_null(pvalue));
502 boost::python::handle<> htraceback(boost::python::allow_null(ptraceback));
503 boost::python::object traceback = boost::python::import("traceback");
504 boost::python::object format_exc = traceback.attr("format_exception");
505 boost::python::object formatted = format_exc(htype, hvalue, htraceback);
506 error = boost::python::extract<std::string>(boost::python::str("\n").join(formatted));
508 PyObject* new_stderr = newPyStdOut(error);
509 PyObject* old_stderr = PySys_GetObject((char*)"stderr");
510 Py_INCREF(old_stderr);
511 PySys_SetObject((char*)"stderr", new_stderr);
513 PySys_SetObject((char*)"stderr", old_stderr);
514 Py_DECREF(new_stderr);
521 Engines::vectorOfDouble* Abstract_Engines_Container_i::loadOfCPUCores()
523 PyGILState_STATE gstate = PyGILState_Ensure();
524 PyObject *module = PyImport_ImportModuleNoBlock((char*)"salome_psutil");
525 PyObject *result = PyObject_CallMethod(module,
526 (char*)"loadOfCPUCores", "s",
527 _load_script.c_str());
528 if (PyErr_Occurred())
530 std::string error = parseException();
532 PyGILState_Release(gstate);
533 SALOME::ExceptionStruct es;
534 es.type = SALOME::INTERNAL_ERROR;
535 es.text = CORBA::string_dup(error.c_str());
536 throw SALOME::SALOME_Exception(es);
539 int n = this->getNumberOfCPUCores();
540 if (!PyList_Check(result) || PyList_Size(result) != n) {
541 // bad number of cores
542 PyGILState_Release(gstate);
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
558 PyGILState_Release(gstate);
560 SALOME::ExceptionStruct es;
561 es.type = SALOME::INTERNAL_ERROR;
562 es.text = "load not in [0, 1] range";
563 throw SALOME::SALOME_Exception(es);
569 PyGILState_Release(gstate);
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()
608 PyGILState_STATE gstate = PyGILState_Ensure();
609 PyObject *module = PyImport_ImportModuleNoBlock((char*)"salome_psutil");
610 PyObject *result = PyObject_CallMethod(module,
611 (char*)"getTotalPhysicalMemory", NULL);
612 int n = PyLong_AsLong(result);
614 PyGILState_Release(gstate);
616 return (CORBA::Long)n;
619 //=============================================================================
620 //! Get used physical memory of calculation node, in megabytes
622 * CORBA method: get used physical memory of calculation node
624 //=============================================================================
626 CORBA::Long Abstract_Engines_Container_i::getTotalPhysicalMemoryInUse()
628 PyGILState_STATE gstate = PyGILState_Ensure();
629 PyObject *module = PyImport_ImportModuleNoBlock((char*)"salome_psutil");
630 PyObject *result = PyObject_CallMethod(module,
631 (char*)"getTotalPhysicalMemoryInUse", NULL);
632 int n = PyLong_AsLong(result);
634 PyGILState_Release(gstate);
636 return (CORBA::Long)n;
639 //=============================================================================
640 //! Obtain physical memory, used by the current process, in megabytes.
642 * CORBA method: get physical memory, used by the current process
644 //=============================================================================
646 CORBA::Long Abstract_Engines_Container_i::getTotalPhysicalMemoryInUseByMe()
648 PyGILState_STATE gstate = PyGILState_Ensure();
649 PyObject *module = PyImport_ImportModuleNoBlock((char*)"salome_psutil");
650 PyObject *result = PyObject_CallMethod(module,
651 (char*)"getTotalPhysicalMemoryInUseByMe", NULL);
652 int n = PyLong_AsLong(result);
654 PyGILState_Release(gstate);
656 return (CORBA::Long)n;
659 //=============================================================================
660 //! Shutdown the container
662 * CORBA method, oneway: Server shutdown.
663 * - Container name removed from naming service,
664 * - servant deactivation,
665 * - orb shutdown if no other servants in the process
667 //=============================================================================
668 void Abstract_Engines_Container_i::Shutdown()
670 MESSAGE("Engines_Container_i::Shutdown()");
672 // Clear registered temporary files
673 clearTemporaryFiles();
675 /* For each component contained in this container
676 * tell it to self-destroy
678 std::map<std::string, Engines::EngineComponent_var>::iterator itm;
679 for (itm = _listInstances_map.begin(); itm != _listInstances_map.end(); itm++)
683 itm->second->destroy();
685 catch(const CORBA::Exception&)
687 // ignore this entry and continue
691 // ignore this entry and continue
694 _listInstances_map.clear();
696 // NS unregistering may throw in SSL mode if master process hosting SALOME_Embedded_NamingService servant has vanished
697 // In this case it's skip it and still continue.
700 _NS->Destroy_FullDirectory(_containerName.c_str());
701 _NS->Destroy_Name(_containerName.c_str());
707 this->cleanAllPyScripts();
709 if(_isServantAloneInProcess)
711 MESSAGE("Effective Shutdown of container Begins...");
712 if(!CORBA::is_nil(_orb))
717 //=============================================================================
718 //! load a component implementation
721 * \param componentName component name
722 * \param reason explains error when load fails
723 * \return true if dlopen successful or already done, false otherwise
725 //=============================================================================
727 Abstract_Engines_Container_i::load_component_Library(const char* componentName, CORBA::String_out reason)
730 //=================================================================
731 // --- C++ implementation section
732 //=================================================================
734 if(load_component_CppImplementation(componentName,retso))
736 reason=CORBA::string_dup("");
739 else if(retso != "ImplementationNotFound")
741 reason=CORBA::string_dup(retso.c_str());
746 retso+=componentName;
747 retso+=": Can't find C++ implementation ";
748 retso+=std::string(LIB) + componentName + ENGINESO;
750 //=================================================================
751 // --- Python implementation section
752 //=================================================================
754 if(load_component_PythonImplementation(componentName,retpy))
756 reason=CORBA::string_dup("");
759 else if(retpy != "ImplementationNotFound")
761 reason=CORBA::string_dup(retpy.c_str());
766 retpy+=componentName;
767 retpy+=": Can't find python implementation ";
768 retpy+=componentName;
771 //=================================================================
772 // -- Executable implementation section
773 //=================================================================
775 if(load_component_ExecutableImplementation(componentName,retex))
777 reason=CORBA::string_dup("");
780 else if(retex != "ImplementationNotFound")
782 reason=CORBA::string_dup(retex.c_str());
787 retex+=componentName;
788 retex+=": Can't find executable implementation ";
789 retex+=componentName;
792 std::string ret="Component implementation not found: ";
793 ret += componentName ;
799 std::cerr << ret << std::endl;
800 reason=CORBA::string_dup(ret.c_str());
805 //=============================================================================
806 //! try to load a C++ component implementation
809 * \param componentName the name of the component (COMPONENT, for example)
810 * \param reason explains error when load fails
811 * \return true if loading is successful or already done, false otherwise
813 //=============================================================================
815 Abstract_Engines_Container_i::load_component_CppImplementation(const char* componentName, std::string& reason)
817 std::string aCompName(componentName);
818 std::string impl_name = std::string(LIB) + aCompName + ENGINESO;
821 _numInstanceMutex.lock(); // lock to be alone
822 // (see decInstanceCnt, finalize_removal))
823 if (_toRemove_map.count(impl_name) != 0) _toRemove_map.erase(impl_name);
824 if (_library_map.count(impl_name) != 0)
826 MESSAGE("Library " << impl_name << " already loaded");
827 _numInstanceMutex.unlock();
831 _numInstanceMutex.unlock();
835 handle = dlopen( impl_name.c_str() , RTLD_NOW | RTLD_GLOBAL ) ;
838 //not loadable. Try to find the lib file in LD_LIBRARY_PATH
841 char* p=getenv("DYLD_LIBRARY_PATH");
843 char* p=getenv("LD_LIBRARY_PATH");
846 path=path+SEP+"/usr/lib"+SEP+"/lib";
849 if(findpathof(path, pth, impl_name))
851 //found but not loadable
854 reason+=": C++ implementation found ";
856 reason+=" but it is not loadable. Error:\n";
858 std::cerr << reason << std::endl;
864 //continue with other implementation
865 reason="ImplementationNotFound";
872 std::wstring libToLoad = Kernel_Utils::utf8_decode_s( impl_name );
874 std::string libToLoad = impl_name;
876 handle = LoadLibrary(libToLoad.c_str() );
879 reason="ImplementationNotFound";
885 _numInstanceMutex.lock();
886 _library_map[impl_name] = handle;
887 _numInstanceMutex.unlock();
895 //=============================================================================
896 //! try to load a Python component implementation
899 * \param componentName name of the component
900 * \param reason explains error when load fails
901 * \return true if loading is successful or already done, false otherwise
903 //=============================================================================
905 Abstract_Engines_Container_i::load_component_PythonImplementation(const char* componentName, std::string& reason)
907 std::string aCompName(componentName);
909 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
910 if (_library_map.count(aCompName) != 0)
912 _numInstanceMutex.unlock() ;
914 return true; // Python Component, already imported
916 _numInstanceMutex.unlock() ;
918 PyGILState_STATE gstate = PyGILState_Ensure();
919 PyObject *result = PyObject_CallMethod(_pyCont,
920 (char*)"import_component",
921 (char*)"s",componentName);
923 reason=PyUnicode_AsUTF8(result);
926 PyGILState_Release(gstate);
930 //Python component has been loaded (import componentName)
931 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
932 _library_map[aCompName] = (void *)_pyCont; // any non O value OK
933 _numInstanceMutex.unlock() ;
934 MESSAGE("import Python: "<< aCompName <<" OK");
937 else if(reason=="ImplementationNotFound")
939 //Python implementation has not been found. Continue with other implementation
940 reason="ImplementationNotFound";
944 //Python implementation has been found but loading has failed
945 std::cerr << reason << std::endl;
950 //=============================================================================
951 //! try to load a Executable component implementation
954 * \param componentName name of the component
955 * \param reason explains error when load fails
956 * \return true if loading is successful or already done, false otherwise
958 //=============================================================================
960 Abstract_Engines_Container_i::load_component_ExecutableImplementation(const char* componentName, std::string& reason)
962 std::string aCompName(componentName);
963 std::string executable=aCompName+".exe";
968 char* p=getenv("PATH");
971 if (findpathof(path, pth, executable))
973 if(checkifexecutable(pth))
975 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
976 _library_map[executable] = (void *)1; // any non O value OK
977 _numInstanceMutex.unlock() ;
978 MESSAGE("import executable: "<< pth <<" OK");
984 reason+=": implementation found ";
986 reason+=" but it is not executable";
987 std::cerr << reason << std::endl;
991 reason="ImplementationNotFound";
996 //=============================================================================
997 //! Create a new component instance
999 * CORBA method: Creates a new servant instance of a component.
1000 * The servant registers itself to naming service and Registry.
1001 * \param genericRegisterName Name of the component instance to register
1002 * in Registry & Name Service (without _inst_n suffix)
1003 * \return a loaded component
1005 //=============================================================================
1006 Engines::EngineComponent_ptr
1007 Abstract_Engines_Container_i::create_component_instance(const char*genericRegisterName)
1009 Engines::FieldsDict_var env = new Engines::FieldsDict;
1011 Engines::EngineComponent_ptr compo =
1012 create_component_instance_env(genericRegisterName, env, reason);
1013 CORBA::string_free(reason);
1017 //=============================================================================
1018 //! Create a new component instance with environment variables specified
1020 * CORBA method: Creates a new servant instance of a component.
1021 * The servant registers itself to naming service and Registry.
1022 * \param genericRegisterName Name of the component instance to register
1023 * in Registry & Name Service (without _inst_n suffix)
1024 * \param env dict of env variables
1025 * \param reason explains error when create_component_instance_env fails
1026 * \return a loaded component
1028 //=============================================================================
1029 Engines::EngineComponent_ptr
1030 Abstract_Engines_Container_i::create_component_instance_env(const char*genericRegisterName,
1031 const Engines::FieldsDict& env,
1032 CORBA::String_out reason)
1035 if (_library_map.count(genericRegisterName) != 0)
1037 // It's a Python component
1038 Engines::EngineComponent_ptr compo = createPythonInstance(genericRegisterName, error);
1039 reason=CORBA::string_dup(error.c_str());
1043 std::string impl_name = std::string(LIB) + genericRegisterName + ENGINESO;
1044 if (_library_map.count(impl_name) != 0)
1046 // It's a C++ component
1047 void* handle = _library_map[impl_name];
1048 Engines::EngineComponent_ptr compo = createInstance(genericRegisterName, handle, error);
1049 reason=CORBA::string_dup(error.c_str());
1053 impl_name = std::string(genericRegisterName) + ".exe";
1054 if (_library_map.count(impl_name) != 0)
1056 //It's an executable component
1057 Engines::EngineComponent_ptr compo = createExecutableInstance(genericRegisterName, env, error);
1058 reason=CORBA::string_dup(error.c_str());
1062 error="load_component_Library has probably not been called for component: ";
1063 error += genericRegisterName;
1065 reason=CORBA::string_dup(error.c_str());
1066 return Engines::EngineComponent::_nil() ;
1069 //=============================================================================
1070 //! Create a new component instance (Executable implementation)
1072 * \param CompName Name of the component instance
1073 * \param env dict of env variables
1074 * \param reason explains error when creation fails
1075 * \return a loaded component
1077 * This component is implemented in an executable with name genericRegisterName.exe
1078 * It must register itself in Naming Service. The container waits some time (10 s max)
1079 * it's registration.
1081 //=============================================================================
1082 Engines::EngineComponent_ptr
1083 Abstract_Engines_Container_i::createExecutableInstance(std::string CompName,
1084 const Engines::FieldsDict& env,
1085 std::string& reason)
1087 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1089 _numInstanceMutex.lock() ; // lock on the instance number
1091 int numInstance = _numInstance ;
1092 _numInstanceMutex.unlock() ;
1095 sprintf( aNumI , "%d" , numInstance ) ;
1096 std::string instanceName = CompName + "_inst_" + aNumI ;
1097 std::string component_registerName = _containerName + "/" + instanceName;
1099 //check if an entry exist in naming service
1100 CORBA::Object_var nsobj = _NS->Resolve(component_registerName.c_str());
1101 if ( !CORBA::is_nil(nsobj) )
1103 // unregister the registered component
1104 _NS->Destroy_Name(component_registerName.c_str());
1105 //kill or shutdown it ???
1108 // first arg container ior string
1109 // second arg container name
1110 // third arg instance name
1112 Engines::Container_var pCont= _this();
1113 CORBA::String_var sior = _orb->object_to_string(pCont);
1115 std::string command;
1116 command="mkdir -p ";
1117 command+=instanceName;
1119 command+=instanceName;
1124 command+= sior; // container ior string
1126 command+=_containerName; //container name
1128 command+=instanceName; //instance name
1130 MESSAGE("SALOME_Container::create_component_instance command=" << command);
1133 // use fork/execl instead of system to get finer control on env variables
1136 if(pid == 0) // child
1138 for (CORBA::ULong i=0; i < env.length(); i++)
1140 if (env[i].value.type()->kind() == CORBA::tk_string)
1143 env[i].value >>= value;
1144 std::string s(env[i].key);
1147 putenv(strdup(s.c_str()));
1151 execl("/bin/sh", "sh", "-c", command.c_str() , (char *)0);
1154 else if(pid < 0) // failed to fork
1163 tpid = wait(&status);
1164 } while (tpid != pid);
1167 // launch component with a system call
1168 int status=system(command.c_str());
1173 reason="SALOME_Container::create_component_instance system failed (system command status -1)";
1175 return Engines::EngineComponent::_nil();
1178 else if (WEXITSTATUS(status) == 217)
1180 reason="SALOME_Container::create_component_instance system failed (system command status 217)";
1182 return Engines::EngineComponent::_nil();
1188 if (getenv("TIMEOUT_TO_WAIT_EXE_COMPONENT") != 0)
1190 std::string new_count_str = getenv("TIMEOUT_TO_WAIT_EXE_COMPONENT");
1192 std::istringstream ss(new_count_str);
1193 if (!(ss >> new_count))
1195 INFOS("[Container] TIMEOUT_TO_WAIT_EXE_COMPONENT should be an int");
1200 INFOS("[Container] waiting " << count << " second steps exe component ");
1201 CORBA::Object_var obj = CORBA::Object::_nil() ;
1202 while ( CORBA::is_nil(obj) && count )
1210 MESSAGE( count << ". Waiting for component " << CompName);
1211 obj = _NS->Resolve(component_registerName.c_str());
1214 if(CORBA::is_nil(obj))
1216 reason="SALOME_Container::create_component_instance failed";
1218 return Engines::EngineComponent::_nil();
1222 MESSAGE("SALOME_Container::create_component_instance successful");
1223 iobject = Engines::EngineComponent::_narrow(obj);
1224 _listInstances_map[instanceName] = iobject;
1225 return iobject._retn();
1231 //=============================================================================
1232 //! Create a new component instance (Python implementation)
1234 * \param CompName Name of the component instance
1235 * \param reason explains error when creation fails
1236 * \return a loaded component
1238 //=============================================================================
1239 Engines::EngineComponent_ptr
1240 Abstract_Engines_Container_i::createPythonInstance(std::string CompName,
1241 std::string& reason)
1243 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1245 _numInstanceMutex.lock() ; // lock on the instance number
1247 int numInstance = _numInstance ;
1248 _numInstanceMutex.unlock() ;
1251 sprintf( aNumI , "%d" , numInstance ) ;
1252 std::string instanceName = CompName + "_inst_" + aNumI ;
1253 std::string component_registerName = _containerName + "/" + instanceName;
1255 PyGILState_STATE gstate = PyGILState_Ensure();
1256 PyObject *result = PyObject_CallMethod(_pyCont,
1257 (char*)"create_component_instance",
1260 instanceName.c_str());
1263 PyArg_ParseTuple(result,"ss", &ior, &error);
1264 std::string iors = ior;
1267 PyGILState_Release(gstate);
1271 CORBA::Object_var obj = _orb->string_to_object(iors.c_str());
1272 iobject = Engines::EngineComponent::_narrow( obj ) ;
1273 _listInstances_map[instanceName] = iobject;
1275 return iobject._retn();
1279 Abstract_Engines_Container_i::create_python_service_instance(const char * CompName,
1280 CORBA::String_out reason)
1282 CORBA::Object_var object = CORBA::Object::_nil();
1284 _numInstanceMutex.lock() ; // lock on the instance number
1286 int numInstance = _numInstance ;
1287 _numInstanceMutex.unlock() ;
1290 sprintf( aNumI , "%d" , numInstance ) ;
1291 std::string instanceName = std::string(CompName) + "_inst_" + aNumI ;
1292 std::string component_registerName = _containerName + "/" + instanceName;
1294 PyGILState_STATE gstate = PyGILState_Ensure();
1295 PyObject *result = PyObject_CallMethod(_pyCont,
1296 (char*)"create_component_instance",
1299 instanceName.c_str());
1302 PyArg_ParseTuple(result,"ss", &ior, &error);
1303 reason = CORBA::string_dup(error);
1304 char * _ior = CORBA::string_dup(ior);
1306 PyGILState_Release(gstate);
1312 //=============================================================================
1313 //! Create a new component instance (C++ implementation)
1315 * C++ method: create a servant instance of a component.
1316 * \param genericRegisterName Name of the component instance to register
1317 * in Registry & Name Service,
1318 * (without _inst_n suffix, like "COMPONENT")
1319 * \param handle loaded library handle
1320 * \param reason explains error when creation fails
1321 * \return a loaded component
1323 * example with names:
1324 * - aGenRegisterName = COMPONENT (= first argument)
1325 * - _containerName = /Containers/cli76ce/FactoryServer
1326 * - factoryName = COMPONENTEngine_factory
1327 * - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
1328 * - instanceName = COMPONENT_inst_1
1329 * - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1331 //=============================================================================
1332 Engines::EngineComponent_ptr
1333 Abstract_Engines_Container_i::createInstance(std::string genericRegisterName,
1335 std::string& reason)
1337 // --- find the factory
1339 std::string aGenRegisterName = genericRegisterName;
1340 std::string factory_name = aGenRegisterName + std::string("Engine_factory");
1341 SCRUTE(factory_name) ;
1343 typedef PortableServer::ObjectId* (*FACTORY_FUNCTION) (CORBA::ORB_ptr,
1344 PortableServer::POA_ptr,
1345 PortableServer::ObjectId *,
1350 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)dlsym( handle, factory_name.c_str() );
1352 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)GetProcAddress( (HINSTANCE)handle, factory_name.c_str() );
1355 if ( !Component_factory )
1357 MESSAGE( "Can't resolve symbol: " + factory_name );
1362 return Engines::EngineComponent::_nil() ;
1365 // --- create instance
1367 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1371 _numInstanceMutex.lock() ; // lock on the instance number
1373 int numInstance = _numInstance ;
1374 _numInstanceMutex.unlock() ;
1377 sprintf( aNumI , "%d" , numInstance ) ;
1378 std::string instanceName = aGenRegisterName + "_inst_" + aNumI ;
1379 std::string component_registerName =
1380 _containerName + "/" + instanceName;
1382 // --- Instantiate required CORBA object
1384 PortableServer::ObjectId *id ; //not owner, do not delete (nore use var)
1385 id = (Component_factory) ( _orb, _poa, _id, instanceName.c_str(),
1386 aGenRegisterName.c_str() ) ;
1389 reason="Can't get ObjectId from factory";
1391 return iobject._retn();
1394 // --- get reference from id
1396 CORBA::Object_var obj = _poa->id_to_reference(*id);
1397 iobject = Engines::EngineComponent::_narrow( obj ) ;
1399 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1400 _listInstances_map[instanceName] = iobject;
1401 _cntInstances_map[aGenRegisterName] += 1;
1402 _numInstanceMutex.unlock() ;
1403 SCRUTE(aGenRegisterName);
1404 SCRUTE(_cntInstances_map[aGenRegisterName]);
1406 // --- register the engine under the name
1407 // containerName(.dir)/instanceName(.object)
1409 _NS->Register( iobject , component_registerName.c_str() ) ;
1410 MESSAGE( component_registerName.c_str() << " bound" ) ;
1414 reason="Container_i::createInstance exception caught";
1417 return iobject._retn();
1420 //=============================================================================
1421 //! Find an existing (in the container) component instance
1423 * CORBA method: Finds a servant instance of a component
1424 * \param registeredName Name of the component in Registry or Name Service,
1425 * without instance suffix number
1426 * \return the first found instance
1428 //=============================================================================
1429 Engines::EngineComponent_ptr
1430 Abstract_Engines_Container_i::find_component_instance( const char* registeredName)
1432 Engines::EngineComponent_var anEngine = Engines::EngineComponent::_nil();
1433 std::map<std::string,Engines::EngineComponent_var>::iterator itm =_listInstances_map.begin();
1434 while (itm != _listInstances_map.end())
1436 std::string instance = (*itm).first;
1438 if (instance.find(registeredName) == 0)
1440 anEngine = (*itm).second;
1441 return anEngine._retn();
1445 return anEngine._retn();
1448 //=============================================================================
1449 //! Remove the component instance from container
1451 * CORBA method: Stops the component servant, and deletes all related objects
1452 * \param component_i Component to be removed
1454 //=============================================================================
1456 void Abstract_Engines_Container_i::remove_impl(Engines::EngineComponent_ptr component_i)
1458 ASSERT(! CORBA::is_nil(component_i));
1459 std::string instanceName = component_i->instanceName() ;
1460 MESSAGE("unload component " << instanceName);
1461 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1462 _listInstances_map.erase(instanceName);
1463 _numInstanceMutex.unlock() ;
1464 component_i->destroy() ;
1465 _NS->Destroy_Name(instanceName.c_str());
1468 //=============================================================================
1469 //! Unload component libraries from the container
1471 * CORBA method: Discharges unused libraries from the container.
1473 //=============================================================================
1474 void Abstract_Engines_Container_i::finalize_removal()
1476 MESSAGE("finalize unload : dlclose");
1477 _numInstanceMutex.lock(); // lock to be alone
1478 // (see decInstanceCnt, load_component_Library)
1479 std::map<std::string, void *>::iterator ith;
1480 for (ith = _toRemove_map.begin(); ith != _toRemove_map.end(); ith++)
1482 void *handle = (*ith).second;
1483 std::string impl_name= (*ith).first;
1488 // dlclose(handle); // SALOME unstable after ...
1489 // _library_map.erase(impl_name);
1492 _toRemove_map.clear();
1493 _numInstanceMutex.unlock();
1496 //=============================================================================
1497 //! Decrement component instance reference count
1501 //=============================================================================
1502 void Abstract_Engines_Container_i::decInstanceCnt(std::string genericRegisterName)
1504 if(_cntInstances_map.count(genericRegisterName)==0)
1506 std::string aGenRegisterName =genericRegisterName;
1507 MESSAGE("Engines_Container_i::decInstanceCnt " << aGenRegisterName);
1508 ASSERT(_cntInstances_map[aGenRegisterName] > 0);
1509 _numInstanceMutex.lock(); // lock to be alone
1510 // (see finalize_removal, load_component_Library)
1511 _cntInstances_map[aGenRegisterName] -= 1;
1512 SCRUTE(_cntInstances_map[aGenRegisterName]);
1513 if (_cntInstances_map[aGenRegisterName] == 0)
1515 std::string impl_name =
1516 Engines_Component_i::GetDynLibraryName(aGenRegisterName.c_str());
1518 void* handle = _library_map[impl_name];
1520 _toRemove_map[impl_name] = handle;
1522 _numInstanceMutex.unlock();
1525 //=============================================================================
1526 //! Find or create a new component instance
1528 * CORBA method: find or create an instance of the component (servant),
1529 * load a new component class (dynamic library) if required,
1531 * ---- FOR COMPATIBILITY WITH 2.2 ----
1533 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
1535 * The servant registers itself to naming service and Registry.
1536 * \param genericRegisterName Name of the component to register
1537 * in Registry & Name Service
1538 * \param componentName Name of the constructed library of the component
1539 * \return a loaded component
1541 //=============================================================================
1543 Engines::EngineComponent_ptr
1544 Abstract_Engines_Container_i::load_impl( const char* genericRegisterName,
1545 const char* /*componentName*/ )
1548 std::string impl_name = std::string(LIB) + genericRegisterName + ENGINESO;
1549 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1550 if (load_component_Library(genericRegisterName,reason))
1551 iobject = find_or_create_instance(genericRegisterName, impl_name);
1552 CORBA::string_free(reason);
1553 return iobject._retn();
1556 Engines::EmbeddedNamingService_ptr Abstract_Engines_Container_i::get_embedded_NS_if_ssl()
1558 SALOME_Embedded_NamingService_Client *nsc(dynamic_cast<SALOME_Embedded_NamingService_Client *>(this->_NS));
1561 Engines::EmbeddedNamingService_var obj = nsc->GetObject();
1562 return Engines::EmbeddedNamingService::_duplicate(obj);
1566 SALOME_Fake_NamingService *fns(dynamic_cast<SALOME_Fake_NamingService *>(this->_NS));
1569 Engines::EmbeddedNamingService_var ret = GetEmbeddedNamingService();
1573 return Engines::EmbeddedNamingService::_nil();
1577 //=============================================================================
1578 //! Finds an already existing component instance or create a new instance
1580 * C++ method: Finds an already existing servant instance of a component, or
1581 * create an instance.
1582 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
1583 * \param genericRegisterName Name of the component instance to register
1584 * in Registry & Name Service,
1585 * (without _inst_n suffix, like "COMPONENT")
1586 * \param componentLibraryName like "libCOMPONENTEngine.so"
1587 * \return a loaded component
1589 * example with names:
1590 * - aGenRegisterName = COMPONENT (= first argument)
1591 * - impl_name = libCOMPONENTEngine.so (= second argument)
1592 * - _containerName = /Containers/cli76ce/FactoryServer
1593 * - factoryName = COMPONENTEngine_factory
1594 * - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
1595 * - instanceName = COMPONENT_inst_1
1596 * - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1598 //=============================================================================
1600 Engines::EngineComponent_ptr
1601 Abstract_Engines_Container_i::find_or_create_instance(std::string genericRegisterName,
1602 std::string componentLibraryName)
1604 std::string aGenRegisterName = genericRegisterName;
1605 std::string impl_name = componentLibraryName;
1606 if (_library_map.count(impl_name) == 0)
1608 INFOS("shared library " << impl_name <<" must be loaded before creating instance");
1609 return Engines::EngineComponent::_nil() ;
1613 // --- find a registered instance in naming service, or create
1615 void* handle = _library_map[impl_name];
1616 std::string component_registerBase =
1617 _containerName + "/" + aGenRegisterName;
1618 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1622 CORBA::Object_var obj =
1623 _NS->ResolveFirst( component_registerBase.c_str());
1624 if ( CORBA::is_nil( obj ) )
1626 iobject = createInstance(genericRegisterName,
1632 iobject = Engines::EngineComponent::_narrow( obj ) ;
1637 INFOS( "Container_i::load_impl caught" ) ;
1639 return iobject._retn();
1643 //=============================================================================
1644 //! Indicate if container is a python one
1646 * Retrieves only with container naming convention if it is a python container
1648 //=============================================================================
1649 bool Abstract_Engines_Container_i::isPythonContainer(const char* ContainerName)
1652 size_t len=strlen(ContainerName);
1654 if(strcmp(ContainerName+len-2,"Py")==0)
1659 //=============================================================================
1660 //! Kill the container
1662 * CORBA method: Kill the container process with exit(0).
1663 * To remove : never returns !
1665 //=============================================================================
1666 bool Abstract_Engines_Container_i::Kill_impl()
1668 MESSAGE("Engines_Container_i::Kill() pid "<< getpid() << " containerName "
1669 << _containerName.c_str() << " machineName "
1670 << Kernel_Utils::GetHostname().c_str());
1671 INFOS("===============================================================");
1672 INFOS("= REMOVE calls to Kill_impl in C++ container =");
1673 INFOS("===============================================================");
1679 //=============================================================================
1683 //=============================================================================
1684 void ActSigIntHandler()
1687 struct sigaction SigIntAct ;
1688 SigIntAct.sa_sigaction = &SigIntHandler ;
1689 sigemptyset(&SigIntAct.sa_mask);
1690 SigIntAct.sa_flags = SA_SIGINFO ;
1693 // DEBUG 03.02.2005 : the first parameter of sigaction is not a mask of signals
1694 // (SIGINT | SIGUSR1) :
1695 // it must be only one signal ===> one call for SIGINT
1696 // and an other one for SIGUSR1
1699 if ( sigaction( SIGINT , &SigIntAct, NULL ) )
1701 perror("SALOME_Container main ") ;
1704 if ( sigaction( SIGUSR1 , &SigIntAct, NULL ) )
1706 perror("SALOME_Container main ") ;
1709 if ( sigaction( SIGUSR2 , &SigIntAct, NULL ) )
1711 perror("SALOME_Container main ") ;
1715 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1716 // use of streams (and so on) should never be used because :
1717 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1718 // A stream operation may be interrupted by a signal and if the Handler use stream we
1719 // may have a "Dead-Lock" ===HangUp
1720 //==INFOS is commented
1721 // INFOS(pthread_self() << "SigIntHandler activated") ;
1724 signal( SIGINT, SigIntHandler );
1725 // legacy code required to supervisor. Commented in order to avoid problems on Windows
1726 // signal( SIGUSR1, SigIntHandler );
1732 void CallCancelThread() ;
1735 void SigIntHandler(int /*what*/ ,
1736 siginfo_t * siginfo ,
1739 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1740 // use of streams (and so on) should never be used because :
1741 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1742 // A stream operation may be interrupted by a signal and if the Handler use stream we
1743 // may have a "Dead-Lock" ===HangUp
1744 //==MESSAGE is commented
1745 // MESSAGE(pthread_self() << "SigIntHandler what " << what << std::endl
1746 // << " si_signo " << siginfo->si_signo << std::endl
1747 // << " si_code " << siginfo->si_code << std::endl
1748 // << " si_pid " << siginfo->si_pid) ;
1753 // MESSAGE("SigIntHandler END sleeping.") ;
1758 ActSigIntHandler() ;
1759 if ( siginfo->si_signo == SIGUSR1 )
1763 else if ( siginfo->si_signo == SIGUSR2 )
1765 CallCancelThread() ;
1770 // MESSAGE("SigIntHandler BEGIN sleeping.") ;
1777 // MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1783 void SigIntHandler( int what )
1786 MESSAGE( pthread_self() << "SigIntHandler what " << what << std::endl );
1788 MESSAGE( "SigIntHandler what " << what << std::endl );
1793 MESSAGE("SigIntHandler END sleeping.") ;
1798 ActSigIntHandler() ;
1799 if ( what == SIGUSR1 )
1806 MESSAGE("SigIntHandler BEGIN sleeping.") ;
1813 MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1820 //=============================================================================
1821 //! Get or create a file reference object associated to a local file (to transfer it)
1823 * CORBA method: get or create a fileRef object associated to a local file
1824 * (a file on the computer on which runs the container server), which stores
1825 * a list of (machine, localFileName) corresponding to copies already done.
1827 * \param origFileName absolute path for a local file to copy on other
1829 * \return a fileRef object associated to the file.
1831 //=============================================================================
1832 Engines::fileRef_ptr
1833 Abstract_Engines_Container_i::createFileRef(const char* origFileName)
1835 std::string origName(origFileName);
1836 Engines::fileRef_var theFileRef = Engines::fileRef::_nil();
1838 if (origName[0] != '/')
1840 INFOS("path of file to copy must be an absolute path beginning with '/'");
1841 return Engines::fileRef::_nil();
1844 if (CORBA::is_nil(_fileRef_map[origName]))
1846 CORBA::Object_var obj=_poa->id_to_reference(*_id);
1847 Engines::Container_var pCont = Engines::Container::_narrow(obj);
1848 fileRef_i* aFileRef = new fileRef_i(pCont, origFileName);
1849 theFileRef = Engines::fileRef::_narrow(aFileRef->_this());
1850 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1851 _fileRef_map[origName] = theFileRef;
1852 _numInstanceMutex.unlock() ;
1855 theFileRef = Engines::fileRef::_duplicate(_fileRef_map[origName]);
1856 ASSERT(! CORBA::is_nil(theFileRef));
1857 return theFileRef._retn();
1860 //=============================================================================
1861 //! Get a fileTransfer reference
1864 * \return a reference to the fileTransfer object
1866 //=============================================================================
1867 Engines::fileTransfer_ptr
1868 Abstract_Engines_Container_i::getFileTransfer()
1870 Engines::fileTransfer_var aFileTransfer
1871 = Engines::fileTransfer::_duplicate(_fileTransfer);
1872 return aFileTransfer._retn();
1875 //=============================================================================
1876 //! Create a Salome file
1877 //=============================================================================
1878 Engines::Salome_file_ptr
1879 Abstract_Engines_Container_i::createSalome_file(const char* origFileName)
1881 std::string origName(origFileName);
1882 if (CORBA::is_nil(_Salome_file_map[origName]))
1884 Salome_file_i* aSalome_file = new Salome_file_i();
1885 aSalome_file->setContainer(Engines::Container::_duplicate(this->_this()));
1888 aSalome_file->setLocalFile(origFileName);
1889 aSalome_file->recvFiles();
1891 catch (const SALOME::SALOME_Exception& /*e*/) //!< TODO: unused variable
1893 return Engines::Salome_file::_nil();
1896 Engines::Salome_file_var theSalome_file = Engines::Salome_file::_nil();
1897 theSalome_file = Engines::Salome_file::_narrow(aSalome_file->_this());
1898 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1899 _Salome_file_map[origName] = theSalome_file;
1900 _numInstanceMutex.unlock() ;
1903 Engines::Salome_file_ptr theSalome_file =
1904 Engines::Salome_file::_duplicate(_Salome_file_map[origName]);
1905 ASSERT(!CORBA::is_nil(theSalome_file));
1906 return theSalome_file;
1909 //=============================================================================
1910 /*! \brief copy a file from a remote host (container) to the local host
1911 * \param container the remote container
1912 * \param remoteFile the file to copy locally from the remote host into localFile
1913 * \param localFile the local file
1915 //=============================================================================
1916 void Abstract_Engines_Container_i::copyFile(Engines::Container_ptr container, const char* remoteFile, const char* localFile)
1918 Engines::fileTransfer_var fileTransfer = container->getFileTransfer();
1921 if ((fp = fopen(localFile,"wb")) == NULL)
1923 INFOS("file " << localFile << " cannot be open for writing");
1927 CORBA::Long fileId = fileTransfer->open(remoteFile);
1930 Engines::fileBlock* aBlock;
1937 aBlock = fileTransfer->getBlock(fileId);
1938 toFollow = aBlock->length();
1940 CORBA::Octet *buf = aBlock->get_buffer();
1941 fwrite(buf, sizeof(CORBA::Octet), toFollow, fp);
1945 MESSAGE("end of transfer");
1946 fileTransfer->close(fileId);
1950 INFOS("open reference file for copy impossible");
1954 //=============================================================================
1955 /*! \brief create a PyNode object to execute remote python code
1956 * \param nodeName the name of the node
1957 * \param code the python code to load
1958 * \return the PyNode
1960 //=============================================================================
1961 Engines::PyNode_ptr Abstract_Engines_Container_i::createPyNode(const char* nodeName, const char* code)
1963 Engines::PyNode_var node= Engines::PyNode::_nil();
1965 PyGILState_STATE gstate = PyGILState_Ensure();
1966 PyObject *res = PyObject_CallMethod(_pyCont,
1967 (char*)"create_pynode",
1975 PyGILState_Release(gstate);
1976 SALOME::ExceptionStruct es;
1977 es.type = SALOME::INTERNAL_ERROR;
1978 es.text = "can not create a python node";
1979 throw SALOME::SALOME_Exception(es);
1981 long ierr=PyLong_AsLong(PyTuple_GetItem(res,0));
1982 PyObject* result=PyTuple_GetItem(res,1);
1983 std::string astr=PyUnicode_AsUTF8(result);
1985 PyGILState_Release(gstate);
1988 Utils_Locker lck(&_mutexForDftPy);
1989 CORBA::Object_var obj=_orb->string_to_object(astr.c_str());
1990 node=Engines::PyNode::_narrow(obj);
1991 std::map<std::string,Engines::PyNode_var>::iterator it(_dftPyNode.find(nodeName));
1992 if(it==_dftPyNode.end())
1994 _dftPyNode[nodeName]=node;
1998 Engines::PyNode_var oldNode((*it).second);
1999 if(!CORBA::is_nil(oldNode))
2000 oldNode->UnRegister();
2003 if(!CORBA::is_nil(node))
2005 return node._retn();
2009 SALOME::ExceptionStruct es;
2010 es.type = SALOME::INTERNAL_ERROR;
2011 es.text = astr.c_str();
2012 throw SALOME::SALOME_Exception(es);
2016 //=============================================================================
2017 /*! \brief Retrieves the last created PyNode instance with createPyNode.
2020 //=============================================================================
2021 Engines::PyNode_ptr Abstract_Engines_Container_i::getDefaultPyNode(const char *nodeName)
2023 Utils_Locker lck(&_mutexForDftPy);
2024 std::map<std::string,Engines::PyNode_var>::iterator it(_dftPyNode.find(nodeName));
2025 if(it==_dftPyNode.end())
2026 return Engines::PyNode::_nil();
2029 Engines::PyNode_var tmpVar((*it).second);
2030 if(!CORBA::is_nil(tmpVar))
2031 return Engines::PyNode::_duplicate(tmpVar);
2033 return Engines::PyNode::_nil();
2037 //=============================================================================
2038 /*! \brief create a PyScriptNode object to execute remote python code
2039 * \param nodeName the name of the node
2040 * \param code the python code to load
2041 * \return the PyScriptNode
2043 //=============================================================================
2044 Engines::PyScriptNode_ptr Abstract_Engines_Container_i::createPyScriptNode(const char* nodeName, const char* code)
2046 Engines::PyScriptNode_var node= Engines::PyScriptNode::_nil();
2048 PyGILState_STATE gstate = PyGILState_Ensure();
2049 PyObject *res = PyObject_CallMethod(_pyCont,
2050 (char*)"create_pyscriptnode",
2058 PyGILState_Release(gstate);
2059 SALOME::ExceptionStruct es;
2060 es.type = SALOME::INTERNAL_ERROR;
2061 es.text = "can not create a python node";
2062 throw SALOME::SALOME_Exception(es);
2064 long ierr=PyLong_AsLong(PyTuple_GetItem(res,0));
2065 PyObject* result=PyTuple_GetItem(res,1);
2066 std::string astr=PyUnicode_AsUTF8(result);
2068 PyGILState_Release(gstate);
2072 Utils_Locker lck(&_mutexForDftPy);
2073 CORBA::Object_var obj=_orb->string_to_object(astr.c_str());
2074 node=Engines::PyScriptNode::_narrow(obj);
2075 std::map<std::string,Engines::PyScriptNode_var>::iterator it(_dftPyScriptNode.find(nodeName));
2076 if(it==_dftPyScriptNode.end())
2078 _dftPyScriptNode[nodeName]=node;
2082 Engines::PyScriptNode_var oldNode((*it).second);
2083 if(!CORBA::is_nil(oldNode))
2084 oldNode->UnRegister();
2087 return node._retn();
2091 SALOME::ExceptionStruct es;
2092 es.type = SALOME::INTERNAL_ERROR;
2093 es.text = astr.c_str();
2094 throw SALOME::SALOME_Exception(es);
2098 void Abstract_Engines_Container_i::removePyScriptNode(const char *nodeName)
2100 std::map<std::string,Engines::PyScriptNode_var>::iterator it(_dftPyScriptNode.find(nodeName));
2101 if(it==_dftPyScriptNode.end())
2103 std::ostringstream oss; oss << "Engines_Container_i::removePyScriptNode : node \"" << nodeName << "\" is not map !";
2104 SALOME::ExceptionStruct es;
2105 es.type = SALOME::INTERNAL_ERROR;
2106 es.text = oss.str().c_str();
2107 throw SALOME::SALOME_Exception(es);
2109 (*it).second->UnRegister();
2110 _dftPyScriptNode.erase(it);
2113 void Abstract_Engines_Container_i::cleanAllPyScripts()
2115 for(std::map<std::string,Engines::PyNode_var>::iterator it=_dftPyNode.begin();it!=_dftPyNode.end();it++)
2117 Engines::PyNode_var tmpVar((*it).second);
2118 if(!CORBA::is_nil(tmpVar))
2119 tmpVar->UnRegister();
2122 for(std::map<std::string,Engines::PyScriptNode_var>::iterator it=_dftPyScriptNode.begin();it!=_dftPyScriptNode.end();it++)
2124 Engines::PyScriptNode_var tmpVar((*it).second);
2125 if(!CORBA::is_nil(tmpVar))
2126 tmpVar->UnRegister();
2128 _dftPyScriptNode.clear();
2131 //=============================================================================
2132 /*! \brief Retrieves the last created PyScriptNode instance with createPyScriptNode.
2135 //=============================================================================
2136 Engines::PyScriptNode_ptr Abstract_Engines_Container_i::getDefaultPyScriptNode(const char *nodeName)
2138 Utils_Locker lck(&_mutexForDftPy);
2139 std::map<std::string,Engines::PyScriptNode_var>::iterator it(_dftPyScriptNode.find(nodeName));
2140 if(it==_dftPyScriptNode.end())
2141 return Engines::PyScriptNode::_nil();
2144 Engines::PyScriptNode_var tmpVar((*it).second);
2145 if(!CORBA::is_nil(tmpVar))
2146 return Engines::PyScriptNode::_duplicate(tmpVar);
2148 return Engines::PyScriptNode::_nil();
2152 //=============================================================================
2153 /* int checkifexecutable(const char *filename)
2155 * Return non-zero if the name is an executable file, and
2156 * zero if it is not executable, or if it does not exist.
2158 //=============================================================================
2159 int checkifexecutable(const std::string& filename)
2162 struct stat statinfo;
2164 result = stat(filename.c_str(), &statinfo);
2165 if (result < 0) return 0;
2166 if (!S_ISREG(statinfo.st_mode)) return 0;
2171 if (statinfo.st_uid == geteuid()) return statinfo.st_mode & S_IXUSR;
2172 if (statinfo.st_gid == getegid()) return statinfo.st_mode & S_IXGRP;
2173 return statinfo.st_mode & S_IXOTH;
2178 //=============================================================================
2179 /*! \brief Find a file by searching in a path
2180 * \param filename file name to search
2181 * \param path path to search in
2182 * \param pth the complete file path if found
2183 * \return 1 if found 0 if not
2185 //=============================================================================
2186 int findpathof(const std::string& path, std::string& pth, const std::string& filename)
2188 if ( path.size() == 0 ) return 0;
2190 std::string::size_type offset = 0;
2191 std::string::size_type pos = 0;
2193 struct stat statinfo;
2197 pos = path.find( SEP, offset );
2198 pth = path.substr( offset, pos - offset );
2199 if ( pth.size() > 0 )
2201 if( pth[pth.size()-1] != SLASH ) pth += SLASH;
2203 int result=stat(pth.c_str(), &statinfo);
2204 if(result == 0) found=1;
2206 if (pos == std::string::npos) break;
2212 void Abstract_Engines_Container_i::registerTemporaryFile( const std::string& fileName )
2214 _tmp_files.remove( fileName );
2215 _tmp_files.push_back( fileName );
2218 void Abstract_Engines_Container_i::unregisterTemporaryFile( const std::string& fileName )
2220 _tmp_files.remove( fileName );
2223 void Abstract_Engines_Container_i::clearTemporaryFiles()
2225 std::list<std::string>::const_iterator it;
2226 for ( it = _tmp_files.begin(); it != _tmp_files.end(); ++it ) {
2227 #if defined(WIN32) && defined(UNICODE)
2228 std::wstring aFile = Kernel_Utils::utf8_decode_s(*it);
2229 std::wstring command = (GetFileAttributes(aFile.c_str()) == FILE_ATTRIBUTE_DIRECTORY) ? L"rd /Q \"" : L"del /F /Q \"";
2231 command += L"\" 2>NUL";
2232 _wsystem(command.c_str());
2235 std::string aFile = *it;
2236 std::string command = (GetFileAttributes(aFile.c_str()) == FILE_ATTRIBUTE_DIRECTORY) ? "rd /Q \"" : "del /F /Q \"";
2238 command += "\" 2>NUL";
2240 std::string command = "rm -rf ";
2243 system(command.c_str());
2249 static Engines_Container_SSL_i *_container_singleton_ssl = nullptr;
2251 static Engines::Container_var _container_ref_singleton_ssl;
2253 Engines_Container_SSL_i *KERNEL::getContainerSA()
2255 if(!_container_singleton_ssl)
2257 CORBA::ORB_var orb = KERNEL::GetRefToORB();
2258 CORBA::Object_var obj = orb->resolve_initial_references("RootPOA");
2259 PortableServer::POA_var poa = PortableServer::POA::_narrow(obj);
2260 PortableServer::POAManager_var pman = poa->the_POAManager();
2261 CORBA::PolicyList policies;
2264 char *argv[4] = {"Container","FactoryServer","toto",nullptr};
2265 SALOME_Fake_NamingService ns;
2266 _container_singleton_ssl = new Engines_Container_SSL_i(orb,poa,"FactoryServer",2,argv,&ns,false);
2267 PortableServer::ObjectId * cont_id = _container_singleton_ssl->getCORBAId();
2269 CORBA::Object_var zeRef = poa->id_to_reference(*cont_id);
2270 _container_ref_singleton_ssl = Engines::Container::_narrow(zeRef);
2272 return _container_singleton_ssl;
2275 Engines::Container_var KERNEL::getContainerRefSA()
2278 return _container_ref_singleton_ssl;