Newer
Older
//----------------------------------------------------------------------
// Includes
//----------------------------------------------------------------------
#include "MantidKernel/ConfigService.h"
#include "MantidKernel/DateAndTime.h"
#include "MantidKernel/MantidVersion.h"
#include "MantidKernel/Strings.h"
#include "MantidKernel/Logger.h"
#include "MantidKernel/StdoutChannel.h"
#include "MantidKernel/Exception.h"
#include "MantidKernel/FacilityInfo.h"
#include "MantidKernel/NetworkProxy.h"
#include <Poco/Util/LoggingConfigurator.h>
#include <Poco/Util/SystemConfiguration.h>
#include <Poco/Util/PropertyFileConfiguration.h>
#include <Poco/LoggingFactory.h>
#include <Poco/Path.h>
#include <Poco/File.h>
#include <MantidKernel/StringTokenizer.h>
#include <Poco/DOM/DOMParser.h>
#include <Poco/DOM/Document.h>
#include <Poco/DOM/NodeList.h>
#include <Poco/Environment.h>
Robert Whitley
committed
#include <Poco/Process.h>
#include <Poco/AutoPtr.h>
#include <Poco/Channel.h>
#include <Poco/DOM/Element.h>
#include <Poco/DOM/Node.h>
#include <Poco/Exception.h>
#include <Poco/Instantiator.h>
#include <Poco/Pipe.h>
#include <Poco/Platform.h>
#include <Poco/String.h>
#include <Poco/Logger.h>
#include <Poco/LoggingRegistry.h>
#include <Poco/PipeStream.h>
#include <Poco/StreamCopier.h>
Gigg, Martyn Anthony
committed
#include <boost/algorithm/string/join.hpp>
Gigg, Martyn Anthony
committed
#include <functional>
#include <iostream>
#include <stdexcept>
#include <utility>
Janik Zikovsky
committed
/**
* Get the welcome message for Mantid.
* @returns A string containing the welcome message for Mantid.
*/
std::string welcomeMessage() {
return "Welcome to Mantid " +
std::string(Mantid::Kernel::MantidVersion::version()) +
"\nPlease cite: " + Mantid::Kernel::MantidVersion::paperCitation() +
" and this release: " + Mantid::Kernel::MantidVersion::doi();
Janik Zikovsky
committed
}
namespace { // anonymous namespace for some utility functions
/// static Logger object
Logger g_log("ConfigService");
/**
* Split the supplied string on semicolons.
*
* @param path The path to split.
* @returns vector containing the split path.
std::vector<std::string> splitPath(const std::string &path) {
std::vector<std::string> splitted;
if (path.find(';') == std::string::npos) { // don't bother tokenizing
splitted.push_back(path);
int options = Mantid::Kernel::StringTokenizer::TOK_TRIM +
Mantid::Kernel::StringTokenizer::TOK_IGNORE_EMPTY;
Mantid::Kernel::StringTokenizer tokenizer(path, ";,", options);
auto iend = tokenizer.end();
for (auto itr = tokenizer.begin(); itr != iend; ++itr) {
if (!itr->empty()) {
splitted.push_back(*itr);
}
}
} // end of anonymous namespace
Campbell, Stuart
committed
/** Inner templated class to wrap the poco library objects that have protected
* destructors and expose them as public.
*/
template <typename T> class ConfigServiceImpl::WrappedObject : public T {
Campbell, Stuart
committed
public:
/// The template type of class that is being wrapped
Campbell, Stuart
committed
/// Simple constructor
WrappedObject() : T() { m_pPtr = static_cast<T *>(this); }
Campbell, Stuart
committed
/** Constructor with a class to wrap
Janik Zikovsky
committed
* @param F :: The object to wrap
*
* Note that this constructor can hide the copy constructor because it takes
* precedence over the copy constructor if supplied with a non-const
* WrappedObject argument. However, it just calls the base class copy
* constructor and sets m_pPtr, so the behaviour is the same as the copy
* constructor.
template <typename Field> explicit WrappedObject(Field &F) : T(F) {
Campbell, Stuart
committed
}
Campbell, Stuart
committed
/// Overloaded * operator returns the wrapped object pointer
const T &operator*() const { return *m_pPtr; }
Campbell, Stuart
committed
/// Overloaded * operator returns the wrapped object pointer
Campbell, Stuart
committed
/// Overloaded -> operator returns the wrapped object pointer
const T *operator->() const { return m_pPtr; }
Campbell, Stuart
committed
/// Overloaded -> operator returns the wrapped object pointer
Campbell, Stuart
committed
private:
/// Private pointer to the wrapped class
Campbell, Stuart
committed
};
// Back to the ConfigService class itself...
Campbell, Stuart
committed
//-------------------------------
// Private member functions
//-------------------------------
Roman Tolchenov
committed
Campbell, Stuart
committed
/// Private constructor for singleton class
: m_pConf(nullptr), m_pSysConfig(nullptr), m_changed_keys(),
m_ConfigPaths(), m_AbsolutePaths(), m_strBaseDir(""),
m_PropertyString(""), m_properties_file_name("Mantid.properties"),
#ifdef MPI_BUILD
// Use a different user properties file for an mpi-enabled build to avoid
// confusion if both are used on the same file system
m_user_properties_file_name("Mantid-mpi.user.properties"),
#else
m_user_properties_file_name("Mantid.user.properties"),
#endif
m_DataSearchDirs(), m_UserSearchDirs(), m_InstrumentDirs(),
m_instr_prefixes(), m_proxyInfo(), m_isProxySet(false) {
// getting at system details
m_pSysConfig = new WrappedObject<Poco::Util::SystemConfiguration>;
m_pConf = nullptr;
Campbell, Stuart
committed
// Register StdChannel with Poco
Poco::LoggingFactory::defaultFactory().registerChannelClass(
"StdoutChannel",
new Poco::Instantiator<Poco::StdoutChannel, Poco::Channel>);
Campbell, Stuart
committed
setBaseDirectory();
// Fill the list of possible relative path keys that may require conversion to
// absolute paths
m_ConfigPaths.emplace("mantidqt.python_interfaces_directory", true);
m_ConfigPaths.emplace("framework.plugins.directory", true);
m_ConfigPaths.emplace("pvplugins.directory", false);
m_ConfigPaths.emplace("mantidqt.plugins.directory", false);
m_ConfigPaths.emplace("instrumentDefinition.directory", true);
m_ConfigPaths.emplace("instrumentDefinition.vtpDirectory", true);
m_ConfigPaths.emplace("groupingFiles.directory", true);
m_ConfigPaths.emplace("maskFiles.directory", true);
m_ConfigPaths.emplace("colormaps.directory", true);
m_ConfigPaths.emplace("requiredpythonscript.directories", true);
m_ConfigPaths.emplace("pythonscripts.directory", true);
m_ConfigPaths.emplace("pythonscripts.directories", true);
m_ConfigPaths.emplace("python.plugins.directories", true);
m_ConfigPaths.emplace("user.python.plugins.directories", true);
m_ConfigPaths.emplace("datasearch.directories", true);
m_ConfigPaths.emplace("icatDownload.directory", true);
Campbell, Stuart
committed
// attempt to load the default properties file that resides in the directory
// of the executable
Janik Zikovsky
committed
std::string propertiesFilesList;
Gigg, Martyn Anthony
committed
updateConfig(getPropertiesDir() + m_properties_file_name, false, false);
Janik Zikovsky
committed
propertiesFilesList = getPropertiesDir() + m_properties_file_name;
// Load the local (machine) properties file, if it exists
Poco::File localFile(getLocalFilename());
updateConfig(getLocalFilename(), true, false);
propertiesFilesList += ", " + getLocalFilename();
}
if (Poco::Environment::has("MANTIDPROPERTIES")) {
// and then append the user properties
Janik Zikovsky
committed
updateConfig(getUserFilename(), true, false);
propertiesFilesList += ", " + getUserFilename();
// and the extra one from the environment
Janik Zikovsky
committed
updateConfig(Poco::Environment::get("MANTIDPROPERTIES"), true, true);
propertiesFilesList += ", " + Poco::Environment::get("MANTIDPROPERTIES");
Janik Zikovsky
committed
// Just do the user properties
updateConfig(getUserFilename(), true, true);
propertiesFilesList += ", " + getUserFilename();
}
Campbell, Stuart
committed
g_log.debug() << "ConfigService created.\n";
g_log.debug() << "Configured Mantid.properties directory of application as "
g_log.information() << "This is Mantid version " << MantidVersion::version()
<< " revision " << MantidVersion::revision() << '\n';
g_log.information() << "running on " << getComputerName() << " starting "
<< Types::Core::DateAndTime::getCurrentTime()
g_log.information() << "Properties file(s) loaded: " << propertiesFilesList
// Assert that the appdata and the instrument subdirectory exists
std::string appDataDir = getAppDataDir();
Poco::Path path(appDataDir);
path.pushDirectory("instrument");
Poco::File file(path);
// createDirectories will fail gracefully if it is already present - but will
// throw an error if it cannot create the directory
try {
file.createDirectories();
} catch (Poco::FileException &fe) {
g_log.error()
<< "Cannot create the local instrument cache directory ["
<< path.toString()
<< "]. Mantid will not be able to update instrument definitions.\n"
try {
vtpDir.createDirectories();
} catch (Poco::FileException &fe) {
g_log.error()
<< "Cannot create the local instrument geometry cache directory ["
<< path.toString()
<< "]. Mantid will be slower at viewing complex instruments.\n"
// must update the cache of instrument paths
cacheInstrumentPaths();
// update the facilities AFTER we have ensured that all of the directories are
// created and the paths updated
// if we don't do that first the function below will silently fail without
// initialising the facilities vector
// and Mantid will crash when it tries to access them, for example when
// creating the first time startup screen
updateFacilities();
Campbell, Stuart
committed
}
/** Private Destructor
* Prevents client from calling 'delete' on the pointer handed out by Instance
*/
ConfigServiceImpl::~ConfigServiceImpl() {
// std::cerr << "ConfigService destroyed.\n";
Campbell, Stuart
committed
Kernel::Logger::shutdown();
delete m_pSysConfig;
delete m_pConf; // potential double delete???
clearFacilities();
Campbell, Stuart
committed
}
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
/**
* Set the base directory path so we can file the Mantid.properties file.
*
* This will search for the base directory that contains the .properties file
* by checking the following places:
* - The current working directory
* - The executable directory
* - The directory defined by the MANTIDPATH enviroment var
* - OSX only: the directory two directories up from the executable (which
* is the base on the OSX package.
*
*/
void ConfigServiceImpl::setBaseDirectory() {
// Define the directory to search for the Mantid.properties file.
Poco::File f;
// First directory: the current working
m_strBaseDir = Poco::Path::current();
f = Poco::File(m_strBaseDir + m_properties_file_name);
if (f.exists())
return;
// Check the executable directory to see if it includes a mantid.properties
// file
m_strBaseDir = getDirectoryOfExecutable();
f = Poco::File(m_strBaseDir + m_properties_file_name);
if (f.exists())
return;
// Check the MANTIDPATH environment var
if (Poco::Environment::has("MANTIDPATH")) {
// Here we have to follow the convention of the rest of this code and
// add a trailing slash.
// Note: adding it to the MANTIDPATH itself will make other parts of the
// code crash.
m_strBaseDir = Poco::Environment::get("MANTIDPATH") + "/";
f = Poco::File(m_strBaseDir + m_properties_file_name);
return;
}
#ifdef __APPLE__
// Finally, on OSX check if we're in the package directory and the .properties
// file just happens to be two directories up
auto path = Poco::Path(getDirectoryOfExecutable());
m_strBaseDir = path.parent().parent().parent().toString();
#endif
}
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
namespace {
// look for specific keys and throw an exception if one is found
std::string checkForBadConfigOptions(const std::string &filename,
const std::string &propertiesString) {
std::stringstream stream(propertiesString);
std::stringstream resultPropertiesString;
std::string line;
int line_num = 0;
while (std::getline(stream, line)) {
line_num += 1; // increment early
bool is_ok = true;
// Check for common errors. Empty lines are ok, things that are a key
// without a value are a critical failure. Forbidden keys are just commented
// out.
if (line.empty() || (Kernel::Strings::strip(line)[0] == '#')) {
// do nothing
} else if (line.find("FilterChannel") != std::string::npos) {
is_ok = false;
}
// Print warning to error channel and comment out offending line
if (!is_ok) {
const auto end = line.find("=");
std::cerr << "Encontered invalid key \"";
if (end != std::string::npos) {
std::cerr << Kernel::Strings::strip(line.substr(0, end));
} else {
std::cerr << Kernel::Strings::strip(line);
}
std::cerr << "\" in " << filename << " on line " << line_num << std::endl;
// comment out the property
resultPropertiesString << '#';
}
// copy over the line
resultPropertiesString << line << '\n';
}
return resultPropertiesString.str();
}
} // end of anonymous namespace
Campbell, Stuart
committed
/** Loads the config file provided.
* If the file contains logging setup instructions then these will be used to
*setup the logging framework.
Campbell, Stuart
committed
*
Janik Zikovsky
committed
* @param filename :: The filename and optionally path of the file to load
* @param append :: If false (default) then any previous configuration is
*discarded, otherwise the new keys are added, and repeated keys will override
*existing ones.
Campbell, Stuart
committed
*/
void ConfigServiceImpl::loadConfig(const std::string &filename,
const bool append) {
Campbell, Stuart
committed
delete m_pConf;
if (!append) {
// remove the previous property string
Campbell, Stuart
committed
m_PropertyString = "";
m_changed_keys.clear();
Campbell, Stuart
committed
std::string temp;
bool good = readFile(filename, temp);
Campbell, Stuart
committed
// check if we have failed to open the file
if (filename == getUserPropertiesDir() + m_user_properties_file_name) {
// write out a fresh file
Campbell, Stuart
committed
createUserPropertiesFile();
Campbell, Stuart
committed
throw Exception::FileError("Cannot open file", filename);
Campbell, Stuart
committed
}
// verify the contents and comment out offending lines
temp = checkForBadConfigOptions(filename, temp);
if ((append) && (!m_PropertyString.empty())) {
Campbell, Stuart
committed
m_PropertyString = m_PropertyString + "\n" + temp;
Campbell, Stuart
committed
m_PropertyString = temp;
} catch (std::exception &e) {
// there was a problem loading the file - it probably is not there
std::cerr << "Problem loading the configuration file " << filename << " "
std::cerr << "Mantid is unable to start.\n" << std::endl;
throw;
Campbell, Stuart
committed
}
// use the cached property string to initialise the POCO property file
Campbell, Stuart
committed
std::istringstream istr(m_PropertyString);
m_pConf = new WrappedObject<Poco::Util::PropertyFileConfiguration>(istr);
Campbell, Stuart
committed
}
/**
* Read a file and place its contents into the given string
Janik Zikovsky
committed
* @param filename :: The filename of the file to read
* @param contents :: The file contents will be placed here
Campbell, Stuart
committed
* @returns A boolean indicating whether opening the file was successful
*/
bool ConfigServiceImpl::readFile(const std::string &filename,
std::string &contents) const {
Campbell, Stuart
committed
std::ifstream propFile(filename.c_str(), std::ios::in);
bool good = propFile.good();
Campbell, Stuart
committed
contents = "";
propFile.close();
return good;
}
Campbell, Stuart
committed
// slurp in entire file - extremely unlikely delimiter used as an alternate to
// \n
Campbell, Stuart
committed
contents.clear();
getline(propFile, contents, '`');
propFile.close();
return good;
}
/** Configures the Poco logging and starts it up
*
*/
void ConfigServiceImpl::configureLogging() {
// Configure the logging framework
Campbell, Stuart
committed
Poco::Util::LoggingConfigurator configurator;
configurator.configure(m_pConf);
} catch (std::exception &e) {
std::cerr << "Trouble configuring the logging framework " << e.what()
Campbell, Stuart
committed
}
Campbell, Stuart
committed
/**
* Searches the stored list for keys that have been loaded from the config file
* and may contain
* relative paths. Any it find are converted to absolute paths and stored
* separately
Campbell, Stuart
committed
*/
void ConfigServiceImpl::convertRelativeToAbsolute() {
Campbell, Stuart
committed
if (m_ConfigPaths.empty())
return;
Campbell, Stuart
committed
m_AbsolutePaths.clear();
std::map<std::string, bool>::const_iterator send = m_ConfigPaths.end();
for (std::map<std::string, bool>::const_iterator sitr = m_ConfigPaths.begin();
sitr != send; ++sitr) {
Campbell, Stuart
committed
std::string key = sitr->first;
if (!m_pConf->hasProperty(key))
continue;
Campbell, Stuart
committed
std::string value(m_pConf->getString(key));
value = makeAbsolute(value, key);
m_AbsolutePaths.emplace(key, value);
Campbell, Stuart
committed
}
}
/**
* Make a relative path or a list of relative paths into an absolute one.
Janik Zikovsky
committed
* @param dir :: The directory to convert
* @param key :: The key variable this relates to
* @returns A string containing an absolute path by resolving the relative
* directory with the executable directory
Campbell, Stuart
committed
*/
std::string ConfigServiceImpl::makeAbsolute(const std::string &dir,
const std::string &key) const {
if (dir.empty()) {
// Don't do anything for an empty value
return dir;
}
Campbell, Stuart
committed
std::string converted;
// If we have a list, chop it up and convert each one
if (dir.find_first_of(";,") != std::string::npos) {
auto splitted = splitPath(dir);
auto iend = splitted.cend();
for (auto itr = splitted.begin(); itr != iend;) {
Campbell, Stuart
committed
std::string absolute = makeAbsolute(*itr, key);
Campbell, Stuart
committed
++itr;
Campbell, Stuart
committed
converted += absolute;
Campbell, Stuart
committed
converted += ";";
Campbell, Stuart
committed
}
// MG 05/10/09: When the Poco::FilePropertyConfiguration object reads its
// key/value pairs it
// treats a backslash as the start of an escape sequence. If the next
// character does not
// form a valid sequence then the backslash is removed from the stream. This
// has the effect
// of giving malformed paths when using Windows-style directories. E.g
// C:\Mantid ->C:Mantid
Campbell, Stuart
committed
// and Poco::Path::isRelative throws an exception on this
bool is_relative(false);
Campbell, Stuart
committed
is_relative = Poco::Path(dir).isRelative();
} catch (Poco::PathSyntaxException &) {
g_log.warning() << "Malformed path detected in the \"" << key
<< "\" variable, skipping \"" << dir << "\"\n";
Campbell, Stuart
committed
return "";
}
Gigg, Martyn Anthony
committed
const std::string propFileDir(getPropertiesDir());
Gigg, Martyn Anthony
committed
converted = Poco::Path(propFileDir).resolve(dir).toString();
Campbell, Stuart
committed
converted = dir;
Campbell, Stuart
committed
converted = Poco::Path(converted).makeDirectory().toString();
// C++ doesn't have a const version of operator[] for maps so I can't call
// that here
auto it = m_ConfigPaths.find(key);
Campbell, Stuart
committed
bool required = false;
Campbell, Stuart
committed
required = it->second;
}
try {
if (required && !Poco::File(converted).exists()) {
g_log.debug() << "Required properties path \"" << converted
<< "\" in the \"" << key << "\" variable does not exist.\n";
Michael Whitty
committed
converted = "";
}
} catch (Poco::FileException &) {
g_log.debug() << "Required properties path \"" << converted
<< "\" in the \"" << key << "\" variable does not exist.\n";
Campbell, Stuart
committed
converted = "";
}
Gigg, Martyn Anthony
committed
// Backward slashes cannot be allowed to go into our properties file
// Note this is a temporary fix for ticket #2445.
Gigg, Martyn Anthony
committed
// Ticket #2460 prompts a review of our path handling in the config service.
Janik Zikovsky
committed
boost::replace_all(converted, "\\", "/");
Campbell, Stuart
committed
return converted;
}
/**
* Create the store of data search paths from the 'datasearch.directories' key
* within the Mantid.properties file.
Campbell, Stuart
committed
* The value of the key should be a semi-colon separated list of directories
*/
void ConfigServiceImpl::cacheDataSearchPaths() {
Campbell, Stuart
committed
std::string paths = getString("datasearch.directories");
if (paths.empty()) {
m_DataSearchDirs.clear();
} else {
m_DataSearchDirs = splitPath(paths);
}
Campbell, Stuart
committed
}
* Create the store of user search paths from the 'usersearch.directories' key
* within the Mantid.properties file.
* The value of the key should be a semi-colon separated list of directories
*/
void ConfigServiceImpl::cacheUserSearchPaths() {
m_UserSearchDirs.clear();
std::string paths = getString("usersearch.directories");
if (paths.empty()) {
m_UserSearchDirs.clear();
} else {
m_UserSearchDirs = splitPath(paths);
}
}
/**
* The path that is passed should be as returned by makeAbsolute() and
* this function will return true if that path is in the list
Janik Zikovsky
committed
* @param path :: the absolute path name to search for
* @return true if the path was found
*/
bool ConfigServiceImpl::isInDataSearchList(const std::string &path) const {
// the path produced by poco will have \ on windows, but the searchdirs will
// always have /
std::string correctedPath = path;
replace(correctedPath.begin(), correctedPath.end(), '\\', '/');
std::find_if(m_DataSearchDirs.cbegin(), m_DataSearchDirs.cend(),
std::bind2nd(std::equal_to<std::string>(), correctedPath));
Gigg, Martyn Anthony
committed
return (it != m_DataSearchDirs.end());
}
Campbell, Stuart
committed
/**
* writes a basic placeholder user.properties file to disk
* any errors are caught and logged, but not propagated
*/
void ConfigServiceImpl::createUserPropertiesFile() const {
try {
std::fstream filestr(
(getUserPropertiesDir() + m_user_properties_file_name).c_str(),
Janik Zikovsky
committed
std::fstream::out);
Campbell, Stuart
committed
filestr << "# This file can be used to override any properties for this "
filestr << "# Any properties found in this file will override any that are "
"found in the Mantid.Properties file\n";
filestr << "# As this file will not be replaced with further installations "
"of Mantid it is a safe place to put \n";
filestr << "# properties that suit your particular installation.\n";
filestr << "#\n";
filestr << "# See here for a list of possible options:\n";
filestr
<< "# "
"http://docs.mantidproject.org/nightly/concepts/PropertiesFile.html"
"\n\n";
filestr << "##\n";
filestr << "## GENERAL\n";
filestr << "##\n\n";
filestr << "## Set the number of algorithm properties to retain\n";
filestr << "#algorithms.retained=90\n\n";
filestr
<< "## Set the maximum number of cores used to run algorithms over\n";
filestr << "##\n";
filestr << "## FACILITY AND INSTRUMENT\n";
filestr << "## Sets the default facility\n";
filestr << "## e.g.: ISIS, SNS, ILL\n";
filestr << "## Sets the default instrument\n";
filestr << "## e.g. IRIS, HET, NIMROD\n";
filestr << '\n';
filestr << "## Sets the Q.convention\n";
filestr << "## Set to Crystallography for kf-ki instead of default "
"Inelastic which is ki-kf\n";
filestr << "#Q.convention=Crystallography\n";
filestr << "##\n";
filestr << "## DIRECTORIES\n";
filestr << "## Sets a list of directories (separated by semi colons) to "
filestr << "#datasearch.directories=../data;../isis/data\n\n";
filestr << "## Set a list (separated by semi colons) of directories to "
"look for additional Python scripts\n";
filestr << "#pythonscripts.directories=../scripts;../docs/MyScripts\n\n";
filestr << "## Uncomment to enable archive search - ICat and Orbiter\n";
filestr << "#datasearch.searcharchive=On\n\n";
filestr << "## Sets default save directory\n";
filestr << "##\n";
filestr << "## LOGGING\n";
filestr << "## Uncomment to change logging level\n";
filestr << "## Default is information\n";
filestr
<< "## Valid values are: error, warning, notice, information, debug\n";
filestr << "#logging.loggers.root.level=information\n\n";
filestr << "##\n";
filestr << "## MantidPlot\n";
filestr << "## Hides categories from the algorithm list in MantidPlot\n";
filestr << "#algorithms.catagories.hidden=Muons,Inelastic\n\n";
filestr << "## Show invisible workspaces\n";
filestr << "#MantidOptions.InvisibleWorkspaces=0\n";
filestr << "## Re-use plot instances for different plot types\n";
filestr << "#MantidOptions.ReusePlotInstances=Off\n\n";
filestr << "## Uncomment to disable use of OpenGL to render unwrapped "
"instrument views\n";
filestr << "#MantidOptions.InstrumentView.UseOpenGL=Off\n";
Campbell, Stuart
committed
filestr.close();
} catch (std::runtime_error &ex) {
g_log.warning() << "Unable to write out user.properties file to "
<< getUserPropertiesDir() << m_user_properties_file_name
<< " error: " << ex.what() << '\n';
Campbell, Stuart
committed
}
Campbell, Stuart
committed
//-------------------------------
// Public member functions
//-------------------------------
/**
* Removes the user properties file & loads a fresh configuration
*/
// Remove the current user properties file and write a fresh one
Poco::File userFile(getUserFilename());
userFile.remove();
} catch (Poco::Exception &) {
}
createUserPropertiesFile();
const bool append = false;
const bool updateCaches = true;
updateConfig(getPropertiesDir() + m_properties_file_name, append,
updateCaches);
Campbell, Stuart
committed
/** Updates and existing configuration and restarts the logging
Janik Zikovsky
committed
* @param filename :: The filename and optionally path of the file to load
* @param append :: If false (default) then any previous configuration is
* discarded,
* otherwise the new keys are added, and repeated keys will
* override existing ones.
* @param update_caches :: If true(default) then the various property caches
* are updated
Campbell, Stuart
committed
*/
void ConfigServiceImpl::updateConfig(const std::string &filename,
const bool append,
const bool update_caches) {
Campbell, Stuart
committed
loadConfig(filename, append);
// Ensure that the default save directory makes sense
/*
if (!append)
{
std::string save_dir = getString("defaultsave.directory");
if (Poco::trimInPlace(save_dir).size() == 0)
setString("defaultsave.directory", Poco::Path::home());
*/
// Only configure logging once
configureLogging();
// Ensure that any relative paths given in the configuration file are
// relative to the correct directory
Campbell, Stuart
committed
convertRelativeToAbsolute();
// Configure search paths into a specially saved store as they will be used
// frequently
Campbell, Stuart
committed
cacheDataSearchPaths();
Gigg, Martyn Anthony
committed
appendDataSearchDir(getString("defaultsave.directory"));
cacheUserSearchPaths();
cacheInstrumentPaths();
Campbell, Stuart
committed
}
/**
* Save the configuration to the user file
Janik Zikovsky
committed
* @param filename :: The filename for the saved configuration
* @throw std::runtime_error if the file cannot be opened
Campbell, Stuart
committed
*/
void ConfigServiceImpl::saveConfig(const std::string &filename) const {
Campbell, Stuart
committed
// Open and read the user properties file
Campbell, Stuart
committed
std::ifstream reader(filename.c_str(), std::ios::in);
if (reader.bad()) {
throw std::runtime_error("Error opening user properties file. Cannot save "
"updated configuration.");
std::string file_line, output;
Campbell, Stuart
committed
bool line_continuing(false);
while (std::getline(reader, file_line)) {
if (!file_line.empty()) {
Campbell, Stuart
committed
char last = *(file_line.end() - 1);
// If we are not in line continuation mode then need
// a fresh start line
Janik Zikovsky
committed
if (!line_continuing)
output = "";
Campbell, Stuart
committed
line_continuing = true;
output += file_line + "\n";
Gigg, Martyn Anthony
committed
continue;
Campbell, Stuart
committed
output += file_line;
line_continuing = false;
Campbell, Stuart
committed
output = file_line;
Campbell, Stuart
committed
output = "";
Gigg, Martyn Anthony
committed
updated_file += "\n";
Campbell, Stuart
committed
continue;
Robert Whitley
committed
// Output is the current line in the file
Robert Whitley
committed
// Extract the key from the current line
std::string key;
std::string::size_type pos = output.find('=');
if (pos == std::string::npos) {
key = output; // If no equals then the entire thing is the key
} else {
key = output.substr(0, pos); // Strip the equals to get only the key
// Now deal with trimming (removes spaces)
Robert Whitley
committed
Poco::trimInPlace(key);
Robert Whitley
committed
std::string::size_type comment = key.find('#');
// Check if it exists in the service using hasProperty and make sure it
// isn't a comment
if (comment == 0) {
updated_file += output;
} else if (!hasProperty(key)) {
// Remove the key from the changed key list
m_changed_keys.erase(key);
continue;
// If it does exist make sure the value is current
std::string value = getString(key, false);
Poco::replaceInPlace(value, "\\", "\\\\"); // replace single \ with double
Hahn, Steven
committed
updated_file.append(key).append("=").append(value);
// Remove the key from the changed key list
m_changed_keys.erase(key);
Robert Whitley
committed
}
Robert Whitley
committed
} // End while-loop
// Any remaining keys within the changed key store weren't present in the
// current user properties so append them
if (!m_changed_keys.empty()) {
Campbell, Stuart
committed
updated_file += "\n";
auto key_end = m_changed_keys.end();
for (auto key_itr = m_changed_keys.begin(); key_itr != key_end;) {
Campbell, Stuart
committed
updated_file += *key_itr + "=";
std::string value = getString(*key_itr, false);
Poco::replaceInPlace(value, "\\", "\\\\"); // replace single \ with double
updated_file += value;
Campbell, Stuart
committed
updated_file += "\n";
Campbell, Stuart
committed
m_changed_keys.clear();
Campbell, Stuart
committed
// Write out the new file
std::ofstream writer(filename.c_str(), std::ios_base::trunc);
Campbell, Stuart
committed
writer.close();
g_log.error() << "Error writing new user properties file. Cannot save "
"current configuration.\n";
throw std::runtime_error("Error writing new user properties file. Cannot "
"save current configuration.");
Campbell, Stuart
committed
}
Campbell, Stuart
committed
writer.write(updated_file.c_str(), updated_file.size());
writer.close();
}
/** Searches for a string within the currently loaded configuaration values and
* returns the value as a string. If the key is one of those that was a
*possible relative path
Campbell, Stuart
committed
* then the local store is searched first.
*
* @param keyName :: The case sensitive name of the property that you need the
*value of.
* @param use_cache :: If true, the local cache of directory names is queried
*first.
* @returns The string value of the property, or an empty string if the key
*cannot be found
Campbell, Stuart
committed
*/
std::string ConfigServiceImpl::getString(const std::string &keyName,
bool use_cache) const {
if (use_cache) {
auto mitr = m_AbsolutePaths.find(keyName);
Campbell, Stuart
committed
return (*mitr).second;
Campbell, Stuart
committed
std::string retVal;
Campbell, Stuart
committed
retVal = m_pConf->getString(keyName);
} catch (Poco::NotFoundException &) {
g_log.debug() << "Unable to find " << keyName << " in the properties file"
Campbell, Stuart
committed
retVal = "";
Campbell, Stuart
committed
return retVal;
}
Robert Whitley
committed
/** Searches for keys within the currently loaded configuaration values and
Robert Whitley
committed
*
* @param keyName :: The case sensitive name of the property that you need the
*key for.
* @returns The string value of each key within a vector, or an empty vector if
*there isn't
Robert Whitley
committed
* a key or it couldn't be found.
*/
std::vector<std::string>
ConfigServiceImpl::getKeys(const std::string &keyName) const {
std::vector<std::string> rawKeys;
m_pConf->keys(keyName, rawKeys);
return rawKeys;
Robert Whitley
committed
}
* Recursively gets a list of all config options from a given root node.
*
* @return Vector containing all config options
*/
void ConfigServiceImpl::getKeysRecursive(
const std::string &root, std::vector<std::string> &allKeys) const {
std::vector<std::string> rootKeys = getKeys(root);
if (rootKeys.empty())
for (auto &rootKey : rootKeys) {
std::string searchString;
if (root.empty()) {
Hahn, Steven
committed
searchString.append(rootKey);
Hahn, Steven
committed
searchString.append(root).append(".").append(rootKey);
/**
* Recursively gets a list of all config options.
*
* This function is needed as Boost Python does not like calling function with
* default arguments.
*
* @return Vector containing all config options
*/
std::vector<std::string> ConfigServiceImpl::keys() const {
std::vector<std::string> allKeys;
getKeysRecursive("", allKeys);
return allKeys;
/** Removes a key from the memory stored properties file and inserts the key
*into the
* changed key list so that when the program calls saveConfig the properties
*file will
Robert Whitley
committed
* be the same and not contain the key no more
*
* @param rootName :: The key that is to be deleted
Robert Whitley
committed
*/
void ConfigServiceImpl::remove(const std::string &rootName) const {
m_pConf->remove(rootName);
Robert Whitley
committed
m_changed_keys.insert(rootName);
}
/** Checks to see whether the given key exists.
*
* @param rootName :: The case sensitive key that you are looking to see if
*exists.
Robert Whitley
committed
* @returns Boolean value denoting whether the exists or not.
*/
bool ConfigServiceImpl::hasProperty(const std::string &rootName) const {
return m_pConf->hasProperty(rootName);
Robert Whitley
committed
}
/** Checks to see whether the given file target is an executable one and it
*exists.
* This method will expand environment variables found in the given file path.
Robert Whitley
committed
*
* @param target :: The path to the file you wish to see whether it's an
*executable.
Robert Whitley
committed
* @returns Boolean value denoting whether the file is an executable or not.
*/
bool ConfigServiceImpl::isExecutable(const std::string &target) const {
try {
std::string expTarget = Poco::Path::expand(target);
Poco::File tempFile = Poco::File(expTarget);
Robert Whitley
committed
return tempFile.canExecute();
Robert Whitley
committed
return false;
} catch (Poco::Exception &) {
Robert Whitley
committed
return false;
}
}