Statistics
| Branch: | Tag: | Revision:

root / lib / client / gnt_debug.py @ 3f1e065d

History | View | Annotate | Download (19.4 kB)

1 c2855a12 Michael Hanselmann
#
2 fd3ee040 Iustin Pop
#
3 fd3ee040 Iustin Pop
4 b469eb4d Iustin Pop
# Copyright (C) 2006, 2007, 2010, 2011 Google Inc.
5 fd3ee040 Iustin Pop
#
6 fd3ee040 Iustin Pop
# This program is free software; you can redistribute it and/or modify
7 fd3ee040 Iustin Pop
# it under the terms of the GNU General Public License as published by
8 fd3ee040 Iustin Pop
# the Free Software Foundation; either version 2 of the License, or
9 fd3ee040 Iustin Pop
# (at your option) any later version.
10 fd3ee040 Iustin Pop
#
11 fd3ee040 Iustin Pop
# This program is distributed in the hope that it will be useful, but
12 fd3ee040 Iustin Pop
# WITHOUT ANY WARRANTY; without even the implied warranty of
13 fd3ee040 Iustin Pop
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 fd3ee040 Iustin Pop
# General Public License for more details.
15 fd3ee040 Iustin Pop
#
16 fd3ee040 Iustin Pop
# You should have received a copy of the GNU General Public License
17 fd3ee040 Iustin Pop
# along with this program; if not, write to the Free Software
18 fd3ee040 Iustin Pop
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 fd3ee040 Iustin Pop
# 02110-1301, USA.
20 fd3ee040 Iustin Pop
21 7260cfbe Iustin Pop
"""Debugging commands"""
22 fd3ee040 Iustin Pop
23 7260cfbe Iustin Pop
# pylint: disable-msg=W0401,W0614,C0103
24 2f79bd34 Iustin Pop
# W0401: Wildcard import ganeti.cli
25 2f79bd34 Iustin Pop
# W0614: Unused import %s from wildcard import (since we need cli)
26 7260cfbe Iustin Pop
# C0103: Invalid name gnt-backup
27 2f79bd34 Iustin Pop
28 f1c66d13 Iustin Pop
import simplejson
29 f1c66d13 Iustin Pop
import time
30 e58f87a9 Michael Hanselmann
import socket
31 e58f87a9 Michael Hanselmann
import logging
32 f1c66d13 Iustin Pop
33 fd3ee040 Iustin Pop
from ganeti.cli import *
34 9d5ba39a Iustin Pop
from ganeti import cli
35 e58f87a9 Michael Hanselmann
from ganeti import constants
36 fd3ee040 Iustin Pop
from ganeti import opcodes
37 fd3ee040 Iustin Pop
from ganeti import utils
38 fd3ee040 Iustin Pop
from ganeti import errors
39 92ae7daf Michael Hanselmann
from ganeti import compat
40 fd3ee040 Iustin Pop
41 fd3ee040 Iustin Pop
42 19b9ba9a Michael Hanselmann
#: Default fields for L{ListLocks}
43 19b9ba9a Michael Hanselmann
_LIST_LOCKS_DEF_FIELDS = [
44 19b9ba9a Michael Hanselmann
  "name",
45 19b9ba9a Michael Hanselmann
  "mode",
46 19b9ba9a Michael Hanselmann
  "owner",
47 c31825f7 Michael Hanselmann
  "pending",
48 19b9ba9a Michael Hanselmann
  ]
49 19b9ba9a Michael Hanselmann
50 19b9ba9a Michael Hanselmann
51 fd3ee040 Iustin Pop
def Delay(opts, args):
52 fd3ee040 Iustin Pop
  """Sleeps for a while
53 fd3ee040 Iustin Pop

54 6099bfcf Iustin Pop
  @param opts: the command line options selected by the user
55 6099bfcf Iustin Pop
  @type args: list
56 6099bfcf Iustin Pop
  @param args: should contain only one element, the duration
57 6099bfcf Iustin Pop
      the sleep
58 6099bfcf Iustin Pop
  @rtype: int
59 6099bfcf Iustin Pop
  @return: the desired exit code
60 6099bfcf Iustin Pop

61 fd3ee040 Iustin Pop
  """
62 fd3ee040 Iustin Pop
  delay = float(args[0])
63 fd3ee040 Iustin Pop
  op = opcodes.OpTestDelay(duration=delay,
64 fd3ee040 Iustin Pop
                           on_master=opts.on_master,
65 85a87e21 Guido Trotter
                           on_nodes=opts.on_nodes,
66 85a87e21 Guido Trotter
                           repeat=opts.repeat)
67 400ca2f7 Iustin Pop
  SubmitOpCode(op, opts=opts)
68 fd3ee040 Iustin Pop
69 fd3ee040 Iustin Pop
  return 0
70 fd3ee040 Iustin Pop
71 fd3ee040 Iustin Pop
72 f1c66d13 Iustin Pop
def GenericOpCodes(opts, args):
73 6099bfcf Iustin Pop
  """Send any opcode to the master.
74 6099bfcf Iustin Pop

75 6099bfcf Iustin Pop
  @param opts: the command line options selected by the user
76 6099bfcf Iustin Pop
  @type args: list
77 6099bfcf Iustin Pop
  @param args: should contain only one element, the path of
78 6099bfcf Iustin Pop
      the file with the opcode definition
79 6099bfcf Iustin Pop
  @rtype: int
80 6099bfcf Iustin Pop
  @return: the desired exit code
81 f1c66d13 Iustin Pop

82 f1c66d13 Iustin Pop
  """
83 9d5ba39a Iustin Pop
  cl = cli.GetClient()
84 cb573a31 Iustin Pop
  jex = cli.JobExecutor(cl=cl, verbose=opts.verbose, opts=opts)
85 9d95c3af Iustin Pop
86 9d95c3af Iustin Pop
  job_cnt = 0
