4 # Copyright (C) 2007, 2011, 2012, 2013 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
42 from ganeti import pathutils
55 #: Unique ID per QA run
56 _RUN_UUID = utils.NewUUID()
60 INST_UP) = range(500, 502)
63 RETURN_VALUE) = range(1000, 1002)
67 """Initializes the colour constants.
70 # pylint: disable=W0603
72 global _INFO_SEQ, _WARNING_SEQ, _ERROR_SEQ, _RESET_SEQ
74 # Don't use colours if stdout isn't a terminal
75 if not sys.stdout.isatty():
81 # Don't use colours if curses module can't be imported
86 _RESET_SEQ = curses.tigetstr("op")
88 setaf = curses.tigetstr("setaf")
89 _INFO_SEQ = curses.tparm(setaf, curses.COLOR_GREEN)
90 _WARNING_SEQ = curses.tparm(setaf, curses.COLOR_YELLOW)
91 _ERROR_SEQ = curses.tparm(setaf, curses.COLOR_RED)
97 def AssertIn(item, sequence):
98 """Raises an error when item is not in sequence.
101 if item not in sequence:
102 raise qa_error.Error("%r not in %r" % (item, sequence))
105 def AssertNotIn(item, sequence):
106 """Raises an error when item is in sequence.
110 raise qa_error.Error("%r in %r" % (item, sequence))
113 def AssertEqual(first, second):
114 """Raises an error when values aren't equal.
117 if not first == second:
118 raise qa_error.Error("%r == %r" % (first, second))
121 def AssertMatch(string, pattern):
122 """Raises an error when string doesn't match regexp pattern.
125 if not re.match(pattern, string):
126 raise qa_error.Error("%r doesn't match /%r/" % (string, pattern))
129 def _GetName(entity, key):
130 """Tries to get name of an entity.
132 @type entity: string or dict
134 @param key: Dictionary key containing name
137 if isinstance(entity, basestring):
139 elif isinstance(entity, dict):
142 raise qa_error.Error("Expected string or dictionary, got %s: %s" %
143 (type(entity), entity))
145 if not ht.TNonEmptyString(result):
146 raise Exception("Invalid name '%s'" % result)
151 def _AssertRetCode(rcode, fail, cmdstr, nodename):
152 """Check the return value from a command and possibly raise an exception.
155 if fail and rcode == 0:
156 raise qa_error.Error("Command '%s' on node %s was expected to fail but"
157 " didn't" % (cmdstr, nodename))
158 elif not fail and rcode != 0:
159 raise qa_error.Error("Command '%s' on node %s failed, exit code %s" %
160 (cmdstr, nodename, rcode))
163 def AssertCommand(cmd, fail=False, node=None, log_cmd=True):
164 """Checks that a remote command succeeds.
166 @param cmd: either a string (the command to execute) or a list (to
167 be converted using L{utils.ShellQuoteArgs} into a string)
169 @param fail: if the command is expected to fail instead of succeeding
170 @param node: if passed, it should be the node on which the command
171 should be executed, instead of the master node (can be either a
173 @param log_cmd: if False, the command won't be logged (simply passed to
175 @return: the return code of the command
176 @raise qa_error.Error: if the command fails when it shouldn't or vice versa
180 node = qa_config.GetMasterNode()
182 nodename = _GetName(node, "primary")
184 if isinstance(cmd, basestring):
187 cmdstr = utils.ShellQuoteArgs(cmd)
189 rcode = StartSSH(nodename, cmdstr, log_cmd=log_cmd).wait()
190 _AssertRetCode(rcode, fail, cmdstr, nodename)
195 def GetSSHCommand(node, cmd, strict=True, opts=None, tty=None):
196 """Builds SSH command to be executed.
199 @param node: node the command should run on
201 @param cmd: command to be executed in the node; if None or empty
202 string, no command will be executed
203 @type strict: boolean
204 @param strict: whether to enable strict host key checking
206 @param opts: list of additional options
207 @type tty: boolean or None
208 @param tty: if we should use tty; if None, will be auto-detected
211 args = ["ssh", "-oEscapeChar=none", "-oBatchMode=yes", "-lroot"]
214 tty = sys.stdout.isatty()
223 args.append("-oStrictHostKeyChecking=%s" % tmp)
224 args.append("-oClearAllForwardings=yes")
225 args.append("-oForwardAgent=yes")
228 if node in _MULTIPLEXERS:
229 spath = _MULTIPLEXERS[node][0]
230 args.append("-oControlPath=%s" % spath)
231 args.append("-oControlMaster=no")
239 def StartLocalCommand(cmd, _nolog_opts=False, log_cmd=True, **kwargs):
240 """Starts a local command.
245 pcmd = [i for i in cmd if not i.startswith("-")]
248 print "Command: %s" % utils.ShellQuoteArgs(pcmd)
249 return subprocess.Popen(cmd, shell=False, **kwargs)
252 def StartSSH(node, cmd, strict=True, log_cmd=True):
256 return StartLocalCommand(GetSSHCommand(node, cmd, strict=strict),
257 _nolog_opts=True, log_cmd=log_cmd)
260 def StartMultiplexer(node):
261 """Starts a multiplexer command.
263 @param node: the node for which to open the multiplexer
266 if node in _MULTIPLEXERS:
269 # Note: yes, we only need mktemp, since we'll remove the file anyway
270 sname = tempfile.mktemp(prefix="ganeti-qa-multiplexer.")
271 utils.RemoveFile(sname)
272 opts = ["-N", "-oControlPath=%s" % sname, "-oControlMaster=yes"]
273 print "Created socket at %s" % sname
274 child = StartLocalCommand(GetSSHCommand(node, None, opts=opts))
275 _MULTIPLEXERS[node] = (sname, child)
278 def CloseMultiplexers():
279 """Closes all current multiplexers and cleans up.
282 for node in _MULTIPLEXERS.keys():
283 (sname, child) = _MULTIPLEXERS.pop(node)
284 utils.KillProcess(child.pid, timeout=10, waitpid=True)
285 utils.RemoveFile(sname)
288 def GetCommandOutput(node, cmd, tty=None, fail=False):
289 """Returns the output of a command executed on the given node.
292 @param node: node the command should run on
294 @param cmd: command to be executed in the node (cannot be empty or None)
295 @type tty: bool or None
296 @param tty: if we should use tty; if None, it will be auto-detected
298 @param fail: whether the command is expected to fail
301 p = StartLocalCommand(GetSSHCommand(node, cmd, tty=tty),
302 stdout=subprocess.PIPE)
304 _AssertRetCode(rcode, fail, node, cmd)
305 return p.stdout.read()
308 def UploadFile(node, src):
309 """Uploads a file to a node and returns the filename.
311 Caller needs to remove the returned file on the node when it's not needed
315 # Make sure nobody else has access to it while preserving local permissions
316 mode = os.stat(src).st_mode & 0700
318 cmd = ('tmp=$(tempfile --mode %o --prefix gnt) && '
319 '[[ -f "${tmp}" ]] && '
321 'echo "${tmp}"') % mode
325 p = subprocess.Popen(GetSSHCommand(node, cmd), shell=False, stdin=f,
326 stdout=subprocess.PIPE)
327 AssertEqual(p.wait(), 0)
329 # Return temporary filename
330 return p.stdout.read().strip()
335 def UploadData(node, data, mode=0600, filename=None):
336 """Uploads data to a node and returns the filename.
338 Caller needs to remove the returned file on the node when it's not needed
343 tmp = "tmp=%s" % utils.ShellQuote(filename)
345 tmp = "tmp=$(tempfile --mode %o --prefix gnt)" % mode
347 "[[ -f \"${tmp}\" ]] && "
348 "cat > \"${tmp}\" && "
349 "echo \"${tmp}\"") % tmp
351 p = subprocess.Popen(GetSSHCommand(node, cmd), shell=False,
352 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
355 AssertEqual(p.wait(), 0)
357 # Return temporary filename
358 return p.stdout.read().strip()
361 def BackupFile(node, path):
362 """Creates a backup of a file on the node and returns the filename.
364 Caller needs to remove the returned file on the node when it's not needed
368 cmd = ("tmp=$(tempfile --prefix .gnt --directory=$(dirname %s)) && "
369 "[[ -f \"$tmp\" ]] && "
371 "echo $tmp") % (utils.ShellQuote(path), utils.ShellQuote(path))
373 # Return temporary filename
374 return GetCommandOutput(node, cmd).strip()
377 def _ResolveName(cmd, key):
381 master = qa_config.GetMasterNode()
383 output = GetCommandOutput(master["primary"], utils.ShellQuoteArgs(cmd))
384 for line in output.splitlines():
385 (lkey, lvalue) = line.split(":", 1)
387 return lvalue.lstrip()
388 raise KeyError("Key not found")
391 def ResolveInstanceName(instance):
392 """Gets the full name of an instance.
394 @type instance: string
395 @param instance: Instance name
398 return _ResolveName(["gnt-instance", "info", instance],
402 def ResolveNodeName(node):
403 """Gets the full name of a node.
406 return _ResolveName(["gnt-node", "info", node["primary"]],
410 def GetNodeInstances(node, secondaries=False):
411 """Gets a list of instances on a node.
414 master = qa_config.GetMasterNode()
415 node_name = ResolveNodeName(node)
417 # Get list of all instances
418 cmd = ["gnt-instance", "list", "--separator=:", "--no-headers",
419 "--output=name,pnode,snodes"]
420 output = GetCommandOutput(master["primary"], utils.ShellQuoteArgs(cmd))
423 for line in output.splitlines():
424 (name, pnode, snodes) = line.split(":", 2)
425 if ((not secondaries and pnode == node_name) or
426 (secondaries and node_name in snodes.split(","))):
427 instances.append(name)
432 def _SelectQueryFields(rnd, fields):
433 """Generates a list of fields for query tests.
436 # Create copy for shuffling
437 fields = list(fields)
445 yield fields + fields
447 # Check small groups of fields
449 yield [fields.pop() for _ in range(rnd.randint(2, 10)) if fields]
452 def _List(listcmd, fields, names):
453 """Runs a list command.
456 master = qa_config.GetMasterNode()
458 cmd = [listcmd, "list", "--separator=|", "--no-headers",
459 "--output", ",".join(fields)]
464 return GetCommandOutput(master["primary"],
465 utils.ShellQuoteArgs(cmd)).splitlines()
468 def GenericQueryTest(cmd, fields, namefield="name", test_unknown=True):
469 """Runs a number of tests on query commands.
471 @param cmd: Command name
472 @param fields: List of field names
475 rnd = random.Random(hash(cmd))
477 fields = list(fields)
480 # Test a number of field combinations
481 for testfields in _SelectQueryFields(rnd, fields):
482 AssertCommand([cmd, "list", "--output", ",".join(testfields)])
484 if namefield is not None:
485 namelist_fn = compat.partial(_List, cmd, [namefield])
487 # When no names were requested, the list must be sorted
488 names = namelist_fn(None)
489 AssertEqual(names, utils.NiceSort(names))
491 # When requesting specific names, the order must be kept
492 revnames = list(reversed(names))
493 AssertEqual(namelist_fn(revnames), revnames)
495 randnames = list(names)
496 rnd.shuffle(randnames)
497 AssertEqual(namelist_fn(randnames), randnames)
500 # Listing unknown items must fail
501 AssertCommand([cmd, "list", "this.name.certainly.does.not.exist"],
504 # Check exit code for listing unknown field
505 AssertEqual(AssertCommand([cmd, "list", "--output=field/does/not/exist"],
507 constants.EXIT_UNKNOWN_FIELD)
510 def GenericQueryFieldsTest(cmd, fields):
511 master = qa_config.GetMasterNode()
514 AssertCommand([cmd, "list-fields"])
515 AssertCommand([cmd, "list-fields"] + fields)
517 # Check listed fields (all, must be sorted)
518 realcmd = [cmd, "list-fields", "--separator=|", "--no-headers"]
519 output = GetCommandOutput(master["primary"],
520 utils.ShellQuoteArgs(realcmd)).splitlines()
521 AssertEqual([line.split("|", 1)[0] for line in output],
522 utils.NiceSort(fields))
524 # Check exit code for listing unknown field
525 AssertEqual(AssertCommand([cmd, "list-fields", "field/does/not/exist"],
527 constants.EXIT_UNKNOWN_FIELD)
530 def _FormatWithColor(text, seq):
533 return "%s%s%s" % (seq, text, _RESET_SEQ)
536 FormatWarning = lambda text: _FormatWithColor(text, _WARNING_SEQ)
537 FormatError = lambda text: _FormatWithColor(text, _ERROR_SEQ)
538 FormatInfo = lambda text: _FormatWithColor(text, _INFO_SEQ)
541 def AddToEtcHosts(hostnames):
542 """Adds hostnames to /etc/hosts.
544 @param hostnames: List of hostnames first used A records, all other CNAMEs
547 master = qa_config.GetMasterNode()
548 tmp_hosts = UploadData(master["primary"], "", mode=0644)
551 for localhost in ("::1", "127.0.0.1"):
552 data.append("%s %s" % (localhost, " ".join(hostnames)))
555 AssertCommand("{ cat %s && echo -e '%s'; } > %s && mv %s %s" %
556 (utils.ShellQuote(pathutils.ETC_HOSTS),
558 utils.ShellQuote(tmp_hosts),
559 utils.ShellQuote(tmp_hosts),
560 utils.ShellQuote(pathutils.ETC_HOSTS)))
562 AssertCommand(["rm", "-f", tmp_hosts])
566 def RemoveFromEtcHosts(hostnames):
567 """Remove hostnames from /etc/hosts.
569 @param hostnames: List of hostnames first used A records, all other CNAMEs
572 master = qa_config.GetMasterNode()
573 tmp_hosts = UploadData(master["primary"], "", mode=0644)
574 quoted_tmp_hosts = utils.ShellQuote(tmp_hosts)
576 sed_data = " ".join(hostnames)
578 AssertCommand(("sed -e '/^\(::1\|127\.0\.0\.1\)\s\+%s/d' %s > %s"
580 (sed_data, utils.ShellQuote(pathutils.ETC_HOSTS),
581 quoted_tmp_hosts, quoted_tmp_hosts,
582 utils.ShellQuote(pathutils.ETC_HOSTS)))
584 AssertCommand(["rm", "-f", tmp_hosts])
588 def RunInstanceCheck(instance, running):
589 """Check if instance is running or not.
592 instance_name = _GetName(instance, "name")
594 script = qa_config.GetInstanceCheckScript()
598 master_node = qa_config.GetMasterNode()
600 # Build command to connect to master node
601 master_ssh = GetSSHCommand(master_node["primary"], "--")
604 running_shellval = "1"
607 running_shellval = ""
608 running_text = "not "
610 print FormatInfo("Checking if instance '%s' is %srunning" %
611 (instance_name, running_text))
613 args = [script, instance_name]
615 "PATH": constants.HOOKS_PATH,
616 "RUN_UUID": _RUN_UUID,
617 "MASTER_SSH": utils.ShellQuoteArgs(master_ssh),
618 "INSTANCE_NAME": instance_name,
619 "INSTANCE_RUNNING": running_shellval,
622 result = os.spawnve(os.P_WAIT, script, args, env)
624 raise qa_error.Error("Instance check failed with result %s" % result)
627 def _InstanceCheckInner(expected, instarg, args, result):
628 """Helper function used by L{InstanceCheck}.
631 if instarg == FIRST_ARG:
633 elif instarg == RETURN_VALUE:
636 raise Exception("Invalid value '%s' for instance argument" % instarg)
638 if expected in (INST_DOWN, INST_UP):
639 RunInstanceCheck(instance, (expected == INST_UP))
640 elif expected is not None:
641 raise Exception("Invalid value '%s'" % expected)
644 def InstanceCheck(before, after, instarg):
645 """Decorator to check instance status before and after test.
647 @param before: L{INST_DOWN} if instance must be stopped before test,
648 L{INST_UP} if instance must be running before test, L{None} to not check.
649 @param after: L{INST_DOWN} if instance must be stopped after test,
650 L{INST_UP} if instance must be running after test, L{None} to not check.
651 @param instarg: L{FIRST_ARG} to use first argument to test as instance (a
652 dictionary), L{RETURN_VALUE} to use return value (disallows pre-checks)
657 def wrapper(*args, **kwargs):
658 _InstanceCheckInner(before, instarg, args, NotImplemented)
660 result = fn(*args, **kwargs)
662 _InstanceCheckInner(after, instarg, args, result)
669 def GetNonexistentGroups(count):
670 """Gets group names which shouldn't exist on the cluster.
672 @param count: Number of groups to get
676 groups = qa_config.get("groups", {})
678 default = ["group1", "group2", "group3"]
679 assert count <= len(default)
681 candidates = groups.get("inexistent-groups", default)[:count]
683 if len(candidates) < count:
684 raise Exception("At least %s non-existent groups are needed" % count)