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
51 from qa_logging import FormatInfo
56 #: Unique ID per QA run
57 _RUN_UUID = utils.NewUUID()
59 #: Path to the QA query output log file
60 _QA_OUTPUT = pathutils.GetLogFilename("qa-output")
64 INST_UP) = range(500, 502)
67 RETURN_VALUE) = range(1000, 1002)
70 def AssertIn(item, sequence):
71 """Raises an error when item is not in sequence.
74 if item not in sequence:
75 raise qa_error.Error("%r not in %r" % (item, sequence))
78 def AssertNotIn(item, sequence):
79 """Raises an error when item is in sequence.
83 raise qa_error.Error("%r in %r" % (item, sequence))
86 def AssertEqual(first, second):
87 """Raises an error when values aren't equal.
90 if not first == second:
91 raise qa_error.Error("%r == %r" % (first, second))
94 def AssertMatch(string, pattern):
95 """Raises an error when string doesn't match regexp pattern.
98 if not re.match(pattern, string):
99 raise qa_error.Error("%r doesn't match /%r/" % (string, pattern))
102 def _GetName(entity, fn):
103 """Tries to get name of an entity.
105 @type entity: string or dict
106 @param fn: Function retrieving name from entity
109 if isinstance(entity, basestring):
114 if not ht.TNonEmptyString(result):
115 raise Exception("Invalid name '%s'" % result)
120 def _AssertRetCode(rcode, fail, cmdstr, nodename):
121 """Check the return value from a command and possibly raise an exception.
124 if fail and rcode == 0:
125 raise qa_error.Error("Command '%s' on node %s was expected to fail but"
126 " didn't" % (cmdstr, nodename))
127 elif not fail and rcode != 0:
128 raise qa_error.Error("Command '%s' on node %s failed, exit code %s" %
129 (cmdstr, nodename, rcode))
132 def AssertCommand(cmd, fail=False, node=None, log_cmd=True):
133 """Checks that a remote command succeeds.
135 @param cmd: either a string (the command to execute) or a list (to
136 be converted using L{utils.ShellQuoteArgs} into a string)
138 @param fail: if the command is expected to fail instead of succeeding
139 @param node: if passed, it should be the node on which the command
140 should be executed, instead of the master node (can be either a
142 @param log_cmd: if False, the command won't be logged (simply passed to
144 @return: the return code of the command
145 @raise qa_error.Error: if the command fails when it shouldn't or vice versa
149 node = qa_config.GetMasterNode()
151 nodename = _GetName(node, operator.attrgetter("primary"))
153 if isinstance(cmd, basestring):
156 cmdstr = utils.ShellQuoteArgs(cmd)
158 rcode = StartSSH(nodename, cmdstr, log_cmd=log_cmd).wait()
159 _AssertRetCode(rcode, fail, cmdstr, nodename)
164 def AssertRedirectedCommand(cmd, fail=False, node=None, log_cmd=True):
165 """Executes a command with redirected output.
167 The log will go to the qa-output log file in the ganeti log
168 directory on the node where the command is executed. The fail and
169 node parameters are passed unchanged to AssertCommand.
171 @param cmd: the command to be executed, as a list; a string is not
175 if not isinstance(cmd, list):
176 raise qa_error.Error("Non-list passed to AssertRedirectedCommand")
177 ofile = utils.ShellQuote(_QA_OUTPUT)
178 cmdstr = utils.ShellQuoteArgs(cmd)
179 AssertCommand("echo ---- $(date) %s ---- >> %s" % (cmdstr, ofile),
180 fail=False, node=node, log_cmd=False)
181 return AssertCommand(cmdstr + " >> %s" % ofile,
182 fail=fail, node=node, log_cmd=log_cmd)
185 def GetSSHCommand(node, cmd, strict=True, opts=None, tty=None):
186 """Builds SSH command to be executed.
189 @param node: node the command should run on
191 @param cmd: command to be executed in the node; if None or empty
192 string, no command will be executed
193 @type strict: boolean
194 @param strict: whether to enable strict host key checking
196 @param opts: list of additional options
197 @type tty: boolean or None
198 @param tty: if we should use tty; if None, will be auto-detected
201 args = ["ssh", "-oEscapeChar=none", "-oBatchMode=yes", "-lroot"]
204 tty = sys.stdout.isatty()
213 args.append("-oStrictHostKeyChecking=%s" % tmp)
214 args.append("-oClearAllForwardings=yes")
215 args.append("-oForwardAgent=yes")
218 if node in _MULTIPLEXERS:
219 spath = _MULTIPLEXERS[node][0]
220 args.append("-oControlPath=%s" % spath)
221 args.append("-oControlMaster=no")
223 (vcluster_master, vcluster_basedir) = \
224 qa_config.GetVclusterSettings()
227 args.append(vcluster_master)
228 args.append("%s/%s/cmd" % (vcluster_basedir, node))
231 # For virtual clusters the whole command must be wrapped using the "cmd"
232 # script, as that script sets a number of environment variables. If the
233 # command contains shell meta characters the whole command needs to be
235 args.append(utils.ShellQuote(cmd))
245 def StartLocalCommand(cmd, _nolog_opts=False, log_cmd=True, **kwargs):
246 """Starts a local command.
251 pcmd = [i for i in cmd if not i.startswith("-")]
254 print "Command: %s" % utils.ShellQuoteArgs(pcmd)
255 return subprocess.Popen(cmd, shell=False, **kwargs)
258 def StartSSH(node, cmd, strict=True, log_cmd=True):
262 return StartLocalCommand(GetSSHCommand(node, cmd, strict=strict),
263 _nolog_opts=True, log_cmd=log_cmd)
266 def StartMultiplexer(node):
267 """Starts a multiplexer command.
269 @param node: the node for which to open the multiplexer
272 if node in _MULTIPLEXERS:
275 # Note: yes, we only need mktemp, since we'll remove the file anyway
276 sname = tempfile.mktemp(prefix="ganeti-qa-multiplexer.")
277 utils.RemoveFile(sname)
278 opts = ["-N", "-oControlPath=%s" % sname, "-oControlMaster=yes"]
279 print "Created socket at %s" % sname
280 child = StartLocalCommand(GetSSHCommand(node, None, opts=opts))
281 _MULTIPLEXERS[node] = (sname, child)
284 def CloseMultiplexers():
285 """Closes all current multiplexers and cleans up.
288 for node in _MULTIPLEXERS.keys():
289 (sname, child) = _MULTIPLEXERS.pop(node)
290 utils.KillProcess(child.pid, timeout=10, waitpid=True)
291 utils.RemoveFile(sname)
294 def GetCommandOutput(node, cmd, tty=None, fail=False):
295 """Returns the output of a command executed on the given node.
298 @param node: node the command should run on
300 @param cmd: command to be executed in the node (cannot be empty or None)
301 @type tty: bool or None
302 @param tty: if we should use tty; if None, it will be auto-detected
304 @param fail: whether the command is expected to fail
307 p = StartLocalCommand(GetSSHCommand(node, cmd, tty=tty),
308 stdout=subprocess.PIPE)
310 _AssertRetCode(rcode, fail, cmd, node)
311 return p.stdout.read()
314 def GetObjectInfo(infocmd):
315 """Get and parse information about a Ganeti object.
317 @type infocmd: list of strings
318 @param infocmd: command to be executed, e.g. ["gnt-cluster", "info"]
319 @return: the information parsed, appropriately stored in dictionaries,
323 master = qa_config.GetMasterNode()
324 cmdline = utils.ShellQuoteArgs(infocmd)
325 info_out = GetCommandOutput(master.primary, cmdline)
326 return yaml.load(info_out)
329 def UploadFile(node, src):
330 """Uploads a file to a node and returns the filename.
332 Caller needs to remove the returned file on the node when it's not needed
336 # Make sure nobody else has access to it while preserving local permissions
337 mode = os.stat(src).st_mode & 0700
339 cmd = ('tmp=$(tempfile --mode %o --prefix gnt) && '
340 '[[ -f "${tmp}" ]] && '
342 'echo "${tmp}"') % mode
346 p = subprocess.Popen(GetSSHCommand(node, cmd), shell=False, stdin=f,
347 stdout=subprocess.PIPE)
348 AssertEqual(p.wait(), 0)
350 # Return temporary filename
351 return p.stdout.read().strip()
356 def UploadData(node, data, mode=0600, filename=None):
357 """Uploads data to a node and returns the filename.
359 Caller needs to remove the returned file on the node when it's not needed
364 tmp = "tmp=%s" % utils.ShellQuote(filename)
366 tmp = "tmp=$(tempfile --mode %o --prefix gnt)" % mode
368 "[[ -f \"${tmp}\" ]] && "
369 "cat > \"${tmp}\" && "
370 "echo \"${tmp}\"") % tmp
372 p = subprocess.Popen(GetSSHCommand(node, cmd), shell=False,
373 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
376 AssertEqual(p.wait(), 0)
378 # Return temporary filename
379 return p.stdout.read().strip()
382 def BackupFile(node, path):
383 """Creates a backup of a file on the node and returns the filename.
385 Caller needs to remove the returned file on the node when it's not needed
389 vpath = MakeNodePath(node, path)
391 cmd = ("tmp=$(tempfile --prefix .gnt --directory=$(dirname %s)) && "
392 "[[ -f \"$tmp\" ]] && "
394 "echo $tmp") % (utils.ShellQuote(vpath), utils.ShellQuote(vpath))
396 # Return temporary filename
397 result = GetCommandOutput(node, cmd).strip()
399 print "Backup filename: %s" % result
404 def ResolveInstanceName(instance):
405 """Gets the full name of an instance.
407 @type instance: string
408 @param instance: Instance name
411 info = GetObjectInfo(["gnt-instance", "info", instance])
412 return info[0]["Instance name"]
415 def ResolveNodeName(node):
416 """Gets the full name of a node.
419 info = GetObjectInfo(["gnt-node", "info", node.primary])
420 return info[0]["Node name"]
423 def GetNodeInstances(node, secondaries=False):
424 """Gets a list of instances on a node.
427 master = qa_config.GetMasterNode()
428 node_name = ResolveNodeName(node)
430 # Get list of all instances
431 cmd = ["gnt-instance", "list", "--separator=:", "--no-headers",
432 "--output=name,pnode,snodes"]
433 output = GetCommandOutput(master.primary, utils.ShellQuoteArgs(cmd))
436 for line in output.splitlines():
437 (name, pnode, snodes) = line.split(":", 2)
438 if ((not secondaries and pnode == node_name) or
439 (secondaries and node_name in snodes.split(","))):
440 instances.append(name)
445 def _SelectQueryFields(rnd, fields):
446 """Generates a list of fields for query tests.
449 # Create copy for shuffling
450 fields = list(fields)
458 yield fields + fields
460 # Check small groups of fields
462 yield [fields.pop() for _ in range(rnd.randint(2, 10)) if fields]
465 def _List(listcmd, fields, names):
466 """Runs a list command.
469 master = qa_config.GetMasterNode()
471 cmd = [listcmd, "list", "--separator=|", "--no-headers",
472 "--output", ",".join(fields)]
477 return GetCommandOutput(master.primary,
478 utils.ShellQuoteArgs(cmd)).splitlines()
481 def GenericQueryTest(cmd, fields, namefield="name", test_unknown=True):
482 """Runs a number of tests on query commands.
484 @param cmd: Command name
485 @param fields: List of field names
488 rnd = random.Random(hash(cmd))
490 fields = list(fields)
493 # Test a number of field combinations
494 for testfields in _SelectQueryFields(rnd, fields):
495 AssertRedirectedCommand([cmd, "list", "--output", ",".join(testfields)])
497 if namefield is not None:
498 namelist_fn = compat.partial(_List, cmd, [namefield])
500 # When no names were requested, the list must be sorted
501 names = namelist_fn(None)
502 AssertEqual(names, utils.NiceSort(names))
504 # When requesting specific names, the order must be kept
505 revnames = list(reversed(names))
506 AssertEqual(namelist_fn(revnames), revnames)
508 randnames = list(names)
509 rnd.shuffle(randnames)
510 AssertEqual(namelist_fn(randnames), randnames)
513 # Listing unknown items must fail
514 AssertCommand([cmd, "list", "this.name.certainly.does.not.exist"],
517 # Check exit code for listing unknown field
518 AssertEqual(AssertRedirectedCommand([cmd, "list",
519 "--output=field/does/not/exist"],
521 constants.EXIT_UNKNOWN_FIELD)
524 def GenericQueryFieldsTest(cmd, fields):
525 master = qa_config.GetMasterNode()
528 AssertRedirectedCommand([cmd, "list-fields"])
529 AssertRedirectedCommand([cmd, "list-fields"] + fields)
531 # Check listed fields (all, must be sorted)
532 realcmd = [cmd, "list-fields", "--separator=|", "--no-headers"]
533 output = GetCommandOutput(master.primary,
534 utils.ShellQuoteArgs(realcmd)).splitlines()
535 AssertEqual([line.split("|", 1)[0] for line in output],
536 utils.NiceSort(fields))
538 # Check exit code for listing unknown field
539 AssertEqual(AssertCommand([cmd, "list-fields", "field/does/not/exist"],
541 constants.EXIT_UNKNOWN_FIELD)
544 def AddToEtcHosts(hostnames):
545 """Adds hostnames to /etc/hosts.
547 @param hostnames: List of hostnames first used A records, all other CNAMEs
550 master = qa_config.GetMasterNode()
551 tmp_hosts = UploadData(master.primary, "", mode=0644)
554 for localhost in ("::1", "127.0.0.1"):
555 data.append("%s %s" % (localhost, " ".join(hostnames)))
558 AssertCommand("{ cat %s && echo -e '%s'; } > %s && mv %s %s" %
559 (utils.ShellQuote(pathutils.ETC_HOSTS),
561 utils.ShellQuote(tmp_hosts),
562 utils.ShellQuote(tmp_hosts),
563 utils.ShellQuote(pathutils.ETC_HOSTS)))
565 AssertCommand(["rm", "-f", tmp_hosts])
569 def RemoveFromEtcHosts(hostnames):
570 """Remove hostnames from /etc/hosts.
572 @param hostnames: List of hostnames first used A records, all other CNAMEs
575 master = qa_config.GetMasterNode()
576 tmp_hosts = UploadData(master.primary, "", mode=0644)
577 quoted_tmp_hosts = utils.ShellQuote(tmp_hosts)
579 sed_data = " ".join(hostnames)
581 AssertCommand(("sed -e '/^\(::1\|127\.0\.0\.1\)\s\+%s/d' %s > %s"
583 (sed_data, utils.ShellQuote(pathutils.ETC_HOSTS),
584 quoted_tmp_hosts, quoted_tmp_hosts,
585 utils.ShellQuote(pathutils.ETC_HOSTS)))
587 AssertCommand(["rm", "-f", tmp_hosts])
591 def RunInstanceCheck(instance, running):
592 """Check if instance is running or not.
595 instance_name = _GetName(instance, operator.attrgetter("name"))
597 script = qa_config.GetInstanceCheckScript()
601 master_node = qa_config.GetMasterNode()
603 # Build command to connect to master node
604 master_ssh = GetSSHCommand(master_node.primary, "--")
607 running_shellval = "1"
610 running_shellval = ""
611 running_text = "not "
613 print FormatInfo("Checking if instance '%s' is %srunning" %
614 (instance_name, running_text))
616 args = [script, instance_name]
618 "PATH": constants.HOOKS_PATH,
619 "RUN_UUID": _RUN_UUID,
620 "MASTER_SSH": utils.ShellQuoteArgs(master_ssh),
621 "INSTANCE_NAME": instance_name,
622 "INSTANCE_RUNNING": running_shellval,
625 result = os.spawnve(os.P_WAIT, script, args, env)
627 raise qa_error.Error("Instance check failed with result %s" % result)
630 def _InstanceCheckInner(expected, instarg, args, result):
631 """Helper function used by L{InstanceCheck}.
634 if instarg == FIRST_ARG:
636 elif instarg == RETURN_VALUE:
639 raise Exception("Invalid value '%s' for instance argument" % instarg)
641 if expected in (INST_DOWN, INST_UP):
642 RunInstanceCheck(instance, (expected == INST_UP))
643 elif expected is not None:
644 raise Exception("Invalid value '%s'" % expected)
647 def InstanceCheck(before, after, instarg):
648 """Decorator to check instance status before and after test.
650 @param before: L{INST_DOWN} if instance must be stopped before test,
651 L{INST_UP} if instance must be running before test, L{None} to not check.
652 @param after: L{INST_DOWN} if instance must be stopped after test,
653 L{INST_UP} if instance must be running after test, L{None} to not check.
654 @param instarg: L{FIRST_ARG} to use first argument to test as instance (a
655 dictionary), L{RETURN_VALUE} to use return value (disallows pre-checks)
660 def wrapper(*args, **kwargs):
661 _InstanceCheckInner(before, instarg, args, NotImplemented)
663 result = fn(*args, **kwargs)
665 _InstanceCheckInner(after, instarg, args, result)
672 def GetNonexistentGroups(count):
673 """Gets group names which shouldn't exist on the cluster.
675 @param count: Number of groups to get
679 return GetNonexistentEntityNames(count, "groups", "group")
682 def GetNonexistentEntityNames(count, name_config, name_prefix):
683 """Gets entity names which shouldn't exist on the cluster.
685 The actualy names can refer to arbitrary entities (for example
688 @param count: Number of names to get
690 @param name_config: name of the leaf in the config containing
691 this entity's configuration, including a 'inexistent-'
694 @param name_prefix: prefix of the entity's names, used to compose
695 the default values; for example for groups, the prefix is
696 'group' and the generated names are then group1, group2, ...
700 entities = qa_config.get(name_config, {})
702 default = [name_prefix + str(i) for i in range(count)]
703 assert count <= len(default)
705 name_config_inexistent = "inexistent-" + name_config
706 candidates = entities.get(name_config_inexistent, default)[:count]
708 if len(candidates) < count:
709 raise Exception("At least %s non-existent %s are needed" %
710 (count, name_config))
715 def MakeNodePath(node, path):
716 """Builds an absolute path for a virtual node.
718 @type node: string or L{qa_config._QaNode}
721 @param path: Path without node-specific prefix
724 (_, basedir) = qa_config.GetVclusterSettings()
726 if isinstance(node, basestring):
732 assert path.startswith("/")
733 return "%s%s" % (vcluster.MakeNodeRoot(basedir, name), path)
738 def _GetParameterOptions(specs):
739 """Helper to build policy options."""
740 values = ["%s=%s" % (par, val)
741 for (par, val) in specs.items()]
742 return ",".join(values)
745 def TestSetISpecs(new_specs=None, diff_specs=None, get_policy_fn=None,
746 build_cmd_fn=None, fail=False, old_values=None):
747 """Change instance specs for an object.
749 At most one of new_specs or diff_specs can be specified.
751 @type new_specs: dict
752 @param new_specs: new complete specs, in the same format returned by
754 @type diff_specs: dict
755 @param diff_specs: partial specs, it can be an incomplete specifications, but
756 if min/max specs are specified, their number must match the number of the
758 @type get_policy_fn: function
759 @param get_policy_fn: function that returns the current policy as in
761 @type build_cmd_fn: function
762 @param build_cmd_fn: function that return the full command line from the
765 @param fail: if the change is expected to fail
766 @type old_values: tuple
767 @param old_values: (old_policy, old_specs), as returned by
769 @return: same as L{ParseIPolicy}
772 assert get_policy_fn is not None
773 assert build_cmd_fn is not None
774 assert new_specs is None or diff_specs is None
777 (old_policy, old_specs) = old_values
779 (old_policy, old_specs) = get_policy_fn()
782 new_specs = copy.deepcopy(old_specs)
783 if constants.ISPECS_MINMAX in diff_specs:
784 AssertEqual(len(new_specs[constants.ISPECS_MINMAX]),
785 len(diff_specs[constants.ISPECS_MINMAX]))
786 for (new_minmax, diff_minmax) in zip(new_specs[constants.ISPECS_MINMAX],
787 diff_specs[constants.ISPECS_MINMAX]):
788 for (key, parvals) in diff_minmax.items():
789 for (par, val) in parvals.items():
790 new_minmax[key][par] = val
791 for (par, val) in diff_specs.get(constants.ISPECS_STD, {}).items():
792 new_specs[constants.ISPECS_STD][par] = val
796 if (diff_specs is None or constants.ISPECS_MINMAX in diff_specs):
797 minmax_opt_items = []
798 for minmax in new_specs[constants.ISPECS_MINMAX]:
800 for key in ["min", "max"]:
801 keyopt = _GetParameterOptions(minmax[key])
802 minmax_opts.append("%s:%s" % (key, keyopt))
803 minmax_opt_items.append("/".join(minmax_opts))
805 "--ipolicy-bounds-specs",
806 "//".join(minmax_opt_items)
808 if diff_specs is None:
809 std_source = new_specs
811 std_source = diff_specs
812 std_opt = _GetParameterOptions(std_source.get("std", {}))
814 cmd.extend(["--ipolicy-std-specs", std_opt])
815 AssertCommand(build_cmd_fn(cmd), fail=fail)
817 # Check the new state
818 (eff_policy, eff_specs) = get_policy_fn()
819 AssertEqual(eff_policy, old_policy)
821 AssertEqual(eff_specs, old_specs)
823 AssertEqual(eff_specs, new_specs)
826 (eff_policy, eff_specs) = (old_policy, old_specs)
828 return (eff_policy, eff_specs)
831 def ParseIPolicy(policy):
832 """Parse and split instance an instance policy.
835 @param policy: policy, as returned by L{GetObjectInfo}
837 @return: (policy, specs), where:
838 - policy is a dictionary of the policy values, instance specs excluded
839 - specs is a dictionary containing only the specs, using the internal
840 format (see L{constants.IPOLICY_DEFAULTS} for an example)
845 for (key, val) in policy.items():
846 if key == "bounds specs":
847 ret_specs[constants.ISPECS_MINMAX] = []
851 keyparts = key.split("/", 1)
852 assert len(keyparts) > 1
853 ret_minmax[keyparts[0]] = minmax[key]
854 ret_specs[constants.ISPECS_MINMAX].append(ret_minmax)
855 elif key == constants.ISPECS_STD:
858 ret_policy[key] = val
859 return (ret_policy, ret_specs)