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