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