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