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 "opend": "OpCode_end",
86 "received_ts": "Received",
87 "lock_status": "LockStatus",
92 # change raw values to nicer strings
93 for row_id, row in enumerate(output):
95 ToStderr("No such job: %s" % args[row_id])
98 for idx, field in enumerate(selected_fields):
100 if field == "status":
101 if val in _USER_JOB_STATUS:
102 val = _USER_JOB_STATUS[val]
104 raise errors.ProgrammerError("Unknown job status code '%s'" % val)
105 elif field == "summary":
107 elif field in ("start_ts", "end_ts", "received_ts"):
108 val = FormatTimestamp(val)
109 elif field in ("opstart", "opend"):
110 val = [FormatTimestamp(entry) for entry in val]
111 elif field == "lock_status" and not val:
116 data = GenerateTable(separator=opts.separator, headers=headers,
117 fields=selected_fields, data=output)
124 def ArchiveJobs(opts, args):
127 @param opts: the command line options selected by the user
129 @param args: should contain the job IDs to be archived
131 @return: the desired exit code
137 client.ArchiveJob(job_id)
142 def AutoArchiveJobs(opts, args):
143 """Archive jobs based on age.
145 This will archive jobs based on their age, or all jobs if a 'all' is
148 @param opts: the command line options selected by the user
150 @param args: should contain only one element, the age as a time spec
151 that can be parsed by L{ganeti.cli.ParseTimespec} or the
152 keyword I{all}, which will cause all jobs to be archived
154 @return: the desired exit code
164 age = ParseTimespec(age)
166 (archived_count, jobs_left) = client.AutoArchiveJobs(age)
167 ToStdout("Archived %s jobs, %s unchecked left", archived_count, jobs_left)
172 def CancelJobs(opts, args):
173 """Cancel not-yet-started jobs.
175 @param opts: the command line options selected by the user
177 @param args: should contain the job IDs to be cancelled
179 @return: the desired exit code
185 (_, msg) = client.CancelJob(job_id)
188 # TODO: Different exit value if not all jobs were canceled?
192 def ShowJobs(opts, args):
193 """Show detailed information about jobs.
195 @param opts: the command line options selected by the user
197 @param args: should contain the job IDs to be queried
199 @return: the desired exit code
202 def format(level, text):
203 """Display the text indented."""
204 ToStdout("%s%s", " " * level, text)
206 def result_helper(value):
207 """Format a result field in a nice way."""
208 if isinstance(value, (tuple, list)):
209 return "[%s]" % utils.CommaJoin(value)
214 "id", "status", "ops", "opresult", "opstatus", "oplog",
215 "opstart", "opend", "received_ts", "start_ts", "end_ts",
218 result = GetClient().QueryJobs(args, selected_fields)
222 for idx, entry in enumerate(result):
230 format(0, "Job ID %s not found" % args[idx])
232 # this should not happen, when we don't pass args it will be a
234 format(0, "Job ID requested as argument %s not found" % (idx + 1))
237 (job_id, status, ops, opresult, opstatus, oplog,
238 opstart, opend, recv_ts, start_ts, end_ts) = entry
239 format(0, "Job ID: %s" % job_id)
240 if status in _USER_JOB_STATUS:
241 status = _USER_JOB_STATUS[status]
243 raise errors.ProgrammerError("Unknown job status code '%s'" % status)
245 format(1, "Status: %s" % status)
247 if recv_ts is not None:
248 format(1, "Received: %s" % FormatTimestamp(recv_ts))
250 format(1, "Missing received timestamp (%s)" % str(recv_ts))
252 if start_ts is not None:
253 if recv_ts is not None:
254 d1 = start_ts[0] - recv_ts[0] + (start_ts[1] - recv_ts[1]) / 1000000.0
255 delta = " (delta %.6fs)" % d1
258 format(1, "Processing start: %s%s" % (FormatTimestamp(start_ts), delta))
260 format(1, "Processing start: unknown (%s)" % str(start_ts))
262 if end_ts is not None:
263 if start_ts is not None:
264 d2 = end_ts[0] - start_ts[0] + (end_ts[1] - start_ts[1]) / 1000000.0
265 delta = " (delta %.6fs)" % d2
268 format(1, "Processing end: %s%s" % (FormatTimestamp(end_ts), delta))
270 format(1, "Processing end: unknown (%s)" % str(end_ts))
272 if end_ts is not None and recv_ts is not None:
273 d3 = end_ts[0] - recv_ts[0] + (end_ts[1] - recv_ts[1]) / 1000000.0
274 format(1, "Total processing time: %.6f seconds" % d3)
276 format(1, "Total processing time: N/A")
277 format(1, "Opcodes:")
278 for (opcode, result, status, log, s_ts, e_ts) in \
279 zip(ops, opresult, opstatus, oplog, opstart, opend):
280 format(2, "%s" % opcode["OP_ID"])
281 format(3, "Status: %s" % status)
282 if isinstance(s_ts, (tuple, list)):
283 format(3, "Processing start: %s" % FormatTimestamp(s_ts))
285 format(3, "No processing start time")
286 if isinstance(e_ts, (tuple, list)):
287 format(3, "Processing end: %s" % FormatTimestamp(e_ts))
289 format(3, "No processing end time")
290 format(3, "Input fields:")
291 for key, val in opcode.iteritems():
294 if isinstance(val, (tuple, list)):
295 val = ",".join([str(item) for item in val])
296 format(4, "%s: %s" % (key, val))
298 format(3, "No output data")
299 elif isinstance(result, (tuple, list)):
301 format(3, "Result: empty sequence")
305 format(4, result_helper(elem))
306 elif isinstance(result, dict):
308 format(3, "Result: empty dictionary")
310 for key, val in result.iteritems():
311 format(4, "%s: %s" % (key, result_helper(val)))
313 format(3, "Result: %s" % result)
314 format(3, "Execution log:")
315 for serial, log_ts, log_type, log_msg in log:
316 time_txt = FormatTimestamp(log_ts)
317 encoded = utils.SafeEncode(log_msg)
318 format(4, "%s:%s:%s %s" % (serial, time_txt, log_type, encoded))
322 def WatchJob(opts, args):
323 """Follow a job and print its output as it arrives.
325 @param opts: the command line options selected by the user
327 @param args: Contains the job ID
329 @return: the desired exit code
334 msg = ("Output from job %s follows" % job_id)
336 ToStdout("-" * len(msg))
341 except errors.GenericError, err:
342 (retcode, job_result) = cli.FormatError(err)
343 ToStderr("Job %s failed: %s", job_id, job_result)
350 ListJobs, [ArgJobId()],
351 [NOHDR_OPT, SEP_OPT, FIELDS_OPT],
353 "List the jobs and their status. The available fields are"
354 " (see the man page for details): id, status, op_list,"
355 " op_status, op_result."
357 " list is (in order): %s." % utils.CommaJoin(_LIST_DEF_FIELDS)),
359 ArchiveJobs, [ArgJobId(min=1)], [],
360 "<job-id> [<job-id> ...]", "Archive specified jobs"),
363 [ArgSuggest(min=1, max=1, choices=["1d", "1w", "4w"])],
365 "<age>", "Auto archive jobs older than the given age"),
367 CancelJobs, [ArgJobId(min=1)], [],
368 "<job-id> [<job-id> ...]", "Cancel specified jobs"),
370 ShowJobs, [ArgJobId(min=1)], [],
371 "<job-id> [<job-id> ...]",
372 "Show detailed information about the specified jobs"),
374 WatchJob, [ArgJobId(min=1, max=1)], [],
375 "<job-id>", "Follows a job and prints its output as it arrives"),
379 if __name__ == '__main__':
380 sys.exit(GenericMain(commands))