Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Bad cast.
[simgrid.git] / src / xbt / config.cpp
1 /* Copyright (c) 2004-2019. 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 <stdexcept>
16 #include <string>
17 #include <string>
18 #include <type_traits>
19 #include <typeinfo>
20 #include <vector>
21
22 #include "simgrid/Exception.hpp"
23 #include "simgrid/sg_config.hpp"
24 #include "xbt/dynar.h"
25 #include "xbt/log.h"
26 #include "xbt/misc.h"
27 #include "xbt/sysdep.h"
28 #include <xbt/config.h>
29 #include <xbt/config.hpp>
30
31 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_cfg, xbt, "configuration support");
32
33 XBT_EXPORT_NO_IMPORT xbt_cfg_t simgrid_config = nullptr;
34
35 namespace simgrid {
36 namespace config {
37
38 namespace {
39
40 const char* true_values[] = {
41   "yes", "on", "true", "1"
42 };
43 const char* false_values[] = {
44   "no", "off", "false", "0"
45 };
46
47 static bool parse_bool(const char* value)
48 {
49   for (const char* const& true_value : true_values)
50     if (std::strcmp(true_value, value) == 0)
51       return true;
52   for (const char* const& false_value : false_values)
53     if (std::strcmp(false_value, value) == 0)
54       return false;
55   throw std::range_error("not a boolean");
56 }
57
58 static double parse_double(const char* value)
59 {
60   char* end;
61   errno = 0;
62   double res = std::strtod(value, &end);
63   if (errno == ERANGE)
64     throw std::range_error("out of range");
65   else if (errno)
66     xbt_die("Unexpected errno");
67   if (end == value || *end != '\0')
68     throw std::range_error("invalid double");
69   else
70     return res;
71 }
72
73 static long int parse_long(const char* value)
74 {
75   char* end;
76   errno = 0;
77   long int res = std::strtol(value, &end, 0);
78   if (errno) {
79     if (res == LONG_MIN && errno == ERANGE)
80       throw std::range_error("underflow");
81     else if (res == LONG_MAX && errno == ERANGE)
82       throw std::range_error("overflow");
83     xbt_die("Unexpected errno");
84   }
85   if (end == value || *end != '\0')
86     throw std::range_error("invalid integer");
87   else
88     return res;
89 }
90
91 // ***** ConfigType *****
92
93 /// A trait which define possible options types:
94 template <class T> class ConfigType;
95
96 template <> class ConfigType<int> {
97 public:
98   static constexpr const char* type_name = "int";
99   static inline double parse(const char* value)
100   {
101     return parse_long(value);
102   }
103 };
104 template <> class ConfigType<double> {
105 public:
106   static constexpr const char* type_name = "double";
107   static inline double parse(const char* value)
108   {
109     return parse_double(value);
110   }
111 };
112 template <> class ConfigType<std::string> {
113 public:
114   static constexpr const char* type_name = "string";
115   static inline std::string parse(const char* value)
116   {
117     return std::string(value);
118   }
119 };
120 template <> class ConfigType<bool> {
121 public:
122   static constexpr const char* type_name = "boolean";
123   static inline bool parse(const char* value)
124   {
125     return parse_bool(value);
126   }
127 };
128
129 // **** Forward declarations ****
130
131 class ConfigurationElement ;
132 template<class T> class TypedConfigurationElement;
133
134 // **** ConfigurationElement ****
135
136 class ConfigurationElement {
137 private:
138   std::string key;
139   std::string desc;
140   bool isdefault = true;
141
142 public:
143   /* Callback */
144   xbt_cfg_cb_t old_callback = nullptr;
145
146   ConfigurationElement(std::string key, std::string desc) : key(std::move(key)), desc(std::move(desc)) {}
147   ConfigurationElement(std::string key, std::string desc, xbt_cfg_cb_t cb)
148       : key(std::move(key)), desc(std::move(desc)), old_callback(cb)
149   {
150   }
151
152   virtual ~ConfigurationElement() = default;
153
154   virtual std::string get_string_value()           = 0;
155   virtual void set_string_value(const char* value) = 0;
156   virtual const char* get_type_name()              = 0;
157
158   template <class T> T const& get_value() const
159   {
160     return static_cast<const TypedConfigurationElement<T>&>(*this).get_value();
161   }
162   template <class T> void set_value(T value)
163   {
164     static_cast<TypedConfigurationElement<T>&>(*this).set_value(std::move(value));
165   }
166   template <class T> void set_default_value(T value)
167   {
168     static_cast<TypedConfigurationElement<T>&>(*this).set_default_value(std::move(value));
169   }
170   void unset_default() { isdefault = false; }
171   bool is_default() const { return isdefault; }
172
173   std::string const& get_description() const { return desc; }
174   std::string const& get_key() const { return key; }
175 };
176
177 // **** TypedConfigurationElement<T> ****
178
179 // TODO, could we use boost::any with some Type* reference?
180 template<class T>
181 class TypedConfigurationElement : public ConfigurationElement {
182 private:
183   T content;
184   std::function<void(T&)> callback;
185
186 public:
187   TypedConfigurationElement(std::string key, std::string desc, T value = T())
188       : ConfigurationElement(std::move(key), std::move(desc)), content(std::move(value))
189   {}
190   TypedConfigurationElement(std::string key, std::string desc, T value, xbt_cfg_cb_t cb)
191       : ConfigurationElement(std::move(key), std::move(desc), cb), content(std::move(value))
192   {}
193   TypedConfigurationElement(std::string key, std::string desc, T value, std::function<void(T&)> callback)
194       : ConfigurationElement(std::move(key), std::move(desc)), content(std::move(value)), callback(std::move(callback))
195   {}
196   ~TypedConfigurationElement() = default;
197
198   std::string get_string_value() override;
199   const char* get_type_name() override;
200   void set_string_value(const char* value) override;
201
202   void update()
203   {
204     if (old_callback)
205       this->old_callback(get_key().c_str());
206     if (this->callback)
207       this->callback(this->content);
208   }
209
210   T const& get_value() const { return content; }
211
212   void set_value(T value)
213   {
214     this->content = std::move(value);
215     this->update();
216     this->unset_default();
217   }
218
219   void set_default_value(T value)
220   {
221     if (this->is_default()) {
222       this->content = std::move(value);
223       this->update();
224     } else {
225       XBT_DEBUG("Do not override configuration variable '%s' with value '%s' because it was already set.",
226                 get_key().c_str(), to_string(value).c_str());
227     }
228   }
229 };
230
231 template <class T> std::string TypedConfigurationElement<T>::get_string_value() // override
232 {
233   return to_string(content);
234 }
235
236 template <class T> void TypedConfigurationElement<T>::set_string_value(const char* value) // override
237 {
238   this->content = ConfigType<T>::parse(value);
239   this->unset_default();
240   this->update();
241 }
242
243 template <class T> const char* TypedConfigurationElement<T>::get_type_name() // override
244 {
245   return ConfigType<T>::type_name;
246 }
247
248 } // end of anonymous namespace
249
250 // **** Config ****
251
252 class Config {
253 private:
254   // name -> ConfigElement:
255   std::map<std::string, simgrid::config::ConfigurationElement*> options;
256   // alias -> ConfigElement from options:
257   std::map<std::string, simgrid::config::ConfigurationElement*> aliases;
258   bool warn_for_aliases = true;
259
260 public:
261   Config();
262   ~Config();
263
264   // No copy:
265   Config(Config const&) = delete;
266   Config& operator=(Config const&) = delete;
267
268   ConfigurationElement& operator[](const std::string& name);
269   void alias(const std::string& realname, const std::string& aliasname);
270
271   template <class T, class... A>
272   simgrid::config::TypedConfigurationElement<T>* register_option(const std::string& name, A&&... a)
273   {
274     xbt_assert(options.find(name) == options.end(), "Refusing to register the config element '%s' twice.",
275                name.c_str());
276     TypedConfigurationElement<T>* variable = new TypedConfigurationElement<T>(name, std::forward<A>(a)...);
277     XBT_DEBUG("Register cfg elm %s (%s) of type %s @%p in set %p)", name.c_str(), variable->get_description().c_str(),
278               variable->get_type_name(), variable, this);
279     options.insert({name, variable});
280     variable->update();
281     return variable;
282   }
283
284   // Debug:
285   void dump(const char *name, const char *indent);
286   void show_aliases();
287   void help();
288
289 protected:
290   ConfigurationElement* get_dict_element(const std::string& name);
291 };
292
293 Config::Config()
294 {
295   atexit(&sg_config_finalize);
296 }
297 Config::~Config()
298 {
299   XBT_DEBUG("Frees cfg set %p", this);
300   for (auto const& elm : options)
301     delete elm.second;
302 }
303
304 inline ConfigurationElement* Config::get_dict_element(const std::string& name)
305 {
306   auto opt = options.find(name);
307   if (opt != options.end()) {
308     return opt->second;
309   } else {
310     auto als = aliases.find(name);
311     if (als != aliases.end()) {
312       ConfigurationElement* res = als->second;
313       if (warn_for_aliases)
314         XBT_INFO("Option %s has been renamed to %s. Consider switching.", name.c_str(), res->get_key().c_str());
315       return res;
316     } else {
317       THROWF(not_found_error, 0, "Bad config key: %s", name.c_str());
318     }
319   }
320 }
321
322 inline ConfigurationElement& Config::operator[](const std::string& name)
323 {
324   return *(get_dict_element(name));
325 }
326
327 void Config::alias(const std::string& realname, const std::string& aliasname)
328 {
329   xbt_assert(aliases.find(aliasname) == aliases.end(), "Alias '%s' already.", aliasname.c_str());
330   ConfigurationElement* element = this->get_dict_element(realname);
331   xbt_assert(element, "Cannot define an alias to the non-existing option '%s'.", realname.c_str());
332   this->aliases.insert({aliasname, element});
333 }
334
335 /** @brief Dump a config set for debuging purpose
336  *
337  * @param name The name to give to this config set
338  * @param indent what to write at the beginning of each line (right number of spaces)
339  */
340 void Config::dump(const char *name, const char *indent)
341 {
342   if (name)
343     printf("%s>> Dumping of the config set '%s':\n", indent, name);
344
345   for (auto const& elm : options)
346     printf("%s  %s: ()%s) %s", indent, elm.first.c_str(), elm.second->get_type_name(),
347            elm.second->get_string_value().c_str());
348
349   if (name)
350     printf("%s<< End of the config set '%s'\n", indent, name);
351   fflush(stdout);
352 }
353
354 /** @brief Displays the declared aliases and their replacement */
355 void Config::show_aliases()
356 {
357   for (auto const& elm : aliases)
358     printf("   %-40s %s\n", elm.first.c_str(), elm.second->get_key().c_str());
359 }
360
361 /** @brief Displays the declared options and their description */
362 void Config::help()
363 {
364   for (auto const& elm : options) {
365     simgrid::config::ConfigurationElement* variable = this->options.at(elm.first);
366     printf("   %s: %s\n", elm.first.c_str(), variable->get_description().c_str());
367     printf("       Type: %s; ", variable->get_type_name());
368     printf("Current value: %s\n", variable->get_string_value().c_str());
369   }
370 }
371
372 // ***** set_default *****
373
374 template <class T> XBT_PUBLIC void set_default(const char* name, T value)
375 {
376   (*simgrid_config)[name].set_default_value<T>(std::move(value));
377 }
378
379 template XBT_PUBLIC void set_default<int>(const char* name, int value);
380 template XBT_PUBLIC void set_default<double>(const char* name, double value);
381 template XBT_PUBLIC void set_default<bool>(const char* name, bool value);
382 template XBT_PUBLIC void set_default<std::string>(const char* name, std::string value);
383
384 bool is_default(const char* name)
385 {
386   return (*simgrid_config)[name].is_default();
387 }
388
389 // ***** set_value *****
390
391 template <class T> XBT_PUBLIC void set_value(const char* name, T value)
392 {
393   (*simgrid_config)[name].set_value<T>(std::move(value));
394 }
395
396 template XBT_PUBLIC void set_value<int>(const char* name, int value);
397 template XBT_PUBLIC void set_value<double>(const char* name, double value);
398 template XBT_PUBLIC void set_value<bool>(const char* name, bool value);
399 template XBT_PUBLIC void set_value<std::string>(const char* name, std::string value);
400
401 void set_as_string(const char* name, const std::string& value)
402 {
403   (*simgrid_config)[name].set_string_value(value.c_str());
404 }
405
406 void set_parse(std::string options)
407 {
408   XBT_DEBUG("List to parse and set:'%s'", options.c_str());
409   while (not options.empty()) {
410     XBT_DEBUG("Still to parse and set: '%s'", options.c_str());
411
412     // skip separators
413     size_t pos = options.find_first_not_of(" \t\n,");
414     options.erase(0, pos);
415     // find option
416     pos              = options.find_first_of(" \t\n,");
417     std::string name = options.substr(0, pos);
418     options.erase(0, pos);
419     XBT_DEBUG("parse now:'%s'; parse later:'%s'", name.c_str(), options.c_str());
420
421     if (name.empty())
422       continue;
423
424     pos = name.find(':');
425     xbt_assert(pos != std::string::npos, "Option '%s' badly formatted. Should be of the form 'name:value'",
426                name.c_str());
427
428     std::string val = name.substr(pos + 1);
429     name.erase(pos);
430
431     const std::string path("path");
432     if (name.compare(0, path.length(), path) != 0)
433       XBT_INFO("Configuration change: Set '%s' to '%s'", name.c_str(), val.c_str());
434
435     set_as_string(name.c_str(), val);
436   }
437 }
438
439 // ***** get_value *****
440
441 template <class T> XBT_PUBLIC T const& get_value(const std::string& name)
442 {
443   return (*simgrid_config)[name].get_value<T>();
444 }
445
446 template XBT_PUBLIC int const& get_value<int>(const std::string& name);
447 template XBT_PUBLIC double const& get_value<double>(const std::string& name);
448 template XBT_PUBLIC bool const& get_value<bool>(const std::string& name);
449 template XBT_PUBLIC std::string const& get_value<std::string>(const std::string& name);
450
451 // ***** alias *****
452
453 void alias(const char* realname, std::initializer_list<const char*> aliases)
454 {
455   for (auto const& aliasname : aliases)
456     simgrid_config->alias(realname, aliasname);
457 }
458
459 // ***** declare_flag *****
460
461 template <class T>
462 XBT_PUBLIC void declare_flag(const std::string& name, std::string description, T value,
463                              std::function<void(const T&)> callback)
464 {
465   if (simgrid_config == nullptr)
466     simgrid_config = new simgrid::config::Config();
467   simgrid_config->register_option<T>(name, std::move(description), std::move(value), std::move(callback));
468 }
469
470 template XBT_PUBLIC void declare_flag(const std::string& name, std::string description, int value,
471                                       std::function<void(int const&)> callback);
472 template XBT_PUBLIC void declare_flag(const std::string& name, std::string description, double value,
473                                       std::function<void(double const&)> callback);
474 template XBT_PUBLIC void declare_flag(const std::string& name, std::string description, bool value,
475                                       std::function<void(bool const&)> callback);
476 template XBT_PUBLIC void declare_flag(const std::string& name, std::string description, std::string value,
477                                       std::function<void(std::string const&)> callback);
478
479 void finalize()
480 {
481   delete simgrid_config;
482   simgrid_config = nullptr;
483 }
484
485 void show_aliases()
486 {
487   simgrid_config->show_aliases();
488 }
489
490 void help()
491 {
492   simgrid_config->help();
493 }
494 }
495 }
496
497 // ***** C bindings *****
498
499 xbt_cfg_t xbt_cfg_new()
500 {
501   return new simgrid::config::Config();
502 }
503 void xbt_cfg_free(xbt_cfg_t * cfg) { delete *cfg; }
504
505 void xbt_cfg_dump(const char *name, const char *indent, xbt_cfg_t cfg)
506 {
507   cfg->dump(name, indent);
508 }
509
510 /*----[ Registering stuff ]-----------------------------------------------*/
511
512 void xbt_cfg_register_double(const char *name, double default_value,
513   xbt_cfg_cb_t cb_set, const char *desc)
514 {
515   if (simgrid_config == nullptr)
516     simgrid_config = new simgrid::config::Config();
517   simgrid_config->register_option<double>(name, desc, default_value, cb_set);
518 }
519
520 void xbt_cfg_register_int(const char *name, int default_value,xbt_cfg_cb_t cb_set, const char *desc)
521 {
522   if (simgrid_config == nullptr)
523     simgrid_config = new simgrid::config::Config();
524   simgrid_config->register_option<int>(name, desc, default_value, cb_set);
525 }
526
527 void xbt_cfg_register_string(const char *name, const char *default_value, xbt_cfg_cb_t cb_set, const char *desc)
528 {
529   if (simgrid_config == nullptr)
530     simgrid_config = new simgrid::config::Config();
531   simgrid_config->register_option<std::string>(name, desc, default_value ? default_value : "", cb_set);
532 }
533
534 void xbt_cfg_register_boolean(const char *name, const char*default_value,xbt_cfg_cb_t cb_set, const char *desc)
535 {
536   if (simgrid_config == nullptr)
537     simgrid_config = new simgrid::config::Config();
538   simgrid_config->register_option<bool>(name, desc, simgrid::config::parse_bool(default_value), cb_set);
539 }
540
541 void xbt_cfg_register_alias(const char *realname, const char *aliasname)
542 {
543   if (simgrid_config == nullptr)
544     simgrid_config = new simgrid::config::Config();
545   simgrid_config->alias(realname, aliasname);
546 }
547
548 void xbt_cfg_aliases()
549 {
550   simgrid_config->show_aliases();
551 }
552 void xbt_cfg_help()
553 {
554   simgrid_config->help();
555 }
556
557 /*----[ Setting ]---------------------------------------------------------*/
558
559 /** @brief Add values parsed from a string into a config set
560  *
561  * @param options a string containing the content to add to the config set. This is a '\\t',' ' or '\\n' or ','
562  * separated list of variables. Each individual variable is like "[name]:[value]" where [name] is the name of an
563  * already registered variable, and [value] conforms to the data type under which this variable was registered.
564  *
565  * @todo This is a crude manual parser, it should be a proper lexer.
566  */
567 void xbt_cfg_set_parse(const char *options)
568 {
569   if (options && strlen(options) > 0)
570     simgrid::config::set_parse(std::string(options));
571 }
572
573 /** @brief Set the value of a variable, using the string representation of that value
574  *
575  * @param key name of the variable to modify
576  * @param value string representation of the value to set
577  */
578
579 void xbt_cfg_set_as_string(const char *key, const char *value)
580 {
581   (*simgrid_config)[key].set_string_value(value);
582 }
583
584 /** @brief Set an integer value to \a name within \a cfg if it wasn't changed yet
585  *
586  * This is useful to change the default value of a variable while allowing
587  * users to override it with command line arguments
588  */
589 void xbt_cfg_setdefault_int(const char *key, int value)
590 {
591   (*simgrid_config)[key].set_default_value<int>(value);
592 }
593
594 /** @brief Set an integer value to \a name within \a cfg if it wasn't changed yet
595  *
596  * This is useful to change the default value of a variable while allowing
597  * users to override it with command line arguments
598  */
599 void xbt_cfg_setdefault_double(const char *key, double value)
600 {
601   (*simgrid_config)[key].set_default_value<double>(value);
602 }
603
604 /** @brief Set a string value to \a name within \a cfg if it wasn't changed yet
605  *
606  * This is useful to change the default value of a variable while allowing
607  * users to override it with command line arguments
608  */
609 void xbt_cfg_setdefault_string(const char *key, const char *value)
610 {
611   (*simgrid_config)[key].set_default_value<std::string>(value ? value : "");
612 }
613
614 /** @brief Set an boolean value to \a name within \a cfg if it wasn't changed yet
615  *
616  * This is useful to change the default value of a variable while allowing
617  * users to override it with command line arguments
618  */
619 void xbt_cfg_setdefault_boolean(const char *key, const char *value)
620 {
621   (*simgrid_config)[key].set_default_value<bool>(simgrid::config::parse_bool(value));
622 }
623
624 /** @brief Set an integer value to \a name within \a cfg
625  *
626  * @param key the name of the variable
627  * @param value the value of the variable
628  */
629 void xbt_cfg_set_int(const char *key, int value)
630 {
631   (*simgrid_config)[key].set_value<int>(value);
632 }
633
634 /** @brief Set or add a double value to \a name within \a cfg
635  *
636  * @param key the name of the variable
637  * @param value the double to set
638  */
639 void xbt_cfg_set_double(const char *key, double value)
640 {
641   (*simgrid_config)[key].set_value<double>(value);
642 }
643
644 /** @brief Set or add a string value to \a name within \a cfg
645  *
646  * @param key the name of the variable
647  * @param value the value to be added
648  *
649  */
650 void xbt_cfg_set_string(const char* key, const char* value)
651 {
652   (*simgrid_config)[key].set_value<std::string>(value);
653 }
654
655 /** @brief Set or add a boolean value to \a name within \a cfg
656  *
657  * @param key the name of the variable
658  * @param value the value of the variable
659  */
660 void xbt_cfg_set_boolean(const char *key, const char *value)
661 {
662   (*simgrid_config)[key].set_value<bool>(simgrid::config::parse_bool(value));
663 }
664
665
666 /* Say if the value is the default value */
667 int xbt_cfg_is_default_value(const char *key)
668 {
669   return (*simgrid_config)[key].is_default() ? 1 : 0;
670 }
671
672 /*----[ Getting ]---------------------------------------------------------*/
673 /** @brief Retrieve an integer value of a variable (get a warning if not uniq)
674  *
675  * @param key the name of the variable
676  *
677  * Returns the first value from the config set under the given name.
678  */
679 int xbt_cfg_get_int(const char *key)
680 {
681   return (*simgrid_config)[key].get_value<int>();
682 }
683
684 /** @brief Retrieve a double value of a variable (get a warning if not uniq)
685  *
686  * @param key the name of the variable
687  *
688  * Returns the first value from the config set under the given name.
689  */
690 double xbt_cfg_get_double(const char *key)
691 {
692   return (*simgrid_config)[key].get_value<double>();
693 }
694
695 /** @brief Retrieve a string value of a variable (get a warning if not uniq)
696  *
697  * @param key the name of the variable
698  *
699  * Returns the first value from the config set under the given name.
700  * If there is more than one value, it will issue a warning.
701  * Returns nullptr if there is no value.
702  *
703  * \warning the returned value is the actual content of the config set
704  */
705 std::string xbt_cfg_get_string(const char* key)
706 {
707   return (*simgrid_config)[key].get_value<std::string>();
708 }
709
710 /** @brief Retrieve a boolean value of a variable (get a warning if not uniq)
711  *
712  * @param key the name of the variable
713  *
714  * Returns the first value from the config set under the given name.
715  * If there is more than one value, it will issue a warning.
716  */
717 int xbt_cfg_get_boolean(const char *key)
718 {
719   return (*simgrid_config)[key].get_value<bool>() ? 1 : 0;
720 }