Remove QA hook functionality
[ganeti-local] / qa / qa_utils.py
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 AssertEqual(first, second):
72   """Raises an error when values aren't equal.
73
74   """
75   if not first == second:
76     raise qa_error.Error('%r == %r' % (first, second))
77
78
79 def AssertNotEqual(first, second):
80   """Raises an error when values are equal.
81
82   """
83   if not first != second:
84     raise qa_error.Error('%r != %r' % (first, second))
85
86
87 def GetSSHCommand(node, cmd, strict=True):
88   """Builds SSH command to be executed.
89
90   Args:
91   - node: Node the command should run on
92   - cmd: Command to be executed as a list with all parameters
93   - strict: Whether to enable strict host key checking
94
95   """
96   args = [ 'ssh', '-oEscapeChar=none', '-oBatchMode=yes', '-l', 'root' ]
97
98   if strict:
99     tmp = 'yes'
100   else:
101     tmp = 'no'
102   args.append('-oStrictHostKeyChecking=%s' % tmp)
103   args.append('-oClearAllForwardings=yes')
104   args.append('-oForwardAgent=yes')
105   args.append(node)
106
107   if qa_config.options.dry_run:
108     prefix = 'exit 0; '
109   else:
110     prefix = ''
111
112   args.append(prefix + cmd)
113
114   print 'SSH:', utils.ShellQuoteArgs(args)
115
116   return args
117
118
119 def StartSSH(node, cmd, strict=True):
120   """Starts SSH.
121
122   """
123   return subprocess.Popen(GetSSHCommand(node, cmd, strict=strict),
124                           shell=False)
125
126
127 def GetCommandOutput(node, cmd):
128   """Returns the output of a command executed on the given node.
129
130   """
131   p = subprocess.Popen(GetSSHCommand(node, cmd),
132                        shell=False, stdout=subprocess.PIPE)
133   AssertEqual(p.wait(), 0)
134   return p.stdout.read()
135
136
137 def UploadFile(node, src):
138   """Uploads a file to a node and returns the filename.
139
140   Caller needs to remove the returned file on the node when it's not needed
141   anymore.
142   """
143   # Make sure nobody else has access to it while preserving local permissions
144   mode = os.stat(src).st_mode & 0700
145
146   cmd = ('tmp=$(tempfile --mode %o --prefix gnt) && '
147          '[[ -f "${tmp}" ]] && '
148          'cat > "${tmp}" && '
149          'echo "${tmp}"') % mode
150
151   f = open(src, 'r')
152   try:
153     p = subprocess.Popen(GetSSHCommand(node, cmd), shell=False, stdin=f,
154                          stdout=subprocess.PIPE)
155     AssertEqual(p.wait(), 0)
156
157     # Return temporary filename
158     return p.stdout.read().strip()
159   finally:
160     f.close()
161
162
163 def _ResolveName(cmd, key):
164   """Helper function.
165
166   """
167   master = qa_config.GetMasterNode()
168
169   output = GetCommandOutput(master['primary'], utils.ShellQuoteArgs(cmd))
170   for line in output.splitlines():
171     (lkey, lvalue) = line.split(':', 1)
172     if lkey == key:
173       return lvalue.lstrip()
174   raise KeyError("Key not found")
175
176
177 def ResolveInstanceName(instance):
178   """Gets the full name of an instance.
179
180   """
181   return _ResolveName(['gnt-instance', 'info', instance['name']],
182                       'Instance name')
183
184
185 def ResolveNodeName(node):
186   """Gets the full name of a node.
187
188   """
189   return _ResolveName(['gnt-node', 'info', node['primary']],
190                       'Node name')
191
192
193 def GetNodeInstances(node, secondaries=False):
194   """Gets a list of instances on a node.
195
196   """
197   master = qa_config.GetMasterNode()
198   node_name = ResolveNodeName(node)
199
200   # Get list of all instances
201   cmd = ['gnt-instance', 'list', '--separator=:', '--no-headers',
202          '--output=name,pnode,snodes']
203   output = GetCommandOutput(master['primary'], utils.ShellQuoteArgs(cmd))
204
205   instances = []
206   for line in output.splitlines():
207     (name, pnode, snodes) = line.split(':', 2)
208     if ((not secondaries and pnode == node_name) or
209         (secondaries and node_name in snodes.split(','))):
210       instances.append(name)
211
212   return instances
213
214
215 def _FormatWithColor(text, seq):
216   if not seq:
217     return text
218   return "%s%s%s" % (seq, text, _RESET_SEQ)
219
220
221 FormatWarning = lambda text: _FormatWithColor(text, _WARNING_SEQ)
222 FormatError = lambda text: _FormatWithColor(text, _ERROR_SEQ)
223 FormatInfo = lambda text: _FormatWithColor(text, _INFO_SEQ)