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