root / lib / client / gnt_job.py @ 43d51ef2
History | View | Annotate | Download (13 kB)
1 |
#
|
---|---|
2 |
#
|
3 |
|
4 |
# Copyright (C) 2006, 2007, 2012 Google Inc.
|
5 |
#
|
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.
|
10 |
#
|
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.
|
15 |
#
|
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
|
19 |
# 02110-1301, USA.
|
20 |
|
21 |
"""Job related commands"""
|
22 |
|
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
|
28 |
|
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 |
34 |
from ganeti import qlang |
35 |
|
36 |
|
37 |
#: default list of fields for L{ListJobs}
|
38 |
_LIST_DEF_FIELDS = ["id", "status", "summary"] |
39 |
|
40 |
#: map converting the job status contants to user-visible
|
41 |
#: names
|
42 |
_USER_JOB_STATUS = { |
43 |
constants.JOB_STATUS_QUEUED: "queued",
|
44 |
constants.JOB_STATUS_WAITING: "waiting",
|
45 |
constants.JOB_STATUS_CANCELING: "canceling",
|
46 |
constants.JOB_STATUS_RUNNING: "running",
|
47 |
constants.JOB_STATUS_CANCELED: "canceled",
|
48 |
constants.JOB_STATUS_SUCCESS: "success",
|
49 |
constants.JOB_STATUS_ERROR: "error",
|
50 |
} |
51 |
|
52 |
|
53 |
def _FormatStatus(value): |
54 |
"""Formats a job status.
|
55 |
|
56 |
"""
|
57 |
try:
|
58 |
return _USER_JOB_STATUS[value]
|
59 |
except KeyError: |
60 |
raise errors.ProgrammerError("Unknown job status code '%s'" % value) |
61 |
|
62 |
|
63 |
def _ParseJobIds(args): |
64 |
"""Parses a list of string job IDs into integers.
|
65 |
|
66 |
@param args: list of strings
|
67 |
@return: list of integers
|
68 |
@raise OpPrereqError: in case of invalid values
|
69 |
|
70 |
"""
|
71 |
try:
|
72 |
return [int(a) for a in args] |
73 |
except (ValueError, TypeError), err: |
74 |
raise errors.OpPrereqError("Invalid job ID passed: %s" % err, |
75 |
errors.ECODE_INVAL) |
76 |
|
77 |
|
78 |
def ListJobs(opts, args): |
79 |
"""List the jobs
|
80 |
|
81 |
@param opts: the command line options selected by the user
|
82 |
@type args: list
|
83 |
@param args: should be an empty list
|
84 |
@rtype: int
|
85 |
@return: the desired exit code
|
86 |
|
87 |
"""
|
88 |
selected_fields = ParseFields(opts.output, _LIST_DEF_FIELDS) |
89 |
|
90 |
if opts.archived and "archived" not in selected_fields: |
91 |
selected_fields.append("archived")
|
92 |
|
93 |
fmtoverride = { |
94 |
"status": (_FormatStatus, False), |
95 |
"summary": (lambda value: ",".join(str(item) for item in value), False), |
96 |
} |
97 |
fmtoverride.update(dict.fromkeys(["opstart", "opexec", "opend"], |
98 |
(lambda value: map(FormatTimestamp, value), |
99 |
None)))
|
100 |
|
101 |
qfilter = qlang.MakeSimpleFilter("status", opts.status_filter)
|
102 |
|
103 |
return GenericList(constants.QR_JOB, selected_fields, args, None, |
104 |
opts.separator, not opts.no_headers,
|
105 |
format_override=fmtoverride, verbose=opts.verbose, |
106 |
force_filter=opts.force_filter, namefield="id",
|
107 |
qfilter=qfilter, isnumeric=True)
|
108 |
|
109 |
|
110 |
def ListJobFields(opts, args): |
111 |
"""List job fields.
|
112 |
|
113 |
@param opts: the command line options selected by the user
|
114 |
@type args: list
|
115 |
@param args: fields to list, or empty for all
|
116 |
@rtype: int
|
117 |
@return: the desired exit code
|
118 |
|
119 |
"""
|
120 |
return GenericListFields(constants.QR_JOB, args, opts.separator,
|
121 |
not opts.no_headers)
|
122 |
|
123 |
|
124 |
def ArchiveJobs(opts, args): |
125 |
"""Archive jobs.
|
126 |
|
127 |
@param opts: the command line options selected by the user
|
128 |
@type args: list
|
129 |
@param args: should contain the job IDs to be archived
|
130 |
@rtype: int
|
131 |
@return: the desired exit code
|
132 |
|
133 |
"""
|
134 |
client = GetClient() |
135 |
|
136 |
rcode = 0
|
137 |
for job_id in args: |
138 |
if not client.ArchiveJob(job_id): |
139 |
ToStderr("Failed to archive job with ID '%s'", job_id)
|
140 |
rcode = 1
|
141 |
|
142 |
return rcode
|
143 |
|
144 |
|
145 |
def AutoArchiveJobs(opts, args): |
146 |
"""Archive jobs based on age.
|
147 |
|
148 |
This will archive jobs based on their age, or all jobs if a 'all' is
|
149 |
passed.
|
150 |
|
151 |
@param opts: the command line options selected by the user
|
152 |
@type args: list
|
153 |
@param args: should contain only one element, the age as a time spec
|
154 |
that can be parsed by L{ganeti.cli.ParseTimespec} or the
|
155 |
keyword I{all}, which will cause all jobs to be archived
|
156 |
@rtype: int
|
157 |
@return: the desired exit code
|
158 |
|
159 |
"""
|
160 |
client = GetClient() |
161 |
|
162 |
age = args[0]
|
163 |
|
164 |
if age == "all": |
165 |
age = -1
|
166 |
else:
|
167 |
age = ParseTimespec(age) |
168 |
|
169 |
(archived_count, jobs_left) = client.AutoArchiveJobs(age) |
170 |
ToStdout("Archived %s jobs, %s unchecked left", archived_count, jobs_left)
|
171 |
|
172 |
return 0 |
173 |
|
174 |
|
175 |
def CancelJobs(opts, args): |
176 |
"""Cancel not-yet-started jobs.
|
177 |
|
178 |
@param opts: the command line options selected by the user
|
179 |
@type args: list
|
180 |
@param args: should contain the job IDs to be cancelled
|
181 |
@rtype: int
|
182 |
@return: the desired exit code
|
183 |
|
184 |
"""
|
185 |
client = GetClient() |
186 |
result = constants.EXIT_SUCCESS |
187 |
|
188 |
for job_id in args: |
189 |
(success, msg) = client.CancelJob(job_id) |
190 |
|
191 |
if not success: |
192 |
result = constants.EXIT_FAILURE |
193 |
|
194 |
ToStdout(msg) |
195 |
|
196 |
return result
|
197 |
|
198 |
|
199 |
def ShowJobs(opts, args): |
200 |
"""Show detailed information about jobs.
|
201 |
|
202 |
@param opts: the command line options selected by the user
|
203 |
@type args: list
|
204 |
@param args: should contain the job IDs to be queried
|
205 |
@rtype: int
|
206 |
@return: the desired exit code
|
207 |
|
208 |
"""
|
209 |
def format_msg(level, text): |
210 |
"""Display the text indented."""
|
211 |
ToStdout("%s%s", " " * level, text) |
212 |
|
213 |
def result_helper(value): |
214 |
"""Format a result field in a nice way."""
|
215 |
if isinstance(value, (tuple, list)): |
216 |
return "[%s]" % utils.CommaJoin(value) |
217 |
else:
|
218 |
return str(value) |
219 |
|
220 |
selected_fields = [ |
221 |
"id", "status", "ops", "opresult", "opstatus", "oplog", |
222 |
"opstart", "opexec", "opend", "received_ts", "start_ts", "end_ts", |
223 |
] |
224 |
|
225 |
qfilter = qlang.MakeSimpleFilter("id", _ParseJobIds(args))
|
226 |
result = GetClient().Query(constants.QR_JOB, selected_fields, qfilter).data |
227 |
|
228 |
first = True
|
229 |
|
230 |
for entry in result: |
231 |
if not first: |
232 |
format_msg(0, "") |
233 |
else:
|
234 |
first = False
|
235 |
|
236 |
((_, job_id), (rs_status, status), (_, ops), (_, opresult), (_, opstatus), |
237 |
(_, oplog), (_, opstart), (_, opexec), (_, opend), (_, recv_ts), |
238 |
(_, start_ts), (_, end_ts)) = entry |
239 |
|
240 |
# Detect non-normal results
|
241 |
if rs_status != constants.RS_NORMAL:
|
242 |
format_msg(0, "Job ID %s not found" % job_id) |
243 |
continue
|
244 |
|
245 |
format_msg(0, "Job ID: %s" % job_id) |
246 |
if status in _USER_JOB_STATUS: |
247 |
status = _USER_JOB_STATUS[status] |
248 |
else:
|
249 |
raise errors.ProgrammerError("Unknown job status code '%s'" % status) |
250 |
|
251 |
format_msg(1, "Status: %s" % status) |
252 |
|
253 |
if recv_ts is not None: |
254 |
format_msg(1, "Received: %s" % FormatTimestamp(recv_ts)) |
255 |
else:
|
256 |
format_msg(1, "Missing received timestamp (%s)" % str(recv_ts)) |
257 |
|
258 |
if start_ts is not None: |
259 |
if recv_ts is not None: |
260 |
d1 = start_ts[0] - recv_ts[0] + (start_ts[1] - recv_ts[1]) / 1000000.0 |
261 |
delta = " (delta %.6fs)" % d1
|
262 |
else:
|
263 |
delta = ""
|
264 |
format_msg(1, "Processing start: %s%s" % |
265 |
(FormatTimestamp(start_ts), delta)) |
266 |
else:
|
267 |
format_msg(1, "Processing start: unknown (%s)" % str(start_ts)) |
268 |
|
269 |
if end_ts is not None: |
270 |
if start_ts is not None: |
271 |
d2 = end_ts[0] - start_ts[0] + (end_ts[1] - start_ts[1]) / 1000000.0 |
272 |
delta = " (delta %.6fs)" % d2
|
273 |
else:
|
274 |
delta = ""
|
275 |
format_msg(1, "Processing end: %s%s" % |
276 |
(FormatTimestamp(end_ts), delta)) |
277 |
else:
|
278 |
format_msg(1, "Processing end: unknown (%s)" % str(end_ts)) |
279 |
|
280 |
if end_ts is not None and recv_ts is not None: |
281 |
d3 = end_ts[0] - recv_ts[0] + (end_ts[1] - recv_ts[1]) / 1000000.0 |
282 |
format_msg(1, "Total processing time: %.6f seconds" % d3) |
283 |
else:
|
284 |
format_msg(1, "Total processing time: N/A") |
285 |
format_msg(1, "Opcodes:") |
286 |
for (opcode, result, status, log, s_ts, x_ts, e_ts) in \ |
287 |
zip(ops, opresult, opstatus, oplog, opstart, opexec, opend):
|
288 |
format_msg(2, "%s" % opcode["OP_ID"]) |
289 |
format_msg(3, "Status: %s" % status) |
290 |
if isinstance(s_ts, (tuple, list)): |
291 |
format_msg(3, "Processing start: %s" % FormatTimestamp(s_ts)) |
292 |
else:
|
293 |
format_msg(3, "No processing start time") |
294 |
if isinstance(x_ts, (tuple, list)): |
295 |
format_msg(3, "Execution start: %s" % FormatTimestamp(x_ts)) |
296 |
else:
|
297 |
format_msg(3, "No execution start time") |
298 |
if isinstance(e_ts, (tuple, list)): |
299 |
format_msg(3, "Processing end: %s" % FormatTimestamp(e_ts)) |
300 |
else:
|
301 |
format_msg(3, "No processing end time") |
302 |
format_msg(3, "Input fields:") |
303 |
for key in utils.NiceSort(opcode.keys()): |
304 |
if key == "OP_ID": |
305 |
continue
|
306 |
val = opcode[key] |
307 |
if isinstance(val, (tuple, list)): |
308 |
val = ",".join([str(item) for item in val]) |
309 |
format_msg(4, "%s: %s" % (key, val)) |
310 |
if result is None: |
311 |
format_msg(3, "No output data") |
312 |
elif isinstance(result, (tuple, list)): |
313 |
if not result: |
314 |
format_msg(3, "Result: empty sequence") |
315 |
else:
|
316 |
format_msg(3, "Result:") |
317 |
for elem in result: |
318 |
format_msg(4, result_helper(elem))
|
319 |
elif isinstance(result, dict): |
320 |
if not result: |
321 |
format_msg(3, "Result: empty dictionary") |
322 |
else:
|
323 |
format_msg(3, "Result:") |
324 |
for key, val in result.iteritems(): |
325 |
format_msg(4, "%s: %s" % (key, result_helper(val))) |
326 |
else:
|
327 |
format_msg(3, "Result: %s" % result) |
328 |
format_msg(3, "Execution log:") |
329 |
for serial, log_ts, log_type, log_msg in log: |
330 |
time_txt = FormatTimestamp(log_ts) |
331 |
encoded = FormatLogMessage(log_type, log_msg) |
332 |
format_msg(4, "%s:%s:%s %s" % (serial, time_txt, log_type, encoded)) |
333 |
return 0 |
334 |
|
335 |
|
336 |
def WatchJob(opts, args): |
337 |
"""Follow a job and print its output as it arrives.
|
338 |
|
339 |
@param opts: the command line options selected by the user
|
340 |
@type args: list
|
341 |
@param args: Contains the job ID
|
342 |
@rtype: int
|
343 |
@return: the desired exit code
|
344 |
|
345 |
"""
|
346 |
job_id = args[0]
|
347 |
|
348 |
msg = ("Output from job %s follows" % job_id)
|
349 |
ToStdout(msg) |
350 |
ToStdout("-" * len(msg)) |
351 |
|
352 |
retcode = 0
|
353 |
try:
|
354 |
cli.PollJob(job_id) |
355 |
except errors.GenericError, err:
|
356 |
(retcode, job_result) = cli.FormatError(err) |
357 |
ToStderr("Job %s failed: %s", job_id, job_result)
|
358 |
|
359 |
return retcode
|
360 |
|
361 |
|
362 |
_PENDING_OPT = \ |
363 |
cli_option("--pending", default=None, |
364 |
action="store_const", dest="status_filter", |
365 |
const=frozenset([
|
366 |
constants.JOB_STATUS_QUEUED, |
367 |
constants.JOB_STATUS_WAITING, |
368 |
]), |
369 |
help="Show only jobs pending execution")
|
370 |
|
371 |
_RUNNING_OPT = \ |
372 |
cli_option("--running", default=None, |
373 |
action="store_const", dest="status_filter", |
374 |
const=frozenset([
|
375 |
constants.JOB_STATUS_RUNNING, |
376 |
]), |
377 |
help="Show jobs currently running only")
|
378 |
|
379 |
_ERROR_OPT = \ |
380 |
cli_option("--error", default=None, |
381 |
action="store_const", dest="status_filter", |
382 |
const=frozenset([
|
383 |
constants.JOB_STATUS_ERROR, |
384 |
]), |
385 |
help="Show failed jobs only")
|
386 |
|
387 |
_FINISHED_OPT = \ |
388 |
cli_option("--finished", default=None, |
389 |
action="store_const", dest="status_filter", |
390 |
const=constants.JOBS_FINALIZED, |
391 |
help="Show finished jobs only")
|
392 |
|
393 |
_ARCHIVED_OPT = \ |
394 |
cli_option("--archived", default=False, |
395 |
action="store_true", dest="archived", |
396 |
help="Include archived jobs in list (slow and expensive)")
|
397 |
|
398 |
|
399 |
commands = { |
400 |
"list": (
|
401 |
ListJobs, [ArgJobId()], |
402 |
[NOHDR_OPT, SEP_OPT, FIELDS_OPT, VERBOSE_OPT, FORCE_FILTER_OPT, |
403 |
_PENDING_OPT, _RUNNING_OPT, _ERROR_OPT, _FINISHED_OPT, _ARCHIVED_OPT], |
404 |
"[job_id ...]",
|
405 |
"Lists the jobs and their status. The available fields can be shown"
|
406 |
" using the \"list-fields\" command (see the man page for details)."
|
407 |
" The default field list is (in order): %s." %
|
408 |
utils.CommaJoin(_LIST_DEF_FIELDS)), |
409 |
"list-fields": (
|
410 |
ListJobFields, [ArgUnknown()], |
411 |
[NOHDR_OPT, SEP_OPT], |
412 |
"[fields...]",
|
413 |
"Lists all available fields for jobs"),
|
414 |
"archive": (
|
415 |
ArchiveJobs, [ArgJobId(min=1)], [],
|
416 |
"<job-id> [<job-id> ...]", "Archive specified jobs"), |
417 |
"autoarchive": (
|
418 |
AutoArchiveJobs, |
419 |
[ArgSuggest(min=1, max=1, choices=["1d", "1w", "4w", "all"])], |
420 |
[], |
421 |
"<age>", "Auto archive jobs older than the given age"), |
422 |
"cancel": (
|
423 |
CancelJobs, [ArgJobId(min=1)], [],
|
424 |
"<job-id> [<job-id> ...]", "Cancel specified jobs"), |
425 |
"info": (
|
426 |
ShowJobs, [ArgJobId(min=1)], [],
|
427 |
"<job-id> [<job-id> ...]",
|
428 |
"Show detailed information about the specified jobs"),
|
429 |
"watch": (
|
430 |
WatchJob, [ArgJobId(min=1, max=1)], [], |
431 |
"<job-id>", "Follows a job and prints its output as it arrives"), |
432 |
} |
433 |
|
434 |
|
435 |
#: dictionary with aliases for commands
|
436 |
aliases = { |
437 |
"show": "info", |
438 |
} |
439 |
|
440 |
|
441 |
def Main(): |
442 |
return GenericMain(commands, aliases=aliases)
|