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
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 AssertCommand(cmd, fail=False, node=None):
152 """Checks that a remote command succeeds.
154 @param cmd: either a string (the command to execute) or a list (to
155 be converted using L{utils.ShellQuoteArgs} into a string)
157 @param fail: if the command is expected to fail instead of succeeding
158 @param node: if passed, it should be the node on which the command
159 should be executed, instead of the master node (can be either a
161 @return: the return code of the command
162 @raise qa_error.Error: if the command fails when it shouldn't or vice versa
166 node = qa_config.GetMasterNode()
168 nodename = _GetName(node, "primary")
170 if isinstance(cmd, basestring):
173 cmdstr = utils.ShellQuoteArgs(cmd)
175 rcode = StartSSH(nodename, cmdstr).wait()
179 raise qa_error.Error("Command '%s' on node %s was expected to fail but"
180 " didn't" % (cmdstr, nodename))
183 raise qa_error.Error("Command '%s' on node %s failed, exit code %s" %
184 (cmdstr, nodename, rcode))
189 def GetSSHCommand(node, cmd, strict=True, opts=None, tty=None):
190 """Builds SSH command to be executed.
193 @param node: node the command should run on
195 @param cmd: command to be executed in the node; if None or empty
196 string, no command will be executed
197 @type strict: boolean
198 @param strict: whether to enable strict host key checking
200 @param opts: list of additional options
201 @type tty: boolean or None
202 @param tty: if we should use tty; if None, will be auto-detected
205 args = ["ssh", "-oEscapeChar=none", "-oBatchMode=yes", "-lroot"]
208 tty = sys.stdout.isatty()
217 args.append("-oStrictHostKeyChecking=%s" % tmp)
218 args.append("-oClearAllForwardings=yes")
219 args.append("-oForwardAgent=yes")
222 if node in _MULTIPLEXERS:
223 spath = _MULTIPLEXERS[node][0]
224 args.append("-oControlPath=%s" % spath)
225 args.append("-oControlMaster=no")
233 def StartLocalCommand(cmd, _nolog_opts=False, **kwargs):
234 """Starts a local command.
238 pcmd = [i for i in cmd if not i.startswith("-")]
241 print "Command: %s" % utils.ShellQuoteArgs(pcmd)
242 return subprocess.Popen(cmd, shell=False, **kwargs)
245 def StartSSH(node, cmd, strict=True):
249 return StartLocalCommand(GetSSHCommand(node, cmd, strict=strict),
253 def StartMultiplexer(node):
254 """Starts a multiplexer command.
256 @param node: the node for which to open the multiplexer
259 if node in _MULTIPLEXERS:
262 # Note: yes, we only need mktemp, since we'll remove the file anyway
263 sname = tempfile.mktemp(prefix="ganeti-qa-multiplexer.")
264 utils.RemoveFile(sname)
265 opts = ["-N", "-oControlPath=%s" % sname, "-oControlMaster=yes"]
266 print "Created socket at %s" % sname
267 child = StartLocalCommand(GetSSHCommand(node, None, opts=opts))
268 _MULTIPLEXERS[node] = (sname, child)
271 def CloseMultiplexers():
272 """Closes all current multiplexers and cleans up.
275 for node in _MULTIPLEXERS.keys():
276 (sname, child) = _MULTIPLEXERS.pop(node)
277 utils.KillProcess(child.pid, timeout=10, waitpid=True)
278 utils.RemoveFile(sname)
281 def GetCommandOutput(node, cmd, tty=None):
282 """Returns the output of a command executed on the given node.
285 p = StartLocalCommand(GetSSHCommand(node, cmd, tty=tty),
286 stdout=subprocess.PIPE)
287 AssertEqual(p.wait(), 0)
288 return p.stdout.read()
291 def UploadFile(node, src):
292 """Uploads a file to a node and returns the filename.
294 Caller needs to remove the returned file on the node when it's not needed
298 # Make sure nobody else has access to it while preserving local permissions
299 mode = os.stat(src).st_mode & 0700
301 cmd = ('tmp=$(tempfile --mode %o --prefix gnt) && '
302 '[[ -f "${tmp}" ]] && '
304 'echo "${tmp}"') % mode
308 p = subprocess.Popen(GetSSHCommand(node, cmd), shell=False, stdin=f,
309 stdout=subprocess.PIPE)
310 AssertEqual(p.wait(), 0)
312 # Return temporary filename
313 return p.stdout.read().strip()
318 def UploadData(node, data, mode=0600, filename=None):
319 """Uploads data to a node and returns the filename.
321 Caller needs to remove the returned file on the node when it's not needed
326 tmp = "tmp=%s" % utils.ShellQuote(filename)
328 tmp = "tmp=$(tempfile --mode %o --prefix gnt)" % mode
330 "[[ -f \"${tmp}\" ]] && "
331 "cat > \"${tmp}\" && "
332 "echo \"${tmp}\"") % tmp
334 p = subprocess.Popen(GetSSHCommand(node, cmd), shell=False,
335 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
338 AssertEqual(p.wait(), 0)
340 # Return temporary filename
341 return p.stdout.read().strip()
344 def BackupFile(node, path):
345 """Creates a backup of a file on the node and returns the filename.
347 Caller needs to remove the returned file on the node when it's not needed
351 cmd = ("tmp=$(tempfile --prefix .gnt --directory=$(dirname %s)) && "
352 "[[ -f \"$tmp\" ]] && "
354 "echo $tmp") % (utils.ShellQuote(path), utils.ShellQuote(path))
356 # Return temporary filename
357 return GetCommandOutput(node, cmd).strip()
360 def _ResolveName(cmd, key):
364 master = qa_config.GetMasterNode()
366 output = GetCommandOutput(master["primary"], utils.ShellQuoteArgs(cmd))
367 for line in output.splitlines():
368 (lkey, lvalue) = line.split(":", 1)
370 return lvalue.lstrip()
371 raise KeyError("Key not found")
374 def ResolveInstanceName(instance):
375 """Gets the full name of an instance.
377 @type instance: string
378 @param instance: Instance name
381 return _ResolveName(["gnt-instance", "info", instance],
385 def ResolveNodeName(node):
386 """Gets the full name of a node.
389 return _ResolveName(["gnt-node", "info", node["primary"]],
393 def GetNodeInstances(node, secondaries=False):
394 """Gets a list of instances on a node.
397 master = qa_config.GetMasterNode()
398 node_name = ResolveNodeName(node)
400 # Get list of all instances
401 cmd = ["gnt-instance", "list", "--separator=:", "--no-headers",
402 "--output=name,pnode,snodes"]
403 output = GetCommandOutput(master["primary"], utils.ShellQuoteArgs(cmd))
406 for line in output.splitlines():
407 (name, pnode, snodes) = line.split(":", 2)
408 if ((not secondaries and pnode == node_name) or
409 (secondaries and node_name in snodes.split(","))):
410 instances.append(name)
415 def _SelectQueryFields(rnd, fields):
416 """Generates a list of fields for query tests.
419 # Create copy for shuffling
420 fields = list(fields)
428 yield fields + fields
430 # Check small groups of fields
432 yield [fields.pop() for _ in range(rnd.randint(2, 10)) if fields]
435 def _List(listcmd, fields, names):
436 """Runs a list command.
439 master = qa_config.GetMasterNode()
441 cmd = [listcmd, "list", "--separator=|", "--no-headers",
442 "--output", ",".join(fields)]
447 return GetCommandOutput(master["primary"],
448 utils.ShellQuoteArgs(cmd)).splitlines()
451 def GenericQueryTest(cmd, fields, namefield="name", test_unknown=True):
452 """Runs a number of tests on query commands.
454 @param cmd: Command name
455 @param fields: List of field names
458 rnd = random.Random(hash(cmd))
460 fields = list(fields)
463 # Test a number of field combinations
464 for testfields in _SelectQueryFields(rnd, fields):
465 AssertCommand([cmd, "list", "--output", ",".join(testfields)])
467 if namefield is not None:
468 namelist_fn = compat.partial(_List, cmd, [namefield])
470 # When no names were requested, the list must be sorted
471 names = namelist_fn(None)
472 AssertEqual(names, utils.NiceSort(names))
474 # When requesting specific names, the order must be kept
475 revnames = list(reversed(names))
476 AssertEqual(namelist_fn(revnames), revnames)
478 randnames = list(names)
479 rnd.shuffle(randnames)
480 AssertEqual(namelist_fn(randnames), randnames)
483 # Listing unknown items must fail
484 AssertCommand([cmd, "list", "this.name.certainly.does.not.exist"],
487 # Check exit code for listing unknown field
488 AssertEqual(AssertCommand([cmd, "list", "--output=field/does/not/exist"],
490 constants.EXIT_UNKNOWN_FIELD)
493 def GenericQueryFieldsTest(cmd, fields):
494 master = qa_config.GetMasterNode()
497 AssertCommand([cmd, "list-fields"])
498 AssertCommand([cmd, "list-fields"] + fields)
500 # Check listed fields (all, must be sorted)
501 realcmd = [cmd, "list-fields", "--separator=|", "--no-headers"]
502 output = GetCommandOutput(master["primary"],
503 utils.ShellQuoteArgs(realcmd)).splitlines()
504 AssertEqual([line.split("|", 1)[0] for line in output],
505 utils.NiceSort(fields))
507 # Check exit code for listing unknown field
508 AssertEqual(AssertCommand([cmd, "list-fields", "field/does/not/exist"],
510 constants.EXIT_UNKNOWN_FIELD)
513 def _FormatWithColor(text, seq):
516 return "%s%s%s" % (seq, text, _RESET_SEQ)
519 FormatWarning = lambda text: _FormatWithColor(text, _WARNING_SEQ)
520 FormatError = lambda text: _FormatWithColor(text, _ERROR_SEQ)
521 FormatInfo = lambda text: _FormatWithColor(text, _INFO_SEQ)
524 def AddToEtcHosts(hostnames):
525 """Adds hostnames to /etc/hosts.
527 @param hostnames: List of hostnames first used A records, all other CNAMEs
530 master = qa_config.GetMasterNode()
531 tmp_hosts = UploadData(master["primary"], "", mode=0644)
534 for localhost in ("::1", "127.0.0.1"):
535 data.append("%s %s" % (localhost, " ".join(hostnames)))
538 AssertCommand("{ cat %s && echo -e '%s'; } > %s && mv %s %s" %
539 (utils.ShellQuote(pathutils.ETC_HOSTS),
541 utils.ShellQuote(tmp_hosts),
542 utils.ShellQuote(tmp_hosts),
543 utils.ShellQuote(pathutils.ETC_HOSTS)))
545 AssertCommand(["rm", "-f", tmp_hosts])
549 def RemoveFromEtcHosts(hostnames):
550 """Remove hostnames from /etc/hosts.
552 @param hostnames: List of hostnames first used A records, all other CNAMEs
555 master = qa_config.GetMasterNode()
556 tmp_hosts = UploadData(master["primary"], "", mode=0644)
557 quoted_tmp_hosts = utils.ShellQuote(tmp_hosts)
559 sed_data = " ".join(hostnames)
561 AssertCommand(("sed -e '/^\(::1\|127\.0\.0\.1\)\s\+%s/d' %s > %s"
563 (sed_data, utils.ShellQuote(pathutils.ETC_HOSTS),
564 quoted_tmp_hosts, quoted_tmp_hosts,
565 utils.ShellQuote(pathutils.ETC_HOSTS)))
567 AssertCommand(["rm", "-f", tmp_hosts])
571 def RunInstanceCheck(instance, running):
572 """Check if instance is running or not.
575 instance_name = _GetName(instance, "name")
577 script = qa_config.GetInstanceCheckScript()
581 master_node = qa_config.GetMasterNode()
583 # Build command to connect to master node
584 master_ssh = GetSSHCommand(master_node["primary"], "--")
587 running_shellval = "1"
590 running_shellval = ""
591 running_text = "not "
593 print FormatInfo("Checking if instance '%s' is %srunning" %
594 (instance_name, running_text))
596 args = [script, instance_name]
598 "PATH": constants.HOOKS_PATH,
599 "RUN_UUID": _RUN_UUID,
600 "MASTER_SSH": utils.ShellQuoteArgs(master_ssh),
601 "INSTANCE_NAME": instance_name,
602 "INSTANCE_RUNNING": running_shellval,
605 result = os.spawnve(os.P_WAIT, script, args, env)
607 raise qa_error.Error("Instance check failed with result %s" % result)
610 def _InstanceCheckInner(expected, instarg, args, result):
611 """Helper function used by L{InstanceCheck}.
614 if instarg == FIRST_ARG:
616 elif instarg == RETURN_VALUE:
619 raise Exception("Invalid value '%s' for instance argument" % instarg)
621 if expected in (INST_DOWN, INST_UP):
622 RunInstanceCheck(instance, (expected == INST_UP))
623 elif expected is not None:
624 raise Exception("Invalid value '%s'" % expected)
627 def InstanceCheck(before, after, instarg):
628 """Decorator to check instance status before and after test.
630 @param before: L{INST_DOWN} if instance must be stopped before test,
631 L{INST_UP} if instance must be running before test, L{None} to not check.
632 @param after: L{INST_DOWN} if instance must be stopped after test,
633 L{INST_UP} if instance must be running after test, L{None} to not check.
634 @param instarg: L{FIRST_ARG} to use first argument to test as instance (a
635 dictionary), L{RETURN_VALUE} to use return value (disallows pre-checks)
640 def wrapper(*args, **kwargs):
641 _InstanceCheckInner(before, instarg, args, NotImplemented)
643 result = fn(*args, **kwargs)
645 _InstanceCheckInner(after, instarg, args, result)
652 def GetNonexistentGroups(count):
653 """Gets group names which shouldn't exist on the cluster.
655 @param count: Number of groups to get
659 groups = qa_config.get("groups", {})
661 default = ["group1", "group2", "group3"]
662 assert count <= len(default)
664 candidates = groups.get("inexistent-groups", default)[:count]
666 if len(candidates) < count:
667 raise Exception("At least %s non-existent groups are needed" % count)