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