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