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