Statistics
| Branch: | Tag: | Revision:

root / qa / qa_utils.py @ 305cb9bb

History | View | Annotate | Download (5.4 kB)

1
#
2
#
3

    
4
# Copyright (C) 2007 Google Inc.
5
#
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.
10
#
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.
15
#
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
19
# 02110-1301, USA.
20

    
21

    
22
"""Utilities for QA tests.
23

24
"""
25

    
26
import os
27
import sys
28
import subprocess
29

    
30
from ganeti import utils
31

    
32
import qa_config
33
import qa_error
34

    
35

    
36
_INFO_SEQ = None
37
_WARNING_SEQ = None
38
_ERROR_SEQ = None
39
_RESET_SEQ = None
40

    
41

    
42
def _SetupColours():
43
  """Initializes the colour constants.
44

45
  """
46
  global _INFO_SEQ, _WARNING_SEQ, _ERROR_SEQ, _RESET_SEQ
47

    
48
  # Don't use colours if stdout isn't a terminal
49
  if not sys.stdout.isatty():
50
    return
51

    
52
  try:
53
    import curses
54
  except ImportError:
55
    # Don't use colours if curses module can't be imported
56
    return
57

    
58
  curses.setupterm()
59

    
60
  _RESET_SEQ = curses.tigetstr("op")
61

    
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)
66

    
67

    
68
_SetupColours()
69

    
70

    
71
def AssertIn(item, sequence):
72
  """Raises an error when item is not in sequence.
73

74
  """
75
  if item not in sequence:
76
    raise qa_error.Error('%r not in %r' % (item, sequence))
77

    
78

    
79
def AssertEqual(first, second):
80
  """Raises an error when values aren't equal.
81

82
  """
83
  if not first == second:
84
    raise qa_error.Error('%r == %r' % (first, second))
85

    
86

    
87
def AssertNotEqual(first, second):
88
  """Raises an error when values are equal.
89

90
  """
91
  if not first != second:
92
    raise qa_error.Error('%r != %r' % (first, second))
93

    
94

    
95
def GetSSHCommand(node, cmd, strict=True):
96
  """Builds SSH command to be executed.
97

98
  Args:
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
102

103
  """
104
  args = [ 'ssh', '-oEscapeChar=none', '-oBatchMode=yes', '-l', 'root', '-t' ]
105

    
106
  if strict:
107
    tmp = 'yes'
108
  else:
109
    tmp = 'no'
110
  args.append('-oStrictHostKeyChecking=%s' % tmp)
111
  args.append('-oClearAllForwardings=yes')
112
  args.append('-oForwardAgent=yes')
113
  args.append(node)
114

    
115
  if qa_config.options.dry_run:
116
    prefix = 'exit 0; '
117
  else:
118
    prefix = ''
119

    
120
  args.append(prefix + cmd)
121

    
122
  print 'SSH:', utils.ShellQuoteArgs(args)
123

    
124
  return args
125

    
126

    
127
def StartSSH(node, cmd, strict=True):
128
  """Starts SSH.
129

130
  """
131
  return subprocess.Popen(GetSSHCommand(node, cmd, strict=strict),
132
                          shell=False)
133

    
134

    
135
def GetCommandOutput(node, cmd):
136
  """Returns the output of a command executed on the given node.
137

138
  """
139
  p = subprocess.Popen(GetSSHCommand(node, cmd),
140
                       shell=False, stdout=subprocess.PIPE)
141
  AssertEqual(p.wait(), 0)
142
  return p.stdout.read()
143

    
144

    
145
def UploadFile(node, src):
146
  """Uploads a file to a node and returns the filename.
147

148
  Caller needs to remove the returned file on the node when it's not needed
149
  anymore.
150
  """
151
  # Make sure nobody else has access to it while preserving local permissions
152
  mode = os.stat(src).st_mode & 0700
153

    
154
  cmd = ('tmp=$(tempfile --mode %o --prefix gnt) && '
155
         '[[ -f "${tmp}" ]] && '
156
         'cat > "${tmp}" && '
157
         'echo "${tmp}"') % mode
158

    
159
  f = open(src, 'r')
160
  try:
161
    p = subprocess.Popen(GetSSHCommand(node, cmd), shell=False, stdin=f,
162
                         stdout=subprocess.PIPE)
163
    AssertEqual(p.wait(), 0)
164

    
165
    # Return temporary filename
166
    return p.stdout.read().strip()
167
  finally:
168
    f.close()
169

    
170

    
171
def _ResolveName(cmd, key):
172
  """Helper function.
173

174
  """
175
  master = qa_config.GetMasterNode()
176

    
177
  output = GetCommandOutput(master['primary'], utils.ShellQuoteArgs(cmd))
178
  for line in output.splitlines():
179
    (lkey, lvalue) = line.split(':', 1)
180
    if lkey == key:
181
      return lvalue.lstrip()
182
  raise KeyError("Key not found")
183

    
184

    
185
def ResolveInstanceName(instance):
186
  """Gets the full name of an instance.
187

188
  """
189
  return _ResolveName(['gnt-instance', 'info', instance['name']],
190
                      'Instance name')
191

    
192

    
193
def ResolveNodeName(node):
194
  """Gets the full name of a node.
195

196
  """
197
  return _ResolveName(['gnt-node', 'info', node['primary']],
198
                      'Node name')
199

    
200

    
201
def GetNodeInstances(node, secondaries=False):
202
  """Gets a list of instances on a node.
203

204
  """
205
  master = qa_config.GetMasterNode()
206
  node_name = ResolveNodeName(node)
207

    
208
  # Get list of all instances
209
  cmd = ['gnt-instance', 'list', '--separator=:', '--no-headers',
210
         '--output=name,pnode,snodes']
211
  output = GetCommandOutput(master['primary'], utils.ShellQuoteArgs(cmd))
212

    
213
  instances = []
214
  for line in output.splitlines():
215
    (name, pnode, snodes) = line.split(':', 2)
216
    if ((not secondaries and pnode == node_name) or
217
        (secondaries and node_name in snodes.split(','))):
218
      instances.append(name)
219

    
220
  return instances
221

    
222

    
223
def _FormatWithColor(text, seq):
224
  if not seq:
225
    return text
226
  return "%s%s%s" % (seq, text, _RESET_SEQ)
227

    
228

    
229
FormatWarning = lambda text: _FormatWithColor(text, _WARNING_SEQ)
230
FormatError = lambda text: _FormatWithColor(text, _ERROR_SEQ)
231
FormatInfo = lambda text: _FormatWithColor(text, _INFO_SEQ)