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