Logo AND Algorithmique Numérique Distribuée

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