qa_utils.py 13.4 KB
Newer Older
1 2 3
#
#

4
# Copyright (C) 2007, 2011 Google Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.


"""Utilities for QA tests.

"""

import os
27
import re
Michael Hanselmann's avatar
Michael Hanselmann committed
28
import sys
29
import subprocess
30
import random
31
import tempfile
32 33

from ganeti import utils
34
from ganeti import compat
35
from ganeti import constants
36 37 38 39 40

import qa_config
import qa_error


Michael Hanselmann's avatar
Michael Hanselmann committed
41 42 43 44 45
_INFO_SEQ = None
_WARNING_SEQ = None
_ERROR_SEQ = None
_RESET_SEQ = None

46 47
_MULTIPLEXERS = {}

Michael Hanselmann's avatar
Michael Hanselmann committed
48 49 50 51 52

def _SetupColours():
  """Initializes the colour constants.

  """
53
  # pylint: disable=W0603
Iustin Pop's avatar
Iustin Pop committed
54
  # due to global usage
Michael Hanselmann's avatar
Michael Hanselmann committed
55 56
  global _INFO_SEQ, _WARNING_SEQ, _ERROR_SEQ, _RESET_SEQ

57 58 59 60
  # Don't use colours if stdout isn't a terminal
  if not sys.stdout.isatty():
    return

Michael Hanselmann's avatar
Michael Hanselmann committed
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
  try:
    import curses
  except ImportError:
    # Don't use colours if curses module can't be imported
    return

  curses.setupterm()

  _RESET_SEQ = curses.tigetstr("op")

  setaf = curses.tigetstr("setaf")
  _INFO_SEQ = curses.tparm(setaf, curses.COLOR_GREEN)
  _WARNING_SEQ = curses.tparm(setaf, curses.COLOR_YELLOW)
  _ERROR_SEQ = curses.tparm(setaf, curses.COLOR_RED)


_SetupColours()


80 81 82 83 84
def AssertIn(item, sequence):
  """Raises an error when item is not in sequence.

  """
  if item not in sequence:
Iustin Pop's avatar
Iustin Pop committed
85
    raise qa_error.Error("%r not in %r" % (item, sequence))
86 87


88 89 90 91 92
def AssertNotIn(item, sequence):
  """Raises an error when item is in sequence.

  """
  if item in sequence:
Iustin Pop's avatar
Iustin Pop committed
93
    raise qa_error.Error("%r in %r" % (item, sequence))
94 95


96
def AssertEqual(first, second):
97 98 99 100
  """Raises an error when values aren't equal.

  """
  if not first == second:
Iustin Pop's avatar
Iustin Pop committed
101
    raise qa_error.Error("%r == %r" % (first, second))
102 103 104 105 106 107 108


def AssertNotEqual(first, second):
  """Raises an error when values are equal.

  """
  if not first != second:
Iustin Pop's avatar
Iustin Pop committed
109
    raise qa_error.Error("%r != %r" % (first, second))
110 111


112 113 114 115 116 117 118 119
def AssertMatch(string, pattern):
  """Raises an error when string doesn't match regexp pattern.

  """
  if not re.match(pattern, string):
    raise qa_error.Error("%r doesn't match /%r/" % (string, pattern))


Iustin Pop's avatar
Iustin Pop committed
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
def AssertCommand(cmd, fail=False, node=None):
  """Checks that a remote command succeeds.

  @param cmd: either a string (the command to execute) or a list (to
      be converted using L{utils.ShellQuoteArgs} into a string)
  @type fail: boolean
  @param fail: if the command is expected to fail instead of succeeding
  @param node: if passed, it should be the node on which the command
      should be executed, instead of the master node (can be either a
      dict or a string)

  """
  if node is None:
    node = qa_config.GetMasterNode()

  if isinstance(node, basestring):
    nodename = node
  else:
    nodename = node["primary"]

  if isinstance(cmd, basestring):
    cmdstr = cmd
  else:
    cmdstr = utils.ShellQuoteArgs(cmd)

  rcode = StartSSH(nodename, cmdstr).wait()

  if fail:
    if rcode == 0:
      raise qa_error.Error("Command '%s' on node %s was expected to fail but"
                           " didn't" % (cmdstr, nodename))
  else:
    if rcode != 0:
      raise qa_error.Error("Command '%s' on node %s failed, exit code %s" %
                           (cmdstr, nodename, rcode))

156 157
  return rcode

