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