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
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)
71 """Initializes the colour constants.
74 # pylint: disable=W0603
76 global _INFO_SEQ, _WARNING_SEQ, _ERROR_SEQ, _RESET_SEQ
78 # Don't use colours if stdout isn't a terminal
79 if not sys.stdout.isatty():
85 # Don't use colours if curses module can't be imported
90 _RESET_SEQ = curses.tigetstr("op")
92 setaf = curses.tigetstr("setaf")
93 _INFO_SEQ = curses.tparm(setaf, curses.COLOR_GREEN)
94 _WARNING_SEQ = curses.tparm(setaf, curses.COLOR_YELLOW)
95 _ERROR_SEQ = curses.tparm(setaf, curses.COLOR_RED)
101 def AssertIn(item, sequence):
102 """Raises an error when item is not in sequence.
105 if item not in sequence:
106 raise qa_error.Error("%r not in %r" % (item, sequence))
109 def AssertNotIn(item, sequence):
110 """Raises an error when item is in sequence.
114 raise qa_error.Error("%r in %r" % (item, sequence))
117 def AssertEqual(first, second):
118 """Raises an error when values aren't equal.
121 if not first == second:
122 raise qa_error.Error("%r == %r" % (first, second))
125 def AssertMatch(string, pattern):
126 """Raises an error when string doesn't match regexp pattern.
129 if not re.match(pattern, string):
130 raise qa_error.Error("%r doesn't match /%r/" % (string, pattern))
133 def _GetName(entity, fn):
134 """Tries to get name of an entity.
136 @type entity: string or dict
137 @param fn: Function retrieving name from entity
140 if isinstance(entity, basestring):
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, log_cmd=True):
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 @param log_cmd: if False, the command won't be logged (simply passed to
175 @return: the return code of the command
176 @raise qa_error.Error: if the command fails when it shouldn't or vice versa
180 node = qa_config.GetMasterNode()
182 nodename = _GetName(node, operator.attrgetter("primary"))
184 if isinstance(cmd, basestring):
187 cmdstr = utils.ShellQuoteArgs(cmd)
189 rcode = StartSSH(nodename, cmdstr, log_cmd=log_cmd).wait()
190 _AssertRetCode(rcode, fail, cmdstr, nodename)
195 def AssertRedirectedCommand(cmd, fail=False, node=None, log_cmd=True):
196 """Executes a command with redirected output.
198 The log will go to the qa-output log file in the ganeti log
199 directory on the node where the command is executed. The fail and
200 node parameters are passed unchanged to AssertCommand.
202 @param cmd: the command to be executed, as a list; a string is not
206 if not isinstance(cmd, list):
207 raise qa_error.Error("Non-list passed to AssertRedirectedCommand")
208 ofile = utils.ShellQuote(_QA_OUTPUT)
209 cmdstr = utils.ShellQuoteArgs(cmd)
210 AssertCommand("echo ---- $(date) %s ---- >> %s" % (cmdstr, ofile),
211 fail=False, node=node, log_cmd=False)
212 return AssertCommand(cmdstr + " >> %s" % ofile,
213 fail=fail, node=node, log_cmd=log_cmd)
216 def GetSSHCommand(node, cmd, strict=True, opts=None, tty=None):
217 """Builds SSH command to be executed.
220 @param node: node the command should run on
222 @param cmd: command to be executed in the node; if None or empty
223 string, no command will be executed
224 @type strict: boolean
225 @param strict: whether to enable strict host key checking
227 @param opts: list of additional options
228 @type tty: boolean or None
229 @param tty: if we should use tty; if None, will be auto-detected
232 args = ["ssh", "-oEscapeChar=none", "-oBatchMode=yes", "-lroot"]
235 tty = sys.stdout.isatty()
244 args.append("-oStrictHostKeyChecking=%s" % tmp)
245 args.append("-oClearAllForwardings=yes")
246 args.append("-oForwardAgent=yes")
249 if node in _MULTIPLEXERS:
250 spath = _MULTIPLEXERS[node][0]
251 args.append("-oControlPath=%s" % spath)
252 args.append("-oControlMaster=no")
260 def StartLocalCommand(cmd, _nolog_opts=False, log_cmd=True, **kwargs):
261 """Starts a local command.
266 pcmd = [i for i in cmd if not i.startswith("-")]
269 print "Command: %s" % utils.ShellQuoteArgs(pcmd)
270 return subprocess.Popen(cmd, shell=False, **kwargs)
273 def StartSSH(node, cmd, strict=True, log_cmd=True):
277 return StartLocalCommand(GetSSHCommand(node, cmd, strict=strict),
278 _nolog_opts=True, log_cmd=log_cmd)
281 def StartMultiplexer(node):
282 """Starts a multiplexer command.
284 @param node: the node for which to open the multiplexer
287 if node in _MULTIPLEXERS:
290 # Note: yes, we only need mktemp, since we'll remove the file anyway
291 sname = tempfile.mktemp(prefix="ganeti-qa-multiplexer.")
292 utils.RemoveFile(sname)
293 opts = ["-N", "-oControlPath=%s" % sname, "-oControlMaster=yes"]
294 print "Created socket at %s" % sname
295 child = StartLocalCommand(GetSSHCommand(node, None, opts=opts))
296 _MULTIPLEXERS[node] = (sname, child)
299 def CloseMultiplexers():
300 """Closes all current multiplexers and cleans up.
303 for node in _MULTIPLEXERS.keys():
304 (sname, child) = _MULTIPLEXERS.pop(node)
305 utils.KillProcess(child.pid, timeout=10, waitpid=True)
306 utils.RemoveFile(sname)
309 def GetCommandOutput(node, cmd, tty=None, fail=False):
310 """Returns the output of a command executed on the given node.
313 @param node: node the command should run on
315 @param cmd: command to be executed in the node (cannot be empty or None)
316 @type tty: bool or None
317 @param tty: if we should use tty; if None, it will be auto-detected
319 @param fail: whether the command is expected to fail
322 p = StartLocalCommand(GetSSHCommand(node, cmd, tty=tty),
323 stdout=subprocess.PIPE)
325 _AssertRetCode(rcode, fail, node, cmd)
326 return p.stdout.read()
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 cmd = ("tmp=$(tempfile --prefix .gnt --directory=$(dirname %s)) && "
390 "[[ -f \"$tmp\" ]] && "
392 "echo $tmp") % (utils.ShellQuote(path), utils.ShellQuote(path))
394 # Return temporary filename
395 return GetCommandOutput(node, cmd).strip()
398 def _ResolveName(cmd, key):
402 master = qa_config.GetMasterNode()
404 output = GetCommandOutput(master.primary, utils.ShellQuoteArgs(cmd))
405 for line in output.splitlines():
406 (lkey, lvalue) = line.split(":", 1)
408 return lvalue.lstrip()
409 raise KeyError("Key not found")
412 def ResolveInstanceName(instance):
413 """Gets the full name of an instance.
415 @type instance: string
416 @param instance: Instance name
419 return _ResolveName(["gnt-instance", "info", instance],
423 def ResolveNodeName(node):
424 """Gets the full name of a node.
427 return _ResolveName(["gnt-node", "info", node.primary],
431 def GetNodeInstances(node, secondaries=False):
432 """Gets a list of instances on a node.
435 master = qa_config.GetMasterNode()
436 node_name = ResolveNodeName(node)
438 # Get list of all instances
439 cmd = ["gnt-instance", "list", "--separator=:", "--no-headers",
440 "--output=name,pnode,snodes"]
441 output = GetCommandOutput(master.primary, utils.ShellQuoteArgs(cmd))
444 for line in output.splitlines():
445 (name, pnode, snodes) = line.split(":", 2)
446 if ((not secondaries and pnode == node_name) or
447 (secondaries and node_name in snodes.split(","))):
448 instances.append(name)
453 def _SelectQueryFields(rnd, fields):
454 """Generates a list of fields for query tests.
457 # Create copy for shuffling
458 fields = list(fields)
466 yield fields + fields
468 # Check small groups of fields
470 yield [fields.pop() for _ in range(rnd.randint(2, 10)) if fields]
473 def _List(listcmd, fields, names):
474 """Runs a list command.
477 master = qa_config.GetMasterNode()
479 cmd = [listcmd, "list", "--separator=|", "--no-headers",
480 "--output", ",".join(fields)]
485 return GetCommandOutput(master.primary,
486 utils.ShellQuoteArgs(cmd)).splitlines()
489 def GenericQueryTest(cmd, fields, namefield="name", test_unknown=True):
490 """Runs a number of tests on query commands.
492 @param cmd: Command name
493 @param fields: List of field names
496 rnd = random.Random(hash(cmd))
498 fields = list(fields)
501 # Test a number of field combinations
502 for testfields in _SelectQueryFields(rnd, fields):
503 AssertRedirectedCommand([cmd, "list", "--output", ",".join(testfields)])
505 if namefield is not None:
506 namelist_fn = compat.partial(_List, cmd, [namefield])
508 # When no names were requested, the list must be sorted
509 names = namelist_fn(None)
510 AssertEqual(names, utils.NiceSort(names))
512 # When requesting specific names, the order must be kept
513 revnames = list(reversed(names))
514 AssertEqual(namelist_fn(revnames), revnames)
516 randnames = list(names)
517 rnd.shuffle(randnames)
518 AssertEqual(namelist_fn(randnames), randnames)
521 # Listing unknown items must fail
522 AssertCommand([cmd, "list", "this.name.certainly.does.not.exist"],
525 # Check exit code for listing unknown field
526 AssertEqual(AssertRedirectedCommand([cmd, "list",
527 "--output=field/does/not/exist"],
529 constants.EXIT_UNKNOWN_FIELD)
532 def GenericQueryFieldsTest(cmd, fields):
533 master = qa_config.GetMasterNode()
536 AssertRedirectedCommand([cmd, "list-fields"])
537 AssertRedirectedCommand([cmd, "list-fields"] + fields)
539 # Check listed fields (all, must be sorted)
540 realcmd = [cmd, "list-fields", "--separator=|", "--no-headers"]
541 output = GetCommandOutput(master.primary,
542 utils.ShellQuoteArgs(realcmd)).splitlines()
543 AssertEqual([line.split("|", 1)[0] for line in output],
544 utils.NiceSort(fields))
546 # Check exit code for listing unknown field
547 AssertEqual(AssertCommand([cmd, "list-fields", "field/does/not/exist"],
549 constants.EXIT_UNKNOWN_FIELD)
552 def _FormatWithColor(text, seq):
555 return "%s%s%s" % (seq, text, _RESET_SEQ)
558 FormatWarning = lambda text: _FormatWithColor(text, _WARNING_SEQ)
559 FormatError = lambda text: _FormatWithColor(text, _ERROR_SEQ)
560 FormatInfo = lambda text: _FormatWithColor(text, _INFO_SEQ)
563 def AddToEtcHosts(hostnames):
564 """Adds hostnames to /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)
573 for localhost in ("::1", "127.0.0.1"):
574 data.append("%s %s" % (localhost, " ".join(hostnames)))
577 AssertCommand("{ cat %s && echo -e '%s'; } > %s && mv %s %s" %
578 (utils.ShellQuote(pathutils.ETC_HOSTS),
580 utils.ShellQuote(tmp_hosts),
581 utils.ShellQuote(tmp_hosts),
582 utils.ShellQuote(pathutils.ETC_HOSTS)))
584 AssertCommand(["rm", "-f", tmp_hosts])
588 def RemoveFromEtcHosts(hostnames):
589 """Remove hostnames from /etc/hosts.
591 @param hostnames: List of hostnames first used A records, all other CNAMEs
594 master = qa_config.GetMasterNode()
595 tmp_hosts = UploadData(master.primary, "", mode=0644)
596 quoted_tmp_hosts = utils.ShellQuote(tmp_hosts)
598 sed_data = " ".join(hostnames)
600 AssertCommand(("sed -e '/^\(::1\|127\.0\.0\.1\)\s\+%s/d' %s > %s"
602 (sed_data, utils.ShellQuote(pathutils.ETC_HOSTS),
603 quoted_tmp_hosts, quoted_tmp_hosts,
604 utils.ShellQuote(pathutils.ETC_HOSTS)))
606 AssertCommand(["rm", "-f", tmp_hosts])
610 def RunInstanceCheck(instance, running):
611 """Check if instance is running or not.
614 instance_name = _GetName(instance, operator.attrgetter("name"))
616 script = qa_config.GetInstanceCheckScript()
620 master_node = qa_config.GetMasterNode()
622 # Build command to connect to master node
623 master_ssh = GetSSHCommand(master_node.primary, "--")
626 running_shellval = "1"
629 running_shellval = ""
630 running_text = "not "
632 print FormatInfo("Checking if instance '%s' is %srunning" %
633 (instance_name, running_text))
635 args = [script, instance_name]
637 "PATH": constants.HOOKS_PATH,
638 "RUN_UUID": _RUN_UUID,
639 "MASTER_SSH": utils.ShellQuoteArgs(master_ssh),
640 "INSTANCE_NAME": instance_name,
641 "INSTANCE_RUNNING": running_shellval,
644 result = os.spawnve(os.P_WAIT, script, args, env)
646 raise qa_error.Error("Instance check failed with result %s" % result)
649 def _InstanceCheckInner(expected, instarg, args, result):
650 """Helper function used by L{InstanceCheck}.
653 if instarg == FIRST_ARG:
655 elif instarg == RETURN_VALUE:
658 raise Exception("Invalid value '%s' for instance argument" % instarg)
660 if expected in (INST_DOWN, INST_UP):
661 RunInstanceCheck(instance, (expected == INST_UP))
662 elif expected is not None:
663 raise Exception("Invalid value '%s'" % expected)
666 def InstanceCheck(before, after, instarg):
667 """Decorator to check instance status before and after test.
669 @param before: L{INST_DOWN} if instance must be stopped before test,
670 L{INST_UP} if instance must be running before test, L{None} to not check.
671 @param after: L{INST_DOWN} if instance must be stopped after test,
672 L{INST_UP} if instance must be running after test, L{None} to not check.
673 @param instarg: L{FIRST_ARG} to use first argument to test as instance (a
674 dictionary), L{RETURN_VALUE} to use return value (disallows pre-checks)
679 def wrapper(*args, **kwargs):
680 _InstanceCheckInner(before, instarg, args, NotImplemented)
682 result = fn(*args, **kwargs)
684 _InstanceCheckInner(after, instarg, args, result)
691 def GetNonexistentGroups(count):
692 """Gets group names which shouldn't exist on the cluster.
694 @param count: Number of groups to get
698 return GetNonexistentEntityNames(count, "groups", "group")
701 def GetNonexistentEntityNames(count, name_config, name_prefix):
702 """Gets entity names which shouldn't exist on the cluster.
704 The actualy names can refer to arbitrary entities (for example
707 @param count: Number of names to get
709 @param name_config: name of the leaf in the config containing
710 this entity's configuration, including a 'inexistent-'
713 @param name_prefix: prefix of the entity's names, used to compose
714 the default values; for example for groups, the prefix is
715 'group' and the generated names are then group1, group2, ...
719 entities = qa_config.get(name_config, {})
721 default = [name_prefix + str(i) for i in range(count)]
722 assert count <= len(default)
724 name_config_inexistent = "inexistent-" + name_config
725 candidates = entities.get(name_config_inexistent, default)[:count]
727 if len(candidates) < count:
728 raise Exception("At least %s non-existent %s are needed" %
729 (count, name_config))