Iustin Pop's avatar
Iustin Pop committed
158

159
def GetSSHCommand(node, cmd, strict=True, opts=None, tty=True):
160 161
  """Builds SSH command to be executed.

162 163 164
  @type node: string
  @param node: node the command should run on
  @type cmd: string
165 166
  @param cmd: command to be executed in the node; if None or empty
      string, no command will be executed
167 168
  @type strict: boolean
  @param strict: whether to enable strict host key checking
169 170
  @type opts: list
  @param opts: list of additional options
171 172
  @type tty: Bool
  @param tty: If we should use tty
173

174
  """
175 176 177 178
  args = ["ssh", "-oEscapeChar=none", "-oBatchMode=yes", "-l", "root"]

  if tty:
    args.append("-t")
179 180

  if strict:
Iustin Pop's avatar
Iustin Pop committed
181
    tmp = "yes"
182
  else:
Iustin Pop's avatar
Iustin Pop committed
183 184 185 186
    tmp = "no"
  args.append("-oStrictHostKeyChecking=%s" % tmp)
  args.append("-oClearAllForwardings=yes")
  args.append("-oForwardAgent=yes")
187 188 189 190
  if opts:
    args.extend(opts)
  if node in _MULTIPLEXERS:
    spath = _MULTIPLEXERS[node][0]
Iustin Pop's avatar
Iustin Pop committed
191 192
    args.append("-oControlPath=%s" % spath)
    args.append("-oControlMaster=no")
193
  args.append(node)
194 195
  if cmd:
    args.append(cmd)
196 197 198 199

  return args


200 201 202 203 204 205 206 207
def StartLocalCommand(cmd, **kwargs):
  """Starts a local command.

  """
  print "Command: %s" % utils.ShellQuoteArgs(cmd)
  return subprocess.Popen(cmd, shell=False, **kwargs)


208 209 210 211
def StartSSH(node, cmd, strict=True):
  """Starts SSH.

  """
212
  return StartLocalCommand(GetSSHCommand(node, cmd, strict=strict))
213 214


215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
def StartMultiplexer(node):
  """Starts a multiplexer command.

  @param node: the node for which to open the multiplexer

  """
  if node in _MULTIPLEXERS:
    return

  # Note: yes, we only need mktemp, since we'll remove the file anyway
  sname = tempfile.mktemp(prefix="ganeti-qa-multiplexer.")
  utils.RemoveFile(sname)
  opts = ["-N", "-oControlPath=%s" % sname, "-oControlMaster=yes"]
  print "Created socket at %s" % sname
  child = StartLocalCommand(GetSSHCommand(node, None, opts=opts))
  _MULTIPLEXERS[node] = (sname, child)


def CloseMultiplexers():
  """Closes all current multiplexers and cleans up.

  """
  for node in _MULTIPLEXERS.keys():
    (sname, child) = _MULTIPLEXERS.pop(node)
    utils.KillProcess(child.pid, timeout=10, waitpid=True)
    utils.RemoveFile(sname)


243
def GetCommandOutput(node, cmd, tty=True):
244 245 246
  """Returns the output of a command executed on the given node.

  """
247 248
  p = StartLocalCommand(GetSSHCommand(node, cmd, tty=tty),
                        stdout=subprocess.PIPE)
249 250
  AssertEqual(p.wait(), 0)
  return p.stdout.read()
251 252 253 254 255 256 257


def UploadFile(node, src):
  """Uploads a file to a node and returns the filename.

  Caller needs to remove the returned file on the node when it's not needed
  anymore.
258

259 260 261 262 263 264 265 266 267
  """
  # Make sure nobody else has access to it while preserving local permissions
  mode = os.stat(src).st_mode & 0700

  cmd = ('tmp=$(tempfile --mode %o --prefix gnt) && '
         '[[ -f "${tmp}" ]] && '
         'cat > "${tmp}" && '
         'echo "${tmp}"') % mode

Iustin Pop's avatar
Iustin Pop committed
268
  f = open(src, "r")
269 270 271 272 273 274 275 276 277
  try:
    p = subprocess.Popen(GetSSHCommand(node, cmd), shell=False, stdin=f,
                         stdout=subprocess.PIPE)
    AssertEqual(p.wait(), 0)

    # Return temporary filename
    return p.stdout.read().strip()
  finally:
    f.close()
Michael Hanselmann's avatar
Michael Hanselmann committed
278 279


