Salome HOME
CCAR: reset temporary file name attribute
[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::Component_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::Component_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::Component_ptr compo = create_component_instance_env(genericRegisterName, studyId, env, reason);
654   CORBA::string_free(reason);
655   return compo;
656 }
657
658 //=============================================================================
659 //! Create a new component instance with environment variables specified
660 /*! 
661 *  CORBA method: Creates a new servant instance of a component.
662 *  The servant registers itself to naming service and Registry.
663 *  \param genericRegisterName  Name of the component instance to register
664 *                         in Registry & Name Service (without _inst_n suffix)
665 *  \param studyId         0 for multiStudy instance, 
666 *                         study Id (>0) otherwise
667 *  \param env             dict of env variables
668 *  \param reason          explains error when create_component_instance_env fails
669 *  \return a loaded component
670 */
671 //=============================================================================
672 Engines::Component_ptr
673 Engines_Container_i::create_component_instance_env(const char*genericRegisterName,
674                                                    CORBA::Long studyId,
675                                                    const Engines::FieldsDict& env,
676                                                    CORBA::String_out reason)
677 {
678   if (studyId < 0)
679     {
680       INFOS("studyId must be > 0 for mono study instance, =0 for multiStudy");
681       reason=CORBA::string_dup("studyId must be > 0 for mono study instance, =0 for multiStudy");
682       return Engines::Component::_nil() ;
683     }
684
685   std::string error;
686   if (_library_map.count(genericRegisterName) != 0)
687     {
688       // It's a Python component
689       Engines::Component_ptr compo = createPythonInstance(genericRegisterName, studyId, error);
690       reason=CORBA::string_dup(error.c_str());
691       return compo;
692     }
693
694   std::string impl_name = std::string(LIB) + genericRegisterName + ENGINESO;
695   if (_library_map.count(impl_name) != 0)
696     {
697       // It's a C++ component
698       void* handle = _library_map[impl_name];
699       Engines::Component_ptr compo = createInstance(genericRegisterName, handle, studyId, error);
700       reason=CORBA::string_dup(error.c_str());
701       return compo;
702     }
703
704   impl_name = std::string(genericRegisterName) + ".exe";
705   if (_library_map.count(impl_name) != 0)
706     {
707       //It's an executable component
708       Engines::Component_ptr compo = createExecutableInstance(genericRegisterName, studyId, env, error);
709       reason=CORBA::string_dup(error.c_str());
710       return compo;
711     }
712
713   error="load_component_Library has probably not been called for component: ";
714   error += genericRegisterName;
715   INFOS(error);
716   reason=CORBA::string_dup(error.c_str());
717   return Engines::Component::_nil() ;
718 }
719
720 //=============================================================================
721 //! Create a new component instance (Executable implementation)
722 /*! 
723 *  \param CompName               Name of the component instance
724 *  \param studyId                0 for multiStudy instance, 
725 *                                study Id (>0) otherwise
726 *  \param env                    dict of env variables
727 *  \param reason                 explains error when creation fails
728 *  \return a loaded component
729 *
730 *   This component is implemented in an executable with name genericRegisterName.exe
731 *   It must register itself in Naming Service. The container waits some time (10 s max)
732 *   it's registration.
733 */
734 //=============================================================================
735 Engines::Component_ptr
736 Engines_Container_i::createExecutableInstance(std::string CompName, int studyId,
737                                               const Engines::FieldsDict& env,
738                                               std::string& reason)
739 {
740   Engines::Component_var iobject = Engines::Component::_nil() ;
741
742   _numInstanceMutex.lock() ; // lock on the instance number
743   _numInstance++ ;
744   int numInstance = _numInstance ;
745   _numInstanceMutex.unlock() ;
746
747   char aNumI[12];
748   sprintf( aNumI , "%d" , numInstance ) ;
749   std::string instanceName = CompName + "_inst_" + aNumI ;
750   std::string component_registerName = _containerName + "/" + instanceName;
751
752   //check if an entry exist in naming service
753   CORBA::Object_var nsobj = _NS->Resolve(component_registerName.c_str());
754   if ( !CORBA::is_nil(nsobj) )
755   {
756     // unregister the registered component
757     _NS->Destroy_Name(component_registerName.c_str());
758     //kill or shutdown it ???
759   }
760
761   // first arg container ior string
762   // second arg container name
763   // third arg instance name
764
765   Engines::Container_var pCont= _this();
766   CORBA::String_var sior =  _orb->object_to_string(pCont);
767
768   std::string command;
769   command="mkdir -p ";
770   command+=instanceName;
771   command+=";cd ";
772   command+=instanceName;
773   command+=";";
774   command+=CompName ;
775   command+=".exe";
776   command+=" ";
777   command+= sior; // container ior string
778   command+=" ";
779   command+=_containerName; //container name
780   command+=" ";
781   command+=instanceName; //instance name
782   command+=" &";
783   MESSAGE("SALOME_Container::create_component_instance command=" << command);
784
785 #ifndef WIN32
786   // use fork/execl instead of system to get finer control on env variables
787   int status;
788   pid_t pid = fork();
789   if(pid == 0) // child
790     {
791       for (CORBA::ULong i=0; i < env.length(); i++)
792         {
793           if (env[i].value.type()->kind() == CORBA::tk_string)
794             {
795               const char* value;
796               env[i].value >>= value;
797               std::string s(env[i].key);
798               s+='=';
799               s+=value;
800               putenv(strdup(s.c_str()));
801             }
802         }
803
804       execl("/bin/sh", "sh", "-c", command.c_str() , (char *)0);
805       status=-1;
806     }
807   else if(pid < 0)       // failed to fork
808     {
809       status=-1;
810     }
811   else            //parent
812     {
813       pid_t tpid;
814       do
815         {
816           tpid = wait(&status);
817         } while (tpid != pid);
818     }
819 #else
820   // launch component with a system call
821   int status=system(command.c_str());
822 #endif
823
824   if (status == -1)
825   {
826     reason="SALOME_Container::create_component_instance system failed (system command status -1)";
827     MESSAGE(reason);
828     return Engines::Component::_nil();
829   }
830 #ifndef WIN32
831   else if (WEXITSTATUS(status) == 217)
832   {
833     reason="SALOME_Container::create_component_instance system failed (system command status 217)";
834     MESSAGE(reason);
835     return Engines::Component::_nil();
836   }
837 #endif
838   else
839   {
840     int count=20;
841     CORBA::Object_var obj = CORBA::Object::_nil() ;
842     while ( CORBA::is_nil(obj) && count )
843     {
844 #ifndef WIN32
845       sleep( 1 ) ;
846 #else
847       Sleep(1000);
848 #endif
849       count-- ;
850       MESSAGE( count << ". Waiting for component " << CompName);
851       obj = _NS->Resolve(component_registerName.c_str());
852     }
853
854     if(CORBA::is_nil(obj))
855     {
856       reason="SALOME_Container::create_component_instance failed";
857       MESSAGE(reason);
858       return Engines::Component::_nil();
859     }
860     else
861     {
862       MESSAGE("SALOME_Container::create_component_instance successful");
863       iobject=Engines::Component::_narrow(obj);
864       _listInstances_map[instanceName] = iobject;
865       return iobject._retn();
866     }
867   }
868 }
869
870
871 //=============================================================================
872 //! Create a new component instance (Python implementation)
873 /*! 
874 *  \param CompName               Name of the component instance
875 *  \param studyId                0 for multiStudy instance, 
876 *                                study Id (>0) otherwise
877 *  \param reason                 explains error when creation fails
878 *  \return a loaded component
879 */
880 //=============================================================================
881 Engines::Component_ptr
882 Engines_Container_i::createPythonInstance(std::string CompName, int studyId,
883                                           std::string& reason)
884 {
885   Engines::Component_var iobject = Engines::Component::_nil() ;
886
887   _numInstanceMutex.lock() ; // lock on the instance number
888   _numInstance++ ;
889   int numInstance = _numInstance ;
890   _numInstanceMutex.unlock() ;
891
892   char aNumI[12];
893   sprintf( aNumI , "%d" , numInstance ) ;
894   std::string instanceName = CompName + "_inst_" + aNumI ;
895   std::string component_registerName = _containerName + "/" + instanceName;
896
897   PyGILState_STATE gstate = PyGILState_Ensure();
898   PyObject *result = PyObject_CallMethod(_pyCont,
899                                          (char*)"create_component_instance",
900                                          (char*)"ssl",
901                                          CompName.c_str(),
902                                          instanceName.c_str(),
903                                          studyId);
904   const char *ior;
905   const char *error;
906   PyArg_ParseTuple(result,"ss", &ior, &error);
907   std::string iors = ior;
908   reason=error;
909   Py_DECREF(result);
910   PyGILState_Release(gstate);
911
912   if( iors!="" )
913     {
914       CORBA::Object_var obj = _orb->string_to_object(iors.c_str());
915       iobject = Engines::Component::_narrow( obj ) ;
916       _listInstances_map[instanceName] = iobject;
917     }
918   return iobject._retn();
919 }
920
921 //=============================================================================
922 //! Create a new component instance (C++ implementation)
923 /*! 
924 *  C++ method: create a servant instance of a component.
925 *  \param genericRegisterName    Name of the component instance to register
926 *                                in Registry & Name Service,
927 *                                (without _inst_n suffix, like "COMPONENT")
928 *  \param handle                 loaded library handle
929 *  \param studyId                0 for multiStudy instance, 
930 *                                study Id (>0) otherwise
931 *  \param reason                 explains error when creation fails
932 *  \return a loaded component
933
934 *  example with names:
935 *    - aGenRegisterName = COMPONENT (= first argument)
936 *    - _containerName = /Containers/cli76ce/FactoryServer
937 *    - factoryName = COMPONENTEngine_factory
938 *    - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
939 *    - instanceName = COMPONENT_inst_1
940 *    - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
941 */
942 //=============================================================================
943 Engines::Component_ptr
944 Engines_Container_i::createInstance(std::string genericRegisterName,
945                                     void *handle,
946                                     int studyId,
947                                     std::string& reason)
948 {
949   // --- find the factory
950
951   std::string aGenRegisterName = genericRegisterName;
952   std::string factory_name = aGenRegisterName + std::string("Engine_factory");
953   SCRUTE(factory_name) ;
954
955   typedef PortableServer::ObjectId* (*FACTORY_FUNCTION) (CORBA::ORB_ptr,
956                                                          PortableServer::POA_ptr, 
957                                                          PortableServer::ObjectId *, 
958                                                          const char *, 
959                                                          const char *) ;
960
961 #ifndef WIN32
962   FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)dlsym( handle, factory_name.c_str() );
963 #else
964   FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)GetProcAddress( (HINSTANCE)handle, factory_name.c_str() );
965 #endif
966
967   if ( !Component_factory )
968   {
969     INFOS( "Can't resolve symbol: " + factory_name );
970 #ifndef WIN32
971     reason=dlerror();
972     INFOS(reason);
973 #endif
974     return Engines::Component::_nil() ;
975   }
976
977   // --- create instance
978
979   Engines::Component_var iobject = Engines::Component::_nil() ;
980
981   try
982   {
983     _numInstanceMutex.lock() ; // lock on the instance number
984     _numInstance++ ;
985     int numInstance = _numInstance ;
986     _numInstanceMutex.unlock() ;
987
988     char aNumI[12];
989     sprintf( aNumI , "%d" , numInstance ) ;
990     std::string instanceName = aGenRegisterName + "_inst_" + aNumI ;
991     std::string component_registerName =
992       _containerName + "/" + instanceName;
993
994     // --- Instanciate required CORBA object
995
996     PortableServer::ObjectId *id ; //not owner, do not delete (nore use var)
997     id = (Component_factory) ( _orb, _poa, _id, instanceName.c_str(),
998                                                 aGenRegisterName.c_str() ) ;
999     if (id == NULL)
1000       {
1001         reason="Can't get ObjectId from factory";
1002         INFOS(reason);
1003         return iobject._retn();
1004       }
1005
1006     // --- get reference & servant from id
1007
1008     CORBA::Object_var obj = _poa->id_to_reference(*id);
1009     iobject = Engines::Component::_narrow( obj ) ;
1010
1011     Engines_Component_i *servant =
1012       dynamic_cast<Engines_Component_i*>(_poa->reference_to_servant(iobject));
1013     ASSERT(servant);
1014     //SCRUTE(servant->_refcount_value());
1015     _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1016     _listInstances_map[instanceName] = iobject;
1017     _cntInstances_map[aGenRegisterName] += 1;
1018     _numInstanceMutex.unlock() ;
1019     SCRUTE(aGenRegisterName);
1020     SCRUTE(_cntInstances_map[aGenRegisterName]);
1021     servant->setStudyId(studyId);
1022     servant->_remove_ref(); // do not need servant any more (remove ref from reference_to_servant)
1023     //SCRUTE(servant->_refcount_value());
1024
1025     // --- register the engine under the name
1026     //     containerName(.dir)/instanceName(.object)
1027
1028     _NS->Register( iobject , component_registerName.c_str() ) ;
1029     MESSAGE( component_registerName.c_str() << " bound" ) ;
1030   }
1031   catch (...)
1032   {
1033     reason="Container_i::createInstance exception catched";
1034     INFOS(reason) ;
1035   }
1036   return iobject._retn();
1037 }
1038
1039 //=============================================================================
1040 //! Find an existing (in the container) component instance
1041 /*!
1042 *  CORBA method: Finds a servant instance of a component
1043 *  \param registeredName  Name of the component in Registry or Name Service,
1044 *                         without instance suffix number
1045 *  \param studyId         0 if instance is not associated to a study,
1046 *                         >0 otherwise (== study id)
1047 *  \return the first instance found with same studyId
1048 */
1049 //=============================================================================
1050 Engines::Component_ptr
1051 Engines_Container_i::find_component_instance( const char* registeredName,
1052                                               CORBA::Long studyId)
1053 {
1054   Engines::Component_var anEngine = Engines::Component::_nil();
1055   std::map<std::string,Engines::Component_var>::iterator itm =_listInstances_map.begin();
1056   while (itm != _listInstances_map.end())
1057   {
1058     std::string instance = (*itm).first;
1059     SCRUTE(instance);
1060     if (instance.find(registeredName) == 0)
1061     {
1062       anEngine = (*itm).second;
1063       if (studyId == anEngine->getStudyId())
1064       {
1065         return anEngine._retn();
1066       }
1067     }
1068     itm++;
1069   }
1070   return anEngine._retn();
1071 }
1072
1073 //=============================================================================
1074 //! Remove the component instance from container
1075 /*!
1076 *  CORBA method: Stops the component servant, and deletes all related objects
1077 *  \param component_i     Component to be removed
1078 */
1079 //=============================================================================
1080
1081 void Engines_Container_i::remove_impl(Engines::Component_ptr component_i)
1082 {
1083   ASSERT(! CORBA::is_nil(component_i));
1084   std::string instanceName = component_i->instanceName() ;
1085   MESSAGE("unload component " << instanceName);
1086   _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1087   _listInstances_map.erase(instanceName);
1088   _numInstanceMutex.unlock() ;
1089   component_i->destroy() ;
1090   _NS->Destroy_Name(instanceName.c_str());
1091 }
1092
1093 //=============================================================================
1094 //! Unload component libraries from the container
1095 /*!
1096 *  CORBA method: Discharges unused libraries from the container.
1097 */
1098 //=============================================================================
1099 void Engines_Container_i::finalize_removal()
1100 {
1101   MESSAGE("finalize unload : dlclose");
1102   _numInstanceMutex.lock(); // lock to be alone
1103   // (see decInstanceCnt, load_component_Library)
1104   std::map<std::string, void *>::iterator ith;
1105   for (ith = _toRemove_map.begin(); ith != _toRemove_map.end(); ith++)
1106   {
1107     void *handle = (*ith).second;
1108     std::string impl_name= (*ith).first;
1109     if (handle)
1110     {
1111       SCRUTE(handle);
1112       SCRUTE(impl_name);
1113       //        dlclose(handle);                // SALOME unstable after ...
1114       //        _library_map.erase(impl_name);
1115     }
1116   }
1117   _toRemove_map.clear();
1118   _numInstanceMutex.unlock();
1119 }
1120
1121 //=============================================================================
1122 //! Decrement component instance reference count
1123 /*!
1124 *
1125 */
1126 //=============================================================================
1127 void Engines_Container_i::decInstanceCnt(std::string genericRegisterName)
1128 {
1129   if(_cntInstances_map.count(genericRegisterName)==0)
1130     return;
1131   std::string aGenRegisterName =genericRegisterName;
1132   MESSAGE("Engines_Container_i::decInstanceCnt " << aGenRegisterName);
1133   ASSERT(_cntInstances_map[aGenRegisterName] > 0);
1134   _numInstanceMutex.lock(); // lock to be alone
1135   // (see finalize_removal, load_component_Library)
1136   _cntInstances_map[aGenRegisterName] -= 1;
1137   SCRUTE(_cntInstances_map[aGenRegisterName]);
1138   if (_cntInstances_map[aGenRegisterName] == 0)
1139   {
1140     std::string impl_name =
1141       Engines_Component_i::GetDynLibraryName(aGenRegisterName.c_str());
1142     SCRUTE(impl_name);
1143     void* handle = _library_map[impl_name];
1144     ASSERT(handle);
1145     _toRemove_map[impl_name] = handle;
1146   }
1147   _numInstanceMutex.unlock();
1148 }
1149
1150 //=============================================================================
1151 //! Find or create a new component instance
1152 /*!
1153 *  CORBA method: find or create an instance of the component (servant),
1154 *  load a new component class (dynamic library) if required,
1155 *
1156 *  ---- FOR COMPATIBILITY WITH 2.2 ----
1157 *
1158 *  ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
1159 *
1160 *  The servant registers itself to naming service and Registry.
1161 *  \param genericRegisterName  Name of the component to register
1162 *                              in Registry & Name Service
1163 *  \param componentName       Name of the constructed library of the component
1164 *  \return a loaded component
1165 */
1166 //=============================================================================
1167
1168 Engines::Component_ptr
1169 Engines_Container_i::load_impl( const char* genericRegisterName,
1170                                 const char* componentName )
1171 {
1172   char* reason;
1173   std::string impl_name = std::string(LIB) + genericRegisterName + ENGINESO;
1174   Engines::Component_var iobject = Engines::Component::_nil() ;
1175   if (load_component_Library(genericRegisterName,reason))
1176     iobject = find_or_create_instance(genericRegisterName, impl_name);
1177   CORBA::string_free(reason);
1178   return iobject._retn();
1179 }
1180
1181 //=============================================================================
1182 //! Finds an already existing component instance or create a new instance
1183 /*!
1184 *  C++ method: Finds an already existing servant instance of a component, or
1185 *              create an instance.
1186 *  ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
1187 *  \param genericRegisterName    Name of the component instance to register
1188 *                                in Registry & Name Service,
1189 *                                (without _inst_n suffix, like "COMPONENT")
1190 *  \param componentLibraryName   like "libCOMPONENTEngine.so"
1191 *  \return a loaded component
1192 *
1193 *  example with names:
1194 *    - aGenRegisterName = COMPONENT (= first argument)
1195 *    - impl_name = libCOMPONENTEngine.so (= second argument)
1196 *    - _containerName = /Containers/cli76ce/FactoryServer
1197 *    - factoryName = COMPONENTEngine_factory
1198 *    - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
1199 *    - instanceName = COMPONENT_inst_1
1200 *    - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1201 */
1202 //=============================================================================
1203
1204 Engines::Component_ptr
1205 Engines_Container_i::find_or_create_instance(std::string genericRegisterName,
1206                                              std::string componentLibraryName)
1207 {
1208   std::string aGenRegisterName = genericRegisterName;
1209   std::string impl_name = componentLibraryName;
1210   if (_library_map.count(impl_name) == 0)
1211   {
1212     INFOS("shared library " << impl_name <<" must be loaded before creating instance");
1213     return Engines::Component::_nil() ;
1214   }
1215   else
1216   {
1217     // --- find a registered instance in naming service, or create
1218
1219     void* handle = _library_map[impl_name];
1220     std::string component_registerBase =
1221       _containerName + "/" + aGenRegisterName;
1222     Engines::Component_var iobject = Engines::Component::_nil() ;
1223     std::string reason;
1224     try
1225     {
1226       CORBA::Object_var obj =
1227         _NS->ResolveFirst( component_registerBase.c_str());
1228       if ( CORBA::is_nil( obj ) )
1229       {
1230         iobject = createInstance(genericRegisterName,
1231                                  handle,
1232                                  0,
1233                                  reason); // force multiStudy instance here !
1234       }
1235       else
1236       {
1237         iobject = Engines::Component::_narrow( obj ) ;
1238         Engines_Component_i *servant =
1239           dynamic_cast<Engines_Component_i*>
1240           (_poa->reference_to_servant(iobject));
1241         ASSERT(servant)
1242           int studyId = servant->getStudyId();
1243         ASSERT (studyId >= 0);
1244         if (studyId == 0) // multiStudy instance, OK
1245         {
1246           // No ReBind !
1247           MESSAGE(component_registerBase.c_str()<<" already bound");
1248         }
1249         else // monoStudy instance: NOK
1250         {
1251           iobject = Engines::Component::_nil();
1252           INFOS("load_impl & find_component_instance methods "
1253             << "NOT SUITABLE for mono study components");
1254         }
1255       }
1256     }
1257     catch (...)
1258     {
1259       INFOS( "Container_i::load_impl catched" ) ;
1260     }
1261     return iobject._retn();
1262   }
1263 }
1264
1265 //=============================================================================
1266 //! Indicate if container is a python one
1267 /*! 
1268 *  Retrieves only with container naming convention if it is a python container
1269 */
1270 //=============================================================================
1271 bool Engines_Container_i::isPythonContainer(const char* ContainerName)
1272 {
1273   bool ret=false;
1274   int len=strlen(ContainerName);
1275   if(len>=2)
1276     if(strcmp(ContainerName+len-2,"Py")==0)
1277       ret=true;
1278   return ret;
1279 }
1280
1281 //=============================================================================
1282 //! Kill the container
1283 /*!
1284 *  CORBA method: Kill the container process with exit(0).
1285 *  To remove :  never returns !
1286 */
1287 //=============================================================================
1288 bool Engines_Container_i::Kill_impl()
1289 {
1290   MESSAGE("Engines_Container_i::Kill() pid "<< getpid() << " containerName "
1291     << _containerName.c_str() << " machineName "
1292     << Kernel_Utils::GetHostname().c_str());
1293   INFOS("===============================================================");
1294   INFOS("= REMOVE calls to Kill_impl in C++ container                  =");
1295   INFOS("===============================================================");
1296   //_exit( 0 ) ;
1297   ASSERT(0);
1298   return false;
1299 }
1300
1301 //=============================================================================
1302 /*! 
1303 *  
1304 */
1305 //=============================================================================
1306 void ActSigIntHandler()
1307 {
1308 #ifndef WIN32
1309   struct sigaction SigIntAct ;
1310   SigIntAct.sa_sigaction = &SigIntHandler ;
1311   sigemptyset(&SigIntAct.sa_mask);
1312   SigIntAct.sa_flags = SA_SIGINFO ;
1313 #endif
1314
1315   // DEBUG 03.02.2005 : the first parameter of sigaction is not a mask of signals
1316   // (SIGINT | SIGUSR1) :
1317   // it must be only one signal ===> one call for SIGINT 
1318   // and an other one for SIGUSR1
1319
1320 #ifndef WIN32
1321   if ( sigaction( SIGINT , &SigIntAct, NULL ) ) 
1322   {
1323     perror("SALOME_Container main ") ;
1324     exit(0) ;
1325   }
1326   if ( sigaction( SIGUSR1 , &SigIntAct, NULL ) )
1327   {
1328     perror("SALOME_Container main ") ;
1329     exit(0) ;
1330   }
1331   if ( sigaction( SIGUSR2 , &SigIntAct, NULL ) )
1332   {
1333     perror("SALOME_Container main ") ;
1334     exit(0) ;
1335   }
1336
1337   //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1338   //             use of streams (and so on) should never be used because :
1339   //             streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1340   //             A stream operation may be interrupted by a signal and if the Handler use stream we
1341   //             may have a "Dead-Lock" ===HangUp
1342   //==INFOS is commented
1343   //  INFOS(pthread_self() << "SigIntHandler activated") ;
1344
1345 #else  
1346   signal( SIGINT, SigIntHandler );
1347   signal( SIGUSR1, SigIntHandler );
1348 #endif
1349
1350 }
1351
1352 void SetCpuUsed() ;
1353 void CallCancelThread() ;
1354
1355 #ifndef WIN32
1356 void SigIntHandler(int what ,
1357                    siginfo_t * siginfo ,
1358                    void * toto ) 
1359 {
1360   //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1361   //             use of streams (and so on) should never be used because :
1362   //             streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1363   //             A stream operation may be interrupted by a signal and if the Handler use stream we
1364   //             may have a "Dead-Lock" ===HangUp
1365   //==MESSAGE is commented
1366   //  MESSAGE(pthread_self() << "SigIntHandler what     " << what << std::endl
1367   //          << "              si_signo " << siginfo->si_signo << std::endl
1368   //          << "              si_code  " << siginfo->si_code << std::endl
1369   //          << "              si_pid   " << siginfo->si_pid) ;
1370
1371   if ( _Sleeping )
1372   {
1373     _Sleeping = false ;
1374     //     MESSAGE("SigIntHandler END sleeping.") ;
1375     return ;
1376   }
1377   else
1378   {
1379     ActSigIntHandler() ;
1380     if ( siginfo->si_signo == SIGUSR1 )
1381     {
1382       SetCpuUsed() ;
1383     }
1384     else if ( siginfo->si_signo == SIGUSR2 )
1385     {
1386       CallCancelThread() ;
1387     }
1388     else 
1389     {
1390       _Sleeping = true ;
1391       //      MESSAGE("SigIntHandler BEGIN sleeping.") ;
1392       int count = 0 ;
1393       while( _Sleeping )
1394       {
1395         sleep( 1 ) ;
1396         count += 1 ;
1397       }
1398       //      MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1399     }
1400     return ;
1401   }
1402 }
1403 #else // Case WIN32
1404 void SigIntHandler( int what )
1405 {
1406 #ifndef WIN32
1407   MESSAGE( pthread_self() << "SigIntHandler what     " << what << std::endl );
1408 #else
1409   MESSAGE( "SigIntHandler what     " << what << std::endl );
1410 #endif
1411   if ( _Sleeping )
1412   {
1413     _Sleeping = false ;
1414     MESSAGE("SigIntHandler END sleeping.") ;
1415     return ;
1416   }
1417   else
1418   {
1419     ActSigIntHandler() ;
1420     if ( what == SIGUSR1 )
1421     {
1422       SetCpuUsed() ;
1423     }
1424     else
1425     {
1426       _Sleeping = true ;
1427       MESSAGE("SigIntHandler BEGIN sleeping.") ;
1428       int count = 0 ;
1429       while( _Sleeping ) 
1430       {
1431         Sleep( 1000 ) ;
1432         count += 1 ;
1433       }
1434       MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1435     }
1436     return ;
1437   }
1438 }
1439 #endif
1440
1441 //=============================================================================
1442 //! Get or create a file reference object associated to a local file (to transfer it)
1443 /*!
1444 *  CORBA method: get or create a fileRef object associated to a local file
1445 *  (a file on the computer on which runs the container server), which stores
1446 *  a list of (machine, localFileName) corresponding to copies already done.
1447 *
1448 *  \param  origFileName absolute path for a local file to copy on other
1449 *          computers
1450 *  \return a fileRef object associated to the file.
1451 */
1452 //=============================================================================
1453 Engines::fileRef_ptr
1454 Engines_Container_i::createFileRef(const char* origFileName)
1455 {
1456   std::string origName(origFileName);
1457   Engines::fileRef_var theFileRef = Engines::fileRef::_nil();
1458
1459   if (origName[0] != '/')
1460   {
1461     INFOS("path of file to copy must be an absolute path begining with '/'");
1462     return Engines::fileRef::_nil();
1463   }
1464
1465   if (CORBA::is_nil(_fileRef_map[origName]))
1466   {
1467     CORBA::Object_var obj=_poa->id_to_reference(*_id);
1468     Engines::Container_var pCont = Engines::Container::_narrow(obj);
1469     fileRef_i* aFileRef = new fileRef_i(pCont, origFileName);
1470     theFileRef = Engines::fileRef::_narrow(aFileRef->_this());
1471     _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1472     _fileRef_map[origName] = theFileRef;
1473     _numInstanceMutex.unlock() ;
1474   }
1475
1476   theFileRef =  Engines::fileRef::_duplicate(_fileRef_map[origName]);
1477   ASSERT(! CORBA::is_nil(theFileRef));
1478   return theFileRef._retn();
1479 }
1480
1481 //=============================================================================
1482 //! Get a fileTransfer reference
1483 /*!
1484 *  CORBA method:
1485 *  \return a reference to the fileTransfer object
1486 */
1487 //=============================================================================
1488 Engines::fileTransfer_ptr
1489 Engines_Container_i::getFileTransfer()
1490 {
1491   Engines::fileTransfer_var aFileTransfer
1492     = Engines::fileTransfer::_duplicate(_fileTransfer);
1493   return aFileTransfer._retn();
1494 }
1495
1496 //=============================================================================
1497 //! Create a Salome file
1498 //=============================================================================
1499 Engines::Salome_file_ptr
1500 Engines_Container_i::createSalome_file(const char* origFileName)
1501 {
1502   std::string origName(origFileName);
1503   if (CORBA::is_nil(_Salome_file_map[origName]))
1504   {
1505     Salome_file_i* aSalome_file = new Salome_file_i();
1506     aSalome_file->setContainer(Engines::Container::_duplicate(this->_this()));
1507     try
1508     {
1509       aSalome_file->setLocalFile(origFileName);
1510       aSalome_file->recvFiles();
1511     }
1512     catch (const SALOME::SALOME_Exception& e)
1513     {
1514       return Engines::Salome_file::_nil();
1515     }
1516
1517     Engines::Salome_file_var theSalome_file = Engines::Salome_file::_nil();
1518     theSalome_file = Engines::Salome_file::_narrow(aSalome_file->_this());
1519     _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1520     _Salome_file_map[origName] = theSalome_file;
1521     _numInstanceMutex.unlock() ;
1522   }
1523
1524   Engines::Salome_file_ptr theSalome_file =
1525     Engines::Salome_file::_duplicate(_Salome_file_map[origName]);
1526   ASSERT(!CORBA::is_nil(theSalome_file));
1527   return theSalome_file;
1528 }
1529
1530 //=============================================================================
1531 /*! \brief copy a file from a remote host (container) to the local host
1532  * \param container the remote container
1533  * \param remoteFile the file to copy locally from the remote host into localFile
1534  * \param localFile the local file
1535  */
1536 //=============================================================================
1537 void Engines_Container_i::copyFile(Engines::Container_ptr container, const char* remoteFile, const char* localFile)
1538 {
1539   Engines::fileTransfer_var fileTransfer = container->getFileTransfer();
1540
1541   FILE* fp;
1542   if ((fp = fopen(localFile,"wb")) == NULL)
1543     {
1544       INFOS("file " << localFile << " cannot be open for writing");
1545       return;
1546     }
1547
1548   CORBA::Long fileId = fileTransfer->open(remoteFile);
1549   if (fileId > 0)
1550     {
1551       Engines::fileBlock* aBlock;
1552       int toFollow = 1;
1553       int ctr=0;
1554       while (toFollow)
1555         {
1556           ctr++;
1557           SCRUTE(ctr);
1558           aBlock = fileTransfer->getBlock(fileId);
1559           toFollow = aBlock->length();
1560           SCRUTE(toFollow);
1561           CORBA::Octet *buf = aBlock->get_buffer();
1562           fwrite(buf, sizeof(CORBA::Octet), toFollow, fp);
1563           delete aBlock;
1564         }
1565       fclose(fp);
1566       MESSAGE("end of transfer");
1567       fileTransfer->close(fileId);
1568     }
1569   else
1570     {
1571       INFOS("open reference file for copy impossible");
1572     }
1573 }
1574
1575 //=============================================================================
1576 /*! \brief create a PyNode object to execute remote python code
1577  * \param nodeName the name of the node
1578  * \param code the python code to load
1579  * \return the PyNode
1580  */
1581 //=============================================================================
1582 Engines::PyNode_ptr Engines_Container_i::createPyNode(const char* nodeName, const char* code)
1583 {
1584     Engines::PyNode_var node= Engines::PyNode::_nil();
1585
1586     PyGILState_STATE gstate = PyGILState_Ensure();
1587     PyObject *res = PyObject_CallMethod(_pyCont,
1588       (char*)"create_pynode",
1589       (char*)"ss",
1590       nodeName,
1591       code);
1592     if(res==NULL)
1593       {
1594         //internal error
1595         PyErr_Print();
1596         PyGILState_Release(gstate);
1597         SALOME::ExceptionStruct es;
1598         es.type = SALOME::INTERNAL_ERROR;
1599         es.text = "can not create a python node";
1600         throw SALOME::SALOME_Exception(es);
1601       }
1602     long ierr=PyInt_AsLong(PyTuple_GetItem(res,0));
1603     PyObject* result=PyTuple_GetItem(res,1);
1604     std::string astr=PyString_AsString(result);
1605     Py_DECREF(res);
1606     PyGILState_Release(gstate);
1607
1608     if(ierr==0)
1609       {
1610         CORBA::Object_var obj = _orb->string_to_object(astr.c_str());
1611         node = Engines::PyNode::_narrow(obj);
1612         return node._retn();
1613       }
1614     else
1615       {
1616         SALOME::ExceptionStruct es;
1617         es.type = SALOME::INTERNAL_ERROR;
1618         es.text = astr.c_str();
1619         throw SALOME::SALOME_Exception(es);
1620       }
1621
1622 }
1623
1624 //=============================================================================
1625 /* int checkifexecutable(const char *filename)
1626 *
1627 * Return non-zero if the name is an executable file, and
1628 * zero if it is not executable, or if it does not exist.
1629 */
1630 //=============================================================================
1631 int checkifexecutable(const std::string& filename)
1632 {
1633   int result;
1634   struct stat statinfo;
1635
1636   result = stat(filename.c_str(), &statinfo);
1637   if (result < 0) return 0;
1638   if (!S_ISREG(statinfo.st_mode)) return 0;
1639
1640 #ifdef WIN32
1641   return 1;
1642 #else
1643   if (statinfo.st_uid == geteuid()) return statinfo.st_mode & S_IXUSR;
1644   if (statinfo.st_gid == getegid()) return statinfo.st_mode & S_IXGRP;
1645   return statinfo.st_mode & S_IXOTH;
1646 #endif
1647 }
1648
1649
1650 //=============================================================================
1651 /*! \brief Find a file by searching in a path
1652  *  \param filename file name to search
1653  *  \param path path to search in
1654  *  \param pth the complete file path if found
1655  *  \return 1 if found 0 if not 
1656 */
1657 //=============================================================================
1658 int findpathof(const std::string& path, std::string& pth, const std::string& filename)
1659 {
1660   if ( path.size() == 0 ) return 0;
1661
1662   std::string::size_type offset = 0;
1663   std::string::size_type pos = 0;
1664   int found = 0;
1665   struct stat statinfo;
1666
1667   while(!found)
1668   {
1669     pos = path.find( SEP, offset );
1670     pth = path.substr( offset, pos - offset );
1671     if ( pth.size() > 0 )
1672     {
1673       if( pth[pth.size()-1] != SLASH ) pth += SLASH;
1674       pth += filename;
1675       int result=stat(pth.c_str(), &statinfo);
1676       if(result == 0) found=1;
1677     }
1678     if (pos == std::string::npos) break;
1679     offset = pos+1;
1680   }
1681   return found;
1682 }
1683