Some command line scripts fixes
[ganeti-local] / scripts / gnt-job
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
22 # pylint: disable-msg=W0401,W0614
23 # W0401: Wildcard import ganeti.cli
24 # W0614: Unused import %s from wildcard import (since we need cli)
25
26 import sys
27
28 from ganeti.cli import *
29 from ganeti import constants
30 from ganeti import errors
31 from ganeti import utils
32
33
34 #: default list of fields for L{ListJobs}
35 _LIST_DEF_FIELDS = ["id", "status", "summary"]
36
37 #: map converting the job status contants to user-visible
38 #: names
39 _USER_JOB_STATUS = {
40   constants.JOB_STATUS_QUEUED: "queued",
41   constants.JOB_STATUS_WAITLOCK: "waiting",
42   constants.JOB_STATUS_CANCELING: "canceling",
43   constants.JOB_STATUS_RUNNING: "running",
44   constants.JOB_STATUS_CANCELED: "canceled",
45   constants.JOB_STATUS_SUCCESS: "success",
46   constants.JOB_STATUS_ERROR: "error",
47   }
48
49
50 def ListJobs(opts, args):
51   """List the jobs
52
53   @param opts: the command line options selected by the user
54   @type args: list
55   @param args: should be an empty list
56   @rtype: int
57   @return: the desired exit code
58
59   """
60   if opts.output is None:
61     selected_fields = _LIST_DEF_FIELDS
62   elif opts.output.startswith("+"):
63     selected_fields = _LIST_DEF_FIELDS + opts.output[1:].split(",")
64   else:
65     selected_fields = opts.output.split(",")
66
67   output = GetClient().QueryJobs(args, selected_fields)
68   if not opts.no_headers:
69     # TODO: Implement more fields
70     headers = {
71       "id": "ID",
72       "status": "Status",
73       "ops": "OpCodes",
74       "opresult": "OpCode_result",
75       "opstatus": "OpCode_status",
76       "oplog": "OpCode_log",
77       "summary": "Summary",
78       "opstart": "OpCode_start",
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 in output:
89     for idx, field in enumerate(selected_fields):
90       val = row[idx]
91       if field == "status":
92         if val in _USER_JOB_STATUS:
93           val = _USER_JOB_STATUS[val]
94         else:
95           raise errors.ProgrammerError("Unknown job status code '%s'" % val)
96       elif field == "summary":
97         val = ",".join(val)
98       elif field in ("start_ts", "end_ts", "received_ts"):
99         val = FormatTimestamp(val)
100       elif field in ("opstart", "opend"):
101         val = [FormatTimestamp(entry) for entry in val]
102
103       row[idx] = str(val)
104
105   data = GenerateTable(separator=opts.separator, headers=headers,
106                        fields=selected_fields, data=output)
107   for line in data:
108     ToStdout(line)
109
110   return 0
111
112
113 def ArchiveJobs(opts, args):
114   """Archive jobs.
115
116   @param opts: the command line options selected by the user
117   @type args: list
118   @param args: should contain the job IDs to be archived
119   @rtype: int
120   @return: the desired exit code
121
122   """
123   client = GetClient()
124
125   for job_id in args:
126     client.ArchiveJob(job_id)
127
128   return 0
129
130
131 def AutoArchiveJobs(opts, args):
132   """Archive jobs based on age.
133
134   This will archive jobs based on their age, or all jobs if a 'all' is
135   passed.
136
137   @param opts: the command line options selected by the user
138   @type args: list
139   @param args: should contain only one element, the age as a time spec
140       that can be parsed by L{ganeti.cli.ParseTimespec} or the
141       keyword I{all}, which will cause all jobs to be archived
142   @rtype: int
143   @return: the desired exit code
144
145   """
146   client = GetClient()
147
148   age = args[0]
149
150   if age == 'all':
151     age = -1
152   else:
153     age = ParseTimespec(age)
154
155   (archived_count, jobs_left) = client.AutoArchiveJobs(age)
156   ToStdout("Archived %s jobs, %s unchecked left", archived_count, jobs_left)
157
158   return 0
159
160
161 def CancelJobs(opts, args):
162   """Cancel not-yet-started jobs.
163
164   @param opts: the command line options selected by the user
165   @type args: list
166   @param args: should contain the job IDs to be cancelled
167   @rtype: int
168   @return: the desired exit code
169
170   """
171   client = GetClient()
172
173   for job_id in args:
174     (success, msg) = client.CancelJob(job_id)
175     ToStdout(msg)
176
177   # TODO: Different exit value if not all jobs were canceled?
178   return 0
179
180
181 def ShowJobs(opts, args):
182   """Show detailed information about jobs.
183
184   @param opts: the command line options selected by the user
185   @type args: list
186   @param args: should contain the job IDs to be queried
187   @rtype: int
188   @return: the desired exit code
189
190   """
191   def format(level, text):
192     """Display the text indented."""
193     ToStdout("%s%s", "  " * level, text)
194
195   def result_helper(value):
196     """Format a result field in a nice way."""
197     if isinstance(value, (tuple, list)):
198       return "[%s]" % (", ".join(str(elem) for elem in value))
199     else:
200       return str(value)
201
202   selected_fields = [
203     "id", "status", "ops", "opresult", "opstatus", "oplog",
204     "opstart", "opend", "received_ts", "start_ts", "end_ts",
205     ]
206
207   result = GetClient().QueryJobs(args, selected_fields)
208
209   first = True
210
211   for idx, entry in enumerate(result):
212     if not first:
213       format(0, "")
214     else:
215       first = False
216
217     if entry is None:
218       if idx <= len(args):
219         format(0, "Job ID %s not found" % args[idx])
220       else:
221         # this should not happen, when we don't pass args it will be a
222         # valid job returned
223         format(0, "Job ID requested as argument %s not found" % (idx + 1))
224       continue
225
226     (job_id, status, ops, opresult, opstatus, oplog,
227      opstart, opend, recv_ts, start_ts, end_ts) = entry
228     format(0, "Job ID: %s" % job_id)
229     if status in _USER_JOB_STATUS:
230       status = _USER_JOB_STATUS[status]
231     else:
232       raise errors.ProgrammerError("Unknown job status code '%s'" % status)
233
234     format(1, "Status: %s" % status)
235
236     if recv_ts is not None:
237       format(1, "Received:         %s" % FormatTimestamp(recv_ts))
238     else:
239       format(1, "Missing received timestamp (%s)" % str(recv_ts))
240
241     if start_ts is not None:
242       if recv_ts is not None:
243         d1 = start_ts[0] - recv_ts[0] + (start_ts[1] - recv_ts[1]) / 1000000.0
244         delta = " (delta %.6fs)" % d1
245       else:
246         delta = ""
247       format(1, "Processing start: %s%s" % (FormatTimestamp(start_ts), delta))
248     else:
249       format(1, "Processing start: unknown (%s)" % str(start_ts))
250
251     if end_ts is not None:
252       if start_ts is not None:
253         d2 = end_ts[0] - start_ts[0] + (end_ts[1] - start_ts[1]) / 1000000.0
254         delta = " (delta %.6fs)" % d2
255       else:
256         delta = ""
257       format(1, "Processing end:   %s%s" % (FormatTimestamp(end_ts), delta))
258     else:
259       format(1, "Processing end:   unknown (%s)" % str(end_ts))
260
261     if end_ts is not None and recv_ts is not None:
262       d3 = end_ts[0] - recv_ts[0] + (end_ts[1] - recv_ts[1]) / 1000000.0
263       format(1, "Total processing time: %.6f seconds" % d3)
264     else:
265       format(1, "Total processing time: N/A")
266     format(1, "Opcodes:")
267     for (opcode, result, status, log, s_ts, e_ts) in \
268             zip(ops, opresult, opstatus, oplog, opstart, opend):
269       format(2, "%s" % opcode["OP_ID"])
270       format(3, "Status: %s" % status)
271       if isinstance(s_ts, (tuple, list)):
272         format(3, "Processing start: %s" % FormatTimestamp(s_ts))
273       else:
274         format(3, "No processing start time")
275       if isinstance(e_ts, (tuple, list)):
276         format(3, "Processing end:   %s" % FormatTimestamp(e_ts))
277       else:
278         format(3, "No processing end time")
279       format(3, "Input fields:")
280       for key, val in opcode.iteritems():
281         if key == "OP_ID":
282           continue
283         if isinstance(val, (tuple, list)):
284           val = ",".join([str(item) for item in val])
285         format(4, "%s: %s" % (key, val))
286       if result is None:
287         format(3, "No output data")
288       elif isinstance(result, (tuple, list)):
289         if not result:
290           format(3, "Result: empty sequence")
291         else:
292           format(3, "Result:")
293           for elem in result:
294             format(4, result_helper(elem))
295       elif isinstance(result, dict):
296         if not result:
297           format(3, "Result: empty dictionary")
298         else:
299           for key, val in result.iteritems():
300             format(4, "%s: %s" % (key, result_helper(val)))
301       else:
302         format(3, "Result: %s" % result)
303       format(3, "Execution log:")
304       for serial, log_ts, log_type, log_msg in log:
305         time_txt = FormatTimestamp(log_ts)
306         encoded = utils.SafeEncode(log_msg)
307         format(4, "%s:%s:%s %s" % (serial, time_txt, log_type, encoded))
308   return 0
309
310
311 commands = {
312   'list': (ListJobs, ARGS_ANY,
313             [DEBUG_OPT, NOHDR_OPT, SEP_OPT, FIELDS_OPT],
314             "[job_id ...]",
315            "List the jobs and their status. The available fields are"
316            " (see the man page for details): id, status, op_list,"
317            " op_status, op_result."
318            " The default field"
319            " list is (in order): %s." % ", ".join(_LIST_DEF_FIELDS)),
320   'archive': (ArchiveJobs, ARGS_ANY,
321               [DEBUG_OPT],
322               "<job-id> [<job-id> ...]",
323               "Archive specified jobs"),
324   'autoarchive': (AutoArchiveJobs, ARGS_ONE,
325               [DEBUG_OPT],
326               "<age>",
327               "Auto archive jobs older than the given age"),
328   'cancel': (CancelJobs, ARGS_ANY,
329              [DEBUG_OPT],
330              "<job-id> [<job-id> ...]",
331              "Cancel specified jobs"),
332   'info': (ShowJobs, ARGS_ANY, [DEBUG_OPT],
333            "<job-id> [<job-id> ...]",
334            "Show detailed information about the specified jobs"),
335   }
336
337
338 if __name__ == '__main__':
339   sys.exit(GenericMain(commands))