4 # Copyright (C) 2007, 2011, 2012 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.
35 except ImportError, err:
36 raise ImportError("Python 2.5 or higher is required: %s" % err)
38 from ganeti import utils
39 from ganeti import compat
40 from ganeti import constants
42 from ganeti import pathutils
55 #: Unique ID per QA run
56 _RUN_UUID = utils.NewUUID()
60 INST_UP) = range(500, 502)
63 RETURN_VALUE) = range(1000, 1002)
67 """Initializes the colour constants.
70 # pylint: disable=W0603
72 global _INFO_SEQ, _WARNING_SEQ, _ERROR_SEQ, _RESET_SEQ
74 # Don't use colours if stdout isn't a terminal
75 if not sys.stdout.isatty():
81 # Don't use colours if curses module can't be imported
86 _RESET_SEQ = curses.tigetstr("op")
88 setaf = curses.tigetstr("setaf")
89 _INFO_SEQ = curses.tparm(setaf, curses.COLOR_GREEN)
90 _WARNING_SEQ = curses.tparm(setaf, curses.COLOR_YELLOW)
91 _ERROR_SEQ = curses.tparm(setaf, curses.COLOR_RED)
97 def AssertIn(item, sequence):
98 """Raises an error when item is not in sequence.
101 if item not in sequence:
102 raise qa_error.Error("%r not in %r" % (item, sequence))
105 def AssertNotIn(item, sequence):
106 """Raises an error when item is in sequence.
110 raise qa_error.Error("%r in %r" % (item, sequence))
113 def AssertEqual(first, second):
114 """Raises an error when values aren't equal.
117 if not first == second:
118 raise qa_error.Error("%r == %r" % (first, second))
121 def AssertNotEqual(first, second):
122 """Raises an error when values are equal.
125 if not first != second:
126 raise qa_error.Error("%r != %r" % (first, second))
129 def AssertMatch(string, pattern):
130 """Raises an error when string doesn't match regexp pattern.
133 if not re.match(pattern, string):
134 raise qa_error.Error("%r doesn't match /%r/" % (string, pattern))
137 def _GetName(entity, key):
138 """Tries to get name of an entity.
140 @type entity: string or dict
142 @param key: Dictionary key containing name
145 if isinstance(entity, basestring):
147 elif isinstance(entity, dict):
150 raise qa_error.Error("Expected string or dictionary, got %s: %s" %
151 (type(entity), entity))
153 if not ht.TNonEmptyString(result):
154 raise Exception("Invalid name '%s'" % result)
159 def AssertCommand(cmd, fail=False, node=None):
160 """Checks that a remote command succeeds.
162 @param cmd: either a string (the command to execute) or a list (to
163 be converted using L{utils.ShellQuoteArgs} into a string)
165 @param fail: if the command is expected to fail instead of succeeding
166 @param node: if passed, it should be the node on which the command
167 should be executed, instead of the master node (can be either a
172 node = qa_config.GetMasterNode()
174 nodename = _GetName(node, "primary")
176 if isinstance(cmd, basestring):
179 cmdstr = utils.ShellQuoteArgs(cmd)
181 rcode = StartSSH(nodename, cmdstr).wait()
185 raise qa_error.Error("Command '%s' on node %s was expected to fail but"
186 " didn't" % (cmdstr, nodename))
189 raise qa_error.Error("Command '%s' on node %s failed, exit code %s" %
190 (cmdstr, nodename, rcode))
195 def GetSSHCommand(node, cmd, strict=True, opts=None, tty=None):
196 """Builds SSH command to be executed.
199 @param node: node the command should run on
201 @param cmd: command to be executed in the node; if None or empty
202 string, no command will be executed
203 @type strict: boolean
204 @param strict: whether to enable strict host key checking
206 @param opts: list of additional options
207 @type tty: boolean or None
208 @param tty: if we should use tty; if None, will be auto-detected
211 args = ["ssh", "-oEscapeChar=none", "-oBatchMode=yes", "-lroot"]
214 tty = sys.stdout.isatty()
223 args.append("-oStrictHostKeyChecking=%s" % tmp)
224 args.append("-oClearAllForwardings=yes")
225 args.append("-oForwardAgent=yes")
228 if node in _MULTIPLEXERS:
229 spath = _MULTIPLEXERS[node][0]
230 args.append("-oControlPath=%s" % spath)
231 args.append("-oControlMaster=no")
239 def StartLocalCommand(cmd, _nolog_opts=False, **kwargs):
240 """Starts a local command.
244 pcmd = [i for i in cmd if not i.startswith("-")]
247 print "Command: %s" % utils.ShellQuoteArgs(pcmd)
248 return subprocess.Popen(cmd, shell=False, **kwargs)
251 def StartSSH(node, cmd, strict=True):
255 return StartLocalCommand(GetSSHCommand(node, cmd, strict=strict),
259 def StartMultiplexer(node):
260 """Starts a multiplexer command.
262 @param node: the node for which to open the multiplexer
265 if node in _MULTIPLEXERS:
268 # Note: yes, we only need mktemp, since we'll remove the file anyway
269 sname = tempfile.mktemp(prefix="ganeti-qa-multiplexer.")
270 utils.RemoveFile(sname)
271 opts = ["-N", "-oControlPath=%s" % sname, "-oControlMaster=yes"]
272 print "Created socket at %s" % sname
273 child = StartLocalCommand(GetSSHCommand(node, None, opts=opts))
274 _MULTIPLEXERS[node] = (sname, child)
277 def CloseMultiplexers():
278 """Closes all current multiplexers and cleans up.
281 for node in _MULTIPLEXERS.keys():
282 (sname, child) = _MULTIPLEXERS.pop(node)
283 utils.KillProcess(child.pid, timeout=10, waitpid=True)
284 utils.RemoveFile(sname)
287 def GetCommandOutput(node, cmd, tty=None):
288 """Returns the output of a command executed on the given node.
291 p = StartLocalCommand(GetSSHCommand(node, cmd, tty=tty),
292 stdout=subprocess.PIPE)
293 AssertEqual(p.wait(), 0)
294 return p.stdout.read()
297 def UploadFile(node, src):
298 """Uploads a file to a node and returns the filename.
300 Caller needs to remove the returned file on the node when it's not needed
304 # Make sure nobody else has access to it while preserving local permissions
305 mode = os.stat(src).st_mode & 0700
307 cmd = ('tmp=$(tempfile --mode %o --prefix gnt) && '
308 '[[ -f "${tmp}" ]] && '
310 'echo "${tmp}"') % mode
314 p = subprocess.Popen(GetSSHCommand(node, cmd), shell=False, stdin=f,
315 stdout=subprocess.PIPE)
316 AssertEqual(p.wait(), 0)
318 # Return temporary filename
319 return p.stdout.read().strip()
324 def UploadData(node, data, mode=0600, filename=None):
325 """Uploads data to a node and returns the filename.
327 Caller needs to remove the returned file on the node when it's not needed
332 tmp = "tmp=%s" % utils.ShellQuote(filename)
334 tmp = "tmp=$(tempfile --mode %o --prefix gnt)" % mode
336 "[[ -f \"${tmp}\" ]] && "
337 "cat > \"${tmp}\" && "
338 "echo \"${tmp}\"") % tmp
340 p = subprocess.Popen(GetSSHCommand(node, cmd), shell=False,
341 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
344 AssertEqual(p.wait(), 0)
346 # Return temporary filename
347 return p.stdout.read().strip()
350 def BackupFile(node, path):
351 """Creates a backup of a file on the node and returns the filename.
353 Caller needs to remove the returned file on the node when it's not needed
357 cmd = ("tmp=$(tempfile --prefix .gnt --directory=$(dirname %s)) && "
358 "[[ -f \"$tmp\" ]] && "
360 "echo $tmp") % (utils.ShellQuote(path), utils.ShellQuote(path))
362 # Return temporary filename
363 return GetCommandOutput(node, cmd).strip()
366 def _ResolveName(cmd, key):
370 master = qa_config.GetMasterNode()
372 output = GetCommandOutput(master["primary"], utils.ShellQuoteArgs(cmd))
373 for line in output.splitlines():
374 (lkey, lvalue) = line.split(":", 1)
376 return lvalue.lstrip()
377 raise KeyError("Key not found")
380 def ResolveInstanceName(instance):
381 """Gets the full name of an instance.
383 @type instance: string
384 @param instance: Instance name
387 return _ResolveName(["gnt-instance", "info", instance],
391 def ResolveNodeName(node):
392 """Gets the full name of a node.
395 return _ResolveName(["gnt-node", "info", node["primary"]],
399 def GetNodeInstances(node, secondaries=False):
400 """Gets a list of instances on a node.
403 master = qa_config.GetMasterNode()
404 node_name = ResolveNodeName(node)
406 # Get list of all instances
407 cmd = ["gnt-instance", "list", "--separator=:", "--no-headers",
408 "--output=name,pnode,snodes"]
409 output = GetCommandOutput(master["primary"], utils.ShellQuoteArgs(cmd))
412 for line in output.splitlines():
413 (name, pnode, snodes) = line.split(":", 2)
414 if ((not secondaries and pnode == node_name) or
415 (secondaries and node_name in snodes.split(","))):
416 instances.append(name)
421 def _SelectQueryFields(rnd, fields):
422 """Generates a list of fields for query tests.
425 # Create copy for shuffling
426 fields = list(fields)
434 yield fields + fields
436 # Check small groups of fields
438 yield [fields.pop() for _ in range(rnd.randint(2, 10)) if fields]
441 def _List(listcmd, fields, names):
442 """Runs a list command.
445 master = qa_config.GetMasterNode()
447 cmd = [listcmd, "list", "--separator=|", "--no-headers",
448 "--output", ",".join(fields)]
453 return GetCommandOutput(master["primary"],
454 utils.ShellQuoteArgs(cmd)).splitlines()
457 def GenericQueryTest(cmd, fields, namefield="name", test_unknown=True):
458 """Runs a number of tests on query commands.
460 @param cmd: Command name
461 @param fields: List of field names
464 rnd = random.Random(hash(cmd))
466 fields = list(fields)
469 # Test a number of field combinations
470 for testfields in _SelectQueryFields(rnd, fields):
471 AssertCommand([cmd, "list", "--output", ",".join(testfields)])
473 if namefield is not None:
474 namelist_fn = compat.partial(_List, cmd, [namefield])
476 # When no names were requested, the list must be sorted
477 names = namelist_fn(None)
478 AssertEqual(names, utils.NiceSort(names))
480 # When requesting specific names, the order must be kept
481 revnames = list(reversed(names))
482 AssertEqual(namelist_fn(revnames), revnames)
484 randnames = list(names)
485 rnd.shuffle(randnames)
486 AssertEqual(namelist_fn(randnames), randnames)
489 # Listing unknown items must fail
490 AssertCommand([cmd, "list", "this.name.certainly.does.not.exist"],
493 # Check exit code for listing unknown field
494 AssertEqual(AssertCommand([cmd, "list", "--output=field/does/not/exist"],
496 constants.EXIT_UNKNOWN_FIELD)
499 def GenericQueryFieldsTest(cmd, fields):
500 master = qa_config.GetMasterNode()
503 AssertCommand([cmd, "list-fields"])
504 AssertCommand([cmd, "list-fields"] + fields)
506 # Check listed fields (all, must be sorted)
507 realcmd = [cmd, "list-fields", "--separator=|", "--no-headers"]
508 output = GetCommandOutput(master["primary"],
509 utils.ShellQuoteArgs(realcmd)).splitlines()
510 AssertEqual([line.split("|", 1)[0] for line in output],
511 utils.NiceSort(fields))
513 # Check exit code for listing unknown field
514 AssertEqual(AssertCommand([cmd, "list-fields", "field/does/not/exist"],
516 constants.EXIT_UNKNOWN_FIELD)
519 def _FormatWithColor(text, seq):
522 return "%s%s%s" % (seq, text, _RESET_SEQ)
525 FormatWarning = lambda text: _FormatWithColor(text, _WARNING_SEQ)
526 FormatError = lambda text: _FormatWithColor(text, _ERROR_SEQ)
527 FormatInfo = lambda text: _FormatWithColor(text, _INFO_SEQ)
530 def AddToEtcHosts(hostnames):
531 """Adds hostnames to /etc/hosts.
533 @param hostnames: List of hostnames first used A records, all other CNAMEs
536 master = qa_config.GetMasterNode()
537 tmp_hosts = UploadData(master["primary"], "", mode=0644)
540 for localhost in ("::1", "127.0.0.1"):
541 data.append("%s %s" % (localhost, " ".join(hostnames)))
544 AssertCommand("{ cat %s && echo -e '%s'; } > %s && mv %s %s" %
545 (utils.ShellQuote(pathutils.ETC_HOSTS),
547 utils.ShellQuote(tmp_hosts),
548 utils.ShellQuote(tmp_hosts),
549 utils.ShellQuote(pathutils.ETC_HOSTS)))
551 AssertCommand(["rm", "-f", tmp_hosts])
555 def RemoveFromEtcHosts(hostnames):
556 """Remove hostnames from /etc/hosts.
558 @param hostnames: List of hostnames first used A records, all other CNAMEs
561 master = qa_config.GetMasterNode()
562 tmp_hosts = UploadData(master["primary"], "", mode=0644)
563 quoted_tmp_hosts = utils.ShellQuote(tmp_hosts)
565 sed_data = " ".join(hostnames)
567 AssertCommand(("sed -e '/^\(::1\|127\.0\.0\.1\)\s\+%s/d' %s > %s"
569 (sed_data, utils.ShellQuote(pathutils.ETC_HOSTS),
570 quoted_tmp_hosts, quoted_tmp_hosts,
571 utils.ShellQuote(pathutils.ETC_HOSTS)))
573 AssertCommand(["rm", "-f", tmp_hosts])
577 def RunInstanceCheck(instance, running):
578 """Check if instance is running or not.
581 instance_name = _GetName(instance, "name")
583 script = qa_config.GetInstanceCheckScript()
587 master_node = qa_config.GetMasterNode()
589 # Build command to connect to master node
590 master_ssh = GetSSHCommand(master_node["primary"], "--")
593 running_shellval = "1"
596 running_shellval = ""
597 running_text = "not "
599 print FormatInfo("Checking if instance '%s' is %srunning" %
600 (instance_name, running_text))
602 args = [script, instance_name]
604 "PATH": constants.HOOKS_PATH,
605 "RUN_UUID": _RUN_UUID,
606 "MASTER_SSH": utils.ShellQuoteArgs(master_ssh),
607 "INSTANCE_NAME": instance_name,
608 "INSTANCE_RUNNING": running_shellval,
611 result = os.spawnve(os.P_WAIT, script, args, env)
613 raise qa_error.Error("Instance check failed with result %s" % result)
616 def _InstanceCheckInner(expected, instarg, args, result):
617 """Helper function used by L{InstanceCheck}.
620 if instarg == FIRST_ARG:
622 elif instarg == RETURN_VALUE:
625 raise Exception("Invalid value '%s' for instance argument" % instarg)
627 if expected in (INST_DOWN, INST_UP):
628 RunInstanceCheck(instance, (expected == INST_UP))
629 elif expected is not None:
630 raise Exception("Invalid value '%s'" % expected)
633 def InstanceCheck(before, after, instarg):
634 """Decorator to check instance status before and after test.
636 @param before: L{INST_DOWN} if instance must be stopped before test,
637 L{INST_UP} if instance must be running before test, L{None} to not check.
638 @param after: L{INST_DOWN} if instance must be stopped after test,
639 L{INST_UP} if instance must be running after test, L{None} to not check.
640 @param instarg: L{FIRST_ARG} to use first argument to test as instance (a
641 dictionary), L{RETURN_VALUE} to use return value (disallows pre-checks)
646 def wrapper(*args, **kwargs):
647 _InstanceCheckInner(before, instarg, args, NotImplemented)
649 result = fn(*args, **kwargs)
651 _InstanceCheckInner(after, instarg, args, result)