003495a6d2f093e01589c8ec440142b43cc76649
[sfa.git] / geni-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 traceback
19 from optparse import OptionParser
20
21 from geni.util.config import Config
22
23 usual_variables = ["GENI_REGISTRY_ROOT_AUTH",
24                    "GENI_REGISTRY_LEVEL1_AUTH",
25                    "GENI_REGISTRY_ENABLED",
26                    "GENI_REGISTRY_HOST", 
27                    "GENI_REGISTRY_PORT",
28                    "GENI_AGGREGATE_ENABLED",
29                    "GENI_AGGREGATE_HOST",
30                    "GENI_AGGREGATE_PORT",
31                    "GENI_SM_ENABLED",
32                    "GENI_SM_HOST",
33                    "GENI_SM_PORT",
34                    "GENI_PLC_USER",
35                    "GENI_PLC_PASSWORD",    
36                    "GENI_PLC_HOST",
37                    "GENI_PLC_PORT",
38                    "GENI_PLC_API_PATH"
39                    ]
40
41
42 mainloop_usage= """Available commands:
43  Uppercase versions give variables comments, when available
44  u/U\t\t\tEdit usual variables
45  w/W\t\t\tWrite / Write & reload
46  q\t\t\tQuit (without saving)
47  h/?\t\t\tThis help
48 ---
49  l/L [<var>]\tShow Locally modified variables/values
50  s/S [<var>]\tShow variables/values (all, in category, single)
51  e/E [<var>]\tEdit variables (all, in category, single)
52 ---
53 """ 
54
55 command_usage="%prog [options]"
56 command_usage += """
57   Unless you specify the -d option, meaning you want to configure
58   myplc-devel instead of regular myplc, in which case""" 
59
60 variable_usage= """Edit Commands :
61 .\tStops prompting, return to mainloop
62 =\tShows default value
63 ?\tThis help    
64 """
65
66 def save(changes, config_file):
67     cfile = open(config_file, 'r')
68     newlines = []
69     for line in cfile:
70         newlines.append(line)
71         for variable in changes:
72             if line.startswith(variable):
73                 print variable
74                 try:
75                     value = int(changes[variable])
76                     newlines.append('%s=%s' % (variable, value))
77                 except:
78                     value = changes[variable]
79                     newlines.append('%s="%s"' % (variable, value))
80     from pprint import pprint
81     pprint(newlines)
82     cfile.close()
83     cfile = open(config_file, 'w')
84     cfile.writelines(newlines)
85     cfile.close()
86
87 def get_defaults():
88     geni_config = Config()
89     plc_vars = {'PLC_API_MAINTENANCE_PASSWORD': 'GENI_PLC_PASSWORD',
90                 'PLC_API_MAINTENCE_USER': 'GENI_PLC_PASSWORD'
91                }
92     try:
93         from geni.util.config import plcConfig
94         plc_config = plcConfig
95     except:
96         plc_config = None
97     
98     defaults = {}
99     for var in dir(geni_config):
100         if var.startswith('GENI'):
101             value = eval("geni_config.%s" % var)
102             defaults[var] = value
103
104     # some defaults come from plc_config
105     for var in dir(plc_config):
106         if var in plc_vars:
107             value = eval("plc_config.%s" % var)
108             defaults[plc_vars[var]] = value
109
110     return defaults       
111
112 def prompt_variable(variable, default_config):
113     if variable in default_config:
114         default_value = default_config[variable]
115     else:
116         default_value = ""  
117    
118     while True:
119         prompt = "%(variable)s : [%(default_value)s] " % locals()
120         try: 
121             answer = raw_input(prompt).strip()
122         except EOFError:
123             raise Exception ('BailOut')
124         except KeyboardInterrupt:
125             print "\n"
126             raise Excception ('BailOut')
127
128         if (answer == "") or (answer == default_value):
129             return default_value
130         elif (answer == "."):
131             raise Exception ('BailOut')
132         elif (answer == "?"):
133             print variable_usage.strip()
134         elif (answer == "="):
135             print ("%s defaults to %s" %(variable,default_value))
136         else:
137             return answer        
138     
139 def mainloop (default_config, config_file):
140     changes = {}
141     while True:
142         try:
143             answer = raw_input("Enter command (u for usual changes, w to save, ? for help) ").strip()
144         except EOFError:
145             answer =""
146         except KeyboardInterrupt:
147             print "\nBye"
148             sys.exit()
149
150         if (answer == "") or (answer in "?hH"):
151             print mainloop_usage
152             continue
153         if answer in ['?']:
154             print "help"  
155
156         if (answer in ["q","Q"]):
157             # todo check confirmation
158             return
159         elif (answer == "w"):
160             save(changes, config_file)
161         elif (answer == "u"):
162             try: 
163                 for varname in usual_variables:
164                     changes[varname] = prompt_variable(varname, default_config)
165             except Exception, inst:
166                 if (str(inst) != 'BailOut'):
167                     raise
168         elif (answer in ["e","E"]):
169             try:
170                 prompt_variable (cdef,cread,cwrite,category,variable,
171                                  show_comments,False)
172             except Exception, inst:
173                 if (str(inst) != 'BailOut'):
174                     raise
175         elif (answer in "vVsSlL"):
176             pass
177             #show_variable (c1,c2,c3,category,variable,show_value,show_comments)
178         else:
179             print ("Unknown command >%s< -- use h for help" % answer)
180
181 ####################
182 def main ():
183
184     command=sys.argv[0]
185     argv = sys.argv[1:]
186     save = True
187     parser = OptionParser(usage=command_usage, version="%prog 1.0")
188     parser.set_defaults(config_dir="/etc/geni",
189                         usual_variables=[])
190     parser.add_option("","--configdir",dest="config_dir",help="specify configuration directory")
191     parser.add_option("","--usual_variable",dest="usual_variables",action="append", help="add a usual variable")
192
193     (config,args) = parser.parse_args()
194     if len(args)>3:
195         parser.error("too many arguments")
196
197     config_dir = parser.values.config_dir
198     config_file = os.sep.join([config_dir, 'geni_config'])
199     defaults = get_defaults()
200     mainloop (defaults, config_file)
201     return 0
202
203 if __name__ == '__main__':
204     main()