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.
36 except ImportError, err:
37 raise ImportError("Python 2.5 or higher is required: %s" % err)
39 from ganeti import utils
40 from ganeti import compat
41 from ganeti import constants
43 from ganeti import pathutils
44 from ganeti import vcluster
57 #: Unique ID per QA run
58 _RUN_UUID = utils.NewUUID()
60 #: Path to the QA query output log file
61 _QA_OUTPUT = pathutils.GetLogFilename("qa-output")
65 INST_UP) = range(500, 502)
68 RETURN_VALUE) = range(1000, 1002)
72 """Initializes the colour constants.
75 # pylint: disable=W0603
77 global _INFO_SEQ, _WARNING_SEQ, _ERROR_SEQ, _RESET_SEQ
79 # Don't use colours if stdout isn't a terminal
80 if not sys.stdout.isatty():
86 # Don't use colours if curses module can't be imported
91 _RESET_SEQ = curses.tigetstr("op")
93 setaf = curses.tigetstr("setaf")
94 _INFO_SEQ = curses.tparm(setaf, curses.COLOR_GREEN)
95 _WARNING_SEQ = curses.tparm(setaf, curses.COLOR_YELLOW)
96 _ERROR_SEQ = curses.tparm(setaf, curses.COLOR_RED)
102 def AssertIn(item, sequence):
103 """Raises an error when item is not in sequence.
106 if item not in sequence:
107 raise qa_error.Error("%r not in %r" % (item, sequence))
110 def AssertNotIn(item, sequence):
111 """Raises an error when item is in sequence.
115 raise qa_error.Error("%r in %r" % (item, sequence))
118 def AssertEqual(first, second):
119 """Raises an error when values aren't equal.
122 if not first == second:
123 raise qa_error.Error("%r == %r" % (first, second))
126 def AssertMatch(string, pattern):
127 """Raises an error when string doesn't match regexp pattern.
130 if not re.match(pattern, string):
131 raise qa_error.Error("%r doesn't match /%r/" % (string, pattern))
134 def _GetName(entity, fn):
135 """Tries to get name of an entity.
137 @type entity: string or dict
138 @param fn: Function retrieving name from entity
141 if isinstance(entity, basestring):
146 if not ht.TNonEmptyString(result):
147 raise Exception("Invalid name '%s'" % result)
152 def _AssertRetCode(rcode, fail, cmdstr, nodename):
153 """Check the return value from a command and possibly raise an exception.
156 if fail and rcode == 0:
157 raise qa_error.Error("Command '%s' on node %s was expected to fail but"
158 " didn't" % (cmdstr, nodename))
159 elif not fail and rcode != 0:
160 raise qa_error.Error("Command '%s' on node %s failed, exit code %s" %
161 (cmdstr, nodename, rcode))
164 def AssertCommand(cmd, fail=False, node=None, log_cmd=True):
165 """Checks that a remote command succeeds.
167 @param cmd: either a string (the command to execute) or a list (to
168 be converted using L{utils.ShellQuoteArgs} into a string)
170 @param fail: if the command is expected to fail instead of succeeding
171 @param node: if passed, it should be the node on which the command
172 should be executed, instead of the master node (can be either a
174 @param log_cmd: if False, the command won't be logged (simply passed to
176 @return: the return code of the command
177 @raise qa_error.Error: if the command fails when it shouldn't or vice versa
181 node = qa_config.GetMasterNode()
183 nodename = _GetName(node, operator.attrgetter("primary"))
185 if isinstance(cmd, basestring):
188 cmdstr = utils.ShellQuoteArgs(cmd)
190 rcode = StartSSH(nodename, cmdstr, log_cmd=log_cmd).wait()
191 _AssertRetCode(rcode, fail, cmdstr, nodename)
196 def AssertRedirectedCommand(cmd, fail=False, node=None, log_cmd=True):
197 """Executes a command with redirected output.
199 The log will go to the qa-output log file in the ganeti log
200 directory on the node where the command is executed. The fail and
201 node parameters are passed unchanged to AssertCommand.
203 @param cmd: the command to be executed, as a list; a string is not
207 if not isinstance(cmd, list):
208 raise qa_error.Error("Non-list passed to AssertRedirectedCommand")
209 ofile = utils.ShellQuote(_QA_OUTPUT)
210 cmdstr = utils.ShellQuoteArgs(cmd)
211 AssertCommand("echo ---- $(date) %s ---- >> %s" % (cmdstr, ofile),
212 fail=False, node=node, log_cmd=False)
213 return AssertCommand(cmdstr + " >> %s" % ofile,
214 fail=fail, node=node, log_cmd=log_cmd)
217 def GetSSHCommand(node, cmd, strict=True, opts=None, tty=None):
218 """Builds SSH command to be executed.
221 @param node: node the command should run on
223 @param cmd: command to be executed in the node; if None or empty
224 string, no command will be executed
225 @type strict: boolean
226 @param strict: whether to enable strict host key checking
228 @param opts: list of additional options
229 @type tty: boolean or None
230 @param tty: if we should use tty; if None, will be auto-detected
233 args = ["ssh", "-oEscapeChar=none", "-oBatchMode=yes", "-lroot"]
236 tty = sys.stdout.isatty()
245 args.append("-oStrictHostKeyChecking=%s" % tmp)
246 args.append("-oClearAllForwardings=yes")
247 args.append("-oForwardAgent=yes")
250 if node in _MULTIPLEXERS:
251 spath = _MULTIPLEXERS[node][0]
252 args.append("-oControlPath=%s" % spath)
253 args.append("-oControlMaster=no")
255 (vcluster_master, vcluster_basedir) = \
256 qa_config.GetVclusterSettings()
259 args.append(vcluster_master)
260 args.append("%s/%s/cmd" % (vcluster_basedir, node))
263 # For virtual clusters the whole command must be wrapped using the "cmd"
264 # script, as that script sets a number of environment variables. If the
265 # command contains shell meta characters the whole command needs to be
267 args.append(utils.ShellQuote(cmd))
277 def StartLocalCommand(cmd, _nolog_opts=False, log_cmd=True, **kwargs):
278 """Starts a local command.
283 pcmd = [i for i in cmd if not i.startswith("-")]
286 print "Command: %s" % utils.ShellQuoteArgs(pcmd)
287 return subprocess.Popen(cmd, shell=False, **kwargs)
290 def StartSSH(node, cmd, strict=True, log_cmd=True):
294 return StartLocalCommand(GetSSHCommand(node, cmd, strict=strict),
295 _nolog_opts=True, log_cmd=log_cmd)
298 def StartMultiplexer(node):
299 """Starts a multiplexer command.
301 @param node: the node for which to open the multiplexer
304 if node in _MULTIPLEXERS:
307 # Note: yes, we only need mktemp, since we'll remove the file anyway
308 sname = tempfile.mktemp(prefix="ganeti-qa-multiplexer.")
309 utils.RemoveFile(sname)
310 opts = ["-N", "-oControlPath=%s" % sname, "-oControlMaster=yes"]
311 print "Created socket at %s" % sname
312 child = StartLocalCommand(GetSSHCommand(node, None, opts=opts))
313 _MULTIPLEXERS[node] = (sname, child)
316 def CloseMultiplexers():
317 """Closes all current multiplexers and cleans up.
320 for node in _MULTIPLEXERS.keys():
321 (sname, child) = _MULTIPLEXERS.pop(node)
322 utils.KillProcess(child.pid, timeout=10, waitpid=True)
323 utils.RemoveFile(sname)
326 def GetCommandOutput(node, cmd, tty=None, fail=False):
327 """Returns the output of a command executed on the given node.
330 @param node: node the command should run on
332 @param cmd: command to be executed in the node (cannot be empty or None)
333 @type tty: bool or None
334 @param tty: if we should use tty; if None, it will be auto-detected
336 @param fail: whether the command is expected to fail
339 p = StartLocalCommand(GetSSHCommand(node, cmd, tty=tty),
340 stdout=subprocess.PIPE)
342 _AssertRetCode(rcode, fail, cmd, node)
343 return p.stdout.read()
346 def UploadFile(node, src):
347 """Uploads a file to a node and returns the filename.
349 Caller needs to remove the returned file on the node when it's not needed
353 # Make sure nobody else has access to it while preserving local permissions
354 mode = os.stat(src).st_mode & 0700
356 cmd = ('tmp=$(tempfile --mode %o --prefix gnt) && '
357 '[[ -f "${tmp}" ]] && '
359 'echo "${tmp}"') % mode
363 p = subprocess.Popen(GetSSHCommand(node, cmd), shell=False, stdin=f,
364 stdout=subprocess.PIPE)
365 AssertEqual(p.wait(), 0)
367 # Return temporary filename
368 return p.stdout.read().strip()
373 def UploadData(node, data, mode=0600, filename=None):
374 """Uploads data to a node and returns the filename.
376 Caller needs to remove the returned file on the node when it's not needed
381 tmp = "tmp=%s" % utils.ShellQuote(filename)
383 tmp = "tmp=$(tempfile --mode %o --prefix gnt)" % mode
385 "[[ -f \"${tmp}\" ]] && "
386 "cat > \"${tmp}\" && "
387 "echo \"${tmp}\"") % tmp
389 p = subprocess.Popen(GetSSHCommand(node, cmd), shell=False,
390 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
393 AssertEqual(p.wait(), 0)
395 # Return temporary filename
396 return p.stdout.read().strip()
399 def BackupFile(node, path):
400 """Creates a backup of a file on the node and returns the filename.
402 Caller needs to remove the returned file on the node when it's not needed
406 vpath = MakeNodePath(node, path)
408 cmd = ("tmp=$(tempfile --prefix .gnt --directory=$(dirname %s)) && "
409 "[[ -f \"$tmp\" ]] && "
411 "echo $tmp") % (utils.ShellQuote(vpath), utils.ShellQuote(vpath))
413 # Return temporary filename
414 result = GetCommandOutput(node, cmd).strip()
416 print "Backup filename: %s" % result
421 def _ResolveName(cmd, key):
425 master = qa_config.GetMasterNode()
427 output = GetCommandOutput(master.primary, utils.ShellQuoteArgs(cmd))
428 for line in output.splitlines():
429 (lkey, lvalue) = line.split(":", 1)
431 return lvalue.lstrip()
432 raise KeyError("Key not found")
435 def ResolveInstanceName(instance):
436 """Gets the full name of an instance.
438 @type instance: string
439 @param instance: Instance name
442 return _ResolveName(["gnt-instance", "info", instance],
446 def ResolveNodeName(node):
447 """Gets the full name of a node.
450 return _ResolveName(["gnt-node", "info", node.primary],
454 def GetNodeInstances(node, secondaries=False):
455 """Gets a list of instances on a node.
458 master = qa_config.GetMasterNode()
459 node_name = ResolveNodeName(node)
461 # Get list of all instances
462 cmd = ["gnt-instance", "list", "--separator=:", "--no-headers",
463 "--output=name,pnode,snodes"]
464 output = GetCommandOutput(master.primary, utils.ShellQuoteArgs(cmd))
467 for line in output.splitlines():
468 (name, pnode, snodes) = line.split(":", 2)
469 if ((not secondaries and pnode == node_name) or
470 (secondaries and node_name in snodes.split(","))):
471 instances.append(name)
476 def _SelectQueryFields(rnd, fields):
477 """Generates a list of fields for query tests.
480 # Create copy for shuffling
481 fields = list(fields)
489 yield fields + fields
491 # Check small groups of fields
493 yield [fields.pop() for _ in range(rnd.randint(2, 10)) if fields]
496 def _List(listcmd, fields, names):
497 """Runs a list command.
500 master = qa_config.GetMasterNode()
502 cmd = [listcmd, "list", "--separator=|", "--no-headers",
503 "--output", ",".join(fields)]
508 return GetCommandOutput(master.primary,
509 utils.ShellQuoteArgs(cmd)).splitlines()
512 def GenericQueryTest(cmd, fields, namefield="name", test_unknown=True):
513 """Runs a number of tests on query commands.
515 @param cmd: Command name
516 @param fields: List of field names
519 rnd = random.Random(hash(cmd))
521 fields = list(fields)
524 # Test a number of field combinations
525 for testfields in _SelectQueryFields(rnd, fields):
526 AssertRedirectedCommand([cmd, "list", "--output", ",".join(testfields)])
528 if namefield is not None:
529 namelist_fn = compat.partial(_List, cmd, [namefield])
531 # When no names were requested, the list must be sorted
532 names = namelist_fn(None)
533 AssertEqual(names, utils.NiceSort(names))
535 # When requesting specific names, the order must be kept
536 revnames = list(reversed(names))
537 AssertEqual(namelist_fn(revnames), revnames)
539 randnames = list(names)
540 rnd.shuffle(randnames)
541 AssertEqual(namelist_fn(randnames), randnames)
544 # Listing unknown items must fail
545 AssertCommand([cmd, "list", "this.name.certainly.does.not.exist"],
548 # Check exit code for listing unknown field
549 AssertEqual(AssertRedirectedCommand([cmd, "list",
550 "--output=field/does/not/exist"],
552 constants.EXIT_UNKNOWN_FIELD)
555 def GenericQueryFieldsTest(cmd, fields):
556 master = qa_config.GetMasterNode()
559 AssertRedirectedCommand([cmd, "list-fields"])
560 AssertRedirectedCommand([cmd, "list-fields"] + fields)
562 # Check listed fields (all, must be sorted)
563 realcmd = [cmd, "list-fields", "--separator=|", "--no-headers"]
564 output = GetCommandOutput(master.primary,
565 utils.ShellQuoteArgs(realcmd)).splitlines()
566 AssertEqual([line.split("|", 1)[0] for line in output],
567 utils.NiceSort(fields))
569 # Check exit code for listing unknown field
570 AssertEqual(AssertCommand([cmd, "list-fields", "field/does/not/exist"],
572 constants.EXIT_UNKNOWN_FIELD)
575 def _FormatWithColor(text, seq):
578 return "%s%s%s" % (seq, text, _RESET_SEQ)
581 FormatWarning = lambda text: _FormatWithColor(text, _WARNING_SEQ)
582 FormatError = lambda text: _FormatWithColor(text, _ERROR_SEQ)
583 FormatInfo = lambda text: _FormatWithColor(text, _INFO_SEQ)
586 def AddToEtcHosts(hostnames):
587 """Adds hostnames to /etc/hosts.
589 @param hostnames: List of hostnames first used A records, all other CNAMEs
592 master = qa_config.GetMasterNode()
593 tmp_hosts = UploadData(master.primary, "", mode=0644)
596 for localhost in ("::1", "127.0.0.1"):
597 data.append("%s %s" % (localhost, " ".join(hostnames)))
600 AssertCommand("{ cat %s && echo -e '%s'; } > %s && mv %s %s" %
601 (utils.ShellQuote(pathutils.ETC_HOSTS),
603 utils.ShellQuote(tmp_hosts),
604 utils.ShellQuote(tmp_hosts),
605 utils.ShellQuote(pathutils.ETC_HOSTS)))
607 AssertCommand(["rm", "-f", tmp_hosts])
611 def RemoveFromEtcHosts(hostnames):
612 """Remove hostnames from /etc/hosts.
614 @param hostnames: List of hostnames first used A records, all other CNAMEs
617 master = qa_config.GetMasterNode()
618 tmp_hosts = UploadData(master.primary, "", mode=0644)
619 quoted_tmp_hosts = utils.ShellQuote(tmp_hosts)
621 sed_data = " ".join(hostnames)
623 AssertCommand(("sed -e '/^\(::1\|127\.0\.0\.1\)\s\+%s/d' %s > %s"
625 (sed_data, utils.ShellQuote(pathutils.ETC_HOSTS),
626 quoted_tmp_hosts, quoted_tmp_hosts,
627 utils.ShellQuote(pathutils.ETC_HOSTS)))
629 AssertCommand(["rm", "-f", tmp_hosts])
633 def RunInstanceCheck(instance, running):
634 """Check if instance is running or not.
637 instance_name = _GetName(instance, operator.attrgetter("name"))
639 script = qa_config.GetInstanceCheckScript()
643 master_node = qa_config.GetMasterNode()
645 # Build command to connect to master node
646 master_ssh = GetSSHCommand(master_node.primary, "--")
649 running_shellval = "1"
652 running_shellval = ""
653 running_text = "not "
655 print FormatInfo("Checking if instance '%s' is %srunning" %
656 (instance_name, running_text))
658 args = [script, instance_name]
660 "PATH": constants.HOOKS_PATH,
661 "RUN_UUID": _RUN_UUID,
662 "MASTER_SSH": utils.ShellQuoteArgs(master_ssh),
663 "INSTANCE_NAME": instance_name,
664 "INSTANCE_RUNNING": running_shellval,
667 result = os.spawnve(os.P_WAIT, script, args, env)
669 raise qa_error.Error("Instance check failed with result %s" % result)
672 def _InstanceCheckInner(expected, instarg, args, result):
673 """Helper function used by L{InstanceCheck}.
676 if instarg == FIRST_ARG:
678 elif instarg == RETURN_VALUE:
681 raise Exception("Invalid value '%s' for instance argument" % instarg)
683 if expected in (INST_DOWN, INST_UP):
684 RunInstanceCheck(instance, (expected == INST_UP))
685 elif expected is not None:
686 raise Exception("Invalid value '%s'" % expected)
689 def InstanceCheck(before, after, instarg):
690 """Decorator to check instance status before and after test.
692 @param before: L{INST_DOWN} if instance must be stopped before test,
693 L{INST_UP} if instance must be running before test, L{None} to not check.
694 @param after: L{INST_DOWN} if instance must be stopped after test,
695 L{INST_UP} if instance must be running after test, L{None} to not check.
696 @param instarg: L{FIRST_ARG} to use first argument to test as instance (a
697 dictionary), L{RETURN_VALUE} to use return value (disallows pre-checks)
702 def wrapper(*args, **kwargs):
703 _InstanceCheckInner(before, instarg, args, NotImplemented)
705 result = fn(*args, **kwargs)
707 _InstanceCheckInner(after, instarg, args, result)
714 def GetNonexistentGroups(count):
715 """Gets group names which shouldn't exist on the cluster.
717 @param count: Number of groups to get
721 return GetNonexistentEntityNames(count, "groups", "group")
724 def GetNonexistentEntityNames(count, name_config, name_prefix):
725 """Gets entity names which shouldn't exist on the cluster.
727 The actualy names can refer to arbitrary entities (for example
730 @param count: Number of names to get
732 @param name_config: name of the leaf in the config containing
733 this entity's configuration, including a 'inexistent-'
736 @param name_prefix: prefix of the entity's names, used to compose
737 the default values; for example for groups, the prefix is
738 'group' and the generated names are then group1, group2, ...
742 entities = qa_config.get(name_config, {})
744 default = [name_prefix + str(i) for i in range(count)]
745 assert count <= len(default)
747 name_config_inexistent = "inexistent-" + name_config
748 candidates = entities.get(name_config_inexistent, default)[:count]
750 if len(candidates) < count:
751 raise Exception("At least %s non-existent %s are needed" %
752 (count, name_config))
757 def MakeNodePath(node, path):
758 """Builds an absolute path for a virtual node.
760 @type node: string or L{qa_config._QaNode}
763 @param path: Path without node-specific prefix
766 (_, basedir) = qa_config.GetVclusterSettings()
768 if isinstance(node, basestring):
774 assert path.startswith("/")
775 return "%s%s" % (vcluster.MakeNodeRoot(basedir, name), path)