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