Logo AND Algorithmique Numérique Distribuée

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