87 9d95c3af Iustin Pop
  op_cnt = 0
88 9d95c3af Iustin Pop
  if opts.timing_stats:
89 9d95c3af Iustin Pop
    ToStdout("Loading...")
90 9d95c3af Iustin Pop
  for job_idx in range(opts.rep_job):
91 9d95c3af Iustin Pop
    for fname in args:
92 7260cfbe Iustin Pop
      # pylint: disable-msg=W0142
93 4d5fe81b Michael Hanselmann
      op_data = simplejson.loads(utils.ReadFile(fname))
94 9d95c3af Iustin Pop
      op_list = [opcodes.OpCode.LoadOpCode(val) for val in op_data]
95 9d95c3af Iustin Pop
      op_list = op_list * opts.rep_op
96 9d95c3af Iustin Pop
      jex.QueueJob("file %s/%d" % (fname, job_idx), *op_list)
97 9d95c3af Iustin Pop
      op_cnt += len(op_list)
98 9d95c3af Iustin Pop
      job_cnt += 1
99 9d95c3af Iustin Pop
100 9d95c3af Iustin Pop
  if opts.timing_stats:
101 9d95c3af Iustin Pop
    t1 = time.time()
102 9d95c3af Iustin Pop
    ToStdout("Submitting...")
103 4d5fe81b Michael Hanselmann
104 66ecc479 Guido Trotter
  jex.SubmitPending(each=opts.each)
105 9d95c3af Iustin Pop
106 9d95c3af Iustin Pop
  if opts.timing_stats:
107 9d95c3af Iustin Pop
    t2 = time.time()
108 9d95c3af Iustin Pop
    ToStdout("Executing...")
109 b59252fe Iustin Pop
110 b59252fe Iustin Pop
  jex.GetResults()
111 9d95c3af Iustin Pop
  if opts.timing_stats:
112 9d95c3af Iustin Pop
    t3 = time.time()
113 9d95c3af Iustin Pop
    ToStdout("C:op     %4d" % op_cnt)
114 9d95c3af Iustin Pop
    ToStdout("C:job    %4d" % job_cnt)
115 9d95c3af Iustin Pop
    ToStdout("T:submit %4.4f" % (t2-t1))
116 9d95c3af Iustin Pop
    ToStdout("T:exec   %4.4f" % (t3-t2))
117 9d95c3af Iustin Pop
    ToStdout("T:total  %4.4f" % (t3-t1))
118 f1c66d13 Iustin Pop
  return 0
119 f1c66d13 Iustin Pop
120 f1c66d13 Iustin Pop
121 d61df03e Iustin Pop
def TestAllocator(opts, args):
122 6099bfcf Iustin Pop
  """Runs the test allocator opcode.
123 d61df03e Iustin Pop

124 6099bfcf Iustin Pop
  @param opts: the command line options selected by the user
125 6099bfcf Iustin Pop
  @type args: list
126 6099bfcf Iustin Pop
  @param args: should contain only one element, the iallocator name
127 6099bfcf Iustin Pop
  @rtype: int
128 6099bfcf Iustin Pop
  @return: the desired exit code
129 6099bfcf Iustin Pop

130 6099bfcf Iustin Pop
  """
131 d61df03e Iustin Pop
  try:
132 fdbe29ee Michael Hanselmann
    disks = [{
133 fdbe29ee Michael Hanselmann
      constants.IDISK_SIZE: utils.ParseUnit(val),
134 fdbe29ee Michael Hanselmann
      constants.IDISK_MODE: constants.DISK_RDWR,
135 fdbe29ee Michael Hanselmann
      } for val in opts.disks.split(",")]
136 d61df03e Iustin Pop
  except errors.UnitParseError, err:
137 3a24c527 Iustin Pop
    ToStderr("Invalid disks parameter '%s': %s", opts.disks, err)
138 d61df03e Iustin Pop
    return 1
139 d61df03e Iustin Pop
140 d61df03e Iustin Pop
  nics = [val.split("/") for val in opts.nics.split(",")]
141 d61df03e Iustin Pop
  for row in nics:
142 d61df03e Iustin Pop
    while len(row) < 3:
143 d61df03e Iustin Pop
      row.append(None)
144 d61df03e Iustin Pop
    for i in range(3):
145 d61df03e Iustin Pop
      if row[i] == '':
146 d61df03e Iustin Pop
        row[i] = None
147 fdbe29ee Michael Hanselmann
  nic_dict = [{
148 fdbe29ee Michael Hanselmann
    constants.INIC_MAC: v[0],
149 fdbe29ee Michael Hanselmann
    constants.INIC_IP: v[1],
150 fdbe29ee Michael Hanselmann
    # The iallocator interface defines a "bridge" item
151 fdbe29ee Michael Hanselmann
    "bridge": v[2],
152 fdbe29ee Michael Hanselmann
    } for v in nics]
153 d61df03e Iustin Pop
154 d61df03e Iustin Pop
  if opts.tags is None:
155 d61df03e Iustin Pop
    opts.tags = []
156 d61df03e Iustin Pop
  else:
157 d61df03e Iustin Pop
    opts.tags = opts.tags.split(",")
158 d61df03e Iustin Pop
159 d61df03e Iustin Pop
  op = opcodes.OpTestAllocator(mode=opts.mode,
160 d61df03e Iustin Pop
                               name=args[0],
161 823a72bc Iustin Pop
                               evac_nodes=args,
162 42c161cf Michael Hanselmann
                               instances=args,
163 d61df03e Iustin Pop
                               mem_size=opts.mem,
164 d61df03e Iustin Pop
                               disks=disks,
165 d61df03e Iustin Pop
                               disk_template=opts.disk_template,
166 d61df03e Iustin Pop
                               nics=nic_dict,
167 705dd60e Iustin Pop
                               os=opts.os,
168 d61df03e Iustin Pop
                               vcpus=opts.vcpus,
169 d61df03e Iustin Pop
                               tags=opts.tags,
170 d61df03e Iustin Pop
                               direction=opts.direction,
171 705dd60e Iustin Pop
                               allocator=opts.iallocator,
172 42c161cf Michael Hanselmann
                               reloc_mode=opts.reloc_mode,
173 42c161cf Michael Hanselmann
                               target_groups=opts.target_groups)
