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.
30 from ganeti import utils
43 """Initializes the colour constants.
46 global _INFO_SEQ, _WARNING_SEQ, _ERROR_SEQ, _RESET_SEQ
48 # Don't use colours if stdout isn't a terminal
49 if not sys.stdout.isatty():
55 # Don't use colours if curses module can't be imported
60 _RESET_SEQ = curses.tigetstr("op")
62 setaf = curses.tigetstr("setaf")
63 _INFO_SEQ = curses.tparm(setaf, curses.COLOR_GREEN)
64 _WARNING_SEQ = curses.tparm(setaf, curses.COLOR_YELLOW)
65 _ERROR_SEQ = curses.tparm(setaf, curses.COLOR_RED)
71 def AssertIn(item, sequence):
72 """Raises an error when item is not in sequence.
75 if item not in sequence:
76 raise qa_error.Error('%r not in %r' % (item, sequence))
79 def AssertEqual(first, second):
80 """Raises an error when values aren't equal.
83 if not first == second:
84 raise qa_error.Error('%r == %r' % (first, second))
87 def AssertNotEqual(first, second):
88 """Raises an error when values are equal.
91 if not first != second:
92 raise qa_error.Error('%r != %r' % (first, second))
95 def GetSSHCommand(node, cmd, strict=True):
96 """Builds SSH command to be executed.
99 - node: Node the command should run on
100 - cmd: Command to be executed as a list with all parameters
101 - strict: Whether to enable strict host key checking
104 args = [ 'ssh', '-oEscapeChar=none', '-oBatchMode=yes', '-l', 'root', '-t' ]
110 args.append('-oStrictHostKeyChecking=%s' % tmp)
111 args.append('-oClearAllForwardings=yes')
112 args.append('-oForwardAgent=yes')
116 print 'SSH:', utils.ShellQuoteArgs(args)
121 def StartSSH(node, cmd, strict=True):
125 return subprocess.Popen(GetSSHCommand(node, cmd, strict=strict),
129 def GetCommandOutput(node, cmd):
130 """Returns the output of a command executed on the given node.
133 p = subprocess.Popen(GetSSHCommand(node, cmd),
134 shell=False, stdout=subprocess.PIPE)
135 AssertEqual(p.wait(), 0)
136 return p.stdout.read()
139 def UploadFile(node, src):
140 """Uploads a file to a node and returns the filename.
142 Caller needs to remove the returned file on the node when it's not needed
145 # Make sure nobody else has access to it while preserving local permissions
146 mode = os.stat(src).st_mode & 0700
148 cmd = ('tmp=$(tempfile --mode %o --prefix gnt) && '
149 '[[ -f "${tmp}" ]] && '
151 'echo "${tmp}"') % mode
155 p = subprocess.Popen(GetSSHCommand(node, cmd), shell=False, stdin=f,
156 stdout=subprocess.PIPE)
157 AssertEqual(p.wait(), 0)
159 # Return temporary filename
160 return p.stdout.read().strip()
165 def _ResolveName(cmd, key):
169 master = qa_config.GetMasterNode()
171 output = GetCommandOutput(master['primary'], utils.ShellQuoteArgs(cmd))
172 for line in output.splitlines():
173 (lkey, lvalue) = line.split(':', 1)
175 return lvalue.lstrip()
176 raise KeyError("Key not found")
179 def ResolveInstanceName(instance):
180 """Gets the full name of an instance.
183 return _ResolveName(['gnt-instance', 'info', instance['name']],
187 def ResolveNodeName(node):
188 """Gets the full name of a node.
191 return _ResolveName(['gnt-node', 'info', node['primary']],
195 def GetNodeInstances(node, secondaries=False):
196 """Gets a list of instances on a node.
199 master = qa_config.GetMasterNode()
200 node_name = ResolveNodeName(node)
202 # Get list of all instances
203 cmd = ['gnt-instance', 'list', '--separator=:', '--no-headers',
204 '--output=name,pnode,snodes']
205 output = GetCommandOutput(master['primary'], utils.ShellQuoteArgs(cmd))
208 for line in output.splitlines():
209 (name, pnode, snodes) = line.split(':', 2)
210 if ((not secondaries and pnode == node_name) or
211 (secondaries and node_name in snodes.split(','))):
212 instances.append(name)
217 def _FormatWithColor(text, seq):
220 return "%s%s%s" % (seq, text, _RESET_SEQ)
223 FormatWarning = lambda text: _FormatWithColor(text, _WARNING_SEQ)
224 FormatError = lambda text: _FormatWithColor(text, _ERROR_SEQ)
225 FormatInfo = lambda text: _FormatWithColor(text, _INFO_SEQ)