Salome HOME
[EDF27562] : Fix clustertest
[modules/kernel.git] / src / Container / SALOME_ContainerManager.cxx
index 59693ea01b0b41cdc23ff0f1d055bd35800cafd2..ffb6252f56a11688d73926559f33e589a6c8b5dc 100644 (file)
@@ -1,4 +1,4 @@
-// Copyright (C) 2007-2017  CEA/DEN, EDF R&D, OPEN CASCADE
+// Copyright (C) 2007-2023  CEA, EDF, OPEN CASCADE
 //
 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
 #include "SALOME_LoadRateManager.hxx"
 #include "SALOME_NamingService.hxx"
 #include "SALOME_ResourcesManager_Client.hxx"
+#include "SALOME_Embedded_NamingService.hxx"
 #include "SALOME_ModuleCatalog.hh"
 #include "Basics_Utils.hxx"
 #include "Basics_DirUtils.hxx"
+#include "PythonCppUtils.hxx"
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <signal.h>
 #include "Utils_CorbaException.hxx"
 #include <sstream>
 #include <string>
+#include <queue>
 
 #include <SALOMEconfig.h>
 #include CORBA_CLIENT_HEADER(SALOME_Session)
 
 #ifdef HAVE_MPI2
 #include <mpi.h>
+#include <sys/wait.h>
 #endif
 
 #ifdef WIN32
 #include <process.h>
 #define getpid _getpid
+
+#ifndef S_ISREG
+#define S_ISREG(mode)  (((mode) & S_IFMT) == S_IFREG)
+#endif
+
 #endif
 
 #ifdef WITH_PACO_PARALLEL
@@ -75,7 +84,7 @@ Utils_Mutex SALOME_ContainerManager::_systemMutex;
  */
 //=============================================================================
 