174 400ca2f7 Iustin Pop
  result = SubmitOpCode(op, opts=opts)
175 3a24c527 Iustin Pop
  ToStdout("%s" % result)
176 d61df03e Iustin Pop
  return 0
177 d61df03e Iustin Pop
178 d61df03e Iustin Pop
179 92ae7daf Michael Hanselmann
def _TestJobSubmission(opts):
180 92ae7daf Michael Hanselmann
  """Tests submitting jobs.
181 92ae7daf Michael Hanselmann

182 92ae7daf Michael Hanselmann
  """
183 92ae7daf Michael Hanselmann
  ToStdout("Testing job submission")
184 92ae7daf Michael Hanselmann
185 92ae7daf Michael Hanselmann
  testdata = [
186 92ae7daf Michael Hanselmann
    (0, 0, constants.OP_PRIO_LOWEST),
187 92ae7daf Michael Hanselmann
    (0, 0, constants.OP_PRIO_HIGHEST),
188 92ae7daf Michael Hanselmann
    ]
189 92ae7daf Michael Hanselmann
190 92ae7daf Michael Hanselmann
  for priority in (constants.OP_PRIO_SUBMIT_VALID |
191 92ae7daf Michael Hanselmann
                   frozenset([constants.OP_PRIO_LOWEST,
192 92ae7daf Michael Hanselmann
                              constants.OP_PRIO_HIGHEST])):
193 92ae7daf Michael Hanselmann
    for offset in [-1, +1]:
194 92ae7daf Michael Hanselmann
      testdata.extend([
195 92ae7daf Michael Hanselmann
        (0, 0, priority + offset),
196 92ae7daf Michael Hanselmann
        (3, 0, priority + offset),
197 92ae7daf Michael Hanselmann
        (0, 3, priority + offset),
198 92ae7daf Michael Hanselmann
        (4, 2, priority + offset),
199 92ae7daf Michael Hanselmann
        ])
200 92ae7daf Michael Hanselmann
201 92ae7daf Michael Hanselmann
  cl = cli.GetClient()
202 92ae7daf Michael Hanselmann
203 92ae7daf Michael Hanselmann
  for before, after, failpriority in testdata:
204 92ae7daf Michael Hanselmann
    ops = []
205 92ae7daf Michael Hanselmann
    ops.extend([opcodes.OpTestDelay(duration=0) for _ in range(before)])
206 92ae7daf Michael Hanselmann
    ops.append(opcodes.OpTestDelay(duration=0, priority=failpriority))
207 92ae7daf Michael Hanselmann
    ops.extend([opcodes.OpTestDelay(duration=0) for _ in range(after)])
208 92ae7daf Michael Hanselmann
209 92ae7daf Michael Hanselmann
    try:
210 92ae7daf Michael Hanselmann
      cl.SubmitJob(ops)
211 92ae7daf Michael Hanselmann
    except errors.GenericError, err:
212 92ae7daf Michael Hanselmann
      if opts.debug:
213 92ae7daf Michael Hanselmann
        ToStdout("Ignoring error: %s", err)
214 92ae7daf Michael Hanselmann
    else:
215 92ae7daf Michael Hanselmann
      raise errors.OpExecError("Submitting opcode with priority %s did not"
216 92ae7daf Michael Hanselmann
                               " fail when it should (allowed are %s)" %
217 92ae7daf Michael Hanselmann
                               (failpriority, constants.OP_PRIO_SUBMIT_VALID))
218 92ae7daf Michael Hanselmann
219 92ae7daf Michael Hanselmann
    jobs = [
220 92ae7daf Michael Hanselmann
      [opcodes.OpTestDelay(duration=0),
221 92ae7daf Michael Hanselmann
       opcodes.OpTestDelay(duration=0, dry_run=False),
222 92ae7daf Michael Hanselmann
       opcodes.OpTestDelay(duration=0, dry_run=True)],
223 92ae7daf Michael Hanselmann
      ops,
224 92ae7daf Michael Hanselmann
      ]
225 92ae7daf Michael Hanselmann
    result = cl.SubmitManyJobs(jobs)
226 92ae7daf Michael Hanselmann
    if not (len(result) == 2 and
227 92ae7daf Michael Hanselmann
            compat.all(len(i) == 2 for i in result) and
228 92ae7daf Michael Hanselmann
            compat.all(isinstance(i[1], basestring) for i in result) and
229 92ae7daf Michael Hanselmann
            result[0][0] and not result[1][0]):
230 92ae7daf Michael Hanselmann
      raise errors.OpExecError("Submitting multiple jobs did not work as"
231 92ae7daf Michael Hanselmann
                               " expected, result %s" % result)
232 92ae7daf Michael Hanselmann
    assert len(result) == 2
233 92ae7daf Michael Hanselmann
234 92ae7daf Michael Hanselmann
  ToStdout("Job submission tests were successful")
235 92ae7daf Michael Hanselmann
236 92ae7daf Michael Hanselmann
237 e58f87a9 Michael Hanselmann
class _JobQueueTestReporter(cli.StdioJobPollReportCb):
238 e58f87a9 Michael Hanselmann
  def __init__(self):
239 e58f87a9 Michael Hanselmann
    """Initializes this class.
240 e58f87a9 Michael Hanselmann

241 e58f87a9 Michael Hanselmann
    """
242 e58f87a9 Michael Hanselmann
    cli.StdioJobPollReportCb.__init__(self)
