-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathconfig.cpp
More file actions
368 lines (277 loc) · 8.81 KB
/
config.cpp
File metadata and controls
368 lines (277 loc) · 8.81 KB
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
/* Configuration file parsing.
*
* Author: Steffen Vogel <post@steffenvogel.de>
* SPDX-FileCopyrightText: 2014-2023 Institute for Automation of Complex Power Systems, RWTH Aachen University
* SPDX-License-Identifier: Apache-2.0
*/
#include <regex>
#include <string>
#include <glob.h>
#include <libgen.h>
#include <linux/limits.h>
#include <unistd.h>
#include <villas/boxes.hpp>
#include <villas/config_class.hpp>
#include <villas/config_helper.hpp>
#include <villas/log.hpp>
#include <villas/node/config.hpp>
#include <villas/node/exceptions.hpp>
#include <villas/utils.hpp>
#ifdef WITH_CONFIG
#include <libconfig.h>
#endif
using namespace villas;
using namespace villas::node;
Config::Config() : logger(Log::get("config")), root(nullptr) {}
Config::Config(const std::string &u) : Config() { root = load(u); }
Config::~Config() { json_decref(root); }
json_t *Config::load(std::FILE *f, bool resolveInc, bool resolveEnvVars) {
json_t *root = decode(f);
if (resolveInc) {
json_t *root_old = root;
root = expandIncludes(root);
json_decref(root_old);
}
if (resolveEnvVars) {
json_t *root_old = root;
root = expandEnvVars(root);
json_decref(root_old);
}
return root;
}
json_t *Config::load(const std::string &u, bool resolveInc,
bool resolveEnvVars) {
FILE *f;
if (u == "-")
f = loadFromStdio();
else
f = loadFromLocalFile(u);
json_t *root = load(f, resolveInc, resolveEnvVars);
fclose(f);
return root;
}
FILE *Config::loadFromStdio() {
logger->info("Reading configuration from standard input");
auto *cwd = new char[PATH_MAX];
configPath = getcwd(cwd, PATH_MAX);
delete[] cwd;
return stdin;
}
FILE *Config::loadFromLocalFile(const std::string &u) {
logger->info("Reading configuration from local file: {}", u);
configPath = u;
FILE *f = fopen(u.c_str(), "r");
if (!f)
throw RuntimeError("Failed to open configuration from: {}", u);
return f;
}
json_t *Config::decode(FILE *f) {
json_error_t err;
// Update list of include directories
auto incDirs = getIncludeDirectories(f);
includeDirectories.insert(includeDirectories.end(), incDirs.begin(),
incDirs.end());
json_t *root = json_loadf(f, 0, &err);
if (root == nullptr) {
#ifdef WITH_CONFIG
// We try again to parse the config in the legacy format
root = libconfigDecode(f);
#else
throw JanssonParseError(err);
#endif // WITH_CONFIG
}
return root;
}
std::list<std::string> Config::getIncludeDirectories(FILE *f) const {
int ret, fd;
char buf[PATH_MAX];
char *dir;
std::list<std::string> dirs;
// Adding directory of base configuration file
fd = fileno(f);
if (fd < 0)
throw SystemError("Failed to get file descriptor");
auto path = fmt::format("/proc/self/fd/{}", fd);
ret = readlink(path.c_str(), buf, sizeof(buf));
if (ret > 0) {
buf[ret] = 0;
if (isLocalFile(buf)) {
dir = dirname(buf);
dirs.push_back(dir);
}
}
// Adding current working directory
dir = getcwd(buf, sizeof(buf));
if (dir != nullptr)
dirs.push_back(dir);
return dirs;
}
std::list<std::string> Config::resolveIncludes(const std::string &n) {
glob_t gb;
int ret, flags = 0;
memset(&gb, 0, sizeof(gb));
auto name = n;
resolveEnvVars(name);
if (name.size() >= 1 && name[0] == '/') { // absolute path
ret = glob(name.c_str(), flags, nullptr, &gb);
if (ret && ret != GLOB_NOMATCH)
gb.gl_pathc = 0;
} else { // relative path
for (auto &dir : includeDirectories) {
auto pattern = fmt::format("{}/{}", dir, name.c_str());
ret = glob(pattern.c_str(), flags, nullptr, &gb);
if (ret && ret != GLOB_NOMATCH) {
gb.gl_pathc = 0;
goto out;
}
flags |= GLOB_APPEND;
}
}
out:
std::list<std::string> files;
for (unsigned i = 0; i < gb.gl_pathc; i++)
files.push_back(gb.gl_pathv[i]);
globfree(&gb);
return files;
}
void Config::resolveEnvVars(std::string &text) {
static const std::regex env_re{R"--(\$\{([^}]+)\})--"};
std::smatch match;
while (std::regex_search(text, match, env_re)) {
auto const from = match[0];
auto const var_name = match[1].str();
char *var_value = std::getenv(var_name.c_str());
if (!var_value)
throw RuntimeError("Unresolved environment variable: {}", var_name);
text.replace(from.first - text.begin(), from.second - from.first,
var_value);
logger->debug("Replace env var {} in \"{}\" with value \"{}\"", var_name,
text, var_value);
}
}
#ifdef WITH_CONFIG
#if (LIBCONFIG_VER_MAJOR > 1) || \
((LIBCONFIG_VER_MAJOR == 1) && (LIBCONFIG_VER_MINOR >= 7))
const char **Config::includeFuncStub(config_t *cfg, const char *include_dir,
const char *path, const char **error) {
void *ctx = config_get_hook(cfg);
return reinterpret_cast<Config *>(ctx)->includeFunc(cfg, include_dir, path,
error);
}
const char **Config::includeFunc(config_t *cfg, const char *include_dir,
const char *path, const char **error) {
auto paths = resolveIncludes(path);
unsigned i = 0;
auto files = (const char **)malloc(sizeof(char **) * (paths.size() + 1));
for (auto &path : paths)
files[i++] = strdup(path.c_str());
files[i] = NULL;
return files;
}
#endif
json_t *Config::libconfigDecode(FILE *f) {
int ret;
config_t cfg;
config_setting_t *cfg_root;
config_init(&cfg);
config_set_auto_convert(&cfg, 1);
// Setup libconfig include path
#if (LIBCONFIG_VER_MAJOR > 1) || \
((LIBCONFIG_VER_MAJOR == 1) && (LIBCONFIG_VER_MINOR >= 7))
config_set_hook(&cfg, this);
config_set_include_func(&cfg, includeFuncStub);
#else
if (includeDirectories.size() > 0) {
logger->info("Setting include dir to: {}", includeDirectories.front());
config_set_include_dir(&cfg, includeDirectories.front().c_str());
if (includeDirectories.size() > 1) {
logger->warn(
"Ignoring all but the first include directories for libconfig");
logger->warn(
" libconfig does not support more than a single include dir!");
}
}
#endif
// Rewind before re-reading
rewind(f);
ret = config_read(&cfg, f);
if (ret != CONFIG_TRUE)
throw LibconfigParseError(&cfg);
cfg_root = config_root_setting(&cfg);
json_t *root = config_to_json(cfg_root);
if (!root)
throw RuntimeError("Failed to convert JSON to configuration file");
config_destroy(&cfg);
return root;
}
#endif // WITH_CONFIG
json_t *Config::walkStrings(json_t *root, str_walk_fcn_t cb) {
const char *key;
size_t index;
json_t *val, *new_val, *new_root;
switch (json_typeof(root)) {
case JSON_STRING:
return cb(root);
case JSON_OBJECT:
new_root = json_object();
json_object_foreach (root, key, val) {
new_val = walkStrings(val, cb);
json_object_set_new(new_root, key, new_val);
}
return new_root;
case JSON_ARRAY:
new_root = json_array();
json_array_foreach (root, index, val) {
new_val = walkStrings(val, cb);
json_array_append_new(new_root, new_val);
}
return new_root;
default:
return json_incref(root);
};
}
json_t *Config::expandEnvVars(json_t *in) {
return walkStrings(in, [this](json_t *str) -> json_t * {
std::string text = json_string_value(str);
resolveEnvVars(text);
return json_string(text.c_str());
});
}
json_t *Config::expandIncludes(json_t *in) {
return walkStrings(in, [this](json_t *str) -> json_t * {
int ret;
std::string text = json_string_value(str);
static const std::string kw = "@include ";
auto res = std::mismatch(kw.begin(), kw.end(), text.begin());
if (res.first != kw.end())
return json_incref(str);
else {
std::string pattern = text.substr(kw.size());
resolveEnvVars(pattern);
json_t *incl = nullptr;
for (auto &path : resolveIncludes(pattern)) {
json_t *other = load(path);
if (!other)
throw ConfigError(str, "include",
"Failed to include config file from {}", path);
if (!incl)
incl = other;
else if (json_is_object(incl) && json_is_object(other)) {
ret = json_object_update_recursive(incl, other);
if (ret)
throw ConfigError(
str, "include",
"Can not mix object and array-typed include files");
} else if (json_is_array(incl) && json_is_array(other)) {
ret = json_array_extend(incl, other);
if (ret)
throw ConfigError(
str, "include",
"Can not mix object and array-typed include files");
}
logger->debug("Included config from: {}", path);
}
return incl;
}
});
}