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