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> 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 const& elm : options)
306 inline ConfigurationElement* Config::getDictElement(const char* name)
308 auto opt = options.find(name);
309 if (opt != options.end()) {
312 auto als = aliases.find(name);
313 if (als != aliases.end()) {
314 ConfigurationElement* res = als->second;
315 if (warn_for_aliases)
316 XBT_INFO("Option %s has been renamed to %s. Consider switching.", name, res->getKey().c_str());
319 throw simgrid::config::missing_key_error(std::string("Bad config key: ") + name);
324 inline ConfigurationElement& Config::operator[](const char* name)
326 return *(getDictElement(name));
329 void Config::alias(const char* realname, const char* aliasname)
331 xbt_assert(aliases.find(aliasname) == aliases.end(), "Alias '%s' already.", aliasname);
332 ConfigurationElement* element = this->getDictElement(realname);
333 xbt_assert(element, "Cannot define an alias to the non-existing option '%s'.", realname);
334 this->aliases.insert({aliasname, element});
337 /** @brief Dump a config set for debuging purpose
339 * @param name The name to give to this config set
340 * @param indent what to write at the beginning of each line (right number of spaces)
342 void Config::dump(const char *name, const char *indent)
345 printf("%s>> Dumping of the config set '%s':\n", indent, name);
347 for (auto const& elm : options)
348 printf("%s %s: ()%s) %s", indent, elm.first.c_str(), elm.second->getTypeName(),
349 elm.second->getStringValue().c_str());
352 printf("%s<< End of the config set '%s'\n", indent, name);
356 /** @brief Displays the declared aliases and their description */
357 void Config::showAliases()
359 bool old_warn_for_aliases = false;
360 std::swap(warn_for_aliases, old_warn_for_aliases);
361 for (auto const& elm : aliases)
362 printf(" %s: %s\n", elm.first.c_str(), (*this)[elm.first.c_str()].getDescription().c_str());
363 std::swap(warn_for_aliases, old_warn_for_aliases);
366 /** @brief Displays the declared options and their description */
369 for (auto const& elm : options) {
370 simgrid::config::ConfigurationElement* variable = this->options.at(elm.first);
371 printf(" %s: %s\n", elm.first.c_str(), variable->getDescription().c_str());
372 printf(" Type: %s; ", variable->getTypeName());
373 printf("Current value: %s\n", variable->getStringValue().c_str());
377 // ***** getConfig *****
380 XBT_PUBLIC(T const&) getConfig(const char* name)
382 return (*simgrid_config)[name].getValue<T>();
385 template XBT_PUBLIC(int const&) getConfig<int>(const char* name);
386 template XBT_PUBLIC(double const&) getConfig<double>(const char* name);
387 template XBT_PUBLIC(bool const&) getConfig<bool>(const char* name);
388 template XBT_PUBLIC(std::string const&) getConfig<std::string>(const char* name);
392 void alias(const char* realname, const char* aliasname)
394 simgrid_config->alias(realname, aliasname);
397 // ***** declareFlag *****
400 XBT_PUBLIC(void) declareFlag(const char* name, const char* description,
401 T value, std::function<void(const T&)> callback)
403 if (simgrid_config == nullptr) {
404 simgrid_config = xbt_cfg_new();
405 atexit(sg_config_finalize);
407 simgrid_config->registerOption<T>(
408 name, description, std::move(value), std::move(callback));
411 template XBT_PUBLIC(void) declareFlag(const char* name,
412 const char* description, int value, std::function<void(int const &)> callback);
413 template XBT_PUBLIC(void) declareFlag(const char* name,
414 const char* description, double value, std::function<void(double const &)> callback);
415 template XBT_PUBLIC(void) declareFlag(const char* name,
416 const char* description, bool value, std::function<void(bool const &)> callback);
417 template XBT_PUBLIC(void) declareFlag(const char* name,
418 const char* description, std::string value, std::function<void(std::string const &)> callback);
423 // ***** C bindings *****
425 xbt_cfg_t xbt_cfg_new() { return new simgrid::config::Config(); }
426 void xbt_cfg_free(xbt_cfg_t * cfg) { delete *cfg; }
428 void xbt_cfg_dump(const char *name, const char *indent, xbt_cfg_t cfg)
430 cfg->dump(name, indent);
433 /*----[ Registering stuff ]-----------------------------------------------*/
435 void xbt_cfg_register_double(const char *name, double default_value,
436 xbt_cfg_cb_t cb_set, const char *desc)
438 if (simgrid_config == nullptr)
439 simgrid_config = xbt_cfg_new();
440 simgrid_config->registerOption<double>(name, desc, default_value, cb_set);
443 void xbt_cfg_register_int(const char *name, int default_value,xbt_cfg_cb_t cb_set, const char *desc)
445 if (simgrid_config == nullptr) {
446 simgrid_config = xbt_cfg_new();
447 atexit(&sg_config_finalize);
449 simgrid_config->registerOption<int>(name, desc, default_value, cb_set);
452 void xbt_cfg_register_string(const char *name, const char *default_value, xbt_cfg_cb_t cb_set, const char *desc)
454 if (simgrid_config == nullptr) {
455 simgrid_config = xbt_cfg_new();
456 atexit(sg_config_finalize);
458 simgrid_config->registerOption<std::string>(name, desc,
459 default_value ? default_value : "", cb_set);
462 void xbt_cfg_register_boolean(const char *name, const char*default_value,xbt_cfg_cb_t cb_set, const char *desc)
464 if (simgrid_config == nullptr) {
465 simgrid_config = xbt_cfg_new();
466 atexit(sg_config_finalize);
468 simgrid_config->registerOption<bool>(name, desc, simgrid::config::parseBool(default_value), cb_set);
471 void xbt_cfg_register_alias(const char *realname, const char *aliasname)
473 if (simgrid_config == nullptr) {
474 simgrid_config = xbt_cfg_new();
475 atexit(sg_config_finalize);
477 simgrid_config->alias(realname, aliasname);
480 void xbt_cfg_aliases() { simgrid_config->showAliases(); }
481 void xbt_cfg_help() { simgrid_config->help(); }
483 /*----[ Setting ]---------------------------------------------------------*/
485 /** @brief Add values parsed from a string into a config set
487 * @param options a string containing the content to add to the config set. This is a '\\t',' ' or '\\n' or ','
488 * separated list of variables. Each individual variable is like "[name]:[value]" where [name] is the name of an
489 * already registered variable, and [value] conforms to the data type under which this variable was registered.
491 * @todo This is a crude manual parser, it should be a proper lexer.
493 void xbt_cfg_set_parse(const char *options)
495 if (not options || not strlen(options)) { /* nothing to do */
498 char *optionlist_cpy = xbt_strdup(options);
500 XBT_DEBUG("List to parse and set:'%s'", options);
501 char *option = optionlist_cpy;
502 while (1) { /* breaks in the code */
506 int len = strlen(name);
507 XBT_DEBUG("Still to parse and set: '%s'. len=%d; option-name=%ld", name, len, (long) (option - name));
510 while (option - name <= (len - 1) && *option != ' ' && *option != '\n' && *option != '\t' && *option != ',') {
511 XBT_DEBUG("Take %c.", *option);
514 if (option - name == len) {
515 XBT_DEBUG("Boundary=EOL");
516 option = nullptr; /* don't do next iteration */
518 XBT_DEBUG("Boundary on '%c'. len=%d;option-name=%ld", *option, len, (long) (option - name));
519 /* Pass the following blank chars */
521 while (option - name < (len - 1) && (*option == ' ' || *option == '\n' || *option == '\t')) {
524 if (option - name == len - 1)
525 option = nullptr; /* don't do next iteration */
527 XBT_DEBUG("parse now:'%s'; parse later:'%s'", name, option);
529 if (name[0] == ' ' || name[0] == '\n' || name[0] == '\t')
531 if (not strlen(name))
534 char *val = strchr(name, ':');
535 xbt_assert(val, "Option '%s' badly formatted. Should be of the form 'name:value'", name);
536 /* don't free(optionlist_cpy) if the assert fails, 'name' points inside it */
539 if (strncmp(name, "path", strlen("path")))
540 XBT_INFO("Configuration change: Set '%s' to '%s'", name, val);
543 (*simgrid_config)[name].setStringValue(val);
545 catch (simgrid::config::missing_key_error& e) {
553 free(optionlist_cpy);
556 /* Do not THROWF from a C++ exception catching context, or some cleanups will be missing */
558 free(optionlist_cpy);
559 THROWF(not_found_error, 0, "Could not set variables %s", options);
562 free(optionlist_cpy);
563 THROWF(unknown_error, 0, "Could not set variables %s", options);
566 // Horrible mess to translate C++ exceptions to C exceptions:
567 // Exit from the catch block (and do the correct exception cleaning) before attempting to THROWF.
568 #define TRANSLATE_EXCEPTIONS(...) \
569 catch(simgrid::config::missing_key_error& e) { THROWF(not_found_error, 0, __VA_ARGS__); abort(); } \
570 catch(...) { THROWF(not_found_error, 0, __VA_ARGS__); abort(); }
572 /** @brief Set the value of a variable, using the string representation of that value
574 * @param key name of the variable to modify
575 * @param value string representation of the value to set
578 void xbt_cfg_set_as_string(const char *key, const char *value)
581 (*simgrid_config)[key].setStringValue(value);
584 TRANSLATE_EXCEPTIONS("Could not set variable %s as string %s", key, value);
587 /** @brief Set an integer value to \a name within \a cfg if it wasn't changed yet
589 * This is useful to change the default value of a variable while allowing
590 * users to override it with command line arguments
592 void xbt_cfg_setdefault_int(const char *key, int value)
595 (*simgrid_config)[key].setDefaultValue<int>(value);
598 TRANSLATE_EXCEPTIONS("Could not set variable %s to default integer %i", key, value);
601 /** @brief Set an integer value to \a name within \a cfg if it wasn't changed yet
603 * This is useful to change the default value of a variable while allowing
604 * users to override it with command line arguments
606 void xbt_cfg_setdefault_double(const char *key, double value)
609 (*simgrid_config)[key].setDefaultValue<double>(value);
612 TRANSLATE_EXCEPTIONS("Could not set variable %s to default double %f", key, value);
615 /** @brief Set a string value to \a name within \a cfg if it wasn't changed yet
617 * This is useful to change the default value of a variable while allowing
618 * users to override it with command line arguments
620 void xbt_cfg_setdefault_string(const char *key, const char *value)
623 (*simgrid_config)[key].setDefaultValue<std::string>(value ? value : "");
626 TRANSLATE_EXCEPTIONS("Could not set variable %s to default string %s", key, value);
629 /** @brief Set an boolean value to \a name within \a cfg if it wasn't changed yet
631 * This is useful to change the default value of a variable while allowing
632 * users to override it with command line arguments
634 void xbt_cfg_setdefault_boolean(const char *key, const char *value)
637 (*simgrid_config)[key].setDefaultValue<bool>(simgrid::config::parseBool(value));
640 TRANSLATE_EXCEPTIONS("Could not set variable %s to default boolean %s", key, value);
643 /** @brief Set an integer value to \a name within \a cfg
645 * @param key the name of the variable
646 * @param value the value of the variable
648 void xbt_cfg_set_int(const char *key, int value)
651 (*simgrid_config)[key].setValue<int>(value);
654 TRANSLATE_EXCEPTIONS("Could not set variable %s to integer %i", key, value);
657 /** @brief Set or add a double value to \a name within \a cfg
659 * @param key the name of the variable
660 * @param value the double to set
662 void xbt_cfg_set_double(const char *key, double value)
665 (*simgrid_config)[key].setValue<double>(value);
668 TRANSLATE_EXCEPTIONS("Could not set variable %s to double %f", key, value);
671 /** @brief Set or add a string value to \a name within \a cfg
673 * @param key the name of the variable
674 * @param value the value to be added
677 void xbt_cfg_set_string(const char *key, const char *value)
680 (*simgrid_config)[key].setValue<std::string>(value ? value : "");
683 TRANSLATE_EXCEPTIONS("Could not set variable %s to string %s", key, value);
686 /** @brief Set or add a boolean value to \a name within \a cfg
688 * @param key the name of the variable
689 * @param value the value of the variable
691 void xbt_cfg_set_boolean(const char *key, const char *value)
694 (*simgrid_config)[key].setValue<bool>(simgrid::config::parseBool(value));
697 TRANSLATE_EXCEPTIONS("Could not set variable %s to boolean %s", key, value);
701 /* Say if the value is the default value */
702 int xbt_cfg_is_default_value(const char *key)
705 return (*simgrid_config)[key].isDefault() ? 1 : 0;
707 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
710 /*----[ Getting ]---------------------------------------------------------*/
711 /** @brief Retrieve an integer value of a variable (get a warning if not uniq)
713 * @param key the name of the variable
715 * Returns the first value from the config set under the given name.
717 int xbt_cfg_get_int(const char *key)
720 return (*simgrid_config)[key].getValue<int>();
722 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
725 /** @brief Retrieve a double value of a variable (get a warning if not uniq)
727 * @param key the name of the variable
729 * Returns the first value from the config set under the given name.
731 double xbt_cfg_get_double(const char *key)
734 return (*simgrid_config)[key].getValue<double>();
736 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
739 /** @brief Retrieve a string 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.
745 * Returns nullptr if there is no value.
747 * \warning the returned value is the actual content of the config set
749 char *xbt_cfg_get_string(const char *key)
752 return (char*) (*simgrid_config)[key].getValue<std::string>().c_str();
754 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
757 /** @brief Retrieve a boolean value of a variable (get a warning if not uniq)
759 * @param key the name of the variable
761 * Returns the first value from the config set under the given name.
762 * If there is more than one value, it will issue a warning.
764 int xbt_cfg_get_boolean(const char *key)
767 return (*simgrid_config)[key].getValue<bool>() ? 1 : 0;
769 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
778 #include <xbt/ex.hpp>
780 #include <xbt/config.hpp>
782 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(xbt_cfg);
784 XBT_TEST_SUITE("config", "Configuration support");
786 XBT_PUBLIC_DATA(xbt_cfg_t) simgrid_config;
788 static void make_set()
790 simgrid_config = nullptr;
791 xbt_log_threshold_set(&_XBT_LOGV(xbt_cfg), xbt_log_priority_critical);
792 xbt_cfg_register_int("speed", 0, nullptr, "");
793 xbt_cfg_register_string("peername", "", nullptr, "");
794 xbt_cfg_register_string("user", "", nullptr, "");
795 } /* end_of_make_set */
797 XBT_TEST_UNIT("memuse", test_config_memuse, "Alloc and free a config set")
799 auto temp = simgrid_config;
801 xbt_test_add("Alloc and free a config set");
802 xbt_cfg_set_parse("peername:veloce user:bidule");
803 xbt_cfg_free(&simgrid_config);
804 simgrid_config = temp;
807 XBT_TEST_UNIT("use", test_config_use, "Data retrieving tests")
809 auto temp = simgrid_config;
811 xbt_test_add("Get a single value");
813 /* get_single_value */
814 xbt_cfg_set_parse("peername:toto:42 speed:42");
815 int ival = xbt_cfg_get_int("speed");
817 xbt_test_fail("Speed value = %d, I expected 42", ival);
820 xbt_test_add("Access to a non-existant entry");
823 xbt_cfg_set_parse("color:blue");
825 if (e.category != not_found_error)
826 xbt_test_exception(e);
829 xbt_cfg_free(&simgrid_config);
830 simgrid_config = temp;
833 XBT_TEST_UNIT("c++flags", test_config_cxx_flags, "C++ flags")
835 auto temp = simgrid_config;
837 xbt_test_add("C++ declaration of flags");
839 simgrid::config::Flag<int> int_flag("int", "", 0);
840 simgrid::config::Flag<std::string> string_flag("string", "", "foo");
841 simgrid::config::Flag<double> double_flag("double", "", 0.32);
842 simgrid::config::Flag<bool> bool_flag1("bool1", "", false);
843 simgrid::config::Flag<bool> bool_flag2("bool2", "", true);
845 xbt_test_add("Parse values");
846 xbt_cfg_set_parse("int:42 string:bar double:8.0 bool1:true bool2:false");
847 xbt_test_assert(int_flag == 42, "Check int flag");
848 xbt_test_assert(string_flag == "bar", "Check string flag");
849 xbt_test_assert(double_flag == 8.0, "Check double flag");
850 xbt_test_assert(bool_flag1, "Check bool1 flag");
851 xbt_test_assert(not bool_flag2, "Check bool2 flag");
853 xbt_cfg_free(&simgrid_config);
854 simgrid_config = temp;
857 #endif /* SIMGRID_TEST */