3 # Interactively prompts for variable values
4 # expected arguments are
5 # command -d [default-xml [custom-xml [ consolidated-xml ]]]
7 # -d is for the myplc-devel package
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
19 import distutils.file_util
20 from optparse import OptionParser
22 from sfa.util.config import Config
23 from sfa.trust.hierarchy import *
24 from sfa.util.misc import *
27 all_variables = ["SFA_REGISTRY_ROOT_AUTH",
28 "SFA_REGISTRY_LEVEL1_AUTH",
29 "SFA_REGISTRY_ENABLED",
32 "SFA_AGGREGATE_ENABLED",
45 "SFA_PLC_DB_PASSWORD",
47 usual_variables = ["SFA_REGISTRY_ROOT_AUTH",
48 "SFA_REGISTRY_LEVEL1_AUTH",
52 "SFA_PLC_DB_PASSWORD",
56 mainloop_usage= """Available commands:
57 u/U\t\t\tEdit usual variables
58 w/W\t\t\tWrite / Write & reload
59 q\t\t\tQuit (without saving)
62 l/L [<var>]\tShow Locally modified variables/values
63 s/S [<var>]\tShow all current variables/values
64 e/E [<var>]\tEdit variables (all, in category, single)
68 command_usage="%prog [options]"
70 Unless you specify the -d option, meaning you want to configure
71 using defaults without interactive prompts"""
73 variable_usage= """Edit Commands :
74 .\tStops prompting, return to mainloop
75 =\tShows default value
79 def save_config(changes, config_file):
80 # always validate before saving
81 changes = validate(changes)
83 cfile = open(config_file, 'r')
84 lines = cfile.readlines()
89 for variable in changes:
90 if line.startswith(variable+'='):
92 value = int(changes[variable])
93 newline = '%s=%s\n' % (variable, value)
94 newlines.append(newline)
96 value = changes[variable]
97 newline = '%s="%s"\n' % (variable, value)
98 newlines.append(newline)
102 newlines.append(line)
104 cfile = open(config_file, 'w')
105 cfile.writelines(newlines)
107 print 'updated config file',config_file
109 def validate(changes):
114 defaults = get_defaults()
116 # SFA_INTERFACE_HRN is SFA_REGISTRY_LEVEL1_AUTH, if thats blank it
117 # then defaults to SFA_REGISTRY_ROOT_AUTH
118 # SFA_REGISTRY_LEVEL1_AUTH, so if either of these are present we must
119 # update SFA_INTERFACE_HRN
120 if 'SFA_REGISTRY_ROOT_AUTH' in changes:
121 root_auth = changes['SFA_REGISTRY_ROOT_AUTH']
123 root_auth = defaults['SFA_REGISTRY_ROOT_AUTH']
125 if 'SFA_REGISTRY_LEVEL1_AUTH' in changes:
126 level1_auth = changes['SFA_REGISTRY_LEVEL1_AUTH']
128 level1_auth = defaults['SFA_REGISTRY_LEVEL1_AUTH']
131 interface_hrn = level1_auth
133 interface_hrn = root_auth
134 changes['SFA_INTERFACE_HRN'] = interface_hrn
138 sfa_config = Config()
141 for var in dir(sfa_config):
142 if var.startswith('SFA'):
143 value = eval("sfa_config.%s" % var)
144 defaults[var] = value
148 def prompt_variable(variable, default_config):
149 if variable in default_config:
150 default_value = default_config[variable]
155 prompt = "%(variable)s : [%(default_value)s] " % locals()
157 answer = raw_input(prompt).strip()
159 raise Exception ('BailOut')
160 except KeyboardInterrupt:
162 raise Exception ('BailOut')
164 if (answer == "") or (answer == default_value):
166 elif answer in ['""', "''"]:
168 elif (answer == "."):
169 raise Exception ('BailOut')
170 elif (answer == "?"):
171 print variable_usage.strip()
172 elif (answer == "="):
173 print ("%s defaults to %s" %(variable,default_value))
177 def show_variable(variable, value_dict):
178 print "%s=%s" % (variable, value_dict[variable])
180 def mainloop (default_config, config_file):
184 answer = raw_input("Enter command (u for usual changes, w to save, ? for help) ").strip()
187 except KeyboardInterrupt:
191 if (answer == "") or (answer in "?hH"):
197 if (answer in ["q","Q"]):
199 elif (answer == "w"):
200 save_config(changes, config_file)
201 elif (answer == "u"):
203 for varname in usual_variables:
204 changes[varname] = prompt_variable(varname, default_config)
205 except Exception, inst:
206 if (str(inst) != 'BailOut'):
208 elif (answer in ["e","E"]):
210 for varname in all_variables:
211 changes[varname] = prompt_variable(varname, default_config)
212 except Exception, inst:
213 if (str(inst) != 'BailOut'):
215 elif (answer in "sS"):
216 for varname in usual_variables:
217 show_variable (varname, default_config)
218 elif (answer in "lL"):
220 print "No changes to display"
222 for varname in changes:
223 show_variable(varname, changes)
225 print ("Unknown command >%s< -- use h for help" % answer)
228 result.update(default_config)
229 result.update(changes)
232 def setup_server_key(config_dict):
233 hrn = config_dict.get('SFA_INTERFACE_HRN')
236 # Get the path to the authorities directory hierarchy
237 hierarchy = Hierarchy()
238 path = hierarchy.basedir
239 auth_path = hrn.replace(".", os.sep)
241 # define some useful variables
244 hrn_leaf = get_leaf(hrn)
247 new_server_key = os.sep.join([path, auth_path, hrn_leaf]) + ".pkey"
248 old_server_key = os.sep.join([path, key])
249 old_server_cert = os.sep.join([path, cert])
251 # remove old key/cert
252 for fd in [old_server_key, old_server_cert]:
253 if os.path.isfile(fd):
256 # create new server.key
258 distutils.file_util.copy_file(src=new_server_key, dst=old_server_key, verbose=1)
259 print "\t\t%(old_server_key)s\ncopied from\t%(new_server_key)s" % locals()
260 # this is expected when running this tool for the first time (before sfa-import-plc.py)
262 print "Could not create %(old_server_key)s - ignore if you haven't run sfa-import-plc.py yet"%locals()
272 parser = OptionParser(usage=command_usage, version="%prog 1.0")
273 parser.set_defaults(config_dir="/etc/sfa",
275 parser.add_option("","--configdir",dest="config_dir",action="append", help="specify configuration directory")
276 parser.add_option("","--usual_variable",dest="usual_variables",action="append", help="add a usual variable")
277 parser.add_option("-d", "--default", action="count", help="dont prompt for values, just use defaults")
278 (config,args) = parser.parse_args()
280 parser.error("too many arguments")
282 config_dir = parser.values.config_dir
283 config_file = os.sep.join([config_dir, 'sfa_config'])
284 defaults = get_defaults()
285 # if -d is specified dont prompt, just configure with defaults
287 save_config(defaults, config_file)
290 results = mainloop (defaults, config_file)
291 setup_server_key(results)
294 if __name__ == '__main__':