1 // Copyright (C) 2007-2021 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
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.
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.
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
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 #include "ResourcesManager.hxx"
25 #include "SALOME_ResourcesCatalog_Handler.hxx"
26 #include <Basics_Utils.hxx>
27 #include <Basics_DirUtils.hxx>
35 #include <sys/types.h>
41 #include <libxml/parser.h>
45 #define MAX_SIZE_FOR_HOSTNAME 256;
49 const string ResourcesManager_cpp::DEFAULT_RESOURCE_NAME = "localhost";
51 static LoadRateManagerFirst first;
52 static LoadRateManagerCycl cycl;
53 static LoadRateManagerAltCycl altcycl;
55 resourceParams::resourceParams()
56 : can_launch_batch_jobs(false),
57 can_run_containers(false),
66 //=============================================================================
70 //=============================================================================
72 ResourcesManager_cpp::
73 ResourcesManager_cpp(const char *xmlFilePath)
75 _path_resources.push_back(xmlFilePath);
76 #if defined(_DEBUG_) || defined(_DEBUG)
77 std::cerr << "ResourcesManager_cpp constructor" << std::endl;
79 _resourceManagerMap["first"]=&first;
80 _resourceManagerMap["cycl"]=&cycl;
81 _resourceManagerMap["altcycl"]=&altcycl;
82 _resourceManagerMap["best"]=&altcycl;
83 _resourceManagerMap[""]=&altcycl;
85 AddDefaultResourceInCatalog();
89 //=============================================================================
91 * Standard constructor, parse resource file.
92 * - if ${APPLI} exists in environment,
93 * look for ${HOME}/${APPLI}/CatalogResources.xml
94 * - else look for default:
95 * ${KERNEL_ROOT_DIR}/share/salome/resources/kernel/CatalogResources.xml
96 * - parse XML resource file.
98 //=============================================================================
100 ResourcesManager_cpp::ResourcesManager_cpp()
102 RES_MESSAGE("ResourcesManager_cpp constructor");
104 _resourceManagerMap["first"]=&first;
105 _resourceManagerMap["cycl"]=&cycl;
106 _resourceManagerMap["altcycl"]=&altcycl;
107 _resourceManagerMap["best"]=&altcycl;
108 _resourceManagerMap[""]=&altcycl;
110 AddDefaultResourceInCatalog();
112 bool default_catalog_resource = true;
113 if (getenv("USER_CATALOG_RESOURCES_FILE") != 0)
115 default_catalog_resource = false;
116 std::string user_file("");
117 user_file = getenv("USER_CATALOG_RESOURCES_FILE");
118 std::ifstream ifile(user_file.c_str(), std::ifstream::in );
120 // The file exists, and is open for input
121 _path_resources.push_back(user_file);
124 default_catalog_resource = false;
125 RES_INFOS("Warning: USER_CATALOG_RESOURCES_FILE is set and file cannot be found.")
126 RES_INFOS("Warning: That's why we try to create a new one.")
127 std::ofstream user_catalog_file;
128 user_catalog_file.open(user_file.c_str());
129 if (user_catalog_file.fail())
131 RES_INFOS("Error: cannot write in the user catalog resources files");
132 RES_INFOS("Error: using default CatalogResources.xml file");
133 default_catalog_resource = true;
137 user_catalog_file << "<!-- File created by SALOME -->" << std::endl;
138 user_catalog_file << "<!DOCTYPE ResourcesCatalog>" << std::endl;
139 user_catalog_file << "<resources>" << std::endl;
140 user_catalog_file << " <machine name=\"localhost\" hostname=\"localhost\" />" << std::endl;
141 user_catalog_file << "</resources>" << std::endl;
142 user_catalog_file.close();
146 if (default_catalog_resource)
148 std::string default_file("");
149 if (getenv("APPLI") != 0)
151 default_file += Kernel_Utils::HomePath();
153 default_file += getenv("APPLI");
154 default_file += "/CatalogResources.xml";
155 std::ifstream ifile(default_file.c_str(), std::ifstream::in );
157 // The file exists, and is open for input
158 _path_resources.push_back(default_file);
159 default_catalog_resource=false;
163 if (default_catalog_resource)
165 std::string default_file("");
166 if(!getenv("KERNEL_ROOT_DIR"))
167 throw ResourcesException("you must define KERNEL_ROOT_DIR environment variable!! -> cannot load a CatalogResources.xml");
168 default_file = getenv("KERNEL_ROOT_DIR");
169 default_file += "/share/salome/resources/kernel/CatalogResources.xml";
170 _path_resources.push_back(default_file);
174 RES_MESSAGE("ResourcesManager_cpp constructor end");
177 //=============================================================================
179 * Standard Destructor
181 //=============================================================================
183 ResourcesManager_cpp::~ResourcesManager_cpp()
185 RES_MESSAGE("ResourcesManager_cpp destructor");
188 //=============================================================================
189 //! get the list of resource names fitting constraints given by params
192 * 1: Restrict list with resourceList if defined
193 * 2: If name is defined -> check resource list
194 * 3: If not 2:, if hostname is defined -> check resource list
195 * 4: If not 3:, sort resource with nb_proc, etc...
196 * 5: In all cases remove resource that does not correspond with OS
197 * 6: And remove resource with componentList - if list is empty ignored it...
199 //=============================================================================
201 std::vector<std::string>
202 ResourcesManager_cpp::GetFittingResources(const resourceParams& params)
204 RES_MESSAGE("[GetFittingResources] on computer " << Kernel_Utils::GetHostname().c_str());
205 RES_MESSAGE("[GetFittingResources] with resource name: " << params.name);
206 RES_MESSAGE("[GetFittingResources] with hostname: "<< params.hostname);
209 std::vector<std::string> vec;
211 // Parse Again CalatogResource File
215 // 1: If name is defined -> check resource list
216 // 2: Restrict list with resourceList if defined
217 // 3: If not 2:, if hostname is defined -> check resource list
218 // 4: If not 3:, sort resource with nb_proc, etc...
219 // 5: In all cases remove resource that does not correspond with OS
220 // 6: And remove resource with componentList - if list is empty ignored it...
223 if (params.name != "")
225 RES_MESSAGE("[GetFittingResources] name parameter found !");
226 if (_resourcesList.find(params.name) != _resourcesList.end())
228 vec.push_back(params.name);
232 RES_MESSAGE("[GetFittingResources] resource name was not found on resource list ! name requested was " << params.name);
233 std::string error("[GetFittingResources] resource name was not found on resource list ! name requested was " + params.name);
234 throw ResourcesException(error);
237 MapOfParserResourcesType local_resourcesList = _resourcesList;
239 if (params.resourceList.size() > 0)
241 RES_MESSAGE("[GetFittingResources] Restricted resource list found !");
242 local_resourcesList.clear();
243 std::vector<std::string>::size_type sz = params.resourceList.size();
245 for (unsigned int i=0; i < sz; i++)
247 if (_resourcesList.find(params.resourceList[i]) != _resourcesList.end())
248 local_resourcesList[params.resourceList[i]] = _resourcesList[params.resourceList[i]];
253 if (params.hostname != "")
255 RES_MESSAGE("[GetFittingResources] Entering in hostname case !");
257 std::string hostname = params.hostname;
258 if (hostname == "localhost")
259 hostname = Kernel_Utils::GetHostname().c_str();
261 std::map<std::string, ParserResourcesType>::const_iterator iter = _resourcesList.begin();
262 for (; iter != _resourcesList.end(); iter++)
264 if ((*iter).second.HostName == hostname)
265 vec.push_back((*iter).first);
271 // --- Search for available resources sorted by priority
272 MapOfParserResourcesType_it i = local_resourcesList.begin();
273 for (; i != local_resourcesList.end(); ++i)
274 vec.push_back(i->first);
276 // --- set wanted parameters
277 ResourceDataToSort::_nbOfProcWanted = params.nb_proc;
278 ResourceDataToSort::_nbOfNodesWanted = params.nb_node;
279 ResourceDataToSort::_nbOfProcPerNodeWanted = params.nb_proc_per_node;
280 ResourceDataToSort::_CPUFreqMHzWanted = params.cpu_clock;
281 ResourceDataToSort::_memInMBWanted = params.mem_mb;
285 std::list<ResourceDataToSort> li;
286 std::vector<std::string>::iterator iter = vec.begin();
287 for (; iter != vec.end(); iter++)
288 li.push_back(local_resourcesList[(*iter)].DataForSort);
292 for (std::list<ResourceDataToSort>::iterator iter2 = li.begin(); iter2 != li.end(); iter2++)
293 vec.push_back((*iter2)._Name);
297 SelectOnlyResourcesWithOS(vec, params.OS.c_str());
300 std::vector<std::string> vec_save(vec);
301 KeepOnlyResourcesWithComponent(vec, params.componentList);
305 // Step 7 : Filter on possible usage
306 vector<string> prev_list(vec);
308 for (vector<string>::iterator iter = prev_list.begin() ; iter != prev_list.end() ; iter++)
310 MapOfParserResourcesType::const_iterator it = _resourcesList.find(*iter);
311 if (it != _resourcesList.end() &&
312 (!params.can_launch_batch_jobs || it->second.can_launch_batch_jobs) &&
313 (!params.can_run_containers || it->second.can_run_containers))
314 vec.push_back(*iter);
318 // Send an exception if return list is empty...
321 std::string error("[GetFittingResources] ResourcesManager doesn't find any resource that fits to your parameters");
322 throw ResourcesException(error);
328 //=============================================================================
330 * add an entry in the resources catalog xml file.
332 //=============================================================================
335 ResourcesManager_cpp::AddResourceInCatalog(const ParserResourcesType & new_resource)
337 if (new_resource.Name == DEFAULT_RESOURCE_NAME){
338 ParserResourcesType default_resource = _resourcesList[DEFAULT_RESOURCE_NAME];
339 // some of the properties of the default resource shouldn't be modified
341 if( default_resource.HostName != new_resource.HostName)
342 check += "The Hostname property of the default resource can not be modified.\n";
343 if( default_resource.AppliPath != new_resource.AppliPath)
344 check += "The Applipath property of the default resource can not be modified.\n";
345 if( !new_resource.can_run_containers)
346 check += "The default resource should be able to run containers.\n";
347 if( !new_resource.can_launch_batch_jobs)
348 check += "The default resource should be able to launch batch jobs.\n";
349 if( default_resource.Protocol != new_resource.Protocol)
350 check += "The Protocol property of the default resource can not be modified.\n";
352 throw ResourcesException(check);
354 // TODO - Add minimal check
355 _resourcesList[new_resource.Name] = new_resource;
358 //=============================================================================
360 * Deletes a resource from the catalog
362 //=============================================================================
364 void ResourcesManager_cpp::DeleteResourceInCatalog(const char * name)
366 if (DEFAULT_RESOURCE_NAME == name){
367 std::string error("Cannot delete default local resource \"" + DEFAULT_RESOURCE_NAME + "\"");
368 throw ResourcesException(error);
370 MapOfParserResourcesType_it it = _resourcesList.find(name);
371 if (it != _resourcesList.end())
372 _resourcesList.erase(name);
374 RES_INFOS("You try to delete a resource that does not exist... : " << name);
377 //=============================================================================
379 * write the current data in memory in file.
381 //=============================================================================
383 void ResourcesManager_cpp::WriteInXmlFile(std::string xml_file)
385 RES_MESSAGE("WriteInXmlFile : start");
387 MapOfParserResourcesType resourceListToSave(_resourcesList);
388 if (resourceListToSave.empty())
390 RES_MESSAGE("WriteInXmlFile: nothing to do, no resource to save!");
396 _path_resources_it = _path_resources.begin();
397 xml_file = *_path_resources_it;
400 const char* aFilePath = xml_file.c_str();
401 FILE* aFile = fopen(aFilePath, "w");
405 std::cerr << "Error opening file in WriteInXmlFile : " << xml_file << std::endl;
409 xmlDocPtr aDoc = xmlNewDoc(BAD_CAST "1.0");
410 xmlNewDocComment(aDoc, BAD_CAST "ResourcesCatalog");
412 SALOME_ResourcesCatalog_Handler* handler =
413 new SALOME_ResourcesCatalog_Handler(resourceListToSave);
414 handler->PrepareDocToXmlFile(aDoc);
417 int isOk = xmlSaveFormatFile(aFilePath, aDoc, 1);
419 std::cerr << "Error while XML file saving : " << xml_file << std::endl;
424 RES_MESSAGE("WriteInXmlFile : WRITING DONE!");
427 //=============================================================================
429 * parse the data type catalog
431 //=============================================================================
433 const MapOfParserResourcesType& ResourcesManager_cpp::ParseXmlFiles()
435 // Parse file only if its modification time is greater than lasttime (last registered modification time)
436 bool to_parse = false;
437 for(_path_resources_it = _path_resources.begin(); _path_resources_it != _path_resources.end(); ++_path_resources_it)
439 struct stat statinfo;
440 int result = stat((*_path_resources_it).c_str(), &statinfo);
443 RES_MESSAGE("Resource file " << *_path_resources_it << " does not exist");
444 return _resourcesList;
447 if(_lasttime == 0 || statinfo.st_mtime > _lasttime)
450 _lasttime = statinfo.st_mtime;
456 _resourcesList.clear();
457 AddDefaultResourceInCatalog();
458 // On parse tous les fichiers
459 for(_path_resources_it = _path_resources.begin(); _path_resources_it != _path_resources.end(); ++_path_resources_it)
461 MapOfParserResourcesType _resourcesList_tmp;
462 MapOfParserResourcesType _resourcesBatchList_tmp;
463 SALOME_ResourcesCatalog_Handler *handler( new SALOME_ResourcesCatalog_Handler(_resourcesList_tmp) );
464 const char *aFilePath( (*_path_resources_it).c_str() );
465 FILE* aFile = fopen(aFilePath, "r");
469 xmlDocPtr aDoc = xmlReadFile(aFilePath, NULL, 0);
472 handler->ProcessXmlDocument(aDoc);
474 // adding new resources to the file
475 for (MapOfParserResourcesType_it i = _resourcesList_tmp.begin(); i != _resourcesList_tmp.end(); ++i)
477 MapOfParserResourcesType_it j = _resourcesList.find(i->first);
478 if (i->second.HostName == DEFAULT_RESOURCE_NAME || i->second.HostName == Kernel_Utils::GetHostname())
480 MapOfParserResourcesType_it it0(_resourcesList.find(DEFAULT_RESOURCE_NAME));
481 if(it0!=_resourcesList.end())
483 ParserResourcesType& localhostElt((*it0).second);
484 localhostElt.DataForSort._nbOfNodes=(*i).second.DataForSort._nbOfNodes;
485 localhostElt.DataForSort._nbOfProcPerNode=(*i).second.DataForSort._nbOfProcPerNode;
486 localhostElt.DataForSort._CPUFreqMHz=(*i).second.DataForSort._CPUFreqMHz;
487 localhostElt.DataForSort._memInMB=(*i).second.DataForSort._memInMB;
489 RES_MESSAGE("Resource " << i->first << " is not added because it is the same "
490 "machine as default local resource \"" << DEFAULT_RESOURCE_NAME << "\"");
492 else if (j != _resourcesList.end())
494 cerr << "ParseXmlFiles Warning, two resources with the same name were found, "
495 "taking the first declaration : " << i->first << endl;
499 _resourcesList[i->first] = i->second;
504 std::cerr << "ResourcesManager_cpp: could not parse file " << aFilePath << std::endl;
510 std::cerr << "ResourcesManager_cpp: file " << aFilePath << " is not readable." << std::endl;
515 return _resourcesList;
518 //=============================================================================
520 * consult the content of the list
522 //=============================================================================
524 const MapOfParserResourcesType& ResourcesManager_cpp::GetList() const
526 return _resourcesList;
530 std::string ResourcesManager_cpp::Find(const std::string& policy, const std::vector<std::string>& listOfResources) const
532 std::map<std::string , LoadRateManager*>::const_iterator it(_resourceManagerMap.find(policy));
533 if(it==_resourceManagerMap.end())
535 it=_resourceManagerMap.find("");
536 return ((*it).second)->Find(listOfResources, _resourcesList);
538 return ((*it).second)->Find(listOfResources, _resourcesList);
541 //=============================================================================
543 * Gives a sublist of resources with matching OS.
544 * If parameter OS is empty, gives the complete list of resources
546 //=============================================================================
548 ResourcesManager_cpp::SelectOnlyResourcesWithOS(std::vector<std::string>& resources, std::string OS)
552 // a computer list is given : take only resources with OS on those computers
553 std::vector<std::string> vec_tmp = resources;
555 std::vector<std::string>::iterator iter = vec_tmp.begin();
556 for (; iter != vec_tmp.end(); iter++)
558 MapOfParserResourcesType::const_iterator it = _resourcesList.find(*iter);
559 if(it != _resourcesList.end())
560 if ( (*it).second.OS == OS)
561 resources.push_back(*iter);
567 //=============================================================================
569 * Gives a sublist of machines on which the component is known.
571 //=============================================================================
573 ResourcesManager_cpp::KeepOnlyResourcesWithComponent(std::vector<std::string>& resources,
574 const std::vector<std::string>& componentList)
576 std::vector<std::string> kept_resources;
578 std::vector<std::string>::iterator iter = resources.begin();
579 for (; iter != resources.end(); iter++)
581 const std::vector<std::string>& mapOfComponentsOfCurrentHost = _resourcesList[*iter].ComponentsList;
583 bool erasedHost = false;
584 if( mapOfComponentsOfCurrentHost.size() > 0 )
586 for(unsigned int i=0; i<componentList.size(); i++)
588 std::vector<std::string>::const_iterator itt = find(mapOfComponentsOfCurrentHost.begin(),
589 mapOfComponentsOfCurrentHost.end(),
591 if (itt == mapOfComponentsOfCurrentHost.end())
599 kept_resources.push_back(*iter);
601 resources=kept_resources;
605 ParserResourcesType ResourcesManager_cpp::GetResourcesDescr(const std::string & name) const
607 MapOfParserResourcesType::const_iterator it(_resourcesList.find(name));
608 if (it != _resourcesList.end())
612 std::string error("[GetResourcesDescr] Resource does not exist: ");
614 throw ResourcesException(error);
618 void ResourcesManager_cpp::AddDefaultResourceInCatalog()
620 ParserResourcesType resource;
621 resource.Name = DEFAULT_RESOURCE_NAME;
622 // We can't use "localhost" for parameter hostname because the containers are registered in the
623 // naming service with the real hostname, not "localhost"
624 resource.HostName = Kernel_Utils::GetHostname();
625 resource.DataForSort._Name = DEFAULT_RESOURCE_NAME;
626 resource.Protocol = sh;
627 resource.Batch = none;
630 std::string aHomePath = Kernel_Utils::HomePath();
631 if (aHomePath != "" && getenv("APPLI") != NULL)
633 if (stat(getenv("APPLI"), &statbuf) ==0 && S_ISREG(statbuf.st_mode))
635 // if $APPLI is a regular file, we asume it's a salome Launcher file
636 resource.AppliPath = string(getenv("APPLI"));
640 resource.AppliPath = aHomePath + "/" + getenv("APPLI");
643 string tmpdir = "/tmp";
644 if (getenv("TMPDIR") != NULL)
645 tmpdir = getenv("TMPDIR");
646 resource.working_directory = tmpdir + "/salome_localres_workdir";
647 if (getenv("USER") != NULL)
648 resource.working_directory += string("_") + getenv("USER");
650 if (getenv("USERPROFILE") != NULL && getenv("APPLI") != NULL)
652 resource.AppliPath = string(getenv("USERPROFILE")) + "\\" + getenv("APPLI");
654 string tmpdir = "C:\\tmp";
655 if (getenv("TEMP") != NULL)
656 tmpdir = getenv("TEMP");
657 resource.working_directory = tmpdir + "\\salome_localres_workdir";
658 if (getenv("USERNAME") != NULL)
659 resource.working_directory += string("_") + getenv("USERNAME");
661 resource.can_launch_batch_jobs = true;
662 resource.can_run_containers = true;
663 _resourcesList[resource.Name] = resource;