blob: 784d03169231f671c3998f07620ef44324a073d6 [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
Slawek Kaplonski8cccfe02020-09-29 22:34:09 +020024from paramiko import ssh_exception as ssh_exc
Genadi Chereshnya6d10c6e2017-07-05 11:34:20 +030025from tempest.common.utils import net_utils
Itzik Browne67ebb52016-05-15 05:34:41 +000026from tempest.common import waiters
Itzik Browne67ebb52016-05-15 05:34:41 +000027from tempest.lib.common.utils import data_utils
YAMAMOTO Takashi25935722017-01-23 15:34:11 +090028from tempest.lib.common.utils import test_utils
Jakub Libosvarc0c2f1d2017-01-31 12:12:21 -050029from tempest.lib import exceptions as lib_exc
Itzik Browne67ebb52016-05-15 05:34:41 +000030
Chandan Kumar667d3d32017-09-22 12:24:06 +053031from neutron_tempest_plugin.api import base as base_api
Rodolfo Alonso Hernandez4849f002020-01-16 16:01:10 +000032from neutron_tempest_plugin.common import ip as ip_utils
Slawek Kaplonskic4e963e2019-09-11 22:55:34 +020033from neutron_tempest_plugin.common import shell
Chandan Kumar667d3d32017-09-22 12:24:06 +053034from neutron_tempest_plugin.common import ssh
Slawek Kaplonskifd4141f2020-03-14 14:34:00 +010035from neutron_tempest_plugin.common import utils
Chandan Kumar667d3d32017-09-22 12:24:06 +053036from neutron_tempest_plugin import config
Slawek Kaplonskiaf83e832020-02-05 12:11:54 +010037from neutron_tempest_plugin import exceptions
Chandan Kumar667d3d32017-09-22 12:24:06 +053038from neutron_tempest_plugin.scenario import constants
Itzik Browne67ebb52016-05-15 05:34:41 +000039
40CONF = config.CONF
Itzik Browne67ebb52016-05-15 05:34:41 +000041
Alex Stafeyevc4d9c352016-12-12 04:13:33 -050042LOG = log.getLogger(__name__)
43
Itzik Browne67ebb52016-05-15 05:34:41 +000044
Slawek Kaplonskiaf83e832020-02-05 12:11:54 +010045def get_ncat_version(ssh_client=None):
46 cmd = "ncat --version 2>&1"
47 try:
48 version_result = shell.execute(cmd, ssh_client=ssh_client).stdout
49 except exceptions.ShellCommandFailed:
50 m = None
51 else:
52 m = re.match(r"Ncat: Version ([\d.]+) *.", version_result)
53 # NOTE(slaweq): by default lets assume we have ncat 7.60 which is in Ubuntu
54 # 18.04 which is used on u/s gates
55 return distutils.version.StrictVersion(m.group(1) if m else '7.60')
56
57
Slawek Kaplonskifd4141f2020-03-14 14:34:00 +010058def get_ncat_server_cmd(port, protocol, msg=None):
Slawek Kaplonskiaf83e832020-02-05 12:11:54 +010059 udp = ''
60 if protocol.lower() == neutron_lib_constants.PROTO_NAME_UDP:
61 udp = '-u'
62 cmd = "nc %(udp)s -p %(port)s -lk " % {
63 'udp': udp, 'port': port}
Slawek Kaplonskifd4141f2020-03-14 14:34:00 +010064 if msg:
65 if CONF.neutron_plugin_options.default_image_is_advanced:
Flavio Fernandesb056ac22020-07-01 14:57:13 -040066 cmd += "-c 'echo %s' " % msg
Slawek Kaplonskifd4141f2020-03-14 14:34:00 +010067 else:
Flavio Fernandesb056ac22020-07-01 14:57:13 -040068 cmd += "-e echo %s " % msg
69 cmd += "< /dev/zero &{0}sleep 0.1{0}".format('\n')
Slawek Kaplonskiaf83e832020-02-05 12:11:54 +010070 return cmd
71
72
73def get_ncat_client_cmd(ip_address, port, protocol):
74 udp = ''
75 if protocol.lower() == neutron_lib_constants.PROTO_NAME_UDP:
76 udp = '-u'
77 cmd = 'echo "knock knock" | nc '
78 ncat_version = get_ncat_version()
79 if ncat_version > distutils.version.StrictVersion('7.60'):
80 cmd += '-z '
81 cmd += '-w 1 %(udp)s %(host)s %(port)s' % {
82 'udp': udp, 'host': ip_address, 'port': port}
83 return cmd
84
85
Itzik Browne67ebb52016-05-15 05:34:41 +000086class BaseTempestTestCase(base_api.BaseNetworkTest):
Itzik Browne67ebb52016-05-15 05:34:41 +000087
Genadi Chereshnya918dd0b2017-05-17 13:02:20 +000088 def create_server(self, flavor_ref, image_ref, key_name, networks,
Roee Agiman6a0a18a2017-11-16 11:51:56 +020089 **kwargs):
Itzik Brownbac51dc2016-10-31 12:25:04 +000090 """Create a server using tempest lib
Brian Haleyaee61ac2018-10-09 20:00:27 -040091
Itzik Brownbac51dc2016-10-31 12:25:04 +000092 All the parameters are the ones used in Compute API
Roee Agiman6a0a18a2017-11-16 11:51:56 +020093 * - Kwargs that require admin privileges
Itzik Brownbac51dc2016-10-31 12:25:04 +000094
95 Args:
96 flavor_ref(str): The flavor of the server to be provisioned.
97 image_ref(str): The image of the server to be provisioned.
98 key_name(str): SSH key to to be used to connect to the
99 provisioned server.
100 networks(list): List of dictionaries where each represent
101 an interface to be attached to the server. For network
102 it should be {'uuid': network_uuid} and for port it should
103 be {'port': port_uuid}
Roee Agiman6a0a18a2017-11-16 11:51:56 +0200104 kwargs:
Itzik Brownbac51dc2016-10-31 12:25:04 +0000105 name(str): Name of the server to be provisioned.
106 security_groups(list): List of dictionaries where
107 the keys is 'name' and the value is the name of
108 the security group. If it's not passed the default
109 security group will be used.
Roee Agiman6a0a18a2017-11-16 11:51:56 +0200110 availability_zone(str)*: The availability zone that
111 the instance will be in.
112 You can request a specific az without actually creating one,
113 Just pass 'X:Y' where X is the default availability
114 zone, and Y is the compute host name.
Itzik Brownbac51dc2016-10-31 12:25:04 +0000115 """
116
Jakub Libosvarffd9b912017-11-16 09:54:14 +0000117 kwargs.setdefault('name', data_utils.rand_name('server-test'))
Itzik Brownbac51dc2016-10-31 12:25:04 +0000118
Jakub Libosvarffd9b912017-11-16 09:54:14 +0000119 # We cannot use setdefault() here because caller could have passed
120 # security_groups=None and we don't want to pass None to
121 # client.create_server()
122 if not kwargs.get('security_groups'):
123 kwargs['security_groups'] = [{'name': 'default'}]
Roee Agiman6a0a18a2017-11-16 11:51:56 +0200124
Slawek Kaplonski2211eab2020-10-20 16:43:53 +0200125 client = kwargs.pop('client', None)
126 if client is None:
127 client = self.os_primary.servers_client
128 if kwargs.get('availability_zone'):
129 client = self.os_admin.servers_client
Roee Agiman6a0a18a2017-11-16 11:51:56 +0200130
Jakub Libosvarffd9b912017-11-16 09:54:14 +0000131 server = client.create_server(
132 flavorRef=flavor_ref,
133 imageRef=image_ref,
134 key_name=key_name,
135 networks=networks,
136 **kwargs)
Genadi Chereshnya918dd0b2017-05-17 13:02:20 +0000137
138 self.addCleanup(test_utils.call_and_ignore_notfound_exc,
Roee Agiman6a0a18a2017-11-16 11:51:56 +0200139 waiters.wait_for_server_termination,
140 client,
141 server['server']['id'])
Genadi Chereshnya918dd0b2017-05-17 13:02:20 +0000142 self.addCleanup(test_utils.call_and_ignore_notfound_exc,
Roee Agiman6a0a18a2017-11-16 11:51:56 +0200143 client.delete_server,
Genadi Chereshnya918dd0b2017-05-17 13:02:20 +0000144 server['server']['id'])
Slawek Kaplonski2211eab2020-10-20 16:43:53 +0200145
146 self.wait_for_server_active(server['server'], client=client)
147 self.wait_for_guest_os_ready(server['server'], client=client)
148
Itzik Browne67ebb52016-05-15 05:34:41 +0000149 return server
150
151 @classmethod
Jens Harbott54357632017-11-21 11:47:06 +0000152 def create_secgroup_rules(cls, rule_list, secgroup_id=None,
153 client=None):
Roee Agiman6a0a18a2017-11-16 11:51:56 +0200154 client = client or cls.os_primary.network_client
Itzik Browne67ebb52016-05-15 05:34:41 +0000155 if not secgroup_id:
156 sgs = client.list_security_groups()['security_groups']
157 for sg in sgs:
158 if sg['name'] == constants.DEFAULT_SECURITY_GROUP:
159 secgroup_id = sg['id']
160 break
Hang Yange6e0ccf2021-02-26 15:07:05 -0600161 resp = []
Itzik Brown1ef813a2016-06-06 12:56:21 +0000162 for rule in rule_list:
163 direction = rule.pop('direction')
Hang Yange6e0ccf2021-02-26 15:07:05 -0600164 resp.append(client.create_security_group_rule(
165 direction=direction,
166 security_group_id=secgroup_id,
167 **rule)['security_group_rule'])
168 return resp
Itzik Brown1ef813a2016-06-06 12:56:21 +0000169
170 @classmethod
Roee Agiman6a0a18a2017-11-16 11:51:56 +0200171 def create_loginable_secgroup_rule(cls, secgroup_id=None,
172 client=None):
Itzik Brown1ef813a2016-06-06 12:56:21 +0000173 """This rule is intended to permit inbound ssh
174
175 Allowing ssh traffic traffic from all sources, so no group_id is
176 provided.
177 Setting a group_id would only permit traffic from ports
178 belonging to the same security group.
179 """
Federico Ressi4c590d72018-10-10 14:01:08 +0200180 return cls.create_security_group_rule(
181 security_group_id=secgroup_id,
182 client=client,
183 protocol=neutron_lib_constants.PROTO_NAME_TCP,
184 direction=neutron_lib_constants.INGRESS_DIRECTION,
185 port_range_min=22,
186 port_range_max=22)
Itzik Browne67ebb52016-05-15 05:34:41 +0000187
188 @classmethod
Roee Agiman6a0a18a2017-11-16 11:51:56 +0200189 def create_pingable_secgroup_rule(cls, secgroup_id=None,
190 client=None):
Federico Ressi4c590d72018-10-10 14:01:08 +0200191 """This rule is intended to permit inbound ping
YAMAMOTO Takashi25935722017-01-23 15:34:11 +0900192
Federico Ressi4c590d72018-10-10 14:01:08 +0200193 """
194 return cls.create_security_group_rule(
195 security_group_id=secgroup_id, client=client,
196 protocol=neutron_lib_constants.PROTO_NAME_ICMP,
197 direction=neutron_lib_constants.INGRESS_DIRECTION)
YAMAMOTO Takashi25935722017-01-23 15:34:11 +0900198
199 @classmethod
Genadi Chereshnyac0411e92016-07-11 16:59:42 +0300200 def create_router_by_client(cls, is_admin=False, **kwargs):
201 kwargs.update({'router_name': data_utils.rand_name('router'),
202 'admin_state_up': True,
203 'external_network_id': CONF.network.public_network_id})
204 if not is_admin:
205 router = cls.create_router(**kwargs)
206 else:
207 router = cls.create_admin_router(**kwargs)
Alex Stafeyevc4d9c352016-12-12 04:13:33 -0500208 LOG.debug("Created router %s", router['name'])
Slawek Kaplonskiedf3cba2021-04-21 10:34:02 +0200209 cls._wait_for_router_ha_active(router['id'])
Itzik Browne67ebb52016-05-15 05:34:41 +0000210 return router
211
ccamposre6b10042021-02-12 12:26:08 +0100212 @classmethod
Slawek Kaplonskiedf3cba2021-04-21 10:34:02 +0200213 def _wait_for_router_ha_active(cls, router_id):
214 router = cls.os_admin.network_client.show_router(router_id)['router']
215 if not router.get('ha'):
216 return
217
218 def _router_active_on_l3_agent():
219 agents = cls.os_admin.network_client.list_l3_agents_hosting_router(
220 router_id)['agents']
221 return "active" in [agent['ha_state'] for agent in agents]
222
223 error_msg = (
224 "Router %s is not active on any of the L3 agents" % router_id)
Slawek Kaplonski03c795e2021-04-28 08:45:03 +0200225 # NOTE(slaweq): Due to bug
226 # the bug https://launchpad.net/bugs/1923633 let's temporary skip test
227 # if router will not become active on any of the L3 agents in 600
228 # seconds. When that bug will be fixed, we should get rid of that skip
229 # and lower timeout to e.g. 300 seconds, or even less
230 try:
231 utils.wait_until_true(
232 _router_active_on_l3_agent,
233 timeout=600, sleep=5,
234 exception=lib_exc.TimeoutException(error_msg))
235 except lib_exc.TimeoutException:
236 raise cls.skipException("Bug 1923633. %s" % error_msg)
Slawek Kaplonskiedf3cba2021-04-21 10:34:02 +0200237
238 @classmethod
ccamposre6b10042021-02-12 12:26:08 +0100239 def skip_if_no_extension_enabled_in_l3_agents(cls, extension):
240 l3_agents = cls.os_admin.network_client.list_agents(
241 binary='neutron-l3-agent')['agents']
242 if not l3_agents:
243 # the tests should not be skipped when neutron-l3-agent does not
244 # exist (this validation doesn't apply to the setups like
245 # e.g. ML2/OVN)
246 return
247 for agent in l3_agents:
248 if extension in agent['configurations'].get('extensions', []):
249 return
250 raise cls.skipTest("No L3 agent with '%s' extension enabled found." %
251 extension)
252
Federico Ressibf877c82018-08-22 08:36:37 +0200253 @removals.remove(version='Stein',
254 message="Please use create_floatingip method instead of "
255 "create_and_associate_floatingip.")
Roee Agiman6a0a18a2017-11-16 11:51:56 +0200256 def create_and_associate_floatingip(self, port_id, client=None):
257 client = client or self.os_primary.network_client
Federico Ressibf877c82018-08-22 08:36:37 +0200258 return self.create_floatingip(port_id=port_id, client=client)
Itzik Browne67ebb52016-05-15 05:34:41 +0000259
Hongbin Lu965b03d2018-04-25 22:32:30 +0000260 def create_interface(cls, server_id, port_id, client=None):
261 client = client or cls.os_primary.interfaces_client
262 body = client.create_interface(server_id, port_id=port_id)
263 return body['interfaceAttachment']
264
265 def delete_interface(cls, server_id, port_id, client=None):
266 client = client or cls.os_primary.interfaces_client
267 client.delete_interface(server_id, port_id=port_id)
268
Brian Haleyd11f4ec2019-08-13 12:09:57 -0400269 def setup_network_and_server(self, router=None, server_name=None,
270 network=None, **kwargs):
Genadi Chereshnyac0411e92016-07-11 16:59:42 +0300271 """Create network resources and a server.
Itzik Brownbac51dc2016-10-31 12:25:04 +0000272
273 Creating a network, subnet, router, keypair, security group
274 and a server.
275 """
Assaf Mullerd54ae6c2018-05-31 11:38:00 -0400276 self.network = network or self.create_network()
Genadi Chereshnya918dd0b2017-05-17 13:02:20 +0000277 LOG.debug("Created network %s", self.network['name'])
278 self.subnet = self.create_subnet(self.network)
279 LOG.debug("Created subnet %s", self.subnet['id'])
Itzik Brown1ef813a2016-06-06 12:56:21 +0000280
Brian Haleyf86ac2e2017-06-21 10:43:50 -0400281 secgroup = self.os_primary.network_client.create_security_group(
Chandan Kumarc125fd12017-11-15 19:41:01 +0530282 name=data_utils.rand_name('secgroup'))
Alex Stafeyevc4d9c352016-12-12 04:13:33 -0500283 LOG.debug("Created security group %s",
284 secgroup['security_group']['name'])
Genadi Chereshnya918dd0b2017-05-17 13:02:20 +0000285 self.security_groups.append(secgroup['security_group'])
Genadi Chereshnyac0411e92016-07-11 16:59:42 +0300286 if not router:
Genadi Chereshnya918dd0b2017-05-17 13:02:20 +0000287 router = self.create_router_by_client(**kwargs)
288 self.create_router_interface(router['id'], self.subnet['id'])
289 self.keypair = self.create_keypair()
290 self.create_loginable_secgroup_rule(
Itzik Brownbac51dc2016-10-31 12:25:04 +0000291 secgroup_id=secgroup['security_group']['id'])
Assaf Muller92fdc782018-05-31 10:32:47 -0400292
293 server_kwargs = {
294 'flavor_ref': CONF.compute.flavor_ref,
295 'image_ref': CONF.compute.image_ref,
296 'key_name': self.keypair['name'],
297 'networks': [{'uuid': self.network['id']}],
298 'security_groups': [{'name': secgroup['security_group']['name']}],
299 }
300 if server_name is not None:
301 server_kwargs['name'] = server_name
302
303 self.server = self.create_server(**server_kwargs)
Jakub Libosvar1345d9d2017-06-09 13:59:05 +0000304 self.port = self.client.list_ports(network_id=self.network['id'],
305 device_id=self.server[
306 'server']['id'])['ports'][0]
Federico Ressibf877c82018-08-22 08:36:37 +0200307 self.fip = self.create_floatingip(port=self.port)
Jakub Libosvarc0c2f1d2017-01-31 12:12:21 -0500308
Bence Romsics2abbc922020-09-30 16:10:07 +0200309 def check_connectivity(self, host, ssh_user=None, ssh_key=None,
310 servers=None, ssh_timeout=None, ssh_client=None):
311 # Either ssh_client or ssh_user+ssh_key is mandatory.
312 if ssh_client is None:
313 ssh_client = ssh.Client(host, ssh_user,
314 pkey=ssh_key, timeout=ssh_timeout)
Jakub Libosvarc0c2f1d2017-01-31 12:12:21 -0500315 try:
316 ssh_client.test_connection_auth()
Slawek Kaplonski8cccfe02020-09-29 22:34:09 +0200317 except (lib_exc.SSHTimeout, ssh_exc.AuthenticationException) as ssh_e:
Jakub Libosvarc0c2f1d2017-01-31 12:12:21 -0500318 LOG.debug(ssh_e)
319 self._log_console_output(servers)
Rodolfo Alonso Hernandez4849f002020-01-16 16:01:10 +0000320 self._log_local_network_status()
Jakub Libosvarc0c2f1d2017-01-31 12:12:21 -0500321 raise
322
323 def _log_console_output(self, servers=None):
324 if not CONF.compute_feature_enabled.console_output:
325 LOG.debug('Console output not supported, cannot log')
326 return
327 if not servers:
Brian Haleyf86ac2e2017-06-21 10:43:50 -0400328 servers = self.os_primary.servers_client.list_servers()
Jakub Libosvarc0c2f1d2017-01-31 12:12:21 -0500329 servers = servers['servers']
330 for server in servers:
Slawek Kaplonskicff79232020-03-03 14:12:18 +0100331 # NOTE(slaweq): sometimes servers are passed in dictionary with
332 # "server" key as first level key and in other cases it may be that
333 # it is just the "inner" dict without "server" key. Lets try to
334 # handle both cases
335 server = server.get("server") or server
Jakub Libosvarc0c2f1d2017-01-31 12:12:21 -0500336 try:
337 console_output = (
Brian Haleyf86ac2e2017-06-21 10:43:50 -0400338 self.os_primary.servers_client.get_console_output(
Jakub Libosvarc0c2f1d2017-01-31 12:12:21 -0500339 server['id'])['output'])
340 LOG.debug('Console output for %s\nbody=\n%s',
341 server['id'], console_output)
342 except lib_exc.NotFound:
343 LOG.debug("Server %s disappeared(deleted) while looking "
344 "for the console log", server['id'])
YAMAMOTO Takashi25935722017-01-23 15:34:11 +0900345
Rodolfo Alonso Hernandez4849f002020-01-16 16:01:10 +0000346 def _log_local_network_status(self):
Slawek Kaplonski8033af72020-05-05 12:01:37 +0200347 self._log_ns_network_status()
348 for ns_name in ip_utils.IPCommand().list_namespaces():
349 self._log_ns_network_status(ns_name=ns_name)
350
351 def _log_ns_network_status(self, ns_name=None):
Rodolfo Alonso Hernandez9817d4f2020-11-17 08:50:50 +0000352 try:
353 local_ips = ip_utils.IPCommand(namespace=ns_name).list_addresses()
354 local_routes = ip_utils.IPCommand(namespace=ns_name).list_routes()
355 arp_table = ip_utils.arp_table()
356 except exceptions.ShellCommandFailed:
357 LOG.debug('Namespace %s has been deleted synchronously during the '
358 'host network collection process', ns_name)
359 return
360
Slawek Kaplonski8033af72020-05-05 12:01:37 +0200361 LOG.debug('Namespace %s; IP Addresses:\n%s',
362 ns_name, '\n'.join(str(r) for r in local_ips))
Slawek Kaplonski8033af72020-05-05 12:01:37 +0200363 LOG.debug('Namespace %s; Local routes:\n%s',
364 ns_name, '\n'.join(str(r) for r in local_routes))
Slawek Kaplonski8033af72020-05-05 12:01:37 +0200365 LOG.debug('Namespace %s; Local ARP table:\n%s',
366 ns_name, '\n'.join(str(r) for r in arp_table))
Rodolfo Alonso Hernandez4849f002020-01-16 16:01:10 +0000367
LIU Yulong68ab2452019-05-18 10:19:49 +0800368 def _check_remote_connectivity(self, source, dest, count,
369 should_succeed=True,
Assaf Muller92fdc782018-05-31 10:32:47 -0400370 nic=None, mtu=None, fragmentation=True,
Roman Safronov12663cf2020-07-27 13:11:07 +0300371 timeout=None, pattern=None,
372 forbid_packet_loss=False):
YAMAMOTO Takashi25935722017-01-23 15:34:11 +0900373 """check ping server via source ssh connection
374
375 :param source: RemoteClient: an ssh connection from which to ping
376 :param dest: and IP to ping against
LIU Yulong68ab2452019-05-18 10:19:49 +0800377 :param count: Number of ping packet(s) to send
YAMAMOTO Takashi25935722017-01-23 15:34:11 +0900378 :param should_succeed: boolean should ping succeed or not
379 :param nic: specific network interface to ping from
Genadi Chereshnya6d10c6e2017-07-05 11:34:20 +0300380 :param mtu: mtu size for the packet to be sent
381 :param fragmentation: Flag for packet fragmentation
LIU Yulong68ab2452019-05-18 10:19:49 +0800382 :param timeout: Timeout for all ping packet(s) to succeed
Eduardo Olivaresf2b60542020-01-30 09:37:22 +0100383 :param pattern: hex digits included in ICMP messages
Roman Safronov12663cf2020-07-27 13:11:07 +0300384 :param forbid_packet_loss: forbid or allow some lost packets
YAMAMOTO Takashi25935722017-01-23 15:34:11 +0900385 :returns: boolean -- should_succeed == ping
386 :returns: ping is false if ping failed
387 """
LIU Yulong68ab2452019-05-18 10:19:49 +0800388 def ping_host(source, host, count,
Genadi Chereshnya6d10c6e2017-07-05 11:34:20 +0300389 size=CONF.validation.ping_size, nic=None, mtu=None,
Eduardo Olivaresf2b60542020-01-30 09:37:22 +0100390 fragmentation=True, pattern=None):
Assaf Muller92fdc782018-05-31 10:32:47 -0400391 IP_VERSION_4 = neutron_lib_constants.IP_VERSION_4
392 IP_VERSION_6 = neutron_lib_constants.IP_VERSION_6
393
394 # Use 'ping6' for IPv6 addresses, 'ping' for IPv4 and hostnames
395 ip_version = (
396 IP_VERSION_6 if netaddr.valid_ipv6(host) else IP_VERSION_4)
397 cmd = (
398 'ping6' if ip_version == IP_VERSION_6 else 'ping')
YAMAMOTO Takashi25935722017-01-23 15:34:11 +0900399 if nic:
400 cmd = 'sudo {cmd} -I {nic}'.format(cmd=cmd, nic=nic)
Genadi Chereshnya6d10c6e2017-07-05 11:34:20 +0300401 if mtu:
402 if not fragmentation:
403 cmd += ' -M do'
404 size = str(net_utils.get_ping_payload_size(
Assaf Muller92fdc782018-05-31 10:32:47 -0400405 mtu=mtu, ip_version=ip_version))
Eduardo Olivaresf2b60542020-01-30 09:37:22 +0100406 if pattern:
407 cmd += ' -p {pattern}'.format(pattern=pattern)
Maciej Józefczyk3c324e02020-03-16 10:52:08 +0000408 cmd += ' -c{0} -W{0} -s{1} {2}'.format(count, size, host)
YAMAMOTO Takashi25935722017-01-23 15:34:11 +0900409 return source.exec_command(cmd)
410
411 def ping_remote():
412 try:
LIU Yulong68ab2452019-05-18 10:19:49 +0800413 result = ping_host(source, dest, count, nic=nic, mtu=mtu,
Eduardo Olivaresf2b60542020-01-30 09:37:22 +0100414 fragmentation=fragmentation,
415 pattern=pattern)
YAMAMOTO Takashi25935722017-01-23 15:34:11 +0900416
417 except lib_exc.SSHExecCommandFailed:
418 LOG.warning('Failed to ping IP: %s via a ssh connection '
419 'from: %s.', dest, source.host)
420 return not should_succeed
421 LOG.debug('ping result: %s', result)
Assaf Muller92fdc782018-05-31 10:32:47 -0400422
Roman Safronov12663cf2020-07-27 13:11:07 +0300423 if forbid_packet_loss and ' 0% packet loss' not in result:
424 LOG.debug('Packet loss detected')
425 return not should_succeed
426
Assaf Muller92fdc782018-05-31 10:32:47 -0400427 if validators.validate_ip_address(dest) is None:
428 # Assert that the return traffic was from the correct
429 # source address.
430 from_source = 'from %s' % dest
431 self.assertIn(from_source, result)
YAMAMOTO Takashi25935722017-01-23 15:34:11 +0900432 return should_succeed
433
Assaf Muller92fdc782018-05-31 10:32:47 -0400434 return test_utils.call_until_true(
435 ping_remote, timeout or CONF.validation.ping_timeout, 1)
YAMAMOTO Takashi25935722017-01-23 15:34:11 +0900436
437 def check_remote_connectivity(self, source, dest, should_succeed=True,
Slawek Kaplonskib07251f2018-05-16 12:21:50 +0200438 nic=None, mtu=None, fragmentation=True,
LIU Yulong68ab2452019-05-18 10:19:49 +0800439 servers=None, timeout=None,
Eduardo Olivaresf2b60542020-01-30 09:37:22 +0100440 ping_count=CONF.validation.ping_count,
Roman Safronov12663cf2020-07-27 13:11:07 +0300441 pattern=None, forbid_packet_loss=False):
Slawek Kaplonskib07251f2018-05-16 12:21:50 +0200442 try:
443 self.assertTrue(self._check_remote_connectivity(
LIU Yulong68ab2452019-05-18 10:19:49 +0800444 source, dest, ping_count, should_succeed, nic, mtu,
445 fragmentation,
Roman Safronov12663cf2020-07-27 13:11:07 +0300446 timeout=timeout, pattern=pattern,
447 forbid_packet_loss=forbid_packet_loss))
Slawek Kaplonski8cccfe02020-09-29 22:34:09 +0200448 except (lib_exc.SSHTimeout, ssh_exc.AuthenticationException) as ssh_e:
Slawek Kaplonskib07251f2018-05-16 12:21:50 +0200449 LOG.debug(ssh_e)
450 self._log_console_output(servers)
Slawek Kaplonski8cccfe02020-09-29 22:34:09 +0200451 self._log_local_network_status()
Slawek Kaplonskib07251f2018-05-16 12:21:50 +0200452 raise
453 except AssertionError:
454 self._log_console_output(servers)
Slawek Kaplonski8cccfe02020-09-29 22:34:09 +0200455 self._log_local_network_status()
Slawek Kaplonskib07251f2018-05-16 12:21:50 +0200456 raise
Chandan Kumarc125fd12017-11-15 19:41:01 +0530457
458 def ping_ip_address(self, ip_address, should_succeed=True,
459 ping_timeout=None, mtu=None):
460 # the code is taken from tempest/scenario/manager.py in tempest git
461 timeout = ping_timeout or CONF.validation.ping_timeout
462 cmd = ['ping', '-c1', '-w1']
463
464 if mtu:
465 cmd += [
466 # don't fragment
467 '-M', 'do',
468 # ping receives just the size of ICMP payload
469 '-s', str(net_utils.get_ping_payload_size(mtu, 4))
470 ]
471 cmd.append(ip_address)
472
473 def ping():
474 proc = subprocess.Popen(cmd,
475 stdout=subprocess.PIPE,
476 stderr=subprocess.PIPE)
477 proc.communicate()
478
479 return (proc.returncode == 0) == should_succeed
480
481 caller = test_utils.find_test_caller()
482 LOG.debug('%(caller)s begins to ping %(ip)s in %(timeout)s sec and the'
483 ' expected result is %(should_succeed)s', {
484 'caller': caller, 'ip': ip_address, 'timeout': timeout,
485 'should_succeed':
486 'reachable' if should_succeed else 'unreachable'
487 })
488 result = test_utils.call_until_true(ping, timeout, 1)
Manjeet Singh Bhatia8bbf8992019-03-04 11:59:57 -0800489
490 # To make sure ping_ip_address called by test works
491 # as expected.
492 self.assertTrue(result)
493
Chandan Kumarc125fd12017-11-15 19:41:01 +0530494 LOG.debug('%(caller)s finishes ping %(ip)s in %(timeout)s sec and the '
495 'ping result is %(result)s', {
496 'caller': caller, 'ip': ip_address, 'timeout': timeout,
497 'result': 'expected' if result else 'unexpected'
498 })
499 return result
Federico Ressie7417b72018-05-30 05:50:58 +0200500
501 def wait_for_server_status(self, server, status, client=None, **kwargs):
502 """Waits for a server to reach a given status.
503
504 :param server: mapping having schema {'id': <server_id>}
505 :param status: string status to wait for (es: 'ACTIVE')
506 :param clien: servers client (self.os_primary.servers_client as
507 default value)
508 """
509
510 client = client or self.os_primary.servers_client
511 waiters.wait_for_server_status(client, server['id'], status, **kwargs)
512
513 def wait_for_server_active(self, server, client=None):
514 """Waits for a server to reach active status.
515
516 :param server: mapping having schema {'id': <server_id>}
517 :param clien: servers client (self.os_primary.servers_client as
518 default value)
519 """
520 self.wait_for_server_status(
521 server, constants.SERVER_STATUS_ACTIVE, client)
Jakub Libosvar031fd5a2019-07-15 16:10:07 +0000522
Slawek Kaplonski2211eab2020-10-20 16:43:53 +0200523 def wait_for_guest_os_ready(self, server, client=None):
524 if not CONF.compute_feature_enabled.console_output:
525 LOG.debug('Console output not supported, cannot check if server '
Rodolfo Alonso Hernandezdff870b2020-11-06 08:41:44 +0000526 '%s is ready.', server['id'])
Slawek Kaplonski2211eab2020-10-20 16:43:53 +0200527 return
528
529 client = client or self.os_primary.servers_client
530
531 def system_booted():
532 console_output = client.get_console_output(server['id'])['output']
533 for line in console_output.split('\n'):
534 if 'login:' in line.lower():
535 return True
536 return False
537
538 try:
539 utils.wait_until_true(system_booted, sleep=5)
540 except utils.WaitTimeout:
541 LOG.debug("No correct output in console of server %s found. "
542 "Guest operating system status can't be checked.",
543 server['id'])
544
Flavio Fernandesa1952c62020-10-02 06:39:08 -0400545 def check_servers_hostnames(self, servers, timeout=None, log_errors=True,
546 external_port=None):
Jakub Libosvar031fd5a2019-07-15 16:10:07 +0000547 """Compare hostnames of given servers with their names."""
548 try:
549 for server in servers:
550 kwargs = {}
nfridmand8969542020-06-02 14:59:09 +0300551 if timeout:
552 kwargs['timeout'] = timeout
Jakub Libosvar031fd5a2019-07-15 16:10:07 +0000553 try:
Flavio Fernandesa1952c62020-10-02 06:39:08 -0400554 kwargs['port'] = external_port or (
Slawek Kaplonskic4e963e2019-09-11 22:55:34 +0200555 server['port_forwarding_tcp']['external_port'])
Jakub Libosvar031fd5a2019-07-15 16:10:07 +0000556 except KeyError:
557 pass
558 ssh_client = ssh.Client(
559 self.fip['floating_ip_address'],
560 CONF.validation.image_ssh_user,
561 pkey=self.keypair['private_key'],
562 **kwargs)
563 self.assertIn(server['name'],
Rodolfo Alonso Hernandezaf394dd2020-11-12 14:26:13 +0000564 ssh_client.get_hostname())
Slawek Kaplonski8cccfe02020-09-29 22:34:09 +0200565 except (lib_exc.SSHTimeout, ssh_exc.AuthenticationException) as ssh_e:
Jakub Libosvar031fd5a2019-07-15 16:10:07 +0000566 LOG.debug(ssh_e)
567 if log_errors:
568 self._log_console_output(servers)
Slawek Kaplonski8cccfe02020-09-29 22:34:09 +0200569 self._log_local_network_status()
Jakub Libosvar031fd5a2019-07-15 16:10:07 +0000570 raise
571 except AssertionError as assert_e:
572 LOG.debug(assert_e)
573 if log_errors:
574 self._log_console_output(servers)
Slawek Kaplonski8cccfe02020-09-29 22:34:09 +0200575 self._log_local_network_status()
Jakub Libosvar031fd5a2019-07-15 16:10:07 +0000576 raise
Slawek Kaplonskic4e963e2019-09-11 22:55:34 +0200577
Slawek Kaplonskifd4141f2020-03-14 14:34:00 +0100578 def ensure_nc_listen(self, ssh_client, port, protocol, echo_msg=None,
579 servers=None):
580 """Ensure that nc server listening on the given TCP/UDP port is up.
581
582 Listener is created always on remote host.
583 """
584 def spawn_and_check_process():
585 self.nc_listen(ssh_client, port, protocol, echo_msg, servers)
586 return utils.process_is_running(ssh_client, "nc")
587
588 utils.wait_until_true(spawn_and_check_process)
589
590 def nc_listen(self, ssh_client, port, protocol, echo_msg=None,
591 servers=None):
Slawek Kaplonskic4e963e2019-09-11 22:55:34 +0200592 """Create nc server listening on the given TCP/UDP port.
593
594 Listener is created always on remote host.
595 """
Slawek Kaplonskic4e963e2019-09-11 22:55:34 +0200596 try:
Slawek Kaplonskiaf83e832020-02-05 12:11:54 +0100597 return ssh_client.execute_script(
598 get_ncat_server_cmd(port, protocol, echo_msg),
Flavio Fernandesb056ac22020-07-01 14:57:13 -0400599 become_root=True, combine_stderr=True)
Slawek Kaplonski8cccfe02020-09-29 22:34:09 +0200600 except (lib_exc.SSHTimeout, ssh_exc.AuthenticationException) as ssh_e:
Slawek Kaplonskic4e963e2019-09-11 22:55:34 +0200601 LOG.debug(ssh_e)
Slawek Kaplonskifd4141f2020-03-14 14:34:00 +0100602 self._log_console_output(servers)
Slawek Kaplonski8cccfe02020-09-29 22:34:09 +0200603 self._log_local_network_status()
Slawek Kaplonskic4e963e2019-09-11 22:55:34 +0200604 raise
605
606 def nc_client(self, ip_address, port, protocol):
607 """Check connectivity to TCP/UDP port at host via nc.
608
609 Client is always executed locally on host where tests are executed.
610 """
Slawek Kaplonskiaf83e832020-02-05 12:11:54 +0100611 cmd = get_ncat_client_cmd(ip_address, port, protocol)
Slawek Kaplonskic4e963e2019-09-11 22:55:34 +0200612 result = shell.execute_local_command(cmd)
613 self.assertEqual(0, result.exit_status)
614 return result.stdout