blob: d8993bbf0e0fd88d1b1bd3017e5cb9e59222492b [file] [log] [blame]
Sean Dague556add52013-07-19 14:28:44 -04001# Licensed under the Apache License, Version 2.0 (the "License"); you may
2# not use this file except in compliance with the License. You may obtain
3# a copy of the License at
4#
5# http://www.apache.org/licenses/LICENSE-2.0
6#
7# Unless required by applicable law or agreed to in writing, software
8# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10# License for the specific language governing permissions and limitations
11# under the License.
12
Kirill Shileev14113572014-11-21 16:58:02 +030013import netaddr
Attila Fazekasa23f5002012-10-23 19:32:45 +020014import re
Andrea Frittoli (andreaf)5f5e4fc2016-04-29 16:00:17 -050015import six
16import sys
Matthew Treinisha83a16e2012-12-07 13:44:02 -050017import time
18
David Kranz968f1b32015-06-18 16:58:18 -040019from oslo_log import log as logging
Matthew Treinish96e9e882014-06-09 18:37:19 -040020
Sean Dague86bd8422013-12-20 09:56:44 -050021from tempest import config
Andrea Frittoli (andreaf)db9672e2016-02-23 14:07:24 -050022from tempest.lib.common import ssh
Jordan Pittier9e227c52016-02-09 14:35:18 +010023from tempest.lib.common.utils import test_utils
Andrea Frittoli (andreaf)db9672e2016-02-23 14:07:24 -050024import tempest.lib.exceptions
Daryl Walleck98e66dd2012-06-21 04:58:39 -050025
Sean Dague86bd8422013-12-20 09:56:44 -050026CONF = config.CONF
27
David Kranz968f1b32015-06-18 16:58:18 -040028LOG = logging.getLogger(__name__)
29
Daryl Walleck6b9b2882012-04-08 21:43:39 -050030
Andrea Frittoli (andreaf)5f5e4fc2016-04-29 16:00:17 -050031def debug_ssh(function):
32 """Decorator to generate extra debug info in case off SSH failure"""
33 def wrapper(self, *args, **kwargs):
34 try:
35 return function(self, *args, **kwargs)
36 except tempest.lib.exceptions.SSHTimeout:
37 try:
38 original_exception = sys.exc_info()
Jordan Pittier9e227c52016-02-09 14:35:18 +010039 caller = test_utils.find_test_caller() or "not found"
Andrea Frittoli (andreaf)5f5e4fc2016-04-29 16:00:17 -050040 if self.server:
41 msg = 'Caller: %s. Timeout trying to ssh to server %s'
42 LOG.debug(msg, caller, self.server)
43 if self.log_console and self.servers_client:
44 try:
45 msg = 'Console log for server %s: %s'
46 console_log = (
47 self.servers_client.get_console_output(
48 self.server['id'])['output'])
49 LOG.debug(msg, self.server['id'], console_log)
50 except Exception:
51 msg = 'Could not get console_log for server %s'
52 LOG.debug(msg, self.server['id'])
53 # re-raise the original ssh timeout exception
54 six.reraise(*original_exception)
55 finally:
56 # Delete the traceback to avoid circular references
57 _, _, trace = original_exception
58 del trace
59 return wrapper
60
61
Joe Gordon28788b42015-02-25 12:42:37 -080062class RemoteClient(object):
Daryl Walleck6b9b2882012-04-08 21:43:39 -050063
Andrea Frittoli (andreaf)5f5e4fc2016-04-29 16:00:17 -050064 def __init__(self, ip_address, username, password=None, pkey=None,
65 server=None, servers_client=None):
66 """Executes commands in a VM over ssh
67
68 :param ip_address: IP address to ssh to
69 :param username: ssh username
70 :param password: ssh password (optional)
71 :param pkey: ssh public key (optional)
72 :param server: server dict, used for debugging purposes
73 :param servers_client: servers client, used for debugging purposes
74 """
75 self.server = server
76 self.servers_client = servers_client
nithya-ganesan67da2872015-02-08 23:13:48 +000077 ssh_timeout = CONF.validation.ssh_timeout
nithya-ganesan67da2872015-02-08 23:13:48 +000078 connect_timeout = CONF.validation.connect_timeout
Andrea Frittoli (andreaf)5f5e4fc2016-04-29 16:00:17 -050079 self.log_console = CONF.compute_feature_enabled.console_output
Sean Dague20e98612016-01-06 14:33:28 -050080
Masayuki Igawa7e9eb542014-02-17 15:03:44 +090081 self.ssh_client = ssh.Client(ip_address, username, password,
82 ssh_timeout, pkey=pkey,
nithya-ganesan67da2872015-02-08 23:13:48 +000083 channel_timeout=connect_timeout)
Daryl Walleck6b9b2882012-04-08 21:43:39 -050084
Andrea Frittoli (andreaf)5f5e4fc2016-04-29 16:00:17 -050085 @debug_ssh
Elena Ezhova91db24e2014-02-28 20:47:10 +040086 def exec_command(self, cmd):
Evgeny Antyshevf58ab6d2015-04-15 08:23:05 +000087 # Shell options below add more clearness on failures,
88 # path is extended for some non-cirros guest oses (centos7)
lanoux283273b2015-12-04 03:01:54 -080089 cmd = CONF.validation.ssh_shell_prologue + " " + cmd
David Kranz968f1b32015-06-18 16:58:18 -040090 LOG.debug("Remote command: %s" % cmd)
Elena Ezhova91db24e2014-02-28 20:47:10 +040091 return self.ssh_client.exec_command(cmd)
92
Andrea Frittoli (andreaf)5f5e4fc2016-04-29 16:00:17 -050093 @debug_ssh
Attila Fazekasad7ef7d2013-11-20 10:12:53 +010094 def validate_authentication(self):
95 """Validate ssh connection and authentication
Ken'ichi Ohmichicb67d2d2015-11-19 08:23:22 +000096
Attila Fazekasad7ef7d2013-11-20 10:12:53 +010097 This method raises an Exception when the validation fails.
98 """
99 self.ssh_client.test_connection_auth()
Daryl Walleck6b9b2882012-04-08 21:43:39 -0500100
imran malikcdf20382016-06-16 00:43:57 -0700101 def get_hostname(self):
Chang Bo Guocc1623c2013-09-13 20:11:27 -0700102 # Get host name using command "hostname"
Elena Ezhova91db24e2014-02-28 20:47:10 +0400103 actual_hostname = self.exec_command("hostname").rstrip()
imran malikcdf20382016-06-16 00:43:57 -0700104 return actual_hostname
Daryl Walleck6b9b2882012-04-08 21:43:39 -0500105
Daryl Walleck6b9b2882012-04-08 21:43:39 -0500106 def get_ram_size_in_mb(self):
Elena Ezhova91db24e2014-02-28 20:47:10 +0400107 output = self.exec_command('free -m | grep Mem')
Daryl Walleck6b9b2882012-04-08 21:43:39 -0500108 if output:
109 return output.split()[1]
110
111 def get_number_of_vcpus(self):
Mathieu Gagné2020d6e2015-12-10 19:52:12 -0500112 output = self.exec_command('grep -c ^processor /proc/cpuinfo')
Daryl Walleck6b9b2882012-04-08 21:43:39 -0500113 return int(output)
Dan Smithc18d8c62012-07-02 08:09:26 -0700114
Evgeny Antyshev4894a912016-11-21 12:17:18 +0000115 def get_disks(self):
116 # Select root disk devices as shown by lsblk
117 command = 'lsblk -lb --nodeps'
Elena Ezhova91db24e2014-02-28 20:47:10 +0400118 output = self.exec_command(command)
Evgeny Antyshev4894a912016-11-21 12:17:18 +0000119 selected = []
120 pos = None
121 for l in output.splitlines():
122 if pos is None and l.find("TYPE") > 0:
123 pos = l.find("TYPE")
124 # Show header line too
125 selected.append(l)
126 # lsblk lists disk type in a column right-aligned with TYPE
127 elif pos > 0 and l[pos:pos + 4] == "disk":
128 selected.append(l)
129
130 return "\n".join(selected)
Daryl Walleck98e66dd2012-06-21 04:58:39 -0500131
132 def get_boot_time(self):
Vincent Untz3c0b5b92014-01-18 10:56:00 +0100133 cmd = 'cut -f1 -d. /proc/uptime'
Elena Ezhova91db24e2014-02-28 20:47:10 +0400134 boot_secs = self.exec_command(cmd)
Vincent Untz3c0b5b92014-01-18 10:56:00 +0100135 boot_time = time.time() - int(boot_secs)
136 return time.localtime(boot_time)
Attila Fazekasa23f5002012-10-23 19:32:45 +0200137
138 def write_to_console(self, message):
139 message = re.sub("([$\\`])", "\\\\\\\\\\1", message)
140 # usually to /dev/ttyS0
141 cmd = 'sudo sh -c "echo \\"%s\\" >/dev/console"' % message
Elena Ezhova91db24e2014-02-28 20:47:10 +0400142 return self.exec_command(cmd)
Yair Fried5f670ab2013-12-09 09:26:51 +0200143
lanoux283273b2015-12-04 03:01:54 -0800144 def ping_host(self, host, count=CONF.validation.ping_count,
145 size=CONF.validation.ping_size, nic=None):
Kirill Shileev14113572014-11-21 16:58:02 +0300146 addr = netaddr.IPAddress(host)
147 cmd = 'ping6' if addr.version == 6 else 'ping'
Yair Friedbc46f592015-11-18 16:29:34 +0200148 if nic:
149 cmd = 'sudo {cmd} -I {nic}'.format(cmd=cmd, nic=nic)
Richard Wintersf87059b2015-02-17 11:46:54 -0500150 cmd += ' -c{0} -w{0} -s{1} {2}'.format(count, size, host)
Elena Ezhova91db24e2014-02-28 20:47:10 +0400151 return self.exec_command(cmd)
Yair Fried4d7efa62013-11-17 17:12:29 +0200152
Yair Friedbc46f592015-11-18 16:29:34 +0200153 def set_mac_address(self, nic, address):
154 self.set_nic_state(nic=nic, state="down")
155 cmd = "sudo ip link set dev {0} address {1}".format(nic, address)
156 self.exec_command(cmd)
157 self.set_nic_state(nic=nic, state="up")
158
159 def get_mac_address(self, nic=""):
160 show_nic = "show {nic} ".format(nic=nic) if nic else ""
161 cmd = "ip addr %s| awk '/ether/ {print $2}'" % show_nic
162 return self.exec_command(cmd).strip().lower()
Yair Fried3097dc12014-01-26 08:46:43 +0200163
Evgeny Antyshev9b77ae52016-02-16 09:48:57 +0000164 def get_nic_name_by_mac(self, address):
165 cmd = "ip -o link | awk '/%s/ {print $2}'" % address
166 nic = self.exec_command(cmd)
167 return nic.strip().strip(":").lower()
168
169 def get_nic_name_by_ip(self, address):
Evgeny Antyshevf58ab6d2015-04-15 08:23:05 +0000170 cmd = "ip -o addr | awk '/%s/ {print $2}'" % address
Daniel Mellado9e3e1062015-08-06 18:07:05 +0200171 nic = self.exec_command(cmd)
172 return nic.strip().strip(":").lower()
Yair Fried413bf2d2014-11-19 17:07:11 +0200173
Yair Fried3097dc12014-01-26 08:46:43 +0200174 def get_ip_list(self):
Evgeny Antyshevf58ab6d2015-04-15 08:23:05 +0000175 cmd = "ip address"
Elena Ezhova91db24e2014-02-28 20:47:10 +0400176 return self.exec_command(cmd)
Yair Fried3097dc12014-01-26 08:46:43 +0200177
178 def assign_static_ip(self, nic, addr):
Evgeny Antyshevf58ab6d2015-04-15 08:23:05 +0000179 cmd = "sudo ip addr add {ip}/{mask} dev {nic}".format(
Sean Dagueed6e5862016-04-04 10:49:13 -0400180 ip=addr, mask=CONF.network.project_network_mask_bits,
Yair Fried3097dc12014-01-26 08:46:43 +0200181 nic=nic
182 )
Elena Ezhova91db24e2014-02-28 20:47:10 +0400183 return self.exec_command(cmd)
Yair Fried3097dc12014-01-26 08:46:43 +0200184
Yair Friedbc46f592015-11-18 16:29:34 +0200185 def set_nic_state(self, nic, state="up"):
186 cmd = "sudo ip link set {nic} {state}".format(nic=nic, state=state)
Elena Ezhova91db24e2014-02-28 20:47:10 +0400187 return self.exec_command(cmd)
Elena Ezhova4a27b462014-04-09 15:25:46 +0400188
189 def get_pids(self, pr_name):
190 # Get pid(s) of a process/program
191 cmd = "ps -ef | grep %s | grep -v 'grep' | awk {'print $1'}" % pr_name
192 return self.exec_command(cmd).split('\n')
Yair Fried413bf2d2014-11-19 17:07:11 +0200193
194 def get_dns_servers(self):
195 cmd = 'cat /etc/resolv.conf'
196 resolve_file = self.exec_command(cmd).strip().split('\n')
197 entries = (l.split() for l in resolve_file)
198 dns_servers = [l[1] for l in entries
199 if len(l) and l[0] == 'nameserver']
200 return dns_servers
201
202 def send_signal(self, pid, signum):
203 cmd = 'sudo /bin/kill -{sig} {pid}'.format(pid=pid, sig=signum)
204 return self.exec_command(cmd)
205
206 def _renew_lease_udhcpc(self, fixed_ip=None):
207 """Renews DHCP lease via udhcpc client. """
208 file_path = '/var/run/udhcpc.'
Evgeny Antyshev9b77ae52016-02-16 09:48:57 +0000209 nic_name = self.get_nic_name_by_ip(fixed_ip)
Yair Fried413bf2d2014-11-19 17:07:11 +0200210 pid = self.exec_command('cat {path}{nic}.pid'.
211 format(path=file_path, nic=nic_name))
212 pid = pid.strip()
213 self.send_signal(pid, 'USR1')
214
215 def _renew_lease_dhclient(self, fixed_ip=None):
216 """Renews DHCP lease via dhclient client. """
Itzik Brownffb14022015-03-23 17:03:55 +0200217 cmd = "sudo /sbin/dhclient -r && sudo /sbin/dhclient"
Yair Fried413bf2d2014-11-19 17:07:11 +0200218 self.exec_command(cmd)
219
220 def renew_lease(self, fixed_ip=None):
221 """Wrapper method for renewing DHCP lease via given client
222
223 Supporting:
224 * udhcpc
225 * dhclient
226 """
227 # TODO(yfried): add support for dhcpcd
Takashi NATSUME6d5a2b42015-09-08 11:27:49 +0900228 supported_clients = ['udhcpc', 'dhclient']
Yair Fried413bf2d2014-11-19 17:07:11 +0200229 dhcp_client = CONF.scenario.dhcp_client
Takashi NATSUME6d5a2b42015-09-08 11:27:49 +0900230 if dhcp_client not in supported_clients:
Matthew Treinish4217a702016-10-07 17:27:11 -0400231 raise tempest.lib.exceptions.InvalidConfiguration(
232 '%s DHCP client unsupported' % dhcp_client)
Yair Fried413bf2d2014-11-19 17:07:11 +0200233 if dhcp_client == 'udhcpc' and not fixed_ip:
234 raise ValueError("need to set 'fixed_ip' for udhcpc client")
Joe Gordon28788b42015-02-25 12:42:37 -0800235 return getattr(self, '_renew_lease_' + dhcp_client)(fixed_ip=fixed_ip)
Alexander Gubanovabd154c2015-09-23 23:24:06 +0300236
237 def mount(self, dev_name, mount_path='/mnt'):
238 cmd_mount = 'sudo mount /dev/%s %s' % (dev_name, mount_path)
239 self.exec_command(cmd_mount)
240
241 def umount(self, mount_path='/mnt'):
242 self.exec_command('sudo umount %s' % mount_path)
243
244 def make_fs(self, dev_name, fs='ext4'):
245 cmd_mkfs = 'sudo /usr/sbin/mke2fs -t %s /dev/%s' % (fs, dev_name)
Sean Dague57c66552016-02-08 08:51:13 -0500246 try:
247 self.exec_command(cmd_mkfs)
Andrea Frittoli (andreaf)db9672e2016-02-23 14:07:24 -0500248 except tempest.lib.exceptions.SSHExecCommandFailed:
Sean Dague57c66552016-02-08 08:51:13 -0500249 LOG.error("Couldn't mke2fs")
250 cmd_why = 'sudo ls -lR /dev'
251 LOG.info("Contents of /dev: %s" % self.exec_command(cmd_why))
252 raise