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