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