forked from npshub/mantid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConfigService.cpp
1907 lines (1710 loc) · 64.5 KB
/
ConfigService.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
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
316
317
318
319
320
321
322
323
324
325
326
327
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Mantid Repository : https://github.com/mantidproject/mantid
//
// Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
// NScD Oak Ridge National Laboratory, European Spallation Source,
// Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
// SPDX - License - Identifier: GPL - 3.0 +
//----------------------------------------------------------------------
// Includes
//----------------------------------------------------------------------
#include "MantidKernel/ConfigService.h"
#include "MantidKernel/DateAndTime.h"
#include "MantidKernel/Exception.h"
#include "MantidKernel/FacilityInfo.h"
#include "MantidKernel/Glob.h"
#include "MantidKernel/Logger.h"
#include "MantidKernel/MantidVersion.h"
#include "MantidKernel/NetworkProxy.h"
#include "MantidKernel/StdoutChannel.h"
#include "MantidKernel/StringTokenizer.h"
#include "MantidKernel/Strings.h"
#include "MantidKernel/System.h"
#include <Poco/AutoPtr.h>
#include <Poco/Channel.h>
#include <Poco/DOM/DOMParser.h>
#include <Poco/DOM/Document.h>
#include <Poco/DOM/Element.h>
#include <Poco/DOM/Node.h>
#include <Poco/DOM/NodeList.h>
#include <Poco/Environment.h>
#include <Poco/Exception.h>
#include <Poco/File.h>
#include <Poco/Instantiator.h>
#include <Poco/Logger.h>
#include <Poco/LoggingFactory.h>
#include <Poco/LoggingRegistry.h>
#include <Poco/Path.h>
#include <Poco/Pipe.h>
#include <Poco/PipeStream.h>
#include <Poco/Platform.h>
#include <Poco/Process.h>
#include <Poco/StreamCopier.h>
#include <Poco/String.h>
#include <Poco/URI.h>
#include <Poco/Util/LoggingConfigurator.h>
#include <Poco/Util/PropertyFileConfiguration.h>
#include <Poco/Util/SystemConfiguration.h>
#include <Poco/Version.h>
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/optional/optional.hpp>
#include <algorithm>
#include <cctype>
#include <exception>
#include <fstream>
#include <functional>
#include <iostream>
#include <stdexcept>
#include <utility>
#ifdef __APPLE__
#include <mach-o/dyld.h>
#endif
namespace Mantid {
/**
* 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();
}
namespace Kernel {
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.emplace_back(path);
} else {
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.emplace_back(*itr);
}
}
}
return splitted;
}
} // end of anonymous namespace
//-------------------------------
// Private member functions
//-------------------------------
/// Private constructor for singleton class
ConfigServiceImpl::ConfigServiceImpl()
: m_pConf(nullptr), m_pSysConfig(new Poco::Util::SystemConfiguration()), m_changed_keys(), 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_instrumentDirs(), m_proxyInfo(), m_isProxySet(false) {
// Register StdChannel with Poco
Poco::LoggingFactory::defaultFactory().registerChannelClass(
"StdoutChannel", new Poco::Instantiator<Poco::StdoutChannel, Poco::Channel>);
setBaseDirectory();
m_configPaths.insert("framework.plugins.directory");
m_configPaths.insert("mantidqt.plugins.directory");
m_configPaths.insert("instrumentDefinition.directory");
m_configPaths.insert("instrumentDefinition.vtpDirectory");
m_configPaths.insert("groupingFiles.directory");
m_configPaths.insert("maskFiles.directory");
m_configPaths.insert("colormaps.directory");
m_configPaths.insert("requiredpythonscript.directories");
m_configPaths.insert("pythonscripts.directory");
m_configPaths.insert("pythonscripts.directories");
m_configPaths.insert("python.plugins.directories");
m_configPaths.insert("user.python.plugins.directories");
m_configPaths.insert("icatDownload.directory");
m_configPaths.insert("datasearch.directories");
m_configPaths.insert("python.plugins.manifest");
m_configPaths.insert("python.templates.directory");
// attempt to load the default properties file that resides in the directory
// of the executable
std::string propertiesFilesList;
updateConfig(getPropertiesDir() + m_properties_file_name, false, false);
propertiesFilesList = getPropertiesDir() + m_properties_file_name;
// Load the local (machine) properties file, if it exists
Poco::File localFile(getLocalFilename());
if (localFile.exists()) {
updateConfig(getLocalFilename(), true, false);
propertiesFilesList += ", " + getLocalFilename();
}
if (Poco::Environment::has("MANTIDPROPERTIES")) {
// and then append the user properties
updateConfig(getUserFilename(), true, false);
propertiesFilesList += ", " + getUserFilename();
// and the extra one from the environment
updateConfig(Poco::Environment::get("MANTIDPROPERTIES"), true, true);
propertiesFilesList += ", " + Poco::Environment::get("MANTIDPROPERTIES");
} else {
// Just do the user properties
updateConfig(getUserFilename(), true, true);
propertiesFilesList += ", " + getUserFilename();
}
g_log.debug() << "ConfigService created.\n";
g_log.debug() << "Configured Mantid.properties directory of application as " << getPropertiesDir() << '\n';
g_log.information() << "This is Mantid version " << MantidVersion::version() << " revision "
<< MantidVersion::revision() << '\n';
g_log.information() << "running on " << getComputerName() << " starting "
<< Types::Core::DateAndTime::getCurrentTime().toFormattedString("%Y-%m-%dT%H:%MZ") << "\n";
g_log.information() << "Properties file(s) loaded: " << propertiesFilesList << '\n';
// 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"
<< fe.what() << '\n';
}
Poco::File vtpDir(getVTPFileDirectory());
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"
<< fe.what() << '\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();
}
/** Private Destructor
* Prevents client from calling 'delete' on the pointer handed out by Instance
*/
ConfigServiceImpl::~ConfigServiceImpl() {
Kernel::Logger::shutdown();
clearFacilities();
}
/**
* 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);
if (f.exists())
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
}
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("=");
g_log.warning() << "Encontered invalid key \"";
if (end != std::string::npos) {
g_log.warning() << Kernel::Strings::strip(line.substr(0, end));
} else {
g_log.warning() << Kernel::Strings::strip(line);
}
g_log.warning() << "\" 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
/** Loads the config file provided.
* If the file contains logging setup instructions then these will be used to
*setup the logging framework.
*
* @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.
*/
void ConfigServiceImpl::loadConfig(const std::string &filename, const bool append) {
if (!append) {
// remove the previous property string
m_propertyString = "";
m_changed_keys.clear();
}
try {
// slurp in entire file
std::string temp;
bool good = readFile(filename, temp);
// check if we have failed to open the file
if ((!good) || (temp.empty())) {
if (filename == getUserPropertiesDir() + m_user_properties_file_name) {
// write out a fresh file
createUserPropertiesFile();
} else {
throw Exception::FileError("Cannot open file", filename);
}
}
// verify the contents and comment out offending lines
temp = checkForBadConfigOptions(filename, temp);
// store the property string
if ((append) && (!m_propertyString.empty())) {
m_propertyString = m_propertyString + "\n" + temp;
} else {
m_propertyString = temp;
}
} catch (std::exception &e) {
// there was a problem loading the file - it probably is not there
g_log.error() << "Problem loading the configuration file " << filename << " " << e.what() << '\n';
g_log.error() << "Mantid is unable to start.\n" << std::endl;
throw;
}
// use the cached property string to initialise the POCO property file
std::istringstream istr(m_propertyString);
m_pConf = new Poco::Util::PropertyFileConfiguration(istr);
}
/**
* Read a file and place its contents into the given string
* @param filename :: The filename of the file to read
* @param contents :: The file contents will be placed here
* @returns A boolean indicating whether opening the file was successful
*/
bool ConfigServiceImpl::readFile(const std::string &filename, std::string &contents) const {
std::ifstream propFile(filename.c_str(), std::ios::in);
bool good = propFile.good();
if (!good) {
contents = "";
propFile.close();
return good;
}
// slurp in entire file - extremely unlikely delimiter used as an alternate to
// \n
contents.clear();
getline(propFile, contents, '`');
propFile.close();
return good;
}
/** Configures the Poco logging and starts it up
*
*/
void ConfigServiceImpl::configureLogging() {
try {
// Configure the logging framework
Poco::Util::LoggingConfigurator configurator;
#if POCO_VERSION > 0x01090400
configurator.configure(m_pConf);
#else
configurator.configure(m_pConf.get());
#endif
} catch (std::exception &e) {
std::cerr << "Trouble configuring the logging framework " << e.what() << '\n';
}
}
/**
* Make a relative path or a list of relative paths into an absolute one.
* @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
*/
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;
}
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;) {
std::string absolute = makeAbsolute(*itr, key);
if (absolute.empty()) {
++itr;
} else {
converted += absolute;
if (++itr != iend) {
converted += ";";
}
}
}
return converted;
}
// 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
// and Poco::Path::isRelative throws an exception on this
bool is_relative(false);
try {
is_relative = Poco::Path(dir).isRelative();
} catch (Poco::PathSyntaxException &) {
g_log.warning() << "Malformed path detected in the \"" << key << "\" variable, skipping \"" << dir << "\"\n";
return "";
}
if (is_relative) {
const std::string propFileDir(getPropertiesDir());
converted = Poco::Path(propFileDir).resolve(dir).toString();
} else {
converted = dir;
}
if (Poco::Path(converted).getExtension() != "") {
converted = Poco::Path(converted).toString();
} else {
converted = Poco::Path(converted).makeDirectory().toString();
}
// Backward slashes cannot be allowed to go into our properties file
// Note this is a temporary fix for ticket #2445.
// Ticket #2460 prompts a review of our path handling in the config service.
boost::replace_all(converted, "\\", "/");
return converted;
}
/**
* Create the store of data search paths from the 'datasearch.directories' key
* within the Mantid.properties file.
* The value of the key should be a semi-colon separated list of directories
*/
void ConfigServiceImpl::cacheDataSearchPaths() {
std::string paths = getString("datasearch.directories", true);
if (paths.empty()) {
m_dataSearchDirs.clear();
} else {
m_dataSearchDirs = 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
* @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(), '\\', '/');
using std::placeholders::_1;
auto it = std::find_if(m_dataSearchDirs.cbegin(), m_dataSearchDirs.cend(),
std::bind(std::equal_to<std::string>(), _1, correctedPath));
return (it != m_dataSearchDirs.end());
}
/**
* 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(), std::fstream::out);
filestr << "# This file can be used to override any properties for this "
"installation.\n";
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 maximum number of cores used to run algorithms over\n";
filestr << "#MultiThreaded.MaxCores=4\n\n";
filestr << "##\n";
filestr << "## FACILITY AND INSTRUMENT\n";
filestr << "##\n\n";
filestr << "## Sets the default facility\n";
filestr << "## e.g.: ISIS, SNS, ILL\n";
filestr << "default.facility=\n\n";
filestr << "## Sets the default instrument\n";
filestr << "## e.g. IRIS, HET, NIMROD\n";
filestr << "default.instrument=\n\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 << "##\n\n";
filestr << "## Sets a list of directories (separated by semi colons) to "
"search for data\n";
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 << "#defaultsave.directory=../data\n\n";
filestr << "##\n";
filestr << "## LOGGING\n";
filestr << "##\n\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 << "##\n\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\n";
filestr << "## Muon GUI settings\n";
filestr << "#muon.GUI = \n";
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';
}
}
//-------------------------------
// Public member functions
//-------------------------------
/**
* Removes the user properties file & loads a fresh configuration
*/
void ConfigServiceImpl::reset() {
// Remove the current user properties file and write a fresh one
try {
Poco::File userFile(getUserFilename());
userFile.remove();
} catch (Poco::Exception &) {
}
createUserPropertiesFile();
// Now load the original
const bool append = false;
const bool updateCaches = true;
updateConfig(getPropertiesDir() + m_properties_file_name, append, updateCaches);
}
/** Updates and existing configuration and restarts the logging
* @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
*/
void ConfigServiceImpl::updateConfig(const std::string &filename, const bool append, const bool update_caches) {
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());
}
*/
if (update_caches) {
// Only configure logging once
configureLogging();
// Configure search paths into a specially saved store as they will be used
// frequently
cacheDataSearchPaths();
appendDataSearchDir(getString("defaultsave.directory"));
cacheInstrumentPaths();
}
}
/**
* Save the configuration to the user file
* @param filename :: The filename for the saved configuration
* @throw std::runtime_error if the file cannot be opened
*/
void ConfigServiceImpl::saveConfig(const std::string &filename) const {
// Open and read the user properties file
std::string updated_file;
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;
bool line_continuing(false);
while (std::getline(reader, file_line)) {
if (!file_line.empty()) {
char last = *(file_line.end() - 1);
if (last == '\\') {
// If we are not in line continuation mode then need
// a fresh start line
if (!line_continuing)
output = "";
line_continuing = true;
output += file_line + "\n";
continue;
} else if (line_continuing) {
output += file_line;
line_continuing = false;
} else {
output = file_line;
}
} else {
output = "";
updated_file += "\n";
continue;
} // end if-else
// Output is the current line in the file
// 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)
Poco::trimInPlace(key);
// Find the comments
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;
} else {
// If it does exist make sure the value is current
std::string value = getString(key, false);
Poco::replaceInPlace(value, "\\", "\\\\"); // replace single \ with double
updated_file.append(key).append("=").append(value);
// Remove the key from the changed key list
m_changed_keys.erase(key);
}
updated_file += "\n";
} // 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()) {
updated_file += "\n";
auto key_end = m_changed_keys.end();
for (auto key_itr = m_changed_keys.begin(); key_itr != key_end;) {
updated_file += *key_itr + "=";
std::string value = getString(*key_itr, false);
Poco::replaceInPlace(value, "\\", "\\\\"); // replace single \ with double
updated_file += value;
if (++key_itr != key_end) {
updated_file += "\n";
}
}
m_changed_keys.clear();
}
// Write out the new file
std::ofstream writer(filename.c_str(), std::ios_base::trunc);
if (writer.bad()) {
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.");
}
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
* then the local store is searched first.
*
* @param keyName :: The case sensitive name of the property that you need the
*value of.
* @param pathAbsolute :: If true then any key that looks like it contains
* a path has this path converted to an absolute path.
* @returns The string value of the property, or an empty string if the key
*cannot be found
*/
std::string ConfigServiceImpl::getString(const std::string &keyName, bool pathAbsolute) const {
if (m_pConf->hasProperty(keyName)) {
std::string value = m_pConf->getString(keyName);
const auto key = m_configPaths.find(keyName);
if (pathAbsolute && key != m_configPaths.end()) {
value = makeAbsolute(value, keyName);
}
return value;
}
g_log.debug() << "Unable to find " << keyName << " in the properties file" << '\n';
return {};
}
/** Searches for keys within the currently loaded configuaration values and
* returns them as strings in a vector.
*
* @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
* 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;
}
/**
* 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())
allKeys.emplace_back(root);
for (auto &rootKey : rootKeys) {
std::string searchString;
if (root.empty()) {
searchString.append(rootKey);
} else {
searchString.append(root).append(".").append(rootKey);
}
getKeysRecursive(searchString, allKeys);
}
}
/**
* 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
* be the same and not contain the key no more
*
* @param rootName :: The key that is to be deleted
*/
void ConfigServiceImpl::remove(const std::string &rootName) {
m_pConf->remove(rootName);
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.
* @returns Boolean value denoting whether the exists or not.
*/
bool ConfigServiceImpl::hasProperty(const std::string &rootName) const { return m_pConf->hasProperty(rootName); }
/** 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.
*
* @param target :: The path to the file you wish to see whether it's an
*executable.
* @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);
if (tempFile.exists()) {
return tempFile.canExecute();
} else
return false;
} catch (Poco::Exception &) {
return false;
}
}
/** Runs a command line string to open a program. The function can take program
*arguments.
* i.e it can load in a file to the program on startup.
*
* This method will expand environment variables found in the given file path.
*
* @param programFilePath :: The directory where the program is located.
* @param programArguments :: The arguments that the program can take on
*startup. For example,
* the file to load up.
*/
void ConfigServiceImpl::launchProcess(const std::string &programFilePath,
const std::vector<std::string> &programArguments) const {
try {
std::string expTarget = Poco::Path::expand(programFilePath);
Poco::Process::launch(expTarget, programArguments);
} catch (Poco::SystemException &e) {
throw std::runtime_error(e.what());
}
}
/**
* Set a configuration property. An existing key will have its value updated.
* @param key :: The key to refer to this property
* @param value :: The value of the property
*/
void ConfigServiceImpl::setString(const std::string &key, const std::string &value) {
// If the value is unchanged (after any path conversions), there's nothing to
// do.
const std::string old = getString(key);
if (value == old)
return;
// Update the internal value
m_pConf->setString(key, value);
// Cache things that are accessed frequently
if (key == "datasearch.directories") {
cacheDataSearchPaths();
} else if (key == "instrumentDefinition.directory") {
cacheInstrumentPaths();
} else if (key == "defaultsave.directory") {
appendDataSearchDir(value);
} else if (key == "logging.channels.consoleChannel.class") {
// this key requires reloading logging for it to take effect
configureLogging();
}
m_notificationCenter.postNotification(new ValueChanged(key, value, old));
m_changed_keys.insert(key);
}
/** Searches for a string within the currently loaded configuration values and
* attempts to convert the values to the template type supplied.
*
* @param keyName :: The case sensitive name of the property that you need the
*value of.
* @returns An optional container with the value if found
*/
template <typename T> boost::optional<T> ConfigServiceImpl::getValue(const std::string &keyName) {
std::string strValue = getString(keyName);
T output;
int result = Mantid::Kernel::Strings::convert(strValue, output);
if (result != 1) {
return boost::none;
}
return boost::optional<T>(output);
}
/** Searches for a string within the currently loaded configuration values and
* attempts to convert the values to a boolean value
*
* @param keyName :: The case sensitive name of the property that you need the
*value of.
* @returns An optional container with the value if found
*/
template <> boost::optional<bool> ConfigServiceImpl::getValue(const std::string &keyName) {
auto returnedValue = getValue<std::string>(keyName);
if (!returnedValue.is_initialized()) {
return boost::none;
}
auto &configVal = returnedValue.get();
std::transform(configVal.begin(), configVal.end(), configVal.begin(), ::tolower);
boost::trim(configVal);
bool trueString = configVal == "true";
bool valueOne = configVal == "1";
bool onOffString = configVal == "on";
// A string of 1 or true both count
return trueString || valueOne || onOffString;
}
/**
* Return the full filename of the local properties file.
* @returns A string containing the full path to the local file.
*/
std::string ConfigServiceImpl::getLocalFilename() const {
#ifdef _WIN32
return "Mantid.local.properties";
#else
return "/etc/mantid.local.properties";
#endif
}
/**
* Return the full filename of the user properties file
* @returns A string containing the full path to the user file
*/
std::string ConfigServiceImpl::getUserFilename() const { return getUserPropertiesDir() + m_user_properties_file_name; }
/** Searches for the string within the environment variables and returns the
* value as a string.
*
* @param keyName :: The name of the environment variable that you need the
*value of.
* @returns The string value of the property
*/
std::string ConfigServiceImpl::getEnvironment(const std::string &keyName) {
return m_pSysConfig->getString("system.env." + keyName);
}
/** Gets the name of the host operating system
*
* @returns The name pf the OS version