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