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