4 # Copyright (C) 2007, 2011, 2012 Google Inc.
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.
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.
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
22 """Utilities for QA tests.
35 except ImportError, err:
36 raise ImportError("Python 2.5 or higher is required: %s" % err)
38 from ganeti import utils
39 from ganeti import compat
40 from ganeti import constants
54 #: Unique ID per QA run
55 _RUN_UUID = utils.NewUUID()
59 INST_UP) = range(500, 502)
62 RETURN_VALUE) = range(1000, 1002)
66 """Initializes the colour constants.
69 # pylint: disable=W0603
71 global _INFO_SEQ, _WARNING_SEQ, _ERROR_SEQ, _RESET_SEQ
73 # Don't use colours if stdout isn't a terminal
74 if not sys.stdout.isatty():
80 # Don't use colours if curses module can't be imported
85 _RESET_SEQ = curses.tigetstr("op")
87 setaf = curses.tigetstr("setaf")
88 _INFO_SEQ = curses.tparm(setaf, curses.COLOR_GREEN)
89 _WARNING_SEQ = curses.tparm(setaf, curses.COLOR_YELLOW)
90 _ERROR_SEQ = curses.tparm(setaf, curses.COLOR_RED)
96 def AssertIn(item, sequence):
97 """Raises an error when item is not in sequence.
100 if item not in sequence:
101 raise qa_error.Error("%r not in %r" % (item, sequence))
104 def AssertNotIn(item, sequence):
105 """Raises an error when item is in sequence.
109 raise qa_error.Error("%r in %r" % (item, sequence))
112 def AssertEqual(first, second):
113 """Raises an error when values aren't equal.
116 if not first == second:
117 raise qa_error.Error("%r == %r" % (first, second))
120 def AssertNotEqual(first, second):
121 """Raises an error when values are equal.
124 if not first != second:
125 raise qa_error.Error("%r != %r" % (first, second))
128 def AssertMatch(string, pattern):
129 """Raises an error when string doesn't match regexp pattern.
132 if not re.match(pattern, string):
133 raise qa_error.Error("%r doesn't match /%r/" % (string, pattern))
136 def _GetName(entity, key):
137 """Tries to get name of an entity.
139 @type entity: string or dict
141 @param key: Dictionary key containing name
144 if isinstance(entity, basestring):
146 elif isinstance(entity, dict):
149 raise qa_error.Error("Expected string or dictionary, got %s: %s" %
150 (type(entity), entity))
152 if not ht.TNonEmptyString(result):
153 raise Exception("Invalid name '%s'" % result)
158 def AssertCommand(cmd, fail=False, node=None):
159 """Checks that a remote command succeeds.
161 @param cmd: either a string (the command to execute) or a list (to
162 be converted using L{utils.ShellQuoteArgs} into a string)
164 @param fail: if the command is expected to fail instead of succeeding
165 @param node: if passed, it should be the node on which the command
166 should be executed, instead of the master node (can be either a
171 node = qa_config.GetMasterNode()
173 nodename = _GetName(node, "primary")
175 if isinstance(cmd, basestring):
178 cmdstr = utils.ShellQuoteArgs(cmd)
180 rcode = StartSSH(nodename, cmdstr).wait()
184 raise qa_error.Error("Command '%s' on node %s was expected to fail but"
185 " didn't" % (cmdstr, nodename))
188 raise qa_error.Error("Command '%s' on node %s failed, exit code %s" %
189 (cmdstr, nodename, rcode))
194 def GetSSHCommand(node, cmd, strict=True, opts=None, tty=None):
195 """Builds SSH command to be executed.
198 @param node: node the command should run on
200 @param cmd: command to be executed in the node; if None or empty
201 string, no command will be executed
202 @type strict: boolean
203 @param strict: whether to enable strict host key checking
205 @param opts: list of additional options
206 @type tty: boolean or None
207 @param tty: if we should use tty; if None, will be auto-detected
210 args = ["ssh", "-oEscapeChar=none", "-oBatchMode=yes", "-lroot"]
213 tty = sys.stdout.isatty()
222 args.append("-oStrictHostKeyChecking=%s" % tmp)
223 args.append("-oClearAllForwardings=yes")
224 args.append("-oForwardAgent=yes")
227 if node in _MULTIPLEXERS:
228 spath = _MULTIPLEXERS[node][0]
229 args.append("-oControlPath=%s" % spath)
230 args.append("-oControlMaster=no")
238 def StartLocalCommand(cmd, _nolog_opts=False, **kwargs):
239 """Starts a local command.
243 pcmd = [i for i in cmd if not i.startswith("-")]
246 print "Command: %s" % utils.ShellQuoteArgs(pcmd)
247 return subprocess.Popen(cmd, shell=False, **kwargs)
250 def StartSSH(node, cmd, strict=True):
254 return StartLocalCommand(GetSSHCommand(node, cmd, strict=strict),
258 def StartMultiplexer(node):
259 """Starts a multiplexer command.
261 @param node: the node for which to open the multiplexer
264 if node in _MULTIPLEXERS:
267 # Note: yes, we only need mktemp, since we'll remove the file anyway
268 sname = tempfile.mktemp(prefix="ganeti-qa-multiplexer.")
269 utils.RemoveFile(sname)
270 opts = ["-N", "-oControlPath=%s" % sname, "-oControlMaster=yes"]
271 print "Created socket at %s" % sname
272 child = StartLocalCommand(GetSSHCommand(node, None, opts=opts))
273 _MULTIPLEXERS[node] = (sname, child)
276 def CloseMultiplexers():
277 """Closes all current multiplexers and cleans up.
280 for node in _MULTIPLEXERS.keys():
281 (sname, child) = _MULTIPLEXERS.pop(node)
282 utils.KillProcess(child.pid, timeout=10, waitpid=True)
283 utils.RemoveFile(sname)
286 def GetCommandOutput(node, cmd, tty=None):
287 """Returns the output of a command executed on the given node.
290 p = StartLocalCommand(GetSSHCommand(node, cmd, tty=tty),
291 stdout=subprocess.PIPE)
292 AssertEqual(p.wait(), 0)
293 return p.stdout.read()
296 def UploadFile(node, src):
297 """Uploads a file to a node and returns the filename.
299 Caller needs to remove the returned file on the node when it's not needed
303 # Make sure nobody else has access to it while preserving local permissions
304 mode = os.stat(src).st_mode & 0700
306 cmd = ('tmp=$(tempfile --mode %o --prefix gnt) && '
307 '[[ -f "${tmp}" ]] && '
309 'echo "${tmp}"') % mode
313 p = subprocess.Popen(GetSSHCommand(node, cmd), shell=False, stdin=f,
314 stdout=subprocess.PIPE)
315 AssertEqual(p.wait(), 0)
317 # Return temporary filename
318 return p.stdout.read().strip()
323 def UploadData(node, data, mode=0600, filename=None):
324 """Uploads data to a node and returns the filename.
326 Caller needs to remove the returned file on the node when it's not needed
331 tmp = "tmp=%s" % utils.ShellQuote(filename)
333 tmp = "tmp=$(tempfile --mode %o --prefix gnt)" % mode
335 "[[ -f \"${tmp}\" ]] && "
336 "cat > \"${tmp}\" && "
337 "echo \"${tmp}\"") % tmp
339 p = subprocess.Popen(GetSSHCommand(node, cmd), shell=False,
340 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
343 AssertEqual(p.wait(), 0)
345 # Return temporary filename
346 return p.stdout.read().strip()
349 def BackupFile(node, path):
350 """Creates a backup of a file on the node and returns the filename.
352 Caller needs to remove the returned file on the node when it's not needed
356 cmd = ("tmp=$(tempfile --prefix .gnt --directory=$(dirname %s)) && "
357 "[[ -f \"$tmp\" ]] && "
359 "echo $tmp") % (utils.ShellQuote(path), utils.ShellQuote(path))
361 # Return temporary filename
362 return GetCommandOutput(node, cmd).strip()
365 def _ResolveName(cmd, key):
369 master = qa_config.GetMasterNode()
371 output = GetCommandOutput(master["primary"], utils.ShellQuoteArgs(cmd))
372 for line in output.splitlines():
373 (lkey, lvalue) = line.split(":", 1)
375 return lvalue.lstrip()
376 raise KeyError("Key not found")
379 def ResolveInstanceName(instance):
380 """Gets the full name of an instance.
382 @type instance: string
383 @param instance: Instance name
386 return _ResolveName(["gnt-instance", "info", instance],
390 def ResolveNodeName(node):
391 """Gets the full name of a node.
394 return _ResolveName(["gnt-node", "info", node["primary"]],
398 def GetNodeInstances(node, secondaries=False):
399 """Gets a list of instances on a node.
402 master = qa_config.GetMasterNode()
403 node_name = ResolveNodeName(node)
405 # Get list of all instances
406 cmd = ["gnt-instance", "list", "--separator=:", "--no-headers",
407 "--output=name,pnode,snodes"]
408 output = GetCommandOutput(master["primary"], utils.ShellQuoteArgs(cmd))
411 for line in output.splitlines():
412 (name, pnode, snodes) = line.split(":", 2)
413 if ((not secondaries and pnode == node_name) or
414 (secondaries and node_name in snodes.split(","))):
415 instances.append(name)
420 def _SelectQueryFields(rnd, fields):
421 """Generates a list of fields for query tests.
424 # Create copy for shuffling
425 fields = list(fields)
433 yield fields + fields
435 # Check small groups of fields
437 yield [fields.pop() for _ in range(rnd.randint(2, 10)) if fields]
440 def _List(listcmd, fields, names):
441 """Runs a list command.
444 master = qa_config.GetMasterNode()
446 cmd = [listcmd, "list", "--separator=|", "--no-headers",
447 "--output", ",".join(fields)]
452 return GetCommandOutput(master["primary"],
453 utils.ShellQuoteArgs(cmd)).splitlines()
456 def GenericQueryTest(cmd, fields, namefield="name", test_unknown=True):
457 """Runs a number of tests on query commands.
459 @param cmd: Command name
460 @param fields: List of field names
463 rnd = random.Random(hash(cmd))
465 fields = list(fields)
468 # Test a number of field combinations
469 for testfields in _SelectQueryFields(rnd, fields):
470 AssertCommand([cmd, "list", "--output", ",".join(testfields)])
472 if namefield is not None:
473 namelist_fn = compat.partial(_List, cmd, [namefield])
475 # When no names were requested, the list must be sorted
476 names = namelist_fn(None)
477 AssertEqual(names, utils.NiceSort(names))
479 # When requesting specific names, the order must be kept
480 revnames = list(reversed(names))
481 AssertEqual(namelist_fn(revnames), revnames)
483 randnames = list(names)
484 rnd.shuffle(randnames)
485 AssertEqual(namelist_fn(randnames), randnames)
488 # Listing unknown items must fail
489 AssertCommand([cmd, "list", "this.name.certainly.does.not.exist"],
492 # Check exit code for listing unknown field
493 AssertEqual(AssertCommand([cmd, "list", "--output=field/does/not/exist"],
495 constants.EXIT_UNKNOWN_FIELD)
498 def GenericQueryFieldsTest(cmd, fields):
499 master = qa_config.GetMasterNode()
502 AssertCommand([cmd, "list-fields"])
503 AssertCommand([cmd, "list-fields"] + fields)
505 # Check listed fields (all, must be sorted)
506 realcmd = [cmd, "list-fields", "--separator=|", "--no-headers"]
507 output = GetCommandOutput(master["primary"],
508 utils.ShellQuoteArgs(realcmd)).splitlines()
509 AssertEqual([line.split("|", 1)[0] for line in output],
510 utils.NiceSort(fields))
512 # Check exit code for listing unknown field
513 AssertEqual(AssertCommand([cmd, "list-fields", "field/does/not/exist"],
515 constants.EXIT_UNKNOWN_FIELD)
518 def _FormatWithColor(text, seq):
521 return "%s%s%s" % (seq, text, _RESET_SEQ)
524 FormatWarning = lambda text: _FormatWithColor(text, _WARNING_SEQ)
525 FormatError = lambda text: _FormatWithColor(text, _ERROR_SEQ)
526 FormatInfo = lambda text: _FormatWithColor(text, _INFO_SEQ)
529 def AddToEtcHosts(hostnames):
530 """Adds hostnames to /etc/hosts.
532 @param hostnames: List of hostnames first used A records, all other CNAMEs
535 master = qa_config.GetMasterNode()
536 tmp_hosts = UploadData(master["primary"], "", mode=0644)
538 quoted_tmp_hosts = utils.ShellQuote(tmp_hosts)
540 for localhost in ("::1", "127.0.0.1"):
541 data.append("%s %s" % (localhost, " ".join(hostnames)))
544 AssertCommand(("cat /etc/hosts > %s && echo -e '%s' >> %s && mv %s"
545 " /etc/hosts") % (quoted_tmp_hosts, "\\n".join(data),
546 quoted_tmp_hosts, quoted_tmp_hosts))
547 except qa_error.Error:
548 AssertCommand(["rm", tmp_hosts])
551 def RemoveFromEtcHosts(hostnames):
552 """Remove hostnames from /etc/hosts.
554 @param hostnames: List of hostnames first used A records, all other CNAMEs
557 master = qa_config.GetMasterNode()
558 tmp_hosts = UploadData(master["primary"], "", mode=0644)
559 quoted_tmp_hosts = utils.ShellQuote(tmp_hosts)
561 sed_data = " ".join(hostnames)
563 AssertCommand(("sed -e '/^\(::1\|127\.0\.0\.1\)\s\+%s/d' /etc/hosts > %s"
564 " && mv %s /etc/hosts") % (sed_data, quoted_tmp_hosts,
566 except qa_error.Error:
567 AssertCommand(["rm", tmp_hosts])
570 def RunInstanceCheck(instance, running):
571 """Check if instance is running or not.
574 instance_name = _GetName(instance, "name")
576 script = qa_config.GetInstanceCheckScript()
580 master_node = qa_config.GetMasterNode()
582 # Build command to connect to master node
583 master_ssh = GetSSHCommand(master_node["primary"], "--")
586 running_shellval = "1"
589 running_shellval = ""
590 running_text = "not "
592 print FormatInfo("Checking if instance '%s' is %srunning" %
593 (instance_name, running_text))
595 args = [script, instance_name]
597 "PATH": constants.HOOKS_PATH,
598 "RUN_UUID": _RUN_UUID,
599 "MASTER_SSH": utils.ShellQuoteArgs(master_ssh),
600 "INSTANCE_NAME": instance_name,
601 "INSTANCE_RUNNING": running_shellval,
604 result = os.spawnve(os.P_WAIT, script, args, env)
606 raise qa_error.Error("Instance check failed with result %s" % result)
609 def _InstanceCheckInner(expected, instarg, args, result):
610 """Helper function used by L{InstanceCheck}.
613 if instarg == FIRST_ARG:
615 elif instarg == RETURN_VALUE:
618 raise Exception("Invalid value '%s' for instance argument" % instarg)
620 if expected in (INST_DOWN, INST_UP):
621 RunInstanceCheck(instance, (expected == INST_UP))
622 elif expected is not None:
623 raise Exception("Invalid value '%s'" % expected)
626 def InstanceCheck(before, after, instarg):
627 """Decorator to check instance status before and after test.
629 @param before: L{INST_DOWN} if instance must be stopped before test,
630 L{INST_UP} if instance must be running before test, L{None} to not check.
631 @param after: L{INST_DOWN} if instance must be stopped after test,
632 L{INST_UP} if instance must be running after test, L{None} to not check.
633 @param instarg: L{FIRST_ARG} to use first argument to test as instance (a
634 dictionary), L{RETURN_VALUE} to use return value (disallows pre-checks)
639 def wrapper(*args, **kwargs):
640 _InstanceCheckInner(before, instarg, args, NotImplemented)
642 result = fn(*args, **kwargs)
644 _InstanceCheckInner(after, instarg, args, result)