Salome HOME
CCAR: protect Fortran Calcium calls against unneeded float arguments incorrectly...
[modules/kernel.git] / src / Container / SALOME_ContainerManager.cxx
index 3c7fdf021649b1be5d1454d72a60648294a30bb0..a22a39c2fc7a866980f68da5e639bb35c9fbe0e3 100644 (file)
@@ -1,4 +1,4 @@
-//  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, OPEN CASCADE
+//  Copyright (C) 2007-2010  CEA/DEN, EDF R&D, OPEN CASCADE
 //
 //  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
@@ -19,6 +19,7 @@
 //
 //  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
 //
+
 #include "SALOME_ContainerManager.hxx"
 #include "SALOME_NamingService.hxx"
 #include "SALOME_ModuleCatalog.hh"
 #endif
 #include <vector>
 #include "Utils_CorbaException.hxx"
-#include "Batch_Date.hxx"
+#include <sstream>
+
+#ifdef WNT
+#include <process.h>
+#define getpid _getpid
+#endif
 
 #ifdef WITH_PACO_PARALLEL
-#include "PaCO++.h"
+#include "PaCOPP.hxx"
 #endif
 
 #define TIME_OUT_TO_LAUNCH_CONT 61
 
-using namespace std;
-
-vector<Engines::Container_ptr> SALOME_ContainerManager::_batchLaunchedContainers;
-
-vector<Engines::Container_ptr>::iterator SALOME_ContainerManager::_batchLaunchedContainersIter;
-
 const char *SALOME_ContainerManager::_ContainerManagerNameInNS = 
   "/ContainerManager";
 
+omni_mutex SALOME_ContainerManager::_numInstanceMutex;
+
+
 //=============================================================================
 /*! 
  *  Constructor
@@ -57,12 +60,11 @@ const char *SALOME_ContainerManager::_ContainerManagerNameInNS =
  */
 //=============================================================================
 
