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