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