-SALOME_ContainerManager::SALOME_ContainerManager(CORBA::ORB_ptr orb, PortableServer::POA_var poa, SALOME_NamingService *ns)
+SALOME_ContainerManager::SALOME_ContainerManager(CORBA::ORB_ptr orb, PortableServer::POA_var poa, SALOME_NamingService_Abstract *ns)
   : _nbprocUsed(1)
 {
   MESSAGE("constructor");
@@ -93,10 +102,9 @@ SALOME_ContainerManager::SALOME_ContainerManager(CORBA::ORB_ptr orb, PortableSer
   threadPol->destroy();
   PortableServer::ObjectId_var id = _poa->activate_object(this);
   CORBA::Object_var obj = _poa->id_to_reference(id);
-  Engines::ContainerManager_var refContMan =
-    Engines::ContainerManager::_narrow(obj);
-
-  _NS->Register(refContMan,_ContainerManagerNameInNS);
+  Engines::ContainerManager_var refContMan = Engines::ContainerManager::_narrow(obj);
+  if(_NS)
+    _NS->Register(refContMan,_ContainerManagerNameInNS);
   _isAppliSalomeDefined = (GetenvThreadSafe("APPLI") != 0);
 
 #ifdef HAVE_MPI2
@@ -107,40 +115,42 @@ SALOME_ContainerManager::SALOME_ContainerManager(CORBA::ORB_ptr orb, PortableSer
   urifile << GetenvThreadSafeAsString("HOME") << "/.urifile_" << getpid();
   setenv("OMPI_URI_FILE",urifile.str().c_str(),1);
   if( GetenvThreadSafe("OMPI_URI_FILE") != NULL ){
-    // get the pid of all ompi-server
-    std::set<pid_t> thepids1 = getpidofprogram("ompi-server");
-    // launch a new ompi-server
-    std::string command;
-    command = "ompi-server -r ";
-    command += GetenvThreadSafeAsString("OMPI_URI_FILE");
-    int status=SystemThreadSafe(command.c_str());
-    if(status!=0)
-      throw SALOME_Exception("Error when launching ompi-server");
-    // get the pid of all ompi-server
-    std::set<pid_t> thepids2 = getpidofprogram("ompi-server");
-    // my ompi-server is the new one
-    std::set<pid_t>::const_iterator it;
-    for(it=thepids2.begin();it!=thepids2.end();it++)
-      if(thepids1.find(*it) == thepids1.end())
-        _pid_mpiServer = *it;
-    if(_pid_mpiServer < 0)
-      throw SALOME_Exception("Error when getting ompi-server id");
+    // Linux specific code
+    pid_t pid = fork(); // spawn a child process, following code is executed in both processes
+    if ( pid == 0 ) // I'm a child, replace myself with a new ompi-server
+    {
+      std::string uriarg = GetenvThreadSafeAsString("OMPI_URI_FILE");
+      execlp( "ompi-server", "ompi-server", "-r", uriarg.c_str(), NULL );
+      throw SALOME_Exception("Error when launching ompi-server"); // execlp failed
+    }
+    else if ( pid < 0 )
+    {
+      throw SALOME_Exception("fork() failed");
+    }
+    else // I'm a parent
+    {
+      //wait(NULL); // wait(?) for a child end
+      _pid_mpiServer = pid;
+    }
   }
 #elif defined(MPICH)
   _pid_mpiServer = -1;
-  // get the pid of all hydra_nameserver
-  std::set<pid_t> thepids1 = getpidofprogram("hydra_nameserver");
-  // launch a new hydra_nameserver
-  std::string command;
-  command = "hydra_nameserver &";
-  SystemThreadSafe(command.c_str());
-  // get the pid of all hydra_nameserver
-  std::set<pid_t> thepids2 = getpidofprogram("hydra_nameserver");
-  // my hydra_nameserver is the new one
-  std::set<pid_t>::const_iterator it;
-  for(it=thepids2.begin();it!=thepids2.end();it++)
-    if(thepids1.find(*it) == thepids1.end())
-      _pid_mpiServer = *it;
+  // Linux specific code
+  pid_t pid = fork(); // spawn a child process, following code is executed in both processes
+  if ( pid == 0 ) // I'm a child, replace myself with a new hydra_nameserver
+  {
+    execlp( "hydra_nameserver", "hydra_nameserver", NULL );
+    throw SALOME_Exception("Error when launching hydra_nameserver"); // execlp failed
+  }
+  else if ( pid < 0 )
+  {
+    throw SALOME_Exception("fork() failed");
+  }
+  else // I'm a parent
+  {
+    //wait(NULL);
+    _pid_mpiServer = pid;
+  }
 #endif
 #endif
 
@@ -187,7 +197,8 @@ void SALOME_ContainerManager::Shutdown()
 {
   MESSAGE("Shutdown");
   ShutdownContainers();
-  _NS->Destroy_Name(_ContainerManagerNameInNS);
+  if(_NS)
+    _NS->Destroy_Name(_ContainerManagerNameInNS);
   PortableServer::ObjectId_var oid = _poa->servant_to_id(this);
   _poa->deactivate_object(oid);
 }
@@ -201,7 +212,8 @@ void SALOME_ContainerManager::Shutdown()
 void SALOME_ContainerManager::ShutdownContainers()
 {
   MESSAGE("ShutdownContainers");
-
+  if(!_NS)
+    return ;
   SALOME::Session_var session = SALOME::Session::_nil();
   CORBA::Long pid = 0;
   CORBA::Object_var objS = _NS->Resolve("/Kernel/Session");
@@ -227,7 +239,7 @@ void SALOME_ContainerManager::ShutdownContainers()
             if(!CORBA::is_nil(cont) && pid != cont->getPID())
               lstCont.push_back((*iter));
           }
-        catch(const CORBA::Exception& e)
+        catch(const CORBA::Exception&)
           {
             // ignore this entry and continue
           }
@@ -267,6 +279,27 @@ void SALOME_ContainerManager::ShutdownContainers()
   }
 }
 
+void SALOME_ContainerManager::SetOverrideEnvForContainers(const Engines::KeyValDict& env)
+{
+  this->_override_env.clear();
+  auto sz = env.length();
+  for(auto i = 0 ; i < sz ; ++i)
+    _override_env.emplace_back(env[i].key.in(), env[i].val.in());
+}
+
+Engines::KeyValDict *SALOME_ContainerManager::GetOverrideEnvForContainers()
+{
+  std::unique_ptr<Engines::KeyValDict> ret( new Engines::KeyValDict );
+  auto sz = _override_env.size();
+  ret->length(sz);
+  for(auto i = 0 ; i < sz ; ++i)
+  {
+    (*ret)[i].key = CORBA::string_dup( _override_env[i].first.c_str() );
+    (*ret)[i].val = CORBA::string_dup( _override_env[i].second.c_str() );
+  }
+  return ret.release();
+}
+
 //=============================================================================
 //! Give a suitable Container given constraints
 /*! CORBA Method:
@@ -360,7 +393,7 @@ Engines::Container_ptr SALOME_ContainerManager::GiveContainer(const Engines::Con
             break;
           }
       }
-      catch(const SALOME_Exception &ex)
+      catch(const SALOME_Exception &ex) //!< TODO: unused variable
       {
         MESSAGE("[GiveContainer] Exception in ResourceManager find !: " << ex.what());
         return ret;
@@ -372,11 +405,7 @@ Engines::Container_ptr SALOME_ContainerManager::GiveContainer(const Engines::Con
       std::string hostname(resource_definition.HostName);
       std::string containerNameInNS;
       if(params.isMPI){
-        int nbproc;
-        if ( params.nb_proc <= 0 )
-          nbproc = 1;
-        else
-          nbproc = params.nb_proc;
+        int nbproc = params.nb_proc <= 0 ? 1 : params.nb_proc;
         try
         {
           if( GetenvThreadSafe("LIBBATCH_NODEFILE") != NULL )
@@ -431,6 +460,20 @@ Engines::Container_ptr SALOME_ContainerManager::GiveContainer(const Engines::Con
       if (!CORBA::is_nil(cont))
       {
         INFOS("[GiveContainer] container " << containerNameInNS << " launched");
+        std::ostringstream envInfo;
+        std::for_each( _override_env.begin(), _override_env.end(), [&envInfo](const std::pair<std::string,std::string>& p) { envInfo << p.first << " = " << p.second << std::endl; } );
+        INFOS("[GiveContainer] container " << containerNameInNS << " override " << envInfo.str());
+        Engines::FieldsDict envCorba;
+        {
+          auto sz = _override_env.size();
+          envCorba.length(sz);
+          for(auto i = 0 ; i < sz ; ++i)
+          {
+            envCorba[i].key = CORBA::string_dup( _override_env[i].first.c_str() );
+            envCorba[i].value <<= CORBA::string_dup( _override_env[i].second.c_str() );
+          }
+        }
+        cont->override_environment_python( envCorba );
         return cont._retn();
       }
       else
@@ -448,6 +491,18 @@ Engines::Container_ptr SALOME_ContainerManager::GiveContainer(const Engines::Con
   return ret;
 }
 
+std::string SALOME_ContainerManager::GetCppBinaryOfKernelContainer() const
+{
+  std::string ret = this->_isSSL ? "SALOME_Container_No_NS_Serv" : "SALOME_Container";
+  return ret;
+}
+
+std::string SALOME_ContainerManager::GetRunRemoteExecutableScript() const
+{
+  std::string ret = this->_isSSL ? "runRemoteSSL.sh" : "runRemote.sh";
+  return ret;
+}
+
 Engines::Container_ptr
 SALOME_ContainerManager::LaunchContainer(const Engines::ContainerParameters& params,
                                          const std::string & resource_selected,
@@ -464,7 +519,7 @@ SALOME_ContainerManager::LaunchContainer(const Engines::ContainerParameters& par
     // 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
+    std::string container_exe = this->GetCppBinaryOfKernelContainer();
     Engines::ContainerParameters local_params(params);
     int found=0;
     try
@@ -516,27 +571,15 @@ SALOME_ContainerManager::LaunchContainer(const Engines::ContainerParameters& par
     // Only if an application directory is set
     if(hostname != Kernel_Utils::GetHostname() && _isAppliSalomeDefined)
       {
-        // Preparing remote command
-        std::string command = "";
+
         const ParserResourcesType resInfo(_resManager->GetResourceDefinition(resource_selected));
-        command = getCommandToRunRemoteProcess(resInfo.Protocol, resInfo.HostName, resInfo.UserName);
-        if (resInfo.AppliPath != "")
-          command += resInfo.AppliPath;
-        else
-          {
-            ASSERT(GetenvThreadSafe("APPLI"));
-            command += GetenvThreadSafeAsString("APPLI");
-          }
-        command += "/runRemote.sh ";
-        ASSERT(GetenvThreadSafe("NSHOST"));
-        command += GetenvThreadSafeAsString("NSHOST"); // hostname of CORBA name server
-        command += " ";
-        ASSERT(GetenvThreadSafe("NSPORT"));
-        command += GetenvThreadSafeAsString("NSPORT"); // port of CORBA name server
-        command += " \"ls /tmp >/dev/null 2>&1\"";
+        std::string command = getCommandToRunRemoteProcess(resInfo.Protocol, resInfo.HostName, 
+                                                           resInfo.UserName, resInfo.AppliPath);
 
         // Launch remote command
-        int status = SystemThreadSafe(command.c_str());
+          command += " \"ls /tmp >/dev/null 2>&1\"";
+        // Anthony : command is NO MORE launched to improve dramatically time to launch containers
+        int status = 0;
         if (status != 0)
           {
             // Error on resource - cannot launch commands
@@ -561,13 +604,22 @@ SALOME_ContainerManager::LaunchContainer(const Engines::ContainerParameters& par
     MESSAGE("[GiveContainer] Try to launch a new container on " << resource_selected);
     // if a parallel container is launched in batch job, command is: "mpirun -np nbproc -machinefile nodesfile SALOME_MPIContainer"
     if( GetenvThreadSafe("LIBBATCH_NODEFILE") != NULL && params.isMPI )
+    {
       command = BuildCommandToLaunchLocalContainer(params, machFile, container_exe, tmpFileName);
+      MESSAGE("[LaunchContainer] LIBBATCH_NODEFILE : \"" << command << "\"");
+    }
     // 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, tmpFileName);
+      MESSAGE("[LaunchContainer] hostname local : \"" << command << "\"");
+    }
     // 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);
+      MESSAGE("[LaunchContainer] remote : \"" << command << "\"");
+    }
 
     //redirect stdout and stderr in a file
 #ifdef WIN32
@@ -597,7 +649,8 @@ SALOME_ContainerManager::LaunchContainer(const Engines::ContainerParameters& par
     logFilename += ".log" ;
     command += " > " + logFilename + " 2>&1";
     MakeTheCommandToBeLaunchedASync(command);
-
+    
+    MESSAGE("[LaunchContainer] SYSTEM COMMAND that will be launched : \"" << command << "\"");
     // launch container with a system call
     status=SystemThreadSafe(command.c_str());
   }//end of critical of section
@@ -688,7 +741,7 @@ SALOME_ContainerManager::FindContainer(const Engines::ContainerParameters& param
     else
       return Engines::Container::_narrow(obj);
   }
-  catch(const CORBA::Exception& e)
+  catch(const CORBA::Exception&)
   {
     return Engines::Container::_nil();
   }
@@ -706,7 +759,7 @@ bool isPythonContainer(const char* ContainerName)
 {
   return false; // VSR 02/08/2013: Python containers are no more supported
   bool ret = false;
-  int len = strlen(ContainerName);
+  size_t len = strlen(ContainerName);
 
   if (len >= 2)
     if (strcmp(ContainerName + len - 2, "Py") == 0)
@@ -742,85 +795,171 @@ std::string
 SALOME_ContainerManager::BuildCommandToLaunchRemoteContainer(const std::string& resource_name, const Engines::ContainerParameters& params, const std::string& container_exe) const
 {
   std::string command,tmpFileName;
+  const ParserResourcesType resInfo(_resManager->GetResourceDefinition(resource_name));
+  std::string wdir = params.workingdir.in();
   if (!_isAppliSalomeDefined)
-    command = BuildTempFileToLaunchRemoteContainer(resource_name, params, tmpFileName);
+  {
+      MESSAGE("[BuildCommandToLaunchRemoteContainer] NO APPLI MODE : " << " Protocol :" << resInfo.Protocol << " hostname :" << resInfo.HostName << " username : " << resInfo.UserName << " appli : " << resInfo.AppliPath << " wdir : \"" << wdir << "\"");
+      command = getCommandToRunRemoteProcessNoAppli(resInfo.Protocol, resInfo.HostName, 
+                                                    resInfo.UserName, resInfo.AppliPath,
+                                                    wdir);
+  }
   else
   {
-    int nbproc;
-    const ParserResourcesType resInfo(_resManager->GetResourceDefinition(resource_name));
-
-    if (params.isMPI)
-    {
-      if ( params.nb_proc <= 0 )
-        nbproc = 1;
-      else
-        nbproc = params.nb_proc;
+    MESSAGE("[BuildCommandToLaunchRemoteContainer] WITH APPLI MODE : " << " Protocol :" << resInfo.Protocol << " hostname :" << resInfo.HostName << " username : " << resInfo.UserName << " appli : " << resInfo.AppliPath << " wdir : \"" << wdir << "\"");
+    // "ssh -l user machine distantPath/runRemote.sh hostNS portNS WORKINGDIR workingdir
+    //      SALOME_Container containerName -ORBInitRef NameService=IOR:01000..."
+    //  or 
+    //  "ssh -l user machine distantLauncher remote -p hostNS -m portNS -d dir
+    //      --  SALOME_Container contName -ORBInitRef NameService=IOR:01000..."
+    command = getCommandToRunRemoteProcess(resInfo.Protocol, resInfo.HostName, 
+                                           resInfo.UserName, resInfo.AppliPath,
+                                           wdir);
+  }
+  if(params.isMPI)
+  {
+    int nbproc = params.nb_proc <= 0 ? 1 : params.nb_proc;
+    command += " mpirun -np ";
+    std::ostringstream o;
+    o << nbproc << " ";
+    command += o.str();
+#ifdef LAM_MPI
+    command += "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
+#elif defined(OPEN_MPI)
+    if( GetenvThreadSafe("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 += GetenvThreadSafeAsString("OMPI_URI_FILE");
     }
+#elif defined(MPICH)
+    command += "-nameserver " + Kernel_Utils::GetHostname();
+#endif
+    command += " SALOME_MPIContainer ";
+  }
+  else
+    command += " " +container_exe+ " ";
 
-    // "ssh -l user machine distantPath/runRemote.sh hostNS portNS WORKINGDIR workingdir
-    //  SALOME_Container containerName &"
-    command = getCommandToRunRemoteProcess(resInfo.Protocol, resInfo.HostName, resInfo.UserName);
+  command += _NS->ContainerName(params) + " ";
+  if(this->_isSSL)
+  {
+    Engines::EmbeddedNamingService_var ns = GetEmbeddedNamingService();
+    CORBA::String_var iorNS = _orb->object_to_string(ns);
+    command += std::string(iorNS);
+  }
+  else //if(!this->_isSSL)
+  {
+    command += " -";
+    AddOmninamesParams(command);
+  }
+  MESSAGE("command =" << command);
 
-    if (resInfo.AppliPath != "")
-      command += resInfo.AppliPath; // path relative to user@machine $HOME
-    else
+  return command;
+}
+
+//=============================================================================
+//! Return a path to the directory with scripts templates
+/*! 
+ *  \return the path pointed by SALOME_KERNEL_SCRIPTS_DIR environment variable, if it is defined,
+ *  ${KERNEL_ROOT_DIR}/share/salome/resources/separator/kernel/ScriptsTemplate - otherwise
+ */
+//=============================================================================
+std::string getScriptTemplateFilePath()
+{
+  auto parseScriptTemplateFilePath = []() -> std::string
+  {
+    std::string scriptTemplateFilePath = SALOME_ContainerManager::GetenvThreadSafeAsString("SALOME_KERNEL_SCRIPTS_DIR");
+    if (!scriptTemplateFilePath.empty())
     {
-      ASSERT(GetenvThreadSafe("APPLI"));
-      command += GetenvThreadSafeAsString("APPLI"); // path relative to user@machine $HOME
+      return scriptTemplateFilePath;
     }
+    else {
+      return SALOME_ContainerManager::GetenvThreadSafeAsString("KERNEL_ROOT_DIR") +
+             "/share/salome/resources/kernel/ScriptsTemplate";
+    }
+  };
 
-    command += "/runRemote.sh ";
+  static const std::string scriptTemplateFilePath = parseScriptTemplateFilePath();
+  return scriptTemplateFilePath;
+}
 
-    ASSERT(GetenvThreadSafe("NSHOST"));
-    command += GetenvThreadSafeAsString("NSHOST"); // hostname of CORBA name server
+//=============================================================================
+//! Return a command line constructed based on Python scripts templates
+/*! 
+ *  \param theScriptName        the name of Python script template
+ *  \param theScriptParameters  the queue of parameter values
+ *  \return the command line constructed according to the given parameters
+ */
+//=============================================================================
+std::string GetCommandFromTemplate(const std::string& theScriptName,
+                                   std::queue<std::string>& theScriptParameters)
+{
+  std::string command;
+  AutoGIL agil;
+  // manage GIL
 
-    command += " ";
-    ASSERT(GetenvThreadSafe("NSPORT"));
-    command += GetenvThreadSafeAsString("NSPORT"); // port of CORBA name server
+  PyObject* mod(PyImport_ImportModule(theScriptName.c_str()));
+  if (!mod)
+  {
+    PyObject* sys = PyImport_ImportModule("sys");
+    PyObject* sys_path = PyObject_GetAttrString(sys, "path");
+    PyObject* folder_path = PyUnicode_FromString(getScriptTemplateFilePath().c_str());
+    PyList_Append(sys_path, folder_path);
 
-    std::string wdir = params.workingdir.in();
-    if(wdir != "")
-    {
-      command += " WORKINGDIR ";
-      command += " '";
-      if(wdir == "$TEMPDIR")
-        wdir="\\$TEMPDIR";
-      command += wdir; // requested working directory
-      command += "'";
-    }
+    mod = PyImport_ImportModule(theScriptName.c_str());
 
-    if(params.isMPI)
+    Py_XDECREF(folder_path);
+    Py_XDECREF(sys_path);
+    Py_XDECREF(sys);
+  }
+
+  if (mod)
+  {
+    PyObject* meth(PyObject_GetAttrString(mod, "command"));
+    if (!meth)
     {
-      command += " mpirun -np ";
-      std::ostringstream o;
-      o << nbproc << " ";
-      command += o.str();
-#ifdef LAM_MPI
-      command += "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
-#elif defined(OPEN_MPI)
-      if( GetenvThreadSafe("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 += GetenvThreadSafeAsString("OMPI_URI_FILE");
-      }
-#elif defined(MPICH)
-      command += "-nameserver " + Kernel_Utils::GetHostname();
-#endif
-      command += " SALOME_MPIContainer ";
+      Py_XDECREF(mod);
     }
     else
-      command += " " +container_exe+ " ";
+    {
+      int id = -1;
+      PyObject* tuple(PyTuple_New(theScriptParameters.size()));
 
-    command += _NS->ContainerName(params);
-    command += " -";
-    AddOmninamesParams(command);
+      auto insert_parameter = [&tuple, &theScriptParameters, &id]()
+      {
+        if (!theScriptParameters.empty())
+        {
+          PyTuple_SetItem(tuple, ++id, PyUnicode_FromString(theScriptParameters.front().c_str()));
+          theScriptParameters.pop();
+        }
+      };
+
+      while (!theScriptParameters.empty())
+      {
+        insert_parameter();
+      }
+      
+      PyObject *args(PyTuple_New(1));
+      PyTuple_SetItem(args, 0, tuple);
+
+      PyObject *res(PyObject_CallObject(meth, args));
+      if (res)
+      {
+        command = PyUnicode_AsUTF8(res);
+        Py_XDECREF(res);
+      }
 
-    MESSAGE("command =" << command);
+      Py_XDECREF(args);
+      Py_XDECREF(tuple);
+      Py_XDECREF(meth);
+      Py_XDECREF(mod);
+    }
   }
 
+  MESSAGE("Command from template is ... " << command << std::endl);
   return command;
 }
+//=============================================================================
 
 //=============================================================================
 /*!
@@ -829,86 +968,90 @@ SALOME_ContainerManager::BuildCommandToLaunchRemoteContainer(const std::string&
 //=============================================================================
 std::string SALOME_ContainerManager::BuildCommandToLaunchLocalContainer(const Engines::ContainerParameters& params, const std::string& machinesFile, const std::string& container_exe, std::string& tmpFileName) const
 {
-  tmpFileName = BuildTemporaryFileName();
-  std::string command;
-  int nbproc = 0;
-
-  std::ostringstream o;
-
+  // Prepare name of the script to be used
+  std::string script_name = "SALOME_CM_LOCAL_NO_MPI";
   if (params.isMPI)
-    {
-      o << "mpirun -np ";
-
-      if ( params.nb_proc <= 0 )
-        nbproc = 1;
-      else
-        nbproc = params.nb_proc;
-
-      o << nbproc << " ";
-
-      if( GetenvThreadSafe("LIBBATCH_NODEFILE") != NULL )
-        o << "-machinefile " << machinesFile << " ";
-
+  {
 #ifdef LAM_MPI
-      o << "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
+    script_name = "SALOME_CM_LOCAL_MPI_LAN";
 #elif defined(OPEN_MPI)
-      if( GetenvThreadSafe("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 << GetenvThreadSafeAsString("OMPI_URI_FILE");
-        }
+    script_name = "SALOME_CM_LOCAL_MPI_OPENMPI";
 #elif defined(MPICH)
-      o << "-nameserver " + Kernel_Utils::GetHostname();
+    script_name = "SALOME_CM_LOCAL_MPI_MPICH";
 #endif
+  }
+  
+  // Prepare parameters to use in the Python script:
+  // 1. All parameters are strings.
+  // 2. For some booleans use "1" = True, "0" = False.
+  // 3. If a parameter is NULL, then its value is "NULL".
+
+  std::queue<std::string> script_parameters;
+  
+  // ===== Number of processes (key = "nb_proc")
+  script_parameters.push(params.isMPI ? std::to_string(params.nb_proc <= 0 ? 1 : params.nb_proc) : "NULL");
+
+  // ===== Working directory (key = "workdir") and temporary directory flag (key = "isTmpDir")
+  // A working directory is requested
+  std::string workdir = params.workingdir.in();
+  std::string isTmpDir = std::to_string(0);
+  if (workdir == "$TEMPDIR")
+  {
+    // A new temporary directory is requested
+    isTmpDir = std::to_string(1);
+    workdir = Kernel_Utils::GetTmpDir();
+  }
+  script_parameters.push(workdir);
+  script_parameters.push(isTmpDir);
+  
+  // ===== Server name (key = "name_server")
+  script_parameters.push(Kernel_Utils::GetHostname());
+
+  // ===== Container (key = "container")
+  std::string container;
+  if (params.isMPI)
+  {
+    container = isPythonContainer(params.container_name) ? "pyMPI SALOME_ContainerPy.py" : "SALOME_MPIContainer";
+  }
+  else
+  {
+    container = isPythonContainer(params.container_name) ? "SALOME_ContainerPy.py" : container_exe;
+  }
+  script_parameters.push(container);
 
-      if (isPythonContainer(params.container_name))
-        o << " pyMPI SALOME_ContainerPy.py ";
-      else
-        o << " SALOME_MPIContainer ";
-    }
+  // ===== Container name (key = "container_name")
+  script_parameters.push(_NS->ContainerName(params));
 
-  else
-    {
-      std::string wdir=params.workingdir.in();
-      if(wdir != "")
-        {
-          // a working directory is requested
-          if(wdir == "$TEMPDIR")
-            {
-              // a new temporary directory is requested
-              std::string dir = Kernel_Utils::GetTmpDir();
-#ifdef WIN32
-              o << "cd /d " << dir << std::endl;
-#else
-              o << "cd " << dir << ";";
-#endif
+  // ===== LIBBATCH node file (key = "libbatch_nodefile")
+  script_parameters.push(std::to_string(GetenvThreadSafe("LIBBATCH_NODEFILE") != NULL ? 1 : 0));
 
-            }
-          else
-            {
-              // a permanent directory is requested use it or create it
-#ifdef WIN32
-              o << "mkdir " + wdir << std::endl;
-              o << "cd /D " + wdir << std::endl;
-#else
-              o << "mkdir -p " << wdir << " && cd " << wdir + ";";
-#endif
-            }
-        }
+  // ===== Machine file (key = "machine_file")
+  script_parameters.push(machinesFile.empty() ? "NULL" : machinesFile);
 
-      if (isPythonContainer(params.container_name))
-        o << "SALOME_ContainerPy.py ";
-      else
-        o << container_exe + " ";
+  // ===== OMPI uri file (key = "ompi_uri_file")
+  std::string ompi_uri_file = GetenvThreadSafeAsString("OMPI_URI_FILE");
+  script_parameters.push(ompi_uri_file.empty() ? "NULL" : ompi_uri_file);
 
-    }
+  std::string command_from_template = GetCommandFromTemplate(script_name, script_parameters);
 
-  o << _NS->ContainerName(params);
-  o << " -";
-  AddOmninamesParams(o);
+  std::ostringstream o;
+  o << command_from_template << " ";
+  
+  //==================================================================================== */
 
+  if( this->_isSSL )
+  {
+    Engines::EmbeddedNamingService_var ns = GetEmbeddedNamingService();
+    CORBA::String_var iorNS = _orb->object_to_string(ns);
+    o << iorNS;
+  }
+  else
+  {
+    o << "-";
+    AddOmninamesParams(o);
+  }
+  
+  tmpFileName = BuildTemporaryFileName();
   std::ofstream command_file( tmpFileName.c_str() );
   command_file << o.str();
   command_file.close();
@@ -916,8 +1059,8 @@ std::string SALOME_ContainerManager::BuildCommandToLaunchLocalContainer(const En
 #ifndef WIN32
   chmod(tmpFileName.c_str(), 0x1ED);
 #endif
-  command = tmpFileName;
-
+  
+  std::string command = tmpFileName;
   MESSAGE("Command is file ... " << command);
   MESSAGE("Command is ... " << o.str());
   return command;
@@ -933,7 +1076,7 @@ std::string SALOME_ContainerManager::BuildCommandToLaunchLocalContainer(const En
 
 void SALOME_ContainerManager::RmTmpFile(std::string& tmpFileName)
 {
-  int length = tmpFileName.size();
+  size_t length = tmpFileName.size();
   if ( length  > 0)
     {
 #ifdef WIN32
@@ -991,11 +1134,15 @@ void SALOME_ContainerManager::AddOmninamesParams(std::ostream& fileStream) const
  */
 //=============================================================================
 
-void SALOME_ContainerManager::AddOmninamesParams(std::ostream& fileStream, SALOME_NamingService *ns)
+void SALOME_ContainerManager::AddOmninamesParams(std::ostream& fileStream, SALOME_NamingService_Abstract *ns)
 {
-  CORBA::String_var iorstr(ns->getIORaddr());
-  fileStream << "ORBInitRef NameService=";
-  fileStream << iorstr;
+  SALOME_NamingService *nsTrad(dynamic_cast<SALOME_NamingService *>(ns));
+  if(nsTrad)
+  {
+    CORBA::String_var iorstr(nsTrad->getIORaddr());
+    fileStream << "ORBInitRef NameService=";
+    fileStream << iorstr;
+  }
 }
 
 void SALOME_ContainerManager::MakeTheCommandToBeLaunchedASync(std::string& command)
@@ -1085,15 +1232,9 @@ std::string SALOME_ContainerManager::BuildTempFileToLaunchRemoteContainer (const
 
   if (params.isMPI)
     {
-      tempOutputFile << "mpirun -np ";
-      int nbproc;
+      int nbproc = params.nb_proc <= 0 ? 1 : params.nb_proc;
 
-      if ( params.nb_proc <= 0 )
-        nbproc = 1;
-      else
-        nbproc = params.nb_proc;
-
-      std::ostringstream o;
+      tempOutputFile << "mpirun -np ";
 
       tempOutputFile << nbproc << " ";
 #ifdef LAM_MPI
@@ -1167,7 +1308,7 @@ std::string SALOME_ContainerManager::BuildTempFileToLaunchRemoteContainer (const
 
   else if (resInfo.Protocol == srun)
     {
-      command = "srun -n 1 -N 1 --share --nodelist=";
+      command = "srun -n 1 -N 1 -s --mem-per-cpu=0 --cpu-bind=none --nodelist=";
       std::string commandRcp = "rcp ";
       commandRcp += tmpFileName;
       commandRcp += " ";
@@ -1209,43 +1350,8 @@ std::string SALOME_ContainerManager::GetMPIZeroNode(const std::string machine, c
     {
       if (_isAppliSalomeDefined)
         {
-
-          if (resInfo.Protocol == rsh)
-            command = "rsh ";
-          else if (resInfo.Protocol == ssh)
-            command = "ssh ";
-          else if (resInfo.Protocol == srun)
-            command = "srun -n 1 -N 1 --share --nodelist=";
-          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(GetenvThreadSafe("APPLI"));
-              command += GetenvThreadSafeAsString("APPLI"); // path relative to user@machine $HOME
-            }
-
-          command += "/runRemote.sh ";
-
-          ASSERT(GetenvThreadSafe("NSHOST"));
-          command += GetenvThreadSafeAsString("NSHOST"); // hostname of CORBA name server
-
-          command += " ";
-          ASSERT(GetenvThreadSafe("NSPORT"));
-          command += GetenvThreadSafeAsString("NSPORT"); // port of CORBA name server
-
+          command = getCommandToRunRemoteProcess(resInfo.Protocol, resInfo.HostName, 
+                                                 resInfo.UserName, resInfo.AppliPath);
           command += " mpirun -np 1 hostname -s > " + tmpFile;
         }
       else
@@ -1294,58 +1400,99 @@ std::string SALOME_ContainerManager::machinesFile(const int nbproc)
 
 }
 
-std::set<pid_t> SALOME_ContainerManager::getpidofprogram(const std::string program)
+std::string SALOME_ContainerManager::getCommandToRunRemoteProcessNoAppli(AccessProtocolType protocol, const std::string & hostname, const std::string & username, const std::string & applipath, const std::string & workdir) const
 {
-  std::set<pid_t> thepids;
-  std::string tmpFile = Kernel_Utils::GetTmpFileName();
-  std::string cmd;
-  std::string thepid;
-  cmd = "pidof " + program + " > " + tmpFile;
-  SystemThreadSafe(cmd.c_str());
-  std::ifstream fpi(tmpFile.c_str(),std::ios::in);
-  while(fpi >> thepid){
-    thepids.insert(atoi(thepid.c_str()));
-  }
-  return thepids;
+  return getCommandToRunRemoteProcessCommon("SALOME_CM_REMOTE","salome shell --",protocol,hostname,username,applipath,workdir);
 }
 
-std::string SALOME_ContainerManager::getCommandToRunRemoteProcess(AccessProtocolType protocol,
+std::string SALOME_ContainerManager::getCommandToRunRemoteProcess(AccessProtocolType protocol, const std::string & hostname, const std::string & username, const std::string & applipath, const std::string & workdir) const
+{
+  return getCommandToRunRemoteProcessCommon("SALOME_CM_REMOTE_OLD",this->GetRunRemoteExecutableScript(),protocol,hostname,username,applipath,workdir);
+}
+
+std::string SALOME_ContainerManager::getCommandToRunRemoteProcessCommon(const std::string& templateName,
+                                                                  const std::string& remoteScript,
+                                                                  AccessProtocolType protocol,
                                                                   const std::string & hostname,
-                                                                  const std::string & username)
+                                                                  const std::string & username,
+                                                                  const std::string & applipath,
+                                                                  const std::string & workdir) const
 {
   std::ostringstream command;
+  
+  // Prepare parameters to use in the Python script:
+  // 1. All parameters are strings.
+  // 2. For some booleans use "1" = True, "0" = False.
+  // 3. If a parameter is NULL, then its value is "NULL".
+  
+  std::queue<std::string> script_parameters;
+
+  // ===== Protocol (key = "protocol")
+  std::string strProtocol;
   switch (protocol)
   {
-  case rsh:
-    command << "rsh ";
-    if (username != "")
-    {
-      command << "-l " << username << " ";
-    }
-    command << hostname << " ";
-    break;
-  case ssh:
-    command << "ssh ";
-    if (username != "")
-    {
-      command << "-l " << username << " ";
-    }
-    command << hostname << " ";
-    break;
-  case srun:
-    // no need to redefine the user with srun, the job user is taken by default
-    // (note: for srun, user id can be specified with " --uid=<user>")
-    command << "srun -n 1 -N 1 --share --nodelist=" << hostname << " ";
-    break;
-  case pbsdsh:
-    command << "pbsdsh -o -h " << hostname << " ";
-    break;
-  case blaunch:
-    command << "blaunch -no-shell " << hostname << " ";
-    break;
+  case rsh: strProtocol = "rsh"; break;
+  case ssh: strProtocol = "ssh"; break;
+  case srun: strProtocol = "srun"; break;
+  case pbsdsh: strProtocol = "pbsdsh"; break;
+  case blaunch: strProtocol = "blaunch"; break;
   default:
     throw SALOME_Exception("Unknown protocol");
   }
+  script_parameters.push(strProtocol);
+
+  // ===== User name (key = "user")
+  script_parameters.push(username.empty() ? "NULL" : username);
+  
+  // ===== Host name (key = "host")
+  script_parameters.push(hostname.empty() ? "NULL" : hostname);
+  
+  // ===== Remote APPLI path (key = "appli")
+  script_parameters.push(applipath.empty() ? GetenvThreadSafeAsString("APPLI") : applipath);
+  
+  if(!this->_isSSL)
+  {
+    ASSERT(GetenvThreadSafe("NSHOST"));
+    ASSERT(GetenvThreadSafe("NSPORT"));
+  }
+
+  struct stat statbuf;
+  std::string appli_mode = (stat(GetenvThreadSafe("APPLI"), &statbuf) == 0 && S_ISREG(statbuf.st_mode)) ? "launcher" : "dir";
+
+  // ===== Working directory (key = "workdir")
+  script_parameters.push(workdir == "$TEMPDIR" ? "\\$TEMPDIR" : workdir);
+  
+  // ===== SSL (key = "ssl")
+  script_parameters.push(this->_isSSL ? "1" : "0");
+  
+  // ===== Hostname of CORBA name server (key = "nshost")
+  std::string nshost = GetenvThreadSafeAsString("NSHOST");
+  script_parameters.push(nshost.empty() ? "NULL" : nshost);
+
+  // ===== Port of CORBA name server (key = "nsport")
+  std::string nsport = GetenvThreadSafeAsString("NSPORT");
+  script_parameters.push(nsport.empty() ? "NULL" : nsport);
+
+  // ===== Remote script (key = "remote_script")
+  script_parameters.push(remoteScript.empty() ? "NONE" : remoteScript);
+  
+  // ===== Naming service (key = "naming_service")
+  std::string namingService = "NONE";
+  if(this->_isSSL)
+  {
+    Engines::EmbeddedNamingService_var ns = GetEmbeddedNamingService();
+    CORBA::String_var iorNS = _orb->object_to_string(ns);
+    namingService = iorNS;
+  }
+  script_parameters.push(namingService);
+
+  // ===== APPLI mode (key = "appli_mode")
+  // $APPLI points either to an application directory, or to a salome launcher file
+  // we prepare the remote command according to the case
+  script_parameters.push(appli_mode);
+
+  command << GetCommandFromTemplate(templateName, script_parameters);
 
   return command.str();
 }
@@ -1427,6 +1574,38 @@ int SALOME_ContainerManager::SystemThreadSafe(const char *command)
   return system(command);
 }
 
+long SALOME_ContainerManager::SystemWithPIDThreadSafe(const std::vector<std::string>& command)
+{
+  Utils_Locker lock(&_systemMutex);
+  if(command.size()<1)
+    throw SALOME_Exception("SystemWithPIDThreadSafe : command is expected to have a length of size 1 at least !");
+#ifndef WIN32
+  pid_t pid ( fork() ) ; // spawn a child process, following code is executed in both processes
+#else 
+  pid_t pid = -1; //Throw SALOME_Exception on Windows
+#endif
+  if ( pid == 0 ) // I'm a child, replace myself with a new ompi-server
+    {
+      std::size_t sz(command.size());
+      char **args = new char *[sz+1];
+      for(std::size_t i=0;i<sz;i++)
+        args[i] = strdup(command[i].c_str());
+      args[sz] = nullptr;
+      execvp( command[0].c_str() , args ); 
+      std::ostringstream oss;
+      oss << "Error when launching " << command[0];
+      throw SALOME_Exception(oss.str().c_str()); // execvp failed
+    }
+  else if ( pid < 0 )
+    {
+      throw SALOME_Exception("fork() failed");
+    }
+  else // I'm a parent
+    {
+      return pid;
+    }
+}
+
 #ifdef WITH_PACO_PARALLEL
 
 //=============================================================================
@@ -1633,7 +1812,7 @@ SALOME_ContainerManager::BuildCommandToLaunchPaCOProxyContainer(const Engines::C
     remote_execution = true;
   }
 
-  // Log environnement
+  // Log environment
   std::string log_type("");
   char * get_val = GetenvThreadSafe("PARALLEL_LOG");
   if (get_val)
@@ -1699,7 +1878,7 @@ SALOME_ContainerManager::BuildCommandToLaunchPaCONodeContainer(const Engines::Co
   ParserResourcesType resource_definition =
       _resManager->GetResourceDefinition(params.resource_params.name.in());
 
-  // Log environnement
+  // Log environment
   std::string log_type("");
   char * get_val = GetenvThreadSafe("PARALLEL_LOG");
   if (get_val)
@@ -2005,8 +2184,8 @@ SALOME_ContainerManager::LaunchPaCONodeContainer(const std::string& command,
 #else
 
 Engines::Container_ptr
-SALOME_ContainerManager::StartPaCOPPContainer(const Engines::ContainerParameters& params,
-                                              std::string resource_selected)
+SALOME_ContainerManager::StartPaCOPPContainer(const Engines::ContainerParameters& /*params*/,
+                                              std::string /*resource_selected*/)
 {
   Engines::Container_ptr ret = Engines::Container::_nil();
   INFOS("[StarPaCOPPContainer] is disabled !");
@@ -2015,45 +2194,45 @@ SALOME_ContainerManager::StartPaCOPPContainer(const Engines::ContainerParameters
 }
 
 std::string
-SALOME_ContainerManager::BuildCommandToLaunchPaCOProxyContainer(const Engines::ContainerParameters& params,
-                                                                std::string machine_file_name,
-                                                                std::string & proxy_hostname)
+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)
+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)
+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)
+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)
+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;
 }