Salome HOME
Fix compilation with gcc 4.4
[modules/kernel.git] / src / ParallelContainer / SALOME_ParallelContainer_i.cxx
1 // Copyright (C) 2007-2016  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22 //  File   : SALOME_ParallelContainer_i.cxx
23 //  Author : AndrĂ© RIBES, EDF
24
25 #include "SALOME_ParallelContainer_i.hxx"
26 #include "SALOME_Component_i.hxx"
27 #include "SALOME_FileRef_i.hxx"
28 #include "SALOME_FileTransfer_i.hxx"
29 #include "SALOME_NamingService.hxx"
30 #include "OpUtil.hxx"
31 #include "utilities.h"
32 #include "Basics_Utils.hxx"
33
34 #include <string.h>
35 #include <stdio.h>
36 #ifndef WIN32
37 #include <sys/time.h>
38 #include <dlfcn.h>
39 #include <unistd.h>
40 #else
41 #include <signal.h>
42 #include <process.h>
43 #include <direct.h>
44 int SIGUSR1 = 1000;
45 #endif
46
47 #include <paco_omni.h>
48
49 #include <Python.h>
50 #include "Container_init_python.hxx"
51
52
53 bool _Sleeping = false ;
54
55 extern "C" {void ActSigIntHandler() ; }
56 #ifndef WIN32
57 extern "C" {void SigIntHandler(int, siginfo_t *, void *) ; }
58 #else
59 extern "C" {void SigIntHandler( int ) ; }
60 #endif
61
62 /*! \class Engines_Parallel_Container_i
63  *  \brief C++ implementation of Engines::Container interface for parallel
64  *  container implemented with PaCO++
65  */
66
67 //=============================================================================
68 /*! 
69  *  Construtor
70  */
71 //=============================================================================
72
73 Engines_Parallel_Container_i::Engines_Parallel_Container_i (CORBA::ORB_ptr orb, 
74                                                             char * ior, 
75                                                             int rank,
76                                                             PortableServer::POA_ptr poa,
77                                                             std::string containerName,
78                                                             bool isServantAloneInProcess) :
79   InterfaceParallel_impl(orb,ior,rank), 
80   Engines::PACO_Container_serv(orb,ior,rank),
81   Engines::PACO_Container_base_serv(orb,ior,rank),
82   Engines::Container_serv(orb,ior,rank),
83   Engines::Container_base_serv(orb,ior,rank),
84   _numInstance(0),_isServantAloneInProcess(isServantAloneInProcess)
85 {
86   // Members init
87   _pid = getpid();
88   _hostname = Kernel_Utils::GetHostname();
89   _orb = CORBA::ORB::_duplicate(orb);
90   _poa = PortableServer::POA::_duplicate(poa);
91
92   // Add CORBA object to the poa
93   _id = _poa->activate_object(this);
94   this->_remove_ref();
95   CORBA::Object_var container_node = _poa->id_to_reference(*_id);
96
97   // Adding this servant to SALOME
98   _NS = new SALOME_NamingService();
99   _NS->init_orb(_orb);
100   _containerName = _NS->BuildContainerNameForNS(containerName.c_str(), _hostname.c_str());
101
102   // Ajout du numero de noeud
103   char node_number[12];
104   sprintf(node_number, "%d", getMyRank());
105   _containerName = _containerName + node_number;
106
107   // Init Python container part
108   CORBA::String_var sior =  _orb->object_to_string(container_node);
109   std::string myCommand="pyCont = SALOME_Container.SALOME_Container_i('";
110   myCommand += _containerName + "','";
111   myCommand += sior;
112   myCommand += "')\n";
113   Py_ACQUIRE_NEW_THREAD;
114   PyRun_SimpleString("import SALOME_Container\n");
115   PyRun_SimpleString((char*)myCommand.c_str());
116   Py_RELEASE_NEW_THREAD;
117
118   // Init FileTransfer service
119   fileTransfer_i* aFileTransfer = new fileTransfer_i();
120   _fileTransfer = aFileTransfer->_this();
121   aFileTransfer->_remove_ref();
122
123   // Some signal handlers
124   ActSigIntHandler();
125 }
126
127 //=============================================================================
128 /*! 
129  *  Destructor
130  */
131 //=============================================================================
132
133 Engines_Parallel_Container_i::~Engines_Parallel_Container_i()
134 {
135   MESSAGE("Container_i::~Container_i()");
136   if (_id)
137     delete _id;
138   if(_NS)
139     delete _NS;
140 }
141
142 //=============================================================================
143 //! Get container name
144 /*! 
145  *  CORBA attribute: Container name (see constructor)
146  */
147 //=============================================================================
148
149 char* Engines_Parallel_Container_i::name()
150 {
151   return CORBA::string_dup(_containerName.c_str()) ;
152 }
153
154 //=============================================================================
155 //! Get container working directory
156 /*! 
157  *  CORBA attribute: Container working directory 
158  */
159 //=============================================================================
160
161 char* 
162 Engines_Parallel_Container_i::workingdir()
163 {
164   char wd[256];
165   getcwd (wd,256);
166   return CORBA::string_dup(wd) ;
167 }
168
169 //=============================================================================
170 //! Get container log file name
171 /*! 
172  *  CORBA attribute: Container log file name
173  */
174 //=============================================================================
175
176 char* 
177 Engines_Parallel_Container_i::logfilename()
178 {
179   return CORBA::string_dup(_logfilename.c_str()) ;
180 }
181
182 //! Set container log file name
183 void 
184 Engines_Parallel_Container_i::logfilename(const char* name)
185 {
186   _logfilename=name;
187 }
188
189 //=============================================================================
190 //! Get container host name
191 /*! 
192  *  CORBA method: Get the hostName of the Container (without domain extensions)
193  */
194 //=============================================================================
195
196 char* Engines_Parallel_Container_i::getHostName()
197 {
198   MESSAGE("Warning: getHostName of a parallel container returns the hostname of the first servant node");
199   return CORBA::string_dup(_hostname.c_str()) ;
200 }
201
202 //=============================================================================
203 //! Get container PID
204 /*! 
205  *  CORBA method: Get the PID (process identification) of the Container
206  */
207 //=============================================================================
208
209 CORBA::Long Engines_Parallel_Container_i::getPID()
210 {
211   MESSAGE("Warning: getPID of a parallel container returns the PID of the first servant node");
212   return _pid;
213 }
214
215 //=============================================================================
216 //! Ping the servant to check it is still alive
217 /*! 
218  *  CORBA method: check if servant is still alive
219  */
220 //=============================================================================
221
222 void Engines_Parallel_Container_i::ping()
223 {
224   MESSAGE("Engines_Parallel_Container_i::ping() my pid is "<< _pid);
225 }
226
227 //=============================================================================
228 //! Shutdown the container
229 /*! 
230  *  CORBA method, oneway: Server shutdown. 
231  *  - Container name removed from naming service,
232  *  - servant deactivation,
233  *  - orb shutdown if no other servants in the process 
234  */
235 //=============================================================================
236
237 void Engines_Parallel_Container_i::Shutdown()
238 {
239   MESSAGE("Engines_Parallel_Container_i::Shutdown()");
240
241   /* For each seq component contained in this container
242   * tell it to self-destroy
243   */
244   std::map<std::string, Engines::EngineComponent_var>::iterator itm;
245   for (itm = _listInstances_map.begin(); itm != _listInstances_map.end(); itm++)
246   {
247     try
248     {
249       itm->second->destroy();
250     }
251     catch(const CORBA::Exception& e)
252     {
253       // ignore this entry and continue
254     }
255     catch(...)
256     {
257       // ignore this entry and continue
258     }
259   }
260
261   // Destroy each parallel component node...
262   std::map<std::string, PortableServer::ObjectId *>::iterator i;
263   for (i = _par_obj_inst_map.begin(); i != _par_obj_inst_map.end(); i++)
264     _poa->deactivate_object(*(i->second));
265
266   _NS->Destroy_FullDirectory(_containerName.c_str());
267   _NS->Destroy_Name(_containerName.c_str());
268
269   if(_isServantAloneInProcess)
270   {
271     MESSAGE("Effective Shutdown of container Begins...");
272     if(!CORBA::is_nil(_orb))
273       _orb->shutdown(0);
274   }
275 }
276
277
278 //=============================================================================
279 //! load a new component class
280 /*! 
281  *  CORBA method: load a new component class (Python or C++ implementation)
282  *  \param componentName like COMPONENT
283  *                          try to make a Python import of COMPONENT,
284  *                          then a lib open of libCOMPONENTEngine.so
285  *  \return true if dlopen successfull or already done, false otherwise
286  */
287 //=============================================================================
288
289 bool
290 Engines_Parallel_Container_i::load_component_Library(const char* componentName, CORBA::String_out reason)
291 {
292   reason=CORBA::string_dup("");
293
294   MESSAGE("Begin of load_component_Library : " << componentName)
295   bool ret = false;
296   std::string aCompName = componentName;
297 #ifndef WIN32
298   std::string impl_name = string ("lib") + aCompName + string("Engine.so");
299 #else
300   std::string impl_name = aCompName + string("Engine.dll");
301 #endif
302
303   _numInstanceMutex.lock(); // lock to be alone 
304
305   // Check if already loaded or imported in the container
306   if (_toRemove_map.count(impl_name) != 0) _toRemove_map.erase(impl_name);
307   if (_library_map.count(impl_name) != 0)
308   {
309     MESSAGE("Library " << impl_name << " already loaded");
310     ret = true;
311   }
312   if (_library_map.count(aCompName) != 0)
313   {
314     MESSAGE("Python component already imported");
315     ret = true;
316   }
317
318   // --- try dlopen C++ component
319   if (!ret)
320   {
321     MESSAGE("Try to load C++ component");
322     void* handle;
323 #ifndef WIN32
324     handle = dlopen( impl_name.c_str() , RTLD_LAZY ) ;
325 #else
326     handle = dlopen( impl_name.c_str() , 0 ) ;
327 #endif
328     if ( handle )
329     {
330       _library_map[impl_name] = handle;
331       MESSAGE("Library " << impl_name << " loaded");
332       ret = true;
333     }
334     else
335     {
336       std::cerr << "Can't load shared library : " << impl_name << std::endl;
337       std::cerr << "error of dlopen: " << dlerror() << std::endl;
338     }
339   }
340
341   // --- try import Python component
342   if (!ret)
343   {
344     MESSAGE("Try to import Python component "<<componentName);
345     Py_ACQUIRE_NEW_THREAD;
346     PyObject *mainmod = PyImport_AddModule("__main__");
347     PyObject *globals = PyModule_GetDict(mainmod);
348     PyObject *pyCont = PyDict_GetItemString(globals, "pyCont");
349     PyObject *result = PyObject_CallMethod(pyCont,
350                                            (char*)"import_component",
351                                            (char*)"s",componentName);
352     std::string ret_p= PyString_AsString(result);
353     Py_XDECREF(result);
354     Py_RELEASE_NEW_THREAD;
355
356     if (ret_p=="") // import possible: Python component
357     {
358       _library_map[aCompName] = (void *)pyCont; // any non O value OK
359       MESSAGE("import Python: " << aCompName <<" OK");
360       ret = true;
361     }
362     else
363     {
364       std::cerr << "Error in importing Python component : " << aCompName << std::endl;
365     }
366   }
367
368   _numInstanceMutex.unlock();
369   return ret;
370 }
371
372 //=============================================================================
373 //! Create a new component instance
374 /*! 
375  *  CORBA method: Creates a new servant instance of a component.
376  *  The servant registers itself to naming service and Registry.
377  *  \param genericRegisterName  Name of the component instance to register
378  *                         in Registry & Name Service (without _inst_n suffix)
379  *  \return a loaded component
380  */
381 //=============================================================================
382 Engines::EngineComponent_ptr
383 Engines_Parallel_Container_i::create_component_instance(const char*genericRegisterName)
384 {
385   Engines::FieldsDict_var env = new Engines::FieldsDict;
386   char* reason;
387   Engines::EngineComponent_ptr compo = create_component_instance_env(genericRegisterName,env, reason);
388   CORBA::string_free(reason);
389   return compo;
390 }
391
392 //=============================================================================
393 //! Create a new component instance
394 /*! 
395  *  CORBA method: Creates a new servant instance of a component.
396  *  The servant registers itself to naming service and Registry.
397  *  \param genericRegisterName  Name of the component instance to register
398  *                         in Registry & Name Service (without _inst_n suffix)
399  *  \param env             dict of environment variables
400  *  \return a loaded component
401  */
402 //=============================================================================
403
404 Engines::EngineComponent_ptr
405 Engines_Parallel_Container_i::create_component_instance_env(const char*genericRegisterName,
406                                                             const Engines::FieldsDict& env,
407                                                             CORBA::String_out reason)
408 {
409   MESSAGE("Begin of create_component_instance in node : " << getMyRank());
410   reason=CORBA::string_dup("");
411
412   std::string aCompName = genericRegisterName;
413 #ifndef WIN32
414   std::string impl_name = string ("lib") + aCompName +string("Engine.so");
415 #else
416   std::string impl_name = aCompName +string("Engine.dll");
417 #endif
418
419   _numInstanceMutex.lock();
420   _numInstance++;
421
422   // Test if the component lib is loaded
423   std::string type_of_lib("Not Loaded");
424   void* handle = _library_map[impl_name];
425   if (handle)
426     type_of_lib = "cpp";
427   if (_library_map.count(aCompName) != 0 and !handle)
428     type_of_lib = "python";
429   
430   if (type_of_lib == "Not Loaded")
431   {
432     std::cerr << "Component library is not loaded or imported ! lib was : " << aCompName << std::endl;
433     _numInstanceMutex.unlock();
434     return Engines::EngineComponent::_nil();
435   }
436
437   Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil();
438   if (type_of_lib == "cpp")
439     iobject = createCPPInstance(aCompName, handle);
440   else
441     iobject = createPythonInstance(aCompName);
442
443   _numInstanceMutex.unlock();
444   return iobject._retn();
445 }
446
447 //=============================================================================
448 //! Find an existing (in the container) component instance
449 /*! 
450  *  CORBA method: Finds a servant instance of a component
451  *  \param registeredName  Name of the component in Registry or Name Service,
452  *                         without instance suffix number
453  *  \return the first found instance
454  */
455 //=============================================================================
456
457 Engines::EngineComponent_ptr Engines_Parallel_Container_i::find_component_instance(const char* registeredName)
458 {
459   Engines::EngineComponent_var anEngine = Engines::EngineComponent::_nil();
460   std::map<std::string,Engines::EngineComponent_var>::iterator itm =_listInstances_map.begin();
461   while (itm != _listInstances_map.end())
462   {
463     std::string instance = (*itm).first;
464     SCRUTE(instance);
465     if (instance.find(registeredName) == 0)
466     {
467       anEngine = (*itm).second;
468       return anEngine._retn();
469     }
470     itm++;
471   }
472   return anEngine._retn();  
473 }
474
475 char* Engines_Parallel_Container_i::create_python_service_instance(const char* CompName,
476                                                                    CORBA::String_out reason)
477 {
478   // not implemented
479   reason=CORBA::string_dup("");
480   return CORBA::string_dup("");
481 }
482
483 //=============================================================================
484 //! Find or create a new component instance
485 /*! 
486  *  CORBA method: find or create an instance of the component (servant),
487  *  load a new component class (dynamic library) if required,
488  *  ---- FOR COMPATIBILITY WITH 2.2 ---- 
489  *  ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
490  *  The servant registers itself to naming service and Registry.
491  *  \param genericRegisterName  Name of the component to register
492  *                              in Registry & Name Service
493  *  \param componentName       Name of the constructed library of the component
494  *  \return a loaded component
495  */
496 //=============================================================================
497
498 Engines::EngineComponent_ptr Engines_Parallel_Container_i::load_impl( const char* genericRegisterName,
499                                                                 const char* componentName )
500 {
501   Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil();
502   char* reason;
503   if (load_component_Library(genericRegisterName,reason))
504     iobject = find_or_create_instance(genericRegisterName);
505   CORBA::string_free(reason);
506   return iobject._retn();
507 }
508
509
510 //=============================================================================
511 //! Remove the component instance from container
512 /*! 
513  *  CORBA method: Stops the component servant, and deletes all related objects
514  *  \param component_i     Component to be removed
515  */
516 //=============================================================================
517
518 void Engines_Parallel_Container_i::remove_impl(Engines::EngineComponent_ptr component_i)
519 {
520   ASSERT(!CORBA::is_nil(component_i));
521   std::string instanceName = component_i->instanceName();
522   _numInstanceMutex.lock() ; // lock to be alone (stl container write)
523   // Test if the component is in this container
524   std::map<std::string, Engines::EngineComponent_var>::iterator itm;
525   itm = _listInstances_map.find(instanceName);
526   if (itm != _listInstances_map.end())
527   {
528     MESSAGE("Unloading component " << instanceName);
529     _listInstances_map.erase(instanceName);
530     component_i->destroy() ;
531     _NS->Destroy_Name(instanceName.c_str());
532   }
533   else
534     std::cerr << "WARNING !!!! component instance was not in this container !!!" << std::endl;
535   _numInstanceMutex.unlock() ;
536 }
537
538 //=============================================================================
539 //! Unload component libraries from the container
540 /*! 
541  *  CORBA method: Discharges unused libraries from the container.
542  */
543 //=============================================================================
544
545 void Engines_Parallel_Container_i::finalize_removal()
546 {
547   MESSAGE("Finalize removal : dlclose");
548   MESSAGE("WARNING FINALIZE DOES CURRENTLY NOTHING !!!");
549
550   // (see decInstanceCnt, load_component_Library)
551   //std::map<std::string, void *>::iterator ith;
552   //for (ith = _toRemove_map.begin(); ith != _toRemove_map.end(); ith++)
553   //{
554   //  void *handle = (*ith).second;
555   //  std::string impl_name= (*ith).first;
556   //  if (handle)
557   //  {
558   //    SCRUTE(handle);
559   //    SCRUTE(impl_name);
560   //    dlclose(handle);                // SALOME unstable after ...
561   //    _library_map.erase(impl_name);
562   //  }
563   //}
564
565   _numInstanceMutex.lock(); // lock to be alone
566   _toRemove_map.clear();
567   _numInstanceMutex.unlock();
568 }
569
570 //=============================================================================
571 //! Kill the container
572 /*! 
573  *  CORBA method: Kill the container process with exit(0).
574  *  To remove :  never returns !
575  */
576 //=============================================================================
577
578 bool Engines_Parallel_Container_i::Kill_impl()
579 {
580   MESSAGE("Engines_Parallel_Container_i::Kill() my pid is "<< _pid 
581           << " my containerName is " << _containerName.c_str() 
582           << " my machineName is " << _hostname.c_str());
583   INFOS("===============================================================");
584   INFOS("= REMOVE calls to Kill_impl in C++ container                  =");
585   INFOS("===============================================================");
586   //exit( 0 ) ;
587   ASSERT(0);
588   return false;
589 }
590
591 //=============================================================================
592 //! Get or create a file reference object associated to a local file (to transfer it)
593 /*! 
594  *  CORBA method: get or create a fileRef object associated to a local file
595  *  (a file on the computer on which runs the container server), which stores
596  *  a list of (machine, localFileName) corresponding to copies already done.
597  * 
598  *  \param  origFileName absolute path for a local file to copy on other
599  *          computers
600  *  \return a fileRef object associated to the file.
601  */
602 //=============================================================================
603
604 Engines::fileRef_ptr
605 Engines_Parallel_Container_i::createFileRef(const char* origFileName)
606 {
607   std::string origName(origFileName);
608   Engines::fileRef_var theFileRef = Engines::fileRef::_nil();
609
610   if (origName[0] != '/')
611   {
612     INFOS("path of file to copy must be an absolute path begining with '/'");
613     return Engines::fileRef::_nil();
614   }
615
616   if (CORBA::is_nil(_fileRef_map[origName]))
617   {
618     CORBA::Object_var obj=_poa->id_to_reference(*_id);
619     Engines::Container_var pCont = Engines::Container::_narrow(obj);
620     fileRef_i* aFileRef = new fileRef_i(pCont, origFileName);
621     theFileRef = Engines::fileRef::_narrow(aFileRef->_this());
622     _numInstanceMutex.lock() ; // lock to be alone (stl container write)
623     _fileRef_map[origName] = theFileRef;
624     _numInstanceMutex.unlock() ;
625   }
626
627   theFileRef =  Engines::fileRef::_duplicate(_fileRef_map[origName]);
628   ASSERT(! CORBA::is_nil(theFileRef));
629   return theFileRef._retn();
630 }
631
632 //=============================================================================
633 /*! 
634  *  CORBA method:
635  *  \return a reference to the fileTransfer object
636  */
637 //=============================================================================
638
639 Engines::fileTransfer_ptr
640 Engines_Parallel_Container_i::getFileTransfer()
641 {
642   Engines::fileTransfer_var aFileTransfer
643     = Engines::fileTransfer::_duplicate(_fileTransfer);
644   return aFileTransfer._retn();
645 }
646
647
648 Engines::Salome_file_ptr 
649 Engines_Parallel_Container_i::createSalome_file(const char* origFileName) 
650 {
651   string origName(origFileName);
652   if (CORBA::is_nil(_Salome_file_map[origName]))
653   {
654     Salome_file_i* aSalome_file = new Salome_file_i();
655     try 
656     {
657       aSalome_file->setLocalFile(origFileName);
658       aSalome_file->recvFiles();
659     }
660     catch (const SALOME::SALOME_Exception& e)
661     {
662       return Engines::Salome_file::_nil();
663     }
664
665     Engines::Salome_file_var theSalome_file = Engines::Salome_file::_nil();
666     theSalome_file = Engines::Salome_file::_narrow(aSalome_file->_this());
667     _numInstanceMutex.lock() ; // lock to be alone (stl container write)
668     _Salome_file_map[origName] = theSalome_file;
669     _numInstanceMutex.unlock() ;
670   }
671
672   Engines::Salome_file_ptr theSalome_file =  
673     Engines::Salome_file::_duplicate(_Salome_file_map[origName]);
674   ASSERT(!CORBA::is_nil(theSalome_file));
675   return theSalome_file;
676 }
677
678
679 //=============================================================================
680 //! Finds an already existing component instance or create a new instance
681 /*! 
682  *  C++ method: Finds an already existing servant instance of a component, or
683  *              create an instance.
684  *  ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
685  *  \param genericRegisterName    Name of the component instance to register
686  *                                in Registry & Name Service,
687  *                                (without _inst_n suffix, like "COMPONENT")
688  *  \return a loaded component
689  * 
690  *  example with names:
691  *  aGenRegisterName = COMPONENT (= first argument)
692  *  impl_name = libCOMPONENTEngine.so (= second argument)
693  *  _containerName = /Containers/cli76ce/FactoryServer
694  *  factoryName = COMPONENTEngine_factory
695  *  component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
696  *
697  *  instanceName = COMPONENT_inst_1
698  *  component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
699  */
700 //=============================================================================
701
702 Engines::EngineComponent_ptr
703 Engines_Parallel_Container_i::find_or_create_instance(std::string genericRegisterName)
704 {
705   Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil();
706   try
707   {
708     std::string aGenRegisterName = genericRegisterName;
709     // --- find a registered instance in naming service, or create
710     std::string component_registerBase = _containerName + "/" + aGenRegisterName;
711     CORBA::Object_var obj = _NS->ResolveFirst(component_registerBase.c_str());
712     if (CORBA::is_nil( obj ))
713     {
714       iobject = create_component_instance(genericRegisterName.c_str());
715     }
716     else
717     { 
718       iobject = Engines::EngineComponent::_narrow(obj) ;
719     }
720   }
721   catch (...)
722   {
723     INFOS( "Container_i::load_impl catched" ) ;
724   }
725   return iobject._retn();
726 }
727
728 //=============================================================================
729 //! Create a new Python component instance 
730 /*! 
731  *  C++ method: create a servant instance of a component.
732  *  \param genericRegisterName    Name of the component instance to register
733  *                                in Registry & Name Service,
734  *                                (without _inst_n suffix, like "COMPONENT")
735  *  \param handle                 loaded library handle
736  *  \return a loaded component
737  * 
738  *  example with names:
739  *  aGenRegisterName = COMPONENT (= first argument)
740  *  _containerName = /Containers/cli76ce/FactoryServer
741  *  factoryName = COMPONENTEngine_factory
742  *  component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
743  *  instanceName = COMPONENT_inst_1
744  *  component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
745  */
746 //=============================================================================
747 Engines::EngineComponent_ptr
748 Engines_Parallel_Container_i::createPythonInstance(std::string genericRegisterName)
749 {
750
751   Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil();
752
753   int numInstance = _numInstance;
754   char aNumI[12];
755   sprintf( aNumI , "%d" , numInstance ) ;
756   std::string instanceName = genericRegisterName + "_inst_" + aNumI ;
757   std::string component_registerName = _containerName + "/" + instanceName;
758
759   Py_ACQUIRE_NEW_THREAD;
760   PyObject *mainmod = PyImport_AddModule("__main__");
761   PyObject *globals = PyModule_GetDict(mainmod);
762   PyObject *pyCont = PyDict_GetItemString(globals, "pyCont");
763   PyObject *result = PyObject_CallMethod(pyCont,
764                                          (char*)"create_component_instance",
765                                          (char*)"ssl",
766                                          genericRegisterName.c_str(),
767                                          instanceName.c_str());
768   const char *ior;
769   const char *error;
770   PyArg_ParseTuple(result,"ss", &ior, &error);
771   string iors = ior;
772   Py_DECREF(result);
773   Py_RELEASE_NEW_THREAD;
774
775   if( iors!="" )
776   {
777     CORBA::Object_var obj = _orb->string_to_object(iors.c_str());
778     iobject = Engines::EngineComponent::_narrow(obj);
779     _listInstances_map[instanceName] = iobject;
780   }
781   else
782     std::cerr << "createPythonInstance ior is empty ! Error in creation" << std::endl;
783
784   return iobject._retn();
785 }
786
787 //=============================================================================
788 //! Create a new CPP component instance 
789 /*! 
790  *  C++ method: create a servant instance of a component.
791  *  \param genericRegisterName    Name of the component instance to register
792  *                                in Registry & Name Service,
793  *                                (without _inst_n suffix, like "COMPONENT")
794  *  \param handle                 loaded library handle
795  *  \return a loaded component
796  * 
797  *  example with names:
798  *  aGenRegisterName = COMPONENT (= first argument)
799  *  _containerName = /Containers/cli76ce/FactoryServer
800  *  factoryName = COMPONENTEngine_factory
801  *  component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
802  *  instanceName = COMPONENT_inst_1
803  *  component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
804  */
805 //=============================================================================
806 Engines::EngineComponent_ptr
807 Engines_Parallel_Container_i::createCPPInstance(std::string genericRegisterName,
808                                                 void *handle)
809 {
810   MESSAGE("Entering Engines_Parallel_Container_i::createCPPInstance");
811
812   // --- find the factory
813
814   std::string aGenRegisterName = genericRegisterName;
815   std::string factory_name = aGenRegisterName + string("Engine_factory");
816
817   typedef  PortableServer::ObjectId * (*FACTORY_FUNCTION_2)
818     (CORBA::ORB_ptr,
819      PortableServer::POA_ptr, 
820      PortableServer::ObjectId *, 
821      const char *, 
822      const char *) ;
823
824   FACTORY_FUNCTION_2 Component_factory = NULL;
825 #ifndef WIN32
826   Component_factory = (FACTORY_FUNCTION_2)dlsym( handle, factory_name.c_str() );
827 #else
828   Component_factory = (FACTORY_FUNCTION_2)GetProcAddress( (HINSTANCE)handle, factory_name.c_str() );
829 #endif
830
831   if (!Component_factory)
832   {
833     INFOS("Can't resolve symbol: " + factory_name);
834 #ifndef WIN32
835     INFOS("dlerror() result is : " << dlerror());
836 #endif
837     return Engines::EngineComponent::_nil() ;
838   }
839
840   // --- create instance
841   Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
842   try
843   {
844     int numInstance = _numInstance;
845     char aNumI[12];
846     sprintf( aNumI , "%d" , numInstance );
847     std::string instanceName = aGenRegisterName + "_inst_" + aNumI;
848     std::string component_registerName =
849       _containerName + "/" + instanceName;
850
851     // --- Instanciate required CORBA object
852
853     PortableServer::ObjectId *id; //not owner, do not delete (nore use var)
854     id = (Component_factory) ( _orb, _poa, _id, instanceName.c_str(),
855                                aGenRegisterName.c_str() );
856     if (id == NULL)
857     {
858       INFOS("Factory function returns NULL !");
859       return iobject._retn();
860     }
861
862     // --- get reference from id
863     CORBA::Object_var obj = _poa->id_to_reference(*id);
864     iobject = Engines::EngineComponent::_narrow(obj);
865
866     _listInstances_map[instanceName] = iobject;
867     _cntInstances_map[aGenRegisterName] += 1;
868
869     // --- register the engine under the name
870     //     containerName(.dir)/instanceName(.object)
871     _NS->Register(iobject , component_registerName.c_str());
872     MESSAGE( component_registerName.c_str() << " bound" );
873   }
874   catch (...)
875   {
876     INFOS( "Container_i::createInstance exception catched" );
877   }
878   return iobject._retn();
879 }
880
881 void
882 Engines_Parallel_Container_i::create_paco_component_node_instance(const char* componentName,
883                                                                   const char* proxy_containerName)
884 {
885   // Init de la mĂ©thode
886   char * proxy_ior;
887   Engines::EngineComponent_PaCO_var work_node;
888   std::string aCompName = componentName;
889   std::string _proxy_containerName = proxy_containerName;
890
891 #ifndef WIN32
892   string impl_name = string ("lib") + aCompName +string("Engine.so");
893 #else
894   string impl_name = aCompName +string("Engine.dll");
895 #endif
896   void* handle = _library_map[impl_name];
897   _numInstanceMutex.lock() ; // lock on the instance number
898   _numInstance++ ;
899   int numInstance = _numInstance ;
900   _numInstanceMutex.unlock() ;
901   char aNumI[12];
902   sprintf( aNumI , "%d" , numInstance ) ;
903   string instanceName = aCompName + "_inst_" + aNumI ;
904
905   // Step 1 : Get proxy !
906   string component_registerName = _proxy_containerName + "/" + instanceName;
907   CORBA::Object_var temp = _NS->Resolve(component_registerName.c_str());
908   Engines::EngineComponent_var obj_proxy = Engines::EngineComponent::_narrow(temp);
909   if (CORBA::is_nil(obj_proxy))
910   {
911     INFOS("Proxy reference from NamingService is nil !");
912     INFOS("Proxy name was : " << component_registerName);
913     SALOME::ExceptionStruct es;
914     es.type = SALOME::INTERNAL_ERROR;
915     es.text = "Proxy reference from NamingService is nil !";
916     throw SALOME::SALOME_Exception(es);
917   }
918   proxy_ior = _orb->object_to_string(obj_proxy);
919
920   // Get factory
921   string factory_name = aCompName + string("Engine_factory");
922   FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION) dlsym(handle, factory_name.c_str());
923   if (!Component_factory)
924   {
925     INFOS("Can't resolve symbol : " + factory_name);
926 #ifndef WIN32
927     INFOS("dlerror() result is : " << dlerror());
928 #endif
929     std::string ex_text = "Can't resolve symbol : " + factory_name;
930     SALOME::ExceptionStruct es;
931     es.type = SALOME::INTERNAL_ERROR;
932     es.text = CORBA::string_dup(ex_text.c_str());
933     throw SALOME::SALOME_Exception(es);
934   }
935
936   try
937   {
938     char aNumI2[12];
939     sprintf(aNumI2 , "%d" , getMyRank()) ;
940     std::string instanceName = aCompName + "_inst_" + aNumI + "_work_node_" + aNumI2;
941     std::string component_registerName = _containerName + "/" + instanceName;
942
943     // --- Instanciate work node
944     PortableServer::ObjectId *id ; //not owner, do not delete (nore use var)
945     id = (Component_factory) (_orb, proxy_ior, getMyRank(), _poa, _id, instanceName.c_str(), componentName);
946     CORBA::string_free(proxy_ior);
947
948     // --- get reference from id
949     CORBA::Object_var obj = _poa->id_to_reference(*id);
950     work_node = Engines::EngineComponent_PaCO::_narrow(obj) ;
951     if (CORBA::is_nil(work_node))
952     {
953       INFOS("work_node reference from factory is nil !");
954       SALOME::ExceptionStruct es;
955       es.type = SALOME::INTERNAL_ERROR;
956       es.text = "work_node reference from factory is nil !";
957       throw SALOME::SALOME_Exception(es);
958     }
959     work_node->deploy();
960     _NS->Register(work_node, component_registerName.c_str());
961     _par_obj_inst_map[instanceName] = id;
962     MESSAGE(component_registerName.c_str() << " bound" );
963   }
964   catch (...)
965   {
966     INFOS("Container_i::create_paco_component_node_instance exception catched");
967     SALOME::ExceptionStruct es;
968     es.type = SALOME::INTERNAL_ERROR;
969     es.text = "Container_i::create_paco_component_node_instance exception catched";
970     throw SALOME::SALOME_Exception(es);
971   }
972 }
973
974 //=============================================================================
975 //! Decrement component instance reference count
976 /*! 
977  *
978  */
979 //=============================================================================
980
981 void Engines_Parallel_Container_i::decInstanceCnt(std::string genericRegisterName)
982 {
983   if(_cntInstances_map.count(genericRegisterName) !=0 )
984   {
985     std::string aGenRegisterName =genericRegisterName;
986     MESSAGE("Engines_Parallel_Container_i::decInstanceCnt " << aGenRegisterName);
987     ASSERT(_cntInstances_map[aGenRegisterName] > 0); 
988     _numInstanceMutex.lock(); // lock to be alone
989     // (see finalize_removal, load_component_Library)
990     _cntInstances_map[aGenRegisterName] -= 1;
991     SCRUTE(_cntInstances_map[aGenRegisterName]);
992     if (_cntInstances_map[aGenRegisterName] == 0)
993     {
994       std::string impl_name =
995         Engines_Component_i::GetDynLibraryName(aGenRegisterName.c_str());
996       SCRUTE(impl_name);
997       void* handle = _library_map[impl_name];
998       ASSERT(handle);
999       _toRemove_map[impl_name] = handle;
1000     }
1001     _numInstanceMutex.unlock();
1002   }
1003 }
1004
1005 //=============================================================================
1006 //! Indicate if container is a python one
1007 /*! 
1008  *  Retrieves only with container naming convention if it is a python container
1009  */
1010 //=============================================================================
1011
1012 bool Engines_Parallel_Container_i::isPythonContainer(const char* ContainerName)
1013 {
1014   bool ret=false;
1015   return ret;
1016 }
1017
1018
1019 // Cette mĂ©thode permet de tenir Ă  jour le compteur des
1020 // instances pour le container parallèle.
1021 // En effet losrque l'on charge un composant sĂ©quentielle seul
1022 // le compteur du noeud 0 est augmentĂ©, il faut donc tenir les autres 
1023 // noeuds Ă  jour.
1024 void
1025 Engines_Parallel_Container_i::updateInstanceNumber()
1026 {
1027   if (getMyRank() != 0)
1028   {
1029     _numInstanceMutex.lock();
1030     _numInstance++;
1031     _numInstanceMutex.unlock();
1032   }
1033 }
1034
1035 /*! \brief copy a file from a remote host (container) to the local host
1036  * \param container the remote container
1037  * \param remoteFile the file to copy locally from the remote host into localFile
1038  * \param localFile the local file
1039  */
1040 void 
1041 Engines_Parallel_Container_i::copyFile(Engines::Container_ptr container, const char* remoteFile, const char* localFile)
1042 {
1043   Engines::fileTransfer_var fileTransfer = container->getFileTransfer();
1044
1045   FILE* fp;
1046   if ((fp = fopen(localFile,"wb")) == NULL)
1047     {
1048       INFOS("file " << localFile << " cannot be open for writing");
1049       return;
1050     }
1051
1052   CORBA::Long fileId = fileTransfer->open(remoteFile);
1053   if (fileId > 0)
1054     {
1055       Engines::fileBlock* aBlock;
1056       int toFollow = 1;
1057       int ctr=0;
1058       while (toFollow)
1059         {
1060           ctr++;
1061           SCRUTE(ctr);
1062           aBlock = fileTransfer->getBlock(fileId);
1063           toFollow = aBlock->length();
1064           SCRUTE(toFollow);
1065           CORBA::Octet *buf = aBlock->get_buffer();
1066           fwrite(buf, sizeof(CORBA::Octet), toFollow, fp);
1067           delete aBlock;
1068         }
1069       fclose(fp);
1070       MESSAGE("end of transfer");
1071       fileTransfer->close(fileId);
1072     }
1073   else
1074     {
1075       INFOS("open reference file for copy impossible");
1076     }
1077 }
1078
1079 /*! \brief create a PyNode object to execute remote python code
1080  * \param nodeName the name of the node
1081  * \param code the python code to load
1082  * \return the PyNode
1083  */
1084 Engines::PyNode_ptr 
1085 Engines_Parallel_Container_i::createPyNode(const char* nodeName, const char* code)
1086 {
1087   INFOS("Python component not yet implemented");
1088   Engines::PyNode_var node= Engines::PyNode::_nil();
1089   return node._retn();
1090 }
1091
1092 Engines::PyNode_ptr Engines_Parallel_Container_i::getDefaultPyNode(const char *nodeName)
1093 {
1094   INFOS("Python component not yet implemented");
1095   return Engines::PyNode::_nil();
1096 }
1097
1098 Engines::PyScriptNode_ptr 
1099 Engines_Parallel_Container_i::createPyScriptNode(const char* nodeName, const char* cod)
1100 {
1101   INFOS("Python script node not yet implemented");
1102   Engines::PyScriptNode_var node= Engines::PyScriptNode::_nil();
1103   return node._retn();
1104 }
1105
1106 Engines::PyScriptNode_ptr Engines_Parallel_Container_i::getDefaultPyScriptNode(const char *nodeName)
1107 {
1108   INFOS("Python script node not yet implemented");
1109   return Engines::PyScriptNode::_nil();
1110 }
1111
1112 //=============================================================================
1113 /*! 
1114  *  
1115  */
1116 //=============================================================================
1117
1118 void ActSigIntHandler()
1119 {
1120 #ifndef WIN32
1121   struct sigaction SigIntAct ;
1122   SigIntAct.sa_sigaction = &SigIntHandler ;
1123   SigIntAct.sa_flags = SA_SIGINFO ;
1124 #endif
1125
1126   // DEBUG 03.02.2005 : the first parameter of sigaction is not a mask of signals
1127   // (SIGINT | SIGUSR1) :
1128   // it must be only one signal ===> one call for SIGINT 
1129   // and an other one for SIGUSR1
1130
1131 #ifndef WIN32
1132   if ( sigaction( SIGINT , &SigIntAct, NULL ) ) {
1133     perror("SALOME_Container main ") ;
1134     exit(0) ;
1135   }
1136   if ( sigaction( SIGUSR1 , &SigIntAct, NULL ) ) {
1137     perror("SALOME_Container main ") ;
1138     exit(0) ;
1139   }
1140   if ( sigaction( SIGUSR2 , &SigIntAct, NULL ) )
1141   {
1142     perror("SALOME_Container main ") ;
1143     exit(0) ;
1144   }
1145
1146   //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1147   //             use of streams (and so on) should never be used because :
1148   //             streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1149   //             A stream operation may be interrupted by a signal and if the Handler use stream we
1150   //             may have a "Dead-Lock" ===HangUp
1151   //==INFOS is commented
1152   //  INFOS(pthread_self() << "SigIntHandler activated") ;
1153 #else  
1154   signal( SIGINT, SigIntHandler );
1155   signal( SIGUSR1, SigIntHandler );
1156 #endif
1157
1158 }
1159
1160 void SetCpuUsed();
1161 void CallCancelThread();
1162
1163 #ifndef WIN32
1164 void SigIntHandler(int what , siginfo_t * siginfo ,
1165                    void * toto ) {
1166   //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1167   //             use of streams (and so on) should never be used because :
1168   //             streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1169   //             A stream operation may be interrupted by a signal and if the Handler use stream we
1170   //             may have a "Dead-Lock" ===HangUp
1171   //==MESSAGE is commented
1172   //  MESSAGE(pthread_self() << "SigIntHandler what     " << what << endl
1173   //          << "              si_signo " << siginfo->si_signo << endl
1174   //          << "              si_code  " << siginfo->si_code << endl
1175   //          << "              si_pid   " << siginfo->si_pid) ;
1176   if ( _Sleeping ) {
1177     _Sleeping = false ;
1178     //     MESSAGE("SigIntHandler END sleeping.") ;
1179     return ;
1180   }
1181   else {
1182     ActSigIntHandler() ;
1183     if ( siginfo->si_signo == SIGUSR1 ) {
1184       SetCpuUsed() ;
1185     }
1186     else if ( siginfo->si_signo == SIGUSR2 )
1187     {
1188       CallCancelThread() ;
1189     }
1190     else {
1191       _Sleeping = true ;
1192       //      MESSAGE("SigIntHandler BEGIN sleeping.") ;
1193       int count = 0 ;
1194       while( _Sleeping ) {
1195         sleep( 1 ) ;
1196         count += 1 ;
1197       }
1198       //      MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1199     }
1200     return ;
1201   }
1202 }
1203 #else // Case WIN32
1204 void SigIntHandler( int what ) {
1205   MESSAGE( pthread_self() << "SigIntHandler what     " << what << endl );
1206   if ( _Sleeping ) {
1207     _Sleeping = false ;
1208     MESSAGE("SigIntHandler END sleeping.") ;
1209     return ;
1210   }
1211   else {
1212     ActSigIntHandler() ;
1213     if ( what == SIGUSR1 ) {
1214       SetCpuUsed() ;
1215     }
1216     else {
1217       _Sleeping = true ;
1218       MESSAGE("SigIntHandler BEGIN sleeping.") ;
1219       int count = 0 ;
1220       while( _Sleeping ) {
1221         Sleep( 1000 ) ;
1222         count += 1 ;
1223       }
1224       MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1225     }
1226     return ;
1227   }
1228 }
1229 #endif