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