Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Remove features marked with XBT_ATTRIB_DEPRECATED_v325.
[simgrid.git] / src / xbt / config.cpp
1 /* Copyright (c) 2004-2019. The SimGrid Team. All rights reserved.     */
2
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. */
5
6 #include <cstdio>
7
8 #include <algorithm>
9 #include <cerrno>
10 #include <cstring>
11 #include <climits>
12
13 #include <functional>
14 #include <map>
15 #include <memory>
16 #include <stdexcept>
17 #include <string>
18 #include <string>
19 #include <type_traits>
20 #include <typeinfo>
21 #include <vector>
22
23 #include "simgrid/Exception.hpp"
24 #include "simgrid/sg_config.hpp"
25 #include "xbt/dynar.h"
26 #include "xbt/log.h"
27 #include "xbt/misc.h"
28 #include "xbt/sysdep.h"
29 #include <xbt/config.h>
30 #include <xbt/config.hpp>
31
32 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_cfg, xbt, "configuration support");
33
34 XBT_EXPORT_NO_IMPORT xbt_cfg_t simgrid_config = nullptr;
35
36 namespace simgrid {
37 namespace config {
38
39 namespace {
40
41 const char* true_values[] = {
42   "yes", "on", "true", "1"
43 };
44 const char* false_values[] = {
45   "no", "off", "false", "0"
46 };
47
48 static bool parse_bool(const char* value)
49 {
50   for (const char* const& true_value : true_values)
51     if (std::strcmp(true_value, value) == 0)
52       return true;
53   for (const char* const& false_value : false_values)
54     if (std::strcmp(false_value, value) == 0)
55       return false;
56   throw std::range_error("not a boolean");
57 }
58
59 static double parse_double(const char* value)
60 {
61   char* end;
62   errno = 0;
63   double res = std::strtod(value, &end);
64   if (errno == ERANGE)
65     throw std::range_error("out of range");
66   else if (errno)
67     xbt_die("Unexpected errno");
68   if (end == value || *end != '\0')
69     throw std::range_error("invalid double");
70   else
71     return res;
72 }
73
74 static long int parse_long(const char* value)
75 {
76   char* end;
77   errno = 0;
78   long int res = std::strtol(value, &end, 0);
79   if (errno) {
80     if (res == LONG_MIN && errno == ERANGE)
81       throw std::range_error("underflow");
82     else if (res == LONG_MAX && errno == ERANGE)
83       throw std::range_error("overflow");
84     xbt_die("Unexpected errno");
85   }
86   if (end == value || *end != '\0')
87     throw std::range_error("invalid integer");
88   else
89     return res;
90 }
91
92 // ***** ConfigType *****
93
94 /// A trait which define possible options types:
95 template <class T> class ConfigType;
96
97 template <> class ConfigType<int> {
98 public:
99   static constexpr const char* type_name = "int";
100   static inline double parse(const char* value)
101   {
102     return parse_long(value);
103   }
104 };
105 template <> class ConfigType<double> {
106 public:
107   static constexpr const char* type_name = "double";
108   static inline double parse(const char* value)
109   {
110     return parse_double(value);
111   }
112 };
113 template <> class ConfigType<std::string> {
114 public:
115   static constexpr const char* type_name = "string";
116   static inline std::string parse(const char* value)
117   {
118     return std::string(value);
119   }
120 };
121 template <> class ConfigType<bool> {
122 public:
123   static constexpr const char* type_name = "boolean";
124   static inline bool parse(const char* value)
125   {
126     return parse_bool(value);
127   }
128 };
129
130 // **** Forward declarations ****
131
132 class ConfigurationElement ;
133 template<class T> class TypedConfigurationElement;
134
135 // **** ConfigurationElement ****
136
137 class ConfigurationElement {
138 private:
139   std::string key;
140   std::string desc;
141   bool isdefault = true;
142
143 public:
144   /* Callback */
145   xbt_cfg_cb_t old_callback = nullptr;
146
147   ConfigurationElement(const std::string& key, const std::string& desc) : key(key), desc(desc) {}
148   ConfigurationElement(const std::string& key, const std::string& desc, xbt_cfg_cb_t cb)
149       : key(key), desc(desc), old_callback(cb)
150   {
151   }
152
153   virtual ~ConfigurationElement() = default;
154
155   virtual std::string get_string_value()           = 0;
156   virtual void set_string_value(const char* value) = 0;
157   virtual const char* get_type_name()              = 0;
158
159   template <class T> T const& get_value() const
160   {
161     return static_cast<const TypedConfigurationElement<T>&>(*this).get_value();
162   }
163   template <class T> void set_value(T value)
164   {
165     static_cast<TypedConfigurationElement<T>&>(*this).set_value(std::move(value));
166   }
167   template <class T> void set_default_value(T value)
168   {
169     static_cast<TypedConfigurationElement<T>&>(*this).set_default_value(std::move(value));
170   }
171   void unset_default() { isdefault = false; }
172   bool is_default() const { return isdefault; }
173
174   std::string const& get_description() const { return desc; }
175   std::string const& get_key() const { return key; }
176 };
177
178 // **** TypedConfigurationElement<T> ****
179
180 // TODO, could we use boost::any with some Type* reference?
181 template<class T>
182 class TypedConfigurationElement : public ConfigurationElement {
183 private:
184   T content;
185   std::function<void(T&)> callback;
186
187 public:
188   TypedConfigurationElement(const std::string& key, const std::string& desc, T value = T())
189       : ConfigurationElement(key, desc), content(std::move(value))
190   {}
191   TypedConfigurationElement(const std::string& key, const std::string& desc, T value, xbt_cfg_cb_t cb)
192       : ConfigurationElement(key, desc, cb), content(std::move(value))
193   {}
194   TypedConfigurationElement(const std::string& key, const std::string& desc, T value, std::function<void(T&)> callback)
195       : ConfigurationElement(key, desc), content(std::move(value)), callback(std::move(callback))
196   {}
197   ~TypedConfigurationElement() = default;
198
199   std::string get_string_value() override;
200   const char* get_type_name() override;
201   void set_string_value(const char* value) override;
202
203   void update()
204   {
205     if (old_callback)
206       this->old_callback(get_key().c_str());
207     if (this->callback)
208       this->callback(this->content);
209   }
210
211   T const& get_value() const { return content; }
212
213   void set_value(T value)
214   {
215     this->content = std::move(value);
216     this->update();
217     this->unset_default();
218   }
219
220   void set_default_value(T value)
221   {
222     if (this->is_default()) {
223       this->content = std::move(value);
224       this->update();
225     } else {
226       XBT_DEBUG("Do not override configuration variable '%s' with value '%s' because it was already set.",
227                 get_key().c_str(), to_string(value).c_str());
228     }
229   }
230 };
231
232 template <class T> std::string TypedConfigurationElement<T>::get_string_value() // override
233 {
234   return to_string(content);
235 }
236
237 template <class T> void TypedConfigurationElement<T>::set_string_value(const char* value) // override
238 {
239   this->content = ConfigType<T>::parse(value);
240   this->unset_default();
241   this->update();
242 }
243
244 template <class T> const char* TypedConfigurationElement<T>::get_type_name() // override
245 {
246   return ConfigType<T>::type_name;
247 }
248
249 } // end of anonymous namespace
250
251 // **** Config ****
252
253 class Config {
254 private:
255   // name -> ConfigElement:
256   std::map<std::string, std::unique_ptr<ConfigurationElement>> options;
257   // alias -> ConfigElement from options:
258   std::map<std::string, ConfigurationElement*> aliases;
259   bool warn_for_aliases = true;
260
261 public:
262   Config();
263
264   // No copy:
265   Config(Config const&) = delete;
266   Config& operator=(Config const&) = delete;
267
268   ConfigurationElement& operator[](const std::string& name);
269   void alias(const std::string& realname, const std::string& aliasname);
270
271   template <class T, class... A> TypedConfigurationElement<T>* register_option(const std::string& name, A&&... a)
272   {
273     xbt_assert(options.find(name) == options.end(), "Refusing to register the config element '%s' twice.",
274                name.c_str());
275     TypedConfigurationElement<T>* variable = new TypedConfigurationElement<T>(name, std::forward<A>(a)...);
276     XBT_DEBUG("Register cfg elm %s (%s) of type %s @%p in set %p)", name.c_str(), variable->get_description().c_str(),
277               variable->get_type_name(), variable, this);
278     options[name].reset(variable);
279     variable->update();
280     return variable;
281   }
282
283   // Debug:
284   void dump(const char *name, const char *indent);
285   void show_aliases();
286   void help();
287
288 protected:
289   ConfigurationElement* get_dict_element(const std::string& name);
290 };
291
292 Config::Config()
293 {
294   atexit(&sg_config_finalize);
295 }
296
297 inline ConfigurationElement* Config::get_dict_element(const std::string& name)
298 {
299   auto opt = options.find(name);
300   if (opt != options.end()) {
301     return opt->second.get();
302   } else {
303     auto als = aliases.find(name);
304     if (als != aliases.end()) {
305       ConfigurationElement* res = als->second;
306       if (warn_for_aliases)
307         XBT_INFO("Option %s has been renamed to %s. Consider switching.", name.c_str(), res->get_key().c_str());
308       return res;
309     } else {
310       std::string msg = "Bad config key: " + name + "\nExisting config keys:\n";
311       for (auto const& elm : options)
312         msg += "  " + elm.first + ": (" + elm.second->get_type_name() + ")" + elm.second->get_string_value() + "\n";
313       throw std::out_of_range(msg);
314     }
315   }
316 }
317
318 inline ConfigurationElement& Config::operator[](const std::string& name)
319 {
320   return *(get_dict_element(name));
321 }
322
323 void Config::alias(const std::string& realname, const std::string& aliasname)
324 {
325   xbt_assert(aliases.find(aliasname) == aliases.end(), "Alias '%s' already.", aliasname.c_str());
326   ConfigurationElement* element = this->get_dict_element(realname);
327   xbt_assert(element, "Cannot define an alias to the non-existing option '%s'.", realname.c_str());
328   this->aliases.insert({aliasname, element});
329 }
330
331 /** @brief Dump a config set for debuging purpose
332  *
333  * @param name The name to give to this config set
334  * @param indent what to write at the beginning of each line (right number of spaces)
335  */
336 void Config::dump(const char *name, const char *indent)
337 {
338   XBT_LOG_DEFAULT_CATEGORY(xbt_help);
339   if (name)
340     XBT_VERB("%s>> Dumping of the config set '%s':", indent, name);
341
342   for (auto const& elm : options)
343     XBT_VERB("%s  %s: ()%s) %s", indent, elm.first.c_str(), elm.second->get_type_name(),
344              elm.second->get_string_value().c_str());
345
346   if (name)
347     XBT_VERB("%s<< End of the config set '%s'", indent, name);
348 }
349
350 /** @brief Displays the declared aliases and their replacement */
351 void Config::show_aliases()
352 {
353   for (auto const& elm : aliases)
354     XBT_HELP("   %-40s %s", elm.first.c_str(), elm.second->get_key().c_str());
355 }
356
357 /** @brief Displays the declared options and their description */
358 void Config::help()
359 {
360   for (auto const& elm : options) {
361     simgrid::config::ConfigurationElement* variable = elm.second.get();
362     XBT_HELP("   %s: %s", elm.first.c_str(), variable->get_description().c_str());
363     XBT_HELP("       Type: %s; Current value: %s", variable->get_type_name(), variable->get_string_value().c_str());
364   }
365 }
366
367 // ***** set_default *****
368
369 template <class T> XBT_PUBLIC void set_default(const char* name, T value)
370 {
371   (*simgrid_config)[name].set_default_value<T>(std::move(value));
372 }
373
374 template XBT_PUBLIC void set_default<int>(const char* name, int value);
375 template XBT_PUBLIC void set_default<double>(const char* name, double value);
376 template XBT_PUBLIC void set_default<bool>(const char* name, bool value);
377 template XBT_PUBLIC void set_default<std::string>(const char* name, std::string value);
378
379 bool is_default(const char* name)
380 {
381   return (*simgrid_config)[name].is_default();
382 }
383
384 // ***** set_value *****
385
386 template <class T> XBT_PUBLIC void set_value(const char* name, T value)
387 {
388   (*simgrid_config)[name].set_value<T>(std::move(value));
389 }
390
391 template XBT_PUBLIC void set_value<int>(const char* name, int value);
392 template XBT_PUBLIC void set_value<double>(const char* name, double value);
393 template XBT_PUBLIC void set_value<bool>(const char* name, bool value);
394 template XBT_PUBLIC void set_value<std::string>(const char* name, std::string value);
395
396 void set_as_string(const char* name, const std::string& value)
397 {
398   (*simgrid_config)[name].set_string_value(value.c_str());
399 }
400
401 void set_parse(const std::string& opt)
402 {
403   std::string options(opt);
404   XBT_DEBUG("List to parse and set:'%s'", options.c_str());
405   while (not options.empty()) {
406     XBT_DEBUG("Still to parse and set: '%s'", options.c_str());
407
408     // skip separators
409     size_t pos = options.find_first_not_of(" \t\n,");
410     options.erase(0, pos);
411     // find option
412     pos              = options.find_first_of(" \t\n,");
413     std::string name = options.substr(0, pos);
414     options.erase(0, pos);
415     XBT_DEBUG("parse now:'%s'; parse later:'%s'", name.c_str(), options.c_str());
416
417     if (name.empty())
418       continue;
419
420     pos = name.find(':');
421     xbt_assert(pos != std::string::npos, "Option '%s' badly formatted. Should be of the form 'name:value'",
422                name.c_str());
423
424     std::string val = name.substr(pos + 1);
425     name.erase(pos);
426
427     const std::string path("path");
428     if (name.compare(0, path.length(), path) != 0)
429       XBT_INFO("Configuration change: Set '%s' to '%s'", name.c_str(), val.c_str());
430
431     set_as_string(name.c_str(), val);
432   }
433 }
434
435 // ***** get_value *****
436
437 template <class T> XBT_PUBLIC T const& get_value(const std::string& name)
438 {
439   return (*simgrid_config)[name].get_value<T>();
440 }
441
442 template XBT_PUBLIC int const& get_value<int>(const std::string& name);
443 template XBT_PUBLIC double const& get_value<double>(const std::string& name);
444 template XBT_PUBLIC bool const& get_value<bool>(const std::string& name);
445 template XBT_PUBLIC std::string const& get_value<std::string>(const std::string& name);
446
447 // ***** alias *****
448
449 void alias(const char* realname, std::initializer_list<const char*> aliases)
450 {
451   for (auto const& aliasname : aliases)
452     simgrid_config->alias(realname, aliasname);
453 }
454
455 // ***** declare_flag *****
456
457 template <class T>
458 XBT_PUBLIC void declare_flag(const std::string& name, const std::string& description, T value,
459                              std::function<void(const T&)> callback)
460 {
461   if (simgrid_config == nullptr)
462     simgrid_config = new simgrid::config::Config();
463   simgrid_config->register_option<T>(name, description, std::move(value), std::move(callback));
464 }
465
466 template XBT_PUBLIC void declare_flag(const std::string& name, const std::string& description, int value,
467                                       std::function<void(int const&)> callback);
468 template XBT_PUBLIC void declare_flag(const std::string& name, const std::string& description, double value,
469                                       std::function<void(double const&)> callback);
470 template XBT_PUBLIC void declare_flag(const std::string& name, const std::string& description, bool value,
471                                       std::function<void(bool const&)> callback);
472 template XBT_PUBLIC void declare_flag(const std::string& name, const std::string& description, std::string value,
473                                       std::function<void(std::string const&)> callback);
474
475 void finalize()
476 {
477   delete simgrid_config;
478   simgrid_config = nullptr;
479 }
480
481 void show_aliases()
482 {
483   simgrid_config->show_aliases();
484 }
485
486 void help()
487 {
488   simgrid_config->help();
489 }
490 }
491 }
492
493 /*----[ Setting ]---------------------------------------------------------*/
494
495 /** @brief Set an integer value to \a name within \a cfg
496  *
497  * @param key the name of the variable
498  * @param value the value of the variable
499  */
500 void sg_cfg_set_int(const char* key, int value)
501 {
502   (*simgrid_config)[key].set_value<int>(value);
503 }
504
505 /** @brief Set or add a double value to \a name within \a cfg
506  *
507  * @param key the name of the variable
508  * @param value the double to set
509  */
510 void sg_cfg_set_double(const char* key, double value)
511 {
512   (*simgrid_config)[key].set_value<double>(value);
513 }
514
515 /** @brief Set or add a string value to \a name within \a cfg
516  *
517  * @param key the name of the variable
518  * @param value the value to be added
519  *
520  */
521 void sg_cfg_set_string(const char* key, const char* value)
522 {
523   (*simgrid_config)[key].set_value<std::string>(value);
524 }
525
526 /** @brief Set or add a boolean value to \a name within \a cfg
527  *
528  * @param key the name of the variable
529  * @param value the value of the variable
530  */
531 void sg_cfg_set_boolean(const char* key, const char* value)
532 {
533   (*simgrid_config)[key].set_value<bool>(simgrid::config::parse_bool(value));
534 }
535
536 /*----[ Getting ]---------------------------------------------------------*/
537 /** @brief Retrieve an integer value of a variable (get a warning if not uniq)
538  *
539  * @param key the name of the variable
540  *
541  * Returns the first value from the config set under the given name.
542  */
543 int sg_cfg_get_int(const char* key)
544 {
545   return (*simgrid_config)[key].get_value<int>();
546 }
547
548 /** @brief Retrieve a double value of a variable (get a warning if not uniq)
549  *
550  * @param key the name of the variable
551  *
552  * Returns the first value from the config set under the given name.
553  */
554 double sg_cfg_get_double(const char* key)
555 {
556   return (*simgrid_config)[key].get_value<double>();
557 }
558
559 /** @brief Retrieve a boolean value of a variable (get a warning if not uniq)
560  *
561  * @param key the name of the variable
562  *
563  * Returns the first value from the config set under the given name.
564  * If there is more than one value, it will issue a warning.
565  */
566 int sg_cfg_get_boolean(const char* key)
567 {
568   return (*simgrid_config)[key].get_value<bool>() ? 1 : 0;
569 }