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
26 from optparse import make_option
27 from cStringIO import StringIO
29 from ganeti.cli import *
30 from ganeti import opcodes
31 from ganeti import logger
32 from ganeti import constants
33 from ganeti import utils
34 from ganeti import errors
37 _LIST_DEF_FIELDS = ["id", "status", "summary"]
40 constants.JOB_STATUS_QUEUED: "queued",
41 constants.JOB_STATUS_WAITLOCK: "waiting",
42 constants.JOB_STATUS_RUNNING: "running",
43 constants.JOB_STATUS_CANCELED: "canceled",
44 constants.JOB_STATUS_SUCCESS: "success",
45 constants.JOB_STATUS_ERROR: "error",
49 def ListJobs(opts, args):
53 if opts.output is None:
54 selected_fields = _LIST_DEF_FIELDS
55 elif opts.output.startswith("+"):
56 selected_fields = _LIST_DEF_FIELDS + opts.output[1:].split(",")
58 selected_fields = opts.output.split(",")
60 output = GetClient().QueryJobs(None, selected_fields)
61 if not opts.no_headers:
62 # TODO: Implement more fields
67 "opresult": "OpCode_result",
68 "opstatus": "OpCode_status",
69 "oplog": "OpCode_log",
71 "opstart": "OpCode_start",
72 "opend": "OpCode_end",
75 "received_ts": "Received",
80 # we don't have yet unitfields here
84 # change raw values to nicer strings
86 for idx, field in enumerate(selected_fields):
89 if val in _USER_JOB_STATUS:
90 val = _USER_JOB_STATUS[val]
92 raise errors.ProgrammerError("Unknown job status code '%s'" % val)
93 elif field == "summary":
95 elif field in ("start_ts", "end_ts", "received_ts"):
96 val = FormatTimestamp(val)
97 elif field in ("opstart", "opend"):
98 val = [FormatTimestamp(entry) for entry in val]
102 data = GenerateTable(separator=opts.separator, headers=headers,
103 fields=selected_fields, unitfields=unitfields,
104 numfields=numfields, data=output)
111 def ArchiveJobs(opts, args):
115 client.ArchiveJob(job_id)
120 def AutoArchiveJobs(opts, args):
128 age = ParseTimespec(age)
130 client.AutoArchiveJobs(age)
134 def CancelJobs(opts, args):
138 client.CancelJob(job_id)
143 def ShowJobs(opts, args):
147 def format(level, text):
148 """Display the text indented."""
149 print "%s%s" % (" " * level, text)
151 def result_helper(value):
152 """Format a result field in a nice way."""
153 if isinstance(value, (tuple, list)):
154 return "[%s]" % (", ".join(str(elem) for elem in value))
159 "id", "status", "ops", "opresult", "opstatus", "oplog",
160 "opstart", "opend", "received_ts", "start_ts", "end_ts",
163 result = GetClient().QueryJobs(args, selected_fields)
167 for idx, entry in enumerate(result):
175 format(0, "Job ID %s not found" % args[idx])
177 # this should not happen, when we don't pass args it will be a
179 format(0, "Job ID requested as argument %s not found" % (idx + 1))
182 (job_id, status, ops, opresult, opstatus, oplog,
183 opstart, opend, recv_ts, start_ts, end_ts) = entry
184 format(0, "Job ID: %s" % job_id)
185 if status in _USER_JOB_STATUS:
186 status = _USER_JOB_STATUS[status]
188 raise errors.ProgrammerError("Unknown job status code '%s'" % val)
190 format(1, "Status: %s" % status)
192 if recv_ts is not None:
193 format(1, "Received: %s" % FormatTimestamp(recv_ts))
195 format(1, "Missing received timestamp (%s)" % str(recv_ts))
197 if start_ts is not None:
198 if recv_ts is not None:
199 d1 = start_ts[0] - recv_ts[0] + (start_ts[1] - recv_ts[1]) / 1000000.0
200 delta = " (delta %.6fs)" % d1
203 format(1, "Processing start: %s%s" % (FormatTimestamp(start_ts), delta))
205 format(1, "Processing start: unknown (%s)" % str(start_ts))
207 if end_ts is not None:
208 if start_ts is not None:
209 d2 = end_ts[0] - start_ts[0] + (end_ts[1] - start_ts[1]) / 1000000.0
210 delta = " (delta %.6fs)" % d2
213 format(1, "Processing end: %s%s" % (FormatTimestamp(end_ts), delta))
215 format(1, "Processing end: unknown (%s)" % str(end_ts))
217 if end_ts is not None and recv_ts is not None:
218 d3 = end_ts[0] - recv_ts[0] + (end_ts[1] - recv_ts[1]) / 1000000.0
219 format(1, "Total processing time: %.6f seconds" % d3)
221 format(1, "Total processing time: N/A")
222 format(1, "Opcodes:")
223 for (opcode, result, status, log, s_ts, e_ts) in \
224 zip(ops, opresult, opstatus, oplog, opstart, opend):
225 format(2, "%s" % opcode["OP_ID"])
226 format(3, "Status: %s" % status)
227 if isinstance(s_ts, (tuple, list)):
228 format(3, "Processing start: %s" % FormatTimestamp(s_ts))
230 format(3, "No processing start time")
231 if isinstance(e_ts, (tuple, list)):
232 format(3, "Processing end: %s" % FormatTimestamp(e_ts))
234 format(3, "No processing end time")
235 format(3, "Input fields:")
236 for key, val in opcode.iteritems():
239 if isinstance(val, (tuple, list)):
241 format(4, "%s: %s" % (key, val))
243 format(3, "No output data")
244 elif isinstance(result, (tuple, list)):
246 format(3, "Result: empty sequence")
250 format(4, result_helper(elem))
251 elif isinstance(result, dict):
253 format(3, "Result: empty dictionary")
255 for key, val in result.iteritems():
256 format(4, "%s: %s" % (key, result_helper(val)))
258 format(3, "Result: %s" % result)
259 format(3, "Execution log:")
260 for serial, log_ts, log_type, log_msg in log:
261 time_txt = FormatTimestamp(log_ts)
262 encoded = str(log_msg).encode('string_escape')
263 format(4, "%s:%s:%s %s" % (serial, time_txt, log_type, encoded))
268 'list': (ListJobs, ARGS_NONE,
269 [DEBUG_OPT, NOHDR_OPT, SEP_OPT, USEUNITS_OPT, FIELDS_OPT],
270 "", "List the jobs and their status. The available fields are"
271 " (see the man page for details): id, status, op_list,"
272 " op_status, op_result."
274 " list is (in order): %s." % ", ".join(_LIST_DEF_FIELDS)),
275 'archive': (ArchiveJobs, ARGS_ANY,
277 "<job-id> [<job-id> ...]",
278 "Archive specified jobs"),
279 'autoarchive': (AutoArchiveJobs, ARGS_ONE,
282 "Auto archive jobs older than the given age"),
283 'cancel': (CancelJobs, ARGS_ANY,
285 "<job-id> [<job-id> ...]",
286 "Cancel specified jobs"),
287 'info': (ShowJobs, ARGS_ANY, [DEBUG_OPT],
288 "<job-id> [<job-id> ...]",
289 "Show detailed information about the specified jobs"),
293 if __name__ == '__main__':
294 sys.exit(GenericMain(commands))