4 # Copyright (C) 2007 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.
31 from ganeti import utils
44 """Initializes the colour constants.
47 global _INFO_SEQ, _WARNING_SEQ, _ERROR_SEQ, _RESET_SEQ
49 # Don't use colours if stdout isn't a terminal
50 if not sys.stdout.isatty():
56 # Don't use colours if curses module can't be imported
61 _RESET_SEQ = curses.tigetstr("op")
63 setaf = curses.tigetstr("setaf")
64 _INFO_SEQ = curses.tparm(setaf, curses.COLOR_GREEN)
65 _WARNING_SEQ = curses.tparm(setaf, curses.COLOR_YELLOW)
66 _ERROR_SEQ = curses.tparm(setaf, curses.COLOR_RED)
72 def AssertIn(item, sequence):
73 """Raises an error when item is not in sequence.
76 if item not in sequence:
77 raise qa_error.Error('%r not in %r' % (item, sequence))
80 def AssertEqual(first, second):
81 """Raises an error when values aren't equal.
84 if not first == second:
85 raise qa_error.Error('%r == %r' % (first, second))
88 def AssertNotEqual(first, second):
89 """Raises an error when values are equal.
92 if not first != second:
93 raise qa_error.Error('%r != %r' % (first, second))
96 def AssertMatch(string, pattern):
97 """Raises an error when string doesn't match regexp pattern.
100 if not re.match(pattern, string):
101 raise qa_error.Error("%r doesn't match /%r/" % (string, pattern))
104 def GetSSHCommand(node, cmd, strict=True):
105 """Builds SSH command to be executed.
108 - node: Node the command should run on
109 - cmd: Command to be executed as a list with all parameters
110 - strict: Whether to enable strict host key checking
113 args = [ 'ssh', '-oEscapeChar=none', '-oBatchMode=yes', '-l', 'root', '-t' ]
119 args.append('-oStrictHostKeyChecking=%s' % tmp)
120 args.append('-oClearAllForwardings=yes')
121 args.append('-oForwardAgent=yes')
125 print 'SSH:', utils.ShellQuoteArgs(args)
130 def StartSSH(node, cmd, strict=True):
134 return subprocess.Popen(GetSSHCommand(node, cmd, strict=strict),
138 def GetCommandOutput(node, cmd):
139 """Returns the output of a command executed on the given node.
142 p = subprocess.Popen(GetSSHCommand(node, cmd),
143 shell=False, stdout=subprocess.PIPE)
144 AssertEqual(p.wait(), 0)
145 return p.stdout.read()
148 def UploadFile(node, src):
149 """Uploads a file to a node and returns the filename.
151 Caller needs to remove the returned file on the node when it's not needed
155 # Make sure nobody else has access to it while preserving local permissions
156 mode = os.stat(src).st_mode & 0700
158 cmd = ('tmp=$(tempfile --mode %o --prefix gnt) && '
159 '[[ -f "${tmp}" ]] && '
161 'echo "${tmp}"') % mode
165 p = subprocess.Popen(GetSSHCommand(node, cmd), shell=False, stdin=f,
166 stdout=subprocess.PIPE)
167 AssertEqual(p.wait(), 0)
169 # Return temporary filename
170 return p.stdout.read().strip()
175 def BackupFile(node, path):
176 """Creates a backup of a file on the node and returns the filename.
178 Caller needs to remove the returned file on the node when it's not needed
182 cmd = ("tmp=$(tempfile --prefix .gnt --directory=$(dirname %s)) && "
183 "[[ -f \"$tmp\" ]] && "
185 "echo $tmp") % (utils.ShellQuote(path), utils.ShellQuote(path))
187 # Return temporary filename
188 return GetCommandOutput(node, cmd).strip()
191 def _ResolveName(cmd, key):
195 master = qa_config.GetMasterNode()
197 output = GetCommandOutput(master['primary'], utils.ShellQuoteArgs(cmd))
198 for line in output.splitlines():
199 (lkey, lvalue) = line.split(':', 1)
201 return lvalue.lstrip()
202 raise KeyError("Key not found")
205 def ResolveInstanceName(instance):
206 """Gets the full name of an instance.
209 return _ResolveName(['gnt-instance', 'info', instance['name']],
213 def ResolveNodeName(node):
214 """Gets the full name of a node.
217 return _ResolveName(['gnt-node', 'info', node['primary']],
221 def GetNodeInstances(node, secondaries=False):
222 """Gets a list of instances on a node.
225 master = qa_config.GetMasterNode()
226 node_name = ResolveNodeName(node)
228 # Get list of all instances
229 cmd = ['gnt-instance', 'list', '--separator=:', '--no-headers',
230 '--output=name,pnode,snodes']
231 output = GetCommandOutput(master['primary'], utils.ShellQuoteArgs(cmd))
234 for line in output.splitlines():
235 (name, pnode, snodes) = line.split(':', 2)
236 if ((not secondaries and pnode == node_name) or
237 (secondaries and node_name in snodes.split(','))):
238 instances.append(name)
243 def _FormatWithColor(text, seq):
246 return "%s%s%s" % (seq, text, _RESET_SEQ)
249 FormatWarning = lambda text: _FormatWithColor(text, _WARNING_SEQ)
250 FormatError = lambda text: _FormatWithColor(text, _ERROR_SEQ)
251 FormatInfo = lambda text: _FormatWithColor(text, _INFO_SEQ)