blob: 0ffe4987e3726f44841238bb133becd9abddf7d9 [file] [log] [blame]
Jude Cross986e3f52017-07-24 14:57:20 -07001# Copyright 2018 Rackspace US Inc. All rights reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License"); you may
4# not use this file except in compliance with the License. You may obtain
5# a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12# License for the specific language governing permissions and limitations
13# under the License.
14
Gregory Thiemonge29d17902019-04-30 15:06:17 +020015import errno
Jude Cross986e3f52017-07-24 14:57:20 -070016import ipaddress
17import pkg_resources
18import random
Adam Harwellcd72b562018-05-07 11:37:22 -070019import requests
Jude Cross986e3f52017-07-24 14:57:20 -070020import shlex
21import six
Gregory Thiemonge29d17902019-04-30 15:06:17 +020022import socket
Jude Cross986e3f52017-07-24 14:57:20 -070023import string
24import subprocess
25import tempfile
Adam Harwellcd72b562018-05-07 11:37:22 -070026import time
Jude Cross986e3f52017-07-24 14:57:20 -070027
28from oslo_log import log as logging
29from oslo_utils import uuidutils
30from tempest import config
31from tempest.lib.common.utils import data_utils
32from tempest.lib.common.utils.linux import remote_client
Jude Cross986e3f52017-07-24 14:57:20 -070033from tempest.lib import exceptions
34from tempest import test
Michael Johnson04dc5cb2019-01-20 11:03:50 -080035import tenacity
Jude Cross986e3f52017-07-24 14:57:20 -070036
37from octavia_tempest_plugin import clients
38from octavia_tempest_plugin.common import constants as const
39from octavia_tempest_plugin.tests import validators
40from octavia_tempest_plugin.tests import waiters
41
42CONF = config.CONF
43LOG = logging.getLogger(__name__)
44
Michael Johnson04dc5cb2019-01-20 11:03:50 -080045RETRY_ATTEMPTS = 15
46RETRY_INITIAL_DELAY = 1
47RETRY_BACKOFF = 1
48RETRY_MAX = 5
49
Gregory Thiemonge29d17902019-04-30 15:06:17 +020050SRC_PORT_NUMBER_MIN = 32768
51SRC_PORT_NUMBER_MAX = 61000
52
Jude Cross986e3f52017-07-24 14:57:20 -070053
54class LoadBalancerBaseTest(test.BaseTestCase):
55 """Base class for load balancer tests."""
56
57 # Setup cls.os_roles_lb_member. cls.os_primary, cls.os_roles_lb_member,
58 # and cls.os_roles_lb_admin credentials.
59 credentials = ['admin', 'primary',
60 ['lb_member', CONF.load_balancer.member_role],
61 ['lb_member2', CONF.load_balancer.member_role],
62 ['lb_admin', CONF.load_balancer.admin_role]]
63
64 client_manager = clients.ManagerV2
Adam Harwelle029af22018-05-24 17:13:28 -070065 webserver1_response = 1
66 webserver2_response = 5
Michael Johnsondfd818a2018-08-21 20:54:54 -070067 used_ips = []
Jude Cross986e3f52017-07-24 14:57:20 -070068
Gregory Thiemonge29d17902019-04-30 15:06:17 +020069 src_port_number = SRC_PORT_NUMBER_MIN
70
Jude Cross986e3f52017-07-24 14:57:20 -070071 @classmethod
72 def skip_checks(cls):
73 """Check if we should skip all of the children tests."""
74 super(LoadBalancerBaseTest, cls).skip_checks()
75
76 service_list = {
77 'load_balancer': CONF.service_available.load_balancer,
78 }
79
80 live_service_list = {
81 'compute': CONF.service_available.nova,
82 'image': CONF.service_available.glance,
83 'neutron': CONF.service_available.neutron
84 }
85
86 if not CONF.load_balancer.test_with_noop:
87 service_list.update(live_service_list)
88
89 for service, available in service_list.items():
90 if not available:
zhangzs2a6cf672018-11-10 16:13:11 +080091 skip_msg = ("{0} skipped as {1} service is not "
Jude Cross986e3f52017-07-24 14:57:20 -070092 "available.".format(cls.__name__, service))
93 raise cls.skipException(skip_msg)
94
95 # We must be able to reach our VIP and instances
96 if not (CONF.network.project_networks_reachable
97 or CONF.network.public_network_id):
98 msg = ('Either project_networks_reachable must be "true", or '
99 'public_network_id must be defined.')
100 raise cls.skipException(msg)
101
102 @classmethod
103 def setup_credentials(cls):
104 """Setup test credentials and network resources."""
105 # Do not auto create network resources
106 cls.set_network_resources()
107 super(LoadBalancerBaseTest, cls).setup_credentials()
108
109 @classmethod
110 def setup_clients(cls):
111 """Setup client aliases."""
112 super(LoadBalancerBaseTest, cls).setup_clients()
113 cls.lb_mem_float_ip_client = cls.os_roles_lb_member.floating_ips_client
114 cls.lb_mem_keypairs_client = cls.os_roles_lb_member.keypairs_client
115 cls.lb_mem_net_client = cls.os_roles_lb_member.networks_client
116 cls.lb_mem_ports_client = cls.os_roles_lb_member.ports_client
117 cls.lb_mem_routers_client = cls.os_roles_lb_member.routers_client
118 cls.lb_mem_SG_client = cls.os_roles_lb_member.security_groups_client
119 cls.lb_mem_SGr_client = (
120 cls.os_roles_lb_member.security_group_rules_client)
121 cls.lb_mem_servers_client = cls.os_roles_lb_member.servers_client
122 cls.lb_mem_subnet_client = cls.os_roles_lb_member.subnets_client
123 cls.mem_lb_client = cls.os_roles_lb_member.loadbalancer_client
Jude Crossfbbd2b42017-08-09 15:21:04 -0700124 cls.mem_listener_client = cls.os_roles_lb_member.listener_client
Adam Harwell8ffce3e2018-05-01 21:18:44 -0700125 cls.mem_pool_client = cls.os_roles_lb_member.pool_client
Adam Harwellde3e0542018-05-03 18:21:06 -0700126 cls.mem_member_client = cls.os_roles_lb_member.member_client
Adam Harwell60ed9d92018-05-10 13:23:13 -0700127 cls.mem_healthmonitor_client = (
128 cls.os_roles_lb_member.healthmonitor_client)
Adam Harwell446f8be2018-05-24 16:51:03 -0700129 cls.mem_l7policy_client = cls.os_roles_lb_member.l7policy_client
Adam Harwelle029af22018-05-24 17:13:28 -0700130 cls.mem_l7rule_client = cls.os_roles_lb_member.l7rule_client
Michael Johnson2b10e0a2019-01-25 15:42:13 -0800131 cls.lb_admin_amphora_client = cls.os_roles_lb_admin.amphora_client
Michael Johnsonaff2e862019-01-11 16:38:00 -0800132 cls.lb_admin_flavor_profile_client = (
133 cls.os_roles_lb_admin.flavor_profile_client)
Michael Johnsona2d03072019-01-14 17:18:21 -0800134 cls.lb_admin_flavor_client = cls.os_roles_lb_admin.flavor_client
135 cls.mem_flavor_client = cls.os_roles_lb_member.flavor_client
Michael Johnsonfc223fe2019-01-15 16:40:05 -0800136 cls.mem_provider_client = cls.os_roles_lb_member.provider_client
Carlos Goncalvesc2e12162019-02-14 23:57:44 +0100137 cls.os_admin_servers_client = cls.os_admin.servers_client
Adam Harwellc2aa20c2019-11-20 11:15:07 -0800138 cls.lb_admin_flavor_capabilities_client = (
Michael Johnson77df0322019-01-15 18:27:58 -0800139 cls.os_roles_lb_admin.flavor_capabilities_client)
Adam Harwellc2aa20c2019-11-20 11:15:07 -0800140 cls.lb_admin_availability_zone_capabilities_client = (
141 cls.os_roles_lb_admin.availability_zone_capabilities_client)
142 cls.lb_admin_availability_zone_profile_client = (
143 cls.os_roles_lb_admin.availability_zone_profile_client)
144 cls.lb_admin_availability_zone_client = (
145 cls.os_roles_lb_admin.availability_zone_client)
146 cls.mem_availability_zone_client = (
147 cls.os_roles_lb_member.availability_zone_client)
Jude Cross986e3f52017-07-24 14:57:20 -0700148
149 @classmethod
150 def resource_setup(cls):
151 """Setup resources needed by the tests."""
152 super(LoadBalancerBaseTest, cls).resource_setup()
153
154 conf_lb = CONF.load_balancer
155
Michael Johnsondfd818a2018-08-21 20:54:54 -0700156 cls.api_version = cls.mem_lb_client.get_max_api_version()
157
Jude Cross986e3f52017-07-24 14:57:20 -0700158 if conf_lb.test_subnet_override and not conf_lb.test_network_override:
159 raise exceptions.InvalidConfiguration(
160 "Configuration value test_network_override must be "
161 "specified if test_subnet_override is used.")
162
Maciej Józefczykb6df5f82019-12-10 10:12:30 +0000163 # Get loadbalancing algorithms supported by provider driver.
164 try:
165 algorithms = const.SUPPORTED_LB_ALGORITHMS[
166 CONF.load_balancer.provider]
167 except KeyError:
168 algorithms = const.SUPPORTED_LB_ALGORITHMS['default']
169 # Set default algorithm as first from the list.
170 cls.lb_algorithm = algorithms[0]
171
Jude Cross986e3f52017-07-24 14:57:20 -0700172 show_subnet = cls.lb_mem_subnet_client.show_subnet
173 if CONF.load_balancer.test_with_noop:
174 cls.lb_member_vip_net = {'id': uuidutils.generate_uuid()}
175 cls.lb_member_vip_subnet = {'id': uuidutils.generate_uuid()}
176 cls.lb_member_1_net = {'id': uuidutils.generate_uuid()}
177 cls.lb_member_1_subnet = {'id': uuidutils.generate_uuid()}
178 cls.lb_member_2_net = {'id': uuidutils.generate_uuid()}
179 cls.lb_member_2_subnet = {'id': uuidutils.generate_uuid()}
180 if CONF.load_balancer.test_with_ipv6:
Michael Johnson5a16ad32018-10-18 14:49:11 -0700181 cls.lb_member_vip_ipv6_net = {'id': uuidutils.generate_uuid()}
Jude Cross986e3f52017-07-24 14:57:20 -0700182 cls.lb_member_vip_ipv6_subnet = {'id':
183 uuidutils.generate_uuid()}
184 cls.lb_member_1_ipv6_subnet = {'id': uuidutils.generate_uuid()}
185 cls.lb_member_2_ipv6_subnet = {'id': uuidutils.generate_uuid()}
Michael Johnson590fbe12019-07-03 14:30:01 -0700186 cls.lb_member_vip_ipv6_subnet_stateful = True
Jude Cross986e3f52017-07-24 14:57:20 -0700187 return
188 elif CONF.load_balancer.test_network_override:
189 if conf_lb.test_subnet_override:
190 override_subnet = show_subnet(conf_lb.test_subnet_override)
191 else:
192 override_subnet = None
193
194 show_net = cls.lb_mem_net_client.show_network
195 override_network = show_net(conf_lb.test_network_override)
196 override_network = override_network.get('network')
197
198 cls.lb_member_vip_net = override_network
199 cls.lb_member_vip_subnet = override_subnet
200 cls.lb_member_1_net = override_network
201 cls.lb_member_1_subnet = override_subnet
202 cls.lb_member_2_net = override_network
203 cls.lb_member_2_subnet = override_subnet
204
205 if (CONF.load_balancer.test_with_ipv6 and
206 conf_lb.test_IPv6_subnet_override):
207 override_ipv6_subnet = show_subnet(
208 conf_lb.test_IPv6_subnet_override)
209 cls.lb_member_vip_ipv6_subnet = override_ipv6_subnet
210 cls.lb_member_1_ipv6_subnet = override_ipv6_subnet
211 cls.lb_member_2_ipv6_subnet = override_ipv6_subnet
Michael Johnson590fbe12019-07-03 14:30:01 -0700212 cls.lb_member_vip_ipv6_subnet_stateful = False
213 if (override_ipv6_subnet[0]['ipv6_address_mode'] ==
214 'dhcpv6-stateful'):
215 cls.lb_member_vip_ipv6_subnet_stateful = True
Jude Cross986e3f52017-07-24 14:57:20 -0700216 else:
217 cls.lb_member_vip_ipv6_subnet = None
218 cls.lb_member_1_ipv6_subnet = None
219 cls.lb_member_2_ipv6_subnet = None
220 else:
221 cls._create_networks()
222
223 LOG.debug('Octavia Setup: lb_member_vip_net = {}'.format(
224 cls.lb_member_vip_net[const.ID]))
225 if cls.lb_member_vip_subnet:
226 LOG.debug('Octavia Setup: lb_member_vip_subnet = {}'.format(
227 cls.lb_member_vip_subnet[const.ID]))
228 LOG.debug('Octavia Setup: lb_member_1_net = {}'.format(
229 cls.lb_member_1_net[const.ID]))
230 if cls.lb_member_1_subnet:
231 LOG.debug('Octavia Setup: lb_member_1_subnet = {}'.format(
232 cls.lb_member_1_subnet[const.ID]))
233 LOG.debug('Octavia Setup: lb_member_2_net = {}'.format(
234 cls.lb_member_2_net[const.ID]))
235 if cls.lb_member_2_subnet:
236 LOG.debug('Octavia Setup: lb_member_2_subnet = {}'.format(
237 cls.lb_member_2_subnet[const.ID]))
Michael Johnson124ba8b2018-08-30 16:06:05 -0700238 if CONF.load_balancer.test_with_ipv6:
239 if cls.lb_member_vip_ipv6_subnet:
240 LOG.debug('Octavia Setup: lb_member_vip_ipv6_subnet = '
241 '{}'.format(cls.lb_member_vip_ipv6_subnet[const.ID]))
242 if cls.lb_member_1_ipv6_subnet:
243 LOG.debug('Octavia Setup: lb_member_1_ipv6_subnet = {}'.format(
244 cls.lb_member_1_ipv6_subnet[const.ID]))
245 if cls.lb_member_2_ipv6_subnet:
246 LOG.debug('Octavia Setup: lb_member_2_ipv6_subnet = {}'.format(
247 cls.lb_member_2_ipv6_subnet[const.ID]))
Jude Cross986e3f52017-07-24 14:57:20 -0700248
Jude Cross986e3f52017-07-24 14:57:20 -0700249 @classmethod
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800250 # Neutron can be slow to clean up ports from the subnets/networks.
251 # Retry this delete a few times if we get a "Conflict" error to give
252 # neutron time to fully cleanup the ports.
253 @tenacity.retry(
254 retry=tenacity.retry_if_exception_type(exceptions.Conflict),
255 wait=tenacity.wait_incrementing(
256 RETRY_INITIAL_DELAY, RETRY_BACKOFF, RETRY_MAX),
257 stop=tenacity.stop_after_attempt(RETRY_ATTEMPTS))
258 def _logging_delete_network(cls, net_id):
259 try:
260 cls.lb_mem_net_client.delete_network(net_id)
261 except Exception:
262 LOG.error('Unable to delete network {}. Active ports:'.format(
263 net_id))
264 LOG.error(cls.lb_mem_ports_client.list_ports())
265 raise
266
267 @classmethod
268 # Neutron can be slow to clean up ports from the subnets/networks.
269 # Retry this delete a few times if we get a "Conflict" error to give
270 # neutron time to fully cleanup the ports.
271 @tenacity.retry(
272 retry=tenacity.retry_if_exception_type(exceptions.Conflict),
273 wait=tenacity.wait_incrementing(
274 RETRY_INITIAL_DELAY, RETRY_BACKOFF, RETRY_MAX),
275 stop=tenacity.stop_after_attempt(RETRY_ATTEMPTS))
276 def _logging_delete_subnet(cls, subnet_id):
277 try:
278 cls.lb_mem_subnet_client.delete_subnet(subnet_id)
279 except Exception:
280 LOG.error('Unable to delete subnet {}. Active ports:'.format(
281 subnet_id))
282 LOG.error(cls.lb_mem_ports_client.list_ports())
283 raise
284
285 @classmethod
Jude Cross986e3f52017-07-24 14:57:20 -0700286 def _create_networks(cls):
287 """Creates networks, subnets, and routers used in tests.
288
289 The following are expected to be defined and available to the tests:
290 cls.lb_member_vip_net
291 cls.lb_member_vip_subnet
292 cls.lb_member_vip_ipv6_subnet (optional)
293 cls.lb_member_1_net
294 cls.lb_member_1_subnet
295 cls.lb_member_1_ipv6_subnet (optional)
296 cls.lb_member_2_net
297 cls.lb_member_2_subnet
298 cls.lb_member_2_ipv6_subnet (optional)
299 """
300
301 # Create tenant VIP network
302 network_kwargs = {
303 'name': data_utils.rand_name("lb_member_vip_network")}
304 if CONF.network_feature_enabled.port_security:
Andreas Jaeger4215b702020-03-28 20:13:46 +0100305 # Note: Allowed Address Pairs requires port security
306 network_kwargs['port_security_enabled'] = True
Jude Cross986e3f52017-07-24 14:57:20 -0700307 result = cls.lb_mem_net_client.create_network(**network_kwargs)
308 cls.lb_member_vip_net = result['network']
309 LOG.info('lb_member_vip_net: {}'.format(cls.lb_member_vip_net))
310 cls.addClassResourceCleanup(
311 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800312 cls._logging_delete_network,
Jude Cross986e3f52017-07-24 14:57:20 -0700313 cls.lb_mem_net_client.show_network,
314 cls.lb_member_vip_net['id'])
315
316 # Create tenant VIP subnet
317 subnet_kwargs = {
318 'name': data_utils.rand_name("lb_member_vip_subnet"),
319 'network_id': cls.lb_member_vip_net['id'],
320 'cidr': CONF.load_balancer.vip_subnet_cidr,
321 'ip_version': 4}
322 result = cls.lb_mem_subnet_client.create_subnet(**subnet_kwargs)
323 cls.lb_member_vip_subnet = result['subnet']
324 LOG.info('lb_member_vip_subnet: {}'.format(cls.lb_member_vip_subnet))
325 cls.addClassResourceCleanup(
326 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800327 cls._logging_delete_subnet,
Jude Cross986e3f52017-07-24 14:57:20 -0700328 cls.lb_mem_subnet_client.show_subnet,
329 cls.lb_member_vip_subnet['id'])
330
331 # Create tenant VIP IPv6 subnet
332 if CONF.load_balancer.test_with_ipv6:
Adam Harwell2b9432f2019-05-02 13:56:09 -0600333 # See if ipv6-private-subnet exists and use it if so.
334 priv_ipv6_subnet = cls.os_admin.subnets_client.list_subnets(
335 name='ipv6-private-subnet')['subnets']
Michael Johnson5a16ad32018-10-18 14:49:11 -0700336
Michael Johnson590fbe12019-07-03 14:30:01 -0700337 cls.lb_member_vip_ipv6_subnet_stateful = False
Adam Harwell2b9432f2019-05-02 13:56:09 -0600338 if len(priv_ipv6_subnet) == 1:
Carlos Goncalves84af48c2019-07-25 15:51:30 +0200339 if (priv_ipv6_subnet[0]['ipv6_address_mode'] ==
340 'dhcpv6-stateful'):
341 cls.lb_member_vip_ipv6_subnet_stateful = True
Adam Harwell2b9432f2019-05-02 13:56:09 -0600342 cls.lb_member_vip_ipv6_subnet = priv_ipv6_subnet[0]
Michael Johnson5a16ad32018-10-18 14:49:11 -0700343 cls.lb_member_vip_ipv6_net = {
Adam Harwell2b9432f2019-05-02 13:56:09 -0600344 'id': priv_ipv6_subnet[0]['network_id']}
Michael Johnson5a16ad32018-10-18 14:49:11 -0700345 else:
346 subnet_kwargs = {
347 'name': data_utils.rand_name("lb_member_vip_ipv6_subnet"),
348 'network_id': cls.lb_member_vip_net['id'],
349 'cidr': CONF.load_balancer.vip_ipv6_subnet_cidr,
350 'ip_version': 6}
351 result = cls.lb_mem_subnet_client.create_subnet(
352 **subnet_kwargs)
Michael Johnson7c5b9012019-05-28 11:02:29 -0700353 cls.lb_member_vip_ipv6_net = cls.lb_member_vip_net
Michael Johnson5a16ad32018-10-18 14:49:11 -0700354 cls.lb_member_vip_ipv6_subnet = result['subnet']
355 cls.addClassResourceCleanup(
356 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800357 cls._logging_delete_subnet,
Michael Johnson5a16ad32018-10-18 14:49:11 -0700358 cls.lb_mem_subnet_client.show_subnet,
359 cls.lb_member_vip_ipv6_subnet['id'])
Carlos Goncalves84af48c2019-07-25 15:51:30 +0200360
Jude Cross986e3f52017-07-24 14:57:20 -0700361 LOG.info('lb_member_vip_ipv6_subnet: {}'.format(
362 cls.lb_member_vip_ipv6_subnet))
Jude Cross986e3f52017-07-24 14:57:20 -0700363
364 # Create tenant member 1 network
365 network_kwargs = {
366 'name': data_utils.rand_name("lb_member_1_network")}
367 if CONF.network_feature_enabled.port_security:
368 if CONF.load_balancer.enable_security_groups:
369 network_kwargs['port_security_enabled'] = True
370 else:
371 network_kwargs['port_security_enabled'] = False
372 result = cls.lb_mem_net_client.create_network(**network_kwargs)
373 cls.lb_member_1_net = result['network']
374 LOG.info('lb_member_1_net: {}'.format(cls.lb_member_1_net))
375 cls.addClassResourceCleanup(
376 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800377 cls._logging_delete_network,
Jude Cross986e3f52017-07-24 14:57:20 -0700378 cls.lb_mem_net_client.show_network,
379 cls.lb_member_1_net['id'])
380
381 # Create tenant member 1 subnet
382 subnet_kwargs = {
383 'name': data_utils.rand_name("lb_member_1_subnet"),
384 'network_id': cls.lb_member_1_net['id'],
385 'cidr': CONF.load_balancer.member_1_ipv4_subnet_cidr,
386 'ip_version': 4}
387 result = cls.lb_mem_subnet_client.create_subnet(**subnet_kwargs)
388 cls.lb_member_1_subnet = result['subnet']
389 LOG.info('lb_member_1_subnet: {}'.format(cls.lb_member_1_subnet))
390 cls.addClassResourceCleanup(
391 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800392 cls._logging_delete_subnet,
Jude Cross986e3f52017-07-24 14:57:20 -0700393 cls.lb_mem_subnet_client.show_subnet,
394 cls.lb_member_1_subnet['id'])
395
396 # Create tenant member 1 ipv6 subnet
397 if CONF.load_balancer.test_with_ipv6:
398 subnet_kwargs = {
399 'name': data_utils.rand_name("lb_member_1_ipv6_subnet"),
400 'network_id': cls.lb_member_1_net['id'],
401 'cidr': CONF.load_balancer.member_1_ipv6_subnet_cidr,
402 'ip_version': 6}
403 result = cls.lb_mem_subnet_client.create_subnet(**subnet_kwargs)
Michael Johnsonbf916df2018-10-17 10:59:28 -0700404 cls.lb_member_1_subnet_prefix = (
405 CONF.load_balancer.member_1_ipv6_subnet_cidr.rpartition('/')[2]
406 )
407 assert(cls.lb_member_1_subnet_prefix.isdigit())
Jude Cross986e3f52017-07-24 14:57:20 -0700408 cls.lb_member_1_ipv6_subnet = result['subnet']
409 LOG.info('lb_member_1_ipv6_subnet: {}'.format(
410 cls.lb_member_1_ipv6_subnet))
411 cls.addClassResourceCleanup(
412 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800413 cls._logging_delete_subnet,
Jude Cross986e3f52017-07-24 14:57:20 -0700414 cls.lb_mem_subnet_client.show_subnet,
415 cls.lb_member_1_ipv6_subnet['id'])
416
417 # Create tenant member 2 network
418 network_kwargs = {
419 'name': data_utils.rand_name("lb_member_2_network")}
420 if CONF.network_feature_enabled.port_security:
421 if CONF.load_balancer.enable_security_groups:
422 network_kwargs['port_security_enabled'] = True
423 else:
424 network_kwargs['port_security_enabled'] = False
425 result = cls.lb_mem_net_client.create_network(**network_kwargs)
426 cls.lb_member_2_net = result['network']
427 LOG.info('lb_member_2_net: {}'.format(cls.lb_member_2_net))
428 cls.addClassResourceCleanup(
429 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800430 cls._logging_delete_network,
Jude Cross986e3f52017-07-24 14:57:20 -0700431 cls.lb_mem_net_client.show_network,
432 cls.lb_member_2_net['id'])
433
434 # Create tenant member 2 subnet
435 subnet_kwargs = {
436 'name': data_utils.rand_name("lb_member_2_subnet"),
437 'network_id': cls.lb_member_2_net['id'],
438 'cidr': CONF.load_balancer.member_2_ipv4_subnet_cidr,
439 'ip_version': 4}
440 result = cls.lb_mem_subnet_client.create_subnet(**subnet_kwargs)
441 cls.lb_member_2_subnet = result['subnet']
442 LOG.info('lb_member_2_subnet: {}'.format(cls.lb_member_2_subnet))
443 cls.addClassResourceCleanup(
444 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800445 cls._logging_delete_subnet,
Jude Cross986e3f52017-07-24 14:57:20 -0700446 cls.lb_mem_subnet_client.show_subnet,
447 cls.lb_member_2_subnet['id'])
448
449 # Create tenant member 2 ipv6 subnet
450 if CONF.load_balancer.test_with_ipv6:
451 subnet_kwargs = {
452 'name': data_utils.rand_name("lb_member_2_ipv6_subnet"),
453 'network_id': cls.lb_member_2_net['id'],
454 'cidr': CONF.load_balancer.member_2_ipv6_subnet_cidr,
455 'ip_version': 6}
456 result = cls.lb_mem_subnet_client.create_subnet(**subnet_kwargs)
Michael Johnsonbf916df2018-10-17 10:59:28 -0700457 cls.lb_member_2_subnet_prefix = (
458 CONF.load_balancer.member_2_ipv6_subnet_cidr.rpartition('/')[2]
459 )
460 assert(cls.lb_member_2_subnet_prefix.isdigit())
Jude Cross986e3f52017-07-24 14:57:20 -0700461 cls.lb_member_2_ipv6_subnet = result['subnet']
462 LOG.info('lb_member_2_ipv6_subnet: {}'.format(
463 cls.lb_member_2_ipv6_subnet))
464 cls.addClassResourceCleanup(
465 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800466 cls._logging_delete_subnet,
Jude Cross986e3f52017-07-24 14:57:20 -0700467 cls.lb_mem_subnet_client.show_subnet,
468 cls.lb_member_2_ipv6_subnet['id'])
469
Adam Harwellcd72b562018-05-07 11:37:22 -0700470 @classmethod
Michael Johnson07c9a632018-06-07 13:27:42 -0700471 def _setup_lb_network_kwargs(cls, lb_kwargs, ip_version=None,
472 use_fixed_ip=False):
Adam Harwell60ed9d92018-05-10 13:23:13 -0700473 if not ip_version:
474 ip_version = 6 if CONF.load_balancer.test_with_ipv6 else 4
Michael Johnson5a16ad32018-10-18 14:49:11 -0700475 if cls.lb_member_vip_subnet or cls.lb_member_vip_ipv6_subnet:
Adam Harwellcd72b562018-05-07 11:37:22 -0700476 ip_index = data_utils.rand_int_id(start=10, end=100)
Michael Johnsondfd818a2018-08-21 20:54:54 -0700477 while ip_index in cls.used_ips:
478 ip_index = data_utils.rand_int_id(start=10, end=100)
479 cls.used_ips.append(ip_index)
Adam Harwellcd72b562018-05-07 11:37:22 -0700480 if ip_version == 4:
Adam Harwellcd72b562018-05-07 11:37:22 -0700481 subnet_id = cls.lb_member_vip_subnet[const.ID]
Michael Johnson5a16ad32018-10-18 14:49:11 -0700482 if CONF.load_balancer.test_with_noop:
483 lb_vip_address = '198.18.33.33'
484 else:
485 subnet = cls.os_admin.subnets_client.show_subnet(subnet_id)
486 network = ipaddress.IPv4Network(subnet['subnet']['cidr'])
487 lb_vip_address = str(network[ip_index])
Adam Harwellcd72b562018-05-07 11:37:22 -0700488 else:
Adam Harwellcd72b562018-05-07 11:37:22 -0700489 subnet_id = cls.lb_member_vip_ipv6_subnet[const.ID]
Michael Johnson5a16ad32018-10-18 14:49:11 -0700490 if CONF.load_balancer.test_with_noop:
491 lb_vip_address = '2001:db8:33:33:33:33:33:33'
492 else:
493 subnet = cls.os_admin.subnets_client.show_subnet(subnet_id)
494 network = ipaddress.IPv6Network(subnet['subnet']['cidr'])
495 lb_vip_address = str(network[ip_index])
Michael Johnson590fbe12019-07-03 14:30:01 -0700496 # If the subnet is IPv6 slaac or dhcpv6-stateless
497 # neutron does not allow a fixed IP
498 if not cls.lb_member_vip_ipv6_subnet_stateful:
499 use_fixed_ip = False
Adam Harwellcd72b562018-05-07 11:37:22 -0700500 lb_kwargs[const.VIP_SUBNET_ID] = subnet_id
Michael Johnson07c9a632018-06-07 13:27:42 -0700501 if use_fixed_ip:
502 lb_kwargs[const.VIP_ADDRESS] = lb_vip_address
Adam Harwellcd72b562018-05-07 11:37:22 -0700503 if CONF.load_balancer.test_with_noop:
504 lb_kwargs[const.VIP_NETWORK_ID] = (
505 cls.lb_member_vip_net[const.ID])
506 else:
507 lb_kwargs[const.VIP_NETWORK_ID] = cls.lb_member_vip_net[const.ID]
508 lb_kwargs[const.VIP_SUBNET_ID] = None
509
ibumarskov072fab32020-09-03 18:21:29 +0400510 @classmethod
511 def _create_tf_listener(cls, name, proto, port, lb_id):
512 listener_kwargs = {
513 const.NAME: name,
514 const.PROTOCOL: proto,
515 const.PROTOCOL_PORT: port,
516 const.LOADBALANCER_ID: lb_id,
517 }
518 listener = cls.mem_listener_client.create_listener(**listener_kwargs)
519 return listener
520
Adam Harwellcd72b562018-05-07 11:37:22 -0700521
522class LoadBalancerBaseTestWithCompute(LoadBalancerBaseTest):
523 @classmethod
524 def resource_setup(cls):
525 super(LoadBalancerBaseTestWithCompute, cls).resource_setup()
526 # If validation is disabled in this cloud, we won't be able to
527 # start the webservers, so don't even boot them.
528 if not CONF.validation.run_validation:
529 return
530
531 # Create a keypair for the webservers
532 keypair_name = data_utils.rand_name('lb_member_keypair')
533 result = cls.lb_mem_keypairs_client.create_keypair(
534 name=keypair_name)
535 cls.lb_member_keypair = result['keypair']
536 LOG.info('lb_member_keypair: {}'.format(cls.lb_member_keypair))
537 cls.addClassResourceCleanup(
538 waiters.wait_for_not_found,
539 cls.lb_mem_keypairs_client.delete_keypair,
540 cls.lb_mem_keypairs_client.show_keypair,
541 keypair_name)
542
543 if (CONF.load_balancer.enable_security_groups and
544 CONF.network_feature_enabled.port_security):
545 # Set up the security group for the webservers
546 SG_name = data_utils.rand_name('lb_member_SG')
547 cls.lb_member_sec_group = (
548 cls.lb_mem_SG_client.create_security_group(
549 name=SG_name)['security_group'])
550 cls.addClassResourceCleanup(
551 waiters.wait_for_not_found,
552 cls.lb_mem_SG_client.delete_security_group,
553 cls.lb_mem_SG_client.show_security_group,
554 cls.lb_member_sec_group['id'])
555
556 # Create a security group rule to allow 80-81 (test webservers)
557 SGr = cls.lb_mem_SGr_client.create_security_group_rule(
558 direction='ingress',
559 security_group_id=cls.lb_member_sec_group['id'],
560 protocol='tcp',
561 ethertype='IPv4',
562 port_range_min=80,
563 port_range_max=81)['security_group_rule']
564 cls.addClassResourceCleanup(
565 waiters.wait_for_not_found,
566 cls.lb_mem_SGr_client.delete_security_group_rule,
567 cls.lb_mem_SGr_client.show_security_group_rule,
568 SGr['id'])
Gregory Thiemonge29d17902019-04-30 15:06:17 +0200569 # Create a security group rule to allow UDP 80-81 (test webservers)
570 SGr = cls.lb_mem_SGr_client.create_security_group_rule(
571 direction='ingress',
572 security_group_id=cls.lb_member_sec_group['id'],
573 protocol='udp',
574 ethertype='IPv4',
575 port_range_min=80,
576 port_range_max=81)['security_group_rule']
577 cls.addClassResourceCleanup(
578 waiters.wait_for_not_found,
579 cls.lb_mem_SGr_client.delete_security_group_rule,
580 cls.lb_mem_SGr_client.show_security_group_rule,
581 SGr['id'])
582 # Create a security group rule to allow UDP 9999 (test webservers)
583 # Port 9999 is used to illustrate health monitor ERRORs on closed
584 # ports.
585 SGr = cls.lb_mem_SGr_client.create_security_group_rule(
586 direction='ingress',
587 security_group_id=cls.lb_member_sec_group['id'],
588 protocol='udp',
589 ethertype='IPv4',
590 port_range_min=9999,
591 port_range_max=9999)['security_group_rule']
592 cls.addClassResourceCleanup(
593 waiters.wait_for_not_found,
594 cls.lb_mem_SGr_client.delete_security_group_rule,
595 cls.lb_mem_SGr_client.show_security_group_rule,
596 SGr['id'])
Adam Harwellcd72b562018-05-07 11:37:22 -0700597 # Create a security group rule to allow 22 (ssh)
598 SGr = cls.lb_mem_SGr_client.create_security_group_rule(
599 direction='ingress',
600 security_group_id=cls.lb_member_sec_group['id'],
601 protocol='tcp',
602 ethertype='IPv4',
603 port_range_min=22,
604 port_range_max=22)['security_group_rule']
605 cls.addClassResourceCleanup(
606 waiters.wait_for_not_found,
607 cls.lb_mem_SGr_client.delete_security_group_rule,
608 cls.lb_mem_SGr_client.show_security_group_rule,
609 SGr['id'])
610 if CONF.load_balancer.test_with_ipv6:
611 # Create a security group rule to allow 80-81 (test webservers)
612 SGr = cls.lb_mem_SGr_client.create_security_group_rule(
613 direction='ingress',
614 security_group_id=cls.lb_member_sec_group['id'],
615 protocol='tcp',
616 ethertype='IPv6',
617 port_range_min=80,
618 port_range_max=81)['security_group_rule']
619 cls.addClassResourceCleanup(
620 waiters.wait_for_not_found,
621 cls.lb_mem_SGr_client.delete_security_group_rule,
622 cls.lb_mem_SGr_client.show_security_group_rule,
623 SGr['id'])
Gregory Thiemonge29d17902019-04-30 15:06:17 +0200624 # Create a security group rule to allow UDP 80-81 (test
625 # webservers)
626 SGr = cls.lb_mem_SGr_client.create_security_group_rule(
627 direction='ingress',
628 security_group_id=cls.lb_member_sec_group['id'],
629 protocol='udp',
630 ethertype='IPv6',
631 port_range_min=80,
632 port_range_max=81)['security_group_rule']
633 cls.addClassResourceCleanup(
634 waiters.wait_for_not_found,
635 cls.lb_mem_SGr_client.delete_security_group_rule,
636 cls.lb_mem_SGr_client.show_security_group_rule,
637 SGr['id'])
Adam Harwellcd72b562018-05-07 11:37:22 -0700638 # Create a security group rule to allow 22 (ssh)
639 SGr = cls.lb_mem_SGr_client.create_security_group_rule(
640 direction='ingress',
641 security_group_id=cls.lb_member_sec_group['id'],
642 protocol='tcp',
643 ethertype='IPv6',
644 port_range_min=22,
645 port_range_max=22)['security_group_rule']
646 cls.addClassResourceCleanup(
647 waiters.wait_for_not_found,
648 cls.lb_mem_SGr_client.delete_security_group_rule,
649 cls.lb_mem_SGr_client.show_security_group_rule,
650 SGr['id'])
651
652 LOG.info('lb_member_sec_group: {}'.format(cls.lb_member_sec_group))
653
654 # Create webserver 1 instance
655 server_details = cls._create_webserver('lb_member_webserver1',
656 cls.lb_member_1_net)
657
658 cls.lb_member_webserver1 = server_details['server']
659 cls.webserver1_ip = server_details.get('ipv4_address')
660 cls.webserver1_ipv6 = server_details.get('ipv6_address')
661 cls.webserver1_public_ip = server_details['public_ipv4_address']
662
663 LOG.debug('Octavia Setup: lb_member_webserver1 = {}'.format(
664 cls.lb_member_webserver1[const.ID]))
665 LOG.debug('Octavia Setup: webserver1_ip = {}'.format(
666 cls.webserver1_ip))
667 LOG.debug('Octavia Setup: webserver1_ipv6 = {}'.format(
668 cls.webserver1_ipv6))
669 LOG.debug('Octavia Setup: webserver1_public_ip = {}'.format(
670 cls.webserver1_public_ip))
671
672 # Create webserver 2 instance
673 server_details = cls._create_webserver('lb_member_webserver2',
674 cls.lb_member_2_net)
675
676 cls.lb_member_webserver2 = server_details['server']
677 cls.webserver2_ip = server_details.get('ipv4_address')
678 cls.webserver2_ipv6 = server_details.get('ipv6_address')
679 cls.webserver2_public_ip = server_details['public_ipv4_address']
680
681 LOG.debug('Octavia Setup: lb_member_webserver2 = {}'.format(
682 cls.lb_member_webserver2[const.ID]))
683 LOG.debug('Octavia Setup: webserver2_ip = {}'.format(
684 cls.webserver2_ip))
685 LOG.debug('Octavia Setup: webserver2_ipv6 = {}'.format(
686 cls.webserver2_ipv6))
687 LOG.debug('Octavia Setup: webserver2_public_ip = {}'.format(
688 cls.webserver2_public_ip))
689
Michael Johnsonbf916df2018-10-17 10:59:28 -0700690 if CONF.load_balancer.test_with_ipv6:
691 # Enable the IPv6 nic in webserver 1
692 cls._enable_ipv6_nic_webserver(
693 cls.webserver1_public_ip, cls.lb_member_keypair['private_key'],
694 cls.webserver1_ipv6, cls.lb_member_1_subnet_prefix)
695
696 # Enable the IPv6 nic in webserver 2
697 cls._enable_ipv6_nic_webserver(
698 cls.webserver2_public_ip, cls.lb_member_keypair['private_key'],
699 cls.webserver2_ipv6, cls.lb_member_2_subnet_prefix)
700
Adam Harwellcd72b562018-05-07 11:37:22 -0700701 # Set up serving on webserver 1
702 cls._install_start_webserver(cls.webserver1_public_ip,
Adam Harwelle029af22018-05-24 17:13:28 -0700703 cls.lb_member_keypair['private_key'],
704 cls.webserver1_response)
Adam Harwellcd72b562018-05-07 11:37:22 -0700705
706 # Validate webserver 1
Adam Harwelle029af22018-05-24 17:13:28 -0700707 cls._validate_webserver(cls.webserver1_public_ip,
708 cls.webserver1_response)
Adam Harwellcd72b562018-05-07 11:37:22 -0700709
Gregory Thiemonge29d17902019-04-30 15:06:17 +0200710 # Validate udp server 1
711 cls._validate_udp_server(cls.webserver1_public_ip,
712 cls.webserver1_response)
713
Adam Harwellcd72b562018-05-07 11:37:22 -0700714 # Set up serving on webserver 2
715 cls._install_start_webserver(cls.webserver2_public_ip,
Adam Harwelle029af22018-05-24 17:13:28 -0700716 cls.lb_member_keypair['private_key'],
717 cls.webserver2_response)
Adam Harwellcd72b562018-05-07 11:37:22 -0700718
719 # Validate webserver 2
Adam Harwelle029af22018-05-24 17:13:28 -0700720 cls._validate_webserver(cls.webserver2_public_ip,
721 cls.webserver2_response)
Adam Harwellcd72b562018-05-07 11:37:22 -0700722
Gregory Thiemonge29d17902019-04-30 15:06:17 +0200723 # Validate udp server 2
724 cls._validate_udp_server(cls.webserver2_public_ip,
725 cls.webserver2_response)
726
Adam Harwellcd72b562018-05-07 11:37:22 -0700727 @classmethod
728 def _create_networks(cls):
729 super(LoadBalancerBaseTestWithCompute, cls)._create_networks()
Jude Cross986e3f52017-07-24 14:57:20 -0700730 # Create a router for the subnets (required for the floating IP)
731 router_name = data_utils.rand_name("lb_member_router")
732 result = cls.lb_mem_routers_client.create_router(
733 name=router_name, admin_state_up=True,
734 external_gateway_info=dict(
735 network_id=CONF.network.public_network_id))
736 cls.lb_member_router = result['router']
737 LOG.info('lb_member_router: {}'.format(cls.lb_member_router))
738 cls.addClassResourceCleanup(
739 waiters.wait_for_not_found,
740 cls.lb_mem_routers_client.delete_router,
741 cls.lb_mem_routers_client.show_router,
742 cls.lb_member_router['id'])
743
744 # Add VIP subnet to router
745 cls.lb_mem_routers_client.add_router_interface(
746 cls.lb_member_router['id'],
747 subnet_id=cls.lb_member_vip_subnet['id'])
748 cls.addClassResourceCleanup(
749 waiters.wait_for_not_found,
750 cls.lb_mem_routers_client.remove_router_interface,
751 cls.lb_mem_routers_client.remove_router_interface,
752 cls.lb_member_router['id'],
753 subnet_id=cls.lb_member_vip_subnet['id'])
754
755 # Add member subnet 1 to router
756 cls.lb_mem_routers_client.add_router_interface(
757 cls.lb_member_router['id'],
758 subnet_id=cls.lb_member_1_subnet['id'])
759 cls.addClassResourceCleanup(
760 waiters.wait_for_not_found,
Jude Cross986e3f52017-07-24 14:57:20 -0700761 cls.lb_mem_routers_client.remove_router_interface,
762 cls.lb_mem_routers_client.remove_router_interface,
763 cls.lb_member_router['id'], subnet_id=cls.lb_member_1_subnet['id'])
764
765 # Add member subnet 2 to router
766 cls.lb_mem_routers_client.add_router_interface(
767 cls.lb_member_router['id'],
768 subnet_id=cls.lb_member_2_subnet['id'])
769 cls.addClassResourceCleanup(
770 waiters.wait_for_not_found,
771 cls.lb_mem_routers_client.remove_router_interface,
772 cls.lb_mem_routers_client.remove_router_interface,
773 cls.lb_member_router['id'], subnet_id=cls.lb_member_2_subnet['id'])
774
775 @classmethod
776 def _create_webserver(cls, name, network):
777 """Creates a webserver with two ports.
778
779 webserver_details dictionary contains:
780 server - The compute server object
781 ipv4_address - The IPv4 address for the server (optional)
782 ipv6_address - The IPv6 address for the server (optional)
783 public_ipv4_address - The publicly accessible IPv4 address for the
784 server, this may be a floating IP (optional)
785
786 :param name: The name of the server to create.
787 :param network: The network to boot the server on.
788 :returns: webserver_details dictionary.
789 """
790 server_kwargs = {
791 'name': data_utils.rand_name(name),
792 'flavorRef': CONF.compute.flavor_ref,
793 'imageRef': CONF.compute.image_ref,
794 'key_name': cls.lb_member_keypair['name']}
795 if (CONF.load_balancer.enable_security_groups and
796 CONF.network_feature_enabled.port_security):
797 server_kwargs['security_groups'] = [
798 {'name': cls.lb_member_sec_group['name']}]
799 if not CONF.load_balancer.disable_boot_network:
800 server_kwargs['networks'] = [{'uuid': network['id']}]
801
802 # Replace the name for clouds that have limitations
803 if CONF.load_balancer.random_server_name_length:
804 r = random.SystemRandom()
805 server_kwargs['name'] = "m{}".format("".join(
806 [r.choice(string.ascii_uppercase + string.digits)
807 for _ in range(
808 CONF.load_balancer.random_server_name_length - 1)]
809 ))
810 if CONF.load_balancer.availability_zone:
811 server_kwargs['availability_zone'] = (
812 CONF.load_balancer.availability_zone)
813
814 server = cls.lb_mem_servers_client.create_server(
815 **server_kwargs)['server']
816 cls.addClassResourceCleanup(
817 waiters.wait_for_not_found,
818 cls.lb_mem_servers_client.delete_server,
819 cls.lb_mem_servers_client.show_server,
820 server['id'])
821 server = waiters.wait_for_status(
822 cls.lb_mem_servers_client.show_server,
823 server['id'], 'status', 'ACTIVE',
824 CONF.load_balancer.build_interval,
825 CONF.load_balancer.build_timeout,
826 root_tag='server')
827 webserver_details = {'server': server}
828 LOG.info('Created server: {}'.format(server))
829
830 addresses = server['addresses']
831 if CONF.load_balancer.disable_boot_network:
832 instance_network = addresses.values()[0]
833 else:
834 instance_network = addresses[network['name']]
835 for addr in instance_network:
836 if addr['version'] == 4:
837 webserver_details['ipv4_address'] = addr['addr']
838 if addr['version'] == 6:
839 webserver_details['ipv6_address'] = addr['addr']
840
841 if CONF.validation.connect_method == 'floating':
842 result = cls.lb_mem_ports_client.list_ports(
843 network_id=network['id'],
844 mac_address=instance_network[0]['OS-EXT-IPS-MAC:mac_addr'])
845 port_id = result['ports'][0]['id']
846 result = cls.lb_mem_float_ip_client.create_floatingip(
847 floating_network_id=CONF.network.public_network_id,
848 port_id=port_id)
849 floating_ip = result['floatingip']
850 LOG.info('webserver1_floating_ip: {}'.format(floating_ip))
851 cls.addClassResourceCleanup(
852 waiters.wait_for_not_found,
853 cls.lb_mem_float_ip_client.delete_floatingip,
854 cls.lb_mem_float_ip_client.show_floatingip,
855 floatingip_id=floating_ip['id'])
856 webserver_details['public_ipv4_address'] = (
857 floating_ip['floating_ip_address'])
858 else:
859 webserver_details['public_ipv4_address'] = (
860 instance_network[0]['addr'])
861
862 return webserver_details
863
864 @classmethod
Adam Harwellcd72b562018-05-07 11:37:22 -0700865 def _install_start_webserver(cls, ip_address, ssh_key, start_id):
866 local_file = pkg_resources.resource_filename(
Gregory Thiemonge29d17902019-04-30 15:06:17 +0200867 'octavia_tempest_plugin.contrib.test_server', 'test_server.bin')
868 dest_file = '/dev/shm/test_server.bin'
Adam Harwellcd72b562018-05-07 11:37:22 -0700869
870 linux_client = remote_client.RemoteClient(
871 ip_address, CONF.validation.image_ssh_user, pkey=ssh_key)
872 linux_client.validate_authentication()
873
874 with tempfile.NamedTemporaryFile() as key:
875 key.write(ssh_key.encode('utf-8'))
876 key.flush()
877 cmd = ("scp -v -o UserKnownHostsFile=/dev/null "
878 "-o StrictHostKeyChecking=no "
879 "-o ConnectTimeout={0} -o ConnectionAttempts={1} "
880 "-i {2} {3} {4}@{5}:{6}").format(
881 CONF.load_balancer.scp_connection_timeout,
882 CONF.load_balancer.scp_connection_attempts,
883 key.name, local_file, CONF.validation.image_ssh_user,
884 ip_address, dest_file)
885 args = shlex.split(cmd)
886 subprocess_args = {'stdout': subprocess.PIPE,
887 'stderr': subprocess.STDOUT,
888 'cwd': None}
889 proc = subprocess.Popen(args, **subprocess_args)
890 stdout, stderr = proc.communicate()
891 if proc.returncode != 0:
892 raise exceptions.CommandFailed(proc.returncode, cmd,
893 stdout, stderr)
Gregory Thiemongef72a8862019-08-06 17:25:42 +0200894
895 # Enabling memory overcommit allows to run golang static binaries
896 # compiled with a recent golang toolchain (>=1.11). Those binaries
897 # allocate a large amount of virtual memory at init time, and this
898 # allocation fails in tempest's nano flavor (64MB of RAM)
899 # (golang issue reported in https://github.com/golang/go/issues/28114,
900 # follow-up: https://github.com/golang/go/issues/28081)
901 # TODO(gthiemonge): Remove this call when golang issue is resolved.
902 linux_client.exec_command('sudo sh -c "echo 1 > '
903 '/proc/sys/vm/overcommit_memory"')
904
Adam Harwellcd72b562018-05-07 11:37:22 -0700905 linux_client.exec_command('sudo screen -d -m {0} -port 80 '
906 '-id {1}'.format(dest_file, start_id))
907 linux_client.exec_command('sudo screen -d -m {0} -port 81 '
908 '-id {1}'.format(dest_file, start_id + 1))
909
Michael Johnsonbf916df2018-10-17 10:59:28 -0700910 # Cirros does not configure the assigned IPv6 address by default
911 # so enable it manually like tempest does here:
912 # tempest/scenario/test_netowrk_v6.py turn_nic6_on()
913 @classmethod
914 def _enable_ipv6_nic_webserver(cls, ip_address, ssh_key,
915 ipv6_address, ipv6_prefix):
916 linux_client = remote_client.RemoteClient(
917 ip_address, CONF.validation.image_ssh_user, pkey=ssh_key)
918 linux_client.validate_authentication()
919
920 linux_client.exec_command('sudo ip address add {0}/{1} dev '
921 'eth0'.format(ipv6_address, ipv6_prefix))
922
Adam Harwellcd72b562018-05-07 11:37:22 -0700923 @classmethod
Jude Cross986e3f52017-07-24 14:57:20 -0700924 def _validate_webserver(cls, ip_address, start_id):
925 URL = 'http://{0}'.format(ip_address)
926 validators.validate_URL_response(URL, expected_body=str(start_id))
927 URL = 'http://{0}:81'.format(ip_address)
928 validators.validate_URL_response(URL, expected_body=str(start_id + 1))
929
Gregory Thiemonge29d17902019-04-30 15:06:17 +0200930 @classmethod
931 def _validate_udp_server(cls, ip_address, start_id):
932 res = cls._udp_request(ip_address, 80)
933 if res != str(start_id):
934 raise Exception("Response from test server doesn't match the "
935 "expected value ({0} != {1}).".format(
936 res, str(start_id)))
937
938 res = cls._udp_request(ip_address, 81)
939 if res != str(start_id + 1):
940 raise Exception("Response from test server doesn't match the "
941 "expected value ({0} != {1}).".format(
942 res, str(start_id + 1)))
943
944 @classmethod
945 def _udp_request(cls, vip_address, port=80, timeout=None):
946 if ipaddress.ip_address(vip_address).version == 6:
947 family = socket.AF_INET6
948 else:
949 family = socket.AF_INET
950
951 sock = socket.socket(family, socket.SOCK_DGRAM)
952
953 # Force the use of an incremental port number for source to avoid
954 # re-use of a previous source port that will affect the round-robin
955 # dispatch
956 while True:
957 port_number = cls.src_port_number
958 cls.src_port_number += 1
959 if cls.src_port_number >= SRC_PORT_NUMBER_MAX:
960 cls.src_port_number = SRC_PORT_NUMBER_MIN
961
962 # catch and skip already used ports on the host
963 try:
964 sock.bind(('', port_number))
965 except OSError as e:
966 # if error is 'Address already in use', try next port number
967 if e.errno != errno.EADDRINUSE:
968 raise e
969 else:
970 # successfully bind the socket
971 break
972
973 server_address = (vip_address, port)
974 data = b"data\n"
975
976 if timeout is not None:
977 sock.settimeout(timeout)
978
979 sock.sendto(data, server_address)
980 data, addr = sock.recvfrom(4096)
981
982 sock.close()
983
984 return data.decode('utf-8')
985
986 def _wait_for_lb_functional(self, vip_address, traffic_member_count,
987 protocol_port, protocol, verify):
988 if protocol != const.UDP:
989 session = requests.Session()
Adam Harwellcd72b562018-05-07 11:37:22 -0700990 start = time.time()
991
Gregory Thiemonge29d17902019-04-30 15:06:17 +0200992 response_counts = {}
993
994 # Send requests to the load balancer until at least
995 # "traffic_member_count" members have replied (ensure network
996 # connectivity is functional between the load balancer and the membesr)
Adam Harwellcd72b562018-05-07 11:37:22 -0700997 while time.time() - start < CONF.load_balancer.build_timeout:
998 try:
Gregory Thiemonge29d17902019-04-30 15:06:17 +0200999 if protocol != const.UDP:
1000 url = "{0}://{1}{2}{3}".format(
1001 protocol.lower(),
1002 vip_address,
1003 ':' if protocol_port else '',
1004 protocol_port or '')
1005 r = session.get(url, timeout=2, verify=verify)
1006 data = r.content
1007 else:
1008 data = self._udp_request(vip_address, port=protocol_port,
1009 timeout=2)
1010 if data in response_counts:
1011 response_counts[data] += 1
1012 else:
1013 response_counts[data] = 1
1014
1015 if traffic_member_count == len(response_counts):
1016 LOG.debug('Loadbalancer response totals: %s',
1017 response_counts)
1018 time.sleep(1)
1019 return
Adam Harwellcd72b562018-05-07 11:37:22 -07001020 except Exception:
1021 LOG.warning('Server is not passing initial traffic. Waiting.')
1022 time.sleep(1)
Gregory Thiemonge29d17902019-04-30 15:06:17 +02001023
1024 LOG.debug('Loadbalancer response totals: %s', response_counts)
Adam Harwellcd72b562018-05-07 11:37:22 -07001025 LOG.error('Server did not begin passing traffic within the timeout '
1026 'period. Failing test.')
1027 raise Exception()
1028
Maciej Józefczykb6df5f82019-12-10 10:12:30 +00001029 def _send_lb_request(self, handler, protocol, vip_address,
1030 verify, protocol_port, num=20):
Adam Harwellcd72b562018-05-07 11:37:22 -07001031 response_counts = {}
Gregory Thiemonge29d17902019-04-30 15:06:17 +02001032
Adam Harwellcd72b562018-05-07 11:37:22 -07001033 # Send a number requests to lb vip
Maciej Józefczykb6df5f82019-12-10 10:12:30 +00001034 for i in range(num):
Adam Harwellcd72b562018-05-07 11:37:22 -07001035 try:
Gregory Thiemonge29d17902019-04-30 15:06:17 +02001036 if protocol != const.UDP:
1037 url = "{0}://{1}{2}{3}".format(
1038 protocol.lower(),
1039 vip_address,
1040 ':' if protocol_port else '',
1041 protocol_port or '')
1042 r = handler.get(url, timeout=2, verify=verify)
1043 data = r.content
Adam Harwellcd72b562018-05-07 11:37:22 -07001044 else:
Gregory Thiemonge29d17902019-04-30 15:06:17 +02001045 data = self._udp_request(vip_address, port=protocol_port,
1046 timeout=2)
1047
1048 if data in response_counts:
1049 response_counts[data] += 1
1050 else:
1051 response_counts[data] = 1
1052
Adam Harwellcd72b562018-05-07 11:37:22 -07001053 except Exception:
1054 LOG.exception('Failed to send request to loadbalancer vip')
1055 raise Exception('Failed to connect to lb')
Adam Harwellcd72b562018-05-07 11:37:22 -07001056 LOG.debug('Loadbalancer response totals: %s', response_counts)
Maciej Józefczykb6df5f82019-12-10 10:12:30 +00001057 return response_counts
1058
1059 def _check_members_balanced_round_robin(
Gregory Thiemonge29d17902019-04-30 15:06:17 +02001060 self, vip_address, traffic_member_count=2, protocol=const.HTTP,
Maciej Józefczykb6df5f82019-12-10 10:12:30 +00001061 verify=True, protocol_port=80):
1062
1063 handler = requests.Session()
1064 response_counts = self._send_lb_request(
1065 handler, protocol, vip_address,
1066 verify, protocol_port)
1067
Adam Harwellcd72b562018-05-07 11:37:22 -07001068 # Ensure the correct number of members
Adam Harwell60ed9d92018-05-10 13:23:13 -07001069 self.assertEqual(traffic_member_count, len(response_counts))
Adam Harwellcd72b562018-05-07 11:37:22 -07001070
1071 # Ensure both members got the same number of responses
1072 self.assertEqual(1, len(set(response_counts.values())))
Adam Harwelle029af22018-05-24 17:13:28 -07001073
Maciej Józefczykb6df5f82019-12-10 10:12:30 +00001074 def _check_members_balanced_source_ip_port(
Gregory Thiemonge29d17902019-04-30 15:06:17 +02001075 self, vip_address, traffic_member_count=2, protocol=const.HTTP,
Maciej Józefczykb6df5f82019-12-10 10:12:30 +00001076 verify=True, protocol_port=80):
1077
1078 handler = requests
1079 response_counts = self._send_lb_request(
1080 handler, protocol, vip_address,
1081 verify, protocol_port)
1082 # Ensure the correct number of members
1083 self.assertEqual(traffic_member_count, len(response_counts))
1084
1085 if CONF.load_balancer.test_reuse_connection:
1086 handler = requests.Session()
1087 response_counts = self._send_lb_request(
1088 handler, protocol, vip_address,
1089 verify, protocol_port)
1090 # Ensure only one member answered
1091 self.assertEqual(1, len(response_counts))
1092
1093 def check_members_balanced(self, vip_address, traffic_member_count=2,
Gregory Thiemonge29d17902019-04-30 15:06:17 +02001094 protocol=const.HTTP, verify=True,
1095 protocol_port=80):
Maciej Józefczykb6df5f82019-12-10 10:12:30 +00001096
Gregory Thiemonge29d17902019-04-30 15:06:17 +02001097 if (ipaddress.ip_address(vip_address).version == 6 and
1098 protocol != const.UDP):
Maciej Józefczykb6df5f82019-12-10 10:12:30 +00001099 vip_address = '[{}]'.format(vip_address)
Gregory Thiemonge29d17902019-04-30 15:06:17 +02001100 self._wait_for_lb_functional(vip_address, traffic_member_count,
1101 protocol_port, protocol, verify)
Maciej Józefczykb6df5f82019-12-10 10:12:30 +00001102
1103 validate_func = '_check_members_balanced_%s' % self.lb_algorithm
1104 validate_func = getattr(self, validate_func.lower())
1105 validate_func(
1106 vip_address=vip_address,
1107 traffic_member_count=traffic_member_count,
1108 protocol=protocol,
1109 verify=verify,
1110 protocol_port=protocol_port)
1111
Adam Harwelle029af22018-05-24 17:13:28 -07001112 def assertConsistentResponse(self, response, url, method='GET', repeat=10,
1113 redirect=False, timeout=2, **kwargs):
1114 """Assert that a request to URL gets the expected response.
1115
1116 :param response: Expected response in format (status_code, content).
1117 :param url: The URL to request.
1118 :param method: The HTTP method to use (GET, POST, PUT, etc)
1119 :param repeat: How many times to test the response.
1120 :param data: Optional data to send in the request.
1121 :param headers: Optional headers to send in the request.
1122 :param cookies: Optional cookies to send in the request.
1123 :param redirect: Is the request a redirect? If true, assume the passed
1124 content should be the next URL in the chain.
Carlos Goncalvesc451ff92018-12-19 19:11:53 +01001125 :param timeout: Optional seconds to wait for the server to send data.
1126
Adam Harwelle029af22018-05-24 17:13:28 -07001127 :return: boolean success status
1128
1129 :raises: testtools.matchers.MismatchError
1130 """
1131 session = requests.Session()
1132 response_code, response_content = response
1133
1134 for i in range(0, repeat):
1135 req = session.request(method, url, allow_redirects=not redirect,
1136 timeout=timeout, **kwargs)
1137 if response_code:
1138 self.assertEqual(response_code, req.status_code)
1139 if redirect:
1140 self.assertTrue(req.is_redirect)
Carlos Goncalvesc451ff92018-12-19 19:11:53 +01001141 self.assertEqual(response_content,
1142 session.get_redirect_target(req))
Adam Harwelle029af22018-05-24 17:13:28 -07001143 elif response_content:
1144 self.assertEqual(six.text_type(response_content), req.text)