fix type bugs
[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             if filename.endswith('.xml'):
49                 try:
50                     self.load_xml(filename)
51                 except:
52                     self.config.read(filename)
53             else:
54                 self.config.read(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
74     def locate_varname(self, varname):
75         varname = varname.lower()
76         sections = self.config.sections()
77         section_name = ""
78         var_name = ""
79         for section in sections:
80             if varname.startswith(section.lower()) and len(section) > len(section_name):
81                 section_name = section.lower()
82                 var_name = varname.replace(section_name, "")[1:]
83         if not self.config.has_option(section_name, var_name):
84             raise ConfigParser.NoOptionError(varname, section_name)
85         return (section_name, var_name)             
86
87     def set_attributes(self):
88         sections = self.config.sections()
89         for section in sections:
90             for item in self.config.items(section):
91                 name = "%s_%s" % (section, item[0])
92                 value = item[1]
93                 setattr(self, name, value)
94                 setattr(self, name.upper(), value)
95         
96
97     def verify(self, config1, config2, validate_method):
98         return True
99
100     def validate_type(self, var_type, value):
101         return True
102
103     def dump(self, sections = []):
104         sys.stdout.write(output_python())
105
106     def output_python(self, encoding = "utf-8"):
107         buf = codecs.lookup(encoding)[3](StringIO())
108         buf.writelines(["# " + line + os.linesep for line in self._header()]) 
109         
110         for section in self.sections():
111             buf.write("[%s]%s" % (section, os.linesep))
112             for (name,value) in self.items(section):
113                 buf.write("%s=%s%s" % (name,value,os.linesep))
114             buf.write(os.linesep)
115         return buf.getvalue()
116                 
117     def output_shell(self, show_comments = True, encoding = "utf-8"):
118         """
119         Return variables as a shell script.
120         """
121
122         buf = codecs.lookup(encoding)[3](StringIO())
123         buf.writelines(["# " + line + os.linesep for line in self._header()])
124
125         for section in self.sections():
126             for (name,value) in self.items(section):
127                 # bash does not have the concept of NULL
128                 if value:
129                     option = "%s_%s" % (section.upper(), name.upper())
130                     if not value.isdigit() and not bool(value):
131                         value = "'%s'" % value  
132                     buf.write(option + "=" + value + os.linesep)
133         return buf.getvalue()        
134
135     def output_php(selfi, encoding = "utf-8"):
136         """
137         Return variables as a PHP script.
138         """
139
140         buf = codecs.lookup(encoding)[3](StringIO())
141         buf.write("<?php" + os.linesep)
142         buf.writelines(["// " + line + os.linesep for line in self._header()])
143
144         for section in self.sections():
145             for (name,value) in self.items(section):
146                 option = "%s_%s" % (section, name)
147                 buf.write(os.linesep)
148                 buf.write("// " + option + os.linesep)
149                 if value is None:
150                     value = 'NULL'
151                 buf.write("define('%s', %s);" % (option, value) + os.linesep)
152
153         buf.write("?>" + os.linesep)
154
155         return buf.getvalue()    
156
157     def output_xml(self, encoding = "utf-8"):
158         pass
159
160     def output_variables(self):
161         """
162         Return list of all variable names.
163         """
164
165         buf = codecs.lookup(encoding)[3](StringIO())
166         for section in self.sections():
167             for (name,value) in self.items(section):
168                 option = "%s_%s" % (section,name) 
169                 buf.write(option + os.linesep)
170
171         return buf.getvalue()
172         pass 
173         
174     def write(self, filename=None):
175         if not filename:
176             filename = self.filename
177         configfile = open(filename, 'w') 
178         self.config.write(configfile)
179     
180     def save(self, filename=None):
181         self.write(filename)
182
183
184     def get_trustedroots_dir(self):
185         return self.config_path + os.sep + 'trusted_roots'
186
187     def get_openflow_aggrMgr_info(self):
188         aggr_mgr_ip = 'localhost'
189         if (hasattr(self,'openflow_aggregate_manager_ip')):
190             aggr_mgr_ip = self.OPENFLOW_AGGREGATE_MANAGER_IP
191
192         aggr_mgr_port = 2603
193         if (hasattr(self,'openflow_aggregate_manager_port')):
194             aggr_mgr_port = self.OPENFLOW_AGGREGATE_MANAGER_PORT
195
196         return (aggr_mgr_ip,aggr_mgr_port)
197
198     def get_interface_hrn(self):
199         if (hasattr(self,'sfa_interface_hrn')):
200             return self.SFA_INTERFACE_HRN
201         else:
202             return "plc"
203
204     def __getattr__(self, attr):
205         return getattr(self.config, attr)
206
207 if __name__ == '__main__':
208     filename = None
209     if len(sys.argv) > 1:
210         filename = sys.argv[1]
211         config = Config(filename)
212     else:    
213         config = Config()
214     config.dump()
215