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. */
17 #include <type_traits>
22 #include <xbt/config.h>
23 #include <xbt/config.hpp>
25 #include "xbt/sysdep.h"
27 #include "xbt/dynar.h"
29 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_cfg, xbt, "configuration support");
31 XBT_EXPORT_NO_IMPORT(xbt_cfg_t) simgrid_config = nullptr;
33 XBT_PUBLIC(void) sg_config_finalize();
39 missing_key_error::~missing_key_error() = default;
45 const char* true_values[] = {
46 "yes", "on", "true", "1"
48 const char* false_values[] = {
49 "no", "off", "false", "0"
52 static bool parseBool(const char* value)
54 for (const char* const& true_value : true_values)
55 if (std::strcmp(true_value, value) == 0)
57 for (const char* const& false_value : false_values)
58 if (std::strcmp(false_value, value) == 0)
60 throw std::range_error("not a boolean");
63 static double parseDouble(const char* value)
67 double res = std::strtod(value, &end);
69 throw std::range_error("out of range");
71 xbt_die("Unexpected errno");
72 if (end == value || *end != '\0')
73 throw std::range_error("invalid double");
78 static long int parseLong(const char* value)
82 long int res = std::strtol(value, &end, 0);
84 if (res == LONG_MIN && errno == ERANGE)
85 throw std::range_error("underflow");
86 else if (res == LONG_MAX && errno == ERANGE)
87 throw std::range_error("overflow");
88 xbt_die("Unexpected errno");
90 if (end == value || *end != '\0')
91 throw std::range_error("invalid integer");
96 // ***** ConfigType *****
98 /// A trait which define possible options types:
99 template <class T> class ConfigType;
101 template <> class ConfigType<int> {
103 static constexpr const char* type_name = "int";
104 static inline double parse(const char* value)
106 return parseLong(value);
109 template <> class ConfigType<double> {
111 static constexpr const char* type_name = "double";
112 static inline double parse(const char* value)
114 return parseDouble(value);
117 template <> class ConfigType<std::string> {
119 static constexpr const char* type_name = "string";
120 static inline std::string parse(const char* value)
122 return std::string(value);
125 template <> class ConfigType<bool> {
127 static constexpr const char* type_name = "boolean";
128 static inline bool parse(const char* value)
130 return parseBool(value);
134 // **** Forward declarations ****
136 class ConfigurationElement ;
137 template<class T> class TypedConfigurationElement;
139 // **** ConfigurationElement ****
141 class ConfigurationElement {
145 bool isdefault = true;
149 xbt_cfg_cb_t old_callback = nullptr;
151 ConfigurationElement(const char* key, const char* desc)
152 : key(key ? key : ""), desc(desc ? desc : "") {}
153 ConfigurationElement(const char* key, const char* desc, xbt_cfg_cb_t cb)
154 : key(key ? key : ""), desc(desc ? desc : ""), old_callback(cb) {}
156 virtual ~ConfigurationElement()=default;
158 virtual std::string getStringValue() = 0;
159 virtual void setStringValue(const char* value) = 0;
160 virtual const char* getTypeName() = 0;
163 T const& getValue() const
165 return dynamic_cast<const TypedConfigurationElement<T>&>(*this).getValue();
168 void setValue(T value)
170 dynamic_cast<TypedConfigurationElement<T>&>(*this).setValue(std::move(value));
173 void setDefaultValue(T value)
175 dynamic_cast<TypedConfigurationElement<T>&>(*this).setDefaultValue(std::move(value));
177 void unsetDefault() { isdefault = false; }
178 bool isDefault() const { return isdefault; }
180 std::string const& getDescription() const { return desc; }
181 std::string const& getKey() const { return key; }
184 // **** TypedConfigurationElement<T> ****
186 // TODO, could we use boost::any with some Type* reference?
188 class TypedConfigurationElement : public ConfigurationElement {
191 std::function<void(T&)> callback;
194 TypedConfigurationElement(const char* key, const char* desc, T value = T())
195 : ConfigurationElement(key, desc), content(std::move(value))
197 TypedConfigurationElement(const char* key, const char* desc, T value, xbt_cfg_cb_t cb)
198 : ConfigurationElement(key, desc, cb), content(std::move(value))
200 TypedConfigurationElement(const char* key, const char* desc, T value, std::function<void(T&)> callback)
201 : ConfigurationElement(key, desc), content(std::move(value)), callback(std::move(callback))
203 ~TypedConfigurationElement() = default;
205 std::string getStringValue() override;
206 const char* getTypeName() override;
207 void setStringValue(const char* value) override;
212 this->old_callback(getKey().c_str());
214 this->callback(this->content);
217 T const& getValue() const { return content; }
219 void setValue(T value)
221 this->content = std::move(value);
225 void setDefaultValue(T value)
227 if (this->isDefault()) {
228 this->content = std::move(value);
231 XBT_DEBUG("Do not override configuration variable '%s' with value '%s' because it was already set.",
232 getKey().c_str(), to_string(value).c_str());
238 std::string TypedConfigurationElement<T>::getStringValue() // override
240 return to_string(content);
244 void TypedConfigurationElement<T>::setStringValue(const char* value) // override
246 this->content = ConfigType<T>::parse(value);
247 this->unsetDefault();
252 const char* TypedConfigurationElement<T>::getTypeName() // override
254 return ConfigType<T>::type_name;
257 } // end of anonymous namespace
263 // name -> ConfigElement:
264 std::map<std::string, simgrid::config::ConfigurationElement*> options;
265 // alias -> xbt_dict_elm_t from options:
266 std::map<std::string, simgrid::config::ConfigurationElement*> aliases;
267 bool warn_for_aliases = true;
274 Config(Config const&) = delete;
275 Config& operator=(Config const&) = delete;
277 ConfigurationElement& operator[](const char* name);
279 TypedConfigurationElement<T>& getTyped(const char* name);
280 void alias(const char* realname, const char* aliasname);
282 template<class T, class... A>
283 simgrid::config::TypedConfigurationElement<T>*
284 registerOption(const char* name, A&&... a)
286 xbt_assert(options.find(name) == options.end(), "Refusing to register the config element '%s' twice.", name);
287 TypedConfigurationElement<T>* variable = new TypedConfigurationElement<T>(name, std::forward<A>(a)...);
288 XBT_DEBUG("Register cfg elm %s (%s) of type %s @%p in set %p)", name, variable->getDescription().c_str(),
289 variable->getTypeName(), variable, this);
290 options.insert({name, variable});
296 void dump(const char *name, const char *indent);
301 ConfigurationElement* getDictElement(const char* name);
306 XBT_DEBUG("Frees cfg set %p", this);
307 for (auto const& elm : options)
311 inline ConfigurationElement* Config::getDictElement(const char* name)
313 auto opt = options.find(name);
314 if (opt != options.end()) {
317 auto als = aliases.find(name);
318 if (als != aliases.end()) {
319 ConfigurationElement* res = als->second;
320 if (warn_for_aliases)
321 XBT_INFO("Option %s has been renamed to %s. Consider switching.", name, res->getKey().c_str());
324 throw simgrid::config::missing_key_error(std::string("Bad config key: ") + name);
329 inline ConfigurationElement& Config::operator[](const char* name)
331 return *(getDictElement(name));
334 void Config::alias(const char* realname, const char* aliasname)
336 xbt_assert(aliases.find(aliasname) == aliases.end(), "Alias '%s' already.", aliasname);
337 ConfigurationElement* element = this->getDictElement(realname);
338 xbt_assert(element, "Cannot define an alias to the non-existing option '%s'.", realname);
339 this->aliases.insert({aliasname, element});
342 /** @brief Dump a config set for debuging purpose
344 * @param name The name to give to this config set
345 * @param indent what to write at the beginning of each line (right number of spaces)
347 void Config::dump(const char *name, const char *indent)
350 printf("%s>> Dumping of the config set '%s':\n", indent, name);
352 for (auto const& elm : options)
353 printf("%s %s: ()%s) %s", indent, elm.first.c_str(), elm.second->getTypeName(),
354 elm.second->getStringValue().c_str());
357 printf("%s<< End of the config set '%s'\n", indent, name);
361 /** @brief Displays the declared aliases and their description */
362 void Config::showAliases()
364 bool old_warn_for_aliases = false;
365 std::swap(warn_for_aliases, old_warn_for_aliases);
366 for (auto const& elm : aliases)
367 printf(" %s: %s\n", elm.first.c_str(), (*this)[elm.first.c_str()].getDescription().c_str());
368 std::swap(warn_for_aliases, old_warn_for_aliases);
371 /** @brief Displays the declared options and their description */
374 for (auto const& elm : options) {
375 simgrid::config::ConfigurationElement* variable = this->options.at(elm.first);
376 printf(" %s: %s\n", elm.first.c_str(), variable->getDescription().c_str());
377 printf(" Type: %s; ", variable->getTypeName());
378 printf("Current value: %s\n", variable->getStringValue().c_str());
382 // ***** getConfig *****
385 XBT_PUBLIC(T const&) getConfig(const char* name)
387 return (*simgrid_config)[name].getValue<T>();
390 template XBT_PUBLIC(int const&) getConfig<int>(const char* name);
391 template XBT_PUBLIC(double const&) getConfig<double>(const char* name);
392 template XBT_PUBLIC(bool const&) getConfig<bool>(const char* name);
393 template XBT_PUBLIC(std::string const&) getConfig<std::string>(const char* name);
397 void alias(const char* realname, const char* aliasname)
399 simgrid_config->alias(realname, aliasname);
402 // ***** declareFlag *****
405 XBT_PUBLIC(void) declareFlag(const char* name, const char* description,
406 T value, std::function<void(const T&)> callback)
408 if (simgrid_config == nullptr) {
409 simgrid_config = xbt_cfg_new();
410 atexit(sg_config_finalize);
412 simgrid_config->registerOption<T>(
413 name, description, std::move(value), std::move(callback));
416 template XBT_PUBLIC(void) declareFlag(const char* name,
417 const char* description, int value, std::function<void(int const &)> callback);
418 template XBT_PUBLIC(void) declareFlag(const char* name,
419 const char* description, double value, std::function<void(double const &)> callback);
420 template XBT_PUBLIC(void) declareFlag(const char* name,
421 const char* description, bool value, std::function<void(bool const &)> callback);
422 template XBT_PUBLIC(void) declareFlag(const char* name,
423 const char* description, std::string value, std::function<void(std::string const &)> callback);
428 // ***** C bindings *****
430 xbt_cfg_t xbt_cfg_new() { return new simgrid::config::Config(); }
431 void xbt_cfg_free(xbt_cfg_t * cfg) { delete *cfg; }
433 void xbt_cfg_dump(const char *name, const char *indent, xbt_cfg_t cfg)
435 cfg->dump(name, indent);
438 /*----[ Registering stuff ]-----------------------------------------------*/
440 void xbt_cfg_register_double(const char *name, double default_value,
441 xbt_cfg_cb_t cb_set, const char *desc)
443 if (simgrid_config == nullptr)
444 simgrid_config = xbt_cfg_new();
445 simgrid_config->registerOption<double>(name, desc, default_value, cb_set);
448 void xbt_cfg_register_int(const char *name, int default_value,xbt_cfg_cb_t cb_set, const char *desc)
450 if (simgrid_config == nullptr) {
451 simgrid_config = xbt_cfg_new();
452 atexit(&sg_config_finalize);
454 simgrid_config->registerOption<int>(name, desc, default_value, cb_set);
457 void xbt_cfg_register_string(const char *name, const char *default_value, xbt_cfg_cb_t cb_set, const char *desc)
459 if (simgrid_config == nullptr) {
460 simgrid_config = xbt_cfg_new();
461 atexit(sg_config_finalize);
463 simgrid_config->registerOption<std::string>(name, desc,
464 default_value ? default_value : "", cb_set);
467 void xbt_cfg_register_boolean(const char *name, const char*default_value,xbt_cfg_cb_t cb_set, const char *desc)
469 if (simgrid_config == nullptr) {
470 simgrid_config = xbt_cfg_new();
471 atexit(sg_config_finalize);
473 simgrid_config->registerOption<bool>(name, desc, simgrid::config::parseBool(default_value), cb_set);
476 void xbt_cfg_register_alias(const char *realname, const char *aliasname)
478 if (simgrid_config == nullptr) {
479 simgrid_config = xbt_cfg_new();
480 atexit(sg_config_finalize);
482 simgrid_config->alias(realname, aliasname);
485 void xbt_cfg_aliases() { simgrid_config->showAliases(); }
486 void xbt_cfg_help() { simgrid_config->help(); }
488 /*----[ Setting ]---------------------------------------------------------*/
490 /** @brief Add values parsed from a string into a config set
492 * @param options a string containing the content to add to the config set. This is a '\\t',' ' or '\\n' or ','
493 * separated list of variables. Each individual variable is like "[name]:[value]" where [name] is the name of an
494 * already registered variable, and [value] conforms to the data type under which this variable was registered.
496 * @todo This is a crude manual parser, it should be a proper lexer.
498 void xbt_cfg_set_parse(const char *options)
500 if (not options || not strlen(options)) { /* nothing to do */
503 char *optionlist_cpy = xbt_strdup(options);
505 XBT_DEBUG("List to parse and set:'%s'", options);
506 char *option = optionlist_cpy;
507 while (1) { /* breaks in the code */
511 int len = strlen(name);
512 XBT_DEBUG("Still to parse and set: '%s'. len=%d; option-name=%ld", name, len, (long) (option - name));
515 while (option - name <= (len - 1) && *option != ' ' && *option != '\n' && *option != '\t' && *option != ',') {
516 XBT_DEBUG("Take %c.", *option);
519 if (option - name == len) {
520 XBT_DEBUG("Boundary=EOL");
521 option = nullptr; /* don't do next iteration */
523 XBT_DEBUG("Boundary on '%c'. len=%d;option-name=%ld", *option, len, (long) (option - name));
524 /* Pass the following blank chars */
526 while (option - name < (len - 1) && (*option == ' ' || *option == '\n' || *option == '\t')) {
529 if (option - name == len - 1)
530 option = nullptr; /* don't do next iteration */
532 XBT_DEBUG("parse now:'%s'; parse later:'%s'", name, option);
534 if (name[0] == ' ' || name[0] == '\n' || name[0] == '\t')
536 if (not strlen(name))
539 char *val = strchr(name, ':');
540 xbt_assert(val, "Option '%s' badly formatted. Should be of the form 'name:value'", name);
541 /* don't free(optionlist_cpy) if the assert fails, 'name' points inside it */
544 if (strncmp(name, "path", strlen("path")))
545 XBT_INFO("Configuration change: Set '%s' to '%s'", name, val);
548 (*simgrid_config)[name].setStringValue(val);
550 catch (simgrid::config::missing_key_error& e) {
558 free(optionlist_cpy);
561 /* Do not THROWF from a C++ exception catching context, or some cleanups will be missing */
563 free(optionlist_cpy);
564 THROWF(not_found_error, 0, "Could not set variables %s", options);
567 free(optionlist_cpy);
568 THROWF(unknown_error, 0, "Could not set variables %s", options);
571 // Horrible mess to translate C++ exceptions to C exceptions:
572 // Exit from the catch block (and do the correct exception cleaning) before attempting to THROWF.
573 #define TRANSLATE_EXCEPTIONS(...) \
574 catch(simgrid::config::missing_key_error& e) { THROWF(not_found_error, 0, __VA_ARGS__); abort(); } \
575 catch(...) { THROWF(not_found_error, 0, __VA_ARGS__); abort(); }
577 /** @brief Set the value of a variable, using the string representation of that value
579 * @param key name of the variable to modify
580 * @param value string representation of the value to set
583 void xbt_cfg_set_as_string(const char *key, const char *value)
586 (*simgrid_config)[key].setStringValue(value);
589 TRANSLATE_EXCEPTIONS("Could not set variable %s as string %s", key, value);
592 /** @brief Set an integer value to \a name within \a cfg if it wasn't changed yet
594 * This is useful to change the default value of a variable while allowing
595 * users to override it with command line arguments
597 void xbt_cfg_setdefault_int(const char *key, int value)
600 (*simgrid_config)[key].setDefaultValue<int>(value);
603 TRANSLATE_EXCEPTIONS("Could not set variable %s to default integer %i", key, value);
606 /** @brief Set an integer value to \a name within \a cfg if it wasn't changed yet
608 * This is useful to change the default value of a variable while allowing
609 * users to override it with command line arguments
611 void xbt_cfg_setdefault_double(const char *key, double value)
614 (*simgrid_config)[key].setDefaultValue<double>(value);
617 TRANSLATE_EXCEPTIONS("Could not set variable %s to default double %f", key, value);
620 /** @brief Set a string value to \a name within \a cfg if it wasn't changed yet
622 * This is useful to change the default value of a variable while allowing
623 * users to override it with command line arguments
625 void xbt_cfg_setdefault_string(const char *key, const char *value)
628 (*simgrid_config)[key].setDefaultValue<std::string>(value ? value : "");
631 TRANSLATE_EXCEPTIONS("Could not set variable %s to default string %s", key, value);
634 /** @brief Set an boolean value to \a name within \a cfg if it wasn't changed yet
636 * This is useful to change the default value of a variable while allowing
637 * users to override it with command line arguments
639 void xbt_cfg_setdefault_boolean(const char *key, const char *value)
642 (*simgrid_config)[key].setDefaultValue<bool>(simgrid::config::parseBool(value));
645 TRANSLATE_EXCEPTIONS("Could not set variable %s to default boolean %s", key, value);
648 /** @brief Set an integer value to \a name within \a cfg
650 * @param key the name of the variable
651 * @param value the value of the variable
653 void xbt_cfg_set_int(const char *key, int value)
656 (*simgrid_config)[key].setValue<int>(value);
659 TRANSLATE_EXCEPTIONS("Could not set variable %s to integer %i", key, value);
662 /** @brief Set or add a double value to \a name within \a cfg
664 * @param key the name of the variable
665 * @param value the double to set
667 void xbt_cfg_set_double(const char *key, double value)
670 (*simgrid_config)[key].setValue<double>(value);
673 TRANSLATE_EXCEPTIONS("Could not set variable %s to double %f", key, value);
676 /** @brief Set or add a string value to \a name within \a cfg
678 * @param key the name of the variable
679 * @param value the value to be added
682 void xbt_cfg_set_string(const char *key, const char *value)
685 (*simgrid_config)[key].setValue<std::string>(value ? value : "");
688 TRANSLATE_EXCEPTIONS("Could not set variable %s to string %s", key, value);
691 /** @brief Set or add a boolean value to \a name within \a cfg
693 * @param key the name of the variable
694 * @param value the value of the variable
696 void xbt_cfg_set_boolean(const char *key, const char *value)
699 (*simgrid_config)[key].setValue<bool>(simgrid::config::parseBool(value));
702 TRANSLATE_EXCEPTIONS("Could not set variable %s to boolean %s", key, value);
706 /* Say if the value is the default value */
707 int xbt_cfg_is_default_value(const char *key)
710 return (*simgrid_config)[key].isDefault() ? 1 : 0;
712 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
715 /*----[ Getting ]---------------------------------------------------------*/
716 /** @brief Retrieve an integer value of a variable (get a warning if not uniq)
718 * @param key the name of the variable
720 * Returns the first value from the config set under the given name.
722 int xbt_cfg_get_int(const char *key)
725 return (*simgrid_config)[key].getValue<int>();
727 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
730 /** @brief Retrieve a double value of a variable (get a warning if not uniq)
732 * @param key the name of the variable
734 * Returns the first value from the config set under the given name.
736 double xbt_cfg_get_double(const char *key)
739 return (*simgrid_config)[key].getValue<double>();
741 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
744 /** @brief Retrieve a string value of a variable (get a warning if not uniq)
746 * @param key the name of the variable
748 * Returns the first value from the config set under the given name.
749 * If there is more than one value, it will issue a warning.
750 * Returns nullptr if there is no value.
752 * \warning the returned value is the actual content of the config set
754 char *xbt_cfg_get_string(const char *key)
757 return (char*) (*simgrid_config)[key].getValue<std::string>().c_str();
759 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
762 /** @brief Retrieve a boolean value of a variable (get a warning if not uniq)
764 * @param key the name of the variable
766 * Returns the first value from the config set under the given name.
767 * If there is more than one value, it will issue a warning.
769 int xbt_cfg_get_boolean(const char *key)
772 return (*simgrid_config)[key].getValue<bool>() ? 1 : 0;
774 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
783 #include <xbt/ex.hpp>
785 #include <xbt/config.hpp>
787 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(xbt_cfg);
789 XBT_TEST_SUITE("config", "Configuration support");
791 XBT_PUBLIC_DATA(xbt_cfg_t) simgrid_config;
793 static void make_set()
795 simgrid_config = nullptr;
796 xbt_log_threshold_set(&_XBT_LOGV(xbt_cfg), xbt_log_priority_critical);
797 xbt_cfg_register_int("speed", 0, nullptr, "");
798 xbt_cfg_register_string("peername", "", nullptr, "");
799 xbt_cfg_register_string("user", "", nullptr, "");
800 } /* end_of_make_set */
802 XBT_TEST_UNIT("memuse", test_config_memuse, "Alloc and free a config set")
804 auto temp = simgrid_config;
806 xbt_test_add("Alloc and free a config set");
807 xbt_cfg_set_parse("peername:veloce user:bidule");
808 xbt_cfg_free(&simgrid_config);
809 simgrid_config = temp;
812 XBT_TEST_UNIT("use", test_config_use, "Data retrieving tests")
814 auto temp = simgrid_config;
816 xbt_test_add("Get a single value");
818 /* get_single_value */
819 xbt_cfg_set_parse("peername:toto:42 speed:42");
820 int ival = xbt_cfg_get_int("speed");
822 xbt_test_fail("Speed value = %d, I expected 42", ival);
825 xbt_test_add("Access to a non-existant entry");
828 xbt_cfg_set_parse("color:blue");
830 if (e.category != not_found_error)
831 xbt_test_exception(e);
834 xbt_cfg_free(&simgrid_config);
835 simgrid_config = temp;
838 XBT_TEST_UNIT("c++flags", test_config_cxx_flags, "C++ flags")
840 auto temp = simgrid_config;
842 xbt_test_add("C++ declaration of flags");
844 simgrid::config::Flag<int> int_flag("int", "", 0);
845 simgrid::config::Flag<std::string> string_flag("string", "", "foo");
846 simgrid::config::Flag<double> double_flag("double", "", 0.32);
847 simgrid::config::Flag<bool> bool_flag1("bool1", "", false);
848 simgrid::config::Flag<bool> bool_flag2("bool2", "", true);
850 xbt_test_add("Parse values");
851 xbt_cfg_set_parse("int:42 string:bar double:8.0 bool1:true bool2:false");
852 xbt_test_assert(int_flag == 42, "Check int flag");
853 xbt_test_assert(string_flag == "bar", "Check string flag");
854 xbt_test_assert(double_flag == 8.0, "Check double flag");
855 xbt_test_assert(bool_flag1, "Check bool1 flag");
856 xbt_test_assert(not bool_flag2, "Check bool2 flag");
858 xbt_cfg_free(&simgrid_config);
859 simgrid_config = temp;
862 #endif /* SIMGRID_TEST */