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