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