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.
38 except ImportError, err:
39 raise ImportError("Python 2.5 or higher is required: %s" % err)
41 from ganeti import utils
42 from ganeti import compat
43 from ganeti import constants
45 from ganeti import pathutils
46 from ganeti import vcluster
59 #: Unique ID per QA run
60 _RUN_UUID = utils.NewUUID()
62 #: Path to the QA query output log file
63 _QA_OUTPUT = pathutils.GetLogFilename("qa-output")
67 INST_UP) = range(500, 502)
70 RETURN_VALUE) = range(1000, 1002)
74 """Initializes the colour constants.
77 # pylint: disable=W0603
79 global _INFO_SEQ, _WARNING_SEQ, _ERROR_SEQ, _RESET_SEQ
81 # Don't use colours if stdout isn't a terminal
82 if not sys.stdout.isatty():
88 # Don't use colours if curses module can't be imported
93 _RESET_SEQ = curses.tigetstr("op")
95 setaf = curses.tigetstr("setaf")
96 _INFO_SEQ = curses.tparm(setaf, curses.COLOR_GREEN)
97 _WARNING_SEQ = curses.tparm(setaf, curses.COLOR_YELLOW)
98 _ERROR_SEQ = curses.tparm(setaf, curses.COLOR_RED)
104 def AssertIn(item, sequence):
105 """Raises an error when item is not in sequence.
108 if item not in sequence:
109 raise qa_error.Error("%r not in %r" % (item, sequence))
112 def AssertNotIn(item, sequence):
113 """Raises an error when item is in sequence.
117 raise qa_error.Error("%r in %r" % (item, sequence))
120 def AssertEqual(first, second):
121 """Raises an error when values aren't 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, fn):
137 """Tries to get name of an entity.
139 @type entity: string or dict
140 @param fn: Function retrieving name from entity
143 if isinstance(entity, basestring):
148 if not ht.TNonEmptyString(result):
149 raise Exception("Invalid name '%s'" % result)
154 def _AssertRetCode(rcode, fail, cmdstr, nodename):
155 """Check the return value from a command and possibly raise an exception.
158 if fail and rcode == 0:
159 raise qa_error.Error("Command '%s' on node %s was expected to fail but"
160 " didn't" % (cmdstr, nodename))
161 elif not fail and rcode != 0:
162 raise qa_error.Error("Command '%s' on node %s failed, exit code %s" %
163 (cmdstr, nodename, rcode))
166 def AssertCommand(cmd, fail=False, node=None, log_cmd=True):
167 """Checks that a remote command succeeds.
169 @param cmd: either a string (the command to execute) or a list (to
170 be converted using L{utils.ShellQuoteArgs} into a string)
172 @param fail: if the command is expected to fail instead of succeeding
173 @param node: if passed, it should be the node on which the command
174 should be executed, instead of the master node (can be either a
176 @param log_cmd: if False, the command won't be logged (simply passed to
178 @return: the return code of the command
179 @raise qa_error.Error: if the command fails when it shouldn't or vice versa
183 node = qa_config.GetMasterNode()
185 nodename = _GetName(node, operator.attrgetter("primary"))
187 if isinstance(cmd, basestring):
190 cmdstr = utils.ShellQuoteArgs(cmd)
192 rcode = StartSSH(nodename, cmdstr, log_cmd=log_cmd).wait()
193 _AssertRetCode(rcode, fail, cmdstr, nodename)
198 def AssertRedirectedCommand(cmd, fail=False, node=None, log_cmd=True):
199 """Executes a command with redirected output.
201 The log will go to the qa-output log file in the ganeti log
202 directory on the node where the command is executed. The fail and
203 node parameters are passed unchanged to AssertCommand.
205 @param cmd: the command to be executed, as a list; a string is not
209 if not isinstance(cmd, list):
210 raise qa_error.Error("Non-list passed to AssertRedirectedCommand")
211 ofile = utils.ShellQuote(_QA_OUTPUT)
212 cmdstr = utils.ShellQuoteArgs(cmd)
213 AssertCommand("echo ---- $(date) %s ---- >> %s" % (cmdstr, ofile),
214 fail=False, node=node, log_cmd=False)
215 return AssertCommand(cmdstr + " >> %s" % ofile,
216 fail=fail, node=node, log_cmd=log_cmd)
219 def GetSSHCommand(node, cmd, strict=True, opts=None, tty=None):
220 """Builds SSH command to be executed.
223 @param node: node the command should run on
225 @param cmd: command to be executed in the node; if None or empty
226 string, no command will be executed
227 @type strict: boolean
228 @param strict: whether to enable strict host key checking
230 @param opts: list of additional options
231 @type tty: boolean or None
232 @param tty: if we should use tty; if None, will be auto-detected
235 args = ["ssh", "-oEscapeChar=none", "-oBatchMode=yes", "-lroot"]
238 tty = sys.stdout.isatty()
247 args.append("-oStrictHostKeyChecking=%s" % tmp)
248 args.append("-oClearAllForwardings=yes")
249 args.append("-oForwardAgent=yes")
252 if node in _MULTIPLEXERS:
253 spath = _MULTIPLEXERS[node][0]
254 args.append("-oControlPath=%s" % spath)
255 args.append("-oControlMaster=no")
257 (vcluster_master, vcluster_basedir) = \
258 qa_config.GetVclusterSettings()
261 args.append(vcluster_master)
262 args.append("%s/%s/cmd" % (vcluster_basedir, node))
265 # For virtual clusters the whole command must be wrapped using the "cmd"
266 # script, as that script sets a number of environment variables. If the
267 # command contains shell meta characters the whole command needs to be
269 args.append(utils.ShellQuote(cmd))
279 def StartLocalCommand(cmd, _nolog_opts=False, log_cmd=True, **kwargs):
280 """Starts a local command.
285 pcmd = [i for i in cmd if not i.startswith("-")]
288 print "Command: %s" % utils.ShellQuoteArgs(pcmd)
289 return subprocess.Popen(cmd, shell=False, **kwargs)
292 def StartSSH(node, cmd, strict=True, log_cmd=True):
296 return StartLocalCommand(GetSSHCommand(node, cmd, strict=strict),
297 _nolog_opts=True, log_cmd=log_cmd)
300 def StartMultiplexer(node):
301 """Starts a multiplexer command.
303 @param node: the node for which to open the multiplexer
306 if node in _MULTIPLEXERS:
309 # Note: yes, we only need mktemp, since we'll remove the file anyway
310 sname = tempfile.mktemp(prefix="ganeti-qa-multiplexer.")
311 utils.RemoveFile(sname)
312 opts = ["-N", "-oControlPath=%s" % sname, "-oControlMaster=yes"]
313 print "Created socket at %s" % sname
314 child = StartLocalCommand(GetSSHCommand(node, None, opts=opts))
315 _MULTIPLEXERS[node] = (sname, child)
318 def CloseMultiplexers():
319 """Closes all current multiplexers and cleans up.
322 for node in _MULTIPLEXERS.keys():
323 (sname, child) = _MULTIPLEXERS.pop(node)
324 utils.KillProcess(child.pid, timeout=10, waitpid=True)
325 utils.RemoveFile(sname)
328 def GetCommandOutput(node, cmd, tty=None, fail=False):
329 """Returns the output of a command executed on the given node.
332 @param node: node the command should run on
334 @param cmd: command to be executed in the node (cannot be empty or None)
335 @type tty: bool or None
336 @param tty: if we should use tty; if None, it will be auto-detected
338 @param fail: whether the command is expected to fail
341 p = StartLocalCommand(GetSSHCommand(node, cmd, tty=tty),
342 stdout=subprocess.PIPE)
344 _AssertRetCode(rcode, fail, cmd, node)
345 return p.stdout.read()
348 def GetObjectInfo(infocmd):
349 """Get and parse information about a Ganeti object.
351 @type infocmd: list of strings
352 @param infocmd: command to be executed, e.g. ["gnt-cluster", "info"]
353 @return: the information parsed, appropriately stored in dictionaries,
357 master = qa_config.GetMasterNode()
358 cmdline = utils.ShellQuoteArgs(infocmd)
359 info_out = GetCommandOutput(master.primary, cmdline)
360 return yaml.load(info_out)
363 def UploadFile(node, src):
364 """Uploads a file to a node and returns the filename.
366 Caller needs to remove the returned file on the node when it's not needed
370 # Make sure nobody else has access to it while preserving local permissions
371 mode = os.stat(src).st_mode & 0700
373 cmd = ('tmp=$(mktemp --tmpdir gnt.XXXXXX) && '
374 'chmod %o "${tmp}" && '
375 '[[ -f "${tmp}" ]] && '
377 'echo "${tmp}"') % mode
381 p = subprocess.Popen(GetSSHCommand(node, cmd), shell=False, stdin=f,
382 stdout=subprocess.PIPE)
383 AssertEqual(p.wait(), 0)
385 # Return temporary filename
386 return p.stdout.read().strip()
391 def UploadData(node, data, mode=0600, filename=None):
392 """Uploads data to a node and returns the filename.
394 Caller needs to remove the returned file on the node when it's not needed
399 tmp = "tmp=%s" % utils.ShellQuote(filename)
401 tmp = ('tmp=$(mktemp --tmpdir gnt.XXXXXX) && '
402 'chmod %o "${tmp}"') % mode
404 "[[ -f \"${tmp}\" ]] && "
405 "cat > \"${tmp}\" && "
406 "echo \"${tmp}\"") % tmp
408 p = subprocess.Popen(GetSSHCommand(node, cmd), shell=False,
409 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
412 AssertEqual(p.wait(), 0)
414 # Return temporary filename
415 return p.stdout.read().strip()
418 def BackupFile(node, path):
419 """Creates a backup of a file on the node and returns the filename.
421 Caller needs to remove the returned file on the node when it's not needed
425 vpath = MakeNodePath(node, path)
427 cmd = ("tmp=$(mktemp .gnt.XXXXXX --tmpdir=$(dirname %s)) && "
428 "[[ -f \"$tmp\" ]] && "
430 "echo $tmp") % (utils.ShellQuote(vpath), utils.ShellQuote(vpath))
432 # Return temporary filename
433 result = GetCommandOutput(node, cmd).strip()
435 print "Backup filename: %s" % result
440 def ResolveInstanceName(instance):
441 """Gets the full name of an instance.
443 @type instance: string
444 @param instance: Instance name
447 info = GetObjectInfo(["gnt-instance", "info", instance])
448 return info[0]["Instance name"]
451 def ResolveNodeName(node):
452 """Gets the full name of a node.
455 info = GetObjectInfo(["gnt-node", "info", node.primary])
456 return info[0]["Node name"]
459 def GetNodeInstances(node, secondaries=False):
460 """Gets a list of instances on a node.
463 master = qa_config.GetMasterNode()
464 node_name = ResolveNodeName(node)
466 # Get list of all instances
467 cmd = ["gnt-instance", "list", "--separator=:", "--no-headers",
468 "--output=name,pnode,snodes"]
469 output = GetCommandOutput(master.primary, utils.ShellQuoteArgs(cmd))
472 for line in output.splitlines():
473 (name, pnode, snodes) = line.split(":", 2)
474 if ((not secondaries and pnode == node_name) or
475 (secondaries and node_name in snodes.split(","))):
476 instances.append(name)
481 def _SelectQueryFields(rnd, fields):
482 """Generates a list of fields for query tests.
485 # Create copy for shuffling
486 fields = list(fields)
494 yield fields + fields
496 # Check small groups of fields
498 yield [fields.pop() for _ in range(rnd.randint(2, 10)) if fields]
501 def _List(listcmd, fields, names):
502 """Runs a list command.
505 master = qa_config.GetMasterNode()
507 cmd = [listcmd, "list", "--separator=|", "--no-headers",
508 "--output", ",".join(fields)]
513 return GetCommandOutput(master.primary,
514 utils.ShellQuoteArgs(cmd)).splitlines()
517 def GenericQueryTest(cmd, fields, namefield="name", test_unknown=True):
518 """Runs a number of tests on query commands.
520 @param cmd: Command name
521 @param fields: List of field names
524 rnd = random.Random(hash(cmd))
526 fields = list(fields)
529 # Test a number of field combinations
530 for testfields in _SelectQueryFields(rnd, fields):
531 AssertRedirectedCommand([cmd, "list", "--output", ",".join(testfields)])
533 if namefield is not None:
534 namelist_fn = compat.partial(_List, cmd, [namefield])
536 # When no names were requested, the list must be sorted
537 names = namelist_fn(None)
538 AssertEqual(names, utils.NiceSort(names))
540 # When requesting specific names, the order must be kept
541 revnames = list(reversed(names))
542 AssertEqual(namelist_fn(revnames), revnames)
544 randnames = list(names)
545 rnd.shuffle(randnames)
546 AssertEqual(namelist_fn(randnames), randnames)
549 # Listing unknown items must fail
550 AssertCommand([cmd, "list", "this.name.certainly.does.not.exist"],
553 # Check exit code for listing unknown field
554 AssertEqual(AssertRedirectedCommand([cmd, "list",
555 "--output=field/does/not/exist"],
557 constants.EXIT_UNKNOWN_FIELD)
560 def GenericQueryFieldsTest(cmd, fields):
561 master = qa_config.GetMasterNode()
564 AssertRedirectedCommand([cmd, "list-fields"])
565 AssertRedirectedCommand([cmd, "list-fields"] + fields)
567 # Check listed fields (all, must be sorted)
568 realcmd = [cmd, "list-fields", "--separator=|", "--no-headers"]
569 output = GetCommandOutput(master.primary,
570 utils.ShellQuoteArgs(realcmd)).splitlines()
571 AssertEqual([line.split("|", 1)[0] for line in output],
572 utils.NiceSort(fields))
574 # Check exit code for listing unknown field
575 AssertEqual(AssertCommand([cmd, "list-fields", "field/does/not/exist"],
577 constants.EXIT_UNKNOWN_FIELD)
580 def _FormatWithColor(text, seq):
583 return "%s%s%s" % (seq, text, _RESET_SEQ)
586 FormatWarning = lambda text: _FormatWithColor(text, _WARNING_SEQ)
587 FormatError = lambda text: _FormatWithColor(text, _ERROR_SEQ)
588 FormatInfo = lambda text: _FormatWithColor(text, _INFO_SEQ)
591 def AddToEtcHosts(hostnames):
592 """Adds hostnames to /etc/hosts.
594 @param hostnames: List of hostnames first used A records, all other CNAMEs
597 master = qa_config.GetMasterNode()
598 tmp_hosts = UploadData(master.primary, "", mode=0644)
601 for localhost in ("::1", "127.0.0.1"):
602 data.append("%s %s" % (localhost, " ".join(hostnames)))
605 AssertCommand("{ cat %s && echo -e '%s'; } > %s && mv %s %s" %
606 (utils.ShellQuote(pathutils.ETC_HOSTS),
608 utils.ShellQuote(tmp_hosts),
609 utils.ShellQuote(tmp_hosts),
610 utils.ShellQuote(pathutils.ETC_HOSTS)))
612 AssertCommand(["rm", "-f", tmp_hosts])
616 def RemoveFromEtcHosts(hostnames):
617 """Remove hostnames from /etc/hosts.
619 @param hostnames: List of hostnames first used A records, all other CNAMEs
622 master = qa_config.GetMasterNode()
623 tmp_hosts = UploadData(master.primary, "", mode=0644)
624 quoted_tmp_hosts = utils.ShellQuote(tmp_hosts)
626 sed_data = " ".join(hostnames)
628 AssertCommand(("sed -e '/^\(::1\|127\.0\.0\.1\)\s\+%s/d' %s > %s"
630 (sed_data, utils.ShellQuote(pathutils.ETC_HOSTS),
631 quoted_tmp_hosts, quoted_tmp_hosts,
632 utils.ShellQuote(pathutils.ETC_HOSTS)))
634 AssertCommand(["rm", "-f", tmp_hosts])
638 def RunInstanceCheck(instance, running):
639 """Check if instance is running or not.
642 instance_name = _GetName(instance, operator.attrgetter("name"))
644 script = qa_config.GetInstanceCheckScript()
648 master_node = qa_config.GetMasterNode()
650 # Build command to connect to master node
651 master_ssh = GetSSHCommand(master_node.primary, "--")
654 running_shellval = "1"
657 running_shellval = ""
658 running_text = "not "
660 print FormatInfo("Checking if instance '%s' is %srunning" %
661 (instance_name, running_text))
663 args = [script, instance_name]
665 "PATH": constants.HOOKS_PATH,
666 "RUN_UUID": _RUN_UUID,
667 "MASTER_SSH": utils.ShellQuoteArgs(master_ssh),
668 "INSTANCE_NAME": instance_name,
669 "INSTANCE_RUNNING": running_shellval,
672 result = os.spawnve(os.P_WAIT, script, args, env)
674 raise qa_error.Error("Instance check failed with result %s" % result)
677 def _InstanceCheckInner(expected, instarg, args, result):
678 """Helper function used by L{InstanceCheck}.
681 if instarg == FIRST_ARG:
683 elif instarg == RETURN_VALUE:
686 raise Exception("Invalid value '%s' for instance argument" % instarg)
688 if expected in (INST_DOWN, INST_UP):
689 RunInstanceCheck(instance, (expected == INST_UP))
690 elif expected is not None:
691 raise Exception("Invalid value '%s'" % expected)
694 def InstanceCheck(before, after, instarg):
695 """Decorator to check instance status before and after test.
697 @param before: L{INST_DOWN} if instance must be stopped before test,
698 L{INST_UP} if instance must be running before test, L{None} to not check.
699 @param after: L{INST_DOWN} if instance must be stopped after test,
700 L{INST_UP} if instance must be running after test, L{None} to not check.
701 @param instarg: L{FIRST_ARG} to use first argument to test as instance (a
702 dictionary), L{RETURN_VALUE} to use return value (disallows pre-checks)
707 def wrapper(*args, **kwargs):
708 _InstanceCheckInner(before, instarg, args, NotImplemented)
710 result = fn(*args, **kwargs)
712 _InstanceCheckInner(after, instarg, args, result)
719 def GetNonexistentGroups(count):
720 """Gets group names which shouldn't exist on the cluster.
722 @param count: Number of groups to get
726 return GetNonexistentEntityNames(count, "groups", "group")
729 def GetNonexistentEntityNames(count, name_config, name_prefix):
730 """Gets entity names which shouldn't exist on the cluster.
732 The actualy names can refer to arbitrary entities (for example
735 @param count: Number of names to get
737 @param name_config: name of the leaf in the config containing
738 this entity's configuration, including a 'inexistent-'
741 @param name_prefix: prefix of the entity's names, used to compose
742 the default values; for example for groups, the prefix is
743 'group' and the generated names are then group1, group2, ...
747 entities = qa_config.get(name_config, {})
749 default = [name_prefix + str(i) for i in range(count)]
750 assert count <= len(default)
752 name_config_inexistent = "inexistent-" + name_config
753 candidates = entities.get(name_config_inexistent, default)[:count]
755 if len(candidates) < count:
756 raise Exception("At least %s non-existent %s are needed" %
757 (count, name_config))
762 def MakeNodePath(node, path):
763 """Builds an absolute path for a virtual node.
765 @type node: string or L{qa_config._QaNode}
768 @param path: Path without node-specific prefix
771 (_, basedir) = qa_config.GetVclusterSettings()
773 if isinstance(node, basestring):
779 assert path.startswith("/")
780 return "%s%s" % (vcluster.MakeNodeRoot(basedir, name), path)
785 def _GetParameterOptions(specs):
786 """Helper to build policy options."""
787 values = ["%s=%s" % (par, val)
788 for (par, val) in specs.items()]
789 return ",".join(values)
792 def TestSetISpecs(new_specs=None, diff_specs=None, get_policy_fn=None,
793 build_cmd_fn=None, fail=False, old_values=None):
794 """Change instance specs for an object.
796 At most one of new_specs or diff_specs can be specified.
798 @type new_specs: dict
799 @param new_specs: new complete specs, in the same format returned by
801 @type diff_specs: dict
802 @param diff_specs: partial specs, it can be an incomplete specifications, but
803 if min/max specs are specified, their number must match the number of the
805 @type get_policy_fn: function
806 @param get_policy_fn: function that returns the current policy as in
808 @type build_cmd_fn: function
809 @param build_cmd_fn: function that return the full command line from the
812 @param fail: if the change is expected to fail
813 @type old_values: tuple
814 @param old_values: (old_policy, old_specs), as returned by
816 @return: same as L{ParseIPolicy}
819 assert get_policy_fn is not None
820 assert build_cmd_fn is not None
821 assert new_specs is None or diff_specs is None
824 (old_policy, old_specs) = old_values
826 (old_policy, old_specs) = get_policy_fn()
829 new_specs = copy.deepcopy(old_specs)
830 if constants.ISPECS_MINMAX in diff_specs:
831 AssertEqual(len(new_specs[constants.ISPECS_MINMAX]),
832 len(diff_specs[constants.ISPECS_MINMAX]))
833 for (new_minmax, diff_minmax) in zip(new_specs[constants.ISPECS_MINMAX],
834 diff_specs[constants.ISPECS_MINMAX]):
835 for (key, parvals) in diff_minmax.items():
836 for (par, val) in parvals.items():
837 new_minmax[key][par] = val
838 for (par, val) in diff_specs.get(constants.ISPECS_STD, {}).items():
839 new_specs[constants.ISPECS_STD][par] = val
843 if (diff_specs is None or constants.ISPECS_MINMAX in diff_specs):
844 minmax_opt_items = []
845 for minmax in new_specs[constants.ISPECS_MINMAX]:
847 for key in ["min", "max"]:
848 keyopt = _GetParameterOptions(minmax[key])
849 minmax_opts.append("%s:%s" % (key, keyopt))
850 minmax_opt_items.append("/".join(minmax_opts))
852 "--ipolicy-bounds-specs",
853 "//".join(minmax_opt_items)
855 if diff_specs is None:
856 std_source = new_specs
858 std_source = diff_specs
859 std_opt = _GetParameterOptions(std_source.get("std", {}))
861 cmd.extend(["--ipolicy-std-specs", std_opt])
862 AssertCommand(build_cmd_fn(cmd), fail=fail)
864 # Check the new state
865 (eff_policy, eff_specs) = get_policy_fn()
866 AssertEqual(eff_policy, old_policy)
868 AssertEqual(eff_specs, old_specs)
870 AssertEqual(eff_specs, new_specs)
873 (eff_policy, eff_specs) = (old_policy, old_specs)
875 return (eff_policy, eff_specs)
878 def ParseIPolicy(policy):
879 """Parse and split instance an instance policy.
882 @param policy: policy, as returned by L{GetObjectInfo}
884 @return: (policy, specs), where:
885 - policy is a dictionary of the policy values, instance specs excluded
886 - specs is a dictionary containing only the specs, using the internal
887 format (see L{constants.IPOLICY_DEFAULTS} for an example)
892 for (key, val) in policy.items():
893 if key == "bounds specs":
894 ret_specs[constants.ISPECS_MINMAX] = []
898 keyparts = key.split("/", 1)
899 assert len(keyparts) > 1
900 ret_minmax[keyparts[0]] = minmax[key]
901 ret_specs[constants.ISPECS_MINMAX].append(ret_minmax)
902 elif key == constants.ISPECS_STD:
905 ret_policy[key] = val
906 return (ret_policy, ret_specs)