1 // Copyright (C) 2007-2012 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.
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 PyGILState_STATE gstate = PyGILState_Ensure();
207 // mpv: this is temporary solution: there is a unregular crash if not
210 // first element is the path to Registry.dll, but it's wrong
211 PyRun_SimpleString("import sys\n");
212 PyRun_SimpleString("sys.path = sys.path[1:]\n");
214 PyRun_SimpleString("import SALOME_Container\n");
215 PyRun_SimpleString((char*)myCommand.c_str());
216 PyObject *mainmod = PyImport_AddModule("__main__");
217 PyObject *globals = PyModule_GetDict(mainmod);
218 _pyCont = PyDict_GetItemString(globals, "pyCont");
220 PyGILState_Release(gstate);
222 fileTransfer_i* aFileTransfer = new fileTransfer_i();
223 CORBA::Object_var obref=aFileTransfer->_this();
224 _fileTransfer = Engines::fileTransfer::_narrow(obref);
225 aFileTransfer->_remove_ref();
229 //=============================================================================
233 //=============================================================================
235 Engines_Container_i::~Engines_Container_i()
237 MESSAGE("Container_i::~Container_i()");
244 //=============================================================================
245 //! Get container name
247 * CORBA attribute: Container name (see constructor)
249 //=============================================================================
251 char* Engines_Container_i::name()
253 return CORBA::string_dup(_containerName.c_str()) ;
256 //=============================================================================
257 //! Get container working directory
259 * CORBA attribute: Container working directory
261 //=============================================================================
263 char* Engines_Container_i::workingdir()
267 return CORBA::string_dup(wd) ;
270 //=============================================================================
271 //! Get container log file name
273 * CORBA attribute: Container log file name
275 //=============================================================================
277 char* Engines_Container_i::logfilename()
279 return CORBA::string_dup(_logfilename.c_str()) ;
282 //! Set container log file name
283 void Engines_Container_i::logfilename(const char* name)
288 //=============================================================================
289 //! Get container host name
291 * CORBA method: Get the hostName of the Container (without domain extensions)
293 //=============================================================================
295 char* Engines_Container_i::getHostName()
297 std::string s = Kernel_Utils::GetHostname();
298 // MESSAGE("Engines_Container_i::getHostName " << s);
299 return CORBA::string_dup(s.c_str()) ;
302 //=============================================================================
303 //! Get container PID
305 * CORBA method: Get the PID (process identification) of the Container
307 //=============================================================================
309 CORBA::Long Engines_Container_i::getPID()
311 return (CORBA::Long)getpid();
314 //=============================================================================
315 //! Ping the servant to check it is still alive
317 * CORBA method: check if servant is still alive
319 //=============================================================================
320 void Engines_Container_i::ping()
322 MESSAGE("Engines_Container_i::ping() pid "<< getpid());
325 //=============================================================================
326 //! Shutdown the container
328 * CORBA method, oneway: Server shutdown.
329 * - Container name removed from naming service,
330 * - servant deactivation,
331 * - orb shutdown if no other servants in the process
333 //=============================================================================
334 void Engines_Container_i::Shutdown()
336 MESSAGE("Engines_Container_i::Shutdown()");
338 // Clear registered temporary files
339 clearTemporaryFiles();
341 /* For each component contained in this container
342 * tell it to self-destroy
344 std::map<std::string, Engines::EngineComponent_var>::iterator itm;
345 for (itm = _listInstances_map.begin(); itm != _listInstances_map.end(); itm++)
349 itm->second->destroy();
351 catch(const CORBA::Exception& e)
353 // ignore this entry and continue
357 // ignore this entry and continue
360 _listInstances_map.clear();
362 _NS->Destroy_FullDirectory(_containerName.c_str());
363 _NS->Destroy_Name(_containerName.c_str());
364 if(_isServantAloneInProcess)
366 MESSAGE("Effective Shutdown of container Begins...");
367 if(!CORBA::is_nil(_orb))
372 //=============================================================================
373 //! load a component implementation
376 * \param componentName component name
377 * \param reason explains error when load fails
378 * \return true if dlopen successfull or already done, false otherwise
380 //=============================================================================
382 Engines_Container_i::load_component_Library(const char* componentName, CORBA::String_out reason)
385 //=================================================================
386 // --- C++ implementation section
387 //=================================================================
389 if(load_component_CppImplementation(componentName,retso))
391 reason=CORBA::string_dup("");
394 else if(retso != "ImplementationNotFound")
396 reason=CORBA::string_dup(retso.c_str());
401 retso+=componentName;
402 retso+=": Can't find C++ implementation ";
403 retso+=std::string(LIB) + componentName + ENGINESO;
405 //=================================================================
406 // --- Python implementation section
407 //=================================================================
409 if(load_component_PythonImplementation(componentName,retpy))
411 reason=CORBA::string_dup("");
414 else if(retpy != "ImplementationNotFound")
416 reason=CORBA::string_dup(retpy.c_str());
421 retpy+=componentName;
422 retpy+=": Can't find python implementation ";
423 retpy+=componentName;
426 //=================================================================
427 // -- Executable implementation section
428 //=================================================================
430 if(load_component_ExecutableImplementation(componentName,retex))
432 reason=CORBA::string_dup("");
435 else if(retex != "ImplementationNotFound")
437 reason=CORBA::string_dup(retex.c_str());
442 retex+=componentName;
443 retex+=": Can't find executable implementation ";
444 retex+=componentName;
447 std::string ret="Component implementation not found: ";
448 ret += componentName ;
454 std::cerr << ret << std::endl;
455 reason=CORBA::string_dup(ret.c_str());
460 //=============================================================================
461 //! try to load a C++ component implementation
464 * \param componentName the name of the component (COMPONENT, for example)
465 * \param reason explains error when load fails
466 * \return true if loading is successfull or already done, false otherwise
468 //=============================================================================
470 Engines_Container_i::load_component_CppImplementation(const char* componentName, std::string& reason)
472 std::string aCompName(componentName);
473 std::string impl_name = std::string(LIB) + aCompName + ENGINESO;
476 _numInstanceMutex.lock(); // lock to be alone
477 // (see decInstanceCnt, finalize_removal))
478 if (_toRemove_map.count(impl_name) != 0) _toRemove_map.erase(impl_name);
479 if (_library_map.count(impl_name) != 0)
481 MESSAGE("Library " << impl_name << " already loaded");
482 _numInstanceMutex.unlock();
486 _numInstanceMutex.unlock();
490 handle = dlopen( impl_name.c_str() , RTLD_NOW ) ;
493 //not loadable. Try to find the lib file in LD_LIBRARY_PATH
495 char* p=getenv("LD_LIBRARY_PATH");
497 path=path+SEP+"/usr/lib"+SEP+"/lib";
500 if(findpathof(path, pth, impl_name))
502 //found but not loadable
505 reason+=": C++ implementation found ";
507 reason+=" but it is not loadable. Error:\n";
509 std::cerr << reason << std::endl;
515 //continue with other implementation
516 reason="ImplementationNotFound";
522 handle = LoadLibrary( impl_name.c_str() );
525 reason="ImplementationNotFound";
531 _numInstanceMutex.lock();
532 _library_map[impl_name] = handle;
533 _numInstanceMutex.unlock();
541 //=============================================================================
542 //! try to load a Python component implementation
545 * \param componentName name of the component
546 * \param reason explains error when load fails
547 * \return true if loading is successfull or already done, false otherwise
549 //=============================================================================
551 Engines_Container_i::load_component_PythonImplementation(const char* componentName, std::string& reason)
553 std::string aCompName(componentName);
555 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
556 if (_library_map.count(aCompName) != 0)
558 _numInstanceMutex.unlock() ;
560 return true; // Python Component, already imported
562 _numInstanceMutex.unlock() ;
564 PyGILState_STATE gstate = PyGILState_Ensure();
565 PyObject *result = PyObject_CallMethod(_pyCont,
566 (char*)"import_component",
567 (char*)"s",componentName);
569 reason=PyString_AsString(result);
572 PyGILState_Release(gstate);
576 //Python component has been loaded (import componentName)
577 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
578 _library_map[aCompName] = (void *)_pyCont; // any non O value OK
579 _numInstanceMutex.unlock() ;
580 MESSAGE("import Python: "<< aCompName <<" OK");
583 else if(reason=="ImplementationNotFound")
585 //Python implementation has not been found. Continue with other implementation
586 reason="ImplementationNotFound";
590 //Python implementation has been found but loading has failed
591 std::cerr << reason << std::endl;
596 //=============================================================================
597 //! try to load a Executable component implementation
600 * \param componentName name of the component
601 * \param reason explains error when load fails
602 * \return true if loading is successfull or already done, false otherwise
604 //=============================================================================
606 Engines_Container_i::load_component_ExecutableImplementation(const char* componentName, std::string& reason)
608 std::string aCompName(componentName);
609 std::string executable=aCompName+".exe";
614 char* p=getenv("PATH");
617 if (findpathof(path, pth, executable))
619 if(checkifexecutable(pth))
621 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
622 _library_map[executable] = (void *)1; // any non O value OK
623 _numInstanceMutex.unlock() ;
624 MESSAGE("import executable: "<< pth <<" OK");
630 reason+=": implementation found ";
632 reason+=" but it is not executable";
633 std::cerr << reason << std::endl;
637 reason="ImplementationNotFound";
642 //=============================================================================
643 //! Create a new component instance
645 * CORBA method: Creates a new servant instance of a component.
646 * The servant registers itself to naming service and Registry.
647 * \param genericRegisterName Name of the component instance to register
648 * in Registry & Name Service (without _inst_n suffix)
649 * \param studyId 0 for multiStudy instance,
650 * study Id (>0) otherwise
651 * \return a loaded component
653 //=============================================================================
654 Engines::EngineComponent_ptr
655 Engines_Container_i::create_component_instance(const char*genericRegisterName,
658 Engines::FieldsDict_var env = new Engines::FieldsDict;
660 Engines::EngineComponent_ptr compo =
661 create_component_instance_env(genericRegisterName, studyId, env, reason);
662 CORBA::string_free(reason);
666 //=============================================================================
667 //! Create a new component instance with environment variables specified
669 * CORBA method: Creates a new servant instance of a component.
670 * The servant registers itself to naming service and Registry.
671 * \param genericRegisterName Name of the component instance to register
672 * in Registry & Name Service (without _inst_n suffix)
673 * \param studyId 0 for multiStudy instance,
674 * study Id (>0) otherwise
675 * \param env dict of env variables
676 * \param reason explains error when create_component_instance_env fails
677 * \return a loaded component
679 //=============================================================================
680 Engines::EngineComponent_ptr
681 Engines_Container_i::create_component_instance_env(const char*genericRegisterName,
683 const Engines::FieldsDict& env,
684 CORBA::String_out reason)
688 INFOS("studyId must be > 0 for mono study instance, =0 for multiStudy");
689 reason=CORBA::string_dup("studyId must be > 0 for mono study instance, =0 for multiStudy");
690 return Engines::EngineComponent::_nil() ;
694 if (_library_map.count(genericRegisterName) != 0)
696 // It's a Python component
697 Engines::EngineComponent_ptr compo = createPythonInstance(genericRegisterName, studyId, error);
698 reason=CORBA::string_dup(error.c_str());
702 std::string impl_name = std::string(LIB) + genericRegisterName + ENGINESO;
703 if (_library_map.count(impl_name) != 0)
705 // It's a C++ component
706 void* handle = _library_map[impl_name];
707 Engines::EngineComponent_ptr compo = createInstance(genericRegisterName, handle, studyId, error);
708 reason=CORBA::string_dup(error.c_str());
712 impl_name = std::string(genericRegisterName) + ".exe";
713 if (_library_map.count(impl_name) != 0)
715 //It's an executable component
716 Engines::EngineComponent_ptr compo = createExecutableInstance(genericRegisterName, studyId, env, error);
717 reason=CORBA::string_dup(error.c_str());
721 error="load_component_Library has probably not been called for component: ";
722 error += genericRegisterName;
724 reason=CORBA::string_dup(error.c_str());
725 return Engines::EngineComponent::_nil() ;
728 //=============================================================================
729 //! Create a new component instance (Executable implementation)
731 * \param CompName Name of the component instance
732 * \param studyId 0 for multiStudy instance,
733 * study Id (>0) otherwise
734 * \param env dict of env variables
735 * \param reason explains error when creation fails
736 * \return a loaded component
738 * This component is implemented in an executable with name genericRegisterName.exe
739 * It must register itself in Naming Service. The container waits some time (10 s max)
742 //=============================================================================
743 Engines::EngineComponent_ptr
744 Engines_Container_i::createExecutableInstance(std::string CompName, int studyId,
745 const Engines::FieldsDict& env,
748 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
750 _numInstanceMutex.lock() ; // lock on the instance number
752 int numInstance = _numInstance ;
753 _numInstanceMutex.unlock() ;
756 sprintf( aNumI , "%d" , numInstance ) ;
757 std::string instanceName = CompName + "_inst_" + aNumI ;
758 std::string component_registerName = _containerName + "/" + instanceName;
760 //check if an entry exist in naming service
761 CORBA::Object_var nsobj = _NS->Resolve(component_registerName.c_str());
762 if ( !CORBA::is_nil(nsobj) )
764 // unregister the registered component
765 _NS->Destroy_Name(component_registerName.c_str());
766 //kill or shutdown it ???
769 // first arg container ior string
770 // second arg container name
771 // third arg instance name
773 Engines::Container_var pCont= _this();
774 CORBA::String_var sior = _orb->object_to_string(pCont);
778 command+=instanceName;
780 command+=instanceName;
785 command+= sior; // container ior string
787 command+=_containerName; //container name
789 command+=instanceName; //instance name
791 MESSAGE("SALOME_Container::create_component_instance command=" << command);
794 // use fork/execl instead of system to get finer control on env variables
797 if(pid == 0) // child
799 for (CORBA::ULong i=0; i < env.length(); i++)
801 if (env[i].value.type()->kind() == CORBA::tk_string)
804 env[i].value >>= value;
805 std::string s(env[i].key);
808 putenv(strdup(s.c_str()));
812 execl("/bin/sh", "sh", "-c", command.c_str() , (char *)0);
815 else if(pid < 0) // failed to fork
824 tpid = wait(&status);
825 } while (tpid != pid);
828 // launch component with a system call
829 int status=system(command.c_str());
834 reason="SALOME_Container::create_component_instance system failed (system command status -1)";
836 return Engines::EngineComponent::_nil();
839 else if (WEXITSTATUS(status) == 217)
841 reason="SALOME_Container::create_component_instance system failed (system command status 217)";
843 return Engines::EngineComponent::_nil();
849 if (getenv("TIMEOUT_TO_WAIT_EXE_COMPONENT") != 0)
851 std::string new_count_str = getenv("TIMEOUT_TO_WAIT_EXE_COMPONENT");
853 std::istringstream ss(new_count_str);
854 if (!(ss >> new_count))
856 INFOS("[Container] TIMEOUT_TO_WAIT_EXE_COMPONENT should be an int");
861 INFOS("[Container] waiting " << count << " second steps exe component ");
862 CORBA::Object_var obj = CORBA::Object::_nil() ;
863 while ( CORBA::is_nil(obj) && count )
871 MESSAGE( count << ". Waiting for component " << CompName);
872 obj = _NS->Resolve(component_registerName.c_str());
875 if(CORBA::is_nil(obj))
877 reason="SALOME_Container::create_component_instance failed";
879 return Engines::EngineComponent::_nil();
883 MESSAGE("SALOME_Container::create_component_instance successful");
884 iobject = Engines::EngineComponent::_narrow(obj);
885 _listInstances_map[instanceName] = iobject;
886 return iobject._retn();
892 //=============================================================================
893 //! Create a new component instance (Python implementation)
895 * \param CompName Name of the component instance
896 * \param studyId 0 for multiStudy instance,
897 * study Id (>0) otherwise
898 * \param reason explains error when creation fails
899 * \return a loaded component
901 //=============================================================================
902 Engines::EngineComponent_ptr
903 Engines_Container_i::createPythonInstance(std::string CompName, int studyId,
906 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
908 _numInstanceMutex.lock() ; // lock on the instance number
910 int numInstance = _numInstance ;
911 _numInstanceMutex.unlock() ;
914 sprintf( aNumI , "%d" , numInstance ) ;
915 std::string instanceName = CompName + "_inst_" + aNumI ;
916 std::string component_registerName = _containerName + "/" + instanceName;
918 PyGILState_STATE gstate = PyGILState_Ensure();
919 PyObject *result = PyObject_CallMethod(_pyCont,
920 (char*)"create_component_instance",
923 instanceName.c_str(),
927 PyArg_ParseTuple(result,"ss", &ior, &error);
928 std::string iors = ior;
931 PyGILState_Release(gstate);
935 CORBA::Object_var obj = _orb->string_to_object(iors.c_str());
936 iobject = Engines::EngineComponent::_narrow( obj ) ;
937 _listInstances_map[instanceName] = iobject;
939 return iobject._retn();
942 //=============================================================================
943 //! Create a new component instance (C++ implementation)
945 * C++ method: create a servant instance of a component.
946 * \param genericRegisterName Name of the component instance to register
947 * in Registry & Name Service,
948 * (without _inst_n suffix, like "COMPONENT")
949 * \param handle loaded library handle
950 * \param studyId 0 for multiStudy instance,
951 * study Id (>0) otherwise
952 * \param reason explains error when creation fails
953 * \return a loaded component
955 * example with names:
956 * - aGenRegisterName = COMPONENT (= first argument)
957 * - _containerName = /Containers/cli76ce/FactoryServer
958 * - factoryName = COMPONENTEngine_factory
959 * - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
960 * - instanceName = COMPONENT_inst_1
961 * - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
963 //=============================================================================
964 Engines::EngineComponent_ptr
965 Engines_Container_i::createInstance(std::string genericRegisterName,
970 // --- find the factory
972 std::string aGenRegisterName = genericRegisterName;
973 std::string factory_name = aGenRegisterName + std::string("Engine_factory");
974 SCRUTE(factory_name) ;
976 typedef PortableServer::ObjectId* (*FACTORY_FUNCTION) (CORBA::ORB_ptr,
977 PortableServer::POA_ptr,
978 PortableServer::ObjectId *,
983 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)dlsym( handle, factory_name.c_str() );
985 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)GetProcAddress( (HINSTANCE)handle, factory_name.c_str() );
988 if ( !Component_factory )
990 INFOS( "Can't resolve symbol: " + factory_name );
995 return Engines::EngineComponent::_nil() ;
998 // --- create instance
1000 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1004 _numInstanceMutex.lock() ; // lock on the instance number
1006 int numInstance = _numInstance ;
1007 _numInstanceMutex.unlock() ;
1010 sprintf( aNumI , "%d" , numInstance ) ;
1011 std::string instanceName = aGenRegisterName + "_inst_" + aNumI ;
1012 std::string component_registerName =
1013 _containerName + "/" + instanceName;
1015 // --- Instanciate required CORBA object
1017 PortableServer::ObjectId *id ; //not owner, do not delete (nore use var)
1018 id = (Component_factory) ( _orb, _poa, _id, instanceName.c_str(),
1019 aGenRegisterName.c_str() ) ;
1022 reason="Can't get ObjectId from factory";
1024 return iobject._retn();
1027 // --- get reference & servant from id
1029 CORBA::Object_var obj = _poa->id_to_reference(*id);
1030 iobject = Engines::EngineComponent::_narrow( obj ) ;
1032 Engines_Component_i *servant =
1033 dynamic_cast<Engines_Component_i*>(_poa->reference_to_servant(iobject));
1035 //SCRUTE(servant->_refcount_value());
1036 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1037 _listInstances_map[instanceName] = iobject;
1038 _cntInstances_map[aGenRegisterName] += 1;
1039 _numInstanceMutex.unlock() ;
1040 SCRUTE(aGenRegisterName);
1041 SCRUTE(_cntInstances_map[aGenRegisterName]);
1042 servant->setStudyId(studyId);
1043 servant->_remove_ref(); // do not need servant any more (remove ref from reference_to_servant)
1044 //SCRUTE(servant->_refcount_value());
1046 // --- register the engine under the name
1047 // containerName(.dir)/instanceName(.object)
1049 _NS->Register( iobject , component_registerName.c_str() ) ;
1050 MESSAGE( component_registerName.c_str() << " bound" ) ;
1054 reason="Container_i::createInstance exception catched";
1057 return iobject._retn();
1060 //=============================================================================
1061 //! Find an existing (in the container) component instance
1063 * CORBA method: Finds a servant instance of a component
1064 * \param registeredName Name of the component in Registry or Name Service,
1065 * without instance suffix number
1066 * \param studyId 0 if instance is not associated to a study,
1067 * >0 otherwise (== study id)
1068 * \return the first instance found with same studyId
1070 //=============================================================================
1071 Engines::EngineComponent_ptr
1072 Engines_Container_i::find_component_instance( const char* registeredName,
1073 CORBA::Long studyId)
1075 Engines::EngineComponent_var anEngine = Engines::EngineComponent::_nil();
1076 std::map<std::string,Engines::EngineComponent_var>::iterator itm =_listInstances_map.begin();
1077 while (itm != _listInstances_map.end())
1079 std::string instance = (*itm).first;
1081 if (instance.find(registeredName) == 0)
1083 anEngine = (*itm).second;
1084 if (studyId == anEngine->getStudyId())
1086 return anEngine._retn();
1091 return anEngine._retn();
1094 //=============================================================================
1095 //! Remove the component instance from container
1097 * CORBA method: Stops the component servant, and deletes all related objects
1098 * \param component_i Component to be removed
1100 //=============================================================================
1102 void Engines_Container_i::remove_impl(Engines::EngineComponent_ptr component_i)
1104 ASSERT(! CORBA::is_nil(component_i));
1105 std::string instanceName = component_i->instanceName() ;
1106 MESSAGE("unload component " << instanceName);
1107 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1108 _listInstances_map.erase(instanceName);
1109 _numInstanceMutex.unlock() ;
1110 component_i->destroy() ;
1111 _NS->Destroy_Name(instanceName.c_str());
1114 //=============================================================================
1115 //! Unload component libraries from the container
1117 * CORBA method: Discharges unused libraries from the container.
1119 //=============================================================================
1120 void Engines_Container_i::finalize_removal()
1122 MESSAGE("finalize unload : dlclose");
1123 _numInstanceMutex.lock(); // lock to be alone
1124 // (see decInstanceCnt, load_component_Library)
1125 std::map<std::string, void *>::iterator ith;
1126 for (ith = _toRemove_map.begin(); ith != _toRemove_map.end(); ith++)
1128 void *handle = (*ith).second;
1129 std::string impl_name= (*ith).first;
1134 // dlclose(handle); // SALOME unstable after ...
1135 // _library_map.erase(impl_name);
1138 _toRemove_map.clear();
1139 _numInstanceMutex.unlock();
1142 //=============================================================================
1143 //! Decrement component instance reference count
1147 //=============================================================================
1148 void Engines_Container_i::decInstanceCnt(std::string genericRegisterName)
1150 if(_cntInstances_map.count(genericRegisterName)==0)
1152 std::string aGenRegisterName =genericRegisterName;
1153 MESSAGE("Engines_Container_i::decInstanceCnt " << aGenRegisterName);
1154 ASSERT(_cntInstances_map[aGenRegisterName] > 0);
1155 _numInstanceMutex.lock(); // lock to be alone
1156 // (see finalize_removal, load_component_Library)
1157 _cntInstances_map[aGenRegisterName] -= 1;
1158 SCRUTE(_cntInstances_map[aGenRegisterName]);
1159 if (_cntInstances_map[aGenRegisterName] == 0)
1161 std::string impl_name =
1162 Engines_Component_i::GetDynLibraryName(aGenRegisterName.c_str());
1164 void* handle = _library_map[impl_name];
1166 _toRemove_map[impl_name] = handle;
1168 _numInstanceMutex.unlock();
1171 //=============================================================================
1172 //! Find or create a new component instance
1174 * CORBA method: find or create an instance of the component (servant),
1175 * load a new component class (dynamic library) if required,
1177 * ---- FOR COMPATIBILITY WITH 2.2 ----
1179 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
1181 * The servant registers itself to naming service and Registry.
1182 * \param genericRegisterName Name of the component to register
1183 * in Registry & Name Service
1184 * \param componentName Name of the constructed library of the component
1185 * \return a loaded component
1187 //=============================================================================
1189 Engines::EngineComponent_ptr
1190 Engines_Container_i::load_impl( const char* genericRegisterName,
1191 const char* componentName )
1194 std::string impl_name = std::string(LIB) + genericRegisterName + ENGINESO;
1195 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1196 if (load_component_Library(genericRegisterName,reason))
1197 iobject = find_or_create_instance(genericRegisterName, impl_name);
1198 CORBA::string_free(reason);
1199 return iobject._retn();
1202 //=============================================================================
1203 //! Finds an already existing component instance or create a new instance
1205 * C++ method: Finds an already existing servant instance of a component, or
1206 * create an instance.
1207 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
1208 * \param genericRegisterName Name of the component instance to register
1209 * in Registry & Name Service,
1210 * (without _inst_n suffix, like "COMPONENT")
1211 * \param componentLibraryName like "libCOMPONENTEngine.so"
1212 * \return a loaded component
1214 * example with names:
1215 * - aGenRegisterName = COMPONENT (= first argument)
1216 * - impl_name = libCOMPONENTEngine.so (= second argument)
1217 * - _containerName = /Containers/cli76ce/FactoryServer
1218 * - factoryName = COMPONENTEngine_factory
1219 * - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
1220 * - instanceName = COMPONENT_inst_1
1221 * - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1223 //=============================================================================
1225 Engines::EngineComponent_ptr
1226 Engines_Container_i::find_or_create_instance(std::string genericRegisterName,
1227 std::string componentLibraryName)
1229 std::string aGenRegisterName = genericRegisterName;
1230 std::string impl_name = componentLibraryName;
1231 if (_library_map.count(impl_name) == 0)
1233 INFOS("shared library " << impl_name <<" must be loaded before creating instance");
1234 return Engines::EngineComponent::_nil() ;
1238 // --- find a registered instance in naming service, or create
1240 void* handle = _library_map[impl_name];
1241 std::string component_registerBase =
1242 _containerName + "/" + aGenRegisterName;
1243 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1247 CORBA::Object_var obj =
1248 _NS->ResolveFirst( component_registerBase.c_str());
1249 if ( CORBA::is_nil( obj ) )
1251 iobject = createInstance(genericRegisterName,
1254 reason); // force multiStudy instance here !
1258 iobject = Engines::EngineComponent::_narrow( obj ) ;
1259 Engines_Component_i *servant =
1260 dynamic_cast<Engines_Component_i*>
1261 (_poa->reference_to_servant(iobject));
1263 int studyId = servant->getStudyId();
1264 ASSERT (studyId >= 0);
1265 if (studyId == 0) // multiStudy instance, OK
1268 MESSAGE(component_registerBase.c_str()<<" already bound");
1270 else // monoStudy instance: NOK
1272 iobject = Engines::EngineComponent::_nil();
1273 INFOS("load_impl & find_component_instance methods "
1274 << "NOT SUITABLE for mono study components");
1280 INFOS( "Container_i::load_impl catched" ) ;
1282 return iobject._retn();
1286 //=============================================================================
1287 //! Indicate if container is a python one
1289 * Retrieves only with container naming convention if it is a python container
1291 //=============================================================================
1292 bool Engines_Container_i::isPythonContainer(const char* ContainerName)
1295 int len=strlen(ContainerName);
1297 if(strcmp(ContainerName+len-2,"Py")==0)
1302 //=============================================================================
1303 //! Kill the container
1305 * CORBA method: Kill the container process with exit(0).
1306 * To remove : never returns !
1308 //=============================================================================
1309 bool Engines_Container_i::Kill_impl()
1311 MESSAGE("Engines_Container_i::Kill() pid "<< getpid() << " containerName "
1312 << _containerName.c_str() << " machineName "
1313 << Kernel_Utils::GetHostname().c_str());
1314 INFOS("===============================================================");
1315 INFOS("= REMOVE calls to Kill_impl in C++ container =");
1316 INFOS("===============================================================");
1322 //=============================================================================
1326 //=============================================================================
1327 void ActSigIntHandler()
1330 struct sigaction SigIntAct ;
1331 SigIntAct.sa_sigaction = &SigIntHandler ;
1332 sigemptyset(&SigIntAct.sa_mask);
1333 SigIntAct.sa_flags = SA_SIGINFO ;
1336 // DEBUG 03.02.2005 : the first parameter of sigaction is not a mask of signals
1337 // (SIGINT | SIGUSR1) :
1338 // it must be only one signal ===> one call for SIGINT
1339 // and an other one for SIGUSR1
1342 if ( sigaction( SIGINT , &SigIntAct, NULL ) )
1344 perror("SALOME_Container main ") ;
1347 if ( sigaction( SIGUSR1 , &SigIntAct, NULL ) )
1349 perror("SALOME_Container main ") ;
1352 if ( sigaction( SIGUSR2 , &SigIntAct, NULL ) )
1354 perror("SALOME_Container main ") ;
1358 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1359 // use of streams (and so on) should never be used because :
1360 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1361 // A stream operation may be interrupted by a signal and if the Handler use stream we
1362 // may have a "Dead-Lock" ===HangUp
1363 //==INFOS is commented
1364 // INFOS(pthread_self() << "SigIntHandler activated") ;
1367 signal( SIGINT, SigIntHandler );
1368 signal( SIGUSR1, SigIntHandler );
1374 void CallCancelThread() ;
1377 void SigIntHandler(int what ,
1378 siginfo_t * siginfo ,
1381 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1382 // use of streams (and so on) should never be used because :
1383 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1384 // A stream operation may be interrupted by a signal and if the Handler use stream we
1385 // may have a "Dead-Lock" ===HangUp
1386 //==MESSAGE is commented
1387 // MESSAGE(pthread_self() << "SigIntHandler what " << what << std::endl
1388 // << " si_signo " << siginfo->si_signo << std::endl
1389 // << " si_code " << siginfo->si_code << std::endl
1390 // << " si_pid " << siginfo->si_pid) ;
1395 // MESSAGE("SigIntHandler END sleeping.") ;
1400 ActSigIntHandler() ;
1401 if ( siginfo->si_signo == SIGUSR1 )
1405 else if ( siginfo->si_signo == SIGUSR2 )
1407 CallCancelThread() ;
1412 // MESSAGE("SigIntHandler BEGIN sleeping.") ;
1419 // MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1425 void SigIntHandler( int what )
1428 MESSAGE( pthread_self() << "SigIntHandler what " << what << std::endl );
1430 MESSAGE( "SigIntHandler what " << what << std::endl );
1435 MESSAGE("SigIntHandler END sleeping.") ;
1440 ActSigIntHandler() ;
1441 if ( what == SIGUSR1 )
1448 MESSAGE("SigIntHandler BEGIN sleeping.") ;
1455 MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1462 //=============================================================================
1463 //! Get or create a file reference object associated to a local file (to transfer it)
1465 * CORBA method: get or create a fileRef object associated to a local file
1466 * (a file on the computer on which runs the container server), which stores
1467 * a list of (machine, localFileName) corresponding to copies already done.
1469 * \param origFileName absolute path for a local file to copy on other
1471 * \return a fileRef object associated to the file.
1473 //=============================================================================
1474 Engines::fileRef_ptr
1475 Engines_Container_i::createFileRef(const char* origFileName)
1477 std::string origName(origFileName);
1478 Engines::fileRef_var theFileRef = Engines::fileRef::_nil();
1480 if (origName[0] != '/')
1482 INFOS("path of file to copy must be an absolute path begining with '/'");
1483 return Engines::fileRef::_nil();
1486 if (CORBA::is_nil(_fileRef_map[origName]))
1488 CORBA::Object_var obj=_poa->id_to_reference(*_id);
1489 Engines::Container_var pCont = Engines::Container::_narrow(obj);
1490 fileRef_i* aFileRef = new fileRef_i(pCont, origFileName);
1491 theFileRef = Engines::fileRef::_narrow(aFileRef->_this());
1492 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1493 _fileRef_map[origName] = theFileRef;
1494 _numInstanceMutex.unlock() ;
1497 theFileRef = Engines::fileRef::_duplicate(_fileRef_map[origName]);
1498 ASSERT(! CORBA::is_nil(theFileRef));
1499 return theFileRef._retn();
1502 //=============================================================================
1503 //! Get a fileTransfer reference
1506 * \return a reference to the fileTransfer object
1508 //=============================================================================
1509 Engines::fileTransfer_ptr
1510 Engines_Container_i::getFileTransfer()
1512 Engines::fileTransfer_var aFileTransfer
1513 = Engines::fileTransfer::_duplicate(_fileTransfer);
1514 return aFileTransfer._retn();
1517 //=============================================================================
1518 //! Create a Salome file
1519 //=============================================================================
1520 Engines::Salome_file_ptr
1521 Engines_Container_i::createSalome_file(const char* origFileName)
1523 std::string origName(origFileName);
1524 if (CORBA::is_nil(_Salome_file_map[origName]))
1526 Salome_file_i* aSalome_file = new Salome_file_i();
1527 aSalome_file->setContainer(Engines::Container::_duplicate(this->_this()));
1530 aSalome_file->setLocalFile(origFileName);
1531 aSalome_file->recvFiles();
1533 catch (const SALOME::SALOME_Exception& e)
1535 return Engines::Salome_file::_nil();
1538 Engines::Salome_file_var theSalome_file = Engines::Salome_file::_nil();
1539 theSalome_file = Engines::Salome_file::_narrow(aSalome_file->_this());
1540 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1541 _Salome_file_map[origName] = theSalome_file;
1542 _numInstanceMutex.unlock() ;
1545 Engines::Salome_file_ptr theSalome_file =
1546 Engines::Salome_file::_duplicate(_Salome_file_map[origName]);
1547 ASSERT(!CORBA::is_nil(theSalome_file));
1548 return theSalome_file;
1551 //=============================================================================
1552 /*! \brief copy a file from a remote host (container) to the local host
1553 * \param container the remote container
1554 * \param remoteFile the file to copy locally from the remote host into localFile
1555 * \param localFile the local file
1557 //=============================================================================
1558 void Engines_Container_i::copyFile(Engines::Container_ptr container, const char* remoteFile, const char* localFile)
1560 Engines::fileTransfer_var fileTransfer = container->getFileTransfer();
1563 if ((fp = fopen(localFile,"wb")) == NULL)
1565 INFOS("file " << localFile << " cannot be open for writing");
1569 CORBA::Long fileId = fileTransfer->open(remoteFile);
1572 Engines::fileBlock* aBlock;
1579 aBlock = fileTransfer->getBlock(fileId);
1580 toFollow = aBlock->length();
1582 CORBA::Octet *buf = aBlock->get_buffer();
1583 fwrite(buf, sizeof(CORBA::Octet), toFollow, fp);
1587 MESSAGE("end of transfer");
1588 fileTransfer->close(fileId);
1592 INFOS("open reference file for copy impossible");
1596 //=============================================================================
1597 /*! \brief create a PyNode object to execute remote python code
1598 * \param nodeName the name of the node
1599 * \param code the python code to load
1600 * \return the PyNode
1602 //=============================================================================
1603 Engines::PyNode_ptr Engines_Container_i::createPyNode(const char* nodeName, const char* code)
1605 Engines::PyNode_var node= Engines::PyNode::_nil();
1607 PyGILState_STATE gstate = PyGILState_Ensure();
1608 PyObject *res = PyObject_CallMethod(_pyCont,
1609 (char*)"create_pynode",
1617 PyGILState_Release(gstate);
1618 SALOME::ExceptionStruct es;
1619 es.type = SALOME::INTERNAL_ERROR;
1620 es.text = "can not create a python node";
1621 throw SALOME::SALOME_Exception(es);
1623 long ierr=PyInt_AsLong(PyTuple_GetItem(res,0));
1624 PyObject* result=PyTuple_GetItem(res,1);
1625 std::string astr=PyString_AsString(result);
1627 PyGILState_Release(gstate);
1631 CORBA::Object_var obj = _orb->string_to_object(astr.c_str());
1632 node = Engines::PyNode::_narrow(obj);
1633 return node._retn();
1637 SALOME::ExceptionStruct es;
1638 es.type = SALOME::INTERNAL_ERROR;
1639 es.text = astr.c_str();
1640 throw SALOME::SALOME_Exception(es);
1645 //=============================================================================
1646 /*! \brief create a PyScriptNode object to execute remote python code
1647 * \param nodeName the name of the node
1648 * \param code the python code to load
1649 * \return the PyScriptNode
1651 //=============================================================================
1652 Engines::PyScriptNode_ptr Engines_Container_i::createPyScriptNode(const char* nodeName, const char* code)
1654 Engines::PyScriptNode_var node= Engines::PyScriptNode::_nil();
1656 PyGILState_STATE gstate = PyGILState_Ensure();
1657 PyObject *res = PyObject_CallMethod(_pyCont,
1658 (char*)"create_pyscriptnode",
1666 PyGILState_Release(gstate);
1667 SALOME::ExceptionStruct es;
1668 es.type = SALOME::INTERNAL_ERROR;
1669 es.text = "can not create a python node";
1670 throw SALOME::SALOME_Exception(es);
1672 long ierr=PyInt_AsLong(PyTuple_GetItem(res,0));
1673 PyObject* result=PyTuple_GetItem(res,1);
1674 std::string astr=PyString_AsString(result);
1676 PyGILState_Release(gstate);
1680 CORBA::Object_var obj = _orb->string_to_object(astr.c_str());
1681 node = Engines::PyScriptNode::_narrow(obj);
1682 return node._retn();
1686 SALOME::ExceptionStruct es;
1687 es.type = SALOME::INTERNAL_ERROR;
1688 es.text = astr.c_str();
1689 throw SALOME::SALOME_Exception(es);
1693 //=============================================================================
1694 /* int checkifexecutable(const char *filename)
1696 * Return non-zero if the name is an executable file, and
1697 * zero if it is not executable, or if it does not exist.
1699 //=============================================================================
1700 int checkifexecutable(const std::string& filename)
1703 struct stat statinfo;
1705 result = stat(filename.c_str(), &statinfo);
1706 if (result < 0) return 0;
1707 if (!S_ISREG(statinfo.st_mode)) return 0;
1712 if (statinfo.st_uid == geteuid()) return statinfo.st_mode & S_IXUSR;
1713 if (statinfo.st_gid == getegid()) return statinfo.st_mode & S_IXGRP;
1714 return statinfo.st_mode & S_IXOTH;
1719 //=============================================================================
1720 /*! \brief Find a file by searching in a path
1721 * \param filename file name to search
1722 * \param path path to search in
1723 * \param pth the complete file path if found
1724 * \return 1 if found 0 if not
1726 //=============================================================================
1727 int findpathof(const std::string& path, std::string& pth, const std::string& filename)
1729 if ( path.size() == 0 ) return 0;
1731 std::string::size_type offset = 0;
1732 std::string::size_type pos = 0;
1734 struct stat statinfo;
1738 pos = path.find( SEP, offset );
1739 pth = path.substr( offset, pos - offset );
1740 if ( pth.size() > 0 )
1742 if( pth[pth.size()-1] != SLASH ) pth += SLASH;
1744 int result=stat(pth.c_str(), &statinfo);
1745 if(result == 0) found=1;
1747 if (pos == std::string::npos) break;
1753 void Engines_Container_i::registerTemporaryFile( const std::string& fileName )
1755 _tmp_files.remove( fileName );
1756 _tmp_files.push_back( fileName );
1759 void Engines_Container_i::unregisterTemporaryFile( const std::string& fileName )
1761 _tmp_files.remove( fileName );
1764 void Engines_Container_i::clearTemporaryFiles()
1766 std::list<std::string>::const_iterator it;
1767 for ( it = _tmp_files.begin(); it != _tmp_files.end(); ++it ) {
1769 std::string command = "del /F ";
1771 std::string command = "rm -rf ";
1774 system( command.c_str() );