root / scripts / gnt-job @ 06fef5e0
History | View | Annotate | Download (11.2 kB)
1 |
#!/usr/bin/python |
---|---|
2 |
# |
3 |
|
4 |
# Copyright (C) 2006, 2007 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-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 |
28 |
|
29 |
import sys |
30 |
|
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 |
36 |
|
37 |
|
38 |
#: default list of fields for L{ListJobs} |
39 |
_LIST_DEF_FIELDS = ["id", "status", "summary"] |
40 |
|
41 |
#: map converting the job status contants to user-visible |
42 |
#: names |
43 |
_USER_JOB_STATUS = { |
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", |
51 |
} |
52 |
|
53 |
|
54 |
def ListJobs(opts, args): |
55 |
"""List the jobs |
56 |
|
57 |
@param opts: the command line options selected by the user |
58 |
@type args: list |
59 |
@param args: should be an empty list |
60 |
@rtype: int |
61 |
@return: the desired exit code |
62 |
|
63 |
""" |
64 |
selected_fields = ParseFields(opts.output, _LIST_DEF_FIELDS) |
65 |
|
66 |
output = GetClient().QueryJobs(args, selected_fields) |
67 |
if not opts.no_headers: |
68 |
# TODO: Implement more fields |
69 |
headers = { |
70 |
"id": "ID", |
71 |
"status": "Status", |
72 |
"ops": "OpCodes", |
73 |
"opresult": "OpCode_result", |
74 |
"opstatus": "OpCode_status", |
75 |
"oplog": "OpCode_log", |
76 |
"summary": "Summary", |
77 |
"opstart": "OpCode_start", |
78 |
"opexec": "OpCode_exec", |
79 |
"opend": "OpCode_end", |
80 |
"start_ts": "Start", |
81 |
"end_ts": "End", |
82 |
"received_ts": "Received", |
83 |
} |
84 |
else: |
85 |
headers = None |
86 |
|
87 |
# change raw values to nicer strings |
88 |
for row_id, row in enumerate(output): |
89 |
if row is None: |
90 |
ToStderr("No such job: %s" % args[row_id]) |
91 |
continue |
92 |
|
93 |
for idx, field in enumerate(selected_fields): |
94 |
val = row[idx] |
95 |
if field == "status": |
96 |
if val in _USER_JOB_STATUS: |
97 |
val = _USER_JOB_STATUS[val] |
98 |
else: |
99 |
raise errors.ProgrammerError("Unknown job status code '%s'" % val) |
100 |
elif field == "summary": |
101 |
val = ",".join(val) |
102 |
elif field in ("start_ts", "end_ts", "received_ts"): |
103 |
val = FormatTimestamp(val) |
104 |
elif field in ("opstart", "opexec", "opend"): |
105 |
val = [FormatTimestamp(entry) for entry in val] |
106 |
|
107 |
row[idx] = str(val) |
108 |
|
109 |
data = GenerateTable(separator=opts.separator, headers=headers, |
110 |
fields=selected_fields, data=output) |
111 |
for line in data: |
112 |
ToStdout(line) |
113 |
|
114 |
return 0 |
115 |
|
116 |
|
117 |
def ArchiveJobs(opts, args): |
118 |
"""Archive jobs. |
119 |
|
120 |
@param opts: the command line options selected by the user |
121 |
@type args: list |
122 |
@param args: should contain the job IDs to be archived |
123 |
@rtype: int |
124 |
@return: the desired exit code |
125 |
|
126 |
""" |
127 |
client = GetClient() |
128 |
|
129 |
rcode = 0 |
130 |
for job_id in args: |
131 |
if not client.ArchiveJob(job_id): |
132 |
ToStderr("Failed to archive job with ID '%s'", job_id) |
133 |
rcode = 1 |
134 |
|
135 |
return rcode |
136 |
|
137 |
|
138 |
def AutoArchiveJobs(opts, args): |
139 |
"""Archive jobs based on age. |
140 |
|
141 |
This will archive jobs based on their age, or all jobs if a 'all' is |
142 |
passed. |
143 |
|
144 |
@param opts: the command line options selected by the user |
145 |
@type args: list |
146 |
@param args: should contain only one element, the age as a time spec |
147 |
that can be parsed by L{ganeti.cli.ParseTimespec} or the |
148 |
keyword I{all}, which will cause all jobs to be archived |
149 |
@rtype: int |
150 |
@return: the desired exit code |
151 |
|
152 |
""" |
153 |
client = GetClient() |
154 |
|
155 |
age = args[0] |
156 |
|
157 |
if age == 'all': |
158 |
age = -1 |
159 |
else: |
160 |
age = ParseTimespec(age) |
161 |
|
162 |
(archived_count, jobs_left) = client.AutoArchiveJobs(age) |
163 |
ToStdout("Archived %s jobs, %s unchecked left", archived_count, jobs_left) |
164 |
|
165 |
return 0 |
166 |
|
167 |
|
168 |
def CancelJobs(opts, args): |
169 |
"""Cancel not-yet-started jobs. |
170 |
|
171 |
@param opts: the command line options selected by the user |
172 |
@type args: list |
173 |
@param args: should contain the job IDs to be cancelled |
174 |
@rtype: int |
175 |
@return: the desired exit code |
176 |
|
177 |
""" |
178 |
client = GetClient() |
179 |
result = constants.EXIT_SUCCESS |
180 |
|
181 |
for job_id in args: |
182 |
(success, msg) = client.CancelJob(job_id) |
183 |
|
184 |
if not success: |
185 |
result = constants.EXIT_FAILURE |
186 |
|
187 |
ToStdout(msg) |
188 |
|
189 |
return result |
190 |
|
191 |
|
192 |
def ShowJobs(opts, args): |
193 |
"""Show detailed information about jobs. |
194 |
|
195 |
@param opts: the command line options selected by the user |
196 |
@type args: list |
197 |
@param args: should contain the job IDs to be queried |
198 |
@rtype: int |
199 |
@return: the desired exit code |
200 |
|
201 |
""" |
202 |
def format_msg(level, text): |
203 |
"""Display the text indented.""" |
204 |
ToStdout("%s%s", " " * level, text) |
205 |
|
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) |
210 |
else: |
211 |
return str(value) |
212 |
|
213 |
selected_fields = [ |
214 |
"id", "status", "ops", "opresult", "opstatus", "oplog", |
215 |
"opstart", "opexec", "opend", "received_ts", "start_ts", "end_ts", |
216 |
] |
217 |
|
218 |
result = GetClient().QueryJobs(args, selected_fields) |
219 |
|
220 |
first = True |
221 |
|
222 |
for idx, entry in enumerate(result): |
223 |
if not first: |
224 |
format_msg(0, "") |
225 |
else: |
226 |
first = False |
227 |
|
228 |
if entry is None: |
229 |
if idx <= len(args): |
230 |
format_msg(0, "Job ID %s not found" % args[idx]) |
231 |
else: |
232 |
# this should not happen, when we don't pass args it will be a |
233 |
# valid job returned |
234 |
format_msg(0, "Job ID requested as argument %s not found" % (idx + 1)) |
235 |
continue |
236 |
|
237 |
(job_id, status, ops, opresult, opstatus, oplog, |
238 |
opstart, opexec, opend, recv_ts, start_ts, end_ts) = entry |
239 |
format_msg(0, "Job ID: %s" % job_id) |
240 |
if status in _USER_JOB_STATUS: |
241 |
status = _USER_JOB_STATUS[status] |
242 |
else: |
243 |
raise errors.ProgrammerError("Unknown job status code '%s'" % status) |
244 |
|
245 |
format_msg(1, "Status: %s" % status) |
246 |
|
247 |
if recv_ts is not None: |
248 |
format_msg(1, "Received: %s" % FormatTimestamp(recv_ts)) |
249 |
else: |
250 |
format_msg(1, "Missing received timestamp (%s)" % str(recv_ts)) |
251 |
|
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 |
256 |
else: |
257 |
delta = "" |
258 |
format_msg(1, "Processing start: %s%s" % |
259 |
(FormatTimestamp(start_ts), delta)) |
260 |
else: |
261 |
format_msg(1, "Processing start: unknown (%s)" % str(start_ts)) |
262 |
|
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 |
267 |
else: |
268 |
delta = "" |
269 |
format_msg(1, "Processing end: %s%s" % |
270 |
(FormatTimestamp(end_ts), delta)) |
271 |
else: |
272 |
format_msg(1, "Processing end: unknown (%s)" % str(end_ts)) |
273 |
|
274 |
if end_ts is not None and recv_ts is not None: |
275 |
d3 = end_ts[0] - recv_ts[0] + (end_ts[1] - recv_ts[1]) / 1000000.0 |
276 |
format_msg(1, "Total processing time: %.6f seconds" % d3) |
277 |
else: |
278 |
format_msg(1, "Total processing time: N/A") |
279 |
format_msg(1, "Opcodes:") |
280 |
for (opcode, result, status, log, s_ts, x_ts, e_ts) in \ |
281 |
zip(ops, opresult, opstatus, oplog, opstart, opexec, opend): |
282 |
format_msg(2, "%s" % opcode["OP_ID"]) |
283 |
format_msg(3, "Status: %s" % status) |
284 |
if isinstance(s_ts, (tuple, list)): |
285 |
format_msg(3, "Processing start: %s" % FormatTimestamp(s_ts)) |
286 |
else: |
287 |
format_msg(3, "No processing start time") |
288 |
if isinstance(x_ts, (tuple, list)): |
289 |
format_msg(3, "Execution start: %s" % FormatTimestamp(x_ts)) |
290 |
else: |
291 |
format_msg(3, "No execution start time") |
292 |
if isinstance(e_ts, (tuple, list)): |
293 |
format_msg(3, "Processing end: %s" % FormatTimestamp(e_ts)) |
294 |
else: |
295 |
format_msg(3, "No processing end time") |
296 |
format_msg(3, "Input fields:") |
297 |
for key in utils.NiceSort(opcode.keys()): |
298 |
if key == "OP_ID": |
299 |
continue |
300 |
val = opcode[key] |
301 |
if isinstance(val, (tuple, list)): |
302 |
val = ",".join([str(item) for item in val]) |
303 |
format_msg(4, "%s: %s" % (key, val)) |
304 |
if result is None: |
305 |
format_msg(3, "No output data") |
306 |
elif isinstance(result, (tuple, list)): |
307 |
if not result: |
308 |
format_msg(3, "Result: empty sequence") |
309 |
else: |
310 |
format_msg(3, "Result:") |
311 |
for elem in result: |
312 |
format_msg(4, result_helper(elem)) |
313 |
elif isinstance(result, dict): |
314 |
if not result: |
315 |
format_msg(3, "Result: empty dictionary") |
316 |
else: |
317 |
for key, val in result.iteritems(): |
318 |
format_msg(4, "%s: %s" % (key, result_helper(val))) |
319 |
else: |
320 |
format_msg(3, "Result: %s" % result) |
321 |
format_msg(3, "Execution log:") |
322 |
for serial, log_ts, log_type, log_msg in log: |
323 |
time_txt = FormatTimestamp(log_ts) |
324 |
encoded = FormatLogMessage(log_type, log_msg) |
325 |
format_msg(4, "%s:%s:%s %s" % (serial, time_txt, log_type, encoded)) |
326 |
return 0 |
327 |
|
328 |
|
329 |
def WatchJob(opts, args): |
330 |
"""Follow a job and print its output as it arrives. |
331 |
|
332 |
@param opts: the command line options selected by the user |
333 |
@type args: list |
334 |
@param args: Contains the job ID |
335 |
@rtype: int |
336 |
@return: the desired exit code |
337 |
|
338 |
""" |
339 |
job_id = args[0] |
340 |
|
341 |
msg = ("Output from job %s follows" % job_id) |
342 |
ToStdout(msg) |
343 |
ToStdout("-" * len(msg)) |
344 |
|
345 |
retcode = 0 |
346 |
try: |
347 |
cli.PollJob(job_id) |
348 |
except errors.GenericError, err: |
349 |
(retcode, job_result) = cli.FormatError(err) |
350 |
ToStderr("Job %s failed: %s", job_id, job_result) |
351 |
|
352 |
return retcode |
353 |
|
354 |
|
355 |
commands = { |
356 |
'list': ( |
357 |
ListJobs, [ArgJobId()], |
358 |
[NOHDR_OPT, SEP_OPT, FIELDS_OPT], |
359 |
"[job_id ...]", |
360 |
"List the jobs and their status. The available fields are" |
361 |
" (see the man page for details): id, status, op_list," |
362 |
" op_status, op_result." |
363 |
" The default field" |
364 |
" list is (in order): %s." % utils.CommaJoin(_LIST_DEF_FIELDS)), |
365 |
'archive': ( |
366 |
ArchiveJobs, [ArgJobId(min=1)], [], |
367 |
"<job-id> [<job-id> ...]", "Archive specified jobs"), |
368 |
'autoarchive': ( |
369 |
AutoArchiveJobs, |
370 |
[ArgSuggest(min=1, max=1, choices=["1d", "1w", "4w", "all"])], |
371 |
[], |
372 |
"<age>", "Auto archive jobs older than the given age"), |
373 |
'cancel': ( |
374 |
CancelJobs, [ArgJobId(min=1)], [], |
375 |
"<job-id> [<job-id> ...]", "Cancel specified jobs"), |
376 |
'info': ( |
377 |
ShowJobs, [ArgJobId(min=1)], [], |
378 |
"<job-id> [<job-id> ...]", |
379 |
"Show detailed information about the specified jobs"), |
380 |
'watch': ( |
381 |
WatchJob, [ArgJobId(min=1, max=1)], [], |
382 |
"<job-id>", "Follows a job and prints its output as it arrives"), |
383 |
} |
384 |
|
385 |
|
386 |
if __name__ == '__main__': |
387 |
sys.exit(GenericMain(commands)) |