]> SALOME platform Git repositories - modules/kernel.git/blob - src/Container/SALOME_ContainerManager.cxx
Salome HOME
Merge from V5_1_4_BR (5_1_4rc2) 09/06/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   std::ostringstream tmp;
424   tmp << "_" << getpid();
425   logFilename += tmp.str();
426   logFilename += ".log" ;
427   command += " > " + logFilename + " 2>&1";
428 #ifdef WNT
429   command = "%PYTHONBIN% -c \"import win32pm ; win32pm.spawnpid(r'" + command + "', '')\"";
430 #else
431   command += " &";
432 #endif
433
434   // launch container with a system call
435   int status=system(command.c_str());
436
437   if (status == -1){
438     MESSAGE("SALOME_ContainerManager::StartContainer rsh failed (system command status -1)");
439     RmTmpFile(_TmpFileName); // command file can be removed here
440     return Engines::Container::_nil();
441   }
442   else if (status == 217){
443     MESSAGE("SALOME_ContainerManager::StartContainer rsh failed (system command status 217)");
444     RmTmpFile(_TmpFileName); // command file can be removed here
445     return Engines::Container::_nil();
446   }
447   else
448   {
449     int count = TIME_OUT_TO_LAUNCH_CONT;
450     MESSAGE("[GiveContainer] waiting " << count << " second steps");
451     while (CORBA::is_nil(ret) && count)
452     {
453 #ifndef WIN32
454       sleep( 1 ) ;
455 #else
456       Sleep(1000);
457 #endif
458       count--;
459       MESSAGE("[GiveContainer] step " << count << " Waiting for container on " << resource_selected);
460       CORBA::Object_var obj = _NS->Resolve(containerNameInNS.c_str());
461       ret=Engines::Container::_narrow(obj);
462     }
463     if (CORBA::is_nil(ret))
464     {
465       INFOS("[GiveContainer] was not able to launch container " << containerNameInNS);
466     }
467     else
468     {
469       // Setting log file name
470       logFilename=":"+logFilename;
471       logFilename="@"+Kernel_Utils::GetHostname()+logFilename;
472       logFilename=getenv( "USER" )+logFilename;
473       ret->logfilename(logFilename.c_str());
474       RmTmpFile(_TmpFileName); // command file can be removed here
475     }
476   }
477   return ret;
478 }
479
480 //=============================================================================
481 //! Find a container given constraints (params) on a list of machines (possibleComputers)
482 /*!
483  *
484  */
485 //=============================================================================
486
487 Engines::Container_ptr
488 SALOME_ContainerManager::FindContainer(const Engines::ContainerParameters& params,
489                                        const Engines::ResourceList& possibleResources)
490 {
491   MESSAGE("[FindContainer] FindContainer on " << possibleResources.length() << " resources");
492   for(unsigned int i=0; i < possibleResources.length();i++)
493     {
494       Engines::Container_ptr cont = FindContainer(params, possibleResources[i].in());
495       if(!CORBA::is_nil(cont))
496         return cont;
497     }
498   MESSAGE("[FindContainer] no container found");
499   return Engines::Container::_nil();
500 }
501
502 //=============================================================================
503 //! Find a container given constraints (params) on a machine (theMachine)
504 /*!
505  *
506  */
507 //=============================================================================
508
509 Engines::Container_ptr
510 SALOME_ContainerManager::FindContainer(const Engines::ContainerParameters& params,
511                                        const std::string& resource)
512 {
513   Engines::ResourceDefinition_var resource_definition = _ResManager->GetResourceDefinition(resource.c_str());
514   std::string hostname(resource_definition->hostname.in());
515   std::string containerNameInNS(_NS->BuildContainerNameForNS(params, hostname.c_str()));
516   MESSAGE("[FindContainer] Try to find a container  " << containerNameInNS << " on resource " << resource);
517   CORBA::Object_var obj = _NS->Resolve(containerNameInNS.c_str());
518   try
519   {
520     if(obj->_non_existent())
521       return Engines::Container::_nil();
522     else
523       return Engines::Container::_narrow(obj);
524   }
525   catch(const CORBA::Exception& e)
526   {
527     return Engines::Container::_nil();
528   }
529 }
530
531
532 bool isPythonContainer(const char* ContainerName);
533
534 //=============================================================================
535 /*!
536  *  This is no longer valid (C++ container are also python containers)
537  */ 
538 //=============================================================================
539 bool isPythonContainer(const char* ContainerName)
540 {
541   bool ret = false;
542   int len = strlen(ContainerName);
543
544   if (len >= 2)
545     if (strcmp(ContainerName + len - 2, "Py") == 0)
546       ret = true;
547
548   return ret;
549 }
550
551 //=============================================================================
552 /*!
553  *  Builds the script to be launched
554  *
555  *  If SALOME Application not defined ($APPLI),
556  *  see BuildTempFileToLaunchRemoteContainer()
557  *
558  *  Else rely on distant configuration. Command is under the form (example):
559  *  ssh user@machine distantPath/runRemote.sh hostNS portNS WORKINGDIR workingdir \
560  *                   SALOME_Container containerName &"
561
562  *  - where user is ommited if not specified in CatalogResources,
563  *  - where distant path is always relative to user@machine $HOME, and
564  *    equal to $APPLI if not specified in CatalogResources,
565  *  - where hostNS is the hostname of CORBA naming server (set by scripts to
566  *    use to launch SALOME and servers in $APPLI: runAppli.sh, runRemote.sh)
567  *  - where portNS is the port used by CORBA naming server (set by scripts to
568  *    use to launch SALOME and servers in $APPLI: runAppli.sh, runRemote.sh)
569  *  - where workingdir is the requested working directory for the container.
570  *    If WORKINGDIR (and workingdir) is not present the working dir will be $HOME
571  */ 
572 //=============================================================================
573
574 std::string
575 SALOME_ContainerManager::BuildCommandToLaunchRemoteContainer
576 (const std::string& resource_name,
577  const Engines::ContainerParameters& params, const std::string& container_exe)
578 {
579           
580   std::string command;
581   if (!_isAppliSalomeDefined)
582     command = BuildTempFileToLaunchRemoteContainer(resource_name, params);
583   else
584   {
585     int nbproc;
586     Engines::ResourceDefinition_var resource_definition = _ResManager->GetResourceDefinition(resource_name.c_str());
587     std::string hostname(resource_definition->hostname.in());
588     const ParserResourcesType& resInfo = _ResManager->GetImpl()->GetResourcesDescr(resource_name);
589
590     if (params.isMPI)
591     {
592       if ((params.resource_params.nb_node <= 0) && (params.resource_params.nb_proc_per_node <= 0))
593         nbproc = 1;
594       else if (params.resource_params.nb_node == 0)
595         nbproc = params.resource_params.nb_proc_per_node;
596       else if (params.resource_params.nb_proc_per_node == 0)
597         nbproc = params.resource_params.nb_node;
598       else
599         nbproc = params.resource_params.nb_node * params.resource_params.nb_proc_per_node;
600     }
601
602     // "ssh -l user machine distantPath/runRemote.sh hostNS portNS WORKINGDIR workingdir \
603     //  SALOME_Container containerName &"
604     if (resInfo.Protocol == rsh)
605       command = "rsh ";
606     else if (resInfo.Protocol == ssh)
607       command = "ssh ";
608     else
609       throw SALOME_Exception("Unknown protocol");
610
611     if (resInfo.UserName != "")
612     {
613       command += "-l ";
614       command += resInfo.UserName;
615       command += " ";
616     }
617
618     command += resInfo.HostName;
619     command += " ";
620
621     if (resInfo.AppliPath != "")
622       command += resInfo.AppliPath; // path relative to user@machine $HOME
623     else
624     {
625       ASSERT(getenv("APPLI"));
626       command += getenv("APPLI"); // path relative to user@machine $HOME
627     }
628
629     command += "/runRemote.sh ";
630
631     ASSERT(getenv("NSHOST")); 
632     command += getenv("NSHOST"); // hostname of CORBA name server
633
634     command += " ";
635     ASSERT(getenv("NSPORT"));
636     command += getenv("NSPORT"); // port of CORBA name server
637
638     std::string wdir = params.workingdir.in();
639     if(wdir != "")
640     {
641       command += " WORKINGDIR ";
642       command += " '";
643       if(wdir == "$TEMPDIR")
644         wdir="\\$TEMPDIR";
645       command += wdir; // requested working directory
646       command += "'"; 
647     }
648
649     if(params.isMPI)
650     {
651       command += " mpirun -np ";
652       std::ostringstream o;
653       o << nbproc << " ";
654       command += o.str();
655 #ifdef WITHLAM
656       command += "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
657 #elif defined(WITHOPENMPI)
658       if( getenv("OMPI_URI_FILE") == NULL )
659         command += "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace";
660       else{
661         command += "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace -ompi-server file:";
662         command += getenv("OMPI_URI_FILE");
663       }
664 #endif        
665       command += " SALOME_MPIContainer ";
666     }
667     else
668       command += " " +container_exe+ " ";
669
670     command += _NS->ContainerName(params);
671     command += " -";
672     AddOmninamesParams(command);
673
674     MESSAGE("command =" << command);
675   }
676
677   return command;
678 }
679
680 //=============================================================================
681 /*!
682  *  builds the command to be launched.
683  */ 
684 //=============================================================================
685 std::string
686 SALOME_ContainerManager::BuildCommandToLaunchLocalContainer
687 (const Engines::ContainerParameters& params, const std::string& machinesFile, const std::string& container_exe)
688 {
689   _TmpFileName = BuildTemporaryFileName();
690   std::string command;
691   int nbproc = 0;
692
693   std::ostringstream o;
694
695   if (params.isMPI)
696     {
697       o << "mpirun -np ";
698
699       if ( (params.resource_params.nb_node <= 0) && (params.resource_params.nb_proc_per_node <= 0) )
700         nbproc = 1;
701       else if ( params.resource_params.nb_node == 0 )
702         nbproc = params.resource_params.nb_proc_per_node;
703       else if ( params.resource_params.nb_proc_per_node == 0 )
704         nbproc = params.resource_params.nb_node;
705       else
706         nbproc = params.resource_params.nb_node * params.resource_params.nb_proc_per_node;
707
708       o << nbproc << " ";
709
710       if( getenv("LIBBATCH_NODEFILE") != NULL )
711         o << "-machinefile " << machinesFile << " ";
712
713 #ifdef WITHLAM
714       o << "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
715 #elif defined(WITHOPENMPI)
716       if( getenv("OMPI_URI_FILE") == NULL )
717         o << "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace";
718       else
719         {
720           o << "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace -ompi-server file:";
721           o << getenv("OMPI_URI_FILE");
722         }
723 #endif
724
725       if (isPythonContainer(params.container_name))
726         o << " pyMPI SALOME_ContainerPy.py ";
727       else
728         o << " SALOME_MPIContainer ";
729     }
730
731   else
732     {
733       std::string wdir=params.workingdir.in();
734       if(wdir != "")
735         {
736           // a working directory is requested
737           if(wdir == "$TEMPDIR")
738             {
739               // a new temporary directory is requested
740               std::string dir = Kernel_Utils::GetTmpDir();
741 #ifdef WIN32
742               o << "cd /d " << dir << std::endl;
743 #else
744               o << "cd " << dir << ";";
745 #endif
746
747             }
748           else
749             {
750               // a permanent directory is requested use it or create it
751 #ifdef WIN32
752               o << "mkdir " + wdir << std::endl;
753               o << "cd /D " + wdir << std::endl;
754 #else
755               o << "mkdir -p " << wdir << " && cd " << wdir + ";";
756 #endif
757             }
758         }
759       if (isPythonContainer(params.container_name))
760         o << "SALOME_ContainerPy.py ";
761       else
762         o << container_exe + " ";
763
764     }
765
766   o << _NS->ContainerName(params);
767   o << " -";
768   AddOmninamesParams(o);
769
770   std::ofstream command_file( _TmpFileName.c_str() );
771   command_file << o.str();
772   command_file.close();
773
774 #ifndef WIN32
775   chmod(_TmpFileName.c_str(), 0x1ED);
776 #endif
777   command = _TmpFileName;
778
779   MESSAGE("Command is file ... " << command);
780   MESSAGE("Command is ... " << o.str());
781   return command;
782 }
783
784
785 //=============================================================================
786 /*!
787  *  removes the generated temporary file in case of a remote launch.
788  */ 
789 //=============================================================================
790
791 void SALOME_ContainerManager::RmTmpFile(std::string& tmpFileName)
792 {
793   int lenght = tmpFileName.size();
794   if ( lenght  > 0)
795     {
796 #ifdef WIN32
797       std::string command = "del /F ";
798 #else
799       std::string command = "rm ";      
800 #endif
801       if ( lenght > 4 )
802         command += tmpFileName.substr(0, lenght - 3 );
803       else
804         command += tmpFileName;
805       command += '*';
806       system(command.c_str());
807       //if dir is empty - remove it
808       std::string tmp_dir = Kernel_Utils::GetDirByPath( tmpFileName );
809       if ( Kernel_Utils::IsEmptyDir( tmp_dir ) )
810         {
811 #ifdef WIN32
812           command = "del /F " + tmp_dir;
813 #else
814           command = "rmdir " + tmp_dir;
815 #endif
816           system(command.c_str());
817         }
818     }
819 }
820
821 //=============================================================================
822 /*!
823  *   add to command all options relative to naming service.
824  */ 
825 //=============================================================================
826
827 void SALOME_ContainerManager::AddOmninamesParams(std::string& command) const
828 {
829   CORBA::String_var iorstr = _NS->getIORaddr();
830   command += "ORBInitRef NameService=";
831   command += iorstr;
832 }
833
834 //=============================================================================
835 /*!
836  *  add to command all options relative to naming service.
837  */ 
838 //=============================================================================
839
840 void SALOME_ContainerManager::AddOmninamesParams(std::ofstream& fileStream) const
841 {
842   CORBA::String_var iorstr = _NS->getIORaddr();
843   fileStream << "ORBInitRef NameService=";
844   fileStream << iorstr;
845 }
846
847 //=============================================================================
848 /*!
849  *  add to command all options relative to naming service.
850  */ 
851 //=============================================================================
852
853 void SALOME_ContainerManager::AddOmninamesParams(std::ostringstream& oss) const
854 {
855   CORBA::String_var iorstr = _NS->getIORaddr();
856   oss << "ORBInitRef NameService=";
857   oss << iorstr;
858 }
859
860 //=============================================================================
861 /*!
862  *  generate a file name in /tmp directory
863  */ 
864 //=============================================================================
865
866 std::string SALOME_ContainerManager::BuildTemporaryFileName() const
867 {
868   //build more complex file name to support multiple salome session
869   std::string aFileName = Kernel_Utils::GetTmpFileName();
870 #ifndef WIN32
871   aFileName += ".sh";
872 #else
873   aFileName += ".bat";
874 #endif
875   return aFileName;
876 }
877
878 //=============================================================================
879 /*!
880  *  Builds in a temporary file the script to be launched.
881  *  
882  *  Used if SALOME Application ($APPLI) is not defined.
883  *  The command is build with data from CatalogResources, in which every path
884  *  used on remote computer must be defined.
885  */ 
886 //=============================================================================
887
888 std::string
889 SALOME_ContainerManager::BuildTempFileToLaunchRemoteContainer
890 (const std::string& resource_name,
891  const Engines::ContainerParameters& params) throw(SALOME_Exception)
892 {
893   int status;
894
895   _TmpFileName = BuildTemporaryFileName();
896   std::ofstream tempOutputFile;
897   tempOutputFile.open(_TmpFileName.c_str(), std::ofstream::out );
898   const ParserResourcesType& resInfo = _ResManager->GetImpl()->GetResourcesDescr(resource_name);
899   tempOutputFile << "#! /bin/sh" << std::endl;
900
901   // --- set env vars
902
903   tempOutputFile << "export SALOME_trace=local" << std::endl; // mkr : 27.11.2006 : PAL13967 - Distributed supervision graphs - Problem with "SALOME_trace"
904   //tempOutputFile << "source " << resInfo.PreReqFilePath << endl;
905
906   // ! env vars
907
908   if (params.isMPI)
909     {
910       tempOutputFile << "mpirun -np ";
911       int nbproc;
912
913       if ( (params.resource_params.nb_node <= 0) && (params.resource_params.nb_proc_per_node <= 0) )
914         nbproc = 1;
915       else if ( params.resource_params.nb_node == 0 )
916         nbproc = params.resource_params.nb_proc_per_node;
917       else if ( params.resource_params.nb_proc_per_node == 0 )
918         nbproc = params.resource_params.nb_node;
919       else
920         nbproc = params.resource_params.nb_node * params.resource_params.nb_proc_per_node;
921
922       std::ostringstream o;
923
924       tempOutputFile << nbproc << " ";
925 #ifdef WITHLAM
926       tempOutputFile << "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
927 #elif defined(WITHOPENMPI)
928       if( getenv("OMPI_URI_FILE") == NULL )
929         tempOutputFile << "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace";
930       else{
931         tempOutputFile << "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace -ompi-server file:";
932         tempOutputFile << getenv("OMPI_URI_FILE");
933       }
934 #endif
935     }
936
937   tempOutputFile << getenv("KERNEL_ROOT_DIR") << "/bin/salome/";
938
939   if (params.isMPI)
940     {
941       if (isPythonContainer(params.container_name))
942         tempOutputFile << " pyMPI SALOME_ContainerPy.py ";
943       else
944         tempOutputFile << " SALOME_MPIContainer ";
945     }
946
947   else
948     {
949       if (isPythonContainer(params.container_name))
950         tempOutputFile << "SALOME_ContainerPy.py ";
951       else
952         tempOutputFile << "SALOME_Container ";
953     }
954
955   tempOutputFile << _NS->ContainerName(params) << " -";
956   AddOmninamesParams(tempOutputFile);
957   tempOutputFile << " &" << std::endl;
958   tempOutputFile.flush();
959   tempOutputFile.close();
960 #ifndef WIN32
961   chmod(_TmpFileName.c_str(), 0x1ED);
962 #endif
963
964   // --- Build command
965
966   std::string command;
967
968   if (resInfo.Protocol == rsh)
969     {
970       command = "rsh ";
971       std::string commandRcp = "rcp ";
972       commandRcp += _TmpFileName;
973       commandRcp += " ";
974       commandRcp += resInfo.HostName;
975       commandRcp += ":";
976       commandRcp += _TmpFileName;
977       status = system(commandRcp.c_str());
978     }
979
980   else if (resInfo.Protocol == ssh)
981     {
982       command = "ssh ";
983       std::string commandRcp = "scp ";
984       commandRcp += _TmpFileName;
985       commandRcp += " ";
986       commandRcp += resInfo.HostName;
987       commandRcp += ":";
988       commandRcp += _TmpFileName;
989       status = system(commandRcp.c_str());
990     }
991   else
992     throw SALOME_Exception("Unknown protocol");
993
994   if(status)
995     throw SALOME_Exception("Error of connection on remote host");    
996
997   command += resInfo.HostName;
998   _CommandForRemAccess = command;
999   command += " ";
1000   command += _TmpFileName;
1001
1002   SCRUTE(command);
1003
1004   return command;
1005
1006 }
1007
1008 std::string SALOME_ContainerManager::GetMPIZeroNode(const std::string machine, const std::string machinesFile)
1009 {
1010   int status;
1011   std::string zeronode;
1012   std::string command;
1013   std::string tmpFile = BuildTemporaryFileName();
1014
1015   if( getenv("LIBBATCH_NODEFILE") == NULL )
1016     {
1017       if (_isAppliSalomeDefined)
1018         {
1019           const ParserResourcesType& resInfo = _ResManager->GetImpl()->GetResourcesDescr(machine);
1020
1021           if (resInfo.Protocol == rsh)
1022             command = "rsh ";
1023           else if (resInfo.Protocol == ssh)
1024             command = "ssh ";
1025           else
1026             throw SALOME_Exception("Unknown protocol");
1027
1028           if (resInfo.UserName != "")
1029             {
1030               command += "-l ";
1031               command += resInfo.UserName;
1032               command += " ";
1033             }
1034
1035           command += resInfo.HostName;
1036           command += " ";
1037
1038           if (resInfo.AppliPath != "")
1039             command += resInfo.AppliPath; // path relative to user@machine $HOME
1040           else
1041             {
1042               ASSERT(getenv("APPLI"));
1043               command += getenv("APPLI"); // path relative to user@machine $HOME
1044             }
1045
1046           command += "/runRemote.sh ";
1047
1048           ASSERT(getenv("NSHOST")); 
1049           command += getenv("NSHOST"); // hostname of CORBA name server
1050
1051           command += " ";
1052           ASSERT(getenv("NSPORT"));
1053           command += getenv("NSPORT"); // port of CORBA name server
1054
1055           command += " mpirun -np 1 hostname > " + tmpFile;
1056         }
1057       else
1058         command = "mpirun -np 1 hostname > " + tmpFile;
1059     }
1060   else
1061     command = "mpirun -np 1 -machinefile " + machinesFile + " hostname > " + tmpFile;
1062
1063   status = system(command.c_str());
1064   if( status == 0 ){
1065     std::ifstream fp(tmpFile.c_str(),std::ios::in);
1066     fp >> zeronode;
1067   }
1068
1069   RmTmpFile(tmpFile);
1070
1071   return zeronode;
1072 }
1073
1074 std::string SALOME_ContainerManager::machinesFile(const int nbproc)
1075 {
1076   std::string tmp;
1077   std::string nodesFile = getenv("LIBBATCH_NODEFILE");
1078   std::string machinesFile = Kernel_Utils::GetTmpFileName();
1079   std::ifstream fpi(nodesFile.c_str(),std::ios::in);
1080   std::ofstream fpo(machinesFile.c_str(),std::ios::out);
1081
1082   _numInstanceMutex.lock();
1083
1084   for(int i=0;i<_nbprocUsed;i++)
1085     fpi >> tmp;
1086
1087   for(int i=0;i<nbproc;i++)
1088     if( fpi >> tmp )
1089       fpo << tmp << std::endl;
1090     else
1091       throw SALOME_Exception("You ask more processes than batch session have allocated!");
1092
1093   _nbprocUsed += nbproc;
1094   fpi.close();
1095   fpo.close();
1096
1097   _numInstanceMutex.unlock();
1098
1099   return machinesFile;
1100
1101 }
1102
1103 bool 
1104 SALOME_ContainerManager::checkPaCOParameters(Engines::ContainerParameters & params, std::string resource_selected)
1105 {
1106   bool result = true;
1107  
1108   // Step 1 : check ContainerParameters
1109   // Check container_name, has to be defined
1110   if (std::string(params.container_name.in()) == "")
1111   {
1112     INFOS("[checkPaCOParameters] You must define a container_name to launch a PaCO++ container");
1113     result = false;
1114   }
1115   // Check parallelLib
1116   std::string parallelLib = params.parallelLib.in();
1117   if (parallelLib != "Mpi" && parallelLib != "Dummy")
1118   {
1119     INFOS("[checkPaCOParameters] parallelLib is not correctly defined");
1120     INFOS("[checkPaCOParameters] you can chosse between: Mpi and Dummy");
1121     INFOS("[checkPaCOParameters] you entered: " << parallelLib);
1122     result = false;
1123   }
1124   // Check nb_proc
1125   if (params.nb_proc <= 0)
1126   {
1127     INFOS("[checkPaCOParameters] You must define a nb_proc > 0");
1128     result = false;
1129   }
1130
1131   // Step 2 : check resource_selected
1132   Engines::ResourceDefinition_var resource_definition = _ResManager->GetResourceDefinition(resource_selected.c_str());
1133   std::string protocol = resource_definition->protocol.in();
1134   std::string username = resource_definition->username.in();
1135   std::string applipath = resource_definition->applipath.in();
1136
1137   if (protocol == "" || username == "" || applipath == "")
1138   {
1139     INFOS("[checkPaCOParameters] resource selected is not well defined");
1140     INFOS("[checkPaCOParameters] resource name: " << resource_definition->name.in());
1141     INFOS("[checkPaCOParameters] resource hostname: " << resource_definition->hostname.in());
1142     INFOS("[checkPaCOParameters] resource protocol: " << protocol);
1143     INFOS("[checkPaCOParameters] resource username: " << username);
1144     INFOS("[checkPaCOParameters] resource applipath: " << applipath);
1145     result = false;
1146   }
1147
1148   return result;
1149 }
1150 #ifdef WITH_PACO_PARALLEL
1151
1152 //=============================================================================
1153 /*! CORBA Method:
1154  *  Start a suitable PaCO++ Parallel Container in a list of machines.
1155  *  \param params           Container Parameters required for the container
1156  *  \return CORBA container reference.
1157  */
1158 //=============================================================================
1159 Engines::Container_ptr
1160 SALOME_ContainerManager::StartPaCOPPContainer(const Engines::ContainerParameters& params_const,
1161                                               std::string resource_selected)
1162 {
1163   CORBA::Object_var obj;
1164   PaCO::InterfaceManager_var container_proxy;
1165   Engines::Container_ptr ret = Engines::Container::_nil();
1166   Engines::ContainerParameters params(params_const);
1167   params.resource_params.name = CORBA::string_dup(resource_selected.c_str());
1168
1169   // Step 0 : Check parameters
1170   if (!checkPaCOParameters(params, resource_selected))
1171   {
1172     INFOS("[StartPaCOPPContainer] check parameters failed ! see logs...");
1173     return ret;
1174   }
1175
1176   // Step 1 : Starting a new parallel container !
1177   INFOS("[StartPaCOPPContainer] Starting a PaCO++ parallel container");
1178   INFOS("[StartPaCOPPContainer] on resource : " << resource_selected);
1179
1180   // Step 2 : Get a MachineFile for the parallel container
1181   std::string machine_file_name = _ResManager->getMachineFile(resource_selected, 
1182                                                               params.nb_proc,
1183                                                               params.parallelLib.in());
1184
1185   if (machine_file_name == "")
1186   {
1187     INFOS("[StartPaCOPPContainer] Machine file generation failed");
1188     return ret;
1189   }
1190
1191   // Step 3 : starting parallel container proxy
1192   std::string command_proxy("");
1193   std::string proxy_machine;
1194   try 
1195   {
1196     command_proxy = BuildCommandToLaunchPaCOProxyContainer(params, machine_file_name, proxy_machine);
1197   }
1198   catch(const SALOME_Exception & ex)
1199   {
1200     INFOS("[StartPaCOPPContainer] Exception in BuildCommandToLaunchPaCOContainer");
1201     INFOS(ex.what());
1202     return ret;
1203   }
1204   obj = LaunchPaCOProxyContainer(command_proxy, params, proxy_machine);
1205   if (CORBA::is_nil(obj))
1206   {
1207     INFOS("[StartPaCOPPContainer] LaunchPaCOContainer for proxy returns NIL !");
1208     return ret;
1209   }
1210   container_proxy = PaCO::InterfaceManager::_narrow(obj);
1211   MESSAGE("[StartPaCOPPContainer] PaCO container proxy is launched");
1212
1213   // Step 4 : starting parallel container nodes
1214   std::string command_nodes("");
1215   SALOME_ContainerManager::actual_launch_machine_t nodes_machines;
1216   try 
1217   {
1218     command_nodes = BuildCommandToLaunchPaCONodeContainer(params, machine_file_name, nodes_machines, proxy_machine);
1219   }
1220   catch(const SALOME_Exception & ex)
1221   {
1222     INFOS("[StarPaCOPPContainer] Exception in BuildCommandToLaunchPaCONodeContainer");
1223     INFOS(ex.what());
1224     return ret;
1225   }
1226
1227   std::string container_generic_node_name = std::string(params.container_name.in()) + std::string("Node");
1228   bool result = LaunchPaCONodeContainer(command_nodes, params, container_generic_node_name, nodes_machines);
1229   if (!result)
1230   {
1231     INFOS("[StarPaCOPPContainer] LaunchPaCONodeContainer failed !");
1232     // Il faut tuer le proxy
1233     try 
1234     {
1235       Engines::Container_var proxy = Engines::Container::_narrow(container_proxy);
1236       proxy->Shutdown();
1237     }
1238     catch (...)
1239     {
1240       INFOS("[StarPaCOPPContainer] Exception catched from proxy Shutdown...");
1241     }
1242     return ret;
1243   }
1244
1245   // Step 4 : connecting nodes and the proxy to actually create a parallel container
1246   for (int i = 0; i < params.nb_proc; i++) 
1247   {
1248     std::ostringstream tmp;
1249     tmp << i;
1250     std::string proc_number = tmp.str();
1251     std::string container_node_name = container_generic_node_name + proc_number;
1252
1253     std::string theNodeMachine(nodes_machines[i]);
1254     std::string containerNameInNS = _NS->BuildContainerNameForNS(container_node_name.c_str(), theNodeMachine.c_str());
1255     obj = _NS->Resolve(containerNameInNS.c_str());
1256     if (CORBA::is_nil(obj)) 
1257     {
1258       INFOS("[StarPaCOPPContainer] CONNECTION FAILED From Naming Service !");
1259       INFOS("[StarPaCOPPContainer] Container name is " << containerNameInNS);
1260       return ret;
1261     }
1262     try
1263     {
1264       MESSAGE("[StarPaCOPPContainer] Deploying node : " << container_node_name);
1265       PaCO::InterfaceParallel_var node = PaCO::InterfaceParallel::_narrow(obj);
1266       node->deploy();
1267       MESSAGE("[StarPaCOPPContainer] node " << container_node_name << " is deployed");
1268     }
1269     catch(CORBA::SystemException& e)
1270     {
1271       INFOS("[StarPaCOPPContainer] Exception in deploying node : " << containerNameInNS);
1272       INFOS("CORBA::SystemException : " << e);
1273       return ret;
1274     }
1275     catch(CORBA::Exception& e)
1276     {
1277       INFOS("[StarPaCOPPContainer] Exception in deploying node : " << containerNameInNS);
1278       INFOS("CORBA::Exception" << e);
1279       return ret;
1280     }
1281     catch(...)
1282     {
1283       INFOS("[StarPaCOPPContainer] Exception in deploying node : " << containerNameInNS);
1284       INFOS("Unknown exception !");
1285       return ret;
1286     }
1287   }
1288
1289   // Step 5 : starting parallel container
1290   try 
1291   {
1292     MESSAGE ("[StarPaCOPPContainer] Starting parallel object");
1293     container_proxy->start();
1294     MESSAGE ("[StarPaCOPPContainer] Parallel object is started");
1295     ret = Engines::Container::_narrow(container_proxy);
1296   }
1297   catch(CORBA::SystemException& e)
1298   {
1299     INFOS("Caught CORBA::SystemException. : " << e);
1300   }
1301   catch(PortableServer::POA::ServantAlreadyActive&)
1302   {
1303     INFOS("Caught CORBA::ServantAlreadyActiveException");
1304   }
1305   catch(CORBA::Exception&)
1306   {
1307     INFOS("Caught CORBA::Exception.");
1308   }
1309   catch(std::exception& exc)
1310   {
1311     INFOS("Caught std::exception - "<<exc.what()); 
1312   }
1313   catch(...)
1314   {
1315     INFOS("Caught unknown exception.");
1316   }
1317   return ret;
1318 }
1319
1320 std::string 
1321 SALOME_ContainerManager::BuildCommandToLaunchPaCOProxyContainer(const Engines::ContainerParameters& params,
1322                                                                 std::string machine_file_name,
1323                                                                 std::string & proxy_hostname)
1324 {
1325   // In the proxy case, we always launch a Dummy Proxy
1326   std::string exe_name = "SALOME_ParallelContainerProxyDummy";
1327   std::string container_name = params.container_name.in();
1328
1329   // Convert nb_proc in string
1330   std::ostringstream tmp_string;
1331   tmp_string << params.nb_proc;
1332   std::string nb_proc_str = tmp_string.str();
1333
1334   // Get resource definition
1335   Engines::ResourceDefinition_var resource_definition = 
1336     _ResManager->GetResourceDefinition(params.resource_params.name);
1337
1338   // Choose hostname
1339   std::string hostname;
1340   std::ifstream machine_file(machine_file_name.c_str());
1341   std::getline(machine_file, hostname, ' ');
1342   size_t found = hostname.find('\n');
1343   if (found!=std::string::npos)
1344     hostname.erase(found, 1); // Remove \n
1345   proxy_hostname = hostname;
1346   MESSAGE("[BuildCommandToLaunchPaCOProxyContainer] machine file name extracted is " << hostname);
1347
1348   // Remote execution
1349   bool remote_execution = false;
1350   if (hostname != std::string(Kernel_Utils::GetHostname()))
1351   {
1352     MESSAGE("[BuildCommandToLaunchPaCOProxyContainer] remote machine case detected !");
1353     remote_execution = true;
1354   }
1355   
1356   // Log environnement
1357   std::string log_type("");
1358   char * get_val = getenv("PARALLEL_LOG");
1359   if (get_val)
1360     log_type = get_val;
1361
1362   // Generating the command
1363   std::string command_begin("");
1364   std::string command_end("");
1365   std::ostringstream command;
1366
1367   LogConfiguration(log_type, "proxy", container_name, hostname, command_begin, command_end);
1368   command << command_begin;
1369
1370   // Adding connection command
1371   // We can only have a remote execution with
1372   // a SALOME application
1373   if (remote_execution)
1374   {
1375     ASSERT(getenv("NSHOST")); 
1376     ASSERT(getenv("NSPORT"));
1377
1378     command << resource_definition->protocol.in();
1379     command << " -l ";
1380     command << resource_definition->username.in();
1381     command << " " << hostname;
1382     command << " " << resource_definition->applipath.in();
1383     command << "/runRemote.sh ";
1384     command << getenv("NSHOST") << " "; // hostname of CORBA name server
1385     command << getenv("NSPORT") << " "; // port of CORBA name server
1386   }
1387
1388   command << exe_name;
1389   command << " " << container_name;
1390   command << " Dummy";
1391   command << " " << hostname;
1392   command << " " << nb_proc_str;
1393   command << " -";
1394   AddOmninamesParams(command);
1395
1396   // Final command
1397   command << command_end;
1398   MESSAGE("[BuildCommandToLaunchPaCOProxyContainer] Command is: " << command.str());
1399
1400   return command.str();
1401 }
1402
1403 std::string 
1404 SALOME_ContainerManager::BuildCommandToLaunchPaCONodeContainer(const Engines::ContainerParameters& params,
1405                                                                const std::string & machine_file_name,
1406                                                                SALOME_ContainerManager::actual_launch_machine_t & vect_machine,
1407                                                                const std::string & proxy_hostname)
1408 {
1409   // Name of exe
1410   std::string exe_name = "SALOME_ParallelContainerNode";
1411   exe_name += params.parallelLib.in();
1412   std::string container_name = params.container_name.in();
1413
1414   // Convert nb_proc in string
1415   std::ostringstream nb_proc_stream;
1416   nb_proc_stream << params.nb_proc;
1417
1418   // Get resource definition
1419   Engines::ResourceDefinition_var resource_definition = 
1420     _ResManager->GetResourceDefinition(params.resource_params.name);
1421   
1422   // Log environnement
1423   std::string log_type("");
1424   char * get_val = getenv("PARALLEL_LOG");
1425   if (get_val)
1426     log_type = get_val;
1427
1428   // Now the command is different according to paralleLib
1429   std::ostringstream command_nodes;
1430   std::ifstream machine_file(machine_file_name.c_str());
1431   if (std::string(params.parallelLib.in()) == "Dummy")
1432   {
1433     for (int i= 0; i < params.nb_proc; i++)
1434     {
1435       // Choose hostname
1436       std::string hostname;
1437       std::getline(machine_file, hostname);
1438       MESSAGE("[BuildCommandToLaunchPaCONodeContainer] machine file name extracted is " << hostname);
1439
1440       // Remote execution
1441       bool remote_execution = false;
1442       if (hostname != std::string(Kernel_Utils::GetHostname()))
1443       {
1444         MESSAGE("[BuildCommandToLaunchPaCONodeContainer] remote machine case detected !");
1445         remote_execution = true;
1446       }
1447
1448       // For each node we have a new command
1449       // Generating the command
1450       std::ostringstream command_node_stream;
1451       std::string command_node_begin("");
1452       std::string command_node_end("");
1453       std::ostringstream node_number;
1454       node_number << i;
1455       std::string container_node_name = container_name + node_number.str();
1456       LogConfiguration(log_type, "node", container_node_name, hostname, command_node_begin, command_node_end);
1457
1458       // Adding connection command
1459       // We can only have a remote execution with
1460       // a SALOME application
1461       if (remote_execution)
1462       {
1463         ASSERT(getenv("NSHOST")); 
1464         ASSERT(getenv("NSPORT"));
1465
1466         command_node_stream << resource_definition->protocol.in();
1467         command_node_stream << " -l ";
1468         command_node_stream << resource_definition->username.in();
1469         command_node_stream << " " << hostname;
1470         command_node_stream << " " << resource_definition->applipath.in();
1471         command_node_stream << "/runRemote.sh ";
1472         command_node_stream << getenv("NSHOST") << " "; // hostname of CORBA name server
1473         command_node_stream << getenv("NSPORT") << " "; // port of CORBA name server
1474       }
1475
1476       command_node_stream << exe_name;
1477       command_node_stream << " " << container_name;
1478       command_node_stream << " " << params.parallelLib.in();
1479       command_node_stream << " " << proxy_hostname;
1480       command_node_stream << " " << node_number.str();
1481       command_node_stream << " -";
1482       AddOmninamesParams(command_node_stream);
1483
1484       command_nodes << command_node_begin << command_node_stream.str() << command_node_end;
1485       vect_machine.push_back(hostname);
1486     }
1487   }
1488
1489   else if (std::string(params.parallelLib.in()) == "Mpi")
1490   {
1491     // Choose hostname
1492     std::string hostname;
1493     std::getline(machine_file, hostname, ' ');
1494     MESSAGE("[BuildCommandToLaunchPaCONodeContainer] machine file name extracted is " << hostname);
1495
1496     // Remote execution
1497     bool remote_execution = false;
1498     if (hostname != std::string(Kernel_Utils::GetHostname()))
1499     {
1500       MESSAGE("[BuildCommandToLaunchPaCONodeContainer] remote machine case detected !");
1501       remote_execution = true;
1502     }
1503
1504     // In case of Mpi and Remote, we copy machine_file in the applipath
1505     // scp mpi_machine_file user@machine:Path
1506     std::ostringstream command_remote_stream;
1507     std::string::size_type last = machine_file_name.find_last_of("/");
1508     if (last == std::string::npos)
1509       last = -1;
1510
1511     std::string protocol = resource_definition->protocol.in();
1512     if (protocol == "rsh")
1513       command_remote_stream << "rcp ";
1514     else 
1515       command_remote_stream << "scp ";
1516     command_remote_stream << machine_file_name << " ";
1517     command_remote_stream << resource_definition->username.in() << "@";
1518     command_remote_stream << hostname << ":" << resource_definition->applipath.in();
1519     command_remote_stream <<  "/" << machine_file_name.substr(last+1);
1520
1521     int status = system(command_remote_stream.str().c_str());
1522     if (status == -1)
1523     {
1524       INFOS("copy of the MPI machine file failed ! - sorry !");
1525       return "";
1526     }
1527
1528     // Generating the command
1529     std::string command_begin("");
1530     std::string command_end("");
1531
1532     LogConfiguration(log_type, "nodes", container_name, hostname, command_begin, command_end);
1533     command_nodes << command_begin;
1534
1535     // Adding connection command
1536     // We can only have a remote execution with
1537     // a SALOME application
1538     if (remote_execution)
1539     {
1540       ASSERT(getenv("NSHOST")); 
1541       ASSERT(getenv("NSPORT"));
1542
1543       command_nodes << resource_definition->protocol.in();
1544       command_nodes << " -l ";
1545       command_nodes << resource_definition->username.in();
1546       command_nodes << " " << hostname;
1547       command_nodes << " " << resource_definition->applipath.in();
1548       command_nodes << "/runRemote.sh ";
1549       command_nodes << getenv("NSHOST") << " "; // hostname of CORBA name server
1550       command_nodes << getenv("NSPORT") << " "; // port of CORBA name server
1551     }
1552
1553     if (std::string(resource_definition->mpiImpl.in()) == "lam")
1554     {
1555       command_nodes << "mpiexec -ssi boot ";
1556       command_nodes << "-machinefile "  << machine_file_name << " "; 
1557       command_nodes <<  "-n " << params.nb_proc;
1558     }
1559     else
1560     {
1561       command_nodes << "mpirun -np " << params.nb_proc;
1562     }
1563     command_nodes << " " << exe_name;
1564     command_nodes << " " << container_name;
1565     command_nodes << " " << params.parallelLib.in();
1566     command_nodes << " " << proxy_hostname;
1567     command_nodes << " -";
1568     AddOmninamesParams(command_nodes);
1569
1570     // We don't put hostname, because nodes are registered in the resource of the proxy
1571     for (int i= 0; i < params.nb_proc; i++)
1572       vect_machine.push_back(proxy_hostname); 
1573
1574     command_nodes << command_end;
1575   }
1576   return command_nodes.str();
1577 }
1578
1579 void
1580 SALOME_ContainerManager::LogConfiguration(const std::string & log_type,
1581                                           const std::string & exe_type,
1582                                           const std::string & container_name,
1583                                           const std::string & hostname,
1584                                           std::string & begin, 
1585                                           std::string & end)
1586 {
1587   if(log_type == "xterm")
1588   {
1589     begin = "xterm -e \"export LD_LIBRARY_PATH=$LD_LIBRARY_PATH; export PATH=$PATH;";
1590     end   = "\"&";
1591   }
1592   else if(log_type == "xterm_debug")
1593   {
1594     begin = "xterm -e \"export LD_LIBRARY_PATH=$LD_LIBRARY_PATH; export PATH=$PATH;";
1595     end   = "; cat \" &";
1596   }
1597   else
1598   {
1599     // default into a file...
1600     std::string logFilename = "/tmp/" + container_name + "_" + hostname + "_" + exe_type + "_";
1601     logFilename += std::string(getenv("USER")) + ".log";
1602     end = " > " + logFilename + " 2>&1 & ";
1603   }
1604 }
1605
1606 CORBA::Object_ptr 
1607 SALOME_ContainerManager::LaunchPaCOProxyContainer(const std::string& command, 
1608                                                   const Engines::ContainerParameters& params,
1609                                                   const std::string & hostname)
1610 {
1611   PaCO::InterfaceManager_ptr container_proxy = PaCO::InterfaceManager::_nil();
1612
1613   MESSAGE("[LaunchPaCOProxyContainer] Launch command");
1614   int status = system(command.c_str());
1615   if (status == -1) {
1616     INFOS("[LaunchPaCOProxyContainer] failed : system command status -1");
1617     return container_proxy;
1618   }
1619   else if (status == 217) {
1620     INFOS("[LaunchPaCOProxyContainer] failed : system command status 217");
1621     return container_proxy;
1622   }
1623
1624   int count = TIME_OUT_TO_LAUNCH_CONT;
1625   CORBA::Object_var obj = CORBA::Object::_nil();
1626   std::string containerNameInNS = _NS->BuildContainerNameForNS(params.container_name.in(), 
1627                                                                hostname.c_str());
1628   MESSAGE("[LaunchParallelContainer]  Waiting for Parallel Container proxy : " << containerNameInNS);
1629
1630   while (CORBA::is_nil(obj) && count) 
1631   {
1632     sleep(1);
1633     count--;
1634     obj = _NS->Resolve(containerNameInNS.c_str());
1635   }
1636
1637   try 
1638   {
1639     container_proxy = PaCO::InterfaceManager::_narrow(obj);
1640   }
1641   catch(CORBA::SystemException& e)
1642   {
1643     INFOS("[StarPaCOPPContainer] Exception in _narrow after LaunchParallelContainer for proxy !");
1644     INFOS("CORBA::SystemException : " << e);
1645     return container_proxy;
1646   }
1647   catch(CORBA::Exception& e)
1648   {
1649     INFOS("[StarPaCOPPContainer] Exception in _narrow after LaunchParallelContainer for proxy !");
1650     INFOS("CORBA::Exception" << e);
1651     return container_proxy;
1652   }
1653   catch(...)
1654   {
1655     INFOS("[StarPaCOPPContainer] Exception in _narrow after LaunchParallelContainer for proxy !");
1656     INFOS("Unknown exception !");
1657     return container_proxy;
1658   }
1659   if (CORBA::is_nil(container_proxy))
1660   {
1661     INFOS("[StarPaCOPPContainer] PaCO::InterfaceManager::_narrow returns NIL !");
1662     return container_proxy;
1663   }
1664   return obj._retn();
1665 }
1666
1667 //=============================================================================
1668 /*! This method launches the parallel container.
1669  *  It will may be placed on the ressources manager.
1670  *
1671  * \param command to launch
1672  * \param container's parameters
1673  * \param name of the container
1674  *
1675  * \return CORBA container reference
1676  */
1677 //=============================================================================
1678 bool
1679 SALOME_ContainerManager::LaunchPaCONodeContainer(const std::string& command, 
1680                                                  const Engines::ContainerParameters& params,
1681                                                  const std::string& name,
1682                                                  SALOME_ContainerManager::actual_launch_machine_t & vect_machine)
1683 {
1684   INFOS("[LaunchPaCONodeContainer] Launch command");
1685   int status = system(command.c_str());
1686   if (status == -1) {
1687     INFOS("[LaunchPaCONodeContainer] failed : system command status -1");
1688     return false;
1689   }
1690   else if (status == 217) {
1691     INFOS("[LaunchPaCONodeContainer] failed : system command status 217");
1692     return false;
1693   }
1694
1695   INFOS("[LaunchPaCONodeContainer] Waiting for the nodes of the parallel container");
1696   // We are waiting all the nodes
1697   for (int i = 0; i < params.nb_proc; i++) 
1698   {
1699     CORBA::Object_var obj = CORBA::Object::_nil();
1700     std::string theMachine(vect_machine[i]);
1701     // Name of the node
1702     std::ostringstream tmp;
1703     tmp << i;
1704     std::string proc_number = tmp.str();
1705     std::string container_node_name = name + proc_number;
1706     std::string containerNameInNS = _NS->BuildContainerNameForNS((char*) container_node_name.c_str(), theMachine.c_str());
1707     INFOS("[LaunchPaCONodeContainer]  Waiting for Parallel Container node " << containerNameInNS << " on " << theMachine);
1708     int count = TIME_OUT_TO_LAUNCH_CONT;
1709     while (CORBA::is_nil(obj) && count) {
1710       sleep(1) ;
1711       count-- ;
1712       obj = _NS->Resolve(containerNameInNS.c_str());
1713     }
1714     if (CORBA::is_nil(obj))
1715     {
1716       INFOS("[LaunchPaCONodeContainer] Launch of node failed (or not found) !");
1717       return false;
1718     }
1719   }
1720   return true;
1721 }
1722
1723 #else
1724
1725 Engines::Container_ptr
1726 SALOME_ContainerManager::StartPaCOPPContainer(const Engines::ContainerParameters& params,
1727                                               std::string resource_selected)
1728 {
1729   Engines::Container_ptr ret = Engines::Container::_nil();
1730   INFOS("[StarPaCOPPContainer] is disabled !");
1731   INFOS("[StarPaCOPPContainer] recompile SALOME Kernel to enable PaCO++ parallel extension");
1732   return ret;
1733 }
1734
1735 std::string 
1736 SALOME_ContainerManager::BuildCommandToLaunchPaCOProxyContainer(const Engines::ContainerParameters& params,
1737                                                                 std::string machine_file_name,
1738                                                                 std::string & proxy_hostname)
1739 {
1740   return "";
1741 }
1742
1743 std::string 
1744 SALOME_ContainerManager::BuildCommandToLaunchPaCONodeContainer(const Engines::ContainerParameters& params,
1745                                                                const std::string & machine_file_name,
1746                                                                SALOME_ContainerManager::actual_launch_machine_t & vect_machine, 
1747                                                                const std::string & proxy_hostname) 
1748 {
1749   return "";
1750 }
1751 void 
1752 SALOME_ContainerManager::LogConfiguration(const std::string & log_type,
1753                                           const std::string & exe_type,
1754                                           const std::string & container_name,
1755                                           const std::string & hostname,
1756                                           std::string & begin, 
1757                                           std::string & end)
1758 {
1759 }
1760
1761 CORBA::Object_ptr 
1762 SALOME_ContainerManager::LaunchPaCOProxyContainer(const std::string& command, 
1763                                                   const Engines::ContainerParameters& params,
1764                                                   const std::string& hostname)
1765 {
1766   CORBA::Object_ptr ret = CORBA::Object::_nil();
1767   return ret;
1768 }
1769
1770 bool 
1771 SALOME_ContainerManager::LaunchPaCONodeContainer(const std::string& command, 
1772                         const Engines::ContainerParameters& params,
1773                         const std::string& name,
1774                         SALOME_ContainerManager::actual_launch_machine_t & vect_machine)
1775 {
1776   return false;
1777 }
1778 #endif
1779