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