python3 - 2to3 + miscell obvious tweaks
[sfa.git] / sfa / util / config.py
1 #!/usr/bin/env python3
2 import sys
3 import os
4 import time
5 import tempfile
6 import codecs
7 from sfa.util.xml import XML
8 from sfa.util.py23 import StringIO
9 from sfa.util.py23 import ConfigParser
10
11 default_config = \
12     """
13 """
14
15
16 def isbool(v):
17     return v.lower() in ("true", "false")
18
19
20 def str2bool(v):
21     return v.lower() in ("true", "1")
22
23
24 class Config:
25
26     def __init__(self, config_file='/etc/sfa/sfa_config'):
27         self._files = []
28         self.config_path = os.path.dirname(config_file)
29         self.config = ConfigParser.ConfigParser()
30         self.filename = config_file
31         if not os.path.isfile(self.filename):
32             self.create(self.filename)
33         self.load(self.filename)
34
35     def _header(self):
36         header = """
37 DO NOT EDIT. This file was automatically generated at
38 %s from:
39
40 %s
41 """ % (time.asctime(), os.linesep.join(self._files))
42
43         # Get rid of the surrounding newlines
44         return header.strip().split(os.linesep)
45
46     def create(self, filename):
47         if not os.path.exists(os.path.dirname(filename)):
48             os.makedirs(os.path.dirname(filename))
49         configfile = open(filename, 'w')
50         configfile.write(default_config)
51         configfile.close()
52
53     def load(self, filename):
54         if filename:
55             try:
56                 self.config.read(filename)
57             except ConfigParser.MissingSectionHeaderError:
58                 if filename.endswith('.xml'):
59                     self.load_xml(filename)
60                 else:
61                     self.load_shell(filename)
62             self._files.append(filename)
63             self.set_attributes()
64
65     def load_xml(self, filename):
66         xml = XML(filename)
67         categories = xml.xpath('//configuration/variables/category')
68         for category in categories:
69             section_name = category.get('id')
70             if not self.config.has_section(section_name):
71                 self.config.add_section(section_name)
72             options = category.xpath('./variablelist/variable')
73             for option in options:
74                 option_name = option.get('id')
75                 value = option.xpath('./value')[0].text
76                 if not value:
77                     value = ""
78                 self.config.set(section_name, option_name, value)
79
80     def load_shell(self, filename):
81         f = open(filename, 'r')
82         for line in f:
83             try:
84                 if line.startswith('#'):
85                     continue
86                 parts = line.strip().split("=")
87                 if len(parts) < 2:
88                     continue
89                 option = parts[0]
90                 value = parts[1].replace('"', '').replace("'", "")
91                 section, var = self.locate_varname(option, strict=False)
92                 if section and var:
93                     self.set(section, var, value)
94             except:
95                 pass
96         f.close()
97
98     def locate_varname(self, varname, strict=True):
99         varname = varname.lower()
100         sections = self.config.sections()
101         section_name = ""
102         var_name = ""
103         for section in sections:
104             if varname.startswith(section.lower()) and len(section) > len(section_name):
105                 section_name = section.lower()
106                 var_name = varname.replace(section_name, "")[1:]
107         if strict and not self.config.has_option(section_name, var_name):
108             raise ConfigParser.NoOptionError(var_name, section_name)
109         return (section_name, var_name)
110
111     def set_attributes(self):
112         sections = self.config.sections()
113         for section in sections:
114             for item in self.config.items(section):
115                 name = "%s_%s" % (section, item[0])
116                 value = item[1]
117                 if isbool(value):
118                     value = str2bool(value)
119                 elif value.isdigit():
120                     value = int(value)
121                 setattr(self, name, value)
122                 setattr(self, name.upper(), value)
123
124     def variables(self):
125         """
126         Return all variables.
127
128         Returns:
129
130         variables = { 'category_id': (category, variablelist) }
131
132         category = { 'id': "category_identifier",
133                      'name': "Category name",
134                      'description': "Category description" }
135
136         variablelist = { 'variable_id': variable }
137
138         variable = { 'id': "variable_identifier",
139                      'type': "variable_type",
140                      'value': "variable_value",
141                      'name': "Variable name",
142                      'description': "Variable description" }
143         """
144
145         variables = {}
146         for section in self.config.sections():
147             category = {
148                 'id': section,
149                 'name': section,
150                 'description': section,
151             }
152             variable_list = {}
153             for item in self.config.items(section):
154                 var_name = item[0]
155                 name = "%s_%s" % (section, var_name)
156                 value = item[1]
157                 if isbool(value):
158                     value_type = bool
159                 elif value.isdigit():
160                     value_type = int
161                 else:
162                     value_type = str
163                 variable = {
164                     'id': var_name,
165                     'type': value_type,
166                     'value': value,
167                     'name': name,
168                     'description': name,
169                 }
170                 variable_list[name] = variable
171             variables[section] = (category, variable_list)
172         return variables
173
174     def verify(self, config1, config2, validate_method):
175         return True
176
177     def validate_type(self, var_type, value):
178         return True
179
180     @staticmethod
181     def is_xml(config_file):
182         try:
183             x = Xml(config_file)
184             return True
185         except:
186             return False
187
188     @staticmethod
189     def is_ini(config_file):
190         try:
191             c = ConfigParser.ConfigParser()
192             c.read(config_file)
193             return True
194         except ConfigParser.MissingSectionHeaderError:
195             return False
196
197     def dump(self, sections=None):
198         if sections is None:
199             sections = []
200         sys.stdout.write(output_python())
201
202     def output_python(self, encoding="utf-8"):
203         buf = codecs.lookup(encoding)[3](StringIO())
204         buf.writelines(["# " + line + os.linesep for line in self._header()])
205
206         for section in self.sections():
207             buf.write("[%s]%s" % (section, os.linesep))
208             for (name, value) in self.items(section):
209                 buf.write("%s=%s%s" % (name, value, os.linesep))
210             buf.write(os.linesep)
211         return buf.getvalue()
212
213     def output_shell(self, show_comments=True, encoding="utf-8"):
214         """
215         Return variables as a shell script.
216         """
217
218         buf = codecs.lookup(encoding)[3](StringIO())
219         buf.writelines(["# " + line + os.linesep for line in self._header()])
220
221         for section in self.sections():
222             for (name, value) in self.items(section):
223                 # bash does not have the concept of NULL
224                 if value:
225                     option = "%s_%s" % (section.upper(), name.upper())
226                     if isbool(value):
227                         value = str(str2bool(value))
228                     elif not value.isdigit():
229                         value = '"%s"' % value
230                     buf.write(option + "=" + value + os.linesep)
231         return buf.getvalue()
232
233     def output_php(selfi, encoding="utf-8"):
234         """
235         Return variables as a PHP script.
236         """
237
238         buf = codecs.lookup(encoding)[3](StringIO())
239         buf.write("<?php" + os.linesep)
240         buf.writelines(["// " + line + os.linesep for line in self._header()])
241
242         for section in self.sections():
243             for (name, value) in self.items(section):
244                 option = "%s_%s" % (section, name)
245                 buf.write(os.linesep)
246                 buf.write("// " + option + os.linesep)
247                 if value is None:
248                     value = 'NULL'
249                 buf.write("define('%s', %s);" % (option, value) + os.linesep)
250
251         buf.write("?>" + os.linesep)
252
253         return buf.getvalue()
254
255     def output_xml(self, encoding="utf-8"):
256         pass
257
258     def output_variables(self, encoding="utf-8"):
259         """
260         Return list of all variable names.
261         """
262
263         buf = codecs.lookup(encoding)[3](StringIO())
264         for section in self.sections():
265             for (name, value) in self.items(section):
266                 option = "%s_%s" % (section, name)
267                 buf.write(option + os.linesep)
268
269         return buf.getvalue()
270         pass
271
272     def write(self, filename=None):
273         if not filename:
274             filename = self.filename
275         configfile = open(filename, 'w')
276         self.config.write(configfile)
277
278     def save(self, filename=None):
279         self.write(filename)
280
281     def get_trustedroots_dir(self):
282         return self.config_path + os.sep + 'trusted_roots'
283
284     def get_openflow_aggrMgr_info(self):
285         aggr_mgr_ip = 'localhost'
286         if (hasattr(self, 'openflow_aggregate_manager_ip')):
287             aggr_mgr_ip = self.OPENFLOW_AGGREGATE_MANAGER_IP
288
289         aggr_mgr_port = 2603
290         if (hasattr(self, 'openflow_aggregate_manager_port')):
291             aggr_mgr_port = self.OPENFLOW_AGGREGATE_MANAGER_PORT
292
293         return (aggr_mgr_ip, aggr_mgr_port)
294
295     def get_interface_hrn(self):
296         if (hasattr(self, 'sfa_interface_hrn')):
297             return self.SFA_INTERFACE_HRN
298         else:
299             return "plc"
300
301     def __getattr__(self, attr):
302         return getattr(self.config, attr)
303
304 if __name__ == '__main__':
305     filename = None
306     if len(sys.argv) > 1:
307         filename = sys.argv[1]
308         config = Config(filename)
309     else:
310         config = Config()
311     config.dump()