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
21 """Job related commands"""
23 # pylint: disable-msg=W0401,W0613,W0614,C0103
24 # W0401: Wildcard import ganeti.cli
25 # W0613: Unused argument, since all functions follow the same API
26 # W0614: Unused import %s from wildcard import (since we need cli)
27 # C0103: Invalid name gnt-job
31 from ganeti.cli import *
32 from ganeti import constants
33 from ganeti import errors
34 from ganeti import utils
35 from ganeti import cli
38 #: default list of fields for L{ListJobs}
39 _LIST_DEF_FIELDS = ["id", "status", "summary"]
41 #: map converting the job status contants to user-visible
44 constants.JOB_STATUS_QUEUED: "queued",
45 constants.JOB_STATUS_WAITLOCK: "waiting",
46 constants.JOB_STATUS_CANCELING: "canceling",
47 constants.JOB_STATUS_RUNNING: "running",
48 constants.JOB_STATUS_CANCELED: "canceled",
49 constants.JOB_STATUS_SUCCESS: "success",
50 constants.JOB_STATUS_ERROR: "error",
54 def ListJobs(opts, args):
57 @param opts: the command line options selected by the user
59 @param args: should be an empty list
61 @return: the desired exit code
64 selected_fields = ParseFields(opts.output, _LIST_DEF_FIELDS)
66 output = GetClient().QueryJobs(args, selected_fields)
67 if not opts.no_headers:
68 # TODO: Implement more fields
73 "opresult": "OpCode_result",
74 "opstatus": "OpCode_status",
75 "oplog": "OpCode_log",
77 "opstart": "OpCode_start",
78 "opexec": "OpCode_exec",
79 "opend": "OpCode_end",
82 "received_ts": "Received",
87 # change raw values to nicer strings
88 for row_id, row in enumerate(output):
90 ToStderr("No such job: %s" % args[row_id])
93 for idx, field in enumerate(selected_fields):
96 if val in _USER_JOB_STATUS:
97 val = _USER_JOB_STATUS[val]
99 raise errors.ProgrammerError("Unknown job status code '%s'" % val)
100 elif field == "summary":
102 elif field in ("start_ts", "end_ts", "received_ts"):
103 val = FormatTimestamp(val)
104 elif field in ("opstart", "opexec", "opend"):
105 val = [FormatTimestamp(entry) for entry in val]
109 data = GenerateTable(separator=opts.separator, headers=headers,
110 fields=selected_fields, data=output)
117 def ArchiveJobs(opts, args):
120 @param opts: the command line options selected by the user
122 @param args: should contain the job IDs to be archived
124 @return: the desired exit code
131 if not client.ArchiveJob(job_id):
132 ToStderr("Failed to archive job with ID '%s'", job_id)
138 def AutoArchiveJobs(opts, args):
139 """Archive jobs based on age.
141 This will archive jobs based on their age, or all jobs if a 'all' is
144 @param opts: the command line options selected by the user
146 @param args: should contain only one element, the age as a time spec
147 that can be parsed by L{ganeti.cli.ParseTimespec} or the
148 keyword I{all}, which will cause all jobs to be archived
150 @return: the desired exit code
160 age = ParseTimespec(age)
162 (archived_count, jobs_left) = client.AutoArchiveJobs(age)
163 ToStdout("Archived %s jobs, %s unchecked left", archived_count, jobs_left)
168 def CancelJobs(opts, args):
169 """Cancel not-yet-started jobs.
171 @param opts: the command line options selected by the user
173 @param args: should contain the job IDs to be cancelled
175 @return: the desired exit code
181 (_, msg) = client.CancelJob(job_id)
184 # TODO: Different exit value if not all jobs were canceled?
188 def ShowJobs(opts, args):
189 """Show detailed information about jobs.
191 @param opts: the command line options selected by the user
193 @param args: should contain the job IDs to be queried
195 @return: the desired exit code
198 def format_msg(level, text):
199 """Display the text indented."""
200 ToStdout("%s%s", " " * level, text)
202 def result_helper(value):
203 """Format a result field in a nice way."""
204 if isinstance(value, (tuple, list)):
205 return "[%s]" % utils.CommaJoin(value)
210 "id", "status", "ops", "opresult", "opstatus", "oplog",
211 "opstart", "opexec", "opend", "received_ts", "start_ts", "end_ts",
214 result = GetClient().QueryJobs(args, selected_fields)
218 for idx, entry in enumerate(result):
226 format_msg(0, "Job ID %s not found" % args[idx])
228 # this should not happen, when we don't pass args it will be a
230 format_msg(0, "Job ID requested as argument %s not found" % (idx + 1))
233 (job_id, status, ops, opresult, opstatus, oplog,
234 opstart, opexec, opend, recv_ts, start_ts, end_ts) = entry
235 format_msg(0, "Job ID: %s" % job_id)
236 if status in _USER_JOB_STATUS:
237 status = _USER_JOB_STATUS[status]
239 raise errors.ProgrammerError("Unknown job status code '%s'" % status)
241 format_msg(1, "Status: %s" % status)
243 if recv_ts is not None:
244 format_msg(1, "Received: %s" % FormatTimestamp(recv_ts))
246 format_msg(1, "Missing received timestamp (%s)" % str(recv_ts))
248 if start_ts is not None:
249 if recv_ts is not None:
250 d1 = start_ts[0] - recv_ts[0] + (start_ts[1] - recv_ts[1]) / 1000000.0
251 delta = " (delta %.6fs)" % d1
254 format_msg(1, "Processing start: %s%s" %
255 (FormatTimestamp(start_ts), delta))
257 format_msg(1, "Processing start: unknown (%s)" % str(start_ts))
259 if end_ts is not None:
260 if start_ts is not None:
261 d2 = end_ts[0] - start_ts[0] + (end_ts[1] - start_ts[1]) / 1000000.0
262 delta = " (delta %.6fs)" % d2
265 format_msg(1, "Processing end: %s%s" %
266 (FormatTimestamp(end_ts), delta))
268 format_msg(1, "Processing end: unknown (%s)" % str(end_ts))
270 if end_ts is not None and recv_ts is not None:
271 d3 = end_ts[0] - recv_ts[0] + (end_ts[1] - recv_ts[1]) / 1000000.0
272 format_msg(1, "Total processing time: %.6f seconds" % d3)
274 format_msg(1, "Total processing time: N/A")
275 format_msg(1, "Opcodes:")
276 for (opcode, result, status, log, s_ts, x_ts, e_ts) in \
277 zip(ops, opresult, opstatus, oplog, opstart, opexec, opend):
278 format_msg(2, "%s" % opcode["OP_ID"])
279 format_msg(3, "Status: %s" % status)
280 if isinstance(s_ts, (tuple, list)):
281 format_msg(3, "Processing start: %s" % FormatTimestamp(s_ts))
283 format_msg(3, "No processing start time")
284 if isinstance(x_ts, (tuple, list)):
285 format_msg(3, "Execution start: %s" % FormatTimestamp(x_ts))
287 format_msg(3, "No execution start time")
288 if isinstance(e_ts, (tuple, list)):
289 format_msg(3, "Processing end: %s" % FormatTimestamp(e_ts))
291 format_msg(3, "No processing end time")
292 format_msg(3, "Input fields:")
293 for key in utils.NiceSort(opcode.keys()):
297 if isinstance(val, (tuple, list)):
298 val = ",".join([str(item) for item in val])
299 format_msg(4, "%s: %s" % (key, val))
301 format_msg(3, "No output data")
302 elif isinstance(result, (tuple, list)):
304 format_msg(3, "Result: empty sequence")
306 format_msg(3, "Result:")
308 format_msg(4, result_helper(elem))
309 elif isinstance(result, dict):
311 format_msg(3, "Result: empty dictionary")
313 for key, val in result.iteritems():
314 format_msg(4, "%s: %s" % (key, result_helper(val)))
316 format_msg(3, "Result: %s" % result)
317 format_msg(3, "Execution log:")
318 for serial, log_ts, log_type, log_msg in log:
319 time_txt = FormatTimestamp(log_ts)
320 encoded = FormatLogMessage(log_type, log_msg)
321 format_msg(4, "%s:%s:%s %s" % (serial, time_txt, log_type, encoded))
325 def WatchJob(opts, args):
326 """Follow a job and print its output as it arrives.
328 @param opts: the command line options selected by the user
330 @param args: Contains the job ID
332 @return: the desired exit code
337 msg = ("Output from job %s follows" % job_id)
339 ToStdout("-" * len(msg))
344 except errors.GenericError, err:
345 (retcode, job_result) = cli.FormatError(err)
346 ToStderr("Job %s failed: %s", job_id, job_result)
353 ListJobs, [ArgJobId()],
354 [NOHDR_OPT, SEP_OPT, FIELDS_OPT],
356 "List the jobs and their status. The available fields are"
357 " (see the man page for details): id, status, op_list,"
358 " op_status, op_result."
360 " list is (in order): %s." % utils.CommaJoin(_LIST_DEF_FIELDS)),
362 ArchiveJobs, [ArgJobId(min=1)], [],
363 "<job-id> [<job-id> ...]", "Archive specified jobs"),
366 [ArgSuggest(min=1, max=1, choices=["1d", "1w", "4w", "all"])],
368 "<age>", "Auto archive jobs older than the given age"),
370 CancelJobs, [ArgJobId(min=1)], [],
371 "<job-id> [<job-id> ...]", "Cancel specified jobs"),
373 ShowJobs, [ArgJobId(min=1)], [],
374 "<job-id> [<job-id> ...]",
375 "Show detailed information about the specified jobs"),
377 WatchJob, [ArgJobId(min=1, max=1)], [],
378 "<job-id>", "Follows a job and prints its output as it arrives"),
382 if __name__ == '__main__':
383 sys.exit(GenericMain(commands))