Salome HOME
PR: merge from branch BR_auto_V310 tag mergefrom_OCC_development_for_3_2_0a2_10mar06
[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 //#define private public
30 #include <string.h>
31 #include <stdio.h>
32 #include <time.h>
33 #include <sys/time.h>
34 #ifndef WNT
35 #include <dlfcn.h>
36 #include <unistd.h>
37 #else
38 #include "../../adm/win32/SALOME_WNT.hxx"
39 #include <signal.h>
40 #include <process.h>
41 int SIGUSR1 = 1000;
42 #endif
43
44 #include "utilities.h"
45 #include <SALOMEconfig.h>
46 #ifndef WNT
47 #include CORBA_SERVER_HEADER(SALOME_Component)
48 #else
49 #include <SALOME_Component.hh>
50 #endif
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"
55 #include "OpUtil.hxx"
56
57 #include <Python.h>
58 #include "Container_init_python.hxx"
59
60 using namespace std;
61
62 bool _Sleeping = false ;
63
64 // // Needed by multi-threaded Python --- Supervision
65 int _ArgC ;
66 char ** _ArgV ;
67
68
69 // Containers with name FactoryServer are started via rsh in LifeCycleCORBA
70 // Other Containers are started via start_impl of FactoryServer
71
72 extern "C" {void ActSigIntHandler() ; }
73 #ifndef WNT
74 extern "C" {void SigIntHandler(int, siginfo_t *, void *) ; }
75 #else
76   extern "C" {void SigIntHandler( int ) ; }
77 #endif
78
79
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 ;
84
85 //=============================================================================
86 /*! 
87  *  Default constructor, not for use
88  */
89 //=============================================================================
90
91 Engines_Container_i::Engines_Container_i () :
92   _numInstance(0)
93 {
94 }
95
96 //=============================================================================
97 /*! 
98  *  Construtor to use
99  */
100 //=============================================================================
101
102 Engines_Container_i::Engines_Container_i (CORBA::ORB_ptr orb, 
103                                           PortableServer::POA_var poa,
104                                           char *containerName ,
105                                           int argc , char* argv[],
106                                           bool activAndRegist,
107                                           bool isServantAloneInProcess
108                                           ) :
109   _numInstance(0),_isServantAloneInProcess(isServantAloneInProcess)
110 {
111   _pid = (long)getpid();
112
113   if(activAndRegist)
114     ActSigIntHandler() ;
115
116   _argc = argc ;
117   _argv = argv ;
118
119   string hostname = GetHostname();
120   MESSAGE(hostname << " " << getpid() << " Engines_Container_i starting argc "
121           << _argc << " Thread " << pthread_self() ) ;
122
123   int i = 0 ;
124   while ( _argv[ i ] )
125     {
126       MESSAGE("           argv" << i << " " << _argv[ i ]) ;
127       i++ ;
128     }
129
130   if ( argc < 2 )
131     {
132       INFOS("SALOME_Container usage : SALOME_Container ServerName");
133       ASSERT(0) ;
134     }
135   SCRUTE(argv[1]);
136   _isSupervContainer = false;
137   if (strcmp(argv[1],"SuperVisionContainer") == 0) _isSupervContainer = true;
138
139   if (_isSupervContainer)
140     {
141       _ArgC = argc ;
142       _ArgV = argv ;
143     }
144
145   _orb = CORBA::ORB::_duplicate(orb) ;
146   _poa = PortableServer::POA::_duplicate(poa) ;
147   
148   // Pour les containers paralleles: il ne faut pas enregistrer et activer
149   // le container generique, mais le container specialise
150
151   if(activAndRegist)
152     {
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);
159
160       _containerName = _NS->BuildContainerNameForNS(containerName,
161                                                     hostname.c_str());
162       SCRUTE(_containerName);
163       _NS->Register(pCont, _containerName.c_str());
164       MESSAGE("Engines_Container_i::Engines_Container_i : Container name "
165               << _containerName);
166
167       // Python: 
168       // import SALOME_Container
169       // pycont = SALOME_Container.SALOME_Container_i(containerIORStr)
170     
171       CORBA::String_var sior =  _orb->object_to_string(pCont);
172       string myCommand="pyCont = SALOME_Container.SALOME_Container_i('";
173       myCommand += _containerName + "','";
174       myCommand += sior;
175       myCommand += "')\n";
176       SCRUTE(myCommand);
177
178       if (!_isSupervContainer)
179         {
180           Py_ACQUIRE_NEW_THREAD;
181 #ifdef WNT
182           // mpv: this is temporary solution: there is a unregular crash if not
183           Sleep(2000);
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");
187 #endif
188           PyRun_SimpleString("import SALOME_Container\n");
189           PyRun_SimpleString((char*)myCommand.c_str());
190           Py_RELEASE_NEW_THREAD;
191         }
192     }
193 }
194
195 //=============================================================================
196 /*! 
197  *  Destructor
198  */
199 //=============================================================================
200
201 Engines_Container_i::~Engines_Container_i()
202 {
203   MESSAGE("Container_i::~Container_i()");
204   delete _id;
205 }
206
207 //=============================================================================
208 /*! 
209  *  CORBA attribute: Container name (see constructor)
210  */
211 //=============================================================================
212
213 char* Engines_Container_i::name()
214 {
215    return CORBA::string_dup(_containerName.c_str()) ;
216 }
217
218 //=============================================================================
219 /*! 
220  *  CORBA method: Get the hostName of the Container (without domain extensions)
221  */
222 //=============================================================================
223
224 char* Engines_Container_i::getHostName()
225 {
226   string s = GetHostname();
227   //  MESSAGE("Engines_Container_i::getHostName " << s);
228   return CORBA::string_dup(s.c_str()) ;
229 }
230
231 //=============================================================================
232 /*! 
233  *  CORBA method: Get the PID (process identification) of the Container
234  */
235 //=============================================================================
236
237 CORBA::Long Engines_Container_i::getPID()
238 {
239   return (CORBA::Long)getpid();
240 }
241
242 //=============================================================================
243 /*! 
244  *  CORBA method: check if servant is still alive
245  */
246 //=============================================================================
247
248 void Engines_Container_i::ping()
249 {
250   MESSAGE("Engines_Container_i::ping() pid "<< getpid());
251 }
252
253 //=============================================================================
254 /*! 
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 
259  */
260 //=============================================================================
261
262 void Engines_Container_i::Shutdown()
263 {
264   MESSAGE("Engines_Container_i::Shutdown()");
265   _NS->Destroy_FullDirectory(_containerName.c_str());
266   //_remove_ref();
267   //_poa->deactivate_object(*_id);
268   if(_isServantAloneInProcess)
269     {
270       MESSAGE("Effective Shutdown of container Begins...");
271       LocalTraceBufferPool* bp1 = LocalTraceBufferPool::instance();
272       bp1->deleteInstance(bp1);
273       _orb->shutdown(0);
274     }
275 }
276
277
278 //=============================================================================
279 /*! 
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
285  */
286 //=============================================================================
287
288 bool
289 Engines_Container_i::load_component_Library(const char* componentName)
290 {
291
292   string aCompName = componentName;
293
294   // --- try dlopen C++ component
295
296 #ifndef WNT
297   string impl_name = string ("lib") + aCompName + string("Engine.so");
298 #else
299   string impl_name = aCompName + string("Engine.dll");
300 #endif
301   SCRUTE(impl_name);
302   
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])
307     {
308       MESSAGE("Library " << impl_name << " already loaded");
309       _numInstanceMutex.unlock();
310       return true;
311     }
312   
313   void* handle;
314 #if defined( WNT )
315   handle = dlopen( impl_name.c_str() , 0 ) ;
316 //#elif defined( __osf1__ )
317 //  handle = dlopen( impl_name.c_str() , RTLD_NOW ) ;
318 #else
319   handle = dlopen( impl_name.c_str() , RTLD_LAZY ) ;
320 #endif
321   if ( handle )
322     {
323       _library_map[impl_name] = handle;
324       _numInstanceMutex.unlock();
325       return true;
326     }
327   else
328     {
329       INFOS("Can't load shared library : " << impl_name);
330       INFOS("error dlopen: " << dlerror());
331     }
332   _numInstanceMutex.unlock();
333
334   // --- try import Python component
335
336   INFOS("try import Python component "<<componentName);
337   if (_isSupervContainer)
338     {
339       INFOS("Supervision Container does not support Python Component Engines");
340       return false;
341     }
342   if (_library_map[aCompName])
343     {
344       return true; // Python Component, already imported
345     }
346   else
347     {
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,
353                                              "import_component",
354                                              "s",componentName);
355       int ret= PyInt_AsLong(result);
356       SCRUTE(ret);
357       Py_RELEASE_NEW_THREAD;
358   
359       if (ret) // import possible: Python component
360         {
361           _library_map[aCompName] = (void *)pyCont; // any non O value OK
362           MESSAGE("import Python: "<<aCompName<<" OK");
363           return true;
364         }
365     }
366   return false;
367 }
368
369 //=============================================================================
370 /*! 
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
378  */
379 //=============================================================================
380
381 Engines::Component_ptr
382 Engines_Container_i::create_component_instance(const char*genericRegisterName,
383                                                CORBA::Long studyId)
384 {
385   if (studyId < 0)
386     {
387       INFOS("studyId must be > 0 for mono study instance, =0 for multiStudy");
388       return Engines::Component::_nil() ;
389     }
390
391   Engines::Component_var iobject = Engines::Component::_nil() ;
392
393   string aCompName = genericRegisterName;
394   if (_library_map[aCompName]) // Python component
395     {
396       if (_isSupervContainer)
397         {
398           INFOS("Supervision Container does not support Python Component Engines");
399           return Engines::Component::_nil();
400         }
401       _numInstanceMutex.lock() ; // lock on the instance number
402       _numInstance++ ;
403       int numInstance = _numInstance ;
404       _numInstanceMutex.unlock() ;
405
406       char aNumI[12];
407       sprintf( aNumI , "%d" , numInstance ) ;
408       string instanceName = aCompName + "_inst_" + aNumI ;
409       string component_registerName =
410         _containerName + "/" + instanceName;
411
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",
418                                              "ssl",
419                                              aCompName.c_str(),
420                                              instanceName.c_str(),
421                                              studyId);
422       string iors = PyString_AsString(result);
423       SCRUTE(iors);
424       Py_RELEASE_NEW_THREAD;
425   
426       if( iors!="" )
427       {
428         CORBA::Object_var obj = _orb->string_to_object(iors.c_str());
429         iobject = Engines::Component::_narrow( obj ) ;
430       }
431       return iobject._retn();
432     }
433   
434   //--- try C++
435
436 #ifndef WNT
437   string impl_name = string ("lib") + genericRegisterName +string("Engine.so");
438 #else
439   string impl_name = genericRegisterName +string("Engine.dll");
440 #endif
441   void* handle = _library_map[impl_name];
442   if ( !handle )
443     {
444       INFOS("shared library " << impl_name <<"must be loaded before instance");
445       return Engines::Component::_nil() ;
446     }
447   else
448     {
449       iobject = createInstance(genericRegisterName,
450                                handle,
451                                studyId);
452       return iobject._retn();
453     }
454 }
455
456 //=============================================================================
457 /*! 
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
464  */
465 //=============================================================================
466
467 Engines::Component_ptr
468 Engines_Container_i::find_component_instance( const char* registeredName,
469                                               CORBA::Long studyId)
470 {
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())
474     {
475       string instance = (*itm).first;
476       SCRUTE(instance);
477       if (instance.find(registeredName) == 0)
478         {
479           anEngine = (*itm).second;
480           if (studyId == anEngine->getStudyId())
481             {
482               return anEngine._retn();
483             }
484         }
485       itm++;
486     }
487   return anEngine._retn();  
488 }
489
490 //=============================================================================
491 /*! 
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
501  */
502 //=============================================================================
503
504 Engines::Component_ptr
505 Engines_Container_i::load_impl( const char* genericRegisterName,
506                                 const char* componentName )
507 {
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();
513 }
514     
515
516 //=============================================================================
517 /*! 
518  *  CORBA method: Stops the component servant, and deletes all related objects
519  *  \param component_i     Component to be removed
520  */
521 //=============================================================================
522
523 void Engines_Container_i::remove_impl(Engines::Component_ptr component_i)
524 {
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());
531 }
532
533 //=============================================================================
534 /*! 
535  *  CORBA method: Discharges unused libraries from the container.
536  */
537 //=============================================================================
538
539 void Engines_Container_i::finalize_removal()
540 {
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++)
546     {
547       void *handle = (*ith).second;
548       string impl_name= (*ith).first;
549       if (handle)
550         {
551           SCRUTE(handle);
552           SCRUTE(impl_name);
553 //        dlclose(handle);                // SALOME unstable after ...
554 //        _library_map.erase(impl_name);
555         }
556     }
557   _toRemove_map.clear();
558   _numInstanceMutex.unlock();
559 }
560
561 //=============================================================================
562 /*! 
563  *  CORBA method: Kill the container process with exit(0).
564  *  To remove :  never returns !
565  */
566 //=============================================================================
567
568 bool Engines_Container_i::Kill_impl()
569 {
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("===============================================================");
576   //exit( 0 ) ;
577   ASSERT(0);
578   return false;
579 }
580
581 //=============================================================================
582 /*! 
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
591  * 
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
598  *
599  *  instanceName = COMPONENT_inst_1
600  *  component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
601  */
602 //=============================================================================
603
604 Engines::Component_ptr
605 Engines_Container_i::find_or_create_instance(string genericRegisterName,
606                                              string componentLibraryName)
607 {
608   string aGenRegisterName = genericRegisterName;
609   string impl_name = componentLibraryName;
610   void* handle = _library_map[impl_name];
611   if ( !handle )
612     {
613       INFOS("shared library " << impl_name <<"must be loaded before instance");
614       return Engines::Component::_nil() ;
615     }
616   else
617     {
618       // --- find a registered instance in naming service, or create
619
620       string component_registerBase =
621         _containerName + "/" + aGenRegisterName;
622       Engines::Component_var iobject = Engines::Component::_nil() ;
623       try
624         {
625           CORBA::Object_var obj =
626             _NS->ResolveFirst( component_registerBase.c_str());
627           if ( CORBA::is_nil( obj ) )
628             {
629               iobject = createInstance(genericRegisterName,
630                                        handle,
631                                        0); // force multiStudy instance here !
632             }
633           else
634             { 
635               iobject = Engines::Component::_narrow( obj ) ;
636               Engines_Component_i *servant =
637                 dynamic_cast<Engines_Component_i*>
638                 (_poa->reference_to_servant(iobject));
639               ASSERT(servant)
640               int studyId = servant->getStudyId();
641               ASSERT (studyId >= 0);
642               if (studyId == 0) // multiStudy instance, OK
643                 {
644                   // No ReBind !
645                   MESSAGE(component_registerBase.c_str()<<" already bound");
646                 }
647               else // monoStudy instance: NOK
648                 {
649                   iobject = Engines::Component::_nil();
650                   INFOS("load_impl & find_component_instance methods "
651                         << "NOT SUITABLE for mono study components");
652                 }
653             }
654         }
655       catch (...)
656         {
657           INFOS( "Container_i::load_impl catched" ) ;
658         }
659       return iobject._retn();
660     }
661 }
662
663 //=============================================================================
664 /*! 
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
673  * 
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
681  */
682 //=============================================================================
683
684 Engines::Component_ptr
685 Engines_Container_i::createInstance(string genericRegisterName,
686                                     void *handle,
687                                     int studyId)
688 {
689   // --- find the factory
690
691   string aGenRegisterName = genericRegisterName;
692   string factory_name = aGenRegisterName + string("Engine_factory");
693   SCRUTE(factory_name) ;
694
695   typedef  PortableServer::ObjectId * (*FACTORY_FUNCTION)
696     (CORBA::ORB_ptr,
697      PortableServer::POA_ptr, 
698      PortableServer::ObjectId *, 
699      const char *, 
700      const char *) ;
701
702   FACTORY_FUNCTION Component_factory
703     = (FACTORY_FUNCTION) dlsym(handle, factory_name.c_str());
704
705   char *error ;
706   if ( (error = dlerror() ) != NULL)
707     {
708       INFOS("Can't resolve symbol: " + factory_name);
709       SCRUTE(error);
710       return Engines::Component::_nil() ;
711     }
712
713   // --- create instance
714
715   Engines::Component_var iobject = Engines::Component::_nil() ;
716
717   try
718     {
719       _numInstanceMutex.lock() ; // lock on the instance number
720       _numInstance++ ;
721       int numInstance = _numInstance ;
722       _numInstanceMutex.unlock() ;
723
724       char aNumI[12];
725       sprintf( aNumI , "%d" , numInstance ) ;
726       string instanceName = aGenRegisterName + "_inst_" + aNumI ;
727       string component_registerName =
728         _containerName + "/" + instanceName;
729
730       // --- Instanciate required CORBA object
731
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() ) ;
735
736       // --- get reference & servant from id
737
738       CORBA::Object_var obj = _poa->id_to_reference(*id);
739       iobject = Engines::Component::_narrow( obj ) ;
740
741       Engines_Component_i *servant =
742         dynamic_cast<Engines_Component_i*>(_poa->reference_to_servant(iobject));
743       ASSERT(servant);
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);
753       ASSERT(ret_studyId);
754
755       // --- register the engine under the name
756       //     containerName(.dir)/instanceName(.object)
757
758       _NS->Register( iobject , component_registerName.c_str() ) ;
759       MESSAGE( component_registerName.c_str() << " bound" ) ;
760     }
761   catch (...)
762     {
763       INFOS( "Container_i::createInstance exception catched" ) ;
764     }
765   return iobject._retn();
766 }
767
768 //=============================================================================
769 /*! 
770  *
771  */
772 //=============================================================================
773
774 void Engines_Container_i::decInstanceCnt(string genericRegisterName)
775 {
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)
784     {
785       string impl_name =
786         Engines_Component_i::GetDynLibraryName(aGenRegisterName.c_str());
787       SCRUTE(impl_name);
788       void* handle = _library_map[impl_name];
789       ASSERT(handle);
790       _toRemove_map[impl_name] = handle;
791     }
792   _numInstanceMutex.unlock();
793 }
794
795 //=============================================================================
796 /*! 
797  *  Retrieves only with container naming convention if it is a python container
798  */
799 //=============================================================================
800
801 bool Engines_Container_i::isPythonContainer(const char* ContainerName)
802 {
803   bool ret=false;
804   int len=strlen(ContainerName);
805   if(len>=2)
806     if(strcmp(ContainerName+len-2,"Py")==0)
807       ret=true;
808   return ret;
809 }
810
811 //=============================================================================
812 /*! 
813  *  
814  */
815 //=============================================================================
816
817 void ActSigIntHandler()
818 {
819 #ifndef WNT
820   struct sigaction SigIntAct ;
821   SigIntAct.sa_sigaction = &SigIntHandler ;
822   SigIntAct.sa_flags = SA_SIGINFO ;
823 #endif
824
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
829
830 #ifndef WNT
831   if ( sigaction( SIGINT , &SigIntAct, NULL ) ) 
832     {
833       perror("SALOME_Container main ") ;
834       exit(0) ;
835     }
836   if ( sigaction( SIGUSR1 , &SigIntAct, NULL ) )
837     {
838       perror("SALOME_Container main ") ;
839       exit(0) ;
840     }
841
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") ;
849
850 #else  
851   signal( SIGINT, SigIntHandler );
852   signal( SIGUSR1, SigIntHandler );
853 #endif
854
855 }
856
857 void SetCpuUsed() ;
858
859 #ifndef WNT
860 void SigIntHandler(int what ,
861                    siginfo_t * siginfo ,
862                    void * toto ) 
863 {
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) ;
874
875   if ( _Sleeping )
876     {
877       _Sleeping = false ;
878       //     MESSAGE("SigIntHandler END sleeping.") ;
879       return ;
880     }
881   else
882     {
883       ActSigIntHandler() ;
884       if ( siginfo->si_signo == SIGUSR1 )
885         {
886           SetCpuUsed() ;
887         }
888       else 
889         {
890           _Sleeping = true ;
891           //      MESSAGE("SigIntHandler BEGIN sleeping.") ;
892           int count = 0 ;
893           while( _Sleeping )
894             {
895               sleep( 1 ) ;
896               count += 1 ;
897             }
898           //      MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
899         }
900       return ;
901     }
902 }
903 #else // Case WNT
904 void SigIntHandler( int what )
905 {
906   MESSAGE( pthread_self() << "SigIntHandler what     " << what << endl );
907   if ( _Sleeping )
908     {
909       _Sleeping = false ;
910       MESSAGE("SigIntHandler END sleeping.") ;
911       return ;
912     }
913   else
914     {
915       ActSigIntHandler() ;
916       if ( what == SIGUSR1 )
917         {
918           SetCpuUsed() ;
919         }
920       else
921         {
922           _Sleeping = true ;
923           MESSAGE("SigIntHandler BEGIN sleeping.") ;
924           int count = 0 ;
925           while( _Sleeping ) 
926             {
927               Sleep( 1000 ) ;
928               count += 1 ;
929             }
930           MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
931         }
932       return ;
933     }
934 }
935 #endif
936