7 from sfa.util.xml import XML
8 from sfa.util.py23 import StringIO
9 from sfa.util.py23 import ConfigParser
17 return v.lower() in ("true", "false")
21 return v.lower() in ("true", "1")
26 def __init__(self, config_file='/etc/sfa/sfa_config'):
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)
37 DO NOT EDIT. This file was automatically generated at
41 """ % (time.asctime(), os.linesep.join(self._files))
43 # Get rid of the surrounding newlines
44 return header.strip().split(os.linesep)
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)
53 def load(self, filename):
56 self.config.read(filename)
57 except ConfigParser.MissingSectionHeaderError:
58 if filename.endswith('.xml'):
59 self.load_xml(filename)
61 self.load_shell(filename)
62 self._files.append(filename)
65 def load_xml(self, 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
78 self.config.set(section_name, option_name, value)
80 def load_shell(self, filename):
81 f = open(filename, 'r')
84 if line.startswith('#'):
86 parts = line.strip().split("=")
90 value = parts[1].replace('"', '').replace("'", "")
91 section, var = self.locate_varname(option, strict=False)
93 self.set(section, var, value)
98 def locate_varname(self, varname, strict=True):
99 varname = varname.lower()
100 sections = self.config.sections()
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)
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])
118 value = str2bool(value)
119 elif value.isdigit():
121 setattr(self, name, value)
122 setattr(self, name.upper(), value)
126 Return all variables.
130 variables = { 'category_id': (category, variablelist) }
132 category = { 'id': "category_identifier",
133 'name': "Category name",
134 'description': "Category description" }
136 variablelist = { 'variable_id': variable }
138 variable = { 'id': "variable_identifier",
139 'type': "variable_type",
140 'value': "variable_value",
141 'name': "Variable name",
142 'description': "Variable description" }
146 for section in self.config.sections():
150 'description': section,
153 for item in self.config.items(section):
155 name = "%s_%s" % (section, var_name)
159 elif value.isdigit():
170 variable_list[name] = variable
171 variables[section] = (category, variable_list)
174 def verify(self, config1, config2, validate_method):
177 def validate_type(self, var_type, value):
181 def is_xml(config_file):
189 def is_ini(config_file):
191 c = ConfigParser.ConfigParser()
194 except ConfigParser.MissingSectionHeaderError:
197 def dump(self, sections=None):
200 sys.stdout.write(output_python())
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()])
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()
213 def output_shell(self, show_comments=True, encoding="utf-8"):
215 Return variables as a shell script.
218 buf = codecs.lookup(encoding)[3](StringIO())
219 buf.writelines(["# " + line + os.linesep for line in self._header()])
221 for section in self.sections():
222 for (name, value) in self.items(section):
223 # bash does not have the concept of NULL
225 option = "%s_%s" % (section.upper(), name.upper())
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()
233 def output_php(selfi, encoding="utf-8"):
235 Return variables as a PHP script.
238 buf = codecs.lookup(encoding)[3](StringIO())
239 buf.write("<?php" + os.linesep)
240 buf.writelines(["// " + line + os.linesep for line in self._header()])
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)
249 buf.write("define('%s', %s);" % (option, value) + os.linesep)
251 buf.write("?>" + os.linesep)
253 return buf.getvalue()
255 def output_xml(self, encoding="utf-8"):
258 def output_variables(self, encoding="utf-8"):
260 Return list of all variable names.
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)
269 return buf.getvalue()
272 def write(self, filename=None):
274 filename = self.filename
275 configfile = open(filename, 'w')
276 self.config.write(configfile)
278 def save(self, filename=None):
281 def get_trustedroots_dir(self):
282 return self.config_path + os.sep + 'trusted_roots'
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
290 if (hasattr(self, 'openflow_aggregate_manager_port')):
291 aggr_mgr_port = self.OPENFLOW_AGGREGATE_MANAGER_PORT
293 return (aggr_mgr_ip, aggr_mgr_port)
295 def get_interface_hrn(self):
296 if (hasattr(self, 'sfa_interface_hrn')):
297 return self.SFA_INTERFACE_HRN
301 def __getattr__(self, attr):
302 return getattr(self.config, attr)
304 if __name__ == '__main__':
306 if len(sys.argv) > 1:
307 filename = sys.argv[1]
308 config = Config(filename)