TrinityCore
Config.cpp
Go to the documentation of this file.
1/*
2 * This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
3 *
4 * This program is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License as published by the
6 * Free Software Foundation; either version 2 of the License, or (at your
7 * option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
12 * more details.
13 *
14 * You should have received a copy of the GNU General Public License along
15 * with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18#include "Config.h"
19#include "Log.h"
20#include "StringConvert.h"
21#include <boost/filesystem/operations.hpp>
22#include <boost/property_tree/ini_parser.hpp>
23#include <algorithm>
24#include <cstdlib>
25#include <memory>
26#include <mutex>
27
28namespace bpt = boost::property_tree;
29namespace fs = boost::filesystem;
30
31namespace
32{
33 std::string _filename;
34 std::vector<std::string> _additonalFiles;
35 std::vector<std::string> _args;
36 bpt::ptree _config;
37 std::mutex _configLock;
38
39 bool LoadFile(std::string const& file, bpt::ptree& fullTree, std::string& error)
40 {
41 try
42 {
43 bpt::ini_parser::read_ini(file, fullTree);
44
45 if (fullTree.empty())
46 {
47 error = "empty file (" + file + ")";
48 return false;
49 }
50 }
51 catch (bpt::ini_parser::ini_parser_error const& e)
52 {
53 if (e.line() == 0)
54 error = e.message() + " (" + e.filename() + ")";
55 else
56 error = e.message() + " (" + e.filename() + ":" + std::to_string(e.line()) + ")";
57 return false;
58 }
59
60 return true;
61 }
62
63 // Converts ini keys to the environment variable key (upper snake case).
64 // Example of conversions:
65 // SomeConfig => SOME_CONFIG
66 // myNestedConfig.opt1 => MY_NESTED_CONFIG_OPT_1
67 // LogDB.Opt.ClearTime => LOG_DB_OPT_CLEAR_TIME
68 std::string IniKeyToEnvVarKey(std::string const& key)
69 {
70 std::string result;
71
72 const char *str = key.c_str();
73 size_t n = key.length();
74
75 char curr;
76 bool isEnd;
77 bool nextIsUpper;
78 bool currIsNumeric;
79 bool nextIsNumeric;
80
81 for (size_t i = 0; i < n; ++i)
82 {
83 curr = str[i];
84 if (curr == ' ' || curr == '.' || curr == '-')
85 {
86 result += '_';
87 continue;
88 }
89
90 isEnd = i == n - 1;
91 if (!isEnd)
92 {
93 nextIsUpper = isupper(str[i + 1]);
94
95 // handle "aB" to "A_B"
96 if (!isupper(curr) && nextIsUpper)
97 {
98 result += static_cast<char>(std::toupper(curr));
99 result += '_';
100 continue;
101 }
102
103 currIsNumeric = isNumeric(curr);
104 nextIsNumeric = isNumeric(str[i + 1]);
105
106 // handle "a1" to "a_1"
107 if (!currIsNumeric && nextIsNumeric)
108 {
109 result += static_cast<char>(std::toupper(curr));
110 result += '_';
111 continue;
112 }
113
114 // handle "1a" to "1_a"
115 if (currIsNumeric && !nextIsNumeric)
116 {
117 result += static_cast<char>(std::toupper(curr));
118 result += '_';
119 continue;
120 }
121 }
122
123 result += static_cast<char>(std::toupper(curr));
124 }
125 return result;
126 }
127
128 Optional<std::string> EnvVarForIniKey(std::string const& key)
129 {
130 std::string envKey = "TC_" + IniKeyToEnvVarKey(key);
131 char* val = std::getenv(envKey.c_str());
132 if (!val)
133 return std::nullopt;
134
135 return std::string(val);
136 }
137}
138
139bool ConfigMgr::LoadInitial(std::string file, std::vector<std::string> args,
140 std::string& error)
141{
142 std::lock_guard<std::mutex> lock(_configLock);
143
144 _filename = std::move(file);
145 _args = std::move(args);
146
147 bpt::ptree fullTree;
148 if (!LoadFile(_filename, fullTree, error))
149 return false;
150
151 // Since we're using only one section per config file, we skip the section and have direct property access
152 _config = fullTree.begin()->second;
153
154 return true;
155}
156
157bool ConfigMgr::LoadAdditionalFile(std::string file, bool keepOnReload, std::string& error)
158{
159 bpt::ptree fullTree;
160 if (!LoadFile(file, fullTree, error))
161 return false;
162
163 std::lock_guard<std::mutex> lock(_configLock);
164
165 for (bpt::ptree::value_type const& child : fullTree.begin()->second)
166 _config.put_child(bpt::ptree::path_type(child.first, '/'), child.second);
167
168 if (keepOnReload)
169 _additonalFiles.emplace_back(std::move(file));
170
171 return true;
172}
173
174bool ConfigMgr::LoadAdditionalDir(std::string const& dir, bool keepOnReload, std::vector<std::string>& loadedFiles, std::vector<std::string>& errors)
175{
176 fs::path dirPath = dir;
177 if (!fs::exists(dirPath) || !fs::is_directory(dirPath))
178 return true;
179
180 for (fs::directory_entry const& f : fs::recursive_directory_iterator(dirPath))
181 {
182 if (!fs::is_regular_file(f))
183 continue;
184
185 fs::path configFile = fs::absolute(f);
186 if (configFile.extension() != ".conf")
187 continue;
188
189 std::string fileName = configFile.generic_string();
190 std::string error;
191 if (LoadAdditionalFile(fileName, keepOnReload, error))
192 loadedFiles.push_back(std::move(fileName));
193 else
194 errors.push_back(std::move(error));
195 }
196
197 return errors.empty();
198}
199
201{
202 std::lock_guard<std::mutex> lock(_configLock);
203
204 std::vector<std::string> overriddenKeys;
205
206 for (bpt::ptree::value_type& itr: _config)
207 {
208 if (!itr.second.empty() || itr.first.empty())
209 continue;
210
211 Optional<std::string> envVar = EnvVarForIniKey(itr.first);
212 if (!envVar)
213 continue;
214
215 itr.second = bpt::ptree(*envVar);
216
217 overriddenKeys.push_back(itr.first);
218 }
219
220 return overriddenKeys;
221}
222
224{
225 static ConfigMgr instance;
226 return &instance;
227}
228
229bool ConfigMgr::Reload(std::vector<std::string>& errors)
230{
231 std::string error;
232 if (!LoadInitial(_filename, std::move(_args), error))
233 errors.push_back(std::move(error));
234
235 for (std::string const& additionalFile : _additonalFiles)
236 if (!LoadAdditionalFile(additionalFile, false, error))
237 errors.push_back(std::move(error));
238
240
241 return errors.empty();
242}
243
244template<class T>
245T ConfigMgr::GetValueDefault(std::string const& name, T def, bool quiet) const
246{
247 try
248 {
249 return _config.get<T>(bpt::ptree::path_type(name, '/'));
250 }
251 catch (bpt::ptree_bad_path const&)
252 {
253 Optional<std::string> envVar = EnvVarForIniKey(name);
254 if (envVar)
255 {
256 Optional<T> castedVar = Trinity::StringTo<T>(*envVar);
257 if (!castedVar)
258 {
259 TC_LOG_ERROR("server.loading", "Bad value defined for name {} in environment variables, going to use default instead", name);
260 return def;
261 }
262
263 if (!quiet)
264 TC_LOG_WARN("server.loading", "Missing name {} in config file {}, recovered with environment '{}' value.", name, _filename, *envVar);
265
266 return *castedVar;
267 }
268 else if (!quiet)
269 {
270 TC_LOG_WARN("server.loading", "Missing name {} in config file {}, add \"{} = {}\" to this file",
271 name, _filename, name, def);
272 }
273 }
274 catch (bpt::ptree_bad_data const&)
275 {
276 TC_LOG_ERROR("server.loading", "Bad value defined for name {} in config file {}, going to use {} instead",
277 name, _filename, def);
278 }
279
280 return def;
281}
282
283template<>
284std::string ConfigMgr::GetValueDefault<std::string>(std::string const& name, std::string def, bool quiet) const
285{
286 try
287 {
288 return _config.get<std::string>(bpt::ptree::path_type(name, '/'));
289 }
290 catch (bpt::ptree_bad_path const&)
291 {
292 Optional<std::string> envVar = EnvVarForIniKey(name);
293 if (envVar)
294 {
295 if (!quiet)
296 TC_LOG_WARN("server.loading", "Missing name {} in config file {}, recovered with environment '{}' value.", name, _filename, *envVar);
297
298 return *envVar;
299 }
300 else if (!quiet)
301 {
302 TC_LOG_WARN("server.loading", "Missing name {} in config file {}, add \"{} = {}\" to this file",
303 name, _filename, name, def);
304 }
305 }
306 catch (bpt::ptree_bad_data const&)
307 {
308 TC_LOG_ERROR("server.loading", "Bad value defined for name {} in config file {}, going to use {} instead",
309 name, _filename, def);
310 }
311
312 return def;
313}
314
315std::string ConfigMgr::GetStringDefault(std::string const& name, const std::string& def, bool quiet) const
316{
317 std::string val = GetValueDefault(name, def, quiet);
318 val.erase(std::remove(val.begin(), val.end(), '"'), val.end());
319 return val;
320}
321
322bool ConfigMgr::GetBoolDefault(std::string const& name, bool def, bool quiet) const
323{
324 std::string val = GetValueDefault(name, std::string(def ? "1" : "0"), quiet);
325 val.erase(std::remove(val.begin(), val.end(), '"'), val.end());
326 Optional<bool> boolVal = Trinity::StringTo<bool>(val);
327 if (boolVal)
328 return *boolVal;
329 else
330 {
331 TC_LOG_ERROR("server.loading", "Bad value defined for name {} in config file {}, going to use '{}' instead",
332 name, _filename, def ? "true" : "false");
333 return def;
334 }
335}
336
337int32 ConfigMgr::GetIntDefault(std::string const& name, int32 def, bool quiet) const
338{
339 return GetValueDefault(name, def, quiet);
340}
341
342int64 ConfigMgr::GetInt64Default(std::string const& name, int64 def, bool quiet) const
343{
344 return GetValueDefault(name, def, quiet);
345}
346
347float ConfigMgr::GetFloatDefault(std::string const& name, float def, bool quiet) const
348{
349 return GetValueDefault(name, def, quiet);
350}
351
352std::string const& ConfigMgr::GetFilename()
353{
354 std::lock_guard<std::mutex> lock(_configLock);
355 return _filename;
356}
357
358std::vector<std::string> const& ConfigMgr::GetArguments() const
359{
360 return _args;
361}
362
363std::vector<std::string> ConfigMgr::GetKeysByString(std::string const& name)
364{
365 std::lock_guard<std::mutex> lock(_configLock);
366
367 std::vector<std::string> keys;
368
369 for (bpt::ptree::value_type const& child : _config)
370 if (child.first.compare(0, name.length(), name) == 0)
371 keys.push_back(child.first);
372
373 return keys;
374}
int64_t int64
Definition: Define.h:137
int32_t int32
Definition: Define.h:138
#define TC_LOG_WARN(filterType__,...)
Definition: Log.h:162
#define TC_LOG_ERROR(filterType__,...)
Definition: Log.h:165
std::optional< T > Optional
Optional helper class to wrap optional values within.
Definition: Optional.h:25
bool isNumeric(wchar_t wchar)
Definition: Util.h:189
std::vector< std::string > OverrideWithEnvVariablesIfAny()
Overrides configuration with environment variables and returns overridden keys.
Definition: Config.cpp:200
float GetFloatDefault(std::string const &name, float def, bool quiet=false) const
Definition: Config.cpp:347
std::string const & GetFilename()
Definition: Config.cpp:352
bool GetBoolDefault(std::string const &name, bool def, bool quiet=false) const
Definition: Config.cpp:322
int64 GetInt64Default(std::string const &name, int64 def, bool quiet=false) const
Definition: Config.cpp:342
int32 GetIntDefault(std::string const &name, int32 def, bool quiet=false) const
Definition: Config.cpp:337
std::vector< std::string > GetKeysByString(std::string const &name)
Definition: Config.cpp:363
bool Reload(std::vector< std::string > &errors)
Definition: Config.cpp:229
static ConfigMgr * instance()
Definition: Config.cpp:223
bool LoadInitial(std::string file, std::vector< std::string > args, std::string &error)
Method used only for loading main configuration files (bnetserver.conf and worldserver....
Definition: Config.cpp:139
std::vector< std::string > const & GetArguments() const
Definition: Config.cpp:358
bool LoadAdditionalDir(std::string const &dir, bool keepOnReload, std::vector< std::string > &loadedFiles, std::vector< std::string > &errors)
Definition: Config.cpp:174
T GetValueDefault(std::string const &name, T def, bool quiet) const
Definition: Config.cpp:245
bool LoadAdditionalFile(std::string file, bool keepOnReload, std::string &error)
Definition: Config.cpp:157
std::string GetStringDefault(std::string const &name, const std::string &def, bool quiet=false) const
Definition: Config.cpp:315