1 /* Copyright (c) 2004-2017. 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>
23 #include <xbt/config.h>
24 #include <xbt/config.hpp>
26 #include "xbt/sysdep.h"
28 #include "xbt/dynar.h"
30 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_cfg, xbt, "configuration support");
32 XBT_EXPORT_NO_IMPORT(xbt_cfg_t) simgrid_config = nullptr;
34 XBT_PUBLIC(void) sg_config_finalize();
40 missing_key_error::~missing_key_error() = default;
44 const char* true_values[] = {
45 "yes", "on", "true", "1"
47 const char* false_values[] = {
48 "no", "off", "false", "0"
51 static bool parseBool(const char* value)
53 for (const char* const& true_value : true_values)
54 if (std::strcmp(true_value, value) == 0)
56 for (const char* const& false_value : false_values)
57 if (std::strcmp(false_value, value) == 0)
59 throw std::range_error("not a boolean");
62 static double parseDouble(const char* value)
66 double res = std::strtod(value, &end);
68 throw std::range_error("out of range");
70 xbt_die("Unexpected errno");
71 if (end == value || *end != '\0')
72 throw std::range_error("invalid double");
77 static long int parseLong(const char* value)
81 long int res = std::strtol(value, &end, 0);
83 if (res == LONG_MIN && errno == ERANGE)
84 throw std::range_error("underflow");
85 else if (res == LONG_MAX && errno == ERANGE)
86 throw std::range_error("overflow");
87 xbt_die("Unexpected errno");
89 if (end == value || *end != '\0')
90 throw std::range_error("invalid integer");
95 // ***** ConfigType *****
97 /// A trait which define possible options types:
98 template <class T> class ConfigType;
100 template <> class ConfigType<int> {
102 static constexpr const char* type_name = "int";
103 static inline double parse(const char* value)
105 return parseLong(value);
108 template <> class ConfigType<double> {
110 static constexpr const char* type_name = "double";
111 static inline double parse(const char* value)
113 return parseDouble(value);
116 template <> class ConfigType<std::string> {
118 static constexpr const char* type_name = "string";
119 static inline std::string parse(const char* value)
121 return std::string(value);
124 template <> class ConfigType<bool> {
126 static constexpr const char* type_name = "boolean";
127 static inline bool parse(const char* value)
129 return parseBool(value);
133 // **** Forward declarations ****
135 class ConfigurationElement ;
136 template<class T> class TypedConfigurationElement;
138 // **** ConfigurationElement ****
140 class ConfigurationElement {
144 bool isdefault = true;
148 xbt_cfg_cb_t old_callback = nullptr;
150 ConfigurationElement(const char* key, const char* desc) : key(key ? key : ""), desc(desc ? desc : "") {}
151 ConfigurationElement(const char* key, const char* desc, xbt_cfg_cb_t cb)
152 : key(key ? key : ""), desc(desc ? desc : ""), old_callback(cb) {}
154 virtual ~ConfigurationElement()=default;
156 virtual std::string getStringValue() = 0;
157 virtual void setStringValue(const char* value) = 0;
158 virtual const char* getTypeName() = 0;
161 T const& getValue() const
163 return dynamic_cast<const TypedConfigurationElement<T>&>(*this).getValue();
166 void setValue(T value)
168 dynamic_cast<TypedConfigurationElement<T>&>(*this).setValue(std::move(value));
171 void setDefaultValue(T value)
173 dynamic_cast<TypedConfigurationElement<T>&>(*this).setDefaultValue(std::move(value));
175 void unsetDefault() { isdefault = false; }
176 bool isDefault() const { return isdefault; }
178 std::string const& getDescription() const { return desc; }
179 std::string const& getKey() const { return key; }
182 // **** TypedConfigurationElement<T> ****
184 // TODO, could we use boost::any with some Type* reference?
186 class TypedConfigurationElement : public ConfigurationElement {
189 std::function<void(T&)> callback;
192 TypedConfigurationElement(const char* key, const char* desc, T value = T())
193 : ConfigurationElement(key, desc), content(std::move(value))
195 TypedConfigurationElement(const char* key, const char* desc, T value, xbt_cfg_cb_t cb)
196 : ConfigurationElement(key, desc, cb), content(std::move(value))
198 TypedConfigurationElement(const char* key, const char* desc, T value, std::function<void(T&)> callback)
199 : ConfigurationElement(key, desc), content(std::move(value)), callback(std::move(callback))
201 ~TypedConfigurationElement() = default;
203 std::string getStringValue() override;
204 const char* getTypeName() override;
205 void setStringValue(const char* value) override;
210 this->old_callback(getKey().c_str());
212 this->callback(this->content);
215 T const& getValue() const { return content; }
217 void setValue(T value)
219 this->content = std::move(value);
223 void setDefaultValue(T value)
225 if (this->isDefault()) {
226 this->content = std::move(value);
229 XBT_DEBUG("Do not override configuration variable '%s' with value '%s' because it was already set.",
230 getKey().c_str(), to_string(value).c_str());
236 std::string TypedConfigurationElement<T>::getStringValue() // override
238 return to_string(content);
242 void TypedConfigurationElement<T>::setStringValue(const char* value) // override
244 this->content = ConfigType<T>::parse(value);
245 this->unsetDefault();
250 const char* TypedConfigurationElement<T>::getTypeName() // override
252 return ConfigType<T>::type_name;
255 } // end of anonymous namespace
261 // name -> ConfigElement:
262 std::map<std::string, simgrid::config::ConfigurationElement*> options;
263 // alias -> ConfigElement from options:
264 std::map<std::string, simgrid::config::ConfigurationElement*> aliases;
265 bool warn_for_aliases = true;
272 Config(Config const&) = delete;
273 Config& operator=(Config const&) = delete;
275 ConfigurationElement& operator[](const char* name);
277 TypedConfigurationElement<T>& getTyped(const char* name);
278 void alias(const char* realname, const char* aliasname);
280 template<class T, class... A>
281 simgrid::config::TypedConfigurationElement<T>*
282 registerOption(const char* name, A&&... a)
284 xbt_assert(options.find(name) == options.end(), "Refusing to register the config element '%s' twice.", name);
285 TypedConfigurationElement<T>* variable = new TypedConfigurationElement<T>(name, std::forward<A>(a)...);
286 XBT_DEBUG("Register cfg elm %s (%s) of type %s @%p in set %p)", name, variable->getDescription().c_str(),
287 variable->getTypeName(), variable, this);
288 options.insert({name, variable});
294 void dump(const char *name, const char *indent);
299 ConfigurationElement* getDictElement(const char* name);
304 XBT_DEBUG("Frees cfg set %p", this);
305 for (auto const& elm : options)
309 inline ConfigurationElement* Config::getDictElement(const char* name)
311 auto opt = options.find(name);
312 if (opt != options.end()) {
315 auto als = aliases.find(name);
316 if (als != aliases.end()) {
317 ConfigurationElement* res = als->second;
318 if (warn_for_aliases)
319 XBT_INFO("Option %s has been renamed to %s. Consider switching.", name, res->getKey().c_str());
322 throw simgrid::config::missing_key_error(std::string("Bad config key: ") + name);
327 inline ConfigurationElement& Config::operator[](const char* name)
329 return *(getDictElement(name));
332 void Config::alias(const char* realname, const char* aliasname)
334 xbt_assert(aliases.find(aliasname) == aliases.end(), "Alias '%s' already.", aliasname);
335 ConfigurationElement* element = this->getDictElement(realname);
336 xbt_assert(element, "Cannot define an alias to the non-existing option '%s'.", realname);
337 this->aliases.insert({aliasname, element});
340 /** @brief Dump a config set for debuging purpose
342 * @param name The name to give to this config set
343 * @param indent what to write at the beginning of each line (right number of spaces)
345 void Config::dump(const char *name, const char *indent)
348 printf("%s>> Dumping of the config set '%s':\n", indent, name);
350 for (auto const& elm : options)
351 printf("%s %s: ()%s) %s", indent, elm.first.c_str(), elm.second->getTypeName(),
352 elm.second->getStringValue().c_str());
355 printf("%s<< End of the config set '%s'\n", indent, name);
359 /** @brief Displays the declared aliases and their description */
360 void Config::showAliases()
362 bool old_warn_for_aliases = false;
363 std::swap(warn_for_aliases, old_warn_for_aliases);
364 for (auto const& elm : aliases)
365 printf(" %s: %s\n", elm.first.c_str(), (*this)[elm.first.c_str()].getDescription().c_str());
366 std::swap(warn_for_aliases, old_warn_for_aliases);
369 /** @brief Displays the declared options and their description */
372 for (auto const& elm : options) {
373 simgrid::config::ConfigurationElement* variable = this->options.at(elm.first);
374 printf(" %s: %s\n", elm.first.c_str(), variable->getDescription().c_str());
375 printf(" Type: %s; ", variable->getTypeName());
376 printf("Current value: %s\n", variable->getStringValue().c_str());
380 // ***** getConfig *****
383 XBT_PUBLIC(T const&) getConfig(const char* name)
385 return (*simgrid_config)[name].getValue<T>();
388 template XBT_PUBLIC(int const&) getConfig<int>(const char* name);
389 template XBT_PUBLIC(double const&) getConfig<double>(const char* name);
390 template XBT_PUBLIC(bool const&) getConfig<bool>(const char* name);
391 template XBT_PUBLIC(std::string const&) getConfig<std::string>(const char* name);
395 void alias(const char* realname, const char* aliasname)
397 simgrid_config->alias(realname, aliasname);
400 // ***** declareFlag *****
403 XBT_PUBLIC(void) declareFlag(const char* name, const char* description,
404 T value, std::function<void(const T&)> callback)
406 if (simgrid_config == nullptr) {
407 simgrid_config = xbt_cfg_new();
408 atexit(sg_config_finalize);
410 simgrid_config->registerOption<T>(
411 name, description, std::move(value), std::move(callback));
414 template XBT_PUBLIC(void) declareFlag(const char* name,
415 const char* description, int value, std::function<void(int const &)> callback);
416 template XBT_PUBLIC(void) declareFlag(const char* name,
417 const char* description, double value, std::function<void(double const &)> callback);
418 template XBT_PUBLIC(void) declareFlag(const char* name,
419 const char* description, bool value, std::function<void(bool const &)> callback);
420 template XBT_PUBLIC(void) declareFlag(const char* name,
421 const char* description, std::string value, std::function<void(std::string const &)> callback);
426 // ***** C bindings *****
428 xbt_cfg_t xbt_cfg_new() { return new simgrid::config::Config(); }
429 void xbt_cfg_free(xbt_cfg_t * cfg) { delete *cfg; }
431 void xbt_cfg_dump(const char *name, const char *indent, xbt_cfg_t cfg)
433 cfg->dump(name, indent);
436 /*----[ Registering stuff ]-----------------------------------------------*/
438 void xbt_cfg_register_double(const char *name, double default_value,
439 xbt_cfg_cb_t cb_set, const char *desc)
441 if (simgrid_config == nullptr)
442 simgrid_config = xbt_cfg_new();
443 simgrid_config->registerOption<double>(name, desc, default_value, cb_set);
446 void xbt_cfg_register_int(const char *name, int default_value,xbt_cfg_cb_t cb_set, const char *desc)
448 if (simgrid_config == nullptr) {
449 simgrid_config = xbt_cfg_new();
450 atexit(&sg_config_finalize);
452 simgrid_config->registerOption<int>(name, desc, default_value, cb_set);
455 void xbt_cfg_register_string(const char *name, const char *default_value, xbt_cfg_cb_t cb_set, const char *desc)
457 if (simgrid_config == nullptr) {
458 simgrid_config = xbt_cfg_new();
459 atexit(sg_config_finalize);
461 simgrid_config->registerOption<std::string>(name, desc, default_value ? default_value : "", cb_set);
464 void xbt_cfg_register_boolean(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 atexit(sg_config_finalize);
470 simgrid_config->registerOption<bool>(name, desc, simgrid::config::parseBool(default_value), cb_set);
473 void xbt_cfg_register_alias(const char *realname, const char *aliasname)
475 if (simgrid_config == nullptr) {
476 simgrid_config = xbt_cfg_new();
477 atexit(sg_config_finalize);
479 simgrid_config->alias(realname, aliasname);
482 void xbt_cfg_aliases() { simgrid_config->showAliases(); }
483 void xbt_cfg_help() { simgrid_config->help(); }
485 /*----[ Setting ]---------------------------------------------------------*/
487 /** @brief Add values parsed from a string into a config set
489 * @param options a string containing the content to add to the config set. This is a '\\t',' ' or '\\n' or ','
490 * separated list of variables. Each individual variable is like "[name]:[value]" where [name] is the name of an
491 * already registered variable, and [value] conforms to the data type under which this variable was registered.
493 * @todo This is a crude manual parser, it should be a proper lexer.
495 void xbt_cfg_set_parse(const char *options)
497 if (not options || not strlen(options)) { /* nothing to do */
501 XBT_DEBUG("List to parse and set:'%s'", options);
502 std::string optionlist(options);
503 while (not optionlist.empty()) {
504 XBT_DEBUG("Still to parse and set: '%s'", optionlist.c_str());
507 size_t pos = optionlist.find_first_not_of(" \t\n,");
508 optionlist.erase(0, pos);
510 pos = optionlist.find_first_of(" \t\n,");
511 std::string name = optionlist.substr(0, pos);
512 optionlist.erase(0, pos);
513 XBT_DEBUG("parse now:'%s'; parse later:'%s'", name.c_str(), optionlist.c_str());
518 pos = name.find(':');
519 xbt_assert(pos != std::string::npos, "Option '%s' badly formatted. Should be of the form 'name:value'",
522 std::string val = name.substr(pos + 1);
525 const std::string path("path");
526 if (name.compare(0, path.length(), path) != 0)
527 XBT_INFO("Configuration change: Set '%s' to '%s'", name.c_str(), val.c_str());
530 (*simgrid_config)[name.c_str()].setStringValue(val.c_str());
532 catch (simgrid::config::missing_key_error& e) {
541 /* Do not THROWF from a C++ exception catching context, or some cleanups will be missing */
543 THROWF(not_found_error, 0, "Could not set variables %s", options);
545 THROWF(unknown_error, 0, "Could not set variables %s", options);
548 // Horrible mess to translate C++ exceptions to C exceptions:
549 // Exit from the catch block (and do the correct exception cleaning) before attempting to THROWF.
550 #define TRANSLATE_EXCEPTIONS(...) \
551 catch(simgrid::config::missing_key_error& e) { THROWF(not_found_error, 0, __VA_ARGS__); abort(); } \
552 catch(...) { THROWF(not_found_error, 0, __VA_ARGS__); abort(); }
554 /** @brief Set the value of a variable, using the string representation of that value
556 * @param key name of the variable to modify
557 * @param value string representation of the value to set
560 void xbt_cfg_set_as_string(const char *key, const char *value)
563 (*simgrid_config)[key].setStringValue(value);
566 TRANSLATE_EXCEPTIONS("Could not set variable %s as string %s", key, value);
569 /** @brief Set an integer value to \a name within \a cfg if it wasn't changed yet
571 * This is useful to change the default value of a variable while allowing
572 * users to override it with command line arguments
574 void xbt_cfg_setdefault_int(const char *key, int value)
577 (*simgrid_config)[key].setDefaultValue<int>(value);
580 TRANSLATE_EXCEPTIONS("Could not set variable %s to default integer %i", key, value);
583 /** @brief Set an integer 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_double(const char *key, double value)
591 (*simgrid_config)[key].setDefaultValue<double>(value);
594 TRANSLATE_EXCEPTIONS("Could not set variable %s to default double %f", key, value);
597 /** @brief Set a string value to \a name within \a cfg if it wasn't changed yet
599 * This is useful to change the default value of a variable while allowing
600 * users to override it with command line arguments
602 void xbt_cfg_setdefault_string(const char *key, const char *value)
605 (*simgrid_config)[key].setDefaultValue<std::string>(value ? value : "");
608 TRANSLATE_EXCEPTIONS("Could not set variable %s to default string %s", key, value);
611 /** @brief Set an boolean value to \a name within \a cfg if it wasn't changed yet
613 * This is useful to change the default value of a variable while allowing
614 * users to override it with command line arguments
616 void xbt_cfg_setdefault_boolean(const char *key, const char *value)
619 (*simgrid_config)[key].setDefaultValue<bool>(simgrid::config::parseBool(value));
622 TRANSLATE_EXCEPTIONS("Could not set variable %s to default boolean %s", key, value);
625 /** @brief Set an integer value to \a name within \a cfg
627 * @param key the name of the variable
628 * @param value the value of the variable
630 void xbt_cfg_set_int(const char *key, int value)
633 (*simgrid_config)[key].setValue<int>(value);
636 TRANSLATE_EXCEPTIONS("Could not set variable %s to integer %i", key, value);
639 /** @brief Set or add a double value to \a name within \a cfg
641 * @param key the name of the variable
642 * @param value the double to set
644 void xbt_cfg_set_double(const char *key, double value)
647 (*simgrid_config)[key].setValue<double>(value);
650 TRANSLATE_EXCEPTIONS("Could not set variable %s to double %f", key, value);
653 /** @brief Set or add a string value to \a name within \a cfg
655 * @param key the name of the variable
656 * @param value the value to be added
659 void xbt_cfg_set_string(const char* key, const char* value)
662 (*simgrid_config)[key].setValue<std::string>(value);
665 TRANSLATE_EXCEPTIONS("Could not set variable %s to string %s", key, value);
668 /** @brief Set or add a boolean value to \a name within \a cfg
670 * @param key the name of the variable
671 * @param value the value of the variable
673 void xbt_cfg_set_boolean(const char *key, const char *value)
676 (*simgrid_config)[key].setValue<bool>(simgrid::config::parseBool(value));
679 TRANSLATE_EXCEPTIONS("Could not set variable %s to boolean %s", key, value);
683 /* Say if the value is the default value */
684 int xbt_cfg_is_default_value(const char *key)
687 return (*simgrid_config)[key].isDefault() ? 1 : 0;
689 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
692 /*----[ Getting ]---------------------------------------------------------*/
693 /** @brief Retrieve an integer value of a variable (get a warning if not uniq)
695 * @param key the name of the variable
697 * Returns the first value from the config set under the given name.
699 int xbt_cfg_get_int(const char *key)
702 return (*simgrid_config)[key].getValue<int>();
704 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
707 /** @brief Retrieve a double value of a variable (get a warning if not uniq)
709 * @param key the name of the variable
711 * Returns the first value from the config set under the given name.
713 double xbt_cfg_get_double(const char *key)
716 return (*simgrid_config)[key].getValue<double>();
718 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
721 /** @brief Retrieve a string value of a variable (get a warning if not uniq)
723 * @param key the name of the variable
725 * Returns the first value from the config set under the given name.
726 * If there is more than one value, it will issue a warning.
727 * Returns nullptr if there is no value.
729 * \warning the returned value is the actual content of the config set
731 std::string xbt_cfg_get_string(const char* key)
734 return (*simgrid_config)[key].getValue<std::string>();
736 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
739 /** @brief Retrieve a boolean value of a variable (get a warning if not uniq)
741 * @param key the name of the variable
743 * Returns the first value from the config set under the given name.
744 * If there is more than one value, it will issue a warning.
746 int xbt_cfg_get_boolean(const char *key)
749 return (*simgrid_config)[key].getValue<bool>() ? 1 : 0;
751 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
760 #include <xbt/ex.hpp>
762 #include <xbt/config.hpp>
764 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(xbt_cfg);
766 XBT_TEST_SUITE("config", "Configuration support");
768 XBT_PUBLIC_DATA(xbt_cfg_t) simgrid_config;
770 static void make_set()
772 simgrid_config = nullptr;
773 xbt_log_threshold_set(&_XBT_LOGV(xbt_cfg), xbt_log_priority_critical);
774 xbt_cfg_register_int("speed", 0, nullptr, "");
775 xbt_cfg_register_string("peername", "", nullptr, "");
776 xbt_cfg_register_string("user", "", nullptr, "");
777 } /* end_of_make_set */
779 XBT_TEST_UNIT("memuse", test_config_memuse, "Alloc and free a config set")
781 auto temp = simgrid_config;
783 xbt_test_add("Alloc and free a config set");
784 xbt_cfg_set_parse("peername:veloce user:bidule");
785 xbt_cfg_free(&simgrid_config);
786 simgrid_config = temp;
789 XBT_TEST_UNIT("use", test_config_use, "Data retrieving tests")
791 auto temp = simgrid_config;
793 xbt_test_add("Get a single value");
795 /* get_single_value */
796 xbt_cfg_set_parse("peername:toto:42 speed:42");
797 int ival = xbt_cfg_get_int("speed");
799 xbt_test_fail("Speed value = %d, I expected 42", ival);
802 xbt_test_add("Access to a non-existant entry");
805 xbt_cfg_set_parse("color:blue");
807 if (e.category != not_found_error)
808 xbt_test_exception(e);
811 xbt_cfg_free(&simgrid_config);
812 simgrid_config = temp;
815 XBT_TEST_UNIT("c++flags", test_config_cxx_flags, "C++ flags")
817 auto temp = simgrid_config;
819 xbt_test_add("C++ declaration of flags");
821 simgrid::config::Flag<int> int_flag("int", "", 0);
822 simgrid::config::Flag<std::string> string_flag("string", "", "foo");
823 simgrid::config::Flag<double> double_flag("double", "", 0.32);
824 simgrid::config::Flag<bool> bool_flag1("bool1", "", false);
825 simgrid::config::Flag<bool> bool_flag2("bool2", "", true);
827 xbt_test_add("Parse values");
828 xbt_cfg_set_parse("int:42 string:bar double:8.0 bool1:true bool2:false");
829 xbt_test_assert(int_flag == 42, "Check int flag");
830 xbt_test_assert(string_flag == "bar", "Check string flag");
831 xbt_test_assert(double_flag == 8.0, "Check double flag");
832 xbt_test_assert(bool_flag1, "Check bool1 flag");
833 xbt_test_assert(not bool_flag2, "Check bool2 flag");
835 xbt_cfg_free(&simgrid_config);
836 simgrid_config = temp;
839 #endif /* SIMGRID_TEST */