Salome HOME
Removed CASCatch
[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       if(!CORBA::is_nil(_orb))
304         _orb->shutdown(0);
305     }
306 }
307
308
309 //=============================================================================
310 /*! 
311  *  CORBA method: load a new component class (Python or C++ implementation)
312  *  \param componentName like COMPONENT
313  *                          try to make a Python import of COMPONENT,
314  *                          then a lib open of libCOMPONENTEngine.so
315  *  \return true if dlopen successfull or already done, false otherwise
316  */
317 //=============================================================================
318
319 bool
320 Engines_Container_i::load_component_Library(const char* componentName)
321 {
322
323   string aCompName = componentName;
324
325   // --- try dlopen C++ component
326
327 #ifndef WNT
328   string impl_name = string ("lib") + aCompName + string("Engine.so");
329 #else
330   string impl_name = aCompName + string("Engine.dll");
331 #endif
332   SCRUTE(impl_name);
333   
334   _numInstanceMutex.lock(); // lock to be alone 
335   // (see decInstanceCnt, finalize_removal))
336   if (_toRemove_map[impl_name]) _toRemove_map.erase(impl_name);
337   if (_library_map[impl_name])
338     {
339       MESSAGE("Library " << impl_name << " already loaded");
340       _numInstanceMutex.unlock();
341       return true;
342     }
343   
344 #ifndef WNT
345   void* handle;
346   handle = dlopen( impl_name.c_str() , RTLD_LAZY ) ;
347 #else
348   HINSTANCE handle;
349   handle = LoadLibrary( impl_name.c_str() );
350 #endif
351
352   if ( handle )
353   {
354       _library_map[impl_name] = handle;
355       _numInstanceMutex.unlock();
356       return true;
357   }
358   else
359   {
360       INFOS( "Can't load shared library: " << impl_name );
361 #ifndef WNT
362       INFOS("error dlopen: " << dlerror());
363 #endif
364   }
365   _numInstanceMutex.unlock();
366
367   // --- try import Python component
368
369   INFOS("try import Python component "<<componentName);
370   if (_isSupervContainer)
371     {
372       INFOS("Supervision Container does not support Python Component Engines");
373       return false;
374     }
375   if (_library_map[aCompName])
376     {
377       return true; // Python Component, already imported
378     }
379   else
380     {
381       Py_ACQUIRE_NEW_THREAD;
382       PyObject *mainmod = PyImport_AddModule("__main__");
383       PyObject *globals = PyModule_GetDict(mainmod);
384       PyObject *pyCont = PyDict_GetItemString(globals, "pyCont");
385       PyObject *result = PyObject_CallMethod(pyCont,
386                                              "import_component",
387                                              "s",componentName);
388       int ret= PyInt_AsLong(result);
389       SCRUTE(ret);
390       Py_RELEASE_NEW_THREAD;
391   
392       if (ret) // import possible: Python component
393         {
394           _numInstanceMutex.lock() ; // lock to be alone (stl container write)
395           _library_map[aCompName] = (void *)pyCont; // any non O value OK
396           _numInstanceMutex.unlock() ;
397           MESSAGE("import Python: "<<aCompName<<" OK");
398           return true;
399         }
400     }
401   return false;
402 }
403
404 //=============================================================================
405 /*! 
406  *  CORBA method: Creates a new servant instance of a component.
407  *  The servant registers itself to naming service and Registry.
408  *  \param genericRegisterName  Name of the component instance to register
409  *                         in Registry & Name Service (without _inst_n suffix)
410  *  \param studyId         0 for multiStudy instance, 
411  *                         study Id (>0) otherwise
412  *  \return a loaded component
413  */
414 //=============================================================================
415
416 Engines::Component_ptr
417 Engines_Container_i::create_component_instance(const char*genericRegisterName,
418                                                CORBA::Long studyId)
419 {
420   if (studyId < 0)
421     {
422       INFOS("studyId must be > 0 for mono study instance, =0 for multiStudy");
423       return Engines::Component::_nil() ;
424     }
425
426   Engines::Component_var iobject = Engines::Component::_nil() ;
427
428   string aCompName = genericRegisterName;
429   if (_library_map[aCompName]) // Python component
430     {
431       if (_isSupervContainer)
432         {
433           INFOS("Supervision Container does not support Python Component Engines");
434           return Engines::Component::_nil();
435         }
436       _numInstanceMutex.lock() ; // lock on the instance number
437       _numInstance++ ;
438       int numInstance = _numInstance ;
439       _numInstanceMutex.unlock() ;
440
441       char aNumI[12];
442       sprintf( aNumI , "%d" , numInstance ) ;
443       string instanceName = aCompName + "_inst_" + aNumI ;
444       string component_registerName =
445         _containerName + "/" + instanceName;
446
447       Py_ACQUIRE_NEW_THREAD;
448       PyObject *mainmod = PyImport_AddModule("__main__");
449       PyObject *globals = PyModule_GetDict(mainmod);
450       PyObject *pyCont = PyDict_GetItemString(globals, "pyCont");
451       PyObject *result = PyObject_CallMethod(pyCont,
452                                              "create_component_instance",
453                                              "ssl",
454                                              aCompName.c_str(),
455                                              instanceName.c_str(),
456                                              studyId);
457       string iors = PyString_AsString(result);
458       SCRUTE(iors);
459       Py_RELEASE_NEW_THREAD;
460   
461       if( iors!="" )
462       {
463         CORBA::Object_var obj = _orb->string_to_object(iors.c_str());
464         iobject = Engines::Component::_narrow( obj ) ;
465       }
466       return iobject._retn();
467     }
468   
469   //--- try C++
470
471 #ifndef WNT
472   string impl_name = string ("lib") + genericRegisterName +string("Engine.so");
473 #else
474   string impl_name = genericRegisterName +string("Engine.dll");
475 #endif
476   void* handle = _library_map[impl_name];
477   if ( !handle )
478     {
479       INFOS("shared library " << impl_name <<"must be loaded before instance");
480       return Engines::Component::_nil() ;
481     }
482   else
483     {
484       iobject = createInstance(genericRegisterName,
485                                handle,
486                                studyId);
487       return iobject._retn();
488     }
489 }
490
491 //=============================================================================
492 /*! 
493  *  CORBA method: Finds a servant instance of a component
494  *  \param registeredName  Name of the component in Registry or Name Service,
495  *                         without instance suffix number
496  *  \param studyId         0 if instance is not associated to a study, 
497  *                         >0 otherwise (== study id)
498  *  \return the first instance found with same studyId
499  */
500 //=============================================================================
501
502 Engines::Component_ptr
503 Engines_Container_i::find_component_instance( const char* registeredName,
504                                               CORBA::Long studyId)
505 {
506   Engines::Component_var anEngine = Engines::Component::_nil();
507   map<string,Engines::Component_var>::iterator itm =_listInstances_map.begin();
508   while (itm != _listInstances_map.end())
509     {
510       string instance = (*itm).first;
511       SCRUTE(instance);
512       if (instance.find(registeredName) == 0)
513         {
514           anEngine = (*itm).second;
515           if (studyId == anEngine->getStudyId())
516             {
517               return anEngine._retn();
518             }
519         }
520       itm++;
521     }
522   return anEngine._retn();  
523 }
524
525 //=============================================================================
526 /*! 
527  *  CORBA method: find or create an instance of the component (servant),
528  *  load a new component class (dynamic library) if required,
529  *  ---- FOR COMPATIBILITY WITH 2.2 ---- 
530  *  ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
531  *  The servant registers itself to naming service and Registry.
532  *  \param genericRegisterName  Name of the component to register
533  *                              in Registry & Name Service
534  *  \param componentName       Name of the constructed library of the component
535  *  \return a loaded component
536  */
537 //=============================================================================
538
539 Engines::Component_ptr
540 Engines_Container_i::load_impl( const char* genericRegisterName,
541                                 const char* componentName )
542 {
543   string impl_name = string ("lib") + genericRegisterName +string("Engine.so");
544   Engines::Component_var iobject = Engines::Component::_nil() ;
545   if (load_component_Library(genericRegisterName))
546     iobject = find_or_create_instance(genericRegisterName, impl_name);
547   return iobject._retn();
548 }
549     
550
551 //=============================================================================
552 /*! 
553  *  CORBA method: Stops the component servant, and deletes all related objects
554  *  \param component_i     Component to be removed
555  */
556 //=============================================================================
557
558 void Engines_Container_i::remove_impl(Engines::Component_ptr component_i)
559 {
560   ASSERT(! CORBA::is_nil(component_i));
561   string instanceName = component_i->instanceName() ;
562   MESSAGE("unload component " << instanceName);
563   _numInstanceMutex.lock() ; // lock to be alone (stl container write)
564   _listInstances_map.erase(instanceName);
565   _numInstanceMutex.unlock() ;
566   component_i->destroy() ;
567   _NS->Destroy_Name(instanceName.c_str());
568 }
569
570 //=============================================================================
571 /*! 
572  *  CORBA method: Discharges unused libraries from the container.
573  */
574 //=============================================================================
575
576 void Engines_Container_i::finalize_removal()
577 {
578   MESSAGE("finalize unload : dlclose");
579   _numInstanceMutex.lock(); // lock to be alone
580                             // (see decInstanceCnt, load_component_Library)
581   map<string, void *>::iterator ith;
582   for (ith = _toRemove_map.begin(); ith != _toRemove_map.end(); ith++)
583     {
584       void *handle = (*ith).second;
585       string impl_name= (*ith).first;
586       if (handle)
587         {
588           SCRUTE(handle);
589           SCRUTE(impl_name);
590 //        dlclose(handle);                // SALOME unstable after ...
591 //        _library_map.erase(impl_name);
592         }
593     }
594   _toRemove_map.clear();
595   _numInstanceMutex.unlock();
596 }
597
598 //=============================================================================
599 /*! 
600  *  CORBA method: Kill the container process with exit(0).
601  *  To remove :  never returns !
602  */
603 //=============================================================================
604
605 bool Engines_Container_i::Kill_impl()
606 {
607   MESSAGE("Engines_Container_i::Kill() pid "<< getpid() << " containerName "
608           << _containerName.c_str() << " machineName "
609           << GetHostname().c_str());
610   INFOS("===============================================================");
611   INFOS("= REMOVE calls to Kill_impl in C++ container                  =");
612   INFOS("===============================================================");
613   //exit( 0 ) ;
614   ASSERT(0);
615   return false;
616 }
617
618 //=============================================================================
619 /*! 
620  *  CORBA method: get or create a fileRef object associated to a local file
621  *  (a file on the computer on which runs the container server), which stores
622  *  a list of (machine, localFileName) corresponding to copies already done.
623  * 
624  *  \param  origFileName absolute path for a local file to copy on other
625  *          computers
626  *  \return a fileRef object associated to the file.
627  */
628 //=============================================================================
629
630 Engines::fileRef_ptr
631 Engines_Container_i::createFileRef(const char* origFileName)
632 {
633   string origName(origFileName);
634   Engines::fileRef_var theFileRef = Engines::fileRef::_nil();
635
636   if (origName[0] != '/')
637     {
638       INFOS("path of file to copy must be an absolute path begining with '/'");
639       return Engines::fileRef::_nil();
640     }
641
642   if (CORBA::is_nil(_fileRef_map[origName]))
643     {
644       CORBA::Object_var obj=_poa->id_to_reference(*_id);
645       Engines::Container_var pCont = Engines::Container::_narrow(obj);
646       fileRef_i* aFileRef = new fileRef_i(pCont, origFileName);
647       theFileRef = Engines::fileRef::_narrow(aFileRef->_this());
648       _numInstanceMutex.lock() ; // lock to be alone (stl container write)
649       _fileRef_map[origName] = theFileRef;
650       _numInstanceMutex.unlock() ;
651     }
652   
653   theFileRef =  Engines::fileRef::_duplicate(_fileRef_map[origName]);
654   ASSERT(! CORBA::is_nil(theFileRef));
655   return theFileRef._retn();
656 }
657
658 //=============================================================================
659 /*! 
660  *  CORBA method:
661  *  \return a reference to the fileTransfer object
662  */
663 //=============================================================================
664
665 Engines::fileTransfer_ptr
666 Engines_Container_i::getFileTransfer()
667 {
668   Engines::fileTransfer_var aFileTransfer
669     = Engines::fileTransfer::_duplicate(_fileTransfer);
670   return aFileTransfer._retn();
671 }
672
673
674 Engines::Salome_file_ptr 
675 Engines_Container_i::createSalome_file(const char* origFileName) 
676 {
677   string origName(origFileName);
678   if (CORBA::is_nil(_Salome_file_map[origName]))
679     {
680       Salome_file_i* aSalome_file = new Salome_file_i();
681       aSalome_file->setContainer(Engines::Container::_duplicate(this->_this()));
682       try 
683       {
684         aSalome_file->setLocalFile(origFileName);
685         aSalome_file->recvFiles();
686       }
687       catch (const SALOME::SALOME_Exception& e)
688       {
689         return Engines::Salome_file::_nil();
690       }
691
692       Engines::Salome_file_var theSalome_file = Engines::Salome_file::_nil();
693       theSalome_file = Engines::Salome_file::_narrow(aSalome_file->_this());
694       _numInstanceMutex.lock() ; // lock to be alone (stl container write)
695       _Salome_file_map[origName] = theSalome_file;
696       _numInstanceMutex.unlock() ;
697     }
698   
699   Engines::Salome_file_ptr theSalome_file =  
700     Engines::Salome_file::_duplicate(_Salome_file_map[origName]);
701   ASSERT(!CORBA::is_nil(theSalome_file));
702   return theSalome_file;
703 }
704 //=============================================================================
705 /*! 
706  *  C++ method: Finds an already existing servant instance of a component, or
707  *              create an instance.
708  *  ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
709  *  \param genericRegisterName    Name of the component instance to register
710  *                                in Registry & Name Service,
711  *                                (without _inst_n suffix, like "COMPONENT")
712  *  \param componentLibraryName   like "libCOMPONENTEngine.so"
713  *  \return a loaded component
714  * 
715  *  example with names:
716  *  aGenRegisterName = COMPONENT (= first argument)
717  *  impl_name = libCOMPONENTEngine.so (= second argument)
718  *  _containerName = /Containers/cli76ce/FactoryServer
719  *  factoryName = COMPONENTEngine_factory
720  *  component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
721  *
722  *  instanceName = COMPONENT_inst_1
723  *  component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
724  */
725 //=============================================================================
726
727 Engines::Component_ptr
728 Engines_Container_i::find_or_create_instance(string genericRegisterName,
729                                              string componentLibraryName)
730 {
731   string aGenRegisterName = genericRegisterName;
732   string impl_name = componentLibraryName;
733   void* handle = _library_map[impl_name];
734   if ( !handle )
735     {
736       INFOS("shared library " << impl_name <<"must be loaded before instance");
737       return Engines::Component::_nil() ;
738     }
739   else
740     {
741       // --- find a registered instance in naming service, or create
742
743       string component_registerBase =
744         _containerName + "/" + aGenRegisterName;
745       Engines::Component_var iobject = Engines::Component::_nil() ;
746       try
747         {
748           CORBA::Object_var obj =
749             _NS->ResolveFirst( component_registerBase.c_str());
750           if ( CORBA::is_nil( obj ) )
751             {
752               iobject = createInstance(genericRegisterName,
753                                        handle,
754                                        0); // force multiStudy instance here !
755             }
756           else
757             { 
758               iobject = Engines::Component::_narrow( obj ) ;
759               Engines_Component_i *servant =
760                 dynamic_cast<Engines_Component_i*>
761                 (_poa->reference_to_servant(iobject));
762               ASSERT(servant)
763               int studyId = servant->getStudyId();
764               ASSERT (studyId >= 0);
765               if (studyId == 0) // multiStudy instance, OK
766                 {
767                   // No ReBind !
768                   MESSAGE(component_registerBase.c_str()<<" already bound");
769                 }
770               else // monoStudy instance: NOK
771                 {
772                   iobject = Engines::Component::_nil();
773                   INFOS("load_impl & find_component_instance methods "
774                         << "NOT SUITABLE for mono study components");
775                 }
776             }
777         }
778       catch (...)
779         {
780           INFOS( "Container_i::load_impl catched" ) ;
781         }
782       return iobject._retn();
783     }
784 }
785
786 //=============================================================================
787 /*! 
788  *  C++ method: create a servant instance of a component.
789  *  \param genericRegisterName    Name of the component instance to register
790  *                                in Registry & Name Service,
791  *                                (without _inst_n suffix, like "COMPONENT")
792  *  \param handle                 loaded library handle
793  *  \param studyId                0 for multiStudy instance, 
794  *                                study Id (>0) otherwise
795  *  \return a loaded component
796  * 
797  *  example with names:
798  *  aGenRegisterName = COMPONENT (= first argument)
799  *  _containerName = /Containers/cli76ce/FactoryServer
800  *  factoryName = COMPONENTEngine_factory
801  *  component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
802  *  instanceName = COMPONENT_inst_1
803  *  component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
804  */
805 //=============================================================================
806
807 Engines::Component_ptr
808 Engines_Container_i::createInstance(string genericRegisterName,
809                                     void *handle,
810                                     int studyId)
811 {
812   // --- find the factory
813
814   string aGenRegisterName = genericRegisterName;
815   string factory_name = aGenRegisterName + string("Engine_factory");
816   SCRUTE(factory_name) ;
817
818   typedef  PortableServer::ObjectId * (*FACTORY_FUNCTION)
819     (CORBA::ORB_ptr,
820      PortableServer::POA_ptr, 
821      PortableServer::ObjectId *, 
822      const char *, 
823      const char *) ;
824
825 #ifndef WNT
826   FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)dlsym( handle, factory_name.c_str() );
827 #else
828   FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)GetProcAddress( (HINSTANCE)handle, factory_name.c_str() );
829 #endif
830
831   if ( !Component_factory )
832   {
833       INFOS( "Can't resolve symbol: " + factory_name );
834 #ifndef WNT
835       SCRUTE( dlerror() );
836 #endif
837       return Engines::Component::_nil() ;
838   }
839
840   // --- create instance
841
842   Engines::Component_var iobject = Engines::Component::_nil() ;
843
844   try
845     {
846       _numInstanceMutex.lock() ; // lock on the instance number
847       _numInstance++ ;
848       int numInstance = _numInstance ;
849       _numInstanceMutex.unlock() ;
850
851       char aNumI[12];
852       sprintf( aNumI , "%d" , numInstance ) ;
853       string instanceName = aGenRegisterName + "_inst_" + aNumI ;
854       string component_registerName =
855         _containerName + "/" + instanceName;
856
857       // --- Instanciate required CORBA object
858
859       PortableServer::ObjectId *id ; //not owner, do not delete (nore use var)
860       id = (Component_factory) ( _orb, _poa, _id, instanceName.c_str(),
861                                  aGenRegisterName.c_str() ) ;
862       if (id == NULL)
863         return iobject._retn();
864       
865       // --- get reference & servant from id
866
867       CORBA::Object_var obj = _poa->id_to_reference(*id);
868       iobject = Engines::Component::_narrow( obj ) ;
869
870       Engines_Component_i *servant =
871         dynamic_cast<Engines_Component_i*>(_poa->reference_to_servant(iobject));
872       ASSERT(servant);
873       //SCRUTE(servant->pd_refCount);
874       servant->_remove_ref(); // compensate previous id_to_reference 
875       //SCRUTE(servant->pd_refCount);
876       _numInstanceMutex.lock() ; // lock to be alone (stl container write)
877       _listInstances_map[instanceName] = iobject;
878       _cntInstances_map[aGenRegisterName] += 1;
879       _numInstanceMutex.unlock() ;
880       SCRUTE(aGenRegisterName);
881       SCRUTE(_cntInstances_map[aGenRegisterName]);
882       //SCRUTE(servant->pd_refCount);
883       bool ret_studyId = servant->setStudyId(studyId);
884       ASSERT(ret_studyId);
885
886       // --- register the engine under the name
887       //     containerName(.dir)/instanceName(.object)
888
889       _NS->Register( iobject , component_registerName.c_str() ) ;
890       MESSAGE( component_registerName.c_str() << " bound" ) ;
891     }
892   catch (...)
893     {
894       INFOS( "Container_i::createInstance exception catched" ) ;
895     }
896   return iobject._retn();
897 }
898
899 //=============================================================================
900 /*! 
901  *
902  */
903 //=============================================================================
904
905 void Engines_Container_i::decInstanceCnt(string genericRegisterName)
906 {
907   string aGenRegisterName =genericRegisterName;
908   MESSAGE("Engines_Container_i::decInstanceCnt " << aGenRegisterName);
909   ASSERT(_cntInstances_map[aGenRegisterName] > 0); 
910   _numInstanceMutex.lock(); // lock to be alone
911                             // (see finalize_removal, load_component_Library)
912   _cntInstances_map[aGenRegisterName] -= 1;
913   SCRUTE(_cntInstances_map[aGenRegisterName]);
914   if (_cntInstances_map[aGenRegisterName] == 0)
915     {
916       string impl_name =
917         Engines_Component_i::GetDynLibraryName(aGenRegisterName.c_str());
918       SCRUTE(impl_name);
919       void* handle = _library_map[impl_name];
920       ASSERT(handle);
921       _toRemove_map[impl_name] = handle;
922     }
923   _numInstanceMutex.unlock();
924 }
925
926 //=============================================================================
927 /*! 
928  *  Retrieves only with container naming convention if it is a python container
929  */
930 //=============================================================================
931
932 bool Engines_Container_i::isPythonContainer(const char* ContainerName)
933 {
934   bool ret=false;
935   int len=strlen(ContainerName);
936   if(len>=2)
937     if(strcmp(ContainerName+len-2,"Py")==0)
938       ret=true;
939   return ret;
940 }
941
942 //=============================================================================
943 /*! 
944  *  
945  */
946 //=============================================================================
947
948 void ActSigIntHandler()
949 {
950 #ifndef WNT
951   struct sigaction SigIntAct ;
952   SigIntAct.sa_sigaction = &SigIntHandler ;
953   SigIntAct.sa_flags = SA_SIGINFO ;
954 #endif
955
956 // DEBUG 03.02.2005 : the first parameter of sigaction is not a mask of signals
957 // (SIGINT | SIGUSR1) :
958 // it must be only one signal ===> one call for SIGINT 
959 // and an other one for SIGUSR1
960
961 #ifndef WNT
962   if ( sigaction( SIGINT , &SigIntAct, NULL ) ) 
963     {
964       perror("SALOME_Container main ") ;
965       exit(0) ;
966     }
967   if ( sigaction( SIGUSR1 , &SigIntAct, NULL ) )
968     {
969       perror("SALOME_Container main ") ;
970       exit(0) ;
971     }
972   if ( sigaction( SIGUSR2 , &SigIntAct, NULL ) )
973     {
974       perror("SALOME_Container main ") ;
975       exit(0) ;
976     }
977
978   //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
979   //             use of streams (and so on) should never be used because :
980   //             streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
981   //             A stream operation may be interrupted by a signal and if the Handler use stream we
982   //             may have a "Dead-Lock" ===HangUp
983   //==INFOS is commented
984   //  INFOS(pthread_self() << "SigIntHandler activated") ;
985
986 #else  
987   signal( SIGINT, SigIntHandler );
988   signal( SIGUSR1, SigIntHandler );
989 #endif
990
991 }
992
993 void SetCpuUsed() ;
994 void CallCancelThread() ;
995
996 #ifndef WNT
997 void SigIntHandler(int what ,
998                    siginfo_t * siginfo ,
999                    void * toto ) 
1000 {
1001   //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1002   //             use of streams (and so on) should never be used because :
1003   //             streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1004   //             A stream operation may be interrupted by a signal and if the Handler use stream we
1005   //             may have a "Dead-Lock" ===HangUp
1006   //==MESSAGE is commented
1007   //  MESSAGE(pthread_self() << "SigIntHandler what     " << what << endl
1008   //          << "              si_signo " << siginfo->si_signo << endl
1009   //          << "              si_code  " << siginfo->si_code << endl
1010   //          << "              si_pid   " << siginfo->si_pid) ;
1011
1012   if ( _Sleeping )
1013     {
1014       _Sleeping = false ;
1015       //     MESSAGE("SigIntHandler END sleeping.") ;
1016       return ;
1017     }
1018   else
1019     {
1020       ActSigIntHandler() ;
1021       if ( siginfo->si_signo == SIGUSR1 )
1022         {
1023           SetCpuUsed() ;
1024         }
1025       else if ( siginfo->si_signo == SIGUSR2 )
1026         {
1027           CallCancelThread() ;
1028         }
1029       else 
1030         {
1031           _Sleeping = true ;
1032           //      MESSAGE("SigIntHandler BEGIN sleeping.") ;
1033           int count = 0 ;
1034           while( _Sleeping )
1035             {
1036               sleep( 1 ) ;
1037               count += 1 ;
1038             }
1039           //      MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1040         }
1041       return ;
1042     }
1043 }
1044 #else // Case WNT
1045 void SigIntHandler( int what )
1046 {
1047 #ifndef WNT
1048   MESSAGE( pthread_self() << "SigIntHandler what     " << what << endl );
1049 #else
1050   MESSAGE( "SigIntHandler what     " << what << endl );
1051 #endif
1052   if ( _Sleeping )
1053     {
1054       _Sleeping = false ;
1055       MESSAGE("SigIntHandler END sleeping.") ;
1056       return ;
1057     }
1058   else
1059     {
1060       ActSigIntHandler() ;
1061       if ( what == SIGUSR1 )
1062         {
1063           SetCpuUsed() ;
1064         }
1065       else
1066         {
1067           _Sleeping = true ;
1068           MESSAGE("SigIntHandler BEGIN sleeping.") ;
1069           int count = 0 ;
1070           while( _Sleeping ) 
1071             {
1072               Sleep( 1000 ) ;
1073               count += 1 ;
1074             }
1075           MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1076         }
1077       return ;
1078     }
1079 }
1080 #endif