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