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