Salome HOME
0095b0bc579c69fdc082d273322ff3eb4f4137b0
[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_ptr 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( _orb ) ;
165       CORBA::Object_var obj=_poa->id_to_reference(*_id);
166       Engines::Container_var pCont 
167         = Engines::Container::_narrow(obj);
168       _remove_ref();
169
170       _containerName = _NS->BuildContainerNameForNS(containerName,
171                                                     hostname.c_str());
172       SCRUTE(_containerName);
173       _NS->Register(pCont, _containerName.c_str());
174       MESSAGE("Engines_Container_i::Engines_Container_i : Container name "
175               << _containerName);
176
177       // Python: 
178       // import SALOME_Container
179       // pycont = SALOME_Container.SALOME_Container_i(containerIORStr)
180     
181       CORBA::String_var sior =  _orb->object_to_string(pCont);
182       string myCommand="pyCont = SALOME_Container.SALOME_Container_i('";
183       myCommand += _containerName + "','";
184       myCommand += sior;
185       myCommand += "')\n";
186       SCRUTE(myCommand);
187
188       if (!_isSupervContainer)
189         {
190 #ifdef WNT
191
192           PyEval_AcquireLock();
193           PyThreadState *myTstate = PyThreadState_New(KERNEL_PYTHON::_interp);
194           PyThreadState *myoldTstate = PyThreadState_Swap(myTstate);
195 #else
196           Py_ACQUIRE_NEW_THREAD;
197 #endif
198
199 #ifdef WNT
200           // mpv: this is temporary solution: there is a unregular crash if not
201           //Sleep(2000);
202           //
203     // first element is the path to Registry.dll, but it's wrong
204           PyRun_SimpleString("import sys\n");
205           PyRun_SimpleString("sys.path = sys.path[1:]\n");
206 #endif
207           PyRun_SimpleString("import SALOME_Container\n");
208           PyRun_SimpleString((char*)myCommand.c_str());
209           Py_RELEASE_NEW_THREAD;
210         }
211
212       fileTransfer_i* aFileTransfer = new fileTransfer_i();
213       CORBA::Object_var obref=aFileTransfer->_this();
214       _fileTransfer = Engines::fileTransfer::_narrow(obref);
215       aFileTransfer->_remove_ref();
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   if(_NS)
230     delete _NS;
231 }
232
233 //=============================================================================
234 /*! 
235  *  CORBA attribute: Container name (see constructor)
236  */
237 //=============================================================================
238
239 char* Engines_Container_i::name()
240 {
241    return CORBA::string_dup(_containerName.c_str()) ;
242 }
243
244 //=============================================================================
245 /*! 
246  *  CORBA attribute: Container working directory 
247  */
248 //=============================================================================
249
250 char* Engines_Container_i::workingdir()
251 {
252   char wd[256];
253   getcwd (wd,256);
254   return CORBA::string_dup(wd) ;
255 }
256
257 //=============================================================================
258 /*! 
259  *  CORBA attribute: Container log file name
260  */
261 //=============================================================================
262
263 char* Engines_Container_i::logfilename()
264 {
265   return CORBA::string_dup(_logfilename.c_str()) ;
266 }
267
268 void Engines_Container_i::logfilename(const char* name)
269 {
270   _logfilename=name;
271 }
272
273 //=============================================================================
274 /*! 
275  *  CORBA method: Get the hostName of the Container (without domain extensions)
276  */
277 //=============================================================================
278
279 char* Engines_Container_i::getHostName()
280 {
281   string s = GetHostname();
282   //  MESSAGE("Engines_Container_i::getHostName " << s);
283   return CORBA::string_dup(s.c_str()) ;
284 }
285
286 //=============================================================================
287 /*! 
288  *  CORBA method: Get the PID (process identification) of the Container
289  */
290 //=============================================================================
291
292 CORBA::Long Engines_Container_i::getPID()
293 {
294   return (CORBA::Long)getpid();
295 }
296
297 //=============================================================================
298 /*! 
299  *  CORBA method: check if servant is still alive
300  */
301 //=============================================================================
302
303 void Engines_Container_i::ping()
304 {
305   MESSAGE("Engines_Container_i::ping() pid "<< getpid());
306 }
307
308 //=============================================================================
309 /*! 
310  *  CORBA method, oneway: Server shutdown. 
311  *  - Container name removed from naming service,
312  *  - servant deactivation,
313  *  - orb shutdown if no other servants in the process 
314  */
315 //=============================================================================
316
317 void Engines_Container_i::Shutdown()
318 {
319   MESSAGE("Engines_Container_i::Shutdown()");
320
321   /* For each component contained in this container
322    * tell it to self-destroy
323    */
324   std::map<std::string, Engines::Component_var>::iterator itm;
325   for (itm = _listInstances_map.begin(); itm != _listInstances_map.end(); itm++)
326     itm->second->destroy();
327
328   _NS->Destroy_FullDirectory(_containerName.c_str());
329   _NS->Destroy_Name(_containerName.c_str());
330   //_remove_ref();
331   //_poa->deactivate_object(*_id);
332   if(_isServantAloneInProcess)
333     {
334       MESSAGE("Effective Shutdown of container Begins...");
335       if(!CORBA::is_nil(_orb))
336         _orb->shutdown(0);
337     }
338 }
339
340 /* int checkifexecutable(const char *filename)
341  * 
342  * Return non-zero if the name is an executable file, and
343  * zero if it is not executable, or if it does not exist.
344  */
345
346 int checkifexecutable(const char *filename)
347 {
348      int result;
349      struct stat statinfo;
350      
351      result = stat(filename, &statinfo);
352      if (result < 0) return 0;
353      if (!S_ISREG(statinfo.st_mode)) return 0;
354
355      if (statinfo.st_uid == geteuid()) return statinfo.st_mode & S_IXUSR;
356      if (statinfo.st_gid == getegid()) return statinfo.st_mode & S_IXGRP;
357      return statinfo.st_mode & S_IXOTH;
358 }
359
360
361 /* int findpathof(char *pth, const char *exe)
362  *
363  * Find executable by searching the PATH environment variable.
364  *
365  * const char *exe - executable name to search for.
366  *       char *pth - the path found is stored here, space
367  *                   needs to be available.
368  *
369  * If a path is found, returns non-zero, and the path is stored
370  * in pth.  If exe is not found returns 0, with pth undefined.
371  */
372
373 int findpathof(char *pth, const char *exe)
374 {
375      char *searchpath;
376      char *beg, *end;
377      int stop, found;
378      int len;
379
380      if (strchr(exe, '/') != NULL) {
381       if (realpath(exe, pth) == NULL) return 0;
382       return  checkifexecutable(pth);
383      }
384
385      searchpath = getenv("PATH");
386      if (searchpath == NULL) return 0;
387      if (strlen(searchpath) <= 0) return 0;
388
389      beg = searchpath;
390      stop = 0; found = 0;
391      do {
392       end = strchr(beg, ':');
393       if (end == NULL) {
394            stop = 1;
395            strncpy(pth, beg, PATH_MAX);
396            len = strlen(pth);
397       } else {
398            strncpy(pth, beg, end - beg);
399            pth[end - beg] = '\0';
400            len = end - beg;
401       }
402       if (pth[len - 1] != '/') strncat(pth, "/", 1);
403       strncat(pth, exe, PATH_MAX - len);
404       found = checkifexecutable(pth);
405       if (!stop) beg = end + 1;
406      } while (!stop && !found);
407       
408      return found;
409 }
410
411
412
413 //=============================================================================
414 /*! 
415  *  CORBA method: load a new component class (Python or C++ implementation)
416  *  \param componentName like COMPONENT
417  *                          try to make a Python import of COMPONENT,
418  *                          then a lib open of libCOMPONENTEngine.so
419  *  \return true if dlopen successfull or already done, false otherwise
420  */
421 //=============================================================================
422
423 bool
424 Engines_Container_i::load_component_Library(const char* componentName)
425 {
426
427   string aCompName = componentName;
428
429   // --- try dlopen C++ component
430
431 #ifndef WNT
432   string impl_name = string ("lib") + aCompName + string("Engine.so");
433 #else
434   string impl_name = aCompName + string("Engine.dll");
435 #endif
436   SCRUTE(impl_name);
437   
438   _numInstanceMutex.lock(); // lock to be alone 
439   // (see decInstanceCnt, finalize_removal))
440   if (_toRemove_map.count(impl_name) != 0) _toRemove_map.erase(impl_name);
441   if (_library_map.count(impl_name) != 0)
442     {
443       MESSAGE("Library " << impl_name << " already loaded");
444       _numInstanceMutex.unlock();
445       return true;
446     }
447   
448 #ifndef WNT
449   void* handle;
450   handle = dlopen( impl_name.c_str() , RTLD_LAZY ) ;
451 #else
452   HINSTANCE handle;
453   handle = LoadLibrary( impl_name.c_str() );
454 #endif
455
456   if ( handle )
457   {
458       _library_map[impl_name] = handle;
459       _numInstanceMutex.unlock();
460       return true;
461   }
462   _numInstanceMutex.unlock();
463
464   // --- try import Python component
465
466   INFOS("try import Python component "<<componentName);
467   if (_isSupervContainer)
468     {
469       INFOS("Supervision Container does not support Python Component Engines");
470       return false;
471     }
472   if (_library_map.count(aCompName) != 0)
473     {
474       return true; // Python Component, already imported
475     }
476   else
477     {
478       Py_ACQUIRE_NEW_THREAD;
479       PyObject *mainmod = PyImport_AddModule("__main__");
480       PyObject *globals = PyModule_GetDict(mainmod);
481       PyObject *pyCont = PyDict_GetItemString(globals, "pyCont");
482       PyObject *result = PyObject_CallMethod(pyCont,
483                                              "import_component",
484                                              "s",componentName);
485       int ret= PyInt_AsLong(result);
486       Py_XDECREF(result);
487       SCRUTE(ret);
488       Py_RELEASE_NEW_THREAD;
489   
490       if (ret) // import possible: Python component
491         {
492           _numInstanceMutex.lock() ; // lock to be alone (stl container write)
493           _library_map[aCompName] = (void *)pyCont; // any non O value OK
494           _numInstanceMutex.unlock() ;
495           MESSAGE("import Python: "<<aCompName<<" OK");
496           return true;
497         }
498     }
499   // Try to find an executable
500   std::string executable=aCompName+".exe";
501   char path[PATH_MAX+1];
502   if (findpathof(path, executable.c_str())) 
503     return true;
504
505   INFOS( "Impossible to load component: " << componentName );
506   INFOS( "Can't load shared library: " << impl_name );
507   INFOS( "Can't import Python module: " << componentName );
508   INFOS( "Can't execute program: " << executable );
509   return false;
510 }
511
512 //=============================================================================
513 /*! 
514  *  CORBA method: Creates a new servant instance of a component.
515  *  The servant registers itself to naming service and Registry.
516  *  \param genericRegisterName  Name of the component instance to register
517  *                         in Registry & Name Service (without _inst_n suffix)
518  *  \param studyId         0 for multiStudy instance, 
519  *                         study Id (>0) otherwise
520  *  \return a loaded component
521  */
522 //=============================================================================
523
524 Engines::Component_ptr
525 Engines_Container_i::create_component_instance(const char*genericRegisterName,
526                                                CORBA::Long studyId)
527 {
528   if (studyId < 0)
529     {
530       INFOS("studyId must be > 0 for mono study instance, =0 for multiStudy");
531       return Engines::Component::_nil() ;
532     }
533
534   Engines::Component_var iobject = Engines::Component::_nil() ;
535
536   string aCompName = genericRegisterName;
537   if (_library_map.count(aCompName) != 0) // Python component
538     {
539       if (_isSupervContainer)
540         {
541           INFOS("Supervision Container does not support Python Component Engines");
542           return Engines::Component::_nil();
543         }
544       _numInstanceMutex.lock() ; // lock on the instance number
545       _numInstance++ ;
546       int numInstance = _numInstance ;
547       _numInstanceMutex.unlock() ;
548
549       char aNumI[12];
550       sprintf( aNumI , "%d" , numInstance ) ;
551       string instanceName = aCompName + "_inst_" + aNumI ;
552       string component_registerName =
553         _containerName + "/" + instanceName;
554
555       Py_ACQUIRE_NEW_THREAD;
556       PyObject *mainmod = PyImport_AddModule("__main__");
557       PyObject *globals = PyModule_GetDict(mainmod);
558       PyObject *pyCont = PyDict_GetItemString(globals, "pyCont");
559       PyObject *result = PyObject_CallMethod(pyCont,
560                                              "create_component_instance",
561                                              "ssl",
562                                              aCompName.c_str(),
563                                              instanceName.c_str(),
564                                              studyId);
565       string iors = PyString_AsString(result);
566       Py_DECREF(result);
567       SCRUTE(iors);
568       Py_RELEASE_NEW_THREAD;
569   
570       if( iors!="" )
571       {
572         CORBA::Object_var obj = _orb->string_to_object(iors.c_str());
573         iobject = Engines::Component::_narrow( obj ) ;
574         _listInstances_map[instanceName] = iobject;
575       }
576       return iobject._retn();
577     }
578   
579   //--- try C++
580
581 #ifndef WNT
582   string impl_name = string ("lib") + genericRegisterName +string("Engine.so");
583 #else
584   string impl_name = genericRegisterName +string("Engine.dll");
585 #endif
586   if (_library_map.count(impl_name) != 0) // C++ component
587     {
588       void* handle = _library_map[impl_name];
589       iobject = createInstance(genericRegisterName,
590                                handle,
591                                studyId);
592       return iobject._retn();
593     }
594
595   // If it's not a Python or a C++ component try to launch a standalone component
596   // in a sub directory
597   // This component is implemented in an executable with name genericRegisterName.exe
598   // It must register itself in Naming Service. The container waits some time (10 s max)
599   // it's registration.
600
601   _numInstanceMutex.lock() ; // lock on the instance number
602   _numInstance++ ;
603   int numInstance = _numInstance ;
604   _numInstanceMutex.unlock() ;
605
606   char aNumI[12];
607   sprintf( aNumI , "%d" , numInstance ) ;
608   string instanceName = aCompName + "_inst_" + aNumI ;
609   string component_registerName = _containerName + "/" + instanceName;
610
611   //check if an entry exist in naming service
612   CORBA::Object_var nsobj = _NS->Resolve(component_registerName.c_str());
613   if ( !CORBA::is_nil(nsobj) )
614     {
615       // unregister the registered component
616       _NS->Destroy_Name(component_registerName.c_str());
617       //kill or shutdown it ???
618     }
619
620   // first arg container ior string
621   // second arg container name
622   // third arg instance name
623
624   Engines::Container_var pCont= _this();
625   CORBA::String_var sior =  _orb->object_to_string(pCont);
626
627   std::string command;
628   command="mkdir -p ";
629   command+=instanceName;
630   command+=";cd ";
631   command+=instanceName;
632   command+=";";
633   command+=genericRegisterName ;
634   command+=".exe";
635   command+=" ";
636   command+= sior; // container ior string
637   command+=" ";
638   command+=_containerName; //container name
639   command+=" ";
640   command+=instanceName; //instance name
641   command+=" &";
642   MESSAGE("SALOME_Container::create_component_instance command=" << command);
643   // launch component with a system call
644   int status=system(command.c_str());
645
646   if (status == -1)
647     {
648       MESSAGE("SALOME_Container::create_component_instance system failed " << "(system command status -1)");
649       return Engines::Component::_nil();
650     }
651   else if (WEXITSTATUS(status) == 217)
652     {
653       MESSAGE("SALOME_Container::create_component_instance system failed " << "(system command status 217)");
654       return Engines::Component::_nil();
655     }
656   else
657     {
658       int count=10;
659       CORBA::Object_var obj = CORBA::Object::_nil() ;
660       while ( CORBA::is_nil(obj) && count )
661         {
662 #ifndef WNT
663           sleep( 1 ) ;
664 #else
665           Sleep(1000);
666 #endif
667           count-- ;
668           MESSAGE( count << ". Waiting for component " << genericRegisterName);
669           obj = _NS->Resolve(component_registerName.c_str());
670         }
671
672       if(CORBA::is_nil(obj))
673         {
674           MESSAGE("SALOME_Container::create_component_instance failed");
675           return Engines::Component::_nil();
676         }
677       else
678         {
679           MESSAGE("SALOME_Container::create_component_instance successful");
680           iobject=Engines::Component::_narrow(obj);
681           return iobject._retn();
682         }
683     }
684 }
685
686 //=============================================================================
687 /*! 
688  *  CORBA method: Finds a servant instance of a component
689  *  \param registeredName  Name of the component in Registry or Name Service,
690  *                         without instance suffix number
691  *  \param studyId         0 if instance is not associated to a study, 
692  *                         >0 otherwise (== study id)
693  *  \return the first instance found with same studyId
694  */
695 //=============================================================================
696
697 Engines::Component_ptr
698 Engines_Container_i::find_component_instance( const char* registeredName,
699                                               CORBA::Long studyId)
700 {
701   Engines::Component_var anEngine = Engines::Component::_nil();
702   map<string,Engines::Component_var>::iterator itm =_listInstances_map.begin();
703   while (itm != _listInstances_map.end())
704     {
705       string instance = (*itm).first;
706       SCRUTE(instance);
707       if (instance.find(registeredName) == 0)
708         {
709           anEngine = (*itm).second;
710           if (studyId == anEngine->getStudyId())
711             {
712               return anEngine._retn();
713             }
714         }
715       itm++;
716     }
717   return anEngine._retn();  
718 }
719
720 //=============================================================================
721 /*! 
722  *  CORBA method: find or create an instance of the component (servant),
723  *  load a new component class (dynamic library) if required,
724  *  ---- FOR COMPATIBILITY WITH 2.2 ---- 
725  *  ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
726  *  The servant registers itself to naming service and Registry.
727  *  \param genericRegisterName  Name of the component to register
728  *                              in Registry & Name Service
729  *  \param componentName       Name of the constructed library of the component
730  *  \return a loaded component
731  */
732 //=============================================================================
733
734 Engines::Component_ptr
735 Engines_Container_i::load_impl( const char* genericRegisterName,
736                                 const char* componentName )
737 {
738   string impl_name = string ("lib") + genericRegisterName +string("Engine.so");
739   Engines::Component_var iobject = Engines::Component::_nil() ;
740   if (load_component_Library(genericRegisterName))
741     iobject = find_or_create_instance(genericRegisterName, impl_name);
742   return iobject._retn();
743 }
744     
745
746 //=============================================================================
747 /*! 
748  *  CORBA method: Stops the component servant, and deletes all related objects
749  *  \param component_i     Component to be removed
750  */
751 //=============================================================================
752
753 void Engines_Container_i::remove_impl(Engines::Component_ptr component_i)
754 {
755   ASSERT(! CORBA::is_nil(component_i));
756   string instanceName = component_i->instanceName() ;
757   MESSAGE("unload component " << instanceName);
758   _numInstanceMutex.lock() ; // lock to be alone (stl container write)
759   _listInstances_map.erase(instanceName);
760   _numInstanceMutex.unlock() ;
761   component_i->destroy() ;
762   _NS->Destroy_Name(instanceName.c_str());
763 }
764
765 //=============================================================================
766 /*! 
767  *  CORBA method: Discharges unused libraries from the container.
768  */
769 //=============================================================================
770
771 void Engines_Container_i::finalize_removal()
772 {
773   MESSAGE("finalize unload : dlclose");
774   _numInstanceMutex.lock(); // lock to be alone
775                             // (see decInstanceCnt, load_component_Library)
776   map<string, void *>::iterator ith;
777   for (ith = _toRemove_map.begin(); ith != _toRemove_map.end(); ith++)
778     {
779       void *handle = (*ith).second;
780       string impl_name= (*ith).first;
781       if (handle)
782         {
783           SCRUTE(handle);
784           SCRUTE(impl_name);
785 //        dlclose(handle);                // SALOME unstable after ...
786 //        _library_map.erase(impl_name);
787         }
788     }
789   _toRemove_map.clear();
790   _numInstanceMutex.unlock();
791 }
792
793 //=============================================================================
794 /*! 
795  *  CORBA method: Kill the container process with exit(0).
796  *  To remove :  never returns !
797  */
798 //=============================================================================
799
800 bool Engines_Container_i::Kill_impl()
801 {
802   MESSAGE("Engines_Container_i::Kill() pid "<< getpid() << " containerName "
803           << _containerName.c_str() << " machineName "
804           << GetHostname().c_str());
805   INFOS("===============================================================");
806   INFOS("= REMOVE calls to Kill_impl in C++ container                  =");
807   INFOS("===============================================================");
808   //exit( 0 ) ;
809   ASSERT(0);
810   return false;
811 }
812
813 //=============================================================================
814 /*! 
815  *  CORBA method: get or create a fileRef object associated to a local file
816  *  (a file on the computer on which runs the container server), which stores
817  *  a list of (machine, localFileName) corresponding to copies already done.
818  * 
819  *  \param  origFileName absolute path for a local file to copy on other
820  *          computers
821  *  \return a fileRef object associated to the file.
822  */
823 //=============================================================================
824
825 Engines::fileRef_ptr
826 Engines_Container_i::createFileRef(const char* origFileName)
827 {
828   string origName(origFileName);
829   Engines::fileRef_var theFileRef = Engines::fileRef::_nil();
830
831   if (origName[0] != '/')
832     {
833       INFOS("path of file to copy must be an absolute path begining with '/'");
834       return Engines::fileRef::_nil();
835     }
836
837   if (CORBA::is_nil(_fileRef_map[origName]))
838     {
839       CORBA::Object_var obj=_poa->id_to_reference(*_id);
840       Engines::Container_var pCont = Engines::Container::_narrow(obj);
841       fileRef_i* aFileRef = new fileRef_i(pCont, origFileName);
842       theFileRef = Engines::fileRef::_narrow(aFileRef->_this());
843       _numInstanceMutex.lock() ; // lock to be alone (stl container write)
844       _fileRef_map[origName] = theFileRef;
845       _numInstanceMutex.unlock() ;
846     }
847   
848   theFileRef =  Engines::fileRef::_duplicate(_fileRef_map[origName]);
849   ASSERT(! CORBA::is_nil(theFileRef));
850   return theFileRef._retn();
851 }
852
853 //=============================================================================
854 /*! 
855  *  CORBA method:
856  *  \return a reference to the fileTransfer object
857  */
858 //=============================================================================
859
860 Engines::fileTransfer_ptr
861 Engines_Container_i::getFileTransfer()
862 {
863   Engines::fileTransfer_var aFileTransfer
864     = Engines::fileTransfer::_duplicate(_fileTransfer);
865   return aFileTransfer._retn();
866 }
867
868
869 Engines::Salome_file_ptr 
870 Engines_Container_i::createSalome_file(const char* origFileName) 
871 {
872   string origName(origFileName);
873   if (CORBA::is_nil(_Salome_file_map[origName]))
874     {
875       Salome_file_i* aSalome_file = new Salome_file_i();
876       aSalome_file->setContainer(Engines::Container::_duplicate(this->_this()));
877       try 
878       {
879         aSalome_file->setLocalFile(origFileName);
880         aSalome_file->recvFiles();
881       }
882       catch (const SALOME::SALOME_Exception& e)
883       {
884         return Engines::Salome_file::_nil();
885       }
886
887       Engines::Salome_file_var theSalome_file = Engines::Salome_file::_nil();
888       theSalome_file = Engines::Salome_file::_narrow(aSalome_file->_this());
889       _numInstanceMutex.lock() ; // lock to be alone (stl container write)
890       _Salome_file_map[origName] = theSalome_file;
891       _numInstanceMutex.unlock() ;
892     }
893   
894   Engines::Salome_file_ptr theSalome_file =  
895     Engines::Salome_file::_duplicate(_Salome_file_map[origName]);
896   ASSERT(!CORBA::is_nil(theSalome_file));
897   return theSalome_file;
898 }
899 //=============================================================================
900 /*! 
901  *  C++ method: Finds an already existing servant instance of a component, or
902  *              create an instance.
903  *  ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
904  *  \param genericRegisterName    Name of the component instance to register
905  *                                in Registry & Name Service,
906  *                                (without _inst_n suffix, like "COMPONENT")
907  *  \param componentLibraryName   like "libCOMPONENTEngine.so"
908  *  \return a loaded component
909  * 
910  *  example with names:
911  *  aGenRegisterName = COMPONENT (= first argument)
912  *  impl_name = libCOMPONENTEngine.so (= second argument)
913  *  _containerName = /Containers/cli76ce/FactoryServer
914  *  factoryName = COMPONENTEngine_factory
915  *  component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
916  *
917  *  instanceName = COMPONENT_inst_1
918  *  component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
919  */
920 //=============================================================================
921
922 Engines::Component_ptr
923 Engines_Container_i::find_or_create_instance(string genericRegisterName,
924                                              string componentLibraryName)
925 {
926   string aGenRegisterName = genericRegisterName;
927   string impl_name = componentLibraryName;
928   if (_library_map.count(impl_name) == 0) 
929     {
930       INFOS("shared library " << impl_name <<" must be loaded before creating instance");
931       return Engines::Component::_nil() ;
932     }
933   else
934     {
935       // --- find a registered instance in naming service, or create
936
937       void* handle = _library_map[impl_name];
938       string component_registerBase =
939         _containerName + "/" + aGenRegisterName;
940       Engines::Component_var iobject = Engines::Component::_nil() ;
941       try
942         {
943           CORBA::Object_var obj =
944             _NS->ResolveFirst( component_registerBase.c_str());
945           if ( CORBA::is_nil( obj ) )
946             {
947               iobject = createInstance(genericRegisterName,
948                                        handle,
949                                        0); // force multiStudy instance here !
950             }
951           else
952             { 
953               iobject = Engines::Component::_narrow( obj ) ;
954               Engines_Component_i *servant =
955                 dynamic_cast<Engines_Component_i*>
956                 (_poa->reference_to_servant(iobject));
957               ASSERT(servant)
958               int studyId = servant->getStudyId();
959               ASSERT (studyId >= 0);
960               if (studyId == 0) // multiStudy instance, OK
961                 {
962                   // No ReBind !
963                   MESSAGE(component_registerBase.c_str()<<" already bound");
964                 }
965               else // monoStudy instance: NOK
966                 {
967                   iobject = Engines::Component::_nil();
968                   INFOS("load_impl & find_component_instance methods "
969                         << "NOT SUITABLE for mono study components");
970                 }
971             }
972         }
973       catch (...)
974         {
975           INFOS( "Container_i::load_impl catched" ) ;
976         }
977       return iobject._retn();
978     }
979 }
980
981 //=============================================================================
982 /*! 
983  *  C++ method: create a servant instance of a component.
984  *  \param genericRegisterName    Name of the component instance to register
985  *                                in Registry & Name Service,
986  *                                (without _inst_n suffix, like "COMPONENT")
987  *  \param handle                 loaded library handle
988  *  \param studyId                0 for multiStudy instance, 
989  *                                study Id (>0) otherwise
990  *  \return a loaded component
991  * 
992  *  example with names:
993  *  aGenRegisterName = COMPONENT (= first argument)
994  *  _containerName = /Containers/cli76ce/FactoryServer
995  *  factoryName = COMPONENTEngine_factory
996  *  component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
997  *  instanceName = COMPONENT_inst_1
998  *  component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
999  */
1000 //=============================================================================
1001
1002 Engines::Component_ptr
1003 Engines_Container_i::createInstance(string genericRegisterName,
1004                                     void *handle,
1005                                     int studyId)
1006 {
1007   // --- find the factory
1008
1009   string aGenRegisterName = genericRegisterName;
1010   string factory_name = aGenRegisterName + string("Engine_factory");
1011   SCRUTE(factory_name) ;
1012
1013   typedef  PortableServer::ObjectId * (*FACTORY_FUNCTION)
1014     (CORBA::ORB_ptr,
1015      PortableServer::POA_ptr, 
1016      PortableServer::ObjectId *, 
1017      const char *, 
1018      const char *) ;
1019
1020 #ifndef WNT
1021   FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)dlsym( handle, factory_name.c_str() );
1022 #else
1023   FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)GetProcAddress( (HINSTANCE)handle, factory_name.c_str() );
1024 #endif
1025
1026   if ( !Component_factory )
1027   {
1028       INFOS( "Can't resolve symbol: " + factory_name );
1029 #ifndef WNT
1030       SCRUTE( dlerror() );
1031 #endif
1032       return Engines::Component::_nil() ;
1033   }
1034
1035   // --- create instance
1036
1037   Engines::Component_var iobject = Engines::Component::_nil() ;
1038
1039   try
1040     {
1041       _numInstanceMutex.lock() ; // lock on the instance number
1042       _numInstance++ ;
1043       int numInstance = _numInstance ;
1044       _numInstanceMutex.unlock() ;
1045
1046       char aNumI[12];
1047       sprintf( aNumI , "%d" , numInstance ) ;
1048       string instanceName = aGenRegisterName + "_inst_" + aNumI ;
1049       string component_registerName =
1050         _containerName + "/" + instanceName;
1051
1052       // --- Instanciate required CORBA object
1053
1054       PortableServer::ObjectId *id ; //not owner, do not delete (nore use var)
1055       id = (Component_factory) ( _orb, _poa, _id, instanceName.c_str(),
1056                                  aGenRegisterName.c_str() ) ;
1057       if (id == NULL)
1058         return iobject._retn();
1059       
1060       // --- get reference & servant from id
1061
1062       CORBA::Object_var obj = _poa->id_to_reference(*id);
1063       iobject = Engines::Component::_narrow( obj ) ;
1064
1065       Engines_Component_i *servant =
1066         dynamic_cast<Engines_Component_i*>(_poa->reference_to_servant(iobject));
1067       ASSERT(servant);
1068       //SCRUTE(servant->pd_refCount);
1069       servant->_remove_ref(); // compensate previous id_to_reference 
1070       //SCRUTE(servant->pd_refCount);
1071       _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1072       _listInstances_map[instanceName] = iobject;
1073       _cntInstances_map[aGenRegisterName] += 1;
1074       _numInstanceMutex.unlock() ;
1075       SCRUTE(aGenRegisterName);
1076       SCRUTE(_cntInstances_map[aGenRegisterName]);
1077       //SCRUTE(servant->pd_refCount);
1078       bool ret_studyId = servant->setStudyId(studyId);
1079       ASSERT(ret_studyId);
1080
1081       // --- register the engine under the name
1082       //     containerName(.dir)/instanceName(.object)
1083
1084       _NS->Register( iobject , component_registerName.c_str() ) ;
1085       MESSAGE( component_registerName.c_str() << " bound" ) ;
1086     }
1087   catch (...)
1088     {
1089       INFOS( "Container_i::createInstance exception catched" ) ;
1090     }
1091   return iobject._retn();
1092 }
1093
1094 //=============================================================================
1095 /*! 
1096  *
1097  */
1098 //=============================================================================
1099
1100 void Engines_Container_i::decInstanceCnt(string genericRegisterName)
1101 {
1102   if(_cntInstances_map.count(genericRegisterName)==0)
1103     return;
1104   string aGenRegisterName =genericRegisterName;
1105   MESSAGE("Engines_Container_i::decInstanceCnt " << aGenRegisterName);
1106   ASSERT(_cntInstances_map[aGenRegisterName] > 0); 
1107   _numInstanceMutex.lock(); // lock to be alone
1108                             // (see finalize_removal, load_component_Library)
1109   _cntInstances_map[aGenRegisterName] -= 1;
1110   SCRUTE(_cntInstances_map[aGenRegisterName]);
1111   if (_cntInstances_map[aGenRegisterName] == 0)
1112     {
1113       string impl_name =
1114         Engines_Component_i::GetDynLibraryName(aGenRegisterName.c_str());
1115       SCRUTE(impl_name);
1116       void* handle = _library_map[impl_name];
1117       ASSERT(handle);
1118       _toRemove_map[impl_name] = handle;
1119     }
1120   _numInstanceMutex.unlock();
1121 }
1122
1123 //=============================================================================
1124 /*! 
1125  *  Retrieves only with container naming convention if it is a python container
1126  */
1127 //=============================================================================
1128
1129 bool Engines_Container_i::isPythonContainer(const char* ContainerName)
1130 {
1131   bool ret=false;
1132   int len=strlen(ContainerName);
1133   if(len>=2)
1134     if(strcmp(ContainerName+len-2,"Py")==0)
1135       ret=true;
1136   return ret;
1137 }
1138
1139 //=============================================================================
1140 /*! 
1141  *  
1142  */
1143 //=============================================================================
1144
1145 void ActSigIntHandler()
1146 {
1147 #ifndef WNT
1148   struct sigaction SigIntAct ;
1149   SigIntAct.sa_sigaction = &SigIntHandler ;
1150   SigIntAct.sa_flags = SA_SIGINFO ;
1151 #endif
1152
1153 // DEBUG 03.02.2005 : the first parameter of sigaction is not a mask of signals
1154 // (SIGINT | SIGUSR1) :
1155 // it must be only one signal ===> one call for SIGINT 
1156 // and an other one for SIGUSR1
1157
1158 #ifndef WNT
1159   if ( sigaction( SIGINT , &SigIntAct, NULL ) ) 
1160     {
1161       perror("SALOME_Container main ") ;
1162       exit(0) ;
1163     }
1164   if ( sigaction( SIGUSR1 , &SigIntAct, NULL ) )
1165     {
1166       perror("SALOME_Container main ") ;
1167       exit(0) ;
1168     }
1169   if ( sigaction( SIGUSR2 , &SigIntAct, NULL ) )
1170     {
1171       perror("SALOME_Container main ") ;
1172       exit(0) ;
1173     }
1174
1175   //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1176   //             use of streams (and so on) should never be used because :
1177   //             streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1178   //             A stream operation may be interrupted by a signal and if the Handler use stream we
1179   //             may have a "Dead-Lock" ===HangUp
1180   //==INFOS is commented
1181   //  INFOS(pthread_self() << "SigIntHandler activated") ;
1182
1183 #else  
1184   signal( SIGINT, SigIntHandler );
1185   signal( SIGUSR1, SigIntHandler );
1186 #endif
1187
1188 }
1189
1190 void SetCpuUsed() ;
1191 void CallCancelThread() ;
1192
1193 #ifndef WNT
1194 void SigIntHandler(int what ,
1195                    siginfo_t * siginfo ,
1196                    void * toto ) 
1197 {
1198   //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1199   //             use of streams (and so on) should never be used because :
1200   //             streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1201   //             A stream operation may be interrupted by a signal and if the Handler use stream we
1202   //             may have a "Dead-Lock" ===HangUp
1203   //==MESSAGE is commented
1204   //  MESSAGE(pthread_self() << "SigIntHandler what     " << what << endl
1205   //          << "              si_signo " << siginfo->si_signo << endl
1206   //          << "              si_code  " << siginfo->si_code << endl
1207   //          << "              si_pid   " << siginfo->si_pid) ;
1208
1209   if ( _Sleeping )
1210     {
1211       _Sleeping = false ;
1212       //     MESSAGE("SigIntHandler END sleeping.") ;
1213       return ;
1214     }
1215   else
1216     {
1217       ActSigIntHandler() ;
1218       if ( siginfo->si_signo == SIGUSR1 )
1219         {
1220           SetCpuUsed() ;
1221         }
1222       else if ( siginfo->si_signo == SIGUSR2 )
1223         {
1224           CallCancelThread() ;
1225         }
1226       else 
1227         {
1228           _Sleeping = true ;
1229           //      MESSAGE("SigIntHandler BEGIN sleeping.") ;
1230           int count = 0 ;
1231           while( _Sleeping )
1232             {
1233               sleep( 1 ) ;
1234               count += 1 ;
1235             }
1236           //      MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1237         }
1238       return ;
1239     }
1240 }
1241 #else // Case WNT
1242 void SigIntHandler( int what )
1243 {
1244 #ifndef WNT
1245   MESSAGE( pthread_self() << "SigIntHandler what     " << what << endl );
1246 #else
1247   MESSAGE( "SigIntHandler what     " << what << endl );
1248 #endif
1249   if ( _Sleeping )
1250     {
1251       _Sleeping = false ;
1252       MESSAGE("SigIntHandler END sleeping.") ;
1253       return ;
1254     }
1255   else
1256     {
1257       ActSigIntHandler() ;
1258       if ( what == SIGUSR1 )
1259         {
1260           SetCpuUsed() ;
1261         }
1262       else
1263         {
1264           _Sleeping = true ;
1265           MESSAGE("SigIntHandler BEGIN sleeping.") ;
1266           int count = 0 ;
1267           while( _Sleeping ) 
1268             {
1269               Sleep( 1000 ) ;
1270               count += 1 ;
1271             }
1272           MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1273         }
1274       return ;
1275     }
1276 }
1277 #endif