Salome HOME
merge from BR_KERNEL_REFACTORING
[modules/kernel.git] / src / LifeCycleCORBA / SALOME_LifeCycleCORBA.cxx
1 // Copyright (C) 2007-2012  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 //  SALOME LifeCycleCORBA : implementation of containers and engines life cycle both in Python and C++
24 //  File   : SALOME_LifeCycleCORBA.cxx
25 //  Author : Paul RASCLE, EDF
26 //  Module : SALOME
27
28 #include <iostream>
29 #include <fstream>
30 #include <sstream>
31 #include <iomanip>
32
33 #include <time.h>
34 #ifndef WIN32
35   #include <sys/time.h>
36   #include <unistd.h>
37 #endif
38
39 #include "Basics_Utils.hxx"
40 #include "utilities.h"
41
42 #include <ServiceUnreachable.hxx>
43
44 #include "SALOME_LifeCycleCORBA.hxx"
45 #include CORBA_CLIENT_HEADER(SALOME_ModuleCatalog)
46 #include CORBA_CLIENT_HEADER(SALOME_Session)
47 #include CORBA_CLIENT_HEADER(DSC_Engines)
48 #include CORBA_CLIENT_HEADER(SALOME_Registry)
49 #include CORBA_CLIENT_HEADER(SALOMEDS)
50 #include CORBA_CLIENT_HEADER(Logger)
51
52 #include "SALOME_ContainerManager.hxx"
53 #include "SALOME_Component_i.hxx"
54 #include "SALOME_NamingService.hxx"
55 #include "SALOME_FileTransferCORBA.hxx"
56
57 IncompatibleComponent::IncompatibleComponent( void ):
58   SALOME_Exception( "IncompatibleComponent" )
59 {
60 }
61
62 IncompatibleComponent::IncompatibleComponent(const IncompatibleComponent &ex):
63   SALOME_Exception( ex ) 
64 {
65 }
66
67 /*! \class SALOME_LifeCycleCORBA
68     \brief A class to manage life cycle of SALOME components.
69
70 */
71
72 //=============================================================================
73 /*! 
74  *  Constructor
75  */
76 //=============================================================================
77
78 SALOME_LifeCycleCORBA::SALOME_LifeCycleCORBA(SALOME_NamingService *ns)
79 {
80   // be sure to have an instance of traceCollector, when used via SWIG
81   // in a Python module
82   int argc = 0;
83   char *xargv = (char*)"";
84   char **argv = &xargv;
85   CORBA::ORB_var orb = CORBA::ORB_init(argc, argv);
86   //  LocalTraceCollector *myThreadTrace = SALOMETraceCollector::instance(orb);
87   _NSnew=0;
88   if (!ns)
89     {
90       _NS = new SALOME_NamingService(orb);
91       _NSnew=_NS;
92     }
93   else _NS = ns;
94   //add try catch
95   _NS->Change_Directory("/"); // mpv 250105: current directory may be not root 
96                               // (in SALOMEDS for an example)
97   // not enough: set a current directory in naming service is not thread safe
98   // if naming service instance is shared among several threads...
99   // ==> allways use absolute path and dot rely on current directory!
100
101   CORBA::Object_var obj =
102     _NS->Resolve(SALOME_ContainerManager::_ContainerManagerNameInNS);
103   if (CORBA::is_nil(obj))
104     throw SALOME_Exception("Error: Cannot resolve ContainerManager in Naming Service");
105   _ContManager=Engines::ContainerManager::_narrow(obj);
106
107   obj = _NS->Resolve(SALOME_ResourcesManager::_ResourcesManagerNameInNS);
108   if (CORBA::is_nil(obj))
109     throw SALOME_Exception("Error: Cannot resolve ResourceManager in Naming Service");
110   _ResManager=Engines::ResourcesManager::_narrow(obj);
111 }
112
113 //=============================================================================
114 /*! 
115  *  Destructor
116  */
117 //=============================================================================
118
119 SALOME_LifeCycleCORBA::~SALOME_LifeCycleCORBA()
120 {
121   if(_NSnew)delete _NSnew;
122 }
123
124 //=============================================================================
125 /*! \brief Find an already existing and registered component instance.
126  *
127  *  \param params         machine parameters like type or name...
128  *  \param componentName  the name of component class
129  *  \param studyId        default = 0  : multistudy instance
130  *  \return a CORBA reference of the component instance, or _nil if not found
131  */
132 //=============================================================================
133 Engines::EngineComponent_ptr
134 SALOME_LifeCycleCORBA::FindComponent(const Engines::MachineParameters& params,
135                                      const char *componentName,
136                                      int studyId)
137 {
138   if (! isKnownComponentClass(componentName))
139     return Engines::EngineComponent::_nil();
140
141   Engines::ContainerParameters new_params;
142   convert(params, new_params);
143   new_params.resource_params.componentList.length(1);
144   new_params.resource_params.componentList[0] = componentName;
145   Engines::ResourceList_var listOfResources;
146   try
147     {
148       listOfResources = _ResManager->GetFittingResources(new_params.resource_params);
149     }
150   catch( const SALOME::SALOME_Exception& ex )
151     {
152       return Engines::EngineComponent::_nil();
153     }
154
155   Engines::EngineComponent_var compo = _FindComponent(new_params,
156                                                 componentName,
157                                                 studyId,
158                                                 listOfResources);
159
160   return compo._retn();
161 }
162
163 //=============================================================================
164 /*! \brief Load a component instance on a container defined by machine parameters
165  *
166  *  \param params         machine parameters like type or name...
167  *  \param componentName  the name of component class
168  *  \param studyId        default = 0  : multistudy instance
169  *  \return a CORBA reference of the component instance, or _nil if problem
170  */
171 //=============================================================================
172
173 Engines::EngineComponent_ptr
174 SALOME_LifeCycleCORBA::LoadComponent(const Engines::MachineParameters& params,
175                                      const char *componentName,
176                                      int studyId)
177 {
178   // --- Check if Component Name is known in ModuleCatalog
179
180   if (! isKnownComponentClass(componentName))
181     return Engines::EngineComponent::_nil();
182
183   Engines::ContainerParameters new_params;
184   convert(params, new_params);
185   new_params.resource_params.componentList.length(1);
186   new_params.resource_params.componentList[0] = componentName;
187
188   Engines::ResourceList_var listOfResources;
189   try
190     {
191       listOfResources = _ResManager->GetFittingResources(new_params.resource_params);
192     }
193   catch( const SALOME::SALOME_Exception& ex )
194     {
195       return Engines::EngineComponent::_nil();
196     }
197   new_params.resource_params.resList = listOfResources;
198
199   Engines::EngineComponent_var compo = _LoadComponent(new_params,
200                                                 componentName,
201                                                 studyId);
202
203   return compo._retn();
204 }
205
206 //=============================================================================
207 /*! \brief Find an already existing and registered component instance or load a new
208  *         component instance on a container defined by machine parameters.
209  *
210  *  \param params         machine parameters like type or name...
211  *  \param componentName  the name of component class
212  *  \param studyId        default = 0  : multistudy instance
213  *  \return a CORBA reference of the component instance, or _nil if problem
214  */
215 //=============================================================================
216
217 Engines::EngineComponent_ptr
218 SALOME_LifeCycleCORBA::
219 FindOrLoad_Component(const Engines::MachineParameters& params,
220                      const char *componentName,
221                      int studyId)
222 {
223   // --- Check if Component Name is known in ModuleCatalog
224
225   if (! isKnownComponentClass(componentName))
226     return Engines::EngineComponent::_nil();
227
228   Engines::ContainerParameters new_params;
229   convert(params, new_params);
230   new_params.resource_params.componentList.length(1);
231   new_params.resource_params.componentList[0] = componentName;
232
233   // For Compatibility -> if hostname == localhost put name == hostname
234   if (std::string(new_params.resource_params.hostname.in()) == "localhost")
235   {
236     new_params.resource_params.hostname = CORBA::string_dup(Kernel_Utils::GetHostname().c_str());
237     new_params.resource_params.name = CORBA::string_dup(Kernel_Utils::GetHostname().c_str());
238   }
239
240   Engines::ResourceList_var listOfResources;
241   try
242     {
243       listOfResources = _ResManager->GetFittingResources(new_params.resource_params);
244     }
245   catch( const SALOME::SALOME_Exception& ex )
246     {
247       return Engines::EngineComponent::_nil();
248     }
249
250   Engines::EngineComponent_var compo = _FindComponent(new_params,
251                                                 componentName,
252                                                 studyId,
253                                                 listOfResources);
254
255   if(CORBA::is_nil(compo))
256   {
257     new_params.resource_params.resList = listOfResources;
258     compo = _LoadComponent(new_params,
259                            componentName,
260                            studyId);
261   }
262
263   return compo._retn();
264 }
265
266 Engines::EngineComponent_ptr
267 SALOME_LifeCycleCORBA::
268 FindOrLoad_Component(const Engines::ContainerParameters& params,
269                      const char *componentName,
270                      int studyId)
271 {
272   // --- Check if Component Name is known in ModuleCatalog
273
274   if (! isKnownComponentClass(componentName))
275     return Engines::EngineComponent::_nil();
276
277   Engines::ContainerParameters new_params(params);
278   new_params.resource_params.componentList.length(1);
279   new_params.resource_params.componentList[0] = componentName;
280
281   Engines::ResourceList_var listOfResources;
282   try
283     {
284       listOfResources = _ResManager->GetFittingResources(new_params.resource_params);
285     }
286   catch( const SALOME::SALOME_Exception& ex )
287     {
288       return Engines::EngineComponent::_nil();
289     }
290
291   Engines::EngineComponent_var compo = _FindComponent(new_params,
292                                                 componentName,
293                                                 studyId,
294                                                 listOfResources);
295
296   if(CORBA::is_nil(compo))
297   {
298     new_params.resource_params.resList = listOfResources;
299     compo = _LoadComponent(new_params,
300                            componentName,
301                            studyId);
302   }
303
304   return compo._retn();
305 }
306
307 //=============================================================================
308 /*! \brief Find an already existing and registered component instance or load a new
309  *         component instance on a container defined by name
310  *
311  *  \param containerName  the name of container, under one of the forms
312  *           - 1 aContainer (local container)
313  *           - 2 machine/aContainer (container on hostname = machine)
314  *  \param componentName  the name of component class
315  *  \return a CORBA reference of the component instance, or _nil if problem
316  */
317 //=============================================================================
318
319 Engines::EngineComponent_ptr
320 SALOME_LifeCycleCORBA::FindOrLoad_Component(const char *containerName,
321                                             const char *componentName)
322 {
323   MESSAGE("SALOME_LifeCycleCORBA::FindOrLoad_Component INTERACTIF " << containerName << " " << componentName ) ;
324
325   // --- Check if Component Name is known in ModuleCatalog
326   if (! isKnownComponentClass(componentName))
327     return Engines::EngineComponent::_nil();
328
329   // --- Check if containerName contains machine name (if yes: rg>0)
330   char *stContainer=strdup(containerName);
331   std::string st2Container(stContainer);
332   int rg=st2Container.find("/");
333
334   Engines::MachineParameters_var params=new Engines::MachineParameters;
335   preSet(params);
336   if (rg<0)
337   {
338     // containerName doesn't contain "/" => Local container
339     params->container_name=CORBA::string_dup(stContainer);
340     params->hostname="";
341   }
342   else 
343   {
344     stContainer[rg]='\0';
345     params->container_name=CORBA::string_dup(stContainer+rg+1);
346     params->hostname=CORBA::string_dup(stContainer);
347   }
348   params->isMPI = false;
349   SCRUTE(params->container_name);
350   free(stContainer);
351   return FindOrLoad_Component(params, componentName);
352 }
353
354 //=============================================================================
355 /*! \brief Check if the component class is known in module catalog
356  *
357  *  \param componentName  the name of component class
358  *  \return true if found, false otherwise
359  */
360 //=============================================================================
361
362 bool SALOME_LifeCycleCORBA::isKnownComponentClass(const char *componentName)
363 {
364   try
365   {
366     CORBA::Object_var obj = _NS->Resolve("/Kernel/ModulCatalog");
367     SALOME_ModuleCatalog::ModuleCatalog_var Catalog = 
368       SALOME_ModuleCatalog::ModuleCatalog::_narrow(obj) ;
369     ASSERT(! CORBA::is_nil(Catalog));
370     SALOME_ModuleCatalog::Acomponent_var compoInfo = 
371       Catalog->GetComponent(componentName);
372     if (CORBA::is_nil (compoInfo)) 
373     {
374       MESSAGE("Catalog Error: Component not found in the catalog " << componentName);
375       return false;
376     }
377     else return true;
378   }
379   catch (ServiceUnreachable&)
380   {
381     INFOS("Caught exception: Naming Service Unreachable");
382   }
383   catch (...)
384   {
385     INFOS("Caught unknown exception.");
386   }
387   return false;
388 }
389
390 //=============================================================================
391 /*! 
392  *  Not so complex... useful ?
393  */
394 //=============================================================================
395
396 bool 
397 SALOME_LifeCycleCORBA::isMpiContainer(const Engines::ContainerParameters& params)
398   throw(IncompatibleComponent)
399 {
400   if( params.isMPI )
401     return true;
402   else
403     return false;
404 }
405
406
407 //=============================================================================
408 /*! \brief Initialisation of a given Engines::MachineParameters with default values.
409  *
410  *  - container_name = ""  : not relevant
411  *  - hostname = ""        : not relevant
412  *  - OS = ""              : not relevant
413  *  - nb_proc = 0          : not relevant
414  *  - mem_mb = 0           : not relevant
415  *  - cpu_clock = 0        : not relevant
416  *  - nb_proc_per_node = 0 : not relevant
417  *  - nb_node = 0          : not relevant
418  *  - isMPI = false        : standard components
419  */
420 //=============================================================================
421
422 void SALOME_LifeCycleCORBA::preSet(Engines::MachineParameters& params)
423 {
424   params.container_name = "";
425   params.hostname = "";
426   params.OS = "";
427   params.mem_mb = 0;
428   params.cpu_clock = 0;
429   params.nb_proc_per_node = 0;
430   params.nb_node = 0;
431   params.isMPI = false;
432   params.workingdir = "";
433   params.mode = "";
434   params.policy = "";
435   params.parallelLib = "";
436   params.nb_component_nodes = 0;
437 }
438
439 void 
440 SALOME_LifeCycleCORBA::preSet(Engines::ResourceParameters& params)
441 {
442   params.name = "";
443   params.hostname = "";
444   params.OS = "";
445   params.nb_proc = 0;
446   params.mem_mb = 0;
447   params.cpu_clock = 0;
448   params.nb_node = 0;
449   params.nb_proc_per_node = 0;
450   params.policy = "";
451 }
452
453 void SALOME_LifeCycleCORBA::preSet( Engines::ContainerParameters& params)
454 {
455   params.container_name = "";
456   params.mode = "";
457   params.workingdir = "";
458   params.nb_proc = 0;
459   params.isMPI = false;
460   params.parallelLib = "";
461   SALOME_LifeCycleCORBA::preSet(params.resource_params);
462 }
463
464 void 
465 SALOME_LifeCycleCORBA::convert(const Engines::MachineParameters& params_in, 
466                                Engines::ContainerParameters& params_out)
467 {
468   SALOME_LifeCycleCORBA::preSet(params_out);
469
470   // Container part
471   params_out.container_name = params_in.container_name;
472   params_out.mode = params_in.mode;
473   params_out.workingdir = params_in.workingdir;
474   params_out.isMPI = params_in.isMPI;
475   params_out.parallelLib = params_in.parallelLib;
476
477   // Resource part
478   params_out.resource_params.hostname = params_in.hostname;
479   params_out.resource_params.OS = params_in.OS;
480   params_out.resource_params.mem_mb = params_in.mem_mb;
481   params_out.resource_params.cpu_clock = params_in.cpu_clock;
482   params_out.resource_params.nb_node = params_in.nb_node;
483   params_out.resource_params.nb_proc_per_node = params_in.nb_proc_per_node;
484   params_out.resource_params.policy = params_in.policy;
485   params_out.resource_params.componentList = params_in.componentList;
486
487   params_out.resource_params.resList.length(params_in.computerList.length());
488   for (CORBA::ULong i = 0; i < params_in.computerList.length(); i++)
489     params_out.resource_params.resList[i] = params_in.computerList[i];
490 }
491
492 //=============================================================================
493 /*! 
494  *  \return a number of processors not 0, only for MPI containers
495  */
496 //=============================================================================
497
498 int SALOME_LifeCycleCORBA::NbProc(const Engines::ContainerParameters& params)
499 {
500   if( !isMpiContainer(params) )
501     return 0;
502   else if( params.nb_proc <= 0 )
503     return 1;
504   else
505     return params.nb_proc;
506 }
507
508 //=============================================================================
509 /*! \brief Get the container manager
510  *
511  *  \return the container Manager
512  */
513 //=============================================================================
514
515 Engines::ContainerManager_ptr SALOME_LifeCycleCORBA::getContainerManager()
516 {
517  Engines::ContainerManager_var contManager =
518    Engines::ContainerManager::_duplicate(_ContManager);
519  return contManager._retn();
520 }
521
522 //=============================================================================
523 /*! \brief Get the resources manager
524  *
525  *  \return the container Manager
526  */
527 //=============================================================================
528
529 Engines::ResourcesManager_ptr SALOME_LifeCycleCORBA::getResourcesManager()
530 {
531  Engines::ResourcesManager_var resManager =
532    Engines::ResourcesManager::_duplicate(_ResManager);
533  return resManager._retn();
534 }
535
536 //=============================================================================
537 /*! \brief shutdown all the SALOME servers except SALOME_Session_Server, omniNames and notifd
538  */
539 //=============================================================================
540
541 void SALOME_LifeCycleCORBA::shutdownServers()
542 {
543   // get each Container from NamingService => shutdown it
544   // (the order is inverse to the order of servers initialization)
545   
546   SALOME::Session_var session = SALOME::Session::_nil();
547   CORBA::Long pid = 0;
548   CORBA::Object_var objS = _NS->Resolve("/Kernel/Session");
549   if (!CORBA::is_nil(objS))
550   {
551     session = SALOME::Session::_narrow(objS);
552     if (!CORBA::is_nil(session))
553     {
554       pid = session->getPID();
555       session->Shutdown();
556     }
557   }
558
559   std::string hostname = Kernel_Utils::GetHostname();
560   
561   // 1) ConnectionManager
562   try
563     {
564       CORBA::Object_var objCnM=_NS->Resolve("/ConnectionManager");
565       Engines::ConnectionManager_var connMan=Engines::ConnectionManager::_narrow(objCnM);
566       if ( !CORBA::is_nil(connMan) && ( pid != connMan->getPID() ) )
567         connMan->ShutdownWithExit();
568     }
569   catch(const CORBA::Exception& e)
570     {
571        // ignore and continue
572     }
573
574   timespec ts_req;
575   ts_req.tv_nsec=100000000;
576   ts_req.tv_sec=0;
577
578 //Wait some time so that ConnectionManager be completely shutdown
579 #ifndef WIN32
580   nanosleep(&ts_req,0);
581 #endif
582
583   // 2) SALOMEDS
584   try
585     {
586       CORBA::Object_var objSDS = _NS->Resolve("/myStudyManager");
587       SALOMEDS::StudyManager_var studyManager = SALOMEDS::StudyManager::_narrow(objSDS) ;
588       if ( !CORBA::is_nil(studyManager) && ( pid != studyManager->getPID() ) )
589         studyManager->Shutdown();
590     }
591   catch(const CORBA::Exception& e)
592     {
593        // ignore and continue
594     }
595
596 //Wait some time so that study be completely shutdown
597 #ifndef WIN32
598   nanosleep(&ts_req,0);
599 #endif
600
601   // 3) ModuleCatalog
602   try
603     {
604       CORBA::Object_var objMC=_NS->Resolve("/Kernel/ModulCatalog");
605       SALOME_ModuleCatalog::ModuleCatalog_var catalog = SALOME_ModuleCatalog::ModuleCatalog::_narrow(objMC);
606       if ( !CORBA::is_nil(catalog) && ( pid != catalog->getPID() ) )
607         catalog->shutdown();
608     }
609   catch(const CORBA::Exception& e)
610     {
611        // ignore and continue
612     }
613
614 //Wait some time so that ModulCatalog be completely shutdown
615 #ifndef WIN32
616   nanosleep(&ts_req,0);
617 #endif
618
619   // 4) SalomeLauncher
620   try
621     {
622       CORBA::Object_var objSL = _NS->Resolve("/SalomeLauncher");
623       Engines::SalomeLauncher_var launcher = Engines::SalomeLauncher::_narrow(objSL);
624       if (!CORBA::is_nil(launcher) && (pid != launcher->getPID()))
625         launcher->Shutdown();
626     }
627   catch(const CORBA::Exception& e)
628     {
629        // ignore and continue
630     }
631   
632 //Wait some time so that launcher be completely shutdown
633 #ifndef WIN32
634   nanosleep(&ts_req,0);
635 #endif
636
637   // 5) Registry
638   try
639     {
640       CORBA::Object_var objR = _NS->Resolve("/Registry");
641       Registry::Components_var registry = Registry::Components::_narrow(objR);
642       if ( !CORBA::is_nil(registry) && ( pid != registry->getPID() ) )
643           registry->Shutdown();
644     }
645   catch(const CORBA::Exception& e)
646     {
647        // ignore and continue
648     }
649
650   /*
651   // 6) Session
652   if ( !CORBA::is_nil( session ) ) {
653     try
654     {
655       session->Shutdown();
656     }
657     catch(const CORBA::Exception& e)
658     {
659       // ignore and continue
660     }
661   }
662   */
663
664   // 7) Logger
665   int argc = 0;
666   char *xargv = (char*)"";
667   char **argv = &xargv;
668   CORBA::ORB_var orb = CORBA::ORB_init(argc, argv);
669
670   CORBA::Object_var objLog = CORBA::Object::_nil();
671   CosNaming::NamingContext_var inc;
672   CORBA::Object_var theObj = CORBA::Object::_nil();
673   std::string stdname = "Logger";
674   CosNaming::Name name;
675   name.length(1);
676   name[0].id = CORBA::string_dup(stdname.c_str());
677   try
678   { 
679     if(!CORBA::is_nil(orb)) 
680       theObj = orb->resolve_initial_references("NameService");
681     if (!CORBA::is_nil(theObj))
682       inc = CosNaming::NamingContext::_narrow(theObj);
683   }
684   catch(...)
685   {
686   }
687   if(!CORBA::is_nil(inc)) 
688   {
689     try
690     {
691       objLog = inc->resolve(name);
692       SALOME_Logger::Logger_var logger = SALOME_Logger::Logger::_narrow(objLog);
693       if ( !CORBA::is_nil(logger) )
694         logger->shutdown();
695     }
696     catch(...)
697     {
698     }
699   }
700 }
701
702 //=============================================================================
703 /*! \brief shutdown  omniNames and notifd
704  */
705 //=============================================================================
706
707 void SALOME_LifeCycleCORBA::killOmniNames()
708 {
709   std::string portNumber (::getenv ("NSPORT") );
710   if ( !portNumber.empty() ) 
711   {
712 #ifdef WNT
713 #else
714     std::string cmd ;
715     cmd = std::string( "ps -eo pid,command | grep -v grep | grep -E \"omniNames.*")
716       + portNumber
717       + std::string("\" | awk '{cmd=sprintf(\"kill -9 %s\",$1); system(cmd)}'" );
718     MESSAGE(cmd);
719     try {
720       system ( cmd.c_str() );
721     }
722     catch ( ... ) {
723     }
724 #endif
725   }
726   
727   // NPAL 18309  (Kill Notifd)
728   if ( !portNumber.empty() ) 
729   {
730     std::string cmd = ("from killSalomeWithPort import killNotifdAndClean; ");
731     cmd += std::string("killNotifdAndClean(") + portNumber + "); ";
732     cmd  = std::string("python -c \"") + cmd +"\" > /dev/null 2> /dev/null";
733     MESSAGE(cmd);
734     system( cmd.c_str() );
735   }
736 }
737
738 //=============================================================================
739 /*! \brief Find an already existing and registered component instance.
740  *
741  * - build a list of machines on which an instance of the component is running,
742  * - find the best machine among the list
743  *
744  *  \param params         machine parameters like type or name...
745  *  \param componentName  the name of component class
746  *  \param studyId        default = 0  : multistudy instance
747  *  \param listOfMachines list of machine address
748  *  \return a CORBA reference of the component instance, or _nil if not found
749  */
750 //=============================================================================
751
752 Engines::EngineComponent_ptr
753 SALOME_LifeCycleCORBA::
754 _FindComponent(const Engines::ContainerParameters& params,
755                const char *componentName,
756                int studyId,
757                const Engines::ResourceList& listOfResources)
758 {
759   // --- build the list of machines on which the component is already running
760   const char *containerName = params.container_name;
761   int nbproc = NbProc(params);
762
763   Engines::ResourceList_var resourcesOK = new Engines::ResourceList;
764
765   unsigned int lghtOfresourcesOK = 0;
766   resourcesOK->length(listOfResources.length());
767
768   for(unsigned int i=0; i < listOfResources.length(); i++)
769   {
770     const char * currentResource = listOfResources[i];
771     CORBA::Object_var obj = _NS->ResolveComponent(currentResource,
772                                                   containerName,
773                                                   componentName,
774                                                   nbproc);
775     if (!CORBA::is_nil(obj))
776       resourcesOK[lghtOfresourcesOK++] = CORBA::string_dup(currentResource);
777   }
778
779   // --- find the best machine among the list
780   if(lghtOfresourcesOK != 0)
781   {
782     resourcesOK->length(lghtOfresourcesOK);
783     CORBA::String_var bestResource = _ResManager->FindFirst(resourcesOK);
784     CORBA::Object_var obj = _NS->ResolveComponent(bestResource,
785                                                   containerName,
786                                                   componentName,
787                                                   nbproc);
788     return Engines::EngineComponent::_narrow(obj);
789   }
790   else
791     return Engines::EngineComponent::_nil();
792 }
793
794 //=============================================================================
795 /*! \brief  Load a component instance.
796  *
797  *  - Finds a container in the list of machine or start one.
798  *  - Try to load the component library in the container,
799  *  - then create an instance of the component.
800  *
801  *  \param params         machine parameters like type or name...
802  *  \param componentName  the name of component class
803  *  \param studyId        default = 0  : multistudy instance
804  *  \return a CORBA reference of the component instance, or _nil if problem
805  */
806 //=============================================================================
807
808 Engines::EngineComponent_ptr 
809 SALOME_LifeCycleCORBA::
810 _LoadComponent(const Engines::ContainerParameters& params, 
811               const char *componentName,
812               int studyId)
813 {
814   MESSAGE("_LoadComponent, required " << params.container_name <<
815           " " << componentName << " " << NbProc(params));
816
817   Engines::ContainerParameters local_params(params);
818   local_params.mode = CORBA::string_dup("findorstart");
819   Engines::Container_var cont = _ContManager->GiveContainer(local_params);
820   if (CORBA::is_nil(cont)) return Engines::EngineComponent::_nil();
821
822   char* reason;
823   bool isLoadable = cont->load_component_Library(componentName,reason);
824   if (!isLoadable) 
825     {
826       //std::cerr << reason << std::endl;
827       CORBA::string_free(reason);
828       return Engines::EngineComponent::_nil();
829     }
830   CORBA::string_free(reason);
831
832   Engines::EngineComponent_var myInstance =
833     cont->create_component_instance(componentName, studyId);
834   return myInstance._retn();
835 }
836
837 //=============================================================================
838 /*! \brief  Load a parallel component instance.
839  *
840  *  \param params         machine parameters like type or name...
841  *  \param componentName  the name of component class
842  *  \param studyId        default = 0  : multistudy instance
843  *  \return a CORBA reference of the parallel component instance, or _nil if problem
844  */
845 //=============================================================================
846 Engines::EngineComponent_ptr
847 SALOME_LifeCycleCORBA::Load_ParallelComponent(const Engines::ContainerParameters& params,
848                                               const char *componentName,
849                                               int studyId)
850 {
851   MESSAGE("Entering LoadParallelComponent");
852
853 /*MESSAGE("Parameters : ");
854   MESSAGE("Container name : " << params.container_name);
855   MESSAGE("Number of component nodes : " << params.nb_component_nodes);
856   MESSAGE("Component Name : " << componentName);*/
857
858   Engines::ContainerParameters parms(params);
859   parms.resource_params.componentList.length(1);
860   parms.resource_params.componentList[0] = componentName;
861   parms.mode = CORBA::string_dup("findorstart");
862
863   MESSAGE("Starting Parallel Container");
864   Engines::Container_var cont = _ContManager->GiveContainer(parms);
865   if (CORBA::is_nil(cont)) {
866     INFOS("FindOrStartParallelContainer() returns a NULL container !");
867     return Engines::EngineComponent::_nil();
868   }
869
870   MESSAGE("Loading component library");
871   char* reason;
872   bool isLoadable = cont->load_component_Library(componentName,reason);
873   if (!isLoadable) {
874     INFOS(componentName <<" library is not loadable !");
875     //std::cerr << reason << std::endl;
876     CORBA::string_free(reason);
877     return Engines::EngineComponent::_nil();
878   }
879   CORBA::string_free(reason);
880
881   MESSAGE("Creating component instance");
882   // @PARALLEL@ permits to identify that the component requested
883   // is a parallel component.
884   std::string name = std::string(componentName);
885   Engines::EngineComponent_var myInstance = cont->create_component_instance(name.c_str(), studyId);
886   if (CORBA::is_nil(myInstance))
887     INFOS("create_component_instance returns a NULL component !");
888   return myInstance._retn();
889 }
890
891 /*! \brief copy a file from a source host to a destination host
892  * \param hostSrc the source host
893  * \param fileSrc the file to copy from the source host to the destination host
894  * \param hostDest the destination host
895  * \param fileDest the destination file
896  */
897 void SALOME_LifeCycleCORBA::copyFile(const char* hostSrc, const char* fileSrc, const char* hostDest, const char* fileDest)
898 {
899   if(strcmp(hostDest,"localhost") == 0)
900     {
901       //if localhost use a shortcut
902       SALOME_FileTransferCORBA transfer(hostSrc,fileSrc);
903       transfer.getLocalFile(fileDest);
904       return;
905     }
906
907   Engines::ContainerManager_var contManager = getContainerManager();
908
909   Engines::ContainerParameters params;
910   preSet(params);
911
912   params.resource_params.hostname = hostDest;
913   params.mode = CORBA::string_dup("findorstart");
914   Engines::Container_var containerDest = contManager->GiveContainer(params);
915
916   params.resource_params.hostname = hostSrc;
917   Engines::Container_var containerSrc = contManager->GiveContainer(params);
918
919   containerDest->copyFile(containerSrc,fileSrc,fileDest);
920 }
921
922 /*! \brief get the naming service used by the life cycle
923  *
924  *  \return the naming service
925  */
926 SALOME_NamingService * SALOME_LifeCycleCORBA::namingService()
927 {
928   return _NS;
929 }
930
931 /*! \brief get the orb used by the life cycle
932  *
933  *  \return the orb
934  */
935 CORBA::ORB_ptr SALOME_LifeCycleCORBA::orb()
936 {
937   return _NS->orb();
938 }