1 // Copyright (C) 2007-2010 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"
60 #include "Container_init_python.hxx"
62 bool _Sleeping = false ;
64 // // Needed by multi-threaded Python --- Supervision
68 extern "C" {void ActSigIntHandler() ; }
70 extern "C" {void SigIntHandler(int, siginfo_t *, void *) ; }
72 extern "C" {void SigIntHandler( int ) ; }
77 #define ENGINESO "Engine.so"
80 #define ENGINESO "Engine.dll"
91 std::map<std::string, int> Engines_Container_i::_cntInstances_map;
92 std::map<std::string, void *> Engines_Container_i::_library_map;
93 std::map<std::string, void *> Engines_Container_i::_toRemove_map;
94 omni_mutex Engines_Container_i::_numInstanceMutex ;
96 static PyObject* _pyCont;
98 int checkifexecutable(const std::string&);
99 int findpathof(const std::string& path, std::string&, const std::string&);
101 /*! \class Engines_Container_i
102 * \brief C++ implementation of Engines::Container interface
107 //=============================================================================
109 * Default constructor, not for use
111 //=============================================================================
113 Engines_Container_i::Engines_Container_i () :
114 _numInstance(0),_id(0),_NS(0)
118 //=============================================================================
122 //=============================================================================
124 Engines_Container_i::Engines_Container_i (CORBA::ORB_ptr orb,
125 PortableServer::POA_ptr poa,
126 char *containerName ,
127 int argc , char* argv[],
129 bool isServantAloneInProcess
131 _numInstance(0),_isServantAloneInProcess(isServantAloneInProcess),_id(0),_NS(0)
133 _pid = (long)getpid();
141 std::string hostname = Kernel_Utils::GetHostname();
143 MESSAGE(hostname << " " << getpid() <<
144 " Engines_Container_i starting argc " <<
145 _argc << " Thread " << pthread_self() ) ;
147 MESSAGE(hostname << " " << _getpid() <<
148 " Engines_Container_i starting argc " << _argc<< " Thread " << pthread_self().p ) ;
154 MESSAGE(" argv" << i << " " << _argv[ i ]) ;
160 INFOS("SALOME_Container usage : SALOME_Container ServerName");
164 _isSupervContainer = false;
166 _orb = CORBA::ORB::_duplicate(orb) ;
167 _poa = PortableServer::POA::_duplicate(poa) ;
169 // Pour les containers paralleles: il ne faut pas enregistrer et activer
170 // le container generique, mais le container specialise
174 _id = _poa->activate_object(this);
175 _NS = new SALOME_NamingService();
176 _NS->init_orb( _orb ) ;
177 CORBA::Object_var obj=_poa->id_to_reference(*_id);
178 Engines::Container_var pCont
179 = Engines::Container::_narrow(obj);
182 _containerName = _NS->BuildContainerNameForNS(containerName,
184 SCRUTE(_containerName);
185 _NS->Register(pCont, _containerName.c_str());
186 MESSAGE("Engines_Container_i::Engines_Container_i : Container name "
190 // import SALOME_Container
191 // pycont = SALOME_Container.SALOME_Container_i(containerIORStr)
193 CORBA::String_var sior = _orb->object_to_string(pCont);
194 std::string myCommand="pyCont = SALOME_Container.SALOME_Container_i('";
195 myCommand += _containerName + "','";
200 PyGILState_STATE gstate = PyGILState_Ensure();
203 // mpv: this is temporary solution: there is a unregular crash if not
206 // first element is the path to Registry.dll, but it's wrong
207 PyRun_SimpleString("import sys\n");
208 PyRun_SimpleString("sys.path = sys.path[1:]\n");
210 PyRun_SimpleString("import SALOME_Container\n");
211 PyRun_SimpleString((char*)myCommand.c_str());
212 PyObject *mainmod = PyImport_AddModule("__main__");
213 PyObject *globals = PyModule_GetDict(mainmod);
214 _pyCont = PyDict_GetItemString(globals, "pyCont");
216 PyGILState_Release(gstate);
218 fileTransfer_i* aFileTransfer = new fileTransfer_i();
219 CORBA::Object_var obref=aFileTransfer->_this();
220 _fileTransfer = Engines::fileTransfer::_narrow(obref);
221 aFileTransfer->_remove_ref();
225 //=============================================================================
229 //=============================================================================
231 Engines_Container_i::~Engines_Container_i()
233 MESSAGE("Container_i::~Container_i()");
240 //=============================================================================
241 //! Get container name
243 * CORBA attribute: Container name (see constructor)
245 //=============================================================================
247 char* Engines_Container_i::name()
249 return CORBA::string_dup(_containerName.c_str()) ;
252 //=============================================================================
253 //! Get container working directory
255 * CORBA attribute: Container working directory
257 //=============================================================================
259 char* Engines_Container_i::workingdir()
263 return CORBA::string_dup(wd) ;
266 //=============================================================================
267 //! Get container log file name
269 * CORBA attribute: Container log file name
271 //=============================================================================
273 char* Engines_Container_i::logfilename()
275 return CORBA::string_dup(_logfilename.c_str()) ;
278 //! Set container log file name
279 void Engines_Container_i::logfilename(const char* name)
284 //=============================================================================
285 //! Get container host name
287 * CORBA method: Get the hostName of the Container (without domain extensions)
289 //=============================================================================
291 char* Engines_Container_i::getHostName()
293 std::string s = Kernel_Utils::GetHostname();
294 // MESSAGE("Engines_Container_i::getHostName " << s);
295 return CORBA::string_dup(s.c_str()) ;
298 //=============================================================================
299 //! Get container PID
301 * CORBA method: Get the PID (process identification) of the Container
303 //=============================================================================
305 CORBA::Long Engines_Container_i::getPID()
307 return (CORBA::Long)getpid();
310 //=============================================================================
311 //! Ping the servant to check it is still alive
313 * CORBA method: check if servant is still alive
315 //=============================================================================
316 void Engines_Container_i::ping()
318 MESSAGE("Engines_Container_i::ping() pid "<< getpid());
321 //=============================================================================
322 //! Shutdown the container
324 * CORBA method, oneway: Server shutdown.
325 * - Container name removed from naming service,
326 * - servant deactivation,
327 * - orb shutdown if no other servants in the process
329 //=============================================================================
330 void Engines_Container_i::Shutdown()
332 MESSAGE("Engines_Container_i::Shutdown()");
334 /* For each component contained in this container
335 * tell it to self-destroy
337 std::map<std::string, Engines::Component_var>::iterator itm;
338 for (itm = _listInstances_map.begin(); itm != _listInstances_map.end(); itm++)
342 itm->second->destroy();
344 catch(const CORBA::Exception& e)
346 // ignore this entry and continue
350 // ignore this entry and continue
353 _listInstances_map.clear();
355 _NS->Destroy_FullDirectory(_containerName.c_str());
356 _NS->Destroy_Name(_containerName.c_str());
357 if(_isServantAloneInProcess)
359 MESSAGE("Effective Shutdown of container Begins...");
360 if(!CORBA::is_nil(_orb))
365 //=============================================================================
366 //! load a component implementation
369 * \param componentName component name
370 * \param reason explains error when load fails
371 * \return true if dlopen successfull or already done, false otherwise
373 //=============================================================================
375 Engines_Container_i::load_component_Library(const char* componentName, CORBA::String_out reason)
378 //=================================================================
379 // --- C++ implementation section
380 //=================================================================
382 if(load_component_CppImplementation(componentName,retso))
384 reason=CORBA::string_dup("");
387 else if(retso != "ImplementationNotFound")
389 reason=CORBA::string_dup(retso.c_str());
394 retso+=componentName;
395 retso+=": Can't find C++ implementation ";
396 retso+=std::string(LIB) + componentName + ENGINESO;
398 //=================================================================
399 // --- Python implementation section
400 //=================================================================
402 if(load_component_PythonImplementation(componentName,retpy))
404 reason=CORBA::string_dup("");
407 else if(retpy != "ImplementationNotFound")
409 reason=CORBA::string_dup(retpy.c_str());
414 retpy+=componentName;
415 retpy+=": Can't find python implementation ";
416 retpy+=componentName;
419 //=================================================================
420 // -- Executable implementation section
421 //=================================================================
423 if(load_component_ExecutableImplementation(componentName,retex))
425 reason=CORBA::string_dup("");
428 else if(retex != "ImplementationNotFound")
430 reason=CORBA::string_dup(retex.c_str());
435 retex+=componentName;
436 retex+=": Can't find executable implementation ";
437 retex+=componentName;
440 std::string ret="Component implementation not found: ";
441 ret += componentName ;
447 std::cerr << ret << std::endl;
448 reason=CORBA::string_dup(ret.c_str());
453 //=============================================================================
454 //! try to load a C++ component implementation
457 * \param componentName the name of the component (COMPONENT, for example)
458 * \param reason explains error when load fails
459 * \return true if loading is successfull or already done, false otherwise
461 //=============================================================================
463 Engines_Container_i::load_component_CppImplementation(const char* componentName, std::string& reason)
465 std::string aCompName(componentName);
466 std::string impl_name = std::string(LIB) + aCompName + ENGINESO;
469 _numInstanceMutex.lock(); // lock to be alone
470 // (see decInstanceCnt, finalize_removal))
471 if (_toRemove_map.count(impl_name) != 0) _toRemove_map.erase(impl_name);
472 if (_library_map.count(impl_name) != 0)
474 MESSAGE("Library " << impl_name << " already loaded");
475 _numInstanceMutex.unlock();
479 _numInstanceMutex.unlock();
483 handle = dlopen( impl_name.c_str() , RTLD_NOW ) ;
486 //not loadable. Try to find the lib file in LD_LIBRARY_PATH
488 char* p=getenv("LD_LIBRARY_PATH");
490 path=path+SEP+"/usr/lib"+SEP+"/lib";
493 if(findpathof(path, pth, impl_name))
495 //found but not loadable
498 reason+=": C++ implementation found ";
500 reason+=" but it is not loadable. Error:\n";
502 std::cerr << reason << std::endl;
508 //continue with other implementation
509 reason="ImplementationNotFound";
515 handle = LoadLibrary( impl_name.c_str() );
518 reason="ImplementationNotFound";
524 _numInstanceMutex.lock();
525 _library_map[impl_name] = handle;
526 _numInstanceMutex.unlock();
534 //=============================================================================
535 //! try to load a Python component implementation
538 * \param componentName name of the component
539 * \param reason explains error when load fails
540 * \return true if loading is successfull or already done, false otherwise
542 //=============================================================================
544 Engines_Container_i::load_component_PythonImplementation(const char* componentName, std::string& reason)
546 std::string aCompName(componentName);
548 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
549 if (_library_map.count(aCompName) != 0)
551 _numInstanceMutex.unlock() ;
553 return true; // Python Component, already imported
555 _numInstanceMutex.unlock() ;
557 PyGILState_STATE gstate = PyGILState_Ensure();
558 PyObject *result = PyObject_CallMethod(_pyCont,
559 (char*)"import_component",
560 (char*)"s",componentName);
562 reason=PyString_AsString(result);
565 PyGILState_Release(gstate);
569 //Python component has been loaded (import componentName)
570 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
571 _library_map[aCompName] = (void *)_pyCont; // any non O value OK
572 _numInstanceMutex.unlock() ;
573 MESSAGE("import Python: "<< aCompName <<" OK");
576 else if(reason=="ImplementationNotFound")
578 //Python implementation has not been found. Continue with other implementation
579 reason="ImplementationNotFound";
583 //Python implementation has been found but loading has failed
584 std::cerr << reason << std::endl;
589 //=============================================================================
590 //! try to load a Executable component implementation
593 * \param componentName name of the component
594 * \param reason explains error when load fails
595 * \return true if loading is successfull or already done, false otherwise
597 //=============================================================================
599 Engines_Container_i::load_component_ExecutableImplementation(const char* componentName, std::string& reason)
601 std::string aCompName(componentName);
602 std::string executable=aCompName+".exe";
607 char* p=getenv("PATH");
610 if (findpathof(path, pth, executable))
612 if(checkifexecutable(pth))
614 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
615 _library_map[executable] = (void *)1; // any non O value OK
616 _numInstanceMutex.unlock() ;
617 MESSAGE("import executable: "<< pth <<" OK");
623 reason+=": implementation found ";
625 reason+=" but it is not executable";
626 std::cerr << reason << std::endl;
630 reason="ImplementationNotFound";
635 //=============================================================================
636 //! Create a new component instance
638 * CORBA method: Creates a new servant instance of a component.
639 * The servant registers itself to naming service and Registry.
640 * \param genericRegisterName Name of the component instance to register
641 * in Registry & Name Service (without _inst_n suffix)
642 * \param studyId 0 for multiStudy instance,
643 * study Id (>0) otherwise
644 * \return a loaded component
646 //=============================================================================
647 Engines::Component_ptr
648 Engines_Container_i::create_component_instance(const char*genericRegisterName,
651 Engines::FieldsDict_var env = new Engines::FieldsDict;
653 Engines::Component_ptr compo = create_component_instance_env(genericRegisterName, studyId, env, reason);
654 CORBA::string_free(reason);
658 //=============================================================================
659 //! Create a new component instance with environment variables specified
661 * CORBA method: Creates a new servant instance of a component.
662 * The servant registers itself to naming service and Registry.
663 * \param genericRegisterName Name of the component instance to register
664 * in Registry & Name Service (without _inst_n suffix)
665 * \param studyId 0 for multiStudy instance,
666 * study Id (>0) otherwise
667 * \param env dict of env variables
668 * \param reason explains error when create_component_instance_env fails
669 * \return a loaded component
671 //=============================================================================
672 Engines::Component_ptr
673 Engines_Container_i::create_component_instance_env(const char*genericRegisterName,
675 const Engines::FieldsDict& env,
676 CORBA::String_out reason)
680 INFOS("studyId must be > 0 for mono study instance, =0 for multiStudy");
681 reason=CORBA::string_dup("studyId must be > 0 for mono study instance, =0 for multiStudy");
682 return Engines::Component::_nil() ;
686 if (_library_map.count(genericRegisterName) != 0)
688 // It's a Python component
689 Engines::Component_ptr compo = createPythonInstance(genericRegisterName, studyId, error);
690 reason=CORBA::string_dup(error.c_str());
694 std::string impl_name = std::string(LIB) + genericRegisterName + ENGINESO;
695 if (_library_map.count(impl_name) != 0)
697 // It's a C++ component
698 void* handle = _library_map[impl_name];
699 Engines::Component_ptr compo = createInstance(genericRegisterName, handle, studyId, error);
700 reason=CORBA::string_dup(error.c_str());
704 impl_name = std::string(genericRegisterName) + ".exe";
705 if (_library_map.count(impl_name) != 0)
707 //It's an executable component
708 Engines::Component_ptr compo = createExecutableInstance(genericRegisterName, studyId, env, error);
709 reason=CORBA::string_dup(error.c_str());
713 error="load_component_Library has probably not been called for component: ";
714 error += genericRegisterName;
716 reason=CORBA::string_dup(error.c_str());
717 return Engines::Component::_nil() ;
720 //=============================================================================
721 //! Create a new component instance (Executable implementation)
723 * \param CompName Name of the component instance
724 * \param studyId 0 for multiStudy instance,
725 * study Id (>0) otherwise
726 * \param env dict of env variables
727 * \param reason explains error when creation fails
728 * \return a loaded component
730 * This component is implemented in an executable with name genericRegisterName.exe
731 * It must register itself in Naming Service. The container waits some time (10 s max)
734 //=============================================================================
735 Engines::Component_ptr
736 Engines_Container_i::createExecutableInstance(std::string CompName, int studyId,
737 const Engines::FieldsDict& env,
740 Engines::Component_var iobject = Engines::Component::_nil() ;
742 _numInstanceMutex.lock() ; // lock on the instance number
744 int numInstance = _numInstance ;
745 _numInstanceMutex.unlock() ;
748 sprintf( aNumI , "%d" , numInstance ) ;
749 std::string instanceName = CompName + "_inst_" + aNumI ;
750 std::string component_registerName = _containerName + "/" + instanceName;
752 //check if an entry exist in naming service
753 CORBA::Object_var nsobj = _NS->Resolve(component_registerName.c_str());
754 if ( !CORBA::is_nil(nsobj) )
756 // unregister the registered component
757 _NS->Destroy_Name(component_registerName.c_str());
758 //kill or shutdown it ???
761 // first arg container ior string
762 // second arg container name
763 // third arg instance name
765 Engines::Container_var pCont= _this();
766 CORBA::String_var sior = _orb->object_to_string(pCont);
770 command+=instanceName;
772 command+=instanceName;
777 command+= sior; // container ior string
779 command+=_containerName; //container name
781 command+=instanceName; //instance name
783 MESSAGE("SALOME_Container::create_component_instance command=" << command);
786 // use fork/execl instead of system to get finer control on env variables
789 if(pid == 0) // child
791 for (CORBA::ULong i=0; i < env.length(); i++)
793 if (env[i].value.type()->kind() == CORBA::tk_string)
796 env[i].value >>= value;
797 std::string s(env[i].key);
800 putenv(strdup(s.c_str()));
804 execl("/bin/sh", "sh", "-c", command.c_str() , (char *)0);
807 else if(pid < 0) // failed to fork
816 tpid = wait(&status);
817 } while (tpid != pid);
820 // launch component with a system call
821 int status=system(command.c_str());
826 reason="SALOME_Container::create_component_instance system failed (system command status -1)";
828 return Engines::Component::_nil();
831 else if (WEXITSTATUS(status) == 217)
833 reason="SALOME_Container::create_component_instance system failed (system command status 217)";
835 return Engines::Component::_nil();
841 CORBA::Object_var obj = CORBA::Object::_nil() ;
842 while ( CORBA::is_nil(obj) && count )
850 MESSAGE( count << ". Waiting for component " << CompName);
851 obj = _NS->Resolve(component_registerName.c_str());
854 if(CORBA::is_nil(obj))
856 reason="SALOME_Container::create_component_instance failed";
858 return Engines::Component::_nil();
862 MESSAGE("SALOME_Container::create_component_instance successful");
863 iobject=Engines::Component::_narrow(obj);
864 _listInstances_map[instanceName] = iobject;
865 return iobject._retn();
871 //=============================================================================
872 //! Create a new component instance (Python implementation)
874 * \param CompName Name of the component instance
875 * \param studyId 0 for multiStudy instance,
876 * study Id (>0) otherwise
877 * \param reason explains error when creation fails
878 * \return a loaded component
880 //=============================================================================
881 Engines::Component_ptr
882 Engines_Container_i::createPythonInstance(std::string CompName, int studyId,
885 Engines::Component_var iobject = Engines::Component::_nil() ;
887 _numInstanceMutex.lock() ; // lock on the instance number
889 int numInstance = _numInstance ;
890 _numInstanceMutex.unlock() ;
893 sprintf( aNumI , "%d" , numInstance ) ;
894 std::string instanceName = CompName + "_inst_" + aNumI ;
895 std::string component_registerName = _containerName + "/" + instanceName;
897 PyGILState_STATE gstate = PyGILState_Ensure();
898 PyObject *result = PyObject_CallMethod(_pyCont,
899 (char*)"create_component_instance",
902 instanceName.c_str(),
906 PyArg_ParseTuple(result,"ss", &ior, &error);
907 std::string iors = ior;
910 PyGILState_Release(gstate);
914 CORBA::Object_var obj = _orb->string_to_object(iors.c_str());
915 iobject = Engines::Component::_narrow( obj ) ;
916 _listInstances_map[instanceName] = iobject;
918 return iobject._retn();
921 //=============================================================================
922 //! Create a new component instance (C++ implementation)
924 * C++ method: create a servant instance of a component.
925 * \param genericRegisterName Name of the component instance to register
926 * in Registry & Name Service,
927 * (without _inst_n suffix, like "COMPONENT")
928 * \param handle loaded library handle
929 * \param studyId 0 for multiStudy instance,
930 * study Id (>0) otherwise
931 * \param reason explains error when creation fails
932 * \return a loaded component
934 * example with names:
935 * - aGenRegisterName = COMPONENT (= first argument)
936 * - _containerName = /Containers/cli76ce/FactoryServer
937 * - factoryName = COMPONENTEngine_factory
938 * - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
939 * - instanceName = COMPONENT_inst_1
940 * - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
942 //=============================================================================
943 Engines::Component_ptr
944 Engines_Container_i::createInstance(std::string genericRegisterName,
949 // --- find the factory
951 std::string aGenRegisterName = genericRegisterName;
952 std::string factory_name = aGenRegisterName + std::string("Engine_factory");
953 SCRUTE(factory_name) ;
955 typedef PortableServer::ObjectId* (*FACTORY_FUNCTION) (CORBA::ORB_ptr,
956 PortableServer::POA_ptr,
957 PortableServer::ObjectId *,
962 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)dlsym( handle, factory_name.c_str() );
964 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)GetProcAddress( (HINSTANCE)handle, factory_name.c_str() );
967 if ( !Component_factory )
969 INFOS( "Can't resolve symbol: " + factory_name );
974 return Engines::Component::_nil() ;
977 // --- create instance
979 Engines::Component_var iobject = Engines::Component::_nil() ;
983 _numInstanceMutex.lock() ; // lock on the instance number
985 int numInstance = _numInstance ;
986 _numInstanceMutex.unlock() ;
989 sprintf( aNumI , "%d" , numInstance ) ;
990 std::string instanceName = aGenRegisterName + "_inst_" + aNumI ;
991 std::string component_registerName =
992 _containerName + "/" + instanceName;
994 // --- Instanciate required CORBA object
996 PortableServer::ObjectId *id ; //not owner, do not delete (nore use var)
997 id = (Component_factory) ( _orb, _poa, _id, instanceName.c_str(),
998 aGenRegisterName.c_str() ) ;
1001 reason="Can't get ObjectId from factory";
1003 return iobject._retn();
1006 // --- get reference & servant from id
1008 CORBA::Object_var obj = _poa->id_to_reference(*id);
1009 iobject = Engines::Component::_narrow( obj ) ;
1011 Engines_Component_i *servant =
1012 dynamic_cast<Engines_Component_i*>(_poa->reference_to_servant(iobject));
1014 //SCRUTE(servant->_refcount_value());
1015 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1016 _listInstances_map[instanceName] = iobject;
1017 _cntInstances_map[aGenRegisterName] += 1;
1018 _numInstanceMutex.unlock() ;
1019 SCRUTE(aGenRegisterName);
1020 SCRUTE(_cntInstances_map[aGenRegisterName]);
1021 servant->setStudyId(studyId);
1022 servant->_remove_ref(); // do not need servant any more (remove ref from reference_to_servant)
1023 //SCRUTE(servant->_refcount_value());
1025 // --- register the engine under the name
1026 // containerName(.dir)/instanceName(.object)
1028 _NS->Register( iobject , component_registerName.c_str() ) ;
1029 MESSAGE( component_registerName.c_str() << " bound" ) ;
1033 reason="Container_i::createInstance exception catched";
1036 return iobject._retn();
1039 //=============================================================================
1040 //! Find an existing (in the container) component instance
1042 * CORBA method: Finds a servant instance of a component
1043 * \param registeredName Name of the component in Registry or Name Service,
1044 * without instance suffix number
1045 * \param studyId 0 if instance is not associated to a study,
1046 * >0 otherwise (== study id)
1047 * \return the first instance found with same studyId
1049 //=============================================================================
1050 Engines::Component_ptr
1051 Engines_Container_i::find_component_instance( const char* registeredName,
1052 CORBA::Long studyId)
1054 Engines::Component_var anEngine = Engines::Component::_nil();
1055 std::map<std::string,Engines::Component_var>::iterator itm =_listInstances_map.begin();
1056 while (itm != _listInstances_map.end())
1058 std::string instance = (*itm).first;
1060 if (instance.find(registeredName) == 0)
1062 anEngine = (*itm).second;
1063 if (studyId == anEngine->getStudyId())
1065 return anEngine._retn();
1070 return anEngine._retn();
1073 //=============================================================================
1074 //! Remove the component instance from container
1076 * CORBA method: Stops the component servant, and deletes all related objects
1077 * \param component_i Component to be removed
1079 //=============================================================================
1081 void Engines_Container_i::remove_impl(Engines::Component_ptr component_i)
1083 ASSERT(! CORBA::is_nil(component_i));
1084 std::string instanceName = component_i->instanceName() ;
1085 MESSAGE("unload component " << instanceName);
1086 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1087 _listInstances_map.erase(instanceName);
1088 _numInstanceMutex.unlock() ;
1089 component_i->destroy() ;
1090 _NS->Destroy_Name(instanceName.c_str());
1093 //=============================================================================
1094 //! Unload component libraries from the container
1096 * CORBA method: Discharges unused libraries from the container.
1098 //=============================================================================
1099 void Engines_Container_i::finalize_removal()
1101 MESSAGE("finalize unload : dlclose");
1102 _numInstanceMutex.lock(); // lock to be alone
1103 // (see decInstanceCnt, load_component_Library)
1104 std::map<std::string, void *>::iterator ith;
1105 for (ith = _toRemove_map.begin(); ith != _toRemove_map.end(); ith++)
1107 void *handle = (*ith).second;
1108 std::string impl_name= (*ith).first;
1113 // dlclose(handle); // SALOME unstable after ...
1114 // _library_map.erase(impl_name);
1117 _toRemove_map.clear();
1118 _numInstanceMutex.unlock();
1121 //=============================================================================
1122 //! Decrement component instance reference count
1126 //=============================================================================
1127 void Engines_Container_i::decInstanceCnt(std::string genericRegisterName)
1129 if(_cntInstances_map.count(genericRegisterName)==0)
1131 std::string aGenRegisterName =genericRegisterName;
1132 MESSAGE("Engines_Container_i::decInstanceCnt " << aGenRegisterName);
1133 ASSERT(_cntInstances_map[aGenRegisterName] > 0);
1134 _numInstanceMutex.lock(); // lock to be alone
1135 // (see finalize_removal, load_component_Library)
1136 _cntInstances_map[aGenRegisterName] -= 1;
1137 SCRUTE(_cntInstances_map[aGenRegisterName]);
1138 if (_cntInstances_map[aGenRegisterName] == 0)
1140 std::string impl_name =
1141 Engines_Component_i::GetDynLibraryName(aGenRegisterName.c_str());
1143 void* handle = _library_map[impl_name];
1145 _toRemove_map[impl_name] = handle;
1147 _numInstanceMutex.unlock();
1150 //=============================================================================
1151 //! Find or create a new component instance
1153 * CORBA method: find or create an instance of the component (servant),
1154 * load a new component class (dynamic library) if required,
1156 * ---- FOR COMPATIBILITY WITH 2.2 ----
1158 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
1160 * The servant registers itself to naming service and Registry.
1161 * \param genericRegisterName Name of the component to register
1162 * in Registry & Name Service
1163 * \param componentName Name of the constructed library of the component
1164 * \return a loaded component
1166 //=============================================================================
1168 Engines::Component_ptr
1169 Engines_Container_i::load_impl( const char* genericRegisterName,
1170 const char* componentName )
1173 std::string impl_name = std::string(LIB) + genericRegisterName + ENGINESO;
1174 Engines::Component_var iobject = Engines::Component::_nil() ;
1175 if (load_component_Library(genericRegisterName,reason))
1176 iobject = find_or_create_instance(genericRegisterName, impl_name);
1177 CORBA::string_free(reason);
1178 return iobject._retn();
1181 //=============================================================================
1182 //! Finds an already existing component instance or create a new instance
1184 * C++ method: Finds an already existing servant instance of a component, or
1185 * create an instance.
1186 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
1187 * \param genericRegisterName Name of the component instance to register
1188 * in Registry & Name Service,
1189 * (without _inst_n suffix, like "COMPONENT")
1190 * \param componentLibraryName like "libCOMPONENTEngine.so"
1191 * \return a loaded component
1193 * example with names:
1194 * - aGenRegisterName = COMPONENT (= first argument)
1195 * - impl_name = libCOMPONENTEngine.so (= second argument)
1196 * - _containerName = /Containers/cli76ce/FactoryServer
1197 * - factoryName = COMPONENTEngine_factory
1198 * - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
1199 * - instanceName = COMPONENT_inst_1
1200 * - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1202 //=============================================================================
1204 Engines::Component_ptr
1205 Engines_Container_i::find_or_create_instance(std::string genericRegisterName,
1206 std::string componentLibraryName)
1208 std::string aGenRegisterName = genericRegisterName;
1209 std::string impl_name = componentLibraryName;
1210 if (_library_map.count(impl_name) == 0)
1212 INFOS("shared library " << impl_name <<" must be loaded before creating instance");
1213 return Engines::Component::_nil() ;
1217 // --- find a registered instance in naming service, or create
1219 void* handle = _library_map[impl_name];
1220 std::string component_registerBase =
1221 _containerName + "/" + aGenRegisterName;
1222 Engines::Component_var iobject = Engines::Component::_nil() ;
1226 CORBA::Object_var obj =
1227 _NS->ResolveFirst( component_registerBase.c_str());
1228 if ( CORBA::is_nil( obj ) )
1230 iobject = createInstance(genericRegisterName,
1233 reason); // force multiStudy instance here !
1237 iobject = Engines::Component::_narrow( obj ) ;
1238 Engines_Component_i *servant =
1239 dynamic_cast<Engines_Component_i*>
1240 (_poa->reference_to_servant(iobject));
1242 int studyId = servant->getStudyId();
1243 ASSERT (studyId >= 0);
1244 if (studyId == 0) // multiStudy instance, OK
1247 MESSAGE(component_registerBase.c_str()<<" already bound");
1249 else // monoStudy instance: NOK
1251 iobject = Engines::Component::_nil();
1252 INFOS("load_impl & find_component_instance methods "
1253 << "NOT SUITABLE for mono study components");
1259 INFOS( "Container_i::load_impl catched" ) ;
1261 return iobject._retn();
1265 //=============================================================================
1266 //! Indicate if container is a python one
1268 * Retrieves only with container naming convention if it is a python container
1270 //=============================================================================
1271 bool Engines_Container_i::isPythonContainer(const char* ContainerName)
1274 int len=strlen(ContainerName);
1276 if(strcmp(ContainerName+len-2,"Py")==0)
1281 //=============================================================================
1282 //! Kill the container
1284 * CORBA method: Kill the container process with exit(0).
1285 * To remove : never returns !
1287 //=============================================================================
1288 bool Engines_Container_i::Kill_impl()
1290 MESSAGE("Engines_Container_i::Kill() pid "<< getpid() << " containerName "
1291 << _containerName.c_str() << " machineName "
1292 << Kernel_Utils::GetHostname().c_str());
1293 INFOS("===============================================================");
1294 INFOS("= REMOVE calls to Kill_impl in C++ container =");
1295 INFOS("===============================================================");
1301 //=============================================================================
1305 //=============================================================================
1306 void ActSigIntHandler()
1309 struct sigaction SigIntAct ;
1310 SigIntAct.sa_sigaction = &SigIntHandler ;
1311 sigemptyset(&SigIntAct.sa_mask);
1312 SigIntAct.sa_flags = SA_SIGINFO ;
1315 // DEBUG 03.02.2005 : the first parameter of sigaction is not a mask of signals
1316 // (SIGINT | SIGUSR1) :
1317 // it must be only one signal ===> one call for SIGINT
1318 // and an other one for SIGUSR1
1321 if ( sigaction( SIGINT , &SigIntAct, NULL ) )
1323 perror("SALOME_Container main ") ;
1326 if ( sigaction( SIGUSR1 , &SigIntAct, NULL ) )
1328 perror("SALOME_Container main ") ;
1331 if ( sigaction( SIGUSR2 , &SigIntAct, NULL ) )
1333 perror("SALOME_Container main ") ;
1337 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1338 // use of streams (and so on) should never be used because :
1339 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1340 // A stream operation may be interrupted by a signal and if the Handler use stream we
1341 // may have a "Dead-Lock" ===HangUp
1342 //==INFOS is commented
1343 // INFOS(pthread_self() << "SigIntHandler activated") ;
1346 signal( SIGINT, SigIntHandler );
1347 signal( SIGUSR1, SigIntHandler );
1353 void CallCancelThread() ;
1356 void SigIntHandler(int what ,
1357 siginfo_t * siginfo ,
1360 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1361 // use of streams (and so on) should never be used because :
1362 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1363 // A stream operation may be interrupted by a signal and if the Handler use stream we
1364 // may have a "Dead-Lock" ===HangUp
1365 //==MESSAGE is commented
1366 // MESSAGE(pthread_self() << "SigIntHandler what " << what << std::endl
1367 // << " si_signo " << siginfo->si_signo << std::endl
1368 // << " si_code " << siginfo->si_code << std::endl
1369 // << " si_pid " << siginfo->si_pid) ;
1374 // MESSAGE("SigIntHandler END sleeping.") ;
1379 ActSigIntHandler() ;
1380 if ( siginfo->si_signo == SIGUSR1 )
1384 else if ( siginfo->si_signo == SIGUSR2 )
1386 CallCancelThread() ;
1391 // MESSAGE("SigIntHandler BEGIN sleeping.") ;
1398 // MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1404 void SigIntHandler( int what )
1407 MESSAGE( pthread_self() << "SigIntHandler what " << what << std::endl );
1409 MESSAGE( "SigIntHandler what " << what << std::endl );
1414 MESSAGE("SigIntHandler END sleeping.") ;
1419 ActSigIntHandler() ;
1420 if ( what == SIGUSR1 )
1427 MESSAGE("SigIntHandler BEGIN sleeping.") ;
1434 MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1441 //=============================================================================
1442 //! Get or create a file reference object associated to a local file (to transfer it)
1444 * CORBA method: get or create a fileRef object associated to a local file
1445 * (a file on the computer on which runs the container server), which stores
1446 * a list of (machine, localFileName) corresponding to copies already done.
1448 * \param origFileName absolute path for a local file to copy on other
1450 * \return a fileRef object associated to the file.
1452 //=============================================================================
1453 Engines::fileRef_ptr
1454 Engines_Container_i::createFileRef(const char* origFileName)
1456 std::string origName(origFileName);
1457 Engines::fileRef_var theFileRef = Engines::fileRef::_nil();
1459 if (origName[0] != '/')
1461 INFOS("path of file to copy must be an absolute path begining with '/'");
1462 return Engines::fileRef::_nil();
1465 if (CORBA::is_nil(_fileRef_map[origName]))
1467 CORBA::Object_var obj=_poa->id_to_reference(*_id);
1468 Engines::Container_var pCont = Engines::Container::_narrow(obj);
1469 fileRef_i* aFileRef = new fileRef_i(pCont, origFileName);
1470 theFileRef = Engines::fileRef::_narrow(aFileRef->_this());
1471 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1472 _fileRef_map[origName] = theFileRef;
1473 _numInstanceMutex.unlock() ;
1476 theFileRef = Engines::fileRef::_duplicate(_fileRef_map[origName]);
1477 ASSERT(! CORBA::is_nil(theFileRef));
1478 return theFileRef._retn();
1481 //=============================================================================
1482 //! Get a fileTransfer reference
1485 * \return a reference to the fileTransfer object
1487 //=============================================================================
1488 Engines::fileTransfer_ptr
1489 Engines_Container_i::getFileTransfer()
1491 Engines::fileTransfer_var aFileTransfer
1492 = Engines::fileTransfer::_duplicate(_fileTransfer);
1493 return aFileTransfer._retn();
1496 //=============================================================================
1497 //! Create a Salome file
1498 //=============================================================================
1499 Engines::Salome_file_ptr
1500 Engines_Container_i::createSalome_file(const char* origFileName)
1502 std::string origName(origFileName);
1503 if (CORBA::is_nil(_Salome_file_map[origName]))
1505 Salome_file_i* aSalome_file = new Salome_file_i();
1506 aSalome_file->setContainer(Engines::Container::_duplicate(this->_this()));
1509 aSalome_file->setLocalFile(origFileName);
1510 aSalome_file->recvFiles();
1512 catch (const SALOME::SALOME_Exception& e)
1514 return Engines::Salome_file::_nil();
1517 Engines::Salome_file_var theSalome_file = Engines::Salome_file::_nil();
1518 theSalome_file = Engines::Salome_file::_narrow(aSalome_file->_this());
1519 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1520 _Salome_file_map[origName] = theSalome_file;
1521 _numInstanceMutex.unlock() ;
1524 Engines::Salome_file_ptr theSalome_file =
1525 Engines::Salome_file::_duplicate(_Salome_file_map[origName]);
1526 ASSERT(!CORBA::is_nil(theSalome_file));
1527 return theSalome_file;
1530 //=============================================================================
1531 /*! \brief copy a file from a remote host (container) to the local host
1532 * \param container the remote container
1533 * \param remoteFile the file to copy locally from the remote host into localFile
1534 * \param localFile the local file
1536 //=============================================================================
1537 void Engines_Container_i::copyFile(Engines::Container_ptr container, const char* remoteFile, const char* localFile)
1539 Engines::fileTransfer_var fileTransfer = container->getFileTransfer();
1542 if ((fp = fopen(localFile,"wb")) == NULL)
1544 INFOS("file " << localFile << " cannot be open for writing");
1548 CORBA::Long fileId = fileTransfer->open(remoteFile);
1551 Engines::fileBlock* aBlock;
1558 aBlock = fileTransfer->getBlock(fileId);
1559 toFollow = aBlock->length();
1561 CORBA::Octet *buf = aBlock->get_buffer();
1562 fwrite(buf, sizeof(CORBA::Octet), toFollow, fp);
1566 MESSAGE("end of transfer");
1567 fileTransfer->close(fileId);
1571 INFOS("open reference file for copy impossible");
1575 //=============================================================================
1576 /*! \brief create a PyNode object to execute remote python code
1577 * \param nodeName the name of the node
1578 * \param code the python code to load
1579 * \return the PyNode
1581 //=============================================================================
1582 Engines::PyNode_ptr Engines_Container_i::createPyNode(const char* nodeName, const char* code)
1584 Engines::PyNode_var node= Engines::PyNode::_nil();
1586 PyGILState_STATE gstate = PyGILState_Ensure();
1587 PyObject *res = PyObject_CallMethod(_pyCont,
1588 (char*)"create_pynode",
1596 PyGILState_Release(gstate);
1597 SALOME::ExceptionStruct es;
1598 es.type = SALOME::INTERNAL_ERROR;
1599 es.text = "can not create a python node";
1600 throw SALOME::SALOME_Exception(es);
1602 long ierr=PyInt_AsLong(PyTuple_GetItem(res,0));
1603 PyObject* result=PyTuple_GetItem(res,1);
1604 std::string astr=PyString_AsString(result);
1606 PyGILState_Release(gstate);
1610 CORBA::Object_var obj = _orb->string_to_object(astr.c_str());
1611 node = Engines::PyNode::_narrow(obj);
1612 return node._retn();
1616 SALOME::ExceptionStruct es;
1617 es.type = SALOME::INTERNAL_ERROR;
1618 es.text = astr.c_str();
1619 throw SALOME::SALOME_Exception(es);
1624 //=============================================================================
1625 /* int checkifexecutable(const char *filename)
1627 * Return non-zero if the name is an executable file, and
1628 * zero if it is not executable, or if it does not exist.
1630 //=============================================================================
1631 int checkifexecutable(const std::string& filename)
1634 struct stat statinfo;
1636 result = stat(filename.c_str(), &statinfo);
1637 if (result < 0) return 0;
1638 if (!S_ISREG(statinfo.st_mode)) return 0;
1643 if (statinfo.st_uid == geteuid()) return statinfo.st_mode & S_IXUSR;
1644 if (statinfo.st_gid == getegid()) return statinfo.st_mode & S_IXGRP;
1645 return statinfo.st_mode & S_IXOTH;
1650 //=============================================================================
1651 /*! \brief Find a file by searching in a path
1652 * \param filename file name to search
1653 * \param path path to search in
1654 * \param pth the complete file path if found
1655 * \return 1 if found 0 if not
1657 //=============================================================================
1658 int findpathof(const std::string& path, std::string& pth, const std::string& filename)
1660 if ( path.size() == 0 ) return 0;
1662 std::string::size_type offset = 0;
1663 std::string::size_type pos = 0;
1665 struct stat statinfo;
1669 pos = path.find( SEP, offset );
1670 pth = path.substr( offset, pos - offset );
1671 if ( pth.size() > 0 )
1673 if( pth[pth.size()-1] != SLASH ) pth += SLASH;
1675 int result=stat(pth.c_str(), &statinfo);
1676 if(result == 0) found=1;
1678 if (pos == std::string::npos) break;