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