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
20 from plc_config import PLCConfiguration
24 release_rev = "$Revision$"
26 def init_flavour (flavour):
28 global usual_variables
29 if (flavour == "devel"):
31 usual_variables=("PLC_DEVEL_FEDORA_URL",
33 config_dir = "/plc/devel/data/etc/planetlab"
36 usual_variables=("PLC_NAME",
41 "PLC_MAIL_SUPPORT_ADDRESS",
49 config_dir = "/etc/planetlab"
50 global def_default_config
51 def_default_config= "%s/default_config.xml" % config_dir
52 global def_site_config
53 def_site_config = "%s/configs/site.xml" % config_dir
54 global def_consolidated_config
55 def_consolidated_config = "%s/plc_config.xml" % config_dir
58 mainloop_usage= """Available commands:
59 Uppercase versions give variables comments, when available
60 u/U\t\t\tEdit usual variables
61 w\t\t\tWrite & consolidate
62 r\t\t\tRestart %s service
63 q\t\t\tQuit (without saving)
66 l/L [<cat>|<var>]\tShow Locally modified variables/values
67 s/S [<cat>|<var>]\tShow variables/values (all, in category, single)
68 e/E [<cat>|<var>]\tEdit variables (all, in category, single)
70 c\t\t\tList categories
71 v/V [<cat>|<var>]List Variables (all, in category, single)
73 Typical usage involves: u, [l,] w, r, q
77 command_usage="Usage: %s [-d] [-v] [default-xml [site-xml [consolidated-xml]]]"% sys.argv[0]
80 -v shows version and exits
81 \t default-xml defaults to %s
82 \t site-xml defaults to %s
83 \t consolidated-xml defaults to %s""" % (def_default_config,def_site_config, def_consolidated_config)
85 Unless you specify the -d option, meaning you want to configure
86 myplc-devel instead of regular myplc, in which case"""
87 init_flavour ("devel")
89 \t default-xml defaults to %s
90 \t site-xml defaults to %s
91 \t consolidated-xml defaults to %s""" % (def_default_config,def_site_config, def_consolidated_config)
96 variable_usage= """Edit Commands :
97 #\tShow variable comments
98 .\tStops prompting, return to mainloop
99 /\tCleans any site-defined value, reverts to default
100 =\tShows default value
101 >\tSkips to next category
106 def get_value (config, category_id, variable_id):
107 (category, variable) = config.get (category_id, variable_id)
108 return variable['value']
110 def get_current_value (cread, cwrite, category_id, variable_id):
111 # the value stored in cwrite, if present, is the one we want
113 result=get_value (cwrite,category_id,variable_id)
115 result=get_value (cread,category_id,variable_id)
118 # refrain from using plc_config's _sanitize
119 def get_varname (config, category_id, variable_id):
120 (category, variable) = config.get (category_id, variable_id)
121 return (category_id+"_"+variable['id']).upper()
123 # could not avoid using _sanitize here..
124 def get_name_comments (config, cid, vid):
126 (category, variable) = config.get (cid, vid)
127 (id, name, value, comments) = config._sanitize_variable (cid,variable)
128 return (name,comments)
132 def print_name_comments (config, cid, vid):
133 (name,comments)=get_name_comments(config,cid,vid)
135 print "### %s" % name
137 for line in comments:
140 print "!!! No comment associated to %s_%s" % (cid,vid)
143 def list_categories (config):
145 for (category_id, (category, variables)) in config.variables().iteritems():
146 result += [category_id]
149 def print_categories (config):
150 print "Known categories"
151 for cid in list_categories(config):
152 print "%s" % (cid.upper())
155 def list_category (config, cid):
157 for (category_id, (category, variables)) in config.variables().iteritems():
158 if (cid == category_id):
159 for variable in variables.values():
160 result += ["%s_%s" %(cid,variable['id'])]
163 def print_category (config, cid, show_comments=True):
166 vids=list_category(config,cid)
168 print "%s : no such category"%CID
170 print "Category %s contains" %(CID)
175 def consolidate (default_config, site_config, consolidated_config):
177 conso = PLCConfiguration (default_config)
178 conso.load (site_config)
179 conso.save (consolidated_config)
180 except Exception, inst:
181 print "Could not consolidate, %s" % (str(inst))
183 print ("Merged\n\t%s\nand\t%s\ninto\t%s"%(default_config,site_config,
184 consolidated_config))
185 os.system("set -x ; service plc reload")
189 print ("==================== Stopping %s" % service)
190 os.system("service %s stop" % service)
191 print ("==================== Starting %s" % service)
192 os.system("service %s start" % service)
195 def prompt_variable (cdef, cread, cwrite, category, variable,
196 show_comments, support_next=False):
198 assert category.has_key('id')
199 assert variable.has_key('id')
201 category_id = category ['id']
202 variable_id = variable['id']
205 default_value = get_value(cdef,category_id,variable_id)
206 current_value = get_current_value(cread,cwrite,category_id, variable_id)
207 varname = get_varname (cread,category_id, variable_id)
210 print_name_comments (cdef, category_id, variable_id)
211 prompt = "== %s : [%s] " % (varname,current_value)
213 answer = raw_input(prompt).strip()
215 raise Exception ('BailOut')
218 if (answer == "") or (answer == current_value):
220 elif (answer == "."):
221 raise Exception ('BailOut')
222 elif (answer == "#"):
223 print_name_comments(cread,category_id,variable_id)
224 elif (answer == "?"):
225 print variable_usage.strip()
226 elif (answer == "="):
227 print ("%s defaults to %s" %(varname,default_value))
228 # revert to default : remove from cwrite (i.e. site-config)
229 elif (answer == "/"):
230 cwrite.delete(category_id,variable_id)
231 print ("%s reverted to %s" %(varname,default_value))
233 elif (answer == ">"):
235 raise Exception ('NextCategory')
237 print "No support for next category"
239 variable['value'] = answer
240 cwrite.set(category,variable)
243 def prompt_variables_all (cdef, cread, cwrite, show_comments):
245 for (category_id, (category, variables)) in cread.variables().iteritems():
246 print ("========== Category = %s" % category_id.upper())
247 for variable in variables.values():
249 newvar = prompt_variable (cdef, cread, cwrite, category, variable,
251 except Exception, inst:
252 if (str(inst) == 'NextCategory'): break
255 except Exception, inst:
256 if (str(inst) == 'BailOut'): return
259 def prompt_variables_category (cdef, cread, cwrite, cid, show_comments):
263 print ("========== Category = %s" % CID)
264 for vid in list_category(cdef,cid):
265 (category,variable) = cdef.locate_varname(vid.upper())
266 newvar = prompt_variable (cdef, cread, cwrite, category, variable,
267 show_comments, False)
268 except Exception, inst:
269 if (str(inst) == 'BailOut'): return
273 def show_variable (cdef, cread, cwrite,
274 category, variable,show_value,show_comments):
275 assert category.has_key('id')
276 assert variable.has_key('id')
278 category_id = category ['id']
279 variable_id = variable['id']
281 default_value = get_value(cdef,category_id,variable_id)
282 current_value = get_current_value(cread,cwrite,category_id,variable_id)
283 varname = get_varname (cread,category_id, variable_id)
285 print_name_comments (cdef, category_id, variable_id)
287 print "%s = %s" % (varname,current_value)
289 print "%s" % (varname)
291 def show_variables_all (cdef, cread, cwrite, show_value, show_comments):
292 for (category_id, (category, variables)) in cread.variables().iteritems():
293 print ("========== Category = %s" % category_id.upper())
294 for variable in variables.values():
295 show_variable (cdef, cread, cwrite,
296 category, variable,show_value,show_comments)
298 def show_variables_category (cdef, cread, cwrite, cid, show_value,show_comments):
301 print ("========== Category = %s" % CID)
302 for vid in list_category(cdef,cid):
303 (category,variable) = cdef.locate_varname(vid.upper())
304 show_variable (cdef, cread, cwrite, category, variable,
305 show_value,show_comments)
308 re_mainloop_0arg="^(?P<command>[uUwrqlLsSeEcvVhH\?])[ \t]*$"
309 re_mainloop_1arg="^(?P<command>[sSeEvV])[ \t]+(?P<arg>\w+)$"
310 matcher_mainloop_0arg=re.compile(re_mainloop_0arg)
311 matcher_mainloop_1arg=re.compile(re_mainloop_1arg)
313 def mainloop (cdef, cread, cwrite, default_config, site_config, consolidated_config):
316 answer = raw_input("Enter command (u for usual changes, w to save, ? for help) ").strip()
319 if (answer == "") or (answer in "?hH"):
322 groups_parse = matcher_mainloop_0arg.match(answer)
325 command = groups_parse.group('command')
328 groups_parse = matcher_mainloop_1arg.match(answer)
330 command = groups_parse.group('command')
331 arg=groups_parse.group('arg')
333 print ("Unknown command >%s< -- use h for help" % answer)
336 show_comments=command.isupper()
337 command=command.lower()
343 variables=list_category (cdef,arg)
345 # category_id as the category name
346 # variables as the list of variable names
350 (category,variable)=cdef.locate_varname(arg)
352 # category/variable as output by locate_varname
355 print "%s: no such category or variable" % arg
358 if (command in "qQ"):
359 # todo check confirmation
361 elif (command in "wW"):
363 cwrite.save(site_config)
365 print ("Could not save -- fix write access on %s" % site_config)
367 print ("Wrote %s" % site_config)
368 consolidate(default_config, site_config, consolidated_config)
369 print ("You might want to type 'r' (restart plc) or 'q' (quit)")
370 elif (command == "u"):
372 for varname in usual_variables:
373 (category,variable) = cdef.locate_varname(varname)
374 prompt_variable(cdef, cread, cwrite, category, variable, False)
375 except Exception, inst:
376 if (str(inst) != 'BailOut'):
378 elif (command == "r"):
380 elif (command == "c"):
381 print_categories(cread)
382 elif (command in "eE"):
384 prompt_variables_all(cdef, cread, cwrite,show_comments)
385 elif mode == 'CATEGORY':
386 prompt_variables_category(cdef,cread,cwrite,category_id,show_comments)
387 elif mode == 'VARIABLE':
389 prompt_variable (cdef,cread,cwrite,category,variable,
391 except Exception, inst:
392 if (str(inst) != 'BailOut'):
394 elif (command in "vVsSlL"):
395 show_value=(command in "sSlL")
396 (c1,c2,c3) = (cdef, cread, cwrite)
397 if (command in "lL"):
398 (c1,c2,c3) = (cwrite,cwrite,cwrite)
400 show_variables_all(c1,c2,c3,show_value,show_comments)
401 elif mode == 'CATEGORY':
402 show_variables_category(c1,c2,c3,category_id,show_value,show_comments)
403 elif mode == 'VARIABLE':
404 show_variable (c1,c2,c3,category,variable,show_value,show_comments)
406 print ("Unknown command >%s< -- use h for help" % answer)
409 # creates directory for file if not yet existing
410 def check_dir (config_file):
411 dirname = os.path.dirname (config_file)
412 if (not os.path.exists (dirname)):
413 os.makedirs(dirname,0755)
414 if (not os.path.exists (dirname)):
415 print "Cannot create dir %s - exiting" % dirname
418 print "Created directory %s" % dirname
427 # default is myplc (non -devel) unless -d is specified
429 optlist,list = getopt.getopt(argv,":dhv")
434 print ("This is %s - %s" %(command,release_rev))
437 init_flavour("devel")
441 (default_config,site_config,consolidated_config) = (def_default_config, def_site_config, def_consolidated_config)
443 (default_config,site_config,consolidated_config) = (argv[0], def_site_config, def_consolidated_config)
445 (default_config, site_config,consolidated_config) = (argv[0], argv[1], def_consolidated_config)
447 (default_config, site_config,consolidated_config) = argv
451 for c in (default_config,site_config,consolidated_config):
455 # the default settings only - read only
456 cdef = PLCConfiguration(default_config)
458 # in effect : default settings + local settings - read only
459 cread = PLCConfiguration(default_config)
462 print ("default config files not found, is myplc installed ?")
465 # local settings only, will be modified & saved
466 cwrite=PLCConfiguration()
469 cread.load(site_config)
470 cwrite.load(site_config)
472 cwrite = PLCConfiguration()
474 mainloop (cdef, cread, cwrite,default_config, site_config, consolidated_config)
477 if __name__ == '__main__':