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