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