Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Whenever possible, use std::move() for parameters (mostly std::string).
[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 <stdexcept>
16 #include <string>
17 #include <string>
18 #include <type_traits>
19 #include <typeinfo>
20 #include <vector>
21
22 #include "simgrid/Exception.hpp"
23 #include "simgrid/sg_config.hpp"
24 #include "xbt/dynar.h"
25 #include "xbt/log.h"
26 #include "xbt/misc.h"
27 #include "xbt/sysdep.h"
28 #include <xbt/config.h>
29 #include <xbt/config.hpp>
30
31 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_cfg, xbt, "configuration support");
32
33 XBT_EXPORT_NO_IMPORT xbt_cfg_t simgrid_config = nullptr;
34
35 namespace simgrid {
36 namespace config {
37
38 namespace {
39
40 const char* true_values[] = {
41   "yes", "on", "true", "1"
42 };
43 const char* false_values[] = {
44   "no", "off", "false", "0"
45 };
46
47 static bool parse_bool(const char* value)
48 {
49   for (const char* const& true_value : true_values)
50     if (std::strcmp(true_value, value) == 0)
51       return true;
52   for (const char* const& false_value : false_values)
53     if (std::strcmp(false_value, value) == 0)
54       return false;
55   throw std::range_error("not a boolean");
56 }
57
58 static double parse_double(const char* value)
59 {
60   char* end;
61   errno = 0;
62   double res = std::strtod(value, &end);
63   if (errno == ERANGE)
64     throw std::range_error("out of range");
65   else if (errno)
66     xbt_die("Unexpected errno");
67   if (end == value || *end != '\0')
68     throw std::range_error("invalid double");
69   else
70     return res;
71 }
72
73 static long int parse_long(const char* value)
74 {
75   char* end;
76   errno = 0;
77   long int res = std::strtol(value, &end, 0);
78   if (errno) {
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");
84   }
85   if (end == value || *end != '\0')
86     throw std::range_error("invalid integer");
87   else
88     return res;
89 }
90
91 // ***** ConfigType *****
92
93 /// A trait which define possible options types:
94 template <class T> class ConfigType;
95
96 template <> class ConfigType<int> {
97 public:
98   static constexpr const char* type_name = "int";
99   static inline double parse(const char* value)
100   {
101     return parse_long(value);
102   }
103 };
104 template <> class ConfigType<double> {
105 public:
106   static constexpr const char* type_name = "double";
107   static inline double parse(const char* value)
108   {
109     return parse_double(value);
110   }
111 };
112 template <> class ConfigType<std::string> {
113 public:
114   static constexpr const char* type_name = "string";
115   static inline std::string parse(const char* value)
116   {
117     return std::string(value);
118   }
119 };
120 template <> class ConfigType<bool> {
121 public:
122   static constexpr const char* type_name = "boolean";
123   static inline bool parse(const char* value)
124   {
125     return parse_bool(value);
126   }
127 };
128
129 // **** Forward declarations ****
130
131 class ConfigurationElement ;
132 template<class T> class TypedConfigurationElement;
133
134 // **** ConfigurationElement ****
135
136 class ConfigurationElement {
137 private:
138   std::string key;
139   std::string desc;
140   bool isdefault = true;
141
142 public:
143   /* Callback */
144   xbt_cfg_cb_t old_callback = nullptr;
145
146   ConfigurationElement(std::string key, std::string desc) : key(key), desc(desc) {}
147   ConfigurationElement(std::string key, std::string desc, xbt_cfg_cb_t cb) : key(key), desc(desc), old_callback(cb) {}
148
149   virtual ~ConfigurationElement() = default;
150
151   virtual std::string get_string_value()           = 0;
152   virtual void set_string_value(const char* value) = 0;
153   virtual const char* get_type_name()              = 0;
154
155   template <class T> T const& get_value() const
156   {
157     return dynamic_cast<const TypedConfigurationElement<T>&>(*this).get_value();
158   }
159   template <class T> void set_value(T value)
160   {
161     dynamic_cast<TypedConfigurationElement<T>&>(*this).set_value(std::move(value));
162   }
163   template <class T> void set_default_value(T value)
164   {
165     dynamic_cast<TypedConfigurationElement<T>&>(*this).set_default_value(std::move(value));
166   }
167   void unset_default() { isdefault = false; }
168   bool is_default() const { return isdefault; }
169
170   std::string const& get_description() const { return desc; }
171   std::string const& get_key() const { return key; }
172 };
173
174 // **** TypedConfigurationElement<T> ****
175
176 // TODO, could we use boost::any with some Type* reference?
177 template<class T>
178 class TypedConfigurationElement : public ConfigurationElement {
179 private:
180   T content;
181   std::function<void(T&)> callback;
182
183 public:
184   TypedConfigurationElement(std::string key, std::string desc, T value = T())
185       : ConfigurationElement(key, desc), content(std::move(value))
186   {}
187   TypedConfigurationElement(std::string key, std::string desc, T value, xbt_cfg_cb_t cb)
188       : ConfigurationElement(key, desc, cb), content(std::move(value))
189   {}
190   TypedConfigurationElement(std::string key, std::string desc, T value, std::function<void(T&)> callback)
191       : ConfigurationElement(key, desc), content(std::move(value)), callback(std::move(callback))
192   {}
193   ~TypedConfigurationElement() = default;
194
195   std::string get_string_value() override;
196   const char* get_type_name() override;
197   void set_string_value(const char* value) override;
198
199   void update()
200   {
201     if (old_callback)
202       this->old_callback(get_key().c_str());
203     if (this->callback)
204       this->callback(this->content);
205   }
206
207   T const& get_value() const { return content; }
208
209   void set_value(T value)
210   {
211     this->content = std::move(value);
212     this->update();
213     this->unset_default();
214   }
215
216   void set_default_value(T value)
217   {
218     if (this->is_default()) {
219       this->content = std::move(value);
220       this->update();
221     } else {
222       XBT_DEBUG("Do not override configuration variable '%s' with value '%s' because it was already set.",
223                 get_key().c_str(), to_string(value).c_str());
224     }
225   }
226 };
227
228 template <class T> std::string TypedConfigurationElement<T>::get_string_value() // override
229 {
230   return to_string(content);
231 }
232
233 template <class T> void TypedConfigurationElement<T>::set_string_value(const char* value) // override
234 {
235   this->content = ConfigType<T>::parse(value);
236   this->unset_default();
237   this->update();
238 }
239
240 template <class T> const char* TypedConfigurationElement<T>::get_type_name() // override
241 {
242   return ConfigType<T>::type_name;
243 }
244
245 } // end of anonymous namespace
246
247 // **** Config ****
248
249 class Config {
250 private:
251   // name -> ConfigElement:
252   std::map<std::string, simgrid::config::ConfigurationElement*> options;
253   // alias -> ConfigElement from options:
254   std::map<std::string, simgrid::config::ConfigurationElement*> aliases;
255   bool warn_for_aliases = true;
256
257 public:
258   Config();
259   ~Config();
260
261   // No copy:
262   Config(Config const&) = delete;
263   Config& operator=(Config const&) = delete;
264
265   ConfigurationElement& operator[](std::string name);
266   void alias(std::string realname, std::string aliasname);
267
268   template <class T, class... A>
269   simgrid::config::TypedConfigurationElement<T>* register_option(std::string name, A&&... a)
270   {
271     xbt_assert(options.find(name) == options.end(), "Refusing to register the config element '%s' twice.",
272                name.c_str());
273     TypedConfigurationElement<T>* variable = new TypedConfigurationElement<T>(name, std::forward<A>(a)...);
274     XBT_DEBUG("Register cfg elm %s (%s) of type %s @%p in set %p)", name.c_str(), variable->get_description().c_str(),
275               variable->get_type_name(), variable, this);
276     options.insert({name, variable});
277     variable->update();
278     return variable;
279   }
280
281   // Debug:
282   void dump(const char *name, const char *indent);
283   void show_aliases();
284   void help();
285
286 protected:
287   ConfigurationElement* get_dict_element(std::string name);
288 };
289
290 Config::Config()
291 {
292   atexit(&sg_config_finalize);
293 }
294 Config::~Config()
295 {
296   XBT_DEBUG("Frees cfg set %p", this);
297   for (auto const& elm : options)
298     delete elm.second;
299 }
300
301 inline ConfigurationElement* Config::get_dict_element(std::string name)
302 {
303   auto opt = options.find(name);
304   if (opt != options.end()) {
305     return opt->second;
306   } else {
307     auto als = aliases.find(name);
308     if (als != aliases.end()) {
309       ConfigurationElement* res = als->second;
310       if (warn_for_aliases)
311         XBT_INFO("Option %s has been renamed to %s. Consider switching.", name.c_str(), res->get_key().c_str());
312       return res;
313     } else {
314       THROWF(not_found_error, 0, "Bad config key: %s", name.c_str());
315     }
316   }
317 }
318
319 inline ConfigurationElement& Config::operator[](std::string name)
320 {
321   return *(get_dict_element(name));
322 }
323
324 void Config::alias(std::string realname, std::string aliasname)
325 {
326   xbt_assert(aliases.find(aliasname) == aliases.end(), "Alias '%s' already.", aliasname.c_str());
327   ConfigurationElement* element = this->get_dict_element(realname);
328   xbt_assert(element, "Cannot define an alias to the non-existing option '%s'.", realname.c_str());
329   this->aliases.insert({aliasname, element});
330 }
331
332 /** @brief Dump a config set for debuging purpose
333  *
334  * @param name The name to give to this config set
335  * @param indent what to write at the beginning of each line (right number of spaces)
336  */
337 void Config::dump(const char *name, const char *indent)
338 {
339   if (name)
340     printf("%s>> Dumping of the config set '%s':\n", indent, name);
341
342   for (auto const& elm : options)
343     printf("%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     printf("%s<< End of the config set '%s'\n", indent, name);
348   fflush(stdout);
349 }
350
351 /** @brief Displays the declared aliases and their replacement */
352 void Config::show_aliases()
353 {
354   for (auto const& elm : aliases)
355     printf("   %-40s %s\n", elm.first.c_str(), elm.second->get_key().c_str());
356 }
357
358 /** @brief Displays the declared options and their description */
359 void Config::help()
360 {
361   for (auto const& elm : options) {
362     simgrid::config::ConfigurationElement* variable = this->options.at(elm.first);
363     printf("   %s: %s\n", elm.first.c_str(), variable->get_description().c_str());
364     printf("       Type: %s; ", variable->get_type_name());
365     printf("Current value: %s\n", variable->get_string_value().c_str());
366   }
367 }
368
369 // ***** set_default *****
370
371 template <class T> XBT_PUBLIC void set_default(const char* name, T value)
372 {
373   (*simgrid_config)[name].set_default_value<T>(std::move(value));
374 }
375
376 template XBT_PUBLIC void set_default<int>(const char* name, int value);
377 template XBT_PUBLIC void set_default<double>(const char* name, double value);
378 template XBT_PUBLIC void set_default<bool>(const char* name, bool value);
379 template XBT_PUBLIC void set_default<std::string>(const char* name, std::string value);
380
381 bool is_default(const char* name)
382 {
383   return (*simgrid_config)[name].is_default();
384 }
385
386 // ***** set_value *****
387
388 template <class T> XBT_PUBLIC void set_value(const char* name, T value)
389 {
390   (*simgrid_config)[name].set_value<T>(std::move(value));
391 }
392
393 template XBT_PUBLIC void set_value<int>(const char* name, int value);
394 template XBT_PUBLIC void set_value<double>(const char* name, double value);
395 template XBT_PUBLIC void set_value<bool>(const char* name, bool value);
396 template XBT_PUBLIC void set_value<std::string>(const char* name, std::string value);
397
398 void set_as_string(const char* name, const std::string& value)
399 {
400   (*simgrid_config)[name].set_string_value(value.c_str());
401 }
402
403 void set_parse(std::string options)
404 {
405   XBT_DEBUG("List to parse and set:'%s'", options.c_str());
406   while (not options.empty()) {
407     XBT_DEBUG("Still to parse and set: '%s'", options.c_str());
408
409     // skip separators
410     size_t pos = options.find_first_not_of(" \t\n,");
411     options.erase(0, pos);
412     // find option
413     pos              = options.find_first_of(" \t\n,");
414     std::string name = options.substr(0, pos);
415     options.erase(0, pos);
416     XBT_DEBUG("parse now:'%s'; parse later:'%s'", name.c_str(), options.c_str());
417
418     if (name.empty())
419       continue;
420
421     pos = name.find(':');
422     xbt_assert(pos != std::string::npos, "Option '%s' badly formatted. Should be of the form 'name:value'",
423                name.c_str());
424
425     std::string val = name.substr(pos + 1);
426     name.erase(pos);
427
428     const std::string path("path");
429     if (name.compare(0, path.length(), path) != 0)
430       XBT_INFO("Configuration change: Set '%s' to '%s'", name.c_str(), val.c_str());
431
432     set_as_string(name.c_str(), val);
433   }
434 }
435
436 // ***** get_value *****
437
438 template <class T> XBT_PUBLIC T const& get_value(std::string name)
439 {
440   return (*simgrid_config)[name].get_value<T>();
441 }
442
443 template XBT_PUBLIC int const& get_value<int>(std::string name);
444 template XBT_PUBLIC double const& get_value<double>(std::string name);
445 template XBT_PUBLIC bool const& get_value<bool>(std::string name);
446 template XBT_PUBLIC std::string const& get_value<std::string>(std::string name);
447
448 // ***** alias *****
449
450 void alias(const char* realname, std::initializer_list<const char*> aliases)
451 {
452   for (auto const& aliasname : aliases)
453     simgrid_config->alias(realname, aliasname);
454 }
455
456 // ***** declare_flag *****
457
458 template <class T>
459 XBT_PUBLIC void declare_flag(std::string name, std::string description, T value, 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, std::move(description), std::move(value), std::move(callback));
464 }
465
466 template XBT_PUBLIC void declare_flag(std::string name, std::string description, int value,
467                                       std::function<void(int const&)> callback);
468 template XBT_PUBLIC void declare_flag(std::string name, std::string description, double value,
469                                       std::function<void(double const&)> callback);
470 template XBT_PUBLIC void declare_flag(std::string name, std::string description, bool value,
471                                       std::function<void(bool const&)> callback);
472 template XBT_PUBLIC void declare_flag(std::string name, 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 // ***** C bindings *****
494
495 xbt_cfg_t xbt_cfg_new()
496 {
497   return new simgrid::config::Config();
498 }
499 void xbt_cfg_free(xbt_cfg_t * cfg) { delete *cfg; }
500
501 void xbt_cfg_dump(const char *name, const char *indent, xbt_cfg_t cfg)
502 {
503   cfg->dump(name, indent);
504 }
505
506 /*----[ Registering stuff ]-----------------------------------------------*/
507
508 void xbt_cfg_register_double(const char *name, double default_value,
509   xbt_cfg_cb_t cb_set, const char *desc)
510 {
511   if (simgrid_config == nullptr)
512     simgrid_config = new simgrid::config::Config();
513   simgrid_config->register_option<double>(name, desc, default_value, cb_set);
514 }
515
516 void xbt_cfg_register_int(const char *name, int default_value,xbt_cfg_cb_t cb_set, const char *desc)
517 {
518   if (simgrid_config == nullptr)
519     simgrid_config = new simgrid::config::Config();
520   simgrid_config->register_option<int>(name, desc, default_value, cb_set);
521 }
522
523 void xbt_cfg_register_string(const char *name, const char *default_value, xbt_cfg_cb_t cb_set, const char *desc)
524 {
525   if (simgrid_config == nullptr)
526     simgrid_config = new simgrid::config::Config();
527   simgrid_config->register_option<std::string>(name, desc, default_value ? default_value : "", cb_set);
528 }
529
530 void xbt_cfg_register_boolean(const char *name, const char*default_value,xbt_cfg_cb_t cb_set, const char *desc)
531 {
532   if (simgrid_config == nullptr)
533     simgrid_config = new simgrid::config::Config();
534   simgrid_config->register_option<bool>(name, desc, simgrid::config::parse_bool(default_value), cb_set);
535 }
536
537 void xbt_cfg_register_alias(const char *realname, const char *aliasname)
538 {
539   if (simgrid_config == nullptr)
540     simgrid_config = new simgrid::config::Config();
541   simgrid_config->alias(realname, aliasname);
542 }
543
544 void xbt_cfg_aliases()
545 {
546   simgrid_config->show_aliases();
547 }
548 void xbt_cfg_help()
549 {
550   simgrid_config->help();
551 }
552
553 /*----[ Setting ]---------------------------------------------------------*/
554
555 /** @brief Add values parsed from a string into a config set
556  *
557  * @param options a string containing the content to add to the config set. This is a '\\t',' ' or '\\n' or ','
558  * separated list of variables. Each individual variable is like "[name]:[value]" where [name] is the name of an
559  * already registered variable, and [value] conforms to the data type under which this variable was registered.
560  *
561  * @todo This is a crude manual parser, it should be a proper lexer.
562  */
563 void xbt_cfg_set_parse(const char *options)
564 {
565   if (options && strlen(options) > 0)
566     simgrid::config::set_parse(std::string(options));
567 }
568
569 /** @brief Set the value of a variable, using the string representation of that value
570  *
571  * @param key name of the variable to modify
572  * @param value string representation of the value to set
573  */
574
575 void xbt_cfg_set_as_string(const char *key, const char *value)
576 {
577   (*simgrid_config)[key].set_string_value(value);
578 }
579
580 /** @brief Set an integer value to \a name within \a cfg if it wasn't changed yet
581  *
582  * This is useful to change the default value of a variable while allowing
583  * users to override it with command line arguments
584  */
585 void xbt_cfg_setdefault_int(const char *key, int value)
586 {
587   (*simgrid_config)[key].set_default_value<int>(value);
588 }
589
590 /** @brief Set an integer value to \a name within \a cfg if it wasn't changed yet
591  *
592  * This is useful to change the default value of a variable while allowing
593  * users to override it with command line arguments
594  */
595 void xbt_cfg_setdefault_double(const char *key, double value)
596 {
597   (*simgrid_config)[key].set_default_value<double>(value);
598 }
599
600 /** @brief Set a string value to \a name within \a cfg if it wasn't changed yet
601  *
602  * This is useful to change the default value of a variable while allowing
603  * users to override it with command line arguments
604  */
605 void xbt_cfg_setdefault_string(const char *key, const char *value)
606 {
607   (*simgrid_config)[key].set_default_value<std::string>(value ? value : "");
608 }
609
610 /** @brief Set an boolean value to \a name within \a cfg if it wasn't changed yet
611  *
612  * This is useful to change the default value of a variable while allowing
613  * users to override it with command line arguments
614  */
615 void xbt_cfg_setdefault_boolean(const char *key, const char *value)
616 {
617   (*simgrid_config)[key].set_default_value<bool>(simgrid::config::parse_bool(value));
618 }
619
620 /** @brief Set an integer value to \a name within \a cfg
621  *
622  * @param key the name of the variable
623  * @param value the value of the variable
624  */
625 void xbt_cfg_set_int(const char *key, int value)
626 {
627   (*simgrid_config)[key].set_value<int>(value);
628 }
629
630 /** @brief Set or add a double value to \a name within \a cfg
631  *
632  * @param key the name of the variable
633  * @param value the double to set
634  */
635 void xbt_cfg_set_double(const char *key, double value)
636 {
637   (*simgrid_config)[key].set_value<double>(value);
638 }
639
640 /** @brief Set or add a string value to \a name within \a cfg
641  *
642  * @param key the name of the variable
643  * @param value the value to be added
644  *
645  */
646 void xbt_cfg_set_string(const char* key, const char* value)
647 {
648   (*simgrid_config)[key].set_value<std::string>(value);
649 }
650
651 /** @brief Set or add a boolean value to \a name within \a cfg
652  *
653  * @param key the name of the variable
654  * @param value the value of the variable
655  */
656 void xbt_cfg_set_boolean(const char *key, const char *value)
657 {
658   (*simgrid_config)[key].set_value<bool>(simgrid::config::parse_bool(value));
659 }
660
661
662 /* Say if the value is the default value */
663 int xbt_cfg_is_default_value(const char *key)
664 {
665   return (*simgrid_config)[key].is_default() ? 1 : 0;
666 }
667
668 /*----[ Getting ]---------------------------------------------------------*/
669 /** @brief Retrieve an integer value of a variable (get a warning if not uniq)
670  *
671  * @param key the name of the variable
672  *
673  * Returns the first value from the config set under the given name.
674  */
675 int xbt_cfg_get_int(const char *key)
676 {
677   return (*simgrid_config)[key].get_value<int>();
678 }
679
680 /** @brief Retrieve a double value of a variable (get a warning if not uniq)
681  *
682  * @param key the name of the variable
683  *
684  * Returns the first value from the config set under the given name.
685  */
686 double xbt_cfg_get_double(const char *key)
687 {
688   return (*simgrid_config)[key].get_value<double>();
689 }
690
691 /** @brief Retrieve a string value of a variable (get a warning if not uniq)
692  *
693  * @param key the name of the variable
694  *
695  * Returns the first value from the config set under the given name.
696  * If there is more than one value, it will issue a warning.
697  * Returns nullptr if there is no value.
698  *
699  * \warning the returned value is the actual content of the config set
700  */
701 std::string xbt_cfg_get_string(const char* key)
702 {
703   return (*simgrid_config)[key].get_value<std::string>();
704 }
705
706 /** @brief Retrieve a boolean value of a variable (get a warning if not uniq)
707  *
708  * @param key the name of the variable
709  *
710  * Returns the first value from the config set under the given name.
711  * If there is more than one value, it will issue a warning.
712  */
713 int xbt_cfg_get_boolean(const char *key)
714 {
715   return (*simgrid_config)[key].get_value<bool>() ? 1 : 0;
716 }