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