-SALOME_ContainerManager::SALOME_ContainerManager(CORBA::ORB_ptr orb, PortableServer::POA_var poa, SALOME_ResourcesManager *rm, SALOME_NamingService *ns)
+SALOME_ContainerManager::SALOME_ContainerManager(CORBA::ORB_ptr orb, PortableServer::POA_var poa, SALOME_ResourcesManager *rm, SALOME_NamingService *ns):_nbprocUsed(0)
 {
   MESSAGE("constructor");
   _NS = ns;
   _ResManager = rm;
-  _id=0;
 
   PortableServer::POAManager_var pman = poa->the_POAManager();
   _orb = CORBA::ORB::_duplicate(orb) ;
@@ -80,8 +82,27 @@ SALOME_ContainerManager::SALOME_ContainerManager(CORBA::ORB_ptr orb, PortableSer
     Engines::ContainerManager::_narrow(obj);
 
   _NS->Register(refContMan,_ContainerManagerNameInNS);
-  _MpiStarted = false;
   _isAppliSalomeDefined = (getenv("APPLI") != 0);
+
+#ifdef HAVE_MPI2
+#ifdef WITHOPENMPI
+  std::string urifile = getenv("HOME");
+  std::ostringstream mypid;
+  mypid << getpid();
+  urifile += "/.urifile_" + mypid.str();
+  setenv("OMPI_URI_FILE",urifile.c_str(),0);
+  if( getenv("OMPI_URI_FILE") != NULL ){
+    system("killall ompi-server");
+    std::string command;
+    command = "ompi-server -r ";
+    command += getenv("OMPI_URI_FILE");
+    int status=system(command.c_str());
+    if(status!=0)
+      throw SALOME_Exception("Error when launching ompi-server");
+  }
+#endif
+#endif
+
   MESSAGE("constructor end");
 }
 
@@ -94,11 +115,17 @@ SALOME_ContainerManager::SALOME_ContainerManager(CORBA::ORB_ptr orb, PortableSer
 SALOME_ContainerManager::~SALOME_ContainerManager()
 {
   MESSAGE("destructor");
+#ifdef HAVE_MPI2
+#ifdef WITHOPENMPI
+  if( getenv("OMPI_URI_FILE") != NULL )
+    system("killall ompi-server");
+#endif
+#endif
 }
 
 //=============================================================================
+//! shutdown all the containers, then the ContainerManager servant
 /*! CORBA method:
- *  shutdown all the containers, then the ContainerManager servant
  */
 //=============================================================================
 
@@ -109,13 +136,11 @@ void SALOME_ContainerManager::Shutdown()
   _NS->Destroy_Name(_ContainerManagerNameInNS);
   PortableServer::ObjectId_var oid = _poa->servant_to_id(this);
   _poa->deactivate_object(oid);
-  //_remove_ref() has already been done at creation
-  //_remove_ref();
 }
 
 //=============================================================================
+//! Loop on all the containers listed in naming service, ask shutdown on each
 /*! CORBA Method:
- *  Loop on all the containers listed in naming service, ask shutdown on each
  */
 //=============================================================================
 
@@ -125,9 +150,9 @@ void SALOME_ContainerManager::ShutdownContainers()
   bool isOK;
   isOK = _NS->Change_Directory("/Containers");
   if( isOK ){
-    vector<string> vec = _NS->list_directory_recurs();
-    list<string> lstCont;
-    for(vector<string>::iterator iter = vec.begin();iter!=vec.end();iter++)
+    std::vector<std::string> vec = _NS->list_directory_recurs();
+    std::list<std::string> lstCont;
+    for(std::vector<std::string>::iterator iter = vec.begin();iter!=vec.end();iter++)
       {
         SCRUTE((*iter));
         CORBA::Object_var obj=_NS->Resolve((*iter).c_str());
@@ -135,7 +160,7 @@ void SALOME_ContainerManager::ShutdownContainers()
           {
             Engines::Container_var cont=Engines::Container::_narrow(obj);
             if(!CORBA::is_nil(cont))
-             lstCont.push_back((*iter));
+              lstCont.push_back((*iter));
           }
         catch(const CORBA::Exception& e)
           {
@@ -143,632 +168,377 @@ void SALOME_ContainerManager::ShutdownContainers()
           }
       }
     MESSAGE("Container list: ");
-    for(list<string>::iterator iter=lstCont.begin();iter!=lstCont.end();iter++){
+    for(std::list<std::string>::iterator iter=lstCont.begin();iter!=lstCont.end();iter++){
       SCRUTE((*iter));
     }
-    for(list<string>::iterator iter=lstCont.begin();iter!=lstCont.end();iter++){
-      SCRUTE((*iter));
-      CORBA::Object_var obj=_NS->Resolve((*iter).c_str());
-      Engines::Container_var cont=Engines::Container::_narrow(obj);
-      if(!CORBA::is_nil(cont))
+    for(std::list<std::string>::iterator iter=lstCont.begin();iter!=lstCont.end();iter++)
+    {
+      try
+      {
+        SCRUTE((*iter));
+        CORBA::Object_var obj=_NS->Resolve((*iter).c_str());
+        Engines::Container_var cont=Engines::Container::_narrow(obj);
+        if(!CORBA::is_nil(cont))
         {
-         MESSAGE("ShutdownContainers: " << (*iter));
-          try
-            {
-              cont->Shutdown();
-            }
-          catch(CORBA::SystemException& e)
-            {
-              INFOS("CORBA::SystemException ignored : " << e);
-            }
-          catch(CORBA::Exception&)
-            {
-              INFOS("CORBA::Exception ignored.");
-            }
-          catch(...)
-            {
-              INFOS("Unknown exception ignored.");
-            }
+          MESSAGE("ShutdownContainers: " << (*iter));
+          cont->Shutdown();
         }
-      else 
-        MESSAGE("ShutdownContainers: no container ref for " << (*iter));
+        else 
+          MESSAGE("ShutdownContainers: no container ref for " << (*iter));
+      }
+      catch(CORBA::SystemException& e)
+      {
+        INFOS("CORBA::SystemException ignored : " << e);
+      }
+      catch(CORBA::Exception&)
+      {
+        INFOS("CORBA::Exception ignored.");
+      }
+      catch(...)
+      {
+        INFOS("Unknown exception ignored.");
+      }
     }
   }
 }
 
 //=============================================================================
+//! Give a suitable Container given constraints
 /*! CORBA Method:
- *  Find a suitable Container in a list of machines, or start one
- *  \param params            Machine Parameters required for the container
- *  \param possibleComputers list of machines usable for find or start
+ *  \param params Container Parameters required for the container
+ *  \return the container or nil
  */
 //=============================================================================
-
 Engines::Container_ptr
-SALOME_ContainerManager::
-FindOrStartContainer(const Engines::MachineParameters& params,
-                    const Engines::MachineList& possibleComputers)
+SALOME_ContainerManager::GiveContainer(const Engines::ContainerParameters& params)
 {
-  Engines::Container_ptr ret = FindContainer(params,possibleComputers);
-  if(!CORBA::is_nil(ret))
-    return ret;
-  MESSAGE("Container doesn't exist try to launch it ...");
-
-  return StartContainer(params,possibleComputers,Engines::P_FIRST);
-
-}
-
-//=============================================================================
-/*! CORBA Method:
- *  Start a suitable Container in a list of machines
- *  \param params            Machine Parameters required for the container
- *  \param possibleComputers list of machines usable for start
- */
-//=============================================================================
-
-Engines::Container_ptr
-SALOME_ContainerManager::
-StartContainer(const Engines::MachineParameters& params,
-              const Engines::MachineList& possibleComputers,
-              Engines::ResPolicy policy,const std::string& container_exe)
-{
-#ifdef WITH_PACO_PARALLEL
-  std::string parallelLib(params.parallelLib);
-  if (parallelLib != "")
-    return FindOrStartParallelContainer(params, possibleComputers);
-#endif
-  long id;
-  string containerNameInNS;
-  char idc[3*sizeof(long)];
+  std::string machFile;
   Engines::Container_ptr ret = Engines::Container::_nil();
 
-  MESSAGE("SALOME_ContainerManager::StartContainer " <<
-         possibleComputers.length());
-
-  vector<string> lm;
-  for(unsigned int i=0;i<possibleComputers.length();i++)
-    lm.push_back(string(possibleComputers[i]));
-
-  string theMachine;
-  try{
-    switch(policy){
-    case Engines::P_FIRST:
-      theMachine=_ResManager->GetImpl()->FindFirst(lm);
-      break;
-    case Engines::P_CYCL:
-      theMachine=_ResManager->GetImpl()->FindNext(lm);
-      break;
-    case Engines::P_BEST:
-      theMachine=_ResManager->GetImpl()->FindBest(lm);
-      break;
+  // Step 0: Default mode is start
+  Engines::ContainerParameters local_params(params);
+  if (std::string(local_params.mode.in()) == "")
+    local_params.mode = CORBA::string_dup("start");
+  std::string mode = local_params.mode.in();
+  MESSAGE("[GiveContainer] starting with mode: " << mode);
+
+  // Step 1: Find Container for find and findorstart mode
+  if (mode == "find" || mode == "findorstart")
+  {
+    ret = FindContainer(params, params.resource_params.resList);
+    if(!CORBA::is_nil(ret))
+      return ret;
+    else
+    {
+      if (mode == "find")
+      {
+        MESSAGE("[GiveContainer] no container found");
+        return ret;
+      }
+      else
+      {
+        mode = "start";
+      }
     }
   }
-  catch( const SALOME_Exception &ex ){
-    MESSAGE(ex.what());
-    return Engines::Container::_nil();
-  }
-
-  //If the machine name is localhost use the real name
-  if(theMachine == "localhost")
-    theMachine=Kernel_Utils::GetHostname();
 
-  MESSAGE("try to launch it on " << theMachine);
+  // Step 2: Get all possibleResources from the parameters
+  Engines::ResourceList_var possibleResources = _ResManager->GetFittingResources(local_params.resource_params);
+  MESSAGE("[GiveContainer] - length of possible resources " << possibleResources->length());
+  std::vector<std::string> local_resources;
 
-  // Get Id for container: a parallel container registers in Naming Service
-  // on the machine where is process 0. ContainerManager does'nt know the name
-  // of this machine before the launch of the parallel container. So to get
-  // the IOR of the parallel container in Naming Service, ContainerManager
-  // gives a unique Id. The parallel container registers his name under
-  // /ContainerManager/Id directory in NamingService
-
-  id = GetIdForContainer();
+  // Step 3: if mode is "get" keep only machines with existing containers 
+  if(mode == "get")
+  {
+    for(unsigned int i=0; i < possibleResources->length(); i++)
+    {
+      Engines::Container_ptr cont = FindContainer(params, possibleResources[i].in());
+      try
+      {
+        if(!cont->_non_existent())
+          local_resources.push_back(std::string(possibleResources[i]));
+      }
+      catch(CORBA::Exception&) {}
+    }
 
-  string command;
-  if(theMachine==""){
-    MESSAGE("SALOME_ContainerManager::StartContainer : " <<
-           "no possible computer");
-    return Engines::Container::_nil();
+    // if local_resources is empty, we cannot give a container
+    if (local_resources.size() == 0)
+    {
+      MESSAGE("[GiveContainer] cannot find a container for mode get");
+      return ret;
+    }
   }
-  else if(theMachine==Kernel_Utils::GetHostname())
-    command = BuildCommandToLaunchLocalContainer(params,id,container_exe);
   else
-    command = BuildCommandToLaunchRemoteContainer(theMachine,params,id,container_exe);
+    for(unsigned int i=0; i < possibleResources->length(); i++)
+      local_resources.push_back(std::string(possibleResources[i]));
 
-  // RmTmpFile(); Too early! May be this function has not been used for a long time...
-
-  //check if an entry exists in Naming service
-  if(params.isMPI)
-    {
-      containerNameInNS = "/ContainerManager/id";
-      sprintf(idc,"%ld",id);
-      containerNameInNS += idc;
-    }
+  // Step 4: select the resource where to get/start the container
+  std::string resource_selected;
+  try
+  {
+    resource_selected = _ResManager->GetImpl()->Find(params.resource_params.policy.in(), local_resources);
+  }
+  catch(const SALOME_Exception &ex)
+  {
+    MESSAGE("[GiveContainer] Exception in ResourceManager find !: " << ex.what());
+    return ret;
+  }
+  MESSAGE("[GiveContainer] Resource selected is: " << resource_selected);
+
+  // Step 5: get container in the naming service
+  Engines::ResourceDefinition_var resource_definition = _ResManager->GetResourceDefinition(resource_selected.c_str());
+  std::string hostname(resource_definition->hostname.in());
+  std::string containerNameInNS;
+  if(params.isMPI){
+    int nbproc;
+    if ( params.nb_proc <= 0 )
+      nbproc = 1;
+    else
+      nbproc = params.nb_proc;
+    if( getenv("LIBBATCH_NODEFILE") != NULL )
+      machFile = machinesFile(nbproc);
+    // A mpi parallel container register on zero node in NS
+    containerNameInNS = _NS->BuildContainerNameForNS(params, GetMPIZeroNode(hostname,machFile).c_str());
+  }
   else
-    containerNameInNS = _NS->BuildContainerNameForNS(params,theMachine.c_str());
+    containerNameInNS = _NS->BuildContainerNameForNS(params, hostname.c_str());
+  MESSAGE("[GiveContainer] Container name in the naming service: " << containerNameInNS);
 
-  SCRUTE(containerNameInNS);
+  // Step 6: check if the name exists in naming service
+  //if params.mode == "getorstart" or "get" use the existing container
+  //if params.mode == "start" shutdown the existing container before launching a new one with that name
   CORBA::Object_var obj = _NS->Resolve(containerNameInNS.c_str());
-  if ( !CORBA::is_nil(obj) )
+  if (!CORBA::is_nil(obj))
+  {
+    try
     {
-      try
+      Engines::Container_var cont=Engines::Container::_narrow(obj);
+      if(!cont->_non_existent())
+      {
+        if(std::string(params.mode.in())=="getorstart" || std::string(params.mode.in())=="get"){
+          return cont._retn(); /* the container exists and params.mode is getorstart or get use it*/
+        }
+        else
         {
-          // shutdown the registered container if it exists
-          Engines::Container_var cont=Engines::Container::_narrow(obj);
-          if(!CORBA::is_nil(cont))
-            cont->Shutdown();
+          INFOS("[GiveContainer] A container is already registered with the name: " << containerNameInNS << ", shutdown the existing container");
+          cont->Shutdown(); // shutdown the registered container if it exists
         }
-      catch(CORBA::Exception&)
+      }
+    }
+    catch(CORBA::Exception&)
+    {
+      INFOS("[GiveContainer] CORBA::Exception ignored when trying to get the container - we start a new one");
+    }
+  }
+
+  // Step 7: type of container: PaCO, Exe, Mpi or Classic
+  // Mpi already tested in step 5, specific code on BuildCommandToLaunch Local/Remote Container methods
+  // TODO -> separates Mpi from Classic/Exe
+  // Classic or Exe ?
+  std::string container_exe = "SALOME_Container"; // Classic container
+  int found=0;
+  try
+  {
+    CORBA::String_var container_exe_tmp;
+    CORBA::Object_var obj = _NS->Resolve("/Kernel/ModulCatalog");
+    SALOME_ModuleCatalog::ModuleCatalog_var Catalog = SALOME_ModuleCatalog::ModuleCatalog::_narrow(obj) ;
+    if (CORBA::is_nil (Catalog))
+    {
+      INFOS("[GiveContainer] Module Catalog is not found -> cannot launch a container");
+      return ret;
+    }
+    // Loop through component list
+    for(unsigned int i=0; i < local_params.resource_params.componentList.length(); i++)
+    {
+      const char* compoi = local_params.resource_params.componentList[i];
+      SALOME_ModuleCatalog::Acomponent_var compoInfo = Catalog->GetComponent(compoi);
+      if (CORBA::is_nil (compoInfo))
+      {
+        continue;
+      }
+      SALOME_ModuleCatalog::ImplType impl=compoInfo->implementation_type();
+      container_exe_tmp=compoInfo->implementation_name();
+      if(impl==SALOME_ModuleCatalog::CEXE)
+      {
+        if(found)
         {
-          INFOS("CORBA::Exception ignored.");
+          INFOS("ContainerManager Error: you can't have 2 CEXE component in the same container" );
+          return Engines::Container::_nil();
         }
+        MESSAGE("[GiveContainer] Exe container found !: " << container_exe_tmp);
+        container_exe = container_exe_tmp.in();
+        found=1;
+      }
     }
+  }
+  catch (ServiceUnreachable&)
+  {
+    INFOS("Caught exception: Naming Service Unreachable");
+    return ret;
+  }
+  catch (...)
+  {
+    INFOS("Caught unknown exception.");
+    return ret;
+  }
+
+  // Step 8: start a new container
+  // Check if a PaCO container
+  // PaCO++
+  if (std::string(local_params.parallelLib.in()) != "")
+  {
+    ret = StartPaCOPPContainer(params, resource_selected);
+    return ret;
+  }
+  // Other type of containers...
+  MESSAGE("[GiveContainer] Try to launch a new container on " << resource_selected);
+  std::string command;
+  // if a parallel container is launched in batch job, command is: "mpirun -np nbproc -machinefile nodesfile SALOME_MPIContainer"
+  if( getenv("LIBBATCH_NODEFILE") != NULL && params.isMPI )
+    command = BuildCommandToLaunchLocalContainer(params, machFile, container_exe);
+  // if a container is launched on localhost, command is "SALOME_Container" or "mpirun -np nbproc SALOME_MPIContainer"
+  else if(hostname == Kernel_Utils::GetHostname())
+    command = BuildCommandToLaunchLocalContainer(params, machFile, container_exe);
+  // if a container is launched in remote mode, command is "ssh resource_selected SALOME_Container" or "ssh resource_selected mpirun -np nbproc SALOME_MPIContainer"
+  else
+    command = BuildCommandToLaunchRemoteContainer(resource_selected, params, container_exe);
 
   //redirect stdout and stderr in a file
-  string logFilename="/tmp/"+_NS->ContainerName(params)+"_"+ theMachine +"_"+getenv( "USER" )+".log" ;
-  command += " > " + logFilename + " 2>&1 &";
+#ifdef WNT
+  std::string logFilename=getenv("TEMP");
+  logFilename += "\\";
+  std::string user = getenv( "USERNAME" );
+#else
+  std::string user = getenv( "USER" );
+  std::string logFilename="/tmp";
+  char* val = getenv("SALOME_TMP_DIR");
+  if(val)
+  {
+    struct stat file_info;
+    stat(val, &file_info);
+    bool is_dir = S_ISDIR(file_info.st_mode);
+    if (is_dir)logFilename=val;
+    else std::cerr << "SALOME_TMP_DIR environment variable is not a directory use /tmp instead" << std::endl;
+  }
+  logFilename += "/";
+#endif
+  logFilename += _NS->ContainerName(params)+"_"+ resource_selected +"_"+user;
+  std::ostringstream tmp;
+  tmp << "_" << getpid();
+  logFilename += tmp.str();
+  logFilename += ".log" ;
+  command += " > " + logFilename + " 2>&1";
+#ifdef WNT
+  command = "%PYTHONBIN% -c \"import win32pm ; win32pm.spawnpid(r'" + command + "', '')\"";
+#else
+  command += " &";
+#endif
 
   // launch container with a system call
   int status=system(command.c_str());
 
-
   if (status == -1){
-    MESSAGE("SALOME_LifeCycleCORBA::StartOrFindContainer rsh failed " <<
-           "(system command status -1)");
-    RmTmpFile(); // command file can be removed here
+    MESSAGE("SALOME_ContainerManager::StartContainer rsh failed (system command status -1)");
+    RmTmpFile(_TmpFileName); // command file can be removed here
     return Engines::Container::_nil();
   }
   else if (status == 217){
-    MESSAGE("SALOME_LifeCycleCORBA::StartOrFindContainer rsh failed " <<
-           "(system command status 217)");
-    RmTmpFile(); // command file can be removed here
+    MESSAGE("SALOME_ContainerManager::StartContainer rsh failed (system command status 217)");
+    RmTmpFile(_TmpFileName); // command file can be removed here
     return Engines::Container::_nil();
   }
-  else{
-    int count=TIME_OUT_TO_LAUNCH_CONT;
-    MESSAGE("count = "<<count);
-    while ( CORBA::is_nil(ret) && count ){
+  else
+  {
+    int count = TIME_OUT_TO_LAUNCH_CONT;
+    MESSAGE("[GiveContainer] waiting " << count << " second steps");
+    while (CORBA::is_nil(ret) && count)
+    {
 #ifndef WIN32
       sleep( 1 ) ;
 #else
       Sleep(1000);
 #endif
-      count-- ;
-      if ( count != 10 )
-       MESSAGE( count << ". Waiting for container on " << theMachine);
-
+      count--;
+      MESSAGE("[GiveContainer] step " << count << " Waiting for container on " << resource_selected);
       CORBA::Object_var obj = _NS->Resolve(containerNameInNS.c_str());
       ret=Engines::Container::_narrow(obj);
     }
-    
-    if ( CORBA::is_nil(ret) )
-      {
-        MESSAGE("SALOME_LifeCycleCORBA::StartOrFindContainer rsh failed");
-      }
-    else
-      {
-        logFilename=":"+logFilename;
-        logFilename="@"+Kernel_Utils::GetHostname()+logFilename;
-        logFilename=getenv( "USER" )+logFilename;
-        ret->logfilename(logFilename.c_str());
-      }
-
-    RmTmpFile(); // command file can be removed here
-    return ret;
-  }
-}
-
-//=============================================================================
-/*! CORBA Method:
- *  Start a suitable Container in a list of machines
- *  \param params            Machine Parameters required for the container
- *  \param possibleComputers list of machines usable for start
- */
-//=============================================================================
-
-Engines::Container_ptr
-SALOME_ContainerManager::
-StartContainer(const Engines::MachineParameters& params,
-              Engines::ResPolicy policy,
-              const Engines::CompoList& componentList)
-{
-  Engines::MachineList_var possibleComputers = _ResManager->GetFittingResources(params,componentList);
-
-  // Look into ModulCatalog if a specific container must be launched
-  CORBA::String_var container_exe;
-  int found=0;
-  try
+    if (CORBA::is_nil(ret))
     {
-      CORBA::Object_var obj = _NS->Resolve("/Kernel/ModulCatalog");
-      SALOME_ModuleCatalog::ModuleCatalog_var Catalog = SALOME_ModuleCatalog::ModuleCatalog::_narrow(obj) ;
-      if (CORBA::is_nil (Catalog))
-        return Engines::Container::_nil();
-      // Loop through component list
-      for(unsigned int i=0;i<componentList.length();i++)
-        {
-          const char* compoi = componentList[i];
-          SALOME_ModuleCatalog::Acomponent_var compoInfo = Catalog->GetComponent(compoi);
-          if (CORBA::is_nil (compoInfo))
-            {
-              continue;
-            }
-          SALOME_ModuleCatalog::ImplType impl=compoInfo->implementation_type();
-          container_exe=compoInfo->implementation_name();
-          if(impl==SALOME_ModuleCatalog::CEXE)
-            {
-              if(found)
-                {
-                  INFOS("ContainerManager Error: you can't have 2 CEXE component in the same container" );
-                  return Engines::Container::_nil();
-                }
-              found=1;
-            }
-        }
-    }
-  catch (ServiceUnreachable&)
-    {
-      INFOS("Caught exception: Naming Service Unreachable");
-      return Engines::Container::_nil();
+      INFOS("[GiveContainer] was not able to launch container " << containerNameInNS);
     }
-  catch (...)
+    else
     {
-      INFOS("Caught unknown exception.");
-      return Engines::Container::_nil();
-    }
-
-  if(found)
-    return StartContainer(params,possibleComputers,policy,container_exe.in());
-  else
-    return StartContainer(params,possibleComputers,policy);
-}
-
-#ifdef WITH_PACO_PARALLEL
-//=============================================================================
-/*! CORBA Method:
- *  Find or Start a suitable PaCO++ Parallel Container in a list of machines.
- *  \param params            Machine Parameters required for the container
- *  \param possibleComputers list of machines usable for find or start
- *
- *  \return CORBA container reference.
- */
-//=============================================================================
-Engines::Container_ptr
-SALOME_ContainerManager::
-FindOrStartParallelContainer(const Engines::MachineParameters& params_const,
-                            const Engines::MachineList& possibleComputers)
-{
-  CORBA::Object_var obj;
-  PaCO::InterfaceManager_var proxy;
-  Engines::Container_ptr ret = Engines::Container::_nil();
-  Engines::MachineParameters params(params_const);
-
-  // Step 1 : Try to find a suitable container
-  // Currently not as good as could be since
-  // we have to verified the number of nodes of the container
-  // if a user tell that.
-  ret = FindContainer(params, possibleComputers);
-
-  if(CORBA::is_nil(ret)) {
-    // Step 2 : Starting a new parallel container
-    INFOS("[FindOrStartParallelContainer] Starting a parallel container");
-
-    // Step 2.1 : Choose a computer
-    string theMachine = _ResManager->FindFirst(possibleComputers);
-    if(theMachine == "") {
-      INFOS("[FindOrStartParallelContainer] !!!!!!!!!!!!!!!!!!!!!!!!!!");
-      INFOS("[FindOrStartParallelContainer] No possible computer found");
-      INFOS("[FindOrStartParallelContainer] !!!!!!!!!!!!!!!!!!!!!!!!!!");
-    }
-    else {
-      INFOS("[FindOrStartParallelContainer] on machine : " << theMachine);
-      string command;
-      if(theMachine == Kernel_Utils::GetHostname()) {
-       // Step 3 : starting parallel container proxy
-       params.hostname = CORBA::string_dup(theMachine.c_str());
-       Engines::MachineParameters params_proxy(params);
-       try {
-         command = BuildCommandToLaunchLocalParallelContainer("SALOME_ParallelContainerProxy", params_proxy, "xterm");
-       }
-       catch(const SALOME_Exception & ex){
-         MESSAGE(ex.what());
-         return Engines::Container::_nil();
-       }
-       // LaunchParallelContainer uses this value to know if it launches the proxy or the nodes
-       params_proxy.nb_component_nodes = 0;
-       obj = LaunchParallelContainer(command, params_proxy, _NS->ContainerName(params));
-       ret = Engines::Container::_narrow(obj);
-       proxy = PaCO::InterfaceManager::_narrow(obj);
-
-       // Step 4 : starting parallel container nodes
-       command = BuildCommandToLaunchLocalParallelContainer("SALOME_ParallelContainerNode", params, "xterm");
-       string name = _NS->ContainerName(params) + "Node";
-       LaunchParallelContainer(command, params, name);
-       // Step 5 : connecting nodes and the proxy to actually create a parallel container
-       try {
-         for (int i = 0; i < params.nb_component_nodes; i++) {
-
-           char buffer [5];
-#ifndef WIN32
-           snprintf(buffer,5,"%d",i);
-#else
-           _snprintf(buffer,5,"%d",i);
-#endif
-           string name_cont = name + string(buffer);
-
-           string theNodeMachine(CORBA::string_dup(params.hostname));
-           string containerNameInNS = _NS->BuildContainerNameForNS(name_cont.c_str(),theNodeMachine.c_str());
-           int count = TIME_OUT_TO_LAUNCH_CONT;
-           obj = _NS->Resolve(containerNameInNS.c_str());
-           while (CORBA::is_nil(obj) && count) {
-             INFOS("[FindOrStartParallelContainer] CONNECTION FAILED !!!!!!!!!!!!!!!!!!!!!!!!");
-#ifndef WIN32
-             sleep(1) ;
-#else
-             Sleep(1000);
-#endif
-             count-- ;
-             obj = _NS->Resolve(containerNameInNS.c_str());
-           }
-
-           PaCO::InterfaceParallel_var node = PaCO::InterfaceParallel::_narrow(obj);
-           MESSAGE("[FindOrStartParallelContainer] Deploying node : " << name);
-           node->deploy();
-         }
-         proxy->start();
-       }
-       catch(CORBA::SystemException& e)
-       {
-         INFOS("Caught CORBA::SystemException. : " << e);
-       }
-       catch(PortableServer::POA::ServantAlreadyActive&)
-       {
-         INFOS("Caught CORBA::ServantAlreadyActiveException");
-       }
-       catch(CORBA::Exception&)
-       {
-         INFOS("Caught CORBA::Exception.");
-       }
-       catch(std::exception& exc)
-       {
-         INFOS("Caught std::exception - "<<exc.what()); 
-       }
-       catch(...)
-       {
-         INFOS("Caught unknown exception.");
-       }
-       INFOS("[FindOrStartParallelContainer] node " << name << " deployed");
-      }
-      else {
-       INFOS("[FindOrStartParallelContainer] Currently parallel containers are launched only on the local host");
-      }
+      // Setting log file name
+      logFilename=":"+logFilename;
+      logFilename="@"+Kernel_Utils::GetHostname()+logFilename;
+      logFilename=user+logFilename;
+      ret->logfilename(logFilename.c_str());
+      RmTmpFile(_TmpFileName); // command file can be removed here
     }
-}
-return ret;
-}
-#else
-//=============================================================================
-/*! CORBA Method:
- *  Find or Start a suitable PaCO++ Parallel Container in a list of machines.
- *  \param params            Machine Parameters required for the container
- *  \param possibleComputers list of machines usable for find or start
- *
- *  \return CORBA container reference.
- */
-//=============================================================================
-Engines::Container_ptr
-SALOME_ContainerManager::
-FindOrStartParallelContainer(const Engines::MachineParameters& params,
-                            const Engines::MachineList& possibleComputers)
-{
-  Engines::Container_ptr ret = Engines::Container::_nil();
-  INFOS("[FindOrStartParallelContainer] is disabled !");
-  INFOS("[FindOrStartParallelContainer] recompile SALOME Kernel to enable parallel extension");
+  }
   return ret;
 }
-#endif
 
 //=============================================================================
-/*! CORBA Method:
- *  Give a suitable Container in a list of machines
- *  \param params            Machine Parameters required for the container
- *  \param possibleComputers list of machines usable for start
- */
-//=============================================================================
-
-Engines::Container_ptr
-SALOME_ContainerManager::
-GiveContainer(const Engines::MachineParameters& params,
-              Engines::ResPolicy policy,
-              const Engines::CompoList& componentList)
-{
-  char *valenv=getenv("SALOME_BATCH");
-  if(valenv)
-    if (strcmp(valenv,"1")==0)
-      {
-       if(_batchLaunchedContainers.empty())
-         fillBatchLaunchedContainers();
-
-       if (_batchLaunchedContainersIter == _batchLaunchedContainers.end())
-         _batchLaunchedContainersIter = _batchLaunchedContainers.begin();
-
-       Engines::Container_ptr rtn = Engines::Container::_duplicate(*_batchLaunchedContainersIter);
-       _batchLaunchedContainersIter++;
-        return rtn;
-      }
-  return StartContainer(params,policy,componentList);
-}
-
-//=============================================================================
-/*! 
- * 
- */
-//=============================================================================
-
-Engines::Container_ptr
-SALOME_ContainerManager::
-FindContainer(const Engines::MachineParameters& params,
-             const char *theMachine)
-{
-  string containerNameInNS(_NS->BuildContainerNameForNS(params,theMachine));
-  CORBA::Object_var obj = _NS->Resolve(containerNameInNS.c_str());
-  if( !CORBA::is_nil(obj) )
-    return Engines::Container::_narrow(obj);
-  else
-    return Engines::Container::_nil();
-}
-
-//=============================================================================
-/*! 
- * 
+//! Find a container given constraints (params) on a list of machines (possibleComputers)
+/*!
+ *
  */
 //=============================================================================
 
 Engines::Container_ptr
-SALOME_ContainerManager::
-FindContainer(const Engines::MachineParameters& params,
-             const Engines::MachineList& possibleComputers)
+SALOME_ContainerManager::FindContainer(const Engines::ContainerParameters& params,
+                                       const Engines::ResourceList& possibleResources)
 {
-  MESSAGE("FindContainer "<<possibleComputers.length());
-  for(unsigned int i=0;i<possibleComputers.length();i++)
+  MESSAGE("[FindContainer] FindContainer on " << possibleResources.length() << " resources");
+  for(unsigned int i=0; i < possibleResources.length();i++)
     {
-      MESSAGE("FindContainer possible " << possibleComputers[i]);
-      Engines::Container_ptr cont = FindContainer(params,possibleComputers[i]);
-      if( !CORBA::is_nil(cont) )
-       return cont;
+      Engines::Container_ptr cont = FindContainer(params, possibleResources[i].in());
+      if(!CORBA::is_nil(cont))
+        return cont;
     }
-  MESSAGE("FindContainer: not found");
+  MESSAGE("[FindContainer] no container found");
   return Engines::Container::_nil();
 }
 
 //=============================================================================
-/*! This method launches the parallel container.
- *  It will may be placed on the ressources manager.
- *
- * \param command to launch
- * \param container's parameters
- * \param name of the container
+//! Find a container given constraints (params) on a machine (theMachine)
+/*!
  *
- * \return CORBA container reference
  */
 //=============================================================================
-CORBA::Object_ptr 
-SALOME_ContainerManager::LaunchParallelContainer(const std::string& command, 
-                                                const Engines::MachineParameters& params,
-                                                const std::string& name)
-{
-  CORBA::Object_ptr obj = CORBA::Object::_nil();
-  string containerNameInNS;
-  MESSAGE("[LaunchParallelContainer] : command to launch...");
-  MESSAGE(command);
-  if (params.nb_component_nodes == 0) {
-    INFOS("[LaunchParallelContainer] launching the proxy of the parallel container");
-    int status = system(command.c_str());
-    if (status == -1) {
-      INFOS("[LaunchParallelContainer] failed : system command status -1");
-    }
-    else if (status == 217) {
-      INFOS("[LaunchParallelContainer] failed : system command status 217");
-    }
 
-    int count = TIME_OUT_TO_LAUNCH_CONT;
-    string theMachine(CORBA::string_dup(params.hostname));
-    containerNameInNS = _NS->BuildContainerNameForNS((char*) name.c_str(),theMachine.c_str());
-
-    INFOS("[LaunchParallelContainer]  Waiting for Parallel Container proxy on " << theMachine);
-    while (CORBA::is_nil(obj) && count) {
-#ifndef WIN32
-      sleep(1) ;
-#else
-      Sleep(1000);
-#endif
-      count-- ;
-      obj = _NS->Resolve(containerNameInNS.c_str());
-    }
-  }
-  else {
-    INFOS("[LaunchParallelContainer] launching the nodes of the parallel container");
-    int status = system(command.c_str());
-    if (status == -1) {
-      INFOS("[LaunchParallelContainer] failed : system command status -1");
-    }
-    else if (status == 217) {
-      INFOS("[LaunchParallelContainer] failed : system command status 217");
-    }
-    // We are waiting all the nodes
-    for (int i = 0; i < params.nb_component_nodes; i++) {
-      obj = CORBA::Object::_nil();
-      int count = TIME_OUT_TO_LAUNCH_CONT;
-
-      // Name of the node
-      char buffer [5];
-#ifndef WIN32
-      snprintf(buffer,5,"%d",i);
-#else
-      _snprintf(buffer,5,"%d",i);
-#endif
-
-      string name_cont = name + string(buffer);
-
-      // I don't like this...
-      string theMachine(CORBA::string_dup(params.hostname));
-      containerNameInNS = _NS->BuildContainerNameForNS((char*) name_cont.c_str(),theMachine.c_str());
-      cerr << "[LaunchContainer]  Waiting for Parllel Container node " << containerNameInNS << " on " << theMachine << endl;
-      while (CORBA::is_nil(obj) && count) {
-#ifndef WIN32
-       sleep(1) ;
-#else
-       Sleep(1000);
-#endif
-       count-- ;
-       obj = _NS->Resolve(containerNameInNS.c_str());
-      }
-    }
+Engines::Container_ptr
+SALOME_ContainerManager::FindContainer(const Engines::ContainerParameters& params,
+                                       const std::string& resource)
+{
+  Engines::ResourceDefinition_var resource_definition = _ResManager->GetResourceDefinition(resource.c_str());
+  std::string hostname(resource_definition->hostname.in());
+  std::string containerNameInNS(_NS->BuildContainerNameForNS(params, hostname.c_str()));
+  MESSAGE("[FindContainer] Try to find a container  " << containerNameInNS << " on resource " << resource);
+  CORBA::Object_var obj = _NS->Resolve(containerNameInNS.c_str());
+  try
+  {
+    if(obj->_non_existent())
+      return Engines::Container::_nil();
+    else
+      return Engines::Container::_narrow(obj);
   }
-
-  if ( CORBA::is_nil(obj) ) {
-    INFOS("[LaunchParallelContainer] failed");
+  catch(const CORBA::Exception& e)
+  {
+    return Engines::Container::_nil();
   }
-  return obj;
 }
 
-//=============================================================================
-/*! 
- * Get Id for container: a parallel container registers in Naming Service
- * on the machine where is process 0. ContainerManager does'nt know the name
- * of this machine before the launch of the parallel container. So to get
- * the IOR of the parallel container in Naming Service, ContainerManager
- * gives a unique Id. The parallel container registers his name under
- * /ContainerManager/Id directory in NamingService
- */
-//=============================================================================
-
-
-long SALOME_ContainerManager::GetIdForContainer(void)
-{
-  _id++;
-  return _id;
-}
 
-void SALOME_ContainerManager::fillBatchLaunchedContainers()
-{
-  _batchLaunchedContainers.clear();
-  _NS->Change_Directory("/Containers");
-  vector<string> vec = _NS->list_directory_recurs();
-  for(vector<string>::iterator iter = vec.begin();iter!=vec.end();iter++){
-    CORBA::Object_var obj=_NS->Resolve((*iter).c_str());
-    Engines::Container_ptr cont=Engines::Container::_narrow(obj);
-    if(!CORBA::is_nil(cont)){
-      _batchLaunchedContainers.push_back(cont);
-    }
-  }
-  _batchLaunchedContainersIter=_batchLaunchedContainers.begin();
-}
+bool isPythonContainer(const char* ContainerName);
 
 //=============================================================================
 /*!
  *  This is no longer valid (C++ container are also python containers)
  */ 
 //=============================================================================
-
 bool isPythonContainer(const char* ContainerName)
 {
   bool ret = false;
@@ -804,104 +574,104 @@ bool isPythonContainer(const char* ContainerName)
  */ 
 //=============================================================================
 
-string
+std::string
 SALOME_ContainerManager::BuildCommandToLaunchRemoteContainer
-(const string& machine,
- const Engines::MachineParameters& params, const long id,const std::string& container_exe)
+(const std::string& resource_name,
+ const Engines::ContainerParameters& params, const std::string& container_exe)
 {
-  string command;
-  int nbproc;
-  char idc[3*sizeof(long)];
-         
-  if ( ! _isAppliSalomeDefined )
-    command = BuildTempFileToLaunchRemoteContainer(machine, params);
-
+          
+  std::string command;
+  if (!_isAppliSalomeDefined)
+    command = BuildTempFileToLaunchRemoteContainer(resource_name, params);
   else
-    {
-      const ParserResourcesType& resInfo = _ResManager->GetImpl()->GetResourcesList(machine);
-
-      if (params.isMPI)
-        {
-          if ( (params.nb_node <= 0) && (params.nb_proc_per_node <= 0) )
-            nbproc = 1;
-          else if ( params.nb_node == 0 )
-            nbproc = params.nb_proc_per_node;
-          else if ( params.nb_proc_per_node == 0 )
-            nbproc = params.nb_node;
-          else
-            nbproc = params.nb_node * params.nb_proc_per_node;
-        }
-
-      // "ssh user@machine distantPath/runRemote.sh hostNS portNS WORKINGDIR workingdir \
-      //  SALOME_Container containerName &"
+  {
+    int nbproc;
+    Engines::ResourceDefinition_var resource_definition = _ResManager->GetResourceDefinition(resource_name.c_str());
+    std::string hostname(resource_definition->hostname.in());
+    const ParserResourcesType& resInfo = _ResManager->GetImpl()->GetResourcesDescr(resource_name);
 
-      if (resInfo.Protocol == rsh)
-        command = "rsh ";
-      else if (resInfo.Protocol == ssh)
-        command = "ssh ";
+    if (params.isMPI)
+    {
+      if ( params.nb_proc <= 0 )
+        nbproc = 1;
       else
-        throw SALOME_Exception("Unknown protocol");
+        nbproc = params.nb_proc;
+    }
 
-      if (resInfo.UserName != "")
-       {
-         command += resInfo.UserName;
-         command += "@";
-       }
+    // "ssh -l user machine distantPath/runRemote.sh hostNS portNS WORKINGDIR workingdir \
+    //  SALOME_Container containerName &"
+    if (resInfo.Protocol == rsh)
+      command = "rsh ";
+    else if (resInfo.Protocol == ssh)
+      command = "ssh ";
+    else
+      throw SALOME_Exception("Unknown protocol");
 
-      command += machine;
+    if (resInfo.UserName != "")
+    {
+      command += "-l ";
+      command += resInfo.UserName;
       command += " ";
+    }
 
-      if (resInfo.AppliPath != "")
-       command += resInfo.AppliPath; // path relative to user@machine $HOME
-      else
-       {
-         ASSERT(getenv("APPLI"));
-         command += getenv("APPLI"); // path relative to user@machine $HOME
-       }
+    command += resInfo.HostName;
+    command += " ";
 
-      command += "/runRemote.sh ";
+    if (resInfo.AppliPath != "")
+      command += resInfo.AppliPath; // path relative to user@machine $HOME
+    else
+    {
+      ASSERT(getenv("APPLI"));
+      command += getenv("APPLI"); // path relative to user@machine $HOME
+    }
 
-      ASSERT(getenv("NSHOST")); 
-      command += getenv("NSHOST"); // hostname of CORBA name server
+    command += "/runRemote.sh ";
 
-      command += " ";
-      ASSERT(getenv("NSPORT"));
-      command += getenv("NSPORT"); // port of CORBA name server
+    ASSERT(getenv("NSHOST")); 
+    command += getenv("NSHOST"); // hostname of CORBA name server
 
-      std::string wdir=params.workingdir.in();
-      if(wdir != "")
-        {
-          command += " WORKINGDIR ";
-          command += " '";
-          if(wdir == "$TEMPDIR")
-            wdir="\\$TEMPDIR";
-          command += wdir; // requested working directory
-          command += "'"; 
-        }
+    command += " ";
+    ASSERT(getenv("NSPORT"));
+    command += getenv("NSPORT"); // port of CORBA name server
+
+    std::string wdir = params.workingdir.in();
+    if(wdir != "")
+    {
+      command += " WORKINGDIR ";
+      command += " '";
+      if(wdir == "$TEMPDIR")
+        wdir="\\$TEMPDIR";
+      command += wdir; // requested working directory
+      command += "'"; 
+    }
 
-      if(params.isMPI)
-       {
-         command += " mpirun -np ";
-         std::ostringstream o;
-         o << nbproc << " ";
-         command += o.str();
+    if(params.isMPI)
+    {
+      command += " mpirun -np ";
+      std::ostringstream o;
+      o << nbproc << " ";
+      command += o.str();
 #ifdef WITHLAM
-         command += "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
-#endif 
-         command += " SALOME_MPIContainer ";
-       }
-      else
-        command += " " +container_exe+ " ";
+      command += "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
+#elif defined(WITHOPENMPI)
+      if( getenv("OMPI_URI_FILE") == NULL )
+        command += "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace";
+      else{
+        command += "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace -ompi-server file:";
+        command += getenv("OMPI_URI_FILE");
+      }
+#endif        
+      command += " SALOME_MPIContainer ";
+    }
+    else
+      command += " " +container_exe+ " ";
 
-      command += _NS->ContainerName(params);
-      command += " -id ";
-      sprintf(idc,"%ld",id);
-      command += idc;
-      command += " -";
-      AddOmninamesParams(command);
+    command += _NS->ContainerName(params);
+    command += " -";
+    AddOmninamesParams(command);
 
-      MESSAGE("command =" << command);
-    }
+    MESSAGE("command =" << command);
+  }
 
   return command;
 }
@@ -911,54 +681,50 @@ SALOME_ContainerManager::BuildCommandToLaunchRemoteContainer
  *  builds the command to be launched.
  */ 
 //=============================================================================
-
-string
+std::string
 SALOME_ContainerManager::BuildCommandToLaunchLocalContainer
-(const Engines::MachineParameters& params, const long id,const std::string& container_exe)
+(const Engines::ContainerParameters& params, const std::string& machinesFile, const std::string& container_exe)
 {
   _TmpFileName = BuildTemporaryFileName();
-  string command;
+  std::string command;
   int nbproc = 0;
-  //char idc[3*sizeof(long)];
 
-  ofstream command_file( _TmpFileName.c_str() );
+  std::ostringstream o;
 
   if (params.isMPI)
     {
-      //command = "mpirun -np ";
-      command_file << "mpirun -np ";
+      o << "mpirun -np ";
 
-      if ( (params.nb_node <= 0) && (params.nb_proc_per_node <= 0) )
+      if ( params.nb_proc <= 0 )
         nbproc = 1;
-      else if ( params.nb_node == 0 )
-        nbproc = params.nb_proc_per_node;
-      else if ( params.nb_proc_per_node == 0 )
-        nbproc = params.nb_node;
       else
-        nbproc = params.nb_node * params.nb_proc_per_node;
+        nbproc = params.nb_proc;
 
-      //std::ostringstream o;
+      o << nbproc << " ";
 
-      //o << nbproc << " ";
-      command_file << nbproc << " ";
+      if( getenv("LIBBATCH_NODEFILE") != NULL )
+        o << "-machinefile " << machinesFile << " ";
 
-      //command += o.str();
 #ifdef WITHLAM
-      //command += "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
-      command_file << "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
+      o << "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
+#elif defined(WITHOPENMPI)
+      if( getenv("OMPI_URI_FILE") == NULL )
+        o << "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace";
+      else
+        {
+          o << "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace -ompi-server file:";
+          o << getenv("OMPI_URI_FILE");
+        }
 #endif
 
       if (isPythonContainer(params.container_name))
-        //command += "pyMPI SALOME_ContainerPy.py ";
-        command_file << "pyMPI SALOME_ContainerPy.py ";
+        o << " pyMPI SALOME_ContainerPy.py ";
       else
-        //command += "SALOME_MPIContainer ";
-        command_file << "SALOME_MPIContainer ";
+        o << " SALOME_MPIContainer ";
     }
 
   else
     {
-      //command="";
       std::string wdir=params.workingdir.in();
       if(wdir != "")
         {
@@ -966,13 +732,11 @@ SALOME_ContainerManager::BuildCommandToLaunchLocalContainer
           if(wdir == "$TEMPDIR")
             {
               // a new temporary directory is requested
-              string dir = Kernel_Utils::GetTmpDir();
+              std::string dir = Kernel_Utils::GetTmpDir();
 #ifdef WIN32
-              //command += "cd /d "+ dir +";";
-              command_file << "cd /d " << dir << endl;
+              o << "cd /d " << dir << std::endl;
 #else
-              //command = "cd "+ dir +";";
-              command_file << "cd " << dir << ";";
+              o << "cd " << dir << ";";
 #endif
 
             }
@@ -980,35 +744,26 @@ SALOME_ContainerManager::BuildCommandToLaunchLocalContainer
             {
               // a permanent directory is requested use it or create it
 #ifdef WIN32
-              //command="mkdir " + wdir;
-              command_file << "mkdir " + wdir << endl;
-              command_file << "cd /D " + wdir << endl;
+              o << "mkdir " + wdir << std::endl;
+              o << "cd /D " + wdir << std::endl;
 #else
-              //command="mkdir -p " + wdir + " && cd " + wdir + ";";
-              command_file << "mkdir -p " << wdir << " && cd " << wdir + ";";
+              o << "mkdir -p " << wdir << " && cd " << wdir + ";";
 #endif
             }
         }
       if (isPythonContainer(params.container_name))
-        //command += "SALOME_ContainerPy.py ";
-        command_file << "SALOME_ContainerPy.py ";
+        o << "SALOME_ContainerPy.py ";
       else
-        //command += container_exe + " ";
-        command_file << container_exe + " ";
+        o << container_exe + " ";
 
     }
 
+  o << _NS->ContainerName(params);
+  o << " -";
+  AddOmninamesParams(o);
 
-  /*command += _NS->ContainerName(params);
-  command += " -id ";
-  sprintf(idc,"%ld",id);
-  command += idc;
-  command += " -";  
-  AddOmninamesParams(command);*/
-
-  command_file << _NS->ContainerName(params);
-  command_file << " -id " << id << " -";
-  AddOmninamesParams(command_file);
+  std::ofstream command_file( _TmpFileName.c_str() );
+  command_file << o.str();
   command_file.close();
 
 #ifndef WIN32
@@ -1017,6 +772,7 @@ SALOME_ContainerManager::BuildCommandToLaunchLocalContainer
   command = _TmpFileName;
 
   MESSAGE("Command is file ... " << command);
+  MESSAGE("Command is ... " << o.str());
   return command;
 }
 
@@ -1027,24 +783,24 @@ SALOME_ContainerManager::BuildCommandToLaunchLocalContainer
  */ 
 //=============================================================================
 
-void SALOME_ContainerManager::RmTmpFile()
+void SALOME_ContainerManager::RmTmpFile(std::string& tmpFileName)
 {
-  int lenght = _TmpFileName.size();
+  int lenght = tmpFileName.size();
   if ( lenght  > 0)
     {
 #ifdef WIN32
-      string command = "del /F ";
+      std::string command = "del /F ";
 #else
-      string command = "rm ";      
+      std::string command = "rm ";      
 #endif
       if ( lenght > 4 )
-        command += _TmpFileName.substr(0, lenght - 3 );
+        command += tmpFileName.substr(0, lenght - 3 );
       else
-        command += _TmpFileName;
+        command += tmpFileName;
       command += '*';
       system(command.c_str());
       //if dir is empty - remove it
-      string tmp_dir = Kernel_Utils::GetDirByPath( _TmpFileName );
+      std::string tmp_dir = Kernel_Utils::GetDirByPath( tmpFileName );
       if ( Kernel_Utils::IsEmptyDir( tmp_dir ) )
         {
 #ifdef WIN32
@@ -1063,13 +819,25 @@ void SALOME_ContainerManager::RmTmpFile()
  */ 
 //=============================================================================
 
-void SALOME_ContainerManager::AddOmninamesParams(string& command) const
-  {
-    CORBA::String_var iorstr = _NS->getIORaddr();
-    command += "ORBInitRef NameService=";
-    command += iorstr;
-  }
+void SALOME_ContainerManager::AddOmninamesParams(std::string& command) const
+{
+  CORBA::String_var iorstr = _NS->getIORaddr();
+  command += "ORBInitRef NameService=";
+  command += iorstr;
+}
 
+//=============================================================================
+/*!
+ *  add to command all options relative to naming service.
+ */ 
+//=============================================================================
+
+void SALOME_ContainerManager::AddOmninamesParams(std::ofstream& fileStream) const
+{
+  CORBA::String_var iorstr = _NS->getIORaddr();
+  fileStream << "ORBInitRef NameService=";
+  fileStream << iorstr;
+}
 
 //=============================================================================
 /*!
@@ -1077,12 +845,12 @@ void SALOME_ContainerManager::AddOmninamesParams(string& command) const
  */ 
 //=============================================================================
 
-void SALOME_ContainerManager::AddOmninamesParams(ofstream& fileStream) const
-  {
-    CORBA::String_var iorstr = _NS->getIORaddr();
-    fileStream << "ORBInitRef NameService=";
-    fileStream << iorstr;
-  }
+void SALOME_ContainerManager::AddOmninamesParams(std::ostringstream& oss) const
+{
+  CORBA::String_var iorstr = _NS->getIORaddr();
+  oss << "ORBInitRef NameService=";
+  oss << iorstr;
+}
 
 //=============================================================================
 /*!
@@ -1090,18 +858,17 @@ void SALOME_ContainerManager::AddOmninamesParams(ofstream& fileStream) const
  */ 
 //=============================================================================
 
-string SALOME_ContainerManager::BuildTemporaryFileName() const
-  {
-    //build more complex file name to support multiple salome session
-    string aFileName = Kernel_Utils::GetTmpFileName();
+std::string SALOME_ContainerManager::BuildTemporaryFileName() const
+{
+  //build more complex file name to support multiple salome session
+  std::string aFileName = Kernel_Utils::GetTmpFileName();
 #ifndef WIN32
-    aFileName += ".sh";
+  aFileName += ".sh";
 #else
-    aFileName += ".bat";
+  aFileName += ".bat";
 #endif
-    return aFileName;
-  }
-
+  return aFileName;
+}
 
 //=============================================================================
 /*!
@@ -1113,22 +880,22 @@ string SALOME_ContainerManager::BuildTemporaryFileName() const
  */ 
 //=============================================================================
 
-string
+std::string
 SALOME_ContainerManager::BuildTempFileToLaunchRemoteContainer
-(const string& machine,
- const Engines::MachineParameters& params) throw(SALOME_Exception)
+(const std::string& resource_name,
+ const Engines::ContainerParameters& params) throw(SALOME_Exception)
 {
   int status;
 
   _TmpFileName = BuildTemporaryFileName();
-  ofstream tempOutputFile;
-  tempOutputFile.open(_TmpFileName.c_str(), ofstream::out );
-  const ParserResourcesType& resInfo = _ResManager->GetImpl()->GetResourcesList(machine);
-  tempOutputFile << "#! /bin/sh" << endl;
+  std::ofstream tempOutputFile;
+  tempOutputFile.open(_TmpFileName.c_str(), std::ofstream::out );
+  const ParserResourcesType& resInfo = _ResManager->GetImpl()->GetResourcesDescr(resource_name);
+  tempOutputFile << "#! /bin/sh" << std::endl;
 
   // --- set env vars
 
-  tempOutputFile << "export SALOME_trace=local" << endl; // mkr : 27.11.2006 : PAL13967 - Distributed supervision graphs - Problem with "SALOME_trace"
+  tempOutputFile << "export SALOME_trace=local" << std::endl; // mkr : 27.11.2006 : PAL13967 - Distributed supervision graphs - Problem with "SALOME_trace"
   //tempOutputFile << "source " << resInfo.PreReqFilePath << endl;
 
   // ! env vars
@@ -1138,20 +905,23 @@ SALOME_ContainerManager::BuildTempFileToLaunchRemoteContainer
       tempOutputFile << "mpirun -np ";
       int nbproc;
 
-      if ( (params.nb_node <= 0) && (params.nb_proc_per_node <= 0) )
+      if ( params.nb_proc <= 0 )
         nbproc = 1;
-      else if ( params.nb_node == 0 )
-        nbproc = params.nb_proc_per_node;
-      else if ( params.nb_proc_per_node == 0 )
-        nbproc = params.nb_node;
       else
-        nbproc = params.nb_node * params.nb_proc_per_node;
+        nbproc = params.nb_proc;
 
       std::ostringstream o;
 
       tempOutputFile << nbproc << " ";
 #ifdef WITHLAM
       tempOutputFile << "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
+#elif defined(WITHOPENMPI)
+      if( getenv("OMPI_URI_FILE") == NULL )
+        tempOutputFile << "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace";
+      else{
+        tempOutputFile << "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace -ompi-server file:";
+        tempOutputFile << getenv("OMPI_URI_FILE");
+      }
 #endif
     }
 
@@ -1160,9 +930,9 @@ SALOME_ContainerManager::BuildTempFileToLaunchRemoteContainer
   if (params.isMPI)
     {
       if (isPythonContainer(params.container_name))
-        tempOutputFile << "pyMPI SALOME_ContainerPy.py ";
+        tempOutputFile << " pyMPI SALOME_ContainerPy.py ";
       else
-        tempOutputFile << "SALOME_MPIContainer ";
+        tempOutputFile << " SALOME_MPIContainer ";
     }
 
   else
@@ -1175,7 +945,7 @@ SALOME_ContainerManager::BuildTempFileToLaunchRemoteContainer
 
   tempOutputFile << _NS->ContainerName(params) << " -";
   AddOmninamesParams(tempOutputFile);
-  tempOutputFile << " &" << endl;
+  tempOutputFile << " &" << std::endl;
   tempOutputFile.flush();
   tempOutputFile.close();
 #ifndef WIN32
@@ -1184,15 +954,15 @@ SALOME_ContainerManager::BuildTempFileToLaunchRemoteContainer
 
   // --- Build command
 
-  string command;
+  std::string command;
 
   if (resInfo.Protocol == rsh)
     {
       command = "rsh ";
-      string commandRcp = "rcp ";
+      std::string commandRcp = "rcp ";
       commandRcp += _TmpFileName;
       commandRcp += " ";
-      commandRcp += machine;
+      commandRcp += resInfo.HostName;
       commandRcp += ":";
       commandRcp += _TmpFileName;
       status = system(commandRcp.c_str());
@@ -1201,10 +971,10 @@ SALOME_ContainerManager::BuildTempFileToLaunchRemoteContainer
   else if (resInfo.Protocol == ssh)
     {
       command = "ssh ";
-      string commandRcp = "scp ";
+      std::string commandRcp = "scp ";
       commandRcp += _TmpFileName;
       commandRcp += " ";
-      commandRcp += machine;
+      commandRcp += resInfo.HostName;
       commandRcp += ":";
       commandRcp += _TmpFileName;
       status = system(commandRcp.c_str());
@@ -1215,7 +985,7 @@ SALOME_ContainerManager::BuildTempFileToLaunchRemoteContainer
   if(status)
     throw SALOME_Exception("Error of connection on remote host");    
 
-  command += machine;
+  command += resInfo.HostName;
   _CommandForRemAccess = command;
   command += " ";
   command += _TmpFileName;
@@ -1226,149 +996,775 @@ SALOME_ContainerManager::BuildTempFileToLaunchRemoteContainer
 
 }
 
+std::string SALOME_ContainerManager::GetMPIZeroNode(const std::string machine, const std::string machinesFile)
+{
+  int status;
+  std::string zeronode;
+  std::string command;
+  std::string tmpFile = BuildTemporaryFileName();
+
+  if( getenv("LIBBATCH_NODEFILE") == NULL )
+    {
+      if (_isAppliSalomeDefined)
+        {
+          const ParserResourcesType& resInfo = _ResManager->GetImpl()->GetResourcesDescr(machine);
+
+          if (resInfo.Protocol == rsh)
+            command = "rsh ";
+          else if (resInfo.Protocol == ssh)
+            command = "ssh ";
+          else
+            throw SALOME_Exception("Unknown protocol");
+
+          if (resInfo.UserName != "")
+            {
+              command += "-l ";
+              command += resInfo.UserName;
+              command += " ";
+            }
+
+          command += resInfo.HostName;
+          command += " ";
+
+          if (resInfo.AppliPath != "")
+            command += resInfo.AppliPath; // path relative to user@machine $HOME
+          else
+            {
+              ASSERT(getenv("APPLI"));
+              command += getenv("APPLI"); // path relative to user@machine $HOME
+            }
+
+          command += "/runRemote.sh ";
+
+          ASSERT(getenv("NSHOST")); 
+          command += getenv("NSHOST"); // hostname of CORBA name server
+
+          command += " ";
+          ASSERT(getenv("NSPORT"));
+          command += getenv("NSPORT"); // port of CORBA name server
+
+          command += " mpirun -np 1 hostname > " + tmpFile;
+        }
+      else
+        command = "mpirun -np 1 hostname > " + tmpFile;
+    }
+  else
+    command = "mpirun -np 1 -machinefile " + machinesFile + " hostname > " + tmpFile;
+
+  status = system(command.c_str());
+  if( status == 0 ){
+    std::ifstream fp(tmpFile.c_str(),std::ios::in);
+    while(fp >> zeronode);
+  }
+
+  RmTmpFile(tmpFile);
+
+  return zeronode;
+}
+
+std::string SALOME_ContainerManager::machinesFile(const int nbproc)
+{
+  std::string tmp;
+  std::string nodesFile = getenv("LIBBATCH_NODEFILE");
+  std::string machinesFile = Kernel_Utils::GetTmpFileName();
+  std::ifstream fpi(nodesFile.c_str(),std::ios::in);
+  std::ofstream fpo(machinesFile.c_str(),std::ios::out);
+
+  _numInstanceMutex.lock();
+
+  for(int i=0;i<_nbprocUsed;i++)
+    fpi >> tmp;
+
+  for(int i=0;i<nbproc;i++)
+    if( fpi >> tmp )
+      fpo << tmp << std::endl;
+    else
+      throw SALOME_Exception("You ask more processes than batch session have allocated!");
+
+  _nbprocUsed += nbproc;
+  fpi.close();
+  fpo.close();
+
+  _numInstanceMutex.unlock();
+
+  return machinesFile;
+
+}
+
+bool 
+SALOME_ContainerManager::checkPaCOParameters(Engines::ContainerParameters & params, std::string resource_selected)
+{
+  bool result = true;
+  // Step 1 : check ContainerParameters
+  // Check container_name, has to be defined
+  if (std::string(params.container_name.in()) == "")
+  {
+    INFOS("[checkPaCOParameters] You must define a container_name to launch a PaCO++ container");
+    result = false;
+  }
+  // Check parallelLib
+  std::string parallelLib = params.parallelLib.in();
+  if (parallelLib != "Mpi" && parallelLib != "Dummy")
+  {
+    INFOS("[checkPaCOParameters] parallelLib is not correctly defined");
+    INFOS("[checkPaCOParameters] you can chosse between: Mpi and Dummy");
+    INFOS("[checkPaCOParameters] you entered: " << parallelLib);
+    result = false;
+  }
+  // Check nb_proc
+  if (params.nb_proc <= 0)
+  {
+    INFOS("[checkPaCOParameters] You must define a nb_proc > 0");
+    result = false;
+  }
+
+  // Step 2 : check resource_selected
+  Engines::ResourceDefinition_var resource_definition = _ResManager->GetResourceDefinition(resource_selected.c_str());
+  std::string protocol = resource_definition->protocol.in();
+  std::string username = resource_definition->username.in();
+  std::string applipath = resource_definition->applipath.in();
+
+  if (protocol == "" || username == "" || applipath == "")
+  {
+    INFOS("[checkPaCOParameters] resource selected is not well defined");
+    INFOS("[checkPaCOParameters] resource name: " << resource_definition->name.in());
+    INFOS("[checkPaCOParameters] resource hostname: " << resource_definition->hostname.in());
+    INFOS("[checkPaCOParameters] resource protocol: " << protocol);
+    INFOS("[checkPaCOParameters] resource username: " << username);
+    INFOS("[checkPaCOParameters] resource applipath: " << applipath);
+    result = false;
+  }
+
+  return result;
+}
+#ifdef WITH_PACO_PARALLEL
+
 //=============================================================================
-/*! Creates a command line that the container manager uses to launch
- * a parallel container.
- */ 
+/*! CORBA Method:
+ *  Start a suitable PaCO++ Parallel Container in a list of machines.
+ *  \param params           Container Parameters required for the container
+ *  \return CORBA container reference.
+ */
 //=============================================================================
-string 
-SALOME_ContainerManager::BuildCommandToLaunchLocalParallelContainer(const std::string& exe_name,
-                                                                   const Engines::MachineParameters& params,
-                                                                   const std::string& log)
+Engines::Container_ptr
+SALOME_ContainerManager::StartPaCOPPContainer(const Engines::ContainerParameters& params_const,
+                                              std::string resource_selected)
 {
-  // This method knows the differences between the proxy and the nodes.
-  // nb_component_nodes is not used in the same way if it is a proxy or 
-  // a node.
-
-  string command;
-  string parallelLib(CORBA::string_dup(params.parallelLib));
-  string hostname(CORBA::string_dup(params.hostname));
-  int par = exe_name.find("Proxy");
-  int nbproc = params.nb_component_nodes;
-  char buffer [33];
-  sprintf(buffer,"%d",nbproc);
-
-  Engines::MachineParameters_var rtn = new Engines::MachineParameters();
-  rtn->container_name = params.container_name;
-  rtn->hostname = params.hostname;
-  rtn->OS = params.OS;
-  rtn->mem_mb = params.mem_mb;
-  rtn->cpu_clock = params.cpu_clock;
-  rtn->nb_proc_per_node = params.nb_proc_per_node;
-  rtn->nb_node = params.nb_node;
-  rtn->isMPI = params.isMPI;
-
-  string real_exe_name  = exe_name + parallelLib;
-
-  if (parallelLib == "Dummy")
+  CORBA::Object_var obj;
+  PaCO::InterfaceManager_var container_proxy;
+  Engines::Container_ptr ret = Engines::Container::_nil();
+  Engines::ContainerParameters params(params_const);
+  params.resource_params.name = CORBA::string_dup(resource_selected.c_str());
+
+  // Step 0 : Check parameters
+  if (!checkPaCOParameters(params, resource_selected))
   {
-    //command = "gdb --args ";
-    //command = "valgrind --tool=memcheck --log-file=val_log ";
-    //command += real_exe_name;
+    INFOS("[StartPaCOPPContainer] check parameters failed ! see logs...");
+    return ret;
+  }
 
-    command = real_exe_name;
+  // Step 1 : Starting a new parallel container !
+  INFOS("[StartPaCOPPContainer] Starting a PaCO++ parallel container");
+  INFOS("[StartPaCOPPContainer] on resource : " << resource_selected);
 
-    command += " " + _NS->ContainerName(rtn);
-    command += " " + parallelLib;
-    command += " " + hostname;
-    command += " -";
-    AddOmninamesParams(command);
+  // Step 2 : Get a MachineFile for the parallel container
+  std::string machine_file_name = _ResManager->getMachineFile(resource_selected, 
+                                                              params.nb_proc,
+                                                              params.parallelLib.in());
+
+  if (machine_file_name == "")
+  {
+    INFOS("[StartPaCOPPContainer] Machine file generation failed");
+    return ret;
+  }
+
+  // Step 3 : starting parallel container proxy
+  std::string command_proxy("");
+  std::string proxy_machine;
+  try 
+  {
+    command_proxy = BuildCommandToLaunchPaCOProxyContainer(params, machine_file_name, proxy_machine);
+  }
+  catch(const SALOME_Exception & ex)
+  {
+    INFOS("[StartPaCOPPContainer] Exception in BuildCommandToLaunchPaCOContainer");
+    INFOS(ex.what());
+    return ret;
+  }
+  obj = LaunchPaCOProxyContainer(command_proxy, params, proxy_machine);
+  if (CORBA::is_nil(obj))
+  {
+    INFOS("[StartPaCOPPContainer] LaunchPaCOContainer for proxy returns NIL !");
+    return ret;
+  }
+  container_proxy = PaCO::InterfaceManager::_narrow(obj);
+  MESSAGE("[StartPaCOPPContainer] PaCO container proxy is launched");
+
+  // Step 4 : starting parallel container nodes
+  std::string command_nodes("");
+  SALOME_ContainerManager::actual_launch_machine_t nodes_machines;
+  try 
+  {
+    command_nodes = BuildCommandToLaunchPaCONodeContainer(params, machine_file_name, nodes_machines, proxy_machine);
+  }
+  catch(const SALOME_Exception & ex)
+  {
+    INFOS("[StarPaCOPPContainer] Exception in BuildCommandToLaunchPaCONodeContainer");
+    INFOS(ex.what());
+    return ret;
   }
 
-  else if (parallelLib == "Mpi")
+  std::string container_generic_node_name = std::string(params.container_name.in()) + std::string("Node");
+  bool result = LaunchPaCONodeContainer(command_nodes, params, container_generic_node_name, nodes_machines);
+  if (!result)
   {
-    // Step 1 : check if MPI is started
-    if (_MpiStarted == false)
+    INFOS("[StarPaCOPPContainer] LaunchPaCONodeContainer failed !");
+    // Il faut tuer le proxy
+    try 
+    {
+      Engines::Container_var proxy = Engines::Container::_narrow(container_proxy);
+      proxy->Shutdown();
+    }
+    catch (...)
     {
-      startMPI();
+      INFOS("[StarPaCOPPContainer] Exception catched from proxy Shutdown...");
     }
+    return ret;
+  }
 
-    if (par < 0)
+  // Step 4 : connecting nodes and the proxy to actually create a parallel container
+  for (int i = 0; i < params.nb_proc; i++) 
+  {
+    std::ostringstream tmp;
+    tmp << i;
+    std::string proc_number = tmp.str();
+    std::string container_node_name = container_generic_node_name + proc_number;
+
+    std::string theNodeMachine(nodes_machines[i]);
+    std::string containerNameInNS = _NS->BuildContainerNameForNS(container_node_name.c_str(), theNodeMachine.c_str());
+    obj = _NS->Resolve(containerNameInNS.c_str());
+    if (CORBA::is_nil(obj)) 
+    {
+      INFOS("[StarPaCOPPContainer] CONNECTION FAILED From Naming Service !");
+      INFOS("[StarPaCOPPContainer] Container name is " << containerNameInNS);
+      return ret;
+    }
+    try
+    {
+      MESSAGE("[StarPaCOPPContainer] Deploying node : " << container_node_name);
+      PaCO::InterfaceParallel_var node = PaCO::InterfaceParallel::_narrow(obj);
+      node->deploy();
+      MESSAGE("[StarPaCOPPContainer] node " << container_node_name << " is deployed");
+    }
+    catch(CORBA::SystemException& e)
     {
-      // Nodes case
-
-      command = "mpiexec -np " + string(buffer) + " ";
-//      command += "gdb --args ";
-      command += real_exe_name;
-      command += " " + _NS->ContainerName(rtn);
-      command += " " + parallelLib;
-      command += " " + hostname;
-      command += " -";
-      AddOmninamesParams(command);
+      INFOS("[StarPaCOPPContainer] Exception in deploying node : " << containerNameInNS);
+      INFOS("CORBA::SystemException : " << e);
+      return ret;
     }
-    else                                          
+    catch(CORBA::Exception& e)
     {
-      // Proxy case
-      command = "mpiexec -np 1 ";
-      command += real_exe_name;
-      command += " " + _NS->ContainerName(rtn);
-      command += " " + string(buffer);
-      command += " " + parallelLib;
-      command += " " + hostname;
-      command += " -";
-      AddOmninamesParams(command);
+      INFOS("[StarPaCOPPContainer] Exception in deploying node : " << containerNameInNS);
+      INFOS("CORBA::Exception" << e);
+      return ret;
+    }
+    catch(...)
+    {
+      INFOS("[StarPaCOPPContainer] Exception in deploying node : " << containerNameInNS);
+      INFOS("Unknown exception !");
+      return ret;
     }
   }
-  else
+
+  // Step 5 : starting parallel container
+  try 
+  {
+    MESSAGE ("[StarPaCOPPContainer] Starting parallel object");
+    container_proxy->start();
+    MESSAGE ("[StarPaCOPPContainer] Parallel object is started");
+    ret = Engines::Container::_narrow(container_proxy);
+  }
+  catch(CORBA::SystemException& e)
+  {
+    INFOS("Caught CORBA::SystemException. : " << e);
+  }
+  catch(PortableServer::POA::ServantAlreadyActive&)
   {
-    std::string message("Unknown parallelLib" + parallelLib);
-    throw SALOME_Exception(message.c_str());
+    INFOS("Caught CORBA::ServantAlreadyActiveException");
   }
+  catch(CORBA::Exception&)
+  {
+    INFOS("Caught CORBA::Exception.");
+  }
+  catch(std::exception& exc)
+  {
+    INFOS("Caught std::exception - "<<exc.what()); 
+  }
+  catch(...)
+  {
+    INFOS("Caught unknown exception.");
+  }
+  return ret;
+}
 
-  // log choice
-  if (log == "default")
+std::string 
+SALOME_ContainerManager::BuildCommandToLaunchPaCOProxyContainer(const Engines::ContainerParameters& params,
+                                                                std::string machine_file_name,
+                                                                std::string & proxy_hostname)
+{
+  // In the proxy case, we always launch a Dummy Proxy
+  std::string exe_name = "SALOME_ParallelContainerProxyDummy";
+  std::string container_name = params.container_name.in();
+
+  // Convert nb_proc in string
+  std::ostringstream tmp_string;
+  tmp_string << params.nb_proc;
+  std::string nb_proc_str = tmp_string.str();
+
+  // Get resource definition
+  Engines::ResourceDefinition_var resource_definition = 
+    _ResManager->GetResourceDefinition(params.resource_params.name);
+
+  // Choose hostname
+  std::string hostname;
+  std::ifstream machine_file(machine_file_name.c_str());
+  std::getline(machine_file, hostname, ' ');
+  size_t found = hostname.find('\n');
+  if (found!=std::string::npos)
+    hostname.erase(found, 1); // Remove \n
+  proxy_hostname = hostname;
+  MESSAGE("[BuildCommandToLaunchPaCOProxyContainer] machine file name extracted is " << hostname);
+
+  // Remote execution
+  bool remote_execution = false;
+  if (hostname != std::string(Kernel_Utils::GetHostname()))
   {
-    command += " > /tmp/";
-    command += _NS->ContainerName(rtn);
-    command += "_";
-    command += Kernel_Utils::GetHostname();
-    command += "_";
-    command += getenv( "USER" ) ;
-    command += ".log 2>&1 &" ;
+    MESSAGE("[BuildCommandToLaunchPaCOProxyContainer] remote machine case detected !");
+    remote_execution = true;
   }
-  if (log == "xterm")
+  
+  // Log environnement
+  std::string log_type("");
+  char * get_val = getenv("PARALLEL_LOG");
+  if (get_val)
+    log_type = get_val;
+
+  // Generating the command
+  std::string command_begin("");
+  std::string command_end("");
+  std::ostringstream command;
+
+  LogConfiguration(log_type, "proxy", container_name, hostname, command_begin, command_end);
+  command << command_begin;
+
+  // Adding connection command
+  // We can only have a remote execution with
+  // a SALOME application
+  if (remote_execution)
   {
-    command = "/usr/X11R6/bin/xterm -e \"export LD_LIBRARY_PATH=$LD_LIBRARY_PATH; export PATH=$PATH;  " 
-             + command + " \" &";
-//           + command + "; echo $LD_LIBRARY_PATH; cat \" &";
+    ASSERT(getenv("NSHOST")); 
+    ASSERT(getenv("NSPORT"));
+
+    command << resource_definition->protocol.in();
+    command << " -l ";
+    command << resource_definition->username.in();
+    command << " " << hostname;
+    command << " " << resource_definition->applipath.in();
+    command << "/runRemote.sh ";
+    command << getenv("NSHOST") << " "; // hostname of CORBA name server
+    command << getenv("NSPORT") << " "; // port of CORBA name server
   }
-  return command;
 
-/*  if (log == "xterm")
+  command << exe_name;
+  command << " " << container_name;
+  command << " Dummy";
+  command << " " << hostname;
+  command << " " << nb_proc_str;
+  command << " -";
+  AddOmninamesParams(command);
+
+  // Final command
+  command << command_end;
+  MESSAGE("[BuildCommandToLaunchPaCOProxyContainer] Command is: " << command.str());
+
+  return command.str();
+}
+
+std::string 
+SALOME_ContainerManager::BuildCommandToLaunchPaCONodeContainer(const Engines::ContainerParameters& params,
+                                                               const std::string & machine_file_name,
+                                                               SALOME_ContainerManager::actual_launch_machine_t & vect_machine,
+                                                               const std::string & proxy_hostname)
+{
+  // Name of exe
+  std::string exe_name = "SALOME_ParallelContainerNode";
+  exe_name += params.parallelLib.in();
+  std::string container_name = params.container_name.in();
+
+  // Convert nb_proc in string
+  std::ostringstream nb_proc_stream;
+  nb_proc_stream << params.nb_proc;
+
+  // Get resource definition
+  Engines::ResourceDefinition_var resource_definition = 
+    _ResManager->GetResourceDefinition(params.resource_params.name);
+  
+  // Log environnement
+  std::string log_type("");
+  char * get_val = getenv("PARALLEL_LOG");
+  if (get_val)
+    log_type = get_val;
+
+  // Now the command is different according to paralleLib
+  std::ostringstream command_nodes;
+  std::ifstream machine_file(machine_file_name.c_str());
+  if (std::string(params.parallelLib.in()) == "Dummy")
+  {
+    for (int i= 0; i < params.nb_proc; i++)
+    {
+      // Choose hostname
+      std::string hostname;
+      std::getline(machine_file, hostname);
+      MESSAGE("[BuildCommandToLaunchPaCONodeContainer] machine file name extracted is " << hostname);
+
+      // Remote execution
+      bool remote_execution = false;
+      if (hostname != std::string(Kernel_Utils::GetHostname()))
+      {
+        MESSAGE("[BuildCommandToLaunchPaCONodeContainer] remote machine case detected !");
+        remote_execution = true;
+      }
+
+      // For each node we have a new command
+      // Generating the command
+      std::ostringstream command_node_stream;
+      std::string command_node_begin("");
+      std::string command_node_end("");
+      std::ostringstream node_number;
+      node_number << i;
+      std::string container_node_name = container_name + node_number.str();
+      LogConfiguration(log_type, "node", container_node_name, hostname, command_node_begin, command_node_end);
+
+      // Adding connection command
+      // We can only have a remote execution with
+      // a SALOME application
+      if (remote_execution)
+      {
+        ASSERT(getenv("NSHOST")); 
+        ASSERT(getenv("NSPORT"));
+
+        command_node_stream << resource_definition->protocol.in();
+        command_node_stream << " -l ";
+        command_node_stream << resource_definition->username.in();
+        command_node_stream << " " << hostname;
+        command_node_stream << " " << resource_definition->applipath.in();
+        command_node_stream << "/runRemote.sh ";
+        command_node_stream << getenv("NSHOST") << " "; // hostname of CORBA name server
+        command_node_stream << getenv("NSPORT") << " "; // port of CORBA name server
+      }
+
+      command_node_stream << exe_name;
+      command_node_stream << " " << container_name;
+      command_node_stream << " " << params.parallelLib.in();
+      command_node_stream << " " << proxy_hostname;
+      command_node_stream << " " << node_number.str();
+      command_node_stream << " -";
+      AddOmninamesParams(command_node_stream);
+
+      command_nodes << command_node_begin << command_node_stream.str() << command_node_end;
+      vect_machine.push_back(hostname);
+    }
+  }
+
+  else if (std::string(params.parallelLib.in()) == "Mpi")
   {
-    command = "/usr/X11R6/bin/xterm -e \"export LD_LIBRARY_PATH=$LD_LIBRARY_PATH; export PATH=$PATH; echo $LD_LIBRARY_PATH; echo $PATH; " + command + "; cat \" &";
+    // Choose hostname
+    std::string hostname;
+    std::getline(machine_file, hostname, ' ');
+    MESSAGE("[BuildCommandToLaunchPaCONodeContainer] machine file name extracted is " << hostname);
+
+    // Remote execution
+    bool remote_execution = false;
+    if (hostname != std::string(Kernel_Utils::GetHostname()))
+    {
+      MESSAGE("[BuildCommandToLaunchPaCONodeContainer] remote machine case detected !");
+      remote_execution = true;
+    }
+
+    // In case of Mpi and Remote, we copy machine_file in the applipath
+    // scp mpi_machine_file user@machine:Path
+    std::ostringstream command_remote_stream;
+    std::string::size_type last = machine_file_name.find_last_of("/");
+    if (last == std::string::npos)
+      last = -1;
+
+    std::string protocol = resource_definition->protocol.in();
+    if (protocol == "rsh")
+      command_remote_stream << "rcp ";
+    else 
+      command_remote_stream << "scp ";
+    command_remote_stream << machine_file_name << " ";
+    command_remote_stream << resource_definition->username.in() << "@";
+    command_remote_stream << hostname << ":" << resource_definition->applipath.in();
+    command_remote_stream <<  "/" << machine_file_name.substr(last+1);
+
+    int status = system(command_remote_stream.str().c_str());
+    if (status == -1)
+    {
+      INFOS("copy of the MPI machine file failed ! - sorry !");
+      return "";
+    }
+
+    // Generating the command
+    std::string command_begin("");
+    std::string command_end("");
+
+    LogConfiguration(log_type, "nodes", container_name, hostname, command_begin, command_end);
+    command_nodes << command_begin;
+
+    // Adding connection command
+    // We can only have a remote execution with
+    // a SALOME application
+    if (remote_execution)
+    {
+      ASSERT(getenv("NSHOST")); 
+      ASSERT(getenv("NSPORT"));
+
+      command_nodes << resource_definition->protocol.in();
+      command_nodes << " -l ";
+      command_nodes << resource_definition->username.in();
+      command_nodes << " " << hostname;
+      command_nodes << " " << resource_definition->applipath.in();
+      command_nodes << "/runRemote.sh ";
+      command_nodes << getenv("NSHOST") << " "; // hostname of CORBA name server
+      command_nodes << getenv("NSPORT") << " "; // port of CORBA name server
+    }
+
+    if (std::string(resource_definition->mpiImpl.in()) == "lam")
+    {
+      command_nodes << "mpiexec -ssi boot ";
+      command_nodes << "-machinefile "  << machine_file_name << " "; 
+      command_nodes <<  "-n " << params.nb_proc;
+    }
+    else
+    {
+      command_nodes << "mpirun -np " << params.nb_proc;
+    }
+    command_nodes << " " << exe_name;
+    command_nodes << " " << container_name;
+    command_nodes << " " << params.parallelLib.in();
+    command_nodes << " " << proxy_hostname;
+    command_nodes << " -";
+    AddOmninamesParams(command_nodes);
+
+    // We don't put hostname, because nodes are registered in the resource of the proxy
+    for (int i= 0; i < params.nb_proc; i++)
+      vect_machine.push_back(proxy_hostname); 
+
+    command_nodes << command_end;
   }
-*/
-/*  command = "cd ; rm " + fichier_commande + "; touch " + \
-            fichier_commande + "; echo \" export LD_LIBRARY_PATH=$LD_LIBRARY_PATH; " + \
-            command + " >& /tmp/ribes_" + fichier_commande + " & \" > " + fichier_commande + ";";
-  command += "ssh cn01 sh " + fichier_commande + " &";
-  cerr << "La commande : " << command << endl;
-*/
+  return command_nodes.str();
 }
 
-void SALOME_ContainerManager::startMPI()
+void
+SALOME_ContainerManager::LogConfiguration(const std::string & log_type,
+                                          const std::string & exe_type,
+                                          const std::string & container_name,
+                                          const std::string & hostname,
+                                          std::string & begin, 
+                                          std::string & end)
 {
-  cerr << "----------------------------------------------" << endl;
-  cerr << "----------------------------------------------" << endl;
-  cerr << "----------------------------------------------" << endl;
-  cerr << "-Only Lam on Localhost is currently supported-" << endl;
-  cerr << "----------------------------------------------" << endl;
-  cerr << "----------------------------------------------" << endl;
-  cerr << "----------------------------------------------" << endl;
-
-  int status = system("lamboot");
-  if (status == -1)
+  if(log_type == "xterm")
   {
-    INFOS("lamboot failed : system command status -1");
+    begin = "xterm -e \"export LD_LIBRARY_PATH=$LD_LIBRARY_PATH; export PATH=$PATH;";
+    end   = "\"&";
   }
-  else if (status == 217)
+  else if(log_type == "xterm_debug")
   {
-    INFOS("lamboot failed : system command status 217");
+    begin = "xterm -e \"export LD_LIBRARY_PATH=$LD_LIBRARY_PATH; export PATH=$PATH;";
+    end   = "; cat \" &";
   }
   else
   {
-    _MpiStarted = true;
+    // default into a file...
+    std::string logFilename = "/tmp/" + container_name + "_" + hostname + "_" + exe_type + "_";
+    logFilename += std::string(getenv("USER")) + ".log";
+    end = " > " + logFilename + " 2>&1 & ";
+  }
+}
+
+CORBA::Object_ptr 
+SALOME_ContainerManager::LaunchPaCOProxyContainer(const std::string& command, 
+                                                  const Engines::ContainerParameters& params,
+                                                  const std::string & hostname)
+{
+  PaCO::InterfaceManager_ptr container_proxy = PaCO::InterfaceManager::_nil();
+
+  MESSAGE("[LaunchPaCOProxyContainer] Launch command");
+  int status = system(command.c_str());
+  if (status == -1) {
+    INFOS("[LaunchPaCOProxyContainer] failed : system command status -1");
+    return container_proxy;
+  }
+  else if (status == 217) {
+    INFOS("[LaunchPaCOProxyContainer] failed : system command status 217");
+    return container_proxy;
+  }
+
+  int count = TIME_OUT_TO_LAUNCH_CONT;
+  CORBA::Object_var obj = CORBA::Object::_nil();
+  std::string containerNameInNS = _NS->BuildContainerNameForNS(params.container_name.in(), 
+                                                               hostname.c_str());
+  MESSAGE("[LaunchParallelContainer]  Waiting for Parallel Container proxy : " << containerNameInNS);
+
+  while (CORBA::is_nil(obj) && count) 
+  {
+    sleep(1);
+    count--;
+    obj = _NS->Resolve(containerNameInNS.c_str());
+  }
+
+  try 
+  {
+    container_proxy = PaCO::InterfaceManager::_narrow(obj);
+  }
+  catch(CORBA::SystemException& e)
+  {
+    INFOS("[StarPaCOPPContainer] Exception in _narrow after LaunchParallelContainer for proxy !");
+    INFOS("CORBA::SystemException : " << e);
+    return container_proxy;
+  }
+  catch(CORBA::Exception& e)
+  {
+    INFOS("[StarPaCOPPContainer] Exception in _narrow after LaunchParallelContainer for proxy !");
+    INFOS("CORBA::Exception" << e);
+    return container_proxy;
+  }
+  catch(...)
+  {
+    INFOS("[StarPaCOPPContainer] Exception in _narrow after LaunchParallelContainer for proxy !");
+    INFOS("Unknown exception !");
+    return container_proxy;
+  }
+  if (CORBA::is_nil(container_proxy))
+  {
+    INFOS("[StarPaCOPPContainer] PaCO::InterfaceManager::_narrow returns NIL !");
+    return container_proxy;
+  }
+  return obj._retn();
+}
+
+//=============================================================================
+/*! This method launches the parallel container.
+ *  It will may be placed on the ressources manager.
+ *
+ * \param command to launch
+ * \param container's parameters
+ * \param name of the container
+ *
+ * \return CORBA container reference
+ */
+//=============================================================================
+bool
+SALOME_ContainerManager::LaunchPaCONodeContainer(const std::string& command, 
+                                                 const Engines::ContainerParameters& params,
+                                                 const std::string& name,
+                                                 SALOME_ContainerManager::actual_launch_machine_t & vect_machine)
+{
+  INFOS("[LaunchPaCONodeContainer] Launch command");
+  int status = system(command.c_str());
+  if (status == -1) {
+    INFOS("[LaunchPaCONodeContainer] failed : system command status -1");
+    return false;
+  }
+  else if (status == 217) {
+    INFOS("[LaunchPaCONodeContainer] failed : system command status 217");
+    return false;
+  }
+
+  INFOS("[LaunchPaCONodeContainer] Waiting for the nodes of the parallel container");
+  // We are waiting all the nodes
+  for (int i = 0; i < params.nb_proc; i++) 
+  {
+    CORBA::Object_var obj = CORBA::Object::_nil();
+    std::string theMachine(vect_machine[i]);
+    // Name of the node
+    std::ostringstream tmp;
+    tmp << i;
+    std::string proc_number = tmp.str();
+    std::string container_node_name = name + proc_number;
+    std::string containerNameInNS = _NS->BuildContainerNameForNS((char*) container_node_name.c_str(), theMachine.c_str());
+    INFOS("[LaunchPaCONodeContainer]  Waiting for Parallel Container node " << containerNameInNS << " on " << theMachine);
+    int count = TIME_OUT_TO_LAUNCH_CONT;
+    while (CORBA::is_nil(obj) && count) {
+      sleep(1) ;
+      count-- ;
+      obj = _NS->Resolve(containerNameInNS.c_str());
+    }
+    if (CORBA::is_nil(obj))
+    {
+      INFOS("[LaunchPaCONodeContainer] Launch of node failed (or not found) !");
+      return false;
+    }
   }
+  return true;
+}
+
+#else
+
+Engines::Container_ptr
+SALOME_ContainerManager::StartPaCOPPContainer(const Engines::ContainerParameters& params,
+                                              std::string resource_selected)
+{
+  Engines::Container_ptr ret = Engines::Container::_nil();
+  INFOS("[StarPaCOPPContainer] is disabled !");
+  INFOS("[StarPaCOPPContainer] recompile SALOME Kernel to enable PaCO++ parallel extension");
+  return ret;
+}
+
+std::string 
+SALOME_ContainerManager::BuildCommandToLaunchPaCOProxyContainer(const Engines::ContainerParameters& params,
+                                                                std::string machine_file_name,
+                                                                std::string & proxy_hostname)
+{
+  return "";
+}
+
+std::string 
+SALOME_ContainerManager::BuildCommandToLaunchPaCONodeContainer(const Engines::ContainerParameters& params,
+                                                               const std::string & machine_file_name,
+                                                               SALOME_ContainerManager::actual_launch_machine_t & vect_machine, 
+                                                               const std::string & proxy_hostname) 
+{
+  return "";
+}
+void 
+SALOME_ContainerManager::LogConfiguration(const std::string & log_type,
+                                          const std::string & exe_type,
+                                          const std::string & container_name,
+                                          const std::string & hostname,
+                                          std::string & begin, 
+                                          std::string & end)
+{
+}
+
+CORBA::Object_ptr 
+SALOME_ContainerManager::LaunchPaCOProxyContainer(const std::string& command, 
+                                                  const Engines::ContainerParameters& params,
+                                                  const std::string& hostname)
+{
+  CORBA::Object_ptr ret = CORBA::Object::_nil();
+  return ret;
 }
 
+bool 
+SALOME_ContainerManager::LaunchPaCONodeContainer(const std::string& command, 
+                        const Engines::ContainerParameters& params,
+                        const std::string& name,
+                        SALOME_ContainerManager::actual_launch_machine_t & vect_machine)
+{
+  return false;
+}
+#endif
+