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=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
29 from ganeti.cli import *
30 from ganeti import constants
31 from ganeti import errors
32 from ganeti import utils
33 from ganeti import cli
36 #: default list of fields for L{ListJobs}
37 _LIST_DEF_FIELDS = ["id", "status", "summary"]
39 #: map converting the job status contants to user-visible
42 constants.JOB_STATUS_QUEUED: "queued",
43 constants.JOB_STATUS_WAITING: "waiting",
44 constants.JOB_STATUS_CANCELING: "canceling",
45 constants.JOB_STATUS_RUNNING: "running",
46 constants.JOB_STATUS_CANCELED: "canceled",
47 constants.JOB_STATUS_SUCCESS: "success",
48 constants.JOB_STATUS_ERROR: "error",
52 def ListJobs(opts, args):
55 @param opts: the command line options selected by the user
57 @param args: should be an empty list
59 @return: the desired exit code
62 selected_fields = ParseFields(opts.output, _LIST_DEF_FIELDS)
64 output = GetClient().QueryJobs(args, selected_fields)
65 if not opts.no_headers:
66 # TODO: Implement more fields
72 "opresult": "OpCode_result",
73 "opstatus": "OpCode_status",
74 "oplog": "OpCode_log",
76 "opstart": "OpCode_start",
77 "opexec": "OpCode_exec",
78 "opend": "OpCode_end",
79 "oppriority": "OpCode_prio",
82 "received_ts": "Received",
87 numfields = ["priority"]
89 # change raw values to nicer strings
90 for row_id, row in enumerate(output):
92 ToStderr("No such job: %s" % args[row_id])
95 for idx, field in enumerate(selected_fields):
98 if val in _USER_JOB_STATUS:
99 val = _USER_JOB_STATUS[val]
101 raise errors.ProgrammerError("Unknown job status code '%s'" % val)
102 elif field == "summary":
104 elif field in ("start_ts", "end_ts", "received_ts"):
105 val = FormatTimestamp(val)
106 elif field in ("opstart", "opexec", "opend"):
107 val = [FormatTimestamp(entry) for entry in val]
111 data = GenerateTable(separator=opts.separator, headers=headers,
112 fields=selected_fields, data=output,
120 def ArchiveJobs(opts, args):
123 @param opts: the command line options selected by the user
125 @param args: should contain the job IDs to be archived
127 @return: the desired exit code
134 if not client.ArchiveJob(job_id):
135 ToStderr("Failed to archive job with ID '%s'", job_id)
141 def AutoArchiveJobs(opts, args):
142 """Archive jobs based on age.
144 This will archive jobs based on their age, or all jobs if a 'all' is
147 @param opts: the command line options selected by the user
149 @param args: should contain only one element, the age as a time spec
150 that can be parsed by L{ganeti.cli.ParseTimespec} or the
151 keyword I{all}, which will cause all jobs to be archived
153 @return: the desired exit code
163 age = ParseTimespec(age)
165 (archived_count, jobs_left) = client.AutoArchiveJobs(age)
166 ToStdout("Archived %s jobs, %s unchecked left", archived_count, jobs_left)
171 def CancelJobs(opts, args):
172 """Cancel not-yet-started jobs.
174 @param opts: the command line options selected by the user
176 @param args: should contain the job IDs to be cancelled
178 @return: the desired exit code
182 result = constants.EXIT_SUCCESS
185 (success, msg) = client.CancelJob(job_id)
188 result = constants.EXIT_FAILURE
195 def ShowJobs(opts, args):
196 """Show detailed information about jobs.
198 @param opts: the command line options selected by the user
200 @param args: should contain the job IDs to be queried
202 @return: the desired exit code
205 def format_msg(level, text):
206 """Display the text indented."""
207 ToStdout("%s%s", " " * level, text)
209 def result_helper(value):
210 """Format a result field in a nice way."""
211 if isinstance(value, (tuple, list)):
212 return "[%s]" % utils.CommaJoin(value)
217 "id", "status", "ops", "opresult", "opstatus", "oplog",
218 "opstart", "opexec", "opend", "received_ts", "start_ts", "end_ts",
221 result = GetClient().QueryJobs(args, selected_fields)
225 for idx, entry in enumerate(result):
233 format_msg(0, "Job ID %s not found" % args[idx])
235 # this should not happen, when we don't pass args it will be a
237 format_msg(0, "Job ID requested as argument %s not found" % (idx + 1))
240 (job_id, status, ops, opresult, opstatus, oplog,
241 opstart, opexec, opend, recv_ts, start_ts, end_ts) = entry
242 format_msg(0, "Job ID: %s" % job_id)
243 if status in _USER_JOB_STATUS:
244 status = _USER_JOB_STATUS[status]
246 raise errors.ProgrammerError("Unknown job status code '%s'" % status)
248 format_msg(1, "Status: %s" % status)
250 if recv_ts is not None:
251 format_msg(1, "Received: %s" % FormatTimestamp(recv_ts))
253 format_msg(1, "Missing received timestamp (%s)" % str(recv_ts))
255 if start_ts is not None:
256 if recv_ts is not None:
257 d1 = start_ts[0] - recv_ts[0] + (start_ts[1] - recv_ts[1]) / 1000000.0
258 delta = " (delta %.6fs)" % d1
261 format_msg(1, "Processing start: %s%s" %
262 (FormatTimestamp(start_ts), delta))
264 format_msg(1, "Processing start: unknown (%s)" % str(start_ts))
266 if end_ts is not None:
267 if start_ts is not None:
268 d2 = end_ts[0] - start_ts[0] + (end_ts[1] - start_ts[1]) / 1000000.0
269 delta = " (delta %.6fs)" % d2
272 format_msg(1, "Processing end: %s%s" %
273 (FormatTimestamp(end_ts), delta))
275 format_msg(1, "Processing end: unknown (%s)" % str(end_ts))
277 if end_ts is not None and recv_ts is not None:
278 d3 = end_ts[0] - recv_ts[0] + (end_ts[1] - recv_ts[1]) / 1000000.0
279 format_msg(1, "Total processing time: %.6f seconds" % d3)
281 format_msg(1, "Total processing time: N/A")
282 format_msg(1, "Opcodes:")
283 for (opcode, result, status, log, s_ts, x_ts, e_ts) in \
284 zip(ops, opresult, opstatus, oplog, opstart, opexec, opend):
285 format_msg(2, "%s" % opcode["OP_ID"])
286 format_msg(3, "Status: %s" % status)
287 if isinstance(s_ts, (tuple, list)):
288 format_msg(3, "Processing start: %s" % FormatTimestamp(s_ts))
290 format_msg(3, "No processing start time")
291 if isinstance(x_ts, (tuple, list)):
292 format_msg(3, "Execution start: %s" % FormatTimestamp(x_ts))
294 format_msg(3, "No execution start time")
295 if isinstance(e_ts, (tuple, list)):
296 format_msg(3, "Processing end: %s" % FormatTimestamp(e_ts))
298 format_msg(3, "No processing end time")
299 format_msg(3, "Input fields:")
300 for key in utils.NiceSort(opcode.keys()):
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 format_msg(3, "Result:")
321 for key, val in result.iteritems():
322 format_msg(4, "%s: %s" % (key, result_helper(val)))
324 format_msg(3, "Result: %s" % result)
325 format_msg(3, "Execution log:")
326 for serial, log_ts, log_type, log_msg in log:
327 time_txt = FormatTimestamp(log_ts)
328 encoded = FormatLogMessage(log_type, log_msg)
329 format_msg(4, "%s:%s:%s %s" % (serial, time_txt, log_type, encoded))
333 def WatchJob(opts, args):
334 """Follow a job and print its output as it arrives.
336 @param opts: the command line options selected by the user
338 @param args: Contains the job ID
340 @return: the desired exit code
345 msg = ("Output from job %s follows" % job_id)
347 ToStdout("-" * len(msg))
352 except errors.GenericError, err:
353 (retcode, job_result) = cli.FormatError(err)
354 ToStderr("Job %s failed: %s", job_id, job_result)
361 ListJobs, [ArgJobId()],
362 [NOHDR_OPT, SEP_OPT, FIELDS_OPT],
364 "List the jobs and their status. The available fields are"
365 " (see the man page for details): id, status, op_list,"
366 " op_status, op_result."
368 " list is (in order): %s." % utils.CommaJoin(_LIST_DEF_FIELDS)),
370 ArchiveJobs, [ArgJobId(min=1)], [],
371 "<job-id> [<job-id> ...]", "Archive specified jobs"),
374 [ArgSuggest(min=1, max=1, choices=["1d", "1w", "4w", "all"])],
376 "<age>", "Auto archive jobs older than the given age"),
378 CancelJobs, [ArgJobId(min=1)], [],
379 "<job-id> [<job-id> ...]", "Cancel specified jobs"),
381 ShowJobs, [ArgJobId(min=1)], [],
382 "<job-id> [<job-id> ...]",
383 "Show detailed information about the specified jobs"),
385 WatchJob, [ArgJobId(min=1, max=1)], [],
386 "<job-id>", "Follows a job and prints its output as it arrives"),
390 #: dictionary with aliases for commands
397 return GenericMain(commands, aliases=aliases)