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>
22 #include "simgrid/sg_config.hpp"
23 #include "xbt/dynar.h"
26 #include "xbt/sysdep.h"
27 #include <xbt/config.h>
28 #include <xbt/config.hpp>
31 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_cfg, xbt, "configuration support");
33 XBT_EXPORT_NO_IMPORT xbt_cfg_t simgrid_config = nullptr;
40 const char* true_values[] = {
41 "yes", "on", "true", "1"
43 const char* false_values[] = {
44 "no", "off", "false", "0"
47 static bool parseBool(const char* value)
49 for (const char* const& true_value : true_values)
50 if (std::strcmp(true_value, value) == 0)
52 for (const char* const& false_value : false_values)
53 if (std::strcmp(false_value, value) == 0)
55 throw std::range_error("not a boolean");
58 static double parseDouble(const char* value)
62 double res = std::strtod(value, &end);
64 throw std::range_error("out of range");
66 xbt_die("Unexpected errno");
67 if (end == value || *end != '\0')
68 throw std::range_error("invalid double");
73 static long int parseLong(const char* value)
77 long int res = std::strtol(value, &end, 0);
79 if (res == LONG_MIN && errno == ERANGE)
80 throw std::range_error("underflow");
81 else if (res == LONG_MAX && errno == ERANGE)
82 throw std::range_error("overflow");
83 xbt_die("Unexpected errno");
85 if (end == value || *end != '\0')
86 throw std::range_error("invalid integer");
91 // ***** ConfigType *****
93 /// A trait which define possible options types:
94 template <class T> class ConfigType;
96 template <> class ConfigType<int> {
98 static constexpr const char* type_name = "int";
99 static inline double parse(const char* value)
101 return parseLong(value);
104 template <> class ConfigType<double> {
106 static constexpr const char* type_name = "double";
107 static inline double parse(const char* value)
109 return parseDouble(value);
112 template <> class ConfigType<std::string> {
114 static constexpr const char* type_name = "string";
115 static inline std::string parse(const char* value)
117 return std::string(value);
120 template <> class ConfigType<bool> {
122 static constexpr const char* type_name = "boolean";
123 static inline bool parse(const char* value)
125 return parseBool(value);
129 // **** Forward declarations ****
131 class ConfigurationElement ;
132 template<class T> class TypedConfigurationElement;
134 // **** ConfigurationElement ****
136 class ConfigurationElement {
140 bool isdefault = true;
144 xbt_cfg_cb_t old_callback = nullptr;
146 ConfigurationElement(const char* key, const char* desc) : 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()=default;
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 void unsetDefault() { isdefault = false; }
172 bool isDefault() const { return isdefault; }
174 std::string const& getDescription() const { return desc; }
175 std::string const& getKey() const { return key; }
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, xbt_cfg_cb_t cb)
192 : ConfigurationElement(key, desc, cb), content(std::move(value))
194 TypedConfigurationElement(const char* key, const char* desc, T value, std::function<void(T&)> callback)
195 : ConfigurationElement(key, desc), content(std::move(value)), callback(std::move(callback))
197 ~TypedConfigurationElement() = default;
199 std::string getStringValue() override;
200 const char* getTypeName() override;
201 void setStringValue(const char* value) override;
206 this->old_callback(getKey().c_str());
208 this->callback(this->content);
211 T const& getValue() const { return content; }
213 void setValue(T value)
215 this->content = std::move(value);
217 this->unsetDefault();
220 void setDefaultValue(T value)
222 if (this->isDefault()) {
223 this->content = std::move(value);
226 XBT_DEBUG("Do not override configuration variable '%s' with value '%s' because it was already set.",
227 getKey().c_str(), to_string(value).c_str());
233 std::string TypedConfigurationElement<T>::getStringValue() // override
235 return to_string(content);
239 void TypedConfigurationElement<T>::setStringValue(const char* value) // override
241 this->content = ConfigType<T>::parse(value);
242 this->unsetDefault();
247 const char* TypedConfigurationElement<T>::getTypeName() // override
249 return ConfigType<T>::type_name;
252 } // end of anonymous namespace
258 // name -> ConfigElement:
259 std::map<std::string, simgrid::config::ConfigurationElement*> options;
260 // alias -> ConfigElement from options:
261 std::map<std::string, simgrid::config::ConfigurationElement*> aliases;
262 bool warn_for_aliases = true;
269 Config(Config const&) = delete;
270 Config& operator=(Config const&) = delete;
272 ConfigurationElement& operator[](const char* name);
273 void alias(const char* realname, const char* aliasname);
275 template<class T, class... A>
276 simgrid::config::TypedConfigurationElement<T>*
277 registerOption(const char* name, A&&... a)
279 xbt_assert(options.find(name) == options.end(), "Refusing to register the config element '%s' twice.", name);
280 TypedConfigurationElement<T>* variable = new TypedConfigurationElement<T>(name, std::forward<A>(a)...);
281 XBT_DEBUG("Register cfg elm %s (%s) of type %s @%p in set %p)", name, variable->getDescription().c_str(),
282 variable->getTypeName(), variable, this);
283 options.insert({name, variable});
289 void dump(const char *name, const char *indent);
294 ConfigurationElement* getDictElement(const char* name);
299 atexit(&sg_config_finalize);
303 XBT_DEBUG("Frees cfg set %p", this);
304 for (auto const& elm : options)
308 inline ConfigurationElement* Config::getDictElement(const char* name)
310 auto opt = options.find(name);
311 if (opt != options.end()) {
314 auto als = aliases.find(name);
315 if (als != aliases.end()) {
316 ConfigurationElement* res = als->second;
317 if (warn_for_aliases)
318 XBT_INFO("Option %s has been renamed to %s. Consider switching.", name, res->getKey().c_str());
321 THROWF(not_found_error, 0, "Bad config key: %s", name);
326 inline ConfigurationElement& Config::operator[](const char* name)
328 return *(getDictElement(name));
331 void Config::alias(const char* realname, const char* aliasname)
333 xbt_assert(aliases.find(aliasname) == aliases.end(), "Alias '%s' already.", aliasname);
334 ConfigurationElement* element = this->getDictElement(realname);
335 xbt_assert(element, "Cannot define an alias to the non-existing option '%s'.", realname);
336 this->aliases.insert({aliasname, element});
339 /** @brief Dump a config set for debuging purpose
341 * @param name The name to give to this config set
342 * @param indent what to write at the beginning of each line (right number of spaces)
344 void Config::dump(const char *name, const char *indent)
347 printf("%s>> Dumping of the config set '%s':\n", indent, name);
349 for (auto const& elm : options)
350 printf("%s %s: ()%s) %s", indent, elm.first.c_str(), elm.second->getTypeName(),
351 elm.second->getStringValue().c_str());
354 printf("%s<< End of the config set '%s'\n", indent, name);
358 /** @brief Displays the declared aliases and their replacement */
359 void Config::showAliases()
361 for (auto const& elm : aliases)
362 printf(" %-40s %s\n", elm.first.c_str(), elm.second->getKey().c_str());
365 /** @brief Displays the declared options and their description */
368 for (auto const& elm : options) {
369 simgrid::config::ConfigurationElement* variable = this->options.at(elm.first);
370 printf(" %s: %s\n", elm.first.c_str(), variable->getDescription().c_str());
371 printf(" Type: %s; ", variable->getTypeName());
372 printf("Current value: %s\n", variable->getStringValue().c_str());
376 // ***** getConfig *****
378 template <class T> XBT_PUBLIC T const& getConfig(const char* name)
380 return (*simgrid_config)[name].getValue<T>();
383 template XBT_PUBLIC int const& getConfig<int>(const char* name);
384 template XBT_PUBLIC double const& getConfig<double>(const char* name);
385 template XBT_PUBLIC bool const& getConfig<bool>(const char* name);
386 template XBT_PUBLIC std::string const& getConfig<std::string>(const char* name);
390 void alias(const char* realname, std::initializer_list<const char*> aliases)
392 for (auto const& aliasname : aliases)
393 simgrid_config->alias(realname, aliasname);
396 // ***** declareFlag *****
399 XBT_PUBLIC void declareFlag(const char* name, const char* description, T value, std::function<void(const T&)> callback)
401 if (simgrid_config == nullptr)
402 simgrid_config = xbt_cfg_new();
403 simgrid_config->registerOption<T>(
404 name, description, std::move(value), std::move(callback));
407 template XBT_PUBLIC void declareFlag(const char* name, const char* description, int value,
408 std::function<void(int const&)> callback);
409 template XBT_PUBLIC void declareFlag(const char* name, const char* description, double value,
410 std::function<void(double const&)> callback);
411 template XBT_PUBLIC void declareFlag(const char* name, const char* description, bool value,
412 std::function<void(bool const&)> callback);
413 template XBT_PUBLIC void declareFlag(const char* name, const char* description, std::string value,
414 std::function<void(std::string const&)> callback);
418 // ***** C bindings *****
420 xbt_cfg_t xbt_cfg_new()
422 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 simgrid_config->registerOption<int>(name, desc, default_value, cb_set);
448 void xbt_cfg_register_string(const char *name, const char *default_value, xbt_cfg_cb_t cb_set, const char *desc)
450 if (simgrid_config == nullptr)
451 simgrid_config = xbt_cfg_new();
452 simgrid_config->registerOption<std::string>(name, desc, default_value ? default_value : "", cb_set);
455 void xbt_cfg_register_boolean(const char *name, const char*default_value,xbt_cfg_cb_t cb_set, const char *desc)
457 if (simgrid_config == nullptr)
458 simgrid_config = xbt_cfg_new();
459 simgrid_config->registerOption<bool>(name, desc, simgrid::config::parseBool(default_value), cb_set);
462 void xbt_cfg_register_alias(const char *realname, const char *aliasname)
464 if (simgrid_config == nullptr)
465 simgrid_config = xbt_cfg_new();
466 simgrid_config->alias(realname, aliasname);
469 void xbt_cfg_aliases() { simgrid_config->showAliases(); }
470 void xbt_cfg_help() { simgrid_config->help(); }
472 /*----[ Setting ]---------------------------------------------------------*/
474 /** @brief Add values parsed from a string into a config set
476 * @param options a string containing the content to add to the config set. This is a '\\t',' ' or '\\n' or ','
477 * separated list of variables. Each individual variable is like "[name]:[value]" where [name] is the name of an
478 * already registered variable, and [value] conforms to the data type under which this variable was registered.
480 * @todo This is a crude manual parser, it should be a proper lexer.
482 void xbt_cfg_set_parse(const char *options)
484 if (not options || not strlen(options)) { /* nothing to do */
488 XBT_DEBUG("List to parse and set:'%s'", options);
489 std::string optionlist(options);
490 while (not optionlist.empty()) {
491 XBT_DEBUG("Still to parse and set: '%s'", optionlist.c_str());
494 size_t pos = optionlist.find_first_not_of(" \t\n,");
495 optionlist.erase(0, pos);
497 pos = optionlist.find_first_of(" \t\n,");
498 std::string name = optionlist.substr(0, pos);
499 optionlist.erase(0, pos);
500 XBT_DEBUG("parse now:'%s'; parse later:'%s'", name.c_str(), optionlist.c_str());
505 pos = name.find(':');
506 xbt_assert(pos != std::string::npos, "Option '%s' badly formatted. Should be of the form 'name:value'",
509 std::string val = name.substr(pos + 1);
512 const std::string path("path");
513 if (name.compare(0, path.length(), path) != 0)
514 XBT_INFO("Configuration change: Set '%s' to '%s'", name.c_str(), val.c_str());
516 (*simgrid_config)[name.c_str()].setStringValue(val.c_str());
520 /** @brief Set the value of a variable, using the string representation of that value
522 * @param key name of the variable to modify
523 * @param value string representation of the value to set
526 void xbt_cfg_set_as_string(const char *key, const char *value)
528 (*simgrid_config)[key].setStringValue(value);
531 /** @brief Set an integer value to \a name within \a cfg if it wasn't changed yet
533 * This is useful to change the default value of a variable while allowing
534 * users to override it with command line arguments
536 void xbt_cfg_setdefault_int(const char *key, int value)
538 (*simgrid_config)[key].setDefaultValue<int>(value);
541 /** @brief Set an integer value to \a name within \a cfg if it wasn't changed yet
543 * This is useful to change the default value of a variable while allowing
544 * users to override it with command line arguments
546 void xbt_cfg_setdefault_double(const char *key, double value)
548 (*simgrid_config)[key].setDefaultValue<double>(value);
551 /** @brief Set a string value to \a name within \a cfg if it wasn't changed yet
553 * This is useful to change the default value of a variable while allowing
554 * users to override it with command line arguments
556 void xbt_cfg_setdefault_string(const char *key, const char *value)
558 (*simgrid_config)[key].setDefaultValue<std::string>(value ? value : "");
561 /** @brief Set an boolean value to \a name within \a cfg if it wasn't changed yet
563 * This is useful to change the default value of a variable while allowing
564 * users to override it with command line arguments
566 void xbt_cfg_setdefault_boolean(const char *key, const char *value)
568 (*simgrid_config)[key].setDefaultValue<bool>(simgrid::config::parseBool(value));
571 /** @brief Set an integer value to \a name within \a cfg
573 * @param key the name of the variable
574 * @param value the value of the variable
576 void xbt_cfg_set_int(const char *key, int value)
578 (*simgrid_config)[key].setValue<int>(value);
581 /** @brief Set or add a double value to \a name within \a cfg
583 * @param key the name of the variable
584 * @param value the double to set
586 void xbt_cfg_set_double(const char *key, double value)
588 (*simgrid_config)[key].setValue<double>(value);
591 /** @brief Set or add a string value to \a name within \a cfg
593 * @param key the name of the variable
594 * @param value the value to be added
597 void xbt_cfg_set_string(const char* key, const char* value)
599 (*simgrid_config)[key].setValue<std::string>(value);
602 /** @brief Set or add a boolean value to \a name within \a cfg
604 * @param key the name of the variable
605 * @param value the value of the variable
607 void xbt_cfg_set_boolean(const char *key, const char *value)
609 (*simgrid_config)[key].setValue<bool>(simgrid::config::parseBool(value));
613 /* Say if the value is the default value */
614 int xbt_cfg_is_default_value(const char *key)
616 return (*simgrid_config)[key].isDefault() ? 1 : 0;
619 /*----[ Getting ]---------------------------------------------------------*/
620 /** @brief Retrieve an integer value of a variable (get a warning if not uniq)
622 * @param key the name of the variable
624 * Returns the first value from the config set under the given name.
626 int xbt_cfg_get_int(const char *key)
628 return (*simgrid_config)[key].getValue<int>();
631 /** @brief Retrieve a double value of a variable (get a warning if not uniq)
633 * @param key the name of the variable
635 * Returns the first value from the config set under the given name.
637 double xbt_cfg_get_double(const char *key)
639 return (*simgrid_config)[key].getValue<double>();
642 /** @brief Retrieve a string value of a variable (get a warning if not uniq)
644 * @param key the name of the variable
646 * Returns the first value from the config set under the given name.
647 * If there is more than one value, it will issue a warning.
648 * Returns nullptr if there is no value.
650 * \warning the returned value is the actual content of the config set
652 std::string xbt_cfg_get_string(const char* key)
654 return (*simgrid_config)[key].getValue<std::string>();
657 /** @brief Retrieve a boolean value of a variable (get a warning if not uniq)
659 * @param key the name of the variable
661 * Returns the first value from the config set under the given name.
662 * If there is more than one value, it will issue a warning.
664 int xbt_cfg_get_boolean(const char *key)
666 return (*simgrid_config)[key].getValue<bool>() ? 1 : 0;
675 #include <xbt/ex.hpp>
677 #include <xbt/config.hpp>
679 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(xbt_cfg);
681 XBT_TEST_SUITE("config", "Configuration support");
683 XBT_PUBLIC_DATA xbt_cfg_t simgrid_config;
685 static void make_set()
687 simgrid_config = nullptr;
688 xbt_log_threshold_set(&_XBT_LOGV(xbt_cfg), xbt_log_priority_critical);
689 simgrid::config::declareFlag<int>("speed", "description", 0);
690 simgrid::config::declareFlag<std::string>("peername", "description", "");
691 simgrid::config::declareFlag<std::string>("user", "description", "");
692 } /* end_of_make_set */
694 XBT_TEST_UNIT("memuse", test_config_memuse, "Alloc and free a config set")
696 auto temp = simgrid_config;
698 xbt_test_add("Alloc and free a config set");
699 xbt_cfg_set_parse("peername:veloce user:bidule");
700 xbt_cfg_free(&simgrid_config);
701 simgrid_config = temp;
704 XBT_TEST_UNIT("use", test_config_use, "Data retrieving tests")
706 auto temp = simgrid_config;
708 xbt_test_add("Get a single value");
710 /* get_single_value */
711 xbt_cfg_set_parse("peername:toto:42 speed:42");
712 int ival = xbt_cfg_get_int("speed");
714 xbt_test_fail("Speed value = %d, I expected 42", ival);
717 xbt_test_add("Access to a non-existant entry");
720 xbt_cfg_set_parse("color:blue");
722 if (e.category != not_found_error)
723 xbt_test_exception(e);
726 xbt_cfg_free(&simgrid_config);
727 simgrid_config = temp;
730 XBT_TEST_UNIT("c++flags", test_config_cxx_flags, "C++ flags")
732 auto temp = simgrid_config;
734 xbt_test_add("C++ declaration of flags");
736 simgrid::config::Flag<int> int_flag("int", "", 0);
737 simgrid::config::Flag<std::string> string_flag("string", "", "foo");
738 simgrid::config::Flag<double> double_flag("double", "", 0.32);
739 simgrid::config::Flag<bool> bool_flag1("bool1", "", false);
740 simgrid::config::Flag<bool> bool_flag2("bool2", "", true);
742 xbt_test_add("Parse values");
743 xbt_cfg_set_parse("int:42 string:bar double:8.0 bool1:true bool2:false");
744 xbt_test_assert(int_flag == 42, "Check int flag");
745 xbt_test_assert(string_flag == "bar", "Check string flag");
746 xbt_test_assert(double_flag == 8.0, "Check double flag");
747 xbt_test_assert(bool_flag1, "Check bool1 flag");
748 xbt_test_assert(not bool_flag2, "Check bool2 flag");
750 xbt_cfg_free(&simgrid_config);
751 simgrid_config = temp;
754 #endif /* SIMGRID_TEST */