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