280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
def UploadData(node, data, mode=0600, filename=None):
  """Uploads data to a node and returns the filename.

  Caller needs to remove the returned file on the node when it's not needed
  anymore.

  """
  if filename:
    tmp = "tmp=%s" % utils.ShellQuote(filename)
  else:
    tmp = "tmp=$(tempfile --mode %o --prefix gnt)" % mode
  cmd = ("%s && "
         "[[ -f \"${tmp}\" ]] && "
         "cat > \"${tmp}\" && "
         "echo \"${tmp}\"") % tmp

  p = subprocess.Popen(GetSSHCommand(node, cmd), shell=False,
                       stdin=subprocess.PIPE, stdout=subprocess.PIPE)
  p.stdin.write(data)
  p.stdin.close()
  AssertEqual(p.wait(), 0)

  # Return temporary filename
  return p.stdout.read().strip()


306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
def BackupFile(node, path):
  """Creates a backup of a file on the node and returns the filename.

  Caller needs to remove the returned file on the node when it's not needed
  anymore.

  """
  cmd = ("tmp=$(tempfile --prefix .gnt --directory=$(dirname %s)) && "
         "[[ -f \"$tmp\" ]] && "
         "cp %s $tmp && "
         "echo $tmp") % (utils.ShellQuote(path), utils.ShellQuote(path))

  # Return temporary filename
  return GetCommandOutput(node, cmd).strip()


322 323 324 325 326 327
def _ResolveName(cmd, key):
  """Helper function.

  """
  master = qa_config.GetMasterNode()

Iustin Pop's avatar
Iustin Pop committed
328
  output = GetCommandOutput(master["primary"], utils.ShellQuoteArgs(cmd))
329
  for line in output.splitlines():
Iustin Pop's avatar
Iustin Pop committed
330
    (lkey, lvalue) = line.split(":", 1)
331 332 333 334 335
    if lkey == key:
      return lvalue.lstrip()
  raise KeyError("Key not found")


Michael Hanselmann's avatar
Michael Hanselmann committed
336 337 338
def ResolveInstanceName(instance):
  """Gets the full name of an instance.

339 340 341
  @type instance: string
  @param instance: Instance name

342
  """
Iustin Pop's avatar
Iustin Pop committed
343 344
  return _ResolveName(["gnt-instance", "info", instance],
                      "Instance name")
345 346 347 348 349 350


def ResolveNodeName(node):
  """Gets the full name of a node.

  """
Iustin Pop's avatar
Iustin Pop committed
351 352
  return _ResolveName(["gnt-node", "info", node["primary"]],
                      "Node name")
353 354 355 356 357


def GetNodeInstances(node, secondaries=False):
  """Gets a list of instances on a node.

Michael Hanselmann's avatar
Michael Hanselmann committed
358 359
  """
  master = qa_config.GetMasterNode()
360
  node_name = ResolveNodeName(node)
Michael Hanselmann's avatar
Michael Hanselmann committed
361

362
  # Get list of all instances
Iustin Pop's avatar
Iustin Pop committed
363 364 365
  cmd = ["gnt-instance", "list", "--separator=:", "--no-headers",
         "--output=name,pnode,snodes"]
  output = GetCommandOutput(master["primary"], utils.ShellQuoteArgs(cmd))
366 367 368

  instances = []
  for line in output.splitlines():
Iustin Pop's avatar
Iustin Pop committed
369
    (name, pnode, snodes) = line.split(":", 2)
370
    if ((not secondaries and pnode == node_name) or
Iustin Pop's avatar
Iustin Pop committed
371
        (secondaries and node_name in snodes.split(","))):
372
      instances.append(name)
Michael Hanselmann's avatar
Michael Hanselmann committed
373

374
  return instances
Michael Hanselmann's avatar
Michael Hanselmann committed
375 376


377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
def _SelectQueryFields(rnd, fields):
  """Generates a list of fields for query tests.

  """
  # Create copy for shuffling
  fields = list(fields)
  rnd.shuffle(fields)

  # Check all fields
  yield fields
  yield sorted(fields)

  # Duplicate fields
  yield fields + fields

  # Check small groups of fields
  while fields:
    yield [fields.pop() for _ in range(rnd.randint(2, 10)) if fields]


def _List(listcmd, fields, names):
  """Runs a list command.

  """
  master = qa_config.GetMasterNode()

