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