Statistics
| Branch: | Tag: | Revision:

root / scripts / gnt-job @ b59252fe

History | View | Annotate | Download (10 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

    
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_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", "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
  for job_id in args:
130
    client.ArchiveJob(job_id)
131

    
132
  return 0
133

    
134

    
135
def AutoArchiveJobs(opts, args):
136
  """Archive jobs based on age.
137

    
138
  This will archive jobs based on their age, or all jobs if a 'all' is
139
  passed.
140

    
141
  @param opts: the command line options selected by the user
142
  @type args: list
143
  @param args: should contain only one element, the age as a time spec
144
      that can be parsed by L{ganeti.cli.ParseTimespec} or the
145
      keyword I{all}, which will cause all jobs to be archived
146
  @rtype: int
147
  @return: the desired exit code
148

    
149
  """
150
  client = GetClient()
151

    
152
  age = args[0]
153

    
154
  if age == 'all':
155
    age = -1
156
  else:
157
    age = ParseTimespec(age)
158

    
159
  (archived_count, jobs_left) = client.AutoArchiveJobs(age)
160
  ToStdout("Archived %s jobs, %s unchecked left", archived_count, jobs_left)
161

    
162
  return 0
163

    
164

    
165
def CancelJobs(opts, args):
166
  """Cancel not-yet-started jobs.
167

    
168
  @param opts: the command line options selected by the user
169
  @type args: list
170
  @param args: should contain the job IDs to be cancelled
171
  @rtype: int
172
  @return: the desired exit code
173

    
174
  """
175
  client = GetClient()
176

    
177
  for job_id in args:
178
    (success, msg) = client.CancelJob(job_id)
179
    ToStdout(msg)
180

    
181
  # TODO: Different exit value if not all jobs were canceled?
182
  return 0
183

    
184

    
185
def ShowJobs(opts, args):
186
  """Show detailed information about jobs.
187

    
188
  @param opts: the command line options selected by the user
189
  @type args: list
190
  @param args: should contain the job IDs to be queried
191
  @rtype: int
192
  @return: the desired exit code
193

    
194
  """
195
  def format(level, text):
196
    """Display the text indented."""
197
    ToStdout("%s%s", "  " * level, text)
198

    
199
  def result_helper(value):
200
    """Format a result field in a nice way."""
201
    if isinstance(value, (tuple, list)):
202
      return "[%s]" % (", ".join(str(elem) for elem in value))
203
    else:
204
      return str(value)
205

    
206
  selected_fields = [
207
    "id", "status", "ops", "opresult", "opstatus", "oplog",
208
    "opstart", "opend", "received_ts", "start_ts", "end_ts",
209
    ]
210

    
211
  result = GetClient().QueryJobs(args, selected_fields)
212

    
213
  first = True
214

    
215
  for idx, entry in enumerate(result):
216
    if not first:
217
      format(0, "")
218
    else:
219
      first = False
220

    
221
    if entry is None:
222
      if idx <= len(args):
223
        format(0, "Job ID %s not found" % args[idx])
224
      else:
225
        # this should not happen, when we don't pass args it will be a
226
        # valid job returned
227
        format(0, "Job ID requested as argument %s not found" % (idx + 1))
228
      continue
229

    
230
    (job_id, status, ops, opresult, opstatus, oplog,
231
     opstart, opend, recv_ts, start_ts, end_ts) = entry
232
    format(0, "Job ID: %s" % job_id)
233
    if status in _USER_JOB_STATUS:
234
      status = _USER_JOB_STATUS[status]
235
    else:
236
      raise errors.ProgrammerError("Unknown job status code '%s'" % status)
237

    
238
    format(1, "Status: %s" % status)
239

    
240
    if recv_ts is not None:
241
      format(1, "Received:         %s" % FormatTimestamp(recv_ts))
242
    else:
243
      format(1, "Missing received timestamp (%s)" % str(recv_ts))
244

    
245
    if start_ts is not None:
246
      if recv_ts is not None:
247
        d1 = start_ts[0] - recv_ts[0] + (start_ts[1] - recv_ts[1]) / 1000000.0
248
        delta = " (delta %.6fs)" % d1
249
      else:
250
        delta = ""
251
      format(1, "Processing start: %s%s" % (FormatTimestamp(start_ts), delta))
252
    else:
253
      format(1, "Processing start: unknown (%s)" % str(start_ts))
254

    
255
    if end_ts is not None:
256
      if start_ts is not None:
257
        d2 = end_ts[0] - start_ts[0] + (end_ts[1] - start_ts[1]) / 1000000.0
258
        delta = " (delta %.6fs)" % d2
259
      else:
260
        delta = ""
261
      format(1, "Processing end:   %s%s" % (FormatTimestamp(end_ts), delta))
262
    else:
263
      format(1, "Processing end:   unknown (%s)" % str(end_ts))
264

    
265
    if end_ts is not None and recv_ts is not None:
266
      d3 = end_ts[0] - recv_ts[0] + (end_ts[1] - recv_ts[1]) / 1000000.0
267
      format(1, "Total processing time: %.6f seconds" % d3)
268
    else:
269
      format(1, "Total processing time: N/A")
270
    format(1, "Opcodes:")
271
    for (opcode, result, status, log, s_ts, e_ts) in \
272
            zip(ops, opresult, opstatus, oplog, opstart, opend):
273
      format(2, "%s" % opcode["OP_ID"])
274
      format(3, "Status: %s" % status)
275
      if isinstance(s_ts, (tuple, list)):
276
        format(3, "Processing start: %s" % FormatTimestamp(s_ts))
277
      else:
278
        format(3, "No processing start time")
279
      if isinstance(e_ts, (tuple, list)):
280
        format(3, "Processing end:   %s" % FormatTimestamp(e_ts))
281
      else:
282
        format(3, "No processing end time")
283
      format(3, "Input fields:")
284
      for key, val in opcode.iteritems():
285
        if key == "OP_ID":
286
          continue
287
        if isinstance(val, (tuple, list)):
288
          val = ",".join([str(item) for item in val])
289
        format(4, "%s: %s" % (key, val))
290
      if result is None:
291
        format(3, "No output data")
292
      elif isinstance(result, (tuple, list)):
293
        if not result:
294
          format(3, "Result: empty sequence")
295
        else:
296
          format(3, "Result:")
297
          for elem in result:
298
            format(4, result_helper(elem))
299
      elif isinstance(result, dict):
300
        if not result:
301
          format(3, "Result: empty dictionary")
302
        else:
303
          for key, val in result.iteritems():
304
            format(4, "%s: %s" % (key, result_helper(val)))
305
      else:
306
        format(3, "Result: %s" % result)
307
      format(3, "Execution log:")
308
      for serial, log_ts, log_type, log_msg in log:
309
        time_txt = FormatTimestamp(log_ts)
310
        encoded = utils.SafeEncode(log_msg)
311
        format(4, "%s:%s:%s %s" % (serial, time_txt, log_type, encoded))
312
  return 0
313

    
314

    
315
commands = {
316
  'list': (ListJobs, ARGS_ANY,
317
            [DEBUG_OPT, NOHDR_OPT, SEP_OPT, FIELDS_OPT],
318
            "[job_id ...]",
319
           "List the jobs and their status. The available fields are"
320
           " (see the man page for details): id, status, op_list,"
321
           " op_status, op_result."
322
           " The default field"
323
           " list is (in order): %s." % ", ".join(_LIST_DEF_FIELDS)),
324
  'archive': (ArchiveJobs, ARGS_ANY,
325
              [DEBUG_OPT],
326
              "<job-id> [<job-id> ...]",
327
              "Archive specified jobs"),
328
  'autoarchive': (AutoArchiveJobs, ARGS_ONE,
329
              [DEBUG_OPT],
330
              "<age>",
331
              "Auto archive jobs older than the given age"),
332
  'cancel': (CancelJobs, ARGS_ANY,
333
             [DEBUG_OPT],
334
             "<job-id> [<job-id> ...]",
335
             "Cancel specified jobs"),
336
  'info': (ShowJobs, ARGS_ANY, [DEBUG_OPT],
337
           "<job-id> [<job-id> ...]",
338
           "Show detailed information about the specified jobs"),
339
  }
340

    
341

    
342
if __name__ == '__main__':
343
  sys.exit(GenericMain(commands))