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 !
51 #include "SALOME_Container_i.hxx"
52 #include "SALOME_Component_i.hxx"
53 #include "SALOME_FileRef_i.hxx"
54 #include "SALOME_FileTransfer_i.hxx"
55 #include "Salome_file_i.hxx"
56 #include "SALOME_NamingService.hxx"
57 #include "SALOME_Fake_NamingService.hxx"
58 #include "SALOME_Embedded_NamingService_Client.hxx"
59 #include "Basics_Utils.hxx"
66 #include "Container_init_python.hxx"
67 #include <boost/python.hpp>
69 bool _Sleeping = false ;
71 // // Needed by multi-threaded Python --- Supervision
75 extern "C" {void ActSigIntHandler() ; }
77 extern "C" {void SigIntHandler(int, siginfo_t *, void *) ; }
79 extern "C" {void SigIntHandler( int ) ; }
85 #define ENGINESO "Engine.dylib"
87 #define ENGINESO "Engine.so"
91 #define ENGINESO "Engine.dll"
102 std::map<std::string, int> Abstract_Engines_Container_i::_cntInstances_map;
103 std::map<std::string, void *> Abstract_Engines_Container_i::_library_map;
104 std::map<std::string, void *> Abstract_Engines_Container_i::_toRemove_map;
105 omni_mutex Abstract_Engines_Container_i::_numInstanceMutex ;
107 static PyObject* _pyCont;
109 int checkifexecutable(const std::string&);
110 int findpathof(const std::string& path, std::string&, const std::string&);
112 /*! \class Engines_Container_i
113 * \brief C++ implementation of Engines::Container interface
118 //=============================================================================
120 * Default constructor, not for use
122 //=============================================================================
124 Abstract_Engines_Container_i::Abstract_Engines_Container_i () :
125 _NS(nullptr),_id(nullptr),_numInstance(0)
129 //=============================================================================
133 //=============================================================================
135 Abstract_Engines_Container_i::Abstract_Engines_Container_i (CORBA::ORB_ptr orb,
136 PortableServer::POA_ptr poa,
137 char *containerName ,
138 int argc , char* argv[],
139 SALOME_NamingService_Container_Abstract *ns,
140 bool isServantAloneInProcess
142 _NS(nullptr),_id(0),_numInstance(0),_isServantAloneInProcess(isServantAloneInProcess)
144 _pid = (long)getpid();
152 std::string hostname = Kernel_Utils::GetHostname();
154 MESSAGE(hostname << " " << getpid() <<
155 " Engines_Container_i starting argc " <<
156 _argc << " Thread " << pthread_self() ) ;
158 MESSAGE(hostname << " " << _getpid() <<
159 " Engines_Container_i starting argc " << _argc<< " Thread " << pthread_self().p ) ;
165 MESSAGE(" argv" << i << " " << _argv[ i ]) ;
171 INFOS("SALOME_Container usage : SALOME_Container ServerName");
175 _isSupervContainer = false;
177 _orb = CORBA::ORB::_duplicate(orb) ;
178 _poa = PortableServer::POA::_duplicate(poa) ;
180 // Pour les containers paralleles: il ne faut pas enregistrer et activer
181 // le container generique, mais le container specialise
184 _id = _poa->activate_object(this);
185 // key point : if ns is nullptr : this servant is alone in its process
186 // if ns is not null : this servant embedded into single process.
187 _NS = ns==nullptr ? new SALOME_NamingService : ns->clone();
188 _NS->init_orb( _orb ) ;
189 CORBA::Object_var obj=_poa->id_to_reference(*_id);
190 Engines::Container_var pCont = Engines::Container::_narrow(obj);
193 _containerName = SALOME_NamingService_Abstract::BuildContainerNameForNS(containerName, hostname.c_str());
194 SCRUTE(_containerName);
195 _NS->Register(pCont, _containerName.c_str());
196 MESSAGE("Engines_Container_i::Engines_Container_i : Container name " << _containerName);
199 // import SALOME_Container
200 // pycont = SALOME_Container.SALOME_Container_i(containerIORStr)
202 CORBA::String_var sior = _orb->object_to_string(pCont);
203 std::string myCommand="pyCont = SALOME_Container.SALOME_Container_i('";
204 myCommand += _containerName + "','";
209 //[RNV]: Comment the PyEval_AcquireLock() and PyEval_ReleaseLock() because this
210 //approach leads to the deadlock of the main thread of the application on Windows platform
211 //in case if cppContainer runs in the standalone mode. The problem with the PyThreadState
212 //described by ABN seems not reproduced, to be checked carefully later...
213 PyGILState_STATE gstate = PyGILState_Ensure();
215 //// [ABN]: using the PyGILState* API here is unstable. omniORB logic is invoked
216 //// by the Python code executed below, and in some (random) cases, the Python code
217 //// execution ends with a PyThreadState which was not the one we have here.
218 //// (TODO: understand why ...)
219 //// To be on the safe side we get and load the thread state ourselves:
220 //PyEval_AcquireLock(); // get GIL
221 //PyThreadState * mainThreadState = PyThreadState_Get();
222 //PyThreadState_Swap(mainThreadState);
225 // mpv: this is temporary solution: there is a unregular crash if not
228 // first element is the path to Registry.dll, but it's wrong
229 PyRun_SimpleString("import sys\n");
230 PyRun_SimpleString("sys.path = sys.path[1:]\n");
232 PyRun_SimpleString("import SALOME_Container\n");
233 PyRun_SimpleString((char*)myCommand.c_str());
234 PyObject *mainmod = PyImport_AddModule("__main__");
235 PyObject *globals = PyModule_GetDict(mainmod);
236 _pyCont = PyDict_GetItemString(globals, "pyCont");
238 //PyThreadState_Swap(NULL);
239 //PyEval_ReleaseLock();
240 PyGILState_Release(gstate);
242 fileTransfer_i* aFileTransfer = new fileTransfer_i();
243 CORBA::Object_var obref=aFileTransfer->_this();
244 _fileTransfer = Engines::fileTransfer::_narrow(obref);
245 aFileTransfer->_remove_ref();
249 //=============================================================================
253 //=============================================================================
255 Abstract_Engines_Container_i::~Abstract_Engines_Container_i()
257 MESSAGE("Abstract_Container_i::~Abstract_Container_i()");
265 //=============================================================================
266 //! Get container name
268 * CORBA attribute: Container name (see constructor)
270 //=============================================================================
272 char* Abstract_Engines_Container_i::name()
274 return CORBA::string_dup(_containerName.c_str()) ;
277 //=============================================================================
278 //! Get container working directory
280 * CORBA attribute: Container working directory
282 //=============================================================================
284 char* Abstract_Engines_Container_i::workingdir()
288 return CORBA::string_dup(wd) ;
291 //=============================================================================
292 //! Get container log file name
294 * CORBA attribute: Container log file name
296 //=============================================================================
298 char* Abstract_Engines_Container_i::logfilename()
300 return CORBA::string_dup(_logfilename.c_str()) ;
303 //! Set container log file name
304 void Abstract_Engines_Container_i::logfilename(const char* name)
309 //=============================================================================
310 //! Get container host name
312 * CORBA method: Get the hostName of the Container (without domain extensions)
314 //=============================================================================
316 char* Abstract_Engines_Container_i::getHostName()
318 std::string s = Kernel_Utils::GetHostname();
319 // MESSAGE("Engines_Container_i::getHostName " << s);
320 return CORBA::string_dup(s.c_str()) ;
323 //=============================================================================
324 //! Get container PID
326 * CORBA method: Get the PID (process identification) of the Container
328 //=============================================================================
330 CORBA::Long Abstract_Engines_Container_i::getPID()
332 return (CORBA::Long)getpid();
335 //=============================================================================
336 //! Ping the servant to check it is still alive
338 * CORBA method: check if servant is still alive
340 //=============================================================================
341 void Abstract_Engines_Container_i::ping()
343 MESSAGE("Engines_Container_i::ping() pid "<< getpid());
346 //=============================================================================
347 //! Get number of CPU cores in the calculation node
349 * CORBA method: get number of CPU cores
351 //=============================================================================
353 CORBA::Long Abstract_Engines_Container_i::getNumberOfCPUCores()
355 PyGILState_STATE gstate = PyGILState_Ensure();
356 PyObject *module = PyImport_ImportModuleNoBlock((char*)"salome_psutil");
357 PyObject *result = PyObject_CallMethod(module,
358 (char*)"getNumberOfCPUCores", NULL);
359 int n = PyLong_AsLong(result);
361 PyGILState_Release(gstate);
363 return (CORBA::Long)n;
366 //=============================================================================
367 //! Get a load of each CPU core in the calculation node
369 * CORBA method: get a load of each CPU core
371 //=============================================================================
373 std::string parseException()
376 if (PyErr_Occurred())
378 PyObject *ptype = nullptr;
379 PyObject *pvalue = nullptr;
380 PyObject *ptraceback = nullptr;
381 PyErr_Fetch(&ptype, &pvalue, &ptraceback);
382 if (ptype == nullptr)
383 return std::string("Null exception type");
384 PyErr_NormalizeException(&ptype, &pvalue, &ptraceback);
385 if (ptraceback != nullptr)
386 PyException_SetTraceback(pvalue, ptraceback);
387 boost::python::handle<> htype(ptype);
388 boost::python::handle<> hvalue(boost::python::allow_null(pvalue));
389 boost::python::handle<> htraceback(boost::python::allow_null(ptraceback));
390 boost::python::object traceback = boost::python::import("traceback");
391 boost::python::object format_exc = traceback.attr("format_exception");
392 boost::python::object formatted = format_exc(htype, hvalue, htraceback);
393 error = boost::python::extract<std::string>(boost::python::str("\n").join(formatted));
399 Engines::vectorOfDouble* Abstract_Engines_Container_i::loadOfCPUCores()
401 PyGILState_STATE gstate = PyGILState_Ensure();
402 PyObject *module = PyImport_ImportModuleNoBlock((char*)"salome_psutil");
403 PyObject *result = PyObject_CallMethod(module,
404 (char*)"loadOfCPUCores", "s",
405 _load_script.c_str());
406 if (PyErr_Occurred())
408 std::string error = parseException();
410 PyGILState_Release(gstate);
411 SALOME::ExceptionStruct es;
412 es.type = SALOME::INTERNAL_ERROR;
413 es.text = CORBA::string_dup(error.c_str());
414 throw SALOME::SALOME_Exception(es);
417 int n = this->getNumberOfCPUCores();
418 if (!PyList_Check(result) || PyList_Size(result) != n) {
419 // bad number of cores
420 PyGILState_Release(gstate);
422 SALOME::ExceptionStruct es;
423 es.type = SALOME::INTERNAL_ERROR;
424 es.text = "wrong number of cores";
425 throw SALOME::SALOME_Exception(es);
428 Engines::vectorOfDouble_var loads = new Engines::vectorOfDouble;
430 for (Py_ssize_t i = 0; i < PyList_Size(result); ++i) {
431 PyObject* item = PyList_GetItem(result, i);
432 double foo = PyFloat_AsDouble(item);
433 if (foo < 0.0 || foo > 1.0)
435 // value not in [0, 1] range
436 PyGILState_Release(gstate);
438 SALOME::ExceptionStruct es;
439 es.type = SALOME::INTERNAL_ERROR;
440 es.text = "load not in [0, 1] range";
441 throw SALOME::SALOME_Exception(es);
447 PyGILState_Release(gstate);
449 return loads._retn();
452 //=============================================================================
453 //! Set custom script to calculate a load of each CPU core
455 * CORBA method: Set custom script to calculate CPU load
456 * \param script Python script to execute
458 //=============================================================================
460 void Abstract_Engines_Container_i::setPyScriptForCPULoad(const char *script)
462 _load_script = script;
465 //=============================================================================
466 //! Nullify custom script to calculate each CPU core's load
468 * CORBA method: reset script for load calculation to default implementation
470 //=============================================================================
472 void Abstract_Engines_Container_i::resetScriptForCPULoad()
477 //=============================================================================
478 //! Get total physical memory of calculation node, in megabytes
480 * CORBA method: get total physical memory of calculation node
482 //=============================================================================
484 CORBA::Long Abstract_Engines_Container_i::getTotalPhysicalMemory()
486 PyGILState_STATE gstate = PyGILState_Ensure();
487 PyObject *module = PyImport_ImportModuleNoBlock((char*)"salome_psutil");
488 PyObject *result = PyObject_CallMethod(module,
489 (char*)"getTotalPhysicalMemory", NULL);
490 int n = PyLong_AsLong(result);
492 PyGILState_Release(gstate);
494 return (CORBA::Long)n;
497 //=============================================================================
498 //! Get used physical memory of calculation node, in megabytes
500 * CORBA method: get used physical memory of calculation node
502 //=============================================================================
504 CORBA::Long Abstract_Engines_Container_i::getTotalPhysicalMemoryInUse()
506 PyGILState_STATE gstate = PyGILState_Ensure();
507 PyObject *module = PyImport_ImportModuleNoBlock((char*)"salome_psutil");
508 PyObject *result = PyObject_CallMethod(module,
509 (char*)"getTotalPhysicalMemoryInUse", NULL);
510 int n = PyLong_AsLong(result);
512 PyGILState_Release(gstate);
514 return (CORBA::Long)n;
517 //=============================================================================
518 //! Obtain physical memory, used by the current process, in megabytes.
520 * CORBA method: get physical memory, used by the current process
522 //=============================================================================
524 CORBA::Long Abstract_Engines_Container_i::getTotalPhysicalMemoryInUseByMe()
526 PyGILState_STATE gstate = PyGILState_Ensure();
527 PyObject *module = PyImport_ImportModuleNoBlock((char*)"salome_psutil");
528 PyObject *result = PyObject_CallMethod(module,
529 (char*)"getTotalPhysicalMemoryInUseByMe", NULL);
530 int n = PyLong_AsLong(result);
532 PyGILState_Release(gstate);
534 return (CORBA::Long)n;
537 //=============================================================================
538 //! Shutdown the container
540 * CORBA method, oneway: Server shutdown.
541 * - Container name removed from naming service,
542 * - servant deactivation,
543 * - orb shutdown if no other servants in the process
545 //=============================================================================
546 void Abstract_Engines_Container_i::Shutdown()
548 MESSAGE("Engines_Container_i::Shutdown()");
550 // Clear registered temporary files
551 clearTemporaryFiles();
553 /* For each component contained in this container
554 * tell it to self-destroy
556 std::map<std::string, Engines::EngineComponent_var>::iterator itm;
557 for (itm = _listInstances_map.begin(); itm != _listInstances_map.end(); itm++)
561 itm->second->destroy();
563 catch(const CORBA::Exception&)
565 // ignore this entry and continue
569 // ignore this entry and continue
572 _listInstances_map.clear();
574 // NS unregistering may throw in SSL mode if master process hosting SALOME_Embedded_NamingService servant has vanished
575 // In this case it's skip it and still continue.
578 _NS->Destroy_FullDirectory(_containerName.c_str());
579 _NS->Destroy_Name(_containerName.c_str());
585 this->cleanAllPyScripts();
587 if(_isServantAloneInProcess)
589 MESSAGE("Effective Shutdown of container Begins...");
590 if(!CORBA::is_nil(_orb))
595 //=============================================================================
596 //! load a component implementation
599 * \param componentName component name
600 * \param reason explains error when load fails
601 * \return true if dlopen successful or already done, false otherwise
603 //=============================================================================
605 Abstract_Engines_Container_i::load_component_Library(const char* componentName, CORBA::String_out reason)
608 //=================================================================
609 // --- C++ implementation section
610 //=================================================================
612 if(load_component_CppImplementation(componentName,retso))
614 reason=CORBA::string_dup("");
617 else if(retso != "ImplementationNotFound")
619 reason=CORBA::string_dup(retso.c_str());
624 retso+=componentName;
625 retso+=": Can't find C++ implementation ";
626 retso+=std::string(LIB) + componentName + ENGINESO;
628 //=================================================================
629 // --- Python implementation section
630 //=================================================================
632 if(load_component_PythonImplementation(componentName,retpy))
634 reason=CORBA::string_dup("");
637 else if(retpy != "ImplementationNotFound")
639 reason=CORBA::string_dup(retpy.c_str());
644 retpy+=componentName;
645 retpy+=": Can't find python implementation ";
646 retpy+=componentName;
649 //=================================================================
650 // -- Executable implementation section
651 //=================================================================
653 if(load_component_ExecutableImplementation(componentName,retex))
655 reason=CORBA::string_dup("");
658 else if(retex != "ImplementationNotFound")
660 reason=CORBA::string_dup(retex.c_str());
665 retex+=componentName;
666 retex+=": Can't find executable implementation ";
667 retex+=componentName;
670 std::string ret="Component implementation not found: ";
671 ret += componentName ;
677 std::cerr << ret << std::endl;
678 reason=CORBA::string_dup(ret.c_str());
683 //=============================================================================
684 //! try to load a C++ component implementation
687 * \param componentName the name of the component (COMPONENT, for example)
688 * \param reason explains error when load fails
689 * \return true if loading is successful or already done, false otherwise
691 //=============================================================================
693 Abstract_Engines_Container_i::load_component_CppImplementation(const char* componentName, std::string& reason)
695 std::string aCompName(componentName);
696 std::string impl_name = std::string(LIB) + aCompName + ENGINESO;
699 _numInstanceMutex.lock(); // lock to be alone
700 // (see decInstanceCnt, finalize_removal))
701 if (_toRemove_map.count(impl_name) != 0) _toRemove_map.erase(impl_name);
702 if (_library_map.count(impl_name) != 0)
704 MESSAGE("Library " << impl_name << " already loaded");
705 _numInstanceMutex.unlock();
709 _numInstanceMutex.unlock();
713 handle = dlopen( impl_name.c_str() , RTLD_NOW | RTLD_GLOBAL ) ;
716 //not loadable. Try to find the lib file in LD_LIBRARY_PATH
719 char* p=getenv("DYLD_LIBRARY_PATH");
721 char* p=getenv("LD_LIBRARY_PATH");
724 path=path+SEP+"/usr/lib"+SEP+"/lib";
727 if(findpathof(path, pth, impl_name))
729 //found but not loadable
732 reason+=": C++ implementation found ";
734 reason+=" but it is not loadable. Error:\n";
736 std::cerr << reason << std::endl;
742 //continue with other implementation
743 reason="ImplementationNotFound";
750 std::wstring libToLoad = Kernel_Utils::utf8_decode_s( impl_name );
752 std::string libToLoad = impl_name;
754 handle = LoadLibrary(libToLoad.c_str() );
757 reason="ImplementationNotFound";
763 _numInstanceMutex.lock();
764 _library_map[impl_name] = handle;
765 _numInstanceMutex.unlock();
773 //=============================================================================
774 //! try to load a Python component implementation
777 * \param componentName name of the component
778 * \param reason explains error when load fails
779 * \return true if loading is successful or already done, false otherwise
781 //=============================================================================
783 Abstract_Engines_Container_i::load_component_PythonImplementation(const char* componentName, std::string& reason)
785 std::string aCompName(componentName);
787 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
788 if (_library_map.count(aCompName) != 0)
790 _numInstanceMutex.unlock() ;
792 return true; // Python Component, already imported
794 _numInstanceMutex.unlock() ;
796 PyGILState_STATE gstate = PyGILState_Ensure();
797 PyObject *result = PyObject_CallMethod(_pyCont,
798 (char*)"import_component",
799 (char*)"s",componentName);
801 reason=PyUnicode_AsUTF8(result);
804 PyGILState_Release(gstate);
808 //Python component has been loaded (import componentName)
809 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
810 _library_map[aCompName] = (void *)_pyCont; // any non O value OK
811 _numInstanceMutex.unlock() ;
812 MESSAGE("import Python: "<< aCompName <<" OK");
815 else if(reason=="ImplementationNotFound")
817 //Python implementation has not been found. Continue with other implementation
818 reason="ImplementationNotFound";
822 //Python implementation has been found but loading has failed
823 std::cerr << reason << std::endl;
828 //=============================================================================
829 //! try to load a Executable component implementation
832 * \param componentName name of the component
833 * \param reason explains error when load fails
834 * \return true if loading is successful or already done, false otherwise
836 //=============================================================================
838 Abstract_Engines_Container_i::load_component_ExecutableImplementation(const char* componentName, std::string& reason)
840 std::string aCompName(componentName);
841 std::string executable=aCompName+".exe";
846 char* p=getenv("PATH");
849 if (findpathof(path, pth, executable))
851 if(checkifexecutable(pth))
853 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
854 _library_map[executable] = (void *)1; // any non O value OK
855 _numInstanceMutex.unlock() ;
856 MESSAGE("import executable: "<< pth <<" OK");
862 reason+=": implementation found ";
864 reason+=" but it is not executable";
865 std::cerr << reason << std::endl;
869 reason="ImplementationNotFound";
874 //=============================================================================
875 //! Create a new component instance
877 * CORBA method: Creates a new servant instance of a component.
878 * The servant registers itself to naming service and Registry.
879 * \param genericRegisterName Name of the component instance to register
880 * in Registry & Name Service (without _inst_n suffix)
881 * \return a loaded component
883 //=============================================================================
884 Engines::EngineComponent_ptr
885 Abstract_Engines_Container_i::create_component_instance(const char*genericRegisterName)
887 Engines::FieldsDict_var env = new Engines::FieldsDict;
889 Engines::EngineComponent_ptr compo =
890 create_component_instance_env(genericRegisterName, env, reason);
891 CORBA::string_free(reason);
895 //=============================================================================
896 //! Create a new component instance with environment variables specified
898 * CORBA method: Creates a new servant instance of a component.
899 * The servant registers itself to naming service and Registry.
900 * \param genericRegisterName Name of the component instance to register
901 * in Registry & Name Service (without _inst_n suffix)
902 * \param env dict of env variables
903 * \param reason explains error when create_component_instance_env fails
904 * \return a loaded component
906 //=============================================================================
907 Engines::EngineComponent_ptr
908 Abstract_Engines_Container_i::create_component_instance_env(const char*genericRegisterName,
909 const Engines::FieldsDict& env,
910 CORBA::String_out reason)
913 if (_library_map.count(genericRegisterName) != 0)
915 // It's a Python component
916 Engines::EngineComponent_ptr compo = createPythonInstance(genericRegisterName, error);
917 reason=CORBA::string_dup(error.c_str());
921 std::string impl_name = std::string(LIB) + genericRegisterName + ENGINESO;
922 if (_library_map.count(impl_name) != 0)
924 // It's a C++ component
925 void* handle = _library_map[impl_name];
926 Engines::EngineComponent_ptr compo = createInstance(genericRegisterName, handle, error);
927 reason=CORBA::string_dup(error.c_str());
931 impl_name = std::string(genericRegisterName) + ".exe";
932 if (_library_map.count(impl_name) != 0)
934 //It's an executable component
935 Engines::EngineComponent_ptr compo = createExecutableInstance(genericRegisterName, env, error);
936 reason=CORBA::string_dup(error.c_str());
940 error="load_component_Library has probably not been called for component: ";
941 error += genericRegisterName;
943 reason=CORBA::string_dup(error.c_str());
944 return Engines::EngineComponent::_nil() ;
947 //=============================================================================
948 //! Create a new component instance (Executable implementation)
950 * \param CompName Name of the component instance
951 * \param env dict of env variables
952 * \param reason explains error when creation fails
953 * \return a loaded component
955 * This component is implemented in an executable with name genericRegisterName.exe
956 * It must register itself in Naming Service. The container waits some time (10 s max)
959 //=============================================================================
960 Engines::EngineComponent_ptr
961 Abstract_Engines_Container_i::createExecutableInstance(std::string CompName,
962 const Engines::FieldsDict& env,
965 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
967 _numInstanceMutex.lock() ; // lock on the instance number
969 int numInstance = _numInstance ;
970 _numInstanceMutex.unlock() ;
973 sprintf( aNumI , "%d" , numInstance ) ;
974 std::string instanceName = CompName + "_inst_" + aNumI ;
975 std::string component_registerName = _containerName + "/" + instanceName;
977 //check if an entry exist in naming service
978 CORBA::Object_var nsobj = _NS->Resolve(component_registerName.c_str());
979 if ( !CORBA::is_nil(nsobj) )
981 // unregister the registered component
982 _NS->Destroy_Name(component_registerName.c_str());
983 //kill or shutdown it ???
986 // first arg container ior string
987 // second arg container name
988 // third arg instance name
990 Engines::Container_var pCont= _this();
991 CORBA::String_var sior = _orb->object_to_string(pCont);
995 command+=instanceName;
997 command+=instanceName;
1002 command+= sior; // container ior string
1004 command+=_containerName; //container name
1006 command+=instanceName; //instance name
1008 MESSAGE("SALOME_Container::create_component_instance command=" << command);
1011 // use fork/execl instead of system to get finer control on env variables
1014 if(pid == 0) // child
1016 for (CORBA::ULong i=0; i < env.length(); i++)
1018 if (env[i].value.type()->kind() == CORBA::tk_string)
1021 env[i].value >>= value;
1022 std::string s(env[i].key);
1025 putenv(strdup(s.c_str()));
1029 execl("/bin/sh", "sh", "-c", command.c_str() , (char *)0);
1032 else if(pid < 0) // failed to fork
1041 tpid = wait(&status);
1042 } while (tpid != pid);
1045 // launch component with a system call
1046 int status=system(command.c_str());
1051 reason="SALOME_Container::create_component_instance system failed (system command status -1)";
1053 return Engines::EngineComponent::_nil();
1056 else if (WEXITSTATUS(status) == 217)
1058 reason="SALOME_Container::create_component_instance system failed (system command status 217)";
1060 return Engines::EngineComponent::_nil();
1066 if (getenv("TIMEOUT_TO_WAIT_EXE_COMPONENT") != 0)
1068 std::string new_count_str = getenv("TIMEOUT_TO_WAIT_EXE_COMPONENT");
1070 std::istringstream ss(new_count_str);
1071 if (!(ss >> new_count))
1073 INFOS("[Container] TIMEOUT_TO_WAIT_EXE_COMPONENT should be an int");
1078 INFOS("[Container] waiting " << count << " second steps exe component ");
1079 CORBA::Object_var obj = CORBA::Object::_nil() ;
1080 while ( CORBA::is_nil(obj) && count )
1088 MESSAGE( count << ". Waiting for component " << CompName);
1089 obj = _NS->Resolve(component_registerName.c_str());
1092 if(CORBA::is_nil(obj))
1094 reason="SALOME_Container::create_component_instance failed";
1096 return Engines::EngineComponent::_nil();
1100 MESSAGE("SALOME_Container::create_component_instance successful");
1101 iobject = Engines::EngineComponent::_narrow(obj);
1102 _listInstances_map[instanceName] = iobject;
1103 return iobject._retn();
1109 //=============================================================================
1110 //! Create a new component instance (Python implementation)
1112 * \param CompName Name of the component instance
1113 * \param reason explains error when creation fails
1114 * \return a loaded component
1116 //=============================================================================
1117 Engines::EngineComponent_ptr
1118 Abstract_Engines_Container_i::createPythonInstance(std::string CompName,
1119 std::string& reason)
1121 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1123 _numInstanceMutex.lock() ; // lock on the instance number
1125 int numInstance = _numInstance ;
1126 _numInstanceMutex.unlock() ;
1129 sprintf( aNumI , "%d" , numInstance ) ;
1130 std::string instanceName = CompName + "_inst_" + aNumI ;
1131 std::string component_registerName = _containerName + "/" + instanceName;
1133 PyGILState_STATE gstate = PyGILState_Ensure();
1134 PyObject *result = PyObject_CallMethod(_pyCont,
1135 (char*)"create_component_instance",
1138 instanceName.c_str());
1141 PyArg_ParseTuple(result,"ss", &ior, &error);
1142 std::string iors = ior;
1145 PyGILState_Release(gstate);
1149 CORBA::Object_var obj = _orb->string_to_object(iors.c_str());
1150 iobject = Engines::EngineComponent::_narrow( obj ) ;
1151 _listInstances_map[instanceName] = iobject;
1153 return iobject._retn();
1157 Abstract_Engines_Container_i::create_python_service_instance(const char * CompName,
1158 CORBA::String_out reason)
1160 CORBA::Object_var object = CORBA::Object::_nil();
1162 _numInstanceMutex.lock() ; // lock on the instance number
1164 int numInstance = _numInstance ;
1165 _numInstanceMutex.unlock() ;
1168 sprintf( aNumI , "%d" , numInstance ) ;
1169 std::string instanceName = std::string(CompName) + "_inst_" + aNumI ;
1170 std::string component_registerName = _containerName + "/" + instanceName;
1172 PyGILState_STATE gstate = PyGILState_Ensure();
1173 PyObject *result = PyObject_CallMethod(_pyCont,
1174 (char*)"create_component_instance",
1177 instanceName.c_str());
1180 PyArg_ParseTuple(result,"ss", &ior, &error);
1181 reason = CORBA::string_dup(error);
1182 char * _ior = CORBA::string_dup(ior);
1184 PyGILState_Release(gstate);
1190 //=============================================================================
1191 //! Create a new component instance (C++ implementation)
1193 * C++ method: create a servant instance of a component.
1194 * \param genericRegisterName Name of the component instance to register
1195 * in Registry & Name Service,
1196 * (without _inst_n suffix, like "COMPONENT")
1197 * \param handle loaded library handle
1198 * \param reason explains error when creation fails
1199 * \return a loaded component
1201 * example with names:
1202 * - aGenRegisterName = COMPONENT (= first argument)
1203 * - _containerName = /Containers/cli76ce/FactoryServer
1204 * - factoryName = COMPONENTEngine_factory
1205 * - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
1206 * - instanceName = COMPONENT_inst_1
1207 * - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1209 //=============================================================================
1210 Engines::EngineComponent_ptr
1211 Abstract_Engines_Container_i::createInstance(std::string genericRegisterName,
1213 std::string& reason)
1215 // --- find the factory
1217 std::string aGenRegisterName = genericRegisterName;
1218 std::string factory_name = aGenRegisterName + std::string("Engine_factory");
1219 SCRUTE(factory_name) ;
1221 typedef PortableServer::ObjectId* (*FACTORY_FUNCTION) (CORBA::ORB_ptr,
1222 PortableServer::POA_ptr,
1223 PortableServer::ObjectId *,
1228 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)dlsym( handle, factory_name.c_str() );
1230 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)GetProcAddress( (HINSTANCE)handle, factory_name.c_str() );
1233 if ( !Component_factory )
1235 MESSAGE( "Can't resolve symbol: " + factory_name );
1240 return Engines::EngineComponent::_nil() ;
1243 // --- create instance
1245 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1249 _numInstanceMutex.lock() ; // lock on the instance number
1251 int numInstance = _numInstance ;
1252 _numInstanceMutex.unlock() ;
1255 sprintf( aNumI , "%d" , numInstance ) ;
1256 std::string instanceName = aGenRegisterName + "_inst_" + aNumI ;
1257 std::string component_registerName =
1258 _containerName + "/" + instanceName;
1260 // --- Instantiate required CORBA object
1262 PortableServer::ObjectId *id ; //not owner, do not delete (nore use var)
1263 id = (Component_factory) ( _orb, _poa, _id, instanceName.c_str(),
1264 aGenRegisterName.c_str() ) ;
1267 reason="Can't get ObjectId from factory";
1269 return iobject._retn();
1272 // --- get reference from id
1274 CORBA::Object_var obj = _poa->id_to_reference(*id);
1275 iobject = Engines::EngineComponent::_narrow( obj ) ;
1277 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1278 _listInstances_map[instanceName] = iobject;
1279 _cntInstances_map[aGenRegisterName] += 1;
1280 _numInstanceMutex.unlock() ;
1281 SCRUTE(aGenRegisterName);
1282 SCRUTE(_cntInstances_map[aGenRegisterName]);
1284 // --- register the engine under the name
1285 // containerName(.dir)/instanceName(.object)
1287 _NS->Register( iobject , component_registerName.c_str() ) ;
1288 MESSAGE( component_registerName.c_str() << " bound" ) ;
1292 reason="Container_i::createInstance exception caught";
1295 return iobject._retn();
1298 //=============================================================================
1299 //! Find an existing (in the container) component instance
1301 * CORBA method: Finds a servant instance of a component
1302 * \param registeredName Name of the component in Registry or Name Service,
1303 * without instance suffix number
1304 * \return the first found instance
1306 //=============================================================================
1307 Engines::EngineComponent_ptr
1308 Abstract_Engines_Container_i::find_component_instance( const char* registeredName)
1310 Engines::EngineComponent_var anEngine = Engines::EngineComponent::_nil();
1311 std::map<std::string,Engines::EngineComponent_var>::iterator itm =_listInstances_map.begin();
1312 while (itm != _listInstances_map.end())
1314 std::string instance = (*itm).first;
1316 if (instance.find(registeredName) == 0)
1318 anEngine = (*itm).second;
1319 return anEngine._retn();
1323 return anEngine._retn();
1326 //=============================================================================
1327 //! Remove the component instance from container
1329 * CORBA method: Stops the component servant, and deletes all related objects
1330 * \param component_i Component to be removed
1332 //=============================================================================
1334 void Abstract_Engines_Container_i::remove_impl(Engines::EngineComponent_ptr component_i)
1336 ASSERT(! CORBA::is_nil(component_i));
1337 std::string instanceName = component_i->instanceName() ;
1338 MESSAGE("unload component " << instanceName);
1339 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1340 _listInstances_map.erase(instanceName);
1341 _numInstanceMutex.unlock() ;
1342 component_i->destroy() ;
1343 _NS->Destroy_Name(instanceName.c_str());
1346 //=============================================================================
1347 //! Unload component libraries from the container
1349 * CORBA method: Discharges unused libraries from the container.
1351 //=============================================================================
1352 void Abstract_Engines_Container_i::finalize_removal()
1354 MESSAGE("finalize unload : dlclose");
1355 _numInstanceMutex.lock(); // lock to be alone
1356 // (see decInstanceCnt, load_component_Library)
1357 std::map<std::string, void *>::iterator ith;
1358 for (ith = _toRemove_map.begin(); ith != _toRemove_map.end(); ith++)
1360 void *handle = (*ith).second;
1361 std::string impl_name= (*ith).first;
1366 // dlclose(handle); // SALOME unstable after ...
1367 // _library_map.erase(impl_name);
1370 _toRemove_map.clear();
1371 _numInstanceMutex.unlock();
1374 //=============================================================================
1375 //! Decrement component instance reference count
1379 //=============================================================================
1380 void Abstract_Engines_Container_i::decInstanceCnt(std::string genericRegisterName)
1382 if(_cntInstances_map.count(genericRegisterName)==0)
1384 std::string aGenRegisterName =genericRegisterName;
1385 MESSAGE("Engines_Container_i::decInstanceCnt " << aGenRegisterName);
1386 ASSERT(_cntInstances_map[aGenRegisterName] > 0);
1387 _numInstanceMutex.lock(); // lock to be alone
1388 // (see finalize_removal, load_component_Library)
1389 _cntInstances_map[aGenRegisterName] -= 1;
1390 SCRUTE(_cntInstances_map[aGenRegisterName]);
1391 if (_cntInstances_map[aGenRegisterName] == 0)
1393 std::string impl_name =
1394 Engines_Component_i::GetDynLibraryName(aGenRegisterName.c_str());
1396 void* handle = _library_map[impl_name];
1398 _toRemove_map[impl_name] = handle;
1400 _numInstanceMutex.unlock();
1403 //=============================================================================
1404 //! Find or create a new component instance
1406 * CORBA method: find or create an instance of the component (servant),
1407 * load a new component class (dynamic library) if required,
1409 * ---- FOR COMPATIBILITY WITH 2.2 ----
1411 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
1413 * The servant registers itself to naming service and Registry.
1414 * \param genericRegisterName Name of the component to register
1415 * in Registry & Name Service
1416 * \param componentName Name of the constructed library of the component
1417 * \return a loaded component
1419 //=============================================================================
1421 Engines::EngineComponent_ptr
1422 Abstract_Engines_Container_i::load_impl( const char* genericRegisterName,
1423 const char* /*componentName*/ )
1426 std::string impl_name = std::string(LIB) + genericRegisterName + ENGINESO;
1427 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1428 if (load_component_Library(genericRegisterName,reason))
1429 iobject = find_or_create_instance(genericRegisterName, impl_name);
1430 CORBA::string_free(reason);
1431 return iobject._retn();
1434 Engines::EmbeddedNamingService_ptr Abstract_Engines_Container_i::get_embedded_NS_if_ssl()
1436 SALOME_Embedded_NamingService_Client *nsc(dynamic_cast<SALOME_Embedded_NamingService_Client *>(this->_NS));
1439 Engines::EmbeddedNamingService_var obj = nsc->GetObject();
1440 return Engines::EmbeddedNamingService::_duplicate(obj);
1444 return Engines::EmbeddedNamingService::_nil();
1448 //=============================================================================
1449 //! Finds an already existing component instance or create a new instance
1451 * C++ method: Finds an already existing servant instance of a component, or
1452 * create an instance.
1453 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
1454 * \param genericRegisterName Name of the component instance to register
1455 * in Registry & Name Service,
1456 * (without _inst_n suffix, like "COMPONENT")
1457 * \param componentLibraryName like "libCOMPONENTEngine.so"
1458 * \return a loaded component
1460 * example with names:
1461 * - aGenRegisterName = COMPONENT (= first argument)
1462 * - impl_name = libCOMPONENTEngine.so (= second argument)
1463 * - _containerName = /Containers/cli76ce/FactoryServer
1464 * - factoryName = COMPONENTEngine_factory
1465 * - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
1466 * - instanceName = COMPONENT_inst_1
1467 * - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1469 //=============================================================================
1471 Engines::EngineComponent_ptr
1472 Abstract_Engines_Container_i::find_or_create_instance(std::string genericRegisterName,
1473 std::string componentLibraryName)
1475 std::string aGenRegisterName = genericRegisterName;
1476 std::string impl_name = componentLibraryName;
1477 if (_library_map.count(impl_name) == 0)
1479 INFOS("shared library " << impl_name <<" must be loaded before creating instance");
1480 return Engines::EngineComponent::_nil() ;
1484 // --- find a registered instance in naming service, or create
1486 void* handle = _library_map[impl_name];
1487 std::string component_registerBase =
1488 _containerName + "/" + aGenRegisterName;
1489 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1493 CORBA::Object_var obj =
1494 _NS->ResolveFirst( component_registerBase.c_str());
1495 if ( CORBA::is_nil( obj ) )
1497 iobject = createInstance(genericRegisterName,
1503 iobject = Engines::EngineComponent::_narrow( obj ) ;
1508 INFOS( "Container_i::load_impl caught" ) ;
1510 return iobject._retn();
1514 //=============================================================================
1515 //! Indicate if container is a python one
1517 * Retrieves only with container naming convention if it is a python container
1519 //=============================================================================
1520 bool Abstract_Engines_Container_i::isPythonContainer(const char* ContainerName)
1523 size_t len=strlen(ContainerName);
1525 if(strcmp(ContainerName+len-2,"Py")==0)
1530 //=============================================================================
1531 //! Kill the container
1533 * CORBA method: Kill the container process with exit(0).
1534 * To remove : never returns !
1536 //=============================================================================
1537 bool Abstract_Engines_Container_i::Kill_impl()
1539 MESSAGE("Engines_Container_i::Kill() pid "<< getpid() << " containerName "
1540 << _containerName.c_str() << " machineName "
1541 << Kernel_Utils::GetHostname().c_str());
1542 INFOS("===============================================================");
1543 INFOS("= REMOVE calls to Kill_impl in C++ container =");
1544 INFOS("===============================================================");
1550 //=============================================================================
1554 //=============================================================================
1555 void ActSigIntHandler()
1558 struct sigaction SigIntAct ;
1559 SigIntAct.sa_sigaction = &SigIntHandler ;
1560 sigemptyset(&SigIntAct.sa_mask);
1561 SigIntAct.sa_flags = SA_SIGINFO ;
1564 // DEBUG 03.02.2005 : the first parameter of sigaction is not a mask of signals
1565 // (SIGINT | SIGUSR1) :
1566 // it must be only one signal ===> one call for SIGINT
1567 // and an other one for SIGUSR1
1570 if ( sigaction( SIGINT , &SigIntAct, NULL ) )
1572 perror("SALOME_Container main ") ;
1575 if ( sigaction( SIGUSR1 , &SigIntAct, NULL ) )
1577 perror("SALOME_Container main ") ;
1580 if ( sigaction( SIGUSR2 , &SigIntAct, NULL ) )
1582 perror("SALOME_Container main ") ;
1586 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1587 // use of streams (and so on) should never be used because :
1588 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1589 // A stream operation may be interrupted by a signal and if the Handler use stream we
1590 // may have a "Dead-Lock" ===HangUp
1591 //==INFOS is commented
1592 // INFOS(pthread_self() << "SigIntHandler activated") ;
1595 signal( SIGINT, SigIntHandler );
1596 // legacy code required to supervisor. Commented in order to avoid problems on Windows
1597 // signal( SIGUSR1, SigIntHandler );
1603 void CallCancelThread() ;
1606 void SigIntHandler(int /*what*/ ,
1607 siginfo_t * siginfo ,
1610 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1611 // use of streams (and so on) should never be used because :
1612 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1613 // A stream operation may be interrupted by a signal and if the Handler use stream we
1614 // may have a "Dead-Lock" ===HangUp
1615 //==MESSAGE is commented
1616 // MESSAGE(pthread_self() << "SigIntHandler what " << what << std::endl
1617 // << " si_signo " << siginfo->si_signo << std::endl
1618 // << " si_code " << siginfo->si_code << std::endl
1619 // << " si_pid " << siginfo->si_pid) ;
1624 // MESSAGE("SigIntHandler END sleeping.") ;
1629 ActSigIntHandler() ;
1630 if ( siginfo->si_signo == SIGUSR1 )
1634 else if ( siginfo->si_signo == SIGUSR2 )
1636 CallCancelThread() ;
1641 // MESSAGE("SigIntHandler BEGIN sleeping.") ;
1648 // MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1654 void SigIntHandler( int what )
1657 MESSAGE( pthread_self() << "SigIntHandler what " << what << std::endl );
1659 MESSAGE( "SigIntHandler what " << what << std::endl );
1664 MESSAGE("SigIntHandler END sleeping.") ;
1669 ActSigIntHandler() ;
1670 if ( what == SIGUSR1 )
1677 MESSAGE("SigIntHandler BEGIN sleeping.") ;
1684 MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1691 //=============================================================================
1692 //! Get or create a file reference object associated to a local file (to transfer it)
1694 * CORBA method: get or create a fileRef object associated to a local file
1695 * (a file on the computer on which runs the container server), which stores
1696 * a list of (machine, localFileName) corresponding to copies already done.
1698 * \param origFileName absolute path for a local file to copy on other
1700 * \return a fileRef object associated to the file.
1702 //=============================================================================
1703 Engines::fileRef_ptr
1704 Abstract_Engines_Container_i::createFileRef(const char* origFileName)
1706 std::string origName(origFileName);
1707 Engines::fileRef_var theFileRef = Engines::fileRef::_nil();
1709 if (origName[0] != '/')
1711 INFOS("path of file to copy must be an absolute path beginning with '/'");
1712 return Engines::fileRef::_nil();
1715 if (CORBA::is_nil(_fileRef_map[origName]))
1717 CORBA::Object_var obj=_poa->id_to_reference(*_id);
1718 Engines::Container_var pCont = Engines::Container::_narrow(obj);
1719 fileRef_i* aFileRef = new fileRef_i(pCont, origFileName);
1720 theFileRef = Engines::fileRef::_narrow(aFileRef->_this());
1721 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1722 _fileRef_map[origName] = theFileRef;
1723 _numInstanceMutex.unlock() ;
1726 theFileRef = Engines::fileRef::_duplicate(_fileRef_map[origName]);
1727 ASSERT(! CORBA::is_nil(theFileRef));
1728 return theFileRef._retn();
1731 //=============================================================================
1732 //! Get a fileTransfer reference
1735 * \return a reference to the fileTransfer object
1737 //=============================================================================
1738 Engines::fileTransfer_ptr
1739 Abstract_Engines_Container_i::getFileTransfer()
1741 Engines::fileTransfer_var aFileTransfer
1742 = Engines::fileTransfer::_duplicate(_fileTransfer);
1743 return aFileTransfer._retn();
1746 //=============================================================================
1747 //! Create a Salome file
1748 //=============================================================================
1749 Engines::Salome_file_ptr
1750 Abstract_Engines_Container_i::createSalome_file(const char* origFileName)
1752 std::string origName(origFileName);
1753 if (CORBA::is_nil(_Salome_file_map[origName]))
1755 Salome_file_i* aSalome_file = new Salome_file_i();
1756 aSalome_file->setContainer(Engines::Container::_duplicate(this->_this()));
1759 aSalome_file->setLocalFile(origFileName);
1760 aSalome_file->recvFiles();
1762 catch (const SALOME::SALOME_Exception& /*e*/) //!< TODO: unused variable
1764 return Engines::Salome_file::_nil();
1767 Engines::Salome_file_var theSalome_file = Engines::Salome_file::_nil();
1768 theSalome_file = Engines::Salome_file::_narrow(aSalome_file->_this());
1769 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1770 _Salome_file_map[origName] = theSalome_file;
1771 _numInstanceMutex.unlock() ;
1774 Engines::Salome_file_ptr theSalome_file =
1775 Engines::Salome_file::_duplicate(_Salome_file_map[origName]);
1776 ASSERT(!CORBA::is_nil(theSalome_file));
1777 return theSalome_file;
1780 //=============================================================================
1781 /*! \brief copy a file from a remote host (container) to the local host
1782 * \param container the remote container
1783 * \param remoteFile the file to copy locally from the remote host into localFile
1784 * \param localFile the local file
1786 //=============================================================================
1787 void Abstract_Engines_Container_i::copyFile(Engines::Container_ptr container, const char* remoteFile, const char* localFile)
1789 Engines::fileTransfer_var fileTransfer = container->getFileTransfer();
1792 if ((fp = fopen(localFile,"wb")) == NULL)
1794 INFOS("file " << localFile << " cannot be open for writing");
1798 CORBA::Long fileId = fileTransfer->open(remoteFile);
1801 Engines::fileBlock* aBlock;
1808 aBlock = fileTransfer->getBlock(fileId);
1809 toFollow = aBlock->length();
1811 CORBA::Octet *buf = aBlock->get_buffer();
1812 fwrite(buf, sizeof(CORBA::Octet), toFollow, fp);
1816 MESSAGE("end of transfer");
1817 fileTransfer->close(fileId);
1821 INFOS("open reference file for copy impossible");
1825 //=============================================================================
1826 /*! \brief create a PyNode object to execute remote python code
1827 * \param nodeName the name of the node
1828 * \param code the python code to load
1829 * \return the PyNode
1831 //=============================================================================
1832 Engines::PyNode_ptr Abstract_Engines_Container_i::createPyNode(const char* nodeName, const char* code)
1834 Engines::PyNode_var node= Engines::PyNode::_nil();
1836 PyGILState_STATE gstate = PyGILState_Ensure();
1837 PyObject *res = PyObject_CallMethod(_pyCont,
1838 (char*)"create_pynode",
1846 PyGILState_Release(gstate);
1847 SALOME::ExceptionStruct es;
1848 es.type = SALOME::INTERNAL_ERROR;
1849 es.text = "can not create a python node";
1850 throw SALOME::SALOME_Exception(es);
1852 long ierr=PyLong_AsLong(PyTuple_GetItem(res,0));
1853 PyObject* result=PyTuple_GetItem(res,1);
1854 std::string astr=PyUnicode_AsUTF8(result);
1856 PyGILState_Release(gstate);
1859 Utils_Locker lck(&_mutexForDftPy);
1860 CORBA::Object_var obj=_orb->string_to_object(astr.c_str());
1861 node=Engines::PyNode::_narrow(obj);
1862 std::map<std::string,Engines::PyNode_var>::iterator it(_dftPyNode.find(nodeName));
1863 if(it==_dftPyNode.end())
1865 _dftPyNode[nodeName]=node;
1869 Engines::PyNode_var oldNode((*it).second);
1870 if(!CORBA::is_nil(oldNode))
1871 oldNode->UnRegister();
1874 if(!CORBA::is_nil(node))
1876 return node._retn();
1880 SALOME::ExceptionStruct es;
1881 es.type = SALOME::INTERNAL_ERROR;
1882 es.text = astr.c_str();
1883 throw SALOME::SALOME_Exception(es);
1887 //=============================================================================
1888 /*! \brief Retrieves the last created PyNode instance with createPyNode.
1891 //=============================================================================
1892 Engines::PyNode_ptr Abstract_Engines_Container_i::getDefaultPyNode(const char *nodeName)
1894 Utils_Locker lck(&_mutexForDftPy);
1895 std::map<std::string,Engines::PyNode_var>::iterator it(_dftPyNode.find(nodeName));
1896 if(it==_dftPyNode.end())
1897 return Engines::PyNode::_nil();
1900 Engines::PyNode_var tmpVar((*it).second);
1901 if(!CORBA::is_nil(tmpVar))
1902 return Engines::PyNode::_duplicate(tmpVar);
1904 return Engines::PyNode::_nil();
1908 //=============================================================================
1909 /*! \brief create a PyScriptNode object to execute remote python code
1910 * \param nodeName the name of the node
1911 * \param code the python code to load
1912 * \return the PyScriptNode
1914 //=============================================================================
1915 Engines::PyScriptNode_ptr Abstract_Engines_Container_i::createPyScriptNode(const char* nodeName, const char* code)
1917 Engines::PyScriptNode_var node= Engines::PyScriptNode::_nil();
1919 PyGILState_STATE gstate = PyGILState_Ensure();
1920 PyObject *res = PyObject_CallMethod(_pyCont,
1921 (char*)"create_pyscriptnode",
1929 PyGILState_Release(gstate);
1930 SALOME::ExceptionStruct es;
1931 es.type = SALOME::INTERNAL_ERROR;
1932 es.text = "can not create a python node";
1933 throw SALOME::SALOME_Exception(es);
1935 long ierr=PyLong_AsLong(PyTuple_GetItem(res,0));
1936 PyObject* result=PyTuple_GetItem(res,1);
1937 std::string astr=PyUnicode_AsUTF8(result);
1939 PyGILState_Release(gstate);
1943 Utils_Locker lck(&_mutexForDftPy);
1944 CORBA::Object_var obj=_orb->string_to_object(astr.c_str());
1945 node=Engines::PyScriptNode::_narrow(obj);
1946 std::map<std::string,Engines::PyScriptNode_var>::iterator it(_dftPyScriptNode.find(nodeName));
1947 if(it==_dftPyScriptNode.end())
1949 _dftPyScriptNode[nodeName]=node;
1953 Engines::PyScriptNode_var oldNode((*it).second);
1954 if(!CORBA::is_nil(oldNode))
1955 oldNode->UnRegister();
1958 return node._retn();
1962 SALOME::ExceptionStruct es;
1963 es.type = SALOME::INTERNAL_ERROR;
1964 es.text = astr.c_str();
1965 throw SALOME::SALOME_Exception(es);
1969 void Abstract_Engines_Container_i::removePyScriptNode(const char *nodeName)
1971 std::map<std::string,Engines::PyScriptNode_var>::iterator it(_dftPyScriptNode.find(nodeName));
1972 if(it==_dftPyScriptNode.end())
1974 std::ostringstream oss; oss << "Engines_Container_i::removePyScriptNode : node \"" << nodeName << "\" is not map !";
1975 SALOME::ExceptionStruct es;
1976 es.type = SALOME::INTERNAL_ERROR;
1977 es.text = oss.str().c_str();
1978 throw SALOME::SALOME_Exception(es);
1980 (*it).second->UnRegister();
1981 _dftPyScriptNode.erase(it);
1984 void Abstract_Engines_Container_i::cleanAllPyScripts()
1986 for(std::map<std::string,Engines::PyNode_var>::iterator it=_dftPyNode.begin();it!=_dftPyNode.end();it++)
1988 Engines::PyNode_var tmpVar((*it).second);
1989 if(!CORBA::is_nil(tmpVar))
1990 tmpVar->UnRegister();
1993 for(std::map<std::string,Engines::PyScriptNode_var>::iterator it=_dftPyScriptNode.begin();it!=_dftPyScriptNode.end();it++)
1995 Engines::PyScriptNode_var tmpVar((*it).second);
1996 if(!CORBA::is_nil(tmpVar))
1997 tmpVar->UnRegister();
1999 _dftPyScriptNode.clear();
2002 //=============================================================================
2003 /*! \brief Retrieves the last created PyScriptNode instance with createPyScriptNode.
2006 //=============================================================================
2007 Engines::PyScriptNode_ptr Abstract_Engines_Container_i::getDefaultPyScriptNode(const char *nodeName)
2009 Utils_Locker lck(&_mutexForDftPy);
2010 std::map<std::string,Engines::PyScriptNode_var>::iterator it(_dftPyScriptNode.find(nodeName));
2011 if(it==_dftPyScriptNode.end())
2012 return Engines::PyScriptNode::_nil();
2015 Engines::PyScriptNode_var tmpVar((*it).second);
2016 if(!CORBA::is_nil(tmpVar))
2017 return Engines::PyScriptNode::_duplicate(tmpVar);
2019 return Engines::PyScriptNode::_nil();
2023 //=============================================================================
2024 /* int checkifexecutable(const char *filename)
2026 * Return non-zero if the name is an executable file, and
2027 * zero if it is not executable, or if it does not exist.
2029 //=============================================================================
2030 int checkifexecutable(const std::string& filename)
2033 struct stat statinfo;
2035 result = stat(filename.c_str(), &statinfo);
2036 if (result < 0) return 0;
2037 if (!S_ISREG(statinfo.st_mode)) return 0;
2042 if (statinfo.st_uid == geteuid()) return statinfo.st_mode & S_IXUSR;
2043 if (statinfo.st_gid == getegid()) return statinfo.st_mode & S_IXGRP;
2044 return statinfo.st_mode & S_IXOTH;
2049 //=============================================================================
2050 /*! \brief Find a file by searching in a path
2051 * \param filename file name to search
2052 * \param path path to search in
2053 * \param pth the complete file path if found
2054 * \return 1 if found 0 if not
2056 //=============================================================================
2057 int findpathof(const std::string& path, std::string& pth, const std::string& filename)
2059 if ( path.size() == 0 ) return 0;
2061 std::string::size_type offset = 0;
2062 std::string::size_type pos = 0;
2064 struct stat statinfo;
2068 pos = path.find( SEP, offset );
2069 pth = path.substr( offset, pos - offset );
2070 if ( pth.size() > 0 )
2072 if( pth[pth.size()-1] != SLASH ) pth += SLASH;
2074 int result=stat(pth.c_str(), &statinfo);
2075 if(result == 0) found=1;
2077 if (pos == std::string::npos) break;
2083 void Abstract_Engines_Container_i::registerTemporaryFile( const std::string& fileName )
2085 _tmp_files.remove( fileName );
2086 _tmp_files.push_back( fileName );
2089 void Abstract_Engines_Container_i::unregisterTemporaryFile( const std::string& fileName )
2091 _tmp_files.remove( fileName );
2094 void Abstract_Engines_Container_i::clearTemporaryFiles()
2096 std::list<std::string>::const_iterator it;
2097 for ( it = _tmp_files.begin(); it != _tmp_files.end(); ++it ) {
2098 #if defined(WIN32) && defined(UNICODE)
2099 std::wstring aFile = Kernel_Utils::utf8_decode_s(*it);
2100 std::wstring command = (GetFileAttributes(aFile.c_str()) == FILE_ATTRIBUTE_DIRECTORY) ? L"rd /Q \"" : L"del /F /Q \"";
2102 command += L"\" 2>NUL";
2103 _wsystem(command.c_str());
2106 std::string aFile = *it;
2107 std::string command = (GetFileAttributes(aFile.c_str()) == FILE_ATTRIBUTE_DIRECTORY) ? "rd /Q \"" : "del /F /Q \"";
2109 command += "\" 2>NUL";
2111 std::string command = "rm -rf ";
2114 system(command.c_str());
2120 static Engines_Container_SSL_i *_container_singleton_ssl = nullptr;
2122 static Engines::Container_var _container_ref_singleton_ssl;
2124 Engines_Container_SSL_i *KERNEL::getContainerSA()
2126 if(!_container_singleton_ssl)
2129 CORBA::ORB_var orb = CORBA::ORB_init(argc,nullptr);
2130 CORBA::Object_var obj = orb->resolve_initial_references("RootPOA");
2131 PortableServer::POA_var poa = PortableServer::POA::_narrow(obj);
2132 PortableServer::POAManager_var pman = poa->the_POAManager();
2133 CORBA::PolicyList policies;
2136 char *argv[4] = {"Container","FactoryServer","toto",nullptr};
2137 SALOME_Fake_NamingService ns;
2138 _container_singleton_ssl = new Engines_Container_SSL_i(orb,poa,"FactoryServer",2,argv,&ns,false);
2139 PortableServer::ObjectId * cont_id = _container_singleton_ssl->getCORBAId();
2141 CORBA::Object_var zeRef = poa->id_to_reference(*cont_id);
2142 _container_ref_singleton_ssl = Engines::Container::_narrow(zeRef);
2144 return _container_singleton_ssl;
2147 Engines::Container_var KERNEL::getContainerRefSA()
2150 return _container_ref_singleton_ssl;