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