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