243 f99010b2 Michael Hanselmann
    self._expected_msgcount = 0
244 f99010b2 Michael Hanselmann
    self._all_testmsgs = []
245 f99010b2 Michael Hanselmann
    self._testmsgs = None
246 e58f87a9 Michael Hanselmann
    self._job_id = None
247 e58f87a9 Michael Hanselmann
248 e58f87a9 Michael Hanselmann
  def GetTestMessages(self):
249 e58f87a9 Michael Hanselmann
    """Returns all test log messages received so far.
250 e58f87a9 Michael Hanselmann

251 e58f87a9 Michael Hanselmann
    """
252 f99010b2 Michael Hanselmann
    return self._all_testmsgs
253 e58f87a9 Michael Hanselmann
254 e58f87a9 Michael Hanselmann
  def GetJobId(self):
255 e58f87a9 Michael Hanselmann
    """Returns the job ID.
256 e58f87a9 Michael Hanselmann

257 e58f87a9 Michael Hanselmann
    """
258 e58f87a9 Michael Hanselmann
    return self._job_id
259 e58f87a9 Michael Hanselmann
260 e58f87a9 Michael Hanselmann
  def ReportLogMessage(self, job_id, serial, timestamp, log_type, log_msg):
261 e58f87a9 Michael Hanselmann
    """Handles a log message.
262 e58f87a9 Michael Hanselmann

263 e58f87a9 Michael Hanselmann
    """
264 e58f87a9 Michael Hanselmann
    if self._job_id is None:
265 e58f87a9 Michael Hanselmann
      self._job_id = job_id
266 e58f87a9 Michael Hanselmann
    elif self._job_id != job_id:
267 e58f87a9 Michael Hanselmann
      raise errors.ProgrammerError("The same reporter instance was used for"
268 e58f87a9 Michael Hanselmann
                                   " more than one job")
269 e58f87a9 Michael Hanselmann
270 e58f87a9 Michael Hanselmann
    if log_type == constants.ELOG_JQUEUE_TEST:
271 e58f87a9 Michael Hanselmann
      (sockname, test, arg) = log_msg
272 e58f87a9 Michael Hanselmann
      return self._ProcessTestMessage(job_id, sockname, test, arg)
273 e58f87a9 Michael Hanselmann
274 e58f87a9 Michael Hanselmann
    elif (log_type == constants.ELOG_MESSAGE and
275 e58f87a9 Michael Hanselmann
          log_msg.startswith(constants.JQT_MSGPREFIX)):
276 f99010b2 Michael Hanselmann
      if self._testmsgs is None:
277 f99010b2 Michael Hanselmann
        raise errors.OpExecError("Received test message without a preceding"
278 f99010b2 Michael Hanselmann
                                 " start message")
279 f99010b2 Michael Hanselmann
      testmsg = log_msg[len(constants.JQT_MSGPREFIX):]
280 f99010b2 Michael Hanselmann
      self._testmsgs.append(testmsg)
281 f99010b2 Michael Hanselmann
      self._all_testmsgs.append(testmsg)
282 e58f87a9 Michael Hanselmann
      return
283 e58f87a9 Michael Hanselmann
284 e58f87a9 Michael Hanselmann
    return cli.StdioJobPollReportCb.ReportLogMessage(self, job_id, serial,
285 e58f87a9 Michael Hanselmann
                                                     timestamp, log_type,
286 e58f87a9 Michael Hanselmann
                                                     log_msg)
287 e58f87a9 Michael Hanselmann
288 e58f87a9 Michael Hanselmann
  def _ProcessTestMessage(self, job_id, sockname, test, arg):
289 e58f87a9 Michael Hanselmann
    """Handles a job queue test message.
290 e58f87a9 Michael Hanselmann

291 e58f87a9 Michael Hanselmann
    """
292 e58f87a9 Michael Hanselmann
    if test not in constants.JQT_ALL:
293 e58f87a9 Michael Hanselmann
      raise errors.OpExecError("Received invalid test message %s" % test)
294 e58f87a9 Michael Hanselmann
295 e58f87a9 Michael Hanselmann
    sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
296 e58f87a9 Michael Hanselmann
    try:
297 e58f87a9 Michael Hanselmann
      sock.settimeout(30.0)
298 e58f87a9 Michael Hanselmann
299 e58f87a9 Michael Hanselmann
      logging.debug("Connecting to %s", sockname)
300 e58f87a9 Michael Hanselmann
      sock.connect(sockname)
301 e58f87a9 Michael Hanselmann
302 e58f87a9 Michael Hanselmann
      logging.debug("Checking status")
303 e58f87a9 Michael Hanselmann
      jobdetails = cli.GetClient().QueryJobs([job_id], ["status"])[0]
304 e58f87a9 Michael Hanselmann
      if not jobdetails:
305 e58f87a9 Michael Hanselmann
        raise errors.OpExecError("Can't find job %s" % job_id)
306 e58f87a9 Michael Hanselmann
307 e58f87a9 Michael Hanselmann
      status = jobdetails[0]
308 e58f87a9 Michael Hanselmann
309 e58f87a9 Michael Hanselmann
      logging.debug("Status of job %s is %s", job_id, status)
310 e58f87a9 Michael Hanselmann
311 e58f87a9 Michael Hanselmann
      if test == constants.JQT_EXPANDNAMES:
312 e58f87a9 Michael Hanselmann
        if status != constants.JOB_STATUS_WAITLOCK:
313 e58f87a9 Michael Hanselmann
          raise errors.OpExecError("Job status while expanding names is '%s',"
314 e58f87a9 Michael Hanselmann
                                   " not '%s' as expected" %
315 e58f87a9 Michael Hanselmann
                                   (status, constants.JOB_STATUS_WAITLOCK))
316 e58f87a9 Michael Hanselmann
      elif test in (constants.JQT_EXEC, constants.JQT_LOGMSG):
