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