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