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