Salome HOME
b65bf13bdc699ace327f474ac8f111e2124c8a3e
[modules/kernel.git] / src / Container / Container_i.cxx
1 //  SALOME Container : implementation of container and engine for Kernel
2 //
3 //  Copyright (C) 2003  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS 
5 // 
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. 
10 // 
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. 
15 // 
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 
19 // 
20 //  See http://www.opencascade.org/SALOME/ or email : webmaster.salome@opencascade.org 
21 //
22 //
23 //
24 //  File   : Container_i.cxx
25 //  Author : Paul RASCLE, EDF - MARC TAJCHMAN, CEA 
26 //  Module : SALOME
27 //  $Header$
28
29 #include <SALOMEconfig.h>
30 #include CORBA_SERVER_HEADER(SALOME_Component)
31 #include "SALOME_Container_i.hxx"
32 #include "SALOME_NamingService.hxx"
33 //#include "Utils_SINGLETON.hxx"
34 #include "OpUtil.hxx"
35 #include <string.h>
36 #include <stdio.h>
37 #include <dlfcn.h>
38 #include <unistd.h>
39
40 #include "utilities.h"
41 using namespace std;
42
43 bool _Sleeping = false ;
44
45 // Needed by multi-threaded Python
46 int _ArgC ;
47 char ** _ArgV ;
48
49
50 // Containers with name FactoryServer are started via rsh in LifeCycleCORBA
51 // Other Containers are started via start_impl of FactoryServer
52
53 extern "C" {void ActSigIntHandler() ; }
54 extern "C" {void SigIntHandler(int, siginfo_t *, void *) ; }
55
56 const char *Engines_Container_i::_defaultContainerName="FactoryServer";
57
58 Engines_Container_i::Engines_Container_i () :
59  _numInstance(0)
60 {
61 }
62
63 Engines_Container_i::Engines_Container_i (CORBA::ORB_ptr orb, 
64                                           PortableServer::POA_ptr poa,
65                                           char *containerName ,
66                                           int argc , char* argv[],
67                                           bool activAndRegist,
68                                           bool isServantAloneInProcess
69                                           ) :
70   _numInstance(0),_isServantAloneInProcess(isServantAloneInProcess)
71 {
72   _pid = (long)getpid();
73
74   if(activAndRegist)
75     ActSigIntHandler() ;
76
77   _ArgC = argc ;
78   _ArgV = argv ;
79
80   _argc = argc ;
81   _argv = argv ;
82   int i = strlen( _argv[ 0 ] ) - 1 ;
83   while ( i >= 0 ) {
84     if ( _argv[ 0 ][ i ] == '/' ) {
85       _argv[ 0 ][ i+1 ] = '\0' ;
86       break ;
87     }
88     i -= 1 ;
89   }
90   string hostname = GetHostname();
91   MESSAGE(hostname << " " << getpid() << " Engines_Container_i starting argc "
92           << _argc << " Thread " << pthread_self() ) ;
93   i = 0 ;
94   while ( _argv[ i ] ) {
95     MESSAGE("           argv" << i << " " << _argv[ i ]) ;
96     i++ ;
97   }
98   if ( argc != 4 ) {
99     MESSAGE("SALOME_Container usage : SALOME_Container ServerName -ORBInitRef NameService=corbaname::hostname:tcpipPortNumber") ;
100 //    exit(0) ;
101   }
102
103   SCRUTE(hostname);
104
105   _containerName = BuildContainerNameForNS(containerName,hostname.c_str());
106
107   _orb = CORBA::ORB::_duplicate(orb) ;
108   _poa = PortableServer::POA::_duplicate(poa) ;
109
110   // Pour les containers paralleles: il ne faut pas enregistrer et activer le container generique, mais le container specialise
111   if(activAndRegist){
112     _id = _poa->activate_object(this);
113     _NS = new SALOME_NamingService();//SINGLETON_<SALOME_NamingService>::Instance() ;
114     //ASSERT(SINGLETON_<SALOME_NamingService>::IsAlreadyExisting()) ;
115     _NS->init_orb( CORBA::ORB::_duplicate(_orb) ) ;
116     CORBA::Object_var obj=_poa->id_to_reference(*_id);
117     Engines::Container_var pCont 
118       = Engines::Container::_narrow(obj);
119     SCRUTE(_containerName);
120     _NS->Register(pCont, _containerName.c_str()); 
121   }
122 }
123
124 Engines_Container_i::~Engines_Container_i()
125 {
126   MESSAGE("Container_i::~Container_i()");
127   delete _id;
128 }
129
130 char* Engines_Container_i::name()
131 {
132    return CORBA::string_dup(_containerName.c_str()) ;
133 }
134
135 char* Engines_Container_i::machineName()
136 {
137   string s = GetHostname();
138   MESSAGE("Engines_Container_i::machineName " << s);
139    return CORBA::string_dup(s.c_str()) ;
140 }
141
142 void Engines_Container_i::ping()
143 {
144   MESSAGE("Engines_Container_i::ping() pid "<< getpid());
145 }
146
147 // shutdown corba server
148 void Engines_Container_i::Shutdown()
149 {
150   MESSAGE("Engines_Container_i::Shutdown()");
151   _NS->Destroy_Name(_containerName.c_str());
152   //_remove_ref();
153   //_poa->deactivate_object(*_id);
154   if(_isServantAloneInProcess)
155     _orb->shutdown(0);
156 }
157
158 //! Kill current container
159 bool Engines_Container_i::Kill_impl() {
160   MESSAGE("Engines_Container_i::Kill() pid "<< getpid() << " containerName "
161           << _containerName.c_str() << " machineName "
162           << GetHostname().c_str());
163   exit( 0 ) ;
164 }
165
166 Engines::Component_ptr Engines_Container_i::load_impl( const char* nameToRegister,
167                                                        const char* componentName ) {
168
169   _numInstanceMutex.lock() ; // lock on the instance number
170   BEGIN_OF( "Container_i::load_impl " << componentName ) ;
171   _numInstance++ ;
172   char _aNumI[12];
173   sprintf( _aNumI , "%d" , _numInstance ) ;
174
175   string _impl_name = componentName;
176   string _nameToRegister = nameToRegister;
177   string instanceName = _nameToRegister + "_inst_" + _aNumI ;
178   //SCRUTE(instanceName);
179
180   //string absolute_impl_name = _library_path + "lib" + _impl_name + ".so";
181   string absolute_impl_name( _impl_name ) ;
182   SCRUTE(absolute_impl_name);
183   void* handle;
184   handle = dlopen( absolute_impl_name.c_str() , RTLD_LAZY ) ;
185   if ( !handle ) {
186     INFOS("Can't load shared library : " << absolute_impl_name);
187     INFOS("error dlopen: " << dlerror());
188     _numInstanceMutex.unlock() ;
189     return Engines::Component::_nil() ;
190   }
191   
192   string factory_name = _nameToRegister + string("Engine_factory");
193   //  SCRUTE(factory_name) ;
194
195   typedef  PortableServer::ObjectId * (*FACTORY_FUNCTION)
196                             (CORBA::ORB_ptr,
197                              PortableServer::POA_ptr, 
198                              PortableServer::ObjectId *, 
199                              const char *, 
200                              const char *) ; 
201   FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION) dlsym(handle, factory_name.c_str());
202
203   char *error ;
204   if ( (error = dlerror() ) != NULL) {
205       INFOS("Can't resolve symbol: " + factory_name);
206       SCRUTE(error);
207       _numInstanceMutex.unlock() ;
208       return Engines::Component::_nil() ;
209     }
210
211   string component_registerName = _containerName + "/" + _nameToRegister;
212   Engines::Component_var iobject = Engines::Component::_nil() ;
213   try {
214     CORBA::Object_var obj = _NS->Resolve( component_registerName.c_str() ) ;
215     if ( CORBA::is_nil( obj ) ) {
216 // Instanciate required CORBA object
217       PortableServer::ObjectId * id ;
218       id = (Component_factory) ( _orb, _poa, _id, instanceName.c_str() ,
219                                  _nameToRegister.c_str() ) ;
220   // get reference from id
221       obj = _poa->id_to_reference(*id);
222       iobject = Engines::Component::_narrow( obj ) ;
223
224 //  _numInstanceMutex.lock() ; // lock on the add on handle_map (necessary ?)
225   // register the engine under the name containerName.dir/nameToRegister.object
226       _NS->Register( iobject , component_registerName.c_str() ) ;
227       MESSAGE( "Container_i::load_impl " << component_registerName.c_str() << " bound" ) ;
228     }
229     else { // JR : No ReBind !!!
230       MESSAGE( "Container_i::load_impl " << component_registerName.c_str() << " already bound" ) ;
231       iobject = Engines::Component::_narrow( obj ) ;
232     }
233   }
234   catch (...) {
235     INFOS( "Container_i::load_impl catched" ) ;
236   }
237
238 //Jr  _numInstanceMutex.lock() ; // lock on the add on handle_map (necessary ?)
239   handle_map[instanceName] = handle;
240   END_OF("Container_i::load_impl");
241   _numInstanceMutex.unlock() ;
242   return Engines::Component::_duplicate(iobject);
243 }
244
245 void Engines_Container_i::remove_impl(Engines::Component_ptr component_i)
246 {
247   ASSERT(! CORBA::is_nil(component_i));
248   string instanceName = component_i->instanceName() ;
249   MESSAGE("unload component " << instanceName);
250   component_i->destroy() ;
251   MESSAGE("test key handle_map");
252   _numInstanceMutex.lock() ; // lock on the remove on handle_map
253   if (handle_map[instanceName]) // if key does not exist, created & initialized null
254     {
255       remove_map[instanceName] = handle_map[instanceName] ;
256     }
257   else MESSAGE("pas d'entree handle_map");
258   handle_map.erase(instanceName) ;   
259   _numInstanceMutex.unlock() ;
260   MESSAGE("contenu handle_map");
261   map<string, void *>::iterator im ;
262   for (im = handle_map.begin() ; im != handle_map.end() ; im ++)
263     {
264       MESSAGE("reste " << (*im).first);
265     }
266 }
267
268 void Engines_Container_i::finalize_removal()
269 {
270   MESSAGE("finalize unload : dlclose");
271   map<string, void *>::iterator im ;
272   _numInstanceMutex.lock() ; // lock on the explore remove_map & dlclose
273   for (im = remove_map.begin() ; im != remove_map.end() ; im ++)
274     {
275       void * handle = (*im).second ;
276       dlclose(handle) ;
277       MESSAGE("dlclose " << (*im).first);
278     }
279   remove_map.clear() ;  
280   _numInstanceMutex.unlock() ;
281   MESSAGE("remove_map.clear()");
282 }
283
284 void ActSigIntHandler() {
285   struct sigaction SigIntAct ;
286   SigIntAct.sa_sigaction = &SigIntHandler ;
287   SigIntAct.sa_flags = SA_SIGINFO ;
288 // DEBUG 03.02.2005 : the first parameter of sigaction is not a mask of signals (SIGINT | SIGUSR1) :
289 // it must be only one signal ===> one call for SIGINT and an other one for SIGUSR1
290   if ( sigaction( SIGINT , &SigIntAct, NULL ) ) {
291     perror("SALOME_Container main ") ;
292     exit(0) ;
293   }
294   if ( sigaction( SIGUSR1 , &SigIntAct, NULL ) ) {
295     perror("SALOME_Container main ") ;
296     exit(0) ;
297   }
298   INFOS(pthread_self() << "SigIntHandler activated") ;
299 }
300
301 void SetCpuUsed() ;
302
303 void SigIntHandler(int what , siginfo_t * siginfo ,
304                                         void * toto ) {
305   MESSAGE(pthread_self() << "SigIntHandler what     " << what << endl
306           << "              si_signo " << siginfo->si_signo << endl
307           << "              si_code  " << siginfo->si_code << endl
308           << "              si_pid   " << siginfo->si_pid) ;
309   if ( _Sleeping ) {
310     _Sleeping = false ;
311     MESSAGE("SigIntHandler END sleeping.") ;
312     return ;
313   }
314   else {
315     ActSigIntHandler() ;
316     if ( siginfo->si_signo == SIGUSR1 ) {
317       SetCpuUsed() ;
318     }
319     else {
320       _Sleeping = true ;
321       MESSAGE("SigIntHandler BEGIN sleeping.") ;
322       int count = 0 ;
323       while( _Sleeping ) {
324         sleep( 1 ) ;
325         count += 1 ;
326       }
327       MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
328     }
329     return ;
330   }
331 }
332
333 // Get the PID of the Container
334
335 long Engines_Container_i::getPID() {
336     return (long)getpid();
337 }
338
339 // Get the hostName of the Container
340
341 char* Engines_Container_i::getHostName() {
342     return((char*)(GetHostname().c_str()));
343 }
344
345 // Retrieves only with container naming convention if it is a python container
346 bool Engines_Container_i::isPythonContainer(const char* ContainerName)
347 {
348   bool ret=false;
349   int len=strlen(ContainerName);
350   if(len>=2)
351     if(strcmp(ContainerName+len-2,"Py")==0)
352       ret=true;
353   return ret;
354 }
355
356 string Engines_Container_i::BuildContainerNameForNS(const char *ContainerName, const char *hostname)
357 {
358   string ret="/Containers/";
359   ret += hostname;
360   ret+="/";
361   if (strlen(ContainerName)== 0)
362     ret+=_defaultContainerName;
363   else
364     ret += ContainerName;
365   return ret;
366 }
367
368
369 /*
370  *  Create one instance of componentName component and register it 
371  *  as nameToRegister in naming service
372  */
373 Engines::Component_ptr Engines_Container_i::instance( const char* nameToRegister,
374                                                       const char* componentName ) {
375
376   _numInstanceMutex.lock() ; // lock on the instance number
377   BEGIN_OF( "Container_i::instance " << componentName ) ;
378
379   string _nameToRegister = nameToRegister;
380   string component_registerName = _containerName + "/" + _nameToRegister;
381   
382   Engines::Component_var iobject = Engines::Component::_nil() ;
383   
384   try {
385     CORBA::Object_var obj = _NS->Resolve( component_registerName.c_str() ) ;
386     if (! CORBA::is_nil( obj ) ) {
387       MESSAGE( "Container_i::instance " << component_registerName.c_str() << " already registered" ) ;
388       iobject = Engines::Component::_narrow( obj ) ;
389     }
390     else{
391       string _compo_name = componentName;
392       string _impl_name = "lib" + _compo_name + "Engine.so";
393       SCRUTE(_impl_name);
394       
395       void* handle;
396       handle = dlopen( _impl_name.c_str() , RTLD_LAZY ) ;
397       
398       if ( handle ) {
399          string factory_name = _compo_name + "Engine_factory";
400          SCRUTE(factory_name) ;
401
402          typedef  PortableServer::ObjectId * (*FACTORY_FUNCTION)
403                                    (CORBA::ORB_ptr,
404                                     PortableServer::POA_ptr, 
405                                     PortableServer::ObjectId *, 
406                                     const char *, 
407                                     const char *) ; 
408          FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION) dlsym(handle, factory_name.c_str());
409
410          char *error ;
411          if ( (error = dlerror() ) == NULL) {
412              // Instanciate required CORBA object
413              _numInstance++ ;
414              char _aNumI[12];
415              sprintf( _aNumI , "%d" , _numInstance ) ;
416              string instanceName = _compo_name + "_inst_" + _aNumI ;
417              SCRUTE(instanceName);
418
419              PortableServer::ObjectId * id ;
420              id = (Component_factory) ( _orb, _poa, _id, instanceName.c_str() ,
421                                  _nameToRegister.c_str() ) ;
422              // get reference from id
423              obj = _poa->id_to_reference(*id);
424              iobject = Engines::Component::_narrow( obj ) ;
425
426              // register the engine under the name containerName.dir/nameToRegister.object
427              _NS->Register( iobject , component_registerName.c_str() ) ;
428              MESSAGE( "Container_i::instance " << component_registerName.c_str() << " registered" ) ;
429              handle_map[instanceName] = handle;
430          }
431          else{
432              INFOS("Can't resolve symbol: " + factory_name);
433              SCRUTE(error);
434          }  
435       }
436       else{
437         INFOS("Can't load shared library : " << _impl_name);
438         INFOS("error dlopen: " << dlerror());
439       }      
440     }
441   }
442   catch (...) {
443     INFOS( "Container_i::instance exception caught" ) ;
444   }
445   END_OF("Container_i::instance");
446   _numInstanceMutex.unlock() ;
447   return Engines::Component::_duplicate(iobject);
448 }
449