317 e58f87a9 Michael Hanselmann
        if status != constants.JOB_STATUS_RUNNING:
318 e58f87a9 Michael Hanselmann
          raise errors.OpExecError("Job status while executing opcode is '%s',"
319 e58f87a9 Michael Hanselmann
                                   " not '%s' as expected" %
320 e58f87a9 Michael Hanselmann
                                   (status, constants.JOB_STATUS_RUNNING))
321 e58f87a9 Michael Hanselmann
322 f99010b2 Michael Hanselmann
      if test == constants.JQT_STARTMSG:
323 f99010b2 Michael Hanselmann
        logging.debug("Expecting %s test messages", arg)
324 f99010b2 Michael Hanselmann
        self._testmsgs = []
325 f99010b2 Michael Hanselmann
      elif test == constants.JQT_LOGMSG:
326 e58f87a9 Michael Hanselmann
        if len(self._testmsgs) != arg:
327 e58f87a9 Michael Hanselmann
          raise errors.OpExecError("Received %s test messages when %s are"
328 e58f87a9 Michael Hanselmann
                                   " expected" % (len(self._testmsgs), arg))
329 e58f87a9 Michael Hanselmann
    finally:
330 e58f87a9 Michael Hanselmann
      logging.debug("Closing socket")
331 e58f87a9 Michael Hanselmann
      sock.close()
332 e58f87a9 Michael Hanselmann
333 e58f87a9 Michael Hanselmann
334 e58f87a9 Michael Hanselmann
def TestJobqueue(opts, _):
335 e58f87a9 Michael Hanselmann
  """Runs a few tests on the job queue.
336 e58f87a9 Michael Hanselmann

337 e58f87a9 Michael Hanselmann
  """
338 92ae7daf Michael Hanselmann
  _TestJobSubmission(opts)
339 92ae7daf Michael Hanselmann
340 f99010b2 Michael Hanselmann
  (TM_SUCCESS,
341 f99010b2 Michael Hanselmann
   TM_MULTISUCCESS,
342 f99010b2 Michael Hanselmann
   TM_FAIL,
343 f99010b2 Michael Hanselmann
   TM_PARTFAIL) = range(4)
344 f99010b2 Michael Hanselmann
  TM_ALL = frozenset([TM_SUCCESS, TM_MULTISUCCESS, TM_FAIL, TM_PARTFAIL])
345 f99010b2 Michael Hanselmann
346 f99010b2 Michael Hanselmann
  for mode in TM_ALL:
347 f99010b2 Michael Hanselmann
    test_messages = [
348 f99010b2 Michael Hanselmann
      "Testing mode %s" % mode,
349 f99010b2 Michael Hanselmann
      "Hello World",
350 f99010b2 Michael Hanselmann
      "A",
351 f99010b2 Michael Hanselmann
      "",
352 f99010b2 Michael Hanselmann
      "B"
353 f99010b2 Michael Hanselmann
      "Foo|bar|baz",
354 f99010b2 Michael Hanselmann
      utils.TimestampForFilename(),
355 f99010b2 Michael Hanselmann
      ]
356 f99010b2 Michael Hanselmann
357 f99010b2 Michael Hanselmann
    fail = mode in (TM_FAIL, TM_PARTFAIL)
358 f99010b2 Michael Hanselmann
359 f99010b2 Michael Hanselmann
    if mode == TM_PARTFAIL:
360 f99010b2 Michael Hanselmann
      ToStdout("Testing partial job failure")
361 f99010b2 Michael Hanselmann
      ops = [
362 b469eb4d Iustin Pop
        opcodes.OpTestJqueue(notify_waitlock=True, notify_exec=True,
363 b469eb4d Iustin Pop
                             log_messages=test_messages, fail=False),
364 b469eb4d Iustin Pop
        opcodes.OpTestJqueue(notify_waitlock=True, notify_exec=True,
365 b469eb4d Iustin Pop
                             log_messages=test_messages, fail=False),
366 b469eb4d Iustin Pop
        opcodes.OpTestJqueue(notify_waitlock=True, notify_exec=True,
367 b469eb4d Iustin Pop
                             log_messages=test_messages, fail=True),
368 b469eb4d Iustin Pop
        opcodes.OpTestJqueue(notify_waitlock=True, notify_exec=True,
369 b469eb4d Iustin Pop
                             log_messages=test_messages, fail=False),
370 f99010b2 Michael Hanselmann
        ]
371 f99010b2 Michael Hanselmann
      expect_messages = 3 * [test_messages]
372 f99010b2 Michael Hanselmann
      expect_opstatus = [
373 f99010b2 Michael Hanselmann
        constants.OP_STATUS_SUCCESS,
374 f99010b2 Michael Hanselmann
        constants.OP_STATUS_SUCCESS,
375 f99010b2 Michael Hanselmann
        constants.OP_STATUS_ERROR,
376 f99010b2 Michael Hanselmann
        constants.OP_STATUS_ERROR,
377 f99010b2 Michael Hanselmann
        ]
378 f99010b2 Michael Hanselmann
      expect_resultlen = 2
379 f99010b2 Michael Hanselmann
    elif mode == TM_MULTISUCCESS:
380 f99010b2 Michael Hanselmann
      ToStdout("Testing multiple successful opcodes")
381 f99010b2 Michael Hanselmann
      ops = [
382 b469eb4d Iustin Pop
        opcodes.OpTestJqueue(notify_waitlock=True, notify_exec=True,
383 b469eb4d Iustin Pop
                             log_messages=test_messages, fail=False),
384 b469eb4d Iustin Pop
        opcodes.OpTestJqueue(notify_waitlock=True, notify_exec=True,
385 b469eb4d Iustin Pop
                             log_messages=test_messages, fail=False),
386 f99010b2 Michael Hanselmann
        ]
