Debian Codegraph @

config_tempest/tempest_conf.py

raw
1 # Copyright 2016, 2017, 2018 Red Hat, Inc.
2 # All Rights Reserved.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License"); you may
5 # not use this file except in compliance with the License. You may obtain
6 # a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations
14 # under the License.
15
16 import os
17 import sys
18
19 from config_tempest import constants as C
20 from oslo_config import cfg
21 from six.moves import configparser
22 import tempest.config
23
24
25 class TempestConf(configparser.ConfigParser):
26
27 CONF = tempest.config.TempestConfigPrivate(parse_conf=False)
28
29 def __init__(self, write_credentials=True, **kwargs):
30 # causes the config parser to preserve case of the options
31 self.optionxform = str
32
33 # set of pairs `(section, key)` which have a higher priority (are
34 # user-defined) and will usually not be overwritten by
35 # `TempestConf.set()`
36 self.priority_sectionkeys = set()
37
38 self.write_credentials = write_credentials
39 super().__init__(**kwargs)
40
41 def get_bool_value(self, value):
42 """Returns boolean value of the string value given.
43
44 :param value: True/False
45 :type value: String
46 :returns: Boolean value of the string value given
47 :rtype: Boolean
48 """
49 strval = str(value).lower()
50 if strval == 'true':
51 return True
52 elif strval == 'false':
53 return False
54 else:
55 raise ValueError("'%s' is not a boolean" % value)
56
57 def get_defaulted(self, section, key):
58 """Returns default value for the section.key pair.
59
60 :param section: a section in a tempest.conf file
61 :type section: String
62 :param key: a key in a section in a tempest.conf file
63 :type key: String
64 :returns: default value for the section.key pair
65 :rtype: String
66 """
67 try:
68 if self.has_option(section, key):
69 return self.get(section, key)
70 else:
71 return self.CONF.get(section).get(key)
72 except cfg.NoSuchOptError:
73 C.LOG.warning("Option %s is not defined in %s section",
74 key, section)
75
76 def set(self, section, key, value, priority=False):
77 """Set value in configuration, similar to `ConfigParser.set`
78
79 Creates non-existent sections. Keeps track of options which were
80 specified by the user and should not be normally overwritten.
81
82 :param section: a section in a tempest.conf file
83 :type section: String
84 :param key: a key in a section in a tempest.conf file
85 :type key: String
86 :param value: a value to be set to the section.key
87 :type value: String
88 :param priority: if True, always over-write the value. If False, don't
89 over-write an existing value if it was written before with a
90 priority (i.e. if it was specified by the user)
91 :type priority: Boolean
92 :returns: True if the value was written, False if not (because of
93 priority)
94 :rtype: Boolean
95 """
96 if not self.has_section(section) and section.lower() != "default":
97 self.add_section(section)
98 if not priority and (section, key) in self.priority_sectionkeys:
99 C.LOG.debug("Option '[%s] %s = %s' was defined by user, NOT"
100 " overwriting into value '%s'", section, key,
101 self.get(section, key), value)
102 return False
103 if priority:
104 self.priority_sectionkeys.add((section, key))
105 C.LOG.debug("Setting [%s] %s = %s", section, key, value)
106 configparser.ConfigParser.set(self, section, key, value)
107 return True
108
109 def write(self, out_path):
110 C.LOG.info("Creating configuration file %s", os.path.abspath(out_path))
111 if not self.write_credentials:
112 C.LOG.info("Credentials will not be printed to a tempest.conf, "
113 "writing credentials is disabled.")
114 self.remove_values(C.ALL_CREDENTIALS_KEYS)
115 with open(out_path, 'w') as f:
116 configparser.ConfigParser.write(self, f)
117
118 def remove_values(self, to_remove):
119 """Remove values from configuration file specified in arguments.
120
121 :param to_remove: {'section.key': [values_to_be_removed], ...}
122 :type to_remove: dict
123 """
124 for key_path in to_remove:
125 section, key = key_path.split('.')
126 try:
127 conf_values = self.get(section, key).split(',')
128 remove = to_remove[key_path]
129 if len(remove) == 0:
130 # delete all values in section.key
131 self.remove_option(section, key)
132 elif len(conf_values) == 1:
133 # make sure only the value specified by user
134 # will be deleted if in the key is other value
135 # than expected, ignore it
136 if conf_values[0] in to_remove[key_path]:
137 self.remove_option(section, key)
138 else:
139 # exclude all unwanted values from the list
140 # and preserve the original order of items
141 conf_values = [v for v in conf_values if v not in remove]
142 self.set(section, key, ",".join(conf_values))
143 except configparser.NoOptionError:
144 # only inform a user, option specified by him doesn't exist
145 C.LOG.error(sys.exc_info()[1])
146 except configparser.NoSectionError:
147 # only inform a user, section specified by him doesn't exist
148 C.LOG.error(sys.exc_info()[1])
149
150 def append_values(self, to_append):
151 """Appends values to configuration file specified in arguments.
152
153 :param to_append: {'section.key': [values_to_be_added], ...}
154 :type to_append: dict
155 """
156 for key_path in to_append:
157 section, key = key_path.split('.')
158 try:
159 conf_val = self.get(section, key).split(',')
160 # omit duplicates if found any
161 conf_val += list(set(to_append[key_path]) - set(conf_val))
162 self.set(section, key, ",".join(conf_val))
163 except configparser.NoOptionError:
164 # only inform a user, option specified by him doesn't exist
165 C.LOG.error(sys.exc_info()[1])
166 except configparser.NoSectionError:
167 # only inform a user, section specified by him doesn't exist
168 C.LOG.error(sys.exc_info()[1])