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* true_value : true_values)
55 if (std::strcmp(true_value, value) == 0)
57 for (const char* 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> struct ConfigType;
101 template<> struct ConfigType<int> {
102 static constexpr const char* type_name = "int";
103 static inline double parse(const char* value)
105 return parseLong(value);
108 template<> struct ConfigType<double> {
109 static constexpr const char* type_name = "double";
110 static inline double parse(const char* value)
112 return parseDouble(value);
115 template<> struct ConfigType<std::string> {
116 static constexpr const char* type_name = "string";
117 static inline std::string parse(const char* value)
119 return std::string(value);
122 template<> struct ConfigType<bool> {
123 static constexpr const char* type_name = "boolean";
124 static inline bool parse(const char* value)
126 return parseBool(value);
130 // **** Forward declarations ****
132 class ConfigurationElement ;
133 template<class T> class TypedConfigurationElement;
135 // **** ConfigurationElement ****
137 class ConfigurationElement {
141 bool isdefault = true;
145 xbt_cfg_cb_t old_callback = nullptr;
147 ConfigurationElement(const char* key, const char* desc)
148 : key(key ? key : ""), desc(desc ? desc : "") {}
149 ConfigurationElement(const char* key, const char* desc, xbt_cfg_cb_t cb)
150 : key(key ? key : ""), desc(desc ? desc : ""), old_callback(cb) {}
152 virtual ~ConfigurationElement()=default;
154 virtual std::string getStringValue() = 0;
155 virtual void setStringValue(const char* value) = 0;
156 virtual const char* getTypeName() = 0;
159 T const& getValue() const
161 return dynamic_cast<const TypedConfigurationElement<T>&>(*this).getValue();
164 void setValue(T value)
166 dynamic_cast<TypedConfigurationElement<T>&>(*this).setValue(std::move(value));
169 void setDefaultValue(T value)
171 dynamic_cast<TypedConfigurationElement<T>&>(*this).setDefaultValue(std::move(value));
173 bool isDefault() const { return isdefault; }
175 std::string const& getDescription() const { return desc; }
176 std::string const& getKey() const { return key; }
179 // **** TypedConfigurationElement<T> ****
181 // TODO, could we use boost::any with some Type* reference?
183 class TypedConfigurationElement : public ConfigurationElement {
186 std::function<void(T&)> callback;
189 TypedConfigurationElement(const char* key, const char* desc, T value = T())
190 : ConfigurationElement(key, desc), content(std::move(value))
192 TypedConfigurationElement(const char* key, const char* desc, T value, xbt_cfg_cb_t cb)
193 : ConfigurationElement(key, desc, cb), content(std::move(value))
195 TypedConfigurationElement(const char* key, const char* desc, T value, std::function<void(T&)> callback)
196 : ConfigurationElement(key, desc), content(std::move(value)), callback(std::move(callback))
198 ~TypedConfigurationElement() = default;
200 std::string getStringValue() override;
201 const char* getTypeName() override;
202 void setStringValue(const char* value) override;
207 this->old_callback(key.c_str());
209 this->callback(this->content);
212 T const& getValue() const { return content; }
214 void setValue(T value)
216 this->content = std::move(value);
220 void setDefaultValue(T value)
222 if (this->isdefault) {
223 this->content = std::move(value);
226 XBT_DEBUG("Do not override configuration variable '%s' with value '%s' because it was already set.", key.c_str(),
227 to_string(value).c_str());
233 std::string TypedConfigurationElement<T>::getStringValue() // override
235 return to_string(content);
239 void TypedConfigurationElement<T>::setStringValue(const char* value) // override
241 this->content = ConfigType<T>::parse(value);
242 this->isdefault = false;
247 const char* TypedConfigurationElement<T>::getTypeName() // override
249 return ConfigType<T>::type_name;
252 } // end of anonymous namespace
258 // name -> ConfigElement:
259 std::map<std::string, simgrid::config::ConfigurationElement*> options;
260 // alias -> xbt_dict_elm_t from options:
261 std::map<std::string, simgrid::config::ConfigurationElement*> aliases;
262 bool warn_for_aliases = true;
269 Config(Config const&) = delete;
270 Config& operator=(Config const&) = delete;
272 ConfigurationElement& operator[](const char* name);
274 TypedConfigurationElement<T>& getTyped(const char* name);
275 void alias(const char* realname, const char* aliasname);
277 template<class T, class... A>
278 simgrid::config::TypedConfigurationElement<T>*
279 registerOption(const char* name, A&&... a)
281 xbt_assert(options.find(name) == options.end(), "Refusing to register the config element '%s' twice.", name);
282 TypedConfigurationElement<T>* variable = new TypedConfigurationElement<T>(name, std::forward<A>(a)...);
283 XBT_DEBUG("Register cfg elm %s (%s) of type %s @%p in set %p)", name, variable->getDescription().c_str(),
284 variable->getTypeName(), variable, this);
285 options.insert({name, variable});
291 void dump(const char *name, const char *indent);
296 ConfigurationElement* getDictElement(const char* name);
301 XBT_DEBUG("Frees cfg set %p", this);
302 for (auto elm : options)
306 inline ConfigurationElement* Config::getDictElement(const char* name)
309 return options.at(name);
310 } catch (std::out_of_range& unfound) {
312 ConfigurationElement* res = aliases.at(name);
313 if (warn_for_aliases)
314 XBT_INFO("Option %s has been renamed to %s. Consider switching.", name, res->getKey().c_str());
316 } catch (std::out_of_range& missing_key) {
317 throw simgrid::config::missing_key_error(std::string("Bad config key: ") + name);
322 inline ConfigurationElement& Config::operator[](const char* name)
324 return *(getDictElement(name));
327 void Config::alias(const char* realname, const char* aliasname)
329 xbt_assert(aliases.find(aliasname) == aliases.end(), "Alias '%s' already.", aliasname);
330 ConfigurationElement* element = this->getDictElement(realname);
331 xbt_assert(element, "Cannot define an alias to the non-existing option '%s'.", realname);
332 this->aliases.insert({aliasname, element});
335 /** @brief Dump a config set for debuging purpose
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)
340 void Config::dump(const char *name, const char *indent)
343 printf("%s>> Dumping of the config set '%s':\n", indent, name);
345 for (auto elm : options)
346 printf("%s %s: ()%s) %s", indent, elm.first.c_str(), elm.second->getTypeName(),
347 elm.second->getStringValue().c_str());
350 printf("%s<< End of the config set '%s'\n", indent, name);
354 /** @brief Displays the declared aliases and their description */
355 void Config::showAliases()
357 bool old_warn_for_aliases = false;
358 std::swap(warn_for_aliases, old_warn_for_aliases);
359 for (auto elm : aliases)
360 printf(" %s: %s\n", elm.first.c_str(), (*this)[elm.first.c_str()].getDescription().c_str());
361 std::swap(warn_for_aliases, old_warn_for_aliases);
364 /** @brief Displays the declared options and their description */
367 for (auto elm : options) {
368 simgrid::config::ConfigurationElement* variable = this->options.at(elm.first);
369 printf(" %s: %s\n", elm.first.c_str(), variable->getDescription().c_str());
370 printf(" Type: %s; ", variable->getTypeName());
371 printf("Current value: %s\n", variable->getStringValue().c_str());
375 // ***** getConfig *****
378 XBT_PUBLIC(T const&) getConfig(const char* name)
380 return (*simgrid_config)[name].getValue<T>();
383 template XBT_PUBLIC(int const&) getConfig<int>(const char* name);
384 template XBT_PUBLIC(double const&) getConfig<double>(const char* name);
385 template XBT_PUBLIC(bool const&) getConfig<bool>(const char* name);
386 template XBT_PUBLIC(std::string const&) getConfig<std::string>(const char* name);
390 void alias(const char* realname, const char* aliasname)
392 simgrid_config->alias(realname, aliasname);
395 // ***** declareFlag *****
398 XBT_PUBLIC(void) declareFlag(const char* name, const char* description,
399 T value, std::function<void(const T&)> callback)
401 if (simgrid_config == nullptr) {
402 simgrid_config = xbt_cfg_new();
403 atexit(sg_config_finalize);
405 simgrid_config->registerOption<T>(
406 name, description, std::move(value), std::move(callback));
409 template XBT_PUBLIC(void) declareFlag(const char* name,
410 const char* description, int value, std::function<void(int const &)> callback);
411 template XBT_PUBLIC(void) declareFlag(const char* name,
412 const char* description, double value, std::function<void(double const &)> callback);
413 template XBT_PUBLIC(void) declareFlag(const char* name,
414 const char* description, bool value, std::function<void(bool const &)> callback);
415 template XBT_PUBLIC(void) declareFlag(const char* name,
416 const char* description, std::string value, std::function<void(std::string const &)> callback);
421 // ***** C bindings *****
423 xbt_cfg_t xbt_cfg_new() { return new simgrid::config::Config(); }
424 void xbt_cfg_free(xbt_cfg_t * cfg) { delete *cfg; }
426 void xbt_cfg_dump(const char *name, const char *indent, xbt_cfg_t cfg)
428 cfg->dump(name, indent);
431 /*----[ Registering stuff ]-----------------------------------------------*/
433 void xbt_cfg_register_double(const char *name, double default_value,
434 xbt_cfg_cb_t cb_set, const char *desc)
436 if (simgrid_config == nullptr)
437 simgrid_config = xbt_cfg_new();
438 simgrid_config->registerOption<double>(name, desc, default_value, cb_set);
441 void xbt_cfg_register_int(const char *name, int default_value,xbt_cfg_cb_t cb_set, const char *desc)
443 if (simgrid_config == nullptr) {
444 simgrid_config = xbt_cfg_new();
445 atexit(&sg_config_finalize);
447 simgrid_config->registerOption<int>(name, desc, default_value, cb_set);
450 void xbt_cfg_register_string(const char *name, const char *default_value, xbt_cfg_cb_t cb_set, const char *desc)
452 if (simgrid_config == nullptr) {
453 simgrid_config = xbt_cfg_new();
454 atexit(sg_config_finalize);
456 simgrid_config->registerOption<std::string>(name, desc,
457 default_value ? default_value : "", cb_set);
460 void xbt_cfg_register_boolean(const char *name, const char*default_value,xbt_cfg_cb_t cb_set, const char *desc)
462 if (simgrid_config == nullptr) {
463 simgrid_config = xbt_cfg_new();
464 atexit(sg_config_finalize);
466 simgrid_config->registerOption<bool>(name, desc, simgrid::config::parseBool(default_value), cb_set);
469 void xbt_cfg_register_alias(const char *realname, const char *aliasname)
471 if (simgrid_config == nullptr) {
472 simgrid_config = xbt_cfg_new();
473 atexit(sg_config_finalize);
475 simgrid_config->alias(realname, aliasname);
478 void xbt_cfg_aliases() { simgrid_config->showAliases(); }
479 void xbt_cfg_help() { simgrid_config->help(); }
481 /*----[ Setting ]---------------------------------------------------------*/
483 /** @brief Add values parsed from a string into a config set
485 * @param options a string containing the content to add to the config set. This is a '\\t',' ' or '\\n' or ','
486 * separated list of variables. Each individual variable is like "[name]:[value]" where [name] is the name of an
487 * already registered variable, and [value] conforms to the data type under which this variable was registered.
489 * @todo This is a crude manual parser, it should be a proper lexer.
491 void xbt_cfg_set_parse(const char *options)
493 if (not options || not strlen(options)) { /* nothing to do */
496 char *optionlist_cpy = xbt_strdup(options);
498 XBT_DEBUG("List to parse and set:'%s'", options);
499 char *option = optionlist_cpy;
500 while (1) { /* breaks in the code */
504 int len = strlen(name);
505 XBT_DEBUG("Still to parse and set: '%s'. len=%d; option-name=%ld", name, len, (long) (option - name));
508 while (option - name <= (len - 1) && *option != ' ' && *option != '\n' && *option != '\t' && *option != ',') {
509 XBT_DEBUG("Take %c.", *option);
512 if (option - name == len) {
513 XBT_DEBUG("Boundary=EOL");
514 option = nullptr; /* don't do next iteration */
516 XBT_DEBUG("Boundary on '%c'. len=%d;option-name=%ld", *option, len, (long) (option - name));
517 /* Pass the following blank chars */
519 while (option - name < (len - 1) && (*option == ' ' || *option == '\n' || *option == '\t')) {
520 /* fprintf(stderr,"Ignore a blank char.\n"); */
523 if (option - name == len - 1)
524 option = nullptr; /* don't do next iteration */
526 XBT_DEBUG("parse now:'%s'; parse later:'%s'", name, option);
528 if (name[0] == ' ' || name[0] == '\n' || name[0] == '\t')
530 if (not strlen(name))
533 char *val = strchr(name, ':');
534 xbt_assert(val, "Option '%s' badly formatted. Should be of the form 'name:value'", name);
535 /* don't free(optionlist_cpy) if the assert fails, 'name' points inside it */
538 if (strncmp(name, "path", strlen("path")))
539 XBT_INFO("Configuration change: Set '%s' to '%s'", name, val);
542 (*simgrid_config)[name].setStringValue(val);
544 catch (simgrid::config::missing_key_error& e) {
552 free(optionlist_cpy);
555 /* Do not THROWF from a C++ exception catching context, or some cleanups will be missing */
557 free(optionlist_cpy);
558 THROWF(not_found_error, 0, "Could not set variables %s", options);
561 free(optionlist_cpy);
562 THROWF(unknown_error, 0, "Could not set variables %s", options);
565 // Horrible mess to translate C++ exceptions to C exceptions:
566 // Exit from the catch block (and do the correct exception cleaning) before attempting to THROWF.
567 #define TRANSLATE_EXCEPTIONS(...) \
568 catch(simgrid::config::missing_key_error& e) { THROWF(not_found_error, 0, __VA_ARGS__); abort(); } \
569 catch(...) { THROWF(not_found_error, 0, __VA_ARGS__); abort(); }
571 /** @brief Set the value of a variable, using the string representation of that value
573 * @param key name of the variable to modify
574 * @param value string representation of the value to set
577 void xbt_cfg_set_as_string(const char *key, const char *value)
580 (*simgrid_config)[key].setStringValue(value);
583 TRANSLATE_EXCEPTIONS("Could not set variable %s as string %s", key, value);
586 /** @brief Set an integer value to \a name within \a cfg if it wasn't changed yet
588 * This is useful to change the default value of a variable while allowing
589 * users to override it with command line arguments
591 void xbt_cfg_setdefault_int(const char *key, int value)
594 (*simgrid_config)[key].setDefaultValue<int>(value);
597 TRANSLATE_EXCEPTIONS("Could not set variable %s to default integer %i", key, value);
600 /** @brief Set an integer value to \a name within \a cfg if it wasn't changed yet
602 * This is useful to change the default value of a variable while allowing
603 * users to override it with command line arguments
605 void xbt_cfg_setdefault_double(const char *key, double value)
608 (*simgrid_config)[key].setDefaultValue<double>(value);
611 TRANSLATE_EXCEPTIONS("Could not set variable %s to default double %f", key, value);
614 /** @brief Set a string value to \a name within \a cfg if it wasn't changed yet
616 * This is useful to change the default value of a variable while allowing
617 * users to override it with command line arguments
619 void xbt_cfg_setdefault_string(const char *key, const char *value)
622 (*simgrid_config)[key].setDefaultValue<std::string>(value ? value : "");
625 TRANSLATE_EXCEPTIONS("Could not set variable %s to default string %s", key, value);
628 /** @brief Set an boolean value to \a name within \a cfg if it wasn't changed yet
630 * This is useful to change the default value of a variable while allowing
631 * users to override it with command line arguments
633 void xbt_cfg_setdefault_boolean(const char *key, const char *value)
636 (*simgrid_config)[key].setDefaultValue<bool>(simgrid::config::parseBool(value));
639 TRANSLATE_EXCEPTIONS("Could not set variable %s to default boolean %s", key, value);
642 /** @brief Set an integer value to \a name within \a cfg
644 * @param key the name of the variable
645 * @param value the value of the variable
647 void xbt_cfg_set_int(const char *key, int value)
650 (*simgrid_config)[key].setValue<int>(value);
653 TRANSLATE_EXCEPTIONS("Could not set variable %s to integer %i", key, value);
656 /** @brief Set or add a double value to \a name within \a cfg
658 * @param key the name of the variable
659 * @param value the double to set
661 void xbt_cfg_set_double(const char *key, double value)
664 (*simgrid_config)[key].setValue<double>(value);
667 TRANSLATE_EXCEPTIONS("Could not set variable %s to double %f", key, value);
670 /** @brief Set or add a string value to \a name within \a cfg
672 * @param key the name of the variable
673 * @param value the value to be added
676 void xbt_cfg_set_string(const char *key, const char *value)
679 (*simgrid_config)[key].setValue<std::string>(value ? value : "");
682 TRANSLATE_EXCEPTIONS("Could not set variable %s to string %s", key, value);
685 /** @brief Set or add a boolean value to \a name within \a cfg
687 * @param key the name of the variable
688 * @param value the value of the variable
690 void xbt_cfg_set_boolean(const char *key, const char *value)
693 (*simgrid_config)[key].setValue<bool>(simgrid::config::parseBool(value));
696 TRANSLATE_EXCEPTIONS("Could not set variable %s to boolean %s", key, value);
700 /* Say if the value is the default value */
701 int xbt_cfg_is_default_value(const char *key)
704 return (*simgrid_config)[key].isDefault() ? 1 : 0;
706 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
709 /*----[ Getting ]---------------------------------------------------------*/
710 /** @brief Retrieve an integer value of a variable (get a warning if not uniq)
712 * @param key the name of the variable
714 * Returns the first value from the config set under the given name.
716 int xbt_cfg_get_int(const char *key)
719 return (*simgrid_config)[key].getValue<int>();
721 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
724 /** @brief Retrieve a double value of a variable (get a warning if not uniq)
726 * @param key the name of the variable
728 * Returns the first value from the config set under the given name.
730 double xbt_cfg_get_double(const char *key)
733 return (*simgrid_config)[key].getValue<double>();
735 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
738 /** @brief Retrieve a string value of a variable (get a warning if not uniq)
740 * @param key the name of the variable
742 * Returns the first value from the config set under the given name.
743 * If there is more than one value, it will issue a warning.
744 * Returns nullptr if there is no value.
746 * \warning the returned value is the actual content of the config set
748 char *xbt_cfg_get_string(const char *key)
751 return (char*) (*simgrid_config)[key].getValue<std::string>().c_str();
753 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
756 /** @brief Retrieve a boolean value of a variable (get a warning if not uniq)
758 * @param key the name of the variable
760 * Returns the first value from the config set under the given name.
761 * If there is more than one value, it will issue a warning.
763 int xbt_cfg_get_boolean(const char *key)
766 return (*simgrid_config)[key].getValue<bool>() ? 1 : 0;
768 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
777 #include <xbt/ex.hpp>
779 #include <xbt/config.hpp>
781 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(xbt_cfg);
783 XBT_TEST_SUITE("config", "Configuration support");
785 XBT_PUBLIC_DATA(xbt_cfg_t) simgrid_config;
787 static void make_set()
789 simgrid_config = nullptr;
790 xbt_log_threshold_set(&_XBT_LOGV(xbt_cfg), xbt_log_priority_critical);
791 xbt_cfg_register_int("speed", 0, nullptr, "");
792 xbt_cfg_register_string("peername", "", nullptr, "");
793 xbt_cfg_register_string("user", "", nullptr, "");
794 } /* end_of_make_set */
796 XBT_TEST_UNIT("memuse", test_config_memuse, "Alloc and free a config set")
798 auto temp = simgrid_config;
800 xbt_test_add("Alloc and free a config set");
801 xbt_cfg_set_parse("peername:veloce user:bidule");
802 xbt_cfg_free(&simgrid_config);
803 simgrid_config = temp;
806 XBT_TEST_UNIT("use", test_config_use, "Data retrieving tests")
808 auto temp = simgrid_config;
810 xbt_test_add("Get a single value");
812 /* get_single_value */
813 xbt_cfg_set_parse("peername:toto:42 speed:42");
814 int ival = xbt_cfg_get_int("speed");
816 xbt_test_fail("Speed value = %d, I expected 42", ival);
819 xbt_test_add("Access to a non-existant entry");
822 xbt_cfg_set_parse("color:blue");
824 if (e.category != not_found_error)
825 xbt_test_exception(e);
828 xbt_cfg_free(&simgrid_config);
829 simgrid_config = temp;
832 XBT_TEST_UNIT("c++flags", test_config_cxx_flags, "C++ flags")
834 auto temp = simgrid_config;
836 xbt_test_add("C++ declaration of flags");
838 simgrid::config::Flag<int> int_flag("int", "", 0);
839 simgrid::config::Flag<std::string> string_flag("string", "", "foo");
840 simgrid::config::Flag<double> double_flag("double", "", 0.32);
841 simgrid::config::Flag<bool> bool_flag1("bool1", "", false);
842 simgrid::config::Flag<bool> bool_flag2("bool2", "", true);
844 xbt_test_add("Parse values");
845 xbt_cfg_set_parse("int:42 string:bar double:8.0 bool1:true bool2:false");
846 xbt_test_assert(int_flag == 42, "Check int flag");
847 xbt_test_assert(string_flag == "bar", "Check string flag");
848 xbt_test_assert(double_flag == 8.0, "Check double flag");
849 xbt_test_assert(bool_flag1, "Check bool1 flag");
850 xbt_test_assert(not bool_flag2, "Check bool2 flag");
852 xbt_cfg_free(&simgrid_config);
853 simgrid_config = temp;
856 #endif /* SIMGRID_TEST */