387 f99010b2 Michael Hanselmann
      expect_messages = 2 * [test_messages]
388 f99010b2 Michael Hanselmann
      expect_opstatus = [
389 f99010b2 Michael Hanselmann
        constants.OP_STATUS_SUCCESS,
390 f99010b2 Michael Hanselmann
        constants.OP_STATUS_SUCCESS,
391 f99010b2 Michael Hanselmann
        ]
392 f99010b2 Michael Hanselmann
      expect_resultlen = 2
393 e58f87a9 Michael Hanselmann
    else:
394 f99010b2 Michael Hanselmann
      if mode == TM_SUCCESS:
395 f99010b2 Michael Hanselmann
        ToStdout("Testing job success")
396 f99010b2 Michael Hanselmann
        expect_opstatus = [constants.OP_STATUS_SUCCESS]
397 f99010b2 Michael Hanselmann
      elif mode == TM_FAIL:
398 f99010b2 Michael Hanselmann
        ToStdout("Testing job failure")
399 f99010b2 Michael Hanselmann
        expect_opstatus = [constants.OP_STATUS_ERROR]
400 f99010b2 Michael Hanselmann
      else:
401 f99010b2 Michael Hanselmann
        raise errors.ProgrammerError("Unknown test mode %s" % mode)
402 f99010b2 Michael Hanselmann
403 f99010b2 Michael Hanselmann
      ops = [
404 b469eb4d Iustin Pop
        opcodes.OpTestJqueue(notify_waitlock=True,
405 b469eb4d Iustin Pop
                             notify_exec=True,
406 b469eb4d Iustin Pop
                             log_messages=test_messages,
407 b469eb4d Iustin Pop
                             fail=fail)
408 f99010b2 Michael Hanselmann
        ]
409 f99010b2 Michael Hanselmann
      expect_messages = [test_messages]
410 f99010b2 Michael Hanselmann
      expect_resultlen = 1
411 f99010b2 Michael Hanselmann
412 f99010b2 Michael Hanselmann
    cl = cli.GetClient()
413 f99010b2 Michael Hanselmann
    cli.SetGenericOpcodeOpts(ops, opts)
414 f99010b2 Michael Hanselmann
415 f99010b2 Michael Hanselmann
    # Send job to master daemon
416 f99010b2 Michael Hanselmann
    job_id = cli.SendJob(ops, cl=cl)
417 e58f87a9 Michael Hanselmann
418 e58f87a9 Michael Hanselmann
    reporter = _JobQueueTestReporter()
419 f99010b2 Michael Hanselmann
    results = None
420 f99010b2 Michael Hanselmann
421 e58f87a9 Michael Hanselmann
    try:
422 f99010b2 Michael Hanselmann
      results = cli.PollJob(job_id, cl=cl, reporter=reporter)
423 f99010b2 Michael Hanselmann
    except errors.OpExecError, err:
424 e58f87a9 Michael Hanselmann
      if not fail:
425 e58f87a9 Michael Hanselmann
        raise
426 f99010b2 Michael Hanselmann
      ToStdout("Ignoring error: %s", err)
427 e58f87a9 Michael Hanselmann
    else:
428 e58f87a9 Michael Hanselmann
      if fail:
429 e58f87a9 Michael Hanselmann
        raise errors.OpExecError("Job didn't fail when it should")
430 e58f87a9 Michael Hanselmann
431 f99010b2 Michael Hanselmann
    # Check length of result
432 f99010b2 Michael Hanselmann
    if fail:
433 f99010b2 Michael Hanselmann
      if results is not None:
434 f99010b2 Michael Hanselmann
        raise errors.OpExecError("Received result from failed job")
435 f99010b2 Michael Hanselmann
    elif len(results) != expect_resultlen:
436 f99010b2 Michael Hanselmann
      raise errors.OpExecError("Received %s results (%s), expected %s" %
437 f99010b2 Michael Hanselmann
                               (len(results), results, expect_resultlen))
438 f99010b2 Michael Hanselmann
439 e58f87a9 Michael Hanselmann
    # Check received log messages
440 f99010b2 Michael Hanselmann
    all_messages = [i for j in expect_messages for i in j]
441 f99010b2 Michael Hanselmann
    if reporter.GetTestMessages() != all_messages:
442 e58f87a9 Michael Hanselmann
      raise errors.OpExecError("Received test messages don't match input"
443 e58f87a9 Michael Hanselmann
                               " (input %r, received %r)" %
444 f99010b2 Michael Hanselmann
                               (all_messages, reporter.GetTestMessages()))
445 e58f87a9 Michael Hanselmann
446 e58f87a9 Michael Hanselmann
    # Check final status
447 f99010b2 Michael Hanselmann
    reported_job_id = reporter.GetJobId()
448 f99010b2 Michael Hanselmann
    if reported_job_id != job_id:
449 f99010b2 Michael Hanselmann
      raise errors.OpExecError("Reported job ID %s doesn't match"
450 f99010b2 Michael Hanselmann
                               "submission job ID %s" %
451 f99010b2 Michael Hanselmann
                               (reported_job_id, job_id))
452 e58f87a9 Michael Hanselmann
453 f99010b2 Michael Hanselmann
    jobdetails = cli.GetClient().QueryJobs([job_id], ["status", "opstatus"])[0]
454 e58f87a9 Michael Hanselmann
    if not jobdetails:
455 e58f87a9 Michael Hanselmann
      raise errors.OpExecError("Can't find job %s" % job_id)
456 e58f87a9 Michael Hanselmann
457 e58f87a9 Michael Hanselmann
    if fail:
458 e58f87a9 Michael Hanselmann
      exp_status = constants.JOB_STATUS_ERROR
459 e58f87a9 Michael Hanselmann
    else:
460 e58f87a9 Michael Hanselmann
      exp_status = constants.JOB_STATUS_SUCCESS
