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):
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 @return: the return code of the command
174 @raise qa_error.Error: if the command fails when it shouldn't or vice versa
178 node = qa_config.GetMasterNode()
180 nodename = _GetName(node, "primary")
182 if isinstance(cmd, basestring):
185 cmdstr = utils.ShellQuoteArgs(cmd)
187 rcode = StartSSH(nodename, cmdstr).wait()
188 _AssertRetCode(rcode, fail, cmdstr, nodename)
193 def GetSSHCommand(node, cmd, strict=True, opts=None, tty=None):
194 """Builds SSH command to be executed.
197 @param node: node the command should run on
199 @param cmd: command to be executed in the node; if None or empty
200 string, no command will be executed
201 @type strict: boolean
202 @param strict: whether to enable strict host key checking
204 @param opts: list of additional options
205 @type tty: boolean or None
206 @param tty: if we should use tty; if None, will be auto-detected
209 args = ["ssh", "-oEscapeChar=none", "-oBatchMode=yes", "-lroot"]
212 tty = sys.stdout.isatty()
221 args.append("-oStrictHostKeyChecking=%s" % tmp)
222 args.append("-oClearAllForwardings=yes")
223 args.append("-oForwardAgent=yes")
226 if node in _MULTIPLEXERS:
227 spath = _MULTIPLEXERS[node][0]
228 args.append("-oControlPath=%s" % spath)
229 args.append("-oControlMaster=no")
237 def StartLocalCommand(cmd, _nolog_opts=False, **kwargs):
238 """Starts a local command.
242 pcmd = [i for i in cmd if not i.startswith("-")]
245 print "Command: %s" % utils.ShellQuoteArgs(pcmd)
246 return subprocess.Popen(cmd, shell=False, **kwargs)
249 def StartSSH(node, cmd, strict=True):
253 return StartLocalCommand(GetSSHCommand(node, cmd, strict=strict),
257 def StartMultiplexer(node):
258 """Starts a multiplexer command.
260 @param node: the node for which to open the multiplexer
263 if node in _MULTIPLEXERS:
266 # Note: yes, we only need mktemp, since we'll remove the file anyway
267 sname = tempfile.mktemp(prefix="ganeti-qa-multiplexer.")
268 utils.RemoveFile(sname)
269 opts = ["-N", "-oControlPath=%s" % sname, "-oControlMaster=yes"]
270 print "Created socket at %s" % sname
271 child = StartLocalCommand(GetSSHCommand(node, None, opts=opts))
272 _MULTIPLEXERS[node] = (sname, child)
275 def CloseMultiplexers():
276 """Closes all current multiplexers and cleans up.
279 for node in _MULTIPLEXERS.keys():
280 (sname, child) = _MULTIPLEXERS.pop(node)
281 utils.KillProcess(child.pid, timeout=10, waitpid=True)
282 utils.RemoveFile(sname)
285 def GetCommandOutput(node, cmd, tty=None, fail=False):
286 """Returns the output of a command executed on the given node.
289 @param node: node the command should run on
291 @param cmd: command to be executed in the node (cannot be empty or None)
292 @type tty: bool or None
293 @param tty: if we should use tty; if None, it will be auto-detected
295 @param fail: whether the command is expected to fail
298 p = StartLocalCommand(GetSSHCommand(node, cmd, tty=tty),
299 stdout=subprocess.PIPE)
301 _AssertRetCode(rcode, fail, node, cmd)
302 return p.stdout.read()
305 def UploadFile(node, src):
306 """Uploads a file to a node and returns the filename.
308 Caller needs to remove the returned file on the node when it's not needed
312 # Make sure nobody else has access to it while preserving local permissions
313 mode = os.stat(src).st_mode & 0700
315 cmd = ('tmp=$(tempfile --mode %o --prefix gnt) && '
316 '[[ -f "${tmp}" ]] && '
318 'echo "${tmp}"') % mode
322 p = subprocess.Popen(GetSSHCommand(node, cmd), shell=False, stdin=f,
323 stdout=subprocess.PIPE)
324 AssertEqual(p.wait(), 0)
326 # Return temporary filename
327 return p.stdout.read().strip()
332 def UploadData(node, data, mode=0600, filename=None):
333 """Uploads data to a node and returns the filename.
335 Caller needs to remove the returned file on the node when it's not needed
340 tmp = "tmp=%s" % utils.ShellQuote(filename)
342 tmp = "tmp=$(tempfile --mode %o --prefix gnt)" % mode
344 "[[ -f \"${tmp}\" ]] && "
345 "cat > \"${tmp}\" && "
346 "echo \"${tmp}\"") % tmp
348 p = subprocess.Popen(GetSSHCommand(node, cmd), shell=False,
349 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
352 AssertEqual(p.wait(), 0)
354 # Return temporary filename
355 return p.stdout.read().strip()
358 def BackupFile(node, path):
359 """Creates a backup of a file on the node and returns the filename.
361 Caller needs to remove the returned file on the node when it's not needed
365 cmd = ("tmp=$(tempfile --prefix .gnt --directory=$(dirname %s)) && "
366 "[[ -f \"$tmp\" ]] && "
368 "echo $tmp") % (utils.ShellQuote(path), utils.ShellQuote(path))
370 # Return temporary filename
371 return GetCommandOutput(node, cmd).strip()
374 def _ResolveName(cmd, key):
378 master = qa_config.GetMasterNode()
380 output = GetCommandOutput(master["primary"], utils.ShellQuoteArgs(cmd))
381 for line in output.splitlines():
382 (lkey, lvalue) = line.split(":", 1)
384 return lvalue.lstrip()
385 raise KeyError("Key not found")
388 def ResolveInstanceName(instance):
389 """Gets the full name of an instance.
391 @type instance: string
392 @param instance: Instance name
395 return _ResolveName(["gnt-instance", "info", instance],
399 def ResolveNodeName(node):
400 """Gets the full name of a node.
403 return _ResolveName(["gnt-node", "info", node["primary"]],
407 def GetNodeInstances(node, secondaries=False):
408 """Gets a list of instances on a node.
411 master = qa_config.GetMasterNode()
412 node_name = ResolveNodeName(node)
414 # Get list of all instances
415 cmd = ["gnt-instance", "list", "--separator=:", "--no-headers",
416 "--output=name,pnode,snodes"]
417 output = GetCommandOutput(master["primary"], utils.ShellQuoteArgs(cmd))
420 for line in output.splitlines():
421 (name, pnode, snodes) = line.split(":", 2)
422 if ((not secondaries and pnode == node_name) or
423 (secondaries and node_name in snodes.split(","))):
424 instances.append(name)
429 def _SelectQueryFields(rnd, fields):
430 """Generates a list of fields for query tests.
433 # Create copy for shuffling
434 fields = list(fields)
442 yield fields + fields
444 # Check small groups of fields
446 yield [fields.pop() for _ in range(rnd.randint(2, 10)) if fields]
449 def _List(listcmd, fields, names):
450 """Runs a list command.
453 master = qa_config.GetMasterNode()
455 cmd = [listcmd, "list", "--separator=|", "--no-headers",
456 "--output", ",".join(fields)]
461 return GetCommandOutput(master["primary"],
462 utils.ShellQuoteArgs(cmd)).splitlines()
465 def GenericQueryTest(cmd, fields, namefield="name", test_unknown=True):
466 """Runs a number of tests on query commands.
468 @param cmd: Command name
469 @param fields: List of field names
472 rnd = random.Random(hash(cmd))
474 fields = list(fields)
477 # Test a number of field combinations
478 for testfields in _SelectQueryFields(rnd, fields):
479 AssertCommand([cmd, "list", "--output", ",".join(testfields)])
481 if namefield is not None:
482 namelist_fn = compat.partial(_List, cmd, [namefield])
484 # When no names were requested, the list must be sorted
485 names = namelist_fn(None)
486 AssertEqual(names, utils.NiceSort(names))
488 # When requesting specific names, the order must be kept
489 revnames = list(reversed(names))
490 AssertEqual(namelist_fn(revnames), revnames)
492 randnames = list(names)
493 rnd.shuffle(randnames)
494 AssertEqual(namelist_fn(randnames), randnames)
497 # Listing unknown items must fail
498 AssertCommand([cmd, "list", "this.name.certainly.does.not.exist"],
501 # Check exit code for listing unknown field
502 AssertEqual(AssertCommand([cmd, "list", "--output=field/does/not/exist"],
504 constants.EXIT_UNKNOWN_FIELD)
507 def GenericQueryFieldsTest(cmd, fields):
508 master = qa_config.GetMasterNode()
511 AssertCommand([cmd, "list-fields"])
512 AssertCommand([cmd, "list-fields"] + fields)
514 # Check listed fields (all, must be sorted)
515 realcmd = [cmd, "list-fields", "--separator=|", "--no-headers"]
516 output = GetCommandOutput(master["primary"],
517 utils.ShellQuoteArgs(realcmd)).splitlines()
518 AssertEqual([line.split("|", 1)[0] for line in output],
519 utils.NiceSort(fields))
521 # Check exit code for listing unknown field
522 AssertEqual(AssertCommand([cmd, "list-fields", "field/does/not/exist"],
524 constants.EXIT_UNKNOWN_FIELD)
527 def _FormatWithColor(text, seq):
530 return "%s%s%s" % (seq, text, _RESET_SEQ)
533 FormatWarning = lambda text: _FormatWithColor(text, _WARNING_SEQ)
534 FormatError = lambda text: _FormatWithColor(text, _ERROR_SEQ)
535 FormatInfo = lambda text: _FormatWithColor(text, _INFO_SEQ)
538 def AddToEtcHosts(hostnames):
539 """Adds hostnames to /etc/hosts.
541 @param hostnames: List of hostnames first used A records, all other CNAMEs
544 master = qa_config.GetMasterNode()
545 tmp_hosts = UploadData(master["primary"], "", mode=0644)
548 for localhost in ("::1", "127.0.0.1"):
549 data.append("%s %s" % (localhost, " ".join(hostnames)))
552 AssertCommand("{ cat %s && echo -e '%s'; } > %s && mv %s %s" %
553 (utils.ShellQuote(pathutils.ETC_HOSTS),
555 utils.ShellQuote(tmp_hosts),
556 utils.ShellQuote(tmp_hosts),
557 utils.ShellQuote(pathutils.ETC_HOSTS)))
559 AssertCommand(["rm", "-f", tmp_hosts])
563 def RemoveFromEtcHosts(hostnames):
564 """Remove hostnames from /etc/hosts.
566 @param hostnames: List of hostnames first used A records, all other CNAMEs
569 master = qa_config.GetMasterNode()
570 tmp_hosts = UploadData(master["primary"], "", mode=0644)
571 quoted_tmp_hosts = utils.ShellQuote(tmp_hosts)
573 sed_data = " ".join(hostnames)
575 AssertCommand(("sed -e '/^\(::1\|127\.0\.0\.1\)\s\+%s/d' %s > %s"
577 (sed_data, utils.ShellQuote(pathutils.ETC_HOSTS),
578 quoted_tmp_hosts, quoted_tmp_hosts,
579 utils.ShellQuote(pathutils.ETC_HOSTS)))
581 AssertCommand(["rm", "-f", tmp_hosts])
585 def RunInstanceCheck(instance, running):
586 """Check if instance is running or not.
589 instance_name = _GetName(instance, "name")
591 script = qa_config.GetInstanceCheckScript()
595 master_node = qa_config.GetMasterNode()
597 # Build command to connect to master node
598 master_ssh = GetSSHCommand(master_node["primary"], "--")
601 running_shellval = "1"
604 running_shellval = ""
605 running_text = "not "
607 print FormatInfo("Checking if instance '%s' is %srunning" %
608 (instance_name, running_text))
610 args = [script, instance_name]
612 "PATH": constants.HOOKS_PATH,
613 "RUN_UUID": _RUN_UUID,
614 "MASTER_SSH": utils.ShellQuoteArgs(master_ssh),
615 "INSTANCE_NAME": instance_name,
616 "INSTANCE_RUNNING": running_shellval,
619 result = os.spawnve(os.P_WAIT, script, args, env)
621 raise qa_error.Error("Instance check failed with result %s" % result)
624 def _InstanceCheckInner(expected, instarg, args, result):
625 """Helper function used by L{InstanceCheck}.
628 if instarg == FIRST_ARG:
630 elif instarg == RETURN_VALUE:
633 raise Exception("Invalid value '%s' for instance argument" % instarg)
635 if expected in (INST_DOWN, INST_UP):
636 RunInstanceCheck(instance, (expected == INST_UP))
637 elif expected is not None:
638 raise Exception("Invalid value '%s'" % expected)
641 def InstanceCheck(before, after, instarg):
642 """Decorator to check instance status before and after test.
644 @param before: L{INST_DOWN} if instance must be stopped before test,
645 L{INST_UP} if instance must be running before test, L{None} to not check.
646 @param after: L{INST_DOWN} if instance must be stopped after test,
647 L{INST_UP} if instance must be running after test, L{None} to not check.
648 @param instarg: L{FIRST_ARG} to use first argument to test as instance (a
649 dictionary), L{RETURN_VALUE} to use return value (disallows pre-checks)
654 def wrapper(*args, **kwargs):
655 _InstanceCheckInner(before, instarg, args, NotImplemented)
657 result = fn(*args, **kwargs)
659 _InstanceCheckInner(after, instarg, args, result)
666 def GetNonexistentGroups(count):
667 """Gets group names which shouldn't exist on the cluster.
669 @param count: Number of groups to get
673 groups = qa_config.get("groups", {})
675 default = ["group1", "group2", "group3"]
676 assert count <= len(default)
678 candidates = groups.get("inexistent-groups", default)[:count]
680 if len(candidates) < count:
681 raise Exception("At least %s non-existent groups are needed" % count)