4 # Copyright (C) 2006, 2007 Google Inc.
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 # General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22 # pylint: disable-msg=W0401,W0614
23 # W0401: Wildcard import ganeti.cli
24 # W0614: Unused import %s from wildcard import (since we need cli)
28 from ganeti.cli import *
29 from ganeti import constants
30 from ganeti import errors
33 #: default list of fields for L{ListJobs}
34 _LIST_DEF_FIELDS = ["id", "status", "summary"]
36 #: map converting the job status contants to user-visible
39 constants.JOB_STATUS_QUEUED: "queued",
40 constants.JOB_STATUS_WAITLOCK: "waiting",
41 constants.JOB_STATUS_RUNNING: "running",
42 constants.JOB_STATUS_CANCELED: "canceled",
43 constants.JOB_STATUS_SUCCESS: "success",
44 constants.JOB_STATUS_ERROR: "error",
48 def ListJobs(opts, args):
51 @param opts: the command line options selected by the user
53 @param args: should be an empty list
55 @return: the desired exit code
58 if opts.output is None:
59 selected_fields = _LIST_DEF_FIELDS
60 elif opts.output.startswith("+"):
61 selected_fields = _LIST_DEF_FIELDS + opts.output[1:].split(",")
63 selected_fields = opts.output.split(",")
65 output = GetClient().QueryJobs(None, selected_fields)
66 if not opts.no_headers:
67 # TODO: Implement more fields
72 "opresult": "OpCode_result",
73 "opstatus": "OpCode_status",
74 "oplog": "OpCode_log",
76 "opstart": "OpCode_start",
77 "opend": "OpCode_end",
80 "received_ts": "Received",
85 # we don't have yet unitfields here
89 # change raw values to nicer strings
91 for idx, field in enumerate(selected_fields):
94 if val in _USER_JOB_STATUS:
95 val = _USER_JOB_STATUS[val]
97 raise errors.ProgrammerError("Unknown job status code '%s'" % val)
98 elif field == "summary":
100 elif field in ("start_ts", "end_ts", "received_ts"):
101 val = FormatTimestamp(val)
102 elif field in ("opstart", "opend"):
103 val = [FormatTimestamp(entry) for entry in val]
107 data = GenerateTable(separator=opts.separator, headers=headers,
108 fields=selected_fields, unitfields=unitfields,
109 numfields=numfields, data=output)
116 def ArchiveJobs(opts, args):
119 @param opts: the command line options selected by the user
121 @param args: should contain the job IDs to be archived
123 @return: the desired exit code
129 client.ArchiveJob(job_id)
134 def AutoArchiveJobs(opts, args):
135 """Archive jobs based on age.
137 This will archive jobs based on their age, or all jobs if a 'all' is
140 @param opts: the command line options selected by the user
142 @param args: should contain only one element, the age as a time spec
143 that can be parsed by L{cli.ParseTimespec} or the keyword I{all},
144 which will cause all jobs to be archived
146 @return: the desired exit code
156 age = ParseTimespec(age)
158 client.AutoArchiveJobs(age)
162 def CancelJobs(opts, args):
163 """Cancel not-yet-started jobs.
165 @param opts: the command line options selected by the user
167 @param args: should contain the job IDs to be cancelled
169 @return: the desired exit code
175 client.CancelJob(job_id)
180 def ShowJobs(opts, args):
181 """Show detailed information about jobs.
183 @param opts: the command line options selected by the user
185 @param args: should contain the job IDs to be queried
187 @return: the desired exit code
190 def format(level, text):
191 """Display the text indented."""
192 ToStdout("%s%s", " " * level, text)
194 def result_helper(value):
195 """Format a result field in a nice way."""
196 if isinstance(value, (tuple, list)):
197 return "[%s]" % (", ".join(str(elem) for elem in value))
202 "id", "status", "ops", "opresult", "opstatus", "oplog",
203 "opstart", "opend", "received_ts", "start_ts", "end_ts",
206 result = GetClient().QueryJobs(args, selected_fields)
210 for idx, entry in enumerate(result):
218 format(0, "Job ID %s not found" % args[idx])
220 # this should not happen, when we don't pass args it will be a
222 format(0, "Job ID requested as argument %s not found" % (idx + 1))
225 (job_id, status, ops, opresult, opstatus, oplog,
226 opstart, opend, recv_ts, start_ts, end_ts) = entry
227 format(0, "Job ID: %s" % job_id)
228 if status in _USER_JOB_STATUS:
229 status = _USER_JOB_STATUS[status]
231 raise errors.ProgrammerError("Unknown job status code '%s'" % status)
233 format(1, "Status: %s" % status)
235 if recv_ts is not None:
236 format(1, "Received: %s" % FormatTimestamp(recv_ts))
238 format(1, "Missing received timestamp (%s)" % str(recv_ts))
240 if start_ts is not None:
241 if recv_ts is not None:
242 d1 = start_ts[0] - recv_ts[0] + (start_ts[1] - recv_ts[1]) / 1000000.0
243 delta = " (delta %.6fs)" % d1
246 format(1, "Processing start: %s%s" % (FormatTimestamp(start_ts), delta))
248 format(1, "Processing start: unknown (%s)" % str(start_ts))
250 if end_ts is not None:
251 if start_ts is not None:
252 d2 = end_ts[0] - start_ts[0] + (end_ts[1] - start_ts[1]) / 1000000.0
253 delta = " (delta %.6fs)" % d2
256 format(1, "Processing end: %s%s" % (FormatTimestamp(end_ts), delta))
258 format(1, "Processing end: unknown (%s)" % str(end_ts))
260 if end_ts is not None and recv_ts is not None:
261 d3 = end_ts[0] - recv_ts[0] + (end_ts[1] - recv_ts[1]) / 1000000.0
262 format(1, "Total processing time: %.6f seconds" % d3)
264 format(1, "Total processing time: N/A")
265 format(1, "Opcodes:")
266 for (opcode, result, status, log, s_ts, e_ts) in \
267 zip(ops, opresult, opstatus, oplog, opstart, opend):
268 format(2, "%s" % opcode["OP_ID"])
269 format(3, "Status: %s" % status)
270 if isinstance(s_ts, (tuple, list)):
271 format(3, "Processing start: %s" % FormatTimestamp(s_ts))
273 format(3, "No processing start time")
274 if isinstance(e_ts, (tuple, list)):
275 format(3, "Processing end: %s" % FormatTimestamp(e_ts))
277 format(3, "No processing end time")
278 format(3, "Input fields:")
279 for key, val in opcode.iteritems():
282 if isinstance(val, (tuple, list)):
284 format(4, "%s: %s" % (key, val))
286 format(3, "No output data")
287 elif isinstance(result, (tuple, list)):
289 format(3, "Result: empty sequence")
293 format(4, result_helper(elem))
294 elif isinstance(result, dict):
296 format(3, "Result: empty dictionary")
298 for key, val in result.iteritems():
299 format(4, "%s: %s" % (key, result_helper(val)))
301 format(3, "Result: %s" % result)
302 format(3, "Execution log:")
303 for serial, log_ts, log_type, log_msg in log:
304 time_txt = FormatTimestamp(log_ts)
305 encoded = str(log_msg).encode('string_escape')
306 format(4, "%s:%s:%s %s" % (serial, time_txt, log_type, encoded))
311 'list': (ListJobs, ARGS_NONE,
312 [DEBUG_OPT, NOHDR_OPT, SEP_OPT, USEUNITS_OPT, FIELDS_OPT],
313 "", "List the jobs and their status. The available fields are"
314 " (see the man page for details): id, status, op_list,"
315 " op_status, op_result."
317 " list is (in order): %s." % ", ".join(_LIST_DEF_FIELDS)),
318 'archive': (ArchiveJobs, ARGS_ANY,
320 "<job-id> [<job-id> ...]",
321 "Archive specified jobs"),
322 'autoarchive': (AutoArchiveJobs, ARGS_ONE,
325 "Auto archive jobs older than the given age"),
326 'cancel': (CancelJobs, ARGS_ANY,
328 "<job-id> [<job-id> ...]",
329 "Cancel specified jobs"),
330 'info': (ShowJobs, ARGS_ANY, [DEBUG_OPT],
331 "<job-id> [<job-id> ...]",
332 "Show detailed information about the specified jobs"),
336 if __name__ == '__main__':
337 sys.exit(GenericMain(commands))