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 if opts.output is None:
65 selected_fields = _LIST_DEF_FIELDS
66 elif opts.output.startswith("+"):
67 selected_fields = _LIST_DEF_FIELDS + opts.output[1:].split(",")
69 selected_fields = opts.output.split(",")
71 output = GetClient().QueryJobs(args, selected_fields)
72 if not opts.no_headers:
73 # TODO: Implement more fields
78 "opresult": "OpCode_result",
79 "opstatus": "OpCode_status",
80 "oplog": "OpCode_log",
82 "opstart": "OpCode_start",
83 "opexec": "OpCode_exec",
84 "opend": "OpCode_end",
87 "received_ts": "Received",
88 "lock_status": "LockStatus",
93 # change raw values to nicer strings
94 for row_id, row in enumerate(output):
96 ToStderr("No such job: %s" % args[row_id])
99 for idx, field in enumerate(selected_fields):
101 if field == "status":
102 if val in _USER_JOB_STATUS:
103 val = _USER_JOB_STATUS[val]
105 raise errors.ProgrammerError("Unknown job status code '%s'" % val)
106 elif field == "summary":
108 elif field in ("start_ts", "end_ts", "received_ts"):
109 val = FormatTimestamp(val)
110 elif field in ("opstart", "opexec", "opend"):
111 val = [FormatTimestamp(entry) for entry in val]
112 elif field == "lock_status" and not val:
117 data = GenerateTable(separator=opts.separator, headers=headers,
118 fields=selected_fields, data=output)
125 def ArchiveJobs(opts, args):
128 @param opts: the command line options selected by the user
130 @param args: should contain the job IDs to be archived
132 @return: the desired exit code
139 if not client.ArchiveJob(job_id):
140 ToStderr("Failed to archive job with ID '%s'", job_id)
146 def AutoArchiveJobs(opts, args):
147 """Archive jobs based on age.
149 This will archive jobs based on their age, or all jobs if a 'all' is
152 @param opts: the command line options selected by the user
154 @param args: should contain only one element, the age as a time spec
155 that can be parsed by L{ganeti.cli.ParseTimespec} or the
156 keyword I{all}, which will cause all jobs to be archived
158 @return: the desired exit code
168 age = ParseTimespec(age)
170 (archived_count, jobs_left) = client.AutoArchiveJobs(age)
171 ToStdout("Archived %s jobs, %s unchecked left", archived_count, jobs_left)
176 def CancelJobs(opts, args):
177 """Cancel not-yet-started jobs.
179 @param opts: the command line options selected by the user
181 @param args: should contain the job IDs to be cancelled
183 @return: the desired exit code
189 (_, msg) = client.CancelJob(job_id)
192 # TODO: Different exit value if not all jobs were canceled?
196 def ShowJobs(opts, args):
197 """Show detailed information about jobs.
199 @param opts: the command line options selected by the user
201 @param args: should contain the job IDs to be queried
203 @return: the desired exit code
206 def format_msg(level, text):
207 """Display the text indented."""
208 ToStdout("%s%s", " " * level, text)
210 def result_helper(value):
211 """Format a result field in a nice way."""
212 if isinstance(value, (tuple, list)):
213 return "[%s]" % utils.CommaJoin(value)
218 "id", "status", "ops", "opresult", "opstatus", "oplog",
219 "opstart", "opexec", "opend", "received_ts", "start_ts", "end_ts",
222 result = GetClient().QueryJobs(args, selected_fields)
226 for idx, entry in enumerate(result):
234 format_msg(0, "Job ID %s not found" % args[idx])
236 # this should not happen, when we don't pass args it will be a
238 format_msg(0, "Job ID requested as argument %s not found" % (idx + 1))
241 (job_id, status, ops, opresult, opstatus, oplog,
242 opstart, opexec, opend, recv_ts, start_ts, end_ts) = entry
243 format_msg(0, "Job ID: %s" % job_id)
244 if status in _USER_JOB_STATUS:
245 status = _USER_JOB_STATUS[status]
247 raise errors.ProgrammerError("Unknown job status code '%s'" % status)
249 format_msg(1, "Status: %s" % status)
251 if recv_ts is not None:
252 format_msg(1, "Received: %s" % FormatTimestamp(recv_ts))
254 format_msg(1, "Missing received timestamp (%s)" % str(recv_ts))
256 if start_ts is not None:
257 if recv_ts is not None:
258 d1 = start_ts[0] - recv_ts[0] + (start_ts[1] - recv_ts[1]) / 1000000.0
259 delta = " (delta %.6fs)" % d1
262 format_msg(1, "Processing start: %s%s" %
263 (FormatTimestamp(start_ts), delta))
265 format_msg(1, "Processing start: unknown (%s)" % str(start_ts))
267 if end_ts is not None:
268 if start_ts is not None:
269 d2 = end_ts[0] - start_ts[0] + (end_ts[1] - start_ts[1]) / 1000000.0
270 delta = " (delta %.6fs)" % d2
273 format_msg(1, "Processing end: %s%s" %
274 (FormatTimestamp(end_ts), delta))
276 format_msg(1, "Processing end: unknown (%s)" % str(end_ts))
278 if end_ts is not None and recv_ts is not None:
279 d3 = end_ts[0] - recv_ts[0] + (end_ts[1] - recv_ts[1]) / 1000000.0
280 format_msg(1, "Total processing time: %.6f seconds" % d3)
282 format_msg(1, "Total processing time: N/A")
283 format_msg(1, "Opcodes:")
284 for (opcode, result, status, log, s_ts, x_ts, e_ts) in \
285 zip(ops, opresult, opstatus, oplog, opstart, opexec, opend):
286 format_msg(2, "%s" % opcode["OP_ID"])
287 format_msg(3, "Status: %s" % status)
288 if isinstance(s_ts, (tuple, list)):
289 format_msg(3, "Processing start: %s" % FormatTimestamp(s_ts))
291 format_msg(3, "No processing start time")
292 if isinstance(x_ts, (tuple, list)):
293 format_msg(3, "Execution start: %s" % FormatTimestamp(x_ts))
295 format_msg(3, "No execution start time")
296 if isinstance(e_ts, (tuple, list)):
297 format_msg(3, "Processing end: %s" % FormatTimestamp(e_ts))
299 format_msg(3, "No processing end time")
300 format_msg(3, "Input fields:")
301 for key, val in opcode.iteritems():
304 if isinstance(val, (tuple, list)):
305 val = ",".join([str(item) for item in val])
306 format_msg(4, "%s: %s" % (key, val))
308 format_msg(3, "No output data")
309 elif isinstance(result, (tuple, list)):
311 format_msg(3, "Result: empty sequence")
313 format_msg(3, "Result:")
315 format_msg(4, result_helper(elem))
316 elif isinstance(result, dict):
318 format_msg(3, "Result: empty dictionary")
320 for key, val in result.iteritems():
321 format_msg(4, "%s: %s" % (key, result_helper(val)))
323 format_msg(3, "Result: %s" % result)
324 format_msg(3, "Execution log:")
325 for serial, log_ts, log_type, log_msg in log:
326 time_txt = FormatTimestamp(log_ts)
327 encoded = FormatLogMessage(log_type, log_msg)
328 format_msg(4, "%s:%s:%s %s" % (serial, time_txt, log_type, encoded))
332 def WatchJob(opts, args):
333 """Follow a job and print its output as it arrives.
335 @param opts: the command line options selected by the user
337 @param args: Contains the job ID
339 @return: the desired exit code
344 msg = ("Output from job %s follows" % job_id)
346 ToStdout("-" * len(msg))
351 except errors.GenericError, err:
352 (retcode, job_result) = cli.FormatError(err)
353 ToStderr("Job %s failed: %s", job_id, job_result)
360 ListJobs, [ArgJobId()],
361 [NOHDR_OPT, SEP_OPT, FIELDS_OPT],
363 "List the jobs and their status. The available fields are"
364 " (see the man page for details): id, status, op_list,"
365 " op_status, op_result."
367 " list is (in order): %s." % utils.CommaJoin(_LIST_DEF_FIELDS)),
369 ArchiveJobs, [ArgJobId(min=1)], [],
370 "<job-id> [<job-id> ...]", "Archive specified jobs"),
373 [ArgSuggest(min=1, max=1, choices=["1d", "1w", "4w", "all"])],
375 "<age>", "Auto archive jobs older than the given age"),
377 CancelJobs, [ArgJobId(min=1)], [],
378 "<job-id> [<job-id> ...]", "Cancel specified jobs"),
380 ShowJobs, [ArgJobId(min=1)], [],
381 "<job-id> [<job-id> ...]",
382 "Show detailed information about the specified jobs"),
384 WatchJob, [ArgJobId(min=1, max=1)], [],
385 "<job-id>", "Follows a job and prints its output as it arrives"),
389 if __name__ == '__main__':
390 sys.exit(GenericMain(commands))