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