Salome HOME
Merge from V6_main_20120808 08Aug12
[modules/kernel.git] / src / ResourcesManager / SALOME_ResourcesManager.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_ResourcesManager.hxx" 
24 #include "Utils_ExceptHandlers.hxx"
25 #include "Utils_CorbaException.hxx"
26 #include "OpUtil.hxx"
27
28 #include <stdlib.h>
29 #include <stdio.h>
30 #ifndef WIN32
31 #include <unistd.h>
32 #else
33 #include <io.h>
34 #include <process.h>
35 #endif
36 #include <fstream>
37 #include <iostream>
38 #include <sstream>
39 #include <string.h>
40 #include <map>
41 #include <list>
42
43 #include <sys/types.h>
44 #include <sys/stat.h>
45 #include "utilities.h"
46
47 #define MAX_SIZE_FOR_HOSTNAME 256;
48
49 const char *SALOME_ResourcesManager::_ResourcesManagerNameInNS = "/ResourcesManager";
50
51 //=============================================================================
52 /*!
53  * just for test
54  */ 
55 //=============================================================================
56
57 SALOME_ResourcesManager::
58 SALOME_ResourcesManager(CORBA::ORB_ptr orb, 
59                         PortableServer::POA_var poa, 
60                         SALOME_NamingService *ns,
61                         const char *xmlFilePath) : _rm(xmlFilePath)
62 {
63   MESSAGE("SALOME_ResourcesManager constructor");
64   _NS = ns;
65   _orb = CORBA::ORB::_duplicate(orb) ;
66   _poa = PortableServer::POA::_duplicate(poa) ;
67   PortableServer::ObjectId_var id = _poa->activate_object(this);
68   CORBA::Object_var obj = _poa->id_to_reference(id);
69   Engines::ResourcesManager_var refContMan = Engines::ResourcesManager::_narrow(obj);
70   _NS->Register(refContMan,_ResourcesManagerNameInNS);
71   MESSAGE("SALOME_ResourcesManager constructor end");
72 }
73
74 //=============================================================================
75 /*!
76  *  Standard constructor, parse resource file.
77  *  - if ${APPLI} exists in environment,
78  *    look for ${HOME}/${APPLI}/CatalogResources.xml
79  *  - else look for default:
80  *    ${KERNEL_ROOT_DIR}/share/salome/resources/kernel/CatalogResources.xml
81  *  - parse XML resource file.
82  */ 
83 //=============================================================================
84
85 SALOME_ResourcesManager::SALOME_ResourcesManager(CORBA::ORB_ptr orb, 
86                                                  PortableServer::POA_var poa, 
87                                                  SALOME_NamingService *ns) : _rm()
88 {
89   MESSAGE("SALOME_ResourcesManager constructor");
90   _NS = ns;
91   _orb = CORBA::ORB::_duplicate(orb) ;
92   _poa = PortableServer::POA::_duplicate(poa) ;
93   PortableServer::ObjectId_var id = _poa->activate_object(this);
94   CORBA::Object_var obj = _poa->id_to_reference(id);
95   Engines::ResourcesManager_var refContMan = Engines::ResourcesManager::_narrow(obj);
96   _NS->Register(refContMan,_ResourcesManagerNameInNS);
97
98   MESSAGE("SALOME_ResourcesManager constructor end");
99 }
100
101 //=============================================================================
102 /*!
103  *  Standard Destructor
104  */ 
105 //=============================================================================
106
107 SALOME_ResourcesManager::~SALOME_ResourcesManager()
108 {
109   MESSAGE("SALOME_ResourcesManager destructor");
110 }
111
112
113 //=============================================================================
114 /*! CORBA method:
115  *  shutdown all the containers, then the ContainerManager servant
116  */
117 //=============================================================================
118
119 void SALOME_ResourcesManager::Shutdown()
120 {
121   MESSAGE("Shutdown");
122   _NS->Destroy_Name(_ResourcesManagerNameInNS);
123   PortableServer::ObjectId_var oid = _poa->servant_to_id(this);
124   _poa->deactivate_object(oid);
125 }
126
127 //=============================================================================
128 //! get the name of resources fitting the specified constraints (params)
129 /*!
130  *  If hostname specified, check it is local or known in resources catalog.
131  *
132  *  Else
133  *  - select first machines with corresponding OS (all machines if
134  *    parameter OS empty),
135  *  - then select the sublist of machines on which the component is known
136  *    (if the result is empty, that probably means that the inventory of
137  *    components is probably not done, so give complete list from previous step)
138  */ 
139 //=============================================================================
140
141 Engines::ResourceList *
142 SALOME_ResourcesManager::GetFittingResources(const Engines::ResourceParameters& params)
143 {
144   MESSAGE("ResourcesManager::GetFittingResources");
145   Engines::ResourceList * ret = new Engines::ResourceList;
146
147   // CORBA -> C++
148   resourceParams p;
149   p.name = params.name;
150   p.hostname = params.hostname;
151   p.OS = params.OS;
152   p.nb_proc = params.nb_proc;
153   p.nb_node = params.nb_node;
154   p.nb_proc_per_node = params.nb_proc_per_node;
155   p.cpu_clock = params.cpu_clock;
156   p.mem_mb = params.mem_mb;
157   for(unsigned int i=0; i<params.componentList.length(); i++)
158     p.componentList.push_back(std::string(params.componentList[i]));
159   for(unsigned int i=0; i<params.resList.length(); i++)
160     p.resourceList.push_back(std::string(params.resList[i]));
161   
162   try
163   {
164     // Call C++ ResourceManager
165     std::vector <std::string> vec = _rm.GetFittingResources(p);
166
167     // C++ -> CORBA
168     ret->length(vec.size());
169     for(unsigned int i=0;i<vec.size();i++)
170       (*ret)[i] = (vec[i]).c_str();
171   }
172   catch(const ResourcesException &ex)
173   {
174     INFOS("Caught exception in GetFittingResources C++:  " << ex.msg);
175     THROW_SALOME_CORBA_EXCEPTION(ex.msg.c_str(),SALOME::BAD_PARAM);
176   }  
177
178   return ret;
179 }
180
181 //=============================================================================
182 /*!
183  *  dynamically obtains the first machines
184  */ 
185 //=============================================================================
186
187 char *
188 SALOME_ResourcesManager::FindFirst(const Engines::ResourceList& listOfResources)
189 {
190   // CORBA -> C++
191   std::vector<std::string> rl;
192   for(unsigned int i=0; i<listOfResources.length(); i++)
193     rl.push_back(std::string(listOfResources[i]));
194
195   return CORBA::string_dup(_rm.Find("first", rl).c_str());
196 }
197
198 char *
199 SALOME_ResourcesManager::Find(const char* policy, const Engines::ResourceList& listOfResources)
200 {
201   // CORBA -> C++
202   std::vector<std::string> rl;
203   for(unsigned int i=0; i<listOfResources.length(); i++)
204     rl.push_back(std::string(listOfResources[i]));
205
206   return CORBA::string_dup(_rm.Find(policy, rl).c_str());
207 }
208
209 Engines::ResourceDefinition* 
210 SALOME_ResourcesManager::GetResourceDefinition(const char * name)
211 {
212   ParserResourcesType resource = _rm.GetResourcesDescr(name);
213   Engines::ResourceDefinition *p_ptr = new Engines::ResourceDefinition;
214
215   p_ptr->name = CORBA::string_dup(resource.Name.c_str());
216   p_ptr->hostname = CORBA::string_dup(resource.HostName.c_str());
217   p_ptr->protocol = ParserResourcesType::protocolToString(resource.Protocol).c_str();
218   p_ptr->iprotocol = ParserResourcesType::protocolToString(resource.ClusterInternalProtocol).c_str();
219   p_ptr->username = CORBA::string_dup(resource.UserName.c_str());
220   p_ptr->applipath = CORBA::string_dup(resource.AppliPath.c_str());
221   p_ptr->componentList.length(resource.ComponentsList.size());
222   for(unsigned int i=0;i<resource.ComponentsList.size();i++)
223     p_ptr->componentList[i] = CORBA::string_dup(resource.ComponentsList[i].c_str());
224   p_ptr->OS = CORBA::string_dup(resource.OS.c_str());
225   p_ptr->mem_mb = resource.DataForSort._memInMB;
226   p_ptr->cpu_clock = resource.DataForSort._CPUFreqMHz;
227   p_ptr->nb_proc_per_node = resource.DataForSort._nbOfProcPerNode;
228   p_ptr->nb_node = resource.DataForSort._nbOfNodes;
229   p_ptr->is_cluster_head = resource.is_cluster_head;
230   p_ptr->working_directory = CORBA::string_dup(resource.working_directory.c_str());
231
232   if( resource.mpi == lam )
233     p_ptr->mpiImpl = "lam";
234   else if( resource.mpi == mpich1 )
235     p_ptr->mpiImpl = "mpich1";
236   else if( resource.mpi == mpich2 )
237     p_ptr->mpiImpl = "mpich2";
238   else if( resource.mpi == openmpi )
239     p_ptr->mpiImpl = "openmpi";
240   else if( resource.mpi == slurmmpi )
241     p_ptr->mpiImpl = "slurmmpi";
242   else if( resource.mpi == prun )
243     p_ptr->mpiImpl = "prun";
244
245   if( resource.Batch == pbs )
246     p_ptr->batch = "pbs";
247   else if( resource.Batch == lsf )
248     p_ptr->batch = "lsf";
249   else if( resource.Batch == sge )
250     p_ptr->batch = "sge";
251   else if( resource.Batch == ccc )
252     p_ptr->batch = "ccc";
253   else if( resource.Batch == slurm )
254     p_ptr->batch = "slurm";
255   else if( resource.Batch == ssh_batch )
256     p_ptr->batch = "ssh";
257   else if( resource.Batch == ll )
258     p_ptr->batch = "ll";
259   else if( resource.Batch == vishnu )
260     p_ptr->batch = "vishnu";
261
262   return p_ptr;
263 }
264
265 void 
266 SALOME_ResourcesManager::AddResource(const Engines::ResourceDefinition& new_resource,
267                                      CORBA::Boolean write,
268                                      const char * xml_file)
269 {
270   ParserResourcesType resource;
271   resource.Name = new_resource.name.in();
272   resource.HostName = new_resource.hostname.in();
273   resource.OS = new_resource.OS.in();
274   resource.AppliPath = new_resource.applipath.in();
275   resource.DataForSort._memInMB = new_resource.mem_mb;
276   resource.DataForSort._CPUFreqMHz = new_resource.cpu_clock;
277   resource.DataForSort._nbOfNodes = new_resource.nb_node;
278   resource.DataForSort._nbOfProcPerNode = new_resource.nb_proc_per_node;
279   resource.UserName = new_resource.username.in();
280   resource.is_cluster_head = new_resource.is_cluster_head;
281   resource.working_directory = new_resource.working_directory.in();
282
283   std::string aBatch = new_resource.batch.in();
284   if (aBatch == "pbs")
285     resource.Batch = pbs;
286   else if  (aBatch == "lsf")
287     resource.Batch = lsf;
288   else if  (aBatch == "sge")
289     resource.Batch = sge;
290   else if  (aBatch == "slurm")
291     resource.Batch = slurm;
292   else if  (aBatch == "ccc")
293     resource.Batch = ccc;
294   else if  (aBatch == "ssh_batch")
295     resource.Batch = ssh_batch;
296   else if  (aBatch == "ll")
297     resource.Batch = ll;
298   else if  (aBatch == "vishnu")
299     resource.Batch = vishnu;
300   else if (aBatch == "")
301     resource.Batch = none;
302   else {
303     INFOS("Bad Batch definition in AddResource: " << aBatch);
304     std::string message("Bad Batch definition in AddResource: ");
305     message += aBatch;
306     THROW_SALOME_CORBA_EXCEPTION(message.c_str(),SALOME::BAD_PARAM);
307   }
308
309   std::string anMpi = new_resource.mpiImpl.in();
310   if (anMpi == "lam")
311     resource.mpi = lam;
312   else if (anMpi == "mpich1")
313     resource.mpi = mpich1;
314   else if (anMpi == "mpich2")
315     resource.mpi = mpich2;
316   else if (anMpi == "openmpi")
317     resource.mpi = openmpi;
318   else if  (anMpi == "slurmmpi")
319     resource.mpi = slurmmpi;
320   else if  (anMpi == "prun")
321     resource.mpi = prun;
322   else if (anMpi == "")
323     resource.mpi = nompi;
324   else {
325     INFOS("Bad MPI definition in AddResource: " << anMpi);
326     std::string message("Bad MPI definition in AddResource: ");
327     message += anMpi;
328     THROW_SALOME_CORBA_EXCEPTION(message.c_str(),SALOME::BAD_PARAM);
329   }
330
331   std::string mode_str = new_resource.mode.in();
332   if (mode_str == "interactive")
333     resource.Mode = interactive;
334   else if (mode_str == "batch")
335     resource.Mode = batch;
336   else if (mode_str == "")
337     resource.Mode = interactive;
338   else {
339     INFOS("Bad mode definition in AddResource: " << mode_str);
340     std::string message("Bad mode definition in AddResource: ");
341     message += mode_str;
342     THROW_SALOME_CORBA_EXCEPTION(message.c_str(),SALOME::BAD_PARAM);
343   }
344   
345   std::string protocol = new_resource.protocol.in();
346   try
347   {
348     resource.Protocol = ParserResourcesType::stringToProtocol(protocol);
349   }
350   catch (SALOME_Exception e)
351   {
352     INFOS("Bad protocol definition in AddResource: " << protocol);
353     std::string message("Bad protocol definition in AddResource: ");
354     message += protocol;
355     THROW_SALOME_CORBA_EXCEPTION(message.c_str(),SALOME::BAD_PARAM);
356   }
357
358   std::string iprotocol = new_resource.iprotocol.in();
359   try
360   {
361     resource.ClusterInternalProtocol = ParserResourcesType::stringToProtocol(iprotocol);
362   }
363   catch (SALOME_Exception e)
364   {
365     INFOS("Bad iprotocol definition in AddResource: " << iprotocol);
366     std::string message("Bad iprotocol definition in AddResource: ");
367     message += iprotocol;
368     THROW_SALOME_CORBA_EXCEPTION(message.c_str(),SALOME::BAD_PARAM);
369   }
370
371   for (CORBA::ULong i = 0; i < new_resource.componentList.length(); i++)
372     resource.ComponentsList.push_back(new_resource.componentList[i].in());
373
374   _rm.AddResourceInCatalog(resource);
375
376   if (write)
377   {
378     _rm.WriteInXmlFile(std::string(xml_file));
379     _rm.ParseXmlFiles();
380   }
381 }
382
383 void
384 SALOME_ResourcesManager::RemoveResource(const char * resource_name,
385                                         CORBA::Boolean write,
386                                         const char * xml_file)
387 {
388   _rm.DeleteResourceInCatalog(resource_name);
389   if (write)
390   {
391     _rm.WriteInXmlFile(std::string(xml_file));
392     _rm.ParseXmlFiles();
393   }
394 }
395
396 std::string 
397 SALOME_ResourcesManager::getMachineFile(std::string resource_name, 
398                                         CORBA::Long nb_procs, 
399                                         std::string parallelLib)
400 {
401   std::string machine_file_name("");
402
403   if (parallelLib == "Dummy")
404   {
405     MESSAGE("[getMachineFile] parallelLib is Dummy");
406     MapOfParserResourcesType resourcesList = _rm.GetList();
407     if (resourcesList.find(resource_name) != resourcesList.end())
408     {
409       ParserResourcesType resource = resourcesList[resource_name];
410
411       // Check if resource is cluster or not
412       if (resource.ClusterMembersList.empty())
413       {
414         //It is not a cluster so we create a cluster with one machine
415         ParserResourcesClusterMembersType fake_node;
416         fake_node.HostName = resource.HostName;
417         fake_node.Protocol = resource.Protocol;
418         fake_node.ClusterInternalProtocol = resource.ClusterInternalProtocol;
419         fake_node.UserName = resource.UserName;
420         fake_node.AppliPath = resource.AppliPath;
421         fake_node.DataForSort = resource.DataForSort;
422
423         resource.ClusterMembersList.push_front(fake_node);
424       }
425
426       // Creating list of machines for creating the machine file
427       std::list<std::string> list_of_machines;
428       std::list<ParserResourcesClusterMembersType>::iterator cluster_it = 
429         resource.ClusterMembersList.begin();
430       while (cluster_it != resource.ClusterMembersList.end())
431       {
432         // For each member of the cluster we add a nbOfNodes * nbOfProcPerNode in the list
433         unsigned int number_of_proc = (*cluster_it).DataForSort._nbOfNodes * 
434                                       (*cluster_it).DataForSort._nbOfProcPerNode;
435         for (unsigned int i = 0; i < number_of_proc; i++)
436           list_of_machines.push_back((*cluster_it).HostName);
437         cluster_it++;
438       }
439
440       // Creating machine file
441       machine_file_name = tmpnam(NULL);
442       std::ofstream machine_file(machine_file_name.c_str(), std::ios_base::out);
443
444       CORBA::Long machine_number = 0;
445       std::list<std::string>::iterator it = list_of_machines.begin();
446       while (machine_number != nb_procs)
447       {
448         // Adding a new node to the machine file
449         machine_file << *it << std::endl;
450
451         // counting...
452         it++;
453         if (it == list_of_machines.end())
454           it = list_of_machines.begin();
455         machine_number++;
456       }
457     }
458     else
459       INFOS("[getMachineFile] Error resource_name not found in resourcesList -> " << resource_name);
460   }
461   else if (parallelLib == "Mpi")
462   {
463     MESSAGE("[getMachineFile] parallelLib is Mpi");
464
465     MapOfParserResourcesType resourcesList = _rm.GetList();
466     if (resourcesList.find(resource_name) != resourcesList.end())
467     {
468       ParserResourcesType resource = resourcesList[resource_name];
469       // Check if resource is cluster or not
470       if (resource.ClusterMembersList.empty())
471       {
472         //It is not a cluster so we create a cluster with one machine
473         ParserResourcesClusterMembersType fake_node;
474         fake_node.HostName = resource.HostName;
475         fake_node.Protocol = resource.Protocol;
476         fake_node.ClusterInternalProtocol = resource.ClusterInternalProtocol;
477         fake_node.UserName = resource.UserName;
478         fake_node.AppliPath = resource.AppliPath;
479         fake_node.DataForSort = resource.DataForSort;
480
481         resource.ClusterMembersList.push_front(fake_node);
482       }
483
484       // Choose mpi implementation -> each MPI implementation has is own machinefile...
485       if (resource.mpi == lam)
486       {
487         // Creating machine file
488         machine_file_name = tmpnam(NULL);
489         std::ofstream machine_file(machine_file_name.c_str(), std::ios_base::out);
490
491         // We add all cluster machines to the file
492         std::list<ParserResourcesClusterMembersType>::iterator cluster_it = 
493           resource.ClusterMembersList.begin();
494         while (cluster_it != resource.ClusterMembersList.end())
495         {
496           unsigned int number_of_proc = (*cluster_it).DataForSort._nbOfNodes * 
497             (*cluster_it).DataForSort._nbOfProcPerNode;
498           machine_file << (*cluster_it).HostName << " cpu=" << number_of_proc << std::endl;
499           cluster_it++;
500         }
501       }
502       else if (resource.mpi == openmpi)
503       {
504         // Creating machine file
505         machine_file_name = tmpnam(NULL);
506         std::ofstream machine_file(machine_file_name.c_str(), std::ios_base::out);
507
508         // We add all cluster machines to the file
509         std::list<ParserResourcesClusterMembersType>::iterator cluster_it =
510           resource.ClusterMembersList.begin();
511         while (cluster_it != resource.ClusterMembersList.end())
512         {
513           unsigned int number_of_proc = (*cluster_it).DataForSort._nbOfNodes *
514             (*cluster_it).DataForSort._nbOfProcPerNode;
515           machine_file << (*cluster_it).HostName << " slots=" << number_of_proc << std::endl;
516           cluster_it++;
517         }
518       }
519       else if (resource.mpi == nompi)
520       {
521         INFOS("[getMachineFile] Error resource_name MPI implementation was defined for " << resource_name);
522       }
523       else
524         INFOS("[getMachineFile] Error resource_name MPI implementation not currenly handled for " << resource_name);
525     }
526     else
527       INFOS("[getMachineFile] Error resource_name not found in resourcesList -> " << resource_name);
528   }
529   else
530     INFOS("[getMachineFile] Error parallelLib is not handled -> " << parallelLib);
531
532   return machine_file_name;
533 }