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