fix bools in output_shell
[sfa.git] / sfa / util / config.py
1 #!/usr/bin/python
2 import sys
3 import os
4 import time
5 import ConfigParser
6 import tempfile
7 import codecs
8 from StringIO import StringIO
9 from sfa.util.xml import XML
10
11 default_config = \
12 """
13 """
14
15 def isbool(v):
16     return v.lower() in ("true", "false")
17
18 def str2bool(v):
19     return v.lower() in ("true", "1")             
20
21 class Config:
22   
23     def __init__(self, config_file='/etc/sfa/sfa_config'):
24         self._files = []
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)
31         
32
33     def _header(self):
34         header = """
35 DO NOT EDIT. This file was automatically generated at
36 %s from:
37
38 %s
39 """ % (time.asctime(), os.linesep.join(self._files))
40
41         # Get rid of the surrounding newlines
42         return header.strip().split(os.linesep)
43
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)
49         configfile.close()
50         
51
52     def load(self, filename):
53         if filename:
54             try:
55                 self.config.read(filename)
56             except ConfigParser.MissingSectionHeaderError:
57                 if filename.endswith('.xml'):
58                     self.load_xml(filename)
59                 else:
60                     self.load_shell(filename)
61             self._files.append(filename)
62             self.set_attributes()
63
64     def load_xml(self, filename):
65         xml = XML(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
75                 if not value:
76                     value = ""
77                 self.config.set(section_name, option_name, value)
78          
79     def load_shell(self, filename):
80         f = open(filename, 'r')
81         for line in f:
82             try:
83                 if line.startswith('#'):
84                     continue
85                 parts = line.strip().split("=")
86                 if len(parts) < 2:
87                     continue
88                 option = parts[0]
89                 value = parts[1].replace('"', '').replace("'","")
90                 section, var = self.locate_varname(option, strict=False)
91                 if section and var:
92                     self.set(section, var, value)
93             except:
94                 pass
95         f.close()               
96
97     def locate_varname(self, varname, strict=True):
98         varname = varname.lower()
99         sections = self.config.sections()
100         section_name = ""
101         var_name = ""
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)             
109
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])
115                 value = item[1]
116                 setattr(self, name, value)
117                 setattr(self, name.upper(), value)
118         
119
120     def verify(self, config1, config2, validate_method):
121         return True
122
123     def validate_type(self, var_type, value):
124         return True
125
126     @staticmethod
127     def is_xml(config_file):
128         try:
129             x = Xml(config_file)
130             return True     
131         except:
132             return False
133
134     @staticmethod
135     def is_ini(config_file):
136         try:
137             c = ConfigParser.ConfigParser()
138             c.read(config_file)
139             return True
140         except ConfigParser.MissingSectionHeaderError:
141             return False
142
143
144     def dump(self, sections = []):
145         sys.stdout.write(output_python())
146
147     def output_python(self, encoding = "utf-8"):
148         buf = codecs.lookup(encoding)[3](StringIO())
149         buf.writelines(["# " + line + os.linesep for line in self._header()]) 
150         
151         for section in self.sections():
152             buf.write("[%s]%s" % (section, os.linesep))
153             for (name,value) in self.items(section):
154                 buf.write("%s=%s%s" % (name,value,os.linesep))
155             buf.write(os.linesep)
156         return buf.getvalue()
157                 
158     def output_shell(self, show_comments = True, encoding = "utf-8"):
159         """
160         Return variables as a shell script.
161         """
162
163         buf = codecs.lookup(encoding)[3](StringIO())
164         buf.writelines(["# " + line + os.linesep for line in self._header()])
165
166         for section in self.sections():
167             for (name,value) in self.items(section):
168                 # bash does not have the concept of NULL
169                 if value:
170                     option = "%s_%s" % (section.upper(), name.upper())
171                     if isbool(value):
172                         value = str(str2bool(value))
173                     elif not value.isdigit():
174                         value = '"%s"' % value  
175                     buf.write(option + "=" + value + os.linesep)
176         return buf.getvalue()        
177
178     def output_php(selfi, encoding = "utf-8"):
179         """
180         Return variables as a PHP script.
181         """
182
183         buf = codecs.lookup(encoding)[3](StringIO())
184         buf.write("<?php" + os.linesep)
185         buf.writelines(["// " + line + os.linesep for line in self._header()])
186
187         for section in self.sections():
188             for (name,value) in self.items(section):
189                 option = "%s_%s" % (section, name)
190                 buf.write(os.linesep)
191                 buf.write("// " + option + os.linesep)
192                 if value is None:
193                     value = 'NULL'
194                 buf.write("define('%s', %s);" % (option, value) + os.linesep)
195
196         buf.write("?>" + os.linesep)
197
198         return buf.getvalue()    
199
200     def output_xml(self, encoding = "utf-8"):
201         pass
202
203     def output_variables(self, encoding="utf-8"):
204         """
205         Return list of all variable names.
206         """
207
208         buf = codecs.lookup(encoding)[3](StringIO())
209         for section in self.sections():
210             for (name,value) in self.items(section):
211                 option = "%s_%s" % (section,name) 
212                 buf.write(option + os.linesep)
213
214         return buf.getvalue()
215         pass 
216         
217     def write(self, filename=None):
218         if not filename:
219             filename = self.filename
220         configfile = open(filename, 'w') 
221         self.config.write(configfile)
222     
223     def save(self, filename=None):
224         self.write(filename)
225
226
227     def get_trustedroots_dir(self):
228         return self.config_path + os.sep + 'trusted_roots'
229
230     def get_openflow_aggrMgr_info(self):
231         aggr_mgr_ip = 'localhost'
232         if (hasattr(self,'openflow_aggregate_manager_ip')):
233             aggr_mgr_ip = self.OPENFLOW_AGGREGATE_MANAGER_IP
234
235         aggr_mgr_port = 2603
236         if (hasattr(self,'openflow_aggregate_manager_port')):
237             aggr_mgr_port = self.OPENFLOW_AGGREGATE_MANAGER_PORT
238
239         return (aggr_mgr_ip,aggr_mgr_port)
240
241     def get_interface_hrn(self):
242         if (hasattr(self,'sfa_interface_hrn')):
243             return self.SFA_INTERFACE_HRN
244         else:
245             return "plc"
246
247     def __getattr__(self, attr):
248         return getattr(self.config, attr)
249
250 if __name__ == '__main__':
251     filename = None
252     if len(sys.argv) > 1:
253         filename = sys.argv[1]
254         config = Config(filename)
255     else:    
256         config = Config()
257     config.dump()
258