461 e58f87a9 Michael Hanselmann
462 f99010b2 Michael Hanselmann
    (final_status, final_opstatus) = jobdetails
463 e58f87a9 Michael Hanselmann
    if final_status != exp_status:
464 e58f87a9 Michael Hanselmann
      raise errors.OpExecError("Final job status is %s, not %s as expected" %
465 e58f87a9 Michael Hanselmann
                               (final_status, exp_status))
466 f99010b2 Michael Hanselmann
    if len(final_opstatus) != len(ops):
467 f99010b2 Michael Hanselmann
      raise errors.OpExecError("Did not receive status for all opcodes (got %s,"
468 f99010b2 Michael Hanselmann
                               " expected %s)" %
469 f99010b2 Michael Hanselmann
                               (len(final_opstatus), len(ops)))
470 f99010b2 Michael Hanselmann
    if final_opstatus != expect_opstatus:
471 f99010b2 Michael Hanselmann
      raise errors.OpExecError("Opcode status is %s, expected %s" %
472 f99010b2 Michael Hanselmann
                               (final_opstatus, expect_opstatus))
473 f99010b2 Michael Hanselmann
474 f99010b2 Michael Hanselmann
  ToStdout("Job queue test successful")
475 e58f87a9 Michael Hanselmann
476 e58f87a9 Michael Hanselmann
  return 0
477 e58f87a9 Michael Hanselmann
478 e58f87a9 Michael Hanselmann
479 19b9ba9a Michael Hanselmann
def ListLocks(opts, args): # pylint: disable-msg=W0613
480 19b9ba9a Michael Hanselmann
  """List all locks.
481 19b9ba9a Michael Hanselmann

482 19b9ba9a Michael Hanselmann
  @param opts: the command line options selected by the user
483 19b9ba9a Michael Hanselmann
  @type args: list
484 19b9ba9a Michael Hanselmann
  @param args: should be an empty list
485 19b9ba9a Michael Hanselmann
  @rtype: int
486 19b9ba9a Michael Hanselmann
  @return: the desired exit code
487 19b9ba9a Michael Hanselmann

488 19b9ba9a Michael Hanselmann
  """
489 19b9ba9a Michael Hanselmann
  selected_fields = ParseFields(opts.output, _LIST_LOCKS_DEF_FIELDS)
490 19b9ba9a Michael Hanselmann
491 24d16f76 Michael Hanselmann
  def _DashIfNone(fn):
492 24d16f76 Michael Hanselmann
    def wrapper(value):
493 24d16f76 Michael Hanselmann
      if not value:
494 24d16f76 Michael Hanselmann
        return "-"
495 24d16f76 Michael Hanselmann
      return fn(value)
496 24d16f76 Michael Hanselmann
    return wrapper
497 24d16f76 Michael Hanselmann
498 24d16f76 Michael Hanselmann
  def _FormatPending(value):
499 24d16f76 Michael Hanselmann
    """Format pending acquires.
500 24d16f76 Michael Hanselmann

501 24d16f76 Michael Hanselmann
    """
502 24d16f76 Michael Hanselmann
    return utils.CommaJoin("%s:%s" % (mode, ",".join(threads))
503 24d16f76 Michael Hanselmann
                           for mode, threads in value)
504 24d16f76 Michael Hanselmann
505 24d16f76 Michael Hanselmann
  # Format raw values
506 24d16f76 Michael Hanselmann
  fmtoverride = {
507 24d16f76 Michael Hanselmann
    "mode": (_DashIfNone(str), False),
508 24d16f76 Michael Hanselmann
    "owner": (_DashIfNone(",".join), False),
509 24d16f76 Michael Hanselmann
    "pending": (_DashIfNone(_FormatPending), False),
510 24d16f76 Michael Hanselmann
    }
511 19b9ba9a Michael Hanselmann
512 19b9ba9a Michael Hanselmann
  while True:
513 24d16f76 Michael Hanselmann
    ret = GenericList(constants.QR_LOCK, selected_fields, None, None,
514 24d16f76 Michael Hanselmann
                      opts.separator, not opts.no_headers,
515 f0b1bafe Iustin Pop
                      format_override=fmtoverride, verbose=opts.verbose)
516 24d16f76 Michael Hanselmann
517 24d16f76 Michael Hanselmann
    if ret != constants.EXIT_SUCCESS:
518 24d16f76 Michael Hanselmann
      return ret
519 19b9ba9a Michael Hanselmann
520 19b9ba9a Michael Hanselmann
    if not opts.interval:
521 19b9ba9a Michael Hanselmann
      break
522 19b9ba9a Michael Hanselmann
523 19b9ba9a Michael Hanselmann
    ToStdout("")
524 19b9ba9a Michael Hanselmann
    time.sleep(opts.interval)
525 19b9ba9a Michael Hanselmann
526 19b9ba9a Michael Hanselmann
  return 0
