Looks like that in the recent release of util-vserver, these variables cannot be...
[sfa.git] / config / sfa-config-tty
1 #!/usr/bin/python
2
3 # Interactively prompts for variable values
4 # expected arguments are
5 # command -d [default-xml [custom-xml [ consolidated-xml ]]]
6 #
7 # -d is for the myplc-devel package
8
9 # we use 3 instances of PLCConfiguration throughout:
10 # cdef : models the defaults, from plc_default.xml
11 # cread : merged from plc_default & configs/site.xml
12 # cwrite : site.xml + pending changes
13
14 import sys
15 import os
16 import re
17 import readline
18 import distutils.file_util
19 from optparse import OptionParser
20
21 from sfa.util.config import Config
22 from sfa.trust.hierarchy import *
23 from sfa.util.misc import *
24
25
26 all_variables   = ["SFA_REGISTRY_ROOT_AUTH",
27                    "SFA_REGISTRY_LEVEL1_AUTH",
28                    "SFA_REGISTRY_ENABLED",
29                    "SFA_REGISTRY_HOST", 
30                    "SFA_REGISTRY_PORT",
31                    "SFA_REGISTRY_TYPE",
32                    "SFA_AGGREGATE_ENABLED",
33                    "SFA_AGGREGATE_HOST",
34                    "SFA_AGGREGATE_PORT",
35                    "SFA_AGGREGATE_TYPE",
36                    "SFA_SM_ENABLED",
37                    "SFA_SM_HOST",
38                    "SFA_SM_PORT",
39                    "SFA_SM_TYPE",
40                    "SFA_PLC_USER",
41                    "SFA_PLC_PASSWORD",    
42                    "SFA_PLC_URL",
43                    "SFA_PLC_DB_NAME",
44                    "SFA_PLC_DB_HOST",
45                    "SFA_PLC_DB_PORT",
46                    "SFA_PLC_DB_USER",
47                    "SFA_PLC_DB_PASSWORD",
48                    ]
49 usual_variables = ["SFA_REGISTRY_ROOT_AUTH",
50                    "SFA_REGISTRY_LEVEL1_AUTH",
51                    "SFA_REGISTRY_HOST", 
52                    "SFA_AGGREGATE_HOST",
53                    "SFA_SM_HOST",
54                    "SFA_PLC_USER",
55                    "SFA_PLC_PASSWORD",
56                    "SFA_PLC_DB_HOST",
57                    "SFA_PLC_DB_USER",
58                    "SFA_PLC_DB_PASSWORD",
59                    "SFA_PLC_URL",
60                    ]
61
62
63 mainloop_usage= """Available commands:
64  u/U\t\t\tEdit usual variables
65  w/W\t\t\tWrite / Write & reload
66  q\t\t\tQuit (without saving)
67  h/?\t\t\tThis help
68 ---
69  l/L [<var>]\tShow Locally modified variables/values
70  s/S [<var>]\tShow all current variables/values 
71  e/E [<var>]\tEdit variables (all, in category, single)
72 ---
73 """ 
74
75 command_usage="%prog [options]"
76 command_usage += """
77   Unless you specify the -d option, meaning you want to configure
78   using defaults without interactive prompts""" 
79
80 variable_usage= """Edit Commands :
81 .\tStops prompting, return to mainloop
82 =\tShows default value
83 ?\tThis help    
84 """
85
86 def save_config(changes, config_file):
87     # always validate before saving
88     changes = validate(changes) 
89     
90     cfile = open(config_file, 'r')
91     lines = cfile.readlines()
92     cfile.close()
93     newlines = []
94     for line in lines:
95         added = False
96         for variable in changes:
97             if line.startswith(variable+'='):
98                 try:
99                     value = int(changes[variable])
100                     newline = '%s=%s\n' % (variable, value)
101                     newlines.append(newline)
102                 except:
103                     value = changes[variable]
104                     newline = '%s="%s"\n' % (variable, value)
105                     newlines.append(newline)
106                 added = True
107                 break
108         if not added:
109             newlines.append(line) 
110     
111     cfile = open(config_file, 'w')
112     cfile.writelines(newlines)
113     cfile.close()
114     print 'updated config file',config_file
115
116 def validate(changes):
117
118     if not changes:
119         return {}
120
121     defaults = get_defaults()
122     
123     # SFA_INTERFACE_HRN is SFA_REGISTRY_LEVEL1_AUTH, if thats blank it
124     # then defaults to SFA_REGISTRY_ROOT_AUTH 
125     # SFA_REGISTRY_LEVEL1_AUTH, so if either of these are present we must 
126     # update SFA_INTERFACE_HRN
127     if 'SFA_REGISTRY_ROOT_AUTH' in changes:
128         root_auth = changes['SFA_REGISTRY_ROOT_AUTH']
129     else:
130         root_auth = defaults['SFA_REGISTRY_ROOT_AUTH']
131              
132     if 'SFA_REGISTRY_LEVEL1_AUTH' in changes:
133         level1_auth = changes['SFA_REGISTRY_LEVEL1_AUTH']
134     else:
135         level1_auth = defaults['SFA_REGISTRY_LEVEL1_AUTH']
136                 
137     if level1_auth:
138         interface_hrn = level1_auth
139     else:
140         interface_hrn = root_auth
141     changes['SFA_INTERFACE_HRN'] = interface_hrn
142     return changes                            
143
144 def get_defaults():
145     sfa_config = Config()
146     
147     defaults = {}
148     for var in dir(sfa_config):
149         if var.startswith('SFA'):
150             value = eval("sfa_config.%s" % var)
151             defaults[var] = value
152
153     return defaults       
154
155 def prompt_variable(variable, default_config):
156     if variable in default_config:
157         default_value = default_config[variable]
158     else:
159         default_value = ""  
160    
161     while True:
162         prompt = "%(variable)s : [%(default_value)s] " % locals()
163         try: 
164             answer = raw_input(prompt).strip()
165         except EOFError:
166             raise Exception ('BailOut')
167         except KeyboardInterrupt:
168             print "\n"
169             raise Exception ('BailOut')
170
171         if (answer == "") or (answer == default_value):
172             return default_value
173         elif answer in ['""', "''"]:
174             return ""
175         elif (answer == "."):
176             raise Exception ('BailOut')
177         elif (answer == "?"):
178             print variable_usage.strip()
179         elif (answer == "="):
180             print ("%s defaults to %s" %(variable,default_value))
181         else:
182             return answer
183
184 def show_variable(variable, value_dict):
185     print "%s=%s" % (variable, value_dict[variable])                    
186     
187 def mainloop (default_config, config_file):
188     changes = {}
189     while True:
190         try:
191             answer = raw_input("Enter command (u for usual changes, w to save, ? for help) ").strip()
192         except EOFError:
193             answer =""
194         except KeyboardInterrupt:
195             print "\nBye"
196             sys.exit()
197         if (answer == "") or (answer in "?hH"):
198             print mainloop_usage
199             continue
200         if answer in ['?']:
201             print "help"  
202
203         if (answer in ["q","Q"]):
204             break
205         elif (answer == "w"):
206             save_config(changes, config_file)
207         elif (answer == "u"):
208             try: 
209                 for varname in usual_variables:
210                     changes[varname] = prompt_variable(varname, default_config)
211             except Exception, inst:
212                 if (str(inst) != 'BailOut'):
213                     raise
214         elif (answer in ["e","E"]):
215             try:
216                 for varname in all_variables:
217                     changes[varname] = prompt_variable(varname, default_config)
218             except Exception, inst:
219                 if (str(inst) != 'BailOut'):
220                     raise
221         elif (answer in "sS"):
222             for varname in usual_variables:
223                 show_variable (varname, default_config)
224         elif (answer in "lL"):
225             if not changes:
226                 print "No changes to display"
227             else:
228                 for varname in changes:
229                     show_variable(varname, changes)
230         else:
231             print ("Unknown command >%s< -- use h for help" % answer)
232
233     result = {}
234     result.update(default_config)
235     result.update(changes)
236     return result
237     
238 def setup_server_key(config_dict):
239     hrn = config_dict.get('SFA_INTERFACE_HRN')
240     if not hrn: return
241    
242     # Get the path to the authorities directory hierarchy
243     hierarchy = Hierarchy()
244     path = hierarchy.basedir
245     auth_path = hrn.replace(".", os.sep)
246  
247     # define some useful variables   
248     key = 'server.key'
249     cert = 'server.cert'
250     hrn_leaf = get_leaf(hrn)
251     if not hrn_leaf:
252         hrn_leaf = hrn
253     new_server_key = os.sep.join([path, auth_path, hrn_leaf]) + ".pkey"
254     old_server_key = os.sep.join([path, key])
255     old_server_cert = os.sep.join([path, cert])
256
257     # remove old key/cert
258     for fd in [old_server_key, old_server_cert]:
259         if os.path.isfile(fd):
260             os.remove(fd)
261
262     # create new server.key
263     try:
264         distutils.file_util.copy_file(src=new_server_key, dst=old_server_key, verbose=1)
265         print "\t\t%(old_server_key)s\ncopied from\t%(new_server_key)s" % locals()
266     # this is expected when running this tool for the first time (before sfa-import-plc.py)
267     except:
268         print "Could not create %(old_server_key)s - ignore if you haven't run sfa-import-plc.py yet"%locals()
269     
270     
271
272 ####################
273 def main ():
274
275     command=sys.argv[0]
276     argv = sys.argv[1:]
277     save = True
278     parser = OptionParser(usage=command_usage, version="%prog 1.0")
279     parser.set_defaults(config_dir="/etc/sfa",
280                         usual_variables=[])
281     parser.add_option("","--configdir",dest="config_dir",action="append", help="specify configuration directory")
282     parser.add_option("","--usual_variable",dest="usual_variables",action="append", help="add a usual variable")
283     parser.add_option("-d", "--default", action="count", help="dont prompt for values, just use defaults")
284     (config,args) = parser.parse_args()
285     if len(args)>3:
286         parser.error("too many arguments")
287
288     config_dir = parser.values.config_dir
289     config_file = os.sep.join([config_dir, 'sfa_config'])
290     defaults = get_defaults()
291     # if -d is specified dont prompt, just configure with defaults
292     if '-d' in argv:
293         save_config(defaults, config_file)
294         results = defaults
295     else:        
296         results = mainloop (defaults, config_file)
297     setup_server_key(results)
298     return 0
299
300 if __name__ == '__main__':
301     main()