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