1 /* Copyright (c) 2004-2014,2016. 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. */
16 #include <type_traits>
18 #include <unordered_map>
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;
146 xbt_cfg_cb_t old_callback = nullptr;
148 ConfigurationElement(const char* key, const char* desc)
149 : key(key ? key : ""), desc(desc ? desc : "") {}
150 ConfigurationElement(const char* key, const char* desc, xbt_cfg_cb_t cb)
151 : key(key ? key : ""), desc(desc ? desc : ""), old_callback(cb) {}
153 virtual ~ConfigurationElement()=default;
155 virtual std::string getStringValue() = 0;
156 virtual void setStringValue(const char* value) = 0;
157 virtual const char* getTypeName() = 0;
160 T const& getValue() const
162 return dynamic_cast<const TypedConfigurationElement<T>&>(*this).getValue();
165 void setValue(T value)
167 dynamic_cast<TypedConfigurationElement<T>&>(*this).setValue(std::move(value));
170 void setDefaultValue(T value)
172 dynamic_cast<TypedConfigurationElement<T>&>(*this).setDefaultValue(std::move(value));
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,
195 : ConfigurationElement(key, desc, cb), content(std::move(value))
197 TypedConfigurationElement(const char* key, const char* desc, T value,
198 std::function<void(T&)> callback)
199 : ConfigurationElement(key, desc), content(std::move(value)),
200 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(key.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'"
231 " because it was already set.", key.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->isdefault = false;
251 const char* TypedConfigurationElement<T>::getTypeName() // override
253 return ConfigType<T>::type_name;
256 } // end of anonymous namespace
262 // name -> ConfigElement:
263 std::unordered_map<std::string, simgrid::config::ConfigurationElement*> options;
264 // alias -> xbt_dict_elm_t from options:
265 std::unordered_map<std::string, simgrid::config::ConfigurationElement*> aliases;
272 Config(Config const&) = delete;
273 Config& operator=(Config const&) = delete;
275 ConfigurationElement& operator[](const char* name);
277 TypedConfigurationElement<T>& getTyped(const char* name);
278 void alias(const char* realname, const char* aliasname);
280 template<class T, class... A>
281 simgrid::config::TypedConfigurationElement<T>*
282 registerOption(const char* name, A&&... a)
284 xbt_assert(options.find(name) == options.end(), "Refusing to register the config element '%s' twice.", name);
285 TypedConfigurationElement<T>* variable = new TypedConfigurationElement<T>(name, std::forward<A>(a)...);
286 XBT_DEBUG("Register cfg elm %s (%s) of type %s @%p in set %p)", name, variable->getDescription().c_str(),
287 variable->getTypeName(), variable, this);
288 options.insert({name, variable});
294 void dump(const char *name, const char *indent);
299 ConfigurationElement* getDictElement(const char* name);
304 XBT_DEBUG("Frees cfg set %p", this);
305 for (auto elm : options)
309 inline ConfigurationElement* Config::getDictElement(const char* name)
312 return options.at(name);
313 } catch (std::out_of_range& unfound) {
315 ConfigurationElement* res = aliases.at(name);
316 XBT_INFO("Option %s has been renamed to %s. Consider switching.", name, res->getKey().c_str());
318 } catch (std::out_of_range& missing_key) {
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 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 std::vector<std::string> names;
361 for (auto elm : aliases)
362 names.push_back(elm.first);
363 std::sort(names.begin(), names.end());
365 for (auto name : names)
366 printf(" %s: %s\n", name.c_str(), (*this)[name.c_str()].getDescription().c_str());
369 /** @brief Displays the declared options and their description */
372 std::vector<std::string> names;
374 for (auto elm : options)
375 names.push_back(elm.first);
376 std::sort(names.begin(), names.end());
378 for (auto name : names) {
379 simgrid::config::ConfigurationElement* variable = this->options.at(name);
380 printf(" %s: %s\n", name.c_str(), variable->getDescription().c_str());
381 printf(" Type: %s; ", variable->getTypeName());
382 printf("Current value: %s\n", variable->getStringValue().c_str());
386 // ***** getConfig *****
389 XBT_PUBLIC(T const&) getConfig(const char* name)
391 return (*simgrid_config)[name].getValue<T>();
394 template XBT_PUBLIC(int const&) getConfig<int>(const char* name);
395 template XBT_PUBLIC(double const&) getConfig<double>(const char* name);
396 template XBT_PUBLIC(bool const&) getConfig<bool>(const char* name);
397 template XBT_PUBLIC(std::string const&) getConfig<std::string>(const char* name);
401 void alias(const char* realname, const char* aliasname)
403 simgrid_config->alias(realname, aliasname);
406 // ***** declareFlag *****
409 XBT_PUBLIC(void) declareFlag(const char* name, const char* description,
410 T value, std::function<void(const T&)> callback)
412 if (simgrid_config == nullptr) {
413 simgrid_config = xbt_cfg_new();
414 atexit(sg_config_finalize);
416 simgrid_config->registerOption<T>(
417 name, description, std::move(value), std::move(callback));
420 template XBT_PUBLIC(void) declareFlag(const char* name,
421 const char* description, int value, std::function<void(int const &)> callback);
422 template XBT_PUBLIC(void) declareFlag(const char* name,
423 const char* description, double value, std::function<void(double const &)> callback);
424 template XBT_PUBLIC(void) declareFlag(const char* name,
425 const char* description, bool value, std::function<void(bool const &)> callback);
426 template XBT_PUBLIC(void) declareFlag(const char* name,
427 const char* description, std::string value, std::function<void(std::string const &)> callback);
432 // ***** C bindings *****
434 xbt_cfg_t xbt_cfg_new() { return new simgrid::config::Config(); }
435 void xbt_cfg_free(xbt_cfg_t * cfg) { delete *cfg; }
437 void xbt_cfg_dump(const char *name, const char *indent, xbt_cfg_t cfg)
439 cfg->dump(name, indent);
442 /*----[ Registering stuff ]-----------------------------------------------*/
444 void xbt_cfg_register_double(const char *name, double default_value,
445 xbt_cfg_cb_t cb_set, const char *desc)
447 if (simgrid_config == nullptr)
448 simgrid_config = xbt_cfg_new();
449 simgrid_config->registerOption<double>(name, desc, default_value, cb_set);
452 void xbt_cfg_register_int(const char *name, int 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<int>(name, desc, default_value, cb_set);
461 void xbt_cfg_register_string(const char *name, const char *default_value, xbt_cfg_cb_t cb_set, const char *desc)
463 if (simgrid_config == nullptr) {
464 simgrid_config = xbt_cfg_new();
465 atexit(sg_config_finalize);
467 simgrid_config->registerOption<std::string>(name, desc,
468 default_value ? default_value : "", cb_set);
471 void xbt_cfg_register_boolean(const char *name, const char*default_value,xbt_cfg_cb_t cb_set, const char *desc)
473 if (simgrid_config == nullptr) {
474 simgrid_config = xbt_cfg_new();
475 atexit(sg_config_finalize);
477 simgrid_config->registerOption<bool>(name, desc, simgrid::config::parseBool(default_value), cb_set);
480 void xbt_cfg_register_alias(const char *realname, const char *aliasname)
482 if (simgrid_config == nullptr) {
483 simgrid_config = xbt_cfg_new();
484 atexit(sg_config_finalize);
486 simgrid_config->alias(realname, aliasname);
489 void xbt_cfg_aliases() { simgrid_config->showAliases(); }
490 void xbt_cfg_help() { simgrid_config->help(); }
492 /*----[ Setting ]---------------------------------------------------------*/
494 /** @brief Add values parsed from a string into a config set
496 * @param options a string containing the content to add to the config set. This is a '\\t',' ' or '\\n' or ','
497 * separated list of variables. Each individual variable is like "[name]:[value]" where [name] is the name of an
498 * already registered variable, and [value] conforms to the data type under which this variable was registered.
500 * @todo This is a crude manual parser, it should be a proper lexer.
502 void xbt_cfg_set_parse(const char *options)
504 if (not options || not strlen(options)) { /* nothing to do */
507 char *optionlist_cpy = xbt_strdup(options);
509 XBT_DEBUG("List to parse and set:'%s'", options);
510 char *option = optionlist_cpy;
511 while (1) { /* breaks in the code */
515 int len = strlen(name);
516 XBT_DEBUG("Still to parse and set: '%s'. len=%d; option-name=%ld", name, len, (long) (option - name));
519 while (option - name <= (len - 1) && *option != ' ' && *option != '\n' && *option != '\t' && *option != ',') {
520 XBT_DEBUG("Take %c.", *option);
523 if (option - name == len) {
524 XBT_DEBUG("Boundary=EOL");
525 option = nullptr; /* don't do next iteration */
527 XBT_DEBUG("Boundary on '%c'. len=%d;option-name=%ld", *option, len, (long) (option - name));
528 /* Pass the following blank chars */
530 while (option - name < (len - 1) && (*option == ' ' || *option == '\n' || *option == '\t')) {
531 /* fprintf(stderr,"Ignore a blank char.\n"); */
534 if (option - name == len - 1)
535 option = nullptr; /* don't do next iteration */
537 XBT_DEBUG("parse now:'%s'; parse later:'%s'", name, option);
539 if (name[0] == ' ' || name[0] == '\n' || name[0] == '\t')
541 if (not strlen(name))
544 char *val = strchr(name, ':');
545 xbt_assert(val, "Option '%s' badly formatted. Should be of the form 'name:value'", name);
546 /* don't free(optionlist_cpy) if the assert fails, 'name' points inside it */
549 if (strncmp(name, "path", strlen("path")))
550 XBT_INFO("Configuration change: Set '%s' to '%s'", name, val);
553 (*simgrid_config)[name].setStringValue(val);
555 catch (simgrid::config::missing_key_error& e) {
563 free(optionlist_cpy);
566 /* Do not THROWF from a C++ exception catching context, or some cleanups will be missing */
568 free(optionlist_cpy);
569 THROWF(not_found_error, 0, "Could not set variables %s", options);
572 free(optionlist_cpy);
573 THROWF(unknown_error, 0, "Could not set variables %s", options);
576 // Horrible mess to translate C++ exceptions to C exceptions:
577 // Exit from the catch blog (and do the correct exceptio cleaning)
578 // before attempting to THROWF.
579 #define TRANSLATE_EXCEPTIONS(...) \
580 catch(simgrid::config::missing_key_error& e) { THROWF(not_found_error, 0, __VA_ARGS__); abort(); } \
581 catch(...) { THROWF(not_found_error, 0, __VA_ARGS__); abort(); }
583 /** @brief Set the value of a variable, using the string representation of that value
585 * @param key name of the variable to modify
586 * @param value string representation of the value to set
589 void xbt_cfg_set_as_string(const char *key, const char *value)
592 (*simgrid_config)[key].setStringValue(value);
595 TRANSLATE_EXCEPTIONS("Could not set variable %s as string %s", key, value);
598 /** @brief Set an integer 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_int(const char *key, int value)
606 (*simgrid_config)[key].setDefaultValue<int>(value);
609 TRANSLATE_EXCEPTIONS("Could not set variable %s to default integer %i",
613 /** @brief Set an integer value to \a name within \a cfg if it wasn't changed yet
615 * This is useful to change the default value of a variable while allowing
616 * users to override it with command line arguments
618 void xbt_cfg_setdefault_double(const char *key, double value)
621 (*simgrid_config)[key].setDefaultValue<double>(value);
624 TRANSLATE_EXCEPTIONS("Could not set variable %s to default double %f",
628 /** @brief Set a string 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_string(const char *key, const char *value)
636 (*simgrid_config)[key].setDefaultValue<std::string>(value ? value : "");
639 TRANSLATE_EXCEPTIONS("Could not set variable %s to default string %s",
643 /** @brief Set an boolean value to \a name within \a cfg if it wasn't changed yet
645 * This is useful to change the default value of a variable while allowing
646 * users to override it with command line arguments
648 void xbt_cfg_setdefault_boolean(const char *key, const char *value)
651 (*simgrid_config)[key].setDefaultValue<bool>(simgrid::config::parseBool(value));
654 TRANSLATE_EXCEPTIONS("Could not set variable %s to default boolean %s",
658 /** @brief Set an integer value to \a name within \a cfg
660 * @param key the name of the variable
661 * @param value the value of the variable
663 void xbt_cfg_set_int(const char *key, int value)
666 (*simgrid_config)[key].setValue<int>(value);
669 TRANSLATE_EXCEPTIONS("Could not set variable %s to integer %i",
673 /** @brief Set or add a double value to \a name within \a cfg
675 * @param key the name of the variable
676 * @param value the double to set
678 void xbt_cfg_set_double(const char *key, double value)
681 (*simgrid_config)[key].setValue<double>(value);
684 TRANSLATE_EXCEPTIONS("Could not set variable %s to double %f",
688 /** @brief Set or add a string value to \a name within \a cfg
690 * @param key the name of the variable
691 * @param value the value to be added
694 void xbt_cfg_set_string(const char *key, const char *value)
697 (*simgrid_config)[key].setValue<std::string>(value ? value : "");
700 TRANSLATE_EXCEPTIONS("Could not set variable %s to string %s",
704 /** @brief Set or add a boolean value to \a name within \a cfg
706 * @param key the name of the variable
707 * @param value the value of the variable
709 void xbt_cfg_set_boolean(const char *key, const char *value)
712 (*simgrid_config)[key].setValue<bool>(simgrid::config::parseBool(value));
715 TRANSLATE_EXCEPTIONS("Could not set variable %s to boolean %s",
720 /* Say if the value is the default value */
721 int xbt_cfg_is_default_value(const char *key)
724 return (*simgrid_config)[key].isDefault() ? 1 : 0;
726 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
729 /*----[ Getting ]---------------------------------------------------------*/
730 /** @brief Retrieve an integer 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 int xbt_cfg_get_int(const char *key)
739 return (*simgrid_config)[key].getValue<int>();
741 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
744 /** @brief Retrieve a double 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.
750 double xbt_cfg_get_double(const char *key)
753 return (*simgrid_config)[key].getValue<double>();
755 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
758 /** @brief Retrieve a string value of a variable (get a warning if not uniq)
760 * @param key the name of the variable
762 * Returns the first value from the config set under the given name.
763 * If there is more than one value, it will issue a warning.
764 * Returns nullptr if there is no value.
766 * \warning the returned value is the actual content of the config set
768 char *xbt_cfg_get_string(const char *key)
771 return (char*) (*simgrid_config)[key].getValue<std::string>().c_str();
773 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
776 /** @brief Retrieve a boolean value of a variable (get a warning if not uniq)
778 * @param key the name of the variable
780 * Returns the first value from the config set under the given name.
781 * If there is more than one value, it will issue a warning.
783 int xbt_cfg_get_boolean(const char *key)
786 return (*simgrid_config)[key].getValue<bool>() ? 1 : 0;
788 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
797 #include <xbt/ex.hpp>
799 #include <xbt/config.hpp>
801 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(xbt_cfg);
803 XBT_TEST_SUITE("config", "Configuration support");
805 XBT_PUBLIC_DATA(xbt_cfg_t) simgrid_config;
807 static void make_set()
809 simgrid_config = nullptr;
810 xbt_log_threshold_set(&_XBT_LOGV(xbt_cfg), xbt_log_priority_critical);
811 xbt_cfg_register_int("speed", 0, nullptr, "");
812 xbt_cfg_register_string("peername", "", nullptr, "");
813 xbt_cfg_register_string("user", "", nullptr, "");
814 } /* end_of_make_set */
816 XBT_TEST_UNIT("memuse", test_config_memuse, "Alloc and free a config set")
818 auto temp = simgrid_config;
820 xbt_test_add("Alloc and free a config set");
821 xbt_cfg_set_parse("peername:veloce user:bidule");
822 xbt_cfg_free(&simgrid_config);
823 simgrid_config = temp;
826 XBT_TEST_UNIT("use", test_config_use, "Data retrieving tests")
828 auto temp = simgrid_config;
830 xbt_test_add("Get a single value");
832 /* get_single_value */
835 xbt_cfg_set_parse("peername:toto:42 speed:42");
836 ival = xbt_cfg_get_int("speed");
838 xbt_test_fail("Speed value = %d, I expected 42", ival);
841 xbt_test_add("Access to a non-existant entry");
844 xbt_cfg_set_parse("color:blue");
846 if (e.category != not_found_error)
847 xbt_test_exception(e);
850 xbt_cfg_free(&simgrid_config);
851 simgrid_config = temp;
854 XBT_TEST_UNIT("c++flags", test_config_cxx_flags, "C++ flags")
856 auto temp = simgrid_config;
858 xbt_test_add("C++ declaration of flags");
860 simgrid::config::Flag<int> int_flag("int", "", 0);
861 simgrid::config::Flag<std::string> string_flag("string", "", "foo");
862 simgrid::config::Flag<double> double_flag("double", "", 0.32);
863 simgrid::config::Flag<bool> bool_flag1("bool1", "", false);
864 simgrid::config::Flag<bool> bool_flag2("bool2", "", true);
866 xbt_test_add("Parse values");
867 xbt_cfg_set_parse("int:42 string:bar double:8.0 bool1:true bool2:false");
868 xbt_test_assert(int_flag == 42, "Check int flag");
869 xbt_test_assert(string_flag == "bar", "Check string flag");
870 xbt_test_assert(double_flag == 8.0, "Check double flag");
871 xbt_test_assert(bool_flag1, "Check bool1 flag");
872 xbt_test_assert(not bool_flag2, "Check bool2 flag");
874 xbt_cfg_free(&simgrid_config);
875 simgrid_config = temp;
878 #endif /* SIMGRID_TEST */