Salome HOME
ca47f23d9da2532f8aa3c385cf20e820ec7a2e30
[modules/yacs.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     //   _NS = new SALOME_NamingService(_orb);
124     _NS = SINGLETON_<SALOME_NamingService>::Instance() ;
125     ASSERT(SINGLETON_<SALOME_NamingService>::IsAlreadyExisting()) ;
126     _NS->init_orb( orb ) ;
127
128     Engines::Container_ptr pCont 
129       = Engines::Container::_narrow(_this());
130     SCRUTE(_containerName);
131     _NS->Register(pCont, _containerName.c_str()); 
132   }
133 }
134
135 Engines_Container_i::~Engines_Container_i()
136 {
137   MESSAGE("Container_i::~Container_i()");
138 }
139
140 char* Engines_Container_i::name()
141 {
142    return CORBA::string_dup(_containerName.c_str()) ;
143 }
144
145 char* Engines_Container_i::machineName()
146 {
147   string s = GetHostname();
148   MESSAGE("Engines_Container_i::machineName " << s);
149    return CORBA::string_dup(s.c_str()) ;
150 }
151
152 void Engines_Container_i::ping()
153 {
154   MESSAGE("Engines_Container_i::ping() pid "<< getpid());
155 }
156
157 //! Kill current container
158 bool Engines_Container_i::Kill_impl() {
159   MESSAGE("Engines_Container_i::Kill() pid "<< getpid() << " containerName "
160           << _containerName.c_str() << " machineName "
161           << GetHostname().c_str());
162   exit( 0 ) ;
163 }
164
165 //! Launch a new container from the current container
166 Engines::Container_ptr Engines_Container_i::start_impl(
167                                       const char* ContainerName ) {
168   MESSAGE("start_impl argc " << _argc << " ContainerName " << ContainerName
169           << hex << this << dec) ;
170   _numInstanceMutex.lock() ; // lock on the instance number
171
172   CORBA::Object_var obj = Engines::Container::_nil() ;
173   bool nilvar = true ;
174   try {
175     string cont("/Containers/");
176     cont += machineName() ;
177     cont += "/" ;
178     cont += ContainerName;
179     INFOS(machineName() << " start_impl unknown container " << cont.c_str()
180           << " try to Resolve" );
181     obj = _NS->Resolve( cont.c_str() );
182     nilvar = CORBA::is_nil( obj ) ;
183     if ( nilvar ) {
184       INFOS(machineName() << " start_impl unknown container "
185             << ContainerName);
186     }
187   }
188   catch (ServiceUnreachable&) {
189     INFOS(machineName() << "Caught exception: Naming Service Unreachable");
190   }
191   catch (...) {
192     INFOS(machineName() << "Caught unknown exception.");
193   }
194   if ( !nilvar ) {
195     _numInstanceMutex.unlock() ;
196     MESSAGE("start_impl container found without new launch") ;
197     return Engines::Container::_narrow(obj);
198   }
199   int i = 0 ;
200   while ( _argv[ i ] ) {
201     MESSAGE("           argv" << i << " " << _argv[ i ]) ;
202     i++ ;
203   }
204   string shstr = string(getenv("KERNEL_ROOT_DIR")) + "/bin/salome/SALOME_Container ";
205 //   string shstr( "./runSession SALOME_Container " ) ;
206   shstr += ContainerName ;
207   if ( _argc == 4 ) {
208     shstr += " " ;
209     shstr += _argv[ 2 ] ;
210     shstr += " " ;
211     shstr += _argv[ 3 ] ;
212   }
213   shstr += " > /tmp/" ;
214   shstr += ContainerName ;
215   shstr += ".log 2>&1 &" ;
216   MESSAGE("system(" << shstr << ")") ;
217   int status = system( shstr.c_str() ) ;
218   if (status == -1) {
219     INFOS("Engines_Container_i::start_impl SALOME_Container failed (system command status -1)") ;
220   }
221   else if (status == 217) {
222     INFOS("Engines_Container_i::start_impl SALOME_Container failed (system command status 217)") ;
223   }
224   INFOS(machineName() << " Engines_Container_i::start_impl SALOME_Container launch done");
225
226 //   pid_t pid = fork() ;
227 //   if ( pid == 0 ) {
228 //     string anExe( _argv[ 0 ] ) ;
229 //     anExe += "runSession" ;
230 //     char * args[ 6 ] ;
231 //     args[ 0 ] = "runSession" ;
232 //     args[ 1 ] = "SALOME_Container" ;
233 //     args[ 2 ] = strdup( ContainerName ) ;
234 //     args[ 3 ] = strdup( _argv[ 2 ] ) ;
235 //     args[ 4 ] = strdup( _argv[ 3 ] ) ;
236 //     args[ 5 ] = NULL ;
237 //     MESSAGE("execl(" << anExe.c_str() << " , " << args[ 0 ] << " , "
238 //                      << args[ 1 ] << " , " << args[ 2 ] << " , " << args[ 3 ]
239 //                      << " , " << args[ 4 ] << ")") ;
240 //     int status = execv( anExe.c_str() , args ) ;
241 //     if (status == -1) {
242 //       INFOS("Engines_Container_i::start_impl execl failed (system command status -1)") ;
243 //       perror( "Engines_Container_i::start_impl execl error ") ;
244 //     }
245 //     else {
246 //       INFOS(machineName() << " Engines_Container_i::start_impl execl done");
247 //     }
248 //     exit(0) ;
249 //   }
250
251   obj = Engines::Container::_nil() ;
252   try {
253     string cont("/Containers/");
254     cont += machineName() ;
255     cont += "/" ;
256     cont += ContainerName;
257     nilvar = true ;
258     int count = 20 ;
259     while ( nilvar && count >= 0) {
260       sleep( 1 ) ;
261       obj = _NS->Resolve(cont.c_str());
262       nilvar = CORBA::is_nil( obj ) ;
263       if ( nilvar ) {
264         INFOS(count << ". " << machineName()
265               << " start_impl unknown container " << cont.c_str());
266         count -= 1 ;
267       }
268     }
269     _numInstanceMutex.unlock() ;
270     if ( !nilvar ) {
271       MESSAGE("start_impl container found after new launch of SALOME_Container") ;
272     }
273     return Engines::Container::_narrow(obj);
274   }
275   catch (ServiceUnreachable&) {
276     INFOS(machineName() << "Caught exception: Naming Service Unreachable");
277   }
278   catch (...) {
279     INFOS(machineName() << "Caught unknown exception.");
280   }
281   _numInstanceMutex.unlock() ;
282   MESSAGE("start_impl container not found after new launch of SALOME_Container") ;
283   return Engines::Container::_nil() ;
284 }
285
286 Engines::Component_ptr Engines_Container_i::load_impl( const char* nameToRegister,
287                                                        const char* componentName ) {
288
289   _numInstanceMutex.lock() ; // lock on the instance number
290   BEGIN_OF( "Container_i::load_impl " << componentName ) ;
291   _numInstance++ ;
292   char _aNumI[12];
293   sprintf( _aNumI , "%d" , _numInstance ) ;
294
295   string _impl_name = componentName;
296   string _nameToRegister = nameToRegister;
297   string instanceName = _nameToRegister + "_inst_" + _aNumI ;
298   //SCRUTE(instanceName);
299
300   //string absolute_impl_name = _library_path + "lib" + _impl_name + ".so";
301   string absolute_impl_name( _impl_name ) ;
302   SCRUTE(absolute_impl_name);
303   void* handle;
304   handle = dlopen( absolute_impl_name.c_str() , RTLD_LAZY ) ;
305   if ( !handle ) {
306     INFOS("Can't load shared library : " << absolute_impl_name);
307     INFOS("error dlopen: " << dlerror());
308     _numInstanceMutex.unlock() ;
309     return Engines::Component::_nil() ;
310   }
311   
312   string factory_name = _nameToRegister + string("Engine_factory");
313   //  SCRUTE(factory_name) ;
314
315   typedef  PortableServer::ObjectId * (*FACTORY_FUNCTION)
316                             (CORBA::ORB_ptr,
317                              PortableServer::POA_ptr, 
318                              PortableServer::ObjectId *, 
319                              const char *, 
320                              const char *) ; 
321   FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION) dlsym(handle, factory_name.c_str());
322
323   char *error ;
324   if ( (error = dlerror() ) != NULL) {
325       INFOS("Can't resolve symbol: " + factory_name);
326       SCRUTE(error);
327       _numInstanceMutex.unlock() ;
328       return Engines::Component::_nil() ;
329     }
330
331   string component_registerName = _containerName + "/" + _nameToRegister;
332   Engines::Component_var iobject = Engines::Component::_nil() ;
333   try {
334     CORBA::Object_var obj = _NS->Resolve( component_registerName.c_str() ) ;
335     if ( CORBA::is_nil( obj ) ) {
336 // Instanciate required CORBA object
337       PortableServer::ObjectId * id ;
338       id = (Component_factory) ( _orb, _poa, _id, instanceName.c_str() ,
339                                  _nameToRegister.c_str() ) ;
340   // get reference from id
341       obj = _poa->id_to_reference(*id);
342       iobject = Engines::Component::_narrow( obj ) ;
343
344 //  _numInstanceMutex.lock() ; // lock on the add on handle_map (necessary ?)
345   // register the engine under the name containerName.dir/nameToRegister.object
346       _NS->Register( iobject , component_registerName.c_str() ) ;
347       MESSAGE( "Container_i::load_impl " << component_registerName.c_str() << " bound" ) ;
348     }
349     else { // JR : No ReBind !!!
350       MESSAGE( "Container_i::load_impl " << component_registerName.c_str() << " already bound" ) ;
351       iobject = Engines::Component::_narrow( obj ) ;
352     }
353   }
354   catch (...) {
355     INFOS( "Container_i::load_impl catched" ) ;
356   }
357
358 //Jr  _numInstanceMutex.lock() ; // lock on the add on handle_map (necessary ?)
359   handle_map[instanceName] = handle;
360   END_OF("Container_i::load_impl");
361   _numInstanceMutex.unlock() ;
362   return Engines::Component::_duplicate(iobject);
363 }
364
365 void Engines_Container_i::remove_impl(Engines::Component_ptr component_i)
366 {
367   ASSERT(! CORBA::is_nil(component_i));
368   string instanceName = component_i->instanceName() ;
369   MESSAGE("unload component " << instanceName);
370   component_i->destroy() ;
371   MESSAGE("test key handle_map");
372   _numInstanceMutex.lock() ; // lock on the remove on handle_map
373   if (handle_map[instanceName]) // if key does not exist, created & initialized null
374     {
375       remove_map[instanceName] = handle_map[instanceName] ;
376     }
377   else MESSAGE("pas d'entree handle_map");
378   handle_map.erase(instanceName) ;   
379   _numInstanceMutex.unlock() ;
380   MESSAGE("contenu handle_map");
381   map<string, void *>::iterator im ;
382   for (im = handle_map.begin() ; im != handle_map.end() ; im ++)
383     {
384       MESSAGE("reste " << (*im).first);
385     }
386 }
387
388 void Engines_Container_i::finalize_removal()
389 {
390   MESSAGE("finalize unload : dlclose");
391   map<string, void *>::iterator im ;
392   _numInstanceMutex.lock() ; // lock on the explore remove_map & dlclose
393   for (im = remove_map.begin() ; im != remove_map.end() ; im ++)
394     {
395       void * handle = (*im).second ;
396       dlclose(handle) ;
397       MESSAGE("dlclose " << (*im).first);
398     }
399   remove_map.clear() ;  
400   _numInstanceMutex.unlock() ;
401   MESSAGE("remove_map.clear()");
402 }
403
404 void ActSigIntHandler() {
405   struct sigaction SigIntAct ;
406   SigIntAct.sa_sigaction = &SigIntHandler ;
407   SigIntAct.sa_flags = SA_SIGINFO ;
408   if ( sigaction( SIGINT | SIGUSR1 , &SigIntAct, NULL ) ) {
409     perror("SALOME_Container main ") ;
410     exit(0) ;
411   }
412   else {
413     INFOS(pthread_self() << "SigIntHandler activated") ;
414   }
415 }
416
417 void SetCpuUsed() ;
418
419 void SigIntHandler(int what , siginfo_t * siginfo ,
420                                         void * toto ) {
421   MESSAGE(pthread_self() << "SigIntHandler what     " << what << endl
422           << "              si_signo " << siginfo->si_signo << endl
423           << "              si_code  " << siginfo->si_code << endl
424           << "              si_pid   " << siginfo->si_pid) ;
425   if ( _Sleeping ) {
426     _Sleeping = false ;
427     MESSAGE("SigIntHandler END sleeping.") ;
428     return ;
429   }
430   else {
431     ActSigIntHandler() ;
432     if ( siginfo->si_signo == SIGUSR1 ) {
433       SetCpuUsed() ;
434     }
435     else {
436       _Sleeping = true ;
437       MESSAGE("SigIntHandler BEGIN sleeping.") ;
438       int count = 0 ;
439       while( _Sleeping ) {
440         sleep( 1 ) ;
441         count += 1 ;
442       }
443       MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
444     }
445     return ;
446   }
447 }
448
449 // Get the PID of the Container
450
451 CORBA::Long Engines_Container_i::getPID() {
452     return (long)getpid();
453 }
454
455 // Get the hostName of the Container
456
457 char* Engines_Container_i::getHostName() {
458     return((char*)(GetHostname().c_str()));
459 }