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