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