Salome HOME
18e51ac2081f67943448d1a19d428b9603770140
[modules/yacs.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 char *
962 Engines_Container_i::create_python_service_instance(const char * CompName,
963                                                     CORBA::String_out reason)
964 {
965   CORBA::Object_var object = CORBA::Object::_nil();
966
967   _numInstanceMutex.lock() ; // lock on the instance number
968   _numInstance++ ;
969   int numInstance = _numInstance ;
970   _numInstanceMutex.unlock() ;
971
972   char aNumI[12];
973   sprintf( aNumI , "%d" , numInstance ) ;
974   std::string instanceName = std::string(CompName) + "_inst_" + aNumI ;
975   std::string component_registerName = _containerName + "/" + instanceName;
976
977   PyGILState_STATE gstate = PyGILState_Ensure();
978   PyObject *result = PyObject_CallMethod(_pyCont,
979                                          (char*)"create_component_instance",
980                                          (char*)"ssl",
981                                          CompName,
982                                          instanceName.c_str(),
983                                          0);
984   const char *ior;
985   const char *error;
986   PyArg_ParseTuple(result,"ss", &ior, &error);
987   reason = CORBA::string_dup(error);
988   Py_DECREF(result);
989   PyGILState_Release(gstate);
990
991   return CORBA::string_dup(ior);
992 }
993
994
995 //=============================================================================
996 //! Create a new component instance (C++ implementation)
997 /*! 
998 *  C++ method: create a servant instance of a component.
999 *  \param genericRegisterName    Name of the component instance to register
1000 *                                in Registry & Name Service,
1001 *                                (without _inst_n suffix, like "COMPONENT")
1002 *  \param handle                 loaded library handle
1003 *  \param studyId                0 for multiStudy instance, 
1004 *                                study Id (>0) otherwise
1005 *  \param reason                 explains error when creation fails
1006 *  \return a loaded component
1007
1008 *  example with names:
1009 *    - aGenRegisterName = COMPONENT (= first argument)
1010 *    - _containerName = /Containers/cli76ce/FactoryServer
1011 *    - factoryName = COMPONENTEngine_factory
1012 *    - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
1013 *    - instanceName = COMPONENT_inst_1
1014 *    - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1015 */
1016 //=============================================================================
1017 Engines::EngineComponent_ptr
1018 Engines_Container_i::createInstance(std::string genericRegisterName,
1019                                     void *handle,
1020                                     int studyId,
1021                                     std::string& reason)
1022 {
1023   // --- find the factory
1024
1025   std::string aGenRegisterName = genericRegisterName;
1026   std::string factory_name = aGenRegisterName + std::string("Engine_factory");
1027   SCRUTE(factory_name) ;
1028
1029   typedef PortableServer::ObjectId* (*FACTORY_FUNCTION) (CORBA::ORB_ptr,
1030                                                          PortableServer::POA_ptr, 
1031                                                          PortableServer::ObjectId *, 
1032                                                          const char *, 
1033                                                          const char *) ;
1034
1035 #ifndef WIN32
1036   FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)dlsym( handle, factory_name.c_str() );
1037 #else
1038   FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)GetProcAddress( (HINSTANCE)handle, factory_name.c_str() );
1039 #endif
1040
1041   if ( !Component_factory )
1042   {
1043     INFOS( "Can't resolve symbol: " + factory_name );
1044 #ifndef WIN32
1045     reason=dlerror();
1046     INFOS(reason);
1047 #endif
1048     return Engines::EngineComponent::_nil() ;
1049   }
1050
1051   // --- create instance
1052
1053   Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1054
1055   try
1056   {
1057     _numInstanceMutex.lock() ; // lock on the instance number
1058     _numInstance++ ;
1059     int numInstance = _numInstance ;
1060     _numInstanceMutex.unlock() ;
1061
1062     char aNumI[12];
1063     sprintf( aNumI , "%d" , numInstance ) ;
1064     std::string instanceName = aGenRegisterName + "_inst_" + aNumI ;
1065     std::string component_registerName =
1066       _containerName + "/" + instanceName;
1067
1068     // --- Instanciate required CORBA object
1069
1070     PortableServer::ObjectId *id ; //not owner, do not delete (nore use var)
1071     id = (Component_factory) ( _orb, _poa, _id, instanceName.c_str(),
1072                                                 aGenRegisterName.c_str() ) ;
1073     if (id == NULL)
1074       {
1075         reason="Can't get ObjectId from factory";
1076         INFOS(reason);
1077         return iobject._retn();
1078       }
1079
1080     // --- get reference & servant from id
1081
1082     CORBA::Object_var obj = _poa->id_to_reference(*id);
1083     iobject = Engines::EngineComponent::_narrow( obj ) ;
1084
1085     Engines_Component_i *servant =
1086       dynamic_cast<Engines_Component_i*>(_poa->reference_to_servant(iobject));
1087     ASSERT(servant);
1088     //SCRUTE(servant->_refcount_value());
1089     _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1090     _listInstances_map[instanceName] = iobject;
1091     _cntInstances_map[aGenRegisterName] += 1;
1092     _numInstanceMutex.unlock() ;
1093     SCRUTE(aGenRegisterName);
1094     SCRUTE(_cntInstances_map[aGenRegisterName]);
1095     servant->setStudyId(studyId);
1096     servant->_remove_ref(); // do not need servant any more (remove ref from reference_to_servant)
1097     //SCRUTE(servant->_refcount_value());
1098
1099     // --- register the engine under the name
1100     //     containerName(.dir)/instanceName(.object)
1101
1102     _NS->Register( iobject , component_registerName.c_str() ) ;
1103     MESSAGE( component_registerName.c_str() << " bound" ) ;
1104   }
1105   catch (...)
1106   {
1107     reason="Container_i::createInstance exception catched";
1108     INFOS(reason) ;
1109   }
1110   return iobject._retn();
1111 }
1112
1113 //=============================================================================
1114 //! Find an existing (in the container) component instance
1115 /*!
1116 *  CORBA method: Finds a servant instance of a component
1117 *  \param registeredName  Name of the component in Registry or Name Service,
1118 *                         without instance suffix number
1119 *  \param studyId         0 if instance is not associated to a study,
1120 *                         >0 otherwise (== study id)
1121 *  \return the first instance found with same studyId
1122 */
1123 //=============================================================================
1124 Engines::EngineComponent_ptr
1125 Engines_Container_i::find_component_instance( const char* registeredName,
1126                                               CORBA::Long studyId)
1127 {
1128   Engines::EngineComponent_var anEngine = Engines::EngineComponent::_nil();
1129   std::map<std::string,Engines::EngineComponent_var>::iterator itm =_listInstances_map.begin();
1130   while (itm != _listInstances_map.end())
1131   {
1132     std::string instance = (*itm).first;
1133     SCRUTE(instance);
1134     if (instance.find(registeredName) == 0)
1135     {
1136       anEngine = (*itm).second;
1137       if (studyId == anEngine->getStudyId())
1138       {
1139         return anEngine._retn();
1140       }
1141     }
1142     itm++;
1143   }
1144   return anEngine._retn();
1145 }
1146
1147 //=============================================================================
1148 //! Remove the component instance from container
1149 /*!
1150 *  CORBA method: Stops the component servant, and deletes all related objects
1151 *  \param component_i     Component to be removed
1152 */
1153 //=============================================================================
1154
1155 void Engines_Container_i::remove_impl(Engines::EngineComponent_ptr component_i)
1156 {
1157   ASSERT(! CORBA::is_nil(component_i));
1158   std::string instanceName = component_i->instanceName() ;
1159   MESSAGE("unload component " << instanceName);
1160   _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1161   _listInstances_map.erase(instanceName);
1162   _numInstanceMutex.unlock() ;
1163   component_i->destroy() ;
1164   _NS->Destroy_Name(instanceName.c_str());
1165 }
1166
1167 //=============================================================================
1168 //! Unload component libraries from the container
1169 /*!
1170 *  CORBA method: Discharges unused libraries from the container.
1171 */
1172 //=============================================================================
1173 void Engines_Container_i::finalize_removal()
1174 {
1175   MESSAGE("finalize unload : dlclose");
1176   _numInstanceMutex.lock(); // lock to be alone
1177   // (see decInstanceCnt, load_component_Library)
1178   std::map<std::string, void *>::iterator ith;
1179   for (ith = _toRemove_map.begin(); ith != _toRemove_map.end(); ith++)
1180   {
1181     void *handle = (*ith).second;
1182     std::string impl_name= (*ith).first;
1183     if (handle)
1184     {
1185       SCRUTE(handle);
1186       SCRUTE(impl_name);
1187       //        dlclose(handle);                // SALOME unstable after ...
1188       //        _library_map.erase(impl_name);
1189     }
1190   }
1191   _toRemove_map.clear();
1192   _numInstanceMutex.unlock();
1193 }
1194
1195 //=============================================================================
1196 //! Decrement component instance reference count
1197 /*!
1198 *
1199 */
1200 //=============================================================================
1201 void Engines_Container_i::decInstanceCnt(std::string genericRegisterName)
1202 {
1203   if(_cntInstances_map.count(genericRegisterName)==0)
1204     return;
1205   std::string aGenRegisterName =genericRegisterName;
1206   MESSAGE("Engines_Container_i::decInstanceCnt " << aGenRegisterName);
1207   ASSERT(_cntInstances_map[aGenRegisterName] > 0);
1208   _numInstanceMutex.lock(); // lock to be alone
1209   // (see finalize_removal, load_component_Library)
1210   _cntInstances_map[aGenRegisterName] -= 1;
1211   SCRUTE(_cntInstances_map[aGenRegisterName]);
1212   if (_cntInstances_map[aGenRegisterName] == 0)
1213   {
1214     std::string impl_name =
1215       Engines_Component_i::GetDynLibraryName(aGenRegisterName.c_str());
1216     SCRUTE(impl_name);
1217     void* handle = _library_map[impl_name];
1218     ASSERT(handle);
1219     _toRemove_map[impl_name] = handle;
1220   }
1221   _numInstanceMutex.unlock();
1222 }
1223
1224 //=============================================================================
1225 //! Find or create a new component instance
1226 /*!
1227 *  CORBA method: find or create an instance of the component (servant),
1228 *  load a new component class (dynamic library) if required,
1229 *
1230 *  ---- FOR COMPATIBILITY WITH 2.2 ----
1231 *
1232 *  ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
1233 *
1234 *  The servant registers itself to naming service and Registry.
1235 *  \param genericRegisterName  Name of the component to register
1236 *                              in Registry & Name Service
1237 *  \param componentName       Name of the constructed library of the component
1238 *  \return a loaded component
1239 */
1240 //=============================================================================
1241
1242 Engines::EngineComponent_ptr
1243 Engines_Container_i::load_impl( const char* genericRegisterName,
1244                                 const char* componentName )
1245 {
1246   char* reason;
1247   std::string impl_name = std::string(LIB) + genericRegisterName + ENGINESO;
1248   Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1249   if (load_component_Library(genericRegisterName,reason))
1250     iobject = find_or_create_instance(genericRegisterName, impl_name);
1251   CORBA::string_free(reason);
1252   return iobject._retn();
1253 }
1254
1255 //=============================================================================
1256 //! Finds an already existing component instance or create a new instance
1257 /*!
1258 *  C++ method: Finds an already existing servant instance of a component, or
1259 *              create an instance.
1260 *  ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
1261 *  \param genericRegisterName    Name of the component instance to register
1262 *                                in Registry & Name Service,
1263 *                                (without _inst_n suffix, like "COMPONENT")
1264 *  \param componentLibraryName   like "libCOMPONENTEngine.so"
1265 *  \return a loaded component
1266 *
1267 *  example with names:
1268 *    - aGenRegisterName = COMPONENT (= first argument)
1269 *    - impl_name = libCOMPONENTEngine.so (= second argument)
1270 *    - _containerName = /Containers/cli76ce/FactoryServer
1271 *    - factoryName = COMPONENTEngine_factory
1272 *    - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
1273 *    - instanceName = COMPONENT_inst_1
1274 *    - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1275 */
1276 //=============================================================================
1277
1278 Engines::EngineComponent_ptr
1279 Engines_Container_i::find_or_create_instance(std::string genericRegisterName,
1280                                              std::string componentLibraryName)
1281 {
1282   std::string aGenRegisterName = genericRegisterName;
1283   std::string impl_name = componentLibraryName;
1284   if (_library_map.count(impl_name) == 0)
1285   {
1286     INFOS("shared library " << impl_name <<" must be loaded before creating instance");
1287     return Engines::EngineComponent::_nil() ;
1288   }
1289   else
1290   {
1291     // --- find a registered instance in naming service, or create
1292
1293     void* handle = _library_map[impl_name];
1294     std::string component_registerBase =
1295       _containerName + "/" + aGenRegisterName;
1296     Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1297     std::string reason;
1298     try
1299     {
1300       CORBA::Object_var obj =
1301         _NS->ResolveFirst( component_registerBase.c_str());
1302       if ( CORBA::is_nil( obj ) )
1303       {
1304         iobject = createInstance(genericRegisterName,
1305                                  handle,
1306                                  0,
1307                                  reason); // force multiStudy instance here !
1308       }
1309       else
1310       {
1311         iobject = Engines::EngineComponent::_narrow( obj ) ;
1312         Engines_Component_i *servant =
1313           dynamic_cast<Engines_Component_i*>
1314           (_poa->reference_to_servant(iobject));
1315         ASSERT(servant)
1316           int studyId = servant->getStudyId();
1317         ASSERT (studyId >= 0);
1318         if (studyId == 0) // multiStudy instance, OK
1319         {
1320           // No ReBind !
1321           MESSAGE(component_registerBase.c_str()<<" already bound");
1322         }
1323         else // monoStudy instance: NOK
1324         {
1325           iobject = Engines::EngineComponent::_nil();
1326           INFOS("load_impl & find_component_instance methods "
1327             << "NOT SUITABLE for mono study components");
1328         }
1329       }
1330     }
1331     catch (...)
1332     {
1333       INFOS( "Container_i::load_impl catched" ) ;
1334     }
1335     return iobject._retn();
1336   }
1337 }
1338
1339 //=============================================================================
1340 //! Indicate if container is a python one
1341 /*! 
1342 *  Retrieves only with container naming convention if it is a python container
1343 */
1344 //=============================================================================
1345 bool Engines_Container_i::isPythonContainer(const char* ContainerName)
1346 {
1347   bool ret=false;
1348   int len=strlen(ContainerName);
1349   if(len>=2)
1350     if(strcmp(ContainerName+len-2,"Py")==0)
1351       ret=true;
1352   return ret;
1353 }
1354
1355 //=============================================================================
1356 //! Kill the container
1357 /*!
1358 *  CORBA method: Kill the container process with exit(0).
1359 *  To remove :  never returns !
1360 */
1361 //=============================================================================
1362 bool Engines_Container_i::Kill_impl()
1363 {
1364   MESSAGE("Engines_Container_i::Kill() pid "<< getpid() << " containerName "
1365     << _containerName.c_str() << " machineName "
1366     << Kernel_Utils::GetHostname().c_str());
1367   INFOS("===============================================================");
1368   INFOS("= REMOVE calls to Kill_impl in C++ container                  =");
1369   INFOS("===============================================================");
1370   //_exit( 0 ) ;
1371   ASSERT(0);
1372   return false;
1373 }
1374
1375 //=============================================================================
1376 /*! 
1377 *  
1378 */
1379 //=============================================================================
1380 void ActSigIntHandler()
1381 {
1382 #ifndef WIN32
1383   struct sigaction SigIntAct ;
1384   SigIntAct.sa_sigaction = &SigIntHandler ;
1385   sigemptyset(&SigIntAct.sa_mask);
1386   SigIntAct.sa_flags = SA_SIGINFO ;
1387 #endif
1388
1389   // DEBUG 03.02.2005 : the first parameter of sigaction is not a mask of signals
1390   // (SIGINT | SIGUSR1) :
1391   // it must be only one signal ===> one call for SIGINT 
1392   // and an other one for SIGUSR1
1393
1394 #ifndef WIN32
1395   if ( sigaction( SIGINT , &SigIntAct, NULL ) ) 
1396   {
1397     perror("SALOME_Container main ") ;
1398     exit(0) ;
1399   }
1400   if ( sigaction( SIGUSR1 , &SigIntAct, NULL ) )
1401   {
1402     perror("SALOME_Container main ") ;
1403     exit(0) ;
1404   }
1405   if ( sigaction( SIGUSR2 , &SigIntAct, NULL ) )
1406   {
1407     perror("SALOME_Container main ") ;
1408     exit(0) ;
1409   }
1410
1411   //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1412   //             use of streams (and so on) should never be used because :
1413   //             streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1414   //             A stream operation may be interrupted by a signal and if the Handler use stream we
1415   //             may have a "Dead-Lock" ===HangUp
1416   //==INFOS is commented
1417   //  INFOS(pthread_self() << "SigIntHandler activated") ;
1418
1419 #else  
1420   signal( SIGINT, SigIntHandler );
1421 // legacy code required to supervisor. Commented in order to avoid problems on Windows 
1422 //  signal( SIGUSR1, SigIntHandler );
1423 #endif
1424
1425 }
1426
1427 void SetCpuUsed() ;
1428 void CallCancelThread() ;
1429
1430 #ifndef WIN32
1431 void SigIntHandler(int what ,
1432                    siginfo_t * siginfo ,
1433                    void * toto ) 
1434 {
1435   //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1436   //             use of streams (and so on) should never be used because :
1437   //             streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1438   //             A stream operation may be interrupted by a signal and if the Handler use stream we
1439   //             may have a "Dead-Lock" ===HangUp
1440   //==MESSAGE is commented
1441   //  MESSAGE(pthread_self() << "SigIntHandler what     " << what << std::endl
1442   //          << "              si_signo " << siginfo->si_signo << std::endl
1443   //          << "              si_code  " << siginfo->si_code << std::endl
1444   //          << "              si_pid   " << siginfo->si_pid) ;
1445
1446   if ( _Sleeping )
1447   {
1448     _Sleeping = false ;
1449     //     MESSAGE("SigIntHandler END sleeping.") ;
1450     return ;
1451   }
1452   else
1453   {
1454     ActSigIntHandler() ;
1455     if ( siginfo->si_signo == SIGUSR1 )
1456     {
1457       SetCpuUsed() ;
1458     }
1459     else if ( siginfo->si_signo == SIGUSR2 )
1460     {
1461       CallCancelThread() ;
1462     }
1463     else 
1464     {
1465       _Sleeping = true ;
1466       //      MESSAGE("SigIntHandler BEGIN sleeping.") ;
1467       int count = 0 ;
1468       while( _Sleeping )
1469       {
1470         sleep( 1 ) ;
1471         count += 1 ;
1472       }
1473       //      MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1474     }
1475     return ;
1476   }
1477 }
1478 #else // Case WIN32
1479 void SigIntHandler( int what )
1480 {
1481 #ifndef WIN32
1482   MESSAGE( pthread_self() << "SigIntHandler what     " << what << std::endl );
1483 #else
1484   MESSAGE( "SigIntHandler what     " << what << std::endl );
1485 #endif
1486   if ( _Sleeping )
1487   {
1488     _Sleeping = false ;
1489     MESSAGE("SigIntHandler END sleeping.") ;
1490     return ;
1491   }
1492   else
1493   {
1494     ActSigIntHandler() ;
1495     if ( what == SIGUSR1 )
1496     {
1497       SetCpuUsed() ;
1498     }
1499     else
1500     {
1501       _Sleeping = true ;
1502       MESSAGE("SigIntHandler BEGIN sleeping.") ;
1503       int count = 0 ;
1504       while( _Sleeping ) 
1505       {
1506         Sleep( 1000 ) ;
1507         count += 1 ;
1508       }
1509       MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1510     }
1511     return ;
1512   }
1513 }
1514 #endif
1515
1516 //=============================================================================
1517 //! Get or create a file reference object associated to a local file (to transfer it)
1518 /*!
1519 *  CORBA method: get or create a fileRef object associated to a local file
1520 *  (a file on the computer on which runs the container server), which stores
1521 *  a list of (machine, localFileName) corresponding to copies already done.
1522 *
1523 *  \param  origFileName absolute path for a local file to copy on other
1524 *          computers
1525 *  \return a fileRef object associated to the file.
1526 */
1527 //=============================================================================
1528 Engines::fileRef_ptr
1529 Engines_Container_i::createFileRef(const char* origFileName)
1530 {
1531   std::string origName(origFileName);
1532   Engines::fileRef_var theFileRef = Engines::fileRef::_nil();
1533
1534   if (origName[0] != '/')
1535   {
1536     INFOS("path of file to copy must be an absolute path begining with '/'");
1537     return Engines::fileRef::_nil();
1538   }
1539
1540   if (CORBA::is_nil(_fileRef_map[origName]))
1541   {
1542     CORBA::Object_var obj=_poa->id_to_reference(*_id);
1543     Engines::Container_var pCont = Engines::Container::_narrow(obj);
1544     fileRef_i* aFileRef = new fileRef_i(pCont, origFileName);
1545     theFileRef = Engines::fileRef::_narrow(aFileRef->_this());
1546     _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1547     _fileRef_map[origName] = theFileRef;
1548     _numInstanceMutex.unlock() ;
1549   }
1550
1551   theFileRef =  Engines::fileRef::_duplicate(_fileRef_map[origName]);
1552   ASSERT(! CORBA::is_nil(theFileRef));
1553   return theFileRef._retn();
1554 }
1555
1556 //=============================================================================
1557 //! Get a fileTransfer reference
1558 /*!
1559 *  CORBA method:
1560 *  \return a reference to the fileTransfer object
1561 */
1562 //=============================================================================
1563 Engines::fileTransfer_ptr
1564 Engines_Container_i::getFileTransfer()
1565 {
1566   Engines::fileTransfer_var aFileTransfer
1567     = Engines::fileTransfer::_duplicate(_fileTransfer);
1568   return aFileTransfer._retn();
1569 }
1570
1571 //=============================================================================
1572 //! Create a Salome file
1573 //=============================================================================
1574 Engines::Salome_file_ptr
1575 Engines_Container_i::createSalome_file(const char* origFileName)
1576 {
1577   std::string origName(origFileName);
1578   if (CORBA::is_nil(_Salome_file_map[origName]))
1579   {
1580     Salome_file_i* aSalome_file = new Salome_file_i();
1581     aSalome_file->setContainer(Engines::Container::_duplicate(this->_this()));
1582     try
1583     {
1584       aSalome_file->setLocalFile(origFileName);
1585       aSalome_file->recvFiles();
1586     }
1587     catch (const SALOME::SALOME_Exception& e)
1588     {
1589       return Engines::Salome_file::_nil();
1590     }
1591
1592     Engines::Salome_file_var theSalome_file = Engines::Salome_file::_nil();
1593     theSalome_file = Engines::Salome_file::_narrow(aSalome_file->_this());
1594     _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1595     _Salome_file_map[origName] = theSalome_file;
1596     _numInstanceMutex.unlock() ;
1597   }
1598
1599   Engines::Salome_file_ptr theSalome_file =
1600     Engines::Salome_file::_duplicate(_Salome_file_map[origName]);
1601   ASSERT(!CORBA::is_nil(theSalome_file));
1602   return theSalome_file;
1603 }
1604
1605 //=============================================================================
1606 /*! \brief copy a file from a remote host (container) to the local host
1607  * \param container the remote container
1608  * \param remoteFile the file to copy locally from the remote host into localFile
1609  * \param localFile the local file
1610  */
1611 //=============================================================================
1612 void Engines_Container_i::copyFile(Engines::Container_ptr container, const char* remoteFile, const char* localFile)
1613 {
1614   Engines::fileTransfer_var fileTransfer = container->getFileTransfer();
1615
1616   FILE* fp;
1617   if ((fp = fopen(localFile,"wb")) == NULL)
1618     {
1619       INFOS("file " << localFile << " cannot be open for writing");
1620       return;
1621     }
1622
1623   CORBA::Long fileId = fileTransfer->open(remoteFile);
1624   if (fileId > 0)
1625     {
1626       Engines::fileBlock* aBlock;
1627       int toFollow = 1;
1628       int ctr=0;
1629       while (toFollow)
1630         {
1631           ctr++;
1632           SCRUTE(ctr);
1633           aBlock = fileTransfer->getBlock(fileId);
1634           toFollow = aBlock->length();
1635           SCRUTE(toFollow);
1636           CORBA::Octet *buf = aBlock->get_buffer();
1637           fwrite(buf, sizeof(CORBA::Octet), toFollow, fp);
1638           delete aBlock;
1639         }
1640       fclose(fp);
1641       MESSAGE("end of transfer");
1642       fileTransfer->close(fileId);
1643     }
1644   else
1645     {
1646       INFOS("open reference file for copy impossible");
1647     }
1648 }
1649
1650 //=============================================================================
1651 /*! \brief create a PyNode object to execute remote python code
1652  * \param nodeName the name of the node
1653  * \param code the python code to load
1654  * \return the PyNode
1655  */
1656 //=============================================================================
1657 Engines::PyNode_ptr Engines_Container_i::createPyNode(const char* nodeName, const char* code)
1658 {
1659     Engines::PyNode_var node= Engines::PyNode::_nil();
1660
1661     PyGILState_STATE gstate = PyGILState_Ensure();
1662     PyObject *res = PyObject_CallMethod(_pyCont,
1663       (char*)"create_pynode",
1664       (char*)"ss",
1665       nodeName,
1666       code);
1667     if(res==NULL)
1668       {
1669         //internal error
1670         PyErr_Print();
1671         PyGILState_Release(gstate);
1672         SALOME::ExceptionStruct es;
1673         es.type = SALOME::INTERNAL_ERROR;
1674         es.text = "can not create a python node";
1675         throw SALOME::SALOME_Exception(es);
1676       }
1677     long ierr=PyInt_AsLong(PyTuple_GetItem(res,0));
1678     PyObject* result=PyTuple_GetItem(res,1);
1679     std::string astr=PyString_AsString(result);
1680     Py_DECREF(res);
1681     PyGILState_Release(gstate);
1682
1683     if(ierr==0)
1684       {
1685         CORBA::Object_var obj = _orb->string_to_object(astr.c_str());
1686         node = Engines::PyNode::_narrow(obj);
1687         if(!CORBA::is_nil(_dftPyNode))
1688           _dftPyNode->UnRegister();
1689         _dftPyNode = node;
1690         if(!CORBA::is_nil(_dftPyNode))
1691           _dftPyNode->Register();
1692         return node._retn();
1693       }
1694     else
1695       {
1696         SALOME::ExceptionStruct es;
1697         es.type = SALOME::INTERNAL_ERROR;
1698         es.text = astr.c_str();
1699         throw SALOME::SALOME_Exception(es);
1700       }
1701
1702 }
1703
1704 //=============================================================================
1705 /*! \brief Retrieves the last created PyNode instance with createPyNode.
1706  *
1707  */
1708 //=============================================================================
1709 Engines::PyNode_ptr  Engines_Container_i::getDefaultPyNode()
1710 {
1711   if(!CORBA::is_nil(_dftPyNode))
1712     return Engines::PyNode::_duplicate(_dftPyNode);
1713   else
1714     return Engines::PyNode::_nil();
1715 }
1716
1717 //=============================================================================
1718 /*! \brief create a PyScriptNode object to execute remote python code
1719  * \param nodeName the name of the node
1720  * \param code the python code to load
1721  * \return the PyScriptNode
1722  */
1723 //=============================================================================
1724 Engines::PyScriptNode_ptr Engines_Container_i::createPyScriptNode(const char* nodeName, const char* code)
1725 {
1726     Engines::PyScriptNode_var node= Engines::PyScriptNode::_nil();
1727
1728     PyGILState_STATE gstate = PyGILState_Ensure();
1729     PyObject *res = PyObject_CallMethod(_pyCont,
1730       (char*)"create_pyscriptnode",
1731       (char*)"ss",
1732       nodeName,
1733       code);
1734     if(res==NULL)
1735       {
1736         //internal error
1737         PyErr_Print();
1738         PyGILState_Release(gstate);
1739         SALOME::ExceptionStruct es;
1740         es.type = SALOME::INTERNAL_ERROR;
1741         es.text = "can not create a python node";
1742         throw SALOME::SALOME_Exception(es);
1743       }
1744     long ierr=PyInt_AsLong(PyTuple_GetItem(res,0));
1745     PyObject* result=PyTuple_GetItem(res,1);
1746     std::string astr=PyString_AsString(result);
1747     Py_DECREF(res);
1748     PyGILState_Release(gstate);
1749
1750     if(ierr==0)
1751       {
1752         CORBA::Object_var obj = _orb->string_to_object(astr.c_str());
1753         node = Engines::PyScriptNode::_narrow(obj);
1754         if(!CORBA::is_nil(_dftPyScriptNode))
1755           _dftPyScriptNode->UnRegister();
1756         _dftPyScriptNode = node;
1757         if(!CORBA::is_nil(_dftPyScriptNode))
1758           _dftPyScriptNode->Register();
1759         return node._retn();
1760       }
1761     else
1762       {
1763         SALOME::ExceptionStruct es;
1764         es.type = SALOME::INTERNAL_ERROR;
1765         es.text = astr.c_str();
1766         throw SALOME::SALOME_Exception(es);
1767       }
1768 }
1769
1770 //=============================================================================
1771 /*! \brief Retrieves the last created PyScriptNode instance with createPyScriptNode.
1772  *
1773  */
1774 //=============================================================================
1775 Engines::PyScriptNode_ptr Engines_Container_i::getDefaultPyScriptNode()
1776 {
1777   if(!CORBA::is_nil(_dftPyScriptNode))
1778     return Engines::PyScriptNode::_duplicate(_dftPyScriptNode);
1779   else
1780     return Engines::PyScriptNode::_nil();
1781 }
1782
1783 //=============================================================================
1784 /* int checkifexecutable(const char *filename)
1785 *
1786 * Return non-zero if the name is an executable file, and
1787 * zero if it is not executable, or if it does not exist.
1788 */
1789 //=============================================================================
1790 int checkifexecutable(const std::string& filename)
1791 {
1792   int result;
1793   struct stat statinfo;
1794
1795   result = stat(filename.c_str(), &statinfo);
1796   if (result < 0) return 0;
1797   if (!S_ISREG(statinfo.st_mode)) return 0;
1798
1799 #ifdef WIN32
1800   return 1;
1801 #else
1802   if (statinfo.st_uid == geteuid()) return statinfo.st_mode & S_IXUSR;
1803   if (statinfo.st_gid == getegid()) return statinfo.st_mode & S_IXGRP;
1804   return statinfo.st_mode & S_IXOTH;
1805 #endif
1806 }
1807
1808
1809 //=============================================================================
1810 /*! \brief Find a file by searching in a path
1811  *  \param filename file name to search
1812  *  \param path path to search in
1813  *  \param pth the complete file path if found
1814  *  \return 1 if found 0 if not 
1815 */
1816 //=============================================================================
1817 int findpathof(const std::string& path, std::string& pth, const std::string& filename)
1818 {
1819   if ( path.size() == 0 ) return 0;
1820
1821   std::string::size_type offset = 0;
1822   std::string::size_type pos = 0;
1823   int found = 0;
1824   struct stat statinfo;
1825
1826   while(!found)
1827   {
1828     pos = path.find( SEP, offset );
1829     pth = path.substr( offset, pos - offset );
1830     if ( pth.size() > 0 )
1831     {
1832       if( pth[pth.size()-1] != SLASH ) pth += SLASH;
1833       pth += filename;
1834       int result=stat(pth.c_str(), &statinfo);
1835       if(result == 0) found=1;
1836     }
1837     if (pos == std::string::npos) break;
1838     offset = pos+1;
1839   }
1840   return found;
1841 }
1842
1843 void Engines_Container_i::registerTemporaryFile( const std::string& fileName )
1844 {
1845   _tmp_files.remove( fileName );
1846   _tmp_files.push_back( fileName );
1847 }
1848
1849 void Engines_Container_i::unregisterTemporaryFile( const std::string& fileName )
1850 {
1851   _tmp_files.remove( fileName );
1852 }
1853
1854 void Engines_Container_i::clearTemporaryFiles()
1855 {
1856   std::list<std::string>::const_iterator it;
1857   for ( it = _tmp_files.begin(); it != _tmp_files.end(); ++it ) {
1858 #ifdef WIN32
1859     std::string command = "del /F /P";
1860 #else
1861     std::string command = "rm -rf ";
1862 #endif
1863     command += *it;
1864     system( command.c_str() );
1865   }
1866   _tmp_files.clear();
1867 }