1 // Copyright (C) 2007-2019 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"
24 #include "SALOME_ResourcesCatalog_Handler.hxx"
25 #include <Basics_Utils.hxx>
32 #include <sys/types.h>
38 #include <libxml/parser.h>
42 #define MAX_SIZE_FOR_HOSTNAME 256;
46 const string ResourcesManager_cpp::DEFAULT_RESOURCE_NAME = "localhost";
48 static LoadRateManagerFirst first;
49 static LoadRateManagerCycl cycl;
50 static LoadRateManagerAltCycl altcycl;
52 resourceParams::resourceParams()
53 : can_launch_batch_jobs(false),
54 can_run_containers(false),
63 //=============================================================================
67 //=============================================================================
69 ResourcesManager_cpp::
70 ResourcesManager_cpp(const char *xmlFilePath)
72 _path_resources.push_back(xmlFilePath);
73 #if defined(_DEBUG_) || defined(_DEBUG)
74 std::cerr << "ResourcesManager_cpp constructor" << std::endl;
76 _resourceManagerMap["first"]=&first;
77 _resourceManagerMap["cycl"]=&cycl;
78 _resourceManagerMap["altcycl"]=&altcycl;
79 _resourceManagerMap["best"]=&altcycl;
80 _resourceManagerMap[""]=&altcycl;
82 AddDefaultResourceInCatalog();
85 //=============================================================================
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.
94 //=============================================================================
96 ResourcesManager_cpp::ResourcesManager_cpp() throw(ResourcesException)
98 RES_MESSAGE("ResourcesManager_cpp constructor");
100 _resourceManagerMap["first"]=&first;
101 _resourceManagerMap["cycl"]=&cycl;
102 _resourceManagerMap["altcycl"]=&altcycl;
103 _resourceManagerMap["best"]=&altcycl;
104 _resourceManagerMap[""]=&altcycl;
106 AddDefaultResourceInCatalog();
108 bool default_catalog_resource = true;
109 if (getenv("USER_CATALOG_RESOURCES_FILE") != 0)
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 );
116 // The file exists, and is open for input
117 _path_resources.push_back(user_file);
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())
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;
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();
142 if (default_catalog_resource)
144 std::string default_file("");
145 if (getenv("APPLI") != 0)
147 default_file += getenv("HOME");
149 default_file += getenv("APPLI");
150 default_file += "/CatalogResources.xml";
151 std::ifstream ifile(default_file.c_str(), std::ifstream::in );
153 // The file exists, and is open for input
154 _path_resources.push_back(default_file);
155 default_catalog_resource=false;
159 if (default_catalog_resource)
161 std::string default_file("");
162 if(!getenv("KERNEL_ROOT_DIR"))
163 throw ResourcesException("you must define KERNEL_ROOT_DIR environment variable!! -> cannot load a CatalogResources.xml");
164 default_file = getenv("KERNEL_ROOT_DIR");
165 default_file += "/share/salome/resources/kernel/CatalogResources.xml";
166 _path_resources.push_back(default_file);
170 RES_MESSAGE("ResourcesManager_cpp constructor end");
173 //=============================================================================
175 * Standard Destructor
177 //=============================================================================
179 ResourcesManager_cpp::~ResourcesManager_cpp()
181 RES_MESSAGE("ResourcesManager_cpp destructor");
184 //=============================================================================
185 //! get the list of resource names fitting constraints given by params
188 * 1: Restrict list with resourceList if defined
189 * 2: If name is defined -> check resource list
190 * 3: If not 2:, if hostname is defined -> check resource list
191 * 4: If not 3:, sort resource with nb_proc, etc...
192 * 5: In all cases remove resource that does not correspond with OS
193 * 6: And remove resource with componentList - if list is empty ignored it...
195 //=============================================================================
197 std::vector<std::string>
198 ResourcesManager_cpp::GetFittingResources(const resourceParams& params) throw(ResourcesException)
200 RES_MESSAGE("[GetFittingResources] on computer " << Kernel_Utils::GetHostname().c_str());
201 RES_MESSAGE("[GetFittingResources] with resource name: " << params.name);
202 RES_MESSAGE("[GetFittingResources] with hostname: "<< params.hostname);
205 std::vector<std::string> vec;
207 // Parse Again CalatogResource File
211 // 1: If name is defined -> check resource list
212 // 2: Restrict list with resourceList if defined
213 // 3: If not 2:, if hostname is defined -> check resource list
214 // 4: If not 3:, sort resource with nb_proc, etc...
215 // 5: In all cases remove resource that does not correspond with OS
216 // 6: And remove resource with componentList - if list is empty ignored it...
219 if (params.name != "")
221 RES_MESSAGE("[GetFittingResources] name parameter found !");
222 if (_resourcesList.find(params.name) != _resourcesList.end())
224 vec.push_back(params.name);
228 RES_MESSAGE("[GetFittingResources] resource name was not found on resource list ! name requested was " << params.name);
229 std::string error("[GetFittingResources] resource name was not found on resource list ! name requested was " + params.name);
230 throw ResourcesException(error);
233 MapOfParserResourcesType local_resourcesList = _resourcesList;
235 if (params.resourceList.size() > 0)
237 RES_MESSAGE("[GetFittingResources] Restricted resource list found !");
238 local_resourcesList.clear();
239 std::vector<std::string>::size_type sz = params.resourceList.size();
241 for (unsigned int i=0; i < sz; i++)
243 if (_resourcesList.find(params.resourceList[i]) != _resourcesList.end())
244 local_resourcesList[params.resourceList[i]] = _resourcesList[params.resourceList[i]];
249 if (params.hostname != "")
251 RES_MESSAGE("[GetFittingResources] Entering in hostname case !");
253 std::string hostname = params.hostname;
254 if (hostname == "localhost")
255 hostname = Kernel_Utils::GetHostname().c_str();
257 std::map<std::string, ParserResourcesType>::const_iterator iter = _resourcesList.begin();
258 for (; iter != _resourcesList.end(); iter++)
260 if ((*iter).second.HostName == hostname)
261 vec.push_back((*iter).first);
267 // --- Search for available resources sorted by priority
268 MapOfParserResourcesType_it i = local_resourcesList.begin();
269 for (; i != local_resourcesList.end(); ++i)
270 vec.push_back(i->first);
272 // --- set wanted parameters
273 ResourceDataToSort::_nbOfProcWanted = params.nb_proc;
274 ResourceDataToSort::_nbOfNodesWanted = params.nb_node;
275 ResourceDataToSort::_nbOfProcPerNodeWanted = params.nb_proc_per_node;
276 ResourceDataToSort::_CPUFreqMHzWanted = params.cpu_clock;
277 ResourceDataToSort::_memInMBWanted = params.mem_mb;
281 std::list<ResourceDataToSort> li;
282 std::vector<std::string>::iterator iter = vec.begin();
283 for (; iter != vec.end(); iter++)
284 li.push_back(local_resourcesList[(*iter)].DataForSort);
288 for (std::list<ResourceDataToSort>::iterator iter2 = li.begin(); iter2 != li.end(); iter2++)
289 vec.push_back((*iter2)._Name);
293 SelectOnlyResourcesWithOS(vec, params.OS.c_str());
296 std::vector<std::string> vec_save(vec);
297 KeepOnlyResourcesWithComponent(vec, params.componentList);
301 // Step 7 : Filter on possible usage
302 vector<string> prev_list(vec);
304 for (vector<string>::iterator iter = prev_list.begin() ; iter != prev_list.end() ; iter++)
306 MapOfParserResourcesType::const_iterator it = _resourcesList.find(*iter);
307 if (it != _resourcesList.end() &&
308 (!params.can_launch_batch_jobs || it->second.can_launch_batch_jobs) &&
309 (!params.can_run_containers || it->second.can_run_containers))
310 vec.push_back(*iter);
314 // Send an exception if return list is empty...
317 std::string error("[GetFittingResources] ResourcesManager doesn't find any resource that fits to your parameters");
318 throw ResourcesException(error);
324 //=============================================================================
326 * add an entry in the resources catalog xml file.
328 //=============================================================================
331 ResourcesManager_cpp::AddResourceInCatalog(const ParserResourcesType & new_resource)
333 if (new_resource.Name == DEFAULT_RESOURCE_NAME){
334 ParserResourcesType default_resource = _resourcesList[DEFAULT_RESOURCE_NAME];
335 // some of the properties of the default resource shouldn't be modified
337 if( default_resource.HostName != new_resource.HostName)
338 check += "The Hostname property of the default resource can not be modified.\n";
339 if( default_resource.AppliPath != new_resource.AppliPath)
340 check += "The Applipath property of the default resource can not be modified.\n";
341 if( !new_resource.can_run_containers)
342 check += "The default resource should be able to run containers.\n";
343 if( !new_resource.can_launch_batch_jobs)
344 check += "The default resource should be able to launch batch jobs.\n";
345 if( default_resource.Protocol != new_resource.Protocol)
346 check += "The Protocol property of the default resource can not be modified.\n";
348 throw ResourcesException(check);
350 // TODO - Add minimal check
351 _resourcesList[new_resource.Name] = new_resource;
354 //=============================================================================
356 * Deletes a resource from the catalog
358 //=============================================================================
360 void ResourcesManager_cpp::DeleteResourceInCatalog(const char * name)
362 if (DEFAULT_RESOURCE_NAME == name){
363 std::string error("Cannot delete default local resource \"" + DEFAULT_RESOURCE_NAME + "\"");
364 throw ResourcesException(error);
366 MapOfParserResourcesType_it it = _resourcesList.find(name);
367 if (it != _resourcesList.end())
368 _resourcesList.erase(name);
370 RES_INFOS("You try to delete a resource that does not exist... : " << name);
373 //=============================================================================
375 * write the current data in memory in file.
377 //=============================================================================
379 void ResourcesManager_cpp::WriteInXmlFile(std::string xml_file)
381 RES_MESSAGE("WriteInXmlFile : start");
383 MapOfParserResourcesType resourceListToSave(_resourcesList);
384 if (resourceListToSave.empty())
386 RES_MESSAGE("WriteInXmlFile: nothing to do, no resource to save!");
392 _path_resources_it = _path_resources.begin();
393 xml_file = *_path_resources_it;
396 const char* aFilePath = xml_file.c_str();
397 FILE* aFile = fopen(aFilePath, "w");
401 std::cerr << "Error opening file in WriteInXmlFile : " << xml_file << std::endl;
405 xmlDocPtr aDoc = xmlNewDoc(BAD_CAST "1.0");
406 xmlNewDocComment(aDoc, BAD_CAST "ResourcesCatalog");
408 SALOME_ResourcesCatalog_Handler* handler =
409 new SALOME_ResourcesCatalog_Handler(resourceListToSave);
410 handler->PrepareDocToXmlFile(aDoc);
413 int isOk = xmlSaveFormatFile(aFilePath, aDoc, 1);
415 std::cerr << "Error while XML file saving : " << xml_file << std::endl;
420 RES_MESSAGE("WriteInXmlFile : WRITING DONE!");
423 //=============================================================================
425 * parse the data type catalog
427 //=============================================================================
429 const MapOfParserResourcesType& ResourcesManager_cpp::ParseXmlFiles()
431 // Parse file only if its modification time is greater than lasttime (last registered modification time)
432 bool to_parse = false;
433 for(_path_resources_it = _path_resources.begin(); _path_resources_it != _path_resources.end(); ++_path_resources_it)
435 struct stat statinfo;
436 int result = stat((*_path_resources_it).c_str(), &statinfo);
439 RES_MESSAGE("Resource file " << *_path_resources_it << " does not exist");
440 return _resourcesList;
443 if(_lasttime == 0 || statinfo.st_mtime > _lasttime)
446 _lasttime = statinfo.st_mtime;
452 _resourcesList.clear();
453 AddDefaultResourceInCatalog();
454 // On parse tous les fichiers
455 for(_path_resources_it = _path_resources.begin(); _path_resources_it != _path_resources.end(); ++_path_resources_it)
457 MapOfParserResourcesType _resourcesList_tmp;
458 MapOfParserResourcesType _resourcesBatchList_tmp;
459 SALOME_ResourcesCatalog_Handler *handler( new SALOME_ResourcesCatalog_Handler(_resourcesList_tmp) );
460 const char *aFilePath( (*_path_resources_it).c_str() );
461 FILE* aFile = fopen(aFilePath, "r");
465 xmlDocPtr aDoc = xmlReadFile(aFilePath, NULL, 0);
468 handler->ProcessXmlDocument(aDoc);
470 // adding new resources to the file
471 for (MapOfParserResourcesType_it i = _resourcesList_tmp.begin(); i != _resourcesList_tmp.end(); ++i)
473 MapOfParserResourcesType_it j = _resourcesList.find(i->first);
474 if (i->second.HostName == DEFAULT_RESOURCE_NAME || i->second.HostName == Kernel_Utils::GetHostname())
476 MapOfParserResourcesType_it it0(_resourcesList.find(DEFAULT_RESOURCE_NAME));
477 if(it0!=_resourcesList.end())
479 ParserResourcesType& localhostElt((*it0).second);
480 localhostElt.DataForSort._nbOfNodes=(*i).second.DataForSort._nbOfNodes;
481 localhostElt.DataForSort._nbOfProcPerNode=(*i).second.DataForSort._nbOfProcPerNode;
482 localhostElt.DataForSort._CPUFreqMHz=(*i).second.DataForSort._CPUFreqMHz;
483 localhostElt.DataForSort._memInMB=(*i).second.DataForSort._memInMB;
485 RES_MESSAGE("Resource " << i->first << " is not added because it is the same "
486 "machine as default local resource \"" << DEFAULT_RESOURCE_NAME << "\"");
488 else if (j != _resourcesList.end())
490 cerr << "ParseXmlFiles Warning, two resources with the same name were found, "
491 "taking the first declaration : " << i->first << endl;
495 _resourcesList[i->first] = i->second;
500 std::cerr << "ResourcesManager_cpp: could not parse file " << aFilePath << std::endl;
506 std::cerr << "ResourcesManager_cpp: file " << aFilePath << " is not readable." << std::endl;
511 return _resourcesList;
514 //=============================================================================
516 * consult the content of the list
518 //=============================================================================
520 const MapOfParserResourcesType& ResourcesManager_cpp::GetList() const
522 return _resourcesList;
526 std::string ResourcesManager_cpp::Find(const std::string& policy, const std::vector<std::string>& listOfResources) const
528 std::map<std::string , LoadRateManager*>::const_iterator it(_resourceManagerMap.find(policy));
529 if(it==_resourceManagerMap.end())
531 it=_resourceManagerMap.find("");
532 return ((*it).second)->Find(listOfResources, _resourcesList);
534 return ((*it).second)->Find(listOfResources, _resourcesList);
537 //=============================================================================
539 * Gives a sublist of resources with matching OS.
540 * If parameter OS is empty, gives the complete list of resources
542 //=============================================================================
544 ResourcesManager_cpp::SelectOnlyResourcesWithOS(std::vector<std::string>& resources, std::string OS)
548 // a computer list is given : take only resources with OS on those computers
549 std::vector<std::string> vec_tmp = resources;
551 std::vector<std::string>::iterator iter = vec_tmp.begin();
552 for (; iter != vec_tmp.end(); iter++)
554 MapOfParserResourcesType::const_iterator it = _resourcesList.find(*iter);
555 if(it != _resourcesList.end())
556 if ( (*it).second.OS == OS)
557 resources.push_back(*iter);
563 //=============================================================================
565 * Gives a sublist of machines on which the component is known.
567 //=============================================================================
569 ResourcesManager_cpp::KeepOnlyResourcesWithComponent(std::vector<std::string>& resources,
570 const std::vector<std::string>& componentList)
572 std::vector<std::string> kept_resources;
574 std::vector<std::string>::iterator iter = resources.begin();
575 for (; iter != resources.end(); iter++)
577 const std::vector<std::string>& mapOfComponentsOfCurrentHost = _resourcesList[*iter].ComponentsList;
579 bool erasedHost = false;
580 if( mapOfComponentsOfCurrentHost.size() > 0 )
582 for(unsigned int i=0; i<componentList.size(); i++)
584 std::vector<std::string>::const_iterator itt = find(mapOfComponentsOfCurrentHost.begin(),
585 mapOfComponentsOfCurrentHost.end(),
587 if (itt == mapOfComponentsOfCurrentHost.end())
595 kept_resources.push_back(*iter);
597 resources=kept_resources;
601 ParserResourcesType ResourcesManager_cpp::GetResourcesDescr(const std::string & name) const
603 MapOfParserResourcesType::const_iterator it(_resourcesList.find(name));
604 if (it != _resourcesList.end())
608 std::string error("[GetResourcesDescr] Resource does not exist: ");
610 throw ResourcesException(error);
614 void ResourcesManager_cpp::AddDefaultResourceInCatalog()
616 ParserResourcesType resource;
617 resource.Name = DEFAULT_RESOURCE_NAME;
618 // We can't use "localhost" for parameter hostname because the containers are registered in the
619 // naming service with the real hostname, not "localhost"
620 resource.HostName = Kernel_Utils::GetHostname();
621 resource.DataForSort._Name = DEFAULT_RESOURCE_NAME;
622 resource.Protocol = sh;
623 resource.Batch = none;
626 if (getenv("HOME") != NULL && getenv("APPLI") != NULL)
628 if (stat(getenv("APPLI"), &statbuf) ==0 && S_ISREG(statbuf.st_mode))
630 // if $APPLI is a regular file, we asume it's a salome Launcher file
631 resource.AppliPath = string(getenv("APPLI"));
635 resource.AppliPath = string(getenv("HOME")) + "/" + getenv("APPLI");
638 string tmpdir = "/tmp";
639 if (getenv("TMPDIR") != NULL)
640 tmpdir = getenv("TMPDIR");
641 resource.working_directory = tmpdir + "/salome_localres_workdir";
642 if (getenv("USER") != NULL)
643 resource.working_directory += string("_") + getenv("USER");
645 if (getenv("USERPROFILE") != NULL && getenv("APPLI") != NULL)
647 resource.AppliPath = string(getenv("USERPROFILE")) + "\\" + getenv("APPLI");
649 string tmpdir = "C:\\tmp";
650 if (getenv("TEMP") != NULL)
651 tmpdir = getenv("TEMP");
652 resource.working_directory = tmpdir + "\\salome_localres_workdir";
653 if (getenv("USERNAME") != NULL)
654 resource.working_directory += string("_") + getenv("USERNAME");
656 resource.can_launch_batch_jobs = true;
657 resource.can_run_containers = true;
658 _resourcesList[resource.Name] = resource;