Logo AND Algorithmique Numérique Distribuée

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