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