3
# Copyright (c) 2006 Andrew Beekhof
6
# This program is free software; you can redistribute it and/or modify
7
# it under the terms of version 2 of the GNU General Public License as
8
# published by the Free Software Foundation.
10
# This program is distributed in the hope that it would be useful, but
11
# WITHOUT ANY WARRANTY; without even the implied warranty of
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
14
# Further, this software is distributed without any warranty that it is
15
# free of the rightful claim of any third person regarding infringement
16
# or the like. Any license provided herein, whether implied or
17
# otherwise, applies only to this software file. Patent licenses, if
18
# any, provided herein do not apply to combinations of this program with
19
# other software, or any other product whatsoever.
21
# You should have received a copy of the GNU General Public License
22
# along with this program; if not, write the Free Software Foundation,
23
# Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307, USA.
25
#######################################################################
31
from popen2 import Popen3
33
# Module copied from Mercurial
35
sys.path.append("@CRM_DAEMON_DIR@")
36
import crm_utils as utl
37
import crm_commands as crm
40
class ParseError(Exception):
41
"""Exception raised on errors in parsing the command line."""
42
class QuotingError(Exception):
43
"""Exception raised on errors in parsing the command line."""
44
class UnknownCommand(Exception):
45
"""Exception raised if command is not in the command table."""
46
class AmbiguousCommand(Exception):
47
"""Exception raised if command shortcut matches more than one command."""
51
crm.help, None, [('v', 'verbose', None, 'extra information')],
53
"^up": (crm.up, None, [], None, "Move up a level in the heirarchy"),
54
"^crm": (crm.cd_, ["crm"], [], None),
55
"^nodes": (crm.cd_, ["crm"], [], None),
56
"^resources": (crm.cd_, ["crm"], [], None),
57
"^config": (crm.cd_, ["crm"], [], None),
59
crm.do_list, ["nodes", "resources"], [('t', 'topic', "", '')],
62
crm.do_status, ["nodes", "resources"], [],
64
"^debug": (crm.toggle_flag, None, [('f', 'flag', 'debug', '')], None, "Toggle debugging information"),
65
"^exit": (crm.exit, None, [], "exit"),
67
crm.debugstate, None, [],
69
"Dump information about the internal state of the program"),
73
('q', 'quiet', None, 'suppress output'),
74
('v', 'verbose', None, 'enable additional output'),
75
('', 'debug', None, 'enable debugging output'),
76
('', 'devlog', None, 'enable developmental debugging output'),
77
('', 'debugger', None, 'start debugger'),
78
('', 'lsprof', None, 'print improved command execution profile'),
79
('', 'traceback', None, 'print traceback on exception'),
80
('', 'time', None, 'time how long the command takes'),
81
('', 'profile', None, 'print command execution profile'),
82
('', 'version', None, 'output version information and exit'),
83
('i', 'interactive', None, 'run in interactive mode'),
84
('h', 'help', None, 'display help and exit'),
88
utl.log_dev("Looking up help text for: %s" % text)
90
utl.log_info("cluster.py [global options] [topic [topic...]] [command]")
93
choice = findpossible(text, None, False)
94
for key in choice.keys():
95
alias, e = choice[key]
97
utl.log_dev("Help text for: %s" % text)
101
utl.log_info("\n"+e[4]+"\n")
102
possible = findpossible("", text).keys()
103
utl.log_dev("Possible sub-commands: "+repr(possible))
104
possible.remove("up")
105
possible.remove("help")
106
possible.remove("exit")
108
possible.remove(text)
110
sub_cmd=' ('+'|'.join(possible)+')'
112
utl.log_info("Usage: %s %s%s" % (text, e[3], sub_cmd))
114
utl.log_info("Usage: %s%s" % (text, sub_cmd))
117
utl.log_err("No help text available for: %s" % text)
120
# Stolen from Mercurial commands.py
122
def findpossible(cmd, topic=None, filter=True):
124
Return cmd -> (aliases, command table entry)
125
for each matching command.
126
Return debug commands (or their aliases) only if no normal command matches.
129
topic = utl.crm_topic
130
utl.log_dev("Searching in default topic: %s" % topic)
132
utl.log_dev("Looking for completions of %s in %s" % (cmd, topic))
136
for e in table.keys():
138
#utl.log_dev("Processing: %s / %s" % (e, repr(t)))
139
aliases = e.lstrip("^").split("|")
141
if "^%s"%topic == e and t[0] == crm.cd_:
142
#utl.log_dev("Found: topic")
143
topicchoice[topic] = (aliases, table[e])
144
if filter and t[1] and topic not in t[1]:
145
#utl.log_dev("Skip: filter")
148
#utl.log_dev("Found: alias")
152
if a.startswith(cmd):
153
#utl.log_dev("Found: alias prefix")
156
if found is not None:
157
if aliases[0].startswith("debug"):
158
debugchoice[found] = (aliases, table[e])
160
choice[found] = (aliases, table[e])
162
if not choice and debugchoice:
165
if not choice and topicchoice:
171
"""Return (aliases, command table entry) for command string."""
172
choice = findpossible(cmd)
174
if choice.has_key(cmd):
175
#utl.log_dev("Choice has: %s" % cmd)
179
clist = choice.keys()
181
raise AmbiguousCommand(cmd, clist)
184
#utl.log_dev("Returning first: %s" % (repr(choice.values()[0])))
185
return choice.values()[0]
187
raise UnknownCommand(cmd)
189
def find_completer(start, i):
190
choice = findpossible(start)
193
elif len(choice.keys()) < i:
195
return choice.keys()[i]
202
args = utl.fancyopts(args, global_opt_table, options)
203
except utl.getopt.GetoptError, inst:
204
raise ParseError(None, inst)
207
cmd, args = args[0], args[1:]
208
utl.log_dev("Initial Command: %s" % cmd)
209
aliases, i = findcmd(cmd)
211
utl.log_dev("Found Command: %s" % cmd)
214
args = defaults.split() + args
220
# combine global options into local
221
for o in global_opt_table:
222
c.append((o[0], o[1], options[o[1]], o[3]))
225
args = utl.fancyopts(args, c, cmdoptions)
226
except utl.getopt.GetoptError, inst:
227
raise ParseError(cmd, inst)
229
# separate global options back out
230
for o in global_opt_table:
232
options[n] = cmdoptions[n]
235
utl.log_dev("args: %s\ncmdoptions: %s"
236
% (repr(args), repr(cmdoptions)))
237
return (cmd, cmd and i[0] or None, args, options, cmdoptions)
245
cmd, func, cmd_args, ignore, cmd_options = parse(args)
248
cmd_options["topic"] = cmd
250
utl.log_dev("Func Command: %s" % cmd)
251
utl.log_dev("Func Args: %s" % repr(cmd_args))
252
utl.log_dev("Func Opts: %s" % repr(cmd_options))
255
utl.log_dev(repr(args))
257
d = lambda: func(*cmd_args, **cmd_options)
260
except crm.HelpRequest, inst:
264
except crm.ReparseRequest:
265
return main_loop(cmd_args)
267
except ParseError, inst:
269
utl.log_err("%s: %s\n" % (inst.args[0], inst.args[1]))
272
utl.log_err("%s\n" % inst.args[1])
275
except AmbiguousCommand, inst:
276
utl.log_info("%s: command '%s' is ambiguous:\n %s\n"
277
% (" ".join(utl.topic_stack), inst.args[0], " ".join(inst.args[1])))
279
except UnknownCommand, inst:
280
utl.log_err("%s: unknown command '%s'\n" % (" ".join(utl.topic_stack), inst.args[0]))
283
except IOError, inst:
284
if hasattr(inst, "code"):
285
utl.log_err("abort: %s\n" % inst)
286
elif hasattr(inst, "reason"):
287
utl.log_err("abort: error: %s\n" % inst.reason[1])
288
elif hasattr(inst, "args"):
289
utl.log_err("broken pipe\n")
290
elif getattr(inst, "strerror", None):
291
if getattr(inst, "filename", None):
292
utl.log_err("abort: %s - %s\n" % (inst.strerror, inst.filename))
294
utl.log_err("abort: %s\n" % inst.strerror)
297
except OSError, inst:
298
if hasattr(inst, "filename"):
299
utl.log_err("abort: %s: %s\n" % (inst.strerror, inst.filename))
301
utl.log_err("abort: %s\n" % inst.strerror)
303
except TypeError, inst:
304
# was this an argument error?
305
tb = traceback.extract_tb(sys.exc_info()[2])
308
utl.log_err((inst, "\n"))
309
utl.log_err(("%s: invalid arguments\n" % cmd))
312
except SystemExit, inst:
317
utl.log_err("** unknown exception encountered, details follow\n")
323
utl.init_readline(find_completer)
325
cmd, f_ignore, a_ignore, utl.global_opts, o_ignore = parse(args)
329
if len(sys.argv) == 1:
330
utl.global_opts["interactive"] = 1
331
elif not utl.global_opts.has_key("interactive"):
332
utl.global_opts["interactive"] = 0
337
utl.set_topic(utl.topic_stack[-1])
339
utl.log_debug("rc: %s" % (repr(rc)))
341
if not utl.global_opts["interactive"]:
345
text = raw_input(" ".join(utl.topic_stack) +" # ")
346
args = utl.create_argv(text)
348
except QuotingError, inst:
350
utl.log_err("%s. Found tokens: %s\n" % (inst.args[0], inst.args[1]))
352
utl.log_err("%s\n" % inst.args[0])
354
except KeyboardInterrupt: