]> SALOME platform Git repositories - modules/kernel.git/blob - src/Container/SALOME_ContainerManager.cxx
Salome HOME
allow launch MPI containers when MPI environment is not defined in default environmen...
[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 <sstream>
35
36 #ifdef WITH_PACO_PARALLEL
37 #include "PaCOPP.hxx"
38 #endif
39
40 #define TIME_OUT_TO_LAUNCH_CONT 61
41
42 using namespace std;
43
44 const char *SALOME_ContainerManager::_ContainerManagerNameInNS = 
45   "/ContainerManager";
46
47 omni_mutex SALOME_ContainerManager::_numInstanceMutex;
48
49
50 //=============================================================================
51 /*! 
52  *  Constructor
53  *  \param orb
54  *  Define a CORBA single thread policy for the server, which avoid to deal
55  *  with non thread-safe usage like Change_Directory in SALOME naming service
56  */
57 //=============================================================================
58
59 SALOME_ContainerManager::SALOME_ContainerManager(CORBA::ORB_ptr orb, PortableServer::POA_var poa, SALOME_ResourcesManager *rm, SALOME_NamingService *ns):_nbprocUsed(0)
60 {
61   MESSAGE("constructor");
62   _NS = ns;
63   _ResManager = rm;
64
65   PortableServer::POAManager_var pman = poa->the_POAManager();
66   _orb = CORBA::ORB::_duplicate(orb) ;
67   CORBA::PolicyList policies;
68   policies.length(1);
69   PortableServer::ThreadPolicy_var threadPol = 
70     poa->create_thread_policy(PortableServer::SINGLE_THREAD_MODEL);
71   policies[0] = PortableServer::ThreadPolicy::_duplicate(threadPol);
72
73   _poa = poa->create_POA("SThreadPOA",pman,policies);
74   threadPol->destroy();
75   PortableServer::ObjectId_var id = _poa->activate_object(this);
76   CORBA::Object_var obj = _poa->id_to_reference(id);
77   Engines::ContainerManager_var refContMan =
78     Engines::ContainerManager::_narrow(obj);
79
80   _NS->Register(refContMan,_ContainerManagerNameInNS);
81   _isAppliSalomeDefined = (getenv("APPLI") != 0);
82
83 #ifdef HAVE_MPI2
84 #ifdef WITHOPENMPI
85   if( getenv("OMPI_URI_FILE") != NULL ){
86     system("killall ompi-server");
87     string command;
88     command = "ompi-server -r ";
89     command += getenv("OMPI_URI_FILE");
90     int status=system(command.c_str());
91     if(status!=0)
92       throw SALOME_Exception("Error when launching ompi-server");
93   }
94 #endif
95 #endif
96
97   MESSAGE("constructor end");
98 }
99
100 //=============================================================================
101 /*! 
102  * destructor
103  */
104 //=============================================================================
105
106 SALOME_ContainerManager::~SALOME_ContainerManager()
107 {
108   MESSAGE("destructor");
109 #ifdef HAVE_MPI2
110 #ifdef WITHOPENMPI
111   if( getenv("OMPI_URI_FILE") != NULL )
112     system("killall ompi-server");
113 #endif
114 #endif
115 }
116
117 //=============================================================================
118 //! shutdown all the containers, then the ContainerManager servant
119 /*! CORBA method:
120  */
121 //=============================================================================
122
123 void SALOME_ContainerManager::Shutdown()
124 {
125   MESSAGE("Shutdown");
126   ShutdownContainers();
127   _NS->Destroy_Name(_ContainerManagerNameInNS);
128   PortableServer::ObjectId_var oid = _poa->servant_to_id(this);
129   _poa->deactivate_object(oid);
130 }
131
132 //=============================================================================
133 //! Loop on all the containers listed in naming service, ask shutdown on each
134 /*! CORBA Method:
135  */
136 //=============================================================================
137
138 void SALOME_ContainerManager::ShutdownContainers()
139 {
140   MESSAGE("ShutdownContainers");
141   bool isOK;
142   isOK = _NS->Change_Directory("/Containers");
143   if( isOK ){
144     vector<string> vec = _NS->list_directory_recurs();
145     list<string> lstCont;
146     for(vector<string>::iterator iter = vec.begin();iter!=vec.end();iter++)
147       {
148         SCRUTE((*iter));
149         CORBA::Object_var obj=_NS->Resolve((*iter).c_str());
150         try
151           {
152             Engines::Container_var cont=Engines::Container::_narrow(obj);
153             if(!CORBA::is_nil(cont))
154               lstCont.push_back((*iter));
155           }
156         catch(const CORBA::Exception& e)
157           {
158             // ignore this entry and continue
159           }
160       }
161     MESSAGE("Container list: ");
162     for(list<string>::iterator iter=lstCont.begin();iter!=lstCont.end();iter++){
163       SCRUTE((*iter));
164     }
165     for(list<string>::iterator iter=lstCont.begin();iter!=lstCont.end();iter++)
166     {
167       try
168       {
169         SCRUTE((*iter));
170         CORBA::Object_var obj=_NS->Resolve((*iter).c_str());
171         Engines::Container_var cont=Engines::Container::_narrow(obj);
172         if(!CORBA::is_nil(cont))
173         {
174           MESSAGE("ShutdownContainers: " << (*iter));
175           cont->Shutdown();
176         }
177         else 
178           MESSAGE("ShutdownContainers: no container ref for " << (*iter));
179       }
180       catch(CORBA::SystemException& e)
181       {
182         INFOS("CORBA::SystemException ignored : " << e);
183       }
184       catch(CORBA::Exception&)
185       {
186         INFOS("CORBA::Exception ignored.");
187       }
188       catch(...)
189       {
190         INFOS("Unknown exception ignored.");
191       }
192     }
193   }
194 }
195
196 //=============================================================================
197 //! Give a suitable Container given constraints
198 /*! CORBA Method:
199  *  \param params Container Parameters required for the container
200  *  \return the container or nil
201  */
202 //=============================================================================
203 Engines::Container_ptr
204 SALOME_ContainerManager::GiveContainer(const Engines::ContainerParameters& params)
205 {
206   string machFile;
207   Engines::Container_ptr ret = Engines::Container::_nil();
208
209   // Step 0: Default mode is start
210   Engines::ContainerParameters local_params(params);
211   if (std::string(local_params.mode.in()) == "")
212     local_params.mode = CORBA::string_dup("start");
213   std::string mode = local_params.mode.in();
214   MESSAGE("[GiveContainer] starting with mode: " << mode);
215
216   // Step 1: Find Container for find and findorstart mode
217   if (mode == "find" or mode == "findorstart")
218   {
219     ret = FindContainer(params, params.resource_params.resList);
220     if(!CORBA::is_nil(ret))
221       return ret;
222     else
223     {
224       if (mode == "find")
225       {
226         MESSAGE("[GiveContainer] no container found");
227         return ret;
228       }
229       else
230       {
231         mode = "start";
232       }
233     }
234   }
235
236   // Step 2: Get all possibleResources from the parameters
237   Engines::ResourceList_var possibleResources = _ResManager->GetFittingResources(local_params.resource_params);
238   MESSAGE("[GiveContainer] - length of possible resources " << possibleResources->length());
239   std::vector<std::string> local_resources;
240
241   // Step 3: if mode is "get" keep only machines with existing containers 
242   if(mode == "get")
243   {
244     for(unsigned int i=0; i < possibleResources->length(); i++)
245     {
246       Engines::Container_ptr cont = FindContainer(params, possibleResources[i].in());
247       try
248       {
249         if(!cont->_non_existent())
250           local_resources.push_back(string(possibleResources[i]));
251       }
252       catch(CORBA::Exception&) {}
253     }
254
255     // if local_resources is empty, we cannot give a container
256     if (local_resources.size() == 0)
257     {
258       MESSAGE("[GiveContainer] cannot find a container for mode get");
259       return ret;
260     }
261   }
262   else
263     for(unsigned int i=0; i < possibleResources->length(); i++)
264       local_resources.push_back(string(possibleResources[i]));
265
266   // Step 4: select the resource where to get/start the container
267   std::string resource_selected;
268   try
269   {
270     resource_selected = _ResManager->GetImpl()->Find(params.resource_params.policy.in(), local_resources);
271   }
272   catch(const SALOME_Exception &ex)
273   {
274     MESSAGE("[GiveContainer] Exception in ResourceManager find !: " << ex.what());
275     return ret;
276   }
277   MESSAGE("[GiveContainer] Resource selected is: " << resource_selected);
278
279   // Step 5: get container in the naming service
280   Engines::ResourceDefinition_var resource_definition = _ResManager->GetResourceDefinition(resource_selected.c_str());
281   std::string hostname(resource_definition->hostname.in());
282   std::string containerNameInNS;
283   if(params.isMPI){
284     int nbproc;
285     if ( (params.resource_params.nb_node <= 0) && (params.resource_params.nb_proc_per_node <= 0) )
286       nbproc = 1;
287     else if ( params.resource_params.nb_node == 0 )
288       nbproc = params.resource_params.nb_proc_per_node;
289     else if ( params.resource_params.nb_proc_per_node == 0 )
290       nbproc = params.resource_params.nb_node;
291     else
292       nbproc = params.resource_params.nb_node * params.resource_params.nb_proc_per_node;
293     if( getenv("LIBBATCH_NODEFILE") != NULL )
294       machFile = machinesFile(nbproc);
295     // A mpi parallel container register on zero node in NS
296     containerNameInNS = _NS->BuildContainerNameForNS(params, GetMPIZeroNode(hostname,machFile).c_str());
297   }
298   else
299     containerNameInNS = _NS->BuildContainerNameForNS(params, hostname.c_str());
300   MESSAGE("[GiveContainer] Container name in the naming service: " << containerNameInNS);
301
302   // Step 6: check if the name exists in naming service
303   //if params.mode == "getorstart" or "get" use the existing container
304   //if params.mode == "start" shutdown the existing container before launching a new one with that name
305   CORBA::Object_var obj = _NS->Resolve(containerNameInNS.c_str());
306   if (!CORBA::is_nil(obj))
307   {
308     try
309     {
310       Engines::Container_var cont=Engines::Container::_narrow(obj);
311       if(!cont->_non_existent())
312       {
313         if(std::string(params.mode.in())=="getorstart" or std::string(params.mode.in())=="get"){
314           return cont._retn(); /* the container exists and params.mode is getorstart or get use it*/
315         }
316         else
317         {
318           INFOS("[GiveContainer] A container is already registered with the name: " << containerNameInNS << ", shutdown the existing container");
319           cont->Shutdown(); // shutdown the registered container if it exists
320         }
321       }
322     }
323     catch(CORBA::Exception&)
324     {
325       INFOS("[GiveContainer] CORBA::Exception ignored when trying to get the container - we start a new one");
326     }
327   }
328
329   // Step 7: type of container: PaCO, Exe, Mpi or Classic
330   // Mpi already tested in step 5, specific code on BuildCommandToLaunch Local/Remote Container methods
331   // TODO -> separates Mpi from Classic/Exe
332   // Classic or Exe ?
333   std::string container_exe = "SALOME_Container"; // Classic container
334   int found=0;
335   try
336   {
337     CORBA::String_var container_exe_tmp;
338     CORBA::Object_var obj = _NS->Resolve("/Kernel/ModulCatalog");
339     SALOME_ModuleCatalog::ModuleCatalog_var Catalog = SALOME_ModuleCatalog::ModuleCatalog::_narrow(obj) ;
340     if (CORBA::is_nil (Catalog))
341     {
342       INFOS("[GiveContainer] Module Catalog is not found -> cannot launch a container");
343       return ret;
344     }
345     // Loop through component list
346     for(unsigned int i=0; i < local_params.resource_params.componentList.length(); i++)
347     {
348       const char* compoi = local_params.resource_params.componentList[i];
349       SALOME_ModuleCatalog::Acomponent_var compoInfo = Catalog->GetComponent(compoi);
350       if (CORBA::is_nil (compoInfo))
351       {
352         continue;
353       }
354       SALOME_ModuleCatalog::ImplType impl=compoInfo->implementation_type();
355       container_exe_tmp=compoInfo->implementation_name();
356       if(impl==SALOME_ModuleCatalog::CEXE)
357       {
358         if(found)
359         {
360           INFOS("ContainerManager Error: you can't have 2 CEXE component in the same container" );
361           return Engines::Container::_nil();
362         }
363         MESSAGE("[GiveContainer] Exe container found !: " << container_exe_tmp);
364         container_exe = container_exe_tmp.in();
365         found=1;
366       }
367     }
368   }
369   catch (ServiceUnreachable&)
370   {
371     INFOS("Caught exception: Naming Service Unreachable");
372     return ret;
373   }
374   catch (...)
375   {
376     INFOS("Caught unknown exception.");
377     return ret;
378   }
379
380   // Step 8: start a new container
381   // Check if a PaCO container
382   // PaCO++
383   if (std::string(local_params.parallelLib.in()) != "")
384   {
385     ret = StartPaCOPPContainer(params, resource_selected);
386     return ret;
387   }
388   // Other type of containers...
389   MESSAGE("[GiveContainer] Try to launch a new container on " << resource_selected);
390   std::string command;
391   // if a parallel container is launched in batch job, command is: "mpirun -np nbproc -machinefile nodesfile SALOME_MPIContainer"
392   if( getenv("LIBBATCH_NODEFILE") != NULL && params.isMPI )
393     command = BuildCommandToLaunchLocalContainer(params, machFile, container_exe);
394   // if a container is launched on localhost, command is "SALOME_Container" or "mpirun -np nbproc SALOME_MPIContainer"
395   else if(hostname == Kernel_Utils::GetHostname())
396     command = BuildCommandToLaunchLocalContainer(params, machFile, container_exe);
397   // if a container is launched in remote mode, command is "ssh resource_selected SALOME_Container" or "ssh resource_selected mpirun -np nbproc SALOME_MPIContainer"
398   else
399     command = BuildCommandToLaunchRemoteContainer(resource_selected, params, container_exe);
400
401   //redirect stdout and stderr in a file
402 #ifdef WNT
403   string logFilename=getenv("TEMP");
404   logFilename += "\\";
405 #else
406   string logFilename="/tmp";
407   char* val = getenv("SALOME_TMP_DIR");
408   if(val)
409   {
410     struct stat file_info;
411     stat(val, &file_info);
412     bool is_dir = S_ISDIR(file_info.st_mode);
413     if (is_dir)logFilename=val;
414     else std::cerr << "SALOME_TMP_DIR environment variable is not a directory use /tmp instead" << std::endl;
415   }
416   logFilename += "/";
417 #endif
418   logFilename += _NS->ContainerName(params)+"_"+ resource_selected +"_"+getenv( "USER" )+".log" ;
419   command += " > " + logFilename + " 2>&1";
420 #ifdef WNT
421   command = "%PYTHONBIN% -c \"import win32pm ; win32pm.spawnpid(r'" + command + "', '')\"";
422 #else
423   command += " &";
424 #endif
425
426   // launch container with a system call
427   int status=system(command.c_str());
428
429   if (status == -1){
430     MESSAGE("SALOME_ContainerManager::StartContainer rsh failed (system command status -1)");
431     RmTmpFile(_TmpFileName); // command file can be removed here
432     return Engines::Container::_nil();
433   }
434   else if (status == 217){
435     MESSAGE("SALOME_ContainerManager::StartContainer rsh failed (system command status 217)");
436     RmTmpFile(_TmpFileName); // command file can be removed here
437     return Engines::Container::_nil();
438   }
439   else
440   {
441     int count = TIME_OUT_TO_LAUNCH_CONT;
442     MESSAGE("[GiveContainer] waiting " << count << " second steps");
443     while (CORBA::is_nil(ret) && count)
444     {
445 #ifndef WIN32
446       sleep( 1 ) ;
447 #else
448       Sleep(1000);
449 #endif
450       count--;
451       MESSAGE("[GiveContainer] step " << count << " Waiting for container on " << resource_selected);
452       CORBA::Object_var obj = _NS->Resolve(containerNameInNS.c_str());
453       ret=Engines::Container::_narrow(obj);
454     }
455     if (CORBA::is_nil(ret))
456     {
457       INFOS("[GiveContainer] was not able to launch container " << containerNameInNS);
458     }
459     else
460     {
461       // Setting log file name
462       logFilename=":"+logFilename;
463       logFilename="@"+Kernel_Utils::GetHostname()+logFilename;
464       logFilename=getenv( "USER" )+logFilename;
465       ret->logfilename(logFilename.c_str());
466       RmTmpFile(_TmpFileName); // command file can be removed here
467     }
468   }
469   return ret;
470 }
471
472 //=============================================================================
473 //! Find a container given constraints (params) on a list of machines (possibleComputers)
474 /*!
475  *
476  */
477 //=============================================================================
478
479 Engines::Container_ptr
480 SALOME_ContainerManager::FindContainer(const Engines::ContainerParameters& params,
481                                        const Engines::ResourceList& possibleResources)
482 {
483   MESSAGE("[FindContainer] FindContainer on " << possibleResources.length() << " resources");
484   for(unsigned int i=0; i < possibleResources.length();i++)
485     {
486       Engines::Container_ptr cont = FindContainer(params, possibleResources[i].in());
487       if(!CORBA::is_nil(cont))
488         return cont;
489     }
490   MESSAGE("[FindContainer] no container found");
491   return Engines::Container::_nil();
492 }
493
494 //=============================================================================
495 //! Find a container given constraints (params) on a machine (theMachine)
496 /*!
497  *
498  */
499 //=============================================================================
500
501 Engines::Container_ptr
502 SALOME_ContainerManager::FindContainer(const Engines::ContainerParameters& params,
503                                        const std::string& resource)
504 {
505   Engines::ResourceDefinition_var resource_definition = _ResManager->GetResourceDefinition(resource.c_str());
506   std::string hostname(resource_definition->hostname.in());
507   std::string containerNameInNS(_NS->BuildContainerNameForNS(params, hostname.c_str()));
508   MESSAGE("[FindContainer] Try to find a container  " << containerNameInNS << " on resource " << resource);
509   CORBA::Object_var obj = _NS->Resolve(containerNameInNS.c_str());
510   try
511   {
512     if(obj->_non_existent())
513       return Engines::Container::_nil();
514     else
515       return Engines::Container::_narrow(obj);
516   }
517   catch(const CORBA::Exception& e)
518   {
519     return Engines::Container::_nil();
520   }
521 }
522
523 //=============================================================================
524 /*!
525  *  This is no longer valid (C++ container are also python containers)
526  */ 
527 //=============================================================================
528 bool isPythonContainer(const char* ContainerName)
529 {
530   bool ret = false;
531   int len = strlen(ContainerName);
532
533   if (len >= 2)
534     if (strcmp(ContainerName + len - 2, "Py") == 0)
535       ret = true;
536
537   return ret;
538 }
539
540 //=============================================================================
541 /*!
542  *  Builds the script to be launched
543  *
544  *  If SALOME Application not defined ($APPLI),
545  *  see BuildTempFileToLaunchRemoteContainer()
546  *
547  *  Else rely on distant configuration. Command is under the form (example):
548  *  ssh user@machine distantPath/runRemote.sh hostNS portNS WORKINGDIR workingdir \
549  *                   SALOME_Container containerName &"
550
551  *  - where user is ommited if not specified in CatalogResources,
552  *  - where distant path is always relative to user@machine $HOME, and
553  *    equal to $APPLI if not specified in CatalogResources,
554  *  - where hostNS is the hostname of CORBA naming server (set by scripts to
555  *    use to launch SALOME and servers in $APPLI: runAppli.sh, runRemote.sh)
556  *  - where portNS is the port used by CORBA naming server (set by scripts to
557  *    use to launch SALOME and servers in $APPLI: runAppli.sh, runRemote.sh)
558  *  - where workingdir is the requested working directory for the container.
559  *    If WORKINGDIR (and workingdir) is not present the working dir will be $HOME
560  */ 
561 //=============================================================================
562
563 string
564 SALOME_ContainerManager::BuildCommandToLaunchRemoteContainer
565 (const string& resource_name,
566  const Engines::ContainerParameters& params, const std::string& container_exe)
567 {
568           
569   string command;
570   if (!_isAppliSalomeDefined)
571     command = BuildTempFileToLaunchRemoteContainer(resource_name, params);
572   else
573   {
574     int nbproc;
575     Engines::ResourceDefinition_var resource_definition = _ResManager->GetResourceDefinition(resource_name.c_str());
576     std::string hostname(resource_definition->hostname.in());
577     const ParserResourcesType& resInfo = _ResManager->GetImpl()->GetResourcesDescr(resource_name);
578
579     if (params.isMPI)
580     {
581       if ((params.resource_params.nb_node <= 0) && (params.resource_params.nb_proc_per_node <= 0))
582         nbproc = 1;
583       else if (params.resource_params.nb_node == 0)
584         nbproc = params.resource_params.nb_proc_per_node;
585       else if (params.resource_params.nb_proc_per_node == 0)
586         nbproc = params.resource_params.nb_node;
587       else
588         nbproc = params.resource_params.nb_node * params.resource_params.nb_proc_per_node;
589     }
590
591     // "ssh -l user machine distantPath/runRemote.sh hostNS portNS WORKINGDIR workingdir \
592     //  SALOME_Container containerName &"
593     if (resInfo.Protocol == rsh)
594       command = "rsh ";
595     else if (resInfo.Protocol == ssh)
596       command = "ssh ";
597     else
598       throw SALOME_Exception("Unknown protocol");
599
600     if (resInfo.UserName != "")
601     {
602       command += "-l ";
603       command += resInfo.UserName;
604       command += " ";
605     }
606
607     command += resInfo.HostName;
608     command += " ";
609
610     if (resInfo.AppliPath != "")
611       command += resInfo.AppliPath; // path relative to user@machine $HOME
612     else
613     {
614       ASSERT(getenv("APPLI"));
615       command += getenv("APPLI"); // path relative to user@machine $HOME
616     }
617
618     command += "/runRemote.sh ";
619
620     ASSERT(getenv("NSHOST")); 
621     command += getenv("NSHOST"); // hostname of CORBA name server
622
623     command += " ";
624     ASSERT(getenv("NSPORT"));
625     command += getenv("NSPORT"); // port of CORBA name server
626
627     std::string wdir = params.workingdir.in();
628     if(wdir != "")
629     {
630       command += " WORKINGDIR ";
631       command += " '";
632       if(wdir == "$TEMPDIR")
633         wdir="\\$TEMPDIR";
634       command += wdir; // requested working directory
635       command += "'"; 
636     }
637
638     if(params.isMPI)
639     {
640       command += " mpirun -np ";
641       std::ostringstream o;
642       o << nbproc << " ";
643       command += o.str();
644 #ifdef WITHLAM
645       command += "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
646 #elif defined(WITHOPENMPI)
647       if( getenv("OMPI_URI_FILE") == NULL )
648         command += "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace";
649       else{
650         command += "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace -ompi-server file:";
651         command += getenv("OMPI_URI_FILE");
652       }
653 #endif        
654       command += " SALOME_MPIContainer ";
655     }
656     else
657       command += " " +container_exe+ " ";
658
659     command += _NS->ContainerName(params);
660     command += " -";
661     AddOmninamesParams(command);
662
663     MESSAGE("command =" << command);
664   }
665
666   return command;
667 }
668
669 //=============================================================================
670 /*!
671  *  builds the command to be launched.
672  */ 
673 //=============================================================================
674 string
675 SALOME_ContainerManager::BuildCommandToLaunchLocalContainer
676 (const Engines::ContainerParameters& params, const std::string& machinesFile, const std::string& container_exe)
677 {
678   _TmpFileName = BuildTemporaryFileName();
679   string command;
680   int nbproc = 0;
681
682   ostringstream o;
683
684   if (params.isMPI)
685     {
686       o << "mpirun -np ";
687
688       if ( (params.resource_params.nb_node <= 0) && (params.resource_params.nb_proc_per_node <= 0) )
689         nbproc = 1;
690       else if ( params.resource_params.nb_node == 0 )
691         nbproc = params.resource_params.nb_proc_per_node;
692       else if ( params.resource_params.nb_proc_per_node == 0 )
693         nbproc = params.resource_params.nb_node;
694       else
695         nbproc = params.resource_params.nb_node * params.resource_params.nb_proc_per_node;
696
697       o << nbproc << " ";
698
699       if( getenv("LIBBATCH_NODEFILE") != NULL )
700         o << "-machinefile " << machinesFile << " ";
701
702 #ifdef WITHLAM
703       o << "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
704 #elif defined(WITHOPENMPI)
705       if( getenv("OMPI_URI_FILE") == NULL )
706         o << "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace";
707       else
708         {
709           o << "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace -ompi-server file:";
710           o << getenv("OMPI_URI_FILE");
711         }
712 #endif
713
714       if (isPythonContainer(params.container_name))
715         o << " pyMPI SALOME_ContainerPy.py ";
716       else
717         o << " SALOME_MPIContainer ";
718     }
719
720   else
721     {
722       std::string wdir=params.workingdir.in();
723       if(wdir != "")
724         {
725           // a working directory is requested
726           if(wdir == "$TEMPDIR")
727             {
728               // a new temporary directory is requested
729               string dir = Kernel_Utils::GetTmpDir();
730 #ifdef WIN32
731               o << "cd /d " << dir << endl;
732 #else
733               o << "cd " << dir << ";";
734 #endif
735
736             }
737           else
738             {
739               // a permanent directory is requested use it or create it
740 #ifdef WIN32
741               o << "mkdir " + wdir << endl;
742               o << "cd /D " + wdir << endl;
743 #else
744               o << "mkdir -p " << wdir << " && cd " << wdir + ";";
745 #endif
746             }
747         }
748       if (isPythonContainer(params.container_name))
749         o << "SALOME_ContainerPy.py ";
750       else
751         o << container_exe + " ";
752
753     }
754
755   o << _NS->ContainerName(params);
756   o << " -";
757   AddOmninamesParams(o);
758
759   ofstream command_file( _TmpFileName.c_str() );
760   command_file << o.str();
761   command_file.close();
762
763 #ifndef WIN32
764   chmod(_TmpFileName.c_str(), 0x1ED);
765 #endif
766   command = _TmpFileName;
767
768   MESSAGE("Command is file ... " << command);
769   MESSAGE("Command is ... " << o.str());
770   return command;
771 }
772
773
774 //=============================================================================
775 /*!
776  *  removes the generated temporary file in case of a remote launch.
777  */ 
778 //=============================================================================
779
780 void SALOME_ContainerManager::RmTmpFile(std::string& tmpFileName)
781 {
782   int lenght = tmpFileName.size();
783   if ( lenght  > 0)
784     {
785 #ifdef WIN32
786       string command = "del /F ";
787 #else
788       string command = "rm ";      
789 #endif
790       if ( lenght > 4 )
791         command += tmpFileName.substr(0, lenght - 3 );
792       else
793         command += tmpFileName;
794       command += '*';
795       system(command.c_str());
796       //if dir is empty - remove it
797       string tmp_dir = Kernel_Utils::GetDirByPath( tmpFileName );
798       if ( Kernel_Utils::IsEmptyDir( tmp_dir ) )
799         {
800 #ifdef WIN32
801           command = "del /F " + tmp_dir;
802 #else
803           command = "rmdir " + tmp_dir;
804 #endif
805           system(command.c_str());
806         }
807     }
808 }
809
810 //=============================================================================
811 /*!
812  *   add to command all options relative to naming service.
813  */ 
814 //=============================================================================
815
816 void SALOME_ContainerManager::AddOmninamesParams(string& command) const
817 {
818   CORBA::String_var iorstr = _NS->getIORaddr();
819   command += "ORBInitRef NameService=";
820   command += iorstr;
821 }
822
823 //=============================================================================
824 /*!
825  *  add to command all options relative to naming service.
826  */ 
827 //=============================================================================
828
829 void SALOME_ContainerManager::AddOmninamesParams(ofstream& fileStream) const
830 {
831   CORBA::String_var iorstr = _NS->getIORaddr();
832   fileStream << "ORBInitRef NameService=";
833   fileStream << iorstr;
834 }
835
836 //=============================================================================
837 /*!
838  *  add to command all options relative to naming service.
839  */ 
840 //=============================================================================
841
842 void SALOME_ContainerManager::AddOmninamesParams(ostringstream& oss) const
843 {
844   CORBA::String_var iorstr = _NS->getIORaddr();
845   oss << "ORBInitRef NameService=";
846   oss << iorstr;
847 }
848
849 //=============================================================================
850 /*!
851  *  generate a file name in /tmp directory
852  */ 
853 //=============================================================================
854
855 string SALOME_ContainerManager::BuildTemporaryFileName() const
856 {
857   //build more complex file name to support multiple salome session
858   string aFileName = Kernel_Utils::GetTmpFileName();
859 #ifndef WIN32
860   aFileName += ".sh";
861 #else
862   aFileName += ".bat";
863 #endif
864   return aFileName;
865 }
866
867 //=============================================================================
868 /*!
869  *  Builds in a temporary file the script to be launched.
870  *  
871  *  Used if SALOME Application ($APPLI) is not defined.
872  *  The command is build with data from CatalogResources, in which every path
873  *  used on remote computer must be defined.
874  */ 
875 //=============================================================================
876
877 string
878 SALOME_ContainerManager::BuildTempFileToLaunchRemoteContainer
879 (const string& resource_name,
880  const Engines::ContainerParameters& params) throw(SALOME_Exception)
881 {
882   int status;
883
884   _TmpFileName = BuildTemporaryFileName();
885   ofstream tempOutputFile;
886   tempOutputFile.open(_TmpFileName.c_str(), ofstream::out );
887   const ParserResourcesType& resInfo = _ResManager->GetImpl()->GetResourcesDescr(resource_name);
888   tempOutputFile << "#! /bin/sh" << endl;
889
890   // --- set env vars
891
892   tempOutputFile << "export SALOME_trace=local" << endl; // mkr : 27.11.2006 : PAL13967 - Distributed supervision graphs - Problem with "SALOME_trace"
893   //tempOutputFile << "source " << resInfo.PreReqFilePath << endl;
894
895   // ! env vars
896
897   if (params.isMPI)
898     {
899       tempOutputFile << "mpirun -np ";
900       int nbproc;
901
902       if ( (params.resource_params.nb_node <= 0) && (params.resource_params.nb_proc_per_node <= 0) )
903         nbproc = 1;
904       else if ( params.resource_params.nb_node == 0 )
905         nbproc = params.resource_params.nb_proc_per_node;
906       else if ( params.resource_params.nb_proc_per_node == 0 )
907         nbproc = params.resource_params.nb_node;
908       else
909         nbproc = params.resource_params.nb_node * params.resource_params.nb_proc_per_node;
910
911       std::ostringstream o;
912
913       tempOutputFile << nbproc << " ";
914 #ifdef WITHLAM
915       tempOutputFile << "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
916 #elif defined(WITHOPENMPI)
917       if( getenv("OMPI_URI_FILE") == NULL )
918         tempOutputFile << "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace";
919       else{
920         tempOutputFile << "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace -ompi-server file:";
921         tempOutputFile << getenv("OMPI_URI_FILE");
922       }
923 #endif
924     }
925
926   tempOutputFile << getenv("KERNEL_ROOT_DIR") << "/bin/salome/";
927
928   if (params.isMPI)
929     {
930       if (isPythonContainer(params.container_name))
931         tempOutputFile << " pyMPI SALOME_ContainerPy.py ";
932       else
933         tempOutputFile << " SALOME_MPIContainer ";
934     }
935
936   else
937     {
938       if (isPythonContainer(params.container_name))
939         tempOutputFile << "SALOME_ContainerPy.py ";
940       else
941         tempOutputFile << "SALOME_Container ";
942     }
943
944   tempOutputFile << _NS->ContainerName(params) << " -";
945   AddOmninamesParams(tempOutputFile);
946   tempOutputFile << " &" << endl;
947   tempOutputFile.flush();
948   tempOutputFile.close();
949 #ifndef WIN32
950   chmod(_TmpFileName.c_str(), 0x1ED);
951 #endif
952
953   // --- Build command
954
955   string command;
956
957   if (resInfo.Protocol == rsh)
958     {
959       command = "rsh ";
960       string commandRcp = "rcp ";
961       commandRcp += _TmpFileName;
962       commandRcp += " ";
963       commandRcp += resInfo.HostName;
964       commandRcp += ":";
965       commandRcp += _TmpFileName;
966       status = system(commandRcp.c_str());
967     }
968
969   else if (resInfo.Protocol == ssh)
970     {
971       command = "ssh ";
972       string commandRcp = "scp ";
973       commandRcp += _TmpFileName;
974       commandRcp += " ";
975       commandRcp += resInfo.HostName;
976       commandRcp += ":";
977       commandRcp += _TmpFileName;
978       status = system(commandRcp.c_str());
979     }
980   else
981     throw SALOME_Exception("Unknown protocol");
982
983   if(status)
984     throw SALOME_Exception("Error of connection on remote host");    
985
986   command += resInfo.HostName;
987   _CommandForRemAccess = command;
988   command += " ";
989   command += _TmpFileName;
990
991   SCRUTE(command);
992
993   return command;
994
995 }
996
997 string SALOME_ContainerManager::GetMPIZeroNode(const string machine, const string machinesFile)
998 {
999   int status;
1000   string zeronode;
1001   string command;
1002   string tmpFile = BuildTemporaryFileName();
1003
1004   if( getenv("LIBBATCH_NODEFILE") == NULL )
1005     {
1006       if (_isAppliSalomeDefined)
1007         {
1008           const ParserResourcesType& resInfo = _ResManager->GetImpl()->GetResourcesDescr(machine);
1009
1010           if (resInfo.Protocol == rsh)
1011             command = "rsh ";
1012           else if (resInfo.Protocol == ssh)
1013             command = "ssh ";
1014           else
1015             throw SALOME_Exception("Unknown protocol");
1016
1017           if (resInfo.UserName != "")
1018             {
1019               command += "-l ";
1020               command += resInfo.UserName;
1021               command += " ";
1022             }
1023
1024           command += resInfo.HostName;
1025           command += " ";
1026
1027           if (resInfo.AppliPath != "")
1028             command += resInfo.AppliPath; // path relative to user@machine $HOME
1029           else
1030             {
1031               ASSERT(getenv("APPLI"));
1032               command += getenv("APPLI"); // path relative to user@machine $HOME
1033             }
1034
1035           command += "/runRemote.sh ";
1036
1037           ASSERT(getenv("NSHOST")); 
1038           command += getenv("NSHOST"); // hostname of CORBA name server
1039
1040           command += " ";
1041           ASSERT(getenv("NSPORT"));
1042           command += getenv("NSPORT"); // port of CORBA name server
1043
1044           command += " mpirun -np 1 hostname > " + tmpFile;
1045         }
1046       else
1047         command = "mpirun -np 1 hostname > " + tmpFile;
1048     }
1049   else
1050     command = "mpirun -np 1 -machinefile " + machinesFile + " hostname > " + tmpFile;
1051
1052   status = system(command.c_str());
1053   if( status == 0 ){
1054     ifstream fp(tmpFile.c_str(),ios::in);
1055     fp >> zeronode;
1056   }
1057
1058   RmTmpFile(tmpFile);
1059
1060   return zeronode;
1061 }
1062
1063 string SALOME_ContainerManager::machinesFile(const int nbproc)
1064 {
1065   string tmp;
1066   string nodesFile = getenv("LIBBATCH_NODEFILE");
1067   string machinesFile = Kernel_Utils::GetTmpFileName();
1068   ifstream fpi(nodesFile.c_str(),ios::in);
1069   ofstream fpo(machinesFile.c_str(),ios::out);
1070
1071   _numInstanceMutex.lock();
1072
1073   for(int i=0;i<_nbprocUsed;i++)
1074     fpi >> tmp;
1075
1076   for(int i=0;i<nbproc;i++)
1077     if( fpi >> tmp )
1078       fpo << tmp << endl;
1079     else
1080       throw SALOME_Exception("You ask more processes than batch session have allocated!");
1081
1082   _nbprocUsed += nbproc;
1083   fpi.close();
1084   fpo.close();
1085
1086   _numInstanceMutex.unlock();
1087
1088   return machinesFile;
1089
1090 }
1091
1092 bool 
1093 SALOME_ContainerManager::checkPaCOParameters(Engines::ContainerParameters & params, std::string resource_selected)
1094 {
1095   bool result = true;
1096  
1097   // Step 1 : check ContainerParameters
1098   // Check container_name, has to be defined
1099   if (std::string(params.container_name.in()) == "")
1100   {
1101     INFOS("[checkPaCOParameters] You must define a container_name to launch a PaCO++ container");
1102     result = false;
1103   }
1104   // Check parallelLib
1105   std::string parallelLib = params.parallelLib.in();
1106   if (parallelLib != "Mpi" and parallelLib != "Dummy")
1107   {
1108     INFOS("[checkPaCOParameters] parallelLib is not correctly defined");
1109     INFOS("[checkPaCOParameters] you can chosse between: Mpi and Dummy");
1110     INFOS("[checkPaCOParameters] you entered: " << parallelLib);
1111     result = false;
1112   }
1113   // Check nb_proc
1114   if (params.nb_proc <= 0)
1115   {
1116     INFOS("[checkPaCOParameters] You must define a nb_proc > 0");
1117     result = false;
1118   }
1119
1120   // Step 2 : check resource_selected
1121   Engines::ResourceDefinition_var resource_definition = _ResManager->GetResourceDefinition(resource_selected.c_str());
1122   std::string protocol = resource_definition->protocol.in();
1123   std::string username = resource_definition->username.in();
1124   std::string applipath = resource_definition->applipath.in();
1125
1126   if (protocol == "" or username == "" or applipath == "")
1127   {
1128     INFOS("[checkPaCOParameters] resource selected is not well defined");
1129     INFOS("[checkPaCOParameters] resource name: " << resource_definition->name.in());
1130     INFOS("[checkPaCOParameters] resource hostname: " << resource_definition->hostname.in());
1131     INFOS("[checkPaCOParameters] resource protocol: " << protocol);
1132     INFOS("[checkPaCOParameters] resource username: " << username);
1133     INFOS("[checkPaCOParameters] resource applipath: " << applipath);
1134     result = false;
1135   }
1136
1137   return result;
1138 }
1139 #ifdef WITH_PACO_PARALLEL
1140
1141 //=============================================================================
1142 /*! CORBA Method:
1143  *  Start a suitable PaCO++ Parallel Container in a list of machines.
1144  *  \param params           Container Parameters required for the container
1145  *  \return CORBA container reference.
1146  */
1147 //=============================================================================
1148 Engines::Container_ptr
1149 SALOME_ContainerManager::StartPaCOPPContainer(const Engines::ContainerParameters& params_const,
1150                                               std::string resource_selected)
1151 {
1152   CORBA::Object_var obj;
1153   PaCO::InterfaceManager_var container_proxy;
1154   Engines::Container_ptr ret = Engines::Container::_nil();
1155   Engines::ContainerParameters params(params_const);
1156   params.resource_params.name = CORBA::string_dup(resource_selected.c_str());
1157
1158   // Step 0 : Check parameters
1159   if (!checkPaCOParameters(params, resource_selected))
1160   {
1161     INFOS("[StartPaCOPPContainer] check parameters failed ! see logs...");
1162     return ret;
1163   }
1164
1165   // Step 1 : Starting a new parallel container !
1166   INFOS("[StartPaCOPPContainer] Starting a PaCO++ parallel container");
1167   INFOS("[StartPaCOPPContainer] on resource : " << resource_selected);
1168
1169   // Step 2 : Get a MachineFile for the parallel container
1170   std::string machine_file_name = _ResManager->getMachineFile(resource_selected, 
1171                                                               params.nb_proc,
1172                                                               params.parallelLib.in());
1173
1174   if (machine_file_name == "")
1175   {
1176     INFOS("[StartPaCOPPContainer] Machine file generation failed");
1177     return ret;
1178   }
1179
1180   // Step 3 : starting parallel container proxy
1181   std::string command_proxy("");
1182   std::string proxy_machine;
1183   try 
1184   {
1185     command_proxy = BuildCommandToLaunchPaCOProxyContainer(params, machine_file_name, proxy_machine);
1186   }
1187   catch(const SALOME_Exception & ex)
1188   {
1189     INFOS("[StartPaCOPPContainer] Exception in BuildCommandToLaunchPaCOContainer");
1190     INFOS(ex.what());
1191     return ret;
1192   }
1193   obj = LaunchPaCOProxyContainer(command_proxy, params, proxy_machine);
1194   if (CORBA::is_nil(obj))
1195   {
1196     INFOS("[StartPaCOPPContainer] LaunchPaCOContainer for proxy returns NIL !");
1197     return ret;
1198   }
1199   container_proxy = PaCO::InterfaceManager::_narrow(obj);
1200   MESSAGE("[StartPaCOPPContainer] PaCO container proxy is launched");
1201
1202   // Step 4 : starting parallel container nodes
1203   std::string command_nodes("");
1204   SALOME_ContainerManager::actual_launch_machine_t nodes_machines;
1205   try 
1206   {
1207     command_nodes = BuildCommandToLaunchPaCONodeContainer(params, machine_file_name, nodes_machines, proxy_machine);
1208   }
1209   catch(const SALOME_Exception & ex)
1210   {
1211     INFOS("[StarPaCOPPContainer] Exception in BuildCommandToLaunchPaCONodeContainer");
1212     INFOS(ex.what());
1213     return ret;
1214   }
1215
1216   std::string container_generic_node_name = std::string(params.container_name.in()) + std::string("Node");
1217   bool result = LaunchPaCONodeContainer(command_nodes, params, container_generic_node_name, nodes_machines);
1218   if (!result)
1219   {
1220     INFOS("[StarPaCOPPContainer] LaunchPaCONodeContainer failed !");
1221     // Il faut tuer le proxy
1222     try 
1223     {
1224       Engines::Container_var proxy = Engines::Container::_narrow(container_proxy);
1225       proxy->Shutdown();
1226     }
1227     catch (...)
1228     {
1229       INFOS("[StarPaCOPPContainer] Exception catched from proxy Shutdown...");
1230     }
1231     return ret;
1232   }
1233
1234   // Step 4 : connecting nodes and the proxy to actually create a parallel container
1235   for (int i = 0; i < params.nb_proc; i++) 
1236   {
1237     std::ostringstream tmp;
1238     tmp << i;
1239     std::string proc_number = tmp.str();
1240     std::string container_node_name = container_generic_node_name + proc_number;
1241
1242     std::string theNodeMachine(nodes_machines[i]);
1243     std::string containerNameInNS = _NS->BuildContainerNameForNS(container_node_name.c_str(), theNodeMachine.c_str());
1244     obj = _NS->Resolve(containerNameInNS.c_str());
1245     if (CORBA::is_nil(obj)) 
1246     {
1247       INFOS("[StarPaCOPPContainer] CONNECTION FAILED From Naming Service !");
1248       INFOS("[StarPaCOPPContainer] Container name is " << containerNameInNS);
1249       return ret;
1250     }
1251     try
1252     {
1253       MESSAGE("[StarPaCOPPContainer] Deploying node : " << container_node_name);
1254       PaCO::InterfaceParallel_var node = PaCO::InterfaceParallel::_narrow(obj);
1255       node->deploy();
1256       MESSAGE("[StarPaCOPPContainer] node " << container_node_name << " is deployed");
1257     }
1258     catch(CORBA::SystemException& e)
1259     {
1260       INFOS("[StarPaCOPPContainer] Exception in deploying node : " << containerNameInNS);
1261       INFOS("CORBA::SystemException : " << e);
1262       return ret;
1263     }
1264     catch(CORBA::Exception& e)
1265     {
1266       INFOS("[StarPaCOPPContainer] Exception in deploying node : " << containerNameInNS);
1267       INFOS("CORBA::Exception" << e);
1268       return ret;
1269     }
1270     catch(...)
1271     {
1272       INFOS("[StarPaCOPPContainer] Exception in deploying node : " << containerNameInNS);
1273       INFOS("Unknown exception !");
1274       return ret;
1275     }
1276   }
1277
1278   // Step 5 : starting parallel container
1279   try 
1280   {
1281     MESSAGE ("[StarPaCOPPContainer] Starting parallel object");
1282     container_proxy->start();
1283     MESSAGE ("[StarPaCOPPContainer] Parallel object is started");
1284     ret = Engines::Container::_narrow(container_proxy);
1285   }
1286   catch(CORBA::SystemException& e)
1287   {
1288     INFOS("Caught CORBA::SystemException. : " << e);
1289   }
1290   catch(PortableServer::POA::ServantAlreadyActive&)
1291   {
1292     INFOS("Caught CORBA::ServantAlreadyActiveException");
1293   }
1294   catch(CORBA::Exception&)
1295   {
1296     INFOS("Caught CORBA::Exception.");
1297   }
1298   catch(std::exception& exc)
1299   {
1300     INFOS("Caught std::exception - "<<exc.what()); 
1301   }
1302   catch(...)
1303   {
1304     INFOS("Caught unknown exception.");
1305   }
1306   return ret;
1307 }
1308
1309 std::string 
1310 SALOME_ContainerManager::BuildCommandToLaunchPaCOProxyContainer(const Engines::ContainerParameters& params,
1311                                                                 std::string machine_file_name,
1312                                                                 std::string & proxy_hostname)
1313 {
1314   // In the proxy case, we always launch a Dummy Proxy
1315   std::string exe_name = "SALOME_ParallelContainerProxyDummy";
1316   std::string container_name = params.container_name.in();
1317
1318   // Convert nb_proc in string
1319   std::ostringstream tmp_string;
1320   tmp_string << params.nb_proc;
1321   std::string nb_proc_str = tmp_string.str();
1322
1323   // Get resource definition
1324   Engines::ResourceDefinition_var resource_definition = 
1325     _ResManager->GetResourceDefinition(params.resource_params.name);
1326
1327   // Choose hostname
1328   std::string hostname;
1329   std::ifstream machine_file(machine_file_name.c_str());
1330   std::getline(machine_file, hostname, ' ');
1331   size_t found = hostname.find('\n');
1332   if (found!=string::npos)
1333     hostname.erase(found, 1); // Remove \n
1334   proxy_hostname = hostname;
1335   MESSAGE("[BuildCommandToLaunchPaCOProxyContainer] machine file name extracted is " << hostname);
1336
1337   // Remote execution
1338   bool remote_execution = false;
1339   if (hostname != std::string(Kernel_Utils::GetHostname()))
1340   {
1341     MESSAGE("[BuildCommandToLaunchPaCOProxyContainer] remote machine case detected !");
1342     remote_execution = true;
1343   }
1344   
1345   // Log environnement
1346   std::string log_type("");
1347   char * get_val = getenv("PARALLEL_LOG");
1348   if (get_val)
1349     log_type = get_val;
1350
1351   // Generating the command
1352   std::string command_begin("");
1353   std::string command_end("");
1354   std::ostringstream command;
1355
1356   LogConfiguration(log_type, "proxy", container_name, hostname, command_begin, command_end);
1357   command << command_begin;
1358
1359   // Adding connection command
1360   // We can only have a remote execution with
1361   // a SALOME application
1362   if (remote_execution)
1363   {
1364     ASSERT(getenv("NSHOST")); 
1365     ASSERT(getenv("NSPORT"));
1366
1367     command << resource_definition->protocol.in();
1368     command << " -l ";
1369     command << resource_definition->username.in();
1370     command << " " << hostname;
1371     command << " " << resource_definition->applipath.in();
1372     command << "/runRemote.sh ";
1373     command << getenv("NSHOST") << " "; // hostname of CORBA name server
1374     command << getenv("NSPORT") << " "; // port of CORBA name server
1375   }
1376
1377   command << exe_name;
1378   command << " " << container_name;
1379   command << " Dummy";
1380   command << " " << hostname;
1381   command << " " << nb_proc_str;
1382   command << " -";
1383   AddOmninamesParams(command);
1384
1385   // Final command
1386   command << command_end;
1387   MESSAGE("[BuildCommandToLaunchPaCOProxyContainer] Command is: " << command.str());
1388
1389   return command.str();
1390 }
1391
1392 std::string 
1393 SALOME_ContainerManager::BuildCommandToLaunchPaCONodeContainer(const Engines::ContainerParameters& params,
1394                                                                const std::string & machine_file_name,
1395                                                                SALOME_ContainerManager::actual_launch_machine_t & vect_machine,
1396                                                                const std::string & proxy_hostname)
1397 {
1398   // Name of exe
1399   std::string exe_name = "SALOME_ParallelContainerNode";
1400   exe_name += params.parallelLib.in();
1401   std::string container_name = params.container_name.in();
1402
1403   // Convert nb_proc in string
1404   std::ostringstream nb_proc_stream;
1405   nb_proc_stream << params.nb_proc;
1406
1407   // Get resource definition
1408   Engines::ResourceDefinition_var resource_definition = 
1409     _ResManager->GetResourceDefinition(params.resource_params.name);
1410   
1411   // Log environnement
1412   std::string log_type("");
1413   char * get_val = getenv("PARALLEL_LOG");
1414   if (get_val)
1415     log_type = get_val;
1416
1417   // Now the command is different according to paralleLib
1418   std::ostringstream command_nodes;
1419   std::ifstream machine_file(machine_file_name.c_str());
1420   if (std::string(params.parallelLib.in()) == "Dummy")
1421   {
1422     for (int i= 0; i < params.nb_proc; i++)
1423     {
1424       // Choose hostname
1425       std::string hostname;
1426       std::getline(machine_file, hostname);
1427       MESSAGE("[BuildCommandToLaunchPaCONodeContainer] machine file name extracted is " << hostname);
1428
1429       // Remote execution
1430       bool remote_execution = false;
1431       if (hostname != std::string(Kernel_Utils::GetHostname()))
1432       {
1433         MESSAGE("[BuildCommandToLaunchPaCONodeContainer] remote machine case detected !");
1434         remote_execution = true;
1435       }
1436
1437       // For each node we have a new command
1438       // Generating the command
1439       std::ostringstream command_node_stream;
1440       std::string command_node_begin("");
1441       std::string command_node_end("");
1442       std::ostringstream node_number;
1443       node_number << i;
1444       std::string container_node_name = container_name + node_number.str();
1445       LogConfiguration(log_type, "node", container_node_name, hostname, command_node_begin, command_node_end);
1446
1447       // Adding connection command
1448       // We can only have a remote execution with
1449       // a SALOME application
1450       if (remote_execution)
1451       {
1452         ASSERT(getenv("NSHOST")); 
1453         ASSERT(getenv("NSPORT"));
1454
1455         command_node_stream << resource_definition->protocol.in();
1456         command_node_stream << " -l ";
1457         command_node_stream << resource_definition->username.in();
1458         command_node_stream << " " << hostname;
1459         command_node_stream << " " << resource_definition->applipath.in();
1460         command_node_stream << "/runRemote.sh ";
1461         command_node_stream << getenv("NSHOST") << " "; // hostname of CORBA name server
1462         command_node_stream << getenv("NSPORT") << " "; // port of CORBA name server
1463       }
1464
1465       command_node_stream << exe_name;
1466       command_node_stream << " " << container_name;
1467       command_node_stream << " " << params.parallelLib.in();
1468       command_node_stream << " " << proxy_hostname;
1469       command_node_stream << " " << node_number.str();
1470       command_node_stream << " -";
1471       AddOmninamesParams(command_node_stream);
1472
1473       command_nodes << command_node_begin << command_node_stream.str() << command_node_end;
1474       vect_machine.push_back(hostname);
1475     }
1476   }
1477
1478   else if (std::string(params.parallelLib.in()) == "Mpi")
1479   {
1480     // Choose hostname
1481     std::string hostname;
1482     std::getline(machine_file, hostname, ' ');
1483     MESSAGE("[BuildCommandToLaunchPaCONodeContainer] machine file name extracted is " << hostname);
1484
1485     // Remote execution
1486     bool remote_execution = false;
1487     if (hostname != std::string(Kernel_Utils::GetHostname()))
1488     {
1489       MESSAGE("[BuildCommandToLaunchPaCONodeContainer] remote machine case detected !");
1490       remote_execution = true;
1491     }
1492
1493     // In case of Mpi and Remote, we copy machine_file in the applipath
1494     // scp mpi_machine_file user@machine:Path
1495     std::ostringstream command_remote_stream;
1496     std::string::size_type last = machine_file_name.find_last_of("/");
1497     if (last == std::string::npos)
1498       last = -1;
1499
1500     std::string protocol = resource_definition->protocol.in();
1501     if (protocol == "rsh")
1502       command_remote_stream << "rcp ";
1503     else 
1504       command_remote_stream << "scp ";
1505     command_remote_stream << machine_file_name << " ";
1506     command_remote_stream << resource_definition->username.in() << "@";
1507     command_remote_stream << hostname << ":" << resource_definition->applipath.in();
1508     command_remote_stream <<  "/" << machine_file_name.substr(last+1);
1509
1510     int status = system(command_remote_stream.str().c_str());
1511     if (status == -1)
1512     {
1513       INFOS("copy of the MPI machine file failed ! - sorry !");
1514       return "";
1515     }
1516
1517     // Generating the command
1518     std::string command_begin("");
1519     std::string command_end("");
1520
1521     LogConfiguration(log_type, "nodes", container_name, hostname, command_begin, command_end);
1522     command_nodes << command_begin;
1523
1524     // Adding connection command
1525     // We can only have a remote execution with
1526     // a SALOME application
1527     if (remote_execution)
1528     {
1529       ASSERT(getenv("NSHOST")); 
1530       ASSERT(getenv("NSPORT"));
1531
1532       command_nodes << resource_definition->protocol.in();
1533       command_nodes << " -l ";
1534       command_nodes << resource_definition->username.in();
1535       command_nodes << " " << hostname;
1536       command_nodes << " " << resource_definition->applipath.in();
1537       command_nodes << "/runRemote.sh ";
1538       command_nodes << getenv("NSHOST") << " "; // hostname of CORBA name server
1539       command_nodes << getenv("NSPORT") << " "; // port of CORBA name server
1540     }
1541
1542     if (std::string(resource_definition->mpiImpl.in()) == "lam")
1543     {
1544       command_nodes << "mpiexec -ssi boot ";
1545       command_nodes << "-machinefile "  << machine_file_name << " "; 
1546       command_nodes <<  "-n " << params.nb_proc;
1547     }
1548     else
1549     {
1550       command_nodes << "mpirun -np " << params.nb_proc;
1551     }
1552     command_nodes << " " << exe_name;
1553     command_nodes << " " << container_name;
1554     command_nodes << " " << params.parallelLib.in();
1555     command_nodes << " " << proxy_hostname;
1556     command_nodes << " -";
1557     AddOmninamesParams(command_nodes);
1558
1559     // We don't put hostname, because nodes are registered in the resource of the proxy
1560     for (int i= 0; i < params.nb_proc; i++)
1561       vect_machine.push_back(proxy_hostname); 
1562
1563     command_nodes << command_end;
1564   }
1565   return command_nodes.str();
1566 }
1567
1568 void
1569 SALOME_ContainerManager::LogConfiguration(const std::string & log_type,
1570                                           const std::string & exe_type,
1571                                           const std::string & container_name,
1572                                           const std::string & hostname,
1573                                           std::string & begin, 
1574                                           std::string & end)
1575 {
1576   if(log_type == "xterm")
1577   {
1578     begin = "xterm -e \"export LD_LIBRARY_PATH=$LD_LIBRARY_PATH; export PATH=$PATH;";
1579     end   = "\"&";
1580   }
1581   else if(log_type == "xterm_debug")
1582   {
1583     begin = "xterm -e \"export LD_LIBRARY_PATH=$LD_LIBRARY_PATH; export PATH=$PATH;";
1584     end   = "; cat \" &";
1585   }
1586   else
1587   {
1588     // default into a file...
1589     std::string logFilename = "/tmp/" + container_name + "_" + hostname + "_" + exe_type + "_";
1590     logFilename += std::string(getenv("USER")) + ".log";
1591     end = " > " + logFilename + " 2>&1 & ";
1592   }
1593 }
1594
1595 CORBA::Object_ptr 
1596 SALOME_ContainerManager::LaunchPaCOProxyContainer(const std::string& command, 
1597                                                   const Engines::ContainerParameters& params,
1598                                                   const std::string & hostname)
1599 {
1600   PaCO::InterfaceManager_ptr container_proxy = PaCO::InterfaceManager::_nil();
1601
1602   MESSAGE("[LaunchPaCOProxyContainer] Launch command");
1603   int status = system(command.c_str());
1604   if (status == -1) {
1605     INFOS("[LaunchPaCOProxyContainer] failed : system command status -1");
1606     return container_proxy;
1607   }
1608   else if (status == 217) {
1609     INFOS("[LaunchPaCOProxyContainer] failed : system command status 217");
1610     return container_proxy;
1611   }
1612
1613   int count = TIME_OUT_TO_LAUNCH_CONT;
1614   CORBA::Object_var obj = CORBA::Object::_nil();
1615   std::string containerNameInNS = _NS->BuildContainerNameForNS(params.container_name.in(), 
1616                                                                hostname.c_str());
1617   MESSAGE("[LaunchParallelContainer]  Waiting for Parallel Container proxy : " << containerNameInNS);
1618
1619   while (CORBA::is_nil(obj) && count) 
1620   {
1621     sleep(1);
1622     count--;
1623     obj = _NS->Resolve(containerNameInNS.c_str());
1624   }
1625
1626   try 
1627   {
1628     container_proxy = PaCO::InterfaceManager::_narrow(obj);
1629   }
1630   catch(CORBA::SystemException& e)
1631   {
1632     INFOS("[StarPaCOPPContainer] Exception in _narrow after LaunchParallelContainer for proxy !");
1633     INFOS("CORBA::SystemException : " << e);
1634     return container_proxy;
1635   }
1636   catch(CORBA::Exception& e)
1637   {
1638     INFOS("[StarPaCOPPContainer] Exception in _narrow after LaunchParallelContainer for proxy !");
1639     INFOS("CORBA::Exception" << e);
1640     return container_proxy;
1641   }
1642   catch(...)
1643   {
1644     INFOS("[StarPaCOPPContainer] Exception in _narrow after LaunchParallelContainer for proxy !");
1645     INFOS("Unknown exception !");
1646     return container_proxy;
1647   }
1648   if (CORBA::is_nil(container_proxy))
1649   {
1650     INFOS("[StarPaCOPPContainer] PaCO::InterfaceManager::_narrow returns NIL !");
1651     return container_proxy;
1652   }
1653   return obj._retn();
1654 }
1655
1656 //=============================================================================
1657 /*! This method launches the parallel container.
1658  *  It will may be placed on the ressources manager.
1659  *
1660  * \param command to launch
1661  * \param container's parameters
1662  * \param name of the container
1663  *
1664  * \return CORBA container reference
1665  */
1666 //=============================================================================
1667 bool
1668 SALOME_ContainerManager::LaunchPaCONodeContainer(const std::string& command, 
1669                                                  const Engines::ContainerParameters& params,
1670                                                  const std::string& name,
1671                                                  SALOME_ContainerManager::actual_launch_machine_t & vect_machine)
1672 {
1673   INFOS("[LaunchPaCONodeContainer] Launch command");
1674   int status = system(command.c_str());
1675   if (status == -1) {
1676     INFOS("[LaunchPaCONodeContainer] failed : system command status -1");
1677     return false;
1678   }
1679   else if (status == 217) {
1680     INFOS("[LaunchPaCONodeContainer] failed : system command status 217");
1681     return false;
1682   }
1683
1684   INFOS("[LaunchPaCONodeContainer] Waiting for the nodes of the parallel container");
1685   // We are waiting all the nodes
1686   for (int i = 0; i < params.nb_proc; i++) 
1687   {
1688     CORBA::Object_var obj = CORBA::Object::_nil();
1689     std::string theMachine(vect_machine[i]);
1690     // Name of the node
1691     std::ostringstream tmp;
1692     tmp << i;
1693     std::string proc_number = tmp.str();
1694     std::string container_node_name = name + proc_number;
1695     std::string containerNameInNS = _NS->BuildContainerNameForNS((char*) container_node_name.c_str(), theMachine.c_str());
1696     INFOS("[LaunchPaCONodeContainer]  Waiting for Parallel Container node " << containerNameInNS << " on " << theMachine);
1697     int count = TIME_OUT_TO_LAUNCH_CONT;
1698     while (CORBA::is_nil(obj) && count) {
1699       sleep(1) ;
1700       count-- ;
1701       obj = _NS->Resolve(containerNameInNS.c_str());
1702     }
1703     if (CORBA::is_nil(obj))
1704     {
1705       INFOS("[LaunchPaCONodeContainer] Launch of node failed (or not found) !");
1706       return false;
1707     }
1708   }
1709   return true;
1710 }
1711
1712 #else
1713
1714 Engines::Container_ptr
1715 SALOME_ContainerManager::StartPaCOPPContainer(const Engines::ContainerParameters& params,
1716                                               std::string resource_selected)
1717 {
1718   Engines::Container_ptr ret = Engines::Container::_nil();
1719   INFOS("[StarPaCOPPContainer] is disabled !");
1720   INFOS("[StarPaCOPPContainer] recompile SALOME Kernel to enable PaCO++ parallel extension");
1721   return ret;
1722 }
1723
1724 std::string 
1725 SALOME_ContainerManager::BuildCommandToLaunchPaCOProxyContainer(const Engines::ContainerParameters& params,
1726                                                                 std::string machine_file_name,
1727                                                                 std::string & proxy_hostname)
1728 {
1729   return "";
1730 }
1731
1732 std::string 
1733 SALOME_ContainerManager::BuildCommandToLaunchPaCONodeContainer(const Engines::ContainerParameters& params,
1734                                                                const std::string & machine_file_name,
1735                                                                SALOME_ContainerManager::actual_launch_machine_t & vect_machine, 
1736                                                                const std::string & proxy_hostname) 
1737 {
1738   return "";
1739 }
1740 void 
1741 SALOME_ContainerManager::LogConfiguration(const std::string & log_type,
1742                                           const std::string & exe_type,
1743                                           const std::string & container_name,
1744                                           const std::string & hostname,
1745                                           std::string & begin, 
1746                                           std::string & end)
1747 {
1748 }
1749
1750 CORBA::Object_ptr 
1751 SALOME_ContainerManager::LaunchPaCOProxyContainer(const std::string& command, 
1752                                                   const Engines::ContainerParameters& params,
1753                                                   const std::string& hostname)
1754 {
1755   CORBA::Object_ptr ret = CORBA::Object::_nil();
1756   return ret;
1757 }
1758
1759 bool 
1760 SALOME_ContainerManager::LaunchPaCONodeContainer(const std::string& command, 
1761                         const Engines::ContainerParameters& params,
1762                         const std::string& name,
1763                         SALOME_ContainerManager::actual_launch_machine_t & vect_machine)
1764 {
1765   return false;
1766 }
1767 #endif
1768