Logo AND Algorithmique Numérique Distribuée

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