Salome HOME
CCAR: several changes in Container Manager and Resources Manager
[modules/kernel.git] / src / Container / SALOME_ContainerManager.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 #include "SALOME_ContainerManager.hxx"
23 #include "SALOME_NamingService.hxx"
24 #include "SALOME_ModuleCatalog.hh"
25 #include "Basics_Utils.hxx"
26 #include "Basics_DirUtils.hxx"
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #ifndef WIN32
30 #include <unistd.h>
31 #endif
32 #include <vector>
33 #include "Utils_CorbaException.hxx"
34 #include "Batch_Date.hxx"
35
36 #ifdef WITH_PACO_PARALLEL
37 #include "PaCO++.h"
38 #endif
39
40 #define TIME_OUT_TO_LAUNCH_CONT 61
41
42 using namespace std;
43
44 vector<Engines::Container_ptr> SALOME_ContainerManager::_batchLaunchedContainers;
45
46 vector<Engines::Container_ptr>::iterator SALOME_ContainerManager::_batchLaunchedContainersIter;
47
48 const char *SALOME_ContainerManager::_ContainerManagerNameInNS = 
49   "/ContainerManager";
50
51 //=============================================================================
52 /*! 
53  *  Constructor
54  *  \param orb
55  *  Define a CORBA single thread policy for the server, which avoid to deal
56  *  with non thread-safe usage like Change_Directory in SALOME naming service
57  */
58 //=============================================================================
59
60 SALOME_ContainerManager::SALOME_ContainerManager(CORBA::ORB_ptr orb, PortableServer::POA_var poa, SALOME_ResourcesManager *rm, SALOME_NamingService *ns)
61 {
62   MESSAGE("constructor");
63   _NS = ns;
64   _ResManager = rm;
65
66   PortableServer::POAManager_var pman = poa->the_POAManager();
67   _orb = CORBA::ORB::_duplicate(orb) ;
68   CORBA::PolicyList policies;
69   policies.length(1);
70   PortableServer::ThreadPolicy_var threadPol = 
71     poa->create_thread_policy(PortableServer::SINGLE_THREAD_MODEL);
72   policies[0] = PortableServer::ThreadPolicy::_duplicate(threadPol);
73
74   _poa = poa->create_POA("SThreadPOA",pman,policies);
75   threadPol->destroy();
76   PortableServer::ObjectId_var id = _poa->activate_object(this);
77   CORBA::Object_var obj = _poa->id_to_reference(id);
78   Engines::ContainerManager_var refContMan =
79     Engines::ContainerManager::_narrow(obj);
80
81   _NS->Register(refContMan,_ContainerManagerNameInNS);
82   _MpiStarted = false;
83   _isAppliSalomeDefined = (getenv("APPLI") != 0);
84   MESSAGE("constructor end");
85 }
86
87 //=============================================================================
88 /*! 
89  * destructor
90  */
91 //=============================================================================
92
93 SALOME_ContainerManager::~SALOME_ContainerManager()
94 {
95   MESSAGE("destructor");
96 }
97
98 //=============================================================================
99 //! shutdown all the containers, then the ContainerManager servant
100 /*! CORBA method:
101  */
102 //=============================================================================
103
104 void SALOME_ContainerManager::Shutdown()
105 {
106   MESSAGE("Shutdown");
107   ShutdownContainers();
108   _NS->Destroy_Name(_ContainerManagerNameInNS);
109   PortableServer::ObjectId_var oid = _poa->servant_to_id(this);
110   _poa->deactivate_object(oid);
111 }
112
113 //=============================================================================
114 //! Loop on all the containers listed in naming service, ask shutdown on each
115 /*! CORBA Method:
116  */
117 //=============================================================================
118
119 void SALOME_ContainerManager::ShutdownContainers()
120 {
121   MESSAGE("ShutdownContainers");
122   bool isOK;
123   isOK = _NS->Change_Directory("/Containers");
124   if( isOK ){
125     vector<string> vec = _NS->list_directory_recurs();
126     list<string> lstCont;
127     for(vector<string>::iterator iter = vec.begin();iter!=vec.end();iter++)
128       {
129         SCRUTE((*iter));
130         CORBA::Object_var obj=_NS->Resolve((*iter).c_str());
131         try
132           {
133             Engines::Container_var cont=Engines::Container::_narrow(obj);
134             if(!CORBA::is_nil(cont))
135               lstCont.push_back((*iter));
136           }
137         catch(const CORBA::Exception& e)
138           {
139             // ignore this entry and continue
140           }
141       }
142     MESSAGE("Container list: ");
143     for(list<string>::iterator iter=lstCont.begin();iter!=lstCont.end();iter++){
144       SCRUTE((*iter));
145     }
146     for(list<string>::iterator iter=lstCont.begin();iter!=lstCont.end();iter++){
147       SCRUTE((*iter));
148       CORBA::Object_var obj=_NS->Resolve((*iter).c_str());
149       Engines::Container_var cont=Engines::Container::_narrow(obj);
150       if(!CORBA::is_nil(cont))
151         {
152           MESSAGE("ShutdownContainers: " << (*iter));
153           try
154             {
155               cont->Shutdown();
156             }
157           catch(CORBA::SystemException& e)
158             {
159               INFOS("CORBA::SystemException ignored : " << e);
160             }
161           catch(CORBA::Exception&)
162             {
163               INFOS("CORBA::Exception ignored.");
164             }
165           catch(...)
166             {
167               INFOS("Unknown exception ignored.");
168             }
169         }
170       else 
171         MESSAGE("ShutdownContainers: no container ref for " << (*iter));
172     }
173   }
174 }
175
176 //=============================================================================
177 //! Give a suitable Container given constraints
178 /*! CORBA Method:
179  *  \param params            Machine Parameters required for the container
180  *  \return the container or nil
181  */
182 //=============================================================================
183
184 Engines::Container_ptr
185 SALOME_ContainerManager::GiveContainer(const Engines::MachineParameters& params)
186 {
187   char *valenv=getenv("SALOME_BATCH");
188   if(valenv)
189     if (strcmp(valenv,"1")==0)
190       {
191         if(_batchLaunchedContainers.empty())
192           fillBatchLaunchedContainers();
193
194         if (_batchLaunchedContainersIter == _batchLaunchedContainers.end())
195           _batchLaunchedContainersIter = _batchLaunchedContainers.begin();
196
197         Engines::Container_ptr rtn = Engines::Container::_duplicate(*_batchLaunchedContainersIter);
198         _batchLaunchedContainersIter++;
199         return rtn;
200       }
201   return StartContainer(params);
202 }
203
204 //=============================================================================
205 //! Start a suitable Container in a list of machines with constraints 
206 /*! C++ Method:
207  * Constraints are given by a machine parameters struct
208  *  \param params            Machine Parameters required for the container
209  *  \param possibleComputers list of machines usable for start
210  *  \param container_exe specific container executable (default=SALOME_Container)
211  */
212 //=============================================================================
213
214 Engines::Container_ptr
215 SALOME_ContainerManager::StartContainer(const Engines::MachineParameters& params,
216                const Engines::MachineList& possibleComputers,
217                const std::string& container_exe)
218 {
219 #ifdef WITH_PACO_PARALLEL
220   std::string parallelLib(params.parallelLib);
221   if (parallelLib != "")
222     {
223       Engines::MachineParameters myparams(params);
224       myparams.computerList=possibleComputers;
225       return FindOrStartParallelContainer(myparams);
226     }
227 #endif
228   string containerNameInNS;
229   Engines::Container_ptr ret = Engines::Container::_nil();
230
231   MESSAGE("SALOME_ContainerManager::StartContainer " << possibleComputers.length());
232
233   vector<string> lm;
234 // if mode is "get" keep only machines with existing containers 
235   if(std::string(params.mode.in())=="get")
236     {
237       for(unsigned int i=0;i<possibleComputers.length();i++)
238         {
239           Engines::Container_ptr cont = FindContainer(params,possibleComputers[i]);
240           try
241             {
242               if(!cont->_non_existent())
243                 lm.push_back(string(possibleComputers[i]));
244             }
245           catch(CORBA::Exception&)
246             {
247               // CORBA::Exception ignored.
248             }
249         }
250     }
251   else
252     {
253       for(unsigned int i=0;i<possibleComputers.length();i++)
254         lm.push_back(string(possibleComputers[i]));
255     }
256
257   string theMachine;
258   try
259     {
260       theMachine=_ResManager->GetImpl()->Find(params.policy.in(),lm);
261     }
262   catch( const SALOME_Exception &ex )
263     {
264       MESSAGE(ex.what());
265       return Engines::Container::_nil();
266     }
267
268   //If the machine name is localhost use the real name
269   if(theMachine == "localhost")
270     theMachine=Kernel_Utils::GetHostname();
271
272   //check if an entry exists in Naming service
273   //if params.mode == "start" or "" shutdown the existing container before launching a new one with that name
274   //if params.mode == "getorstart" or "get" use the existing container
275   containerNameInNS = _NS->BuildContainerNameForNS(params,theMachine.c_str());
276
277   SCRUTE(containerNameInNS);
278   CORBA::Object_var obj = _NS->Resolve(containerNameInNS.c_str());
279   if ( !CORBA::is_nil(obj) )
280     {
281       try
282         {
283           Engines::Container_var cont=Engines::Container::_narrow(obj);
284           if(!cont->_non_existent())
285             {
286               if(std::string(params.mode.in())=="getorstart"||std::string(params.mode.in())=="get")
287                 return cont._retn(); /* the container exists and params.mode is getorstart or get use it*/
288               else
289                 cont->Shutdown(); // shutdown the registered container if it exists
290             }
291         }
292       catch(CORBA::Exception&)
293         {
294           INFOS("CORBA::Exception ignored.");
295         }
296     }
297
298   //try to launch a new container
299   MESSAGE("try to launch it on " << theMachine);
300
301   string command;
302   if(theMachine==""){
303     MESSAGE("SALOME_ContainerManager::StartContainer : no possible computer");
304     return Engines::Container::_nil();
305   }
306   else if(theMachine==Kernel_Utils::GetHostname())
307     command = BuildCommandToLaunchLocalContainer(params,container_exe);
308   else
309     command = BuildCommandToLaunchRemoteContainer(theMachine,params,container_exe);
310
311   //redirect stdout and stderr in a file
312   string logFilename="/tmp/"+_NS->ContainerName(params)+"_"+ theMachine +"_"+getenv( "USER" )+".log" ;
313   command += " > " + logFilename + " 2>&1 &";
314
315   // launch container with a system call
316   int status=system(command.c_str());
317
318   if (status == -1){
319     MESSAGE("SALOME_ContainerManager::StartContainer rsh failed (system command status -1)");
320     RmTmpFile(_TmpFileName); // command file can be removed here
321     return Engines::Container::_nil();
322   }
323   else if (status == 217){
324     MESSAGE("SALOME_ContainerManager::StartContainer rsh failed (system command status 217)");
325     RmTmpFile(_TmpFileName); // command file can be removed here
326     return Engines::Container::_nil();
327   }
328   else{
329     int count=TIME_OUT_TO_LAUNCH_CONT;
330     MESSAGE("count = "<<count);
331     while ( CORBA::is_nil(ret) && count ){
332 #ifndef WIN32
333       sleep( 1 ) ;
334 #else
335       Sleep(1000);
336 #endif
337       count-- ;
338       if ( count != 10 )
339         MESSAGE( count << ". Waiting for container on " << theMachine);
340
341       CORBA::Object_var obj = _NS->Resolve(containerNameInNS.c_str());
342       ret=Engines::Container::_narrow(obj);
343     }
344     
345     if ( CORBA::is_nil(ret) )
346       {
347         MESSAGE("SALOME_ContainerManager::StartContainer rsh failed");
348       }
349     else
350       {
351         logFilename=":"+logFilename;
352         logFilename="@"+Kernel_Utils::GetHostname()+logFilename;
353         logFilename=getenv( "USER" )+logFilename;
354         ret->logfilename(logFilename.c_str());
355       }
356
357     RmTmpFile(_TmpFileName); // command file can be removed here
358     return ret;
359   }
360 }
361
362 //=============================================================================
363 //! Start a suitable Container given constraints 
364 /*! CORBA Method:
365  *  \param params            Machine Parameters required for the container
366  */
367 //=============================================================================
368
369 Engines::Container_ptr
370 SALOME_ContainerManager::StartContainer(const Engines::MachineParameters& params)
371 {
372   Engines::MachineList_var possibleComputers = _ResManager->GetFittingResources(params);
373
374   // Look into ModulCatalog if a specific container must be launched
375   CORBA::String_var container_exe;
376   int found=0;
377   try
378     {
379       CORBA::Object_var obj = _NS->Resolve("/Kernel/ModulCatalog");
380       SALOME_ModuleCatalog::ModuleCatalog_var Catalog = SALOME_ModuleCatalog::ModuleCatalog::_narrow(obj) ;
381       if (CORBA::is_nil (Catalog))
382         return Engines::Container::_nil();
383       // Loop through component list
384       for(unsigned int i=0;i<params.componentList.length();i++)
385         {
386           const char* compoi = params.componentList[i];
387           SALOME_ModuleCatalog::Acomponent_var compoInfo = Catalog->GetComponent(compoi);
388           if (CORBA::is_nil (compoInfo))
389             {
390               continue;
391             }
392           SALOME_ModuleCatalog::ImplType impl=compoInfo->implementation_type();
393           container_exe=compoInfo->implementation_name();
394           if(impl==SALOME_ModuleCatalog::CEXE)
395             {
396               if(found)
397                 {
398                   INFOS("ContainerManager Error: you can't have 2 CEXE component in the same container" );
399                   return Engines::Container::_nil();
400                 }
401               found=1;
402             }
403         }
404     }
405   catch (ServiceUnreachable&)
406     {
407       INFOS("Caught exception: Naming Service Unreachable");
408       return Engines::Container::_nil();
409     }
410   catch (...)
411     {
412       INFOS("Caught unknown exception.");
413       return Engines::Container::_nil();
414     }
415
416   if(found)
417     return StartContainer(params,possibleComputers,container_exe.in());
418   else
419     return StartContainer(params,possibleComputers);
420 }
421
422 //=============================================================================
423 //!  Find or start a suitable Container given some constraints
424 /*! CORBA Method:
425  *  \param params            Machine Parameters required for the container
426  *  \return the container or nil
427  */
428 //=============================================================================
429
430 Engines::Container_ptr
431 SALOME_ContainerManager::FindOrStartContainer(const Engines::MachineParameters& params)
432 {
433   Engines::Container_ptr ret = FindContainer(params,params.computerList);
434   if(!CORBA::is_nil(ret))
435     return ret;
436   MESSAGE("Container doesn't exist try to launch it ...");
437
438   return StartContainer(params);
439 }
440
441 //=============================================================================
442 //! Find a container given constraints (params) on a list of machines (possibleComputers)
443 /*!
444  *
445  */
446 //=============================================================================
447
448 Engines::Container_ptr
449 SALOME_ContainerManager::FindContainer(const Engines::MachineParameters& params,
450                                        const Engines::MachineList& possibleComputers)
451 {
452   MESSAGE("FindContainer "<<possibleComputers.length());
453   for(unsigned int i=0;i<possibleComputers.length();i++)
454     {
455       MESSAGE("FindContainer possible " << possibleComputers[i]);
456       Engines::Container_ptr cont = FindContainer(params,possibleComputers[i]);
457       if( !CORBA::is_nil(cont) )
458         return cont;
459     }
460   MESSAGE("FindContainer: not found");
461   return Engines::Container::_nil();
462 }
463
464 //=============================================================================
465 //! Find a container given constraints (params) on a machine (theMachine)
466 /*!
467  *
468  */
469 //=============================================================================
470
471 Engines::Container_ptr
472 SALOME_ContainerManager::FindContainer(const Engines::MachineParameters& params,
473                                        const char *theMachine)
474 {
475   string containerNameInNS(_NS->BuildContainerNameForNS(params,theMachine));
476   CORBA::Object_var obj = _NS->Resolve(containerNameInNS.c_str());
477   try
478     {
479       if(obj->_non_existent())
480         return Engines::Container::_nil();
481       else
482         return Engines::Container::_narrow(obj);
483     }
484   catch(const CORBA::Exception& e)
485     {
486       return Engines::Container::_nil();
487     }
488 }
489
490 #ifdef WITH_PACO_PARALLEL
491 //=============================================================================
492 /*! CORBA Method:
493  *  Find or Start a suitable PaCO++ Parallel Container in a list of machines.
494  *  \param params            Machine Parameters required for the container
495  *  \return CORBA container reference.
496  */
497 //=============================================================================
498 Engines::Container_ptr
499 SALOME_ContainerManager::FindOrStartParallelContainer(const Engines::MachineParameters& params_const)
500 {
501   CORBA::Object_var obj;
502   PaCO::InterfaceManager_var proxy;
503   Engines::Container_ptr ret = Engines::Container::_nil();
504   Engines::MachineParameters params(params_const);
505
506   // Step 1 : Try to find a suitable container
507   // Currently not as good as could be since
508   // we have to verified the number of nodes of the container
509   // if a user tell that.
510   ret = FindContainer(params, params.computerList);
511
512   if(CORBA::is_nil(ret)) {
513     // Step 2 : Starting a new parallel container
514     INFOS("[FindOrStartParallelContainer] Starting a parallel container");
515
516     // Step 2.1 : Choose a computer
517     string theMachine = _ResManager->FindFirst(params.computerList);
518     if(theMachine == "") {
519       INFOS("[FindOrStartParallelContainer] !!!!!!!!!!!!!!!!!!!!!!!!!!");
520       INFOS("[FindOrStartParallelContainer] No possible computer found");
521       INFOS("[FindOrStartParallelContainer] !!!!!!!!!!!!!!!!!!!!!!!!!!");
522     }
523     else {
524       INFOS("[FindOrStartParallelContainer] on machine : " << theMachine);
525       string command;
526       if(theMachine == Kernel_Utils::GetHostname()) {
527         // Step 3 : starting parallel container proxy
528         params.hostname = CORBA::string_dup(theMachine.c_str());
529         Engines::MachineParameters params_proxy(params);
530         try {
531           command = BuildCommandToLaunchLocalParallelContainer("SALOME_ParallelContainerProxy", params_proxy, "xterm");
532         }
533         catch(const SALOME_Exception & ex){
534           MESSAGE(ex.what());
535           return Engines::Container::_nil();
536         }
537         // LaunchParallelContainer uses this value to know if it launches the proxy or the nodes
538         params_proxy.nb_component_nodes = 0;
539         obj = LaunchParallelContainer(command, params_proxy, _NS->ContainerName(params));
540         ret = Engines::Container::_narrow(obj);
541         proxy = PaCO::InterfaceManager::_narrow(obj);
542
543         // Step 4 : starting parallel container nodes
544         command = BuildCommandToLaunchLocalParallelContainer("SALOME_ParallelContainerNode", params, "xterm");
545         string name = _NS->ContainerName(params) + "Node";
546         LaunchParallelContainer(command, params, name);
547         // Step 5 : connecting nodes and the proxy to actually create a parallel container
548         try {
549           for (int i = 0; i < params.nb_component_nodes; i++) {
550
551             char buffer [5];
552 #ifndef WIN32
553             snprintf(buffer,5,"%d",i);
554 #else
555             _snprintf(buffer,5,"%d",i);
556 #endif
557             string name_cont = name + string(buffer);
558
559             string theNodeMachine(CORBA::string_dup(params.hostname));
560             string containerNameInNS = _NS->BuildContainerNameForNS(name_cont.c_str(),theNodeMachine.c_str());
561             int count = TIME_OUT_TO_LAUNCH_CONT;
562             obj = _NS->Resolve(containerNameInNS.c_str());
563             while (CORBA::is_nil(obj) && count) {
564               INFOS("[FindOrStartParallelContainer] CONNECTION FAILED !!!!!!!!!!!!!!!!!!!!!!!!");
565 #ifndef WIN32
566               sleep(1) ;
567 #else
568               Sleep(1000);
569 #endif
570               count-- ;
571               obj = _NS->Resolve(containerNameInNS.c_str());
572             }
573
574             PaCO::InterfaceParallel_var node = PaCO::InterfaceParallel::_narrow(obj);
575             MESSAGE("[FindOrStartParallelContainer] Deploying node : " << name);
576             node->deploy();
577           }
578           proxy->start();
579         }
580         catch(CORBA::SystemException& e)
581           {
582             INFOS("Caught CORBA::SystemException. : " << e);
583           }
584         catch(PortableServer::POA::ServantAlreadyActive&)
585           {
586             INFOS("Caught CORBA::ServantAlreadyActiveException");
587           }
588         catch(CORBA::Exception&)
589           {
590             INFOS("Caught CORBA::Exception.");
591           }
592         catch(std::exception& exc)
593           {
594             INFOS("Caught std::exception - "<<exc.what()); 
595           }
596         catch(...)
597           {
598             INFOS("Caught unknown exception.");
599           }
600         INFOS("[FindOrStartParallelContainer] node " << name << " deployed");
601       }
602       else {
603         INFOS("[FindOrStartParallelContainer] Currently parallel containers are launched only on the local host");
604       }
605     }
606   }
607   return ret;
608 }
609 #else
610 //=============================================================================
611 /*! CORBA Method:
612  *  Find or Start a suitable PaCO++ Parallel Container in a list of machines.
613  *  \param params            Machine Parameters required for the container
614  *  \return CORBA container reference.
615  */
616 //=============================================================================
617 Engines::Container_ptr
618 SALOME_ContainerManager::FindOrStartParallelContainer(const Engines::MachineParameters& params)
619 {
620   Engines::Container_ptr ret = Engines::Container::_nil();
621   INFOS("[FindOrStartParallelContainer] is disabled !");
622   INFOS("[FindOrStartParallelContainer] recompile SALOME Kernel to enable parallel extension");
623   return ret;
624 }
625 #endif
626
627 //=============================================================================
628 /*! This method launches the parallel container.
629  *  It will may be placed on the ressources manager.
630  *
631  * \param command to launch
632  * \param container's parameters
633  * \param name of the container
634  *
635  * \return CORBA container reference
636  */
637 //=============================================================================
638 CORBA::Object_ptr 
639 SALOME_ContainerManager::LaunchParallelContainer(const std::string& command, 
640                                                  const Engines::MachineParameters& params,
641                                                  const std::string& name)
642 {
643   CORBA::Object_ptr obj = CORBA::Object::_nil();
644   string containerNameInNS;
645   MESSAGE("[LaunchParallelContainer] : command to launch...");
646   MESSAGE(command);
647   if (params.nb_component_nodes == 0) {
648     INFOS("[LaunchParallelContainer] launching the proxy of the parallel container");
649     int status = system(command.c_str());
650     if (status == -1) {
651       INFOS("[LaunchParallelContainer] failed : system command status -1");
652     }
653     else if (status == 217) {
654       INFOS("[LaunchParallelContainer] failed : system command status 217");
655     }
656
657     int count = TIME_OUT_TO_LAUNCH_CONT;
658     string theMachine(CORBA::string_dup(params.hostname));
659     containerNameInNS = _NS->BuildContainerNameForNS((char*) name.c_str(),theMachine.c_str());
660
661     INFOS("[LaunchParallelContainer]  Waiting for Parallel Container proxy on " << theMachine);
662     while (CORBA::is_nil(obj) && count) {
663 #ifndef WIN32
664       sleep(1) ;
665 #else
666       Sleep(1000);
667 #endif
668       count-- ;
669       obj = _NS->Resolve(containerNameInNS.c_str());
670     }
671   }
672   else {
673     INFOS("[LaunchParallelContainer] launching the nodes of the parallel container");
674     int status = system(command.c_str());
675     if (status == -1) {
676       INFOS("[LaunchParallelContainer] failed : system command status -1");
677     }
678     else if (status == 217) {
679       INFOS("[LaunchParallelContainer] failed : system command status 217");
680     }
681     // We are waiting all the nodes
682     for (int i = 0; i < params.nb_component_nodes; i++) {
683       obj = CORBA::Object::_nil();
684       int count = TIME_OUT_TO_LAUNCH_CONT;
685
686       // Name of the node
687       char buffer [5];
688 #ifndef WIN32
689       snprintf(buffer,5,"%d",i);
690 #else
691       _snprintf(buffer,5,"%d",i);
692 #endif
693
694       string name_cont = name + string(buffer);
695
696       // I don't like this...
697       string theMachine(CORBA::string_dup(params.hostname));
698       containerNameInNS = _NS->BuildContainerNameForNS((char*) name_cont.c_str(),theMachine.c_str());
699       cerr << "[LaunchContainer]  Waiting for Parllel Container node " << containerNameInNS << " on " << theMachine << endl;
700       while (CORBA::is_nil(obj) && count) {
701 #ifndef WIN32
702         sleep(1) ;
703 #else
704         Sleep(1000);
705 #endif
706         count-- ;
707         obj = _NS->Resolve(containerNameInNS.c_str());
708       }
709     }
710   }
711
712   if ( CORBA::is_nil(obj) ) {
713     INFOS("[LaunchParallelContainer] failed");
714   }
715   return obj;
716 }
717
718 void SALOME_ContainerManager::fillBatchLaunchedContainers()
719 {
720   _batchLaunchedContainers.clear();
721   _NS->Change_Directory("/Containers");
722   vector<string> vec = _NS->list_directory_recurs();
723   for(vector<string>::iterator iter = vec.begin();iter!=vec.end();iter++){
724     CORBA::Object_var obj=_NS->Resolve((*iter).c_str());
725     Engines::Container_ptr cont=Engines::Container::_narrow(obj);
726     if(!CORBA::is_nil(cont)){
727       _batchLaunchedContainers.push_back(cont);
728     }
729   }
730   _batchLaunchedContainersIter=_batchLaunchedContainers.begin();
731 }
732
733 //=============================================================================
734 /*!
735  *  This is no longer valid (C++ container are also python containers)
736  */ 
737 //=============================================================================
738
739 bool isPythonContainer(const char* ContainerName)
740 {
741   bool ret = false;
742   int len = strlen(ContainerName);
743
744   if (len >= 2)
745     if (strcmp(ContainerName + len - 2, "Py") == 0)
746       ret = true;
747
748   return ret;
749 }
750
751 //=============================================================================
752 /*!
753  *  Builds the script to be launched
754  *
755  *  If SALOME Application not defined ($APPLI),
756  *  see BuildTempFileToLaunchRemoteContainer()
757  *
758  *  Else rely on distant configuration. Command is under the form (example):
759  *  ssh user@machine distantPath/runRemote.sh hostNS portNS WORKINGDIR workingdir \
760  *                   SALOME_Container containerName &"
761
762  *  - where user is ommited if not specified in CatalogResources,
763  *  - where distant path is always relative to user@machine $HOME, and
764  *    equal to $APPLI if not specified in CatalogResources,
765  *  - where hostNS is the hostname of CORBA naming server (set by scripts to
766  *    use to launch SALOME and servers in $APPLI: runAppli.sh, runRemote.sh)
767  *  - where portNS is the port used by CORBA naming server (set by scripts to
768  *    use to launch SALOME and servers in $APPLI: runAppli.sh, runRemote.sh)
769  *  - where workingdir is the requested working directory for the container.
770  *    If WORKINGDIR (and workingdir) is not present the working dir will be $HOME
771  */ 
772 //=============================================================================
773
774 string
775 SALOME_ContainerManager::BuildCommandToLaunchRemoteContainer
776 (const string& machine,
777  const Engines::MachineParameters& params, const std::string& container_exe)
778 {
779   string command;
780   int nbproc;
781           
782   if ( ! _isAppliSalomeDefined )
783     command = BuildTempFileToLaunchRemoteContainer(machine, params);
784
785   else
786     {
787       const ParserResourcesType& resInfo = _ResManager->GetImpl()->GetResourcesList(machine);
788
789       if (params.isMPI)
790         {
791           if ( (params.nb_node <= 0) && (params.nb_proc_per_node <= 0) )
792             nbproc = 1;
793           else if ( params.nb_node == 0 )
794             nbproc = params.nb_proc_per_node;
795           else if ( params.nb_proc_per_node == 0 )
796             nbproc = params.nb_node;
797           else
798             nbproc = params.nb_node * params.nb_proc_per_node;
799         }
800
801       // "ssh user@machine distantPath/runRemote.sh hostNS portNS WORKINGDIR workingdir \
802         //  SALOME_Container containerName &"
803
804       if (resInfo.Protocol == rsh)
805         command = "rsh ";
806       else if (resInfo.Protocol == ssh)
807         command = "ssh ";
808       else
809         throw SALOME_Exception("Unknown protocol");
810
811       if (resInfo.UserName != "")
812         {
813           command += resInfo.UserName;
814           command += "@";
815         }
816
817       command += machine;
818       command += " ";
819
820       if (resInfo.AppliPath != "")
821         command += resInfo.AppliPath; // path relative to user@machine $HOME
822       else
823         {
824           ASSERT(getenv("APPLI"));
825           command += getenv("APPLI"); // path relative to user@machine $HOME
826         }
827
828       command += "/runRemote.sh ";
829
830       ASSERT(getenv("NSHOST")); 
831       command += getenv("NSHOST"); // hostname of CORBA name server
832
833       command += " ";
834       ASSERT(getenv("NSPORT"));
835       command += getenv("NSPORT"); // port of CORBA name server
836
837       std::string wdir=params.workingdir.in();
838       if(wdir != "")
839         {
840           command += " WORKINGDIR ";
841           command += " '";
842           if(wdir == "$TEMPDIR")
843             wdir="\\$TEMPDIR";
844           command += wdir; // requested working directory
845           command += "'"; 
846         }
847
848       if(params.isMPI)
849         {
850           command += " mpirun -np ";
851           std::ostringstream o;
852           o << nbproc << " ";
853           command += o.str();
854 #ifdef WITHLAM
855           command += "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
856 #elif defined(WITHOPENMPI)
857           if( getenv("OMPI_URI_FILE") == NULL )
858             command += "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace";
859           else{
860             command += "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace -ompi-server file:";
861             command += getenv("OMPI_URI_FILE");
862           }
863 #endif  
864           command += " SALOME_MPIContainer ";
865         }
866       else
867         command += " " +container_exe+ " ";
868
869       command += _NS->ContainerName(params);
870       command += " -";
871       AddOmninamesParams(command);
872
873       MESSAGE("command =" << command);
874     }
875
876   return command;
877 }
878
879 //=============================================================================
880 /*!
881  *  builds the command to be launched.
882  */ 
883 //=============================================================================
884
885 string
886 SALOME_ContainerManager::BuildCommandToLaunchLocalContainer
887 (const Engines::MachineParameters& params, const std::string& container_exe)
888 {
889   _TmpFileName = BuildTemporaryFileName();
890   string command;
891   int nbproc = 0;
892
893   ofstream command_file( _TmpFileName.c_str() );
894
895   if (params.isMPI)
896     {
897       //command = "mpirun -np ";
898       command_file << "mpirun -np ";
899
900       if ( (params.nb_node <= 0) && (params.nb_proc_per_node <= 0) )
901         nbproc = 1;
902       else if ( params.nb_node == 0 )
903         nbproc = params.nb_proc_per_node;
904       else if ( params.nb_proc_per_node == 0 )
905         nbproc = params.nb_node;
906       else
907         nbproc = params.nb_node * params.nb_proc_per_node;
908
909       //std::ostringstream o;
910
911       //o << nbproc << " ";
912       command_file << nbproc << " ";
913
914       //command += o.str();
915 #ifdef WITHLAM
916       //command += "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
917       command_file << "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
918 #elif defined(WITHOPENMPI)
919       //command += "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace ";
920       if( getenv("OMPI_URI_FILE") == NULL )
921         command_file << "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace";
922       else
923         {
924           command_file << "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace -ompi-server file:";
925           command_file << getenv("OMPI_URI_FILE");
926         }
927 #endif
928
929       if (isPythonContainer(params.container_name))
930         //command += "pyMPI SALOME_ContainerPy.py ";
931         command_file << " pyMPI SALOME_ContainerPy.py ";
932       else
933         //command += "SALOME_MPIContainer ";
934         command_file << " SALOME_MPIContainer ";
935     }
936
937   else
938     {
939       //command="";
940       std::string wdir=params.workingdir.in();
941       if(wdir != "")
942         {
943           // a working directory is requested
944           if(wdir == "$TEMPDIR")
945             {
946               // a new temporary directory is requested
947               string dir = Kernel_Utils::GetTmpDir();
948 #ifdef WIN32
949               //command += "cd /d "+ dir +";";
950               command_file << "cd /d " << dir << endl;
951 #else
952               //command = "cd "+ dir +";";
953               command_file << "cd " << dir << ";";
954 #endif
955
956             }
957           else
958             {
959               // a permanent directory is requested use it or create it
960 #ifdef WIN32
961               //command="mkdir " + wdir;
962               command_file << "mkdir " + wdir << endl;
963               command_file << "cd /D " + wdir << endl;
964 #else
965               //command="mkdir -p " + wdir + " && cd " + wdir + ";";
966               command_file << "mkdir -p " << wdir << " && cd " << wdir + ";";
967 #endif
968             }
969         }
970       if (isPythonContainer(params.container_name))
971         //command += "SALOME_ContainerPy.py ";
972         command_file << "SALOME_ContainerPy.py ";
973       else
974         //command += container_exe + " ";
975         command_file << container_exe + " ";
976
977     }
978
979   command_file << _NS->ContainerName(params);
980   command_file << " -";
981   AddOmninamesParams(command_file);
982   command_file.close();
983
984 #ifndef WIN32
985   chmod(_TmpFileName.c_str(), 0x1ED);
986 #endif
987   command = _TmpFileName;
988
989   MESSAGE("Command is file ... " << command);
990   return command;
991 }
992
993
994 //=============================================================================
995 /*!
996  *  removes the generated temporary file in case of a remote launch.
997  */ 
998 //=============================================================================
999
1000 void SALOME_ContainerManager::RmTmpFile(std::string& tmpFileName)
1001 {
1002   int lenght = tmpFileName.size();
1003   if ( lenght  > 0)
1004     {
1005 #ifdef WIN32
1006       string command = "del /F ";
1007 #else
1008       string command = "rm ";      
1009 #endif
1010       if ( lenght > 4 )
1011         command += tmpFileName.substr(0, lenght - 3 );
1012       else
1013         command += tmpFileName;
1014       command += '*';
1015       system(command.c_str());
1016       //if dir is empty - remove it
1017       string tmp_dir = Kernel_Utils::GetDirByPath( tmpFileName );
1018       if ( Kernel_Utils::IsEmptyDir( tmp_dir ) )
1019         {
1020 #ifdef WIN32
1021           command = "del /F " + tmp_dir;
1022 #else
1023           command = "rmdir " + tmp_dir;
1024 #endif
1025           system(command.c_str());
1026         }
1027     }
1028 }
1029
1030 //=============================================================================
1031 /*!
1032  *   add to command all options relative to naming service.
1033  */ 
1034 //=============================================================================
1035
1036 void SALOME_ContainerManager::AddOmninamesParams(string& command) const
1037 {
1038   CORBA::String_var iorstr = _NS->getIORaddr();
1039   command += "ORBInitRef NameService=";
1040   command += iorstr;
1041 }
1042
1043
1044 //=============================================================================
1045 /*!
1046  *  add to command all options relative to naming service.
1047  */ 
1048 //=============================================================================
1049
1050 void SALOME_ContainerManager::AddOmninamesParams(ofstream& fileStream) const
1051 {
1052   CORBA::String_var iorstr = _NS->getIORaddr();
1053   fileStream << "ORBInitRef NameService=";
1054   fileStream << iorstr;
1055 }
1056
1057 //=============================================================================
1058 /*!
1059  *  generate a file name in /tmp directory
1060  */ 
1061 //=============================================================================
1062
1063 string SALOME_ContainerManager::BuildTemporaryFileName() const
1064 {
1065   //build more complex file name to support multiple salome session
1066   string aFileName = Kernel_Utils::GetTmpFileName();
1067 #ifndef WIN32
1068   aFileName += ".sh";
1069 #else
1070   aFileName += ".bat";
1071 #endif
1072   return aFileName;
1073 }
1074
1075
1076 //=============================================================================
1077 /*!
1078  *  Builds in a temporary file the script to be launched.
1079  *  
1080  *  Used if SALOME Application ($APPLI) is not defined.
1081  *  The command is build with data from CatalogResources, in which every path
1082  *  used on remote computer must be defined.
1083  */ 
1084 //=============================================================================
1085
1086 string
1087 SALOME_ContainerManager::BuildTempFileToLaunchRemoteContainer
1088 (const string& machine,
1089  const Engines::MachineParameters& params) throw(SALOME_Exception)
1090 {
1091   int status;
1092
1093   _TmpFileName = BuildTemporaryFileName();
1094   ofstream tempOutputFile;
1095   tempOutputFile.open(_TmpFileName.c_str(), ofstream::out );
1096   const ParserResourcesType& resInfo = _ResManager->GetImpl()->GetResourcesList(machine);
1097   tempOutputFile << "#! /bin/sh" << endl;
1098
1099   // --- set env vars
1100
1101   tempOutputFile << "export SALOME_trace=local" << endl; // mkr : 27.11.2006 : PAL13967 - Distributed supervision graphs - Problem with "SALOME_trace"
1102   //tempOutputFile << "source " << resInfo.PreReqFilePath << endl;
1103
1104   // ! env vars
1105
1106   if (params.isMPI)
1107     {
1108       tempOutputFile << "mpirun -np ";
1109       int nbproc;
1110
1111       if ( (params.nb_node <= 0) && (params.nb_proc_per_node <= 0) )
1112         nbproc = 1;
1113       else if ( params.nb_node == 0 )
1114         nbproc = params.nb_proc_per_node;
1115       else if ( params.nb_proc_per_node == 0 )
1116         nbproc = params.nb_node;
1117       else
1118         nbproc = params.nb_node * params.nb_proc_per_node;
1119
1120       std::ostringstream o;
1121
1122       tempOutputFile << nbproc << " ";
1123 #ifdef WITHLAM
1124       tempOutputFile << "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
1125 #elif defined(WITHOPENMPI)
1126       if( getenv("OMPI_URI_FILE") == NULL )
1127         tempOutputFile << "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace";
1128       else{
1129         tempOutputFile << "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace -ompi-server file:";
1130         tempOutputFile << getenv("OMPI_URI_FILE");
1131       }
1132 #endif
1133     }
1134
1135   tempOutputFile << getenv("KERNEL_ROOT_DIR") << "/bin/salome/";
1136
1137   if (params.isMPI)
1138     {
1139       if (isPythonContainer(params.container_name))
1140         tempOutputFile << " pyMPI SALOME_ContainerPy.py ";
1141       else
1142         tempOutputFile << " SALOME_MPIContainer ";
1143     }
1144
1145   else
1146     {
1147       if (isPythonContainer(params.container_name))
1148         tempOutputFile << "SALOME_ContainerPy.py ";
1149       else
1150         tempOutputFile << "SALOME_Container ";
1151     }
1152
1153   tempOutputFile << _NS->ContainerName(params) << " -";
1154   AddOmninamesParams(tempOutputFile);
1155   tempOutputFile << " &" << endl;
1156   tempOutputFile.flush();
1157   tempOutputFile.close();
1158 #ifndef WIN32
1159   chmod(_TmpFileName.c_str(), 0x1ED);
1160 #endif
1161
1162   // --- Build command
1163
1164   string command;
1165
1166   if (resInfo.Protocol == rsh)
1167     {
1168       command = "rsh ";
1169       string commandRcp = "rcp ";
1170       commandRcp += _TmpFileName;
1171       commandRcp += " ";
1172       commandRcp += machine;
1173       commandRcp += ":";
1174       commandRcp += _TmpFileName;
1175       status = system(commandRcp.c_str());
1176     }
1177
1178   else if (resInfo.Protocol == ssh)
1179     {
1180       command = "ssh ";
1181       string commandRcp = "scp ";
1182       commandRcp += _TmpFileName;
1183       commandRcp += " ";
1184       commandRcp += machine;
1185       commandRcp += ":";
1186       commandRcp += _TmpFileName;
1187       status = system(commandRcp.c_str());
1188     }
1189   else
1190     throw SALOME_Exception("Unknown protocol");
1191
1192   if(status)
1193     throw SALOME_Exception("Error of connection on remote host");    
1194
1195   command += machine;
1196   _CommandForRemAccess = command;
1197   command += " ";
1198   command += _TmpFileName;
1199
1200   SCRUTE(command);
1201
1202   return command;
1203
1204 }
1205
1206 //=============================================================================
1207 /*! Creates a command line that the container manager uses to launch
1208  * a parallel container.
1209  */ 
1210 //=============================================================================
1211 string 
1212 SALOME_ContainerManager::BuildCommandToLaunchLocalParallelContainer(const std::string& exe_name,
1213                                                                     const Engines::MachineParameters& params,
1214                                                                     const std::string& log)
1215 {
1216   // This method knows the differences between the proxy and the nodes.
1217   // nb_component_nodes is not used in the same way if it is a proxy or 
1218   // a node.
1219
1220   string command;
1221   string parallelLib(CORBA::string_dup(params.parallelLib));
1222   string hostname(CORBA::string_dup(params.hostname));
1223   int par = exe_name.find("Proxy");
1224   int nbproc = params.nb_component_nodes;
1225   char buffer [33];
1226   sprintf(buffer,"%d",nbproc);
1227
1228   Engines::MachineParameters_var rtn = new Engines::MachineParameters();
1229   rtn->container_name = params.container_name;
1230   rtn->hostname = params.hostname;
1231   rtn->OS = params.OS;
1232   rtn->mem_mb = params.mem_mb;
1233   rtn->cpu_clock = params.cpu_clock;
1234   rtn->nb_proc_per_node = params.nb_proc_per_node;
1235   rtn->nb_node = params.nb_node;
1236   rtn->isMPI = params.isMPI;
1237
1238   string real_exe_name  = exe_name + parallelLib;
1239
1240   if (parallelLib == "Dummy")
1241     {
1242       //command = "gdb --args ";
1243       //command = "valgrind --tool=memcheck --log-file=val_log ";
1244       //command += real_exe_name;
1245
1246       command = real_exe_name;
1247
1248       command += " " + _NS->ContainerName(rtn);
1249       command += " " + parallelLib;
1250       command += " " + hostname;
1251       command += " -";
1252       AddOmninamesParams(command);
1253     }
1254
1255   else if (parallelLib == "Mpi")
1256     {
1257       // Step 1 : check if MPI is started
1258       if (_MpiStarted == false)
1259         {
1260           startMPI();
1261         }
1262
1263       if (par < 0)
1264         {
1265           // Nodes case
1266
1267           command = "mpiexec -np " + string(buffer) + " ";
1268           //      command += "gdb --args ";
1269           command += real_exe_name;
1270           command += " " + _NS->ContainerName(rtn);
1271           command += " " + parallelLib;
1272           command += " " + hostname;
1273           command += " -";
1274           AddOmninamesParams(command);
1275         }
1276       else                                          
1277         {
1278           // Proxy case
1279           command = "mpiexec -np 1 ";
1280           command += real_exe_name;
1281           command += " " + _NS->ContainerName(rtn);
1282           command += " " + string(buffer);
1283           command += " " + parallelLib;
1284           command += " " + hostname;
1285           command += " -";
1286           AddOmninamesParams(command);
1287         }
1288     }
1289   else
1290     {
1291       std::string message("Unknown parallelLib" + parallelLib);
1292       throw SALOME_Exception(message.c_str());
1293     }
1294
1295   // log choice
1296   if (log == "default")
1297     {
1298       command += " > /tmp/";
1299       command += _NS->ContainerName(rtn);
1300       command += "_";
1301       command += Kernel_Utils::GetHostname();
1302       command += "_";
1303       command += getenv( "USER" ) ;
1304       command += ".log 2>&1 &" ;
1305     }
1306   if (log == "xterm")
1307     {
1308       command = "/usr/X11R6/bin/xterm -e \"export LD_LIBRARY_PATH=$LD_LIBRARY_PATH; export PATH=$PATH;  " 
1309         + command + " \" &";
1310       //              + command + "; echo $LD_LIBRARY_PATH; cat \" &";
1311     }
1312   return command;
1313
1314   /*  if (log == "xterm")
1315       {
1316       command = "/usr/X11R6/bin/xterm -e \"export LD_LIBRARY_PATH=$LD_LIBRARY_PATH; export PATH=$PATH; echo $LD_LIBRARY_PATH; echo $PATH; " + command + "; cat \" &";
1317       }
1318   */
1319   /*  command = "cd ; rm " + fichier_commande + "; touch " + \
1320       fichier_commande + "; echo \" export LD_LIBRARY_PATH=$LD_LIBRARY_PATH; " + \
1321       command + " >& /tmp/ribes_" + fichier_commande + " & \" > " + fichier_commande + ";";
1322       command += "ssh cn01 sh " + fichier_commande + " &";
1323       cerr << "La commande : " << command << endl;
1324   */
1325 }
1326
1327 void SALOME_ContainerManager::startMPI()
1328 {
1329   cerr << "----------------------------------------------" << endl;
1330   cerr << "----------------------------------------------" << endl;
1331   cerr << "----------------------------------------------" << endl;
1332   cerr << "-Only Lam on Localhost is currently supported-" << endl;
1333   cerr << "----------------------------------------------" << endl;
1334   cerr << "----------------------------------------------" << endl;
1335   cerr << "----------------------------------------------" << endl;
1336
1337   int status = system("lamboot");
1338   if (status == -1)
1339     {
1340       INFOS("lamboot failed : system command status -1");
1341     }
1342   else if (status == 217)
1343     {
1344       INFOS("lamboot failed : system command status 217");
1345     }
1346   else
1347     {
1348       _MpiStarted = true;
1349     }
1350 }
1351
1352 string SALOME_ContainerManager::GetMPIZeroNode(string machine)
1353 {
1354   int status;
1355   string zeronode;
1356   string cmd;
1357   string tmpFile = BuildTemporaryFileName();
1358
1359   cmd = "ssh " + machine + " mpirun -np 1 hostname > " + tmpFile;
1360
1361   status = system(cmd.c_str());
1362   if( status == 0 ){
1363     ifstream fp(tmpFile.c_str(),ios::in);
1364     fp >> zeronode;
1365   }
1366
1367   RmTmpFile(tmpFile);
1368
1369   return zeronode;
1370 }