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