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