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