blob: 7a59c3bea7b095faa9dcc6e70a6b7bfd8d99dfc0 [file] [log] [blame]
Itzik Browne67ebb52016-05-15 05:34:41 +00001# Copyright 2016 Red Hat, Inc.
2# All Rights Reserved.
3#
4# Licensed under the Apache License, Version 2.0 (the "License"); you may
5# not use this file except in compliance with the License. You may obtain
6# a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13# License for the specific language governing permissions and limitations
14# under the License.
Slawek Kaplonskiaf83e832020-02-05 12:11:54 +010015import distutils
16import re
Chandan Kumarc125fd12017-11-15 19:41:01 +053017import subprocess
Itzik Browne67ebb52016-05-15 05:34:41 +000018
Federico Ressibf877c82018-08-22 08:36:37 +020019from debtcollector import removals
YAMAMOTO Takashi25935722017-01-23 15:34:11 +090020import netaddr
Assaf Muller92fdc782018-05-31 10:32:47 -040021from neutron_lib.api import validators
22from neutron_lib import constants as neutron_lib_constants
Alex Stafeyevc4d9c352016-12-12 04:13:33 -050023from oslo_log import log
Genadi Chereshnya6d10c6e2017-07-05 11:34:20 +030024from tempest.common.utils import net_utils
Itzik Browne67ebb52016-05-15 05:34:41 +000025from tempest.common import waiters
Itzik Browne67ebb52016-05-15 05:34:41 +000026from tempest.lib.common.utils import data_utils
YAMAMOTO Takashi25935722017-01-23 15:34:11 +090027from tempest.lib.common.utils import test_utils
Jakub Libosvarc0c2f1d2017-01-31 12:12:21 -050028from tempest.lib import exceptions as lib_exc
Itzik Browne67ebb52016-05-15 05:34:41 +000029
Chandan Kumar667d3d32017-09-22 12:24:06 +053030from neutron_tempest_plugin.api import base as base_api
Rodolfo Alonso Hernandez4849f002020-01-16 16:01:10 +000031from neutron_tempest_plugin.common import ip as ip_utils
Slawek Kaplonskic4e963e2019-09-11 22:55:34 +020032from neutron_tempest_plugin.common import shell
Chandan Kumar667d3d32017-09-22 12:24:06 +053033from neutron_tempest_plugin.common import ssh
Slawek Kaplonskifd4141f2020-03-14 14:34:00 +010034from neutron_tempest_plugin.common import utils
Chandan Kumar667d3d32017-09-22 12:24:06 +053035from neutron_tempest_plugin import config
Slawek Kaplonskiaf83e832020-02-05 12:11:54 +010036from neutron_tempest_plugin import exceptions
Chandan Kumar667d3d32017-09-22 12:24:06 +053037from neutron_tempest_plugin.scenario import constants
Itzik Browne67ebb52016-05-15 05:34:41 +000038
39CONF = config.CONF
Itzik Browne67ebb52016-05-15 05:34:41 +000040
Alex Stafeyevc4d9c352016-12-12 04:13:33 -050041LOG = log.getLogger(__name__)
42
Itzik Browne67ebb52016-05-15 05:34:41 +000043
Slawek Kaplonskiaf83e832020-02-05 12:11:54 +010044def get_ncat_version(ssh_client=None):
45 cmd = "ncat --version 2>&1"
46 try:
47 version_result = shell.execute(cmd, ssh_client=ssh_client).stdout
48 except exceptions.ShellCommandFailed:
49 m = None
50 else:
51 m = re.match(r"Ncat: Version ([\d.]+) *.", version_result)
52 # NOTE(slaweq): by default lets assume we have ncat 7.60 which is in Ubuntu
53 # 18.04 which is used on u/s gates
54 return distutils.version.StrictVersion(m.group(1) if m else '7.60')
55
56
Slawek Kaplonskifd4141f2020-03-14 14:34:00 +010057def get_ncat_server_cmd(port, protocol, msg=None):
Slawek Kaplonskiaf83e832020-02-05 12:11:54 +010058 udp = ''
59 if protocol.lower() == neutron_lib_constants.PROTO_NAME_UDP:
60 udp = '-u'
61 cmd = "nc %(udp)s -p %(port)s -lk " % {
62 'udp': udp, 'port': port}
Slawek Kaplonskifd4141f2020-03-14 14:34:00 +010063 if msg:
64 if CONF.neutron_plugin_options.default_image_is_advanced:
Flavio Fernandesbbbf5eb2020-07-01 14:57:13 -040065 cmd += "-c 'echo %s' " % msg
Slawek Kaplonskifd4141f2020-03-14 14:34:00 +010066 else:
Flavio Fernandesbbbf5eb2020-07-01 14:57:13 -040067 cmd += "-e echo %s " % msg
68 cmd += "< /dev/zero &{0}sleep 0.1{0}".format('\n')
Slawek Kaplonskiaf83e832020-02-05 12:11:54 +010069 return cmd
70
71
72def get_ncat_client_cmd(ip_address, port, protocol):
73 udp = ''
74 if protocol.lower() == neutron_lib_constants.PROTO_NAME_UDP:
75 udp = '-u'
76 cmd = 'echo "knock knock" | nc '
77 ncat_version = get_ncat_version()
78 if ncat_version > distutils.version.StrictVersion('7.60'):
79 cmd += '-z '
80 cmd += '-w 1 %(udp)s %(host)s %(port)s' % {
81 'udp': udp, 'host': ip_address, 'port': port}
82 return cmd
83
84
Itzik Browne67ebb52016-05-15 05:34:41 +000085class BaseTempestTestCase(base_api.BaseNetworkTest):
Itzik Browne67ebb52016-05-15 05:34:41 +000086
Genadi Chereshnya918dd0b2017-05-17 13:02:20 +000087 def create_server(self, flavor_ref, image_ref, key_name, networks,
Roee Agiman6a0a18a2017-11-16 11:51:56 +020088 **kwargs):
Itzik Brownbac51dc2016-10-31 12:25:04 +000089 """Create a server using tempest lib
Brian Haleyaee61ac2018-10-09 20:00:27 -040090
Itzik Brownbac51dc2016-10-31 12:25:04 +000091 All the parameters are the ones used in Compute API
Roee Agiman6a0a18a2017-11-16 11:51:56 +020092 * - Kwargs that require admin privileges
Itzik Brownbac51dc2016-10-31 12:25:04 +000093
94 Args:
95 flavor_ref(str): The flavor of the server to be provisioned.
96 image_ref(str): The image of the server to be provisioned.
97 key_name(str): SSH key to to be used to connect to the
98 provisioned server.
99 networks(list): List of dictionaries where each represent
100 an interface to be attached to the server. For network
101 it should be {'uuid': network_uuid} and for port it should
102 be {'port': port_uuid}
Roee Agiman6a0a18a2017-11-16 11:51:56 +0200103 kwargs:
Itzik Brownbac51dc2016-10-31 12:25:04 +0000104 name(str): Name of the server to be provisioned.
105 security_groups(list): List of dictionaries where
106 the keys is 'name' and the value is the name of
107 the security group. If it's not passed the default
108 security group will be used.
Roee Agiman6a0a18a2017-11-16 11:51:56 +0200109 availability_zone(str)*: The availability zone that
110 the instance will be in.
111 You can request a specific az without actually creating one,
112 Just pass 'X:Y' where X is the default availability
113 zone, and Y is the compute host name.
Itzik Brownbac51dc2016-10-31 12:25:04 +0000114 """
115
Jakub Libosvarffd9b912017-11-16 09:54:14 +0000116 kwargs.setdefault('name', data_utils.rand_name('server-test'))
Itzik Brownbac51dc2016-10-31 12:25:04 +0000117
Jakub Libosvarffd9b912017-11-16 09:54:14 +0000118 # We cannot use setdefault() here because caller could have passed
119 # security_groups=None and we don't want to pass None to
120 # client.create_server()
121 if not kwargs.get('security_groups'):
122 kwargs['security_groups'] = [{'name': 'default'}]
Roee Agiman6a0a18a2017-11-16 11:51:56 +0200123
Jakub Libosvarffd9b912017-11-16 09:54:14 +0000124 client = self.os_primary.servers_client
125 if kwargs.get('availability_zone'):
Roee Agiman6a0a18a2017-11-16 11:51:56 +0200126 client = self.os_admin.servers_client
Roee Agiman6a0a18a2017-11-16 11:51:56 +0200127
Jakub Libosvarffd9b912017-11-16 09:54:14 +0000128 server = client.create_server(
129 flavorRef=flavor_ref,
130 imageRef=image_ref,
131 key_name=key_name,
132 networks=networks,
133 **kwargs)
Genadi Chereshnya918dd0b2017-05-17 13:02:20 +0000134
135 self.addCleanup(test_utils.call_and_ignore_notfound_exc,
Roee Agiman6a0a18a2017-11-16 11:51:56 +0200136 waiters.wait_for_server_termination,
137 client,
138 server['server']['id'])
Genadi Chereshnya918dd0b2017-05-17 13:02:20 +0000139 self.addCleanup(test_utils.call_and_ignore_notfound_exc,
Roee Agiman6a0a18a2017-11-16 11:51:56 +0200140 client.delete_server,
Genadi Chereshnya918dd0b2017-05-17 13:02:20 +0000141 server['server']['id'])
Itzik Browne67ebb52016-05-15 05:34:41 +0000142 return server
143
144 @classmethod
Jens Harbott54357632017-11-21 11:47:06 +0000145 def create_secgroup_rules(cls, rule_list, secgroup_id=None,
146 client=None):
Roee Agiman6a0a18a2017-11-16 11:51:56 +0200147 client = client or cls.os_primary.network_client
Itzik Browne67ebb52016-05-15 05:34:41 +0000148 if not secgroup_id:
149 sgs = client.list_security_groups()['security_groups']
150 for sg in sgs:
151 if sg['name'] == constants.DEFAULT_SECURITY_GROUP:
152 secgroup_id = sg['id']
153 break
154
Itzik Brown1ef813a2016-06-06 12:56:21 +0000155 for rule in rule_list:
156 direction = rule.pop('direction')
157 client.create_security_group_rule(
158 direction=direction,
159 security_group_id=secgroup_id,
160 **rule)
161
162 @classmethod
Roee Agiman6a0a18a2017-11-16 11:51:56 +0200163 def create_loginable_secgroup_rule(cls, secgroup_id=None,
164 client=None):
Itzik Brown1ef813a2016-06-06 12:56:21 +0000165 """This rule is intended to permit inbound ssh
166
167 Allowing ssh traffic traffic from all sources, so no group_id is
168 provided.
169 Setting a group_id would only permit traffic from ports
170 belonging to the same security group.
171 """
Federico Ressi4c590d72018-10-10 14:01:08 +0200172 return cls.create_security_group_rule(
173 security_group_id=secgroup_id,
174 client=client,
175 protocol=neutron_lib_constants.PROTO_NAME_TCP,
176 direction=neutron_lib_constants.INGRESS_DIRECTION,
177 port_range_min=22,
178 port_range_max=22)
Itzik Browne67ebb52016-05-15 05:34:41 +0000179
180 @classmethod
Roee Agiman6a0a18a2017-11-16 11:51:56 +0200181 def create_pingable_secgroup_rule(cls, secgroup_id=None,
182 client=None):
Federico Ressi4c590d72018-10-10 14:01:08 +0200183 """This rule is intended to permit inbound ping
YAMAMOTO Takashi25935722017-01-23 15:34:11 +0900184
Federico Ressi4c590d72018-10-10 14:01:08 +0200185 """
186 return cls.create_security_group_rule(
187 security_group_id=secgroup_id, client=client,
188 protocol=neutron_lib_constants.PROTO_NAME_ICMP,
189 direction=neutron_lib_constants.INGRESS_DIRECTION)
YAMAMOTO Takashi25935722017-01-23 15:34:11 +0900190
191 @classmethod
Genadi Chereshnyac0411e92016-07-11 16:59:42 +0300192 def create_router_by_client(cls, is_admin=False, **kwargs):
193 kwargs.update({'router_name': data_utils.rand_name('router'),
194 'admin_state_up': True,
195 'external_network_id': CONF.network.public_network_id})
196 if not is_admin:
197 router = cls.create_router(**kwargs)
198 else:
199 router = cls.create_admin_router(**kwargs)
Alex Stafeyevc4d9c352016-12-12 04:13:33 -0500200 LOG.debug("Created router %s", router['name'])
Itzik Browne67ebb52016-05-15 05:34:41 +0000201 cls.routers.append(router)
202 return router
203
Federico Ressibf877c82018-08-22 08:36:37 +0200204 @removals.remove(version='Stein',
205 message="Please use create_floatingip method instead of "
206 "create_and_associate_floatingip.")
Roee Agiman6a0a18a2017-11-16 11:51:56 +0200207 def create_and_associate_floatingip(self, port_id, client=None):
208 client = client or self.os_primary.network_client
Federico Ressibf877c82018-08-22 08:36:37 +0200209 return self.create_floatingip(port_id=port_id, client=client)
Itzik Browne67ebb52016-05-15 05:34:41 +0000210
Hongbin Lu965b03d2018-04-25 22:32:30 +0000211 def create_interface(cls, server_id, port_id, client=None):
212 client = client or cls.os_primary.interfaces_client
213 body = client.create_interface(server_id, port_id=port_id)
214 return body['interfaceAttachment']
215
216 def delete_interface(cls, server_id, port_id, client=None):
217 client = client or cls.os_primary.interfaces_client
218 client.delete_interface(server_id, port_id=port_id)
219
Brian Haleyd11f4ec2019-08-13 12:09:57 -0400220 def setup_network_and_server(self, router=None, server_name=None,
221 network=None, **kwargs):
Genadi Chereshnyac0411e92016-07-11 16:59:42 +0300222 """Create network resources and a server.
Itzik Brownbac51dc2016-10-31 12:25:04 +0000223
224 Creating a network, subnet, router, keypair, security group
225 and a server.
226 """
Assaf Mullerd54ae6c2018-05-31 11:38:00 -0400227 self.network = network or self.create_network()
Genadi Chereshnya918dd0b2017-05-17 13:02:20 +0000228 LOG.debug("Created network %s", self.network['name'])
229 self.subnet = self.create_subnet(self.network)
230 LOG.debug("Created subnet %s", self.subnet['id'])
Itzik Brown1ef813a2016-06-06 12:56:21 +0000231
Brian Haleyf86ac2e2017-06-21 10:43:50 -0400232 secgroup = self.os_primary.network_client.create_security_group(
Chandan Kumarc125fd12017-11-15 19:41:01 +0530233 name=data_utils.rand_name('secgroup'))
Alex Stafeyevc4d9c352016-12-12 04:13:33 -0500234 LOG.debug("Created security group %s",
235 secgroup['security_group']['name'])
Genadi Chereshnya918dd0b2017-05-17 13:02:20 +0000236 self.security_groups.append(secgroup['security_group'])
Genadi Chereshnyac0411e92016-07-11 16:59:42 +0300237 if not router:
Genadi Chereshnya918dd0b2017-05-17 13:02:20 +0000238 router = self.create_router_by_client(**kwargs)
239 self.create_router_interface(router['id'], self.subnet['id'])
240 self.keypair = self.create_keypair()
241 self.create_loginable_secgroup_rule(
Itzik Brownbac51dc2016-10-31 12:25:04 +0000242 secgroup_id=secgroup['security_group']['id'])
Assaf Muller92fdc782018-05-31 10:32:47 -0400243
244 server_kwargs = {
245 'flavor_ref': CONF.compute.flavor_ref,
246 'image_ref': CONF.compute.image_ref,
247 'key_name': self.keypair['name'],
248 'networks': [{'uuid': self.network['id']}],
249 'security_groups': [{'name': secgroup['security_group']['name']}],
250 }
251 if server_name is not None:
252 server_kwargs['name'] = server_name
253
254 self.server = self.create_server(**server_kwargs)
Federico Ressie7417b72018-05-30 05:50:58 +0200255 self.wait_for_server_active(self.server['server'])
Jakub Libosvar1345d9d2017-06-09 13:59:05 +0000256 self.port = self.client.list_ports(network_id=self.network['id'],
257 device_id=self.server[
258 'server']['id'])['ports'][0]
Federico Ressibf877c82018-08-22 08:36:37 +0200259 self.fip = self.create_floatingip(port=self.port)
Jakub Libosvarc0c2f1d2017-01-31 12:12:21 -0500260
261 def check_connectivity(self, host, ssh_user, ssh_key, servers=None):
262 ssh_client = ssh.Client(host, ssh_user, pkey=ssh_key)
263 try:
264 ssh_client.test_connection_auth()
265 except lib_exc.SSHTimeout as ssh_e:
266 LOG.debug(ssh_e)
267 self._log_console_output(servers)
Rodolfo Alonso Hernandez4849f002020-01-16 16:01:10 +0000268 self._log_local_network_status()
Jakub Libosvarc0c2f1d2017-01-31 12:12:21 -0500269 raise
270
271 def _log_console_output(self, servers=None):
272 if not CONF.compute_feature_enabled.console_output:
273 LOG.debug('Console output not supported, cannot log')
274 return
275 if not servers:
Brian Haleyf86ac2e2017-06-21 10:43:50 -0400276 servers = self.os_primary.servers_client.list_servers()
Jakub Libosvarc0c2f1d2017-01-31 12:12:21 -0500277 servers = servers['servers']
278 for server in servers:
Slawek Kaplonskicff79232020-03-03 14:12:18 +0100279 # NOTE(slaweq): sometimes servers are passed in dictionary with
280 # "server" key as first level key and in other cases it may be that
281 # it is just the "inner" dict without "server" key. Lets try to
282 # handle both cases
283 server = server.get("server") or server
Jakub Libosvarc0c2f1d2017-01-31 12:12:21 -0500284 try:
285 console_output = (
Brian Haleyf86ac2e2017-06-21 10:43:50 -0400286 self.os_primary.servers_client.get_console_output(
Jakub Libosvarc0c2f1d2017-01-31 12:12:21 -0500287 server['id'])['output'])
288 LOG.debug('Console output for %s\nbody=\n%s',
289 server['id'], console_output)
290 except lib_exc.NotFound:
291 LOG.debug("Server %s disappeared(deleted) while looking "
292 "for the console log", server['id'])
YAMAMOTO Takashi25935722017-01-23 15:34:11 +0900293
Rodolfo Alonso Hernandez4849f002020-01-16 16:01:10 +0000294 def _log_local_network_status(self):
295 local_routes = ip_utils.IPCommand().list_routes()
296 LOG.debug('Local routes:\n%s', '\n'.join(str(r) for r in local_routes))
297 arp_table = ip_utils.arp_table()
298 LOG.debug('Local ARP table:\n%s', '\n'.join(str(r) for r in arp_table))
299
LIU Yulong68ab2452019-05-18 10:19:49 +0800300 def _check_remote_connectivity(self, source, dest, count,
301 should_succeed=True,
Assaf Muller92fdc782018-05-31 10:32:47 -0400302 nic=None, mtu=None, fragmentation=True,
Eduardo Olivaresf2b60542020-01-30 09:37:22 +0100303 timeout=None, pattern=None):
YAMAMOTO Takashi25935722017-01-23 15:34:11 +0900304 """check ping server via source ssh connection
305
306 :param source: RemoteClient: an ssh connection from which to ping
307 :param dest: and IP to ping against
LIU Yulong68ab2452019-05-18 10:19:49 +0800308 :param count: Number of ping packet(s) to send
YAMAMOTO Takashi25935722017-01-23 15:34:11 +0900309 :param should_succeed: boolean should ping succeed or not
310 :param nic: specific network interface to ping from
Genadi Chereshnya6d10c6e2017-07-05 11:34:20 +0300311 :param mtu: mtu size for the packet to be sent
312 :param fragmentation: Flag for packet fragmentation
LIU Yulong68ab2452019-05-18 10:19:49 +0800313 :param timeout: Timeout for all ping packet(s) to succeed
Eduardo Olivaresf2b60542020-01-30 09:37:22 +0100314 :param pattern: hex digits included in ICMP messages
YAMAMOTO Takashi25935722017-01-23 15:34:11 +0900315 :returns: boolean -- should_succeed == ping
316 :returns: ping is false if ping failed
317 """
LIU Yulong68ab2452019-05-18 10:19:49 +0800318 def ping_host(source, host, count,
Genadi Chereshnya6d10c6e2017-07-05 11:34:20 +0300319 size=CONF.validation.ping_size, nic=None, mtu=None,
Eduardo Olivaresf2b60542020-01-30 09:37:22 +0100320 fragmentation=True, pattern=None):
Assaf Muller92fdc782018-05-31 10:32:47 -0400321 IP_VERSION_4 = neutron_lib_constants.IP_VERSION_4
322 IP_VERSION_6 = neutron_lib_constants.IP_VERSION_6
323
324 # Use 'ping6' for IPv6 addresses, 'ping' for IPv4 and hostnames
325 ip_version = (
326 IP_VERSION_6 if netaddr.valid_ipv6(host) else IP_VERSION_4)
327 cmd = (
328 'ping6' if ip_version == IP_VERSION_6 else 'ping')
YAMAMOTO Takashi25935722017-01-23 15:34:11 +0900329 if nic:
330 cmd = 'sudo {cmd} -I {nic}'.format(cmd=cmd, nic=nic)
Genadi Chereshnya6d10c6e2017-07-05 11:34:20 +0300331 if mtu:
332 if not fragmentation:
333 cmd += ' -M do'
334 size = str(net_utils.get_ping_payload_size(
Assaf Muller92fdc782018-05-31 10:32:47 -0400335 mtu=mtu, ip_version=ip_version))
Eduardo Olivaresf2b60542020-01-30 09:37:22 +0100336 if pattern:
337 cmd += ' -p {pattern}'.format(pattern=pattern)
YAMAMOTO Takashi25935722017-01-23 15:34:11 +0900338 cmd += ' -c{0} -w{0} -s{1} {2}'.format(count, size, host)
339 return source.exec_command(cmd)
340
341 def ping_remote():
342 try:
LIU Yulong68ab2452019-05-18 10:19:49 +0800343 result = ping_host(source, dest, count, nic=nic, mtu=mtu,
Eduardo Olivaresf2b60542020-01-30 09:37:22 +0100344 fragmentation=fragmentation,
345 pattern=pattern)
YAMAMOTO Takashi25935722017-01-23 15:34:11 +0900346
347 except lib_exc.SSHExecCommandFailed:
348 LOG.warning('Failed to ping IP: %s via a ssh connection '
349 'from: %s.', dest, source.host)
350 return not should_succeed
351 LOG.debug('ping result: %s', result)
Assaf Muller92fdc782018-05-31 10:32:47 -0400352
353 if validators.validate_ip_address(dest) is None:
354 # Assert that the return traffic was from the correct
355 # source address.
356 from_source = 'from %s' % dest
357 self.assertIn(from_source, result)
YAMAMOTO Takashi25935722017-01-23 15:34:11 +0900358 return should_succeed
359
Assaf Muller92fdc782018-05-31 10:32:47 -0400360 return test_utils.call_until_true(
361 ping_remote, timeout or CONF.validation.ping_timeout, 1)
YAMAMOTO Takashi25935722017-01-23 15:34:11 +0900362
363 def check_remote_connectivity(self, source, dest, should_succeed=True,
Slawek Kaplonskib07251f2018-05-16 12:21:50 +0200364 nic=None, mtu=None, fragmentation=True,
LIU Yulong68ab2452019-05-18 10:19:49 +0800365 servers=None, timeout=None,
Eduardo Olivaresf2b60542020-01-30 09:37:22 +0100366 ping_count=CONF.validation.ping_count,
367 pattern=None):
Slawek Kaplonskib07251f2018-05-16 12:21:50 +0200368 try:
369 self.assertTrue(self._check_remote_connectivity(
LIU Yulong68ab2452019-05-18 10:19:49 +0800370 source, dest, ping_count, should_succeed, nic, mtu,
371 fragmentation,
Eduardo Olivaresf2b60542020-01-30 09:37:22 +0100372 timeout=timeout, pattern=pattern))
Slawek Kaplonskib07251f2018-05-16 12:21:50 +0200373 except lib_exc.SSHTimeout as ssh_e:
374 LOG.debug(ssh_e)
375 self._log_console_output(servers)
376 raise
377 except AssertionError:
378 self._log_console_output(servers)
379 raise
Chandan Kumarc125fd12017-11-15 19:41:01 +0530380
381 def ping_ip_address(self, ip_address, should_succeed=True,
382 ping_timeout=None, mtu=None):
383 # the code is taken from tempest/scenario/manager.py in tempest git
384 timeout = ping_timeout or CONF.validation.ping_timeout
385 cmd = ['ping', '-c1', '-w1']
386
387 if mtu:
388 cmd += [
389 # don't fragment
390 '-M', 'do',
391 # ping receives just the size of ICMP payload
392 '-s', str(net_utils.get_ping_payload_size(mtu, 4))
393 ]
394 cmd.append(ip_address)
395
396 def ping():
397 proc = subprocess.Popen(cmd,
398 stdout=subprocess.PIPE,
399 stderr=subprocess.PIPE)
400 proc.communicate()
401
402 return (proc.returncode == 0) == should_succeed
403
404 caller = test_utils.find_test_caller()
405 LOG.debug('%(caller)s begins to ping %(ip)s in %(timeout)s sec and the'
406 ' expected result is %(should_succeed)s', {
407 'caller': caller, 'ip': ip_address, 'timeout': timeout,
408 'should_succeed':
409 'reachable' if should_succeed else 'unreachable'
410 })
411 result = test_utils.call_until_true(ping, timeout, 1)
Manjeet Singh Bhatia8bbf8992019-03-04 11:59:57 -0800412
413 # To make sure ping_ip_address called by test works
414 # as expected.
415 self.assertTrue(result)
416
Chandan Kumarc125fd12017-11-15 19:41:01 +0530417 LOG.debug('%(caller)s finishes ping %(ip)s in %(timeout)s sec and the '
418 'ping result is %(result)s', {
419 'caller': caller, 'ip': ip_address, 'timeout': timeout,
420 'result': 'expected' if result else 'unexpected'
421 })
422 return result
Federico Ressie7417b72018-05-30 05:50:58 +0200423
424 def wait_for_server_status(self, server, status, client=None, **kwargs):
425 """Waits for a server to reach a given status.
426
427 :param server: mapping having schema {'id': <server_id>}
428 :param status: string status to wait for (es: 'ACTIVE')
429 :param clien: servers client (self.os_primary.servers_client as
430 default value)
431 """
432
433 client = client or self.os_primary.servers_client
434 waiters.wait_for_server_status(client, server['id'], status, **kwargs)
435
436 def wait_for_server_active(self, server, client=None):
437 """Waits for a server to reach active status.
438
439 :param server: mapping having schema {'id': <server_id>}
440 :param clien: servers client (self.os_primary.servers_client as
441 default value)
442 """
443 self.wait_for_server_status(
444 server, constants.SERVER_STATUS_ACTIVE, client)
Jakub Libosvar031fd5a2019-07-15 16:10:07 +0000445
446 def check_servers_hostnames(self, servers, log_errors=True):
447 """Compare hostnames of given servers with their names."""
448 try:
449 for server in servers:
450 kwargs = {}
451 try:
Slawek Kaplonskic4e963e2019-09-11 22:55:34 +0200452 kwargs['port'] = (
453 server['port_forwarding_tcp']['external_port'])
Jakub Libosvar031fd5a2019-07-15 16:10:07 +0000454 except KeyError:
455 pass
456 ssh_client = ssh.Client(
457 self.fip['floating_ip_address'],
458 CONF.validation.image_ssh_user,
459 pkey=self.keypair['private_key'],
460 **kwargs)
461 self.assertIn(server['name'],
462 ssh_client.exec_command('hostname'))
463 except lib_exc.SSHTimeout as ssh_e:
464 LOG.debug(ssh_e)
465 if log_errors:
466 self._log_console_output(servers)
467 raise
468 except AssertionError as assert_e:
469 LOG.debug(assert_e)
470 if log_errors:
471 self._log_console_output(servers)
472 raise
Slawek Kaplonskic4e963e2019-09-11 22:55:34 +0200473
Slawek Kaplonskifd4141f2020-03-14 14:34:00 +0100474 def ensure_nc_listen(self, ssh_client, port, protocol, echo_msg=None,
475 servers=None):
476 """Ensure that nc server listening on the given TCP/UDP port is up.
477
478 Listener is created always on remote host.
479 """
480 def spawn_and_check_process():
481 self.nc_listen(ssh_client, port, protocol, echo_msg, servers)
482 return utils.process_is_running(ssh_client, "nc")
483
484 utils.wait_until_true(spawn_and_check_process)
485
486 def nc_listen(self, ssh_client, port, protocol, echo_msg=None,
487 servers=None):
Slawek Kaplonskic4e963e2019-09-11 22:55:34 +0200488 """Create nc server listening on the given TCP/UDP port.
489
490 Listener is created always on remote host.
491 """
Slawek Kaplonskic4e963e2019-09-11 22:55:34 +0200492 try:
Slawek Kaplonskiaf83e832020-02-05 12:11:54 +0100493 return ssh_client.execute_script(
494 get_ncat_server_cmd(port, protocol, echo_msg),
Flavio Fernandesbbbf5eb2020-07-01 14:57:13 -0400495 become_root=True, combine_stderr=True)
Slawek Kaplonskic4e963e2019-09-11 22:55:34 +0200496 except lib_exc.SSHTimeout as ssh_e:
497 LOG.debug(ssh_e)
Slawek Kaplonskifd4141f2020-03-14 14:34:00 +0100498 self._log_console_output(servers)
Slawek Kaplonskic4e963e2019-09-11 22:55:34 +0200499 raise
500
501 def nc_client(self, ip_address, port, protocol):
502 """Check connectivity to TCP/UDP port at host via nc.
503
504 Client is always executed locally on host where tests are executed.
505 """
Slawek Kaplonskiaf83e832020-02-05 12:11:54 +0100506 cmd = get_ncat_client_cmd(ip_address, port, protocol)
Slawek Kaplonskic4e963e2019-09-11 22:55:34 +0200507 result = shell.execute_local_command(cmd)
508 self.assertEqual(0, result.exit_status)
509 return result.stdout