1 // Copyright (C) 2007-2014 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 "Basics_Utils.hxx"
64 #include "Container_init_python.hxx"
66 bool _Sleeping = false ;
68 // // Needed by multi-threaded Python --- Supervision
72 extern "C" {void ActSigIntHandler() ; }
74 extern "C" {void SigIntHandler(int, siginfo_t *, void *) ; }
76 extern "C" {void SigIntHandler( int ) ; }
81 #define ENGINESO "Engine.so"
84 #define ENGINESO "Engine.dll"
95 std::map<std::string, int> Engines_Container_i::_cntInstances_map;
96 std::map<std::string, void *> Engines_Container_i::_library_map;
97 std::map<std::string, void *> Engines_Container_i::_toRemove_map;
98 omni_mutex Engines_Container_i::_numInstanceMutex ;
100 static PyObject* _pyCont;
102 int checkifexecutable(const std::string&);
103 int findpathof(const std::string& path, std::string&, const std::string&);
105 /*! \class Engines_Container_i
106 * \brief C++ implementation of Engines::Container interface
111 //=============================================================================
113 * Default constructor, not for use
115 //=============================================================================
117 Engines_Container_i::Engines_Container_i () :
118 _numInstance(0),_id(0),_NS(0)
122 //=============================================================================
126 //=============================================================================
128 Engines_Container_i::Engines_Container_i (CORBA::ORB_ptr orb,
129 PortableServer::POA_ptr poa,
130 char *containerName ,
131 int argc , char* argv[],
133 bool isServantAloneInProcess
135 _numInstance(0),_isServantAloneInProcess(isServantAloneInProcess),_id(0),_NS(0)
137 _pid = (long)getpid();
145 std::string hostname = Kernel_Utils::GetHostname();
147 MESSAGE(hostname << " " << getpid() <<
148 " Engines_Container_i starting argc " <<
149 _argc << " Thread " << pthread_self() ) ;
151 MESSAGE(hostname << " " << _getpid() <<
152 " Engines_Container_i starting argc " << _argc<< " Thread " << pthread_self().p ) ;
158 MESSAGE(" argv" << i << " " << _argv[ i ]) ;
164 INFOS("SALOME_Container usage : SALOME_Container ServerName");
168 _isSupervContainer = false;
170 _orb = CORBA::ORB::_duplicate(orb) ;
171 _poa = PortableServer::POA::_duplicate(poa) ;
173 // Pour les containers paralleles: il ne faut pas enregistrer et activer
174 // le container generique, mais le container specialise
178 _id = _poa->activate_object(this);
179 _NS = new SALOME_NamingService();
180 _NS->init_orb( _orb ) ;
181 CORBA::Object_var obj=_poa->id_to_reference(*_id);
182 Engines::Container_var pCont
183 = Engines::Container::_narrow(obj);
186 _containerName = _NS->BuildContainerNameForNS(containerName,
188 SCRUTE(_containerName);
189 _NS->Register(pCont, _containerName.c_str());
190 MESSAGE("Engines_Container_i::Engines_Container_i : Container name "
194 // import SALOME_Container
195 // pycont = SALOME_Container.SALOME_Container_i(containerIORStr)
197 CORBA::String_var sior = _orb->object_to_string(pCont);
198 std::string myCommand="pyCont = SALOME_Container.SALOME_Container_i('";
199 myCommand += _containerName + "','";
204 //[RNV]: Comment the PyEval_AcquireLock() and PyEval_ReleaseLock() because this
205 //approach leads to the deadlock of the main thread of the application on Windows platform
206 //in case if cppContainer runs in the standalone mode. The problem with the PyThreadState
207 //described by ABN seems not reproduced, to be checked carefully later...
208 PyGILState_STATE gstate = PyGILState_Ensure();
210 //// [ABN]: using the PyGILState* API here is unstable. omniORB logic is invoked
211 //// by the Python code executed below, and in some (random) cases, the Python code
212 //// execution ends with a PyThreadState which was not the one we have here.
213 //// (TODO: understand why ...)
214 //// To be on the safe side we get and load the thread state ourselves:
215 //PyEval_AcquireLock(); // get GIL
216 //PyThreadState * mainThreadState = PyThreadState_Get();
217 //PyThreadState_Swap(mainThreadState);
220 // mpv: this is temporary solution: there is a unregular crash if not
223 // first element is the path to Registry.dll, but it's wrong
224 PyRun_SimpleString("import sys\n");
225 PyRun_SimpleString("sys.path = sys.path[1:]\n");
227 PyRun_SimpleString("import SALOME_Container\n");
228 PyRun_SimpleString((char*)myCommand.c_str());
229 PyObject *mainmod = PyImport_AddModule("__main__");
230 PyObject *globals = PyModule_GetDict(mainmod);
231 _pyCont = PyDict_GetItemString(globals, "pyCont");
233 //PyThreadState_Swap(NULL);
234 //PyEval_ReleaseLock();
235 PyGILState_Release(gstate);
237 fileTransfer_i* aFileTransfer = new fileTransfer_i();
238 CORBA::Object_var obref=aFileTransfer->_this();
239 _fileTransfer = Engines::fileTransfer::_narrow(obref);
240 aFileTransfer->_remove_ref();
244 //=============================================================================
248 //=============================================================================
250 Engines_Container_i::~Engines_Container_i()
252 MESSAGE("Container_i::~Container_i()");
257 if(!CORBA::is_nil(_dftPyNode))
258 _dftPyNode->UnRegister();
259 if(!CORBA::is_nil(_dftPyScriptNode))
260 _dftPyScriptNode->UnRegister();
263 //=============================================================================
264 //! Get container name
266 * CORBA attribute: Container name (see constructor)
268 //=============================================================================
270 char* Engines_Container_i::name()
272 return CORBA::string_dup(_containerName.c_str()) ;
275 //=============================================================================
276 //! Get container working directory
278 * CORBA attribute: Container working directory
280 //=============================================================================
282 char* Engines_Container_i::workingdir()
286 return CORBA::string_dup(wd) ;
289 //=============================================================================
290 //! Get container log file name
292 * CORBA attribute: Container log file name
294 //=============================================================================
296 char* Engines_Container_i::logfilename()
298 return CORBA::string_dup(_logfilename.c_str()) ;
301 //! Set container log file name
302 void Engines_Container_i::logfilename(const char* name)
307 //=============================================================================
308 //! Get container host name
310 * CORBA method: Get the hostName of the Container (without domain extensions)
312 //=============================================================================
314 char* Engines_Container_i::getHostName()
316 std::string s = Kernel_Utils::GetHostname();
317 // MESSAGE("Engines_Container_i::getHostName " << s);
318 return CORBA::string_dup(s.c_str()) ;
321 //=============================================================================
322 //! Get container PID
324 * CORBA method: Get the PID (process identification) of the Container
326 //=============================================================================
328 CORBA::Long Engines_Container_i::getPID()
330 return (CORBA::Long)getpid();
333 //=============================================================================
334 //! Ping the servant to check it is still alive
336 * CORBA method: check if servant is still alive
338 //=============================================================================
339 void Engines_Container_i::ping()
341 MESSAGE("Engines_Container_i::ping() pid "<< getpid());
344 //=============================================================================
345 //! Shutdown the container
347 * CORBA method, oneway: Server shutdown.
348 * - Container name removed from naming service,
349 * - servant deactivation,
350 * - orb shutdown if no other servants in the process
352 //=============================================================================
353 void Engines_Container_i::Shutdown()
355 MESSAGE("Engines_Container_i::Shutdown()");
357 // Clear registered temporary files
358 clearTemporaryFiles();
360 /* For each component contained in this container
361 * tell it to self-destroy
363 std::map<std::string, Engines::EngineComponent_var>::iterator itm;
364 for (itm = _listInstances_map.begin(); itm != _listInstances_map.end(); itm++)
368 itm->second->destroy();
370 catch(const CORBA::Exception& e)
372 // ignore this entry and continue
376 // ignore this entry and continue
379 _listInstances_map.clear();
381 _NS->Destroy_FullDirectory(_containerName.c_str());
382 _NS->Destroy_Name(_containerName.c_str());
383 if(_isServantAloneInProcess)
385 MESSAGE("Effective Shutdown of container Begins...");
386 if(!CORBA::is_nil(_orb))
391 //=============================================================================
392 //! load a component implementation
395 * \param componentName component name
396 * \param reason explains error when load fails
397 * \return true if dlopen successfull or already done, false otherwise
399 //=============================================================================
401 Engines_Container_i::load_component_Library(const char* componentName, CORBA::String_out reason)
404 //=================================================================
405 // --- C++ implementation section
406 //=================================================================
408 if(load_component_CppImplementation(componentName,retso))
410 reason=CORBA::string_dup("");
413 else if(retso != "ImplementationNotFound")
415 reason=CORBA::string_dup(retso.c_str());
420 retso+=componentName;
421 retso+=": Can't find C++ implementation ";
422 retso+=std::string(LIB) + componentName + ENGINESO;
424 //=================================================================
425 // --- Python implementation section
426 //=================================================================
428 if(load_component_PythonImplementation(componentName,retpy))
430 reason=CORBA::string_dup("");
433 else if(retpy != "ImplementationNotFound")
435 reason=CORBA::string_dup(retpy.c_str());
440 retpy+=componentName;
441 retpy+=": Can't find python implementation ";
442 retpy+=componentName;
445 //=================================================================
446 // -- Executable implementation section
447 //=================================================================
449 if(load_component_ExecutableImplementation(componentName,retex))
451 reason=CORBA::string_dup("");
454 else if(retex != "ImplementationNotFound")
456 reason=CORBA::string_dup(retex.c_str());
461 retex+=componentName;
462 retex+=": Can't find executable implementation ";
463 retex+=componentName;
466 std::string ret="Component implementation not found: ";
467 ret += componentName ;
473 std::cerr << ret << std::endl;
474 reason=CORBA::string_dup(ret.c_str());
479 //=============================================================================
480 //! try to load a C++ component implementation
483 * \param componentName the name of the component (COMPONENT, for example)
484 * \param reason explains error when load fails
485 * \return true if loading is successfull or already done, false otherwise
487 //=============================================================================
489 Engines_Container_i::load_component_CppImplementation(const char* componentName, std::string& reason)
491 std::string aCompName(componentName);
492 std::string impl_name = std::string(LIB) + aCompName + ENGINESO;
495 _numInstanceMutex.lock(); // lock to be alone
496 // (see decInstanceCnt, finalize_removal))
497 if (_toRemove_map.count(impl_name) != 0) _toRemove_map.erase(impl_name);
498 if (_library_map.count(impl_name) != 0)
500 MESSAGE("Library " << impl_name << " already loaded");
501 _numInstanceMutex.unlock();
505 _numInstanceMutex.unlock();
509 handle = dlopen( impl_name.c_str() , RTLD_NOW ) ;
512 //not loadable. Try to find the lib file in LD_LIBRARY_PATH
514 char* p=getenv("LD_LIBRARY_PATH");
516 path=path+SEP+"/usr/lib"+SEP+"/lib";
519 if(findpathof(path, pth, impl_name))
521 //found but not loadable
524 reason+=": C++ implementation found ";
526 reason+=" but it is not loadable. Error:\n";
528 std::cerr << reason << std::endl;
534 //continue with other implementation
535 reason="ImplementationNotFound";
541 handle = LoadLibrary( impl_name.c_str() );
544 reason="ImplementationNotFound";
550 _numInstanceMutex.lock();
551 _library_map[impl_name] = handle;
552 _numInstanceMutex.unlock();
560 //=============================================================================
561 //! try to load a Python component implementation
564 * \param componentName name of the component
565 * \param reason explains error when load fails
566 * \return true if loading is successfull or already done, false otherwise
568 //=============================================================================
570 Engines_Container_i::load_component_PythonImplementation(const char* componentName, std::string& reason)
572 std::string aCompName(componentName);
574 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
575 if (_library_map.count(aCompName) != 0)
577 _numInstanceMutex.unlock() ;
579 return true; // Python Component, already imported
581 _numInstanceMutex.unlock() ;
583 PyGILState_STATE gstate = PyGILState_Ensure();
584 PyObject *result = PyObject_CallMethod(_pyCont,
585 (char*)"import_component",
586 (char*)"s",componentName);
588 reason=PyString_AsString(result);
591 PyGILState_Release(gstate);
595 //Python component has been loaded (import componentName)
596 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
597 _library_map[aCompName] = (void *)_pyCont; // any non O value OK
598 _numInstanceMutex.unlock() ;
599 MESSAGE("import Python: "<< aCompName <<" OK");
602 else if(reason=="ImplementationNotFound")
604 //Python implementation has not been found. Continue with other implementation
605 reason="ImplementationNotFound";
609 //Python implementation has been found but loading has failed
610 std::cerr << reason << std::endl;
615 //=============================================================================
616 //! try to load a Executable component implementation
619 * \param componentName name of the component
620 * \param reason explains error when load fails
621 * \return true if loading is successfull or already done, false otherwise
623 //=============================================================================
625 Engines_Container_i::load_component_ExecutableImplementation(const char* componentName, std::string& reason)
627 std::string aCompName(componentName);
628 std::string executable=aCompName+".exe";
633 char* p=getenv("PATH");
636 if (findpathof(path, pth, executable))
638 if(checkifexecutable(pth))
640 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
641 _library_map[executable] = (void *)1; // any non O value OK
642 _numInstanceMutex.unlock() ;
643 MESSAGE("import executable: "<< pth <<" OK");
649 reason+=": implementation found ";
651 reason+=" but it is not executable";
652 std::cerr << reason << std::endl;
656 reason="ImplementationNotFound";
661 //=============================================================================
662 //! Create a new component instance
664 * CORBA method: Creates a new servant instance of a component.
665 * The servant registers itself to naming service and Registry.
666 * \param genericRegisterName Name of the component instance to register
667 * in Registry & Name Service (without _inst_n suffix)
668 * \param studyId 0 for multiStudy instance,
669 * study Id (>0) otherwise
670 * \return a loaded component
672 //=============================================================================
673 Engines::EngineComponent_ptr
674 Engines_Container_i::create_component_instance(const char*genericRegisterName,
677 Engines::FieldsDict_var env = new Engines::FieldsDict;
679 Engines::EngineComponent_ptr compo =
680 create_component_instance_env(genericRegisterName, studyId, env, reason);
681 CORBA::string_free(reason);
685 //=============================================================================
686 //! Create a new component instance with environment variables specified
688 * CORBA method: Creates a new servant instance of a component.
689 * The servant registers itself to naming service and Registry.
690 * \param genericRegisterName Name of the component instance to register
691 * in Registry & Name Service (without _inst_n suffix)
692 * \param studyId 0 for multiStudy instance,
693 * study Id (>0) otherwise
694 * \param env dict of env variables
695 * \param reason explains error when create_component_instance_env fails
696 * \return a loaded component
698 //=============================================================================
699 Engines::EngineComponent_ptr
700 Engines_Container_i::create_component_instance_env(const char*genericRegisterName,
702 const Engines::FieldsDict& env,
703 CORBA::String_out reason)
707 INFOS("studyId must be > 0 for mono study instance, =0 for multiStudy");
708 reason=CORBA::string_dup("studyId must be > 0 for mono study instance, =0 for multiStudy");
709 return Engines::EngineComponent::_nil() ;
713 if (_library_map.count(genericRegisterName) != 0)
715 // It's a Python component
716 Engines::EngineComponent_ptr compo = createPythonInstance(genericRegisterName, studyId, error);
717 reason=CORBA::string_dup(error.c_str());
721 std::string impl_name = std::string(LIB) + genericRegisterName + ENGINESO;
722 if (_library_map.count(impl_name) != 0)
724 // It's a C++ component
725 void* handle = _library_map[impl_name];
726 Engines::EngineComponent_ptr compo = createInstance(genericRegisterName, handle, studyId, error);
727 reason=CORBA::string_dup(error.c_str());
731 impl_name = std::string(genericRegisterName) + ".exe";
732 if (_library_map.count(impl_name) != 0)
734 //It's an executable component
735 Engines::EngineComponent_ptr compo = createExecutableInstance(genericRegisterName, studyId, env, error);
736 reason=CORBA::string_dup(error.c_str());
740 error="load_component_Library has probably not been called for component: ";
741 error += genericRegisterName;
743 reason=CORBA::string_dup(error.c_str());
744 return Engines::EngineComponent::_nil() ;
747 //=============================================================================
748 //! Create a new component instance (Executable implementation)
750 * \param CompName Name of the component instance
751 * \param studyId 0 for multiStudy instance,
752 * study Id (>0) otherwise
753 * \param env dict of env variables
754 * \param reason explains error when creation fails
755 * \return a loaded component
757 * This component is implemented in an executable with name genericRegisterName.exe
758 * It must register itself in Naming Service. The container waits some time (10 s max)
761 //=============================================================================
762 Engines::EngineComponent_ptr
763 Engines_Container_i::createExecutableInstance(std::string CompName, int studyId,
764 const Engines::FieldsDict& env,
767 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
769 _numInstanceMutex.lock() ; // lock on the instance number
771 int numInstance = _numInstance ;
772 _numInstanceMutex.unlock() ;
775 sprintf( aNumI , "%d" , numInstance ) ;
776 std::string instanceName = CompName + "_inst_" + aNumI ;
777 std::string component_registerName = _containerName + "/" + instanceName;
779 //check if an entry exist in naming service
780 CORBA::Object_var nsobj = _NS->Resolve(component_registerName.c_str());
781 if ( !CORBA::is_nil(nsobj) )
783 // unregister the registered component
784 _NS->Destroy_Name(component_registerName.c_str());
785 //kill or shutdown it ???
788 // first arg container ior string
789 // second arg container name
790 // third arg instance name
792 Engines::Container_var pCont= _this();
793 CORBA::String_var sior = _orb->object_to_string(pCont);
797 command+=instanceName;
799 command+=instanceName;
804 command+= sior; // container ior string
806 command+=_containerName; //container name
808 command+=instanceName; //instance name
810 MESSAGE("SALOME_Container::create_component_instance command=" << command);
813 // use fork/execl instead of system to get finer control on env variables
816 if(pid == 0) // child
818 for (CORBA::ULong i=0; i < env.length(); i++)
820 if (env[i].value.type()->kind() == CORBA::tk_string)
823 env[i].value >>= value;
824 std::string s(env[i].key);
827 putenv(strdup(s.c_str()));
831 execl("/bin/sh", "sh", "-c", command.c_str() , (char *)0);
834 else if(pid < 0) // failed to fork
843 tpid = wait(&status);
844 } while (tpid != pid);
847 // launch component with a system call
848 int status=system(command.c_str());
853 reason="SALOME_Container::create_component_instance system failed (system command status -1)";
855 return Engines::EngineComponent::_nil();
858 else if (WEXITSTATUS(status) == 217)
860 reason="SALOME_Container::create_component_instance system failed (system command status 217)";
862 return Engines::EngineComponent::_nil();
868 if (getenv("TIMEOUT_TO_WAIT_EXE_COMPONENT") != 0)
870 std::string new_count_str = getenv("TIMEOUT_TO_WAIT_EXE_COMPONENT");
872 std::istringstream ss(new_count_str);
873 if (!(ss >> new_count))
875 INFOS("[Container] TIMEOUT_TO_WAIT_EXE_COMPONENT should be an int");
880 INFOS("[Container] waiting " << count << " second steps exe component ");
881 CORBA::Object_var obj = CORBA::Object::_nil() ;
882 while ( CORBA::is_nil(obj) && count )
890 MESSAGE( count << ". Waiting for component " << CompName);
891 obj = _NS->Resolve(component_registerName.c_str());
894 if(CORBA::is_nil(obj))
896 reason="SALOME_Container::create_component_instance failed";
898 return Engines::EngineComponent::_nil();
902 MESSAGE("SALOME_Container::create_component_instance successful");
903 iobject = Engines::EngineComponent::_narrow(obj);
904 _listInstances_map[instanceName] = iobject;
905 return iobject._retn();
911 //=============================================================================
912 //! Create a new component instance (Python implementation)
914 * \param CompName Name of the component instance
915 * \param studyId 0 for multiStudy instance,
916 * study Id (>0) otherwise
917 * \param reason explains error when creation fails
918 * \return a loaded component
920 //=============================================================================
921 Engines::EngineComponent_ptr
922 Engines_Container_i::createPythonInstance(std::string CompName, int studyId,
925 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
927 _numInstanceMutex.lock() ; // lock on the instance number
929 int numInstance = _numInstance ;
930 _numInstanceMutex.unlock() ;
933 sprintf( aNumI , "%d" , numInstance ) ;
934 std::string instanceName = CompName + "_inst_" + aNumI ;
935 std::string component_registerName = _containerName + "/" + instanceName;
937 PyGILState_STATE gstate = PyGILState_Ensure();
938 PyObject *result = PyObject_CallMethod(_pyCont,
939 (char*)"create_component_instance",
942 instanceName.c_str(),
946 PyArg_ParseTuple(result,"ss", &ior, &error);
947 std::string iors = ior;
950 PyGILState_Release(gstate);
954 CORBA::Object_var obj = _orb->string_to_object(iors.c_str());
955 iobject = Engines::EngineComponent::_narrow( obj ) ;
956 _listInstances_map[instanceName] = iobject;
958 return iobject._retn();
961 //=============================================================================
962 //! Create a new component instance (C++ implementation)
964 * C++ method: create a servant instance of a component.
965 * \param genericRegisterName Name of the component instance to register
966 * in Registry & Name Service,
967 * (without _inst_n suffix, like "COMPONENT")
968 * \param handle loaded library handle
969 * \param studyId 0 for multiStudy instance,
970 * study Id (>0) otherwise
971 * \param reason explains error when creation fails
972 * \return a loaded component
974 * example with names:
975 * - aGenRegisterName = COMPONENT (= first argument)
976 * - _containerName = /Containers/cli76ce/FactoryServer
977 * - factoryName = COMPONENTEngine_factory
978 * - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
979 * - instanceName = COMPONENT_inst_1
980 * - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
982 //=============================================================================
983 Engines::EngineComponent_ptr
984 Engines_Container_i::createInstance(std::string genericRegisterName,
989 // --- find the factory
991 std::string aGenRegisterName = genericRegisterName;
992 std::string factory_name = aGenRegisterName + std::string("Engine_factory");
993 SCRUTE(factory_name) ;
995 typedef PortableServer::ObjectId* (*FACTORY_FUNCTION) (CORBA::ORB_ptr,
996 PortableServer::POA_ptr,
997 PortableServer::ObjectId *,
1002 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)dlsym( handle, factory_name.c_str() );
1004 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)GetProcAddress( (HINSTANCE)handle, factory_name.c_str() );
1007 if ( !Component_factory )
1009 INFOS( "Can't resolve symbol: " + factory_name );
1014 return Engines::EngineComponent::_nil() ;
1017 // --- create instance
1019 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1023 _numInstanceMutex.lock() ; // lock on the instance number
1025 int numInstance = _numInstance ;
1026 _numInstanceMutex.unlock() ;
1029 sprintf( aNumI , "%d" , numInstance ) ;
1030 std::string instanceName = aGenRegisterName + "_inst_" + aNumI ;
1031 std::string component_registerName =
1032 _containerName + "/" + instanceName;
1034 // --- Instanciate required CORBA object
1036 PortableServer::ObjectId *id ; //not owner, do not delete (nore use var)
1037 id = (Component_factory) ( _orb, _poa, _id, instanceName.c_str(),
1038 aGenRegisterName.c_str() ) ;
1041 reason="Can't get ObjectId from factory";
1043 return iobject._retn();
1046 // --- get reference & servant from id
1048 CORBA::Object_var obj = _poa->id_to_reference(*id);
1049 iobject = Engines::EngineComponent::_narrow( obj ) ;
1051 Engines_Component_i *servant =
1052 dynamic_cast<Engines_Component_i*>(_poa->reference_to_servant(iobject));
1054 //SCRUTE(servant->_refcount_value());
1055 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1056 _listInstances_map[instanceName] = iobject;
1057 _cntInstances_map[aGenRegisterName] += 1;
1058 _numInstanceMutex.unlock() ;
1059 SCRUTE(aGenRegisterName);
1060 SCRUTE(_cntInstances_map[aGenRegisterName]);
1061 servant->setStudyId(studyId);
1062 servant->_remove_ref(); // do not need servant any more (remove ref from reference_to_servant)
1063 //SCRUTE(servant->_refcount_value());
1065 // --- register the engine under the name
1066 // containerName(.dir)/instanceName(.object)
1068 _NS->Register( iobject , component_registerName.c_str() ) ;
1069 MESSAGE( component_registerName.c_str() << " bound" ) ;
1073 reason="Container_i::createInstance exception catched";
1076 return iobject._retn();
1079 //=============================================================================
1080 //! Find an existing (in the container) component instance
1082 * CORBA method: Finds a servant instance of a component
1083 * \param registeredName Name of the component in Registry or Name Service,
1084 * without instance suffix number
1085 * \param studyId 0 if instance is not associated to a study,
1086 * >0 otherwise (== study id)
1087 * \return the first instance found with same studyId
1089 //=============================================================================
1090 Engines::EngineComponent_ptr
1091 Engines_Container_i::find_component_instance( const char* registeredName,
1092 CORBA::Long studyId)
1094 Engines::EngineComponent_var anEngine = Engines::EngineComponent::_nil();
1095 std::map<std::string,Engines::EngineComponent_var>::iterator itm =_listInstances_map.begin();
1096 while (itm != _listInstances_map.end())
1098 std::string instance = (*itm).first;
1100 if (instance.find(registeredName) == 0)
1102 anEngine = (*itm).second;
1103 if (studyId == anEngine->getStudyId())
1105 return anEngine._retn();
1110 return anEngine._retn();
1113 //=============================================================================
1114 //! Remove the component instance from container
1116 * CORBA method: Stops the component servant, and deletes all related objects
1117 * \param component_i Component to be removed
1119 //=============================================================================
1121 void Engines_Container_i::remove_impl(Engines::EngineComponent_ptr component_i)
1123 ASSERT(! CORBA::is_nil(component_i));
1124 std::string instanceName = component_i->instanceName() ;
1125 MESSAGE("unload component " << instanceName);
1126 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1127 _listInstances_map.erase(instanceName);
1128 _numInstanceMutex.unlock() ;
1129 component_i->destroy() ;
1130 _NS->Destroy_Name(instanceName.c_str());
1133 //=============================================================================
1134 //! Unload component libraries from the container
1136 * CORBA method: Discharges unused libraries from the container.
1138 //=============================================================================
1139 void Engines_Container_i::finalize_removal()
1141 MESSAGE("finalize unload : dlclose");
1142 _numInstanceMutex.lock(); // lock to be alone
1143 // (see decInstanceCnt, load_component_Library)
1144 std::map<std::string, void *>::iterator ith;
1145 for (ith = _toRemove_map.begin(); ith != _toRemove_map.end(); ith++)
1147 void *handle = (*ith).second;
1148 std::string impl_name= (*ith).first;
1153 // dlclose(handle); // SALOME unstable after ...
1154 // _library_map.erase(impl_name);
1157 _toRemove_map.clear();
1158 _numInstanceMutex.unlock();
1161 //=============================================================================
1162 //! Decrement component instance reference count
1166 //=============================================================================
1167 void Engines_Container_i::decInstanceCnt(std::string genericRegisterName)
1169 if(_cntInstances_map.count(genericRegisterName)==0)
1171 std::string aGenRegisterName =genericRegisterName;
1172 MESSAGE("Engines_Container_i::decInstanceCnt " << aGenRegisterName);
1173 ASSERT(_cntInstances_map[aGenRegisterName] > 0);
1174 _numInstanceMutex.lock(); // lock to be alone
1175 // (see finalize_removal, load_component_Library)
1176 _cntInstances_map[aGenRegisterName] -= 1;
1177 SCRUTE(_cntInstances_map[aGenRegisterName]);
1178 if (_cntInstances_map[aGenRegisterName] == 0)
1180 std::string impl_name =
1181 Engines_Component_i::GetDynLibraryName(aGenRegisterName.c_str());
1183 void* handle = _library_map[impl_name];
1185 _toRemove_map[impl_name] = handle;
1187 _numInstanceMutex.unlock();
1190 //=============================================================================
1191 //! Find or create a new component instance
1193 * CORBA method: find or create an instance of the component (servant),
1194 * load a new component class (dynamic library) if required,
1196 * ---- FOR COMPATIBILITY WITH 2.2 ----
1198 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
1200 * The servant registers itself to naming service and Registry.
1201 * \param genericRegisterName Name of the component to register
1202 * in Registry & Name Service
1203 * \param componentName Name of the constructed library of the component
1204 * \return a loaded component
1206 //=============================================================================
1208 Engines::EngineComponent_ptr
1209 Engines_Container_i::load_impl( const char* genericRegisterName,
1210 const char* componentName )
1213 std::string impl_name = std::string(LIB) + genericRegisterName + ENGINESO;
1214 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1215 if (load_component_Library(genericRegisterName,reason))
1216 iobject = find_or_create_instance(genericRegisterName, impl_name);
1217 CORBA::string_free(reason);
1218 return iobject._retn();
1221 //=============================================================================
1222 //! Finds an already existing component instance or create a new instance
1224 * C++ method: Finds an already existing servant instance of a component, or
1225 * create an instance.
1226 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
1227 * \param genericRegisterName Name of the component instance to register
1228 * in Registry & Name Service,
1229 * (without _inst_n suffix, like "COMPONENT")
1230 * \param componentLibraryName like "libCOMPONENTEngine.so"
1231 * \return a loaded component
1233 * example with names:
1234 * - aGenRegisterName = COMPONENT (= first argument)
1235 * - impl_name = libCOMPONENTEngine.so (= second argument)
1236 * - _containerName = /Containers/cli76ce/FactoryServer
1237 * - factoryName = COMPONENTEngine_factory
1238 * - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
1239 * - instanceName = COMPONENT_inst_1
1240 * - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1242 //=============================================================================
1244 Engines::EngineComponent_ptr
1245 Engines_Container_i::find_or_create_instance(std::string genericRegisterName,
1246 std::string componentLibraryName)
1248 std::string aGenRegisterName = genericRegisterName;
1249 std::string impl_name = componentLibraryName;
1250 if (_library_map.count(impl_name) == 0)
1252 INFOS("shared library " << impl_name <<" must be loaded before creating instance");
1253 return Engines::EngineComponent::_nil() ;
1257 // --- find a registered instance in naming service, or create
1259 void* handle = _library_map[impl_name];
1260 std::string component_registerBase =
1261 _containerName + "/" + aGenRegisterName;
1262 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1266 CORBA::Object_var obj =
1267 _NS->ResolveFirst( component_registerBase.c_str());
1268 if ( CORBA::is_nil( obj ) )
1270 iobject = createInstance(genericRegisterName,
1273 reason); // force multiStudy instance here !
1277 iobject = Engines::EngineComponent::_narrow( obj ) ;
1278 Engines_Component_i *servant =
1279 dynamic_cast<Engines_Component_i*>
1280 (_poa->reference_to_servant(iobject));
1282 int studyId = servant->getStudyId();
1283 ASSERT (studyId >= 0);
1284 if (studyId == 0) // multiStudy instance, OK
1287 MESSAGE(component_registerBase.c_str()<<" already bound");
1289 else // monoStudy instance: NOK
1291 iobject = Engines::EngineComponent::_nil();
1292 INFOS("load_impl & find_component_instance methods "
1293 << "NOT SUITABLE for mono study components");
1299 INFOS( "Container_i::load_impl catched" ) ;
1301 return iobject._retn();
1305 //=============================================================================
1306 //! Indicate if container is a python one
1308 * Retrieves only with container naming convention if it is a python container
1310 //=============================================================================
1311 bool Engines_Container_i::isPythonContainer(const char* ContainerName)
1314 int len=strlen(ContainerName);
1316 if(strcmp(ContainerName+len-2,"Py")==0)
1321 //=============================================================================
1322 //! Kill the container
1324 * CORBA method: Kill the container process with exit(0).
1325 * To remove : never returns !
1327 //=============================================================================
1328 bool Engines_Container_i::Kill_impl()
1330 MESSAGE("Engines_Container_i::Kill() pid "<< getpid() << " containerName "
1331 << _containerName.c_str() << " machineName "
1332 << Kernel_Utils::GetHostname().c_str());
1333 INFOS("===============================================================");
1334 INFOS("= REMOVE calls to Kill_impl in C++ container =");
1335 INFOS("===============================================================");
1341 //=============================================================================
1345 //=============================================================================
1346 void ActSigIntHandler()
1349 struct sigaction SigIntAct ;
1350 SigIntAct.sa_sigaction = &SigIntHandler ;
1351 sigemptyset(&SigIntAct.sa_mask);
1352 SigIntAct.sa_flags = SA_SIGINFO ;
1355 // DEBUG 03.02.2005 : the first parameter of sigaction is not a mask of signals
1356 // (SIGINT | SIGUSR1) :
1357 // it must be only one signal ===> one call for SIGINT
1358 // and an other one for SIGUSR1
1361 if ( sigaction( SIGINT , &SigIntAct, NULL ) )
1363 perror("SALOME_Container main ") ;
1366 if ( sigaction( SIGUSR1 , &SigIntAct, NULL ) )
1368 perror("SALOME_Container main ") ;
1371 if ( sigaction( SIGUSR2 , &SigIntAct, NULL ) )
1373 perror("SALOME_Container main ") ;
1377 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1378 // use of streams (and so on) should never be used because :
1379 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1380 // A stream operation may be interrupted by a signal and if the Handler use stream we
1381 // may have a "Dead-Lock" ===HangUp
1382 //==INFOS is commented
1383 // INFOS(pthread_self() << "SigIntHandler activated") ;
1386 signal( SIGINT, SigIntHandler );
1387 // legacy code required to supervisor. Commented in order to avoid problems on Windows
1388 // signal( SIGUSR1, SigIntHandler );
1394 void CallCancelThread() ;
1397 void SigIntHandler(int what ,
1398 siginfo_t * siginfo ,
1401 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1402 // use of streams (and so on) should never be used because :
1403 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1404 // A stream operation may be interrupted by a signal and if the Handler use stream we
1405 // may have a "Dead-Lock" ===HangUp
1406 //==MESSAGE is commented
1407 // MESSAGE(pthread_self() << "SigIntHandler what " << what << std::endl
1408 // << " si_signo " << siginfo->si_signo << std::endl
1409 // << " si_code " << siginfo->si_code << std::endl
1410 // << " si_pid " << siginfo->si_pid) ;
1415 // MESSAGE("SigIntHandler END sleeping.") ;
1420 ActSigIntHandler() ;
1421 if ( siginfo->si_signo == SIGUSR1 )
1425 else if ( siginfo->si_signo == SIGUSR2 )
1427 CallCancelThread() ;
1432 // MESSAGE("SigIntHandler BEGIN sleeping.") ;
1439 // MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1445 void SigIntHandler( int what )
1448 MESSAGE( pthread_self() << "SigIntHandler what " << what << std::endl );
1450 MESSAGE( "SigIntHandler what " << what << std::endl );
1455 MESSAGE("SigIntHandler END sleeping.") ;
1460 ActSigIntHandler() ;
1461 if ( what == SIGUSR1 )
1468 MESSAGE("SigIntHandler BEGIN sleeping.") ;
1475 MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1482 //=============================================================================
1483 //! Get or create a file reference object associated to a local file (to transfer it)
1485 * CORBA method: get or create a fileRef object associated to a local file
1486 * (a file on the computer on which runs the container server), which stores
1487 * a list of (machine, localFileName) corresponding to copies already done.
1489 * \param origFileName absolute path for a local file to copy on other
1491 * \return a fileRef object associated to the file.
1493 //=============================================================================
1494 Engines::fileRef_ptr
1495 Engines_Container_i::createFileRef(const char* origFileName)
1497 std::string origName(origFileName);
1498 Engines::fileRef_var theFileRef = Engines::fileRef::_nil();
1500 if (origName[0] != '/')
1502 INFOS("path of file to copy must be an absolute path begining with '/'");
1503 return Engines::fileRef::_nil();
1506 if (CORBA::is_nil(_fileRef_map[origName]))
1508 CORBA::Object_var obj=_poa->id_to_reference(*_id);
1509 Engines::Container_var pCont = Engines::Container::_narrow(obj);
1510 fileRef_i* aFileRef = new fileRef_i(pCont, origFileName);
1511 theFileRef = Engines::fileRef::_narrow(aFileRef->_this());
1512 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1513 _fileRef_map[origName] = theFileRef;
1514 _numInstanceMutex.unlock() ;
1517 theFileRef = Engines::fileRef::_duplicate(_fileRef_map[origName]);
1518 ASSERT(! CORBA::is_nil(theFileRef));
1519 return theFileRef._retn();
1522 //=============================================================================
1523 //! Get a fileTransfer reference
1526 * \return a reference to the fileTransfer object
1528 //=============================================================================
1529 Engines::fileTransfer_ptr
1530 Engines_Container_i::getFileTransfer()
1532 Engines::fileTransfer_var aFileTransfer
1533 = Engines::fileTransfer::_duplicate(_fileTransfer);
1534 return aFileTransfer._retn();
1537 //=============================================================================
1538 //! Create a Salome file
1539 //=============================================================================
1540 Engines::Salome_file_ptr
1541 Engines_Container_i::createSalome_file(const char* origFileName)
1543 std::string origName(origFileName);
1544 if (CORBA::is_nil(_Salome_file_map[origName]))
1546 Salome_file_i* aSalome_file = new Salome_file_i();
1547 aSalome_file->setContainer(Engines::Container::_duplicate(this->_this()));
1550 aSalome_file->setLocalFile(origFileName);
1551 aSalome_file->recvFiles();
1553 catch (const SALOME::SALOME_Exception& e)
1555 return Engines::Salome_file::_nil();
1558 Engines::Salome_file_var theSalome_file = Engines::Salome_file::_nil();
1559 theSalome_file = Engines::Salome_file::_narrow(aSalome_file->_this());
1560 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1561 _Salome_file_map[origName] = theSalome_file;
1562 _numInstanceMutex.unlock() ;
1565 Engines::Salome_file_ptr theSalome_file =
1566 Engines::Salome_file::_duplicate(_Salome_file_map[origName]);
1567 ASSERT(!CORBA::is_nil(theSalome_file));
1568 return theSalome_file;
1571 //=============================================================================
1572 /*! \brief copy a file from a remote host (container) to the local host
1573 * \param container the remote container
1574 * \param remoteFile the file to copy locally from the remote host into localFile
1575 * \param localFile the local file
1577 //=============================================================================
1578 void Engines_Container_i::copyFile(Engines::Container_ptr container, const char* remoteFile, const char* localFile)
1580 Engines::fileTransfer_var fileTransfer = container->getFileTransfer();
1583 if ((fp = fopen(localFile,"wb")) == NULL)
1585 INFOS("file " << localFile << " cannot be open for writing");
1589 CORBA::Long fileId = fileTransfer->open(remoteFile);
1592 Engines::fileBlock* aBlock;
1599 aBlock = fileTransfer->getBlock(fileId);
1600 toFollow = aBlock->length();
1602 CORBA::Octet *buf = aBlock->get_buffer();
1603 fwrite(buf, sizeof(CORBA::Octet), toFollow, fp);
1607 MESSAGE("end of transfer");
1608 fileTransfer->close(fileId);
1612 INFOS("open reference file for copy impossible");
1616 //=============================================================================
1617 /*! \brief create a PyNode object to execute remote python code
1618 * \param nodeName the name of the node
1619 * \param code the python code to load
1620 * \return the PyNode
1622 //=============================================================================
1623 Engines::PyNode_ptr Engines_Container_i::createPyNode(const char* nodeName, const char* code)
1625 Engines::PyNode_var node= Engines::PyNode::_nil();
1627 PyGILState_STATE gstate = PyGILState_Ensure();
1628 PyObject *res = PyObject_CallMethod(_pyCont,
1629 (char*)"create_pynode",
1637 PyGILState_Release(gstate);
1638 SALOME::ExceptionStruct es;
1639 es.type = SALOME::INTERNAL_ERROR;
1640 es.text = "can not create a python node";
1641 throw SALOME::SALOME_Exception(es);
1643 long ierr=PyInt_AsLong(PyTuple_GetItem(res,0));
1644 PyObject* result=PyTuple_GetItem(res,1);
1645 std::string astr=PyString_AsString(result);
1647 PyGILState_Release(gstate);
1651 CORBA::Object_var obj = _orb->string_to_object(astr.c_str());
1652 node = Engines::PyNode::_narrow(obj);
1653 if(!CORBA::is_nil(_dftPyNode))
1654 _dftPyNode->UnRegister();
1656 if(!CORBA::is_nil(_dftPyNode))
1657 _dftPyNode->Register();
1658 return node._retn();
1662 SALOME::ExceptionStruct es;
1663 es.type = SALOME::INTERNAL_ERROR;
1664 es.text = astr.c_str();
1665 throw SALOME::SALOME_Exception(es);
1670 //=============================================================================
1671 /*! \brief Retrieves the last created PyNode instance with createPyNode.
1674 //=============================================================================
1675 Engines::PyNode_ptr Engines_Container_i::getDefaultPyNode()
1677 if(!CORBA::is_nil(_dftPyNode))
1678 return Engines::PyNode::_duplicate(_dftPyNode);
1680 return Engines::PyNode::_nil();
1683 //=============================================================================
1684 /*! \brief create a PyScriptNode object to execute remote python code
1685 * \param nodeName the name of the node
1686 * \param code the python code to load
1687 * \return the PyScriptNode
1689 //=============================================================================
1690 Engines::PyScriptNode_ptr Engines_Container_i::createPyScriptNode(const char* nodeName, const char* code)
1692 Engines::PyScriptNode_var node= Engines::PyScriptNode::_nil();
1694 PyGILState_STATE gstate = PyGILState_Ensure();
1695 PyObject *res = PyObject_CallMethod(_pyCont,
1696 (char*)"create_pyscriptnode",
1704 PyGILState_Release(gstate);
1705 SALOME::ExceptionStruct es;
1706 es.type = SALOME::INTERNAL_ERROR;
1707 es.text = "can not create a python node";
1708 throw SALOME::SALOME_Exception(es);
1710 long ierr=PyInt_AsLong(PyTuple_GetItem(res,0));
1711 PyObject* result=PyTuple_GetItem(res,1);
1712 std::string astr=PyString_AsString(result);
1714 PyGILState_Release(gstate);
1718 CORBA::Object_var obj = _orb->string_to_object(astr.c_str());
1719 node = Engines::PyScriptNode::_narrow(obj);
1720 if(!CORBA::is_nil(_dftPyScriptNode))
1721 _dftPyScriptNode->UnRegister();
1722 _dftPyScriptNode = node;
1723 if(!CORBA::is_nil(_dftPyScriptNode))
1724 _dftPyScriptNode->Register();
1725 return node._retn();
1729 SALOME::ExceptionStruct es;
1730 es.type = SALOME::INTERNAL_ERROR;
1731 es.text = astr.c_str();
1732 throw SALOME::SALOME_Exception(es);
1736 //=============================================================================
1737 /*! \brief Retrieves the last created PyScriptNode instance with createPyScriptNode.
1740 //=============================================================================
1741 Engines::PyScriptNode_ptr Engines_Container_i::getDefaultPyScriptNode()
1743 if(!CORBA::is_nil(_dftPyScriptNode))
1744 return Engines::PyScriptNode::_duplicate(_dftPyScriptNode);
1746 return Engines::PyScriptNode::_nil();
1749 //=============================================================================
1750 /* int checkifexecutable(const char *filename)
1752 * Return non-zero if the name is an executable file, and
1753 * zero if it is not executable, or if it does not exist.
1755 //=============================================================================
1756 int checkifexecutable(const std::string& filename)
1759 struct stat statinfo;
1761 result = stat(filename.c_str(), &statinfo);
1762 if (result < 0) return 0;
1763 if (!S_ISREG(statinfo.st_mode)) return 0;
1768 if (statinfo.st_uid == geteuid()) return statinfo.st_mode & S_IXUSR;
1769 if (statinfo.st_gid == getegid()) return statinfo.st_mode & S_IXGRP;
1770 return statinfo.st_mode & S_IXOTH;
1775 //=============================================================================
1776 /*! \brief Find a file by searching in a path
1777 * \param filename file name to search
1778 * \param path path to search in
1779 * \param pth the complete file path if found
1780 * \return 1 if found 0 if not
1782 //=============================================================================
1783 int findpathof(const std::string& path, std::string& pth, const std::string& filename)
1785 if ( path.size() == 0 ) return 0;
1787 std::string::size_type offset = 0;
1788 std::string::size_type pos = 0;
1790 struct stat statinfo;
1794 pos = path.find( SEP, offset );
1795 pth = path.substr( offset, pos - offset );
1796 if ( pth.size() > 0 )
1798 if( pth[pth.size()-1] != SLASH ) pth += SLASH;
1800 int result=stat(pth.c_str(), &statinfo);
1801 if(result == 0) found=1;
1803 if (pos == std::string::npos) break;
1809 void Engines_Container_i::registerTemporaryFile( const std::string& fileName )
1811 _tmp_files.remove( fileName );
1812 _tmp_files.push_back( fileName );
1815 void Engines_Container_i::unregisterTemporaryFile( const std::string& fileName )
1817 _tmp_files.remove( fileName );
1820 void Engines_Container_i::clearTemporaryFiles()
1822 std::list<std::string>::const_iterator it;
1823 for ( it = _tmp_files.begin(); it != _tmp_files.end(); ++it ) {
1825 std::string command = "del /F ";
1827 std::string command = "rm -rf ";
1830 system( command.c_str() );