Salome HOME
Updated copyright comment
[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;
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(ns)
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   MESSAGE("Engines_Container_i::Shutdown()");
713
714   // Clear registered temporary files
715   clearTemporaryFiles();
716
717   /* For each component contained in this container
718   * tell it to self-destroy
719   */
720   std::map<std::string, Engines::EngineComponent_var>::iterator itm;
721   for (itm = _listInstances_map.begin(); itm != _listInstances_map.end(); itm++)
722   {
723     try
724     {
725       itm->second->destroy();
726     }
727     catch(const CORBA::Exception&)
728     {
729       // ignore this entry and continue
730     }
731     catch(...)
732     {
733       // ignore this entry and continue
734     }
735   }
736   _listInstances_map.clear();
737
738   // NS unregistering may throw in SSL mode if master process hosting SALOME_Embedded_NamingService servant has vanished
739   // In this case it's skip it and still continue.
740   try
741   {
742     _NS->Destroy_FullDirectory(_containerName.c_str());
743     _NS->Destroy_Name(_containerName.c_str());
744   }
745   catch(...)
746   {
747   }
748   //
749   this->cleanAllPyScripts();
750   //
751   if(_isServantAloneInProcess)
752   {
753     MESSAGE("Effective Shutdown of container Begins...");
754     if(!CORBA::is_nil(_orb))
755       _orb->shutdown(0);
756   }
757 }
758
759 //=============================================================================
760 //! load a component implementation
761 /*! 
762 *  CORBA method
763 *  \param componentName         component name
764 *  \param reason                explains error when load fails
765 *  \return true if dlopen successful or already done, false otherwise
766 */
767 //=============================================================================
768 bool
769 Abstract_Engines_Container_i::load_component_Library(const char* componentName, CORBA::String_out reason)
770 {
771
772   //=================================================================
773   // --- C++ implementation section 
774   //=================================================================
775   std::string retso;
776   if(load_component_CppImplementation(componentName,retso))
777   {
778     reason=CORBA::string_dup("");
779     return true;
780   }
781   else if(retso != "ImplementationNotFound")
782   {
783     reason=CORBA::string_dup(retso.c_str());
784     return false;
785   }
786
787   retso="Component ";
788   retso+=componentName;
789   retso+=": Can't find C++ implementation ";
790   retso+=std::string(LIB) + componentName + ENGINESO;
791
792   //=================================================================
793   // --- Python implementation section 
794   //=================================================================
795   std::string retpy;
796   if(load_component_PythonImplementation(componentName,retpy))
797   {
798     reason=CORBA::string_dup("");
799     return true;
800   }
801   else if(retpy != "ImplementationNotFound")
802   {
803     reason=CORBA::string_dup(retpy.c_str());
804     return false;
805   }
806   
807   retpy="Component ";
808   retpy+=componentName;
809   retpy+=": Can't find python implementation ";
810   retpy+=componentName;
811   retpy+="(.py)";
812
813   //=================================================================
814   // -- Executable implementation section
815   //=================================================================
816   std::string retex;
817   if(load_component_ExecutableImplementation(componentName,retex))
818   {
819     reason=CORBA::string_dup("");
820     return true;
821   }
822   else if(retex != "ImplementationNotFound")
823   {
824     reason=CORBA::string_dup(retex.c_str());
825     return false;
826   }
827
828   retex="Component ";
829   retex+=componentName;
830   retex+=": Can't find executable implementation ";
831   retex+=componentName;
832   retex+=".exe";
833
834   std::string ret="Component implementation not found: ";
835   ret += componentName ;
836   ret += '\n' ;
837   ret += retso+ '\n' ;
838   ret += retpy+ '\n' ;
839   ret += retex+ '\n' ;
840
841   std::cerr << ret << std::endl;
842   reason=CORBA::string_dup(ret.c_str());
843
844   return false;
845 }
846
847 //=============================================================================
848 //! try to load a C++ component implementation
849 /*! 
850 *  C++ method: 
851 *  \param componentName      the name of the component (COMPONENT, for example)
852 *  \param reason             explains error when load fails
853 *  \return true if loading is successful or already done, false otherwise
854 */
855 //=============================================================================
856 bool
857 Abstract_Engines_Container_i::load_component_CppImplementation(const char* componentName, std::string& reason)
858 {
859   std::string aCompName(componentName);
860   std::string impl_name = std::string(LIB) + aCompName + ENGINESO;
861   SCRUTE(impl_name);
862
863   _numInstanceMutex.lock(); // lock to be alone
864   // (see decInstanceCnt, finalize_removal))
865   if (_toRemove_map.count(impl_name) != 0) _toRemove_map.erase(impl_name);
866   if (_library_map.count(impl_name) != 0)
867   {
868     MESSAGE("Library " << impl_name << " already loaded");
869     _numInstanceMutex.unlock();
870     reason="";
871     return true;
872   }
873   _numInstanceMutex.unlock();
874
875 #ifndef WIN32
876   void* handle;
877   handle = dlopen( impl_name.c_str() , RTLD_NOW | RTLD_GLOBAL ) ;
878   if ( !handle )
879   {
880     //not loadable. Try to find the lib file in LD_LIBRARY_PATH
881     std::string path;
882 #ifdef __APPLE__
883       char* p=getenv("DYLD_LIBRARY_PATH");
884 #else
885       char* p=getenv("LD_LIBRARY_PATH");
886 #endif
887       if(p)path=p;
888       path=path+SEP+"/usr/lib"+SEP+"/lib";
889
890       std::string pth;
891       if(findpathof(path, pth, impl_name))
892         {
893           //found but not loadable
894           reason="Component ";
895           reason+=aCompName;
896           reason+=": C++ implementation found ";
897           reason+=pth;
898           reason+=" but it is not loadable. Error:\n";
899           reason+=dlerror();
900           std::cerr << reason << std::endl;
901           return false;
902         }
903       else
904         {
905           //not found
906           //continue with other implementation
907           reason="ImplementationNotFound";
908           return false;
909     }
910   }
911 #else
912   HINSTANCE handle;
913 #ifdef UNICODE
914   std::wstring libToLoad = Kernel_Utils::utf8_decode_s( impl_name );
915 #else
916   std::string libToLoad = impl_name;
917 #endif
918   handle = LoadLibrary(libToLoad.c_str() );
919   if ( !handle )
920   {
921     reason="ImplementationNotFound";
922   }
923 #endif
924
925   if ( handle )
926   {
927     _numInstanceMutex.lock();
928     _library_map[impl_name] = handle;
929     _numInstanceMutex.unlock();
930     reason="";
931     return true;
932   }
933
934   return false;
935
936 }
937 //=============================================================================
938 //! try to load a Python component implementation
939 /*! 
940 *  C++ method: 
941 *  \param componentName         name of the component
942 *  \param reason                explains error when load fails
943 *  \return true if loading is successful or already done, false otherwise
944 */
945 //=============================================================================
946 bool
947 Abstract_Engines_Container_i::load_component_PythonImplementation(const char* componentName, std::string& reason)
948 {
949   std::string aCompName(componentName);
950
951   _numInstanceMutex.lock() ; // lock to be alone (stl container write)
952   if (_library_map.count(aCompName) != 0)
953   {
954     _numInstanceMutex.unlock() ;
955     reason="";
956     return true; // Python Component, already imported
957   }
958   _numInstanceMutex.unlock() ;
959
960   {
961     AutoGIL gstate;
962     AutoPyRef result = PyObject_CallMethod(_pyCont,
963                                           (char*)"import_component",
964                                           (char*)"s",componentName);
965
966     reason=PyUnicode_AsUTF8(result);
967     SCRUTE(reason);
968   }
969
970   if (reason=="")
971   {
972     //Python component has been loaded (import componentName)
973     _numInstanceMutex.lock() ; // lock to be alone (stl container write)
974     _library_map[aCompName] = (void *)_pyCont; // any non O value OK
975     _numInstanceMutex.unlock() ;
976     MESSAGE("import Python: "<< aCompName <<" OK");
977     return true;
978   }
979   else if(reason=="ImplementationNotFound")
980   {
981     //Python implementation has not been found. Continue with other implementation
982     reason="ImplementationNotFound";
983   }
984   else
985   {
986     //Python implementation has been found but loading has failed
987     std::cerr << reason << std::endl;
988   }
989   return false;
990
991 }
992 //=============================================================================
993 //! try to load a Executable component implementation
994 /*! 
995 *  C++ method: 
996 *  \param componentName        name of the component
997 *  \param reason               explains error when load fails
998 *  \return true if loading is successful or already done, false otherwise
999 */
1000 //=============================================================================
1001 bool
1002 Abstract_Engines_Container_i::load_component_ExecutableImplementation(const char* componentName, std::string& reason)
1003 {
1004   std::string aCompName(componentName);
1005   std::string executable=aCompName+".exe";
1006
1007   std::string path;
1008   std::string pth;
1009
1010   char* p=getenv("PATH");
1011   if(p)path=p;
1012
1013   if (findpathof(path, pth, executable))
1014   {
1015     if(checkifexecutable(pth))
1016     {
1017       _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1018       _library_map[executable] = (void *)1; // any non O value OK
1019       _numInstanceMutex.unlock() ;
1020       MESSAGE("import executable: "<< pth <<" OK");
1021       reason="";
1022       return true;
1023     }
1024     reason="Component ";
1025     reason+=aCompName;
1026     reason+=": implementation found ";
1027     reason+=pth;
1028     reason+=" but it is not executable";
1029     std::cerr << reason << std::endl;
1030   }
1031   else
1032   {
1033     reason="ImplementationNotFound";
1034   }
1035   return false;
1036 }
1037
1038 //=============================================================================
1039 //! Create a new component instance
1040 /*! 
1041 *  CORBA method: Creates a new servant instance of a component.
1042 *  The servant registers itself to naming service and Registry.tdlib
1043 *  \param genericRegisterName  Name of the component instance to register
1044 *                         in Registry & Name Service (without _inst_n suffix)
1045 *  \return a loaded component
1046 */
1047 //=============================================================================
1048 Engines::EngineComponent_ptr
1049 Abstract_Engines_Container_i::create_component_instance(const char*genericRegisterName)
1050 {
1051   Engines::FieldsDict_var env = new Engines::FieldsDict;
1052   char* reason;
1053   Engines::EngineComponent_ptr compo =
1054     create_component_instance_env(genericRegisterName, env, reason);
1055   CORBA::string_free(reason);
1056   return compo;
1057 }
1058
1059 void EffectiveOverrideEnvironment( const Engines::FieldsDict& env )
1060 {
1061   MESSAGE("Positionning environment on container ");
1062   for (CORBA::ULong i=0; i < env.length(); i++)
1063   {
1064     if (env[i].value.type()->kind() == CORBA::tk_string)
1065     {
1066       const char *value = nullptr;
1067       env[i].value >>= value;
1068       MESSAGE( env[i].key << " = " << value);
1069 #ifndef WIN32
1070       if( setenv(env[i].key,value,1) != 0 )
1071       {
1072         int errsv = errno;
1073         std::string sErr( strerror( errsv) );
1074         MESSAGE(sErr);
1075       }
1076 #endif
1077     }
1078   }
1079 }
1080
1081 std::vector< std::pair<std::string,std::string> > GetOSEnvironment()
1082 {
1083   std::vector< std::pair<std::string,std::string> > ret;
1084 #ifndef WIN32
1085   char **envPt( environ );
1086   for(;*envPt != nullptr; ++envPt)
1087   {
1088     std::string s( *envPt );
1089     auto pos = s.find_first_of('=');
1090     std::string k( s.substr(0,pos) ),v( s.substr(pos+1) );
1091     ret.emplace_back( std::pair<std::string,std::string>(k,v) );
1092   }
1093 #endif
1094   return ret;
1095 }
1096
1097 void Abstract_Engines_Container_i::override_environment( const Engines::FieldsDict& env )
1098 {
1099   EffectiveOverrideEnvironment(env);
1100 }
1101
1102 void Abstract_Engines_Container_i::override_environment_python( const Engines::FieldsDict& env )
1103 {
1104   constexpr char NODE_NAME[] = "ScriptNodeForEnv";
1105   constexpr char SCRIPT[] = R"foo(
1106 import os
1107 for k,v in env:
1108   os.environ[k] = v
1109 )foo";
1110   Engines::PyScriptNode_var scriptNode = this->createPyScriptNode(NODE_NAME,SCRIPT);
1111   auto sz = env.length();
1112   Engines::listofstring keys, vals;
1113   keys.length( sz ); vals.length( sz );
1114   for( auto i = 0 ; i < sz ; ++i )
1115   {
1116     keys[i] = CORBA::string_dup( env[i].key );
1117     const char *value = nullptr;
1118     env[i].value >>= value;
1119     vals[i] = CORBA::string_dup( value );
1120   }
1121   scriptNode->executeSimple(keys,vals);
1122   this->removePyScriptNode(NODE_NAME);
1123 }
1124
1125 Engines::FieldsDict *Abstract_Engines_Container_i::get_os_environment()
1126 {
1127   std::unique_ptr<Engines::FieldsDict> ret( new Engines::FieldsDict );
1128   std::vector< std::pair<std::string,std::string> > retCpp( GetOSEnvironment() );
1129   auto sz = retCpp.size();
1130   ret->length( sz );
1131   for(auto i = 0 ; i < sz ; ++i)
1132   {
1133     (*ret)[i].key = CORBA::string_dup( retCpp[i].first.c_str() );
1134     (*ret)[i].value <<= CORBA::string_dup( retCpp[i].second.c_str() );
1135   }
1136   return ret.release();
1137 }
1138
1139 void Abstract_Engines_Container_i::execute_python_code(const char *code)
1140 {
1141   AutoGIL gstate;
1142   if( PyRun_SimpleString( code ) != 0 )
1143   {
1144     std::string error = parseException();
1145     THROW_SALOME_CORBA_EXCEPTION(error.c_str(),SALOME::INTERNAL_ERROR);
1146   }
1147 }
1148
1149 //=============================================================================
1150 //! Create a new component instance with environment variables specified
1151 /*! 
1152 *  CORBA method: Creates a new servant instance of a component.
1153 *  The servant registers itself to naming service and Registry.
1154 *  \param genericRegisterName  Name of the component instance to register
1155 *                         in Registry & Name Service (without _inst_n suffix)
1156 *  \param env             dict of env variables
1157 *  \param reason          explains error when create_component_instance_env fails
1158 *  \return a loaded component
1159 */
1160 //=============================================================================
1161 Engines::EngineComponent_ptr
1162 Abstract_Engines_Container_i::create_component_instance_env(const char*genericRegisterName,
1163                                                    const Engines::FieldsDict& env,
1164                                                    CORBA::String_out reason)
1165 {
1166   std::string error;
1167   if (_library_map.count(genericRegisterName) != 0)
1168   {
1169     // It's a Python component
1170     Engines::EngineComponent_ptr compo = createPythonInstance(genericRegisterName, error);
1171     reason=CORBA::string_dup(error.c_str());
1172     return compo;
1173   }
1174
1175   std::string impl_name = std::string(LIB) + genericRegisterName + ENGINESO;
1176   if (_library_map.count(impl_name) != 0)
1177   {
1178     // It's a C++ component
1179     void* handle = _library_map[impl_name];
1180     Engines::EngineComponent_ptr compo = createInstance(genericRegisterName, handle, error);
1181     reason=CORBA::string_dup(error.c_str());
1182     return compo;
1183   }
1184
1185   impl_name = std::string(genericRegisterName) + ".exe";
1186   if (_library_map.count(impl_name) != 0)
1187   {
1188     //It's an executable component
1189     Engines::EngineComponent_ptr compo = createExecutableInstance(genericRegisterName, env, error);
1190     reason=CORBA::string_dup(error.c_str());
1191     return compo;
1192   }
1193
1194   error="load_component_Library has probably not been called for component: ";
1195   error += genericRegisterName;
1196   INFOS(error);
1197   reason=CORBA::string_dup(error.c_str());
1198   return Engines::EngineComponent::_nil() ;
1199 }
1200
1201 //=============================================================================
1202 //! Create a new component instance (Executable implementation)
1203 /*! 
1204 *  \param CompName               Name of the component instance
1205 *  \param env                    dict of env variables
1206 *  \param reason                 explains error when creation fails
1207 *  \return a loaded component
1208 *
1209 *   This component is implemented in an executable with name genericRegisterName.exe
1210 *   It must register itself in Naming Service. The container waits some time (10 s max)
1211 *   it's registration.
1212 */
1213 //=============================================================================
1214 Engines::EngineComponent_ptr
1215 Abstract_Engines_Container_i::createExecutableInstance(std::string CompName,
1216                                                       const Engines::FieldsDict& env,
1217                                                       std::string& reason)
1218 {
1219   Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1220
1221   _numInstanceMutex.lock() ; // lock on the instance number
1222   _numInstance++ ;
1223   int numInstance = _numInstance ;
1224   _numInstanceMutex.unlock() ;
1225
1226   char aNumI[12];
1227   sprintf( aNumI , "%d" , numInstance ) ;
1228   std::string instanceName = CompName + "_inst_" + aNumI ;
1229   std::string component_registerName = _containerName + "/" + instanceName;
1230
1231   //check if an entry exist in naming service
1232   CORBA::Object_var nsobj = _NS->Resolve(component_registerName.c_str());
1233   if ( !CORBA::is_nil(nsobj) )
1234   {
1235     // unregister the registered component
1236     _NS->Destroy_Name(component_registerName.c_str());
1237     //kill or shutdown it ???
1238   }
1239
1240   // first arg container ior string
1241   // second arg container name
1242   // third arg instance name
1243
1244   Engines::Container_var pCont= _this();
1245   CORBA::String_var sior =  _orb->object_to_string(pCont);
1246
1247   std::string command;
1248   command="mkdir -p ";
1249   command+=instanceName;
1250   command+=";cd ";
1251   command+=instanceName;
1252   command+=";";
1253   command+=CompName ;
1254   command+=".exe";
1255   command+=" ";
1256   command+= sior; // container ior string
1257   command+=" ";
1258   command+=_containerName; //container name
1259   command+=" ";
1260   command+=instanceName; //instance name
1261   command+=" &";
1262   MESSAGE("SALOME_Container::create_component_instance command=" << command);
1263
1264 #ifndef WIN32
1265   // use fork/execl instead of system to get finer control on env variables
1266   int status;
1267   pid_t pid = fork();
1268   if(pid == 0) // child
1269   {
1270     EffectiveOverrideEnvironment(env);
1271
1272     execl("/bin/sh", "sh", "-c", command.c_str() , (char *)0);
1273     status=-1;
1274   }
1275   else if(pid < 0)       // failed to fork
1276   {
1277     status=-1;
1278   }
1279   else            //parent
1280   {
1281     pid_t tpid;
1282     do
1283     {
1284       tpid = wait(&status);
1285     } while (tpid != pid);
1286   }
1287 #else
1288   // launch component with a system call
1289   int status=system(command.c_str());
1290 #endif
1291
1292   if (status == -1)
1293   {
1294     reason="SALOME_Container::create_component_instance system failed (system command status -1)";
1295     MESSAGE(reason);
1296     return Engines::EngineComponent::_nil();
1297   }
1298 #ifndef WIN32
1299   else if (WEXITSTATUS(status) == 217)
1300   {
1301     reason="SALOME_Container::create_component_instance system failed (system command status 217)";
1302     MESSAGE(reason);
1303     return Engines::EngineComponent::_nil();
1304   }
1305 #endif
1306   else
1307   {
1308     int count=20;
1309     if (getenv("TIMEOUT_TO_WAIT_EXE_COMPONENT") != 0)
1310     {
1311       std::string new_count_str = getenv("TIMEOUT_TO_WAIT_EXE_COMPONENT");
1312       int new_count;
1313       std::istringstream ss(new_count_str);
1314       if (!(ss >> new_count))
1315       {
1316         INFOS("[Container] TIMEOUT_TO_WAIT_EXE_COMPONENT should be an int");
1317       }
1318       else
1319         count = new_count;
1320     }
1321     INFOS("[Container] waiting " << count << " second steps exe component ");
1322     CORBA::Object_var obj = CORBA::Object::_nil() ;
1323     while ( CORBA::is_nil(obj) && count )
1324     {
1325 #ifndef WIN32
1326       sleep( 1 ) ;
1327 #else
1328       Sleep(1000);
1329 #endif
1330       count-- ;
1331       MESSAGE( count << ". Waiting for component " << CompName);
1332       obj = _NS->Resolve(component_registerName.c_str());
1333     }
1334
1335     if(CORBA::is_nil(obj))
1336     {
1337       reason="SALOME_Container::create_component_instance failed";
1338       MESSAGE(reason);
1339       return Engines::EngineComponent::_nil();
1340     }
1341     else
1342     {
1343       MESSAGE("SALOME_Container::create_component_instance successful");
1344       iobject = Engines::EngineComponent::_narrow(obj);
1345       _listInstances_map[instanceName] = iobject;
1346       return iobject._retn();
1347     }
1348   }
1349 }
1350
1351
1352 //=============================================================================
1353 //! Create a new component instance (Python implementation)
1354 /*! 
1355 *  \param CompName               Name of the component instance
1356 *  \param reason                 explains error when creation fails
1357 *  \return a loaded component
1358 */
1359 //=============================================================================
1360 Engines::EngineComponent_ptr
1361 Abstract_Engines_Container_i::createPythonInstance(std::string CompName,
1362                                           std::string& reason)
1363 {
1364   Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1365
1366   _numInstanceMutex.lock() ; // lock on the instance number
1367   _numInstance++ ;
1368   int numInstance = _numInstance ;
1369   _numInstanceMutex.unlock() ;
1370
1371   char aNumI[12];
1372   sprintf( aNumI , "%d" , numInstance ) ;
1373   std::string instanceName = CompName + "_inst_" + aNumI ;
1374   std::string component_registerName = _containerName + "/" + instanceName;
1375   std::string iors;
1376   {
1377     AutoGIL gstate;
1378     AutoPyRef result = PyObject_CallMethod(_pyCont,
1379                                           (char*)"create_component_instance",
1380                                           (char*)"ss",
1381                                           CompName.c_str(),
1382                                           instanceName.c_str());
1383     const char *ior;
1384     const char *error;
1385     PyArg_ParseTuple(result,"ss", &ior, &error);
1386     iors = ior;
1387     reason=error;
1388   }
1389
1390   if( iors!="" )
1391   {
1392     CORBA::Object_var obj = _orb->string_to_object(iors.c_str());
1393     iobject = Engines::EngineComponent::_narrow( obj ) ;
1394     _listInstances_map[instanceName] = iobject;
1395   }
1396   return iobject._retn();
1397 }
1398
1399 char *
1400 Abstract_Engines_Container_i::create_python_service_instance(const char * CompName,
1401                                                     CORBA::String_out reason)
1402 {
1403   CORBA::Object_var object = CORBA::Object::_nil();
1404
1405   _numInstanceMutex.lock() ; // lock on the instance number
1406   _numInstance++ ;
1407   int numInstance = _numInstance ;
1408   _numInstanceMutex.unlock() ;
1409
1410   char aNumI[12];
1411   sprintf( aNumI , "%d" , numInstance ) ;
1412   std::string instanceName = std::string(CompName) + "_inst_" + aNumI ;
1413   std::string component_registerName = _containerName + "/" + instanceName;
1414
1415   char * _ior = nullptr;
1416   {
1417     AutoGIL gstate;
1418     AutoPyRef result = PyObject_CallMethod(_pyCont,
1419                                           (char*)"create_component_instance",
1420                                           (char*)"ss",
1421                                           CompName,
1422                                           instanceName.c_str());
1423     const char *ior;
1424     const char *error;
1425     PyArg_ParseTuple(result,"ss", &ior, &error);
1426     reason = CORBA::string_dup(error);
1427     _ior = CORBA::string_dup(ior);
1428   }
1429   return _ior;
1430 }
1431
1432
1433 //=============================================================================
1434 //! Create a new component instance (C++ implementation)
1435 /*! 
1436 *  C++ method: create a servant instance of a component.
1437 *  \param genericRegisterName    Name of the component instance to register
1438 *                                in Registry & Name Service,
1439 *                                (without _inst_n suffix, like "COMPONENT")
1440 *  \param handle                 loaded library handle
1441 *  \param reason                 explains error when creation fails
1442 *  \return a loaded component
1443
1444 *  example with names:
1445 *    - aGenRegisterName = COMPONENT (= first argument)
1446 *    - _containerName = /Containers/cli76ce/FactoryServer
1447 *    - factoryName = COMPONENTEngine_factory
1448 *    - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
1449 *    - instanceName = COMPONENT_inst_1
1450 *    - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1451 */
1452 //=============================================================================
1453 Engines::EngineComponent_ptr
1454 Abstract_Engines_Container_i::createInstance(std::string genericRegisterName,
1455                                     void *handle,
1456                                     std::string& reason)
1457 {
1458   // --- find the factory
1459
1460   std::string aGenRegisterName = genericRegisterName;
1461   std::string factory_name = aGenRegisterName + std::string("Engine_factory");
1462   SCRUTE(factory_name) ;
1463
1464   typedef PortableServer::ObjectId* (*FACTORY_FUNCTION) (CORBA::ORB_ptr,
1465                                                          PortableServer::POA_ptr, 
1466                                                          PortableServer::ObjectId *, 
1467                                                          const char *, 
1468                                                          const char *) ;
1469
1470 #ifndef WIN32
1471   FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)dlsym( handle, factory_name.c_str() );
1472 #else
1473   FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)GetProcAddress( (HINSTANCE)handle, factory_name.c_str() );
1474 #endif
1475
1476   if ( !Component_factory )
1477   {
1478     MESSAGE( "Can't resolve symbol: " + factory_name );
1479 #ifndef WIN32
1480     reason=dlerror();
1481     MESSAGE(reason);
1482 #endif
1483     return Engines::EngineComponent::_nil() ;
1484   }
1485
1486   // --- create instance
1487
1488   Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1489
1490   try
1491   {
1492     _numInstanceMutex.lock() ; // lock on the instance number
1493     _numInstance++ ;
1494     int numInstance = _numInstance ;
1495     _numInstanceMutex.unlock() ;
1496
1497     char aNumI[12];
1498     sprintf( aNumI , "%d" , numInstance ) ;
1499     std::string instanceName = aGenRegisterName + "_inst_" + aNumI ;
1500     std::string component_registerName =
1501       _containerName + "/" + instanceName;
1502
1503     // --- Instantiate required CORBA object
1504
1505     PortableServer::ObjectId *id ; //not owner, do not delete (nore use var)
1506     id = (Component_factory) ( _orb, _poa, _id, instanceName.c_str(),
1507                                                 aGenRegisterName.c_str() ) ;
1508     if (id == NULL)
1509     {
1510       reason="Can't get ObjectId from factory";
1511       INFOS(reason);
1512       return iobject._retn();
1513     }
1514
1515     // --- get reference from id
1516
1517     CORBA::Object_var obj = _poa->id_to_reference(*id);
1518     iobject = Engines::EngineComponent::_narrow( obj ) ;
1519
1520     _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1521     _listInstances_map[instanceName] = iobject;
1522     _cntInstances_map[aGenRegisterName] += 1;
1523     _numInstanceMutex.unlock() ;
1524     SCRUTE(aGenRegisterName);
1525     SCRUTE(_cntInstances_map[aGenRegisterName]);
1526
1527     // --- register the engine under the name
1528     //     containerName(.dir)/instanceName(.object)
1529
1530     _NS->Register( iobject , component_registerName.c_str() ) ;
1531     MESSAGE( component_registerName.c_str() << " bound" ) ;
1532   }
1533   catch (...)
1534   {
1535     reason="Container_i::createInstance exception caught";
1536     INFOS(reason) ;
1537   }
1538   return iobject._retn();
1539 }
1540
1541 //=============================================================================
1542 //! Find an existing (in the container) component instance
1543 /*!
1544 *  CORBA method: Finds a servant instance of a component
1545 *  \param registeredName  Name of the component in Registry or Name Service,
1546 *                         without instance suffix number
1547 *  \return the first found instance
1548 */
1549 //=============================================================================
1550 Engines::EngineComponent_ptr
1551 Abstract_Engines_Container_i::find_component_instance( const char* registeredName)
1552 {
1553   Engines::EngineComponent_var anEngine = Engines::EngineComponent::_nil();
1554   std::map<std::string,Engines::EngineComponent_var>::iterator itm =_listInstances_map.begin();
1555   while (itm != _listInstances_map.end())
1556   {
1557     std::string instance = (*itm).first;
1558     SCRUTE(instance);
1559     if (instance.find(registeredName) == 0)
1560     {
1561       anEngine = (*itm).second;
1562       return anEngine._retn();
1563     }
1564     itm++;
1565   }
1566   return anEngine._retn();
1567 }
1568
1569 //=============================================================================
1570 //! Remove the component instance from container
1571 /*!
1572 *  CORBA method: Stops the component servant, and deletes all related objects
1573 *  \param component_i     Component to be removed
1574 */
1575 //=============================================================================
1576
1577 void Abstract_Engines_Container_i::remove_impl(Engines::EngineComponent_ptr component_i)
1578 {
1579   ASSERT(! CORBA::is_nil(component_i));
1580   std::string instanceName = component_i->instanceName() ;
1581   MESSAGE("unload component " << instanceName);
1582   _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1583   _listInstances_map.erase(instanceName);
1584   _numInstanceMutex.unlock() ;
1585   component_i->destroy() ;
1586   _NS->Destroy_Name(instanceName.c_str());
1587 }
1588
1589 //=============================================================================
1590 //! Unload component libraries from the container
1591 /*!
1592 *  CORBA method: Discharges unused libraries from the container.
1593 */
1594 //=============================================================================
1595 void Abstract_Engines_Container_i::finalize_removal()
1596 {
1597   MESSAGE("finalize unload : dlclose");
1598   _numInstanceMutex.lock(); // lock to be alone
1599   // (see decInstanceCnt, load_component_Library)
1600   std::map<std::string, void *>::iterator ith;
1601   for (ith = _toRemove_map.begin(); ith != _toRemove_map.end(); ith++)
1602   {
1603     void *handle = (*ith).second;
1604     std::string impl_name= (*ith).first;
1605     if (handle)
1606     {
1607       SCRUTE(handle);
1608       SCRUTE(impl_name);
1609       //        dlclose(handle);                // SALOME unstable after ...
1610       //        _library_map.erase(impl_name);
1611     }
1612   }
1613   _toRemove_map.clear();
1614   _numInstanceMutex.unlock();
1615 }
1616
1617 //=============================================================================
1618 //! Decrement component instance reference count
1619 /*!
1620 *
1621 */
1622 //=============================================================================
1623 void Abstract_Engines_Container_i::decInstanceCnt(std::string genericRegisterName)
1624 {
1625   if(_cntInstances_map.count(genericRegisterName)==0)
1626     return;
1627   std::string aGenRegisterName =genericRegisterName;
1628   MESSAGE("Engines_Container_i::decInstanceCnt " << aGenRegisterName);
1629   ASSERT(_cntInstances_map[aGenRegisterName] > 0);
1630   _numInstanceMutex.lock(); // lock to be alone
1631   // (see finalize_removal, load_component_Library)
1632   _cntInstances_map[aGenRegisterName] -= 1;
1633   SCRUTE(_cntInstances_map[aGenRegisterName]);
1634   if (_cntInstances_map[aGenRegisterName] == 0)
1635   {
1636     std::string impl_name =
1637       Engines_Component_i::GetDynLibraryName(aGenRegisterName.c_str());
1638     SCRUTE(impl_name);
1639     void* handle = _library_map[impl_name];
1640     ASSERT(handle);
1641     _toRemove_map[impl_name] = handle;
1642   }
1643   _numInstanceMutex.unlock();
1644 }
1645
1646 //=============================================================================
1647 //! Find or create a new component instance
1648 /*!
1649 *  CORBA method: find or create an instance of the component (servant),
1650 *  load a new component class (dynamic library) if required,
1651 *
1652 *  ---- FOR COMPATIBILITY WITH 2.2 ----
1653 *
1654 *  ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
1655 *
1656 *  The servant registers itself to naming service and Registry.
1657 *  \param genericRegisterName  Name of the component to register
1658 *                              in Registry & Name Service
1659 *  \param componentName       Name of the constructed library of the component
1660 *  \return a loaded component
1661 */
1662 //=============================================================================
1663
1664 Engines::EngineComponent_ptr
1665 Abstract_Engines_Container_i::load_impl( const char* genericRegisterName,
1666                                          const char* /*componentName*/ )
1667 {
1668   char* reason;
1669   std::string impl_name = std::string(LIB) + genericRegisterName + ENGINESO;
1670   Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1671   if (load_component_Library(genericRegisterName,reason))
1672     iobject = find_or_create_instance(genericRegisterName, impl_name);
1673   CORBA::string_free(reason);
1674   return iobject._retn();
1675 }
1676
1677 Engines::EmbeddedNamingService_ptr Abstract_Engines_Container_i::get_embedded_NS_if_ssl()
1678 {
1679   SALOME_Embedded_NamingService_Client *nsc(dynamic_cast<SALOME_Embedded_NamingService_Client *>(this->_NS));
1680   if(nsc)
1681   {
1682     Engines::EmbeddedNamingService_var obj = nsc->GetObject();
1683     return Engines::EmbeddedNamingService::_duplicate(obj);
1684   }
1685   else
1686   {
1687     SALOME_Fake_NamingService *fns(dynamic_cast<SALOME_Fake_NamingService *>(this->_NS));
1688     if(fns)
1689     {
1690       Engines::EmbeddedNamingService_var ret = GetEmbeddedNamingService();
1691       return ret._retn();
1692     }
1693     else
1694       return Engines::EmbeddedNamingService::_nil();
1695   } 
1696 }
1697
1698 //=============================================================================
1699 //! Finds an already existing component instance or create a new instance
1700 /*!
1701 *  C++ method: Finds an already existing servant instance of a component, or
1702 *              create an instance.
1703 *  ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
1704 *  \param genericRegisterName    Name of the component instance to register
1705 *                                in Registry & Name Service,
1706 *                                (without _inst_n suffix, like "COMPONENT")
1707 *  \param componentLibraryName   like "libCOMPONENTEngine.so"
1708 *  \return a loaded component
1709 *
1710 *  example with names:
1711 *    - aGenRegisterName = COMPONENT (= first argument)
1712 *    - impl_name = libCOMPONENTEngine.so (= second argument)
1713 *    - _containerName = /Containers/cli76ce/FactoryServer
1714 *    - factoryName = COMPONENTEngine_factory
1715 *    - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
1716 *    - instanceName = COMPONENT_inst_1
1717 *    - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1718 */
1719 //=============================================================================
1720
1721 Engines::EngineComponent_ptr
1722 Abstract_Engines_Container_i::find_or_create_instance(std::string genericRegisterName,
1723                                                       std::string componentLibraryName)
1724 {
1725   std::string aGenRegisterName = genericRegisterName;
1726   std::string impl_name = componentLibraryName;
1727   if (_library_map.count(impl_name) == 0)
1728   {
1729     INFOS("shared library " << impl_name <<" must be loaded before creating instance");
1730     return Engines::EngineComponent::_nil() ;
1731   }
1732   else
1733   {
1734     // --- find a registered instance in naming service, or create
1735
1736     void* handle = _library_map[impl_name];
1737     std::string component_registerBase =
1738       _containerName + "/" + aGenRegisterName;
1739     Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1740     std::string reason;
1741     try
1742     {
1743       CORBA::Object_var obj =
1744         _NS->ResolveFirst( component_registerBase.c_str());
1745       if ( CORBA::is_nil( obj ) )
1746       {
1747         iobject = createInstance(genericRegisterName,
1748                                  handle,
1749                                  reason);
1750       }
1751       else
1752       {
1753         iobject = Engines::EngineComponent::_narrow( obj ) ;
1754       }
1755     }
1756     catch (...)
1757     {
1758       INFOS( "Container_i::load_impl caught" ) ;
1759     }
1760     return iobject._retn();
1761   }
1762 }
1763
1764 //=============================================================================
1765 //! Indicate if container is a python one
1766 /*! 
1767 *  Retrieves only with container naming convention if it is a python container
1768 */
1769 //=============================================================================
1770 bool Abstract_Engines_Container_i::isPythonContainer(const char* ContainerName)
1771 {
1772   bool ret=false;
1773   size_t len=strlen(ContainerName);
1774   if(len>=2)
1775     if(strcmp(ContainerName+len-2,"Py")==0)
1776       ret=true;
1777   return ret;
1778 }
1779
1780 //=============================================================================
1781 //! Kill the container
1782 /*!
1783 *  CORBA method: Kill the container process with exit(0).
1784 *  To remove :  never returns !
1785 */
1786 //=============================================================================
1787 bool Abstract_Engines_Container_i::Kill_impl()
1788 {
1789   MESSAGE("Engines_Container_i::Kill() pid "<< getpid() << " containerName "
1790     << _containerName.c_str() << " machineName "
1791     << Kernel_Utils::GetHostname().c_str());
1792   INFOS("===============================================================");
1793   INFOS("= REMOVE calls to Kill_impl in C++ container                  =");
1794   INFOS("===============================================================");
1795   //_exit( 0 ) ;
1796   ASSERT(0);
1797   return false;
1798 }
1799
1800 //=============================================================================
1801 /*! 
1802 *  
1803 */
1804 //=============================================================================
1805 void ActSigIntHandler()
1806 {
1807 #ifndef WIN32
1808   struct sigaction SigIntAct ;
1809   SigIntAct.sa_sigaction = &SigIntHandler ;
1810   sigemptyset(&SigIntAct.sa_mask);
1811   SigIntAct.sa_flags = SA_SIGINFO ;
1812 #endif
1813
1814   // DEBUG 03.02.2005 : the first parameter of sigaction is not a mask of signals
1815   // (SIGINT | SIGUSR1) :
1816   // it must be only one signal ===> one call for SIGINT 
1817   // and an other one for SIGUSR1
1818
1819 #ifndef WIN32
1820   if ( sigaction( SIGINT , &SigIntAct, NULL ) ) 
1821   {
1822     perror("SALOME_Container main ") ;
1823     exit(0) ;
1824   }
1825   if ( sigaction( SIGUSR1 , &SigIntAct, NULL ) )
1826   {
1827     perror("SALOME_Container main ") ;
1828     exit(0) ;
1829   }
1830   if ( sigaction( SIGUSR2 , &SigIntAct, NULL ) )
1831   {
1832     perror("SALOME_Container main ") ;
1833     exit(0) ;
1834   }
1835
1836   //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1837   //             use of streams (and so on) should never be used because :
1838   //             streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1839   //             A stream operation may be interrupted by a signal and if the Handler use stream we
1840   //             may have a "Dead-Lock" ===HangUp
1841   //==INFOS is commented
1842   //  INFOS(pthread_self() << "SigIntHandler activated") ;
1843
1844 #else  
1845   signal( SIGINT, SigIntHandler );
1846 // legacy code required to supervisor. Commented in order to avoid problems on Windows 
1847 //  signal( SIGUSR1, SigIntHandler );
1848 #endif
1849
1850 }
1851
1852 void SetCpuUsed() ;
1853 void CallCancelThread() ;
1854
1855 #ifndef WIN32
1856 void SigIntHandler(int /*what*/ ,
1857                    siginfo_t * siginfo ,
1858                    void * /*toto*/ ) 
1859 {
1860   //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1861   //             use of streams (and so on) should never be used because :
1862   //             streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1863   //             A stream operation may be interrupted by a signal and if the Handler use stream we
1864   //             may have a "Dead-Lock" ===HangUp
1865   //==MESSAGE is commented
1866   //  MESSAGE(pthread_self() << "SigIntHandler what     " << what << std::endl
1867   //          << "              si_signo " << siginfo->si_signo << std::endl
1868   //          << "              si_code  " << siginfo->si_code << std::endl
1869   //          << "              si_pid   " << siginfo->si_pid) ;
1870
1871   if ( _Sleeping )
1872   {
1873     _Sleeping = false ;
1874     //     MESSAGE("SigIntHandler END sleeping.") ;
1875     return ;
1876   }
1877   else
1878   {
1879     ActSigIntHandler() ;
1880     if ( siginfo->si_signo == SIGUSR1 )
1881     {
1882       SetCpuUsed() ;
1883     }
1884     else if ( siginfo->si_signo == SIGUSR2 )
1885     {
1886       CallCancelThread() ;
1887     }
1888     else 
1889     {
1890       _Sleeping = true ;
1891       //      MESSAGE("SigIntHandler BEGIN sleeping.") ;
1892       int count = 0 ;
1893       while( _Sleeping )
1894       {
1895         sleep( 1 ) ;
1896         count += 1 ;
1897       }
1898       //      MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1899     }
1900     return ;
1901   }
1902 }
1903 #else // Case WIN32
1904 void SigIntHandler( int what )
1905 {
1906 #ifndef WIN32
1907   MESSAGE( pthread_self() << "SigIntHandler what     " << what << std::endl );
1908 #else
1909   MESSAGE( "SigIntHandler what     " << what << std::endl );
1910 #endif
1911   if ( _Sleeping )
1912   {
1913     _Sleeping = false ;
1914     MESSAGE("SigIntHandler END sleeping.") ;
1915     return ;
1916   }
1917   else
1918   {
1919     ActSigIntHandler() ;
1920     if ( what == SIGUSR1 )
1921     {
1922       SetCpuUsed() ;
1923     }
1924     else
1925     {
1926       _Sleeping = true ;
1927       MESSAGE("SigIntHandler BEGIN sleeping.") ;
1928       int count = 0 ;
1929       while( _Sleeping ) 
1930       {
1931         Sleep( 1000 ) ;
1932         count += 1 ;
1933       }
1934       MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1935     }
1936     return ;
1937   }
1938 }
1939 #endif
1940
1941 //=============================================================================
1942 //! Get or create a file reference object associated to a local file (to transfer it)
1943 /*!
1944 *  CORBA method: get or create a fileRef object associated to a local file
1945 *  (a file on the computer on which runs the container server), which stores
1946 *  a list of (machine, localFileName) corresponding to copies already done.
1947 *
1948 *  \param  origFileName absolute path for a local file to copy on other
1949 *          computers
1950 *  \return a fileRef object associated to the file.
1951 */
1952 //=============================================================================
1953 Engines::fileRef_ptr
1954 Abstract_Engines_Container_i::createFileRef(const char* origFileName)
1955 {
1956   std::string origName(origFileName);
1957   Engines::fileRef_var theFileRef = Engines::fileRef::_nil();
1958
1959   if (origName[0] != '/')
1960   {
1961     INFOS("path of file to copy must be an absolute path beginning with '/'");
1962     return Engines::fileRef::_nil();
1963   }
1964
1965   if (CORBA::is_nil(_fileRef_map[origName]))
1966   {
1967     CORBA::Object_var obj=_poa->id_to_reference(*_id);
1968     Engines::Container_var pCont = Engines::Container::_narrow(obj);
1969     fileRef_i* aFileRef = new fileRef_i(pCont, origFileName);
1970     theFileRef = Engines::fileRef::_narrow(aFileRef->_this());
1971     _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1972     _fileRef_map[origName] = theFileRef;
1973     _numInstanceMutex.unlock() ;
1974   }
1975
1976   theFileRef =  Engines::fileRef::_duplicate(_fileRef_map[origName]);
1977   ASSERT(! CORBA::is_nil(theFileRef));
1978   return theFileRef._retn();
1979 }
1980
1981 //=============================================================================
1982 //! Get a fileTransfer reference
1983 /*!
1984 *  CORBA method:
1985 *  \return a reference to the fileTransfer object
1986 */
1987 //=============================================================================
1988 Engines::fileTransfer_ptr
1989 Abstract_Engines_Container_i::getFileTransfer()
1990 {
1991   Engines::fileTransfer_var aFileTransfer
1992     = Engines::fileTransfer::_duplicate(_fileTransfer);
1993   return aFileTransfer._retn();
1994 }
1995
1996 //=============================================================================
1997 //! Create a Salome file
1998 //=============================================================================
1999 Engines::Salome_file_ptr
2000 Abstract_Engines_Container_i::createSalome_file(const char* origFileName)
2001 {
2002   std::string origName(origFileName);
2003   if (CORBA::is_nil(_Salome_file_map[origName]))
2004   {
2005     Salome_file_i* aSalome_file = new Salome_file_i();
2006     aSalome_file->setContainer(Engines::Container::_duplicate(this->_this()));
2007     try
2008     {
2009       aSalome_file->setLocalFile(origFileName);
2010       aSalome_file->recvFiles();
2011     }
2012     catch (const SALOME::SALOME_Exception& /*e*/) //!< TODO: unused variable
2013     {
2014       return Engines::Salome_file::_nil();
2015     }
2016
2017     Engines::Salome_file_var theSalome_file = Engines::Salome_file::_nil();
2018     theSalome_file = Engines::Salome_file::_narrow(aSalome_file->_this());
2019     _numInstanceMutex.lock() ; // lock to be alone (stl container write)
2020     _Salome_file_map[origName] = theSalome_file;
2021     _numInstanceMutex.unlock() ;
2022   }
2023
2024   Engines::Salome_file_ptr theSalome_file =
2025     Engines::Salome_file::_duplicate(_Salome_file_map[origName]);
2026   ASSERT(!CORBA::is_nil(theSalome_file));
2027   return theSalome_file;
2028 }
2029
2030 //=============================================================================
2031 /*! \brief copy a file from a remote host (container) to the local host
2032  * \param container the remote container
2033  * \param remoteFile the file to copy locally from the remote host into localFile
2034  * \param localFile the local file
2035  */
2036 //=============================================================================
2037 void Abstract_Engines_Container_i::copyFile(Engines::Container_ptr container, const char* remoteFile, const char* localFile)
2038 {
2039   Engines::fileTransfer_var fileTransfer = container->getFileTransfer();
2040
2041   FILE* fp;
2042   if ((fp = fopen(localFile,"wb")) == NULL)
2043   {
2044     INFOS("file " << localFile << " cannot be open for writing");
2045     return;
2046   }
2047
2048   CORBA::Long fileId = fileTransfer->open(remoteFile);
2049   if (fileId > 0)
2050   {
2051     Engines::fileBlock* aBlock;
2052     int toFollow = 1;
2053     int ctr=0;
2054     while (toFollow)
2055     {
2056       ctr++;
2057       //SCRUTE(ctr);
2058       aBlock = fileTransfer->getBlock(fileId);
2059       toFollow = aBlock->length();
2060       //SCRUTE(toFollow);
2061       CORBA::Octet *buf = aBlock->get_buffer();
2062       fwrite(buf, sizeof(CORBA::Octet), toFollow, fp);
2063       delete aBlock;
2064     }
2065     fclose(fp);
2066     MESSAGE("end of transfer");
2067     fileTransfer->close(fileId);
2068   }
2069   else
2070   {
2071     INFOS("open reference file for copy impossible");
2072   }
2073 }
2074
2075 //=============================================================================
2076 /*! \brief create a PyNode object to execute remote python code
2077  * \param nodeName the name of the node
2078  * \param code the python code to load
2079  * \return the PyNode
2080  */
2081 //=============================================================================
2082 Engines::PyNode_ptr Abstract_Engines_Container_i::createPyNode(const char* nodeName, const char* code)
2083 {
2084   Engines::PyNode_var node= Engines::PyNode::_nil();
2085   long ierr(-1);
2086   std::string astr;
2087   {
2088     AutoGIL gstate;
2089     PyObject *res = PyObject_CallMethod(_pyCont,
2090       (char*)"create_pynode",
2091       (char*)"ss",
2092       nodeName,
2093       code);
2094     if(res==NULL)
2095     {
2096       //internal error
2097       PyErr_Print();
2098       SALOME::ExceptionStruct es;
2099       es.type = SALOME::INTERNAL_ERROR;
2100       es.text = "can not create a python node";
2101       throw SALOME::SALOME_Exception(es);
2102     }
2103     ierr=PyLong_AsLong(PyTuple_GetItem(res,0));
2104     PyObject* result=PyTuple_GetItem(res,1);
2105     astr = PyUnicode_AsUTF8(result);
2106     Py_DECREF(res);
2107   }
2108   if(ierr==0)
2109   {
2110     Utils_Locker lck(&_mutexForDftPy);
2111     CORBA::Object_var obj=_orb->string_to_object(astr.c_str());
2112     node=Engines::PyNode::_narrow(obj);
2113     std::map<std::string,Engines::PyNode_var>::iterator it(_dftPyNode.find(nodeName));
2114     if(it==_dftPyNode.end())
2115     {
2116       _dftPyNode[nodeName]=node;
2117     }
2118     else
2119     {
2120       Engines::PyNode_var oldNode((*it).second);
2121       if(!CORBA::is_nil(oldNode))
2122         oldNode->UnRegister();
2123       (*it).second=node;
2124     }
2125     if(!CORBA::is_nil(node))
2126       node->Register();
2127     return node._retn();
2128   }
2129   else
2130   {
2131     SALOME::ExceptionStruct es;
2132     es.type = SALOME::INTERNAL_ERROR;
2133     es.text = astr.c_str();
2134     throw SALOME::SALOME_Exception(es);
2135   }
2136 }
2137
2138 //=============================================================================
2139 /*! \brief Retrieves the last created PyNode instance with createPyNode.
2140  *
2141  */
2142 //=============================================================================
2143 Engines::PyNode_ptr Abstract_Engines_Container_i::getDefaultPyNode(const char *nodeName)
2144 {
2145   Utils_Locker lck(&_mutexForDftPy);
2146   std::map<std::string,Engines::PyNode_var>::iterator it(_dftPyNode.find(nodeName));
2147   if(it==_dftPyNode.end())
2148     return Engines::PyNode::_nil();
2149   else
2150   {
2151     Engines::PyNode_var tmpVar((*it).second);
2152     if(!CORBA::is_nil(tmpVar))
2153       return Engines::PyNode::_duplicate(tmpVar);
2154     else
2155       return Engines::PyNode::_nil();
2156   }
2157 }
2158
2159 //=============================================================================
2160 /*! \brief create a PyScriptNode object to execute remote python code
2161  * \param nodeName the name of the node
2162  * \param code the python code to load
2163  * \return the PyScriptNode
2164  */
2165 //=============================================================================
2166 Engines::PyScriptNode_ptr Abstract_Engines_Container_i::createPyScriptNode(const char* nodeName, const char* code)
2167 {
2168   Engines::PyScriptNode_var node= Engines::PyScriptNode::_nil();
2169   long ierr(-1);
2170   std::string astr;
2171   {
2172     AutoGIL gstate;
2173     AutoPyRef res = PyObject_CallMethod(_pyCont,
2174       (char*)"create_pyscriptnode",
2175       (char*)"ss",
2176       nodeName,
2177       code);
2178     if( res.isNull() )
2179     {
2180       //internal error
2181       PyErr_Print();
2182       SALOME::ExceptionStruct es;
2183       es.type = SALOME::INTERNAL_ERROR;
2184       es.text = "can not create a python node";
2185       throw SALOME::SALOME_Exception(es);
2186     }
2187     ierr=PyLong_AsLong(PyTuple_GetItem(res,0));
2188     PyObject* result=PyTuple_GetItem(res,1);
2189     astr = PyUnicode_AsUTF8(result);
2190   }
2191
2192   if(ierr==0)
2193   {
2194     Utils_Locker lck(&_mutexForDftPy);
2195     CORBA::Object_var obj=_orb->string_to_object(astr.c_str());
2196     node=Engines::PyScriptNode::_narrow(obj);
2197     std::map<std::string,Engines::PyScriptNode_var>::iterator it(_dftPyScriptNode.find(nodeName));
2198     if(it==_dftPyScriptNode.end())
2199     {
2200       _dftPyScriptNode[nodeName]=node;
2201     }
2202     else
2203     {
2204       Engines::PyScriptNode_var oldNode((*it).second);
2205       if(!CORBA::is_nil(oldNode))
2206         oldNode->UnRegister();
2207       (*it).second=node;
2208     }
2209     return node._retn();
2210   }
2211   else
2212   {
2213     SALOME::ExceptionStruct es;
2214     es.type = SALOME::INTERNAL_ERROR;
2215     es.text = astr.c_str();
2216     throw SALOME::SALOME_Exception(es);
2217   }
2218 }
2219
2220 void Abstract_Engines_Container_i::removePyScriptNode(const char *nodeName)
2221 {
2222   std::map<std::string,Engines::PyScriptNode_var>::iterator it(_dftPyScriptNode.find(nodeName));
2223   if(it==_dftPyScriptNode.end())
2224     {
2225       std::ostringstream oss; oss << "Engines_Container_i::removePyScriptNode : node \"" << nodeName << "\" is not map !";
2226       SALOME::ExceptionStruct es;
2227       es.type = SALOME::INTERNAL_ERROR;
2228       es.text = oss.str().c_str();
2229       throw SALOME::SALOME_Exception(es);
2230     }
2231   (*it).second->UnRegister();
2232   _dftPyScriptNode.erase(it);
2233 }
2234
2235 void Abstract_Engines_Container_i::cleanAllPyScripts()
2236 {
2237   for(std::map<std::string,Engines::PyNode_var>::iterator it=_dftPyNode.begin();it!=_dftPyNode.end();it++)
2238     {
2239       Engines::PyNode_var tmpVar((*it).second);
2240       if(!CORBA::is_nil(tmpVar))
2241         tmpVar->UnRegister();
2242     }
2243   _dftPyNode.clear();
2244   for(std::map<std::string,Engines::PyScriptNode_var>::iterator it=_dftPyScriptNode.begin();it!=_dftPyScriptNode.end();it++)
2245     {
2246       Engines::PyScriptNode_var tmpVar((*it).second);
2247       if(!CORBA::is_nil(tmpVar))
2248         tmpVar->UnRegister();
2249     }
2250   _dftPyScriptNode.clear();
2251 }
2252
2253 //=============================================================================
2254 /*! \brief Retrieves the last created PyScriptNode instance with createPyScriptNode.
2255  *
2256  */
2257 //=============================================================================
2258 Engines::PyScriptNode_ptr Abstract_Engines_Container_i::getDefaultPyScriptNode(const char *nodeName)
2259 {
2260   Utils_Locker lck(&_mutexForDftPy);
2261   std::map<std::string,Engines::PyScriptNode_var>::iterator it(_dftPyScriptNode.find(nodeName));
2262   if(it==_dftPyScriptNode.end())
2263     return Engines::PyScriptNode::_nil();
2264   else
2265   {
2266     Engines::PyScriptNode_var tmpVar((*it).second);
2267     if(!CORBA::is_nil(tmpVar))
2268       return Engines::PyScriptNode::_duplicate(tmpVar);
2269     else
2270       return Engines::PyScriptNode::_nil();
2271   }
2272 }
2273
2274 //=============================================================================
2275 /* int checkifexecutable(const char *filename)
2276 *
2277 * Return non-zero if the name is an executable file, and
2278 * zero if it is not executable, or if it does not exist.
2279 */
2280 //=============================================================================
2281 int checkifexecutable(const std::string& filename)
2282 {
2283   int result;
2284   struct stat statinfo;
2285
2286   result = stat(filename.c_str(), &statinfo);
2287   if (result < 0) return 0;
2288   if (!S_ISREG(statinfo.st_mode)) return 0;
2289
2290 #ifdef WIN32
2291   return 1;
2292 #else
2293   if (statinfo.st_uid == geteuid()) return statinfo.st_mode & S_IXUSR;
2294   if (statinfo.st_gid == getegid()) return statinfo.st_mode & S_IXGRP;
2295   return statinfo.st_mode & S_IXOTH;
2296 #endif
2297 }
2298
2299
2300 //=============================================================================
2301 /*! \brief Find a file by searching in a path
2302  *  \param filename file name to search
2303  *  \param path path to search in
2304  *  \param pth the complete file path if found
2305  *  \return 1 if found 0 if not 
2306 */
2307 //=============================================================================
2308 int findpathof(const std::string& path, std::string& pth, const std::string& filename)
2309 {
2310   if ( path.size() == 0 ) return 0;
2311
2312   std::string::size_type offset = 0;
2313   std::string::size_type pos = 0;
2314   int found = 0;
2315   struct stat statinfo;
2316
2317   while(!found)
2318   {
2319     pos = path.find( SEP, offset );
2320     pth = path.substr( offset, pos - offset );
2321     if ( pth.size() > 0 )
2322     {
2323       if( pth[pth.size()-1] != SLASH ) pth += SLASH;
2324       pth += filename;
2325       int result=stat(pth.c_str(), &statinfo);
2326       if(result == 0) found=1;
2327     }
2328     if (pos == std::string::npos) break;
2329     offset = pos+1;
2330   }
2331   return found;
2332 }
2333
2334 void Abstract_Engines_Container_i::registerTemporaryFile( const std::string& fileName )
2335 {
2336   _tmp_files.remove( fileName );
2337   _tmp_files.push_back( fileName );
2338 }
2339
2340 void Abstract_Engines_Container_i::unregisterTemporaryFile( const std::string& fileName )
2341 {
2342   _tmp_files.remove( fileName );
2343 }
2344
2345 void Abstract_Engines_Container_i::clearTemporaryFiles()
2346 {
2347   std::list<std::string>::const_iterator it;
2348   for ( it = _tmp_files.begin(); it != _tmp_files.end(); ++it ) {
2349 #if defined(WIN32) && defined(UNICODE)
2350         std::wstring aFile = Kernel_Utils::utf8_decode_s(*it);
2351         std::wstring command = (GetFileAttributes(aFile.c_str()) == FILE_ATTRIBUTE_DIRECTORY) ? L"rd /Q \"" : L"del /F /Q \"";
2352         command += aFile;
2353         command += L"\" 2>NUL";
2354         _wsystem(command.c_str());
2355 #else
2356 #if defined(WIN32)
2357         std::string aFile = *it;
2358         std::string command = (GetFileAttributes(aFile.c_str()) == FILE_ATTRIBUTE_DIRECTORY) ? "rd /Q \"" : "del /F /Q \"";
2359         command += aFile;
2360         command += "\" 2>NUL";
2361 #else
2362         std::string command = "rm -rf ";
2363         command += *it;
2364 #endif
2365         system(command.c_str());
2366 #endif
2367   }
2368   _tmp_files.clear();
2369 }
2370
2371 static Engines_Container_SSL_i *_container_singleton_ssl = nullptr;
2372
2373 static Engines::Container_var _container_ref_singleton_ssl;
2374
2375 Engines_Container_SSL_i *KERNEL::getContainerSA()
2376 {
2377   if(!_container_singleton_ssl)
2378   {
2379     CORBA::ORB_var orb = KERNEL::GetRefToORB();
2380     CORBA::Object_var obj = orb->resolve_initial_references("RootPOA");
2381     PortableServer::POA_var poa = PortableServer::POA::_narrow(obj);
2382     PortableServer::POAManager_var pman = poa->the_POAManager();
2383     CORBA::PolicyList policies;
2384     policies.length(0);
2385     //
2386     constexpr int ARGC = 4;
2387     constexpr const char *ARGV[ARGC] = {"Container","FactoryServer","toto",nullptr};
2388     std::unique_ptr<char*[]> argv( new char *[ARGC+1] );
2389     std::vector< std::unique_ptr<char[]> > argvv(ARGC);
2390     argv[ARGC] = nullptr;
2391     for(int i = 0 ; i < ARGC ; ++i)
2392     {
2393       if(ARGV[i])
2394       {
2395         argvv[i].reset( new char[strlen(ARGV[i])+1] );
2396         strcpy(argvv[i].get(),ARGV[i]);
2397         argv[i] = argvv[i].get();
2398       }
2399       else
2400         argv[i] = nullptr;
2401     }
2402     SALOME_Fake_NamingService ns;
2403     _container_singleton_ssl = new Engines_Container_SSL_i(orb,poa,(char *)"FactoryServer",2,argv.get(),&ns,false);
2404     PortableServer::ObjectId * cont_id = _container_singleton_ssl->getCORBAId();
2405     //
2406     CORBA::Object_var zeRef = poa->id_to_reference(*cont_id);
2407     _container_ref_singleton_ssl = Engines::Container::_narrow(zeRef);
2408   }
2409   return _container_singleton_ssl;
2410 }
2411
2412 Engines::Container_var KERNEL::getContainerRefSA()
2413 {
2414   getContainerSA();
2415   return _container_ref_singleton_ssl;
2416 }