403
  cmd = [listcmd, "list", "--separator=|", "--no-headers",
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
         "--output", ",".join(fields)]

  if names:
    cmd.extend(names)

  return GetCommandOutput(master["primary"],
                          utils.ShellQuoteArgs(cmd)).splitlines()


def GenericQueryTest(cmd, fields):
  """Runs a number of tests on query commands.

  @param cmd: Command name
  @param fields: List of field names

  """
  rnd = random.Random(hash(cmd))

Iustin Pop's avatar
Iustin Pop committed
422
  fields = list(fields)
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
  rnd.shuffle(fields)

  # Test a number of field combinations
  for testfields in _SelectQueryFields(rnd, fields):
    AssertCommand([cmd, "list", "--output", ",".join(testfields)])

  namelist_fn = compat.partial(_List, cmd, ["name"])

  # When no names were requested, the list must be sorted
  names = namelist_fn(None)
  AssertEqual(names, utils.NiceSort(names))

  # When requesting specific names, the order must be kept
  revnames = list(reversed(names))
  AssertEqual(namelist_fn(revnames), revnames)

  randnames = list(names)
  rnd.shuffle(randnames)
  AssertEqual(namelist_fn(randnames), randnames)

443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
  # Listing unknown items must fail
  AssertCommand([cmd, "list", "this.name.certainly.does.not.exist"], fail=True)

  # Check exit code for listing unknown field
  AssertEqual(AssertCommand([cmd, "list", "--output=field/does/not/exist"],
                            fail=True),
              constants.EXIT_UNKNOWN_FIELD)


def GenericQueryFieldsTest(cmd, fields):
  master = qa_config.GetMasterNode()

  # Listing fields
  AssertCommand([cmd, "list-fields"])
  AssertCommand([cmd, "list-fields"] + fields)

  # Check listed fields (all, must be sorted)
  realcmd = [cmd, "list-fields", "--separator=|", "--no-headers"]
  output = GetCommandOutput(master["primary"],
                            utils.ShellQuoteArgs(realcmd)).splitlines()
  AssertEqual([line.split("|", 1)[0] for line in output],
464
              utils.NiceSort(fields))
465 466 467 468 469 470

  # Check exit code for listing unknown field
  AssertEqual(AssertCommand([cmd, "list-fields", "field/does/not/exist"],
                            fail=True),
              constants.EXIT_UNKNOWN_FIELD)

471

472 473 474 475
def _FormatWithColor(text, seq):
  if not seq:
    return text
  return "%s%s%s" % (seq, text, _RESET_SEQ)
Michael Hanselmann's avatar
Michael Hanselmann committed
476 477


478 479 480
FormatWarning = lambda text: _FormatWithColor(text, _WARNING_SEQ)
FormatError = lambda text: _FormatWithColor(text, _ERROR_SEQ)
FormatInfo = lambda text: _FormatWithColor(text, _INFO_SEQ)
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521


def AddToEtcHosts(hostnames):
  """Adds hostnames to /etc/hosts.

  @param hostnames: List of hostnames first used A records, all other CNAMEs

  """
  master = qa_config.GetMasterNode()
  tmp_hosts = UploadData(master["primary"], "", mode=0644)

  quoted_tmp_hosts = utils.ShellQuote(tmp_hosts)
  data = []
  for localhost in ("::1", "127.0.0.1"):
    data.append("%s %s" % (localhost, " ".join(hostnames)))

  try:
    AssertCommand(("cat /etc/hosts > %s && echo -e '%s' >> %s && mv %s"
                   " /etc/hosts") % (quoted_tmp_hosts, "\\n".join(data),
                                     quoted_tmp_hosts, quoted_tmp_hosts))
  except qa_error.Error:
    AssertCommand(["rm", tmp_hosts])


def RemoveFromEtcHosts(hostnames):
  """Remove hostnames from /etc/hosts.

  @param hostnames: List of hostnames first used A records, all other CNAMEs

  """
  master = qa_config.GetMasterNode()
  tmp_hosts = UploadData(master["primary"], "", mode=0644)
  quoted_tmp_hosts = utils.ShellQuote(tmp_hosts)

  sed_data = " ".join(hostnames)
  try:
    AssertCommand(("sed -e '/^\(::1\|127\.0\.0\.1\)\s\+%s/d' /etc/hosts > %s"
                   " && mv %s /etc/hosts") % (sed_data, quoted_tmp_hosts,
                                              quoted_tmp_hosts))
  except qa_error.Error:
    AssertCommand(["rm", tmp_hosts])