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