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