Salome HOME
Direct manipulation of resource map singleton
[modules/kernel.git] / src / ResourcesManager / ResourcesManager.cxx
index 6ce6d140e76feb03a0e4ba3d1b02da4b7962343b..fc55861785f9652f41dbdb5456dbb457df8cf95b 100644 (file)
@@ -1,4 +1,4 @@
-// Copyright (C) 2007-2016  CEA/DEN, EDF R&D, OPEN CASCADE
+// Copyright (C) 2007-2024  CEA, EDF, OPEN CASCADE
 //
 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
 //
 
 #include "ResourcesManager.hxx" 
+
 #include "SALOME_ResourcesCatalog_Handler.hxx"
 #include <Basics_Utils.hxx>
+#include <Basics_DirUtils.hxx>
+#include "utilities.h"
+
 #include <fstream>
 #include <iostream>
 #include <sstream>
@@ -38,6 +42,7 @@
 #include <libxml/parser.h>
 
 #include <algorithm>
+#include <memory>
 
 #define MAX_SIZE_FOR_HOSTNAME 256;
 
@@ -53,7 +58,7 @@ resourceParams::resourceParams()
 : can_launch_batch_jobs(false),
   can_run_containers(false),
   nb_proc(-1),
-  nb_node(-1),
+  nb_node(0),
   nb_proc_per_node(-1),
   cpu_clock(-1),
   mem_mb(-1)
@@ -80,6 +85,7 @@ ResourcesManager_cpp(const char *xmlFilePath)
   _resourceManagerMap[""]=&altcycl;
 
   AddDefaultResourceInCatalog();
+  ParseXmlFiles();
 }
 
 //=============================================================================
@@ -93,7 +99,7 @@ ResourcesManager_cpp(const char *xmlFilePath)
  */ 
 //=============================================================================
 
