8 from StringIO import StringIO
9 from sfa.util.xml import XML
16 return v.lower() in ("true", "false")
19 return v.lower() in ("true", "1")
23 def __init__(self, config_file='/etc/sfa/sfa_config'):
25 self.config_path = os.path.dirname(config_file)
26 self.config = ConfigParser.ConfigParser()
27 self.filename = config_file
28 if not os.path.isfile(self.filename):
29 self.create(self.filename)
30 self.load(self.filename)
35 DO NOT EDIT. This file was automatically generated at
39 """ % (time.asctime(), os.linesep.join(self._files))
41 # Get rid of the surrounding newlines
42 return header.strip().split(os.linesep)
44 def create(self, filename):
45 if not os.path.exists(os.path.dirname(filename)):
46 os.makedirs(os.path.dirname(filename))
47 configfile = open(filename, 'w')
48 configfile.write(default_config)
52 def load(self, filename):
55 self.config.read(filename)
56 except ConfigParser.MissingSectionHeaderError:
57 if filename.endswith('.xml'):
58 self.load_xml(filename)
60 self.load_shell(filename)
61 self._files.append(filename)
64 def load_xml(self, filename):
66 categories = xml.xpath('//configuration/variables/category')
67 for category in categories:
68 section_name = category.get('id')
69 if not self.config.has_section(section_name):
70 self.config.add_section(section_name)
71 options = category.xpath('./variablelist/variable')
72 for option in options:
73 option_name = option.get('id')
74 value = option.xpath('./value')[0].text
77 self.config.set(section_name, option_name, value)
79 def load_shell(self, filename):
80 f = open(filename, 'r')
83 if line.startswith('#'):
85 parts = line.strip().split("=")
89 value = parts[1].replace('"', '').replace("'","")
90 section, var = self.locate_varname(option, strict=False)
92 self.set(section, var, value)
97 def locate_varname(self, varname, strict=True):
98 varname = varname.lower()
99 sections = self.config.sections()
102 for section in sections:
103 if varname.startswith(section.lower()) and len(section) > len(section_name):
104 section_name = section.lower()
105 var_name = varname.replace(section_name, "")[1:]
106 if strict and not self.config.has_option(section_name, var_name):
107 raise ConfigParser.NoOptionError(var_name, section_name)
108 return (section_name, var_name)
110 def set_attributes(self):
111 sections = self.config.sections()
112 for section in sections:
113 for item in self.config.items(section):
114 name = "%s_%s" % (section, item[0])
117 value = str2bool(value)
118 elif value.isdigit():
120 setattr(self, name, value)
121 setattr(self, name.upper(), value)
125 Return all variables.
129 variables = { 'category_id': (category, variablelist) }
131 category = { 'id': "category_identifier",
132 'name': "Category name",
133 'description': "Category description" }
135 variablelist = { 'variable_id': variable }
137 variable = { 'id': "variable_identifier",
138 'type': "variable_type",
139 'value': "variable_value",
140 'name': "Variable name",
141 'description': "Variable description" }
145 for section in self.config.sections():
149 'description': section,
152 for item in self.config.items(section):
154 name = "%s_%s" % (section, var_name)
158 elif value.isdigit():
169 variable_list[name] = variable
170 variables[section] = (category, variable_list)
173 def verify(self, config1, config2, validate_method):
176 def validate_type(self, var_type, value):
180 def is_xml(config_file):
188 def is_ini(config_file):
190 c = ConfigParser.ConfigParser()
193 except ConfigParser.MissingSectionHeaderError:
197 def dump(self, sections=None):
198 if sections is None: sections=[]
199 sys.stdout.write(output_python())
201 def output_python(self, encoding = "utf-8"):
202 buf = codecs.lookup(encoding)[3](StringIO())
203 buf.writelines(["# " + line + os.linesep for line in self._header()])
205 for section in self.sections():
206 buf.write("[%s]%s" % (section, os.linesep))
207 for (name,value) in self.items(section):
208 buf.write("%s=%s%s" % (name,value,os.linesep))
209 buf.write(os.linesep)
210 return buf.getvalue()
212 def output_shell(self, show_comments = True, encoding = "utf-8"):
214 Return variables as a shell script.
217 buf = codecs.lookup(encoding)[3](StringIO())
218 buf.writelines(["# " + line + os.linesep for line in self._header()])
220 for section in self.sections():
221 for (name,value) in self.items(section):
222 # bash does not have the concept of NULL
224 option = "%s_%s" % (section.upper(), name.upper())
226 value = str(str2bool(value))
227 elif not value.isdigit():
228 value = '"%s"' % value
229 buf.write(option + "=" + value + os.linesep)
230 return buf.getvalue()
232 def output_php(selfi, encoding = "utf-8"):
234 Return variables as a PHP script.
237 buf = codecs.lookup(encoding)[3](StringIO())
238 buf.write("<?php" + os.linesep)
239 buf.writelines(["// " + line + os.linesep for line in self._header()])
241 for section in self.sections():
242 for (name,value) in self.items(section):
243 option = "%s_%s" % (section, name)
244 buf.write(os.linesep)
245 buf.write("// " + option + os.linesep)
248 buf.write("define('%s', %s);" % (option, value) + os.linesep)
250 buf.write("?>" + os.linesep)
252 return buf.getvalue()
254 def output_xml(self, encoding = "utf-8"):
257 def output_variables(self, encoding="utf-8"):
259 Return list of all variable names.
262 buf = codecs.lookup(encoding)[3](StringIO())
263 for section in self.sections():
264 for (name,value) in self.items(section):
265 option = "%s_%s" % (section,name)
266 buf.write(option + os.linesep)
268 return buf.getvalue()
271 def write(self, filename=None):
273 filename = self.filename
274 configfile = open(filename, 'w')
275 self.config.write(configfile)
277 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)