Salome HOME
390b4740eb4a308fbf85bdef856b93bb32058686
[modules/kernel.git] / src / Container / Container_i.cxx
1 // Copyright (C) 2007-2014  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, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 //  SALOME Container : implementation of container and engine for Kernel
24 //  File   : Container_i.cxx
25 //  Author : Paul RASCLE, EDF - MARC TAJCHMAN, CEA 
26 //  Module : SALOME
27 //  $Header$
28 //#define private public
29 //
30 #include <string.h>
31 #include <stdio.h>
32 #include <time.h>
33 #include <sys/types.h>
34 #ifndef WIN32
35 #include <sys/time.h>
36 #include <dlfcn.h>
37 #include <unistd.h>
38 #include <sys/wait.h>
39 #else
40 #include <signal.h>
41 #include <process.h>
42 #include <direct.h>
43 int SIGUSR1 = 1000;
44 #endif
45
46 #include "utilities.h"
47 #include <SALOMEconfig.h>
48 #include CORBA_SERVER_HEADER(SALOME_Component)
49 #include CORBA_SERVER_HEADER(SALOME_Exception)
50 #include <pthread.h>  // must be before Python.h !
51 #include "SALOME_Container_i.hxx"
52 #include "SALOME_Component_i.hxx"
53 #include "SALOME_FileRef_i.hxx"
54 #include "SALOME_FileTransfer_i.hxx"
55 #include "Salome_file_i.hxx"
56 #include "SALOME_NamingService.hxx"
57 #include "Basics_Utils.hxx"
58
59 #ifdef _XOPEN_SOURCE
60 #undef _XOPEN_SOURCE
61 #endif
62
63 #include <Python.h>
64 #include "Container_init_python.hxx"
65
66 bool _Sleeping = false ;
67
68 // // Needed by multi-threaded Python --- Supervision
69 int _ArgC ;
70 char ** _ArgV ;
71
72 extern "C" {void ActSigIntHandler() ; }
73 #ifndef WIN32
74 extern "C" {void SigIntHandler(int, siginfo_t *, void *) ; }
75 #else
76 extern "C" {void SigIntHandler( int ) ; }
77 #endif
78
79 #ifndef WIN32
80 #define LIB "lib"
81 #define ENGINESO "Engine.so"
82 #else
83 #define LIB ""
84 #define ENGINESO "Engine.dll"
85 #endif
86
87 #ifdef WIN32
88 #define SEP ';'
89 #define SLASH '\\'
90 #else
91 #define SEP ':'
92 #define SLASH '/'
93 #endif
94
95 std::map<std::string, int> Engines_Container_i::_cntInstances_map;
96 std::map<std::string, void *> Engines_Container_i::_library_map;
97 std::map<std::string, void *> Engines_Container_i::_toRemove_map;
98 omni_mutex Engines_Container_i::_numInstanceMutex ;
99
100 static PyObject* _pyCont;
101
102 int checkifexecutable(const std::string&);
103 int findpathof(const std::string& path, std::string&, const std::string&);
104
105 /*! \class Engines_Container_i
106  *  \brief C++ implementation of Engines::Container interface
107  *
108  */
109
110
111 //=============================================================================
112 /*! 
113 *  Default constructor, not for use
114 */
115 //=============================================================================
116
117 Engines_Container_i::Engines_Container_i () :
118 _numInstance(0),_id(0),_NS(0)
119 {
120 }
121
122 //=============================================================================
123 /*! 
124 *  Construtor to use
125 */
126 //=============================================================================
127
128 Engines_Container_i::Engines_Container_i (CORBA::ORB_ptr orb, 
129                                           PortableServer::POA_ptr poa,
130                                           char *containerName ,
131                                           int argc , char* argv[],
132                                           bool activAndRegist,
133                                           bool isServantAloneInProcess
134                                           ) :
135   _numInstance(0),_isServantAloneInProcess(isServantAloneInProcess),_id(0),_NS(0)
136 {
137   _pid = (long)getpid();
138
139   if(activAndRegist)
140     ActSigIntHandler() ;
141
142   _argc = argc ;
143   _argv = argv ;
144
145   std::string hostname = Kernel_Utils::GetHostname();
146 #ifndef WIN32
147   MESSAGE(hostname << " " << getpid() << 
148     " Engines_Container_i starting argc " <<
149     _argc << " Thread " << pthread_self() ) ;
150 #else
151   MESSAGE(hostname << " " << _getpid() << 
152     " Engines_Container_i starting argc " << _argc<< " Thread " << pthread_self().p ) ;
153 #endif
154
155   int i = 0 ;
156   while ( _argv[ i ] )
157   {
158     MESSAGE("           argv" << i << " " << _argv[ i ]) ;
159     i++ ;
160   }
161
162   if ( argc < 2 )
163   {
164     INFOS("SALOME_Container usage : SALOME_Container ServerName");
165     ASSERT(0) ;
166   }
167   SCRUTE(argv[1]);
168   _isSupervContainer = false;
169
170   _orb = CORBA::ORB::_duplicate(orb) ;
171   _poa = PortableServer::POA::_duplicate(poa) ;
172
173   // Pour les containers paralleles: il ne faut pas enregistrer et activer
174   // le container generique, mais le container specialise
175
176   if(activAndRegist)
177   {
178     _id = _poa->activate_object(this);
179     _NS = new SALOME_NamingService();
180     _NS->init_orb( _orb ) ;
181     CORBA::Object_var obj=_poa->id_to_reference(*_id);
182     Engines::Container_var pCont 
183       = Engines::Container::_narrow(obj);
184     _remove_ref();
185
186     _containerName = _NS->BuildContainerNameForNS(containerName,
187       hostname.c_str());
188     SCRUTE(_containerName);
189     _NS->Register(pCont, _containerName.c_str());
190     MESSAGE("Engines_Container_i::Engines_Container_i : Container name "
191       << _containerName);
192
193     // Python: 
194     // import SALOME_Container
195     // pycont = SALOME_Container.SALOME_Container_i(containerIORStr)
196
197     CORBA::String_var sior =  _orb->object_to_string(pCont);
198     std::string myCommand="pyCont = SALOME_Container.SALOME_Container_i('";
199     myCommand += _containerName + "','";
200     myCommand += sior;
201     myCommand += "')\n";
202     SCRUTE(myCommand);
203
204     // [ABN]: using the PyGILState* API here is unstable. omniORB logic is invoked
205     // by the Python code executed below, and in some (random) cases, the Python code
206     // execution ends with a PyThreadState which was not the one we have here.
207     // (TODO: understand why ...)
208     // To be on the safe side we get and load the thread state ourselves:
209     //PyGILState_STATE gstate = PyGILState_Ensure();
210     PyEval_AcquireLock();  // get GIL
211     PyThreadState * mainThreadState = PyThreadState_Get();
212     PyThreadState_Swap(mainThreadState);
213
214 #ifdef WIN32
215     // mpv: this is temporary solution: there is a unregular crash if not
216     //Sleep(2000);
217     //
218     // first element is the path to Registry.dll, but it's wrong
219     PyRun_SimpleString("import sys\n");
220     PyRun_SimpleString("sys.path = sys.path[1:]\n");
221 #endif
222     PyRun_SimpleString("import SALOME_Container\n");
223     PyRun_SimpleString((char*)myCommand.c_str());
224     PyObject *mainmod = PyImport_AddModule("__main__");
225     PyObject *globals = PyModule_GetDict(mainmod);
226     _pyCont = PyDict_GetItemString(globals, "pyCont");
227
228     PyThreadState_Swap(NULL);
229     PyEval_ReleaseLock();
230     //PyGILState_Release(gstate);
231
232     fileTransfer_i* aFileTransfer = new fileTransfer_i();
233     CORBA::Object_var obref=aFileTransfer->_this();
234     _fileTransfer = Engines::fileTransfer::_narrow(obref);
235     aFileTransfer->_remove_ref();
236   }
237 }
238
239 //=============================================================================
240 /*! 
241 *  Destructor
242 */
243 //=============================================================================
244
245 Engines_Container_i::~Engines_Container_i()
246 {
247   MESSAGE("Container_i::~Container_i()");
248   if(_id)
249     delete _id;
250   if(_NS)
251     delete _NS;
252 }
253
254 //=============================================================================
255 //! Get container name
256 /*! 
257 *  CORBA attribute: Container name (see constructor)
258 */
259 //=============================================================================
260
261 char* Engines_Container_i::name()
262 {
263   return CORBA::string_dup(_containerName.c_str()) ;
264 }
265
266 //=============================================================================
267 //! Get container working directory
268 /*! 
269 *  CORBA attribute: Container working directory 
270 */
271 //=============================================================================
272
273 char* Engines_Container_i::workingdir()
274 {
275   char wd[256];
276   getcwd (wd,256);
277   return CORBA::string_dup(wd) ;
278 }
279
280 //=============================================================================
281 //! Get container log file name
282 /*! 
283 *  CORBA attribute: Container log file name
284 */
285 //=============================================================================
286
287 char* Engines_Container_i::logfilename()
288 {
289   return CORBA::string_dup(_logfilename.c_str()) ;
290 }
291
292 //! Set container log file name
293 void Engines_Container_i::logfilename(const char* name)
294 {
295   _logfilename=name;
296 }
297
298 //=============================================================================
299 //! Get container host name
300 /*! 
301 *  CORBA method: Get the hostName of the Container (without domain extensions)
302 */
303 //=============================================================================
304
305 char* Engines_Container_i::getHostName()
306 {
307   std::string s = Kernel_Utils::GetHostname();
308   //  MESSAGE("Engines_Container_i::getHostName " << s);
309   return CORBA::string_dup(s.c_str()) ;
310 }
311
312 //=============================================================================
313 //! Get container PID
314 /*! 
315 *  CORBA method: Get the PID (process identification) of the Container
316 */
317 //=============================================================================
318
319 CORBA::Long Engines_Container_i::getPID()
320 {
321   return (CORBA::Long)getpid();
322 }
323
324 //=============================================================================
325 //! Ping the servant to check it is still alive
326 /*! 
327 *  CORBA method: check if servant is still alive
328 */
329 //=============================================================================
330 void Engines_Container_i::ping()
331 {
332   MESSAGE("Engines_Container_i::ping() pid "<< getpid());
333 }
334
335 //=============================================================================
336 //! Shutdown the container
337 /*! 
338 *  CORBA method, oneway: Server shutdown. 
339 *  - Container name removed from naming service,
340 *  - servant deactivation,
341 *  - orb shutdown if no other servants in the process 
342 */
343 //=============================================================================
344 void Engines_Container_i::Shutdown()
345 {
346   MESSAGE("Engines_Container_i::Shutdown()");
347
348   // Clear registered temporary files
349   clearTemporaryFiles();
350
351   /* For each component contained in this container
352   * tell it to self-destroy
353   */
354   std::map<std::string, Engines::EngineComponent_var>::iterator itm;
355   for (itm = _listInstances_map.begin(); itm != _listInstances_map.end(); itm++)
356     {
357       try
358         {
359           itm->second->destroy();
360         }
361       catch(const CORBA::Exception& e)
362         {
363           // ignore this entry and continue
364         }
365       catch(...)
366         {
367           // ignore this entry and continue
368         }
369     }
370   _listInstances_map.clear();
371
372   _NS->Destroy_FullDirectory(_containerName.c_str());
373   _NS->Destroy_Name(_containerName.c_str());
374   if(_isServantAloneInProcess)
375   {
376     MESSAGE("Effective Shutdown of container Begins...");
377     if(!CORBA::is_nil(_orb))
378       _orb->shutdown(0);
379   }
380 }
381
382 //=============================================================================
383 //! load a component implementation
384 /*! 
385 *  CORBA method
386 *  \param componentName         component name
387 *  \param reason                explains error when load fails
388 *  \return true if dlopen successfull or already done, false otherwise
389 */
390 //=============================================================================
391 bool
392 Engines_Container_i::load_component_Library(const char* componentName, CORBA::String_out reason)
393 {
394
395   //=================================================================
396   // --- C++ implementation section 
397   //=================================================================
398   std::string retso;
399   if(load_component_CppImplementation(componentName,retso))
400     {
401       reason=CORBA::string_dup("");
402       return true;
403     }
404   else if(retso != "ImplementationNotFound")
405     {
406       reason=CORBA::string_dup(retso.c_str());
407       return false;
408     }
409
410   retso="Component ";
411   retso+=componentName;
412   retso+=": Can't find C++ implementation ";
413   retso+=std::string(LIB) + componentName + ENGINESO;
414
415   //=================================================================
416   // --- Python implementation section 
417   //=================================================================
418   std::string retpy;
419   if(load_component_PythonImplementation(componentName,retpy))
420     {
421       reason=CORBA::string_dup("");
422       return true;
423     }
424   else if(retpy != "ImplementationNotFound")
425     {
426       reason=CORBA::string_dup(retpy.c_str());
427       return false;
428     }
429   
430   retpy="Component ";
431   retpy+=componentName;
432   retpy+=": Can't find python implementation ";
433   retpy+=componentName;
434   retpy+="(.py)";
435
436   //=================================================================
437   // -- Executable implementation section
438   //=================================================================
439   std::string retex;
440   if(load_component_ExecutableImplementation(componentName,retex))
441     {
442       reason=CORBA::string_dup("");
443       return true;
444     }
445   else if(retex != "ImplementationNotFound")
446     {
447       reason=CORBA::string_dup(retex.c_str());
448       return false;
449     }
450
451   retex="Component ";
452   retex+=componentName;
453   retex+=": Can't find executable implementation ";
454   retex+=componentName;
455   retex+=".exe";
456
457   std::string ret="Component implementation not found: ";
458   ret += componentName ;
459   ret += '\n' ;
460   ret += retso+ '\n' ;
461   ret += retpy+ '\n' ;
462   ret += retex+ '\n' ;
463
464   std::cerr << ret << std::endl;
465   reason=CORBA::string_dup(ret.c_str());
466
467   return false;
468 }
469
470 //=============================================================================
471 //! try to load a C++ component implementation
472 /*! 
473 *  C++ method: 
474 *  \param componentName      the name of the component (COMPONENT, for example)
475 *  \param reason             explains error when load fails
476 *  \return true if loading is successfull or already done, false otherwise
477 */
478 //=============================================================================
479 bool
480 Engines_Container_i::load_component_CppImplementation(const char* componentName, std::string& reason)
481 {
482   std::string aCompName(componentName);
483   std::string impl_name = std::string(LIB) + aCompName + ENGINESO;
484   SCRUTE(impl_name);
485
486   _numInstanceMutex.lock(); // lock to be alone
487   // (see decInstanceCnt, finalize_removal))
488   if (_toRemove_map.count(impl_name) != 0) _toRemove_map.erase(impl_name);
489   if (_library_map.count(impl_name) != 0)
490     {
491       MESSAGE("Library " << impl_name << " already loaded");
492       _numInstanceMutex.unlock();
493       reason="";
494       return true;
495     }
496   _numInstanceMutex.unlock();
497
498 #ifndef WIN32
499   void* handle;
500   handle = dlopen( impl_name.c_str() , RTLD_NOW ) ;
501   if ( !handle )
502     {
503       //not loadable. Try to find the lib file in LD_LIBRARY_PATH
504       std::string path;
505       char* p=getenv("LD_LIBRARY_PATH");
506       if(p)path=p;
507       path=path+SEP+"/usr/lib"+SEP+"/lib";
508
509       std::string pth;
510       if(findpathof(path, pth, impl_name))
511         {
512           //found but not loadable
513           reason="Component ";
514           reason+=aCompName;
515           reason+=": C++ implementation found ";
516           reason+=pth;
517           reason+=" but it is not loadable. Error:\n";
518           reason+=dlerror();
519           std::cerr << reason << std::endl;
520           return false;
521         }
522       else
523         {
524           //not found
525           //continue with other implementation
526           reason="ImplementationNotFound";
527           return false;
528         }
529     }
530 #else
531   HINSTANCE handle;
532   handle = LoadLibrary( impl_name.c_str() );
533   if ( !handle )
534     {
535       reason="ImplementationNotFound";
536     }
537 #endif
538
539   if ( handle )
540     {
541       _numInstanceMutex.lock();
542       _library_map[impl_name] = handle;
543       _numInstanceMutex.unlock();
544       reason="";
545       return true;
546     }
547
548   return false;
549
550 }
551 //=============================================================================
552 //! try to load a Python component implementation
553 /*! 
554 *  C++ method: 
555 *  \param componentName         name of the component
556 *  \param reason                explains error when load fails
557 *  \return true if loading is successfull or already done, false otherwise
558 */
559 //=============================================================================
560 bool
561 Engines_Container_i::load_component_PythonImplementation(const char* componentName, std::string& reason)
562 {
563   std::string aCompName(componentName);
564
565   _numInstanceMutex.lock() ; // lock to be alone (stl container write)
566   if (_library_map.count(aCompName) != 0)
567     {
568       _numInstanceMutex.unlock() ;
569       reason="";
570       return true; // Python Component, already imported
571     }
572   _numInstanceMutex.unlock() ;
573
574   PyGILState_STATE gstate = PyGILState_Ensure();
575   PyObject *result = PyObject_CallMethod(_pyCont,
576                                          (char*)"import_component",
577                                          (char*)"s",componentName);
578
579   reason=PyString_AsString(result);
580   Py_XDECREF(result);
581   SCRUTE(reason);
582   PyGILState_Release(gstate);
583
584   if (reason=="")
585     {
586       //Python component has been loaded (import componentName)
587       _numInstanceMutex.lock() ; // lock to be alone (stl container write)
588       _library_map[aCompName] = (void *)_pyCont; // any non O value OK
589       _numInstanceMutex.unlock() ;
590       MESSAGE("import Python: "<< aCompName <<" OK");
591       return true;
592     }
593   else if(reason=="ImplementationNotFound")
594     {
595       //Python implementation has not been found. Continue with other implementation
596       reason="ImplementationNotFound";
597     }
598   else
599     {
600       //Python implementation has been found but loading has failed
601       std::cerr << reason << std::endl;
602     }
603   return false;
604
605 }
606 //=============================================================================
607 //! try to load a Executable component implementation
608 /*! 
609 *  C++ method: 
610 *  \param componentName        name of the component
611 *  \param reason               explains error when load fails
612 *  \return true if loading is successfull or already done, false otherwise
613 */
614 //=============================================================================
615 bool
616 Engines_Container_i::load_component_ExecutableImplementation(const char* componentName, std::string& reason)
617 {
618   std::string aCompName(componentName);
619   std::string executable=aCompName+".exe";
620
621   std::string path;
622   std::string pth;
623
624   char* p=getenv("PATH");
625   if(p)path=p;
626
627   if (findpathof(path, pth, executable))
628     {
629       if(checkifexecutable(pth))
630         {
631           _numInstanceMutex.lock() ; // lock to be alone (stl container write)
632           _library_map[executable] = (void *)1; // any non O value OK
633           _numInstanceMutex.unlock() ;
634           MESSAGE("import executable: "<< pth <<" OK");
635           reason="";
636           return true;
637         }
638       reason="Component ";
639       reason+=aCompName;
640       reason+=": implementation found ";
641       reason+=pth;
642       reason+=" but it is not executable";
643       std::cerr << reason << std::endl;
644     }
645   else
646     {
647       reason="ImplementationNotFound";
648     }
649   return false;
650 }
651
652 //=============================================================================
653 //! Create a new component instance
654 /*! 
655 *  CORBA method: Creates a new servant instance of a component.
656 *  The servant registers itself to naming service and Registry.
657 *  \param genericRegisterName  Name of the component instance to register
658 *                         in Registry & Name Service (without _inst_n suffix)
659 *  \param studyId         0 for multiStudy instance, 
660 *                         study Id (>0) otherwise
661 *  \return a loaded component
662 */
663 //=============================================================================
664 Engines::EngineComponent_ptr
665 Engines_Container_i::create_component_instance(const char*genericRegisterName,
666                                                CORBA::Long studyId)
667 {
668   Engines::FieldsDict_var env = new Engines::FieldsDict;
669   char* reason;
670   Engines::EngineComponent_ptr compo =
671     create_component_instance_env(genericRegisterName, studyId, env, reason);
672   CORBA::string_free(reason);
673   return compo;
674 }
675
676 //=============================================================================
677 //! Create a new component instance with environment variables specified
678 /*! 
679 *  CORBA method: Creates a new servant instance of a component.
680 *  The servant registers itself to naming service and Registry.
681 *  \param genericRegisterName  Name of the component instance to register
682 *                         in Registry & Name Service (without _inst_n suffix)
683 *  \param studyId         0 for multiStudy instance, 
684 *                         study Id (>0) otherwise
685 *  \param env             dict of env variables
686 *  \param reason          explains error when create_component_instance_env fails
687 *  \return a loaded component
688 */
689 //=============================================================================
690 Engines::EngineComponent_ptr
691 Engines_Container_i::create_component_instance_env(const char*genericRegisterName,
692                                                    CORBA::Long studyId,
693                                                    const Engines::FieldsDict& env,
694                                                    CORBA::String_out reason)
695 {
696   if (studyId < 0)
697     {
698       INFOS("studyId must be > 0 for mono study instance, =0 for multiStudy");
699       reason=CORBA::string_dup("studyId must be > 0 for mono study instance, =0 for multiStudy");
700       return Engines::EngineComponent::_nil() ;
701     }
702
703   std::string error;
704   if (_library_map.count(genericRegisterName) != 0)
705     {
706       // It's a Python component
707       Engines::EngineComponent_ptr compo = createPythonInstance(genericRegisterName, studyId, error);
708       reason=CORBA::string_dup(error.c_str());
709       return compo;
710     }
711
712   std::string impl_name = std::string(LIB) + genericRegisterName + ENGINESO;
713   if (_library_map.count(impl_name) != 0)
714     {
715       // It's a C++ component
716       void* handle = _library_map[impl_name];
717       Engines::EngineComponent_ptr compo = createInstance(genericRegisterName, handle, studyId, error);
718       reason=CORBA::string_dup(error.c_str());
719       return compo;
720     }
721
722   impl_name = std::string(genericRegisterName) + ".exe";
723   if (_library_map.count(impl_name) != 0)
724     {
725       //It's an executable component
726       Engines::EngineComponent_ptr compo = createExecutableInstance(genericRegisterName, studyId, env, error);
727       reason=CORBA::string_dup(error.c_str());
728       return compo;
729     }
730
731   error="load_component_Library has probably not been called for component: ";
732   error += genericRegisterName;
733   INFOS(error);
734   reason=CORBA::string_dup(error.c_str());
735   return Engines::EngineComponent::_nil() ;
736 }
737
738 //=============================================================================
739 //! Create a new component instance (Executable implementation)
740 /*! 
741 *  \param CompName               Name of the component instance
742 *  \param studyId                0 for multiStudy instance, 
743 *                                study Id (>0) otherwise
744 *  \param env                    dict of env variables
745 *  \param reason                 explains error when creation fails
746 *  \return a loaded component
747 *
748 *   This component is implemented in an executable with name genericRegisterName.exe
749 *   It must register itself in Naming Service. The container waits some time (10 s max)
750 *   it's registration.
751 */
752 //=============================================================================
753 Engines::EngineComponent_ptr
754 Engines_Container_i::createExecutableInstance(std::string CompName, int studyId,
755                                               const Engines::FieldsDict& env,
756                                               std::string& reason)
757 {
758   Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
759
760   _numInstanceMutex.lock() ; // lock on the instance number
761   _numInstance++ ;
762   int numInstance = _numInstance ;
763   _numInstanceMutex.unlock() ;
764
765   char aNumI[12];
766   sprintf( aNumI , "%d" , numInstance ) ;
767   std::string instanceName = CompName + "_inst_" + aNumI ;
768   std::string component_registerName = _containerName + "/" + instanceName;
769
770   //check if an entry exist in naming service
771   CORBA::Object_var nsobj = _NS->Resolve(component_registerName.c_str());
772   if ( !CORBA::is_nil(nsobj) )
773   {
774     // unregister the registered component
775     _NS->Destroy_Name(component_registerName.c_str());
776     //kill or shutdown it ???
777   }
778
779   // first arg container ior string
780   // second arg container name
781   // third arg instance name
782
783   Engines::Container_var pCont= _this();
784   CORBA::String_var sior =  _orb->object_to_string(pCont);
785
786   std::string command;
787   command="mkdir -p ";
788   command+=instanceName;
789   command+=";cd ";
790   command+=instanceName;
791   command+=";";
792   command+=CompName ;
793   command+=".exe";
794   command+=" ";
795   command+= sior; // container ior string
796   command+=" ";
797   command+=_containerName; //container name
798   command+=" ";
799   command+=instanceName; //instance name
800   command+=" &";
801   MESSAGE("SALOME_Container::create_component_instance command=" << command);
802
803 #ifndef WIN32
804   // use fork/execl instead of system to get finer control on env variables
805   int status;
806   pid_t pid = fork();
807   if(pid == 0) // child
808     {
809       for (CORBA::ULong i=0; i < env.length(); i++)
810         {
811           if (env[i].value.type()->kind() == CORBA::tk_string)
812             {
813               const char* value;
814               env[i].value >>= value;
815               std::string s(env[i].key);
816               s+='=';
817               s+=value;
818               putenv(strdup(s.c_str()));
819             }
820         }
821
822       execl("/bin/sh", "sh", "-c", command.c_str() , (char *)0);
823       status=-1;
824     }
825   else if(pid < 0)       // failed to fork
826     {
827       status=-1;
828     }
829   else            //parent
830     {
831       pid_t tpid;
832       do
833         {
834           tpid = wait(&status);
835         } while (tpid != pid);
836     }
837 #else
838   // launch component with a system call
839   int status=system(command.c_str());
840 #endif
841
842   if (status == -1)
843   {
844     reason="SALOME_Container::create_component_instance system failed (system command status -1)";
845     MESSAGE(reason);
846     return Engines::EngineComponent::_nil();
847   }
848 #ifndef WIN32
849   else if (WEXITSTATUS(status) == 217)
850   {
851     reason="SALOME_Container::create_component_instance system failed (system command status 217)";
852     MESSAGE(reason);
853     return Engines::EngineComponent::_nil();
854   }
855 #endif
856   else
857   {
858     int count=20;
859     if (getenv("TIMEOUT_TO_WAIT_EXE_COMPONENT") != 0)
860     {
861       std::string new_count_str = getenv("TIMEOUT_TO_WAIT_EXE_COMPONENT");
862       int new_count;
863       std::istringstream ss(new_count_str);
864       if (!(ss >> new_count))
865       {
866         INFOS("[Container] TIMEOUT_TO_WAIT_EXE_COMPONENT should be an int");
867       }
868       else
869         count = new_count;
870     }
871     INFOS("[Container] waiting " << count << " second steps exe component ");
872     CORBA::Object_var obj = CORBA::Object::_nil() ;
873     while ( CORBA::is_nil(obj) && count )
874     {
875 #ifndef WIN32
876       sleep( 1 ) ;
877 #else
878       Sleep(1000);
879 #endif
880       count-- ;
881       MESSAGE( count << ". Waiting for component " << CompName);
882       obj = _NS->Resolve(component_registerName.c_str());
883     }
884
885     if(CORBA::is_nil(obj))
886     {
887       reason="SALOME_Container::create_component_instance failed";
888       MESSAGE(reason);
889       return Engines::EngineComponent::_nil();
890     }
891     else
892     {
893       MESSAGE("SALOME_Container::create_component_instance successful");
894       iobject = Engines::EngineComponent::_narrow(obj);
895       _listInstances_map[instanceName] = iobject;
896       return iobject._retn();
897     }
898   }
899 }
900
901
902 //=============================================================================
903 //! Create a new component instance (Python implementation)
904 /*! 
905 *  \param CompName               Name of the component instance
906 *  \param studyId                0 for multiStudy instance, 
907 *                                study Id (>0) otherwise
908 *  \param reason                 explains error when creation fails
909 *  \return a loaded component
910 */
911 //=============================================================================
912 Engines::EngineComponent_ptr
913 Engines_Container_i::createPythonInstance(std::string CompName, int studyId,
914                                           std::string& reason)
915 {
916   Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
917
918   _numInstanceMutex.lock() ; // lock on the instance number
919   _numInstance++ ;
920   int numInstance = _numInstance ;
921   _numInstanceMutex.unlock() ;
922
923   char aNumI[12];
924   sprintf( aNumI , "%d" , numInstance ) ;
925   std::string instanceName = CompName + "_inst_" + aNumI ;
926   std::string component_registerName = _containerName + "/" + instanceName;
927
928   PyGILState_STATE gstate = PyGILState_Ensure();
929   PyObject *result = PyObject_CallMethod(_pyCont,
930                                          (char*)"create_component_instance",
931                                          (char*)"ssl",
932                                          CompName.c_str(),
933                                          instanceName.c_str(),
934                                          studyId);
935   const char *ior;
936   const char *error;
937   PyArg_ParseTuple(result,"ss", &ior, &error);
938   std::string iors = ior;
939   reason=error;
940   Py_DECREF(result);
941   PyGILState_Release(gstate);
942
943   if( iors!="" )
944     {
945       CORBA::Object_var obj = _orb->string_to_object(iors.c_str());
946       iobject = Engines::EngineComponent::_narrow( obj ) ;
947       _listInstances_map[instanceName] = iobject;
948     }
949   return iobject._retn();
950 }
951
952 //=============================================================================
953 //! Create a new component instance (C++ implementation)
954 /*! 
955 *  C++ method: create a servant instance of a component.
956 *  \param genericRegisterName    Name of the component instance to register
957 *                                in Registry & Name Service,
958 *                                (without _inst_n suffix, like "COMPONENT")
959 *  \param handle                 loaded library handle
960 *  \param studyId                0 for multiStudy instance, 
961 *                                study Id (>0) otherwise
962 *  \param reason                 explains error when creation fails
963 *  \return a loaded component
964
965 *  example with names:
966 *    - aGenRegisterName = COMPONENT (= first argument)
967 *    - _containerName = /Containers/cli76ce/FactoryServer
968 *    - factoryName = COMPONENTEngine_factory
969 *    - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
970 *    - instanceName = COMPONENT_inst_1
971 *    - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
972 */
973 //=============================================================================
974 Engines::EngineComponent_ptr
975 Engines_Container_i::createInstance(std::string genericRegisterName,
976                                     void *handle,
977                                     int studyId,
978                                     std::string& reason)
979 {
980   // --- find the factory
981
982   std::string aGenRegisterName = genericRegisterName;
983   std::string factory_name = aGenRegisterName + std::string("Engine_factory");
984   SCRUTE(factory_name) ;
985
986   typedef PortableServer::ObjectId* (*FACTORY_FUNCTION) (CORBA::ORB_ptr,
987                                                          PortableServer::POA_ptr, 
988                                                          PortableServer::ObjectId *, 
989                                                          const char *, 
990                                                          const char *) ;
991
992 #ifndef WIN32
993   FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)dlsym( handle, factory_name.c_str() );
994 #else
995   FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)GetProcAddress( (HINSTANCE)handle, factory_name.c_str() );
996 #endif
997
998   if ( !Component_factory )
999   {
1000     INFOS( "Can't resolve symbol: " + factory_name );
1001 #ifndef WIN32
1002     reason=dlerror();
1003     INFOS(reason);
1004 #endif
1005     return Engines::EngineComponent::_nil() ;
1006   }
1007
1008   // --- create instance
1009
1010   Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1011
1012   try
1013   {
1014     _numInstanceMutex.lock() ; // lock on the instance number
1015     _numInstance++ ;
1016     int numInstance = _numInstance ;
1017     _numInstanceMutex.unlock() ;
1018
1019     char aNumI[12];
1020     sprintf( aNumI , "%d" , numInstance ) ;
1021     std::string instanceName = aGenRegisterName + "_inst_" + aNumI ;
1022     std::string component_registerName =
1023       _containerName + "/" + instanceName;
1024
1025     // --- Instanciate required CORBA object
1026
1027     PortableServer::ObjectId *id ; //not owner, do not delete (nore use var)
1028     id = (Component_factory) ( _orb, _poa, _id, instanceName.c_str(),
1029                                                 aGenRegisterName.c_str() ) ;
1030     if (id == NULL)
1031       {
1032         reason="Can't get ObjectId from factory";
1033         INFOS(reason);
1034         return iobject._retn();
1035       }
1036
1037     // --- get reference & servant from id
1038
1039     CORBA::Object_var obj = _poa->id_to_reference(*id);
1040     iobject = Engines::EngineComponent::_narrow( obj ) ;
1041
1042     Engines_Component_i *servant =
1043       dynamic_cast<Engines_Component_i*>(_poa->reference_to_servant(iobject));
1044     ASSERT(servant);
1045     //SCRUTE(servant->_refcount_value());
1046     _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1047     _listInstances_map[instanceName] = iobject;
1048     _cntInstances_map[aGenRegisterName] += 1;
1049     _numInstanceMutex.unlock() ;
1050     SCRUTE(aGenRegisterName);
1051     SCRUTE(_cntInstances_map[aGenRegisterName]);
1052     servant->setStudyId(studyId);
1053     servant->_remove_ref(); // do not need servant any more (remove ref from reference_to_servant)
1054     //SCRUTE(servant->_refcount_value());
1055
1056     // --- register the engine under the name
1057     //     containerName(.dir)/instanceName(.object)
1058
1059     _NS->Register( iobject , component_registerName.c_str() ) ;
1060     MESSAGE( component_registerName.c_str() << " bound" ) ;
1061   }
1062   catch (...)
1063   {
1064     reason="Container_i::createInstance exception catched";
1065     INFOS(reason) ;
1066   }
1067   return iobject._retn();
1068 }
1069
1070 //=============================================================================
1071 //! Find an existing (in the container) component instance
1072 /*!
1073 *  CORBA method: Finds a servant instance of a component
1074 *  \param registeredName  Name of the component in Registry or Name Service,
1075 *                         without instance suffix number
1076 *  \param studyId         0 if instance is not associated to a study,
1077 *                         >0 otherwise (== study id)
1078 *  \return the first instance found with same studyId
1079 */
1080 //=============================================================================
1081 Engines::EngineComponent_ptr
1082 Engines_Container_i::find_component_instance( const char* registeredName,
1083                                               CORBA::Long studyId)
1084 {
1085   Engines::EngineComponent_var anEngine = Engines::EngineComponent::_nil();
1086   std::map<std::string,Engines::EngineComponent_var>::iterator itm =_listInstances_map.begin();
1087   while (itm != _listInstances_map.end())
1088   {
1089     std::string instance = (*itm).first;
1090     SCRUTE(instance);
1091     if (instance.find(registeredName) == 0)
1092     {
1093       anEngine = (*itm).second;
1094       if (studyId == anEngine->getStudyId())
1095       {
1096         return anEngine._retn();
1097       }
1098     }
1099     itm++;
1100   }
1101   return anEngine._retn();
1102 }
1103
1104 //=============================================================================
1105 //! Remove the component instance from container
1106 /*!
1107 *  CORBA method: Stops the component servant, and deletes all related objects
1108 *  \param component_i     Component to be removed
1109 */
1110 //=============================================================================
1111
1112 void Engines_Container_i::remove_impl(Engines::EngineComponent_ptr component_i)
1113 {
1114   ASSERT(! CORBA::is_nil(component_i));
1115   std::string instanceName = component_i->instanceName() ;
1116   MESSAGE("unload component " << instanceName);
1117   _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1118   _listInstances_map.erase(instanceName);
1119   _numInstanceMutex.unlock() ;
1120   component_i->destroy() ;
1121   _NS->Destroy_Name(instanceName.c_str());
1122 }
1123
1124 //=============================================================================
1125 //! Unload component libraries from the container
1126 /*!
1127 *  CORBA method: Discharges unused libraries from the container.
1128 */
1129 //=============================================================================
1130 void Engines_Container_i::finalize_removal()
1131 {
1132   MESSAGE("finalize unload : dlclose");
1133   _numInstanceMutex.lock(); // lock to be alone
1134   // (see decInstanceCnt, load_component_Library)
1135   std::map<std::string, void *>::iterator ith;
1136   for (ith = _toRemove_map.begin(); ith != _toRemove_map.end(); ith++)
1137   {
1138     void *handle = (*ith).second;
1139     std::string impl_name= (*ith).first;
1140     if (handle)
1141     {
1142       SCRUTE(handle);
1143       SCRUTE(impl_name);
1144       //        dlclose(handle);                // SALOME unstable after ...
1145       //        _library_map.erase(impl_name);
1146     }
1147   }
1148   _toRemove_map.clear();
1149   _numInstanceMutex.unlock();
1150 }
1151
1152 //=============================================================================
1153 //! Decrement component instance reference count
1154 /*!
1155 *
1156 */
1157 //=============================================================================
1158 void Engines_Container_i::decInstanceCnt(std::string genericRegisterName)
1159 {
1160   if(_cntInstances_map.count(genericRegisterName)==0)
1161     return;
1162   std::string aGenRegisterName =genericRegisterName;
1163   MESSAGE("Engines_Container_i::decInstanceCnt " << aGenRegisterName);
1164   ASSERT(_cntInstances_map[aGenRegisterName] > 0);
1165   _numInstanceMutex.lock(); // lock to be alone
1166   // (see finalize_removal, load_component_Library)
1167   _cntInstances_map[aGenRegisterName] -= 1;
1168   SCRUTE(_cntInstances_map[aGenRegisterName]);
1169   if (_cntInstances_map[aGenRegisterName] == 0)
1170   {
1171     std::string impl_name =
1172       Engines_Component_i::GetDynLibraryName(aGenRegisterName.c_str());
1173     SCRUTE(impl_name);
1174     void* handle = _library_map[impl_name];
1175     ASSERT(handle);
1176     _toRemove_map[impl_name] = handle;
1177   }
1178   _numInstanceMutex.unlock();
1179 }
1180
1181 //=============================================================================
1182 //! Find or create a new component instance
1183 /*!
1184 *  CORBA method: find or create an instance of the component (servant),
1185 *  load a new component class (dynamic library) if required,
1186 *
1187 *  ---- FOR COMPATIBILITY WITH 2.2 ----
1188 *
1189 *  ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
1190 *
1191 *  The servant registers itself to naming service and Registry.
1192 *  \param genericRegisterName  Name of the component to register
1193 *                              in Registry & Name Service
1194 *  \param componentName       Name of the constructed library of the component
1195 *  \return a loaded component
1196 */
1197 //=============================================================================
1198
1199 Engines::EngineComponent_ptr
1200 Engines_Container_i::load_impl( const char* genericRegisterName,
1201                                 const char* componentName )
1202 {
1203   char* reason;
1204   std::string impl_name = std::string(LIB) + genericRegisterName + ENGINESO;
1205   Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1206   if (load_component_Library(genericRegisterName,reason))
1207     iobject = find_or_create_instance(genericRegisterName, impl_name);
1208   CORBA::string_free(reason);
1209   return iobject._retn();
1210 }
1211
1212 //=============================================================================
1213 //! Finds an already existing component instance or create a new instance
1214 /*!
1215 *  C++ method: Finds an already existing servant instance of a component, or
1216 *              create an instance.
1217 *  ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
1218 *  \param genericRegisterName    Name of the component instance to register
1219 *                                in Registry & Name Service,
1220 *                                (without _inst_n suffix, like "COMPONENT")
1221 *  \param componentLibraryName   like "libCOMPONENTEngine.so"
1222 *  \return a loaded component
1223 *
1224 *  example with names:
1225 *    - aGenRegisterName = COMPONENT (= first argument)
1226 *    - impl_name = libCOMPONENTEngine.so (= second argument)
1227 *    - _containerName = /Containers/cli76ce/FactoryServer
1228 *    - factoryName = COMPONENTEngine_factory
1229 *    - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
1230 *    - instanceName = COMPONENT_inst_1
1231 *    - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1232 */
1233 //=============================================================================
1234
1235 Engines::EngineComponent_ptr
1236 Engines_Container_i::find_or_create_instance(std::string genericRegisterName,
1237                                              std::string componentLibraryName)
1238 {
1239   std::string aGenRegisterName = genericRegisterName;
1240   std::string impl_name = componentLibraryName;
1241   if (_library_map.count(impl_name) == 0)
1242   {
1243     INFOS("shared library " << impl_name <<" must be loaded before creating instance");
1244     return Engines::EngineComponent::_nil() ;
1245   }
1246   else
1247   {
1248     // --- find a registered instance in naming service, or create
1249
1250     void* handle = _library_map[impl_name];
1251     std::string component_registerBase =
1252       _containerName + "/" + aGenRegisterName;
1253     Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1254     std::string reason;
1255     try
1256     {
1257       CORBA::Object_var obj =
1258         _NS->ResolveFirst( component_registerBase.c_str());
1259       if ( CORBA::is_nil( obj ) )
1260       {
1261         iobject = createInstance(genericRegisterName,
1262                                  handle,
1263                                  0,
1264                                  reason); // force multiStudy instance here !
1265       }
1266       else
1267       {
1268         iobject = Engines::EngineComponent::_narrow( obj ) ;
1269         Engines_Component_i *servant =
1270           dynamic_cast<Engines_Component_i*>
1271           (_poa->reference_to_servant(iobject));
1272         ASSERT(servant)
1273           int studyId = servant->getStudyId();
1274         ASSERT (studyId >= 0);
1275         if (studyId == 0) // multiStudy instance, OK
1276         {
1277           // No ReBind !
1278           MESSAGE(component_registerBase.c_str()<<" already bound");
1279         }
1280         else // monoStudy instance: NOK
1281         {
1282           iobject = Engines::EngineComponent::_nil();
1283           INFOS("load_impl & find_component_instance methods "
1284             << "NOT SUITABLE for mono study components");
1285         }
1286       }
1287     }
1288     catch (...)
1289     {
1290       INFOS( "Container_i::load_impl catched" ) ;
1291     }
1292     return iobject._retn();
1293   }
1294 }
1295
1296 //=============================================================================
1297 //! Indicate if container is a python one
1298 /*! 
1299 *  Retrieves only with container naming convention if it is a python container
1300 */
1301 //=============================================================================
1302 bool Engines_Container_i::isPythonContainer(const char* ContainerName)
1303 {
1304   bool ret=false;
1305   int len=strlen(ContainerName);
1306   if(len>=2)
1307     if(strcmp(ContainerName+len-2,"Py")==0)
1308       ret=true;
1309   return ret;
1310 }
1311
1312 //=============================================================================
1313 //! Kill the container
1314 /*!
1315 *  CORBA method: Kill the container process with exit(0).
1316 *  To remove :  never returns !
1317 */
1318 //=============================================================================
1319 bool Engines_Container_i::Kill_impl()
1320 {
1321   MESSAGE("Engines_Container_i::Kill() pid "<< getpid() << " containerName "
1322     << _containerName.c_str() << " machineName "
1323     << Kernel_Utils::GetHostname().c_str());
1324   INFOS("===============================================================");
1325   INFOS("= REMOVE calls to Kill_impl in C++ container                  =");
1326   INFOS("===============================================================");
1327   //_exit( 0 ) ;
1328   ASSERT(0);
1329   return false;
1330 }
1331
1332 //=============================================================================
1333 /*! 
1334 *  
1335 */
1336 //=============================================================================
1337 void ActSigIntHandler()
1338 {
1339 #ifndef WIN32
1340   struct sigaction SigIntAct ;
1341   SigIntAct.sa_sigaction = &SigIntHandler ;
1342   sigemptyset(&SigIntAct.sa_mask);
1343   SigIntAct.sa_flags = SA_SIGINFO ;
1344 #endif
1345
1346   // DEBUG 03.02.2005 : the first parameter of sigaction is not a mask of signals
1347   // (SIGINT | SIGUSR1) :
1348   // it must be only one signal ===> one call for SIGINT 
1349   // and an other one for SIGUSR1
1350
1351 #ifndef WIN32
1352   if ( sigaction( SIGINT , &SigIntAct, NULL ) ) 
1353   {
1354     perror("SALOME_Container main ") ;
1355     exit(0) ;
1356   }
1357   if ( sigaction( SIGUSR1 , &SigIntAct, NULL ) )
1358   {
1359     perror("SALOME_Container main ") ;
1360     exit(0) ;
1361   }
1362   if ( sigaction( SIGUSR2 , &SigIntAct, NULL ) )
1363   {
1364     perror("SALOME_Container main ") ;
1365     exit(0) ;
1366   }
1367
1368   //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1369   //             use of streams (and so on) should never be used because :
1370   //             streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1371   //             A stream operation may be interrupted by a signal and if the Handler use stream we
1372   //             may have a "Dead-Lock" ===HangUp
1373   //==INFOS is commented
1374   //  INFOS(pthread_self() << "SigIntHandler activated") ;
1375
1376 #else  
1377   signal( SIGINT, SigIntHandler );
1378 // legacy code required to supervisor. Commented in order to avoid problems on Windows 
1379 //  signal( SIGUSR1, SigIntHandler );
1380 #endif
1381
1382 }
1383
1384 void SetCpuUsed() ;
1385 void CallCancelThread() ;
1386
1387 #ifndef WIN32
1388 void SigIntHandler(int what ,
1389                    siginfo_t * siginfo ,
1390                    void * toto ) 
1391 {
1392   //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1393   //             use of streams (and so on) should never be used because :
1394   //             streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1395   //             A stream operation may be interrupted by a signal and if the Handler use stream we
1396   //             may have a "Dead-Lock" ===HangUp
1397   //==MESSAGE is commented
1398   //  MESSAGE(pthread_self() << "SigIntHandler what     " << what << std::endl
1399   //          << "              si_signo " << siginfo->si_signo << std::endl
1400   //          << "              si_code  " << siginfo->si_code << std::endl
1401   //          << "              si_pid   " << siginfo->si_pid) ;
1402
1403   if ( _Sleeping )
1404   {
1405     _Sleeping = false ;
1406     //     MESSAGE("SigIntHandler END sleeping.") ;
1407     return ;
1408   }
1409   else
1410   {
1411     ActSigIntHandler() ;
1412     if ( siginfo->si_signo == SIGUSR1 )
1413     {
1414       SetCpuUsed() ;
1415     }
1416     else if ( siginfo->si_signo == SIGUSR2 )
1417     {
1418       CallCancelThread() ;
1419     }
1420     else 
1421     {
1422       _Sleeping = true ;
1423       //      MESSAGE("SigIntHandler BEGIN sleeping.") ;
1424       int count = 0 ;
1425       while( _Sleeping )
1426       {
1427         sleep( 1 ) ;
1428         count += 1 ;
1429       }
1430       //      MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1431     }
1432     return ;
1433   }
1434 }
1435 #else // Case WIN32
1436 void SigIntHandler( int what )
1437 {
1438 #ifndef WIN32
1439   MESSAGE( pthread_self() << "SigIntHandler what     " << what << std::endl );
1440 #else
1441   MESSAGE( "SigIntHandler what     " << what << std::endl );
1442 #endif
1443   if ( _Sleeping )
1444   {
1445     _Sleeping = false ;
1446     MESSAGE("SigIntHandler END sleeping.") ;
1447     return ;
1448   }
1449   else
1450   {
1451     ActSigIntHandler() ;
1452     if ( what == SIGUSR1 )
1453     {
1454       SetCpuUsed() ;
1455     }
1456     else
1457     {
1458       _Sleeping = true ;
1459       MESSAGE("SigIntHandler BEGIN sleeping.") ;
1460       int count = 0 ;
1461       while( _Sleeping ) 
1462       {
1463         Sleep( 1000 ) ;
1464         count += 1 ;
1465       }
1466       MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1467     }
1468     return ;
1469   }
1470 }
1471 #endif
1472
1473 //=============================================================================
1474 //! Get or create a file reference object associated to a local file (to transfer it)
1475 /*!
1476 *  CORBA method: get or create a fileRef object associated to a local file
1477 *  (a file on the computer on which runs the container server), which stores
1478 *  a list of (machine, localFileName) corresponding to copies already done.
1479 *
1480 *  \param  origFileName absolute path for a local file to copy on other
1481 *          computers
1482 *  \return a fileRef object associated to the file.
1483 */
1484 //=============================================================================
1485 Engines::fileRef_ptr
1486 Engines_Container_i::createFileRef(const char* origFileName)
1487 {
1488   std::string origName(origFileName);
1489   Engines::fileRef_var theFileRef = Engines::fileRef::_nil();
1490
1491   if (origName[0] != '/')
1492   {
1493     INFOS("path of file to copy must be an absolute path begining with '/'");
1494     return Engines::fileRef::_nil();
1495   }
1496
1497   if (CORBA::is_nil(_fileRef_map[origName]))
1498   {
1499     CORBA::Object_var obj=_poa->id_to_reference(*_id);
1500     Engines::Container_var pCont = Engines::Container::_narrow(obj);
1501     fileRef_i* aFileRef = new fileRef_i(pCont, origFileName);
1502     theFileRef = Engines::fileRef::_narrow(aFileRef->_this());
1503     _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1504     _fileRef_map[origName] = theFileRef;
1505     _numInstanceMutex.unlock() ;
1506   }
1507
1508   theFileRef =  Engines::fileRef::_duplicate(_fileRef_map[origName]);
1509   ASSERT(! CORBA::is_nil(theFileRef));
1510   return theFileRef._retn();
1511 }
1512
1513 //=============================================================================
1514 //! Get a fileTransfer reference
1515 /*!
1516 *  CORBA method:
1517 *  \return a reference to the fileTransfer object
1518 */
1519 //=============================================================================
1520 Engines::fileTransfer_ptr
1521 Engines_Container_i::getFileTransfer()
1522 {
1523   Engines::fileTransfer_var aFileTransfer
1524     = Engines::fileTransfer::_duplicate(_fileTransfer);
1525   return aFileTransfer._retn();
1526 }
1527
1528 //=============================================================================
1529 //! Create a Salome file
1530 //=============================================================================
1531 Engines::Salome_file_ptr
1532 Engines_Container_i::createSalome_file(const char* origFileName)
1533 {
1534   std::string origName(origFileName);
1535   if (CORBA::is_nil(_Salome_file_map[origName]))
1536   {
1537     Salome_file_i* aSalome_file = new Salome_file_i();
1538     aSalome_file->setContainer(Engines::Container::_duplicate(this->_this()));
1539     try
1540     {
1541       aSalome_file->setLocalFile(origFileName);
1542       aSalome_file->recvFiles();
1543     }
1544     catch (const SALOME::SALOME_Exception& e)
1545     {
1546       return Engines::Salome_file::_nil();
1547     }
1548
1549     Engines::Salome_file_var theSalome_file = Engines::Salome_file::_nil();
1550     theSalome_file = Engines::Salome_file::_narrow(aSalome_file->_this());
1551     _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1552     _Salome_file_map[origName] = theSalome_file;
1553     _numInstanceMutex.unlock() ;
1554   }
1555
1556   Engines::Salome_file_ptr theSalome_file =
1557     Engines::Salome_file::_duplicate(_Salome_file_map[origName]);
1558   ASSERT(!CORBA::is_nil(theSalome_file));
1559   return theSalome_file;
1560 }
1561
1562 //=============================================================================
1563 /*! \brief copy a file from a remote host (container) to the local host
1564  * \param container the remote container
1565  * \param remoteFile the file to copy locally from the remote host into localFile
1566  * \param localFile the local file
1567  */
1568 //=============================================================================
1569 void Engines_Container_i::copyFile(Engines::Container_ptr container, const char* remoteFile, const char* localFile)
1570 {
1571   Engines::fileTransfer_var fileTransfer = container->getFileTransfer();
1572
1573   FILE* fp;
1574   if ((fp = fopen(localFile,"wb")) == NULL)
1575     {
1576       INFOS("file " << localFile << " cannot be open for writing");
1577       return;
1578     }
1579
1580   CORBA::Long fileId = fileTransfer->open(remoteFile);
1581   if (fileId > 0)
1582     {
1583       Engines::fileBlock* aBlock;
1584       int toFollow = 1;
1585       int ctr=0;
1586       while (toFollow)
1587         {
1588           ctr++;
1589           SCRUTE(ctr);
1590           aBlock = fileTransfer->getBlock(fileId);
1591           toFollow = aBlock->length();
1592           SCRUTE(toFollow);
1593           CORBA::Octet *buf = aBlock->get_buffer();
1594           fwrite(buf, sizeof(CORBA::Octet), toFollow, fp);
1595           delete aBlock;
1596         }
1597       fclose(fp);
1598       MESSAGE("end of transfer");
1599       fileTransfer->close(fileId);
1600     }
1601   else
1602     {
1603       INFOS("open reference file for copy impossible");
1604     }
1605 }
1606
1607 //=============================================================================
1608 /*! \brief create a PyNode object to execute remote python code
1609  * \param nodeName the name of the node
1610  * \param code the python code to load
1611  * \return the PyNode
1612  */
1613 //=============================================================================
1614 Engines::PyNode_ptr Engines_Container_i::createPyNode(const char* nodeName, const char* code)
1615 {
1616     Engines::PyNode_var node= Engines::PyNode::_nil();
1617
1618     PyGILState_STATE gstate = PyGILState_Ensure();
1619     PyObject *res = PyObject_CallMethod(_pyCont,
1620       (char*)"create_pynode",
1621       (char*)"ss",
1622       nodeName,
1623       code);
1624     if(res==NULL)
1625       {
1626         //internal error
1627         PyErr_Print();
1628         PyGILState_Release(gstate);
1629         SALOME::ExceptionStruct es;
1630         es.type = SALOME::INTERNAL_ERROR;
1631         es.text = "can not create a python node";
1632         throw SALOME::SALOME_Exception(es);
1633       }
1634     long ierr=PyInt_AsLong(PyTuple_GetItem(res,0));
1635     PyObject* result=PyTuple_GetItem(res,1);
1636     std::string astr=PyString_AsString(result);
1637     Py_DECREF(res);
1638     PyGILState_Release(gstate);
1639
1640     if(ierr==0)
1641       {
1642         CORBA::Object_var obj = _orb->string_to_object(astr.c_str());
1643         node = Engines::PyNode::_narrow(obj);
1644         return node._retn();
1645       }
1646     else
1647       {
1648         SALOME::ExceptionStruct es;
1649         es.type = SALOME::INTERNAL_ERROR;
1650         es.text = astr.c_str();
1651         throw SALOME::SALOME_Exception(es);
1652       }
1653
1654 }
1655
1656 //=============================================================================
1657 /*! \brief create a PyScriptNode object to execute remote python code
1658  * \param nodeName the name of the node
1659  * \param code the python code to load
1660  * \return the PyScriptNode
1661  */
1662 //=============================================================================
1663 Engines::PyScriptNode_ptr Engines_Container_i::createPyScriptNode(const char* nodeName, const char* code)
1664 {
1665     Engines::PyScriptNode_var node= Engines::PyScriptNode::_nil();
1666
1667     PyGILState_STATE gstate = PyGILState_Ensure();
1668     PyObject *res = PyObject_CallMethod(_pyCont,
1669       (char*)"create_pyscriptnode",
1670       (char*)"ss",
1671       nodeName,
1672       code);
1673     if(res==NULL)
1674       {
1675         //internal error
1676         PyErr_Print();
1677         PyGILState_Release(gstate);
1678         SALOME::ExceptionStruct es;
1679         es.type = SALOME::INTERNAL_ERROR;
1680         es.text = "can not create a python node";
1681         throw SALOME::SALOME_Exception(es);
1682       }
1683     long ierr=PyInt_AsLong(PyTuple_GetItem(res,0));
1684     PyObject* result=PyTuple_GetItem(res,1);
1685     std::string astr=PyString_AsString(result);
1686     Py_DECREF(res);
1687     PyGILState_Release(gstate);
1688
1689     if(ierr==0)
1690       {
1691         CORBA::Object_var obj = _orb->string_to_object(astr.c_str());
1692         node = Engines::PyScriptNode::_narrow(obj);
1693         return node._retn();
1694       }
1695     else
1696       {
1697         SALOME::ExceptionStruct es;
1698         es.type = SALOME::INTERNAL_ERROR;
1699         es.text = astr.c_str();
1700         throw SALOME::SALOME_Exception(es);
1701       }
1702 }
1703
1704 //=============================================================================
1705 /* int checkifexecutable(const char *filename)
1706 *
1707 * Return non-zero if the name is an executable file, and
1708 * zero if it is not executable, or if it does not exist.
1709 */
1710 //=============================================================================
1711 int checkifexecutable(const std::string& filename)
1712 {
1713   int result;
1714   struct stat statinfo;
1715
1716   result = stat(filename.c_str(), &statinfo);
1717   if (result < 0) return 0;
1718   if (!S_ISREG(statinfo.st_mode)) return 0;
1719
1720 #ifdef WIN32
1721   return 1;
1722 #else
1723   if (statinfo.st_uid == geteuid()) return statinfo.st_mode & S_IXUSR;
1724   if (statinfo.st_gid == getegid()) return statinfo.st_mode & S_IXGRP;
1725   return statinfo.st_mode & S_IXOTH;
1726 #endif
1727 }
1728
1729
1730 //=============================================================================
1731 /*! \brief Find a file by searching in a path
1732  *  \param filename file name to search
1733  *  \param path path to search in
1734  *  \param pth the complete file path if found
1735  *  \return 1 if found 0 if not 
1736 */
1737 //=============================================================================
1738 int findpathof(const std::string& path, std::string& pth, const std::string& filename)
1739 {
1740   if ( path.size() == 0 ) return 0;
1741
1742   std::string::size_type offset = 0;
1743   std::string::size_type pos = 0;
1744   int found = 0;
1745   struct stat statinfo;
1746
1747   while(!found)
1748   {
1749     pos = path.find( SEP, offset );
1750     pth = path.substr( offset, pos - offset );
1751     if ( pth.size() > 0 )
1752     {
1753       if( pth[pth.size()-1] != SLASH ) pth += SLASH;
1754       pth += filename;
1755       int result=stat(pth.c_str(), &statinfo);
1756       if(result == 0) found=1;
1757     }
1758     if (pos == std::string::npos) break;
1759     offset = pos+1;
1760   }
1761   return found;
1762 }
1763
1764 void Engines_Container_i::registerTemporaryFile( const std::string& fileName )
1765 {
1766   _tmp_files.remove( fileName );
1767   _tmp_files.push_back( fileName );
1768 }
1769
1770 void Engines_Container_i::unregisterTemporaryFile( const std::string& fileName )
1771 {
1772   _tmp_files.remove( fileName );
1773 }
1774
1775 void Engines_Container_i::clearTemporaryFiles()
1776 {
1777   std::list<std::string>::const_iterator it;
1778   for ( it = _tmp_files.begin(); it != _tmp_files.end(); ++it ) {
1779 #ifdef WIN32
1780     std::string command = "del /F ";
1781 #else
1782     std::string command = "rm -rf ";
1783 #endif
1784     command += *it;
1785     system( command.c_str() );
1786   }
1787   _tmp_files.clear();
1788 }