Salome HOME
PR: from Sergey Mozokhin, Supervisor problem, crash after killing a dataflow execution.
[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.salome-platform.org/ or email : webmaster.salome@opencascade.com
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_FileRef_i.hxx"
55 #include "SALOME_FileTransfer_i.hxx"
56 #include "SALOME_NamingService.hxx"
57 #include "OpUtil.hxx"
58
59 #include <Python.h>
60 #include "Container_init_python.hxx"
61
62 using namespace std;
63
64 bool _Sleeping = false ;
65
66 // // Needed by multi-threaded Python --- Supervision
67 int _ArgC ;
68 char ** _ArgV ;
69
70
71 // Containers with name FactoryServer are started via rsh in LifeCycleCORBA
72 // Other Containers are started via start_impl of FactoryServer
73
74 extern "C" {void ActSigIntHandler() ; }
75 #ifndef WNT
76 extern "C" {void SigIntHandler(int, siginfo_t *, void *) ; }
77 #else
78   extern "C" {void SigIntHandler( int ) ; }
79 #endif
80
81
82 map<std::string, int> Engines_Container_i::_cntInstances_map;
83 map<std::string, void *> Engines_Container_i::_library_map;
84 map<std::string, void *> Engines_Container_i::_toRemove_map;
85 omni_mutex Engines_Container_i::_numInstanceMutex ;
86
87 //=============================================================================
88 /*! 
89  *  Default constructor, not for use
90  */
91 //=============================================================================
92
93 Engines_Container_i::Engines_Container_i () :
94   _numInstance(0)
95 {
96 }
97
98 //=============================================================================
99 /*! 
100  *  Construtor to use
101  */
102 //=============================================================================
103
104 Engines_Container_i::Engines_Container_i (CORBA::ORB_ptr orb, 
105                                           PortableServer::POA_var poa,
106                                           char *containerName ,
107                                           int argc , char* argv[],
108                                           bool activAndRegist,
109                                           bool isServantAloneInProcess
110                                           ) :
111   _numInstance(0),_isServantAloneInProcess(isServantAloneInProcess)
112 {
113   _pid = (long)getpid();
114
115   if(activAndRegist)
116     ActSigIntHandler() ;
117
118   _argc = argc ;
119   _argv = argv ;
120
121   string hostname = GetHostname();
122   MESSAGE(hostname << " " << getpid() << " Engines_Container_i starting argc "
123           << _argc << " Thread " << pthread_self() ) ;
124
125   int i = 0 ;
126   while ( _argv[ i ] )
127     {
128       MESSAGE("           argv" << i << " " << _argv[ i ]) ;
129       i++ ;
130     }
131
132   if ( argc < 2 )
133     {
134       INFOS("SALOME_Container usage : SALOME_Container ServerName");
135       ASSERT(0) ;
136     }
137   SCRUTE(argv[1]);
138   _isSupervContainer = false;
139   if (strcmp(argv[1],"SuperVisionContainer") == 0) _isSupervContainer = true;
140
141   if (_isSupervContainer)
142     {
143       _ArgC = argc ;
144       _ArgV = argv ;
145     }
146
147   _orb = CORBA::ORB::_duplicate(orb) ;
148   _poa = PortableServer::POA::_duplicate(poa) ;
149   
150   // Pour les containers paralleles: il ne faut pas enregistrer et activer
151   // le container generique, mais le container specialise
152
153   if(activAndRegist)
154     {
155       _id = _poa->activate_object(this);
156       _NS = new SALOME_NamingService();
157       _NS->init_orb( CORBA::ORB::_duplicate(_orb) ) ;
158       CORBA::Object_var obj=_poa->id_to_reference(*_id);
159       Engines::Container_var pCont 
160         = Engines::Container::_narrow(obj);
161
162       _containerName = _NS->BuildContainerNameForNS(containerName,
163                                                     hostname.c_str());
164       SCRUTE(_containerName);
165       _NS->Register(pCont, _containerName.c_str());
166       MESSAGE("Engines_Container_i::Engines_Container_i : Container name "
167               << _containerName);
168
169       // Python: 
170       // import SALOME_Container
171       // pycont = SALOME_Container.SALOME_Container_i(containerIORStr)
172     
173       CORBA::String_var sior =  _orb->object_to_string(pCont);
174       string myCommand="pyCont = SALOME_Container.SALOME_Container_i('";
175       myCommand += _containerName + "','";
176       myCommand += sior;
177       myCommand += "')\n";
178       SCRUTE(myCommand);
179
180       if (!_isSupervContainer)
181         {
182           Py_ACQUIRE_NEW_THREAD;
183 #ifdef WNT
184           // mpv: this is temporary solution: there is a unregular crash if not
185           Sleep(2000);
186           PyRun_SimpleString("import sys\n");
187           // first element is the path to Registry.dll, but it's wrong
188           PyRun_SimpleString("sys.path = sys.path[1:]\n");
189 #endif
190           PyRun_SimpleString("import SALOME_Container\n");
191           PyRun_SimpleString((char*)myCommand.c_str());
192           Py_RELEASE_NEW_THREAD;
193         }
194
195       fileTransfer_i* aFileTransfer = new fileTransfer_i();
196       _fileTransfer = Engines::fileTransfer::_narrow(aFileTransfer->_this());
197     }
198 }
199
200 //=============================================================================
201 /*! 
202  *  Destructor
203  */
204 //=============================================================================
205
206 Engines_Container_i::~Engines_Container_i()
207 {
208   MESSAGE("Container_i::~Container_i()");
209   delete _id;
210 }
211
212 //=============================================================================
213 /*! 
214  *  CORBA attribute: Container name (see constructor)
215  */
216 //=============================================================================
217
218 char* Engines_Container_i::name()
219 {
220    return CORBA::string_dup(_containerName.c_str()) ;
221 }
222
223 //=============================================================================
224 /*! 
225  *  CORBA method: Get the hostName of the Container (without domain extensions)
226  */
227 //=============================================================================
228
229 char* Engines_Container_i::getHostName()
230 {
231   string s = GetHostname();
232   //  MESSAGE("Engines_Container_i::getHostName " << s);
233   return CORBA::string_dup(s.c_str()) ;
234 }
235
236 //=============================================================================
237 /*! 
238  *  CORBA method: Get the PID (process identification) of the Container
239  */
240 //=============================================================================
241
242 CORBA::Long Engines_Container_i::getPID()
243 {
244   return (CORBA::Long)getpid();
245 }
246
247 //=============================================================================
248 /*! 
249  *  CORBA method: check if servant is still alive
250  */
251 //=============================================================================
252
253 void Engines_Container_i::ping()
254 {
255   MESSAGE("Engines_Container_i::ping() pid "<< getpid());
256 }
257
258 //=============================================================================
259 /*! 
260  *  CORBA method, oneway: Server shutdown. 
261  *  - Container name removed from naming service,
262  *  - servant deactivation,
263  *  - orb shutdown if no other servants in the process 
264  */
265 //=============================================================================
266
267 void Engines_Container_i::Shutdown()
268 {
269   MESSAGE("Engines_Container_i::Shutdown()");
270   _NS->Destroy_FullDirectory(_containerName.c_str());
271   //_remove_ref();
272   //_poa->deactivate_object(*_id);
273   if(_isServantAloneInProcess)
274     {
275       MESSAGE("Effective Shutdown of container Begins...");
276       LocalTraceBufferPool* bp1 = LocalTraceBufferPool::instance();
277       bp1->deleteInstance(bp1);
278       _orb->shutdown(0);
279     }
280 }
281
282
283 //=============================================================================
284 /*! 
285  *  CORBA method: load a new component class (Python or C++ implementation)
286  *  \param componentName like COMPONENT
287  *                          try to make a Python import of COMPONENT,
288  *                          then a lib open of libCOMPONENTEngine.so
289  *  \return true if dlopen successfull or already done, false otherwise
290  */
291 //=============================================================================
292
293 bool
294 Engines_Container_i::load_component_Library(const char* componentName)
295 {
296
297   string aCompName = componentName;
298
299   // --- try dlopen C++ component
300
301 #ifndef WNT
302   string impl_name = string ("lib") + aCompName + string("Engine.so");
303 #else
304   string impl_name = aCompName + string("Engine.dll");
305 #endif
306   SCRUTE(impl_name);
307   
308   _numInstanceMutex.lock(); // lock to be alone 
309   // (see decInstanceCnt, finalize_removal))
310   if (_toRemove_map[impl_name]) _toRemove_map.erase(impl_name);
311   if (_library_map[impl_name])
312     {
313       MESSAGE("Library " << impl_name << " already loaded");
314       _numInstanceMutex.unlock();
315       return true;
316     }
317   
318   void* handle;
319 #if defined( WNT )
320   handle = dlopen( impl_name.c_str() , 0 ) ;
321 //#elif defined( __osf1__ )
322 //  handle = dlopen( impl_name.c_str() , RTLD_NOW ) ;
323 #else
324   handle = dlopen( impl_name.c_str() , RTLD_LAZY ) ;
325 #endif
326   if ( handle )
327     {
328       _library_map[impl_name] = handle;
329       _numInstanceMutex.unlock();
330       return true;
331     }
332   else
333     {
334       INFOS("Can't load shared library : " << impl_name);
335       INFOS("error dlopen: " << dlerror());
336     }
337   _numInstanceMutex.unlock();
338
339   // --- try import Python component
340
341   INFOS("try import Python component "<<componentName);
342   if (_isSupervContainer)
343     {
344       INFOS("Supervision Container does not support Python Component Engines");
345       return false;
346     }
347   if (_library_map[aCompName])
348     {
349       return true; // Python Component, already imported
350     }
351   else
352     {
353       Py_ACQUIRE_NEW_THREAD;
354       PyObject *mainmod = PyImport_AddModule("__main__");
355       PyObject *globals = PyModule_GetDict(mainmod);
356       PyObject *pyCont = PyDict_GetItemString(globals, "pyCont");
357       PyObject *result = PyObject_CallMethod(pyCont,
358                                              "import_component",
359                                              "s",componentName);
360       int ret= PyInt_AsLong(result);
361       SCRUTE(ret);
362       Py_RELEASE_NEW_THREAD;
363   
364       if (ret) // import possible: Python component
365         {
366           _numInstanceMutex.lock() ; // lock to be alone (stl container write)
367           _library_map[aCompName] = (void *)pyCont; // any non O value OK
368           _numInstanceMutex.unlock() ;
369           MESSAGE("import Python: "<<aCompName<<" OK");
370           return true;
371         }
372     }
373   return false;
374 }
375
376 //=============================================================================
377 /*! 
378  *  CORBA method: Creates a new servant instance of a component.
379  *  The servant registers itself to naming service and Registry.
380  *  \param genericRegisterName  Name of the component instance to register
381  *                         in Registry & Name Service (without _inst_n suffix)
382  *  \param studyId         0 for multiStudy instance, 
383  *                         study Id (>0) otherwise
384  *  \return a loaded component
385  */
386 //=============================================================================
387
388 Engines::Component_ptr
389 Engines_Container_i::create_component_instance(const char*genericRegisterName,
390                                                CORBA::Long studyId)
391 {
392   if (studyId < 0)
393     {
394       INFOS("studyId must be > 0 for mono study instance, =0 for multiStudy");
395       return Engines::Component::_nil() ;
396     }
397
398   Engines::Component_var iobject = Engines::Component::_nil() ;
399
400   string aCompName = genericRegisterName;
401   if (_library_map[aCompName]) // Python component
402     {
403       if (_isSupervContainer)
404         {
405           INFOS("Supervision Container does not support Python Component Engines");
406           return Engines::Component::_nil();
407         }
408       _numInstanceMutex.lock() ; // lock on the instance number
409       _numInstance++ ;
410       int numInstance = _numInstance ;
411       _numInstanceMutex.unlock() ;
412
413       char aNumI[12];
414       sprintf( aNumI , "%d" , numInstance ) ;
415       string instanceName = aCompName + "_inst_" + aNumI ;
416       string component_registerName =
417         _containerName + "/" + instanceName;
418
419       Py_ACQUIRE_NEW_THREAD;
420       PyObject *mainmod = PyImport_AddModule("__main__");
421       PyObject *globals = PyModule_GetDict(mainmod);
422       PyObject *pyCont = PyDict_GetItemString(globals, "pyCont");
423       PyObject *result = PyObject_CallMethod(pyCont,
424                                              "create_component_instance",
425                                              "ssl",
426                                              aCompName.c_str(),
427                                              instanceName.c_str(),
428                                              studyId);
429       string iors = PyString_AsString(result);
430       SCRUTE(iors);
431       Py_RELEASE_NEW_THREAD;
432   
433       if( iors!="" )
434       {
435         CORBA::Object_var obj = _orb->string_to_object(iors.c_str());
436         iobject = Engines::Component::_narrow( obj ) ;
437       }
438       return iobject._retn();
439     }
440   
441   //--- try C++
442
443 #ifndef WNT
444   string impl_name = string ("lib") + genericRegisterName +string("Engine.so");
445 #else
446   string impl_name = genericRegisterName +string("Engine.dll");
447 #endif
448   void* handle = _library_map[impl_name];
449   if ( !handle )
450     {
451       INFOS("shared library " << impl_name <<"must be loaded before instance");
452       return Engines::Component::_nil() ;
453     }
454   else
455     {
456       iobject = createInstance(genericRegisterName,
457                                handle,
458                                studyId);
459       return iobject._retn();
460     }
461 }
462
463 //=============================================================================
464 /*! 
465  *  CORBA method: Finds a servant instance of a component
466  *  \param registeredName  Name of the component in Registry or Name Service,
467  *                         without instance suffix number
468  *  \param studyId         0 if instance is not associated to a study, 
469  *                         >0 otherwise (== study id)
470  *  \return the first instance found with same studyId
471  */
472 //=============================================================================
473
474 Engines::Component_ptr
475 Engines_Container_i::find_component_instance( const char* registeredName,
476                                               CORBA::Long studyId)
477 {
478   Engines::Component_var anEngine = Engines::Component::_nil();
479   map<string,Engines::Component_var>::iterator itm =_listInstances_map.begin();
480   while (itm != _listInstances_map.end())
481     {
482       string instance = (*itm).first;
483       SCRUTE(instance);
484       if (instance.find(registeredName) == 0)
485         {
486           anEngine = (*itm).second;
487           if (studyId == anEngine->getStudyId())
488             {
489               return anEngine._retn();
490             }
491         }
492       itm++;
493     }
494   return anEngine._retn();  
495 }
496
497 //=============================================================================
498 /*! 
499  *  CORBA method: find or create an instance of the component (servant),
500  *  load a new component class (dynamic library) if required,
501  *  ---- FOR COMPATIBILITY WITH 2.2 ---- 
502  *  ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
503  *  The servant registers itself to naming service and Registry.
504  *  \param genericRegisterName  Name of the component to register
505  *                              in Registry & Name Service
506  *  \param componentName       Name of the constructed library of the component
507  *  \return a loaded component
508  */
509 //=============================================================================
510
511 Engines::Component_ptr
512 Engines_Container_i::load_impl( const char* genericRegisterName,
513                                 const char* componentName )
514 {
515   string impl_name = string ("lib") + genericRegisterName +string("Engine.so");
516   Engines::Component_var iobject = Engines::Component::_nil() ;
517   if (load_component_Library(genericRegisterName))
518     iobject = find_or_create_instance(genericRegisterName, impl_name);
519   return iobject._retn();
520 }
521     
522
523 //=============================================================================
524 /*! 
525  *  CORBA method: Stops the component servant, and deletes all related objects
526  *  \param component_i     Component to be removed
527  */
528 //=============================================================================
529
530 void Engines_Container_i::remove_impl(Engines::Component_ptr component_i)
531 {
532   ASSERT(! CORBA::is_nil(component_i));
533   string instanceName = component_i->instanceName() ;
534   MESSAGE("unload component " << instanceName);
535   _numInstanceMutex.lock() ; // lock to be alone (stl container write)
536   _listInstances_map.erase(instanceName);
537   _numInstanceMutex.unlock() ;
538   component_i->destroy() ;
539   _NS->Destroy_Name(instanceName.c_str());
540 }
541
542 //=============================================================================
543 /*! 
544  *  CORBA method: Discharges unused libraries from the container.
545  */
546 //=============================================================================
547
548 void Engines_Container_i::finalize_removal()
549 {
550   MESSAGE("finalize unload : dlclose");
551   _numInstanceMutex.lock(); // lock to be alone
552                             // (see decInstanceCnt, load_component_Library)
553   map<string, void *>::iterator ith;
554   for (ith = _toRemove_map.begin(); ith != _toRemove_map.end(); ith++)
555     {
556       void *handle = (*ith).second;
557       string impl_name= (*ith).first;
558       if (handle)
559         {
560           SCRUTE(handle);
561           SCRUTE(impl_name);
562 //        dlclose(handle);                // SALOME unstable after ...
563 //        _library_map.erase(impl_name);
564         }
565     }
566   _toRemove_map.clear();
567   _numInstanceMutex.unlock();
568 }
569
570 //=============================================================================
571 /*! 
572  *  CORBA method: Kill the container process with exit(0).
573  *  To remove :  never returns !
574  */
575 //=============================================================================
576
577 bool Engines_Container_i::Kill_impl()
578 {
579   MESSAGE("Engines_Container_i::Kill() pid "<< getpid() << " containerName "
580           << _containerName.c_str() << " machineName "
581           << GetHostname().c_str());
582   INFOS("===============================================================");
583   INFOS("= REMOVE calls to Kill_impl in C++ container                  =");
584   INFOS("===============================================================");
585   //exit( 0 ) ;
586   ASSERT(0);
587   return false;
588 }
589
590 //=============================================================================
591 /*! 
592  *  CORBA method: get or create a fileRef object associated to a local file
593  *  (a file on the computer on which runs the container server), which stores
594  *  a list of (machine, localFileName) corresponding to copies already done.
595  * 
596  *  \param  origFileName absolute path for a local file to copy on other
597  *          computers
598  *  \return a fileRef object associated to the file.
599  */
600 //=============================================================================
601
602 Engines::fileRef_ptr
603 Engines_Container_i::createFileRef(const char* origFileName)
604 {
605   string origName(origFileName);
606   Engines::fileRef_var theFileRef = Engines::fileRef::_nil();
607
608   if (origName[0] != '/')
609     {
610       INFOS("path of file to copy must be an absolute path begining with '/'");
611       return Engines::fileRef::_nil();
612     }
613
614   if (CORBA::is_nil(_fileRef_map[origName]))
615     {
616       CORBA::Object_var obj=_poa->id_to_reference(*_id);
617       Engines::Container_var pCont = Engines::Container::_narrow(obj);
618       fileRef_i* aFileRef = new fileRef_i(pCont, origFileName);
619       theFileRef = Engines::fileRef::_narrow(aFileRef->_this());
620       _numInstanceMutex.lock() ; // lock to be alone (stl container write)
621       _fileRef_map[origName] = theFileRef;
622       _numInstanceMutex.unlock() ;
623     }
624   
625   theFileRef =  Engines::fileRef::_duplicate(_fileRef_map[origName]);
626   ASSERT(! CORBA::is_nil(theFileRef));
627   return theFileRef._retn();
628 }
629
630 //=============================================================================
631 /*! 
632  *  CORBA method:
633  *  \return a reference to the fileTransfer object
634  */
635 //=============================================================================
636
637 Engines::fileTransfer_ptr
638 Engines_Container_i::getFileTransfer()
639 {
640   Engines::fileTransfer_var aFileTransfer
641     = Engines::fileTransfer::_duplicate(_fileTransfer);
642   return aFileTransfer._retn();
643 }
644
645
646 //=============================================================================
647 /*! 
648  *  C++ method: Finds an already existing servant instance of a component, or
649  *              create an instance.
650  *  ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
651  *  \param genericRegisterName    Name of the component instance to register
652  *                                in Registry & Name Service,
653  *                                (without _inst_n suffix, like "COMPONENT")
654  *  \param componentLibraryName   like "libCOMPONENTEngine.so"
655  *  \return a loaded component
656  * 
657  *  example with names:
658  *  aGenRegisterName = COMPONENT (= first argument)
659  *  impl_name = libCOMPONENTEngine.so (= second argument)
660  *  _containerName = /Containers/cli76ce/FactoryServer
661  *  factoryName = COMPONENTEngine_factory
662  *  component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
663  *
664  *  instanceName = COMPONENT_inst_1
665  *  component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
666  */
667 //=============================================================================
668
669 Engines::Component_ptr
670 Engines_Container_i::find_or_create_instance(string genericRegisterName,
671                                              string componentLibraryName)
672 {
673   string aGenRegisterName = genericRegisterName;
674   string impl_name = componentLibraryName;
675   void* handle = _library_map[impl_name];
676   if ( !handle )
677     {
678       INFOS("shared library " << impl_name <<"must be loaded before instance");
679       return Engines::Component::_nil() ;
680     }
681   else
682     {
683       // --- find a registered instance in naming service, or create
684
685       string component_registerBase =
686         _containerName + "/" + aGenRegisterName;
687       Engines::Component_var iobject = Engines::Component::_nil() ;
688       try
689         {
690           CORBA::Object_var obj =
691             _NS->ResolveFirst( component_registerBase.c_str());
692           if ( CORBA::is_nil( obj ) )
693             {
694               iobject = createInstance(genericRegisterName,
695                                        handle,
696                                        0); // force multiStudy instance here !
697             }
698           else
699             { 
700               iobject = Engines::Component::_narrow( obj ) ;
701               Engines_Component_i *servant =
702                 dynamic_cast<Engines_Component_i*>
703                 (_poa->reference_to_servant(iobject));
704               ASSERT(servant)
705               int studyId = servant->getStudyId();
706               ASSERT (studyId >= 0);
707               if (studyId == 0) // multiStudy instance, OK
708                 {
709                   // No ReBind !
710                   MESSAGE(component_registerBase.c_str()<<" already bound");
711                 }
712               else // monoStudy instance: NOK
713                 {
714                   iobject = Engines::Component::_nil();
715                   INFOS("load_impl & find_component_instance methods "
716                         << "NOT SUITABLE for mono study components");
717                 }
718             }
719         }
720       catch (...)
721         {
722           INFOS( "Container_i::load_impl catched" ) ;
723         }
724       return iobject._retn();
725     }
726 }
727
728 //=============================================================================
729 /*! 
730  *  C++ method: create a servant instance of a component.
731  *  \param genericRegisterName    Name of the component instance to register
732  *                                in Registry & Name Service,
733  *                                (without _inst_n suffix, like "COMPONENT")
734  *  \param handle                 loaded library handle
735  *  \param studyId                0 for multiStudy instance, 
736  *                                study Id (>0) otherwise
737  *  \return a loaded component
738  * 
739  *  example with names:
740  *  aGenRegisterName = COMPONENT (= first argument)
741  *  _containerName = /Containers/cli76ce/FactoryServer
742  *  factoryName = COMPONENTEngine_factory
743  *  component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
744  *  instanceName = COMPONENT_inst_1
745  *  component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
746  */
747 //=============================================================================
748
749 Engines::Component_ptr
750 Engines_Container_i::createInstance(string genericRegisterName,
751                                     void *handle,
752                                     int studyId)
753 {
754   // --- find the factory
755
756   string aGenRegisterName = genericRegisterName;
757   string factory_name = aGenRegisterName + string("Engine_factory");
758   SCRUTE(factory_name) ;
759
760   typedef  PortableServer::ObjectId * (*FACTORY_FUNCTION)
761     (CORBA::ORB_ptr,
762      PortableServer::POA_ptr, 
763      PortableServer::ObjectId *, 
764      const char *, 
765      const char *) ;
766
767   FACTORY_FUNCTION Component_factory
768     = (FACTORY_FUNCTION) dlsym(handle, factory_name.c_str());
769
770   char *error ;
771   if ( (error = dlerror() ) != NULL)
772     {
773       INFOS("Can't resolve symbol: " + factory_name);
774       SCRUTE(error);
775       return Engines::Component::_nil() ;
776     }
777
778   // --- create instance
779
780   Engines::Component_var iobject = Engines::Component::_nil() ;
781
782   try
783     {
784       _numInstanceMutex.lock() ; // lock on the instance number
785       _numInstance++ ;
786       int numInstance = _numInstance ;
787       _numInstanceMutex.unlock() ;
788
789       char aNumI[12];
790       sprintf( aNumI , "%d" , numInstance ) ;
791       string instanceName = aGenRegisterName + "_inst_" + aNumI ;
792       string component_registerName =
793         _containerName + "/" + instanceName;
794
795       // --- Instanciate required CORBA object
796
797       PortableServer::ObjectId *id ; //not owner, do not delete (nore use var)
798       id = (Component_factory) ( _orb, _poa, _id, instanceName.c_str(),
799                                  aGenRegisterName.c_str() ) ;
800
801       // --- get reference & servant from id
802
803       CORBA::Object_var obj = _poa->id_to_reference(*id);
804       iobject = Engines::Component::_narrow( obj ) ;
805
806       Engines_Component_i *servant =
807         dynamic_cast<Engines_Component_i*>(_poa->reference_to_servant(iobject));
808       ASSERT(servant);
809       //SCRUTE(servant->pd_refCount);
810       servant->_remove_ref(); // compensate previous id_to_reference 
811       //SCRUTE(servant->pd_refCount);
812       _numInstanceMutex.lock() ; // lock to be alone (stl container write)
813       _listInstances_map[instanceName] = iobject;
814       _cntInstances_map[aGenRegisterName] += 1;
815       _numInstanceMutex.unlock() ;
816       SCRUTE(aGenRegisterName);
817       SCRUTE(_cntInstances_map[aGenRegisterName]);
818       //SCRUTE(servant->pd_refCount);
819       bool ret_studyId = servant->setStudyId(studyId);
820       ASSERT(ret_studyId);
821
822       // --- register the engine under the name
823       //     containerName(.dir)/instanceName(.object)
824
825       _NS->Register( iobject , component_registerName.c_str() ) ;
826       MESSAGE( component_registerName.c_str() << " bound" ) ;
827     }
828   catch (...)
829     {
830       INFOS( "Container_i::createInstance exception catched" ) ;
831     }
832   return iobject._retn();
833 }
834
835 //=============================================================================
836 /*! 
837  *
838  */
839 //=============================================================================
840
841 void Engines_Container_i::decInstanceCnt(string genericRegisterName)
842 {
843   string aGenRegisterName =genericRegisterName;
844   MESSAGE("Engines_Container_i::decInstanceCnt " << aGenRegisterName);
845   ASSERT(_cntInstances_map[aGenRegisterName] > 0); 
846   _numInstanceMutex.lock(); // lock to be alone
847                             // (see finalize_removal, load_component_Library)
848   _cntInstances_map[aGenRegisterName] -= 1;
849   SCRUTE(_cntInstances_map[aGenRegisterName]);
850   if (_cntInstances_map[aGenRegisterName] == 0)
851     {
852       string impl_name =
853         Engines_Component_i::GetDynLibraryName(aGenRegisterName.c_str());
854       SCRUTE(impl_name);
855       void* handle = _library_map[impl_name];
856       ASSERT(handle);
857       _toRemove_map[impl_name] = handle;
858     }
859   _numInstanceMutex.unlock();
860 }
861
862 //=============================================================================
863 /*! 
864  *  Retrieves only with container naming convention if it is a python container
865  */
866 //=============================================================================
867
868 bool Engines_Container_i::isPythonContainer(const char* ContainerName)
869 {
870   bool ret=false;
871   int len=strlen(ContainerName);
872   if(len>=2)
873     if(strcmp(ContainerName+len-2,"Py")==0)
874       ret=true;
875   return ret;
876 }
877
878 //=============================================================================
879 /*! 
880  *  
881  */
882 //=============================================================================
883
884 void ActSigIntHandler()
885 {
886 #ifndef WNT
887   struct sigaction SigIntAct ;
888   SigIntAct.sa_sigaction = &SigIntHandler ;
889   SigIntAct.sa_flags = SA_SIGINFO ;
890 #endif
891
892 // DEBUG 03.02.2005 : the first parameter of sigaction is not a mask of signals
893 // (SIGINT | SIGUSR1) :
894 // it must be only one signal ===> one call for SIGINT 
895 // and an other one for SIGUSR1
896
897 #ifndef WNT
898   if ( sigaction( SIGINT , &SigIntAct, NULL ) ) 
899     {
900       perror("SALOME_Container main ") ;
901       exit(0) ;
902     }
903   if ( sigaction( SIGUSR1 , &SigIntAct, NULL ) )
904     {
905       perror("SALOME_Container main ") ;
906       exit(0) ;
907     }
908   if ( sigaction( SIGUSR2 , &SigIntAct, NULL ) )
909     {
910       perror("SALOME_Container main ") ;
911       exit(0) ;
912     }
913
914   //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
915   //             use of streams (and so on) should never be used because :
916   //             streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
917   //             A stream operation may be interrupted by a signal and if the Handler use stream we
918   //             may have a "Dead-Lock" ===HangUp
919   //==INFOS is commented
920   //  INFOS(pthread_self() << "SigIntHandler activated") ;
921
922 #else  
923   signal( SIGINT, SigIntHandler );
924   signal( SIGUSR1, SigIntHandler );
925 #endif
926
927 }
928
929 void SetCpuUsed() ;
930 void CallCancelThread() ;
931
932 #ifndef WNT
933 void SigIntHandler(int what ,
934                    siginfo_t * siginfo ,
935                    void * toto ) 
936 {
937   //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
938   //             use of streams (and so on) should never be used because :
939   //             streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
940   //             A stream operation may be interrupted by a signal and if the Handler use stream we
941   //             may have a "Dead-Lock" ===HangUp
942   //==MESSAGE is commented
943   //  MESSAGE(pthread_self() << "SigIntHandler what     " << what << endl
944   //          << "              si_signo " << siginfo->si_signo << endl
945   //          << "              si_code  " << siginfo->si_code << endl
946   //          << "              si_pid   " << siginfo->si_pid) ;
947
948   if ( _Sleeping )
949     {
950       _Sleeping = false ;
951       //     MESSAGE("SigIntHandler END sleeping.") ;
952       return ;
953     }
954   else
955     {
956       ActSigIntHandler() ;
957       if ( siginfo->si_signo == SIGUSR1 )
958         {
959           SetCpuUsed() ;
960         }
961       else if ( siginfo->si_signo == SIGUSR2 )
962         {
963           CallCancelThread() ;
964         }
965       else 
966         {
967           _Sleeping = true ;
968           //      MESSAGE("SigIntHandler BEGIN sleeping.") ;
969           int count = 0 ;
970           while( _Sleeping )
971             {
972               sleep( 1 ) ;
973               count += 1 ;
974             }
975           //      MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
976         }
977       return ;
978     }
979 }
980 #else // Case WNT
981 void SigIntHandler( int what )
982 {
983   MESSAGE( pthread_self() << "SigIntHandler what     " << what << endl );
984   if ( _Sleeping )
985     {
986       _Sleeping = false ;
987       MESSAGE("SigIntHandler END sleeping.") ;
988       return ;
989     }
990   else
991     {
992       ActSigIntHandler() ;
993       if ( what == SIGUSR1 )
994         {
995           SetCpuUsed() ;
996         }
997       else
998         {
999           _Sleeping = true ;
1000           MESSAGE("SigIntHandler BEGIN sleeping.") ;
1001           int count = 0 ;
1002           while( _Sleeping ) 
1003             {
1004               Sleep( 1000 ) ;
1005               count += 1 ;
1006             }
1007           MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1008         }
1009       return ;
1010     }
1011 }
1012 #endif
1013