finished save
[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     from pprint import pprint
68     cfile = open(config_file, 'r')
69     lines = cfile.readlines()
70     newlines = []
71     cfile.close()
72     for line in lines:
73         added = False
74         for variable in changes:
75             if line.startswith(variable):
76                 try:
77                     value = int(changes[variable])
78                     newline = '%s=%s\n' % (variable, value)
79                     print "adding ", newline
80                     newlines.append(newline)
81                 except:
82                     value = changes[variable]
83                     newline = '%s="%s"\n' % (variable, value)
84                     print "adding ", newline
85                     newlines.append(newline)
86                 added = True
87                 break
88         if not added:
89             newlines.append(line) 
90     
91     cfile = open(config_file, 'w')
92     cfile.writelines(newlines)
93     cfile.close()
94
95 def get_defaults():
96     geni_config = Config()
97     plc_vars = {'PLC_API_MAINTENANCE_PASSWORD': 'GENI_PLC_PASSWORD',
98                 'PLC_API_MAINTENCE_USER': 'GENI_PLC_PASSWORD'
99                }
100     try:
101         from geni.util.config import plcConfig
102         plc_config = plcConfig
103     except:
104         plc_config = None
105     
106     defaults = {}
107     for var in dir(geni_config):
108         if var.startswith('GENI'):
109             value = eval("geni_config.%s" % var)
110             defaults[var] = value
111
112     # some defaults come from plc_config
113     for var in dir(plc_config):
114         if var in plc_vars:
115             value = eval("plc_config.%s" % var)
116             defaults[plc_vars[var]] = value
117
118     return defaults       
119
120 def prompt_variable(variable, default_config):
121     if variable in default_config:
122         default_value = default_config[variable]
123     else:
124         default_value = ""  
125    
126     while True:
127         prompt = "%(variable)s : [%(default_value)s] " % locals()
128         try: 
129             answer = raw_input(prompt).strip()
130         except EOFError:
131             raise Exception ('BailOut')
132         except KeyboardInterrupt:
133             print "\n"
134             raise Excception ('BailOut')
135
136         if (answer == "") or (answer == default_value):
137             return default_value
138         elif (answer == "."):
139             raise Exception ('BailOut')
140         elif (answer == "?"):
141             print variable_usage.strip()
142         elif (answer == "="):
143             print ("%s defaults to %s" %(variable,default_value))
144         else:
145             return answer        
146     
147 def mainloop (default_config, config_file):
148     changes = {}
149     while True:
150         try:
151             answer = raw_input("Enter command (u for usual changes, w to save, ? for help) ").strip()
152         except EOFError:
153             answer =""
154         except KeyboardInterrupt:
155             print "\nBye"
156             sys.exit()
157
158         if (answer == "") or (answer in "?hH"):
159             print mainloop_usage
160             continue
161         if answer in ['?']:
162             print "help"  
163
164         if (answer in ["q","Q"]):
165             # todo check confirmation
166             return
167         elif (answer == "w"):
168             save(changes, config_file)
169         elif (answer == "u"):
170             try: 
171                 for varname in usual_variables:
172                     changes[varname] = prompt_variable(varname, default_config)
173             except Exception, inst:
174                 if (str(inst) != 'BailOut'):
175                     raise
176         elif (answer in ["e","E"]):
177             try:
178                 prompt_variable (cdef,cread,cwrite,category,variable,
179                                  show_comments,False)
180             except Exception, inst:
181                 if (str(inst) != 'BailOut'):
182                     raise
183         elif (answer in "vVsSlL"):
184             pass
185             #show_variable (c1,c2,c3,category,variable,show_value,show_comments)
186         else:
187             print ("Unknown command >%s< -- use h for help" % answer)
188
189 ####################
190 def main ():
191
192     command=sys.argv[0]
193     argv = sys.argv[1:]
194     save = True
195     parser = OptionParser(usage=command_usage, version="%prog 1.0")
196     parser.set_defaults(config_dir="/etc/geni",
197                         usual_variables=[])
198     parser.add_option("","--configdir",dest="config_dir",help="specify configuration directory")
199     parser.add_option("","--usual_variable",dest="usual_variables",action="append", help="add a usual variable")
200
201     (config,args) = parser.parse_args()
202     if len(args)>3:
203         parser.error("too many arguments")
204
205     config_dir = parser.values.config_dir
206     config_file = os.sep.join([config_dir, 'geni_config'])
207     defaults = get_defaults()
208     mainloop (defaults, config_file)
209     return 0
210
211 if __name__ == '__main__':
212     main()