Salome HOME
Some parameters of the localhost resource can be changed.
[modules/kernel.git] / src / ResourcesManager / 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 "ResourcesManager.hxx" 
24 #include "SALOME_ResourcesCatalog_Handler.hxx"
25 #include <Basics_Utils.hxx>
26 #include <fstream>
27 #include <iostream>
28 #include <sstream>
29 #include <string.h>
30 #include <map>
31 #include <list>
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #ifdef WIN32
35 #else
36 #include <unistd.h>
37 #endif
38 #include <libxml/parser.h>
39
40 #include <algorithm>
41
42 #define MAX_SIZE_FOR_HOSTNAME 256;
43
44 using namespace std;
45
46 const string ResourcesManager_cpp::DEFAULT_RESOURCE_NAME = "localhost";
47
48 static LoadRateManagerFirst first;
49 static LoadRateManagerCycl cycl;
50 static LoadRateManagerAltCycl altcycl;
51
52 resourceParams::resourceParams()
53 : can_launch_batch_jobs(false),
54   can_run_containers(false),
55   nb_proc(-1),
56   nb_node(0),
57   nb_proc_per_node(-1),
58   cpu_clock(-1),
59   mem_mb(-1)
60 {
61 }
62
63 //=============================================================================
64 /*!
65  * just for test
66  */ 
67 //=============================================================================
68
69 ResourcesManager_cpp::
70 ResourcesManager_cpp(const char *xmlFilePath)
71 {
72   _path_resources.push_back(xmlFilePath);
73 #if defined(_DEBUG_) || defined(_DEBUG)
74   std::cerr << "ResourcesManager_cpp constructor" << std::endl;
75 #endif
76   _resourceManagerMap["first"]=&first;
77   _resourceManagerMap["cycl"]=&cycl;
78   _resourceManagerMap["altcycl"]=&altcycl;
79   _resourceManagerMap["best"]=&altcycl;
80   _resourceManagerMap[""]=&altcycl;
81
82   AddDefaultResourceInCatalog();
83 }
84
85 //=============================================================================
86 /*!
87  *  Standard constructor, parse resource file.
88  *  - if ${APPLI} exists in environment,
89  *    look for ${HOME}/${APPLI}/CatalogResources.xml
90  *  - else look for default:
91  *    ${KERNEL_ROOT_DIR}/share/salome/resources/kernel/CatalogResources.xml
92  *  - parse XML resource file.
93  */ 
94 //=============================================================================
95
96 ResourcesManager_cpp::ResourcesManager_cpp() throw(ResourcesException)
97 {
98   RES_MESSAGE("ResourcesManager_cpp constructor");
99
100   _resourceManagerMap["first"]=&first;
101   _resourceManagerMap["cycl"]=&cycl;
102   _resourceManagerMap["altcycl"]=&altcycl;
103   _resourceManagerMap["best"]=&altcycl;
104   _resourceManagerMap[""]=&altcycl;
105
106   AddDefaultResourceInCatalog();
107
108   bool default_catalog_resource = true;
109   if (getenv("USER_CATALOG_RESOURCES_FILE") != 0)
110   {
111     default_catalog_resource = false;
112     std::string user_file("");
113     user_file = getenv("USER_CATALOG_RESOURCES_FILE");
114     std::ifstream ifile(user_file.c_str(), std::ifstream::in );
115     if (ifile) {
116       // The file exists, and is open for input
117       _path_resources.push_back(user_file);
118     }
119     else {
120       default_catalog_resource = false;
121       RES_INFOS("Warning: USER_CATALOG_RESOURCES_FILE is set and file cannot be found.")
122       RES_INFOS("Warning: That's why we try to create a new one.")
123       std::ofstream user_catalog_file;
124       user_catalog_file.open(user_file.c_str());
125       if (user_catalog_file.fail())
126       {
127         RES_INFOS("Error: cannot write in the user catalog resources files");
128         RES_INFOS("Error: using default CatalogResources.xml file");
129         default_catalog_resource = true;
130       }
131       else
132       {
133         user_catalog_file << "<!-- File created by SALOME -->" << std::endl;
134         user_catalog_file << "<!DOCTYPE ResourcesCatalog>" << std::endl;
135         user_catalog_file << "<resources>" << std::endl;
136         user_catalog_file << "   <machine name=\"localhost\" hostname=\"localhost\" />" << std::endl;
137         user_catalog_file << "</resources>" << std::endl;
138         user_catalog_file.close();
139       }
140     }
141   }
142   if (default_catalog_resource)
143   {
144     std::string default_file("");
145     if (getenv("APPLI") != 0)
146     {
147       default_file += getenv("HOME");
148       default_file += "/";
149       default_file += getenv("APPLI");
150       default_file += "/CatalogResources.xml";
151       _path_resources.push_back(default_file);
152     }
153     else
154     {
155       if(!getenv("KERNEL_ROOT_DIR"))
156         throw ResourcesException("you must define KERNEL_ROOT_DIR environment variable!! -> cannot load a CatalogResources.xml");
157       default_file = getenv("KERNEL_ROOT_DIR");
158       default_file += "/share/salome/resources/kernel/CatalogResources.xml";
159       _path_resources.push_back(default_file);
160     }
161   }
162
163   _lasttime=0;
164
165   ParseXmlFiles();
166   RES_MESSAGE("ResourcesManager_cpp constructor end");
167 }
168
169 //=============================================================================
170 /*!
171  *  Standard Destructor
172  */ 
173 //=============================================================================
174
175 ResourcesManager_cpp::~ResourcesManager_cpp()
176 {
177   RES_MESSAGE("ResourcesManager_cpp destructor");
178 }
179
180 //=============================================================================
181 //! get the list of resource names fitting constraints given by params
182 /*!
183  * Steps:
184  * 1: Restrict list with resourceList if defined
185  * 2: If name is defined -> check resource list
186  * 3: If not 2:, if hostname is defined -> check resource list
187  * 4: If not 3:, sort resource with nb_proc, etc...
188  * 5: In all cases remove resource that does not correspond with OS
189  * 6: And remove resource with componentList - if list is empty ignored it...
190  */ 
191 //=============================================================================
192
193 std::vector<std::string> 
194 ResourcesManager_cpp::GetFittingResources(const resourceParams& params) throw(ResourcesException)
195 {
196   RES_MESSAGE("[GetFittingResources] on computer " << Kernel_Utils::GetHostname().c_str());
197   RES_MESSAGE("[GetFittingResources] with resource name: " << params.name);
198   RES_MESSAGE("[GetFittingResources] with hostname: "<< params.hostname);
199
200   // Result
201   std::vector<std::string> vec;
202
203   // Parse Again CalatogResource File
204   ParseXmlFiles();
205
206   // Steps:
207   // 1: If name is defined -> check resource list
208   // 2: Restrict list with resourceList if defined
209   // 3: If not 2:, if hostname is defined -> check resource list
210   // 4: If not 3:, sort resource with nb_proc, etc...
211   // 5: In all cases remove resource that does not correspond with OS
212   // 6: And remove resource with componentList - if list is empty ignored it...
213
214   // Step 1
215   if (params.name != "")
216   {
217     RES_MESSAGE("[GetFittingResources] name parameter found !");
218     if (_resourcesList.find(params.name) != _resourcesList.end())
219     {
220       vec.push_back(params.name);
221       return vec;
222     }
223     else
224       RES_MESSAGE("[GetFittingResources] resource name was not found on resource list ! name requested was " << params.name);
225       std::string error("[GetFittingResources] resource name was not found on resource list ! name requested was " + params.name);
226       throw ResourcesException(error);
227   }
228
229   MapOfParserResourcesType local_resourcesList = _resourcesList;
230   // Step 2
231   if (params.resourceList.size() > 0)
232   {
233     RES_MESSAGE("[GetFittingResources] Restricted resource list found !");
234     local_resourcesList.clear();
235     std::vector<std::string>::size_type sz = params.resourceList.size();
236
237     for (unsigned int i=0; i < sz; i++)
238     {
239       if (_resourcesList.find(params.resourceList[i]) != _resourcesList.end())
240         local_resourcesList[params.resourceList[i]] = _resourcesList[params.resourceList[i]];
241     }
242   }
243
244   // Step 3
245   if (params.hostname != "")
246   {
247     RES_MESSAGE("[GetFittingResources] Entering in hostname case !");
248
249     std::string hostname = params.hostname;
250     if (hostname ==  "localhost")
251       hostname = Kernel_Utils::GetHostname().c_str();
252
253     std::map<std::string, ParserResourcesType>::const_iterator iter = _resourcesList.begin();
254     for (; iter != _resourcesList.end(); iter++)
255     {
256       if ((*iter).second.HostName == hostname)
257         vec.push_back((*iter).first);
258     }
259   }
260   // Step 4
261   else
262   {
263     // --- Search for available resources sorted by priority
264     MapOfParserResourcesType_it i = local_resourcesList.begin();
265     for (; i != local_resourcesList.end(); ++i)
266       vec.push_back(i->first);
267
268     // --- set wanted parameters
269     ResourceDataToSort::_nbOfProcWanted = params.nb_proc;
270     ResourceDataToSort::_nbOfNodesWanted = params.nb_node;
271     ResourceDataToSort::_nbOfProcPerNodeWanted = params.nb_proc_per_node;
272     ResourceDataToSort::_CPUFreqMHzWanted = params.cpu_clock;
273     ResourceDataToSort::_memInMBWanted = params.mem_mb;
274     // --- end of set
275         
276     // Sort
277     std::list<ResourceDataToSort> li;
278     std::vector<std::string>::iterator iter = vec.begin();
279     for (; iter != vec.end(); iter++)
280       li.push_back(local_resourcesList[(*iter)].DataForSort);
281     li.sort();
282
283     vec.clear();
284     for (std::list<ResourceDataToSort>::iterator iter2 = li.begin(); iter2 != li.end(); iter2++)
285       vec.push_back((*iter2)._Name);
286   }
287
288   // Step 5
289   SelectOnlyResourcesWithOS(vec, params.OS.c_str());
290
291   // Step 6
292   std::vector<std::string> vec_save(vec);
293   KeepOnlyResourcesWithComponent(vec, params.componentList);
294   if (vec.size() == 0)
295     vec = vec_save;
296
297   // Step 7 : Filter on possible usage
298   vector<string> prev_list(vec);
299   vec.clear();
300   for (vector<string>::iterator iter = prev_list.begin() ; iter != prev_list.end() ; iter++)
301   {
302     MapOfParserResourcesType::const_iterator it = _resourcesList.find(*iter);
303     if (it != _resourcesList.end() &&
304         (!params.can_launch_batch_jobs || it->second.can_launch_batch_jobs) &&
305         (!params.can_run_containers || it->second.can_run_containers))
306       vec.push_back(*iter);
307   }
308
309   // End
310   // Send an exception if return list is empty...
311   if (vec.size() == 0)
312   {
313     std::string error("[GetFittingResources] ResourcesManager doesn't find any resource that fits to your parameters");
314     throw ResourcesException(error);
315   }
316
317   return vec;
318 }
319
320 //=============================================================================
321 /*!
322  *  add an entry in the resources catalog xml file.
323  */ 
324 //=============================================================================
325
326 void
327 ResourcesManager_cpp::AddResourceInCatalog(const ParserResourcesType & new_resource)
328 {
329   if (new_resource.Name == DEFAULT_RESOURCE_NAME){
330     ParserResourcesType default_resource = _resourcesList[DEFAULT_RESOURCE_NAME];
331     // some of the properties of the default resource shouldn't be modified
332     std::string check;
333     if( default_resource.HostName != new_resource.HostName)
334       check += "The Hostname property of the default resource can not be modified.\n";
335     if( default_resource.AppliPath != new_resource.AppliPath)
336       check += "The Applipath property of the default resource can not be modified.\n";
337     if( !new_resource.can_run_containers)
338       check += "The default resource should be able to run containers.\n";
339     if( !new_resource.can_launch_batch_jobs)
340       check += "The default resource should be able to launch batch jobs.\n";
341     if( default_resource.Protocol != new_resource.Protocol)
342       check += "The Protocol property of the default resource can not be modified.\n";
343     if(!check.empty())
344       throw ResourcesException(check);
345   }
346   // TODO - Add minimal check
347   _resourcesList[new_resource.Name] = new_resource;
348 }
349
350 //=============================================================================
351 /*!
352  *  Deletes a resource from the catalog
353  */ 
354 //=============================================================================
355
356 void ResourcesManager_cpp::DeleteResourceInCatalog(const char * name)
357 {
358   if (DEFAULT_RESOURCE_NAME == name){
359     std::string error("Cannot delete default local resource \"" + DEFAULT_RESOURCE_NAME + "\"");
360     throw ResourcesException(error);
361   }
362   MapOfParserResourcesType_it it = _resourcesList.find(name);
363   if (it != _resourcesList.end())
364     _resourcesList.erase(name);
365   else
366     RES_INFOS("You try to delete a resource that does not exist... : " << name);
367 }
368
369 //=============================================================================
370 /*!
371  *  write the current data in memory in file.
372  */ 
373 //=============================================================================
374
375 void ResourcesManager_cpp::WriteInXmlFile(std::string xml_file)
376 {
377   RES_MESSAGE("WriteInXmlFile : start");
378
379   MapOfParserResourcesType resourceListToSave(_resourcesList);
380   if (resourceListToSave.empty())
381   {
382     RES_MESSAGE("WriteInXmlFile: nothing to do, no resource to save!");
383     return;
384   }
385
386   if (xml_file == "")
387   {
388     _path_resources_it = _path_resources.begin();
389     xml_file = *_path_resources_it;
390   }
391
392   const char* aFilePath = xml_file.c_str();
393   FILE* aFile = fopen(aFilePath, "w");
394
395   if (aFile == NULL)
396   {
397     std::cerr << "Error opening file in WriteInXmlFile : " << xml_file << std::endl;
398     return;
399   }
400   
401   xmlDocPtr aDoc = xmlNewDoc(BAD_CAST "1.0");
402   xmlNewDocComment(aDoc, BAD_CAST "ResourcesCatalog");
403
404   SALOME_ResourcesCatalog_Handler* handler =
405     new SALOME_ResourcesCatalog_Handler(resourceListToSave);
406   handler->PrepareDocToXmlFile(aDoc);
407   delete handler;
408
409   int isOk = xmlSaveFormatFile(aFilePath, aDoc, 1);
410   if (!isOk) 
411      std::cerr << "Error while XML file saving : " << xml_file << std::endl;
412   
413   // Free the document
414   xmlFreeDoc(aDoc);
415   fclose(aFile);
416   RES_MESSAGE("WriteInXmlFile : WRITING DONE!");
417 }
418
419 //=============================================================================
420 /*!
421  *  parse the data type catalog
422  */ 
423 //=============================================================================
424
425 const MapOfParserResourcesType& ResourcesManager_cpp::ParseXmlFiles()
426 {
427   // Parse file only if its modification time is greater than lasttime (last registered modification time)
428   bool to_parse = false;
429   for(_path_resources_it = _path_resources.begin(); _path_resources_it != _path_resources.end(); ++_path_resources_it)
430   {
431     struct stat statinfo;
432     int result = stat((*_path_resources_it).c_str(), &statinfo);
433     if (result < 0)
434     {
435       RES_MESSAGE("Resource file " << *_path_resources_it << " does not exist");
436       return _resourcesList;
437     }
438
439     if(statinfo.st_mtime > _lasttime)
440     {
441       to_parse = true;
442       _lasttime = statinfo.st_mtime;
443     }
444   }
445
446   if (to_parse)
447   {
448     _resourcesList.clear();
449     AddDefaultResourceInCatalog();
450     // On parse tous les fichiers
451     for(_path_resources_it = _path_resources.begin(); _path_resources_it != _path_resources.end(); ++_path_resources_it)
452     {
453       MapOfParserResourcesType _resourcesList_tmp;
454       MapOfParserResourcesType _resourcesBatchList_tmp;
455       SALOME_ResourcesCatalog_Handler *handler( new SALOME_ResourcesCatalog_Handler(_resourcesList_tmp) );
456       const char *aFilePath( (*_path_resources_it).c_str() );
457       FILE* aFile = fopen(aFilePath, "r");
458
459       if (aFile != NULL)
460       {
461         xmlDocPtr aDoc = xmlReadFile(aFilePath, NULL, 0);
462         if (aDoc != NULL)
463         {
464           handler->ProcessXmlDocument(aDoc);
465
466           // adding new resources to the file
467           for (MapOfParserResourcesType_it i = _resourcesList_tmp.begin(); i != _resourcesList_tmp.end(); ++i)
468           {
469             MapOfParserResourcesType_it j = _resourcesList.find(i->first);
470             if (i->second.HostName == DEFAULT_RESOURCE_NAME || i->second.HostName == Kernel_Utils::GetHostname())
471             {
472               MapOfParserResourcesType_it it0(_resourcesList.find(DEFAULT_RESOURCE_NAME));
473               if(it0!=_resourcesList.end())
474                 {
475                   ParserResourcesType& localhostElt((*it0).second);
476                   localhostElt.DataForSort._nbOfNodes=(*i).second.DataForSort._nbOfNodes;
477                   localhostElt.DataForSort._nbOfProcPerNode=(*i).second.DataForSort._nbOfProcPerNode;
478                   localhostElt.DataForSort._CPUFreqMHz=(*i).second.DataForSort._CPUFreqMHz;
479                   localhostElt.DataForSort._memInMB=(*i).second.DataForSort._memInMB;
480                 }
481               RES_MESSAGE("Resource " << i->first << " is not added because it is the same "
482                           "machine as default local resource \"" << DEFAULT_RESOURCE_NAME << "\"");
483             }
484             else if (j != _resourcesList.end())
485             {
486               cerr << "ParseXmlFiles Warning, two resources with the same name were found, "
487                       "taking the first declaration : " << i->first << endl;
488             }
489             else
490             {
491               _resourcesList[i->first] = i->second;
492             }
493           }
494         }
495         else
496           std::cerr << "ResourcesManager_cpp: could not parse file " << aFilePath << std::endl;
497         // Free the document
498         xmlFreeDoc(aDoc);
499         fclose(aFile);
500       }
501       else
502         std::cerr << "ResourcesManager_cpp: file " << aFilePath << " is not readable." << std::endl;
503
504       delete handler;
505     }
506   }
507   return _resourcesList;
508 }
509
510 //=============================================================================
511 /*!
512  *   consult the content of the list
513  */ 
514 //=============================================================================
515
516 const MapOfParserResourcesType& ResourcesManager_cpp::GetList() const
517 {
518   return _resourcesList;
519 }
520
521 //! threadsafe
522 std::string ResourcesManager_cpp::Find(const std::string& policy, const std::vector<std::string>& listOfResources) const
523 {
524   std::map<std::string , LoadRateManager*>::const_iterator it(_resourceManagerMap.find(policy));
525   if(it==_resourceManagerMap.end())
526         {
527           it=_resourceManagerMap.find("");
528           return ((*it).second)->Find(listOfResources, _resourcesList);
529         }
530   return ((*it).second)->Find(listOfResources, _resourcesList);
531 }
532
533 //=============================================================================
534 /*!
535  *  Gives a sublist of resources with matching OS.
536  *  If parameter OS is empty, gives the complete list of resources
537  */ 
538 //=============================================================================
539 void 
540 ResourcesManager_cpp::SelectOnlyResourcesWithOS(std::vector<std::string>& resources, std::string OS)
541 {
542   if (OS != "")
543   {
544     // a computer list is given : take only resources with OS on those computers
545     std::vector<std::string> vec_tmp = resources;
546     resources.clear();
547     std::vector<std::string>::iterator iter = vec_tmp.begin();
548     for (; iter != vec_tmp.end(); iter++)
549     {
550       MapOfParserResourcesType::const_iterator it = _resourcesList.find(*iter);
551       if(it != _resourcesList.end())
552         if ( (*it).second.OS == OS)
553           resources.push_back(*iter);
554     }
555   }
556 }
557
558
559 //=============================================================================
560 /*!
561  *  Gives a sublist of machines on which the component is known.
562  */ 
563 //=============================================================================
564 void 
565 ResourcesManager_cpp::KeepOnlyResourcesWithComponent(std::vector<std::string>& resources, 
566                                                      const std::vector<std::string>& componentList)
567 {
568   std::vector<std::string> kept_resources;
569
570   std::vector<std::string>::iterator iter = resources.begin();
571   for (; iter != resources.end(); iter++)
572   {
573     const std::vector<std::string>& mapOfComponentsOfCurrentHost = _resourcesList[*iter].ComponentsList;
574
575     bool erasedHost = false;
576     if( mapOfComponentsOfCurrentHost.size() > 0 )
577     {
578       for(unsigned int i=0; i<componentList.size(); i++)
579       {
580         std::vector<std::string>::const_iterator itt = find(mapOfComponentsOfCurrentHost.begin(),
581                                                             mapOfComponentsOfCurrentHost.end(),
582                                                             componentList[i]);
583         if (itt == mapOfComponentsOfCurrentHost.end())
584         {
585           erasedHost = true;
586           break;
587         }
588       }
589     }
590     if(!erasedHost)
591       kept_resources.push_back(*iter);
592   }
593   resources=kept_resources;
594 }
595
596 //! thread safe
597 ParserResourcesType ResourcesManager_cpp::GetResourcesDescr(const std::string & name) const
598 {
599   MapOfParserResourcesType::const_iterator it(_resourcesList.find(name));
600   if (it != _resourcesList.end())
601     return (*it).second;
602   else
603   {
604     std::string error("[GetResourcesDescr] Resource does not exist: ");
605     error += name;
606     throw ResourcesException(error);
607   }
608 }
609
610 void ResourcesManager_cpp::AddDefaultResourceInCatalog()
611 {
612   ParserResourcesType resource;
613   resource.Name = DEFAULT_RESOURCE_NAME;
614   // We can't use "localhost" for parameter hostname because the containers are registered in the
615   // naming service with the real hostname, not "localhost"
616   resource.HostName = Kernel_Utils::GetHostname();
617   resource.DataForSort._Name = DEFAULT_RESOURCE_NAME;
618   resource.Protocol = sh;
619   resource.Batch = none;
620 #ifndef WIN32
621   if (getenv("HOME") != NULL && getenv("APPLI") != NULL)
622   {
623     resource.AppliPath = string(getenv("HOME")) + "/" + getenv("APPLI");
624   }
625   string tmpdir = "/tmp";
626   if (getenv("TMPDIR") != NULL)
627     tmpdir = getenv("TMPDIR");
628   resource.working_directory = tmpdir + "/salome_localres_workdir";
629   if (getenv("USER") != NULL)
630     resource.working_directory += string("_") + getenv("USER");
631 #else
632   if (getenv("USERPROFILE") != NULL && getenv("APPLI") != NULL)
633   {
634     resource.AppliPath = string(getenv("USERPROFILE")) + "\\" + getenv("APPLI");
635   }
636   string tmpdir = "C:\\tmp";
637   if (getenv("TEMP") != NULL)
638     tmpdir = getenv("TEMP");
639   resource.working_directory = tmpdir + "\\salome_localres_workdir";
640   if (getenv("USERNAME") != NULL)
641     resource.working_directory += string("_") + getenv("USERNAME");
642 #endif
643   resource.can_launch_batch_jobs = true;
644   resource.can_run_containers = true;
645   _resourcesList[resource.Name] = resource;
646 }