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