Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Concatenate nested namespaces (sonar).
[simgrid.git] / src / xbt / config.cpp
1 /* Copyright (c) 2004-2022. The SimGrid Team. All rights reserved.     */
2
3 /* This program is free software; you can redistribute it and/or modify it
4  * under the terms of the license (GNU LGPL) which comes with this package. */
5
6 #include <cstdio>
7
8 #include <algorithm>
9 #include <cerrno>
10 #include <cstring>
11 #include <climits>
12
13 #include <functional>
14 #include <map>
15 #include <memory>
16 #include <stdexcept>
17 #include <string>
18 #include <string>
19 #include <vector>
20
21 #include "simgrid/Exception.hpp"
22 #include "simgrid/sg_config.hpp"
23 #include "xbt/dynar.h"
24 #include "xbt/log.h"
25 #include "xbt/misc.h"
26 #include "xbt/sysdep.h"
27 #include <xbt/config.h>
28 #include <xbt/config.hpp>
29
30 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_cfg, xbt, "configuration support");
31
32 XBT_EXPORT_NO_IMPORT xbt_cfg_t simgrid_config = nullptr;
33
34 namespace simgrid::config {
35
36 namespace {
37
38 bool parse_bool(const char* value)
39 {
40   for (const char* true_value : {"yes", "on", "true", "1"})
41     if (std::strcmp(true_value, value) == 0)
42       return true;
43   for (const char* false_value : {"no", "off", "false", "0"})
44     if (std::strcmp(false_value, value) == 0)
45       return false;
46   throw std::range_error("not a boolean");
47 }
48
49 double parse_double(const char* value)
50 {
51   char* end;
52   errno = 0;
53   double res = std::strtod(value, &end);
54   if (errno == ERANGE)
55     throw std::range_error("out of range");
56   xbt_assert(errno == 0, "Unexpected errno: %d", errno);
57   if (end == value || *end != '\0')
58     throw std::range_error("invalid double");
59   return res;
60 }
61
62 long int parse_long(const char* value)
63 {
64   char* end;
65   errno = 0;
66   long int res = std::strtol(value, &end, 0);
67   if (errno == ERANGE)
68     throw std::range_error(res == LONG_MIN ? "underflow" : "overflow");
69   xbt_assert(errno == 0, "Unexpected errno: %d", errno);
70   if (end == value || *end != '\0')
71     throw std::range_error("invalid integer");
72   return res;
73 }
74
75 // ***** ConfigType *****
76
77 /// A trait which define possible options types:
78 template <class T> class ConfigType;
79
80 template <> class ConfigType<int> {
81 public:
82   static constexpr const char* type_name = "int";
83   static inline int parse(const char* value)
84   {
85     long val = parse_long(value);
86     if (val < INT_MIN)
87       throw std::range_error("underflow");
88     if (val > INT_MAX)
89       throw std::range_error("overflow");
90     return static_cast<int>(val);
91   }
92 };
93 template <> class ConfigType<double> {
94 public:
95   static constexpr const char* type_name = "double";
96   static inline double parse(const char* value)
97   {
98     return parse_double(value);
99   }
100 };
101 template <> class ConfigType<std::string> {
102 public:
103   static constexpr const char* type_name = "string";
104   static inline std::string parse(const char* value)
105   {
106     return std::string(value);
107   }
108 };
109 template <> class ConfigType<bool> {
110 public:
111   static constexpr const char* type_name = "boolean";
112   static inline bool parse(const char* value)
113   {
114     return parse_bool(value);
115   }
116 };
117
118 // **** Forward declarations ****
119
120 class ConfigurationElement ;
121 template<class T> class TypedConfigurationElement;
122
123 // **** ConfigurationElement ****
124
125 class ConfigurationElement {
126 private:
127   std::string key;
128   std::string desc;
129   bool isdefault = true;
130
131 public:
132   ConfigurationElement(const std::string& key, const std::string& desc) : key(key), desc(desc) {}
133
134   virtual ~ConfigurationElement() = default;
135
136   virtual std::string get_string_value()           = 0;
137   virtual void set_string_value(const char* value) = 0;
138   virtual const char* get_type_name()              = 0;
139
140   template <class T> T const& get_value() const
141   {
142     return static_cast<const TypedConfigurationElement<T>&>(*this).get_value();
143   }
144   template <class T> void set_value(T value)
145   {
146     static_cast<TypedConfigurationElement<T>&>(*this).set_value(std::move(value));
147   }
148   template <class T> void set_default_value(T value)
149   {
150     static_cast<TypedConfigurationElement<T>&>(*this).set_default_value(std::move(value));
151   }
152   void unset_default() { isdefault = false; }
153   bool is_default() const { return isdefault; }
154
155   std::string const& get_description() const { return desc; }
156   std::string const& get_key() const { return key; }
157 };
158
159 // **** TypedConfigurationElement<T> ****
160
161 // TODO, could we use boost::any with some Type* reference?
162 template<class T>
163 class TypedConfigurationElement : public ConfigurationElement {
164 private:
165   T content;
166   std::function<void(T&)> callback;
167
168 public:
169   TypedConfigurationElement(const std::string& key, const std::string& desc, T value = T())
170       : ConfigurationElement(key, desc), content(std::move(value))
171   {}
172   TypedConfigurationElement(const std::string& key, const std::string& desc, T value, std::function<void(T&)> callback)
173       : ConfigurationElement(key, desc), content(std::move(value)), callback(std::move(callback))
174   {}
175
176   std::string get_string_value() override;
177   const char* get_type_name() override;
178   void set_string_value(const char* value) override;
179
180   void update()
181   {
182     if (this->callback)
183       this->callback(this->content);
184   }
185
186   T const& get_value() const { return content; }
187
188   void set_value(T value)
189   {
190     this->content = std::move(value);
191     this->update();
192     this->unset_default();
193   }
194
195   void set_default_value(T value)
196   {
197     if (this->is_default()) {
198       this->content = std::move(value);
199       this->update();
200     } else {
201       XBT_DEBUG("Do not override configuration variable '%s' with value '%s' because it was already set.",
202                 get_key().c_str(), get_string_value().c_str());
203     }
204   }
205 };
206
207 template <class T> std::string TypedConfigurationElement<T>::get_string_value() // override
208 {
209   return to_string(content);
210 }
211
212 template <> std::string TypedConfigurationElement<double>::get_string_value() // override
213 {
214   // don't want std::to_string which uses %f, and formats very small values as 0.000000
215   return xbt::string_printf("%g", content);
216 }
217
218 template <class T> void TypedConfigurationElement<T>::set_string_value(const char* value) // override
219 {
220   this->content = ConfigType<T>::parse(value);
221   this->unset_default();
222   this->update();
223 }
224
225 template <class T> const char* TypedConfigurationElement<T>::get_type_name() // override
226 {
227   return ConfigType<T>::type_name;
228 }
229
230 } // end of anonymous namespace
231
232 // **** Config ****
233
234 class Config {
235 private:
236   // name -> ConfigElement:
237   std::map<std::string, std::unique_ptr<ConfigurationElement>, std::less<>> options;
238   // alias -> ConfigElement from options:
239   std::map<std::string, ConfigurationElement*, std::less<>> aliases;
240   bool warn_for_aliases = true;
241
242 public:
243   Config();
244
245   // No copy:
246   Config(Config const&) = delete;
247   Config& operator=(Config const&) = delete;
248
249   ConfigurationElement& operator[](const std::string& name);
250   void alias(const std::string& realname, const std::string& aliasname);
251
252   template <class T, class... A> TypedConfigurationElement<T>* register_option(const std::string& name, A&&... a)
253   {
254     xbt_assert(options.find(name) == options.end(), "Refusing to register the config element '%s' twice.",
255                name.c_str());
256     auto* variable = new TypedConfigurationElement<T>(name, std::forward<A>(a)...);
257     XBT_DEBUG("Register cfg elm %s (%s) of type %s @%p in set %p)", name.c_str(), variable->get_description().c_str(),
258               variable->get_type_name(), variable, this);
259     options[name].reset(variable);
260     variable->update();
261     return variable;
262   }
263
264   void show_aliases() const;
265   void help() const;
266
267 protected:
268   ConfigurationElement* get_dict_element(const std::string& name);
269 };
270
271 Config::Config()
272 {
273   atexit(&sg_config_finalize);
274 }
275
276 inline ConfigurationElement* Config::get_dict_element(const std::string& name)
277 {
278   if (auto opt = options.find(name); opt != options.end())
279     return opt->second.get();
280
281   if (auto als = aliases.find(name); als != aliases.end()) {
282     ConfigurationElement* res = als->second;
283     if (warn_for_aliases)
284       XBT_INFO("Option %s has been renamed to %s. Consider switching.", name.c_str(), res->get_key().c_str());
285     return res;
286   }
287
288   std::string msg   = "Bad config key: " + name + "\n";
289   std::string kebab = name;
290   std::replace(begin(kebab), end(kebab), '_', '-'); // convert from snake_case to kebab-case
291   if (options.count(kebab) > 0)
292     msg += "Did you mean '" + kebab + "'?\n";
293   msg += "Existing config keys:\n";
294   for (auto const& [opt_name, opt] : options)
295     msg += "  " + opt_name + ": (" + opt->get_type_name() + ")" + opt->get_string_value() + "\n";
296   throw std::out_of_range(msg);
297 }
298
299 inline ConfigurationElement& Config::operator[](const std::string& name)
300 {
301   return *(get_dict_element(name));
302 }
303
304 void Config::alias(const std::string& realname, const std::string& aliasname)
305 {
306   xbt_assert(aliases.find(aliasname) == aliases.end(), "Alias '%s' already.", aliasname.c_str());
307   ConfigurationElement* element = this->get_dict_element(realname);
308   xbt_assert(element, "Cannot define an alias to the non-existing option '%s'.", realname.c_str());
309   this->aliases.try_emplace(aliasname, element);
310 }
311
312 /** @brief Displays the declared aliases and their replacement */
313 void Config::show_aliases() const
314 {
315   for (auto const& [name, alias] : aliases)
316     XBT_HELP("   %-40s %s", name.c_str(), alias->get_key().c_str());
317 }
318
319 /** @brief Displays the declared options and their description */
320 void Config::help() const
321 {
322   for (auto const& [name, opt] : options) {
323     XBT_HELP("   %s: %s", name.c_str(), opt->get_description().c_str());
324     XBT_HELP("       Type: %s; Current value: %s", opt->get_type_name(), opt->get_string_value().c_str());
325   }
326 }
327
328 // ***** set_default *****
329
330 template <class T> XBT_PUBLIC void set_default(const char* name, T value)
331 {
332   (*simgrid_config)[name].set_default_value<T>(std::move(value));
333 }
334
335 template XBT_PUBLIC void set_default<int>(const char* name, int value);
336 template XBT_PUBLIC void set_default<double>(const char* name, double value);
337 template XBT_PUBLIC void set_default<bool>(const char* name, bool value);
338 template XBT_PUBLIC void set_default<std::string>(const char* name, std::string value);
339
340 bool is_default(const char* name)
341 {
342   return (*simgrid_config)[name].is_default();
343 }
344
345 // ***** set_value *****
346
347 template <class T> XBT_PUBLIC void set_value(const char* name, T value)
348 {
349   (*simgrid_config)[name].set_value<T>(std::move(value));
350 }
351
352 template XBT_PUBLIC void set_value<int>(const char* name, int value);
353 template XBT_PUBLIC void set_value<double>(const char* name, double value);
354 template XBT_PUBLIC void set_value<bool>(const char* name, bool value);
355 template XBT_PUBLIC void set_value<std::string>(const char* name, std::string value);
356
357 void set_as_string(const char* name, const std::string& value)
358 {
359   (*simgrid_config)[name].set_string_value(value.c_str());
360 }
361
362 void set_parse(const std::string& opt)
363 {
364   std::string options(opt);
365   XBT_DEBUG("List to parse and set:'%s'", options.c_str());
366   while (not options.empty()) {
367     XBT_DEBUG("Still to parse and set: '%s'", options.c_str());
368
369     // skip separators
370     size_t pos = options.find_first_not_of(" \t\n,");
371     options.erase(0, pos);
372     // find option
373     pos              = options.find_first_of(" \t\n,");
374     std::string name = options.substr(0, pos);
375     options.erase(0, pos);
376     XBT_DEBUG("parse now:'%s'; parse later:'%s'", name.c_str(), options.c_str());
377
378     if (name.empty())
379       continue;
380
381     pos = name.find(':');
382     xbt_assert(pos != std::string::npos, "Option '%s' badly formatted. Should be of the form 'name:value'",
383                name.c_str());
384
385     std::string val = name.substr(pos + 1);
386     name.erase(pos);
387
388     if (name.rfind("path", 0) != 0)
389       XBT_INFO("Configuration change: Set '%s' to '%s'", name.c_str(), val.c_str());
390
391     set_as_string(name.c_str(), val);
392   }
393 }
394
395 // ***** get_value *****
396
397 template <class T> XBT_PUBLIC T const& get_value(const std::string& name)
398 {
399   return (*simgrid_config)[name].get_value<T>();
400 }
401
402 template XBT_PUBLIC int const& get_value<int>(const std::string& name);
403 template XBT_PUBLIC double const& get_value<double>(const std::string& name);
404 template XBT_PUBLIC bool const& get_value<bool>(const std::string& name);
405 template XBT_PUBLIC std::string const& get_value<std::string>(const std::string& name);
406
407 // ***** alias *****
408
409 void alias(const char* realname, std::initializer_list<const char*> aliases)
410 {
411   for (auto const& aliasname : aliases)
412     simgrid_config->alias(realname, aliasname);
413 }
414
415 // ***** declare_flag *****
416
417 template <class T>
418 XBT_PUBLIC void declare_flag(const std::string& name, const std::string& description, T value,
419                              std::function<void(const T&)> callback)
420 {
421   if (simgrid_config == nullptr)
422     simgrid_config = new simgrid::config::Config();
423   simgrid_config->register_option<T>(name, description, std::move(value), std::move(callback));
424 }
425
426 template XBT_PUBLIC void declare_flag(const std::string& name, const std::string& description, int value,
427                                       std::function<void(int const&)> callback);
428 template XBT_PUBLIC void declare_flag(const std::string& name, const std::string& description, double value,
429                                       std::function<void(double const&)> callback);
430 template XBT_PUBLIC void declare_flag(const std::string& name, const std::string& description, bool value,
431                                       std::function<void(bool const&)> callback);
432 template XBT_PUBLIC void declare_flag(const std::string& name, const std::string& description, std::string value,
433                                       std::function<void(std::string const&)> callback);
434
435 void finalize()
436 {
437   delete simgrid_config;
438   simgrid_config = nullptr;
439 }
440
441 void show_aliases()
442 {
443   simgrid_config->show_aliases();
444 }
445
446 void help()
447 {
448   simgrid_config->help();
449 }
450 } // namespace simgrid::config
451
452 /*----[ Setting ]---------------------------------------------------------*/
453
454 /** @brief Set an integer value to \a name within \a cfg
455  *
456  * @param key the name of the variable
457  * @param value the value of the variable
458  */
459 void sg_cfg_set_int(const char* key, int value)
460 {
461   (*simgrid_config)[key].set_value<int>(value);
462 }
463
464 /** @brief Set or add a double value to \a name within \a cfg
465  *
466  * @param key the name of the variable
467  * @param value the double to set
468  */
469 void sg_cfg_set_double(const char* key, double value)
470 {
471   (*simgrid_config)[key].set_value<double>(value);
472 }
473
474 /** @brief Set or add a string value to \a name within \a cfg
475  *
476  * @param key the name of the variable
477  * @param value the value to be added
478  *
479  */
480 void sg_cfg_set_string(const char* key, const char* value)
481 {
482   (*simgrid_config)[key].set_value<std::string>(value);
483 }
484
485 /** @brief Set or add a boolean value to \a name within \a cfg
486  *
487  * @param key the name of the variable
488  * @param value the value of the variable
489  */
490 void sg_cfg_set_boolean(const char* key, const char* value)
491 {
492   (*simgrid_config)[key].set_value<bool>(simgrid::config::parse_bool(value));
493 }
494
495 /*----[ Getting ]---------------------------------------------------------*/
496 /** @brief Retrieve an integer value of a variable (get a warning if not uniq)
497  *
498  * @param key the name of the variable
499  *
500  * Returns the first value from the config set under the given name.
501  */
502 int sg_cfg_get_int(const char* key)
503 {
504   return (*simgrid_config)[key].get_value<int>();
505 }
506
507 /** @brief Retrieve a double value of a variable (get a warning if not uniq)
508  *
509  * @param key the name of the variable
510  *
511  * Returns the first value from the config set under the given name.
512  */
513 double sg_cfg_get_double(const char* key)
514 {
515   return (*simgrid_config)[key].get_value<double>();
516 }
517
518 /** @brief Retrieve a boolean value of a variable (get a warning if not uniq)
519  *
520  * @param key the name of the variable
521  *
522  * Returns the first value from the config set under the given name.
523  * If there is more than one value, it will issue a warning.
524  */
525 int sg_cfg_get_boolean(const char* key)
526 {
527   return (*simgrid_config)[key].get_value<bool>() ? 1 : 0;
528 }