1 # Copyright (C) 2007 Google Inc.
3 # This program is free software; you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation; either version 2 of the License, or
6 # (at your option) any later version.
8 # This program is distributed in the hope that it will be useful, but
9 # WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 # General Public License for more details.
13 # You should have received a copy of the GNU General Public License
14 # along with this program; if not, write to the Free Software
15 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 """Utilities for QA tests.
27 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 GetSSHCommand(node, cmd, strict=True):
97 """Builds SSH command to be executed.
100 args = [ 'ssh', '-oEscapeChar=none', '-oBatchMode=yes', '-l', 'root' ]
106 args.append('-oStrictHostKeyChecking=%s' % tmp)
107 args.append('-oClearAllForwardings=yes')
108 args.append('-oForwardAgent=yes')
111 if qa_config.options.dry_run:
116 args.append(prefix + cmd)
118 print 'SSH:', utils.ShellQuoteArgs(args)
123 def StartSSH(node, cmd, strict=True):
127 return subprocess.Popen(GetSSHCommand(node, cmd, strict=strict),
131 def GetCommandOutput(node, cmd):
132 """Returns the output of a command executed on the given node.
135 p = subprocess.Popen(GetSSHCommand(node, cmd),
136 shell=False, stdout=subprocess.PIPE)
137 AssertEqual(p.wait(), 0)
138 return p.stdout.read()
141 def UploadFile(node, src):
142 """Uploads a file to a node and returns the filename.
144 Caller needs to remove the returned file on the node when it's not needed
147 # Make sure nobody else has access to it while preserving local permissions
148 mode = os.stat(src).st_mode & 0700
150 cmd = ('tmp=$(tempfile --mode %o --prefix gnt) && '
151 '[[ -f "${tmp}" ]] && '
153 'echo "${tmp}"') % mode
157 p = subprocess.Popen(GetSSHCommand(node, cmd), shell=False, stdin=f,
158 stdout=subprocess.PIPE)
159 AssertEqual(p.wait(), 0)
161 # Return temporary filename
162 return p.stdout.read().strip()
167 def _ResolveName(cmd, key):
171 master = qa_config.GetMasterNode()
173 output = GetCommandOutput(master['primary'], utils.ShellQuoteArgs(cmd))
174 for line in output.splitlines():
175 (lkey, lvalue) = line.split(':', 1)
177 return lvalue.lstrip()
178 raise KeyError("Key not found")
181 def ResolveInstanceName(instance):
182 """Gets the full name of an instance.
185 return _ResolveName(['gnt-instance', 'info', instance['name']],
189 def ResolveNodeName(node):
190 """Gets the full name of a node.
193 return _ResolveName(['gnt-node', 'info', node['primary']],
197 def GetNodeInstances(node, secondaries=False):
198 """Gets a list of instances on a node.
201 master = qa_config.GetMasterNode()
203 node_name = ResolveNodeName(node)
205 # Get list of all instances
206 cmd = ['gnt-instance', 'list', '--separator=:', '--no-headers',
207 '--output=name,pnode,snodes']
208 output = GetCommandOutput(master['primary'], utils.ShellQuoteArgs(cmd))
211 for line in output.splitlines():
212 (name, pnode, snodes) = line.split(':', 2)
213 if ((not secondaries and pnode == node_name) or
214 (secondaries and node_name in snodes.split(','))):
215 instances.append(name)
220 def _FormatWithColor(text, seq):
223 return "%s%s%s" % (seq, text, _RESET_SEQ)
226 FormatWarning = lambda text: _FormatWithColor(text, _WARNING_SEQ)
227 FormatError = lambda text: _FormatWithColor(text, _ERROR_SEQ)
228 FormatInfo = lambda text: _FormatWithColor(text, _INFO_SEQ)
232 """Load all QA hooks.
235 hooks_dir = qa_config.get('options', {}).get('hooks-dir', None)
238 if hooks_dir not in sys.path:
239 sys.path.insert(0, hooks_dir)
240 for name in utils.ListVisibleFiles(hooks_dir):
241 if name.endswith('.py'):
242 # Load and instanciate hook
243 print "Loading hook %s" % name
244 _hooks.append(__import__(name[:-3], None, None, ['']).hook())
256 """Calls all hooks with the given context.
262 name = "%s-%s" % (ctx.phase, ctx.name)
263 if ctx.success is not None:
264 msg = "%s (success=%s)" % (name, ctx.success)
267 print FormatInfo("Begin %s" % msg)
270 print FormatInfo("End %s" % name)
273 def DefineHook(name):
274 """Wraps a function with calls to hooks.
276 Usage: prefix function with @qa_utils.DefineHook(...)
278 This based on PEP 318, "Decorators for Functions and Methods".
282 def new_f(*args, **kwargs):
284 ctx = QaHookContext()
296 return fn(*args, **kwargs)
303 # Override function metadata
304 new_f.func_name = fn.func_name
305 new_f.func_doc = fn.func_doc