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)
151 : key(key ? key : ""), desc(desc ? desc : "") {}
152 ConfigurationElement(const char* key, const char* desc, xbt_cfg_cb_t cb)
153 : key(key ? key : ""), desc(desc ? desc : ""), old_callback(cb) {}
155 virtual ~ConfigurationElement()=default;
157 virtual std::string getStringValue() = 0;
158 virtual void setStringValue(const char* value) = 0;
159 virtual const char* getTypeName() = 0;
162 T const& getValue() const
164 return dynamic_cast<const TypedConfigurationElement<T>&>(*this).getValue();
167 void setValue(T value)
169 dynamic_cast<TypedConfigurationElement<T>&>(*this).setValue(std::move(value));
172 void setDefaultValue(T value)
174 dynamic_cast<TypedConfigurationElement<T>&>(*this).setDefaultValue(std::move(value));
176 void unsetDefault() { isdefault = false; }
177 bool isDefault() const { return isdefault; }
179 std::string const& getDescription() const { return desc; }
180 std::string const& getKey() const { return key; }
183 // **** TypedConfigurationElement<T> ****
185 // TODO, could we use boost::any with some Type* reference?
187 class TypedConfigurationElement : public ConfigurationElement {
190 std::function<void(T&)> callback;
193 TypedConfigurationElement(const char* key, const char* desc, T value = T())
194 : ConfigurationElement(key, desc), content(std::move(value))
196 TypedConfigurationElement(const char* key, const char* desc, T value, xbt_cfg_cb_t cb)
197 : ConfigurationElement(key, desc, cb), content(std::move(value))
199 TypedConfigurationElement(const char* key, const char* desc, T value, std::function<void(T&)> callback)
200 : ConfigurationElement(key, desc), content(std::move(value)), callback(std::move(callback))
202 ~TypedConfigurationElement() = default;
204 std::string getStringValue() override;
205 const char* getTypeName() override;
206 void setStringValue(const char* value) override;
211 this->old_callback(getKey().c_str());
213 this->callback(this->content);
216 T const& getValue() const { return content; }
218 void setValue(T value)
220 this->content = std::move(value);
224 void setDefaultValue(T value)
226 if (this->isDefault()) {
227 this->content = std::move(value);
230 XBT_DEBUG("Do not override configuration variable '%s' with value '%s' because it was already set.",
231 getKey().c_str(), to_string(value).c_str());
237 std::string TypedConfigurationElement<T>::getStringValue() // override
239 return to_string(content);
243 void TypedConfigurationElement<T>::setStringValue(const char* value) // override
245 this->content = ConfigType<T>::parse(value);
246 this->unsetDefault();
251 const char* TypedConfigurationElement<T>::getTypeName() // override
253 return ConfigType<T>::type_name;
256 } // end of anonymous namespace
262 // name -> ConfigElement:
263 std::map<std::string, simgrid::config::ConfigurationElement*> options;
264 // alias -> xbt_dict_elm_t from options:
265 std::map<std::string, simgrid::config::ConfigurationElement*> aliases;
266 bool warn_for_aliases = true;
273 Config(Config const&) = delete;
274 Config& operator=(Config const&) = delete;
276 ConfigurationElement& operator[](const char* name);
278 TypedConfigurationElement<T>& getTyped(const char* name);
279 void alias(const char* realname, const char* aliasname);
281 template<class T, class... A>
282 simgrid::config::TypedConfigurationElement<T>*
283 registerOption(const char* name, A&&... a)
285 xbt_assert(options.find(name) == options.end(), "Refusing to register the config element '%s' twice.", name);
286 TypedConfigurationElement<T>* variable = new TypedConfigurationElement<T>(name, std::forward<A>(a)...);
287 XBT_DEBUG("Register cfg elm %s (%s) of type %s @%p in set %p)", name, variable->getDescription().c_str(),
288 variable->getTypeName(), variable, this);
289 options.insert({name, variable});
295 void dump(const char *name, const char *indent);
300 ConfigurationElement* getDictElement(const char* name);
305 XBT_DEBUG("Frees cfg set %p", this);
306 for (auto const& elm : options)
310 inline ConfigurationElement* Config::getDictElement(const char* name)
312 auto opt = options.find(name);
313 if (opt != options.end()) {
316 auto als = aliases.find(name);
317 if (als != aliases.end()) {
318 ConfigurationElement* res = als->second;
319 if (warn_for_aliases)
320 XBT_INFO("Option %s has been renamed to %s. Consider switching.", name, res->getKey().c_str());
323 throw simgrid::config::missing_key_error(std::string("Bad config key: ") + name);
328 inline ConfigurationElement& Config::operator[](const char* name)
330 return *(getDictElement(name));
333 void Config::alias(const char* realname, const char* aliasname)
335 xbt_assert(aliases.find(aliasname) == aliases.end(), "Alias '%s' already.", aliasname);
336 ConfigurationElement* element = this->getDictElement(realname);
337 xbt_assert(element, "Cannot define an alias to the non-existing option '%s'.", realname);
338 this->aliases.insert({aliasname, element});
341 /** @brief Dump a config set for debuging purpose
343 * @param name The name to give to this config set
344 * @param indent what to write at the beginning of each line (right number of spaces)
346 void Config::dump(const char *name, const char *indent)
349 printf("%s>> Dumping of the config set '%s':\n", indent, name);
351 for (auto const& elm : options)
352 printf("%s %s: ()%s) %s", indent, elm.first.c_str(), elm.second->getTypeName(),
353 elm.second->getStringValue().c_str());
356 printf("%s<< End of the config set '%s'\n", indent, name);
360 /** @brief Displays the declared aliases and their description */
361 void Config::showAliases()
363 bool old_warn_for_aliases = false;
364 std::swap(warn_for_aliases, old_warn_for_aliases);
365 for (auto const& elm : aliases)
366 printf(" %s: %s\n", elm.first.c_str(), (*this)[elm.first.c_str()].getDescription().c_str());
367 std::swap(warn_for_aliases, old_warn_for_aliases);
370 /** @brief Displays the declared options and their description */
373 for (auto const& elm : options) {
374 simgrid::config::ConfigurationElement* variable = this->options.at(elm.first);
375 printf(" %s: %s\n", elm.first.c_str(), variable->getDescription().c_str());
376 printf(" Type: %s; ", variable->getTypeName());
377 printf("Current value: %s\n", variable->getStringValue().c_str());
381 // ***** getConfig *****
384 XBT_PUBLIC(T const&) getConfig(const char* name)
386 return (*simgrid_config)[name].getValue<T>();
389 template XBT_PUBLIC(int const&) getConfig<int>(const char* name);
390 template XBT_PUBLIC(double const&) getConfig<double>(const char* name);
391 template XBT_PUBLIC(bool const&) getConfig<bool>(const char* name);
392 template XBT_PUBLIC(std::string const&) getConfig<std::string>(const char* name);
396 void alias(const char* realname, const char* aliasname)
398 simgrid_config->alias(realname, aliasname);
401 // ***** declareFlag *****
404 XBT_PUBLIC(void) declareFlag(const char* name, const char* description,
405 T value, std::function<void(const T&)> callback)
407 if (simgrid_config == nullptr) {
408 simgrid_config = xbt_cfg_new();
409 atexit(sg_config_finalize);
411 simgrid_config->registerOption<T>(
412 name, description, std::move(value), std::move(callback));
415 template XBT_PUBLIC(void) declareFlag(const char* name,
416 const char* description, int value, std::function<void(int const &)> callback);
417 template XBT_PUBLIC(void) declareFlag(const char* name,
418 const char* description, double value, std::function<void(double const &)> callback);
419 template XBT_PUBLIC(void) declareFlag(const char* name,
420 const char* description, bool value, std::function<void(bool const &)> callback);
421 template XBT_PUBLIC(void) declareFlag(const char* name,
422 const char* description, std::string value, std::function<void(std::string const &)> callback);
427 // ***** C bindings *****
429 xbt_cfg_t xbt_cfg_new() { return new simgrid::config::Config(); }
430 void xbt_cfg_free(xbt_cfg_t * cfg) { delete *cfg; }
432 void xbt_cfg_dump(const char *name, const char *indent, xbt_cfg_t cfg)
434 cfg->dump(name, indent);
437 /*----[ Registering stuff ]-----------------------------------------------*/
439 void xbt_cfg_register_double(const char *name, double default_value,
440 xbt_cfg_cb_t cb_set, const char *desc)
442 if (simgrid_config == nullptr)
443 simgrid_config = xbt_cfg_new();
444 simgrid_config->registerOption<double>(name, desc, default_value, cb_set);
447 void xbt_cfg_register_int(const char *name, int default_value,xbt_cfg_cb_t cb_set, const char *desc)
449 if (simgrid_config == nullptr) {
450 simgrid_config = xbt_cfg_new();
451 atexit(&sg_config_finalize);
453 simgrid_config->registerOption<int>(name, desc, default_value, cb_set);
456 void xbt_cfg_register_string(const char *name, const char *default_value, xbt_cfg_cb_t cb_set, const char *desc)
458 if (simgrid_config == nullptr) {
459 simgrid_config = xbt_cfg_new();
460 atexit(sg_config_finalize);
462 simgrid_config->registerOption<std::string>(name, desc, default_value ? default_value : "", cb_set);
465 void xbt_cfg_register_boolean(const char *name, const char*default_value,xbt_cfg_cb_t cb_set, const char *desc)
467 if (simgrid_config == nullptr) {
468 simgrid_config = xbt_cfg_new();
469 atexit(sg_config_finalize);
471 simgrid_config->registerOption<bool>(name, desc, simgrid::config::parseBool(default_value), cb_set);
474 void xbt_cfg_register_alias(const char *realname, const char *aliasname)
476 if (simgrid_config == nullptr) {
477 simgrid_config = xbt_cfg_new();
478 atexit(sg_config_finalize);
480 simgrid_config->alias(realname, aliasname);
483 void xbt_cfg_aliases() { simgrid_config->showAliases(); }
484 void xbt_cfg_help() { simgrid_config->help(); }
486 /*----[ Setting ]---------------------------------------------------------*/
488 /** @brief Add values parsed from a string into a config set
490 * @param options a string containing the content to add to the config set. This is a '\\t',' ' or '\\n' or ','
491 * separated list of variables. Each individual variable is like "[name]:[value]" where [name] is the name of an
492 * already registered variable, and [value] conforms to the data type under which this variable was registered.
494 * @todo This is a crude manual parser, it should be a proper lexer.
496 void xbt_cfg_set_parse(const char *options)
498 if (not options || not strlen(options)) { /* nothing to do */
502 XBT_DEBUG("List to parse and set:'%s'", options);
503 std::string optionlist(options);
504 while (not optionlist.empty()) {
505 XBT_DEBUG("Still to parse and set: '%s'", optionlist.c_str());
508 size_t pos = optionlist.find_first_not_of(" \t\n,");
509 optionlist.erase(0, pos);
511 pos = optionlist.find_first_of(" \t\n,");
512 std::string name = optionlist.substr(0, pos);
513 optionlist.erase(0, pos);
514 XBT_DEBUG("parse now:'%s'; parse later:'%s'", name.c_str(), optionlist.c_str());
519 pos = name.find(':');
520 xbt_assert(pos != std::string::npos, "Option '%s' badly formatted. Should be of the form 'name:value'",
523 std::string val = name.substr(pos + 1);
526 const std::string path("path");
527 if (name.compare(0, path.length(), path) != 0)
528 XBT_INFO("Configuration change: Set '%s' to '%s'", name.c_str(), val.c_str());
531 (*simgrid_config)[name.c_str()].setStringValue(val.c_str());
533 catch (simgrid::config::missing_key_error& e) {
542 /* Do not THROWF from a C++ exception catching context, or some cleanups will be missing */
544 THROWF(not_found_error, 0, "Could not set variables %s", options);
546 THROWF(unknown_error, 0, "Could not set variables %s", options);
549 // Horrible mess to translate C++ exceptions to C exceptions:
550 // Exit from the catch block (and do the correct exception cleaning) before attempting to THROWF.
551 #define TRANSLATE_EXCEPTIONS(...) \
552 catch(simgrid::config::missing_key_error& e) { THROWF(not_found_error, 0, __VA_ARGS__); abort(); } \
553 catch(...) { THROWF(not_found_error, 0, __VA_ARGS__); abort(); }
555 /** @brief Set the value of a variable, using the string representation of that value
557 * @param key name of the variable to modify
558 * @param value string representation of the value to set
561 void xbt_cfg_set_as_string(const char *key, const char *value)
564 (*simgrid_config)[key].setStringValue(value);
567 TRANSLATE_EXCEPTIONS("Could not set variable %s as string %s", key, value);
570 /** @brief Set an integer value to \a name within \a cfg if it wasn't changed yet
572 * This is useful to change the default value of a variable while allowing
573 * users to override it with command line arguments
575 void xbt_cfg_setdefault_int(const char *key, int value)
578 (*simgrid_config)[key].setDefaultValue<int>(value);
581 TRANSLATE_EXCEPTIONS("Could not set variable %s to default integer %i", key, value);
584 /** @brief Set an integer value to \a name within \a cfg if it wasn't changed yet
586 * This is useful to change the default value of a variable while allowing
587 * users to override it with command line arguments
589 void xbt_cfg_setdefault_double(const char *key, double value)
592 (*simgrid_config)[key].setDefaultValue<double>(value);
595 TRANSLATE_EXCEPTIONS("Could not set variable %s to default double %f", key, value);
598 /** @brief Set a string value to \a name within \a cfg if it wasn't changed yet
600 * This is useful to change the default value of a variable while allowing
601 * users to override it with command line arguments
603 void xbt_cfg_setdefault_string(const char *key, const char *value)
606 (*simgrid_config)[key].setDefaultValue<std::string>(value ? value : "");
609 TRANSLATE_EXCEPTIONS("Could not set variable %s to default string %s", key, value);
612 /** @brief Set an boolean value to \a name within \a cfg if it wasn't changed yet
614 * This is useful to change the default value of a variable while allowing
615 * users to override it with command line arguments
617 void xbt_cfg_setdefault_boolean(const char *key, const char *value)
620 (*simgrid_config)[key].setDefaultValue<bool>(simgrid::config::parseBool(value));
623 TRANSLATE_EXCEPTIONS("Could not set variable %s to default boolean %s", key, value);
626 /** @brief Set an integer value to \a name within \a cfg
628 * @param key the name of the variable
629 * @param value the value of the variable
631 void xbt_cfg_set_int(const char *key, int value)
634 (*simgrid_config)[key].setValue<int>(value);
637 TRANSLATE_EXCEPTIONS("Could not set variable %s to integer %i", key, value);
640 /** @brief Set or add a double value to \a name within \a cfg
642 * @param key the name of the variable
643 * @param value the double to set
645 void xbt_cfg_set_double(const char *key, double value)
648 (*simgrid_config)[key].setValue<double>(value);
651 TRANSLATE_EXCEPTIONS("Could not set variable %s to double %f", key, value);
654 /** @brief Set or add a string value to \a name within \a cfg
656 * @param key the name of the variable
657 * @param value the value to be added
660 void xbt_cfg_set_string(const char* key, std::string value)
663 (*simgrid_config)[key].setValue<std::string>(value);
666 TRANSLATE_EXCEPTIONS("Could not set variable %s to string %s", key, value.c_str());
669 /** @brief Set or add a boolean value to \a name within \a cfg
671 * @param key the name of the variable
672 * @param value the value of the variable
674 void xbt_cfg_set_boolean(const char *key, const char *value)
677 (*simgrid_config)[key].setValue<bool>(simgrid::config::parseBool(value));
680 TRANSLATE_EXCEPTIONS("Could not set variable %s to boolean %s", key, value);
684 /* Say if the value is the default value */
685 int xbt_cfg_is_default_value(const char *key)
688 return (*simgrid_config)[key].isDefault() ? 1 : 0;
690 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
693 /*----[ Getting ]---------------------------------------------------------*/
694 /** @brief Retrieve an integer value of a variable (get a warning if not uniq)
696 * @param key the name of the variable
698 * Returns the first value from the config set under the given name.
700 int xbt_cfg_get_int(const char *key)
703 return (*simgrid_config)[key].getValue<int>();
705 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
708 /** @brief Retrieve a double value of a variable (get a warning if not uniq)
710 * @param key the name of the variable
712 * Returns the first value from the config set under the given name.
714 double xbt_cfg_get_double(const char *key)
717 return (*simgrid_config)[key].getValue<double>();
719 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
722 /** @brief Retrieve a string value of a variable (get a warning if not uniq)
724 * @param key the name of the variable
726 * Returns the first value from the config set under the given name.
727 * If there is more than one value, it will issue a warning.
728 * Returns nullptr if there is no value.
730 * \warning the returned value is the actual content of the config set
732 std::string xbt_cfg_get_string(const char* key)
735 return (*simgrid_config)[key].getValue<std::string>();
737 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
740 /** @brief Retrieve a boolean value of a variable (get a warning if not uniq)
742 * @param key the name of the variable
744 * Returns the first value from the config set under the given name.
745 * If there is more than one value, it will issue a warning.
747 int xbt_cfg_get_boolean(const char *key)
750 return (*simgrid_config)[key].getValue<bool>() ? 1 : 0;
752 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
761 #include <xbt/ex.hpp>
763 #include <xbt/config.hpp>
765 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(xbt_cfg);
767 XBT_TEST_SUITE("config", "Configuration support");
769 XBT_PUBLIC_DATA(xbt_cfg_t) simgrid_config;
771 static void make_set()
773 simgrid_config = nullptr;
774 xbt_log_threshold_set(&_XBT_LOGV(xbt_cfg), xbt_log_priority_critical);
775 xbt_cfg_register_int("speed", 0, nullptr, "");
776 xbt_cfg_register_string("peername", "", nullptr, "");
777 xbt_cfg_register_string("user", "", nullptr, "");
778 } /* end_of_make_set */
780 XBT_TEST_UNIT("memuse", test_config_memuse, "Alloc and free a config set")
782 auto temp = simgrid_config;
784 xbt_test_add("Alloc and free a config set");
785 xbt_cfg_set_parse("peername:veloce user:bidule");
786 xbt_cfg_free(&simgrid_config);
787 simgrid_config = temp;
790 XBT_TEST_UNIT("use", test_config_use, "Data retrieving tests")
792 auto temp = simgrid_config;
794 xbt_test_add("Get a single value");
796 /* get_single_value */
797 xbt_cfg_set_parse("peername:toto:42 speed:42");
798 int ival = xbt_cfg_get_int("speed");
800 xbt_test_fail("Speed value = %d, I expected 42", ival);
803 xbt_test_add("Access to a non-existant entry");
806 xbt_cfg_set_parse("color:blue");
808 if (e.category != not_found_error)
809 xbt_test_exception(e);
812 xbt_cfg_free(&simgrid_config);
813 simgrid_config = temp;
816 XBT_TEST_UNIT("c++flags", test_config_cxx_flags, "C++ flags")
818 auto temp = simgrid_config;
820 xbt_test_add("C++ declaration of flags");
822 simgrid::config::Flag<int> int_flag("int", "", 0);
823 simgrid::config::Flag<std::string> string_flag("string", "", "foo");
824 simgrid::config::Flag<double> double_flag("double", "", 0.32);
825 simgrid::config::Flag<bool> bool_flag1("bool1", "", false);
826 simgrid::config::Flag<bool> bool_flag2("bool2", "", true);
828 xbt_test_add("Parse values");
829 xbt_cfg_set_parse("int:42 string:bar double:8.0 bool1:true bool2:false");
830 xbt_test_assert(int_flag == 42, "Check int flag");
831 xbt_test_assert(string_flag == "bar", "Check string flag");
832 xbt_test_assert(double_flag == 8.0, "Check double flag");
833 xbt_test_assert(bool_flag1, "Check bool1 flag");
834 xbt_test_assert(not bool_flag2, "Check bool2 flag");
836 xbt_cfg_free(&simgrid_config);
837 simgrid_config = temp;
840 #endif /* SIMGRID_TEST */