1 // SALOME Container : implementation of container and engine for Kernel
3 // Copyright (C) 2003 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.opencascade.org/SALOME/ or email : webmaster.salome@opencascade.org
24 // File : Container_i.cxx
25 // Author : Paul RASCLE, EDF - MARC TAJCHMAN, CEA
29 //#define private public
38 #include "../../adm/win32/SALOME_WNT.hxx"
44 #include "utilities.h"
45 #include <SALOMEconfig.h>
47 #include CORBA_SERVER_HEADER(SALOME_Component)
49 #include <SALOME_Component.hh>
51 #include <pthread.h> // must be before Python.h !
52 #include "SALOME_Container_i.hxx"
53 #include "SALOME_Component_i.hxx"
54 #include "SALOME_NamingService.hxx"
58 #include "Container_init_python.hxx"
62 bool _Sleeping = false ;
64 // // Needed by multi-threaded Python --- Supervision
69 // Containers with name FactoryServer are started via rsh in LifeCycleCORBA
70 // Other Containers are started via start_impl of FactoryServer
72 extern "C" {void ActSigIntHandler() ; }
74 extern "C" {void SigIntHandler(int, siginfo_t *, void *) ; }
76 extern "C" {void SigIntHandler( int ) ; }
80 map<std::string, int> Engines_Container_i::_cntInstances_map;
81 map<std::string, void *> Engines_Container_i::_library_map;
82 map<std::string, void *> Engines_Container_i::_toRemove_map;
83 omni_mutex Engines_Container_i::_numInstanceMutex ;
85 //=============================================================================
87 * Default constructor, not for use
89 //=============================================================================
91 Engines_Container_i::Engines_Container_i () :
96 //=============================================================================
100 //=============================================================================
102 Engines_Container_i::Engines_Container_i (CORBA::ORB_ptr orb,
103 PortableServer::POA_var poa,
104 char *containerName ,
105 int argc , char* argv[],
107 bool isServantAloneInProcess
109 _numInstance(0),_isServantAloneInProcess(isServantAloneInProcess)
111 _pid = (long)getpid();
119 string hostname = GetHostname();
120 MESSAGE(hostname << " " << getpid() << " Engines_Container_i starting argc "
121 << _argc << " Thread " << pthread_self() ) ;
126 MESSAGE(" argv" << i << " " << _argv[ i ]) ;
132 INFOS("SALOME_Container usage : SALOME_Container ServerName");
136 _isSupervContainer = false;
137 if (strcmp(argv[1],"SuperVisionContainer") == 0) _isSupervContainer = true;
139 if (_isSupervContainer)
145 _orb = CORBA::ORB::_duplicate(orb) ;
146 _poa = PortableServer::POA::_duplicate(poa) ;
148 // Pour les containers paralleles: il ne faut pas enregistrer et activer
149 // le container generique, mais le container specialise
153 _id = _poa->activate_object(this);
154 _NS = new SALOME_NamingService();
155 _NS->init_orb( CORBA::ORB::_duplicate(_orb) ) ;
156 CORBA::Object_var obj=_poa->id_to_reference(*_id);
157 Engines::Container_var pCont
158 = Engines::Container::_narrow(obj);
160 _containerName = _NS->BuildContainerNameForNS(containerName,
162 SCRUTE(_containerName);
163 _NS->Register(pCont, _containerName.c_str());
164 MESSAGE("Engines_Container_i::Engines_Container_i : Container name "
168 // import SALOME_Container
169 // pycont = SALOME_Container.SALOME_Container_i(containerIORStr)
171 CORBA::String_var sior = _orb->object_to_string(pCont);
172 string myCommand="pyCont = SALOME_Container.SALOME_Container_i('";
173 myCommand += _containerName + "','";
178 if (!_isSupervContainer)
180 Py_ACQUIRE_NEW_THREAD;
182 // mpv: this is temporary solution: there is a unregular crash if not
184 PyRun_SimpleString("import sys\n");
185 // first element is the path to Registry.dll, but it's wrong
186 PyRun_SimpleString("sys.path = sys.path[1:]\n");
188 PyRun_SimpleString("import SALOME_Container\n");
189 PyRun_SimpleString((char*)myCommand.c_str());
190 Py_RELEASE_NEW_THREAD;
195 //=============================================================================
199 //=============================================================================
201 Engines_Container_i::~Engines_Container_i()
203 MESSAGE("Container_i::~Container_i()");
207 //=============================================================================
209 * CORBA attribute: Container name (see constructor)
211 //=============================================================================
213 char* Engines_Container_i::name()
215 return CORBA::string_dup(_containerName.c_str()) ;
218 //=============================================================================
220 * CORBA method: Get the hostName of the Container (without domain extensions)
222 //=============================================================================
224 char* Engines_Container_i::getHostName()
226 string s = GetHostname();
227 // MESSAGE("Engines_Container_i::getHostName " << s);
228 return CORBA::string_dup(s.c_str()) ;
231 //=============================================================================
233 * CORBA method: Get the PID (process identification) of the Container
235 //=============================================================================
237 CORBA::Long Engines_Container_i::getPID()
239 return (CORBA::Long)getpid();
242 //=============================================================================
244 * CORBA method: check if servant is still alive
246 //=============================================================================
248 void Engines_Container_i::ping()
250 MESSAGE("Engines_Container_i::ping() pid "<< getpid());
253 //=============================================================================
255 * CORBA method, oneway: Server shutdown.
256 * - Container name removed from naming service,
257 * - servant deactivation,
258 * - orb shutdown if no other servants in the process
260 //=============================================================================
262 void Engines_Container_i::Shutdown()
264 MESSAGE("Engines_Container_i::Shutdown()");
265 _NS->Destroy_FullDirectory(_containerName.c_str());
267 //_poa->deactivate_object(*_id);
268 if(_isServantAloneInProcess)
270 MESSAGE("Effective Shutdown of container Begins...");
271 LocalTraceBufferPool* bp1 = LocalTraceBufferPool::instance();
272 bp1->deleteInstance(bp1);
278 //=============================================================================
280 * CORBA method: load a new component class (Python or C++ implementation)
281 * \param componentName like COMPONENT
282 * try to make a Python import of COMPONENT,
283 * then a lib open of libCOMPONENTEngine.so
284 * \return true if dlopen successfull or already done, false otherwise
286 //=============================================================================
289 Engines_Container_i::load_component_Library(const char* componentName)
292 string aCompName = componentName;
294 // --- try dlopen C++ component
297 string impl_name = string ("lib") + aCompName + string("Engine.so");
299 string impl_name = aCompName + string("Engine.dll");
303 _numInstanceMutex.lock(); // lock to be alone
304 // (see decInstanceCnt, finalize_removal))
305 if (_toRemove_map[impl_name]) _toRemove_map.erase(impl_name);
306 if (_library_map[impl_name])
308 MESSAGE("Library " << impl_name << " already loaded");
309 _numInstanceMutex.unlock();
315 handle = dlopen( impl_name.c_str() , 0 ) ;
316 //#elif defined( __osf1__ )
317 // handle = dlopen( impl_name.c_str() , RTLD_NOW ) ;
319 handle = dlopen( impl_name.c_str() , RTLD_LAZY ) ;
323 _library_map[impl_name] = handle;
324 _numInstanceMutex.unlock();
329 INFOS("Can't load shared library : " << impl_name);
330 INFOS("error dlopen: " << dlerror());
332 _numInstanceMutex.unlock();
334 // --- try import Python component
336 INFOS("try import Python component "<<componentName);
337 if (_isSupervContainer)
339 INFOS("Supervision Container does not support Python Component Engines");
342 if (_library_map[aCompName])
344 return true; // Python Component, already imported
348 Py_ACQUIRE_NEW_THREAD;
349 PyObject *mainmod = PyImport_AddModule("__main__");
350 PyObject *globals = PyModule_GetDict(mainmod);
351 PyObject *pyCont = PyDict_GetItemString(globals, "pyCont");
352 PyObject *result = PyObject_CallMethod(pyCont,
355 int ret= PyInt_AsLong(result);
357 Py_RELEASE_NEW_THREAD;
359 if (ret) // import possible: Python component
361 _library_map[aCompName] = (void *)pyCont; // any non O value OK
362 MESSAGE("import Python: "<<aCompName<<" OK");
369 //=============================================================================
371 * CORBA method: Creates a new servant instance of a component.
372 * The servant registers itself to naming service and Registry.
373 * \param genericRegisterName Name of the component instance to register
374 * in Registry & Name Service (without _inst_n suffix)
375 * \param studyId 0 for multiStudy instance,
376 * study Id (>0) otherwise
377 * \return a loaded component
379 //=============================================================================
381 Engines::Component_ptr
382 Engines_Container_i::create_component_instance(const char*genericRegisterName,
387 INFOS("studyId must be > 0 for mono study instance, =0 for multiStudy");
388 return Engines::Component::_nil() ;
391 Engines::Component_var iobject = Engines::Component::_nil() ;
393 string aCompName = genericRegisterName;
394 if (_library_map[aCompName]) // Python component
396 if (_isSupervContainer)
398 INFOS("Supervision Container does not support Python Component Engines");
399 return Engines::Component::_nil();
401 _numInstanceMutex.lock() ; // lock on the instance number
403 int numInstance = _numInstance ;
404 _numInstanceMutex.unlock() ;
407 sprintf( aNumI , "%d" , numInstance ) ;
408 string instanceName = aCompName + "_inst_" + aNumI ;
409 string component_registerName =
410 _containerName + "/" + instanceName;
412 Py_ACQUIRE_NEW_THREAD;
413 PyObject *mainmod = PyImport_AddModule("__main__");
414 PyObject *globals = PyModule_GetDict(mainmod);
415 PyObject *pyCont = PyDict_GetItemString(globals, "pyCont");
416 PyObject *result = PyObject_CallMethod(pyCont,
417 "create_component_instance",
420 instanceName.c_str(),
422 string iors = PyString_AsString(result);
424 Py_RELEASE_NEW_THREAD;
428 CORBA::Object_var obj = _orb->string_to_object(iors.c_str());
429 iobject = Engines::Component::_narrow( obj ) ;
431 return iobject._retn();
437 string impl_name = string ("lib") + genericRegisterName +string("Engine.so");
439 string impl_name = genericRegisterName +string("Engine.dll");
441 void* handle = _library_map[impl_name];
444 INFOS("shared library " << impl_name <<"must be loaded before instance");
445 return Engines::Component::_nil() ;
449 iobject = createInstance(genericRegisterName,
452 return iobject._retn();
456 //=============================================================================
458 * CORBA method: Finds a servant instance of a component
459 * \param registeredName Name of the component in Registry or Name Service,
460 * without instance suffix number
461 * \param studyId 0 if instance is not associated to a study,
462 * >0 otherwise (== study id)
463 * \return the first instance found with same studyId
465 //=============================================================================
467 Engines::Component_ptr
468 Engines_Container_i::find_component_instance( const char* registeredName,
471 Engines::Component_var anEngine = Engines::Component::_nil();
472 map<string,Engines::Component_var>::iterator itm =_listInstances_map.begin();
473 while (itm != _listInstances_map.end())
475 string instance = (*itm).first;
477 if (instance.find(registeredName) == 0)
479 anEngine = (*itm).second;
480 if (studyId == anEngine->getStudyId())
482 return anEngine._retn();
487 return anEngine._retn();
490 //=============================================================================
492 * CORBA method: find or create an instance of the component (servant),
493 * load a new component class (dynamic library) if required,
494 * ---- FOR COMPATIBILITY WITH 2.2 ----
495 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
496 * The servant registers itself to naming service and Registry.
497 * \param genericRegisterName Name of the component to register
498 * in Registry & Name Service
499 * \param componentName Name of the constructed library of the component
500 * \return a loaded component
502 //=============================================================================
504 Engines::Component_ptr
505 Engines_Container_i::load_impl( const char* genericRegisterName,
506 const char* componentName )
508 string impl_name = string ("lib") + genericRegisterName +string("Engine.so");
509 Engines::Component_var iobject = Engines::Component::_nil() ;
510 if (load_component_Library(genericRegisterName))
511 iobject = find_or_create_instance(genericRegisterName, impl_name);
512 return iobject._retn();
516 //=============================================================================
518 * CORBA method: Stops the component servant, and deletes all related objects
519 * \param component_i Component to be removed
521 //=============================================================================
523 void Engines_Container_i::remove_impl(Engines::Component_ptr component_i)
525 ASSERT(! CORBA::is_nil(component_i));
526 string instanceName = component_i->instanceName() ;
527 MESSAGE("unload component " << instanceName);
528 _listInstances_map.erase(instanceName);
529 component_i->destroy() ;
530 _NS->Destroy_Name(instanceName.c_str());
533 //=============================================================================
535 * CORBA method: Discharges unused libraries from the container.
537 //=============================================================================
539 void Engines_Container_i::finalize_removal()
541 MESSAGE("finalize unload : dlclose");
542 _numInstanceMutex.lock(); // lock to be alone
543 // (see decInstanceCnt, load_component_Library)
544 map<string, void *>::iterator ith;
545 for (ith = _toRemove_map.begin(); ith != _toRemove_map.end(); ith++)
547 void *handle = (*ith).second;
548 string impl_name= (*ith).first;
553 // dlclose(handle); // SALOME unstable after ...
554 // _library_map.erase(impl_name);
557 _toRemove_map.clear();
558 _numInstanceMutex.unlock();
561 //=============================================================================
563 * CORBA method: Kill the container process with exit(0).
564 * To remove : never returns !
566 //=============================================================================
568 bool Engines_Container_i::Kill_impl()
570 MESSAGE("Engines_Container_i::Kill() pid "<< getpid() << " containerName "
571 << _containerName.c_str() << " machineName "
572 << GetHostname().c_str());
573 INFOS("===============================================================");
574 INFOS("= REMOVE calls to Kill_impl in C++ container =");
575 INFOS("===============================================================");
581 //=============================================================================
583 * C++ method: Finds an already existing servant instance of a component, or
584 * create an instance.
585 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
586 * \param genericRegisterName Name of the component instance to register
587 * in Registry & Name Service,
588 * (without _inst_n suffix, like "COMPONENT")
589 * \param componentLibraryName like "libCOMPONENTEngine.so"
590 * \return a loaded component
592 * example with names:
593 * aGenRegisterName = COMPONENT (= first argument)
594 * impl_name = libCOMPONENTEngine.so (= second argument)
595 * _containerName = /Containers/cli76ce/FactoryServer
596 * factoryName = COMPONENTEngine_factory
597 * component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
599 * instanceName = COMPONENT_inst_1
600 * component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
602 //=============================================================================
604 Engines::Component_ptr
605 Engines_Container_i::find_or_create_instance(string genericRegisterName,
606 string componentLibraryName)
608 string aGenRegisterName = genericRegisterName;
609 string impl_name = componentLibraryName;
610 void* handle = _library_map[impl_name];
613 INFOS("shared library " << impl_name <<"must be loaded before instance");
614 return Engines::Component::_nil() ;
618 // --- find a registered instance in naming service, or create
620 string component_registerBase =
621 _containerName + "/" + aGenRegisterName;
622 Engines::Component_var iobject = Engines::Component::_nil() ;
625 CORBA::Object_var obj =
626 _NS->ResolveFirst( component_registerBase.c_str());
627 if ( CORBA::is_nil( obj ) )
629 iobject = createInstance(genericRegisterName,
631 0); // force multiStudy instance here !
635 iobject = Engines::Component::_narrow( obj ) ;
636 Engines_Component_i *servant =
637 dynamic_cast<Engines_Component_i*>
638 (_poa->reference_to_servant(iobject));
640 int studyId = servant->getStudyId();
641 ASSERT (studyId >= 0);
642 if (studyId == 0) // multiStudy instance, OK
645 MESSAGE(component_registerBase.c_str()<<" already bound");
647 else // monoStudy instance: NOK
649 iobject = Engines::Component::_nil();
650 INFOS("load_impl & find_component_instance methods "
651 << "NOT SUITABLE for mono study components");
657 INFOS( "Container_i::load_impl catched" ) ;
659 return iobject._retn();
663 //=============================================================================
665 * C++ method: create a servant instance of a component.
666 * \param genericRegisterName Name of the component instance to register
667 * in Registry & Name Service,
668 * (without _inst_n suffix, like "COMPONENT")
669 * \param handle loaded library handle
670 * \param studyId 0 for multiStudy instance,
671 * study Id (>0) otherwise
672 * \return a loaded component
674 * example with names:
675 * aGenRegisterName = COMPONENT (= first argument)
676 * _containerName = /Containers/cli76ce/FactoryServer
677 * factoryName = COMPONENTEngine_factory
678 * component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
679 * instanceName = COMPONENT_inst_1
680 * component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
682 //=============================================================================
684 Engines::Component_ptr
685 Engines_Container_i::createInstance(string genericRegisterName,
689 // --- find the factory
691 string aGenRegisterName = genericRegisterName;
692 string factory_name = aGenRegisterName + string("Engine_factory");
693 SCRUTE(factory_name) ;
695 typedef PortableServer::ObjectId * (*FACTORY_FUNCTION)
697 PortableServer::POA_ptr,
698 PortableServer::ObjectId *,
702 FACTORY_FUNCTION Component_factory
703 = (FACTORY_FUNCTION) dlsym(handle, factory_name.c_str());
706 if ( (error = dlerror() ) != NULL)
708 INFOS("Can't resolve symbol: " + factory_name);
710 return Engines::Component::_nil() ;
713 // --- create instance
715 Engines::Component_var iobject = Engines::Component::_nil() ;
719 _numInstanceMutex.lock() ; // lock on the instance number
721 int numInstance = _numInstance ;
722 _numInstanceMutex.unlock() ;
725 sprintf( aNumI , "%d" , numInstance ) ;
726 string instanceName = aGenRegisterName + "_inst_" + aNumI ;
727 string component_registerName =
728 _containerName + "/" + instanceName;
730 // --- Instanciate required CORBA object
732 PortableServer::ObjectId *id ; //not owner, do not delete (nore use var)
733 id = (Component_factory) ( _orb, _poa, _id, instanceName.c_str(),
734 aGenRegisterName.c_str() ) ;
736 // --- get reference & servant from id
738 CORBA::Object_var obj = _poa->id_to_reference(*id);
739 iobject = Engines::Component::_narrow( obj ) ;
741 Engines_Component_i *servant =
742 dynamic_cast<Engines_Component_i*>(_poa->reference_to_servant(iobject));
744 //SCRUTE(servant->pd_refCount);
745 servant->_remove_ref(); // compensate previous id_to_reference
746 //SCRUTE(servant->pd_refCount);
747 _listInstances_map[instanceName] = iobject;
748 _cntInstances_map[aGenRegisterName] += 1;
749 SCRUTE(aGenRegisterName);
750 SCRUTE(_cntInstances_map[aGenRegisterName]);
751 //SCRUTE(servant->pd_refCount);
752 bool ret_studyId = servant->setStudyId(studyId);
755 // --- register the engine under the name
756 // containerName(.dir)/instanceName(.object)
758 _NS->Register( iobject , component_registerName.c_str() ) ;
759 MESSAGE( component_registerName.c_str() << " bound" ) ;
763 INFOS( "Container_i::createInstance exception catched" ) ;
765 return iobject._retn();
768 //=============================================================================
772 //=============================================================================
774 void Engines_Container_i::decInstanceCnt(string genericRegisterName)
776 string aGenRegisterName =genericRegisterName;
777 MESSAGE("Engines_Container_i::decInstanceCnt " << aGenRegisterName);
778 ASSERT(_cntInstances_map[aGenRegisterName] > 0);
779 _numInstanceMutex.lock(); // lock to be alone
780 // (see finalize_removal, load_component_Library)
781 _cntInstances_map[aGenRegisterName] -= 1;
782 SCRUTE(_cntInstances_map[aGenRegisterName]);
783 if (_cntInstances_map[aGenRegisterName] == 0)
786 Engines_Component_i::GetDynLibraryName(aGenRegisterName.c_str());
788 void* handle = _library_map[impl_name];
790 _toRemove_map[impl_name] = handle;
792 _numInstanceMutex.unlock();
795 //=============================================================================
797 * Retrieves only with container naming convention if it is a python container
799 //=============================================================================
801 bool Engines_Container_i::isPythonContainer(const char* ContainerName)
804 int len=strlen(ContainerName);
806 if(strcmp(ContainerName+len-2,"Py")==0)
811 //=============================================================================
815 //=============================================================================
817 void ActSigIntHandler()
820 struct sigaction SigIntAct ;
821 SigIntAct.sa_sigaction = &SigIntHandler ;
822 SigIntAct.sa_flags = SA_SIGINFO ;
825 // DEBUG 03.02.2005 : the first parameter of sigaction is not a mask of signals
826 // (SIGINT | SIGUSR1) :
827 // it must be only one signal ===> one call for SIGINT
828 // and an other one for SIGUSR1
831 if ( sigaction( SIGINT , &SigIntAct, NULL ) )
833 perror("SALOME_Container main ") ;
836 if ( sigaction( SIGUSR1 , &SigIntAct, NULL ) )
838 perror("SALOME_Container main ") ;
842 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
843 // use of streams (and so on) should never be used because :
844 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
845 // A stream operation may be interrupted by a signal and if the Handler use stream we
846 // may have a "Dead-Lock" ===HangUp
847 //==INFOS is commented
848 // INFOS(pthread_self() << "SigIntHandler activated") ;
851 signal( SIGINT, SigIntHandler );
852 signal( SIGUSR1, SigIntHandler );
860 void SigIntHandler(int what ,
861 siginfo_t * siginfo ,
864 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
865 // use of streams (and so on) should never be used because :
866 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
867 // A stream operation may be interrupted by a signal and if the Handler use stream we
868 // may have a "Dead-Lock" ===HangUp
869 //==MESSAGE is commented
870 // MESSAGE(pthread_self() << "SigIntHandler what " << what << endl
871 // << " si_signo " << siginfo->si_signo << endl
872 // << " si_code " << siginfo->si_code << endl
873 // << " si_pid " << siginfo->si_pid) ;
878 // MESSAGE("SigIntHandler END sleeping.") ;
884 if ( siginfo->si_signo == SIGUSR1 )
891 // MESSAGE("SigIntHandler BEGIN sleeping.") ;
898 // MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
904 void SigIntHandler( int what )
906 MESSAGE( pthread_self() << "SigIntHandler what " << what << endl );
910 MESSAGE("SigIntHandler END sleeping.") ;
916 if ( what == SIGUSR1 )
923 MESSAGE("SigIntHandler BEGIN sleeping.") ;
930 MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;