1 // Copyright (C) 2007-2021 CEA/DEN, EDF R&D, 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 "Basics_Utils.hxx"
67 #include <structmember.h>
68 #include "Container_init_python.hxx"
69 #ifdef BOS26455_WITH_BOOST_PYTHON
70 #include <boost/python.hpp>
73 bool _Sleeping = false ;
75 // // Needed by multi-threaded Python --- Supervision
79 extern "C" {void ActSigIntHandler() ; }
81 extern "C" {void SigIntHandler(int, siginfo_t *, void *) ; }
83 extern "C" {void SigIntHandler( int ) ; }
89 #define ENGINESO "Engine.dylib"
91 #define ENGINESO "Engine.so"
95 #define ENGINESO "Engine.dll"
106 std::map<std::string, int> Abstract_Engines_Container_i::_cntInstances_map;
107 std::map<std::string, void *> Abstract_Engines_Container_i::_library_map;
108 std::map<std::string, void *> Abstract_Engines_Container_i::_toRemove_map;
109 omni_mutex Abstract_Engines_Container_i::_numInstanceMutex ;
111 static PyObject* _pyCont;
113 int checkifexecutable(const std::string&);
114 int findpathof(const std::string& path, std::string&, const std::string&);
116 /*! \class Engines_Container_i
117 * \brief C++ implementation of Engines::Container interface
122 //=============================================================================
124 * Default constructor, not for use
126 //=============================================================================
128 Abstract_Engines_Container_i::Abstract_Engines_Container_i () :
129 _NS(nullptr),_id(nullptr),_numInstance(0)
133 //=============================================================================
137 //=============================================================================
139 Abstract_Engines_Container_i::Abstract_Engines_Container_i (CORBA::ORB_ptr orb,
140 PortableServer::POA_ptr poa,
141 char *containerName ,
142 int argc , char* argv[],
143 SALOME_NamingService_Container_Abstract *ns,
144 bool isServantAloneInProcess
146 _NS(nullptr),_id(0),_numInstance(0),_isServantAloneInProcess(isServantAloneInProcess)
148 _pid = (long)getpid();
156 std::string hostname = Kernel_Utils::GetHostname();
158 MESSAGE(hostname << " " << getpid() <<
159 " Engines_Container_i starting argc " <<
160 _argc << " Thread " << pthread_self() ) ;
162 MESSAGE(hostname << " " << _getpid() <<
163 " Engines_Container_i starting argc " << _argc<< " Thread " << pthread_self().p ) ;
169 MESSAGE(" argv" << i << " " << _argv[ i ]) ;
175 INFOS("SALOME_Container usage : SALOME_Container ServerName");
179 _isSupervContainer = false;
181 _orb = CORBA::ORB::_duplicate(orb) ;
182 _poa = PortableServer::POA::_duplicate(poa) ;
184 // Pour les containers paralleles: il ne faut pas enregistrer et activer
185 // le container generique, mais le container specialise
188 _id = _poa->activate_object(this);
189 // key point : if ns is nullptr : this servant is alone in its process
190 // if ns is not null : this servant embedded into single process.
191 _NS = ns==nullptr ? new SALOME_NamingService : ns->clone();
192 _NS->init_orb( _orb ) ;
193 CORBA::Object_var obj=_poa->id_to_reference(*_id);
194 Engines::Container_var pCont = Engines::Container::_narrow(obj);
197 _containerName = SALOME_NamingService_Abstract::BuildContainerNameForNS(containerName, hostname.c_str());
198 SCRUTE(_containerName);
199 _NS->Register(pCont, _containerName.c_str());
200 MESSAGE("Engines_Container_i::Engines_Container_i : Container name " << _containerName);
203 // import SALOME_Container
204 // pycont = SALOME_Container.SALOME_Container_i(containerIORStr)
206 CORBA::String_var sior = _orb->object_to_string(pCont);
207 std::string myCommand="pyCont = SALOME_Container.SALOME_Container_i('";
208 myCommand += _containerName + "','";
213 //[RNV]: Comment the PyEval_AcquireLock() and PyEval_ReleaseLock() because this
214 //approach leads to the deadlock of the main thread of the application on Windows platform
215 //in case if cppContainer runs in the standalone mode. The problem with the PyThreadState
216 //described by ABN seems not reproduced, to be checked carefully later...
217 PyGILState_STATE gstate = PyGILState_Ensure();
219 //// [ABN]: using the PyGILState* API here is unstable. omniORB logic is invoked
220 //// by the Python code executed below, and in some (random) cases, the Python code
221 //// execution ends with a PyThreadState which was not the one we have here.
222 //// (TODO: understand why ...)
223 //// To be on the safe side we get and load the thread state ourselves:
224 //PyEval_AcquireLock(); // get GIL
225 //PyThreadState * mainThreadState = PyThreadState_Get();
226 //PyThreadState_Swap(mainThreadState);
229 // mpv: this is temporary solution: there is a unregular crash if not
232 // first element is the path to Registry.dll, but it's wrong
233 PyRun_SimpleString("import sys\n");
234 PyRun_SimpleString("sys.path = sys.path[1:]\n");
236 PyRun_SimpleString("import SALOME_Container\n");
237 PyRun_SimpleString((char*)myCommand.c_str());
238 PyObject *mainmod = PyImport_AddModule("__main__");
239 PyObject *globals = PyModule_GetDict(mainmod);
240 _pyCont = PyDict_GetItemString(globals, "pyCont");
242 //PyThreadState_Swap(NULL);
243 //PyEval_ReleaseLock();
244 PyGILState_Release(gstate);
246 fileTransfer_i* aFileTransfer = new fileTransfer_i();
247 CORBA::Object_var obref=aFileTransfer->_this();
248 _fileTransfer = Engines::fileTransfer::_narrow(obref);
249 aFileTransfer->_remove_ref();
253 //=============================================================================
257 //=============================================================================
259 Abstract_Engines_Container_i::~Abstract_Engines_Container_i()
261 MESSAGE("Abstract_Container_i::~Abstract_Container_i()");
269 //=============================================================================
270 //! Get container name
272 * CORBA attribute: Container name (see constructor)
274 //=============================================================================
276 char* Abstract_Engines_Container_i::name()
278 return CORBA::string_dup(_containerName.c_str()) ;
281 //=============================================================================
282 //! Get container working directory
284 * CORBA attribute: Container working directory
286 //=============================================================================
288 char* Abstract_Engines_Container_i::workingdir()
292 return CORBA::string_dup(wd) ;
295 //=============================================================================
296 //! Get container log file name
298 * CORBA attribute: Container log file name
300 //=============================================================================
302 char* Abstract_Engines_Container_i::logfilename()
304 return CORBA::string_dup(_logfilename.c_str()) ;
307 //! Set container log file name
308 void Abstract_Engines_Container_i::logfilename(const char* name)
313 //=============================================================================
314 //! Get container host name
316 * CORBA method: Get the hostName of the Container (without domain extensions)
318 //=============================================================================
320 char* Abstract_Engines_Container_i::getHostName()
322 std::string s = Kernel_Utils::GetHostname();
323 // MESSAGE("Engines_Container_i::getHostName " << s);
324 return CORBA::string_dup(s.c_str()) ;
327 //=============================================================================
328 //! Get container PID
330 * CORBA method: Get the PID (process identification) of the Container
332 //=============================================================================
334 CORBA::Long Abstract_Engines_Container_i::getPID()
336 return (CORBA::Long)getpid();
339 //=============================================================================
340 //! Ping the servant to check it is still alive
342 * CORBA method: check if servant is still alive
344 //=============================================================================
345 void Abstract_Engines_Container_i::ping()
347 MESSAGE("Engines_Container_i::ping() pid "<< getpid());
350 //=============================================================================
351 //! Get number of CPU cores in the calculation node
353 * CORBA method: get number of CPU cores
355 //=============================================================================
357 CORBA::Long Abstract_Engines_Container_i::getNumberOfCPUCores()
359 PyGILState_STATE gstate = PyGILState_Ensure();
360 PyObject *module = PyImport_ImportModuleNoBlock((char*)"salome_psutil");
361 PyObject *result = PyObject_CallMethod(module,
362 (char*)"getNumberOfCPUCores", NULL);
363 int n = PyLong_AsLong(result);
365 PyGILState_Release(gstate);
367 return (CORBA::Long)n;
370 //=============================================================================
371 //! Get a load of each CPU core in the calculation node
373 * CORBA method: get a load of each CPU core
375 //=============================================================================
385 PyStdOut_dealloc(PyStdOut *self)
391 PyStdOut_write(PyStdOut* self, PyObject* args)
394 if (!PyArg_ParseTuple(args, "s", &c))
397 *(self->out) = *(self->out) + c;
403 static PyMethodDef PyStdOut_methods[] =
405 {"write", (PyCFunction)PyStdOut_write, METH_VARARGS,
406 PyDoc_STR("write(string) -> None")},
407 {0, 0, 0, 0} /* sentinel */
410 static PyMemberDef PyStdOut_memberlist[] =
412 {(char*)"softspace", T_INT, offsetof(PyStdOut, softspace), 0,
413 (char*)"flag indicating that a space needs to be printed; used by print"},
414 {0, 0, 0, 0, 0} /* sentinel */
417 static PyTypeObject PyStdOut_Type =
419 /* The ob_type field must be initialized in the module init function
420 * to be portable to Windows without using C++. */
421 PyVarObject_HEAD_INIT(NULL, 0)
424 sizeof(PyStdOut), /*tp_basicsize*/
427 (destructor)PyStdOut_dealloc, /*tp_dealloc*/
434 0, /*tp_as_sequence*/
439 PyObject_GenericGetAttr, /*tp_getattro*/
440 /* softspace is writable: we must supply tp_setattro */
441 PyObject_GenericSetAttr, /* tp_setattro */
443 Py_TPFLAGS_DEFAULT, /*tp_flags*/
447 0, /*tp_richcompare*/
448 0, /*tp_weaklistoffset*/
451 PyStdOut_methods, /*tp_methods*/
452 PyStdOut_memberlist, /*tp_members*/
470 0, /*tp_version_tag*/
474 PyObject* newPyStdOut(std::string& out)
476 PyStdOut* self = PyObject_New(PyStdOut, &PyStdOut_Type);
481 return (PyObject*)self;
484 std::string parseException()
487 if (PyErr_Occurred())
489 #ifdef BOS26455_WITH_BOOST_PYTHON
490 PyObject *ptype = nullptr;
491 PyObject *pvalue = nullptr;
492 PyObject *ptraceback = nullptr;
493 PyErr_Fetch(&ptype, &pvalue, &ptraceback);
494 if (ptype == nullptr)
495 return std::string("Null exception type");
496 PyErr_NormalizeException(&ptype, &pvalue, &ptraceback);
497 if (ptraceback != nullptr)
498 PyException_SetTraceback(pvalue, ptraceback);
499 boost::python::handle<> htype(ptype);
500 boost::python::handle<> hvalue(boost::python::allow_null(pvalue));
501 boost::python::handle<> htraceback(boost::python::allow_null(ptraceback));
502 boost::python::object traceback = boost::python::import("traceback");
503 boost::python::object format_exc = traceback.attr("format_exception");
504 boost::python::object formatted = format_exc(htype, hvalue, htraceback);
505 error = boost::python::extract<std::string>(boost::python::str("\n").join(formatted));
507 PyObject* new_stderr = newPyStdOut(error);
508 PyObject* old_stderr = PySys_GetObject((char*)"stderr");
509 Py_INCREF(old_stderr);
510 PySys_SetObject((char*)"stderr", new_stderr);
512 PySys_SetObject((char*)"stderr", old_stderr);
513 Py_DECREF(new_stderr);
520 Engines::vectorOfDouble* Abstract_Engines_Container_i::loadOfCPUCores()
522 PyGILState_STATE gstate = PyGILState_Ensure();
523 PyObject *module = PyImport_ImportModuleNoBlock((char*)"salome_psutil");
524 PyObject *result = PyObject_CallMethod(module,
525 (char*)"loadOfCPUCores", "s",
526 _load_script.c_str());
527 if (PyErr_Occurred())
529 std::string error = parseException();
531 PyGILState_Release(gstate);
532 SALOME::ExceptionStruct es;
533 es.type = SALOME::INTERNAL_ERROR;
534 es.text = CORBA::string_dup(error.c_str());
535 throw SALOME::SALOME_Exception(es);
538 int n = this->getNumberOfCPUCores();
539 if (!PyList_Check(result) || PyList_Size(result) != n) {
540 // bad number of cores
541 PyGILState_Release(gstate);
543 SALOME::ExceptionStruct es;
544 es.type = SALOME::INTERNAL_ERROR;
545 es.text = "wrong number of cores";
546 throw SALOME::SALOME_Exception(es);
549 Engines::vectorOfDouble_var loads = new Engines::vectorOfDouble;
551 for (Py_ssize_t i = 0; i < PyList_Size(result); ++i) {
552 PyObject* item = PyList_GetItem(result, i);
553 double foo = PyFloat_AsDouble(item);
554 if (foo < 0.0 || foo > 1.0)
556 // value not in [0, 1] range
557 PyGILState_Release(gstate);
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);
568 PyGILState_Release(gstate);
570 return loads._retn();
573 //=============================================================================
574 //! Set custom script to calculate a load of each CPU core
576 * CORBA method: Set custom script to calculate CPU load
577 * \param script Python script to execute
579 //=============================================================================
581 void Abstract_Engines_Container_i::setPyScriptForCPULoad(const char *script)
583 _load_script = script;
586 //=============================================================================
587 //! Nullify custom script to calculate each CPU core's load
589 * CORBA method: reset script for load calculation to default implementation
591 //=============================================================================
593 void Abstract_Engines_Container_i::resetScriptForCPULoad()
598 //=============================================================================
599 //! Get total physical memory of calculation node, in megabytes
601 * CORBA method: get total physical memory of calculation node
603 //=============================================================================
605 CORBA::Long Abstract_Engines_Container_i::getTotalPhysicalMemory()
607 PyGILState_STATE gstate = PyGILState_Ensure();
608 PyObject *module = PyImport_ImportModuleNoBlock((char*)"salome_psutil");
609 PyObject *result = PyObject_CallMethod(module,
610 (char*)"getTotalPhysicalMemory", NULL);
611 int n = PyLong_AsLong(result);
613 PyGILState_Release(gstate);
615 return (CORBA::Long)n;
618 //=============================================================================
619 //! Get used physical memory of calculation node, in megabytes
621 * CORBA method: get used physical memory of calculation node
623 //=============================================================================
625 CORBA::Long Abstract_Engines_Container_i::getTotalPhysicalMemoryInUse()
627 PyGILState_STATE gstate = PyGILState_Ensure();
628 PyObject *module = PyImport_ImportModuleNoBlock((char*)"salome_psutil");
629 PyObject *result = PyObject_CallMethod(module,
630 (char*)"getTotalPhysicalMemoryInUse", NULL);
631 int n = PyLong_AsLong(result);
633 PyGILState_Release(gstate);
635 return (CORBA::Long)n;
638 //=============================================================================
639 //! Obtain physical memory, used by the current process, in megabytes.
641 * CORBA method: get physical memory, used by the current process
643 //=============================================================================
645 CORBA::Long Abstract_Engines_Container_i::getTotalPhysicalMemoryInUseByMe()
647 PyGILState_STATE gstate = PyGILState_Ensure();
648 PyObject *module = PyImport_ImportModuleNoBlock((char*)"salome_psutil");
649 PyObject *result = PyObject_CallMethod(module,
650 (char*)"getTotalPhysicalMemoryInUseByMe", NULL);
651 int n = PyLong_AsLong(result);
653 PyGILState_Release(gstate);
655 return (CORBA::Long)n;
658 //=============================================================================
659 //! Shutdown the container
661 * CORBA method, oneway: Server shutdown.
662 * - Container name removed from naming service,
663 * - servant deactivation,
664 * - orb shutdown if no other servants in the process
666 //=============================================================================
667 void Abstract_Engines_Container_i::Shutdown()
669 MESSAGE("Engines_Container_i::Shutdown()");
671 // Clear registered temporary files
672 clearTemporaryFiles();
674 /* For each component contained in this container
675 * tell it to self-destroy
677 std::map<std::string, Engines::EngineComponent_var>::iterator itm;
678 for (itm = _listInstances_map.begin(); itm != _listInstances_map.end(); itm++)
682 itm->second->destroy();
684 catch(const CORBA::Exception&)
686 // ignore this entry and continue
690 // ignore this entry and continue
693 _listInstances_map.clear();
695 // NS unregistering may throw in SSL mode if master process hosting SALOME_Embedded_NamingService servant has vanished
696 // In this case it's skip it and still continue.
699 _NS->Destroy_FullDirectory(_containerName.c_str());
700 _NS->Destroy_Name(_containerName.c_str());
706 this->cleanAllPyScripts();
708 if(_isServantAloneInProcess)
710 MESSAGE("Effective Shutdown of container Begins...");
711 if(!CORBA::is_nil(_orb))
716 //=============================================================================
717 //! load a component implementation
720 * \param componentName component name
721 * \param reason explains error when load fails
722 * \return true if dlopen successful or already done, false otherwise
724 //=============================================================================
726 Abstract_Engines_Container_i::load_component_Library(const char* componentName, CORBA::String_out reason)
729 //=================================================================
730 // --- C++ implementation section
731 //=================================================================
733 if(load_component_CppImplementation(componentName,retso))
735 reason=CORBA::string_dup("");
738 else if(retso != "ImplementationNotFound")
740 reason=CORBA::string_dup(retso.c_str());
745 retso+=componentName;
746 retso+=": Can't find C++ implementation ";
747 retso+=std::string(LIB) + componentName + ENGINESO;
749 //=================================================================
750 // --- Python implementation section
751 //=================================================================
753 if(load_component_PythonImplementation(componentName,retpy))
755 reason=CORBA::string_dup("");
758 else if(retpy != "ImplementationNotFound")
760 reason=CORBA::string_dup(retpy.c_str());
765 retpy+=componentName;
766 retpy+=": Can't find python implementation ";
767 retpy+=componentName;
770 //=================================================================
771 // -- Executable implementation section
772 //=================================================================
774 if(load_component_ExecutableImplementation(componentName,retex))
776 reason=CORBA::string_dup("");
779 else if(retex != "ImplementationNotFound")
781 reason=CORBA::string_dup(retex.c_str());
786 retex+=componentName;
787 retex+=": Can't find executable implementation ";
788 retex+=componentName;
791 std::string ret="Component implementation not found: ";
792 ret += componentName ;
798 std::cerr << ret << std::endl;
799 reason=CORBA::string_dup(ret.c_str());
804 //=============================================================================
805 //! try to load a C++ component implementation
808 * \param componentName the name of the component (COMPONENT, for example)
809 * \param reason explains error when load fails
810 * \return true if loading is successful or already done, false otherwise
812 //=============================================================================
814 Abstract_Engines_Container_i::load_component_CppImplementation(const char* componentName, std::string& reason)
816 std::string aCompName(componentName);
817 std::string impl_name = std::string(LIB) + aCompName + ENGINESO;
820 _numInstanceMutex.lock(); // lock to be alone
821 // (see decInstanceCnt, finalize_removal))
822 if (_toRemove_map.count(impl_name) != 0) _toRemove_map.erase(impl_name);
823 if (_library_map.count(impl_name) != 0)
825 MESSAGE("Library " << impl_name << " already loaded");
826 _numInstanceMutex.unlock();
830 _numInstanceMutex.unlock();
834 handle = dlopen( impl_name.c_str() , RTLD_NOW | RTLD_GLOBAL ) ;
837 //not loadable. Try to find the lib file in LD_LIBRARY_PATH
840 char* p=getenv("DYLD_LIBRARY_PATH");
842 char* p=getenv("LD_LIBRARY_PATH");
845 path=path+SEP+"/usr/lib"+SEP+"/lib";
848 if(findpathof(path, pth, impl_name))
850 //found but not loadable
853 reason+=": C++ implementation found ";
855 reason+=" but it is not loadable. Error:\n";
857 std::cerr << reason << std::endl;
863 //continue with other implementation
864 reason="ImplementationNotFound";
871 std::wstring libToLoad = Kernel_Utils::utf8_decode_s( impl_name );
873 std::string libToLoad = impl_name;
875 handle = LoadLibrary(libToLoad.c_str() );
878 reason="ImplementationNotFound";
884 _numInstanceMutex.lock();
885 _library_map[impl_name] = handle;
886 _numInstanceMutex.unlock();
894 //=============================================================================
895 //! try to load a Python component implementation
898 * \param componentName name of the component
899 * \param reason explains error when load fails
900 * \return true if loading is successful or already done, false otherwise
902 //=============================================================================
904 Abstract_Engines_Container_i::load_component_PythonImplementation(const char* componentName, std::string& reason)
906 std::string aCompName(componentName);
908 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
909 if (_library_map.count(aCompName) != 0)
911 _numInstanceMutex.unlock() ;
913 return true; // Python Component, already imported
915 _numInstanceMutex.unlock() ;
917 PyGILState_STATE gstate = PyGILState_Ensure();
918 PyObject *result = PyObject_CallMethod(_pyCont,
919 (char*)"import_component",
920 (char*)"s",componentName);
922 reason=PyUnicode_AsUTF8(result);
925 PyGILState_Release(gstate);
929 //Python component has been loaded (import componentName)
930 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
931 _library_map[aCompName] = (void *)_pyCont; // any non O value OK
932 _numInstanceMutex.unlock() ;
933 MESSAGE("import Python: "<< aCompName <<" OK");
936 else if(reason=="ImplementationNotFound")
938 //Python implementation has not been found. Continue with other implementation
939 reason="ImplementationNotFound";
943 //Python implementation has been found but loading has failed
944 std::cerr << reason << std::endl;
949 //=============================================================================
950 //! try to load a Executable component implementation
953 * \param componentName name of the component
954 * \param reason explains error when load fails
955 * \return true if loading is successful or already done, false otherwise
957 //=============================================================================
959 Abstract_Engines_Container_i::load_component_ExecutableImplementation(const char* componentName, std::string& reason)
961 std::string aCompName(componentName);
962 std::string executable=aCompName+".exe";
967 char* p=getenv("PATH");
970 if (findpathof(path, pth, executable))
972 if(checkifexecutable(pth))
974 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
975 _library_map[executable] = (void *)1; // any non O value OK
976 _numInstanceMutex.unlock() ;
977 MESSAGE("import executable: "<< pth <<" OK");
983 reason+=": implementation found ";
985 reason+=" but it is not executable";
986 std::cerr << reason << std::endl;
990 reason="ImplementationNotFound";
995 //=============================================================================
996 //! Create a new component instance
998 * CORBA method: Creates a new servant instance of a component.
999 * The servant registers itself to naming service and Registry.
1000 * \param genericRegisterName Name of the component instance to register
1001 * in Registry & Name Service (without _inst_n suffix)
1002 * \return a loaded component
1004 //=============================================================================
1005 Engines::EngineComponent_ptr
1006 Abstract_Engines_Container_i::create_component_instance(const char*genericRegisterName)
1008 Engines::FieldsDict_var env = new Engines::FieldsDict;
1010 Engines::EngineComponent_ptr compo =
1011 create_component_instance_env(genericRegisterName, env, reason);
1012 CORBA::string_free(reason);
1016 //=============================================================================
1017 //! Create a new component instance with environment variables specified
1019 * CORBA method: Creates a new servant instance of a component.
1020 * The servant registers itself to naming service and Registry.
1021 * \param genericRegisterName Name of the component instance to register
1022 * in Registry & Name Service (without _inst_n suffix)
1023 * \param env dict of env variables
1024 * \param reason explains error when create_component_instance_env fails
1025 * \return a loaded component
1027 //=============================================================================
1028 Engines::EngineComponent_ptr
1029 Abstract_Engines_Container_i::create_component_instance_env(const char*genericRegisterName,
1030 const Engines::FieldsDict& env,
1031 CORBA::String_out reason)
1034 if (_library_map.count(genericRegisterName) != 0)
1036 // It's a Python component
1037 Engines::EngineComponent_ptr compo = createPythonInstance(genericRegisterName, error);
1038 reason=CORBA::string_dup(error.c_str());
1042 std::string impl_name = std::string(LIB) + genericRegisterName + ENGINESO;
1043 if (_library_map.count(impl_name) != 0)
1045 // It's a C++ component
1046 void* handle = _library_map[impl_name];
1047 Engines::EngineComponent_ptr compo = createInstance(genericRegisterName, handle, error);
1048 reason=CORBA::string_dup(error.c_str());
1052 impl_name = std::string(genericRegisterName) + ".exe";
1053 if (_library_map.count(impl_name) != 0)
1055 //It's an executable component
1056 Engines::EngineComponent_ptr compo = createExecutableInstance(genericRegisterName, env, error);
1057 reason=CORBA::string_dup(error.c_str());
1061 error="load_component_Library has probably not been called for component: ";
1062 error += genericRegisterName;
1064 reason=CORBA::string_dup(error.c_str());
1065 return Engines::EngineComponent::_nil() ;
1068 //=============================================================================
1069 //! Create a new component instance (Executable implementation)
1071 * \param CompName Name of the component instance
1072 * \param env dict of env variables
1073 * \param reason explains error when creation fails
1074 * \return a loaded component
1076 * This component is implemented in an executable with name genericRegisterName.exe
1077 * It must register itself in Naming Service. The container waits some time (10 s max)
1078 * it's registration.
1080 //=============================================================================
1081 Engines::EngineComponent_ptr
1082 Abstract_Engines_Container_i::createExecutableInstance(std::string CompName,
1083 const Engines::FieldsDict& env,
1084 std::string& reason)
1086 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1088 _numInstanceMutex.lock() ; // lock on the instance number
1090 int numInstance = _numInstance ;
1091 _numInstanceMutex.unlock() ;
1094 sprintf( aNumI , "%d" , numInstance ) ;
1095 std::string instanceName = CompName + "_inst_" + aNumI ;
1096 std::string component_registerName = _containerName + "/" + instanceName;
1098 //check if an entry exist in naming service
1099 CORBA::Object_var nsobj = _NS->Resolve(component_registerName.c_str());
1100 if ( !CORBA::is_nil(nsobj) )
1102 // unregister the registered component
1103 _NS->Destroy_Name(component_registerName.c_str());
1104 //kill or shutdown it ???
1107 // first arg container ior string
1108 // second arg container name
1109 // third arg instance name
1111 Engines::Container_var pCont= _this();
1112 CORBA::String_var sior = _orb->object_to_string(pCont);
1114 std::string command;
1115 command="mkdir -p ";
1116 command+=instanceName;
1118 command+=instanceName;
1123 command+= sior; // container ior string
1125 command+=_containerName; //container name
1127 command+=instanceName; //instance name
1129 MESSAGE("SALOME_Container::create_component_instance command=" << command);
1132 // use fork/execl instead of system to get finer control on env variables
1135 if(pid == 0) // child
1137 for (CORBA::ULong i=0; i < env.length(); i++)
1139 if (env[i].value.type()->kind() == CORBA::tk_string)
1142 env[i].value >>= value;
1143 std::string s(env[i].key);
1146 putenv(strdup(s.c_str()));
1150 execl("/bin/sh", "sh", "-c", command.c_str() , (char *)0);
1153 else if(pid < 0) // failed to fork
1162 tpid = wait(&status);
1163 } while (tpid != pid);
1166 // launch component with a system call
1167 int status=system(command.c_str());
1172 reason="SALOME_Container::create_component_instance system failed (system command status -1)";
1174 return Engines::EngineComponent::_nil();
1177 else if (WEXITSTATUS(status) == 217)
1179 reason="SALOME_Container::create_component_instance system failed (system command status 217)";
1181 return Engines::EngineComponent::_nil();
1187 if (getenv("TIMEOUT_TO_WAIT_EXE_COMPONENT") != 0)
1189 std::string new_count_str = getenv("TIMEOUT_TO_WAIT_EXE_COMPONENT");
1191 std::istringstream ss(new_count_str);
1192 if (!(ss >> new_count))
1194 INFOS("[Container] TIMEOUT_TO_WAIT_EXE_COMPONENT should be an int");
1199 INFOS("[Container] waiting " << count << " second steps exe component ");
1200 CORBA::Object_var obj = CORBA::Object::_nil() ;
1201 while ( CORBA::is_nil(obj) && count )
1209 MESSAGE( count << ". Waiting for component " << CompName);
1210 obj = _NS->Resolve(component_registerName.c_str());
1213 if(CORBA::is_nil(obj))
1215 reason="SALOME_Container::create_component_instance failed";
1217 return Engines::EngineComponent::_nil();
1221 MESSAGE("SALOME_Container::create_component_instance successful");
1222 iobject = Engines::EngineComponent::_narrow(obj);
1223 _listInstances_map[instanceName] = iobject;
1224 return iobject._retn();
1230 //=============================================================================
1231 //! Create a new component instance (Python implementation)
1233 * \param CompName Name of the component instance
1234 * \param reason explains error when creation fails
1235 * \return a loaded component
1237 //=============================================================================
1238 Engines::EngineComponent_ptr
1239 Abstract_Engines_Container_i::createPythonInstance(std::string CompName,
1240 std::string& reason)
1242 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1244 _numInstanceMutex.lock() ; // lock on the instance number
1246 int numInstance = _numInstance ;
1247 _numInstanceMutex.unlock() ;
1250 sprintf( aNumI , "%d" , numInstance ) ;
1251 std::string instanceName = CompName + "_inst_" + aNumI ;
1252 std::string component_registerName = _containerName + "/" + instanceName;
1254 PyGILState_STATE gstate = PyGILState_Ensure();
1255 PyObject *result = PyObject_CallMethod(_pyCont,
1256 (char*)"create_component_instance",
1259 instanceName.c_str());
1262 PyArg_ParseTuple(result,"ss", &ior, &error);
1263 std::string iors = ior;
1266 PyGILState_Release(gstate);
1270 CORBA::Object_var obj = _orb->string_to_object(iors.c_str());
1271 iobject = Engines::EngineComponent::_narrow( obj ) ;
1272 _listInstances_map[instanceName] = iobject;
1274 return iobject._retn();
1278 Abstract_Engines_Container_i::create_python_service_instance(const char * CompName,
1279 CORBA::String_out reason)
1281 CORBA::Object_var object = CORBA::Object::_nil();
1283 _numInstanceMutex.lock() ; // lock on the instance number
1285 int numInstance = _numInstance ;
1286 _numInstanceMutex.unlock() ;
1289 sprintf( aNumI , "%d" , numInstance ) ;
1290 std::string instanceName = std::string(CompName) + "_inst_" + aNumI ;
1291 std::string component_registerName = _containerName + "/" + instanceName;
1293 PyGILState_STATE gstate = PyGILState_Ensure();
1294 PyObject *result = PyObject_CallMethod(_pyCont,
1295 (char*)"create_component_instance",
1298 instanceName.c_str());
1301 PyArg_ParseTuple(result,"ss", &ior, &error);
1302 reason = CORBA::string_dup(error);
1303 char * _ior = CORBA::string_dup(ior);
1305 PyGILState_Release(gstate);
1311 //=============================================================================
1312 //! Create a new component instance (C++ implementation)
1314 * C++ method: create a servant instance of a component.
1315 * \param genericRegisterName Name of the component instance to register
1316 * in Registry & Name Service,
1317 * (without _inst_n suffix, like "COMPONENT")
1318 * \param handle loaded library handle
1319 * \param reason explains error when creation fails
1320 * \return a loaded component
1322 * example with names:
1323 * - aGenRegisterName = COMPONENT (= first argument)
1324 * - _containerName = /Containers/cli76ce/FactoryServer
1325 * - factoryName = COMPONENTEngine_factory
1326 * - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
1327 * - instanceName = COMPONENT_inst_1
1328 * - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1330 //=============================================================================
1331 Engines::EngineComponent_ptr
1332 Abstract_Engines_Container_i::createInstance(std::string genericRegisterName,
1334 std::string& reason)
1336 // --- find the factory
1338 std::string aGenRegisterName = genericRegisterName;
1339 std::string factory_name = aGenRegisterName + std::string("Engine_factory");
1340 SCRUTE(factory_name) ;
1342 typedef PortableServer::ObjectId* (*FACTORY_FUNCTION) (CORBA::ORB_ptr,
1343 PortableServer::POA_ptr,
1344 PortableServer::ObjectId *,
1349 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)dlsym( handle, factory_name.c_str() );
1351 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)GetProcAddress( (HINSTANCE)handle, factory_name.c_str() );
1354 if ( !Component_factory )
1356 MESSAGE( "Can't resolve symbol: " + factory_name );
1361 return Engines::EngineComponent::_nil() ;
1364 // --- create instance
1366 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1370 _numInstanceMutex.lock() ; // lock on the instance number
1372 int numInstance = _numInstance ;
1373 _numInstanceMutex.unlock() ;
1376 sprintf( aNumI , "%d" , numInstance ) ;
1377 std::string instanceName = aGenRegisterName + "_inst_" + aNumI ;
1378 std::string component_registerName =
1379 _containerName + "/" + instanceName;
1381 // --- Instantiate required CORBA object
1383 PortableServer::ObjectId *id ; //not owner, do not delete (nore use var)
1384 id = (Component_factory) ( _orb, _poa, _id, instanceName.c_str(),
1385 aGenRegisterName.c_str() ) ;
1388 reason="Can't get ObjectId from factory";
1390 return iobject._retn();
1393 // --- get reference from id
1395 CORBA::Object_var obj = _poa->id_to_reference(*id);
1396 iobject = Engines::EngineComponent::_narrow( obj ) ;
1398 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1399 _listInstances_map[instanceName] = iobject;
1400 _cntInstances_map[aGenRegisterName] += 1;
1401 _numInstanceMutex.unlock() ;
1402 SCRUTE(aGenRegisterName);
1403 SCRUTE(_cntInstances_map[aGenRegisterName]);
1405 // --- register the engine under the name
1406 // containerName(.dir)/instanceName(.object)
1408 _NS->Register( iobject , component_registerName.c_str() ) ;
1409 MESSAGE( component_registerName.c_str() << " bound" ) ;
1413 reason="Container_i::createInstance exception caught";
1416 return iobject._retn();
1419 //=============================================================================
1420 //! Find an existing (in the container) component instance
1422 * CORBA method: Finds a servant instance of a component
1423 * \param registeredName Name of the component in Registry or Name Service,
1424 * without instance suffix number
1425 * \return the first found instance
1427 //=============================================================================
1428 Engines::EngineComponent_ptr
1429 Abstract_Engines_Container_i::find_component_instance( const char* registeredName)
1431 Engines::EngineComponent_var anEngine = Engines::EngineComponent::_nil();
1432 std::map<std::string,Engines::EngineComponent_var>::iterator itm =_listInstances_map.begin();
1433 while (itm != _listInstances_map.end())
1435 std::string instance = (*itm).first;
1437 if (instance.find(registeredName) == 0)
1439 anEngine = (*itm).second;
1440 return anEngine._retn();
1444 return anEngine._retn();
1447 //=============================================================================
1448 //! Remove the component instance from container
1450 * CORBA method: Stops the component servant, and deletes all related objects
1451 * \param component_i Component to be removed
1453 //=============================================================================
1455 void Abstract_Engines_Container_i::remove_impl(Engines::EngineComponent_ptr component_i)
1457 ASSERT(! CORBA::is_nil(component_i));
1458 std::string instanceName = component_i->instanceName() ;
1459 MESSAGE("unload component " << instanceName);
1460 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1461 _listInstances_map.erase(instanceName);
1462 _numInstanceMutex.unlock() ;
1463 component_i->destroy() ;
1464 _NS->Destroy_Name(instanceName.c_str());
1467 //=============================================================================
1468 //! Unload component libraries from the container
1470 * CORBA method: Discharges unused libraries from the container.
1472 //=============================================================================
1473 void Abstract_Engines_Container_i::finalize_removal()
1475 MESSAGE("finalize unload : dlclose");
1476 _numInstanceMutex.lock(); // lock to be alone
1477 // (see decInstanceCnt, load_component_Library)
1478 std::map<std::string, void *>::iterator ith;
1479 for (ith = _toRemove_map.begin(); ith != _toRemove_map.end(); ith++)
1481 void *handle = (*ith).second;
1482 std::string impl_name= (*ith).first;
1487 // dlclose(handle); // SALOME unstable after ...
1488 // _library_map.erase(impl_name);
1491 _toRemove_map.clear();
1492 _numInstanceMutex.unlock();
1495 //=============================================================================
1496 //! Decrement component instance reference count
1500 //=============================================================================
1501 void Abstract_Engines_Container_i::decInstanceCnt(std::string genericRegisterName)
1503 if(_cntInstances_map.count(genericRegisterName)==0)
1505 std::string aGenRegisterName =genericRegisterName;
1506 MESSAGE("Engines_Container_i::decInstanceCnt " << aGenRegisterName);
1507 ASSERT(_cntInstances_map[aGenRegisterName] > 0);
1508 _numInstanceMutex.lock(); // lock to be alone
1509 // (see finalize_removal, load_component_Library)
1510 _cntInstances_map[aGenRegisterName] -= 1;
1511 SCRUTE(_cntInstances_map[aGenRegisterName]);
1512 if (_cntInstances_map[aGenRegisterName] == 0)
1514 std::string impl_name =
1515 Engines_Component_i::GetDynLibraryName(aGenRegisterName.c_str());
1517 void* handle = _library_map[impl_name];
1519 _toRemove_map[impl_name] = handle;
1521 _numInstanceMutex.unlock();
1524 //=============================================================================
1525 //! Find or create a new component instance
1527 * CORBA method: find or create an instance of the component (servant),
1528 * load a new component class (dynamic library) if required,
1530 * ---- FOR COMPATIBILITY WITH 2.2 ----
1532 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
1534 * The servant registers itself to naming service and Registry.
1535 * \param genericRegisterName Name of the component to register
1536 * in Registry & Name Service
1537 * \param componentName Name of the constructed library of the component
1538 * \return a loaded component
1540 //=============================================================================
1542 Engines::EngineComponent_ptr
1543 Abstract_Engines_Container_i::load_impl( const char* genericRegisterName,
1544 const char* /*componentName*/ )
1547 std::string impl_name = std::string(LIB) + genericRegisterName + ENGINESO;
1548 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1549 if (load_component_Library(genericRegisterName,reason))
1550 iobject = find_or_create_instance(genericRegisterName, impl_name);
1551 CORBA::string_free(reason);
1552 return iobject._retn();
1555 Engines::EmbeddedNamingService_ptr Abstract_Engines_Container_i::get_embedded_NS_if_ssl()
1557 SALOME_Embedded_NamingService_Client *nsc(dynamic_cast<SALOME_Embedded_NamingService_Client *>(this->_NS));
1560 Engines::EmbeddedNamingService_var obj = nsc->GetObject();
1561 return Engines::EmbeddedNamingService::_duplicate(obj);
1565 return Engines::EmbeddedNamingService::_nil();
1569 //=============================================================================
1570 //! Finds an already existing component instance or create a new instance
1572 * C++ method: Finds an already existing servant instance of a component, or
1573 * create an instance.
1574 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
1575 * \param genericRegisterName Name of the component instance to register
1576 * in Registry & Name Service,
1577 * (without _inst_n suffix, like "COMPONENT")
1578 * \param componentLibraryName like "libCOMPONENTEngine.so"
1579 * \return a loaded component
1581 * example with names:
1582 * - aGenRegisterName = COMPONENT (= first argument)
1583 * - impl_name = libCOMPONENTEngine.so (= second argument)
1584 * - _containerName = /Containers/cli76ce/FactoryServer
1585 * - factoryName = COMPONENTEngine_factory
1586 * - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
1587 * - instanceName = COMPONENT_inst_1
1588 * - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1590 //=============================================================================
1592 Engines::EngineComponent_ptr
1593 Abstract_Engines_Container_i::find_or_create_instance(std::string genericRegisterName,
1594 std::string componentLibraryName)
1596 std::string aGenRegisterName = genericRegisterName;
1597 std::string impl_name = componentLibraryName;
1598 if (_library_map.count(impl_name) == 0)
1600 INFOS("shared library " << impl_name <<" must be loaded before creating instance");
1601 return Engines::EngineComponent::_nil() ;
1605 // --- find a registered instance in naming service, or create
1607 void* handle = _library_map[impl_name];
1608 std::string component_registerBase =
1609 _containerName + "/" + aGenRegisterName;
1610 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1614 CORBA::Object_var obj =
1615 _NS->ResolveFirst( component_registerBase.c_str());
1616 if ( CORBA::is_nil( obj ) )
1618 iobject = createInstance(genericRegisterName,
1624 iobject = Engines::EngineComponent::_narrow( obj ) ;
1629 INFOS( "Container_i::load_impl caught" ) ;
1631 return iobject._retn();
1635 //=============================================================================
1636 //! Indicate if container is a python one
1638 * Retrieves only with container naming convention if it is a python container
1640 //=============================================================================
1641 bool Abstract_Engines_Container_i::isPythonContainer(const char* ContainerName)
1644 size_t len=strlen(ContainerName);
1646 if(strcmp(ContainerName+len-2,"Py")==0)
1651 //=============================================================================
1652 //! Kill the container
1654 * CORBA method: Kill the container process with exit(0).
1655 * To remove : never returns !
1657 //=============================================================================
1658 bool Abstract_Engines_Container_i::Kill_impl()
1660 MESSAGE("Engines_Container_i::Kill() pid "<< getpid() << " containerName "
1661 << _containerName.c_str() << " machineName "
1662 << Kernel_Utils::GetHostname().c_str());
1663 INFOS("===============================================================");
1664 INFOS("= REMOVE calls to Kill_impl in C++ container =");
1665 INFOS("===============================================================");
1671 //=============================================================================
1675 //=============================================================================
1676 void ActSigIntHandler()
1679 struct sigaction SigIntAct ;
1680 SigIntAct.sa_sigaction = &SigIntHandler ;
1681 sigemptyset(&SigIntAct.sa_mask);
1682 SigIntAct.sa_flags = SA_SIGINFO ;
1685 // DEBUG 03.02.2005 : the first parameter of sigaction is not a mask of signals
1686 // (SIGINT | SIGUSR1) :
1687 // it must be only one signal ===> one call for SIGINT
1688 // and an other one for SIGUSR1
1691 if ( sigaction( SIGINT , &SigIntAct, NULL ) )
1693 perror("SALOME_Container main ") ;
1696 if ( sigaction( SIGUSR1 , &SigIntAct, NULL ) )
1698 perror("SALOME_Container main ") ;
1701 if ( sigaction( SIGUSR2 , &SigIntAct, NULL ) )
1703 perror("SALOME_Container main ") ;
1707 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1708 // use of streams (and so on) should never be used because :
1709 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1710 // A stream operation may be interrupted by a signal and if the Handler use stream we
1711 // may have a "Dead-Lock" ===HangUp
1712 //==INFOS is commented
1713 // INFOS(pthread_self() << "SigIntHandler activated") ;
1716 signal( SIGINT, SigIntHandler );
1717 // legacy code required to supervisor. Commented in order to avoid problems on Windows
1718 // signal( SIGUSR1, SigIntHandler );
1724 void CallCancelThread() ;
1727 void SigIntHandler(int /*what*/ ,
1728 siginfo_t * siginfo ,
1731 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1732 // use of streams (and so on) should never be used because :
1733 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1734 // A stream operation may be interrupted by a signal and if the Handler use stream we
1735 // may have a "Dead-Lock" ===HangUp
1736 //==MESSAGE is commented
1737 // MESSAGE(pthread_self() << "SigIntHandler what " << what << std::endl
1738 // << " si_signo " << siginfo->si_signo << std::endl
1739 // << " si_code " << siginfo->si_code << std::endl
1740 // << " si_pid " << siginfo->si_pid) ;
1745 // MESSAGE("SigIntHandler END sleeping.") ;
1750 ActSigIntHandler() ;
1751 if ( siginfo->si_signo == SIGUSR1 )
1755 else if ( siginfo->si_signo == SIGUSR2 )
1757 CallCancelThread() ;
1762 // MESSAGE("SigIntHandler BEGIN sleeping.") ;
1769 // MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1775 void SigIntHandler( int what )
1778 MESSAGE( pthread_self() << "SigIntHandler what " << what << std::endl );
1780 MESSAGE( "SigIntHandler what " << what << std::endl );
1785 MESSAGE("SigIntHandler END sleeping.") ;
1790 ActSigIntHandler() ;
1791 if ( what == SIGUSR1 )
1798 MESSAGE("SigIntHandler BEGIN sleeping.") ;
1805 MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1812 //=============================================================================
1813 //! Get or create a file reference object associated to a local file (to transfer it)
1815 * CORBA method: get or create a fileRef object associated to a local file
1816 * (a file on the computer on which runs the container server), which stores
1817 * a list of (machine, localFileName) corresponding to copies already done.
1819 * \param origFileName absolute path for a local file to copy on other
1821 * \return a fileRef object associated to the file.
1823 //=============================================================================
1824 Engines::fileRef_ptr
1825 Abstract_Engines_Container_i::createFileRef(const char* origFileName)
1827 std::string origName(origFileName);
1828 Engines::fileRef_var theFileRef = Engines::fileRef::_nil();
1830 if (origName[0] != '/')
1832 INFOS("path of file to copy must be an absolute path beginning with '/'");
1833 return Engines::fileRef::_nil();
1836 if (CORBA::is_nil(_fileRef_map[origName]))
1838 CORBA::Object_var obj=_poa->id_to_reference(*_id);
1839 Engines::Container_var pCont = Engines::Container::_narrow(obj);
1840 fileRef_i* aFileRef = new fileRef_i(pCont, origFileName);
1841 theFileRef = Engines::fileRef::_narrow(aFileRef->_this());
1842 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1843 _fileRef_map[origName] = theFileRef;
1844 _numInstanceMutex.unlock() ;
1847 theFileRef = Engines::fileRef::_duplicate(_fileRef_map[origName]);
1848 ASSERT(! CORBA::is_nil(theFileRef));
1849 return theFileRef._retn();
1852 //=============================================================================
1853 //! Get a fileTransfer reference
1856 * \return a reference to the fileTransfer object
1858 //=============================================================================
1859 Engines::fileTransfer_ptr
1860 Abstract_Engines_Container_i::getFileTransfer()
1862 Engines::fileTransfer_var aFileTransfer
1863 = Engines::fileTransfer::_duplicate(_fileTransfer);
1864 return aFileTransfer._retn();
1867 //=============================================================================
1868 //! Create a Salome file
1869 //=============================================================================
1870 Engines::Salome_file_ptr
1871 Abstract_Engines_Container_i::createSalome_file(const char* origFileName)
1873 std::string origName(origFileName);
1874 if (CORBA::is_nil(_Salome_file_map[origName]))
1876 Salome_file_i* aSalome_file = new Salome_file_i();
1877 aSalome_file->setContainer(Engines::Container::_duplicate(this->_this()));
1880 aSalome_file->setLocalFile(origFileName);
1881 aSalome_file->recvFiles();
1883 catch (const SALOME::SALOME_Exception& /*e*/) //!< TODO: unused variable
1885 return Engines::Salome_file::_nil();
1888 Engines::Salome_file_var theSalome_file = Engines::Salome_file::_nil();
1889 theSalome_file = Engines::Salome_file::_narrow(aSalome_file->_this());
1890 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1891 _Salome_file_map[origName] = theSalome_file;
1892 _numInstanceMutex.unlock() ;
1895 Engines::Salome_file_ptr theSalome_file =
1896 Engines::Salome_file::_duplicate(_Salome_file_map[origName]);
1897 ASSERT(!CORBA::is_nil(theSalome_file));
1898 return theSalome_file;
1901 //=============================================================================
1902 /*! \brief copy a file from a remote host (container) to the local host
1903 * \param container the remote container
1904 * \param remoteFile the file to copy locally from the remote host into localFile
1905 * \param localFile the local file
1907 //=============================================================================
1908 void Abstract_Engines_Container_i::copyFile(Engines::Container_ptr container, const char* remoteFile, const char* localFile)
1910 Engines::fileTransfer_var fileTransfer = container->getFileTransfer();
1913 if ((fp = fopen(localFile,"wb")) == NULL)
1915 INFOS("file " << localFile << " cannot be open for writing");
1919 CORBA::Long fileId = fileTransfer->open(remoteFile);
1922 Engines::fileBlock* aBlock;
1929 aBlock = fileTransfer->getBlock(fileId);
1930 toFollow = aBlock->length();
1932 CORBA::Octet *buf = aBlock->get_buffer();
1933 fwrite(buf, sizeof(CORBA::Octet), toFollow, fp);
1937 MESSAGE("end of transfer");
1938 fileTransfer->close(fileId);
1942 INFOS("open reference file for copy impossible");
1946 //=============================================================================
1947 /*! \brief create a PyNode object to execute remote python code
1948 * \param nodeName the name of the node
1949 * \param code the python code to load
1950 * \return the PyNode
1952 //=============================================================================
1953 Engines::PyNode_ptr Abstract_Engines_Container_i::createPyNode(const char* nodeName, const char* code)
1955 Engines::PyNode_var node= Engines::PyNode::_nil();
1957 PyGILState_STATE gstate = PyGILState_Ensure();
1958 PyObject *res = PyObject_CallMethod(_pyCont,
1959 (char*)"create_pynode",
1967 PyGILState_Release(gstate);
1968 SALOME::ExceptionStruct es;
1969 es.type = SALOME::INTERNAL_ERROR;
1970 es.text = "can not create a python node";
1971 throw SALOME::SALOME_Exception(es);
1973 long ierr=PyLong_AsLong(PyTuple_GetItem(res,0));
1974 PyObject* result=PyTuple_GetItem(res,1);
1975 std::string astr=PyUnicode_AsUTF8(result);
1977 PyGILState_Release(gstate);
1980 Utils_Locker lck(&_mutexForDftPy);
1981 CORBA::Object_var obj=_orb->string_to_object(astr.c_str());
1982 node=Engines::PyNode::_narrow(obj);
1983 std::map<std::string,Engines::PyNode_var>::iterator it(_dftPyNode.find(nodeName));
1984 if(it==_dftPyNode.end())
1986 _dftPyNode[nodeName]=node;
1990 Engines::PyNode_var oldNode((*it).second);
1991 if(!CORBA::is_nil(oldNode))
1992 oldNode->UnRegister();
1995 if(!CORBA::is_nil(node))
1997 return node._retn();
2001 SALOME::ExceptionStruct es;
2002 es.type = SALOME::INTERNAL_ERROR;
2003 es.text = astr.c_str();
2004 throw SALOME::SALOME_Exception(es);
2008 //=============================================================================
2009 /*! \brief Retrieves the last created PyNode instance with createPyNode.
2012 //=============================================================================
2013 Engines::PyNode_ptr Abstract_Engines_Container_i::getDefaultPyNode(const char *nodeName)
2015 Utils_Locker lck(&_mutexForDftPy);
2016 std::map<std::string,Engines::PyNode_var>::iterator it(_dftPyNode.find(nodeName));
2017 if(it==_dftPyNode.end())
2018 return Engines::PyNode::_nil();
2021 Engines::PyNode_var tmpVar((*it).second);
2022 if(!CORBA::is_nil(tmpVar))
2023 return Engines::PyNode::_duplicate(tmpVar);
2025 return Engines::PyNode::_nil();
2029 //=============================================================================
2030 /*! \brief create a PyScriptNode object to execute remote python code
2031 * \param nodeName the name of the node
2032 * \param code the python code to load
2033 * \return the PyScriptNode
2035 //=============================================================================
2036 Engines::PyScriptNode_ptr Abstract_Engines_Container_i::createPyScriptNode(const char* nodeName, const char* code)
2038 Engines::PyScriptNode_var node= Engines::PyScriptNode::_nil();
2040 PyGILState_STATE gstate = PyGILState_Ensure();
2041 PyObject *res = PyObject_CallMethod(_pyCont,
2042 (char*)"create_pyscriptnode",
2050 PyGILState_Release(gstate);
2051 SALOME::ExceptionStruct es;
2052 es.type = SALOME::INTERNAL_ERROR;
2053 es.text = "can not create a python node";
2054 throw SALOME::SALOME_Exception(es);
2056 long ierr=PyLong_AsLong(PyTuple_GetItem(res,0));
2057 PyObject* result=PyTuple_GetItem(res,1);
2058 std::string astr=PyUnicode_AsUTF8(result);
2060 PyGILState_Release(gstate);
2064 Utils_Locker lck(&_mutexForDftPy);
2065 CORBA::Object_var obj=_orb->string_to_object(astr.c_str());
2066 node=Engines::PyScriptNode::_narrow(obj);
2067 std::map<std::string,Engines::PyScriptNode_var>::iterator it(_dftPyScriptNode.find(nodeName));
2068 if(it==_dftPyScriptNode.end())
2070 _dftPyScriptNode[nodeName]=node;
2074 Engines::PyScriptNode_var oldNode((*it).second);
2075 if(!CORBA::is_nil(oldNode))
2076 oldNode->UnRegister();
2079 return node._retn();
2083 SALOME::ExceptionStruct es;
2084 es.type = SALOME::INTERNAL_ERROR;
2085 es.text = astr.c_str();
2086 throw SALOME::SALOME_Exception(es);
2090 void Abstract_Engines_Container_i::removePyScriptNode(const char *nodeName)
2092 std::map<std::string,Engines::PyScriptNode_var>::iterator it(_dftPyScriptNode.find(nodeName));
2093 if(it==_dftPyScriptNode.end())
2095 std::ostringstream oss; oss << "Engines_Container_i::removePyScriptNode : node \"" << nodeName << "\" is not map !";
2096 SALOME::ExceptionStruct es;
2097 es.type = SALOME::INTERNAL_ERROR;
2098 es.text = oss.str().c_str();
2099 throw SALOME::SALOME_Exception(es);
2101 (*it).second->UnRegister();
2102 _dftPyScriptNode.erase(it);
2105 void Abstract_Engines_Container_i::cleanAllPyScripts()
2107 for(std::map<std::string,Engines::PyNode_var>::iterator it=_dftPyNode.begin();it!=_dftPyNode.end();it++)
2109 Engines::PyNode_var tmpVar((*it).second);
2110 if(!CORBA::is_nil(tmpVar))
2111 tmpVar->UnRegister();
2114 for(std::map<std::string,Engines::PyScriptNode_var>::iterator it=_dftPyScriptNode.begin();it!=_dftPyScriptNode.end();it++)
2116 Engines::PyScriptNode_var tmpVar((*it).second);
2117 if(!CORBA::is_nil(tmpVar))
2118 tmpVar->UnRegister();
2120 _dftPyScriptNode.clear();
2123 //=============================================================================
2124 /*! \brief Retrieves the last created PyScriptNode instance with createPyScriptNode.
2127 //=============================================================================
2128 Engines::PyScriptNode_ptr Abstract_Engines_Container_i::getDefaultPyScriptNode(const char *nodeName)
2130 Utils_Locker lck(&_mutexForDftPy);
2131 std::map<std::string,Engines::PyScriptNode_var>::iterator it(_dftPyScriptNode.find(nodeName));
2132 if(it==_dftPyScriptNode.end())
2133 return Engines::PyScriptNode::_nil();
2136 Engines::PyScriptNode_var tmpVar((*it).second);
2137 if(!CORBA::is_nil(tmpVar))
2138 return Engines::PyScriptNode::_duplicate(tmpVar);
2140 return Engines::PyScriptNode::_nil();
2144 //=============================================================================
2145 /* int checkifexecutable(const char *filename)
2147 * Return non-zero if the name is an executable file, and
2148 * zero if it is not executable, or if it does not exist.
2150 //=============================================================================
2151 int checkifexecutable(const std::string& filename)
2154 struct stat statinfo;
2156 result = stat(filename.c_str(), &statinfo);
2157 if (result < 0) return 0;
2158 if (!S_ISREG(statinfo.st_mode)) return 0;
2163 if (statinfo.st_uid == geteuid()) return statinfo.st_mode & S_IXUSR;
2164 if (statinfo.st_gid == getegid()) return statinfo.st_mode & S_IXGRP;
2165 return statinfo.st_mode & S_IXOTH;
2170 //=============================================================================
2171 /*! \brief Find a file by searching in a path
2172 * \param filename file name to search
2173 * \param path path to search in
2174 * \param pth the complete file path if found
2175 * \return 1 if found 0 if not
2177 //=============================================================================
2178 int findpathof(const std::string& path, std::string& pth, const std::string& filename)
2180 if ( path.size() == 0 ) return 0;
2182 std::string::size_type offset = 0;
2183 std::string::size_type pos = 0;
2185 struct stat statinfo;
2189 pos = path.find( SEP, offset );
2190 pth = path.substr( offset, pos - offset );
2191 if ( pth.size() > 0 )
2193 if( pth[pth.size()-1] != SLASH ) pth += SLASH;
2195 int result=stat(pth.c_str(), &statinfo);
2196 if(result == 0) found=1;
2198 if (pos == std::string::npos) break;
2204 void Abstract_Engines_Container_i::registerTemporaryFile( const std::string& fileName )
2206 _tmp_files.remove( fileName );
2207 _tmp_files.push_back( fileName );
2210 void Abstract_Engines_Container_i::unregisterTemporaryFile( const std::string& fileName )
2212 _tmp_files.remove( fileName );
2215 void Abstract_Engines_Container_i::clearTemporaryFiles()
2217 std::list<std::string>::const_iterator it;
2218 for ( it = _tmp_files.begin(); it != _tmp_files.end(); ++it ) {
2219 #if defined(WIN32) && defined(UNICODE)
2220 std::wstring aFile = Kernel_Utils::utf8_decode_s(*it);
2221 std::wstring command = (GetFileAttributes(aFile.c_str()) == FILE_ATTRIBUTE_DIRECTORY) ? L"rd /Q \"" : L"del /F /Q \"";
2223 command += L"\" 2>NUL";
2224 _wsystem(command.c_str());
2227 std::string aFile = *it;
2228 std::string command = (GetFileAttributes(aFile.c_str()) == FILE_ATTRIBUTE_DIRECTORY) ? "rd /Q \"" : "del /F /Q \"";
2230 command += "\" 2>NUL";
2232 std::string command = "rm -rf ";
2235 system(command.c_str());
2241 static Engines_Container_SSL_i *_container_singleton_ssl = nullptr;
2243 static Engines::Container_var _container_ref_singleton_ssl;
2245 Engines_Container_SSL_i *KERNEL::getContainerSA()
2247 if(!_container_singleton_ssl)
2249 CORBA::ORB_var orb = KERNEL::GetRefToORB();
2250 CORBA::Object_var obj = orb->resolve_initial_references("RootPOA");
2251 PortableServer::POA_var poa = PortableServer::POA::_narrow(obj);
2252 PortableServer::POAManager_var pman = poa->the_POAManager();
2253 CORBA::PolicyList policies;
2256 char *argv[4] = {"Container","FactoryServer","toto",nullptr};
2257 SALOME_Fake_NamingService ns;
2258 _container_singleton_ssl = new Engines_Container_SSL_i(orb,poa,"FactoryServer",2,argv,&ns,false);
2259 PortableServer::ObjectId * cont_id = _container_singleton_ssl->getCORBAId();
2261 CORBA::Object_var zeRef = poa->id_to_reference(*cont_id);
2262 _container_ref_singleton_ssl = Engines::Container::_narrow(zeRef);
2264 return _container_singleton_ssl;
2267 Engines::Container_var KERNEL::getContainerRefSA()
2270 return _container_ref_singleton_ssl;