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=$(tempfile --mode %o --prefix gnt) && '
374 '[[ -f "${tmp}" ]] && '
376 'echo "${tmp}"') % mode
380 p = subprocess.Popen(GetSSHCommand(node, cmd), shell=False, stdin=f,
381 stdout=subprocess.PIPE)
382 AssertEqual(p.wait(), 0)
384 # Return temporary filename
385 return p.stdout.read().strip()
390 def UploadData(node, data, mode=0600, filename=None):
391 """Uploads data to a node and returns the filename.
393 Caller needs to remove the returned file on the node when it's not needed
398 tmp = "tmp=%s" % utils.ShellQuote(filename)
400 tmp = "tmp=$(tempfile --mode %o --prefix gnt)" % mode
402 "[[ -f \"${tmp}\" ]] && "
403 "cat > \"${tmp}\" && "
404 "echo \"${tmp}\"") % tmp
406 p = subprocess.Popen(GetSSHCommand(node, cmd), shell=False,
407 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
410 AssertEqual(p.wait(), 0)
412 # Return temporary filename
413 return p.stdout.read().strip()
416 def BackupFile(node, path):
417 """Creates a backup of a file on the node and returns the filename.
419 Caller needs to remove the returned file on the node when it's not needed
423 vpath = MakeNodePath(node, path)
425 cmd = ("tmp=$(tempfile --prefix .gnt --directory=$(dirname %s)) && "
426 "[[ -f \"$tmp\" ]] && "
428 "echo $tmp") % (utils.ShellQuote(vpath), utils.ShellQuote(vpath))
430 # Return temporary filename
431 result = GetCommandOutput(node, cmd).strip()
433 print "Backup filename: %s" % result
438 def ResolveInstanceName(instance):
439 """Gets the full name of an instance.
441 @type instance: string
442 @param instance: Instance name
445 info = GetObjectInfo(["gnt-instance", "info", instance])
446 return info[0]["Instance name"]
449 def ResolveNodeName(node):
450 """Gets the full name of a node.
453 info = GetObjectInfo(["gnt-node", "info", node.primary])
454 return info[0]["Node name"]
457 def GetNodeInstances(node, secondaries=False):
458 """Gets a list of instances on a node.
461 master = qa_config.GetMasterNode()
462 node_name = ResolveNodeName(node)
464 # Get list of all instances
465 cmd = ["gnt-instance", "list", "--separator=:", "--no-headers",
466 "--output=name,pnode,snodes"]
467 output = GetCommandOutput(master.primary, utils.ShellQuoteArgs(cmd))
470 for line in output.splitlines():
471 (name, pnode, snodes) = line.split(":", 2)
472 if ((not secondaries and pnode == node_name) or
473 (secondaries and node_name in snodes.split(","))):
474 instances.append(name)
479 def _SelectQueryFields(rnd, fields):
480 """Generates a list of fields for query tests.
483 # Create copy for shuffling
484 fields = list(fields)
492 yield fields + fields
494 # Check small groups of fields
496 yield [fields.pop() for _ in range(rnd.randint(2, 10)) if fields]
499 def _List(listcmd, fields, names):
500 """Runs a list command.
503 master = qa_config.GetMasterNode()
505 cmd = [listcmd, "list", "--separator=|", "--no-headers",
506 "--output", ",".join(fields)]
511 return GetCommandOutput(master.primary,
512 utils.ShellQuoteArgs(cmd)).splitlines()
515 def GenericQueryTest(cmd, fields, namefield="name", test_unknown=True):
516 """Runs a number of tests on query commands.
518 @param cmd: Command name
519 @param fields: List of field names
522 rnd = random.Random(hash(cmd))
524 fields = list(fields)
527 # Test a number of field combinations
528 for testfields in _SelectQueryFields(rnd, fields):
529 AssertRedirectedCommand([cmd, "list", "--output", ",".join(testfields)])
531 if namefield is not None:
532 namelist_fn = compat.partial(_List, cmd, [namefield])
534 # When no names were requested, the list must be sorted
535 names = namelist_fn(None)
536 AssertEqual(names, utils.NiceSort(names))
538 # When requesting specific names, the order must be kept
539 revnames = list(reversed(names))
540 AssertEqual(namelist_fn(revnames), revnames)
542 randnames = list(names)
543 rnd.shuffle(randnames)
544 AssertEqual(namelist_fn(randnames), randnames)
547 # Listing unknown items must fail
548 AssertCommand([cmd, "list", "this.name.certainly.does.not.exist"],
551 # Check exit code for listing unknown field
552 AssertEqual(AssertRedirectedCommand([cmd, "list",
553 "--output=field/does/not/exist"],
555 constants.EXIT_UNKNOWN_FIELD)
558 def GenericQueryFieldsTest(cmd, fields):
559 master = qa_config.GetMasterNode()
562 AssertRedirectedCommand([cmd, "list-fields"])
563 AssertRedirectedCommand([cmd, "list-fields"] + fields)
565 # Check listed fields (all, must be sorted)
566 realcmd = [cmd, "list-fields", "--separator=|", "--no-headers"]
567 output = GetCommandOutput(master.primary,
568 utils.ShellQuoteArgs(realcmd)).splitlines()
569 AssertEqual([line.split("|", 1)[0] for line in output],
570 utils.NiceSort(fields))
572 # Check exit code for listing unknown field
573 AssertEqual(AssertCommand([cmd, "list-fields", "field/does/not/exist"],
575 constants.EXIT_UNKNOWN_FIELD)
578 def _FormatWithColor(text, seq):
581 return "%s%s%s" % (seq, text, _RESET_SEQ)
584 FormatWarning = lambda text: _FormatWithColor(text, _WARNING_SEQ)
585 FormatError = lambda text: _FormatWithColor(text, _ERROR_SEQ)
586 FormatInfo = lambda text: _FormatWithColor(text, _INFO_SEQ)
589 def AddToEtcHosts(hostnames):
590 """Adds hostnames to /etc/hosts.
592 @param hostnames: List of hostnames first used A records, all other CNAMEs
595 master = qa_config.GetMasterNode()
596 tmp_hosts = UploadData(master.primary, "", mode=0644)
599 for localhost in ("::1", "127.0.0.1"):
600 data.append("%s %s" % (localhost, " ".join(hostnames)))
603 AssertCommand("{ cat %s && echo -e '%s'; } > %s && mv %s %s" %
604 (utils.ShellQuote(pathutils.ETC_HOSTS),
606 utils.ShellQuote(tmp_hosts),
607 utils.ShellQuote(tmp_hosts),
608 utils.ShellQuote(pathutils.ETC_HOSTS)))
610 AssertCommand(["rm", "-f", tmp_hosts])
614 def RemoveFromEtcHosts(hostnames):
615 """Remove hostnames from /etc/hosts.
617 @param hostnames: List of hostnames first used A records, all other CNAMEs
620 master = qa_config.GetMasterNode()
621 tmp_hosts = UploadData(master.primary, "", mode=0644)
622 quoted_tmp_hosts = utils.ShellQuote(tmp_hosts)
624 sed_data = " ".join(hostnames)
626 AssertCommand(("sed -e '/^\(::1\|127\.0\.0\.1\)\s\+%s/d' %s > %s"
628 (sed_data, utils.ShellQuote(pathutils.ETC_HOSTS),
629 quoted_tmp_hosts, quoted_tmp_hosts,
630 utils.ShellQuote(pathutils.ETC_HOSTS)))
632 AssertCommand(["rm", "-f", tmp_hosts])
636 def RunInstanceCheck(instance, running):
637 """Check if instance is running or not.
640 instance_name = _GetName(instance, operator.attrgetter("name"))
642 script = qa_config.GetInstanceCheckScript()
646 master_node = qa_config.GetMasterNode()
648 # Build command to connect to master node
649 master_ssh = GetSSHCommand(master_node.primary, "--")
652 running_shellval = "1"
655 running_shellval = ""
656 running_text = "not "
658 print FormatInfo("Checking if instance '%s' is %srunning" %
659 (instance_name, running_text))
661 args = [script, instance_name]
663 "PATH": constants.HOOKS_PATH,
664 "RUN_UUID": _RUN_UUID,
665 "MASTER_SSH": utils.ShellQuoteArgs(master_ssh),
666 "INSTANCE_NAME": instance_name,
667 "INSTANCE_RUNNING": running_shellval,
670 result = os.spawnve(os.P_WAIT, script, args, env)
672 raise qa_error.Error("Instance check failed with result %s" % result)
675 def _InstanceCheckInner(expected, instarg, args, result):
676 """Helper function used by L{InstanceCheck}.
679 if instarg == FIRST_ARG:
681 elif instarg == RETURN_VALUE:
684 raise Exception("Invalid value '%s' for instance argument" % instarg)
686 if expected in (INST_DOWN, INST_UP):
687 RunInstanceCheck(instance, (expected == INST_UP))
688 elif expected is not None:
689 raise Exception("Invalid value '%s'" % expected)
692 def InstanceCheck(before, after, instarg):
693 """Decorator to check instance status before and after test.
695 @param before: L{INST_DOWN} if instance must be stopped before test,
696 L{INST_UP} if instance must be running before test, L{None} to not check.
697 @param after: L{INST_DOWN} if instance must be stopped after test,
698 L{INST_UP} if instance must be running after test, L{None} to not check.
699 @param instarg: L{FIRST_ARG} to use first argument to test as instance (a
700 dictionary), L{RETURN_VALUE} to use return value (disallows pre-checks)
705 def wrapper(*args, **kwargs):
706 _InstanceCheckInner(before, instarg, args, NotImplemented)
708 result = fn(*args, **kwargs)
710 _InstanceCheckInner(after, instarg, args, result)
717 def GetNonexistentGroups(count):
718 """Gets group names which shouldn't exist on the cluster.
720 @param count: Number of groups to get
724 return GetNonexistentEntityNames(count, "groups", "group")
727 def GetNonexistentEntityNames(count, name_config, name_prefix):
728 """Gets entity names which shouldn't exist on the cluster.
730 The actualy names can refer to arbitrary entities (for example
733 @param count: Number of names to get
735 @param name_config: name of the leaf in the config containing
736 this entity's configuration, including a 'inexistent-'
739 @param name_prefix: prefix of the entity's names, used to compose
740 the default values; for example for groups, the prefix is
741 'group' and the generated names are then group1, group2, ...
745 entities = qa_config.get(name_config, {})
747 default = [name_prefix + str(i) for i in range(count)]
748 assert count <= len(default)
750 name_config_inexistent = "inexistent-" + name_config
751 candidates = entities.get(name_config_inexistent, default)[:count]
753 if len(candidates) < count:
754 raise Exception("At least %s non-existent %s are needed" %
755 (count, name_config))
760 def MakeNodePath(node, path):
761 """Builds an absolute path for a virtual node.
763 @type node: string or L{qa_config._QaNode}
766 @param path: Path without node-specific prefix
769 (_, basedir) = qa_config.GetVclusterSettings()
771 if isinstance(node, basestring):
777 assert path.startswith("/")
778 return "%s%s" % (vcluster.MakeNodeRoot(basedir, name), path)
783 def _GetParameterOptions(specs):
784 """Helper to build policy options."""
785 values = ["%s=%s" % (par, val)
786 for (par, val) in specs.items()]
787 return ",".join(values)
790 def TestSetISpecs(new_specs=None, diff_specs=None, get_policy_fn=None,
791 build_cmd_fn=None, fail=False, old_values=None):
792 """Change instance specs for an object.
794 At most one of new_specs or diff_specs can be specified.
796 @type new_specs: dict
797 @param new_specs: new complete specs, in the same format returned by
799 @type diff_specs: dict
800 @param diff_specs: partial specs, it can be an incomplete specifications, but
801 if min/max specs are specified, their number must match the number of the
803 @type get_policy_fn: function
804 @param get_policy_fn: function that returns the current policy as in
806 @type build_cmd_fn: function
807 @param build_cmd_fn: function that return the full command line from the
810 @param fail: if the change is expected to fail
811 @type old_values: tuple
812 @param old_values: (old_policy, old_specs), as returned by
814 @return: same as L{ParseIPolicy}
817 assert get_policy_fn is not None
818 assert build_cmd_fn is not None
819 assert new_specs is None or diff_specs is None
822 (old_policy, old_specs) = old_values
824 (old_policy, old_specs) = get_policy_fn()
827 new_specs = copy.deepcopy(old_specs)
828 if constants.ISPECS_MINMAX in diff_specs:
829 AssertEqual(len(new_specs[constants.ISPECS_MINMAX]),
830 len(diff_specs[constants.ISPECS_MINMAX]))
831 for (new_minmax, diff_minmax) in zip(new_specs[constants.ISPECS_MINMAX],
832 diff_specs[constants.ISPECS_MINMAX]):
833 for (key, parvals) in diff_minmax.items():
834 for (par, val) in parvals.items():
835 new_minmax[key][par] = val
836 for (par, val) in diff_specs.get(constants.ISPECS_STD, {}).items():
837 new_specs[constants.ISPECS_STD][par] = val
841 if (diff_specs is None or constants.ISPECS_MINMAX in diff_specs):
842 minmax_opt_items = []
843 for minmax in new_specs[constants.ISPECS_MINMAX]:
845 for key in ["min", "max"]:
846 keyopt = _GetParameterOptions(minmax[key])
847 minmax_opts.append("%s:%s" % (key, keyopt))
848 minmax_opt_items.append("/".join(minmax_opts))
850 "--ipolicy-bounds-specs",
851 "//".join(minmax_opt_items)
853 if diff_specs is None:
854 std_source = new_specs
856 std_source = diff_specs
857 std_opt = _GetParameterOptions(std_source.get("std", {}))
859 cmd.extend(["--ipolicy-std-specs", std_opt])
860 AssertCommand(build_cmd_fn(cmd), fail=fail)
862 # Check the new state
863 (eff_policy, eff_specs) = get_policy_fn()
864 AssertEqual(eff_policy, old_policy)
866 AssertEqual(eff_specs, old_specs)
868 AssertEqual(eff_specs, new_specs)
871 (eff_policy, eff_specs) = (old_policy, old_specs)
873 return (eff_policy, eff_specs)
876 def ParseIPolicy(policy):
877 """Parse and split instance an instance policy.
880 @param policy: policy, as returned by L{GetObjectInfo}
882 @return: (policy, specs), where:
883 - policy is a dictionary of the policy values, instance specs excluded
884 - specs is a dictionary containing only the specs, using the internal
885 format (see L{constants.IPOLICY_DEFAULTS} for an example)
890 for (key, val) in policy.items():
891 if key == "bounds specs":
892 ret_specs[constants.ISPECS_MINMAX] = []
896 keyparts = key.split("/", 1)
897 assert len(keyparts) > 1
898 ret_minmax[keyparts[0]] = minmax[key]
899 ret_specs[constants.ISPECS_MINMAX].append(ret_minmax)
900 elif key == constants.ISPECS_STD:
903 ret_policy[key] = val
904 return (ret_policy, ret_specs)