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