Salome HOME
[EDF27562] : Fix clustertest
[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     {
608       command = BuildCommandToLaunchLocalContainer(params, machFile, container_exe, tmpFileName);
609       MESSAGE("[LaunchContainer] LIBBATCH_NODEFILE : \"" << command << "\"");
610     }
611     // if a container is launched on localhost, command is "SALOME_Container" or "mpirun -np nbproc SALOME_MPIContainer"
612     else if(hostname == Kernel_Utils::GetHostname())
613     {
614       command = BuildCommandToLaunchLocalContainer(params, machFile, container_exe, tmpFileName);
615       MESSAGE("[LaunchContainer] hostname local : \"" << command << "\"");
616     }
617     // if a container is launched in remote mode, command is "ssh resource_selected SALOME_Container" or "ssh resource_selected mpirun -np nbproc SALOME_MPIContainer"
618     else
619     {
620       command = BuildCommandToLaunchRemoteContainer(resource_selected, params, container_exe);
621       MESSAGE("[LaunchContainer] remote : \"" << command << "\"");
622     }
623
624     //redirect stdout and stderr in a file
625 #ifdef WIN32
626     logFilename=GetenvThreadSafeAsString("TEMP");
627     logFilename += "\\";
628     user = GetenvThreadSafeAsString( "USERNAME" );
629 #else
630     user = GetenvThreadSafeAsString( "USER" );
631     if (user.empty())
632       user = GetenvThreadSafeAsString( "LOGNAME" );
633     logFilename="/tmp";
634     char* val = GetenvThreadSafe("SALOME_TMP_DIR");
635     if(val)
636       {
637         struct stat file_info;
638         stat(val, &file_info);
639         bool is_dir = S_ISDIR(file_info.st_mode);
640         if (is_dir)logFilename=val;
641         else std::cerr << "SALOME_TMP_DIR environment variable is not a directory use /tmp instead" << std::endl;
642       }
643     logFilename += "/";
644 #endif
645     logFilename += _NS->ContainerName(params)+"_"+ resource_selected +"_"+user;
646     std::ostringstream tmp;
647     tmp << "_" << getpid();
648     logFilename += tmp.str();
649     logFilename += ".log" ;
650     command += " > " + logFilename + " 2>&1";
651     MakeTheCommandToBeLaunchedASync(command);
652     
653     MESSAGE("[LaunchContainer] SYSTEM COMMAND that will be launched : \"" << command << "\"");
654     // launch container with a system call
655     status=SystemThreadSafe(command.c_str());
656   }//end of critical of section
657
658   if (status == -1)
659     {
660       INFOS("[LaunchContainer] command failed (system command status -1): " << command);
661       RmTmpFile(tmpFileName); // command file can be removed here
662       return Engines::Container::_nil();
663     }
664   else if (status == 217)
665     {
666       INFOS("[LaunchContainer] command failed (system command status 217): " << command);
667       RmTmpFile(tmpFileName); // command file can be removed here
668       return Engines::Container::_nil();
669     }
670   else
671     {
672       // Step 4: Wait for the container
673       int count(GetTimeOutToLoaunchServer());
674       INFOS("[GiveContainer] waiting " << count << " second steps container " << containerNameInNS);
675       while (CORBA::is_nil(ret) && count)
676         {
677           SleepInSecond(1);
678           count--;
679           MESSAGE("[GiveContainer] step " << count << " Waiting for container on " << resource_selected);
680           CORBA::Object_var obj(_NS->Resolve(containerNameInNS.c_str()));
681           ret=Engines::Container::_narrow(obj);
682         }
683       if (CORBA::is_nil(ret))
684         {
685           INFOS("[GiveContainer] was not able to launch container " << containerNameInNS);
686         }
687       else
688         {
689           // Setting log file name
690           logFilename=":"+logFilename;
691           logFilename="@"+Kernel_Utils::GetHostname()+logFilename;//threadsafe
692           logFilename=user+logFilename;
693           ret->logfilename(logFilename.c_str());
694           RmTmpFile(tmpFileName); // command file can be removed here
695         }
696     }
697   return ret;
698 }
699
700 //=============================================================================
701 //! Find a container given constraints (params) on a list of machines (possibleComputers)
702 //! agy : this method is ThreadSafe
703 /*!
704  *
705  */
706 //=============================================================================
707
708 Engines::Container_ptr SALOME_ContainerManager::FindContainer(const Engines::ContainerParameters& params, const Engines::ResourceList& possibleResources)
709 {
710   MESSAGE("[FindContainer] FindContainer on " << possibleResources.length() << " resources");
711   for(unsigned int i=0; i < possibleResources.length();i++)
712     {
713       Engines::Container_ptr cont = FindContainer(params, possibleResources[i].in());
714       if(!CORBA::is_nil(cont))
715         return cont;
716     }
717   MESSAGE("[FindContainer] no container found");
718   return Engines::Container::_nil();
719 }
720
721 //=============================================================================
722 //! Find a container given constraints (params) on a machine (theMachine)
723 //! agy : this method is ThreadSafe
724 /*!
725  *
726  */
727 //=============================================================================
728
729 Engines::Container_ptr
730 SALOME_ContainerManager::FindContainer(const Engines::ContainerParameters& params, const std::string& resource)
731 {
732   ParserResourcesType resource_definition = _resManager->GetResourceDefinition(resource);
733   std::string hostname(resource_definition.HostName);
734   std::string containerNameInNS(_NS->BuildContainerNameForNS(params, hostname.c_str()));
735   MESSAGE("[FindContainer] Try to find a container  " << containerNameInNS << " on resource " << resource);
736   CORBA::Object_var obj = _NS->Resolve(containerNameInNS.c_str());
737   try
738   {
739     if(obj->_non_existent())
740       return Engines::Container::_nil();
741     else
742       return Engines::Container::_narrow(obj);
743   }
744   catch(const CORBA::Exception&)
745   {
746     return Engines::Container::_nil();
747   }
748 }
749
750
751 bool isPythonContainer(const char* ContainerName);
752
753 //=============================================================================
754 /*!
755  *  This is no longer valid (C++ container are also python containers)
756  */
757 //=============================================================================
758 bool isPythonContainer(const char* ContainerName)
759 {
760   return false; // VSR 02/08/2013: Python containers are no more supported
761   bool ret = false;
762   size_t len = strlen(ContainerName);
763
764   if (len >= 2)
765     if (strcmp(ContainerName + len - 2, "Py") == 0)
766       ret = true;
767
768   return ret;
769 }
770
771 //=============================================================================
772 /*!
773  *  Builds the script to be launched
774  *
775  *  If SALOME Application not defined ($APPLI),
776  *  see BuildTempFileToLaunchRemoteContainer()
777  *
778  *  Else rely on distant configuration. Command is under the form (example):
779  *  ssh user@machine distantPath/runRemote.sh hostNS portNS WORKINGDIR workingdir \
780  *                   SALOME_Container containerName &"
781
782  *  - where user is omitted if not specified in CatalogResources,
783  *  - where distant path is always relative to user@machine $HOME, and
784  *    equal to $APPLI if not specified in CatalogResources,
785  *  - where hostNS is the hostname of CORBA naming server (set by scripts to
786  *    use to launch SALOME and servers in $APPLI: runAppli.sh, runRemote.sh)
787  *  - where portNS is the port used by CORBA naming server (set by scripts to
788  *    use to launch SALOME and servers in $APPLI: runAppli.sh, runRemote.sh)
789  *  - where workingdir is the requested working directory for the container.
790  *    If WORKINGDIR (and workingdir) is not present the working dir will be $HOME
791  */
792 //=============================================================================
793
794 std::string
795 SALOME_ContainerManager::BuildCommandToLaunchRemoteContainer(const std::string& resource_name, const Engines::ContainerParameters& params, const std::string& container_exe) const
796 {
797   std::string command,tmpFileName;
798   const ParserResourcesType resInfo(_resManager->GetResourceDefinition(resource_name));
799   std::string wdir = params.workingdir.in();
800   if (!_isAppliSalomeDefined)
801   {
802       MESSAGE("[BuildCommandToLaunchRemoteContainer] NO APPLI MODE : " << " Protocol :" << resInfo.Protocol << " hostname :" << resInfo.HostName << " username : " << resInfo.UserName << " appli : " << resInfo.AppliPath << " wdir : \"" << wdir << "\"");
803       command = getCommandToRunRemoteProcessNoAppli(resInfo.Protocol, resInfo.HostName, 
804                                                     resInfo.UserName, resInfo.AppliPath,
805                                                     wdir);
806   }
807   else
808   {
809     MESSAGE("[BuildCommandToLaunchRemoteContainer] WITH APPLI MODE : " << " Protocol :" << resInfo.Protocol << " hostname :" << resInfo.HostName << " username : " << resInfo.UserName << " appli : " << resInfo.AppliPath << " wdir : \"" << wdir << "\"");
810     // "ssh -l user machine distantPath/runRemote.sh hostNS portNS WORKINGDIR workingdir
811     //      SALOME_Container containerName -ORBInitRef NameService=IOR:01000..."
812     //  or 
813     //  "ssh -l user machine distantLauncher remote -p hostNS -m portNS -d dir
814     //      --  SALOME_Container contName -ORBInitRef NameService=IOR:01000..."
815     command = getCommandToRunRemoteProcess(resInfo.Protocol, resInfo.HostName, 
816                                            resInfo.UserName, resInfo.AppliPath,
817                                            wdir);
818   }
819   if(params.isMPI)
820   {
821     int nbproc = params.nb_proc <= 0 ? 1 : params.nb_proc;
822     command += " mpirun -np ";
823     std::ostringstream o;
824     o << nbproc << " ";
825     command += o.str();
826 #ifdef LAM_MPI
827     command += "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
828 #elif defined(OPEN_MPI)
829     if( GetenvThreadSafe("OMPI_URI_FILE") == NULL )
830       command += "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace";
831     else{
832       command += "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace -ompi-server file:";
833       command += GetenvThreadSafeAsString("OMPI_URI_FILE");
834     }
835 #elif defined(MPICH)
836     command += "-nameserver " + Kernel_Utils::GetHostname();
837 #endif
838     command += " SALOME_MPIContainer ";
839   }
840   else
841     command += " " +container_exe+ " ";
842
843   command += _NS->ContainerName(params) + " ";
844   if(this->_isSSL)
845   {
846     Engines::EmbeddedNamingService_var ns = GetEmbeddedNamingService();
847     CORBA::String_var iorNS = _orb->object_to_string(ns);
848     command += std::string(iorNS);
849   }
850   else //if(!this->_isSSL)
851   {
852     command += " -";
853     AddOmninamesParams(command);
854   }
855   MESSAGE("command =" << command);
856
857   return command;
858 }
859
860 //=============================================================================
861 //! Return a path to the directory with scripts templates
862 /*! 
863  *  \return the path pointed by SALOME_KERNEL_SCRIPTS_DIR environment variable, if it is defined,
864  *  ${KERNEL_ROOT_DIR}/share/salome/resources/separator/kernel/ScriptsTemplate - otherwise
865  */
866 //=============================================================================
867 std::string getScriptTemplateFilePath()
868 {
869   auto parseScriptTemplateFilePath = []() -> std::string
870   {
871     std::string scriptTemplateFilePath = SALOME_ContainerManager::GetenvThreadSafeAsString("SALOME_KERNEL_SCRIPTS_DIR");
872     if (!scriptTemplateFilePath.empty())
873     {
874       return scriptTemplateFilePath;
875     }
876     else {
877       return SALOME_ContainerManager::GetenvThreadSafeAsString("KERNEL_ROOT_DIR") +
878              "/share/salome/resources/kernel/ScriptsTemplate";
879     }
880   };
881
882   static const std::string scriptTemplateFilePath = parseScriptTemplateFilePath();
883   return scriptTemplateFilePath;
884 }
885
886 //=============================================================================
887 //! Return a command line constructed based on Python scripts templates
888 /*! 
889  *  \param theScriptName        the name of Python script template
890  *  \param theScriptParameters  the queue of parameter values
891  *  \return the command line constructed according to the given parameters
892  */
893 //=============================================================================
894 std::string GetCommandFromTemplate(const std::string& theScriptName,
895                                    std::queue<std::string>& theScriptParameters)
896 {
897   std::string command;
898   AutoGIL agil;
899   // manage GIL
900
901   PyObject* mod(PyImport_ImportModule(theScriptName.c_str()));
902   if (!mod)
903   {
904     PyObject* sys = PyImport_ImportModule("sys");
905     PyObject* sys_path = PyObject_GetAttrString(sys, "path");
906     PyObject* folder_path = PyUnicode_FromString(getScriptTemplateFilePath().c_str());
907     PyList_Append(sys_path, folder_path);
908
909     mod = PyImport_ImportModule(theScriptName.c_str());
910
911     Py_XDECREF(folder_path);
912     Py_XDECREF(sys_path);
913     Py_XDECREF(sys);
914   }
915
916   if (mod)
917   {
918     PyObject* meth(PyObject_GetAttrString(mod, "command"));
919     if (!meth)
920     {
921       Py_XDECREF(mod);
922     }
923     else
924     {
925       int id = -1;
926       PyObject* tuple(PyTuple_New(theScriptParameters.size()));
927
928       auto insert_parameter = [&tuple, &theScriptParameters, &id]()
929       {
930         if (!theScriptParameters.empty())
931         {
932           PyTuple_SetItem(tuple, ++id, PyUnicode_FromString(theScriptParameters.front().c_str()));
933           theScriptParameters.pop();
934         }
935       };
936
937       while (!theScriptParameters.empty())
938       {
939         insert_parameter();
940       }
941       
942       PyObject *args(PyTuple_New(1));
943       PyTuple_SetItem(args, 0, tuple);
944
945       PyObject *res(PyObject_CallObject(meth, args));
946       if (res)
947       {
948         command = PyUnicode_AsUTF8(res);
949         Py_XDECREF(res);
950       }
951
952       Py_XDECREF(args);
953       Py_XDECREF(tuple);
954       Py_XDECREF(meth);
955       Py_XDECREF(mod);
956     }
957   }
958
959   MESSAGE("Command from template is ... " << command << std::endl);
960   return command;
961 }
962 //=============================================================================
963
964 //=============================================================================
965 /*!
966  *  builds the command to be launched.
967  */
968 //=============================================================================
969 std::string SALOME_ContainerManager::BuildCommandToLaunchLocalContainer(const Engines::ContainerParameters& params, const std::string& machinesFile, const std::string& container_exe, std::string& tmpFileName) const
970 {
971   // Prepare name of the script to be used
972   std::string script_name = "SALOME_CM_LOCAL_NO_MPI";
973   if (params.isMPI)
974   {
975 #ifdef LAM_MPI
976     script_name = "SALOME_CM_LOCAL_MPI_LAN";
977 #elif defined(OPEN_MPI)
978     script_name = "SALOME_CM_LOCAL_MPI_OPENMPI";
979 #elif defined(MPICH)
980     script_name = "SALOME_CM_LOCAL_MPI_MPICH";
981 #endif
982   }
983   
984   // Prepare parameters to use in the Python script:
985   // 1. All parameters are strings.
986   // 2. For some booleans use "1" = True, "0" = False.
987   // 3. If a parameter is NULL, then its value is "NULL".
988
989   std::queue<std::string> script_parameters;
990   
991   // ===== Number of processes (key = "nb_proc")
992   script_parameters.push(params.isMPI ? std::to_string(params.nb_proc <= 0 ? 1 : params.nb_proc) : "NULL");
993
994   // ===== Working directory (key = "workdir") and temporary directory flag (key = "isTmpDir")
995   // A working directory is requested
996   std::string workdir = params.workingdir.in();
997   std::string isTmpDir = std::to_string(0);
998   if (workdir == "$TEMPDIR")
999   {
1000     // A new temporary directory is requested
1001     isTmpDir = std::to_string(1);
1002     workdir = Kernel_Utils::GetTmpDir();
1003   }
1004   script_parameters.push(workdir);
1005   script_parameters.push(isTmpDir);
1006   
1007   // ===== Server name (key = "name_server")
1008   script_parameters.push(Kernel_Utils::GetHostname());
1009
1010   // ===== Container (key = "container")
1011   std::string container;
1012   if (params.isMPI)
1013   {
1014     container = isPythonContainer(params.container_name) ? "pyMPI SALOME_ContainerPy.py" : "SALOME_MPIContainer";
1015   }
1016   else
1017   {
1018     container = isPythonContainer(params.container_name) ? "SALOME_ContainerPy.py" : container_exe;
1019   }
1020   script_parameters.push(container);
1021
1022   // ===== Container name (key = "container_name")
1023   script_parameters.push(_NS->ContainerName(params));
1024
1025   // ===== LIBBATCH node file (key = "libbatch_nodefile")
1026   script_parameters.push(std::to_string(GetenvThreadSafe("LIBBATCH_NODEFILE") != NULL ? 1 : 0));
1027
1028   // ===== Machine file (key = "machine_file")
1029   script_parameters.push(machinesFile.empty() ? "NULL" : machinesFile);
1030
1031   // ===== OMPI uri file (key = "ompi_uri_file")
1032   std::string ompi_uri_file = GetenvThreadSafeAsString("OMPI_URI_FILE");
1033   script_parameters.push(ompi_uri_file.empty() ? "NULL" : ompi_uri_file);
1034
1035   std::string command_from_template = GetCommandFromTemplate(script_name, script_parameters);
1036
1037   std::ostringstream o;
1038   o << command_from_template << " ";
1039   
1040   //==================================================================================== */
1041
1042   if( this->_isSSL )
1043   {
1044     Engines::EmbeddedNamingService_var ns = GetEmbeddedNamingService();
1045     CORBA::String_var iorNS = _orb->object_to_string(ns);
1046     o << iorNS;
1047   }
1048   else
1049   {
1050     o << "-";
1051     AddOmninamesParams(o);
1052   }
1053   
1054   tmpFileName = BuildTemporaryFileName();
1055   std::ofstream command_file( tmpFileName.c_str() );
1056   command_file << o.str();
1057   command_file.close();
1058
1059 #ifndef WIN32
1060   chmod(tmpFileName.c_str(), 0x1ED);
1061 #endif
1062   
1063   std::string command = tmpFileName;
1064   MESSAGE("Command is file ... " << command);
1065   MESSAGE("Command is ... " << o.str());
1066   return command;
1067 }
1068
1069
1070 //=============================================================================
1071 /*!
1072  *  removes the generated temporary file in case of a remote launch.
1073  *  This method is thread safe
1074  */
1075 //=============================================================================
1076
1077 void SALOME_ContainerManager::RmTmpFile(std::string& tmpFileName)
1078 {
1079   size_t length = tmpFileName.size();
1080   if ( length  > 0)
1081     {
1082 #ifdef WIN32
1083       std::string command = "del /F ";
1084 #else
1085       std::string command = "rm ";
1086 #endif
1087       if ( length > 4 )
1088         command += tmpFileName.substr(0, length - 3 );
1089       else
1090         command += tmpFileName;
1091       command += '*';
1092       SystemThreadSafe(command.c_str());
1093       //if dir is empty - remove it
1094       std::string tmp_dir = Kernel_Utils::GetDirByPath( tmpFileName );
1095       if ( Kernel_Utils::IsEmptyDir( tmp_dir ) )
1096         {
1097 #ifdef WIN32
1098           command = "del /F " + tmp_dir;
1099 #else
1100           command = "rmdir " + tmp_dir;
1101 #endif
1102           SystemThreadSafe(command.c_str());
1103         }
1104     }
1105 }
1106
1107 //=============================================================================
1108 /*!
1109  *   add to command all options relative to naming service.
1110  */
1111 //=============================================================================
1112
1113 void SALOME_ContainerManager::AddOmninamesParams(std::string& command) const
1114 {
1115   std::ostringstream oss;
1116   AddOmninamesParams(oss);
1117   command+=oss.str();
1118 }
1119
1120 //=============================================================================
1121 /*!
1122  *  add to command all options relative to naming service.
1123  */
1124 //=============================================================================
1125
1126 void SALOME_ContainerManager::AddOmninamesParams(std::ostream& fileStream) const
1127 {
1128   AddOmninamesParams(fileStream,_NS);
1129 }
1130
1131 //=============================================================================
1132 /*!
1133  *  add to command all options relative to naming service.
1134  */
1135 //=============================================================================
1136
1137 void SALOME_ContainerManager::AddOmninamesParams(std::ostream& fileStream, SALOME_NamingService_Abstract *ns)
1138 {
1139   SALOME_NamingService *nsTrad(dynamic_cast<SALOME_NamingService *>(ns));
1140   if(nsTrad)
1141   {
1142     CORBA::String_var iorstr(nsTrad->getIORaddr());
1143     fileStream << "ORBInitRef NameService=";
1144     fileStream << iorstr;
1145   }
1146 }
1147
1148 void SALOME_ContainerManager::MakeTheCommandToBeLaunchedASync(std::string& command)
1149 {
1150 #ifdef WIN32
1151     command = "%PYTHONBIN% -c \"import subprocess ; subprocess.Popen(r'" + command + "').pid\"";
1152 #else
1153     command += " &";
1154 #endif
1155 }
1156
1157 int SALOME_ContainerManager::GetTimeOutToLoaunchServer()
1158 {
1159   int count(TIME_OUT_TO_LAUNCH_CONT);
1160   if (GetenvThreadSafe("TIMEOUT_TO_LAUNCH_CONTAINER") != 0)
1161     {
1162       std::string new_count_str(GetenvThreadSafeAsString("TIMEOUT_TO_LAUNCH_CONTAINER"));
1163       int new_count;
1164       std::istringstream ss(new_count_str);
1165       if (!(ss >> new_count))
1166         {
1167           INFOS("[LaunchContainer] TIMEOUT_TO_LAUNCH_CONTAINER should be an int");
1168         }
1169       else
1170         count = new_count;
1171     }
1172   return count;
1173 }
1174
1175 void SALOME_ContainerManager::SleepInSecond(int ellapseTimeInSecond)
1176 {
1177 #ifndef WIN32
1178   sleep( ellapseTimeInSecond ) ;
1179 #else
1180   int timeInMS(1000*ellapseTimeInSecond);
1181   Sleep(timeInMS);
1182 #endif
1183 }
1184
1185 //=============================================================================
1186 /*!
1187  *  generate a file name in /tmp directory
1188  */
1189 //=============================================================================
1190
1191 std::string SALOME_ContainerManager::BuildTemporaryFileName()
1192 {
1193   //build more complex file name to support multiple salome session
1194   std::string aFileName = Kernel_Utils::GetTmpFileName();
1195   std::ostringstream str_pid;
1196   str_pid << ::getpid();
1197   aFileName = aFileName + "-" + str_pid.str();
1198 #ifndef WIN32
1199   aFileName += ".sh";
1200 #else
1201   aFileName += ".bat";
1202 #endif
1203   return aFileName;
1204 }
1205
1206 //=============================================================================
1207 /*!
1208  *  Builds in a temporary file the script to be launched.
1209  *
1210  *  Used if SALOME Application ($APPLI) is not defined.
1211  *  The command is build with data from CatalogResources, in which every path
1212  *  used on remote computer must be defined.
1213  */
1214 //=============================================================================
1215
1216 std::string SALOME_ContainerManager::BuildTempFileToLaunchRemoteContainer (const std::string& resource_name, const Engines::ContainerParameters& params, std::string& tmpFileName) const
1217 {
1218   int status;
1219
1220   tmpFileName = BuildTemporaryFileName();
1221   std::ofstream tempOutputFile;
1222   tempOutputFile.open(tmpFileName.c_str(), std::ofstream::out );
1223   const ParserResourcesType resInfo(_resManager->GetResourceDefinition(resource_name));
1224   tempOutputFile << "#! /bin/sh" << std::endl;
1225
1226   // --- set env vars
1227
1228   tempOutputFile << "export SALOME_trace=local" << std::endl; // mkr : 27.11.2006 : PAL13967 - Distributed supervision graphs - Problem with "SALOME_trace"
1229   //tempOutputFile << "source " << resInfo.PreReqFilePath << endl;
1230
1231   // ! env vars
1232
1233   if (params.isMPI)
1234     {
1235       int nbproc = params.nb_proc <= 0 ? 1 : params.nb_proc;
1236
1237       tempOutputFile << "mpirun -np ";
1238
1239       tempOutputFile << nbproc << " ";
1240 #ifdef LAM_MPI
1241       tempOutputFile << "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
1242 #elif defined(OPEN_MPI)
1243       if( GetenvThreadSafe("OMPI_URI_FILE") == NULL )
1244         tempOutputFile << "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace";
1245       else{
1246         tempOutputFile << "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace -ompi-server file:";
1247         tempOutputFile << GetenvThreadSafeAsString("OMPI_URI_FILE");
1248       }
1249 #elif defined(MPICH)
1250       tempOutputFile << "-nameserver " + Kernel_Utils::GetHostname();
1251 #endif
1252     }
1253
1254   tempOutputFile << GetenvThreadSafeAsString("KERNEL_ROOT_DIR") << "/bin/salome/";
1255
1256   if (params.isMPI)
1257     {
1258       if (isPythonContainer(params.container_name))
1259         tempOutputFile << " pyMPI SALOME_ContainerPy.py ";
1260       else
1261         tempOutputFile << " SALOME_MPIContainer ";
1262     }
1263
1264   else
1265     {
1266       if (isPythonContainer(params.container_name))
1267         tempOutputFile << "SALOME_ContainerPy.py ";
1268       else
1269         tempOutputFile << "SALOME_Container ";
1270     }
1271
1272   tempOutputFile << _NS->ContainerName(params) << " -";
1273   AddOmninamesParams(tempOutputFile);
1274   tempOutputFile << " &" << std::endl;
1275   tempOutputFile.flush();
1276   tempOutputFile.close();
1277 #ifndef WIN32
1278   chmod(tmpFileName.c_str(), 0x1ED);
1279 #endif
1280
1281   // --- Build command
1282
1283   std::string command;
1284
1285   if (resInfo.Protocol == rsh)
1286     {
1287       command = "rsh ";
1288       std::string commandRcp = "rcp ";
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 == ssh)
1298     {
1299       command = "ssh ";
1300       std::string commandRcp = "scp ";
1301       commandRcp += tmpFileName;
1302       commandRcp += " ";
1303       commandRcp += resInfo.HostName;
1304       commandRcp += ":";
1305       commandRcp += tmpFileName;
1306       status = SystemThreadSafe(commandRcp.c_str());
1307     }
1308
1309   else if (resInfo.Protocol == srun)
1310     {
1311       command = "srun -n 1 -N 1 -s --mem-per-cpu=0 --cpu-bind=none --nodelist=";
1312       std::string commandRcp = "rcp ";
1313       commandRcp += tmpFileName;
1314       commandRcp += " ";
1315       commandRcp += resInfo.HostName;
1316       commandRcp += ":";
1317       commandRcp += tmpFileName;
1318       status = SystemThreadSafe(commandRcp.c_str());
1319     }
1320   else
1321     throw SALOME_Exception("Unknown protocol");
1322
1323   if(status)
1324     throw SALOME_Exception("Error of connection on remote host");
1325
1326   command += resInfo.HostName;
1327   command += " ";
1328   command += tmpFileName;
1329
1330   SCRUTE(command);
1331
1332   return command;
1333
1334 }
1335
1336 std::string SALOME_ContainerManager::GetMPIZeroNode(const std::string machine, const std::string machinesFile) const
1337 {
1338   int status;
1339   std::string zeronode;
1340   std::string command;
1341   std::string tmpFile = BuildTemporaryFileName();
1342   const ParserResourcesType resInfo(_resManager->GetResourceDefinition(machine));
1343
1344   if(resInfo.Protocol == sh)
1345   {
1346     return resInfo.HostName;
1347   }
1348
1349   if( GetenvThreadSafe("LIBBATCH_NODEFILE") == NULL )
1350     {
1351       if (_isAppliSalomeDefined)
1352         {
1353           command = getCommandToRunRemoteProcess(resInfo.Protocol, resInfo.HostName, 
1354                                                  resInfo.UserName, resInfo.AppliPath);
1355           command += " mpirun -np 1 hostname -s > " + tmpFile;
1356         }
1357       else
1358         command = "mpirun -np 1 hostname -s > " + tmpFile;
1359     }
1360   else
1361     command = "mpirun -np 1 -machinefile " + machinesFile + " hostname -s > " + tmpFile;
1362
1363   status = SystemThreadSafe(command.c_str());
1364   if( status == 0 ){
1365     std::ifstream fp(tmpFile.c_str(),std::ios::in);
1366     while(fp >> zeronode);
1367   }
1368
1369   RmTmpFile(tmpFile);
1370
1371   return zeronode;
1372 }
1373
1374 std::string SALOME_ContainerManager::machinesFile(const int nbproc)
1375 {
1376   std::string tmp;
1377   std::string nodesFile = GetenvThreadSafeAsString("LIBBATCH_NODEFILE");
1378   std::string machinesFile = Kernel_Utils::GetTmpFileName();
1379   std::ifstream fpi(nodesFile.c_str(),std::ios::in);
1380   std::ofstream fpo(machinesFile.c_str(),std::ios::out);
1381
1382   _numInstanceMutex.lock();
1383
1384   for(int i=0;i<_nbprocUsed;i++)
1385     fpi >> tmp;
1386
1387   for(int i=0;i<nbproc;i++)
1388     if( fpi >> tmp )
1389       fpo << tmp << std::endl;
1390     else
1391       throw SALOME_Exception("You need more processors than batch session have allocated for you! Unable to launch the mpi container: ");
1392
1393   _nbprocUsed += nbproc;
1394   fpi.close();
1395   fpo.close();
1396
1397   _numInstanceMutex.unlock();
1398
1399   return machinesFile;
1400
1401 }
1402
1403 std::string SALOME_ContainerManager::getCommandToRunRemoteProcessNoAppli(AccessProtocolType protocol, const std::string & hostname, const std::string & username, const std::string & applipath, const std::string & workdir) const
1404 {
1405   return getCommandToRunRemoteProcessCommon("SALOME_CM_REMOTE","salome shell --",protocol,hostname,username,applipath,workdir);
1406 }
1407
1408 std::string SALOME_ContainerManager::getCommandToRunRemoteProcess(AccessProtocolType protocol, const std::string & hostname, const std::string & username, const std::string & applipath, const std::string & workdir) const
1409 {
1410   return getCommandToRunRemoteProcessCommon("SALOME_CM_REMOTE_OLD",this->GetRunRemoteExecutableScript(),protocol,hostname,username,applipath,workdir);
1411 }
1412
1413 std::string SALOME_ContainerManager::getCommandToRunRemoteProcessCommon(const std::string& templateName,
1414                                                                   const std::string& remoteScript,
1415                                                                   AccessProtocolType protocol,
1416                                                                   const std::string & hostname,
1417                                                                   const std::string & username,
1418                                                                   const std::string & applipath,
1419                                                                   const std::string & workdir) const
1420 {
1421   std::ostringstream command;
1422   
1423   // Prepare parameters to use in the Python script:
1424   // 1. All parameters are strings.
1425   // 2. For some booleans use "1" = True, "0" = False.
1426   // 3. If a parameter is NULL, then its value is "NULL".
1427   
1428   std::queue<std::string> script_parameters;
1429
1430   // ===== Protocol (key = "protocol")
1431   std::string strProtocol;
1432   switch (protocol)
1433   {
1434   case rsh: strProtocol = "rsh"; break;
1435   case ssh: strProtocol = "ssh"; break;
1436   case srun: strProtocol = "srun"; break;
1437   case pbsdsh: strProtocol = "pbsdsh"; break;
1438   case blaunch: strProtocol = "blaunch"; break;
1439   default:
1440     throw SALOME_Exception("Unknown protocol");
1441   }
1442   script_parameters.push(strProtocol);
1443
1444   // ===== User name (key = "user")
1445   script_parameters.push(username.empty() ? "NULL" : username);
1446   
1447   // ===== Host name (key = "host")
1448   script_parameters.push(hostname.empty() ? "NULL" : hostname);
1449   
1450  
1451   // ===== Remote APPLI path (key = "appli")
1452   script_parameters.push(applipath.empty() ? GetenvThreadSafeAsString("APPLI") : applipath);
1453   
1454   if(!this->_isSSL)
1455   {
1456     ASSERT(GetenvThreadSafe("NSHOST"));
1457     ASSERT(GetenvThreadSafe("NSPORT"));
1458   }
1459
1460   struct stat statbuf;
1461   std::string appli_mode = (stat(GetenvThreadSafe("APPLI"), &statbuf) == 0 && S_ISREG(statbuf.st_mode)) ? "launcher" : "dir";
1462
1463   // ===== Working directory (key = "workdir")
1464   script_parameters.push(workdir == "$TEMPDIR" ? "\\$TEMPDIR" : workdir);
1465   
1466   // ===== SSL (key = "ssl")
1467   script_parameters.push(this->_isSSL ? "1" : "0");
1468   
1469   // ===== Hostname of CORBA name server (key = "nshost")
1470   std::string nshost = GetenvThreadSafeAsString("NSHOST");
1471   script_parameters.push(nshost.empty() ? "NULL" : nshost);
1472
1473   // ===== Port of CORBA name server (key = "nsport")
1474   std::string nsport = GetenvThreadSafeAsString("NSPORT");
1475   script_parameters.push(nsport.empty() ? "NULL" : nsport);
1476
1477   // ===== Remote script (key = "remote_script")
1478   script_parameters.push(remoteScript.empty() ? "NONE" : remoteScript);
1479   
1480   // ===== Naming service (key = "naming_service")
1481   std::string namingService = "NONE";
1482   if(this->_isSSL)
1483   {
1484     Engines::EmbeddedNamingService_var ns = GetEmbeddedNamingService();
1485     CORBA::String_var iorNS = _orb->object_to_string(ns);
1486     namingService = iorNS;
1487   }
1488   script_parameters.push(namingService);
1489
1490   // ===== APPLI mode (key = "appli_mode")
1491   // $APPLI points either to an application directory, or to a salome launcher file
1492   // we prepare the remote command according to the case
1493   script_parameters.push(appli_mode);
1494
1495   command << GetCommandFromTemplate(templateName, script_parameters);
1496
1497   return command.str();
1498 }
1499
1500 bool
1501 SALOME_ContainerManager::checkPaCOParameters(Engines::ContainerParameters & params, std::string resource_selected)
1502 {
1503   bool result = true;
1504
1505   // Step 1 : check ContainerParameters
1506   // Check container_name, has to be defined
1507   if (std::string(params.container_name.in()) == "")
1508   {
1509     INFOS("[checkPaCOParameters] You must define a container_name to launch a PaCO++ container");
1510     result = false;
1511   }
1512   // Check parallelLib
1513   std::string parallelLib = params.parallelLib.in();
1514   if (parallelLib != "Mpi" && parallelLib != "Dummy")
1515   {
1516     INFOS("[checkPaCOParameters] parallelLib is not correctly defined");
1517     INFOS("[checkPaCOParameters] you can chosse between: Mpi and Dummy");
1518     INFOS("[checkPaCOParameters] you entered: " << parallelLib);
1519     result = false;
1520   }
1521   // Check nb_proc
1522   if (params.nb_proc <= 0)
1523   {
1524     INFOS("[checkPaCOParameters] You must define a nb_proc > 0");
1525     result = false;
1526   }
1527
1528   // Step 2 : check resource_selected
1529   const ParserResourcesType resource_definition = _resManager->GetResourceDefinition(resource_selected);
1530   //std::string protocol = resource_definition->protocol.in();
1531   std::string username = resource_definition.UserName;
1532   std::string applipath = resource_definition.AppliPath;
1533
1534   //if (protocol == "" || username == "" || applipath == "")
1535   if (username == "" || applipath == "")
1536   {
1537     INFOS("[checkPaCOParameters] resource selected is not well defined");
1538     INFOS("[checkPaCOParameters] resource name: " << resource_definition.Name);
1539     INFOS("[checkPaCOParameters] resource hostname: " << resource_definition.HostName);
1540     INFOS("[checkPaCOParameters] resource protocol: " << resource_definition.getAccessProtocolTypeStr());
1541     INFOS("[checkPaCOParameters] resource username: " << username);
1542     INFOS("[checkPaCOParameters] resource applipath: " << applipath);
1543     result = false;
1544   }
1545
1546   return result;
1547 }
1548
1549 /*
1550  * :WARNING: Do not directly convert returned value to std::string
1551  * This function may return NULL if env variable is not defined.
1552  * And std::string(NULL) causes undefined behavior.
1553  * Use GetenvThreadSafeAsString to properly get a std::string.
1554 */
1555 char *SALOME_ContainerManager::GetenvThreadSafe(const char *name)
1556 {// getenv is not thread safe. See man 7 pthread.
1557   Utils_Locker lock (&_getenvMutex);
1558   return getenv(name);
1559 }
1560
1561 /*
1562  * Return env variable as a std::string.
1563  * Return empty string if env variable is not set.
1564  */
1565 std::string SALOME_ContainerManager::GetenvThreadSafeAsString(const char *name)
1566 {
1567   char* var = GetenvThreadSafe(name);
1568   return var ? std::string(var) : std::string();
1569 }
1570
1571 int SALOME_ContainerManager::SystemThreadSafe(const char *command)
1572 {
1573   Utils_Locker lock (&_systemMutex);
1574   return system(command);
1575 }
1576
1577 long SALOME_ContainerManager::SystemWithPIDThreadSafe(const std::vector<std::string>& command)
1578 {
1579   Utils_Locker lock(&_systemMutex);
1580   if(command.size()<1)
1581     throw SALOME_Exception("SystemWithPIDThreadSafe : command is expected to have a length of size 1 at least !");
1582 #ifndef WIN32
1583   pid_t pid ( fork() ) ; // spawn a child process, following code is executed in both processes
1584 #else 
1585   pid_t pid = -1; //Throw SALOME_Exception on Windows
1586 #endif
1587   if ( pid == 0 ) // I'm a child, replace myself with a new ompi-server
1588     {
1589       std::size_t sz(command.size());
1590       char **args = new char *[sz+1];
1591       for(std::size_t i=0;i<sz;i++)
1592         args[i] = strdup(command[i].c_str());
1593       args[sz] = nullptr;
1594       execvp( command[0].c_str() , args ); 
1595       std::ostringstream oss;
1596       oss << "Error when launching " << command[0];
1597       throw SALOME_Exception(oss.str().c_str()); // execvp failed
1598     }
1599   else if ( pid < 0 )
1600     {
1601       throw SALOME_Exception("fork() failed");
1602     }
1603   else // I'm a parent
1604     {
1605       return pid;
1606     }
1607 }
1608
1609 #ifdef WITH_PACO_PARALLEL
1610
1611 //=============================================================================
1612 /*! CORBA Method:
1613  *  Start a suitable PaCO++ Parallel Container in a list of machines.
1614  *  \param params           Container Parameters required for the container
1615  *  \return CORBA container reference.
1616  */
1617 //=============================================================================
1618 Engines::Container_ptr
1619 SALOME_ContainerManager::StartPaCOPPContainer(const Engines::ContainerParameters& params_const,
1620                                               std::string resource_selected)
1621 {
1622   CORBA::Object_var obj;
1623   PaCO::InterfaceManager_var container_proxy;
1624   Engines::Container_ptr ret = Engines::Container::_nil();
1625   Engines::ContainerParameters params(params_const);
1626   params.resource_params.name = CORBA::string_dup(resource_selected.c_str());
1627
1628   // Step 0 : Check parameters
1629   if (!checkPaCOParameters(params, resource_selected))
1630   {
1631     INFOS("[StartPaCOPPContainer] check parameters failed ! see logs...");
1632     return ret;
1633   }
1634
1635   // Step 1 : Starting a new parallel container !
1636   INFOS("[StartPaCOPPContainer] Starting a PaCO++ parallel container");
1637   INFOS("[StartPaCOPPContainer] on resource : " << resource_selected);
1638
1639   // Step 2 : Get a MachineFile for the parallel container
1640   std::string machine_file_name = _resManager->getMachineFile(resource_selected,
1641                                                               params.nb_proc,
1642                                                               params.parallelLib.in());
1643
1644   if (machine_file_name == "")
1645   {
1646     INFOS("[StartPaCOPPContainer] Machine file generation failed");
1647     return ret;
1648   }
1649
1650   // Step 3 : starting parallel container proxy
1651   std::string command_proxy("");
1652   std::string proxy_machine;
1653   try
1654   {
1655     command_proxy = BuildCommandToLaunchPaCOProxyContainer(params, machine_file_name, proxy_machine);
1656   }
1657   catch(const SALOME_Exception & ex)
1658   {
1659     INFOS("[StartPaCOPPContainer] Exception in BuildCommandToLaunchPaCOContainer");
1660     INFOS(ex.what());
1661     return ret;
1662   }
1663   obj = LaunchPaCOProxyContainer(command_proxy, params, proxy_machine);
1664   if (CORBA::is_nil(obj))
1665   {
1666     INFOS("[StartPaCOPPContainer] LaunchPaCOContainer for proxy returns NIL !");
1667     return ret;
1668   }
1669   container_proxy = PaCO::InterfaceManager::_narrow(obj);
1670   MESSAGE("[StartPaCOPPContainer] PaCO container proxy is launched");
1671
1672   // Step 4 : starting parallel container nodes
1673   std::string command_nodes("");
1674   SALOME_ContainerManager::actual_launch_machine_t nodes_machines;
1675   try
1676   {
1677     command_nodes = BuildCommandToLaunchPaCONodeContainer(params, machine_file_name, nodes_machines, proxy_machine);
1678   }
1679   catch(const SALOME_Exception & ex)
1680   {
1681     INFOS("[StarPaCOPPContainer] Exception in BuildCommandToLaunchPaCONodeContainer");
1682     INFOS(ex.what());
1683     return ret;
1684   }
1685
1686   std::string container_generic_node_name = std::string(params.container_name.in()) + std::string("Node");
1687   bool result = LaunchPaCONodeContainer(command_nodes, params, container_generic_node_name, nodes_machines);
1688   if (!result)
1689   {
1690     INFOS("[StarPaCOPPContainer] LaunchPaCONodeContainer failed !");
1691     // Il faut tuer le proxy
1692     try
1693     {
1694       Engines::Container_var proxy = Engines::Container::_narrow(container_proxy);
1695       proxy->Shutdown();
1696     }
1697     catch (...)
1698     {
1699       INFOS("[StarPaCOPPContainer] Exception caught from proxy Shutdown...");
1700     }
1701     return ret;
1702   }
1703
1704   // Step 4 : connecting nodes and the proxy to actually create a parallel container
1705   for (int i = 0; i < params.nb_proc; i++)
1706   {
1707     std::ostringstream tmp;
1708     tmp << i;
1709     std::string proc_number = tmp.str();
1710     std::string container_node_name = container_generic_node_name + proc_number;
1711
1712     std::string theNodeMachine(nodes_machines[i]);
1713     std::string containerNameInNS = _NS->BuildContainerNameForNS(container_node_name.c_str(), theNodeMachine.c_str());
1714     obj = _NS->Resolve(containerNameInNS.c_str());
1715     if (CORBA::is_nil(obj))
1716     {
1717       INFOS("[StarPaCOPPContainer] CONNECTION FAILED From Naming Service !");
1718       INFOS("[StarPaCOPPContainer] Container name is " << containerNameInNS);
1719       return ret;
1720     }
1721     try
1722     {
1723       MESSAGE("[StarPaCOPPContainer] Deploying node : " << container_node_name);
1724       PaCO::InterfaceParallel_var node = PaCO::InterfaceParallel::_narrow(obj);
1725       node->deploy();
1726       MESSAGE("[StarPaCOPPContainer] node " << container_node_name << " is deployed");
1727     }
1728     catch(CORBA::SystemException& e)
1729     {
1730       INFOS("[StarPaCOPPContainer] Exception in deploying node : " << containerNameInNS);
1731       INFOS("CORBA::SystemException : " << e);
1732       return ret;
1733     }
1734     catch(CORBA::Exception& e)
1735     {
1736       INFOS("[StarPaCOPPContainer] Exception in deploying node : " << containerNameInNS);
1737       INFOS("CORBA::Exception" << e);
1738       return ret;
1739     }
1740     catch(...)
1741     {
1742       INFOS("[StarPaCOPPContainer] Exception in deploying node : " << containerNameInNS);
1743       INFOS("Unknown exception !");
1744       return ret;
1745     }
1746   }
1747
1748   // Step 5 : starting parallel container
1749   try
1750   {
1751     MESSAGE ("[StarPaCOPPContainer] Starting parallel object");
1752     container_proxy->start();
1753     MESSAGE ("[StarPaCOPPContainer] Parallel object is started");
1754     ret = Engines::Container::_narrow(container_proxy);
1755   }
1756   catch(CORBA::SystemException& e)
1757   {
1758     INFOS("Caught CORBA::SystemException. : " << e);
1759   }
1760   catch(PortableServer::POA::ServantAlreadyActive&)
1761   {
1762     INFOS("Caught CORBA::ServantAlreadyActiveException");
1763   }
1764   catch(CORBA::Exception&)
1765   {
1766     INFOS("Caught CORBA::Exception.");
1767   }
1768   catch(std::exception& exc)
1769   {
1770     INFOS("Caught std::exception - "<<exc.what());
1771   }
1772   catch(...)
1773   {
1774     INFOS("Caught unknown exception.");
1775   }
1776   return ret;
1777 }
1778
1779 std::string
1780 SALOME_ContainerManager::BuildCommandToLaunchPaCOProxyContainer(const Engines::ContainerParameters& params,
1781                                                                 std::string machine_file_name,
1782                                                                 std::string & proxy_hostname)
1783 {
1784   // In the proxy case, we always launch a Dummy Proxy
1785   std::string exe_name = "SALOME_ParallelContainerProxyDummy";
1786   std::string container_name = params.container_name.in();
1787
1788   // Convert nb_proc in string
1789   std::ostringstream tmp_string;
1790   tmp_string << params.nb_proc;
1791   std::string nb_proc_str = tmp_string.str();
1792
1793   // Get resource definition
1794   ParserResourcesType resource_definition =
1795       _resManager->GetResourceDefinition(params.resource_params.name.in());
1796
1797   // Choose hostname
1798   std::string hostname;
1799   std::ifstream machine_file(machine_file_name.c_str());
1800   std::getline(machine_file, hostname, ' ');
1801   size_t found = hostname.find('\n');
1802   if (found!=std::string::npos)
1803     hostname.erase(found, 1); // Remove \n
1804   proxy_hostname = hostname;
1805   MESSAGE("[BuildCommandToLaunchPaCOProxyContainer] machine file name extracted is " << hostname);
1806
1807   // Remote execution
1808   bool remote_execution = false;
1809   if (hostname != std::string(Kernel_Utils::GetHostname()))
1810   {
1811     MESSAGE("[BuildCommandToLaunchPaCOProxyContainer] remote machine case detected !");
1812     remote_execution = true;
1813   }
1814
1815   // Log environment
1816   std::string log_type("");
1817   char * get_val = GetenvThreadSafe("PARALLEL_LOG");
1818   if (get_val)
1819     log_type = get_val;
1820
1821   // Generating the command
1822   std::string command_begin("");
1823   std::string command_end("");
1824   std::ostringstream command;
1825
1826   LogConfiguration(log_type, "proxy", container_name, hostname, command_begin, command_end);
1827   command << command_begin;
1828
1829   // Adding connection command
1830   // We can only have a remote execution with
1831   // a SALOME application
1832   if (remote_execution)
1833   {
1834     ASSERT(GetenvThreadSafe("NSHOST"));
1835     ASSERT(GetenvThreadSafe("NSPORT"));
1836
1837     command << resource_definition.getAccessProtocolTypeStr();
1838     command << " -l ";
1839     command << resource_definition.UserName;
1840     command << " " << hostname;
1841     command << " " << resource_definition.AppliPath;
1842     command << "/runRemote.sh ";
1843     command << GetenvThreadSafeAsString("NSHOST") << " "; // hostname of CORBA name server
1844     command << GetenvThreadSafeAsString("NSPORT") << " "; // port of CORBA name server
1845   }
1846
1847   command << exe_name;
1848   command << " " << container_name;
1849   command << " Dummy";
1850   command << " " << hostname;
1851   command << " " << nb_proc_str;
1852   command << " -";
1853   AddOmninamesParams(command);
1854
1855   // Final command
1856   command << command_end;
1857   MESSAGE("[BuildCommandToLaunchPaCOProxyContainer] Command is: " << command.str());
1858
1859   return command.str();
1860 }
1861
1862 std::string
1863 SALOME_ContainerManager::BuildCommandToLaunchPaCONodeContainer(const Engines::ContainerParameters& params,
1864                                                                const std::string & machine_file_name,
1865                                                                SALOME_ContainerManager::actual_launch_machine_t & vect_machine,
1866                                                                const std::string & proxy_hostname)
1867 {
1868   // Name of exe
1869   std::string exe_name = "SALOME_ParallelContainerNode";
1870   exe_name += params.parallelLib.in();
1871   std::string container_name = params.container_name.in();
1872
1873   // Convert nb_proc in string
1874   std::ostringstream nb_proc_stream;
1875   nb_proc_stream << params.nb_proc;
1876
1877   // Get resource definition
1878   ParserResourcesType resource_definition =
1879       _resManager->GetResourceDefinition(params.resource_params.name.in());
1880
1881   // Log environment
1882   std::string log_type("");
1883   char * get_val = GetenvThreadSafe("PARALLEL_LOG");
1884   if (get_val)
1885     log_type = get_val;
1886
1887   // Now the command is different according to paralleLib
1888   std::ostringstream command_nodes;
1889   std::ifstream machine_file(machine_file_name.c_str());
1890   if (std::string(params.parallelLib.in()) == "Dummy")
1891   {
1892     for (int i= 0; i < params.nb_proc; i++)
1893     {
1894       // Choose hostname
1895       std::string hostname;
1896       std::getline(machine_file, hostname);
1897       MESSAGE("[BuildCommandToLaunchPaCONodeContainer] machine file name extracted is " << hostname);
1898
1899       // Remote execution
1900       bool remote_execution = false;
1901       if (hostname != std::string(Kernel_Utils::GetHostname()))
1902       {
1903         MESSAGE("[BuildCommandToLaunchPaCONodeContainer] remote machine case detected !");
1904         remote_execution = true;
1905       }
1906
1907       // For each node we have a new command
1908       // Generating the command
1909       std::ostringstream command_node_stream;
1910       std::string command_node_begin("");
1911       std::string command_node_end("");
1912       std::ostringstream node_number;
1913       node_number << i;
1914       std::string container_node_name = container_name + node_number.str();
1915       LogConfiguration(log_type, "node", container_node_name, hostname, command_node_begin, command_node_end);
1916
1917       // Adding connection command
1918       // We can only have a remote execution with
1919       // a SALOME application
1920       if (remote_execution)
1921       {
1922         ASSERT(GetenvThreadSafe("NSHOST"));
1923         ASSERT(GetenvThreadSafe("NSPORT"));
1924
1925         command_node_stream << resource_definition.getAccessProtocolTypeStr();
1926         command_node_stream << " -l ";
1927         command_node_stream << resource_definition.UserName;
1928         command_node_stream << " " << hostname;
1929         command_node_stream << " " << resource_definition.AppliPath;
1930         command_node_stream << "/runRemote.sh ";
1931         command_node_stream << GetenvThreadSafeAsString("NSHOST") << " "; // hostname of CORBA name server
1932         command_node_stream << GetenvThreadSafeAsString("NSPORT") << " "; // port of CORBA name server
1933       }
1934
1935       command_node_stream << exe_name;
1936       command_node_stream << " " << container_name;
1937       command_node_stream << " " << params.parallelLib.in();
1938       command_node_stream << " " << proxy_hostname;
1939       command_node_stream << " " << node_number.str();
1940       command_node_stream << " -";
1941       AddOmninamesParams(command_node_stream);
1942
1943       command_nodes << command_node_begin << command_node_stream.str() << command_node_end;
1944       vect_machine.push_back(hostname);
1945     }
1946   }
1947
1948   else if (std::string(params.parallelLib.in()) == "Mpi")
1949   {
1950     // Choose hostname
1951     std::string hostname;
1952     std::getline(machine_file, hostname, ' ');
1953     MESSAGE("[BuildCommandToLaunchPaCONodeContainer] machine file name extracted is " << hostname);
1954
1955     // Remote execution
1956     bool remote_execution = false;
1957     if (hostname != std::string(Kernel_Utils::GetHostname()))
1958     {
1959       MESSAGE("[BuildCommandToLaunchPaCONodeContainer] remote machine case detected !");
1960       remote_execution = true;
1961     }
1962
1963     // In case of Mpi and Remote, we copy machine_file in the applipath
1964     // scp mpi_machine_file user@machine:Path
1965     std::ostringstream command_remote_stream;
1966     std::string::size_type last = machine_file_name.find_last_of("/");
1967     if (last == std::string::npos)
1968       last = -1;
1969
1970     if (resource_definition.Protocol == rsh)
1971       command_remote_stream << "rcp ";
1972     else
1973       command_remote_stream << "scp ";
1974     command_remote_stream << machine_file_name << " ";
1975     command_remote_stream << resource_definition.UserName << "@";
1976     command_remote_stream << hostname << ":" << resource_definition.AppliPath;
1977     command_remote_stream <<  "/" << machine_file_name.substr(last+1);
1978
1979     int status = SystemThreadSafe(command_remote_stream.str().c_str());
1980     if (status == -1)
1981     {
1982       INFOS("copy of the MPI machine file failed ! - sorry !");
1983       return "";
1984     }
1985
1986     // Generating the command
1987     std::string command_begin("");
1988     std::string command_end("");
1989
1990     LogConfiguration(log_type, "nodes", container_name, hostname, command_begin, command_end);
1991     command_nodes << command_begin;
1992
1993     // Adding connection command
1994     // We can only have a remote execution with
1995     // a SALOME application
1996     if (remote_execution)
1997     {
1998       ASSERT(GetenvThreadSafe("NSHOST"));
1999       ASSERT(GetenvThreadSafe("NSPORT"));
2000
2001       command_nodes << resource_definition.getAccessProtocolTypeStr();
2002       command_nodes << " -l ";
2003       command_nodes << resource_definition.UserName;
2004       command_nodes << " " << hostname;
2005       command_nodes << " " << resource_definition.AppliPath;
2006       command_nodes << "/runRemote.sh ";
2007       command_nodes << GetenvThreadSafeAsString("NSHOST") << " "; // hostname of CORBA name server
2008       command_nodes << GetenvThreadSafeAsString("NSPORT") << " "; // port of CORBA name server
2009     }
2010
2011     if (resource_definition.mpi == lam)
2012     {
2013       command_nodes << "mpiexec -ssi boot ";
2014       command_nodes << "-machinefile "  << machine_file_name << " ";
2015       command_nodes <<  "-n " << params.nb_proc;
2016     }
2017     else
2018     {
2019       command_nodes << "mpirun -np " << params.nb_proc;
2020     }
2021     command_nodes << " " << exe_name;
2022     command_nodes << " " << container_name;
2023     command_nodes << " " << params.parallelLib.in();
2024     command_nodes << " " << proxy_hostname;
2025     command_nodes << " -";
2026     AddOmninamesParams(command_nodes);
2027
2028     // We don't put hostname, because nodes are registered in the resource of the proxy
2029     for (int i= 0; i < params.nb_proc; i++)
2030       vect_machine.push_back(proxy_hostname);
2031
2032     command_nodes << command_end;
2033   }
2034   return command_nodes.str();
2035 }
2036
2037 void
2038 SALOME_ContainerManager::LogConfiguration(const std::string & log_type,
2039                                           const std::string & exe_type,
2040                                           const std::string & container_name,
2041                                           const std::string & hostname,
2042                                           std::string & begin,
2043                                           std::string & end)
2044 {
2045   if(log_type == "xterm")
2046   {
2047     begin = "xterm -e \"export LD_LIBRARY_PATH=$LD_LIBRARY_PATH; export PATH=$PATH;";
2048     end   = "\"&";
2049   }
2050   else if(log_type == "xterm_debug")
2051   {
2052     begin = "xterm -e \"export LD_LIBRARY_PATH=$LD_LIBRARY_PATH; export PATH=$PATH;";
2053     end   = "; cat \" &";
2054   }
2055   else
2056   {
2057     // default into a file...
2058     std::string logFilename = "/tmp/" + container_name + "_" + hostname + "_" + exe_type + "_";
2059     std::string user = GetenvThreadSafeAsString("USER");
2060     if (user.empty())
2061       user = GetenvThreadSafeAsString("LOGNAME");
2062     logFilename += user + ".log";
2063     end = " > " + logFilename + " 2>&1 & ";
2064   }
2065 }
2066
2067 CORBA::Object_ptr
2068 SALOME_ContainerManager::LaunchPaCOProxyContainer(const std::string& command,
2069                                                   const Engines::ContainerParameters& params,
2070                                                   const std::string & hostname)
2071 {
2072   PaCO::InterfaceManager_ptr container_proxy = PaCO::InterfaceManager::_nil();
2073
2074   MESSAGE("[LaunchPaCOProxyContainer] Launch command");
2075   int status = SystemThreadSafe(command.c_str());
2076   if (status == -1) {
2077     INFOS("[LaunchPaCOProxyContainer] failed : system command status -1");
2078     return container_proxy;
2079   }
2080   else if (status == 217) {
2081     INFOS("[LaunchPaCOProxyContainer] failed : system command status 217");
2082     return container_proxy;
2083   }
2084
2085   int count(GetTimeOutToLoaunchServer());
2086   CORBA::Object_var obj = CORBA::Object::_nil();
2087   std::string containerNameInNS = _NS->BuildContainerNameForNS(params.container_name.in(),
2088                                                                hostname.c_str());
2089   MESSAGE("[LaunchParallelContainer]  Waiting for Parallel Container proxy : " << containerNameInNS);
2090
2091   while (CORBA::is_nil(obj) && count)
2092   {
2093     sleep(1);
2094     count--;
2095     obj = _NS->Resolve(containerNameInNS.c_str());
2096   }
2097
2098   try
2099   {
2100     container_proxy = PaCO::InterfaceManager::_narrow(obj);
2101   }
2102   catch(CORBA::SystemException& e)
2103   {
2104     INFOS("[StarPaCOPPContainer] Exception in _narrow after LaunchParallelContainer for proxy !");
2105     INFOS("CORBA::SystemException : " << e);
2106     return container_proxy;
2107   }
2108   catch(CORBA::Exception& e)
2109   {
2110     INFOS("[StarPaCOPPContainer] Exception in _narrow after LaunchParallelContainer for proxy !");
2111     INFOS("CORBA::Exception" << e);
2112     return container_proxy;
2113   }
2114   catch(...)
2115   {
2116     INFOS("[StarPaCOPPContainer] Exception in _narrow after LaunchParallelContainer for proxy !");
2117     INFOS("Unknown exception !");
2118     return container_proxy;
2119   }
2120   if (CORBA::is_nil(container_proxy))
2121   {
2122     INFOS("[StarPaCOPPContainer] PaCO::InterfaceManager::_narrow returns NIL !");
2123     return container_proxy;
2124   }
2125   return obj._retn();
2126 }
2127
2128 //=============================================================================
2129 /*! This method launches the parallel container.
2130  *  It will may be placed on the resources manager.
2131  *
2132  * \param command to launch
2133  * \param container's parameters
2134  * \param name of the container
2135  *
2136  * \return CORBA container reference
2137  */
2138 //=============================================================================
2139 bool
2140 SALOME_ContainerManager::LaunchPaCONodeContainer(const std::string& command,
2141                                                  const Engines::ContainerParameters& params,
2142                                                  const std::string& name,
2143                                                  SALOME_ContainerManager::actual_launch_machine_t & vect_machine)
2144 {
2145   INFOS("[LaunchPaCONodeContainer] Launch command");
2146   int status = SystemThreadSafe(command.c_str());
2147   if (status == -1) {
2148     INFOS("[LaunchPaCONodeContainer] failed : system command status -1");
2149     return false;
2150   }
2151   else if (status == 217) {
2152     INFOS("[LaunchPaCONodeContainer] failed : system command status 217");
2153     return false;
2154   }
2155
2156   INFOS("[LaunchPaCONodeContainer] Waiting for the nodes of the parallel container");
2157   // We are waiting all the nodes
2158   for (int i = 0; i < params.nb_proc; i++)
2159   {
2160     CORBA::Object_var obj = CORBA::Object::_nil();
2161     std::string theMachine(vect_machine[i]);
2162     // Name of the node
2163     std::ostringstream tmp;
2164     tmp << i;
2165     std::string proc_number = tmp.str();
2166     std::string container_node_name = name + proc_number;
2167     std::string containerNameInNS = _NS->BuildContainerNameForNS((char*) container_node_name.c_str(), theMachine.c_str());
2168     INFOS("[LaunchPaCONodeContainer]  Waiting for Parallel Container node " << containerNameInNS << " on " << theMachine);
2169     int count(GetTimeOutToLoaunchServer());
2170     while (CORBA::is_nil(obj) && count) {
2171       SleepInSecond(1);
2172       count-- ;
2173       obj = _NS->Resolve(containerNameInNS.c_str());
2174     }
2175     if (CORBA::is_nil(obj))
2176     {
2177       INFOS("[LaunchPaCONodeContainer] Launch of node failed (or not found) !");
2178       return false;
2179     }
2180   }
2181   return true;
2182 }
2183
2184 #else
2185
2186 Engines::Container_ptr
2187 SALOME_ContainerManager::StartPaCOPPContainer(const Engines::ContainerParameters& /*params*/,
2188                                               std::string /*resource_selected*/)
2189 {
2190   Engines::Container_ptr ret = Engines::Container::_nil();
2191   INFOS("[StarPaCOPPContainer] is disabled !");
2192   INFOS("[StarPaCOPPContainer] recompile SALOME Kernel to enable PaCO++ parallel extension");
2193   return ret;
2194 }
2195
2196 std::string
2197 SALOME_ContainerManager::BuildCommandToLaunchPaCOProxyContainer(const Engines::ContainerParameters& /*params*/,
2198                                                                 std::string /*machine_file_name*/,
2199                                                                 std::string & /*proxy_hostname*/)
2200 {
2201   return "";
2202 }
2203
2204 std::string
2205 SALOME_ContainerManager::BuildCommandToLaunchPaCONodeContainer(const Engines::ContainerParameters& /*params*/,
2206                                                                const std::string & /*machine_file_name*/,
2207                                                                SALOME_ContainerManager::actual_launch_machine_t & /*vect_machine*/,
2208                                                                const std::string & /*proxy_hostname*/)
2209 {
2210   return "";
2211 }
2212 void
2213 SALOME_ContainerManager::LogConfiguration(const std::string & /*log_type*/,
2214                                           const std::string & /*exe_type*/,
2215                                           const std::string & /*container_name*/,
2216                                           const std::string & /*hostname*/,
2217                                           std::string & /*begin*/,
2218                                           std::string & /*end*/)
2219 {
2220 }
2221
2222 CORBA::Object_ptr
2223 SALOME_ContainerManager::LaunchPaCOProxyContainer(const std::string& /*command*/,
2224                                                   const Engines::ContainerParameters& /*params*/,
2225                                                   const std::string& /*hostname*/)
2226 {
2227   CORBA::Object_ptr ret = CORBA::Object::_nil();
2228   return ret;
2229 }
2230
2231 bool
2232 SALOME_ContainerManager::LaunchPaCONodeContainer(const std::string& /*command*/,
2233                         const Engines::ContainerParameters& /*params*/,
2234                         const std::string& /*name*/,
2235                         SALOME_ContainerManager::actual_launch_machine_t & /*vect_machine*/)
2236 {
2237   return false;
2238 }
2239 #endif