-ResourcesManager_cpp::ResourcesManager_cpp() throw(ResourcesException)
+ResourcesManager_cpp::ResourcesManager_cpp()
 {
   RES_MESSAGE("ResourcesManager_cpp constructor");
 
@@ -114,18 +120,19 @@ ResourcesManager_cpp::ResourcesManager_cpp() throw(ResourcesException)
     std::ifstream ifile(user_file.c_str(), std::ifstream::in );
     if (ifile) {
       // The file exists, and is open for input
+      DEBUG_MESSAGE("USER_CATALOG_RESOURCES_FILE positioned -> add it into resourcefiles list");
       _path_resources.push_back(user_file);
     }
     else {
       default_catalog_resource = false;
-      RES_INFOS("Warning: USER_CATALOG_RESOURCES_FILE is set and file cannot be found.")
-      RES_INFOS("Warning: That's why we try to create a new one.")
+      WARNING_MESSAGE("Warning: USER_CATALOG_RESOURCES_FILE is set and file cannot be found.")
+      WARNING_MESSAGE("Warning: That's why we try to create a new one.")
       std::ofstream user_catalog_file;
       user_catalog_file.open(user_file.c_str());
       if (user_catalog_file.fail())
       {
-        RES_INFOS("Error: cannot write in the user catalog resources files");
-        RES_INFOS("Error: using default CatalogResources.xml file");
+        WARNING_MESSAGE("Error: cannot write in the user catalog resources files");
+        WARNING_MESSAGE("Error: using default CatalogResources.xml file");
         default_catalog_resource = true;
       }
       else
@@ -144,23 +151,29 @@ ResourcesManager_cpp::ResourcesManager_cpp() throw(ResourcesException)
     std::string default_file("");
     if (getenv("APPLI") != 0)
     {
-      default_file += getenv("HOME");
+      default_file += Kernel_Utils::HomePath();
       default_file += "/";
       default_file += getenv("APPLI");
       default_file += "/CatalogResources.xml";
-      _path_resources.push_back(default_file);
-    }
-    else
-    {
-      if(!getenv("KERNEL_ROOT_DIR"))
-        throw ResourcesException("you must define KERNEL_ROOT_DIR environment variable!! -> cannot load a CatalogResources.xml");
-      default_file = getenv("KERNEL_ROOT_DIR");
-      default_file += "/share/salome/resources/kernel/CatalogResources.xml";
-      _path_resources.push_back(default_file);
+      std::ifstream ifile(default_file.c_str(), std::ifstream::in );
+      if (ifile) {
+        // The file exists, and is open for input
+        DEBUG_MESSAGE("${APPLI}/CatalogResources.xml exists -> add it into resourcefiles list");
+        _path_resources.push_back(default_file);
+        default_catalog_resource=false;
+      }
     }
   }
-
-  _lasttime=0;
+  if (default_catalog_resource)
+  {
+    std::string default_file("");
+    if(!getenv("KERNEL_ROOT_DIR"))
+      throw ResourcesException("you must define KERNEL_ROOT_DIR environment variable!! -> cannot load a CatalogResources.xml");
+    default_file = getenv("KERNEL_ROOT_DIR");
+    default_file += "/share/salome/resources/kernel/CatalogResources.xml";
+    DEBUG_MESSAGE("${KERNEL_ROOT_DIR}/share/salome/resources/kernel/CatalogResources.xml -> add it into resourcefiles list");
+    _path_resources.push_back(default_file);
+  }
 
   ParseXmlFiles();
   RES_MESSAGE("ResourcesManager_cpp constructor end");
@@ -191,7 +204,7 @@ ResourcesManager_cpp::~ResourcesManager_cpp()
 //=============================================================================
 
 std::vector<std::string> 
-ResourcesManager_cpp::GetFittingResources(const resourceParams& params) throw(ResourcesException)
+ResourcesManager_cpp::GetFittingResources(const resourceParams& params) 
 {
   RES_MESSAGE("[GetFittingResources] on computer " << Kernel_Utils::GetHostname().c_str());
   RES_MESSAGE("[GetFittingResources] with resource name: " << params.name);
@@ -317,6 +330,11 @@ ResourcesManager_cpp::GetFittingResources(const resourceParams& params) throw(Re
   return vec;
 }
 
+void ResourcesManager_cpp::AddResourceInCatalogNoQuestion (const ParserResourcesType & new_resource)
+{
+  _resourcesList[new_resource.Name] = new_resource;
+}
+
 //=============================================================================
 /*!
  *  add an entry in the resources catalog xml file.
@@ -327,11 +345,29 @@ void
 ResourcesManager_cpp::AddResourceInCatalog(const ParserResourcesType & new_resource)
 {
   if (new_resource.Name == DEFAULT_RESOURCE_NAME){
-    std::string error("Cannot modify default local resource \"" + DEFAULT_RESOURCE_NAME + "\"");
-    throw ResourcesException(error);
+    ParserResourcesType default_resource = _resourcesList[DEFAULT_RESOURCE_NAME];
+    // some of the properties of the default resource shouldn't be modified
+    std::string check;
+    if( default_resource.HostName != new_resource.HostName)
+      check += "The Hostname property of the default resource can not be modified.\n";
+    if( default_resource.AppliPath != new_resource.AppliPath)
+      check += "The Applipath property of the default resource can not be modified.\n";
+    if( !new_resource.can_run_containers)
+      check += "The default resource should be able to run containers.\n";
+    if( !new_resource.can_launch_batch_jobs)
+      check += "The default resource should be able to launch batch jobs.\n";
+    if( default_resource.Protocol != new_resource.Protocol)
+      check += "The Protocol property of the default resource can not be modified.\n";
+    if(!check.empty())
+      throw ResourcesException(check);
   }
   // TODO - Add minimal check
-  _resourcesList[new_resource.Name] = new_resource;
+  this->AddResourceInCatalogNoQuestion( new_resource );
+}
+
+void ResourcesManager_cpp::DeleteAllResourcesInCatalog()
+{
+  _resourcesList.clear();
 }
 
 //=============================================================================
@@ -364,12 +400,9 @@ void ResourcesManager_cpp::WriteInXmlFile(std::string xml_file)
   RES_MESSAGE("WriteInXmlFile : start");
 
   MapOfParserResourcesType resourceListToSave(_resourcesList);
-  // We do not save default local resource because it is automatically created at startup
-  resourceListToSave.erase(DEFAULT_RESOURCE_NAME);
   if (resourceListToSave.empty())
   {
-    RES_MESSAGE("WriteInXmlFile: nothing to do, no resource except default \"" <<
-                DEFAULT_RESOURCE_NAME << "\"");
+    RES_MESSAGE("WriteInXmlFile: nothing to do, no resource to save!");
     return;
   }
 
@@ -422,12 +455,13 @@ const MapOfParserResourcesType& ResourcesManager_cpp::ParseXmlFiles()
     int result = stat((*_path_resources_it).c_str(), &statinfo);
     if (result < 0)
     {
-      RES_MESSAGE("Resource file " << *_path_resources_it << " does not exist");
+      WARNING_MESSAGE("Resource file " << *_path_resources_it << " does not exist -> no parsing");
       return _resourcesList;
     }
 
-    if(statinfo.st_mtime > _lasttime)
+    if(_lasttime == 0 || statinfo.st_mtime > _lasttime)
     {
+      DEBUG_MESSAGE("Resource file " << *_path_resources_it << " has been detected to be present and newer than Resources in memory");
       to_parse = true;
       _lasttime = statinfo.st_mtime;
     }
@@ -435,6 +469,7 @@ const MapOfParserResourcesType& ResourcesManager_cpp::ParseXmlFiles()
 
   if (to_parse)
   {
+    DEBUG_MESSAGE("After analyze of resoure files time meta data, a load of resources from scratch from files is necessary.");
     _resourcesList.clear();
     AddDefaultResourceInCatalog();
     // On parse tous les fichiers
@@ -442,15 +477,15 @@ const MapOfParserResourcesType& ResourcesManager_cpp::ParseXmlFiles()
     {
       MapOfParserResourcesType _resourcesList_tmp;
       MapOfParserResourcesType _resourcesBatchList_tmp;
-      SALOME_ResourcesCatalog_Handler *handler( new SALOME_ResourcesCatalog_Handler(_resourcesList_tmp) );
+      std::unique_ptr<SALOME_ResourcesCatalog_Handler> handler( new SALOME_ResourcesCatalog_Handler(_resourcesList_tmp) );
       const char *aFilePath( (*_path_resources_it).c_str() );
       FILE* aFile = fopen(aFilePath, "r");
-
       if (aFile != NULL)
       {
         xmlDocPtr aDoc = xmlReadFile(aFilePath, NULL, 0);
         if (aDoc != NULL)
         {
+          DEBUG_MESSAGE("XML parsing of Resource file \"" << aFilePath << "\"");
           handler->ProcessXmlDocument(aDoc);
 
           // adding new resources to the file
@@ -459,39 +494,38 @@ const MapOfParserResourcesType& ResourcesManager_cpp::ParseXmlFiles()
             MapOfParserResourcesType_it j = _resourcesList.find(i->first);
             if (i->second.HostName == DEFAULT_RESOURCE_NAME || i->second.HostName == Kernel_Utils::GetHostname())
             {
+              DEBUG_MESSAGE("Resource \"" << i->first << "\" in file \"" << aFilePath << "\" is detected as localhost");
               MapOfParserResourcesType_it it0(_resourcesList.find(DEFAULT_RESOURCE_NAME));
               if(it0!=_resourcesList.end())
                 {
+                  DEBUG_MESSAGE("Resource \"" << i->first << "\" in file \"" << aFilePath << "\" detected as localhost is already in memory -> update resource with content in file ( for attributes : nbOfNodes, nbOfProcPerNode, CPUFreqMHz and memInMB)");
                   ParserResourcesType& localhostElt((*it0).second);
                   localhostElt.DataForSort._nbOfNodes=(*i).second.DataForSort._nbOfNodes;
                   localhostElt.DataForSort._nbOfProcPerNode=(*i).second.DataForSort._nbOfProcPerNode;
                   localhostElt.DataForSort._CPUFreqMHz=(*i).second.DataForSort._CPUFreqMHz;
                   localhostElt.DataForSort._memInMB=(*i).second.DataForSort._memInMB;
                 }
-              RES_MESSAGE("Resource " << i->first << " is not added because it is the same "
-                          "machine as default local resource \"" << DEFAULT_RESOURCE_NAME << "\"");
+              DEBUG_MESSAGE("Resource \"" << i->first << "\" is not added because it is the same machine as default local resource \"" << DEFAULT_RESOURCE_NAME << "\"");
             }
             else if (j != _resourcesList.end())
             {
-              cerr << "ParseXmlFiles Warning, two resources with the same name were found, "
-                      "taking the first declaration : " << i->first << endl;
+              WARNING_MESSAGE("ParseXmlFiles Warning, two resources with the same name were found, taking the first declaration : " << i->first );
             }
             else
             {
+              DEBUG_MESSAGE("Resource \"" << i->first << "\" added");
               _resourcesList[i->first] = i->second;
             }
           }
         }
         else
-          std::cerr << "ResourcesManager_cpp: could not parse file " << aFilePath << std::endl;
+          ERROR_MESSAGE( "ResourcesManager_cpp: could not parse file " << aFilePath );
         // Free the document
         xmlFreeDoc(aDoc);
         fclose(aFile);
       }
       else
-        std::cerr << "ResourcesManager_cpp: file " << aFilePath << " is not readable." << std::endl;
-
-      delete handler;
+        ERROR_MESSAGE( "ResourcesManager_cpp: file " << aFilePath << " is not readable." );
     }
   }
   return _resourcesList;
@@ -608,9 +642,19 @@ void ResourcesManager_cpp::AddDefaultResourceInCatalog()
   resource.Protocol = sh;
   resource.Batch = none;
 #ifndef WIN32
-  if (getenv("HOME") != NULL && getenv("APPLI") != NULL)
+  struct stat statbuf;
+  std::string aHomePath = Kernel_Utils::HomePath();
+  if (aHomePath != "" && getenv("APPLI") != NULL)
   {
-    resource.AppliPath = string(getenv("HOME")) + "/" + getenv("APPLI");
+    if (stat(getenv("APPLI"), &statbuf) ==0 &&  S_ISREG(statbuf.st_mode))
+    {
+        // if $APPLI is a regular file, we asume it's a salome Launcher file
+        resource.AppliPath = string(getenv("APPLI"));
+    }
+    else
+    {
+        resource.AppliPath = aHomePath + "/" + getenv("APPLI");
+    }
   }
   string tmpdir = "/tmp";
   if (getenv("TMPDIR") != NULL)
@@ -633,4 +677,5 @@ void ResourcesManager_cpp::AddDefaultResourceInCatalog()
   resource.can_launch_batch_jobs = true;
   resource.can_run_containers = true;
   _resourcesList[resource.Name] = resource;
+  DEBUG_MESSAGE("Put Ressource \"" << resource.Name << "\" in dictionary of resources. This resource will be present even if resource files define it later.");
 }