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