Statistics
| Branch: | Tag: | Revision:

root / scripts / gnt-job @ aad81f98

History | View | Annotate | Download (7.9 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 entry, arg_job in zip(result, args):
153
    if not first:
154
      format(0, "")
155
    else:
156
      first = False
157

    
158
    if entry is None:
159
      format(0, "Job ID %s not found" % arg_job)
160
      continue
161

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

    
170
    format(1, "Status: %s" % status)
171

    
172
    if recv_ts is not None:
173
      format(1, "Received:         %s" % FormatTimestamp(recv_ts))
174
    else:
175
      format(1, "Missing received timestamp (%s)" % str(recv_ts))
176

    
177
    if start_ts is not None:
178
      if recv_ts is not None:
179
        d1 = start_ts[0] - recv_ts[0] + (start_ts[1] - recv_ts[1]) / 1000000.0
180
        delta = " (delta %.6fs)" % d1
181
      else:
182
        delta = ""
183
      format(1, "Processing start: %s%s" % (FormatTimestamp(start_ts), delta))
184
    else:
185
      format(1, "Processing start: unknown (%s)" % str(start_ts))
186

    
187
    if end_ts is not None:
188
      if start_ts is not None:
189
        d2 = end_ts[0] - start_ts[0] + (end_ts[1] - start_ts[1]) / 1000000.0
190
        delta = " (delta %.6fs)" % d2
191
      else:
192
        delta = ""
193
      format(1, "Processing end:   %s%s" % (FormatTimestamp(end_ts), delta))
194
    else:
195
      format(1, "Processing end:   unknown (%s)" % str(end_ts))
196

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

    
246

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

    
268

    
269
if __name__ == '__main__':
270
  sys.exit(GenericMain(commands))