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