Salome HOME
CCAR: some corrections in :
[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=20;
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           _listInstances_map[instanceName] = iobject;
682           return iobject._retn();
683         }
684     }
685 }
686
687 //=============================================================================
688 /*! 
689  *  CORBA method: Finds a servant instance of a component
690  *  \param registeredName  Name of the component in Registry or Name Service,
691  *                         without instance suffix number
692  *  \param studyId         0 if instance is not associated to a study, 
693  *                         >0 otherwise (== study id)
694  *  \return the first instance found with same studyId
695  */
696 //=============================================================================
697
698 Engines::Component_ptr
699 Engines_Container_i::find_component_instance( const char* registeredName,
700                                               CORBA::Long studyId)
701 {
702   Engines::Component_var anEngine = Engines::Component::_nil();
703   map<string,Engines::Component_var>::iterator itm =_listInstances_map.begin();
704   while (itm != _listInstances_map.end())
705     {
706       string instance = (*itm).first;
707       SCRUTE(instance);
708       if (instance.find(registeredName) == 0)
709         {
710           anEngine = (*itm).second;
711           if (studyId == anEngine->getStudyId())
712             {
713               return anEngine._retn();
714             }
715         }
716       itm++;
717     }
718   return anEngine._retn();  
719 }
720
721 //=============================================================================
722 /*! 
723  *  CORBA method: find or create an instance of the component (servant),
724  *  load a new component class (dynamic library) if required,
725  *  ---- FOR COMPATIBILITY WITH 2.2 ---- 
726  *  ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
727  *  The servant registers itself to naming service and Registry.
728  *  \param genericRegisterName  Name of the component to register
729  *                              in Registry & Name Service
730  *  \param componentName       Name of the constructed library of the component
731  *  \return a loaded component
732  */
733 //=============================================================================
734
735 Engines::Component_ptr
736 Engines_Container_i::load_impl( const char* genericRegisterName,
737                                 const char* componentName )
738 {
739   string impl_name = string ("lib") + genericRegisterName +string("Engine.so");
740   Engines::Component_var iobject = Engines::Component::_nil() ;
741   if (load_component_Library(genericRegisterName))
742     iobject = find_or_create_instance(genericRegisterName, impl_name);
743   return iobject._retn();
744 }
745     
746
747 //=============================================================================
748 /*! 
749  *  CORBA method: Stops the component servant, and deletes all related objects
750  *  \param component_i     Component to be removed
751  */
752 //=============================================================================
753
754 void Engines_Container_i::remove_impl(Engines::Component_ptr component_i)
755 {
756   ASSERT(! CORBA::is_nil(component_i));
757   string instanceName = component_i->instanceName() ;
758   MESSAGE("unload component " << instanceName);
759   _numInstanceMutex.lock() ; // lock to be alone (stl container write)
760   _listInstances_map.erase(instanceName);
761   _numInstanceMutex.unlock() ;
762   component_i->destroy() ;
763   _NS->Destroy_Name(instanceName.c_str());
764 }
765
766 //=============================================================================
767 /*! 
768  *  CORBA method: Discharges unused libraries from the container.
769  */
770 //=============================================================================
771
772 void Engines_Container_i::finalize_removal()
773 {
774   MESSAGE("finalize unload : dlclose");
775   _numInstanceMutex.lock(); // lock to be alone
776                             // (see decInstanceCnt, load_component_Library)
777   map<string, void *>::iterator ith;
778   for (ith = _toRemove_map.begin(); ith != _toRemove_map.end(); ith++)
779     {
780       void *handle = (*ith).second;
781       string impl_name= (*ith).first;
782       if (handle)
783         {
784           SCRUTE(handle);
785           SCRUTE(impl_name);
786 //        dlclose(handle);                // SALOME unstable after ...
787 //        _library_map.erase(impl_name);
788         }
789     }
790   _toRemove_map.clear();
791   _numInstanceMutex.unlock();
792 }
793
794 //=============================================================================
795 /*! 
796  *  CORBA method: Kill the container process with exit(0).
797  *  To remove :  never returns !
798  */
799 //=============================================================================
800
801 bool Engines_Container_i::Kill_impl()
802 {
803   MESSAGE("Engines_Container_i::Kill() pid "<< getpid() << " containerName "
804           << _containerName.c_str() << " machineName "
805           << GetHostname().c_str());
806   INFOS("===============================================================");
807   INFOS("= REMOVE calls to Kill_impl in C++ container                  =");
808   INFOS("===============================================================");
809   //exit( 0 ) ;
810   ASSERT(0);
811   return false;
812 }
813
814 //=============================================================================
815 /*! 
816  *  CORBA method: get or create a fileRef object associated to a local file
817  *  (a file on the computer on which runs the container server), which stores
818  *  a list of (machine, localFileName) corresponding to copies already done.
819  * 
820  *  \param  origFileName absolute path for a local file to copy on other
821  *          computers
822  *  \return a fileRef object associated to the file.
823  */
824 //=============================================================================
825
826 Engines::fileRef_ptr
827 Engines_Container_i::createFileRef(const char* origFileName)
828 {
829   string origName(origFileName);
830   Engines::fileRef_var theFileRef = Engines::fileRef::_nil();
831
832   if (origName[0] != '/')
833     {
834       INFOS("path of file to copy must be an absolute path begining with '/'");
835       return Engines::fileRef::_nil();
836     }
837
838   if (CORBA::is_nil(_fileRef_map[origName]))
839     {
840       CORBA::Object_var obj=_poa->id_to_reference(*_id);
841       Engines::Container_var pCont = Engines::Container::_narrow(obj);
842       fileRef_i* aFileRef = new fileRef_i(pCont, origFileName);
843       theFileRef = Engines::fileRef::_narrow(aFileRef->_this());
844       _numInstanceMutex.lock() ; // lock to be alone (stl container write)
845       _fileRef_map[origName] = theFileRef;
846       _numInstanceMutex.unlock() ;
847     }
848   
849   theFileRef =  Engines::fileRef::_duplicate(_fileRef_map[origName]);
850   ASSERT(! CORBA::is_nil(theFileRef));
851   return theFileRef._retn();
852 }
853
854 //=============================================================================
855 /*! 
856  *  CORBA method:
857  *  \return a reference to the fileTransfer object
858  */
859 //=============================================================================
860
861 Engines::fileTransfer_ptr
862 Engines_Container_i::getFileTransfer()
863 {
864   Engines::fileTransfer_var aFileTransfer
865     = Engines::fileTransfer::_duplicate(_fileTransfer);
866   return aFileTransfer._retn();
867 }
868
869
870 Engines::Salome_file_ptr 
871 Engines_Container_i::createSalome_file(const char* origFileName) 
872 {
873   string origName(origFileName);
874   if (CORBA::is_nil(_Salome_file_map[origName]))
875     {
876       Salome_file_i* aSalome_file = new Salome_file_i();
877       aSalome_file->setContainer(Engines::Container::_duplicate(this->_this()));
878       try 
879       {
880         aSalome_file->setLocalFile(origFileName);
881         aSalome_file->recvFiles();
882       }
883       catch (const SALOME::SALOME_Exception& e)
884       {
885         return Engines::Salome_file::_nil();
886       }
887
888       Engines::Salome_file_var theSalome_file = Engines::Salome_file::_nil();
889       theSalome_file = Engines::Salome_file::_narrow(aSalome_file->_this());
890       _numInstanceMutex.lock() ; // lock to be alone (stl container write)
891       _Salome_file_map[origName] = theSalome_file;
892       _numInstanceMutex.unlock() ;
893     }
894   
895   Engines::Salome_file_ptr theSalome_file =  
896     Engines::Salome_file::_duplicate(_Salome_file_map[origName]);
897   ASSERT(!CORBA::is_nil(theSalome_file));
898   return theSalome_file;
899 }
900 //=============================================================================
901 /*! 
902  *  C++ method: Finds an already existing servant instance of a component, or
903  *              create an instance.
904  *  ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
905  *  \param genericRegisterName    Name of the component instance to register
906  *                                in Registry & Name Service,
907  *                                (without _inst_n suffix, like "COMPONENT")
908  *  \param componentLibraryName   like "libCOMPONENTEngine.so"
909  *  \return a loaded component
910  * 
911  *  example with names:
912  *  aGenRegisterName = COMPONENT (= first argument)
913  *  impl_name = libCOMPONENTEngine.so (= second argument)
914  *  _containerName = /Containers/cli76ce/FactoryServer
915  *  factoryName = COMPONENTEngine_factory
916  *  component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
917  *
918  *  instanceName = COMPONENT_inst_1
919  *  component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
920  */
921 //=============================================================================
922
923 Engines::Component_ptr
924 Engines_Container_i::find_or_create_instance(string genericRegisterName,
925                                              string componentLibraryName)
926 {
927   string aGenRegisterName = genericRegisterName;
928   string impl_name = componentLibraryName;
929   if (_library_map.count(impl_name) == 0) 
930     {
931       INFOS("shared library " << impl_name <<" must be loaded before creating instance");
932       return Engines::Component::_nil() ;
933     }
934   else
935     {
936       // --- find a registered instance in naming service, or create
937
938       void* handle = _library_map[impl_name];
939       string component_registerBase =
940         _containerName + "/" + aGenRegisterName;
941       Engines::Component_var iobject = Engines::Component::_nil() ;
942       try
943         {
944           CORBA::Object_var obj =
945             _NS->ResolveFirst( component_registerBase.c_str());
946           if ( CORBA::is_nil( obj ) )
947             {
948               iobject = createInstance(genericRegisterName,
949                                        handle,
950                                        0); // force multiStudy instance here !
951             }
952           else
953             { 
954               iobject = Engines::Component::_narrow( obj ) ;
955               Engines_Component_i *servant =
956                 dynamic_cast<Engines_Component_i*>
957                 (_poa->reference_to_servant(iobject));
958               ASSERT(servant)
959               int studyId = servant->getStudyId();
960               ASSERT (studyId >= 0);
961               if (studyId == 0) // multiStudy instance, OK
962                 {
963                   // No ReBind !
964                   MESSAGE(component_registerBase.c_str()<<" already bound");
965                 }
966               else // monoStudy instance: NOK
967                 {
968                   iobject = Engines::Component::_nil();
969                   INFOS("load_impl & find_component_instance methods "
970                         << "NOT SUITABLE for mono study components");
971                 }
972             }
973         }
974       catch (...)
975         {
976           INFOS( "Container_i::load_impl catched" ) ;
977         }
978       return iobject._retn();
979     }
980 }
981
982 //=============================================================================
983 /*! 
984  *  C++ method: create a servant instance of a component.
985  *  \param genericRegisterName    Name of the component instance to register
986  *                                in Registry & Name Service,
987  *                                (without _inst_n suffix, like "COMPONENT")
988  *  \param handle                 loaded library handle
989  *  \param studyId                0 for multiStudy instance, 
990  *                                study Id (>0) otherwise
991  *  \return a loaded component
992  * 
993  *  example with names:
994  *  aGenRegisterName = COMPONENT (= first argument)
995  *  _containerName = /Containers/cli76ce/FactoryServer
996  *  factoryName = COMPONENTEngine_factory
997  *  component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
998  *  instanceName = COMPONENT_inst_1
999  *  component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1000  */
1001 //=============================================================================
1002
1003 Engines::Component_ptr
1004 Engines_Container_i::createInstance(string genericRegisterName,
1005                                     void *handle,
1006                                     int studyId)
1007 {
1008   // --- find the factory
1009
1010   string aGenRegisterName = genericRegisterName;
1011   string factory_name = aGenRegisterName + string("Engine_factory");
1012   SCRUTE(factory_name) ;
1013
1014   typedef  PortableServer::ObjectId * (*FACTORY_FUNCTION)
1015     (CORBA::ORB_ptr,
1016      PortableServer::POA_ptr, 
1017      PortableServer::ObjectId *, 
1018      const char *, 
1019      const char *) ;
1020
1021 #ifndef WNT
1022   FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)dlsym( handle, factory_name.c_str() );
1023 #else
1024   FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)GetProcAddress( (HINSTANCE)handle, factory_name.c_str() );
1025 #endif
1026
1027   if ( !Component_factory )
1028   {
1029       INFOS( "Can't resolve symbol: " + factory_name );
1030 #ifndef WNT
1031       SCRUTE( dlerror() );
1032 #endif
1033       return Engines::Component::_nil() ;
1034   }
1035
1036   // --- create instance
1037
1038   Engines::Component_var iobject = Engines::Component::_nil() ;
1039
1040   try
1041     {
1042       _numInstanceMutex.lock() ; // lock on the instance number
1043       _numInstance++ ;
1044       int numInstance = _numInstance ;
1045       _numInstanceMutex.unlock() ;
1046
1047       char aNumI[12];
1048       sprintf( aNumI , "%d" , numInstance ) ;
1049       string instanceName = aGenRegisterName + "_inst_" + aNumI ;
1050       string component_registerName =
1051         _containerName + "/" + instanceName;
1052
1053       // --- Instanciate required CORBA object
1054
1055       PortableServer::ObjectId *id ; //not owner, do not delete (nore use var)
1056       id = (Component_factory) ( _orb, _poa, _id, instanceName.c_str(),
1057                                  aGenRegisterName.c_str() ) ;
1058       if (id == NULL)
1059         return iobject._retn();
1060       
1061       // --- get reference & servant from id
1062
1063       CORBA::Object_var obj = _poa->id_to_reference(*id);
1064       iobject = Engines::Component::_narrow( obj ) ;
1065
1066       Engines_Component_i *servant =
1067         dynamic_cast<Engines_Component_i*>(_poa->reference_to_servant(iobject));
1068       ASSERT(servant);
1069       //SCRUTE(servant->pd_refCount);
1070       servant->_remove_ref(); // compensate previous id_to_reference 
1071       //SCRUTE(servant->pd_refCount);
1072       _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1073       _listInstances_map[instanceName] = iobject;
1074       _cntInstances_map[aGenRegisterName] += 1;
1075       _numInstanceMutex.unlock() ;
1076       SCRUTE(aGenRegisterName);
1077       SCRUTE(_cntInstances_map[aGenRegisterName]);
1078       //SCRUTE(servant->pd_refCount);
1079       bool ret_studyId = servant->setStudyId(studyId);
1080       ASSERT(ret_studyId);
1081
1082       // --- register the engine under the name
1083       //     containerName(.dir)/instanceName(.object)
1084
1085       _NS->Register( iobject , component_registerName.c_str() ) ;
1086       MESSAGE( component_registerName.c_str() << " bound" ) ;
1087     }
1088   catch (...)
1089     {
1090       INFOS( "Container_i::createInstance exception catched" ) ;
1091     }
1092   return iobject._retn();
1093 }
1094
1095 //=============================================================================
1096 /*! 
1097  *
1098  */
1099 //=============================================================================
1100
1101 void Engines_Container_i::decInstanceCnt(string genericRegisterName)
1102 {
1103   if(_cntInstances_map.count(genericRegisterName)==0)
1104     return;
1105   string aGenRegisterName =genericRegisterName;
1106   MESSAGE("Engines_Container_i::decInstanceCnt " << aGenRegisterName);
1107   ASSERT(_cntInstances_map[aGenRegisterName] > 0); 
1108   _numInstanceMutex.lock(); // lock to be alone
1109                             // (see finalize_removal, load_component_Library)
1110   _cntInstances_map[aGenRegisterName] -= 1;
1111   SCRUTE(_cntInstances_map[aGenRegisterName]);
1112   if (_cntInstances_map[aGenRegisterName] == 0)
1113     {
1114       string impl_name =
1115         Engines_Component_i::GetDynLibraryName(aGenRegisterName.c_str());
1116       SCRUTE(impl_name);
1117       void* handle = _library_map[impl_name];
1118       ASSERT(handle);
1119       _toRemove_map[impl_name] = handle;
1120     }
1121   _numInstanceMutex.unlock();
1122 }
1123
1124 //=============================================================================
1125 /*! 
1126  *  Retrieves only with container naming convention if it is a python container
1127  */
1128 //=============================================================================
1129
1130 bool Engines_Container_i::isPythonContainer(const char* ContainerName)
1131 {
1132   bool ret=false;
1133   int len=strlen(ContainerName);
1134   if(len>=2)
1135     if(strcmp(ContainerName+len-2,"Py")==0)
1136       ret=true;
1137   return ret;
1138 }
1139
1140 //=============================================================================
1141 /*! 
1142  *  
1143  */
1144 //=============================================================================
1145
1146 void ActSigIntHandler()
1147 {
1148 #ifndef WNT
1149   struct sigaction SigIntAct ;
1150   SigIntAct.sa_sigaction = &SigIntHandler ;
1151   SigIntAct.sa_flags = SA_SIGINFO ;
1152 #endif
1153
1154 // DEBUG 03.02.2005 : the first parameter of sigaction is not a mask of signals
1155 // (SIGINT | SIGUSR1) :
1156 // it must be only one signal ===> one call for SIGINT 
1157 // and an other one for SIGUSR1
1158
1159 #ifndef WNT
1160   if ( sigaction( SIGINT , &SigIntAct, NULL ) ) 
1161     {
1162       perror("SALOME_Container main ") ;
1163       exit(0) ;
1164     }
1165   if ( sigaction( SIGUSR1 , &SigIntAct, NULL ) )
1166     {
1167       perror("SALOME_Container main ") ;
1168       exit(0) ;
1169     }
1170   if ( sigaction( SIGUSR2 , &SigIntAct, NULL ) )
1171     {
1172       perror("SALOME_Container main ") ;
1173       exit(0) ;
1174     }
1175
1176   //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1177   //             use of streams (and so on) should never be used because :
1178   //             streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1179   //             A stream operation may be interrupted by a signal and if the Handler use stream we
1180   //             may have a "Dead-Lock" ===HangUp
1181   //==INFOS is commented
1182   //  INFOS(pthread_self() << "SigIntHandler activated") ;
1183
1184 #else  
1185   signal( SIGINT, SigIntHandler );
1186   signal( SIGUSR1, SigIntHandler );
1187 #endif
1188
1189 }
1190
1191 void SetCpuUsed() ;
1192 void CallCancelThread() ;
1193
1194 #ifndef WNT
1195 void SigIntHandler(int what ,
1196                    siginfo_t * siginfo ,
1197                    void * toto ) 
1198 {
1199   //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1200   //             use of streams (and so on) should never be used because :
1201   //             streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1202   //             A stream operation may be interrupted by a signal and if the Handler use stream we
1203   //             may have a "Dead-Lock" ===HangUp
1204   //==MESSAGE is commented
1205   //  MESSAGE(pthread_self() << "SigIntHandler what     " << what << endl
1206   //          << "              si_signo " << siginfo->si_signo << endl
1207   //          << "              si_code  " << siginfo->si_code << endl
1208   //          << "              si_pid   " << siginfo->si_pid) ;
1209
1210   if ( _Sleeping )
1211     {
1212       _Sleeping = false ;
1213       //     MESSAGE("SigIntHandler END sleeping.") ;
1214       return ;
1215     }
1216   else
1217     {
1218       ActSigIntHandler() ;
1219       if ( siginfo->si_signo == SIGUSR1 )
1220         {
1221           SetCpuUsed() ;
1222         }
1223       else if ( siginfo->si_signo == SIGUSR2 )
1224         {
1225           CallCancelThread() ;
1226         }
1227       else 
1228         {
1229           _Sleeping = true ;
1230           //      MESSAGE("SigIntHandler BEGIN sleeping.") ;
1231           int count = 0 ;
1232           while( _Sleeping )
1233             {
1234               sleep( 1 ) ;
1235               count += 1 ;
1236             }
1237           //      MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1238         }
1239       return ;
1240     }
1241 }
1242 #else // Case WNT
1243 void SigIntHandler( int what )
1244 {
1245 #ifndef WNT
1246   MESSAGE( pthread_self() << "SigIntHandler what     " << what << endl );
1247 #else
1248   MESSAGE( "SigIntHandler what     " << what << endl );
1249 #endif
1250   if ( _Sleeping )
1251     {
1252       _Sleeping = false ;
1253       MESSAGE("SigIntHandler END sleeping.") ;
1254       return ;
1255     }
1256   else
1257     {
1258       ActSigIntHandler() ;
1259       if ( what == SIGUSR1 )
1260         {
1261           SetCpuUsed() ;
1262         }
1263       else
1264         {
1265           _Sleeping = true ;
1266           MESSAGE("SigIntHandler BEGIN sleeping.") ;
1267           int count = 0 ;
1268           while( _Sleeping ) 
1269             {
1270               Sleep( 1000 ) ;
1271               count += 1 ;
1272             }
1273           MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1274         }
1275       return ;
1276     }
1277 }
1278 #endif