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