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