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