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
|
/*
* This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Config.h"
#include "Log.h"
#include "StringConvert.h"
#include "StringFormat.h"
#include "Tokenize.h"
#include "Util.h"
#include <cstdlib>
#include <fstream>
#include <mutex>
#include <unordered_map>
namespace
{
std::string _filename;
std::vector<std::string> _additonalFiles;
std::vector<std::string> _args;
std::unordered_map<std::string /*name*/, std::string /*value*/> _configOptions;
std::unordered_map<std::string /*name*/, std::string /*value*/> _envVarCache;
std::mutex _configLock;
std::vector<std::string> _fatalConfigOptions =
{
{ "RealmID" },
{ "LoginDatabaseInfo" },
{ "WorldDatabaseInfo" },
{ "CharacterDatabaseInfo" },
};
// Check system configs like *server.conf*
bool IsAppConfig(std::string_view fileName)
{
size_t foundAuth = fileName.find("authserver.conf");
size_t foundWorld = fileName.find("worldserver.conf");
size_t foundImport = fileName.find("dbimport.conf");
return foundAuth != std::string_view::npos || foundWorld != std::string_view::npos || foundImport != std::string_view::npos;
}
// Check logging system configs like Appender.* and Logger.*
bool IsLoggingSystemOptions(std::string_view optionName)
{
size_t foundAppender = optionName.find("Appender.");
size_t foundLogger = optionName.find("Logger.");
return foundAppender != std::string_view::npos || foundLogger != std::string_view::npos;
}
template<typename Format, typename... Args>
inline void PrintError(std::string_view filename, Format&& fmt, Args&& ... args)
{
std::string message = Acore::StringFormatFmt(std::forward<Format>(fmt), std::forward<Args>(args)...);
if (IsAppConfig(filename))
{
fmt::print("{}\n", message);
}
else
{
LOG_ERROR("server.loading", message);
}
}
void AddKey(std::string const& optionName, std::string const& optionKey, std::string_view fileName, bool isOptional, [[maybe_unused]] bool isReload)
{
auto const& itr = _configOptions.find(optionName);
// Check old option
if (isOptional && itr == _configOptions.end())
{
if (!IsLoggingSystemOptions(optionName) && !isReload)
{
PrintError(fileName, "> Config::LoadFile: Found incorrect option '{}' in config file '{}'. Skip", optionName, fileName);
#ifdef CONFIG_ABORT_INCORRECT_OPTIONS
ABORT("> Core can't start if found incorrect options");
#endif
return;
}
}
// Check exit option
if (itr != _configOptions.end())
{
_configOptions.erase(optionName);
}
_configOptions.emplace(optionName, optionKey);
}
bool ParseFile(std::string const& file, bool isOptional, bool isReload)
{
std::ifstream in(file);
if (in.fail())
{
if (isOptional)
{
// No display erorr if file optional
return false;
}
throw ConfigException(Acore::StringFormatFmt("Config::LoadFile: Failed open {}file '{}'", isOptional ? "optional " : "", file));
}
uint32 count = 0;
uint32 lineNumber = 0;
std::unordered_map<std::string /*name*/, std::string /*value*/> fileConfigs;
auto IsDuplicateOption = [&](std::string const& confOption)
{
auto const& itr = fileConfigs.find(confOption);
if (itr != fileConfigs.end())
{
PrintError(file, "> Config::LoadFile: Duplicate key name '{}' in config file '{}'", confOption, file);
return true;
}
return false;
};
while (in.good())
{
lineNumber++;
std::string line;
std::getline(in, line);
// read line error
if (!in.good() && !in.eof())
throw ConfigException(Acore::StringFormatFmt("> Config::LoadFile: Failure to read line number {} in file '{}'", lineNumber, file));
// remove whitespace in line
line = Acore::String::Trim(line, in.getloc());
if (line.empty())
continue;
// comments and headers
if (line[0] == '#' || line[0] == '[')
continue;
auto const equal_pos = line.find('=');
if (equal_pos == std::string::npos || equal_pos == line.length())
{
PrintError(file, "> Config::LoadFile: Failure to read line number {} in file '{}'. Skip this line", lineNumber, file);
continue;
}
auto entry = Acore::String::Trim(line.substr(0, equal_pos), in.getloc());
auto value = Acore::String::Trim(line.substr(equal_pos + 1, std::string::npos), in.getloc());
value.erase(std::remove(value.begin(), value.end(), '"'), value.end());
// Skip if 2+ same options in one config file
if (IsDuplicateOption(entry))
continue;
// Add to temp container
fileConfigs.emplace(entry, value);
count++;
}
// No lines read
if (!count)
{
if (isOptional)
{
// No display erorr if file optional
return false;
}
throw ConfigException(Acore::StringFormatFmt("Config::LoadFile: Empty file '{}'", file));
}
// Add correct keys if file load without errors
for (auto const& [entry, key] : fileConfigs)
{
AddKey(entry, key, file, isOptional, isReload);
}
return true;
}
bool LoadFile(std::string const& file, bool isOptional, bool isReload)
{
try
{
return ParseFile(file, isOptional, isReload);
}
catch (const std::exception& e)
{
PrintError(file, "> {}", e.what());
}
return false;
}
// Converts ini keys to the environment variable key (upper snake case).
// Example of conversions:
// SomeConfig => SOME_CONFIG
// myNestedConfig.opt1 => MY_NESTED_CONFIG_OPT_1
// LogDB.Opt.ClearTime => LOG_DB_OPT_CLEAR_TIME
std::string IniKeyToEnvVarKey(std::string const& key)
{
std::string result;
const char* str = key.c_str();
size_t n = key.length();
char curr;
bool isEnd;
bool nextIsUpper;
bool currIsNumeric;
bool nextIsNumeric;
for (size_t i = 0; i < n; ++i)
{
curr = str[i];
if (curr == ' ' || curr == '.' || curr == '-')
{
result += '_';
continue;
}
isEnd = i == n - 1;
if (!isEnd)
{
nextIsUpper = isupper(str[i + 1]);
// handle "aB" to "A_B"
if (!isupper(curr) && nextIsUpper)
{
result += static_cast<char>(std::toupper(curr));
result += '_';
continue;
}
currIsNumeric = isNumeric(curr);
nextIsNumeric = isNumeric(str[i + 1]);
// handle "a1" to "a_1"
if (!currIsNumeric && nextIsNumeric)
{
result += static_cast<char>(std::toupper(curr));
result += '_';
continue;
}
// handle "1a" to "1_a"
if (currIsNumeric && !nextIsNumeric)
{
result += static_cast<char>(std::toupper(curr));
result += '_';
continue;
}
}
result += static_cast<char>(std::toupper(curr));
}
return result;
}
std::string GetEnvVarName(std::string const& configName)
{
return "AC_" + IniKeyToEnvVarKey(configName);
}
Optional<std::string> EnvVarForIniKey(std::string const& key)
{
std::string envKey = GetEnvVarName(key);
char* val = std::getenv(envKey.c_str());
if (!val)
return std::nullopt;
return std::string(val);
}
}
bool ConfigMgr::LoadInitial(std::string const& file, bool isReload /*= false*/)
{
std::lock_guard<std::mutex> lock(_configLock);
_configOptions.clear();
return LoadFile(file, false, isReload);
}
bool ConfigMgr::LoadAdditionalFile(std::string file, bool isOptional /*= false*/, bool isReload /*= false*/)
{
std::lock_guard<std::mutex> lock(_configLock);
return LoadFile(file, isOptional, isReload);
}
ConfigMgr* ConfigMgr::instance()
{
static ConfigMgr instance;
return &instance;
}
bool ConfigMgr::Reload()
{
if (!LoadAppConfigs(true))
{
return false;
}
if (!LoadModulesConfigs(true, false))
{
return false;
}
OverrideWithEnvVariablesIfAny();
return true;
}
// Check the _envVarCache if the env var is there
// if not, check the env for the value
Optional<std::string> GetEnvFromCache(std::string const& configName, std::string const& envVarName)
{
auto foundInCache = _envVarCache.find(envVarName);
Optional<std::string> foundInEnv;
// If it's not in the cache
if (foundInCache == _envVarCache.end())
{
// Check the env itself
foundInEnv = EnvVarForIniKey(configName);
if (foundInEnv)
{
// If it's found in the env, put it in the cache
_envVarCache.emplace(envVarName, *foundInEnv);
}
// Return the result of checking env
return foundInEnv;
}
return foundInCache->second;
}
std::vector<std::string> ConfigMgr::OverrideWithEnvVariablesIfAny()
{
std::lock_guard<std::mutex> lock(_configLock);
std::vector<std::string> overriddenKeys;
for (auto& itr : _configOptions)
{
if (itr.first.empty())
continue;
Optional<std::string> envVar = EnvVarForIniKey(itr.first);
if (!envVar)
continue;
itr.second = *envVar;
overriddenKeys.push_back(itr.first);
}
return overriddenKeys;
}
template<class T>
T ConfigMgr::GetValueDefault(std::string const& name, T const& def, bool showLogs /*= true*/) const
{
std::string strValue;
auto const& itr = _configOptions.find(name);
bool fatalConfig = false;
bool notFound = itr == _configOptions.end();
auto envVarName = GetEnvVarName(name);
Optional<std::string> envVar = GetEnvFromCache(name, envVarName);
if (envVar)
{
// If showLogs and this key/value pair wasn't found in the currently saved config
if (showLogs && (notFound || itr->second != envVar->c_str()))
{
LOG_INFO("server.loading", "> Config: Found config value '{}' from environment variable '{}'.", name, envVarName );
AddKey(name, envVar->c_str(), "ENVIRONMENT", false, false);
}
strValue = *envVar;
}
else if (notFound)
{
if (showLogs)
{
for (std::string s : _fatalConfigOptions)
if (s == name)
{
fatalConfig = true;
break;
}
if (fatalConfig)
LOG_FATAL("server.loading", "> Config:\n\nFATAL ERROR: Missing property {} in config file {}, add \"{} = {}\" to this file or define '{}' as an environment variable\n\nYour server cannot start without this option!",
name, _filename, name, Acore::ToString(def), envVarName);
else
LOG_WARN("server.loading", "> Config: Missing property {} in config file {}, add \"{} = {}\" to this file or define '{}' as an environment variable.",
name, _filename, name, Acore::ToString(def), envVarName);
}
return def;
}
else
{
strValue = itr->second;
}
auto value = Acore::StringTo<T>(strValue);
if (!value)
{
if (showLogs)
{
LOG_ERROR("server.loading", "> Config: Bad value defined for name '{}', going to use '{}' instead",
name, Acore::ToString(def));
}
return def;
}
return *value;
}
template<>
std::string ConfigMgr::GetValueDefault<std::string>(std::string const& name, std::string const& def, bool showLogs /*= true*/) const
{
auto const& itr = _configOptions.find(name);
bool fatalConfig = false;
bool notFound = itr == _configOptions.end();
auto envVarName = GetEnvVarName(name);
Optional<std::string> envVar = GetEnvFromCache(name, envVarName);
if (envVar)
{
// If showLogs and this key/value pair wasn't found in the currently saved config
if (showLogs && (notFound || itr->second != envVar->c_str()))
{
LOG_INFO("server.loading", "> Config: Found config value '{}' from environment variable '{}'.", name, envVarName);
AddKey(name, *envVar, "ENVIRONMENT", false, false);
}
return *envVar;
}
else if (notFound)
{
if (showLogs)
{
for (std::string s : _fatalConfigOptions)
if (s == name)
{
fatalConfig = true;
break;
}
if (fatalConfig)
LOG_FATAL("server.loading", "> Config:\n\nFATAL ERROR: Missing property {} in config file {}, add \"{} = {}\" to this file or define '{}' as an environment variable.\n\nYour server cannot start without this option!",
name, _filename, name, def, envVarName);
else
LOG_WARN("server.loading", "> Config: Missing property {} in config file {}, add \"{} = {}\" to this file or define '{}' as an environment variable.",
name, _filename, name, def, envVarName);
}
return def;
}
return itr->second;
}
template<class T>
T ConfigMgr::GetOption(std::string const& name, T const& def, bool showLogs /*= true*/) const
{
return GetValueDefault<T>(name, def, showLogs);
}
template<>
bool ConfigMgr::GetOption<bool>(std::string const& name, bool const& def, bool showLogs /*= true*/) const
{
std::string val = GetValueDefault(name, std::string(def ? "1" : "0"), showLogs);
auto boolVal = Acore::StringTo<bool>(val);
if (!boolVal)
{
if (showLogs)
{
LOG_ERROR("server.loading", "> Config: Bad value defined for name '{}', going to use '{}' instead",
name, def ? "true" : "false");
}
return def;
}
return *boolVal;
}
std::vector<std::string> ConfigMgr::GetKeysByString(std::string const& name)
{
std::lock_guard<std::mutex> lock(_configLock);
std::vector<std::string> keys;
for (auto const& [optionName, key] : _configOptions)
{
if (!optionName.compare(0, name.length(), name))
{
keys.emplace_back(optionName);
}
}
return keys;
}
std::string const ConfigMgr::GetFilename()
{
std::lock_guard<std::mutex> lock(_configLock);
return _filename;
}
std::vector<std::string> const& ConfigMgr::GetArguments() const
{
return _args;
}
std::string const ConfigMgr::GetConfigPath()
{
std::lock_guard<std::mutex> lock(_configLock);
#if AC_PLATFORM == AC_PLATFORM_WINDOWS
return "configs/";
#else
return std::string(_CONF_DIR) + "/";
#endif
}
void ConfigMgr::Configure(std::string const& initFileName, std::vector<std::string> args, std::string_view modulesConfigList /*= {}*/)
{
_filename = initFileName;
_args = std::move(args);
// Add modules config if exist
if (!modulesConfigList.empty())
{
for (auto const& itr : Acore::Tokenize(modulesConfigList, ',', false))
{
_additonalFiles.emplace_back(itr);
}
}
}
bool ConfigMgr::LoadAppConfigs(bool isReload /*= false*/)
{
// #1 - Load init config file .conf
if (!LoadInitial(_filename, isReload))
{
return false;
}
return true;
}
bool ConfigMgr::LoadModulesConfigs(bool isReload /*= false*/, bool isNeedPrintInfo /*= true*/)
{
if (_additonalFiles.empty())
{
// Send successful load if no found files
return true;
}
if (isNeedPrintInfo)
{
LOG_INFO("server.loading", " ");
LOG_INFO("server.loading", "Loading Modules Configuration...");
}
// Start loading module configs
std::string const& moduleConfigPath = GetConfigPath() + "modules/";
bool isExistDefaultConfig = true;
bool isExistDistConfig = true;
for (auto const& distFileName : _additonalFiles)
{
std::string defaultFileName = distFileName;
if (!defaultFileName.empty())
{
defaultFileName.erase(defaultFileName.end() - 5, defaultFileName.end());
}
// Load .conf.dist config
isExistDistConfig = LoadAdditionalFile(moduleConfigPath + distFileName, false, isReload);
if (!isReload && !isExistDistConfig)
{
LOG_FATAL("server.loading", "> ConfigMgr::LoadModulesConfigs: Not found original config '{}'. Stop loading", distFileName);
ABORT();
}
// Load .conf config
isExistDefaultConfig = LoadAdditionalFile(moduleConfigPath + defaultFileName, true, isReload);
if (isExistDefaultConfig && isExistDistConfig)
{
_moduleConfigFiles.emplace_back(defaultFileName);
}
else if (!isExistDefaultConfig && isExistDistConfig)
{
_moduleConfigFiles.emplace_back(distFileName);
}
}
if (isNeedPrintInfo)
{
if (!_moduleConfigFiles.empty())
{
// Print modules configurations
LOG_INFO("server.loading", " ");
LOG_INFO("server.loading", "Using modules configuration:");
for (auto const& itr : _moduleConfigFiles)
{
LOG_INFO("server.loading", "> {}", itr);
}
}
else
{
LOG_INFO("server.loading", "> Not found modules config files");
}
}
if (isNeedPrintInfo)
{
LOG_INFO("server.loading", " ");
}
return true;
}
/// @deprecated DO NOT USE - use GetOption<std::string> instead.
std::string ConfigMgr::GetStringDefault(std::string const& name, const std::string& def, bool showLogs /*= true*/)
{
return GetOption<std::string>(name, def, showLogs);
}
/// @deprecated DO NOT USE - use GetOption<bool> instead.
bool ConfigMgr::GetBoolDefault(std::string const& name, bool def, bool showLogs /*= true*/)
{
return GetOption<bool>(name, def, showLogs);
}
/// @deprecated DO NOT USE - use GetOption<int32> instead.
int ConfigMgr::GetIntDefault(std::string const& name, int def, bool showLogs /*= true*/)
{
return GetOption<int32>(name, def, showLogs);
}
/// @deprecated DO NOT USE - use GetOption<float> instead.
float ConfigMgr::GetFloatDefault(std::string const& name, float def, bool showLogs /*= true*/)
{
return GetOption<float>(name, def, showLogs);
}
#define TEMPLATE_CONFIG_OPTION(__typename) \
template __typename ConfigMgr::GetOption<__typename>(std::string const& name, __typename const& def, bool showLogs /*= true*/) const;
TEMPLATE_CONFIG_OPTION(std::string)
TEMPLATE_CONFIG_OPTION(uint8)
TEMPLATE_CONFIG_OPTION(int8)
TEMPLATE_CONFIG_OPTION(uint16)
TEMPLATE_CONFIG_OPTION(int16)
TEMPLATE_CONFIG_OPTION(uint32)
TEMPLATE_CONFIG_OPTION(int32)
TEMPLATE_CONFIG_OPTION(uint64)
TEMPLATE_CONFIG_OPTION(int64)
TEMPLATE_CONFIG_OPTION(float)
#undef TEMPLATE_CONFIG_OPTION
|