1 /* Copyright (c) 2004-2014,2016. The SimGrid Team.
2 * All rights reserved. */
14 #include <type_traits>
16 #include <xbt/config.h>
17 #include <xbt/config.hpp>
19 #include "xbt/sysdep.h"
22 #include "xbt/dynar.h"
27 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_cfg, xbt, "configuration support");
29 XBT_EXPORT_NO_IMPORT(xbt_cfg_t) simgrid_config = NULL;
38 const char* true_values[] = {
39 "yes", "on", "true", "1"
41 const char* false_values[] = {
42 "no", "off", "false", "0"
45 static bool parseBool(const char* value)
47 for (const char* true_value : true_values)
48 if (std::strcmp(true_value, value) == 0)
50 for (const char* false_value : false_values)
51 if (std::strcmp(false_value, value) == 0)
53 throw std::domain_error("not a boolean");
56 static double parseDouble(const char* value)
60 double res = std::strtod(value, &end);
62 throw std::range_error("out of range");
64 xbt_die("Unexpected errno");
65 if (end == value || *end != '\0')
66 throw std::range_error("invalid double");
71 static long int parseLong(const char* value)
75 long int res = std::strtol(value, &end, 0);
77 if (res == LONG_MIN && errno == ERANGE)
78 throw std::range_error("underflow");
79 else if (res == LONG_MAX && errno == ERANGE)
80 throw std::range_error("overflow");
81 xbt_die("Unexpected errno");
83 if (end == value || *end != '\0')
84 throw std::range_error("invalid integer");
89 // ***** ConfigType *****
91 /// A trait which define possible options types:
92 template<class T> struct ConfigType;
94 template<> struct ConfigType<int> {
95 static constexpr const char* type_name = "int";
96 static inline double parse(const char* value)
98 return parseLong(value);
101 template<> struct ConfigType<double> {
102 static constexpr const char* type_name = "double";
103 static inline double parse(const char* value)
105 return parseDouble(value);
108 template<> struct ConfigType<std::string> {
109 static constexpr const char* type_name = "string";
110 static inline std::string parse(const char* value)
112 return std::string(value);
115 template<> struct ConfigType<bool> {
116 static constexpr const char* type_name = "boolean";
117 static inline bool parse(const char* value)
119 return parseBool(value);
123 // **** Forward declarations ****
125 class ConfigurationElement ;
126 template<class T> class TypedConfigurationElement;
128 // **** ConfigurationElement ****
130 class ConfigurationElement {
134 bool isdefault = true;
139 xbt_cfg_cb_t old_callback = nullptr;
141 ConfigurationElement(const char* key, const char* desc)
142 : key(key ? key : ""), desc(desc ? desc : "") {}
143 ConfigurationElement(const char* key, const char* desc, xbt_cfg_cb_t cb)
144 : key(key ? key : ""), desc(desc ? desc : ""), old_callback(cb) {}
146 virtual ~ConfigurationElement();
148 virtual std::string getStringValue() = 0;
149 virtual void setStringValue(const char* value) = 0;
150 virtual const char* getTypeName() = 0;
153 T const& getValue() const
155 return dynamic_cast<const TypedConfigurationElement<T>&>(*this).getValue();
158 void setValue(T value)
160 dynamic_cast<TypedConfigurationElement<T>&>(*this).setValue(std::move(value));
163 void setDefaultValue(T value)
165 dynamic_cast<TypedConfigurationElement<T>&>(*this).setDefaultValue(std::move(value));
167 bool isDefault() const { return isdefault; }
169 std::string const& getDescription() const { return desc; }
172 ConfigurationElement::~ConfigurationElement() {}
174 // **** TypedConfigurationElement<T> ****
176 // TODO, could we use boost::any with some Type* reference?
178 class TypedConfigurationElement : public ConfigurationElement {
181 std::function<void(T&)> callback;
184 TypedConfigurationElement(const char* key, const char* desc, T value = T())
185 : ConfigurationElement(key, desc), content(std::move(value))
187 TypedConfigurationElement(const char* key, const char* desc, T value,
189 : ConfigurationElement(key, desc, cb), content(std::move(value))
191 TypedConfigurationElement(const char* key, const char* desc, T value,
192 std::function<void(T&)> callback)
193 : ConfigurationElement(key, desc), content(std::move(value)),
194 callback(std::move(callback))
196 ~TypedConfigurationElement() override;
198 std::string getStringValue() override;
199 const char* getTypeName() override;
200 void setStringValue(const char* value) override;
205 this->old_callback(key.c_str());
207 this->callback(this->content);
210 T const& getValue() const { return content; }
212 void setValue(T value)
214 this->content = std::move(value);
218 void setDefaultValue(T value)
220 if (this->isdefault) {
221 this->content = std::move(value);
224 XBT_DEBUG("Do not override configuration variable '%s' with value '%s'"
225 " because it was already set.", key.c_str(), to_string(value).c_str());
231 std::string TypedConfigurationElement<T>::getStringValue() // override
233 return to_string(content);
237 void TypedConfigurationElement<T>::setStringValue(const char* value) // override
239 this->content = ConfigType<T>::parse(value);
240 this->isdefault = false;
245 const char* TypedConfigurationElement<T>::getTypeName() // override
247 return ConfigType<T>::type_name;
251 TypedConfigurationElement<T>::~TypedConfigurationElement()
254 } // end of anonymous namespace
260 // name -> ConfigElement:
262 // alias -> xbt_dict_elm_t from options:
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(xbt_dict_get_or_null(this->options, name) == nullptr,
283 "Refusing to register the config element '%s' twice.", name);
284 TypedConfigurationElement<T>* variable =
285 new TypedConfigurationElement<T>(name, std::forward<A>(a)...);
286 XBT_DEBUG("Register cfg elm %s (%s) of type %s @%p in set %p)",
288 variable->getDescription().c_str(),
289 variable->getTypeName(), variable, this);
290 xbt_dict_set(this->options, name, variable, NULL);
296 void dump(const char *name, const char *indent);
301 xbt_dictelm_t getDictElement(const char* name);
304 /* Internal stuff used in cache to free a variable */
305 static void xbt_cfgelm_free(void *data)
308 delete (simgrid::config::ConfigurationElement*) data;
312 options(xbt_dict_new_homogeneous(xbt_cfgelm_free)),
313 aliases(xbt_dict_new_homogeneous(NULL))
318 XBT_DEBUG("Frees cfg set %p", this);
319 xbt_dict_free(&this->options);
320 xbt_dict_free(&this->aliases);
324 xbt_dictelm_t Config::getDictElement(const char* name)
326 // We are interested in the options dictelm:
327 xbt_dictelm_t res = xbt_dict_get_elm_or_null(options, name);
330 // The aliases dict stores pointers to the options dictelm:
331 res = (xbt_dictelm_t) xbt_dict_get_or_null(aliases, name);
333 XBT_INFO("Option %s has been renamed to %s. Consider switching.", name, res->key);
338 ConfigurationElement& Config::operator[](const char* name)
340 xbt_dictelm_t elm = getDictElement(name);
342 throw std::invalid_argument(std::string("Bad config key, ") + name);
343 return *(ConfigurationElement*)elm->content;
346 void Config::alias(const char* realname, const char* aliasname)
348 xbt_assert(this->getDictElement(aliasname) == nullptr, "Alias '%s' already.", aliasname);
349 xbt_dictelm_t element = this->getDictElement(realname);
350 xbt_assert(element, "Cannot define an alias to the non-existing option '%s'.", realname);
351 xbt_dict_set(this->aliases, aliasname, element, NULL);
354 /** @brief Dump a config set for debuging purpose
356 * @param name The name to give to this config set
357 * @param indent what to write at the beginning of each line (right number of spaces)
359 void Config::dump(const char *name, const char *indent)
361 xbt_dict_t dict = this->options;
362 xbt_dict_cursor_t cursor = NULL;
363 simgrid::config::ConfigurationElement* variable = NULL;
367 printf("%s>> Dumping of the config set '%s':\n", indent, name);
369 xbt_dict_foreach(dict, cursor, key, variable)
370 printf("%s %s: ()%s) %s", indent, key,
371 variable->getTypeName(),
372 variable->getStringValue().c_str());
375 printf("%s<< End of the config set '%s'\n", indent, name);
378 xbt_dict_cursor_free(&cursor);
381 /** @brief Displays the declared aliases and their description */
382 void Config::showAliases()
384 xbt_dict_cursor_t dict_cursor;
385 unsigned int dynar_cursor;
386 xbt_dictelm_t dictel;
388 xbt_dynar_t names = xbt_dynar_new(sizeof(char *), NULL);
390 xbt_dict_foreach(this->aliases, dict_cursor, name, dictel)
391 xbt_dynar_push(names, &name);
392 xbt_dynar_sort_strings(names);
394 xbt_dynar_foreach(names, dynar_cursor, name)
395 printf(" %s: %s\n", name, (*this)[name].getDescription().c_str());
398 /** @brief Displays the declared options and their description */
401 xbt_dict_cursor_t dict_cursor;
402 unsigned int dynar_cursor;
403 simgrid::config::ConfigurationElement* variable;
405 xbt_dynar_t names = xbt_dynar_new(sizeof(char *), NULL);
407 xbt_dict_foreach(this->options, dict_cursor, name, variable)
408 xbt_dynar_push(names, &name);
409 xbt_dynar_sort_strings(names);
411 xbt_dynar_foreach(names, dynar_cursor, name) {
412 variable = (simgrid::config::ConfigurationElement*) xbt_dict_get(this->options, name);
413 printf(" %s: %s\n", name, variable->getDescription().c_str());
414 printf(" Type: %s; ", variable->getTypeName());
415 printf("Current value: %s\n", variable->getStringValue().c_str());
417 xbt_dynar_free(&names);
420 // ***** getConfig *****
423 XBT_PUBLIC(T const&) getConfig(const char* name)
425 return (*simgrid_config)[name].getValue<T>();
428 template XBT_PUBLIC(int const&) getConfig<int>(const char* name);
429 template XBT_PUBLIC(double const&) getConfig<double>(const char* name);
430 template XBT_PUBLIC(bool const&) getConfig<bool>(const char* name);
431 template XBT_PUBLIC(std::string const&) getConfig<std::string>(const char* name);
433 // ***** declareFlag *****
436 XBT_PUBLIC(void) declareFlag(const char* name, const char* description,
437 T value, std::function<void(const T&)> callback)
439 if (simgrid_config == NULL)
440 simgrid_config = xbt_cfg_new();
441 simgrid_config->registerOption<T>(
442 name, description, std::move(value), std::move(callback));
445 template XBT_PUBLIC(void) declareFlag(const char* name,
446 const char* description, int value, std::function<void(int const &)> callback);
447 template XBT_PUBLIC(void) declareFlag(const char* name,
448 const char* description, double value, std::function<void(double const &)> callback);
449 template XBT_PUBLIC(void) declareFlag(const char* name,
450 const char* description, bool value, std::function<void(bool const &)> callback);
451 template XBT_PUBLIC(void) declareFlag(const char* name,
452 const char* description, std::string value, std::function<void(std::string const &)> callback);
458 // ***** C bindings *****
460 xbt_cfg_t xbt_cfg_new(void) { return new simgrid::config::Config(); }
461 void xbt_cfg_free(xbt_cfg_t * cfg) { delete *cfg; }
463 void xbt_cfg_dump(const char *name, const char *indent, xbt_cfg_t cfg)
465 cfg->dump(name, indent);
468 /*----[ Registering stuff ]-----------------------------------------------*/
470 void xbt_cfg_register_double(const char *name, double default_value,
471 xbt_cfg_cb_t cb_set, const char *desc)
473 if (simgrid_config == NULL)
474 simgrid_config = xbt_cfg_new();
475 simgrid_config->registerOption<double>(name, desc, default_value, cb_set);
478 void xbt_cfg_register_int(const char *name, int default_value,xbt_cfg_cb_t cb_set, const char *desc)
480 if (simgrid_config == NULL)
481 simgrid_config = xbt_cfg_new();
482 simgrid_config->registerOption<int>(name, desc, default_value, cb_set);
485 void xbt_cfg_register_string(const char *name, const char *default_value, xbt_cfg_cb_t cb_set, const char *desc)
487 if (simgrid_config == NULL)
488 simgrid_config = xbt_cfg_new();
489 simgrid_config->registerOption<std::string>(name, desc,
490 default_value ? default_value : "", cb_set);
493 void xbt_cfg_register_boolean(const char *name, const char*default_value,xbt_cfg_cb_t cb_set, const char *desc)
495 if (simgrid_config == NULL)
496 simgrid_config = xbt_cfg_new();
497 simgrid_config->registerOption<bool>(name, desc, simgrid::config::parseBool(default_value), cb_set);
500 void xbt_cfg_register_alias(const char *realname, const char *aliasname)
502 if (simgrid_config == NULL)
503 simgrid_config = xbt_cfg_new();
504 simgrid_config->alias(realname, aliasname);
507 void xbt_cfg_aliases(void) { simgrid_config->showAliases(); }
508 void xbt_cfg_help(void) { simgrid_config->help(); }
510 /*----[ Setting ]---------------------------------------------------------*/
512 /** @brief Add values parsed from a string into a config set
514 * @param options a string containing the content to add to the config set. This is a '\\t',' ' or '\\n' or ','
515 * separated list of variables. Each individual variable is like "[name]:[value]" where [name] is the name of an
516 * already registered variable, and [value] conforms to the data type under which this variable was registered.
518 * @todo This is a crude manual parser, it should be a proper lexer.
520 void xbt_cfg_set_parse(const char *options)
522 if (!options || !strlen(options)) { /* nothing to do */
525 char *optionlist_cpy = xbt_strdup(options);
527 XBT_DEBUG("List to parse and set:'%s'", options);
528 char *option = optionlist_cpy;
529 while (1) { /* breaks in the code */
533 int len = strlen(name);
534 XBT_DEBUG("Still to parse and set: '%s'. len=%d; option-name=%ld", name, len, (long) (option - name));
537 while (option - name <= (len - 1) && *option != ' ' && *option != '\n' && *option != '\t' && *option != ',') {
538 XBT_DEBUG("Take %c.", *option);
541 if (option - name == len) {
542 XBT_DEBUG("Boundary=EOL");
543 option = NULL; /* don't do next iteration */
545 XBT_DEBUG("Boundary on '%c'. len=%d;option-name=%ld", *option, len, (long) (option - name));
546 /* Pass the following blank chars */
548 while (option - name < (len - 1) && (*option == ' ' || *option == '\n' || *option == '\t')) {
549 /* fprintf(stderr,"Ignore a blank char.\n"); */
552 if (option - name == len - 1)
553 option = NULL; /* don't do next iteration */
555 XBT_DEBUG("parse now:'%s'; parse later:'%s'", name, option);
557 if (name[0] == ' ' || name[0] == '\n' || name[0] == '\t')
562 char *val = strchr(name, ':');
563 xbt_assert(val, "Option '%s' badly formatted. Should be of the form 'name:value'", name);
564 /* don't free(optionlist_cpy) if the assert fails, 'name' points inside it */
567 if (strncmp(name, "contexts/", strlen("contexts/")) && strncmp(name, "path", strlen("path")))
568 XBT_INFO("Configuration change: Set '%s' to '%s'", name, val);
571 (*simgrid_config)[name].setStringValue(val);
574 THROWF(not_found_error, 0, "Could not set the value %s for %s", val, name);
578 free(optionlist_cpy);
581 /** @brief Set the value of a variable, using the string representation of that value
583 * @param key name of the variable to modify
584 * @param value string representation of the value to set
587 void xbt_cfg_set_as_string(const char *key, const char *value)
590 (*simgrid_config)[key].setStringValue(value);
592 catch (std::exception const& e) {
593 THROWF(unknown_error, 0, "%s", e.what());
597 /** @brief Set an integer value to \a name within \a cfg if it wasn't changed yet
599 * This is useful to change the default value of a variable while allowing
600 * users to override it with command line arguments
602 void xbt_cfg_setdefault_int(const char *name, int val)
605 (*simgrid_config)[name].setDefaultValue<int>(val);
607 catch (std::exception const& e) {
608 THROWF(unknown_error, 0, "%s", e.what());
612 /** @brief Set an integer value to \a name within \a cfg if it wasn't changed yet
614 * This is useful to change the default value of a variable while allowing
615 * users to override it with command line arguments
617 void xbt_cfg_setdefault_double(const char *name, double val)
620 (*simgrid_config)[name].setDefaultValue<double>(val);
622 catch (std::exception const& e) {
623 THROWF(unknown_error, 0, "%s", e.what());
627 /** @brief Set a string value to \a name within \a cfg if it wasn't changed yet
629 * This is useful to change the default value of a variable while allowing
630 * users to override it with command line arguments
632 void xbt_cfg_setdefault_string(const char *name, const char *val)
635 (*simgrid_config)[name].setDefaultValue<std::string>(val ? val : "");
637 catch (std::exception const& e) {
638 THROWF(unknown_error, 0, "%s", e.what());
642 /** @brief Set an boolean value to \a name within \a cfg if it wasn't changed yet
644 * This is useful to change the default value of a variable while allowing
645 * users to override it with command line arguments
647 void xbt_cfg_setdefault_boolean(const char *name, const char *val)
650 (*simgrid_config)[name].setDefaultValue<bool>(simgrid::config::parseBool(val));
652 catch (std::exception const& e) {
653 THROWF(unknown_error, 0, "%s", e.what());
657 /** @brief Set an integer value to \a name within \a cfg
659 * @param name the name of the variable
660 * @param val the value of the variable
662 void xbt_cfg_set_int(const char *name, int val)
665 (*simgrid_config)[name].setValue<int>(val);
667 catch (std::exception const& e) {
668 THROWF(unknown_error, 0, "%s", e.what());
672 /** @brief Set or add a double value to \a name within \a cfg
674 * @param name the name of the variable
675 * @param val the double to set
677 void xbt_cfg_set_double(const char *name, double val)
680 (*simgrid_config)[name].setValue<double>(val);
682 catch (std::exception const& e) {
683 THROWF(unknown_error, 0, "%s", e.what());
687 /** @brief Set or add a string value to \a name within \a cfg
689 * @param cfg the config set
690 * @param name the name of the variable
691 * @param val the value to be added
694 void xbt_cfg_set_string(const char *name, const char *val)
697 (*simgrid_config)[name].setValue<std::string>(val ? val : "");
699 catch (std::exception const& e) {
700 THROWF(unknown_error, 0, "%s", e.what());
704 /** @brief Set or add a boolean value to \a name within \a cfg
706 * @param name the name of the variable
707 * @param val the value of the variable
709 void xbt_cfg_set_boolean(const char *name, const char *val)
712 (*simgrid_config)[name].setValue<bool>(simgrid::config::parseBool(val));
714 catch (std::exception const& e) {
715 THROWF(unknown_error, 0, "%s", e.what());
720 /* Say if the value is the default value */
721 int xbt_cfg_is_default_value(const char *name)
724 return (*simgrid_config)[name].isDefault() ? 1 : 0;
726 catch (std::exception const& e) {
727 THROWF(unknown_error, 0, "%s", e.what());
731 /*----[ Getting ]---------------------------------------------------------*/
732 /** @brief Retrieve an integer value of a variable (get a warning if not uniq)
734 * @param name the name of the variable
736 * Returns the first value from the config set under the given name.
738 int xbt_cfg_get_int(const char *name)
741 return (*simgrid_config)[name].getValue<int>();
743 catch (std::exception const& e) {
744 THROWF(unknown_error, 0, "%s", e.what());
748 /** @brief Retrieve a double value of a variable (get a warning if not uniq)
750 * @param cfg the config set
751 * @param name the name of the variable
753 * Returns the first value from the config set under the given name.
755 double xbt_cfg_get_double(const char *name)
758 return (*simgrid_config)[name].getValue<double>();
760 catch (std::exception const& e) {
761 THROWF(unknown_error, 0, "%s", e.what());
765 /** @brief Retrieve a string value of a variable (get a warning if not uniq)
767 * @param cfg the config set
768 * @param name the name of the variable
770 * Returns the first value from the config set under the given name.
771 * If there is more than one value, it will issue a warning.
772 * Returns NULL if there is no value.
774 * \warning the returned value is the actual content of the config set
776 char *xbt_cfg_get_string(const char *name)
779 return (char*) (*simgrid_config)[name].getValue<std::string>().c_str();
781 catch (std::exception const& e) {
782 THROWF(unknown_error, 0, "%s", e.what());
786 /** @brief Retrieve a boolean value of a variable (get a warning if not uniq)
788 * @param cfg the config set
789 * @param name the name of the variable
791 * Returns the first value from the config set under the given name.
792 * If there is more than one value, it will issue a warning.
794 int xbt_cfg_get_boolean(const char *name)
797 return (*simgrid_config)[name].getValue<bool>() ? 1 : 0;
799 catch (std::exception const& e) {
800 THROWF(unknown_error, 0, "%s", e.what());
811 #include <xbt/config.hpp>
813 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(xbt_cfg);
815 XBT_TEST_SUITE("config", "Configuration support");
817 XBT_PUBLIC_DATA(xbt_cfg_t) simgrid_config;
819 static void make_set()
821 simgrid_config = NULL;
822 xbt_log_threshold_set(&_XBT_LOGV(xbt_cfg), xbt_log_priority_critical);
823 xbt_cfg_register_int("speed", 0, NULL, "");
824 xbt_cfg_register_string("peername", "", NULL, "");
825 xbt_cfg_register_string("user", "", NULL, "");
826 } /* end_of_make_set */
828 XBT_TEST_UNIT("memuse", test_config_memuse, "Alloc and free a config set")
830 auto temp = simgrid_config;
832 xbt_test_add("Alloc and free a config set");
833 xbt_cfg_set_parse("peername:veloce user:bidule");
834 xbt_cfg_free(&simgrid_config);
835 simgrid_config = temp;
838 XBT_TEST_UNIT("use", test_config_use, "Data retrieving tests")
840 auto temp = simgrid_config;
842 xbt_test_add("Get a single value");
844 /* get_single_value */
847 xbt_cfg_set_parse("peername:toto:42 speed:42");
848 ival = xbt_cfg_get_int("speed");
850 xbt_test_fail("Speed value = %d, I expected 42", ival);
853 xbt_test_add("Access to a non-existant entry");
858 xbt_cfg_set_parse("color:blue");
860 if (e.category != not_found_error)
861 xbt_test_exception(e);
865 xbt_cfg_free(&simgrid_config);
866 simgrid_config = temp;
869 XBT_TEST_UNIT("c++flags", test_config_cxx_flags, "C++ flags")
871 auto temp = simgrid_config;
873 xbt_test_add("C++ declaration of flags");
875 simgrid::config::Flag<int> int_flag("int", "", 0);
876 simgrid::config::Flag<std::string> string_flag("string", "", "foo");
877 simgrid::config::Flag<double> double_flag("double", "", 0.32);
878 simgrid::config::Flag<bool> bool_flag1("bool1", "", false);
879 simgrid::config::Flag<bool> bool_flag2("bool2", "", true);
881 xbt_test_add("Parse values");
882 xbt_cfg_set_parse("int:42 string:bar double:8.0 bool1:true bool2:false");
883 xbt_test_assert(int_flag == 42, "Check int flag");
884 xbt_test_assert(string_flag == "bar", "Check string flag");
885 xbt_test_assert(double_flag == 8.0, "Check double flag");
886 xbt_test_assert(bool_flag1, "Check bool1 flag");
887 xbt_test_assert(!bool_flag2, "Check bool2 flag");
889 xbt_cfg_free(&simgrid_config);
890 simgrid_config = temp;
893 #endif /* SIMGRID_TEST */