1 /* Copyright (c) 2004-2018. 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;
33 extern "C" XBT_PUBLIC void sg_config_finalize();
38 missing_key_error::~missing_key_error() = default;
42 const char* true_values[] = {
43 "yes", "on", "true", "1"
45 const char* false_values[] = {
46 "no", "off", "false", "0"
49 static bool parseBool(const char* value)
51 for (const char* const& true_value : true_values)
52 if (std::strcmp(true_value, value) == 0)
54 for (const char* const& false_value : false_values)
55 if (std::strcmp(false_value, value) == 0)
57 throw std::range_error("not a boolean");
60 static double parseDouble(const char* value)
64 double res = std::strtod(value, &end);
66 throw std::range_error("out of range");
68 xbt_die("Unexpected errno");
69 if (end == value || *end != '\0')
70 throw std::range_error("invalid double");
75 static long int parseLong(const char* value)
79 long int res = std::strtol(value, &end, 0);
81 if (res == LONG_MIN && errno == ERANGE)
82 throw std::range_error("underflow");
83 else if (res == LONG_MAX && errno == ERANGE)
84 throw std::range_error("overflow");
85 xbt_die("Unexpected errno");
87 if (end == value || *end != '\0')
88 throw std::range_error("invalid integer");
93 // ***** ConfigType *****
95 /// A trait which define possible options types:
96 template <class T> class ConfigType;
98 template <> class ConfigType<int> {
100 static constexpr const char* type_name = "int";
101 static inline double parse(const char* value)
103 return parseLong(value);
106 template <> class ConfigType<double> {
108 static constexpr const char* type_name = "double";
109 static inline double parse(const char* value)
111 return parseDouble(value);
114 template <> class 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 <> class ConfigType<bool> {
124 static constexpr const char* type_name = "boolean";
125 static inline bool parse(const char* value)
127 return parseBool(value);
131 // **** Forward declarations ****
133 class ConfigurationElement ;
134 template<class T> class TypedConfigurationElement;
136 // **** ConfigurationElement ****
138 class ConfigurationElement {
142 bool isdefault = true;
146 xbt_cfg_cb_t old_callback = nullptr;
148 ConfigurationElement(const char* key, const char* desc) : 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 void unsetDefault() { isdefault = false; }
174 bool isDefault() const { return isdefault; }
176 std::string const& getDescription() const { return desc; }
177 std::string const& getKey() const { return key; }
180 // **** TypedConfigurationElement<T> ****
182 // TODO, could we use boost::any with some Type* reference?
184 class TypedConfigurationElement : public ConfigurationElement {
187 std::function<void(T&)> callback;
190 TypedConfigurationElement(const char* key, const char* desc, T value = T())
191 : ConfigurationElement(key, desc), content(std::move(value))
193 TypedConfigurationElement(const char* key, const char* desc, T value, xbt_cfg_cb_t cb)
194 : ConfigurationElement(key, desc, cb), content(std::move(value))
196 TypedConfigurationElement(const char* key, const char* desc, T value, std::function<void(T&)> callback)
197 : ConfigurationElement(key, desc), content(std::move(value)), callback(std::move(callback))
199 ~TypedConfigurationElement() = default;
201 std::string getStringValue() override;
202 const char* getTypeName() override;
203 void setStringValue(const char* value) override;
208 this->old_callback(getKey().c_str());
210 this->callback(this->content);
213 T const& getValue() const { return content; }
215 void setValue(T value)
217 this->content = std::move(value);
221 void setDefaultValue(T value)
223 if (this->isDefault()) {
224 this->content = std::move(value);
227 XBT_DEBUG("Do not override configuration variable '%s' with value '%s' because it was already set.",
228 getKey().c_str(), to_string(value).c_str());
234 std::string TypedConfigurationElement<T>::getStringValue() // override
236 return to_string(content);
240 void TypedConfigurationElement<T>::setStringValue(const char* value) // override
242 this->content = ConfigType<T>::parse(value);
243 this->unsetDefault();
248 const char* TypedConfigurationElement<T>::getTypeName() // override
250 return ConfigType<T>::type_name;
253 } // end of anonymous namespace
259 // name -> ConfigElement:
260 std::map<std::string, simgrid::config::ConfigurationElement*> options;
261 // alias -> ConfigElement from options:
262 std::map<std::string, simgrid::config::ConfigurationElement*> aliases;
263 bool warn_for_aliases = true;
270 Config(Config const&) = delete;
271 Config& operator=(Config const&) = delete;
273 ConfigurationElement& operator[](const char* name);
275 TypedConfigurationElement<T>& getTyped(const char* name);
276 void alias(const char* realname, const char* aliasname);
278 template<class T, class... A>
279 simgrid::config::TypedConfigurationElement<T>*
280 registerOption(const char* name, A&&... a)
282 xbt_assert(options.find(name) == options.end(), "Refusing to register the config element '%s' twice.", name);
283 TypedConfigurationElement<T>* variable = new TypedConfigurationElement<T>(name, std::forward<A>(a)...);
284 XBT_DEBUG("Register cfg elm %s (%s) of type %s @%p in set %p)", name, variable->getDescription().c_str(),
285 variable->getTypeName(), variable, this);
286 options.insert({name, variable});
292 void dump(const char *name, const char *indent);
297 ConfigurationElement* getDictElement(const char* name);
302 XBT_DEBUG("Frees cfg set %p", this);
303 for (auto const& elm : options)
307 inline ConfigurationElement* Config::getDictElement(const char* name)
309 auto opt = options.find(name);
310 if (opt != options.end()) {
313 auto als = aliases.find(name);
314 if (als != aliases.end()) {
315 ConfigurationElement* res = als->second;
316 if (warn_for_aliases)
317 XBT_INFO("Option %s has been renamed to %s. Consider switching.", name, res->getKey().c_str());
320 throw simgrid::config::missing_key_error(std::string("Bad config key: ") + name);
325 inline ConfigurationElement& Config::operator[](const char* name)
327 return *(getDictElement(name));
330 void Config::alias(const char* realname, const char* aliasname)
332 xbt_assert(aliases.find(aliasname) == aliases.end(), "Alias '%s' already.", aliasname);
333 ConfigurationElement* element = this->getDictElement(realname);
334 xbt_assert(element, "Cannot define an alias to the non-existing option '%s'.", realname);
335 this->aliases.insert({aliasname, element});
338 /** @brief Dump a config set for debuging purpose
340 * @param name The name to give to this config set
341 * @param indent what to write at the beginning of each line (right number of spaces)
343 void Config::dump(const char *name, const char *indent)
346 printf("%s>> Dumping of the config set '%s':\n", indent, name);
348 for (auto const& elm : options)
349 printf("%s %s: ()%s) %s", indent, elm.first.c_str(), elm.second->getTypeName(),
350 elm.second->getStringValue().c_str());
353 printf("%s<< End of the config set '%s'\n", indent, name);
357 /** @brief Displays the declared aliases and their description */
358 void Config::showAliases()
360 bool old_warn_for_aliases = false;
361 std::swap(warn_for_aliases, old_warn_for_aliases);
362 for (auto const& elm : aliases)
363 printf(" %s: %s\n", elm.first.c_str(), (*this)[elm.first.c_str()].getDescription().c_str());
364 std::swap(warn_for_aliases, old_warn_for_aliases);
367 /** @brief Displays the declared options and their description */
370 for (auto const& elm : options) {
371 simgrid::config::ConfigurationElement* variable = this->options.at(elm.first);
372 printf(" %s: %s\n", elm.first.c_str(), variable->getDescription().c_str());
373 printf(" Type: %s; ", variable->getTypeName());
374 printf("Current value: %s\n", variable->getStringValue().c_str());
378 // ***** getConfig *****
380 template <class T> 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, T value, std::function<void(const T&)> callback)
402 if (simgrid_config == nullptr) {
403 simgrid_config = xbt_cfg_new();
404 atexit(sg_config_finalize);
406 simgrid_config->registerOption<T>(
407 name, description, std::move(value), std::move(callback));
410 template XBT_PUBLIC void declareFlag(const char* name, const char* description, int value,
411 std::function<void(int const&)> callback);
412 template XBT_PUBLIC void declareFlag(const char* name, const char* description, double value,
413 std::function<void(double const&)> callback);
414 template XBT_PUBLIC void declareFlag(const char* name, const char* description, bool value,
415 std::function<void(bool const&)> callback);
416 template XBT_PUBLIC void declareFlag(const char* name, const char* description, std::string value,
417 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, default_value ? default_value : "", cb_set);
459 void xbt_cfg_register_boolean(const char *name, const char*default_value,xbt_cfg_cb_t cb_set, const char *desc)
461 if (simgrid_config == nullptr) {
462 simgrid_config = xbt_cfg_new();
463 atexit(sg_config_finalize);
465 simgrid_config->registerOption<bool>(name, desc, simgrid::config::parseBool(default_value), cb_set);
468 void xbt_cfg_register_alias(const char *realname, const char *aliasname)
470 if (simgrid_config == nullptr) {
471 simgrid_config = xbt_cfg_new();
472 atexit(sg_config_finalize);
474 simgrid_config->alias(realname, aliasname);
477 void xbt_cfg_aliases() { simgrid_config->showAliases(); }
478 void xbt_cfg_help() { simgrid_config->help(); }
480 /*----[ Setting ]---------------------------------------------------------*/
482 /** @brief Add values parsed from a string into a config set
484 * @param options a string containing the content to add to the config set. This is a '\\t',' ' or '\\n' or ','
485 * separated list of variables. Each individual variable is like "[name]:[value]" where [name] is the name of an
486 * already registered variable, and [value] conforms to the data type under which this variable was registered.
488 * @todo This is a crude manual parser, it should be a proper lexer.
490 void xbt_cfg_set_parse(const char *options)
492 if (not options || not strlen(options)) { /* nothing to do */
496 XBT_DEBUG("List to parse and set:'%s'", options);
497 std::string optionlist(options);
498 while (not optionlist.empty()) {
499 XBT_DEBUG("Still to parse and set: '%s'", optionlist.c_str());
502 size_t pos = optionlist.find_first_not_of(" \t\n,");
503 optionlist.erase(0, pos);
505 pos = optionlist.find_first_of(" \t\n,");
506 std::string name = optionlist.substr(0, pos);
507 optionlist.erase(0, pos);
508 XBT_DEBUG("parse now:'%s'; parse later:'%s'", name.c_str(), optionlist.c_str());
513 pos = name.find(':');
514 xbt_assert(pos != std::string::npos, "Option '%s' badly formatted. Should be of the form 'name:value'",
517 std::string val = name.substr(pos + 1);
520 const std::string path("path");
521 if (name.compare(0, path.length(), path) != 0)
522 XBT_INFO("Configuration change: Set '%s' to '%s'", name.c_str(), val.c_str());
525 (*simgrid_config)[name.c_str()].setStringValue(val.c_str());
527 catch (simgrid::config::missing_key_error& e) {
536 /* Do not THROWF from a C++ exception catching context, or some cleanups will be missing */
538 THROWF(not_found_error, 0, "Could not set variables %s", options);
540 THROWF(unknown_error, 0, "Could not set variables %s", options);
543 // Horrible mess to translate C++ exceptions to C exceptions:
544 // Exit from the catch block (and do the correct exception cleaning) before attempting to THROWF.
545 #define TRANSLATE_EXCEPTIONS(...) \
546 catch(simgrid::config::missing_key_error& e) { THROWF(not_found_error, 0, __VA_ARGS__); abort(); } \
547 catch(...) { THROWF(not_found_error, 0, __VA_ARGS__); abort(); }
549 /** @brief Set the value of a variable, using the string representation of that value
551 * @param key name of the variable to modify
552 * @param value string representation of the value to set
555 void xbt_cfg_set_as_string(const char *key, const char *value)
558 (*simgrid_config)[key].setStringValue(value);
561 TRANSLATE_EXCEPTIONS("Could not set variable %s as string %s", key, value);
564 /** @brief Set an integer value to \a name within \a cfg if it wasn't changed yet
566 * This is useful to change the default value of a variable while allowing
567 * users to override it with command line arguments
569 void xbt_cfg_setdefault_int(const char *key, int value)
572 (*simgrid_config)[key].setDefaultValue<int>(value);
575 TRANSLATE_EXCEPTIONS("Could not set variable %s to default integer %i", key, value);
578 /** @brief Set an integer value to \a name within \a cfg if it wasn't changed yet
580 * This is useful to change the default value of a variable while allowing
581 * users to override it with command line arguments
583 void xbt_cfg_setdefault_double(const char *key, double value)
586 (*simgrid_config)[key].setDefaultValue<double>(value);
589 TRANSLATE_EXCEPTIONS("Could not set variable %s to default double %f", key, value);
592 /** @brief Set a string 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_string(const char *key, const char *value)
600 (*simgrid_config)[key].setDefaultValue<std::string>(value ? value : "");
603 TRANSLATE_EXCEPTIONS("Could not set variable %s to default string %s", key, value);
606 /** @brief Set an boolean 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_boolean(const char *key, const char *value)
614 (*simgrid_config)[key].setDefaultValue<bool>(simgrid::config::parseBool(value));
617 TRANSLATE_EXCEPTIONS("Could not set variable %s to default boolean %s", key, value);
620 /** @brief Set an integer value to \a name within \a cfg
622 * @param key the name of the variable
623 * @param value the value of the variable
625 void xbt_cfg_set_int(const char *key, int value)
628 (*simgrid_config)[key].setValue<int>(value);
631 TRANSLATE_EXCEPTIONS("Could not set variable %s to integer %i", key, value);
634 /** @brief Set or add a double value to \a name within \a cfg
636 * @param key the name of the variable
637 * @param value the double to set
639 void xbt_cfg_set_double(const char *key, double value)
642 (*simgrid_config)[key].setValue<double>(value);
645 TRANSLATE_EXCEPTIONS("Could not set variable %s to double %f", key, value);
648 /** @brief Set or add a string value to \a name within \a cfg
650 * @param key the name of the variable
651 * @param value the value to be added
654 void xbt_cfg_set_string(const char* key, const char* value)
657 (*simgrid_config)[key].setValue<std::string>(value);
660 TRANSLATE_EXCEPTIONS("Could not set variable %s to string %s", key, value);
663 /** @brief Set or add a boolean value to \a name within \a cfg
665 * @param key the name of the variable
666 * @param value the value of the variable
668 void xbt_cfg_set_boolean(const char *key, const char *value)
671 (*simgrid_config)[key].setValue<bool>(simgrid::config::parseBool(value));
674 TRANSLATE_EXCEPTIONS("Could not set variable %s to boolean %s", key, value);
678 /* Say if the value is the default value */
679 int xbt_cfg_is_default_value(const char *key)
682 return (*simgrid_config)[key].isDefault() ? 1 : 0;
684 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
687 /*----[ Getting ]---------------------------------------------------------*/
688 /** @brief Retrieve an integer value of a variable (get a warning if not uniq)
690 * @param key the name of the variable
692 * Returns the first value from the config set under the given name.
694 int xbt_cfg_get_int(const char *key)
697 return (*simgrid_config)[key].getValue<int>();
699 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
702 /** @brief Retrieve a double value of a variable (get a warning if not uniq)
704 * @param key the name of the variable
706 * Returns the first value from the config set under the given name.
708 double xbt_cfg_get_double(const char *key)
711 return (*simgrid_config)[key].getValue<double>();
713 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
716 /** @brief Retrieve a string 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.
721 * If there is more than one value, it will issue a warning.
722 * Returns nullptr if there is no value.
724 * \warning the returned value is the actual content of the config set
726 std::string xbt_cfg_get_string(const char* key)
729 return (*simgrid_config)[key].getValue<std::string>();
731 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
734 /** @brief Retrieve a boolean value of a variable (get a warning if not uniq)
736 * @param key the name of the variable
738 * Returns the first value from the config set under the given name.
739 * If there is more than one value, it will issue a warning.
741 int xbt_cfg_get_boolean(const char *key)
744 return (*simgrid_config)[key].getValue<bool>() ? 1 : 0;
746 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
755 #include <xbt/ex.hpp>
757 #include <xbt/config.hpp>
759 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(xbt_cfg);
761 XBT_TEST_SUITE("config", "Configuration support");
763 XBT_PUBLIC_DATA(xbt_cfg_t) simgrid_config;
765 static void make_set()
767 simgrid_config = nullptr;
768 xbt_log_threshold_set(&_XBT_LOGV(xbt_cfg), xbt_log_priority_critical);
769 xbt_cfg_register_int("speed", 0, nullptr, "");
770 xbt_cfg_register_string("peername", "", nullptr, "");
771 xbt_cfg_register_string("user", "", nullptr, "");
772 } /* end_of_make_set */
774 XBT_TEST_UNIT("memuse", test_config_memuse, "Alloc and free a config set")
776 auto temp = simgrid_config;
778 xbt_test_add("Alloc and free a config set");
779 xbt_cfg_set_parse("peername:veloce user:bidule");
780 xbt_cfg_free(&simgrid_config);
781 simgrid_config = temp;
784 XBT_TEST_UNIT("use", test_config_use, "Data retrieving tests")
786 auto temp = simgrid_config;
788 xbt_test_add("Get a single value");
790 /* get_single_value */
791 xbt_cfg_set_parse("peername:toto:42 speed:42");
792 int ival = xbt_cfg_get_int("speed");
794 xbt_test_fail("Speed value = %d, I expected 42", ival);
797 xbt_test_add("Access to a non-existant entry");
800 xbt_cfg_set_parse("color:blue");
802 if (e.category != not_found_error)
803 xbt_test_exception(e);
806 xbt_cfg_free(&simgrid_config);
807 simgrid_config = temp;
810 XBT_TEST_UNIT("c++flags", test_config_cxx_flags, "C++ flags")
812 auto temp = simgrid_config;
814 xbt_test_add("C++ declaration of flags");
816 simgrid::config::Flag<int> int_flag("int", "", 0);
817 simgrid::config::Flag<std::string> string_flag("string", "", "foo");
818 simgrid::config::Flag<double> double_flag("double", "", 0.32);
819 simgrid::config::Flag<bool> bool_flag1("bool1", "", false);
820 simgrid::config::Flag<bool> bool_flag2("bool2", "", true);
822 xbt_test_add("Parse values");
823 xbt_cfg_set_parse("int:42 string:bar double:8.0 bool1:true bool2:false");
824 xbt_test_assert(int_flag == 42, "Check int flag");
825 xbt_test_assert(string_flag == "bar", "Check string flag");
826 xbt_test_assert(double_flag == 8.0, "Check double flag");
827 xbt_test_assert(bool_flag1, "Check bool1 flag");
828 xbt_test_assert(not bool_flag2, "Check bool2 flag");
830 xbt_cfg_free(&simgrid_config);
831 simgrid_config = temp;
834 #endif /* SIMGRID_TEST */