Statistics
| Branch: | Tag: | Revision:

root / scripts / gnt-job @ b27b39b0

History | View | Annotate | Download (8.1 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
import sys
23
import os
24
import itertools
25
import time
26
from optparse import make_option
27
from cStringIO import StringIO
28

    
29
from ganeti.cli import *
30
from ganeti import opcodes
31
from ganeti import logger
32
from ganeti import constants
33
from ganeti import utils
34
from ganeti import errors
35

    
36

    
37
_LIST_DEF_FIELDS = ["id", "status", "summary"]
38

    
39
_USER_JOB_STATUS = {
40
  constants.JOB_STATUS_QUEUED: "queued",
41
  constants.JOB_STATUS_RUNNING: "running",
42
  constants.JOB_STATUS_CANCELED: "canceled",
43
  constants.JOB_STATUS_SUCCESS: "success",
44
  constants.JOB_STATUS_ERROR: "error",
45
  }
46

    
47

    
48
def ListJobs(opts, args):
49
  """List the jobs
50

    
51
  """
52
  if opts.output is None:
53
    selected_fields = _LIST_DEF_FIELDS
54
  elif opts.output.startswith("+"):
55
    selected_fields = _LIST_DEF_FIELDS + opts.output[1:].split(",")
56
  else:
57
    selected_fields = opts.output.split(",")
58

    
59
  output = GetClient().QueryJobs(None, selected_fields)
60
  if not opts.no_headers:
61
    # TODO: Implement more fields
62
    headers = {
63
      "id": "ID",
64
      "status": "Status",
65
      "ops": "OpCodes",
66
      "opresult": "OpCode_result",
67
      "opstatus": "OpCode_status",
68
      "oplog": "OpCode_log",
69
      "summary": "Summary",
70
      "opstart": "OpCode_start",
71
      "opend": "OpCode_end",
72
      "start_ts": "Start",
73
      "end_ts": "End",
74
      "received_ts": "Received",
75
      }
76
  else:
77
    headers = None
78

    
79
  # we don't have yet unitfields here
80
  unitfields = None
81
  numfields = None
82

    
83
  # change raw values to nicer strings
84
  for row in output:
85
    for idx, field in enumerate(selected_fields):
86
      val = row[idx]
87
      if field == "status":
88
        if val in _USER_JOB_STATUS:
89
          val = _USER_JOB_STATUS[val]
90
        else:
91
          raise errors.ProgrammerError("Unknown job status code '%s'" % val)
92
      elif field == "summary":
93
        val = ",".join(val)
94
      elif field in ("start_ts", "end_ts", "received_ts"):
95
        val = FormatTimestamp(val)
96
      elif field in ("opstart", "opend"):
97
        val = [FormatTimestamp(entry) for entry in val]
98

    
99
      row[idx] = str(val)
100

    
101
  data = GenerateTable(separator=opts.separator, headers=headers,
102
                       fields=selected_fields, unitfields=unitfields,
103
                       numfields=numfields, data=output)
104
  for line in data:
105
    print line
106

    
107
  return 0
108

    
109

    
110
def ArchiveJobs(opts, args):
111
  client = GetClient()
112

    
113
  for job_id in args:
114
    client.ArchiveJob(job_id)
115

    
116
  return 0
117

    
118

    
119
def CancelJobs(opts, args):
120
  client = GetClient()
121

    
122
  for job_id in args:
123
    client.CancelJob(job_id)
124

    
125
  return 0
126

    
127

    
128
def ShowJobs(opts, args):
129
  """List the jobs
130

    
131
  """
132
  def format(level, text):
133
    """Display the text indented."""
134
    print "%s%s" % ("  " * level, text)
135

    
136
  def result_helper(value):
137
    """Format a result field in a nice way."""
138
    if isinstance(value, (tuple, list)):
139
      return "[%s]" % (", ".join(str(elem) for elem in value))
140
    else:
141
      return str(value)
142

    
143
  selected_fields = [
144
    "id", "status", "ops", "opresult", "opstatus", "oplog",
145
    "opstart", "opend", "received_ts", "start_ts", "end_ts",
146
    ]
147

    
148
  result = GetClient().QueryJobs(args, selected_fields)
149

    
150
  first = True
151

    
152
  for idx, entry in enumerate(result):
153
    if not first:
154
      format(0, "")
155
    else:
156
      first = False
157

    
158
    if entry is None:
159
      if idx <= len(args):
160
        format(0, "Job ID %s not found" % args[idx])
161
      else:
162
        # this should not happen, when we don't pass args it will be a
163
        # valid job returned
164
        format(0, "Job ID requested as argument %s not found" % (idx + 1))
165
      continue
166

    
167
    (job_id, status, ops, opresult, opstatus, oplog,
168
     opstart, opend, recv_ts, start_ts, end_ts) = entry
169
    format(0, "Job ID: %s" % job_id)
170
    if status in _USER_JOB_STATUS:
171
      status = _USER_JOB_STATUS[status]
172
    else:
173
      raise errors.ProgrammerError("Unknown job status code '%s'" % val)
174

    
175
    format(1, "Status: %s" % status)
176

    
177
    if recv_ts is not None:
178
      format(1, "Received:         %s" % FormatTimestamp(recv_ts))
179
    else:
180
      format(1, "Missing received timestamp (%s)" % str(recv_ts))
181

    
182
    if start_ts is not None:
183
      if recv_ts is not None:
184
        d1 = start_ts[0] - recv_ts[0] + (start_ts[1] - recv_ts[1]) / 1000000.0
185
        delta = " (delta %.6fs)" % d1
186
      else:
187
        delta = ""
188
      format(1, "Processing start: %s%s" % (FormatTimestamp(start_ts), delta))
189
    else:
190
      format(1, "Processing start: unknown (%s)" % str(start_ts))
191

    
192
    if end_ts is not None:
193
      if start_ts is not None:
194
        d2 = end_ts[0] - start_ts[0] + (end_ts[1] - start_ts[1]) / 1000000.0
195
        delta = " (delta %.6fs)" % d2
196
      else:
197
        delta = ""
198
      format(1, "Processing end:   %s%s" % (FormatTimestamp(end_ts), delta))
199
    else:
200
      format(1, "Processing end:   unknown (%s)" % str(end_ts))
201

    
202
    if end_ts is not None and recv_ts is not None:
203
      d3 = end_ts[0] - recv_ts[0] + (end_ts[1] - recv_ts[1]) / 1000000.0
204
      format(1, "Total processing time: %.6f seconds" % d3)
205
    else:
206
      format(1, "Total processing time: N/A")
207
    format(1, "Opcodes:")
208
    for (opcode, result, status, log, s_ts, e_ts) in \
209
            zip(ops, opresult, opstatus, oplog, opstart, opend):
210
      format(2, "%s" % opcode["OP_ID"])
211
      format(3, "Status: %s" % status)
212
      if isinstance(s_ts, (tuple, list)):
213
        format(3, "Processing start: %s" % FormatTimestamp(s_ts))
214
      else:
215
        format(3, "No processing start time")
216
      if isinstance(e_ts, (tuple, list)):
217
        format(3, "Processing end:   %s" % FormatTimestamp(e_ts))
218
      else:
219
        format(3, "No processing end time")
220
      format(3, "Input fields:")
221
      for key, val in opcode.iteritems():
222
        if key == "OP_ID":
223
          continue
224
        if isinstance(val, (tuple, list)):
225
          val = ",".join(val)
226
        format(4, "%s: %s" % (key, val))
227
      if result is None:
228
        format(3, "No output data")
229
      elif isinstance(result, (tuple, list)):
230
        if not result:
231
          format(3, "Result: empty sequence")
232
        else:
233
          format(3, "Result:")
234
          for elem in result:
235
            format(4, result_helper(elem))
236
      elif isinstance(result, dict):
237
        if not result:
238
          format(3, "Result: empty dictionary")
239
        else:
240
          for key, val in result.iteritems():
241
            format(4, "%s: %s" % (key, result_helper(val)))
242
      else:
243
        format(3, "Result: %s" % result)
244
      format(3, "Execution log:")
245
      for serial, log_ts, log_type, log_msg in log:
246
        time_txt = FormatTimestamp(log_ts)
247
        encoded = str(log_msg).encode('string_escape')
248
        format(4, "%s:%s:%s %s" % (serial, time_txt, log_type, encoded))
249
  return 0
250

    
251

    
252
commands = {
253
  'list': (ListJobs, ARGS_NONE,
254
            [DEBUG_OPT, NOHDR_OPT, SEP_OPT, USEUNITS_OPT, FIELDS_OPT],
255
            "", "List the jobs and their status. The available fields are"
256
           " (see the man page for details): id, status, op_list,"
257
           " op_status, op_result."
258
           " The default field"
259
           " list is (in order): %s." % ", ".join(_LIST_DEF_FIELDS)),
260
  'archive': (ArchiveJobs, ARGS_ANY,
261
              [DEBUG_OPT],
262
              "<job-id> [<job-id> ...]",
263
              "Archive specified jobs"),
264
  'cancel': (CancelJobs, ARGS_ANY,
265
             [DEBUG_OPT],
266
             "<job-id> [<job-id> ...]",
267
             "Cancel specified jobs"),
268
  'info': (ShowJobs, ARGS_ANY, [DEBUG_OPT],
269
           "<job-id> [<job-id> ...]",
270
           "Show detailed information about the specified jobs"),
271
  }
272

    
273

    
274
if __name__ == '__main__':
275
  sys.exit(GenericMain(commands))