blob: bd1a22512e2b10680d78aef25c86aa995fe1c2b1 [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])
Carlos Goncalvesbb238552020-01-15 10:10:55 +0000506 if ip_version == 6:
507 lb_kwargs[const.VIP_ADDRESS] = lb_vip_address
Adam Harwellcd72b562018-05-07 11:37:22 -0700508 else:
509 lb_kwargs[const.VIP_NETWORK_ID] = cls.lb_member_vip_net[const.ID]
510 lb_kwargs[const.VIP_SUBNET_ID] = None
511
512
513class LoadBalancerBaseTestWithCompute(LoadBalancerBaseTest):
514 @classmethod
515 def resource_setup(cls):
516 super(LoadBalancerBaseTestWithCompute, cls).resource_setup()
517 # If validation is disabled in this cloud, we won't be able to
518 # start the webservers, so don't even boot them.
519 if not CONF.validation.run_validation:
520 return
521
522 # Create a keypair for the webservers
523 keypair_name = data_utils.rand_name('lb_member_keypair')
524 result = cls.lb_mem_keypairs_client.create_keypair(
525 name=keypair_name)
526 cls.lb_member_keypair = result['keypair']
527 LOG.info('lb_member_keypair: {}'.format(cls.lb_member_keypair))
528 cls.addClassResourceCleanup(
529 waiters.wait_for_not_found,
530 cls.lb_mem_keypairs_client.delete_keypair,
531 cls.lb_mem_keypairs_client.show_keypair,
532 keypair_name)
533
534 if (CONF.load_balancer.enable_security_groups and
535 CONF.network_feature_enabled.port_security):
536 # Set up the security group for the webservers
537 SG_name = data_utils.rand_name('lb_member_SG')
538 cls.lb_member_sec_group = (
539 cls.lb_mem_SG_client.create_security_group(
540 name=SG_name)['security_group'])
541 cls.addClassResourceCleanup(
542 waiters.wait_for_not_found,
543 cls.lb_mem_SG_client.delete_security_group,
544 cls.lb_mem_SG_client.show_security_group,
545 cls.lb_member_sec_group['id'])
546
547 # Create a security group rule to allow 80-81 (test webservers)
548 SGr = cls.lb_mem_SGr_client.create_security_group_rule(
549 direction='ingress',
550 security_group_id=cls.lb_member_sec_group['id'],
551 protocol='tcp',
552 ethertype='IPv4',
553 port_range_min=80,
554 port_range_max=81)['security_group_rule']
555 cls.addClassResourceCleanup(
556 waiters.wait_for_not_found,
557 cls.lb_mem_SGr_client.delete_security_group_rule,
558 cls.lb_mem_SGr_client.show_security_group_rule,
559 SGr['id'])
Gregory Thiemonge29d17902019-04-30 15:06:17 +0200560 # Create a security group rule to allow UDP 80-81 (test webservers)
561 SGr = cls.lb_mem_SGr_client.create_security_group_rule(
562 direction='ingress',
563 security_group_id=cls.lb_member_sec_group['id'],
564 protocol='udp',
565 ethertype='IPv4',
566 port_range_min=80,
567 port_range_max=81)['security_group_rule']
568 cls.addClassResourceCleanup(
569 waiters.wait_for_not_found,
570 cls.lb_mem_SGr_client.delete_security_group_rule,
571 cls.lb_mem_SGr_client.show_security_group_rule,
572 SGr['id'])
573 # Create a security group rule to allow UDP 9999 (test webservers)
574 # Port 9999 is used to illustrate health monitor ERRORs on closed
575 # ports.
576 SGr = cls.lb_mem_SGr_client.create_security_group_rule(
577 direction='ingress',
578 security_group_id=cls.lb_member_sec_group['id'],
579 protocol='udp',
580 ethertype='IPv4',
581 port_range_min=9999,
582 port_range_max=9999)['security_group_rule']
583 cls.addClassResourceCleanup(
584 waiters.wait_for_not_found,
585 cls.lb_mem_SGr_client.delete_security_group_rule,
586 cls.lb_mem_SGr_client.show_security_group_rule,
587 SGr['id'])
Adam Harwellcd72b562018-05-07 11:37:22 -0700588 # Create a security group rule to allow 22 (ssh)
589 SGr = cls.lb_mem_SGr_client.create_security_group_rule(
590 direction='ingress',
591 security_group_id=cls.lb_member_sec_group['id'],
592 protocol='tcp',
593 ethertype='IPv4',
594 port_range_min=22,
595 port_range_max=22)['security_group_rule']
596 cls.addClassResourceCleanup(
597 waiters.wait_for_not_found,
598 cls.lb_mem_SGr_client.delete_security_group_rule,
599 cls.lb_mem_SGr_client.show_security_group_rule,
600 SGr['id'])
601 if CONF.load_balancer.test_with_ipv6:
602 # Create a security group rule to allow 80-81 (test webservers)
603 SGr = cls.lb_mem_SGr_client.create_security_group_rule(
604 direction='ingress',
605 security_group_id=cls.lb_member_sec_group['id'],
606 protocol='tcp',
607 ethertype='IPv6',
608 port_range_min=80,
609 port_range_max=81)['security_group_rule']
610 cls.addClassResourceCleanup(
611 waiters.wait_for_not_found,
612 cls.lb_mem_SGr_client.delete_security_group_rule,
613 cls.lb_mem_SGr_client.show_security_group_rule,
614 SGr['id'])
Gregory Thiemonge29d17902019-04-30 15:06:17 +0200615 # Create a security group rule to allow UDP 80-81 (test
616 # webservers)
617 SGr = cls.lb_mem_SGr_client.create_security_group_rule(
618 direction='ingress',
619 security_group_id=cls.lb_member_sec_group['id'],
620 protocol='udp',
621 ethertype='IPv6',
622 port_range_min=80,
623 port_range_max=81)['security_group_rule']
624 cls.addClassResourceCleanup(
625 waiters.wait_for_not_found,
626 cls.lb_mem_SGr_client.delete_security_group_rule,
627 cls.lb_mem_SGr_client.show_security_group_rule,
628 SGr['id'])
Adam Harwellcd72b562018-05-07 11:37:22 -0700629 # Create a security group rule to allow 22 (ssh)
630 SGr = cls.lb_mem_SGr_client.create_security_group_rule(
631 direction='ingress',
632 security_group_id=cls.lb_member_sec_group['id'],
633 protocol='tcp',
634 ethertype='IPv6',
635 port_range_min=22,
636 port_range_max=22)['security_group_rule']
637 cls.addClassResourceCleanup(
638 waiters.wait_for_not_found,
639 cls.lb_mem_SGr_client.delete_security_group_rule,
640 cls.lb_mem_SGr_client.show_security_group_rule,
641 SGr['id'])
642
643 LOG.info('lb_member_sec_group: {}'.format(cls.lb_member_sec_group))
644
645 # Create webserver 1 instance
646 server_details = cls._create_webserver('lb_member_webserver1',
647 cls.lb_member_1_net)
648
649 cls.lb_member_webserver1 = server_details['server']
650 cls.webserver1_ip = server_details.get('ipv4_address')
651 cls.webserver1_ipv6 = server_details.get('ipv6_address')
652 cls.webserver1_public_ip = server_details['public_ipv4_address']
653
654 LOG.debug('Octavia Setup: lb_member_webserver1 = {}'.format(
655 cls.lb_member_webserver1[const.ID]))
656 LOG.debug('Octavia Setup: webserver1_ip = {}'.format(
657 cls.webserver1_ip))
658 LOG.debug('Octavia Setup: webserver1_ipv6 = {}'.format(
659 cls.webserver1_ipv6))
660 LOG.debug('Octavia Setup: webserver1_public_ip = {}'.format(
661 cls.webserver1_public_ip))
662
663 # Create webserver 2 instance
664 server_details = cls._create_webserver('lb_member_webserver2',
665 cls.lb_member_2_net)
666
667 cls.lb_member_webserver2 = server_details['server']
668 cls.webserver2_ip = server_details.get('ipv4_address')
669 cls.webserver2_ipv6 = server_details.get('ipv6_address')
670 cls.webserver2_public_ip = server_details['public_ipv4_address']
671
672 LOG.debug('Octavia Setup: lb_member_webserver2 = {}'.format(
673 cls.lb_member_webserver2[const.ID]))
674 LOG.debug('Octavia Setup: webserver2_ip = {}'.format(
675 cls.webserver2_ip))
676 LOG.debug('Octavia Setup: webserver2_ipv6 = {}'.format(
677 cls.webserver2_ipv6))
678 LOG.debug('Octavia Setup: webserver2_public_ip = {}'.format(
679 cls.webserver2_public_ip))
680
Michael Johnsonbf916df2018-10-17 10:59:28 -0700681 if CONF.load_balancer.test_with_ipv6:
682 # Enable the IPv6 nic in webserver 1
683 cls._enable_ipv6_nic_webserver(
684 cls.webserver1_public_ip, cls.lb_member_keypair['private_key'],
685 cls.webserver1_ipv6, cls.lb_member_1_subnet_prefix)
686
687 # Enable the IPv6 nic in webserver 2
688 cls._enable_ipv6_nic_webserver(
689 cls.webserver2_public_ip, cls.lb_member_keypair['private_key'],
690 cls.webserver2_ipv6, cls.lb_member_2_subnet_prefix)
691
Adam Harwellcd72b562018-05-07 11:37:22 -0700692 # Set up serving on webserver 1
693 cls._install_start_webserver(cls.webserver1_public_ip,
Adam Harwelle029af22018-05-24 17:13:28 -0700694 cls.lb_member_keypair['private_key'],
695 cls.webserver1_response)
Adam Harwellcd72b562018-05-07 11:37:22 -0700696
697 # Validate webserver 1
Adam Harwelle029af22018-05-24 17:13:28 -0700698 cls._validate_webserver(cls.webserver1_public_ip,
699 cls.webserver1_response)
Adam Harwellcd72b562018-05-07 11:37:22 -0700700
Gregory Thiemonge29d17902019-04-30 15:06:17 +0200701 # Validate udp server 1
702 cls._validate_udp_server(cls.webserver1_public_ip,
703 cls.webserver1_response)
704
Adam Harwellcd72b562018-05-07 11:37:22 -0700705 # Set up serving on webserver 2
706 cls._install_start_webserver(cls.webserver2_public_ip,
Adam Harwelle029af22018-05-24 17:13:28 -0700707 cls.lb_member_keypair['private_key'],
708 cls.webserver2_response)
Adam Harwellcd72b562018-05-07 11:37:22 -0700709
710 # Validate webserver 2
Adam Harwelle029af22018-05-24 17:13:28 -0700711 cls._validate_webserver(cls.webserver2_public_ip,
712 cls.webserver2_response)
Adam Harwellcd72b562018-05-07 11:37:22 -0700713
Gregory Thiemonge29d17902019-04-30 15:06:17 +0200714 # Validate udp server 2
715 cls._validate_udp_server(cls.webserver2_public_ip,
716 cls.webserver2_response)
717
Adam Harwellcd72b562018-05-07 11:37:22 -0700718 @classmethod
719 def _create_networks(cls):
720 super(LoadBalancerBaseTestWithCompute, cls)._create_networks()
Jude Cross986e3f52017-07-24 14:57:20 -0700721 # Create a router for the subnets (required for the floating IP)
722 router_name = data_utils.rand_name("lb_member_router")
723 result = cls.lb_mem_routers_client.create_router(
724 name=router_name, admin_state_up=True,
725 external_gateway_info=dict(
726 network_id=CONF.network.public_network_id))
727 cls.lb_member_router = result['router']
728 LOG.info('lb_member_router: {}'.format(cls.lb_member_router))
729 cls.addClassResourceCleanup(
730 waiters.wait_for_not_found,
731 cls.lb_mem_routers_client.delete_router,
732 cls.lb_mem_routers_client.show_router,
733 cls.lb_member_router['id'])
734
735 # Add VIP subnet to router
736 cls.lb_mem_routers_client.add_router_interface(
737 cls.lb_member_router['id'],
738 subnet_id=cls.lb_member_vip_subnet['id'])
739 cls.addClassResourceCleanup(
740 waiters.wait_for_not_found,
741 cls.lb_mem_routers_client.remove_router_interface,
742 cls.lb_mem_routers_client.remove_router_interface,
743 cls.lb_member_router['id'],
744 subnet_id=cls.lb_member_vip_subnet['id'])
745
746 # Add member subnet 1 to router
747 cls.lb_mem_routers_client.add_router_interface(
748 cls.lb_member_router['id'],
749 subnet_id=cls.lb_member_1_subnet['id'])
750 cls.addClassResourceCleanup(
751 waiters.wait_for_not_found,
Jude Cross986e3f52017-07-24 14:57:20 -0700752 cls.lb_mem_routers_client.remove_router_interface,
753 cls.lb_mem_routers_client.remove_router_interface,
754 cls.lb_member_router['id'], subnet_id=cls.lb_member_1_subnet['id'])
755
756 # Add member subnet 2 to router
757 cls.lb_mem_routers_client.add_router_interface(
758 cls.lb_member_router['id'],
759 subnet_id=cls.lb_member_2_subnet['id'])
760 cls.addClassResourceCleanup(
761 waiters.wait_for_not_found,
762 cls.lb_mem_routers_client.remove_router_interface,
763 cls.lb_mem_routers_client.remove_router_interface,
764 cls.lb_member_router['id'], subnet_id=cls.lb_member_2_subnet['id'])
765
766 @classmethod
767 def _create_webserver(cls, name, network):
768 """Creates a webserver with two ports.
769
770 webserver_details dictionary contains:
771 server - The compute server object
772 ipv4_address - The IPv4 address for the server (optional)
773 ipv6_address - The IPv6 address for the server (optional)
774 public_ipv4_address - The publicly accessible IPv4 address for the
775 server, this may be a floating IP (optional)
776
777 :param name: The name of the server to create.
778 :param network: The network to boot the server on.
779 :returns: webserver_details dictionary.
780 """
781 server_kwargs = {
782 'name': data_utils.rand_name(name),
783 'flavorRef': CONF.compute.flavor_ref,
784 'imageRef': CONF.compute.image_ref,
785 'key_name': cls.lb_member_keypair['name']}
786 if (CONF.load_balancer.enable_security_groups and
787 CONF.network_feature_enabled.port_security):
788 server_kwargs['security_groups'] = [
789 {'name': cls.lb_member_sec_group['name']}]
790 if not CONF.load_balancer.disable_boot_network:
791 server_kwargs['networks'] = [{'uuid': network['id']}]
792
793 # Replace the name for clouds that have limitations
794 if CONF.load_balancer.random_server_name_length:
795 r = random.SystemRandom()
796 server_kwargs['name'] = "m{}".format("".join(
797 [r.choice(string.ascii_uppercase + string.digits)
798 for _ in range(
799 CONF.load_balancer.random_server_name_length - 1)]
800 ))
801 if CONF.load_balancer.availability_zone:
802 server_kwargs['availability_zone'] = (
803 CONF.load_balancer.availability_zone)
804
805 server = cls.lb_mem_servers_client.create_server(
806 **server_kwargs)['server']
807 cls.addClassResourceCleanup(
808 waiters.wait_for_not_found,
809 cls.lb_mem_servers_client.delete_server,
810 cls.lb_mem_servers_client.show_server,
811 server['id'])
812 server = waiters.wait_for_status(
813 cls.lb_mem_servers_client.show_server,
814 server['id'], 'status', 'ACTIVE',
815 CONF.load_balancer.build_interval,
816 CONF.load_balancer.build_timeout,
817 root_tag='server')
818 webserver_details = {'server': server}
819 LOG.info('Created server: {}'.format(server))
820
821 addresses = server['addresses']
822 if CONF.load_balancer.disable_boot_network:
823 instance_network = addresses.values()[0]
824 else:
825 instance_network = addresses[network['name']]
826 for addr in instance_network:
827 if addr['version'] == 4:
828 webserver_details['ipv4_address'] = addr['addr']
829 if addr['version'] == 6:
830 webserver_details['ipv6_address'] = addr['addr']
831
832 if CONF.validation.connect_method == 'floating':
833 result = cls.lb_mem_ports_client.list_ports(
834 network_id=network['id'],
835 mac_address=instance_network[0]['OS-EXT-IPS-MAC:mac_addr'])
836 port_id = result['ports'][0]['id']
837 result = cls.lb_mem_float_ip_client.create_floatingip(
838 floating_network_id=CONF.network.public_network_id,
839 port_id=port_id)
840 floating_ip = result['floatingip']
841 LOG.info('webserver1_floating_ip: {}'.format(floating_ip))
842 cls.addClassResourceCleanup(
843 waiters.wait_for_not_found,
844 cls.lb_mem_float_ip_client.delete_floatingip,
845 cls.lb_mem_float_ip_client.show_floatingip,
846 floatingip_id=floating_ip['id'])
847 webserver_details['public_ipv4_address'] = (
848 floating_ip['floating_ip_address'])
849 else:
850 webserver_details['public_ipv4_address'] = (
851 instance_network[0]['addr'])
852
853 return webserver_details
854
855 @classmethod
Adam Harwellcd72b562018-05-07 11:37:22 -0700856 def _install_start_webserver(cls, ip_address, ssh_key, start_id):
857 local_file = pkg_resources.resource_filename(
Gregory Thiemonge29d17902019-04-30 15:06:17 +0200858 'octavia_tempest_plugin.contrib.test_server', 'test_server.bin')
859 dest_file = '/dev/shm/test_server.bin'
Adam Harwellcd72b562018-05-07 11:37:22 -0700860
861 linux_client = remote_client.RemoteClient(
862 ip_address, CONF.validation.image_ssh_user, pkey=ssh_key)
863 linux_client.validate_authentication()
864
865 with tempfile.NamedTemporaryFile() as key:
866 key.write(ssh_key.encode('utf-8'))
867 key.flush()
868 cmd = ("scp -v -o UserKnownHostsFile=/dev/null "
869 "-o StrictHostKeyChecking=no "
870 "-o ConnectTimeout={0} -o ConnectionAttempts={1} "
871 "-i {2} {3} {4}@{5}:{6}").format(
872 CONF.load_balancer.scp_connection_timeout,
873 CONF.load_balancer.scp_connection_attempts,
874 key.name, local_file, CONF.validation.image_ssh_user,
875 ip_address, dest_file)
876 args = shlex.split(cmd)
877 subprocess_args = {'stdout': subprocess.PIPE,
878 'stderr': subprocess.STDOUT,
879 'cwd': None}
880 proc = subprocess.Popen(args, **subprocess_args)
881 stdout, stderr = proc.communicate()
882 if proc.returncode != 0:
883 raise exceptions.CommandFailed(proc.returncode, cmd,
884 stdout, stderr)
Gregory Thiemongef72a8862019-08-06 17:25:42 +0200885
886 # Enabling memory overcommit allows to run golang static binaries
887 # compiled with a recent golang toolchain (>=1.11). Those binaries
888 # allocate a large amount of virtual memory at init time, and this
889 # allocation fails in tempest's nano flavor (64MB of RAM)
890 # (golang issue reported in https://github.com/golang/go/issues/28114,
891 # follow-up: https://github.com/golang/go/issues/28081)
892 # TODO(gthiemonge): Remove this call when golang issue is resolved.
893 linux_client.exec_command('sudo sh -c "echo 1 > '
894 '/proc/sys/vm/overcommit_memory"')
895
Adam Harwellcd72b562018-05-07 11:37:22 -0700896 linux_client.exec_command('sudo screen -d -m {0} -port 80 '
897 '-id {1}'.format(dest_file, start_id))
898 linux_client.exec_command('sudo screen -d -m {0} -port 81 '
899 '-id {1}'.format(dest_file, start_id + 1))
900
Michael Johnsonbf916df2018-10-17 10:59:28 -0700901 # Cirros does not configure the assigned IPv6 address by default
902 # so enable it manually like tempest does here:
903 # tempest/scenario/test_netowrk_v6.py turn_nic6_on()
904 @classmethod
905 def _enable_ipv6_nic_webserver(cls, ip_address, ssh_key,
906 ipv6_address, ipv6_prefix):
907 linux_client = remote_client.RemoteClient(
908 ip_address, CONF.validation.image_ssh_user, pkey=ssh_key)
909 linux_client.validate_authentication()
910
911 linux_client.exec_command('sudo ip address add {0}/{1} dev '
912 'eth0'.format(ipv6_address, ipv6_prefix))
913
Adam Harwellcd72b562018-05-07 11:37:22 -0700914 @classmethod
Jude Cross986e3f52017-07-24 14:57:20 -0700915 def _validate_webserver(cls, ip_address, start_id):
916 URL = 'http://{0}'.format(ip_address)
917 validators.validate_URL_response(URL, expected_body=str(start_id))
918 URL = 'http://{0}:81'.format(ip_address)
919 validators.validate_URL_response(URL, expected_body=str(start_id + 1))
920
Gregory Thiemonge29d17902019-04-30 15:06:17 +0200921 @classmethod
922 def _validate_udp_server(cls, ip_address, start_id):
923 res = cls._udp_request(ip_address, 80)
924 if res != str(start_id):
925 raise Exception("Response from test server doesn't match the "
926 "expected value ({0} != {1}).".format(
927 res, str(start_id)))
928
929 res = cls._udp_request(ip_address, 81)
930 if res != str(start_id + 1):
931 raise Exception("Response from test server doesn't match the "
932 "expected value ({0} != {1}).".format(
933 res, str(start_id + 1)))
934
935 @classmethod
936 def _udp_request(cls, vip_address, port=80, timeout=None):
937 if ipaddress.ip_address(vip_address).version == 6:
938 family = socket.AF_INET6
939 else:
940 family = socket.AF_INET
941
942 sock = socket.socket(family, socket.SOCK_DGRAM)
943
944 # Force the use of an incremental port number for source to avoid
945 # re-use of a previous source port that will affect the round-robin
946 # dispatch
947 while True:
948 port_number = cls.src_port_number
949 cls.src_port_number += 1
950 if cls.src_port_number >= SRC_PORT_NUMBER_MAX:
951 cls.src_port_number = SRC_PORT_NUMBER_MIN
952
953 # catch and skip already used ports on the host
954 try:
955 sock.bind(('', port_number))
956 except OSError as e:
957 # if error is 'Address already in use', try next port number
958 if e.errno != errno.EADDRINUSE:
959 raise e
960 else:
961 # successfully bind the socket
962 break
963
964 server_address = (vip_address, port)
965 data = b"data\n"
966
967 if timeout is not None:
968 sock.settimeout(timeout)
969
970 sock.sendto(data, server_address)
971 data, addr = sock.recvfrom(4096)
972
973 sock.close()
974
975 return data.decode('utf-8')
976
977 def _wait_for_lb_functional(self, vip_address, traffic_member_count,
978 protocol_port, protocol, verify):
979 if protocol != const.UDP:
980 session = requests.Session()
Adam Harwellcd72b562018-05-07 11:37:22 -0700981 start = time.time()
982
Gregory Thiemonge29d17902019-04-30 15:06:17 +0200983 response_counts = {}
984
985 # Send requests to the load balancer until at least
986 # "traffic_member_count" members have replied (ensure network
987 # connectivity is functional between the load balancer and the membesr)
Adam Harwellcd72b562018-05-07 11:37:22 -0700988 while time.time() - start < CONF.load_balancer.build_timeout:
989 try:
Gregory Thiemonge29d17902019-04-30 15:06:17 +0200990 if protocol != const.UDP:
991 url = "{0}://{1}{2}{3}".format(
992 protocol.lower(),
993 vip_address,
994 ':' if protocol_port else '',
995 protocol_port or '')
996 r = session.get(url, timeout=2, verify=verify)
997 data = r.content
998 else:
999 data = self._udp_request(vip_address, port=protocol_port,
1000 timeout=2)
1001 if data in response_counts:
1002 response_counts[data] += 1
1003 else:
1004 response_counts[data] = 1
1005
1006 if traffic_member_count == len(response_counts):
1007 LOG.debug('Loadbalancer response totals: %s',
1008 response_counts)
1009 time.sleep(1)
1010 return
Adam Harwellcd72b562018-05-07 11:37:22 -07001011 except Exception:
1012 LOG.warning('Server is not passing initial traffic. Waiting.')
1013 time.sleep(1)
Gregory Thiemonge29d17902019-04-30 15:06:17 +02001014
1015 LOG.debug('Loadbalancer response totals: %s', response_counts)
Adam Harwellcd72b562018-05-07 11:37:22 -07001016 LOG.error('Server did not begin passing traffic within the timeout '
1017 'period. Failing test.')
1018 raise Exception()
1019
Maciej Józefczykb6df5f82019-12-10 10:12:30 +00001020 def _send_lb_request(self, handler, protocol, vip_address,
1021 verify, protocol_port, num=20):
Adam Harwellcd72b562018-05-07 11:37:22 -07001022 response_counts = {}
Gregory Thiemonge29d17902019-04-30 15:06:17 +02001023
Adam Harwellcd72b562018-05-07 11:37:22 -07001024 # Send a number requests to lb vip
Maciej Józefczykb6df5f82019-12-10 10:12:30 +00001025 for i in range(num):
Adam Harwellcd72b562018-05-07 11:37:22 -07001026 try:
Gregory Thiemonge29d17902019-04-30 15:06:17 +02001027 if protocol != const.UDP:
1028 url = "{0}://{1}{2}{3}".format(
1029 protocol.lower(),
1030 vip_address,
1031 ':' if protocol_port else '',
1032 protocol_port or '')
1033 r = handler.get(url, timeout=2, verify=verify)
1034 data = r.content
Adam Harwellcd72b562018-05-07 11:37:22 -07001035 else:
Gregory Thiemonge29d17902019-04-30 15:06:17 +02001036 data = self._udp_request(vip_address, port=protocol_port,
1037 timeout=2)
1038
1039 if data in response_counts:
1040 response_counts[data] += 1
1041 else:
1042 response_counts[data] = 1
1043
Adam Harwellcd72b562018-05-07 11:37:22 -07001044 except Exception:
1045 LOG.exception('Failed to send request to loadbalancer vip')
1046 raise Exception('Failed to connect to lb')
Adam Harwellcd72b562018-05-07 11:37:22 -07001047 LOG.debug('Loadbalancer response totals: %s', response_counts)
Maciej Józefczykb6df5f82019-12-10 10:12:30 +00001048 return response_counts
1049
1050 def _check_members_balanced_round_robin(
Gregory Thiemonge29d17902019-04-30 15:06:17 +02001051 self, vip_address, traffic_member_count=2, protocol=const.HTTP,
Maciej Józefczykb6df5f82019-12-10 10:12:30 +00001052 verify=True, protocol_port=80):
1053
1054 handler = requests.Session()
1055 response_counts = self._send_lb_request(
1056 handler, protocol, vip_address,
1057 verify, protocol_port)
1058
Adam Harwellcd72b562018-05-07 11:37:22 -07001059 # Ensure the correct number of members
Adam Harwell60ed9d92018-05-10 13:23:13 -07001060 self.assertEqual(traffic_member_count, len(response_counts))
Adam Harwellcd72b562018-05-07 11:37:22 -07001061
1062 # Ensure both members got the same number of responses
1063 self.assertEqual(1, len(set(response_counts.values())))
Adam Harwelle029af22018-05-24 17:13:28 -07001064
Maciej Józefczykb6df5f82019-12-10 10:12:30 +00001065 def _check_members_balanced_source_ip_port(
Gregory Thiemonge29d17902019-04-30 15:06:17 +02001066 self, vip_address, traffic_member_count=2, protocol=const.HTTP,
Maciej Józefczykb6df5f82019-12-10 10:12:30 +00001067 verify=True, protocol_port=80):
1068
1069 handler = requests
1070 response_counts = self._send_lb_request(
1071 handler, protocol, vip_address,
1072 verify, protocol_port)
1073 # Ensure the correct number of members
1074 self.assertEqual(traffic_member_count, len(response_counts))
1075
1076 if CONF.load_balancer.test_reuse_connection:
1077 handler = requests.Session()
1078 response_counts = self._send_lb_request(
1079 handler, protocol, vip_address,
1080 verify, protocol_port)
1081 # Ensure only one member answered
1082 self.assertEqual(1, len(response_counts))
1083
1084 def check_members_balanced(self, vip_address, traffic_member_count=2,
Gregory Thiemonge29d17902019-04-30 15:06:17 +02001085 protocol=const.HTTP, verify=True,
1086 protocol_port=80):
Maciej Józefczykb6df5f82019-12-10 10:12:30 +00001087
Gregory Thiemonge29d17902019-04-30 15:06:17 +02001088 if (ipaddress.ip_address(vip_address).version == 6 and
1089 protocol != const.UDP):
Maciej Józefczykb6df5f82019-12-10 10:12:30 +00001090 vip_address = '[{}]'.format(vip_address)
Gregory Thiemonge29d17902019-04-30 15:06:17 +02001091 self._wait_for_lb_functional(vip_address, traffic_member_count,
1092 protocol_port, protocol, verify)
Maciej Józefczykb6df5f82019-12-10 10:12:30 +00001093
1094 validate_func = '_check_members_balanced_%s' % self.lb_algorithm
1095 validate_func = getattr(self, validate_func.lower())
1096 validate_func(
1097 vip_address=vip_address,
1098 traffic_member_count=traffic_member_count,
1099 protocol=protocol,
1100 verify=verify,
1101 protocol_port=protocol_port)
1102
Adam Harwelle029af22018-05-24 17:13:28 -07001103 def assertConsistentResponse(self, response, url, method='GET', repeat=10,
Carlos Goncalvesbb238552020-01-15 10:10:55 +00001104 redirect=False, timeout=2,
1105 conn_error=False, **kwargs):
Adam Harwelle029af22018-05-24 17:13:28 -07001106 """Assert that a request to URL gets the expected response.
1107
1108 :param response: Expected response in format (status_code, content).
1109 :param url: The URL to request.
1110 :param method: The HTTP method to use (GET, POST, PUT, etc)
1111 :param repeat: How many times to test the response.
1112 :param data: Optional data to send in the request.
1113 :param headers: Optional headers to send in the request.
1114 :param cookies: Optional cookies to send in the request.
1115 :param redirect: Is the request a redirect? If true, assume the passed
1116 content should be the next URL in the chain.
Carlos Goncalvesc451ff92018-12-19 19:11:53 +01001117 :param timeout: Optional seconds to wait for the server to send data.
Carlos Goncalvesbb238552020-01-15 10:10:55 +00001118 :param conn_error: Optional Expect a connection error?
Carlos Goncalvesc451ff92018-12-19 19:11:53 +01001119
Adam Harwelle029af22018-05-24 17:13:28 -07001120 :return: boolean success status
1121
1122 :raises: testtools.matchers.MismatchError
1123 """
1124 session = requests.Session()
1125 response_code, response_content = response
1126
1127 for i in range(0, repeat):
Carlos Goncalvesbb238552020-01-15 10:10:55 +00001128 if conn_error:
1129 self.assertRaises(
1130 requests.exceptions.ConnectionError, session.request,
1131 method, url, allow_redirects=not redirect, timeout=timeout,
1132 **kwargs)
1133 continue
1134
Adam Harwelle029af22018-05-24 17:13:28 -07001135 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)