527 19b9ba9a Michael Hanselmann
528 19b9ba9a Michael Hanselmann
529 fd3ee040 Iustin Pop
commands = {
530 6ea815cf Iustin Pop
  'delay': (
531 6ea815cf Iustin Pop
    Delay, [ArgUnknown(min=1, max=1)],
532 064c21f8 Iustin Pop
    [cli_option("--no-master", dest="on_master", default=True,
533 6ea815cf Iustin Pop
                action="store_false", help="Do not sleep in the master code"),
534 6ea815cf Iustin Pop
     cli_option("-n", dest="on_nodes", default=[],
535 6ea815cf Iustin Pop
                action="append", help="Select nodes to sleep on"),
536 85a87e21 Guido Trotter
     cli_option("-r", "--repeat", type="int", default="0", dest="repeat",
537 85a87e21 Guido Trotter
                help="Number of times to repeat the sleep"),
538 aa06f8c6 Michael Hanselmann
     DRY_RUN_OPT, PRIORITY_OPT,
539 6ea815cf Iustin Pop
     ],
540 6ea815cf Iustin Pop
    "[opts...] <duration>", "Executes a TestDelay OpCode"),
541 6ea815cf Iustin Pop
  'submit-job': (
542 6ea815cf Iustin Pop
    GenericOpCodes, [ArgFile(min=1)],
543 064c21f8 Iustin Pop
    [VERBOSE_OPT,
544 6ea815cf Iustin Pop
     cli_option("--op-repeat", type="int", default="1", dest="rep_op",
545 6ea815cf Iustin Pop
                help="Repeat the opcode sequence this number of times"),
546 6ea815cf Iustin Pop
     cli_option("--job-repeat", type="int", default="1", dest="rep_job",
547 6ea815cf Iustin Pop
                help="Repeat the job this number of times"),
548 6ea815cf Iustin Pop
     cli_option("--timing-stats", default=False,
549 6ea815cf Iustin Pop
                action="store_true", help="Show timing stats"),
550 66ecc479 Guido Trotter
     cli_option("--each", default=False, action="store_true",
551 66ecc479 Guido Trotter
                help="Submit each job separately"),
552 aa06f8c6 Michael Hanselmann
     DRY_RUN_OPT, PRIORITY_OPT,
553 6ea815cf Iustin Pop
     ],
554 6ea815cf Iustin Pop
    "<op_list_file...>", "Submits jobs built from json files"
555 6ea815cf Iustin Pop
    " containing a list of serialized opcodes"),
556 3f1e065d Iustin Pop
  'iallocator': (
557 823a72bc Iustin Pop
    TestAllocator, [ArgUnknown(min=1)],
558 9133387e Michael Hanselmann
    [cli_option("--dir", dest="direction", default=constants.IALLOCATOR_DIR_IN,
559 9133387e Michael Hanselmann
                choices=list(constants.VALID_IALLOCATOR_DIRECTIONS),
560 6ea815cf Iustin Pop
                help="Show allocator input (in) or allocator"
561 6ea815cf Iustin Pop
                " results (out)"),
562 6ea815cf Iustin Pop
     IALLOCATOR_OPT,
563 6ea815cf Iustin Pop
     cli_option("-m", "--mode", default="relocate",
564 42c161cf Michael Hanselmann
                choices=list(constants.VALID_IALLOCATOR_MODES),
565 42c161cf Michael Hanselmann
                help=("Request mode (one of %s)" %
566 42c161cf Michael Hanselmann
                      utils.CommaJoin(constants.VALID_IALLOCATOR_MODES))),
567 6ea815cf Iustin Pop
     cli_option("--mem", default=128, type="unit",
568 6ea815cf Iustin Pop
                help="Memory size for the instance (MiB)"),
569 6ea815cf Iustin Pop
     cli_option("--disks", default="4096,4096",
570 6ea815cf Iustin Pop
                help="Comma separated list of disk sizes (MiB)"),
571 6ea815cf Iustin Pop
     DISK_TEMPLATE_OPT,
572 6ea815cf Iustin Pop
     cli_option("--nics", default="00:11:22:33:44:55",
573 6ea815cf Iustin Pop
                help="Comma separated list of nics, each nic"
574 6ea815cf Iustin Pop
                " definition is of form mac/ip/bridge, if"
575 6ea815cf Iustin Pop
                " missing values are replace by None"),
576 6ea815cf Iustin Pop
     OS_OPT,
577 6ea815cf Iustin Pop
     cli_option("-p", "--vcpus", default=1, type="int",
578 6ea815cf Iustin Pop
                help="Select number of VCPUs for the instance"),
579 6ea815cf Iustin Pop
     cli_option("--tags", default=None,
580 6ea815cf Iustin Pop
                help="Comma separated list of tags"),
581 42c161cf Michael Hanselmann
     cli_option("--reloc-mode", default=constants.IALLOCATOR_MRELOC_ANY,
582 42c161cf Michael Hanselmann
                choices=list(constants.IALLOCATOR_MRELOC_MODES),
583 42c161cf Michael Hanselmann
                help=("Instance relocation mode (one of %s)" %
584 42c161cf Michael Hanselmann
                      utils.CommaJoin(constants.IALLOCATOR_MRELOC_MODES))),
585 42c161cf Michael Hanselmann
     cli_option("--target-groups", help="Target groups for relocation"),
586 aa06f8c6 Michael Hanselmann
     DRY_RUN_OPT, PRIORITY_OPT,
587 6ea815cf Iustin Pop
     ],
588 6ea815cf Iustin Pop
    "{opts...} <instance>", "Executes a TestAllocator OpCode"),
589 e58f87a9 Michael Hanselmann
  "test-jobqueue": (
590 aa06f8c6 Michael Hanselmann
    TestJobqueue, ARGS_NONE, [PRIORITY_OPT],
591 19b9ba9a Michael Hanselmann
    "", "Test a few aspects of the job queue"),
592 19b9ba9a Michael Hanselmann
  "locks": (
593 f0b1bafe Iustin Pop
    ListLocks, ARGS_NONE,
594 f0b1bafe Iustin Pop
    [NOHDR_OPT, SEP_OPT, FIELDS_OPT, INTERVAL_OPT, VERBOSE_OPT],
595 19b9ba9a Michael Hanselmann
    "[--interval N]", "Show a list of locks in the master daemon"),
596 fd3ee040 Iustin Pop
  }
597 fd3ee040 Iustin Pop
598 3f1e065d Iustin Pop
#: dictionary with aliases for commands
599 3f1e065d Iustin Pop
aliases = {
600 3f1e065d Iustin Pop
  "allocator": "iallocator",
601 3f1e065d Iustin Pop
  }
602 fd3ee040 Iustin Pop
603 c2855a12 Michael Hanselmann
def Main():
604 3f1e065d Iustin Pop
  return GenericMain(commands, aliases=aliases)