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