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