Salome HOME
updated copyright message
[modules/kernel.git] / src / ResourcesManager / SALOME_ResourcesManager.cxx
1 // Copyright (C) 2007-2023  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, or (at your option) any later version.
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 using namespace std;
50
51 const char *SALOME_ResourcesManager::_ResourcesManagerNameInNS = "/ResourcesManager";
52
53 //=============================================================================
54 /*!
55  * just for test
56  */ 
57 //=============================================================================
58
59 SALOME_ResourcesManager::SALOME_ResourcesManager(CORBA::ORB_ptr orb,
60                                                  PortableServer::POA_var poa,
61                                                  SALOME_NamingService_Abstract *ns,
62                                                  const char *xmlFilePath)
63 : _rm(new ResourcesManager_cpp(xmlFilePath))
64 {
65   MESSAGE("SALOME_ResourcesManager constructor");
66   _NS = ns;
67   _orb = CORBA::ORB::_duplicate(orb) ;
68   //
69   PortableServer::POAManager_var pman = poa->the_POAManager();
70   CORBA::PolicyList policies;
71   policies.length(1);
72   PortableServer::ThreadPolicy_var threadPol(poa->create_thread_policy(PortableServer::SINGLE_THREAD_MODEL));
73   policies[0] = PortableServer::ThreadPolicy::_duplicate(threadPol);
74   _poa = poa->create_POA("SingleThreadPOA",pman,policies);
75   threadPol->destroy();
76   //
77   PortableServer::ObjectId_var id = _poa->activate_object(this);
78   CORBA::Object_var obj = _poa->id_to_reference(id);
79   Engines::ResourcesManager_var refContMan = Engines::ResourcesManager::_narrow(obj);
80   _NS->Register(refContMan,_ResourcesManagerNameInNS);
81   MESSAGE("SALOME_ResourcesManager constructor end");
82 }
83
84 //=============================================================================
85 /*!
86  *  Standard constructor, parse resource file.
87  *  - if ${APPLI} exists in environment,
88  *    look for ${HOME}/${APPLI}/CatalogResources.xml
89  *  - else look for default:
90  *    ${KERNEL_ROOT_DIR}/share/salome/resources/kernel/CatalogResources.xml
91  *  - parse XML resource file.
92  */ 
93 //=============================================================================
94
95 SALOME_ResourcesManager::SALOME_ResourcesManager(CORBA::ORB_ptr orb, 
96                                                  PortableServer::POA_var poa, 
97                                                  SALOME_NamingService_Abstract *ns) : _rm(new ResourcesManager_cpp())
98 {
99   MESSAGE("SALOME_ResourcesManager constructor");
100   _NS = ns;
101   _orb = CORBA::ORB::_duplicate(orb) ;
102   //
103   PortableServer::POAManager_var pman = poa->the_POAManager();
104   CORBA::PolicyList policies;
105   policies.length(1);
106   PortableServer::ThreadPolicy_var threadPol(poa->create_thread_policy(PortableServer::SINGLE_THREAD_MODEL));
107   policies[0] = PortableServer::ThreadPolicy::_duplicate(threadPol);
108   _poa = poa->create_POA("SingleThreadPOA",pman,policies);
109   threadPol->destroy();
110   //
111   PortableServer::ObjectId_var id = _poa->activate_object(this);
112   CORBA::Object_var obj = _poa->id_to_reference(id);
113   Engines::ResourcesManager_var refContMan = Engines::ResourcesManager::_narrow(obj);
114   if(_NS)
115     _NS->Register(refContMan,_ResourcesManagerNameInNS);
116
117   MESSAGE("SALOME_ResourcesManager constructor end");
118 }
119
120 //=============================================================================
121 /*!
122  *  Standard Destructor
123  */ 
124 //=============================================================================
125
126 SALOME_ResourcesManager::~SALOME_ResourcesManager()
127 {
128   MESSAGE("SALOME_ResourcesManager destructor");
129 }
130
131
132 //=============================================================================
133 /*! CORBA method:
134  *  shutdown all the containers, then the ContainerManager servant
135  */
136 //=============================================================================
137
138 void SALOME_ResourcesManager::Shutdown()
139 {
140   MESSAGE("Shutdown");
141   if(!_NS)
142     return ;
143   _NS->Destroy_Name(_ResourcesManagerNameInNS);
144   PortableServer::ObjectId_var oid = _poa->servant_to_id(this);
145   _poa->deactivate_object(oid);
146 }
147
148 /*!
149  * Return list of resources available (regarding content of CatalogResources.xml) but select only those with canRunContainers attribute set to true.
150  * And for each resource the number of proc available of it.
151  * 
152  * \sa SALOME_ResourcesManager::ListAllResourcesInCatalog
153  */
154 void SALOME_ResourcesManager::ListAllAvailableResources(Engines::ResourceList_out machines, Engines::IntegerList_out nbProcsOfMachines)
155 {
156   const MapOfParserResourcesType& zeList(_rm->GetList());
157   std::vector<std::string> ret0;
158   std::vector<int> ret1;
159   for(MapOfParserResourcesType::const_iterator it=zeList.begin();it!=zeList.end();it++)
160   {
161     const ParserResourcesType& elt((*it).second);
162     if(elt.can_run_containers)
163     {
164       ret0.push_back(elt.HostName);
165       ret1.push_back(elt.DataForSort._nbOfNodes*elt.DataForSort._nbOfProcPerNode);
166     }
167   }
168   machines=new Engines::ResourceList;
169   nbProcsOfMachines=new Engines::IntegerList;
170   std::size_t sz(ret0.size());
171   machines->length((CORBA::ULong)sz); nbProcsOfMachines->length((CORBA::ULong)sz);
172   for(std::size_t j=0;j<sz;j++)
173     {
174       (*machines)[(CORBA::ULong)j]=CORBA::string_dup(ret0[j].c_str());
175       (*nbProcsOfMachines)[(CORBA::ULong)j]=ret1[j];
176     }
177 }
178
179 /*!
180  * Return list of resources available (regarding content of CatalogResources.xml) whatever canRunContainers attribute value.
181  * 
182  * \sa SALOME_ResourcesManager::ListAllAvailableResources
183  */
184 Engines::ResourceList *SALOME_ResourcesManager::ListAllResourcesInCatalog()
185 {
186   const MapOfParserResourcesType& zeList(_rm->GetList());
187   auto sz = zeList.size();
188   Engines::ResourceList *ret(new Engines::ResourceList);
189   ret->length( sz );
190   CORBA::ULong i(0);
191   for(auto it : zeList)
192   {
193     (*ret)[i++] = CORBA::string_dup( it.second.HostName.c_str() );
194   }
195   return ret;
196 }
197
198 //=============================================================================
199 //! get the name of resources fitting the specified constraints (params)
200 /*!
201  *  If hostname specified, check it is local or known in resources catalog.
202  *
203  *  Else
204  *  - select first machines with corresponding OS (all machines if
205  *    parameter OS empty),
206  *  - then select the sublist of machines on which the component is known
207  *    (if the result is empty, that probably means that the inventory of
208  *    components is probably not done, so give complete list from previous step)
209  */ 
210 //=============================================================================
211
212 Engines::ResourceList *
213 SALOME_ResourcesManager::GetFittingResources(const Engines::ResourceParameters& params)
214 {
215   //MESSAGE("ResourcesManager::GetFittingResources");
216   Engines::ResourceList_var ret;
217
218   // CORBA -> C++
219   resourceParams p = resourceParameters_CORBAtoCPP(params);
220
221   try
222   {
223     // Call C++ ResourceManager
224     std::vector <std::string> vec = _rm->GetFittingResources(p);
225
226     // C++ -> CORBA
227     ret = resourceList_CPPtoCORBA(vec);
228   }
229   catch(const ResourcesException &ex)
230   {
231     INFOS("Caught exception in GetFittingResources C++:  " << ex.msg);
232     THROW_SALOME_CORBA_EXCEPTION(ex.msg.c_str(),SALOME::BAD_PARAM);
233   }  
234
235   return ret._retn();
236 }
237
238 //=============================================================================
239 /*!
240  *  dynamically obtains the first machines
241  */ 
242 //=============================================================================
243
244 char *
245 SALOME_ResourcesManager::FindFirst(const Engines::ResourceList& listOfResources)
246 {
247   // CORBA -> C++
248   std::vector<std::string> rl = resourceList_CORBAtoCPP(listOfResources);
249
250   return CORBA::string_dup(_rm->Find("first", rl).c_str());
251 }
252
253 char *
254 SALOME_ResourcesManager::Find(const char* policy, const Engines::ResourceList& listOfResources)
255 {
256   // CORBA -> C++
257   std::vector<std::string> rl = resourceList_CORBAtoCPP(listOfResources);
258
259   return CORBA::string_dup(_rm->Find(policy, rl).c_str());
260 }
261
262 Engines::ResourceDefinition*
263 SALOME_ResourcesManager::GetResourceDefinition(const char * name)
264 {
265   Engines::ResourceDefinition_var resDef;
266   try {
267     ParserResourcesType resource = _rm->GetResourcesDescr(name);
268     resDef = resourceDefinition_CPPtoCORBA(resource);
269   } catch (const exception & ex) {
270     INFOS("Caught exception in GetResourceDefinition: " << ex.what());
271     THROW_SALOME_CORBA_EXCEPTION(ex.what(), SALOME::BAD_PARAM);
272   }
273
274   return resDef._retn();
275 }
276
277 void 
278 SALOME_ResourcesManager::AddResource(const Engines::ResourceDefinition& new_resource,
279                                      CORBA::Boolean write,
280                                      const char * xml_file)
281 {
282   try
283   {
284     ParserResourcesType resource = resourceDefinition_CORBAtoCPP(new_resource);
285     _rm->AddResourceInCatalog(resource);
286
287     if (write)
288     {
289       _rm->WriteInXmlFile(std::string(xml_file));
290       _rm->ParseXmlFiles();
291     }
292   }
293   catch (const SALOME_Exception & e)
294   {
295     INFOS("Error in AddResourceInCatalog: " << e);
296     THROW_SALOME_CORBA_EXCEPTION(e.what(), SALOME::BAD_PARAM);
297   }
298   catch (const ResourcesException & e)
299   {
300     INFOS("Error in AddResourceInCatalog: " << e.msg);
301     THROW_SALOME_CORBA_EXCEPTION(e.msg.c_str(), SALOME::BAD_PARAM);
302   }
303 }
304
305 void
306 SALOME_ResourcesManager::RemoveResource(const char * resource_name,
307                                         CORBA::Boolean write,
308                                         const char * xml_file)
309 {
310   try
311   {
312     _rm->DeleteResourceInCatalog(resource_name);
313   }
314   catch (const SALOME_Exception & e)
315   {
316     INFOS("Error in DeleteResourceInCatalog: " << e);
317     THROW_SALOME_CORBA_EXCEPTION(e.what(), SALOME::BAD_PARAM);
318   }
319
320   if (write)
321   {
322     _rm->WriteInXmlFile(std::string(xml_file));
323     _rm->ParseXmlFiles();
324   }
325 }
326
327 char *
328 SALOME_ResourcesManager::getMachineFile(const char * resource_name,
329                                         CORBA::Long nb_procs, 
330                                         const char * parallelLib)
331 {
332   std::string machine_file_name("");
333
334   if (std::string(parallelLib) == "Dummy")
335   {
336     MESSAGE("[getMachineFile] parallelLib is Dummy");
337     MapOfParserResourcesType resourcesList = _rm->GetList();
338     if (resourcesList.find(std::string(resource_name)) != resourcesList.end())
339     {
340       ParserResourcesType resource = resourcesList[std::string(resource_name)];
341
342       // Check if resource is cluster or not
343       if (resource.ClusterMembersList.empty())
344       {
345         //It is not a cluster so we create a cluster with one machine
346         ParserResourcesType fake_node;
347         fake_node.HostName = resource.HostName;
348         fake_node.Protocol = resource.Protocol;
349         fake_node.ClusterInternalProtocol = resource.ClusterInternalProtocol;
350         fake_node.UserName = resource.UserName;
351         fake_node.AppliPath = resource.AppliPath;
352         fake_node.DataForSort = resource.DataForSort;
353
354         resource.ClusterMembersList.push_front(fake_node);
355       }
356
357       // Creating list of machines for creating the machine file
358       std::list<std::string> list_of_machines;
359       std::list<ParserResourcesType>::iterator cluster_it =
360         resource.ClusterMembersList.begin();
361       while (cluster_it != resource.ClusterMembersList.end())
362       {
363         // For each member of the cluster we add a nbOfNodes * nbOfProcPerNode in the list
364         unsigned int number_of_proc = (*cluster_it).DataForSort._nbOfNodes * 
365                                       (*cluster_it).DataForSort._nbOfProcPerNode;
366         for (unsigned int i = 0; i < number_of_proc; i++)
367           list_of_machines.push_back((*cluster_it).HostName);
368         cluster_it++;
369       }
370
371       // Creating machine file
372       machine_file_name = tmpnam(NULL);
373       std::ofstream machine_file(machine_file_name.c_str(), std::ios_base::out);
374
375       CORBA::Long machine_number = 0;
376       std::list<std::string>::iterator it = list_of_machines.begin();
377       while (machine_number != nb_procs)
378       {
379         // Adding a new node to the machine file
380         machine_file << *it << std::endl;
381
382         // counting...
383         it++;
384         if (it == list_of_machines.end())
385           it = list_of_machines.begin();
386         machine_number++;
387       }
388     }
389     else
390       INFOS("[getMachineFile] Error resource_name not found in resourcesList -> " << resource_name);
391   }
392   else if (std::string(parallelLib) == "Mpi")
393   {
394     MESSAGE("[getMachineFile] parallelLib is Mpi");
395
396     MapOfParserResourcesType resourcesList = _rm->GetList();
397     if (resourcesList.find(std::string(resource_name)) != resourcesList.end())
398     {
399       ParserResourcesType resource = resourcesList[std::string(resource_name)];
400       // Check if resource is cluster or not
401       if (resource.ClusterMembersList.empty())
402       {
403         //It is not a cluster so we create a cluster with one machine
404         ParserResourcesType fake_node;
405         fake_node.HostName = resource.HostName;
406         fake_node.Protocol = resource.Protocol;
407         fake_node.ClusterInternalProtocol = resource.ClusterInternalProtocol;
408         fake_node.UserName = resource.UserName;
409         fake_node.AppliPath = resource.AppliPath;
410         fake_node.DataForSort = resource.DataForSort;
411
412         resource.ClusterMembersList.push_front(fake_node);
413       }
414
415       // Choose mpi implementation -> each MPI implementation has is own machinefile...
416       if (resource.mpi == lam)
417       {
418         // Creating machine file
419         machine_file_name = tmpnam(NULL);
420         std::ofstream machine_file(machine_file_name.c_str(), std::ios_base::out);
421
422         // We add all cluster machines to the file
423         std::list<ParserResourcesType>::iterator cluster_it =
424           resource.ClusterMembersList.begin();
425         while (cluster_it != resource.ClusterMembersList.end())
426         {
427           unsigned int number_of_proc = (*cluster_it).DataForSort._nbOfNodes * 
428             (*cluster_it).DataForSort._nbOfProcPerNode;
429           machine_file << (*cluster_it).HostName << " cpu=" << number_of_proc << std::endl;
430           cluster_it++;
431         }
432       }
433       else if ((resource.mpi == openmpi) || (resource.mpi == ompi))
434       {
435         // Creating machine file
436         machine_file_name = tmpnam(NULL);
437         std::ofstream machine_file(machine_file_name.c_str(), std::ios_base::out);
438
439         // We add all cluster machines to the file
440         std::list<ParserResourcesType>::iterator cluster_it =
441           resource.ClusterMembersList.begin();
442         while (cluster_it != resource.ClusterMembersList.end())
443         {
444           unsigned int number_of_proc = (*cluster_it).DataForSort._nbOfNodes *
445             (*cluster_it).DataForSort._nbOfProcPerNode;
446           machine_file << (*cluster_it).HostName << " slots=" << number_of_proc << std::endl;
447           cluster_it++;
448         }
449       }
450       else if (resource.mpi == nompi)
451       {
452         INFOS("[getMachineFile] Error resource_name MPI implementation was defined for " << resource_name);
453       }
454       else
455         INFOS("[getMachineFile] Error resource_name MPI implementation not currently handled for " << resource_name);
456     }
457     else
458       INFOS("[getMachineFile] Error resource_name not found in resourcesList -> " << resource_name);
459   }
460   else
461     INFOS("[getMachineFile] Error parallelLib is not handled -> " << parallelLib);
462
463   return CORBA::string_dup(machine_file_name.c_str());
464 }