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