1 /* Copyright (c) 2004-2018. The SimGrid Team. All rights reserved. */
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. */
18 #include <type_traits>
22 #include "simgrid/sg_config.hpp"
23 #include "xbt/dynar.h"
26 #include "xbt/sysdep.h"
27 #include <xbt/config.h>
28 #include <xbt/config.hpp>
31 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_cfg, xbt, "configuration support");
33 XBT_EXPORT_NO_IMPORT xbt_cfg_t simgrid_config = nullptr;
40 const char* true_values[] = {
41 "yes", "on", "true", "1"
43 const char* false_values[] = {
44 "no", "off", "false", "0"
47 static bool parse_bool(const char* value)
49 for (const char* const& true_value : true_values)
50 if (std::strcmp(true_value, value) == 0)
52 for (const char* const& false_value : false_values)
53 if (std::strcmp(false_value, value) == 0)
55 throw std::range_error("not a boolean");
58 static double parse_double(const char* value)
62 double res = std::strtod(value, &end);
64 throw std::range_error("out of range");
66 xbt_die("Unexpected errno");
67 if (end == value || *end != '\0')
68 throw std::range_error("invalid double");
73 static long int parse_long(const char* value)
77 long int res = std::strtol(value, &end, 0);
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");
85 if (end == value || *end != '\0')
86 throw std::range_error("invalid integer");
91 // ***** ConfigType *****
93 /// A trait which define possible options types:
94 template <class T> class ConfigType;
96 template <> class ConfigType<int> {
98 static constexpr const char* type_name = "int";
99 static inline double parse(const char* value)
101 return parse_long(value);
104 template <> class ConfigType<double> {
106 static constexpr const char* type_name = "double";
107 static inline double parse(const char* value)
109 return parse_double(value);
112 template <> class ConfigType<std::string> {
114 static constexpr const char* type_name = "string";
115 static inline std::string parse(const char* value)
117 return std::string(value);
120 template <> class ConfigType<bool> {
122 static constexpr const char* type_name = "boolean";
123 static inline bool parse(const char* value)
125 return parse_bool(value);
129 // **** Forward declarations ****
131 class ConfigurationElement ;
132 template<class T> class TypedConfigurationElement;
134 // **** ConfigurationElement ****
136 class ConfigurationElement {
140 bool isdefault = true;
144 xbt_cfg_cb_t old_callback = nullptr;
146 ConfigurationElement(const char* key, const char* desc) : key(key ? key : ""), desc(desc ? desc : "") {}
147 ConfigurationElement(const char* key, const char* desc, xbt_cfg_cb_t cb)
148 : key(key ? key : ""), desc(desc ? desc : ""), old_callback(cb) {}
150 virtual ~ConfigurationElement() = default;
152 virtual std::string get_string_value() = 0;
153 virtual void set_string_value(const char* value) = 0;
154 virtual const char* get_type_name() = 0;
156 template <class T> T const& get_value() const
158 return dynamic_cast<const TypedConfigurationElement<T>&>(*this).get_value();
160 template <class T> void set_value(T value)
162 dynamic_cast<TypedConfigurationElement<T>&>(*this).set_value(std::move(value));
164 template <class T> void set_default_value(T value)
166 dynamic_cast<TypedConfigurationElement<T>&>(*this).set_default_value(std::move(value));
168 void unset_default() { isdefault = false; }
169 bool is_default() const { return isdefault; }
171 std::string const& get_description() const { return desc; }
172 std::string const& get_key() const { return key; }
175 // **** TypedConfigurationElement<T> ****
177 // TODO, could we use boost::any with some Type* reference?
179 class TypedConfigurationElement : public ConfigurationElement {
182 std::function<void(T&)> callback;
185 TypedConfigurationElement(const char* key, const char* desc, T value = T())
186 : ConfigurationElement(key, desc), content(std::move(value))
188 TypedConfigurationElement(const char* key, const char* desc, T value, xbt_cfg_cb_t cb)
189 : ConfigurationElement(key, desc, cb), content(std::move(value))
191 TypedConfigurationElement(const char* key, const char* desc, T value, std::function<void(T&)> callback)
192 : ConfigurationElement(key, desc), content(std::move(value)), callback(std::move(callback))
194 ~TypedConfigurationElement() = default;
196 std::string get_string_value() override;
197 const char* get_type_name() override;
198 void set_string_value(const char* value) override;
203 this->old_callback(get_key().c_str());
205 this->callback(this->content);
208 T const& get_value() const { return content; }
210 void set_value(T value)
212 this->content = std::move(value);
214 this->unset_default();
217 void set_default_value(T value)
219 if (this->is_default()) {
220 this->content = std::move(value);
223 XBT_DEBUG("Do not override configuration variable '%s' with value '%s' because it was already set.",
224 get_key().c_str(), to_string(value).c_str());
229 template <class T> std::string TypedConfigurationElement<T>::get_string_value() // override
231 return to_string(content);
234 template <class T> void TypedConfigurationElement<T>::set_string_value(const char* value) // override
236 this->content = ConfigType<T>::parse(value);
237 this->unset_default();
241 template <class T> const char* TypedConfigurationElement<T>::get_type_name() // override
243 return ConfigType<T>::type_name;
246 } // end of anonymous namespace
252 // name -> ConfigElement:
253 std::map<std::string, simgrid::config::ConfigurationElement*> options;
254 // alias -> ConfigElement from options:
255 std::map<std::string, simgrid::config::ConfigurationElement*> aliases;
256 bool warn_for_aliases = true;
263 Config(Config const&) = delete;
264 Config& operator=(Config const&) = delete;
266 ConfigurationElement& operator[](const char* name);
267 void alias(const char* realname, const char* aliasname);
269 template <class T, class... A>
270 simgrid::config::TypedConfigurationElement<T>* register_option(const char* name, A&&... a)
272 xbt_assert(options.find(name) == options.end(), "Refusing to register the config element '%s' twice.", name);
273 TypedConfigurationElement<T>* variable = new TypedConfigurationElement<T>(name, std::forward<A>(a)...);
274 XBT_DEBUG("Register cfg elm %s (%s) of type %s @%p in set %p)", name, variable->get_description().c_str(),
275 variable->get_type_name(), variable, this);
276 options.insert({name, variable});
282 void dump(const char *name, const char *indent);
287 ConfigurationElement* get_dict_element(const char* name);
292 atexit(&sg_config_finalize);
296 XBT_DEBUG("Frees cfg set %p", this);
297 for (auto const& elm : options)
301 inline ConfigurationElement* Config::get_dict_element(const char* name)
303 auto opt = options.find(name);
304 if (opt != options.end()) {
307 auto als = aliases.find(name);
308 if (als != aliases.end()) {
309 ConfigurationElement* res = als->second;
310 if (warn_for_aliases)
311 XBT_INFO("Option %s has been renamed to %s. Consider switching.", name, res->get_key().c_str());
314 THROWF(not_found_error, 0, "Bad config key: %s", name);
319 inline ConfigurationElement& Config::operator[](const char* name)
321 return *(get_dict_element(name));
324 void Config::alias(const char* realname, const char* aliasname)
326 xbt_assert(aliases.find(aliasname) == aliases.end(), "Alias '%s' already.", aliasname);
327 ConfigurationElement* element = this->get_dict_element(realname);
328 xbt_assert(element, "Cannot define an alias to the non-existing option '%s'.", realname);
329 this->aliases.insert({aliasname, element});
332 /** @brief Dump a config set for debuging purpose
334 * @param name The name to give to this config set
335 * @param indent what to write at the beginning of each line (right number of spaces)
337 void Config::dump(const char *name, const char *indent)
340 printf("%s>> Dumping of the config set '%s':\n", indent, name);
342 for (auto const& elm : options)
343 printf("%s %s: ()%s) %s", indent, elm.first.c_str(), elm.second->get_type_name(),
344 elm.second->get_string_value().c_str());
347 printf("%s<< End of the config set '%s'\n", indent, name);
351 /** @brief Displays the declared aliases and their replacement */
352 void Config::show_aliases()
354 for (auto const& elm : aliases)
355 printf(" %-40s %s\n", elm.first.c_str(), elm.second->get_key().c_str());
358 /** @brief Displays the declared options and their description */
361 for (auto const& elm : options) {
362 simgrid::config::ConfigurationElement* variable = this->options.at(elm.first);
363 printf(" %s: %s\n", elm.first.c_str(), variable->get_description().c_str());
364 printf(" Type: %s; ", variable->get_type_name());
365 printf("Current value: %s\n", variable->get_string_value().c_str());
369 // ***** set_default *****
371 template <class T> XBT_PUBLIC void set_default(const char* name, T value)
373 (*simgrid_config)[name].set_default_value<T>(std::move(value));
376 template XBT_PUBLIC void set_default<int>(const char* name, int value);
377 template XBT_PUBLIC void set_default<double>(const char* name, double value);
378 template XBT_PUBLIC void set_default<bool>(const char* name, bool value);
379 template XBT_PUBLIC void set_default<std::string>(const char* name, std::string value);
381 // ***** set_value *****
383 template <class T> XBT_PUBLIC void set_value(const char* name, T value)
385 (*simgrid_config)[name].set_value<T>(std::move(value));
388 template XBT_PUBLIC void set_value<int>(const char* name, int value);
389 template XBT_PUBLIC void set_value<double>(const char* name, double value);
390 template XBT_PUBLIC void set_value<bool>(const char* name, bool value);
391 template XBT_PUBLIC void set_value<std::string>(const char* name, std::string value);
393 // ***** get_value *****
395 template <class T> XBT_PUBLIC T const& get_value(const char* name)
397 return (*simgrid_config)[name].get_value<T>();
400 template XBT_PUBLIC int const& get_value<int>(const char* name);
401 template XBT_PUBLIC double const& get_value<double>(const char* name);
402 template XBT_PUBLIC bool const& get_value<bool>(const char* name);
403 template XBT_PUBLIC std::string const& get_value<std::string>(const char* name);
407 void alias(const char* realname, std::initializer_list<const char*> aliases)
409 for (auto const& aliasname : aliases)
410 simgrid_config->alias(realname, aliasname);
413 // ***** declare_flag *****
416 XBT_PUBLIC void declare_flag(const char* name, const char* description, T value, std::function<void(const T&)> callback)
418 if (simgrid_config == nullptr)
419 simgrid_config = xbt_cfg_new();
420 simgrid_config->register_option<T>(name, description, std::move(value), std::move(callback));
423 template XBT_PUBLIC void declare_flag(const char* name, const char* description, int value,
424 std::function<void(int const&)> callback);
425 template XBT_PUBLIC void declare_flag(const char* name, const char* description, double value,
426 std::function<void(double const&)> callback);
427 template XBT_PUBLIC void declare_flag(const char* name, const char* description, bool value,
428 std::function<void(bool const&)> callback);
429 template XBT_PUBLIC void declare_flag(const char* name, const char* description, std::string value,
430 std::function<void(std::string const&)> callback);
434 // ***** C bindings *****
436 xbt_cfg_t xbt_cfg_new()
438 return new simgrid::config::Config();
440 void xbt_cfg_free(xbt_cfg_t * cfg) { delete *cfg; }
442 void xbt_cfg_dump(const char *name, const char *indent, xbt_cfg_t cfg)
444 cfg->dump(name, indent);
447 /*----[ Registering stuff ]-----------------------------------------------*/
449 void xbt_cfg_register_double(const char *name, double default_value,
450 xbt_cfg_cb_t cb_set, const char *desc)
452 if (simgrid_config == nullptr)
453 simgrid_config = xbt_cfg_new();
454 simgrid_config->register_option<double>(name, desc, default_value, cb_set);
457 void xbt_cfg_register_int(const char *name, int default_value,xbt_cfg_cb_t cb_set, const char *desc)
459 if (simgrid_config == nullptr)
460 simgrid_config = xbt_cfg_new();
461 simgrid_config->register_option<int>(name, desc, default_value, cb_set);
464 void xbt_cfg_register_string(const char *name, const char *default_value, xbt_cfg_cb_t cb_set, const char *desc)
466 if (simgrid_config == nullptr)
467 simgrid_config = xbt_cfg_new();
468 simgrid_config->register_option<std::string>(name, desc, default_value ? default_value : "", cb_set);
471 void xbt_cfg_register_boolean(const char *name, const char*default_value,xbt_cfg_cb_t cb_set, const char *desc)
473 if (simgrid_config == nullptr)
474 simgrid_config = xbt_cfg_new();
475 simgrid_config->register_option<bool>(name, desc, simgrid::config::parse_bool(default_value), cb_set);
478 void xbt_cfg_register_alias(const char *realname, const char *aliasname)
480 if (simgrid_config == nullptr)
481 simgrid_config = xbt_cfg_new();
482 simgrid_config->alias(realname, aliasname);
485 void xbt_cfg_aliases()
487 simgrid_config->show_aliases();
491 simgrid_config->help();
494 /*----[ Setting ]---------------------------------------------------------*/
496 /** @brief Add values parsed from a string into a config set
498 * @param options a string containing the content to add to the config set. This is a '\\t',' ' or '\\n' or ','
499 * separated list of variables. Each individual variable is like "[name]:[value]" where [name] is the name of an
500 * already registered variable, and [value] conforms to the data type under which this variable was registered.
502 * @todo This is a crude manual parser, it should be a proper lexer.
504 void xbt_cfg_set_parse(const char *options)
506 if (not options || not strlen(options)) { /* nothing to do */
510 XBT_DEBUG("List to parse and set:'%s'", options);
511 std::string optionlist(options);
512 while (not optionlist.empty()) {
513 XBT_DEBUG("Still to parse and set: '%s'", optionlist.c_str());
516 size_t pos = optionlist.find_first_not_of(" \t\n,");
517 optionlist.erase(0, pos);
519 pos = optionlist.find_first_of(" \t\n,");
520 std::string name = optionlist.substr(0, pos);
521 optionlist.erase(0, pos);
522 XBT_DEBUG("parse now:'%s'; parse later:'%s'", name.c_str(), optionlist.c_str());
527 pos = name.find(':');
528 xbt_assert(pos != std::string::npos, "Option '%s' badly formatted. Should be of the form 'name:value'",
531 std::string val = name.substr(pos + 1);
534 const std::string path("path");
535 if (name.compare(0, path.length(), path) != 0)
536 XBT_INFO("Configuration change: Set '%s' to '%s'", name.c_str(), val.c_str());
538 (*simgrid_config)[name.c_str()].set_string_value(val.c_str());
542 /** @brief Set the value of a variable, using the string representation of that value
544 * @param key name of the variable to modify
545 * @param value string representation of the value to set
548 void xbt_cfg_set_as_string(const char *key, const char *value)
550 (*simgrid_config)[key].set_string_value(value);
553 /** @brief Set an integer value to \a name within \a cfg if it wasn't changed yet
555 * This is useful to change the default value of a variable while allowing
556 * users to override it with command line arguments
558 void xbt_cfg_setdefault_int(const char *key, int value)
560 (*simgrid_config)[key].set_default_value<int>(value);
563 /** @brief Set an integer value to \a name within \a cfg if it wasn't changed yet
565 * This is useful to change the default value of a variable while allowing
566 * users to override it with command line arguments
568 void xbt_cfg_setdefault_double(const char *key, double value)
570 (*simgrid_config)[key].set_default_value<double>(value);
573 /** @brief Set a string value to \a name within \a cfg if it wasn't changed yet
575 * This is useful to change the default value of a variable while allowing
576 * users to override it with command line arguments
578 void xbt_cfg_setdefault_string(const char *key, const char *value)
580 (*simgrid_config)[key].set_default_value<std::string>(value ? value : "");
583 /** @brief Set an boolean value to \a name within \a cfg if it wasn't changed yet
585 * This is useful to change the default value of a variable while allowing
586 * users to override it with command line arguments
588 void xbt_cfg_setdefault_boolean(const char *key, const char *value)
590 (*simgrid_config)[key].set_default_value<bool>(simgrid::config::parse_bool(value));
593 /** @brief Set an integer value to \a name within \a cfg
595 * @param key the name of the variable
596 * @param value the value of the variable
598 void xbt_cfg_set_int(const char *key, int value)
600 (*simgrid_config)[key].set_value<int>(value);
603 /** @brief Set or add a double value to \a name within \a cfg
605 * @param key the name of the variable
606 * @param value the double to set
608 void xbt_cfg_set_double(const char *key, double value)
610 (*simgrid_config)[key].set_value<double>(value);
613 /** @brief Set or add a string value to \a name within \a cfg
615 * @param key the name of the variable
616 * @param value the value to be added
619 void xbt_cfg_set_string(const char* key, const char* value)
621 (*simgrid_config)[key].set_value<std::string>(value);
624 /** @brief Set or add a boolean value to \a name within \a cfg
626 * @param key the name of the variable
627 * @param value the value of the variable
629 void xbt_cfg_set_boolean(const char *key, const char *value)
631 (*simgrid_config)[key].set_value<bool>(simgrid::config::parse_bool(value));
635 /* Say if the value is the default value */
636 int xbt_cfg_is_default_value(const char *key)
638 return (*simgrid_config)[key].is_default() ? 1 : 0;
641 /*----[ Getting ]---------------------------------------------------------*/
642 /** @brief Retrieve an integer value of a variable (get a warning if not uniq)
644 * @param key the name of the variable
646 * Returns the first value from the config set under the given name.
648 int xbt_cfg_get_int(const char *key)
650 return (*simgrid_config)[key].get_value<int>();
653 /** @brief Retrieve a double value of a variable (get a warning if not uniq)
655 * @param key the name of the variable
657 * Returns the first value from the config set under the given name.
659 double xbt_cfg_get_double(const char *key)
661 return (*simgrid_config)[key].get_value<double>();
664 /** @brief Retrieve a string value of a variable (get a warning if not uniq)
666 * @param key the name of the variable
668 * Returns the first value from the config set under the given name.
669 * If there is more than one value, it will issue a warning.
670 * Returns nullptr if there is no value.
672 * \warning the returned value is the actual content of the config set
674 std::string xbt_cfg_get_string(const char* key)
676 return (*simgrid_config)[key].get_value<std::string>();
679 /** @brief Retrieve a boolean value of a variable (get a warning if not uniq)
681 * @param key the name of the variable
683 * Returns the first value from the config set under the given name.
684 * If there is more than one value, it will issue a warning.
686 int xbt_cfg_get_boolean(const char *key)
688 return (*simgrid_config)[key].get_value<bool>() ? 1 : 0;
697 #include <xbt/ex.hpp>
699 #include <xbt/config.hpp>
701 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(xbt_cfg);
703 XBT_TEST_SUITE("config", "Configuration support");
705 XBT_PUBLIC_DATA xbt_cfg_t simgrid_config;
707 static void make_set()
709 simgrid_config = nullptr;
710 xbt_log_threshold_set(&_XBT_LOGV(xbt_cfg), xbt_log_priority_critical);
711 simgrid::config::declare_flag<int>("speed", "description", 0);
712 simgrid::config::declare_flag<std::string>("peername", "description", "");
713 simgrid::config::declare_flag<std::string>("user", "description", "");
714 } /* end_of_make_set */
716 XBT_TEST_UNIT("memuse", test_config_memuse, "Alloc and free a config set")
718 auto temp = simgrid_config;
720 xbt_test_add("Alloc and free a config set");
721 xbt_cfg_set_parse("peername:veloce user:bidule");
722 xbt_cfg_free(&simgrid_config);
723 simgrid_config = temp;
726 XBT_TEST_UNIT("use", test_config_use, "Data retrieving tests")
728 auto temp = simgrid_config;
730 xbt_test_add("Get a single value");
732 /* get_single_value */
733 xbt_cfg_set_parse("peername:toto:42 speed:42");
734 int ival = simgrid::config::get_value<int>("speed");
736 xbt_test_fail("Speed value = %d, I expected 42", ival);
739 xbt_test_add("Access to a non-existant entry");
742 xbt_cfg_set_parse("color:blue");
744 if (e.category != not_found_error)
745 xbt_test_exception(e);
748 xbt_cfg_free(&simgrid_config);
749 simgrid_config = temp;
752 XBT_TEST_UNIT("c++flags", test_config_cxx_flags, "C++ flags")
754 auto temp = simgrid_config;
756 xbt_test_add("C++ declaration of flags");
758 simgrid::config::Flag<int> int_flag("int", "", 0);
759 simgrid::config::Flag<std::string> string_flag("string", "", "foo");
760 simgrid::config::Flag<double> double_flag("double", "", 0.32);
761 simgrid::config::Flag<bool> bool_flag1("bool1", "", false);
762 simgrid::config::Flag<bool> bool_flag2("bool2", "", true);
764 xbt_test_add("Parse values");
765 xbt_cfg_set_parse("int:42 string:bar double:8.0 bool1:true bool2:false");
766 xbt_test_assert(int_flag == 42, "Check int flag");
767 xbt_test_assert(string_flag == "bar", "Check string flag");
768 xbt_test_assert(double_flag == 8.0, "Check double flag");
769 xbt_test_assert(bool_flag1, "Check bool1 flag");
770 xbt_test_assert(not bool_flag2, "Check bool2 flag");
772 xbt_cfg_free(&simgrid_config);
773 simgrid_config = temp;
776 #endif /* SIMGRID_TEST */