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 <xbt/config.h>
19 #include <xbt/config.hpp>
21 #include "xbt/sysdep.h"
24 #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;
36 missing_key_error::~missing_key_error() noexcept {}
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* true_value : true_values)
52 if (std::strcmp(true_value, value) == 0)
54 for (const char* 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> struct ConfigType;
98 template<> struct ConfigType<int> {
99 static constexpr const char* type_name = "int";
100 static inline double parse(const char* value)
102 return parseLong(value);
105 template<> struct ConfigType<double> {
106 static constexpr const char* type_name = "double";
107 static inline double parse(const char* value)
109 return parseDouble(value);
112 template<> struct ConfigType<std::string> {
113 static constexpr const char* type_name = "string";
114 static inline std::string parse(const char* value)
116 return std::string(value);
119 template<> struct ConfigType<bool> {
120 static constexpr const char* type_name = "boolean";
121 static inline bool parse(const char* value)
123 return parseBool(value);
127 // **** Forward declarations ****
129 class ConfigurationElement ;
130 template<class T> class TypedConfigurationElement;
132 // **** ConfigurationElement ****
134 class ConfigurationElement {
138 bool isdefault = true;
143 xbt_cfg_cb_t old_callback = nullptr;
145 ConfigurationElement(const char* key, const char* desc)
146 : key(key ? key : ""), desc(desc ? desc : "") {}
147 ConfigurationElement(const char* key, const char* desc, xbt_cfg_cb_t cb)
148 : key(key ? key : ""), desc(desc ? desc : ""), old_callback(cb) {}
150 virtual ~ConfigurationElement();
152 virtual std::string getStringValue() = 0;
153 virtual void setStringValue(const char* value) = 0;
154 virtual const char* getTypeName() = 0;
157 T const& getValue() const
159 return dynamic_cast<const TypedConfigurationElement<T>&>(*this).getValue();
162 void setValue(T value)
164 dynamic_cast<TypedConfigurationElement<T>&>(*this).setValue(std::move(value));
167 void setDefaultValue(T value)
169 dynamic_cast<TypedConfigurationElement<T>&>(*this).setDefaultValue(std::move(value));
171 bool isDefault() const { return isdefault; }
173 std::string const& getDescription() const { return desc; }
176 ConfigurationElement::~ConfigurationElement() {}
178 // **** TypedConfigurationElement<T> ****
180 // TODO, could we use boost::any with some Type* reference?
182 class TypedConfigurationElement : public ConfigurationElement {
185 std::function<void(T&)> callback;
188 TypedConfigurationElement(const char* key, const char* desc, T value = T())
189 : ConfigurationElement(key, desc), content(std::move(value))
191 TypedConfigurationElement(const char* key, const char* desc, T value,
193 : ConfigurationElement(key, desc, cb), content(std::move(value))
195 TypedConfigurationElement(const char* key, const char* desc, T value,
196 std::function<void(T&)> callback)
197 : ConfigurationElement(key, desc), content(std::move(value)),
198 callback(std::move(callback))
200 ~TypedConfigurationElement() override;
202 std::string getStringValue() override;
203 const char* getTypeName() override;
204 void setStringValue(const char* value) override;
209 this->old_callback(key.c_str());
211 this->callback(this->content);
214 T const& getValue() const { return content; }
216 void setValue(T value)
218 this->content = std::move(value);
222 void setDefaultValue(T value)
224 if (this->isdefault) {
225 this->content = std::move(value);
228 XBT_DEBUG("Do not override configuration variable '%s' with value '%s'"
229 " because it was already set.", key.c_str(), to_string(value).c_str());
235 std::string TypedConfigurationElement<T>::getStringValue() // override
237 return to_string(content);
241 void TypedConfigurationElement<T>::setStringValue(const char* value) // override
243 this->content = ConfigType<T>::parse(value);
244 this->isdefault = false;
249 const char* TypedConfigurationElement<T>::getTypeName() // override
251 return ConfigType<T>::type_name;
255 TypedConfigurationElement<T>::~TypedConfigurationElement()
258 } // end of anonymous namespace
264 // name -> ConfigElement:
266 // alias -> xbt_dict_elm_t from options:
274 Config(Config const&) = delete;
275 Config& operator=(Config const&) = delete;
277 ConfigurationElement& operator[](const char* name);
279 TypedConfigurationElement<T>& getTyped(const char* name);
280 void alias(const char* realname, const char* aliasname);
282 template<class T, class... A>
283 simgrid::config::TypedConfigurationElement<T>*
284 registerOption(const char* name, A&&... a)
286 xbt_assert(xbt_dict_get_or_null(this->options, name) == nullptr,
287 "Refusing to register the config element '%s' twice.", name);
288 TypedConfigurationElement<T>* variable =
289 new TypedConfigurationElement<T>(name, std::forward<A>(a)...);
290 XBT_DEBUG("Register cfg elm %s (%s) of type %s @%p in set %p)",
292 variable->getDescription().c_str(),
293 variable->getTypeName(), variable, this);
294 xbt_dict_set(this->options, name, variable, nullptr);
300 void dump(const char *name, const char *indent);
305 xbt_dictelm_t getDictElement(const char* name);
308 /* Internal stuff used in cache to free a variable */
309 static void xbt_cfgelm_free(void *data)
312 delete (simgrid::config::ConfigurationElement*) data;
316 options(xbt_dict_new_homogeneous(xbt_cfgelm_free)),
317 aliases(xbt_dict_new_homogeneous(nullptr))
322 XBT_DEBUG("Frees cfg set %p", this);
323 xbt_dict_free(&this->options);
324 xbt_dict_free(&this->aliases);
328 xbt_dictelm_t Config::getDictElement(const char* name)
330 // We are interested in the options dictelm:
331 xbt_dictelm_t res = xbt_dict_get_elm_or_null(options, name);
334 // The aliases dict stores pointers to the options dictelm:
335 res = (xbt_dictelm_t) xbt_dict_get_or_null(aliases, name);
337 XBT_INFO("Option %s has been renamed to %s. Consider switching.", name, res->key);
342 ConfigurationElement& Config::operator[](const char* name)
344 xbt_dictelm_t elm = getDictElement(name);
346 throw simgrid::config::missing_key_error(std::string("Bad config key, ") + name);
347 return *(ConfigurationElement*)elm->content;
350 void Config::alias(const char* realname, const char* aliasname)
352 xbt_assert(this->getDictElement(aliasname) == nullptr, "Alias '%s' already.", aliasname);
353 xbt_dictelm_t element = this->getDictElement(realname);
354 xbt_assert(element, "Cannot define an alias to the non-existing option '%s'.", realname);
355 xbt_dict_set(this->aliases, aliasname, element, nullptr);
358 /** @brief Dump a config set for debuging purpose
360 * @param name The name to give to this config set
361 * @param indent what to write at the beginning of each line (right number of spaces)
363 void Config::dump(const char *name, const char *indent)
365 xbt_dict_t dict = this->options;
366 xbt_dict_cursor_t cursor = nullptr;
367 simgrid::config::ConfigurationElement* variable = nullptr;
371 printf("%s>> Dumping of the config set '%s':\n", indent, name);
373 xbt_dict_foreach(dict, cursor, key, variable)
374 printf("%s %s: ()%s) %s", indent, key,
375 variable->getTypeName(),
376 variable->getStringValue().c_str());
379 printf("%s<< End of the config set '%s'\n", indent, name);
382 xbt_dict_cursor_free(&cursor);
385 /** @brief Displays the declared aliases and their description */
386 void Config::showAliases()
388 xbt_dict_cursor_t dict_cursor;
389 unsigned int dynar_cursor;
390 xbt_dictelm_t dictel;
392 xbt_dynar_t names = xbt_dynar_new(sizeof(char *), nullptr);
394 xbt_dict_foreach(this->aliases, dict_cursor, name, dictel)
395 xbt_dynar_push(names, &name);
396 xbt_dynar_sort_strings(names);
398 xbt_dynar_foreach(names, dynar_cursor, name)
399 printf(" %s: %s\n", name, (*this)[name].getDescription().c_str());
402 /** @brief Displays the declared options and their description */
405 xbt_dict_cursor_t dict_cursor;
406 unsigned int dynar_cursor;
407 simgrid::config::ConfigurationElement* variable;
409 xbt_dynar_t names = xbt_dynar_new(sizeof(char *), nullptr);
411 xbt_dict_foreach(this->options, dict_cursor, name, variable)
412 xbt_dynar_push(names, &name);
413 xbt_dynar_sort_strings(names);
415 xbt_dynar_foreach(names, dynar_cursor, name) {
416 variable = (simgrid::config::ConfigurationElement*) xbt_dict_get(this->options, name);
417 printf(" %s: %s\n", name, variable->getDescription().c_str());
418 printf(" Type: %s; ", variable->getTypeName());
419 printf("Current value: %s\n", variable->getStringValue().c_str());
421 xbt_dynar_free(&names);
424 // ***** getConfig *****
427 XBT_PUBLIC(T const&) getConfig(const char* name)
429 return (*simgrid_config)[name].getValue<T>();
432 template XBT_PUBLIC(int const&) getConfig<int>(const char* name);
433 template XBT_PUBLIC(double const&) getConfig<double>(const char* name);
434 template XBT_PUBLIC(bool const&) getConfig<bool>(const char* name);
435 template XBT_PUBLIC(std::string const&) getConfig<std::string>(const char* name);
439 void alias(const char* realname, const char* aliasname)
441 simgrid_config->alias(realname, aliasname);
444 // ***** declareFlag *****
447 XBT_PUBLIC(void) declareFlag(const char* name, const char* description,
448 T value, std::function<void(const T&)> callback)
450 if (simgrid_config == nullptr)
451 simgrid_config = xbt_cfg_new();
452 simgrid_config->registerOption<T>(
453 name, description, std::move(value), std::move(callback));
456 template XBT_PUBLIC(void) declareFlag(const char* name,
457 const char* description, int value, std::function<void(int const &)> callback);
458 template XBT_PUBLIC(void) declareFlag(const char* name,
459 const char* description, double value, std::function<void(double const &)> callback);
460 template XBT_PUBLIC(void) declareFlag(const char* name,
461 const char* description, bool value, std::function<void(bool const &)> callback);
462 template XBT_PUBLIC(void) declareFlag(const char* name,
463 const char* description, std::string value, std::function<void(std::string const &)> callback);
468 // ***** C bindings *****
470 xbt_cfg_t xbt_cfg_new(void) { return new simgrid::config::Config(); }
471 void xbt_cfg_free(xbt_cfg_t * cfg) { delete *cfg; }
473 void xbt_cfg_dump(const char *name, const char *indent, xbt_cfg_t cfg)
475 cfg->dump(name, indent);
478 /*----[ Registering stuff ]-----------------------------------------------*/
480 void xbt_cfg_register_double(const char *name, double default_value,
481 xbt_cfg_cb_t cb_set, const char *desc)
483 if (simgrid_config == nullptr)
484 simgrid_config = xbt_cfg_new();
485 simgrid_config->registerOption<double>(name, desc, default_value, cb_set);
488 void xbt_cfg_register_int(const char *name, int default_value,xbt_cfg_cb_t cb_set, const char *desc)
490 if (simgrid_config == nullptr)
491 simgrid_config = xbt_cfg_new();
492 simgrid_config->registerOption<int>(name, desc, default_value, cb_set);
495 void xbt_cfg_register_string(const char *name, const char *default_value, xbt_cfg_cb_t cb_set, const char *desc)
497 if (simgrid_config == nullptr)
498 simgrid_config = xbt_cfg_new();
499 simgrid_config->registerOption<std::string>(name, desc,
500 default_value ? default_value : "", cb_set);
503 void xbt_cfg_register_boolean(const char *name, const char*default_value,xbt_cfg_cb_t cb_set, const char *desc)
505 if (simgrid_config == nullptr)
506 simgrid_config = xbt_cfg_new();
507 simgrid_config->registerOption<bool>(name, desc, simgrid::config::parseBool(default_value), cb_set);
510 void xbt_cfg_register_alias(const char *realname, const char *aliasname)
512 if (simgrid_config == nullptr)
513 simgrid_config = xbt_cfg_new();
514 simgrid_config->alias(realname, aliasname);
517 void xbt_cfg_aliases(void) { simgrid_config->showAliases(); }
518 void xbt_cfg_help(void) { simgrid_config->help(); }
520 /*----[ Setting ]---------------------------------------------------------*/
522 /** @brief Add values parsed from a string into a config set
524 * @param options a string containing the content to add to the config set. This is a '\\t',' ' or '\\n' or ','
525 * separated list of variables. Each individual variable is like "[name]:[value]" where [name] is the name of an
526 * already registered variable, and [value] conforms to the data type under which this variable was registered.
528 * @todo This is a crude manual parser, it should be a proper lexer.
530 void xbt_cfg_set_parse(const char *options)
532 if (!options || !strlen(options)) { /* nothing to do */
535 char *optionlist_cpy = xbt_strdup(options);
537 XBT_DEBUG("List to parse and set:'%s'", options);
538 char *option = optionlist_cpy;
539 while (1) { /* breaks in the code */
543 int len = strlen(name);
544 XBT_DEBUG("Still to parse and set: '%s'. len=%d; option-name=%ld", name, len, (long) (option - name));
547 while (option - name <= (len - 1) && *option != ' ' && *option != '\n' && *option != '\t' && *option != ',') {
548 XBT_DEBUG("Take %c.", *option);
551 if (option - name == len) {
552 XBT_DEBUG("Boundary=EOL");
553 option = nullptr; /* don't do next iteration */
555 XBT_DEBUG("Boundary on '%c'. len=%d;option-name=%ld", *option, len, (long) (option - name));
556 /* Pass the following blank chars */
558 while (option - name < (len - 1) && (*option == ' ' || *option == '\n' || *option == '\t')) {
559 /* fprintf(stderr,"Ignore a blank char.\n"); */
562 if (option - name == len - 1)
563 option = nullptr; /* don't do next iteration */
565 XBT_DEBUG("parse now:'%s'; parse later:'%s'", name, option);
567 if (name[0] == ' ' || name[0] == '\n' || name[0] == '\t')
572 char *val = strchr(name, ':');
573 xbt_assert(val, "Option '%s' badly formatted. Should be of the form 'name:value'", name);
574 /* don't free(optionlist_cpy) if the assert fails, 'name' points inside it */
577 if (strncmp(name, "contexts/", strlen("contexts/")) && strncmp(name, "path", strlen("path")))
578 XBT_INFO("Configuration change: Set '%s' to '%s'", name, val);
581 (*simgrid_config)[name].setStringValue(val);
583 catch (simgrid::config::missing_key_error& e) {
591 free(optionlist_cpy);
595 free(optionlist_cpy);
596 THROWF(not_found_error, 0, "Could not set variables %s", options);
599 free(optionlist_cpy);
600 THROWF(unknown_error, 0, "Could not set variables %s", options);
604 // Horrible mess to translate C++ exceptions to C exceptions:
605 // Exit from the catch blog (and do the correct exceptio cleaning)
606 // before attempting to THROWF.
607 #define TRANSLATE_EXCEPTIONS(...) \
608 catch(simgrid::config::missing_key_error& e) { THROWF(not_found_error, 0, __VA_ARGS__); abort(); } \
609 catch(...) { THROWF(not_found_error, 0, __VA_ARGS__); abort(); }
611 /** @brief Set the value of a variable, using the string representation of that value
613 * @param key name of the variable to modify
614 * @param value string representation of the value to set
617 void xbt_cfg_set_as_string(const char *key, const char *value)
620 (*simgrid_config)[key].setStringValue(value);
623 TRANSLATE_EXCEPTIONS("Could not set variable %s as string %s", key, value);
626 /** @brief Set an integer value to \a name within \a cfg if it wasn't changed yet
628 * This is useful to change the default value of a variable while allowing
629 * users to override it with command line arguments
631 void xbt_cfg_setdefault_int(const char *key, int value)
634 (*simgrid_config)[key].setDefaultValue<int>(value);
637 TRANSLATE_EXCEPTIONS("Could not set variable %s to default integer %i",
641 /** @brief Set an integer value to \a name within \a cfg if it wasn't changed yet
643 * This is useful to change the default value of a variable while allowing
644 * users to override it with command line arguments
646 void xbt_cfg_setdefault_double(const char *key, double value)
649 (*simgrid_config)[key].setDefaultValue<double>(value);
652 TRANSLATE_EXCEPTIONS("Could not set variable %s to default double %f",
656 /** @brief Set a string value to \a name within \a cfg if it wasn't changed yet
658 * This is useful to change the default value of a variable while allowing
659 * users to override it with command line arguments
661 void xbt_cfg_setdefault_string(const char *key, const char *value)
664 (*simgrid_config)[key].setDefaultValue<std::string>(value ? value : "");
667 TRANSLATE_EXCEPTIONS("Could not set variable %s to default string %s",
671 /** @brief Set an boolean value to \a name within \a cfg if it wasn't changed yet
673 * This is useful to change the default value of a variable while allowing
674 * users to override it with command line arguments
676 void xbt_cfg_setdefault_boolean(const char *key, const char *value)
679 (*simgrid_config)[key].setDefaultValue<bool>(simgrid::config::parseBool(value));
682 TRANSLATE_EXCEPTIONS("Could not set variable %s to default boolean %s",
686 /** @brief Set an integer 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_int(const char *key, int value)
694 (*simgrid_config)[key].setValue<int>(value);
697 TRANSLATE_EXCEPTIONS("Could not set variable %s to integer %i",
701 /** @brief Set or add a double value to \a name within \a cfg
703 * @param key the name of the variable
704 * @param value the double to set
706 void xbt_cfg_set_double(const char *key, double value)
709 (*simgrid_config)[key].setValue<double>(value);
712 TRANSLATE_EXCEPTIONS("Could not set variable %s to double %f",
716 /** @brief Set or add a string value to \a name within \a cfg
718 * @param key the name of the variable
719 * @param value the value to be added
722 void xbt_cfg_set_string(const char *key, const char *value)
725 (*simgrid_config)[key].setValue<std::string>(value ? value : "");
728 TRANSLATE_EXCEPTIONS("Could not set variable %s to string %s",
732 /** @brief Set or add a boolean value to \a name within \a cfg
734 * @param key the name of the variable
735 * @param value the value of the variable
737 void xbt_cfg_set_boolean(const char *key, const char *value)
740 (*simgrid_config)[key].setValue<bool>(simgrid::config::parseBool(value));
743 TRANSLATE_EXCEPTIONS("Could not set variable %s to boolean %s",
748 /* Say if the value is the default value */
749 int xbt_cfg_is_default_value(const char *key)
752 return (*simgrid_config)[key].isDefault() ? 1 : 0;
754 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
757 /*----[ Getting ]---------------------------------------------------------*/
758 /** @brief Retrieve an integer 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.
764 int xbt_cfg_get_int(const char *key)
767 return (*simgrid_config)[key].getValue<int>();
769 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
772 /** @brief Retrieve a double value of a variable (get a warning if not uniq)
774 * @param key the name of the variable
776 * Returns the first value from the config set under the given name.
778 double xbt_cfg_get_double(const char *key)
781 return (*simgrid_config)[key].getValue<double>();
783 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
786 /** @brief Retrieve a string value of a variable (get a warning if not uniq)
788 * @param key the name of the variable
790 * Returns the first value from the config set under the given name.
791 * If there is more than one value, it will issue a warning.
792 * Returns nullptr if there is no value.
794 * \warning the returned value is the actual content of the config set
796 char *xbt_cfg_get_string(const char *key)
799 return (char*) (*simgrid_config)[key].getValue<std::string>().c_str();
801 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
804 /** @brief Retrieve a boolean value of a variable (get a warning if not uniq)
806 * @param key the name of the variable
808 * Returns the first value from the config set under the given name.
809 * If there is more than one value, it will issue a warning.
811 int xbt_cfg_get_boolean(const char *key)
814 return (*simgrid_config)[key].getValue<bool>() ? 1 : 0;
816 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
826 #include <xbt/config.hpp>
828 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(xbt_cfg);
830 XBT_TEST_SUITE("config", "Configuration support");
832 XBT_PUBLIC_DATA(xbt_cfg_t) simgrid_config;
834 static void make_set()
836 simgrid_config = nullptr;
837 xbt_log_threshold_set(&_XBT_LOGV(xbt_cfg), xbt_log_priority_critical);
838 xbt_cfg_register_int("speed", 0, nullptr, "");
839 xbt_cfg_register_string("peername", "", nullptr, "");
840 xbt_cfg_register_string("user", "", nullptr, "");
841 } /* end_of_make_set */
843 XBT_TEST_UNIT("memuse", test_config_memuse, "Alloc and free a config set")
845 auto temp = simgrid_config;
847 xbt_test_add("Alloc and free a config set");
848 xbt_cfg_set_parse("peername:veloce user:bidule");
849 xbt_cfg_free(&simgrid_config);
850 simgrid_config = temp;
853 XBT_TEST_UNIT("use", test_config_use, "Data retrieving tests")
855 auto temp = simgrid_config;
857 xbt_test_add("Get a single value");
859 /* get_single_value */
862 xbt_cfg_set_parse("peername:toto:42 speed:42");
863 ival = xbt_cfg_get_int("speed");
865 xbt_test_fail("Speed value = %d, I expected 42", ival);
868 xbt_test_add("Access to a non-existant entry");
871 xbt_cfg_set_parse("color:blue");
873 if (e.category != not_found_error)
874 xbt_test_exception(e);
877 xbt_cfg_free(&simgrid_config);
878 simgrid_config = temp;
881 XBT_TEST_UNIT("c++flags", test_config_cxx_flags, "C++ flags")
883 auto temp = simgrid_config;
885 xbt_test_add("C++ declaration of flags");
887 simgrid::config::Flag<int> int_flag("int", "", 0);
888 simgrid::config::Flag<std::string> string_flag("string", "", "foo");
889 simgrid::config::Flag<double> double_flag("double", "", 0.32);
890 simgrid::config::Flag<bool> bool_flag1("bool1", "", false);
891 simgrid::config::Flag<bool> bool_flag2("bool2", "", true);
893 xbt_test_add("Parse values");
894 xbt_cfg_set_parse("int:42 string:bar double:8.0 bool1:true bool2:false");
895 xbt_test_assert(int_flag == 42, "Check int flag");
896 xbt_test_assert(string_flag == "bar", "Check string flag");
897 xbt_test_assert(double_flag == 8.0, "Check double flag");
898 xbt_test_assert(bool_flag1, "Check bool1 flag");
899 xbt_test_assert(!bool_flag2, "Check bool2 flag");
901 xbt_cfg_free(&simgrid_config);
902 simgrid_config = temp;
905 #endif /* SIMGRID_TEST */