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
138 client.ArchiveJob(job_id)
143 def AutoArchiveJobs(opts, args):
144 """Archive jobs based on age.
146 This will archive jobs based on their age, or all jobs if a 'all' is
149 @param opts: the command line options selected by the user
151 @param args: should contain only one element, the age as a time spec
152 that can be parsed by L{ganeti.cli.ParseTimespec} or the
153 keyword I{all}, which will cause all jobs to be archived
155 @return: the desired exit code
165 age = ParseTimespec(age)
167 (archived_count, jobs_left) = client.AutoArchiveJobs(age)
168 ToStdout("Archived %s jobs, %s unchecked left", archived_count, jobs_left)
173 def CancelJobs(opts, args):
174 """Cancel not-yet-started jobs.
176 @param opts: the command line options selected by the user
178 @param args: should contain the job IDs to be cancelled
180 @return: the desired exit code
186 (_, msg) = client.CancelJob(job_id)
189 # TODO: Different exit value if not all jobs were canceled?
193 def ShowJobs(opts, args):
194 """Show detailed information about jobs.
196 @param opts: the command line options selected by the user
198 @param args: should contain the job IDs to be queried
200 @return: the desired exit code
203 def format(level, text):
204 """Display the text indented."""
205 ToStdout("%s%s", " " * level, text)
207 def result_helper(value):
208 """Format a result field in a nice way."""
209 if isinstance(value, (tuple, list)):
210 return "[%s]" % utils.CommaJoin(value)
215 "id", "status", "ops", "opresult", "opstatus", "oplog",
216 "opstart", "opexec", "opend", "received_ts", "start_ts", "end_ts",
219 result = GetClient().QueryJobs(args, selected_fields)
223 for idx, entry in enumerate(result):
231 format(0, "Job ID %s not found" % args[idx])
233 # this should not happen, when we don't pass args it will be a
235 format(0, "Job ID requested as argument %s not found" % (idx + 1))
238 (job_id, status, ops, opresult, opstatus, oplog,
239 opstart, opexec, opend, recv_ts, start_ts, end_ts) = entry
240 format(0, "Job ID: %s" % job_id)
241 if status in _USER_JOB_STATUS:
242 status = _USER_JOB_STATUS[status]
244 raise errors.ProgrammerError("Unknown job status code '%s'" % status)
246 format(1, "Status: %s" % status)
248 if recv_ts is not None:
249 format(1, "Received: %s" % FormatTimestamp(recv_ts))
251 format(1, "Missing received timestamp (%s)" % str(recv_ts))
253 if start_ts is not None:
254 if recv_ts is not None:
255 d1 = start_ts[0] - recv_ts[0] + (start_ts[1] - recv_ts[1]) / 1000000.0
256 delta = " (delta %.6fs)" % d1
259 format(1, "Processing start: %s%s" % (FormatTimestamp(start_ts), delta))
261 format(1, "Processing start: unknown (%s)" % str(start_ts))
263 if end_ts is not None:
264 if start_ts is not None:
265 d2 = end_ts[0] - start_ts[0] + (end_ts[1] - start_ts[1]) / 1000000.0
266 delta = " (delta %.6fs)" % d2
269 format(1, "Processing end: %s%s" % (FormatTimestamp(end_ts), delta))
271 format(1, "Processing end: unknown (%s)" % str(end_ts))
273 if end_ts is not None and recv_ts is not None:
274 d3 = end_ts[0] - recv_ts[0] + (end_ts[1] - recv_ts[1]) / 1000000.0
275 format(1, "Total processing time: %.6f seconds" % d3)
277 format(1, "Total processing time: N/A")
278 format(1, "Opcodes:")
279 for (opcode, result, status, log, s_ts, x_ts, e_ts) in \
280 zip(ops, opresult, opstatus, oplog, opstart, opexec, opend):
281 format(2, "%s" % opcode["OP_ID"])
282 format(3, "Status: %s" % status)
283 if isinstance(s_ts, (tuple, list)):
284 format(3, "Processing start: %s" % FormatTimestamp(s_ts))
286 format(3, "No processing start time")
287 if isinstance(x_ts, (tuple, list)):
288 format(3, "Execution start: %s" % FormatTimestamp(x_ts))
290 format(3, "No execution start time")
291 if isinstance(e_ts, (tuple, list)):
292 format(3, "Processing end: %s" % FormatTimestamp(e_ts))
294 format(3, "No processing end time")
295 format(3, "Input fields:")
296 for key, val in opcode.iteritems():
299 if isinstance(val, (tuple, list)):
300 val = ",".join([str(item) for item in val])
301 format(4, "%s: %s" % (key, val))
303 format(3, "No output data")
304 elif isinstance(result, (tuple, list)):
306 format(3, "Result: empty sequence")
310 format(4, result_helper(elem))
311 elif isinstance(result, dict):
313 format(3, "Result: empty dictionary")
315 for key, val in result.iteritems():
316 format(4, "%s: %s" % (key, result_helper(val)))
318 format(3, "Result: %s" % result)
319 format(3, "Execution log:")
320 for serial, log_ts, log_type, log_msg in log:
321 time_txt = FormatTimestamp(log_ts)
322 encoded = utils.SafeEncode(log_msg)
323 format(4, "%s:%s:%s %s" % (serial, time_txt, log_type, encoded))
327 def WatchJob(opts, args):
328 """Follow a job and print its output as it arrives.
330 @param opts: the command line options selected by the user
332 @param args: Contains the job ID
334 @return: the desired exit code
339 msg = ("Output from job %s follows" % job_id)
341 ToStdout("-" * len(msg))
346 except errors.GenericError, err:
347 (retcode, job_result) = cli.FormatError(err)
348 ToStderr("Job %s failed: %s", job_id, job_result)
355 ListJobs, [ArgJobId()],
356 [NOHDR_OPT, SEP_OPT, FIELDS_OPT],
358 "List the jobs and their status. The available fields are"
359 " (see the man page for details): id, status, op_list,"
360 " op_status, op_result."
362 " list is (in order): %s." % utils.CommaJoin(_LIST_DEF_FIELDS)),
364 ArchiveJobs, [ArgJobId(min=1)], [],
365 "<job-id> [<job-id> ...]", "Archive specified jobs"),
368 [ArgSuggest(min=1, max=1, choices=["1d", "1w", "4w", "all"])],
370 "<age>", "Auto archive jobs older than the given age"),
372 CancelJobs, [ArgJobId(min=1)], [],
373 "<job-id> [<job-id> ...]", "Cancel specified jobs"),
375 ShowJobs, [ArgJobId(min=1)], [],
376 "<job-id> [<job-id> ...]",
377 "Show detailed information about the specified jobs"),
379 WatchJob, [ArgJobId(min=1, max=1)], [],
380 "<job-id>", "Follows a job and prints its output as it arrives"),
384 if __name__ == '__main__':
385 sys.exit(GenericMain(commands))