blob: d2c401444915f144057d9d25c21862727391b63b [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
Gregory Thiemonge29d17902019-04-30 15:06:17 +020021import socket
Jude Cross986e3f52017-07-24 14:57:20 -070022import string
23import subprocess
24import tempfile
Adam Harwellcd72b562018-05-07 11:37:22 -070025import time
Jude Cross986e3f52017-07-24 14:57:20 -070026
27from oslo_log import log as logging
28from oslo_utils import uuidutils
29from tempest import config
30from tempest.lib.common.utils import data_utils
31from tempest.lib.common.utils.linux import remote_client
Jude Cross986e3f52017-07-24 14:57:20 -070032from tempest.lib import exceptions
33from tempest import test
Michael Johnson04dc5cb2019-01-20 11:03:50 -080034import tenacity
Jude Cross986e3f52017-07-24 14:57:20 -070035
36from octavia_tempest_plugin import clients
37from octavia_tempest_plugin.common import constants as const
38from octavia_tempest_plugin.tests import validators
39from octavia_tempest_plugin.tests import waiters
40
41CONF = config.CONF
42LOG = logging.getLogger(__name__)
43
Michael Johnson04dc5cb2019-01-20 11:03:50 -080044RETRY_ATTEMPTS = 15
45RETRY_INITIAL_DELAY = 1
46RETRY_BACKOFF = 1
47RETRY_MAX = 5
48
Gregory Thiemonge29d17902019-04-30 15:06:17 +020049SRC_PORT_NUMBER_MIN = 32768
50SRC_PORT_NUMBER_MAX = 61000
51
Jude Cross986e3f52017-07-24 14:57:20 -070052
53class LoadBalancerBaseTest(test.BaseTestCase):
54 """Base class for load balancer tests."""
55
56 # Setup cls.os_roles_lb_member. cls.os_primary, cls.os_roles_lb_member,
57 # and cls.os_roles_lb_admin credentials.
58 credentials = ['admin', 'primary',
59 ['lb_member', CONF.load_balancer.member_role],
60 ['lb_member2', CONF.load_balancer.member_role],
61 ['lb_admin', CONF.load_balancer.admin_role]]
62
63 client_manager = clients.ManagerV2
Adam Harwelle029af22018-05-24 17:13:28 -070064 webserver1_response = 1
65 webserver2_response = 5
Michael Johnsondfd818a2018-08-21 20:54:54 -070066 used_ips = []
Jude Cross986e3f52017-07-24 14:57:20 -070067
Gregory Thiemonge29d17902019-04-30 15:06:17 +020068 src_port_number = SRC_PORT_NUMBER_MIN
69
Jude Cross986e3f52017-07-24 14:57:20 -070070 @classmethod
71 def skip_checks(cls):
72 """Check if we should skip all of the children tests."""
73 super(LoadBalancerBaseTest, cls).skip_checks()
74
75 service_list = {
76 'load_balancer': CONF.service_available.load_balancer,
77 }
78
79 live_service_list = {
80 'compute': CONF.service_available.nova,
81 'image': CONF.service_available.glance,
82 'neutron': CONF.service_available.neutron
83 }
84
85 if not CONF.load_balancer.test_with_noop:
86 service_list.update(live_service_list)
87
88 for service, available in service_list.items():
89 if not available:
zhangzs2a6cf672018-11-10 16:13:11 +080090 skip_msg = ("{0} skipped as {1} service is not "
Jude Cross986e3f52017-07-24 14:57:20 -070091 "available.".format(cls.__name__, service))
92 raise cls.skipException(skip_msg)
93
94 # We must be able to reach our VIP and instances
95 if not (CONF.network.project_networks_reachable
96 or CONF.network.public_network_id):
97 msg = ('Either project_networks_reachable must be "true", or '
98 'public_network_id must be defined.')
99 raise cls.skipException(msg)
100
101 @classmethod
102 def setup_credentials(cls):
103 """Setup test credentials and network resources."""
104 # Do not auto create network resources
105 cls.set_network_resources()
106 super(LoadBalancerBaseTest, cls).setup_credentials()
107
108 @classmethod
109 def setup_clients(cls):
110 """Setup client aliases."""
111 super(LoadBalancerBaseTest, cls).setup_clients()
112 cls.lb_mem_float_ip_client = cls.os_roles_lb_member.floating_ips_client
113 cls.lb_mem_keypairs_client = cls.os_roles_lb_member.keypairs_client
114 cls.lb_mem_net_client = cls.os_roles_lb_member.networks_client
115 cls.lb_mem_ports_client = cls.os_roles_lb_member.ports_client
116 cls.lb_mem_routers_client = cls.os_roles_lb_member.routers_client
117 cls.lb_mem_SG_client = cls.os_roles_lb_member.security_groups_client
118 cls.lb_mem_SGr_client = (
119 cls.os_roles_lb_member.security_group_rules_client)
120 cls.lb_mem_servers_client = cls.os_roles_lb_member.servers_client
121 cls.lb_mem_subnet_client = cls.os_roles_lb_member.subnets_client
122 cls.mem_lb_client = cls.os_roles_lb_member.loadbalancer_client
Jude Crossfbbd2b42017-08-09 15:21:04 -0700123 cls.mem_listener_client = cls.os_roles_lb_member.listener_client
Adam Harwell8ffce3e2018-05-01 21:18:44 -0700124 cls.mem_pool_client = cls.os_roles_lb_member.pool_client
Adam Harwellde3e0542018-05-03 18:21:06 -0700125 cls.mem_member_client = cls.os_roles_lb_member.member_client
Adam Harwell60ed9d92018-05-10 13:23:13 -0700126 cls.mem_healthmonitor_client = (
127 cls.os_roles_lb_member.healthmonitor_client)
Adam Harwell446f8be2018-05-24 16:51:03 -0700128 cls.mem_l7policy_client = cls.os_roles_lb_member.l7policy_client
Adam Harwelle029af22018-05-24 17:13:28 -0700129 cls.mem_l7rule_client = cls.os_roles_lb_member.l7rule_client
Michael Johnson2b10e0a2019-01-25 15:42:13 -0800130 cls.lb_admin_amphora_client = cls.os_roles_lb_admin.amphora_client
Michael Johnsonaff2e862019-01-11 16:38:00 -0800131 cls.lb_admin_flavor_profile_client = (
132 cls.os_roles_lb_admin.flavor_profile_client)
Michael Johnsona2d03072019-01-14 17:18:21 -0800133 cls.lb_admin_flavor_client = cls.os_roles_lb_admin.flavor_client
134 cls.mem_flavor_client = cls.os_roles_lb_member.flavor_client
Michael Johnsonfc223fe2019-01-15 16:40:05 -0800135 cls.mem_provider_client = cls.os_roles_lb_member.provider_client
Carlos Goncalvesc2e12162019-02-14 23:57:44 +0100136 cls.os_admin_servers_client = cls.os_admin.servers_client
Adam Harwellc2aa20c2019-11-20 11:15:07 -0800137 cls.lb_admin_flavor_capabilities_client = (
Michael Johnson77df0322019-01-15 18:27:58 -0800138 cls.os_roles_lb_admin.flavor_capabilities_client)
Adam Harwellc2aa20c2019-11-20 11:15:07 -0800139 cls.lb_admin_availability_zone_capabilities_client = (
140 cls.os_roles_lb_admin.availability_zone_capabilities_client)
141 cls.lb_admin_availability_zone_profile_client = (
142 cls.os_roles_lb_admin.availability_zone_profile_client)
143 cls.lb_admin_availability_zone_client = (
144 cls.os_roles_lb_admin.availability_zone_client)
145 cls.mem_availability_zone_client = (
146 cls.os_roles_lb_member.availability_zone_client)
Jude Cross986e3f52017-07-24 14:57:20 -0700147
148 @classmethod
149 def resource_setup(cls):
150 """Setup resources needed by the tests."""
151 super(LoadBalancerBaseTest, cls).resource_setup()
152
153 conf_lb = CONF.load_balancer
154
Michael Johnsondfd818a2018-08-21 20:54:54 -0700155 cls.api_version = cls.mem_lb_client.get_max_api_version()
156
Jude Cross986e3f52017-07-24 14:57:20 -0700157 if conf_lb.test_subnet_override and not conf_lb.test_network_override:
158 raise exceptions.InvalidConfiguration(
159 "Configuration value test_network_override must be "
160 "specified if test_subnet_override is used.")
161
Maciej Józefczykb6df5f82019-12-10 10:12:30 +0000162 # Get loadbalancing algorithms supported by provider driver.
163 try:
164 algorithms = const.SUPPORTED_LB_ALGORITHMS[
165 CONF.load_balancer.provider]
166 except KeyError:
167 algorithms = const.SUPPORTED_LB_ALGORITHMS['default']
168 # Set default algorithm as first from the list.
169 cls.lb_algorithm = algorithms[0]
170
Jude Cross986e3f52017-07-24 14:57:20 -0700171 show_subnet = cls.lb_mem_subnet_client.show_subnet
172 if CONF.load_balancer.test_with_noop:
173 cls.lb_member_vip_net = {'id': uuidutils.generate_uuid()}
174 cls.lb_member_vip_subnet = {'id': uuidutils.generate_uuid()}
175 cls.lb_member_1_net = {'id': uuidutils.generate_uuid()}
176 cls.lb_member_1_subnet = {'id': uuidutils.generate_uuid()}
177 cls.lb_member_2_net = {'id': uuidutils.generate_uuid()}
178 cls.lb_member_2_subnet = {'id': uuidutils.generate_uuid()}
179 if CONF.load_balancer.test_with_ipv6:
Michael Johnson5a16ad32018-10-18 14:49:11 -0700180 cls.lb_member_vip_ipv6_net = {'id': uuidutils.generate_uuid()}
Jude Cross986e3f52017-07-24 14:57:20 -0700181 cls.lb_member_vip_ipv6_subnet = {'id':
182 uuidutils.generate_uuid()}
183 cls.lb_member_1_ipv6_subnet = {'id': uuidutils.generate_uuid()}
184 cls.lb_member_2_ipv6_subnet = {'id': uuidutils.generate_uuid()}
Michael Johnson590fbe12019-07-03 14:30:01 -0700185 cls.lb_member_vip_ipv6_subnet_stateful = True
Jude Cross986e3f52017-07-24 14:57:20 -0700186 return
187 elif CONF.load_balancer.test_network_override:
188 if conf_lb.test_subnet_override:
189 override_subnet = show_subnet(conf_lb.test_subnet_override)
190 else:
191 override_subnet = None
192
193 show_net = cls.lb_mem_net_client.show_network
194 override_network = show_net(conf_lb.test_network_override)
195 override_network = override_network.get('network')
196
197 cls.lb_member_vip_net = override_network
198 cls.lb_member_vip_subnet = override_subnet
199 cls.lb_member_1_net = override_network
200 cls.lb_member_1_subnet = override_subnet
201 cls.lb_member_2_net = override_network
202 cls.lb_member_2_subnet = override_subnet
203
204 if (CONF.load_balancer.test_with_ipv6 and
205 conf_lb.test_IPv6_subnet_override):
206 override_ipv6_subnet = show_subnet(
207 conf_lb.test_IPv6_subnet_override)
208 cls.lb_member_vip_ipv6_subnet = override_ipv6_subnet
209 cls.lb_member_1_ipv6_subnet = override_ipv6_subnet
210 cls.lb_member_2_ipv6_subnet = override_ipv6_subnet
Michael Johnson590fbe12019-07-03 14:30:01 -0700211 cls.lb_member_vip_ipv6_subnet_stateful = False
212 if (override_ipv6_subnet[0]['ipv6_address_mode'] ==
213 'dhcpv6-stateful'):
214 cls.lb_member_vip_ipv6_subnet_stateful = True
Jude Cross986e3f52017-07-24 14:57:20 -0700215 else:
216 cls.lb_member_vip_ipv6_subnet = None
217 cls.lb_member_1_ipv6_subnet = None
218 cls.lb_member_2_ipv6_subnet = None
219 else:
220 cls._create_networks()
221
222 LOG.debug('Octavia Setup: lb_member_vip_net = {}'.format(
223 cls.lb_member_vip_net[const.ID]))
224 if cls.lb_member_vip_subnet:
225 LOG.debug('Octavia Setup: lb_member_vip_subnet = {}'.format(
226 cls.lb_member_vip_subnet[const.ID]))
227 LOG.debug('Octavia Setup: lb_member_1_net = {}'.format(
228 cls.lb_member_1_net[const.ID]))
229 if cls.lb_member_1_subnet:
230 LOG.debug('Octavia Setup: lb_member_1_subnet = {}'.format(
231 cls.lb_member_1_subnet[const.ID]))
232 LOG.debug('Octavia Setup: lb_member_2_net = {}'.format(
233 cls.lb_member_2_net[const.ID]))
234 if cls.lb_member_2_subnet:
235 LOG.debug('Octavia Setup: lb_member_2_subnet = {}'.format(
236 cls.lb_member_2_subnet[const.ID]))
Michael Johnson124ba8b2018-08-30 16:06:05 -0700237 if CONF.load_balancer.test_with_ipv6:
238 if cls.lb_member_vip_ipv6_subnet:
239 LOG.debug('Octavia Setup: lb_member_vip_ipv6_subnet = '
240 '{}'.format(cls.lb_member_vip_ipv6_subnet[const.ID]))
241 if cls.lb_member_1_ipv6_subnet:
242 LOG.debug('Octavia Setup: lb_member_1_ipv6_subnet = {}'.format(
243 cls.lb_member_1_ipv6_subnet[const.ID]))
244 if cls.lb_member_2_ipv6_subnet:
245 LOG.debug('Octavia Setup: lb_member_2_ipv6_subnet = {}'.format(
246 cls.lb_member_2_ipv6_subnet[const.ID]))
Jude Cross986e3f52017-07-24 14:57:20 -0700247
Jude Cross986e3f52017-07-24 14:57:20 -0700248 @classmethod
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800249 # Neutron can be slow to clean up ports from the subnets/networks.
250 # Retry this delete a few times if we get a "Conflict" error to give
251 # neutron time to fully cleanup the ports.
252 @tenacity.retry(
253 retry=tenacity.retry_if_exception_type(exceptions.Conflict),
254 wait=tenacity.wait_incrementing(
255 RETRY_INITIAL_DELAY, RETRY_BACKOFF, RETRY_MAX),
256 stop=tenacity.stop_after_attempt(RETRY_ATTEMPTS))
257 def _logging_delete_network(cls, net_id):
258 try:
259 cls.lb_mem_net_client.delete_network(net_id)
260 except Exception:
261 LOG.error('Unable to delete network {}. Active ports:'.format(
262 net_id))
263 LOG.error(cls.lb_mem_ports_client.list_ports())
264 raise
265
266 @classmethod
267 # Neutron can be slow to clean up ports from the subnets/networks.
268 # Retry this delete a few times if we get a "Conflict" error to give
269 # neutron time to fully cleanup the ports.
270 @tenacity.retry(
271 retry=tenacity.retry_if_exception_type(exceptions.Conflict),
272 wait=tenacity.wait_incrementing(
273 RETRY_INITIAL_DELAY, RETRY_BACKOFF, RETRY_MAX),
274 stop=tenacity.stop_after_attempt(RETRY_ATTEMPTS))
275 def _logging_delete_subnet(cls, subnet_id):
276 try:
277 cls.lb_mem_subnet_client.delete_subnet(subnet_id)
278 except Exception:
279 LOG.error('Unable to delete subnet {}. Active ports:'.format(
280 subnet_id))
281 LOG.error(cls.lb_mem_ports_client.list_ports())
282 raise
283
284 @classmethod
Jude Cross986e3f52017-07-24 14:57:20 -0700285 def _create_networks(cls):
286 """Creates networks, subnets, and routers used in tests.
287
288 The following are expected to be defined and available to the tests:
289 cls.lb_member_vip_net
290 cls.lb_member_vip_subnet
291 cls.lb_member_vip_ipv6_subnet (optional)
292 cls.lb_member_1_net
293 cls.lb_member_1_subnet
294 cls.lb_member_1_ipv6_subnet (optional)
295 cls.lb_member_2_net
296 cls.lb_member_2_subnet
297 cls.lb_member_2_ipv6_subnet (optional)
298 """
299
300 # Create tenant VIP network
301 network_kwargs = {
302 'name': data_utils.rand_name("lb_member_vip_network")}
303 if CONF.network_feature_enabled.port_security:
Andreas Jaeger4215b702020-03-28 20:13:46 +0100304 # Note: Allowed Address Pairs requires port security
305 network_kwargs['port_security_enabled'] = True
Jude Cross986e3f52017-07-24 14:57:20 -0700306 result = cls.lb_mem_net_client.create_network(**network_kwargs)
307 cls.lb_member_vip_net = result['network']
308 LOG.info('lb_member_vip_net: {}'.format(cls.lb_member_vip_net))
309 cls.addClassResourceCleanup(
310 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800311 cls._logging_delete_network,
Jude Cross986e3f52017-07-24 14:57:20 -0700312 cls.lb_mem_net_client.show_network,
313 cls.lb_member_vip_net['id'])
314
315 # Create tenant VIP subnet
316 subnet_kwargs = {
317 'name': data_utils.rand_name("lb_member_vip_subnet"),
318 'network_id': cls.lb_member_vip_net['id'],
319 'cidr': CONF.load_balancer.vip_subnet_cidr,
320 'ip_version': 4}
321 result = cls.lb_mem_subnet_client.create_subnet(**subnet_kwargs)
322 cls.lb_member_vip_subnet = result['subnet']
323 LOG.info('lb_member_vip_subnet: {}'.format(cls.lb_member_vip_subnet))
324 cls.addClassResourceCleanup(
325 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800326 cls._logging_delete_subnet,
Jude Cross986e3f52017-07-24 14:57:20 -0700327 cls.lb_mem_subnet_client.show_subnet,
328 cls.lb_member_vip_subnet['id'])
329
330 # Create tenant VIP IPv6 subnet
331 if CONF.load_balancer.test_with_ipv6:
Adam Harwell2b9432f2019-05-02 13:56:09 -0600332 # See if ipv6-private-subnet exists and use it if so.
333 priv_ipv6_subnet = cls.os_admin.subnets_client.list_subnets(
334 name='ipv6-private-subnet')['subnets']
Michael Johnson5a16ad32018-10-18 14:49:11 -0700335
Michael Johnson590fbe12019-07-03 14:30:01 -0700336 cls.lb_member_vip_ipv6_subnet_stateful = False
Adam Harwell2b9432f2019-05-02 13:56:09 -0600337 if len(priv_ipv6_subnet) == 1:
Carlos Goncalves84af48c2019-07-25 15:51:30 +0200338 if (priv_ipv6_subnet[0]['ipv6_address_mode'] ==
339 'dhcpv6-stateful'):
340 cls.lb_member_vip_ipv6_subnet_stateful = True
Adam Harwell2b9432f2019-05-02 13:56:09 -0600341 cls.lb_member_vip_ipv6_subnet = priv_ipv6_subnet[0]
Michael Johnson5a16ad32018-10-18 14:49:11 -0700342 cls.lb_member_vip_ipv6_net = {
Adam Harwell2b9432f2019-05-02 13:56:09 -0600343 'id': priv_ipv6_subnet[0]['network_id']}
Michael Johnson5a16ad32018-10-18 14:49:11 -0700344 else:
345 subnet_kwargs = {
346 'name': data_utils.rand_name("lb_member_vip_ipv6_subnet"),
347 'network_id': cls.lb_member_vip_net['id'],
348 'cidr': CONF.load_balancer.vip_ipv6_subnet_cidr,
349 'ip_version': 6}
350 result = cls.lb_mem_subnet_client.create_subnet(
351 **subnet_kwargs)
Michael Johnson7c5b9012019-05-28 11:02:29 -0700352 cls.lb_member_vip_ipv6_net = cls.lb_member_vip_net
Michael Johnson5a16ad32018-10-18 14:49:11 -0700353 cls.lb_member_vip_ipv6_subnet = result['subnet']
354 cls.addClassResourceCleanup(
355 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800356 cls._logging_delete_subnet,
Michael Johnson5a16ad32018-10-18 14:49:11 -0700357 cls.lb_mem_subnet_client.show_subnet,
358 cls.lb_member_vip_ipv6_subnet['id'])
Carlos Goncalves84af48c2019-07-25 15:51:30 +0200359
Jude Cross986e3f52017-07-24 14:57:20 -0700360 LOG.info('lb_member_vip_ipv6_subnet: {}'.format(
361 cls.lb_member_vip_ipv6_subnet))
Jude Cross986e3f52017-07-24 14:57:20 -0700362
363 # Create tenant member 1 network
364 network_kwargs = {
365 'name': data_utils.rand_name("lb_member_1_network")}
366 if CONF.network_feature_enabled.port_security:
367 if CONF.load_balancer.enable_security_groups:
368 network_kwargs['port_security_enabled'] = True
369 else:
370 network_kwargs['port_security_enabled'] = False
371 result = cls.lb_mem_net_client.create_network(**network_kwargs)
372 cls.lb_member_1_net = result['network']
373 LOG.info('lb_member_1_net: {}'.format(cls.lb_member_1_net))
374 cls.addClassResourceCleanup(
375 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800376 cls._logging_delete_network,
Jude Cross986e3f52017-07-24 14:57:20 -0700377 cls.lb_mem_net_client.show_network,
378 cls.lb_member_1_net['id'])
379
380 # Create tenant member 1 subnet
381 subnet_kwargs = {
382 'name': data_utils.rand_name("lb_member_1_subnet"),
383 'network_id': cls.lb_member_1_net['id'],
384 'cidr': CONF.load_balancer.member_1_ipv4_subnet_cidr,
385 'ip_version': 4}
386 result = cls.lb_mem_subnet_client.create_subnet(**subnet_kwargs)
387 cls.lb_member_1_subnet = result['subnet']
388 LOG.info('lb_member_1_subnet: {}'.format(cls.lb_member_1_subnet))
389 cls.addClassResourceCleanup(
390 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800391 cls._logging_delete_subnet,
Jude Cross986e3f52017-07-24 14:57:20 -0700392 cls.lb_mem_subnet_client.show_subnet,
393 cls.lb_member_1_subnet['id'])
394
395 # Create tenant member 1 ipv6 subnet
396 if CONF.load_balancer.test_with_ipv6:
397 subnet_kwargs = {
398 'name': data_utils.rand_name("lb_member_1_ipv6_subnet"),
399 'network_id': cls.lb_member_1_net['id'],
400 'cidr': CONF.load_balancer.member_1_ipv6_subnet_cidr,
401 'ip_version': 6}
402 result = cls.lb_mem_subnet_client.create_subnet(**subnet_kwargs)
Michael Johnsonbf916df2018-10-17 10:59:28 -0700403 cls.lb_member_1_subnet_prefix = (
404 CONF.load_balancer.member_1_ipv6_subnet_cidr.rpartition('/')[2]
405 )
406 assert(cls.lb_member_1_subnet_prefix.isdigit())
Jude Cross986e3f52017-07-24 14:57:20 -0700407 cls.lb_member_1_ipv6_subnet = result['subnet']
408 LOG.info('lb_member_1_ipv6_subnet: {}'.format(
409 cls.lb_member_1_ipv6_subnet))
410 cls.addClassResourceCleanup(
411 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800412 cls._logging_delete_subnet,
Jude Cross986e3f52017-07-24 14:57:20 -0700413 cls.lb_mem_subnet_client.show_subnet,
414 cls.lb_member_1_ipv6_subnet['id'])
415
416 # Create tenant member 2 network
417 network_kwargs = {
418 'name': data_utils.rand_name("lb_member_2_network")}
419 if CONF.network_feature_enabled.port_security:
420 if CONF.load_balancer.enable_security_groups:
421 network_kwargs['port_security_enabled'] = True
422 else:
423 network_kwargs['port_security_enabled'] = False
424 result = cls.lb_mem_net_client.create_network(**network_kwargs)
425 cls.lb_member_2_net = result['network']
426 LOG.info('lb_member_2_net: {}'.format(cls.lb_member_2_net))
427 cls.addClassResourceCleanup(
428 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800429 cls._logging_delete_network,
Jude Cross986e3f52017-07-24 14:57:20 -0700430 cls.lb_mem_net_client.show_network,
431 cls.lb_member_2_net['id'])
432
433 # Create tenant member 2 subnet
434 subnet_kwargs = {
435 'name': data_utils.rand_name("lb_member_2_subnet"),
436 'network_id': cls.lb_member_2_net['id'],
437 'cidr': CONF.load_balancer.member_2_ipv4_subnet_cidr,
438 'ip_version': 4}
439 result = cls.lb_mem_subnet_client.create_subnet(**subnet_kwargs)
440 cls.lb_member_2_subnet = result['subnet']
441 LOG.info('lb_member_2_subnet: {}'.format(cls.lb_member_2_subnet))
442 cls.addClassResourceCleanup(
443 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800444 cls._logging_delete_subnet,
Jude Cross986e3f52017-07-24 14:57:20 -0700445 cls.lb_mem_subnet_client.show_subnet,
446 cls.lb_member_2_subnet['id'])
447
448 # Create tenant member 2 ipv6 subnet
449 if CONF.load_balancer.test_with_ipv6:
450 subnet_kwargs = {
451 'name': data_utils.rand_name("lb_member_2_ipv6_subnet"),
452 'network_id': cls.lb_member_2_net['id'],
453 'cidr': CONF.load_balancer.member_2_ipv6_subnet_cidr,
454 'ip_version': 6}
455 result = cls.lb_mem_subnet_client.create_subnet(**subnet_kwargs)
Michael Johnsonbf916df2018-10-17 10:59:28 -0700456 cls.lb_member_2_subnet_prefix = (
457 CONF.load_balancer.member_2_ipv6_subnet_cidr.rpartition('/')[2]
458 )
459 assert(cls.lb_member_2_subnet_prefix.isdigit())
Jude Cross986e3f52017-07-24 14:57:20 -0700460 cls.lb_member_2_ipv6_subnet = result['subnet']
461 LOG.info('lb_member_2_ipv6_subnet: {}'.format(
462 cls.lb_member_2_ipv6_subnet))
463 cls.addClassResourceCleanup(
464 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800465 cls._logging_delete_subnet,
Jude Cross986e3f52017-07-24 14:57:20 -0700466 cls.lb_mem_subnet_client.show_subnet,
467 cls.lb_member_2_ipv6_subnet['id'])
468
Adam Harwellcd72b562018-05-07 11:37:22 -0700469 @classmethod
Michael Johnson07c9a632018-06-07 13:27:42 -0700470 def _setup_lb_network_kwargs(cls, lb_kwargs, ip_version=None,
471 use_fixed_ip=False):
Adam Harwell60ed9d92018-05-10 13:23:13 -0700472 if not ip_version:
473 ip_version = 6 if CONF.load_balancer.test_with_ipv6 else 4
Michael Johnson5a16ad32018-10-18 14:49:11 -0700474 if cls.lb_member_vip_subnet or cls.lb_member_vip_ipv6_subnet:
Adam Harwellcd72b562018-05-07 11:37:22 -0700475 ip_index = data_utils.rand_int_id(start=10, end=100)
Michael Johnsondfd818a2018-08-21 20:54:54 -0700476 while ip_index in cls.used_ips:
477 ip_index = data_utils.rand_int_id(start=10, end=100)
478 cls.used_ips.append(ip_index)
Adam Harwellcd72b562018-05-07 11:37:22 -0700479 if ip_version == 4:
Adam Harwellcd72b562018-05-07 11:37:22 -0700480 subnet_id = cls.lb_member_vip_subnet[const.ID]
Michael Johnson5a16ad32018-10-18 14:49:11 -0700481 if CONF.load_balancer.test_with_noop:
482 lb_vip_address = '198.18.33.33'
483 else:
484 subnet = cls.os_admin.subnets_client.show_subnet(subnet_id)
485 network = ipaddress.IPv4Network(subnet['subnet']['cidr'])
486 lb_vip_address = str(network[ip_index])
Adam Harwellcd72b562018-05-07 11:37:22 -0700487 else:
Adam Harwellcd72b562018-05-07 11:37:22 -0700488 subnet_id = cls.lb_member_vip_ipv6_subnet[const.ID]
Michael Johnson5a16ad32018-10-18 14:49:11 -0700489 if CONF.load_balancer.test_with_noop:
490 lb_vip_address = '2001:db8:33:33:33:33:33:33'
491 else:
492 subnet = cls.os_admin.subnets_client.show_subnet(subnet_id)
493 network = ipaddress.IPv6Network(subnet['subnet']['cidr'])
494 lb_vip_address = str(network[ip_index])
Michael Johnson590fbe12019-07-03 14:30:01 -0700495 # If the subnet is IPv6 slaac or dhcpv6-stateless
496 # neutron does not allow a fixed IP
497 if not cls.lb_member_vip_ipv6_subnet_stateful:
498 use_fixed_ip = False
Adam Harwellcd72b562018-05-07 11:37:22 -0700499 lb_kwargs[const.VIP_SUBNET_ID] = subnet_id
Michael Johnson07c9a632018-06-07 13:27:42 -0700500 if use_fixed_ip:
501 lb_kwargs[const.VIP_ADDRESS] = lb_vip_address
Adam Harwellcd72b562018-05-07 11:37:22 -0700502 if CONF.load_balancer.test_with_noop:
503 lb_kwargs[const.VIP_NETWORK_ID] = (
504 cls.lb_member_vip_net[const.ID])
Carlos Goncalvesbb238552020-01-15 10:10:55 +0000505 if ip_version == 6:
506 lb_kwargs[const.VIP_ADDRESS] = lb_vip_address
Adam Harwellcd72b562018-05-07 11:37:22 -0700507 else:
508 lb_kwargs[const.VIP_NETWORK_ID] = cls.lb_member_vip_net[const.ID]
509 lb_kwargs[const.VIP_SUBNET_ID] = None
510
511
512class LoadBalancerBaseTestWithCompute(LoadBalancerBaseTest):
513 @classmethod
514 def resource_setup(cls):
515 super(LoadBalancerBaseTestWithCompute, cls).resource_setup()
516 # If validation is disabled in this cloud, we won't be able to
517 # start the webservers, so don't even boot them.
518 if not CONF.validation.run_validation:
519 return
520
521 # Create a keypair for the webservers
522 keypair_name = data_utils.rand_name('lb_member_keypair')
523 result = cls.lb_mem_keypairs_client.create_keypair(
524 name=keypair_name)
525 cls.lb_member_keypair = result['keypair']
526 LOG.info('lb_member_keypair: {}'.format(cls.lb_member_keypair))
527 cls.addClassResourceCleanup(
528 waiters.wait_for_not_found,
529 cls.lb_mem_keypairs_client.delete_keypair,
530 cls.lb_mem_keypairs_client.show_keypair,
531 keypair_name)
532
533 if (CONF.load_balancer.enable_security_groups and
534 CONF.network_feature_enabled.port_security):
535 # Set up the security group for the webservers
536 SG_name = data_utils.rand_name('lb_member_SG')
537 cls.lb_member_sec_group = (
538 cls.lb_mem_SG_client.create_security_group(
539 name=SG_name)['security_group'])
540 cls.addClassResourceCleanup(
541 waiters.wait_for_not_found,
542 cls.lb_mem_SG_client.delete_security_group,
543 cls.lb_mem_SG_client.show_security_group,
544 cls.lb_member_sec_group['id'])
545
546 # Create a security group rule to allow 80-81 (test webservers)
547 SGr = cls.lb_mem_SGr_client.create_security_group_rule(
548 direction='ingress',
549 security_group_id=cls.lb_member_sec_group['id'],
550 protocol='tcp',
551 ethertype='IPv4',
552 port_range_min=80,
553 port_range_max=81)['security_group_rule']
554 cls.addClassResourceCleanup(
555 waiters.wait_for_not_found,
556 cls.lb_mem_SGr_client.delete_security_group_rule,
557 cls.lb_mem_SGr_client.show_security_group_rule,
558 SGr['id'])
Gregory Thiemonge29d17902019-04-30 15:06:17 +0200559 # Create a security group rule to allow UDP 80-81 (test webservers)
560 SGr = cls.lb_mem_SGr_client.create_security_group_rule(
561 direction='ingress',
562 security_group_id=cls.lb_member_sec_group['id'],
563 protocol='udp',
564 ethertype='IPv4',
565 port_range_min=80,
566 port_range_max=81)['security_group_rule']
567 cls.addClassResourceCleanup(
568 waiters.wait_for_not_found,
569 cls.lb_mem_SGr_client.delete_security_group_rule,
570 cls.lb_mem_SGr_client.show_security_group_rule,
571 SGr['id'])
572 # Create a security group rule to allow UDP 9999 (test webservers)
573 # Port 9999 is used to illustrate health monitor ERRORs on closed
574 # ports.
575 SGr = cls.lb_mem_SGr_client.create_security_group_rule(
576 direction='ingress',
577 security_group_id=cls.lb_member_sec_group['id'],
578 protocol='udp',
579 ethertype='IPv4',
580 port_range_min=9999,
581 port_range_max=9999)['security_group_rule']
582 cls.addClassResourceCleanup(
583 waiters.wait_for_not_found,
584 cls.lb_mem_SGr_client.delete_security_group_rule,
585 cls.lb_mem_SGr_client.show_security_group_rule,
586 SGr['id'])
Adam Harwellcd72b562018-05-07 11:37:22 -0700587 # Create a security group rule to allow 22 (ssh)
588 SGr = cls.lb_mem_SGr_client.create_security_group_rule(
589 direction='ingress',
590 security_group_id=cls.lb_member_sec_group['id'],
591 protocol='tcp',
592 ethertype='IPv4',
593 port_range_min=22,
594 port_range_max=22)['security_group_rule']
595 cls.addClassResourceCleanup(
596 waiters.wait_for_not_found,
597 cls.lb_mem_SGr_client.delete_security_group_rule,
598 cls.lb_mem_SGr_client.show_security_group_rule,
599 SGr['id'])
600 if CONF.load_balancer.test_with_ipv6:
601 # Create a security group rule to allow 80-81 (test webservers)
602 SGr = cls.lb_mem_SGr_client.create_security_group_rule(
603 direction='ingress',
604 security_group_id=cls.lb_member_sec_group['id'],
605 protocol='tcp',
606 ethertype='IPv6',
607 port_range_min=80,
608 port_range_max=81)['security_group_rule']
609 cls.addClassResourceCleanup(
610 waiters.wait_for_not_found,
611 cls.lb_mem_SGr_client.delete_security_group_rule,
612 cls.lb_mem_SGr_client.show_security_group_rule,
613 SGr['id'])
Gregory Thiemonge29d17902019-04-30 15:06:17 +0200614 # Create a security group rule to allow UDP 80-81 (test
615 # webservers)
616 SGr = cls.lb_mem_SGr_client.create_security_group_rule(
617 direction='ingress',
618 security_group_id=cls.lb_member_sec_group['id'],
619 protocol='udp',
620 ethertype='IPv6',
621 port_range_min=80,
622 port_range_max=81)['security_group_rule']
623 cls.addClassResourceCleanup(
624 waiters.wait_for_not_found,
625 cls.lb_mem_SGr_client.delete_security_group_rule,
626 cls.lb_mem_SGr_client.show_security_group_rule,
627 SGr['id'])
Adam Harwellcd72b562018-05-07 11:37:22 -0700628 # Create a security group rule to allow 22 (ssh)
629 SGr = cls.lb_mem_SGr_client.create_security_group_rule(
630 direction='ingress',
631 security_group_id=cls.lb_member_sec_group['id'],
632 protocol='tcp',
633 ethertype='IPv6',
634 port_range_min=22,
635 port_range_max=22)['security_group_rule']
636 cls.addClassResourceCleanup(
637 waiters.wait_for_not_found,
638 cls.lb_mem_SGr_client.delete_security_group_rule,
639 cls.lb_mem_SGr_client.show_security_group_rule,
640 SGr['id'])
641
642 LOG.info('lb_member_sec_group: {}'.format(cls.lb_member_sec_group))
643
644 # Create webserver 1 instance
645 server_details = cls._create_webserver('lb_member_webserver1',
646 cls.lb_member_1_net)
647
648 cls.lb_member_webserver1 = server_details['server']
649 cls.webserver1_ip = server_details.get('ipv4_address')
650 cls.webserver1_ipv6 = server_details.get('ipv6_address')
651 cls.webserver1_public_ip = server_details['public_ipv4_address']
652
653 LOG.debug('Octavia Setup: lb_member_webserver1 = {}'.format(
654 cls.lb_member_webserver1[const.ID]))
655 LOG.debug('Octavia Setup: webserver1_ip = {}'.format(
656 cls.webserver1_ip))
657 LOG.debug('Octavia Setup: webserver1_ipv6 = {}'.format(
658 cls.webserver1_ipv6))
659 LOG.debug('Octavia Setup: webserver1_public_ip = {}'.format(
660 cls.webserver1_public_ip))
661
662 # Create webserver 2 instance
663 server_details = cls._create_webserver('lb_member_webserver2',
664 cls.lb_member_2_net)
665
666 cls.lb_member_webserver2 = server_details['server']
667 cls.webserver2_ip = server_details.get('ipv4_address')
668 cls.webserver2_ipv6 = server_details.get('ipv6_address')
669 cls.webserver2_public_ip = server_details['public_ipv4_address']
670
671 LOG.debug('Octavia Setup: lb_member_webserver2 = {}'.format(
672 cls.lb_member_webserver2[const.ID]))
673 LOG.debug('Octavia Setup: webserver2_ip = {}'.format(
674 cls.webserver2_ip))
675 LOG.debug('Octavia Setup: webserver2_ipv6 = {}'.format(
676 cls.webserver2_ipv6))
677 LOG.debug('Octavia Setup: webserver2_public_ip = {}'.format(
678 cls.webserver2_public_ip))
679
Michael Johnsonbf916df2018-10-17 10:59:28 -0700680 if CONF.load_balancer.test_with_ipv6:
681 # Enable the IPv6 nic in webserver 1
682 cls._enable_ipv6_nic_webserver(
683 cls.webserver1_public_ip, cls.lb_member_keypair['private_key'],
684 cls.webserver1_ipv6, cls.lb_member_1_subnet_prefix)
685
686 # Enable the IPv6 nic in webserver 2
687 cls._enable_ipv6_nic_webserver(
688 cls.webserver2_public_ip, cls.lb_member_keypair['private_key'],
689 cls.webserver2_ipv6, cls.lb_member_2_subnet_prefix)
690
Adam Harwellcd72b562018-05-07 11:37:22 -0700691 # Set up serving on webserver 1
692 cls._install_start_webserver(cls.webserver1_public_ip,
Adam Harwelle029af22018-05-24 17:13:28 -0700693 cls.lb_member_keypair['private_key'],
694 cls.webserver1_response)
Adam Harwellcd72b562018-05-07 11:37:22 -0700695
696 # Validate webserver 1
Adam Harwelle029af22018-05-24 17:13:28 -0700697 cls._validate_webserver(cls.webserver1_public_ip,
698 cls.webserver1_response)
Adam Harwellcd72b562018-05-07 11:37:22 -0700699
Gregory Thiemonge29d17902019-04-30 15:06:17 +0200700 # Validate udp server 1
701 cls._validate_udp_server(cls.webserver1_public_ip,
702 cls.webserver1_response)
703
Adam Harwellcd72b562018-05-07 11:37:22 -0700704 # Set up serving on webserver 2
705 cls._install_start_webserver(cls.webserver2_public_ip,
Adam Harwelle029af22018-05-24 17:13:28 -0700706 cls.lb_member_keypair['private_key'],
707 cls.webserver2_response)
Adam Harwellcd72b562018-05-07 11:37:22 -0700708
709 # Validate webserver 2
Adam Harwelle029af22018-05-24 17:13:28 -0700710 cls._validate_webserver(cls.webserver2_public_ip,
711 cls.webserver2_response)
Adam Harwellcd72b562018-05-07 11:37:22 -0700712
Gregory Thiemonge29d17902019-04-30 15:06:17 +0200713 # Validate udp server 2
714 cls._validate_udp_server(cls.webserver2_public_ip,
715 cls.webserver2_response)
716
Adam Harwellcd72b562018-05-07 11:37:22 -0700717 @classmethod
718 def _create_networks(cls):
719 super(LoadBalancerBaseTestWithCompute, cls)._create_networks()
Jude Cross986e3f52017-07-24 14:57:20 -0700720 # Create a router for the subnets (required for the floating IP)
721 router_name = data_utils.rand_name("lb_member_router")
722 result = cls.lb_mem_routers_client.create_router(
723 name=router_name, admin_state_up=True,
724 external_gateway_info=dict(
725 network_id=CONF.network.public_network_id))
726 cls.lb_member_router = result['router']
727 LOG.info('lb_member_router: {}'.format(cls.lb_member_router))
728 cls.addClassResourceCleanup(
729 waiters.wait_for_not_found,
730 cls.lb_mem_routers_client.delete_router,
731 cls.lb_mem_routers_client.show_router,
732 cls.lb_member_router['id'])
733
734 # Add VIP subnet to router
735 cls.lb_mem_routers_client.add_router_interface(
736 cls.lb_member_router['id'],
737 subnet_id=cls.lb_member_vip_subnet['id'])
738 cls.addClassResourceCleanup(
739 waiters.wait_for_not_found,
740 cls.lb_mem_routers_client.remove_router_interface,
741 cls.lb_mem_routers_client.remove_router_interface,
742 cls.lb_member_router['id'],
743 subnet_id=cls.lb_member_vip_subnet['id'])
744
745 # Add member subnet 1 to router
746 cls.lb_mem_routers_client.add_router_interface(
747 cls.lb_member_router['id'],
748 subnet_id=cls.lb_member_1_subnet['id'])
749 cls.addClassResourceCleanup(
750 waiters.wait_for_not_found,
Jude Cross986e3f52017-07-24 14:57:20 -0700751 cls.lb_mem_routers_client.remove_router_interface,
752 cls.lb_mem_routers_client.remove_router_interface,
753 cls.lb_member_router['id'], subnet_id=cls.lb_member_1_subnet['id'])
754
755 # Add member subnet 2 to router
756 cls.lb_mem_routers_client.add_router_interface(
757 cls.lb_member_router['id'],
758 subnet_id=cls.lb_member_2_subnet['id'])
759 cls.addClassResourceCleanup(
760 waiters.wait_for_not_found,
761 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_2_subnet['id'])
764
765 @classmethod
766 def _create_webserver(cls, name, network):
767 """Creates a webserver with two ports.
768
769 webserver_details dictionary contains:
770 server - The compute server object
771 ipv4_address - The IPv4 address for the server (optional)
772 ipv6_address - The IPv6 address for the server (optional)
773 public_ipv4_address - The publicly accessible IPv4 address for the
774 server, this may be a floating IP (optional)
775
776 :param name: The name of the server to create.
777 :param network: The network to boot the server on.
778 :returns: webserver_details dictionary.
779 """
780 server_kwargs = {
781 'name': data_utils.rand_name(name),
782 'flavorRef': CONF.compute.flavor_ref,
783 'imageRef': CONF.compute.image_ref,
784 'key_name': cls.lb_member_keypair['name']}
785 if (CONF.load_balancer.enable_security_groups and
786 CONF.network_feature_enabled.port_security):
787 server_kwargs['security_groups'] = [
788 {'name': cls.lb_member_sec_group['name']}]
789 if not CONF.load_balancer.disable_boot_network:
790 server_kwargs['networks'] = [{'uuid': network['id']}]
791
792 # Replace the name for clouds that have limitations
793 if CONF.load_balancer.random_server_name_length:
794 r = random.SystemRandom()
795 server_kwargs['name'] = "m{}".format("".join(
796 [r.choice(string.ascii_uppercase + string.digits)
797 for _ in range(
798 CONF.load_balancer.random_server_name_length - 1)]
799 ))
800 if CONF.load_balancer.availability_zone:
801 server_kwargs['availability_zone'] = (
802 CONF.load_balancer.availability_zone)
803
804 server = cls.lb_mem_servers_client.create_server(
805 **server_kwargs)['server']
806 cls.addClassResourceCleanup(
807 waiters.wait_for_not_found,
808 cls.lb_mem_servers_client.delete_server,
809 cls.lb_mem_servers_client.show_server,
810 server['id'])
811 server = waiters.wait_for_status(
812 cls.lb_mem_servers_client.show_server,
813 server['id'], 'status', 'ACTIVE',
814 CONF.load_balancer.build_interval,
815 CONF.load_balancer.build_timeout,
816 root_tag='server')
817 webserver_details = {'server': server}
818 LOG.info('Created server: {}'.format(server))
819
820 addresses = server['addresses']
821 if CONF.load_balancer.disable_boot_network:
822 instance_network = addresses.values()[0]
823 else:
824 instance_network = addresses[network['name']]
825 for addr in instance_network:
826 if addr['version'] == 4:
827 webserver_details['ipv4_address'] = addr['addr']
828 if addr['version'] == 6:
829 webserver_details['ipv6_address'] = addr['addr']
830
831 if CONF.validation.connect_method == 'floating':
832 result = cls.lb_mem_ports_client.list_ports(
833 network_id=network['id'],
834 mac_address=instance_network[0]['OS-EXT-IPS-MAC:mac_addr'])
835 port_id = result['ports'][0]['id']
836 result = cls.lb_mem_float_ip_client.create_floatingip(
837 floating_network_id=CONF.network.public_network_id,
838 port_id=port_id)
839 floating_ip = result['floatingip']
840 LOG.info('webserver1_floating_ip: {}'.format(floating_ip))
841 cls.addClassResourceCleanup(
842 waiters.wait_for_not_found,
843 cls.lb_mem_float_ip_client.delete_floatingip,
844 cls.lb_mem_float_ip_client.show_floatingip,
845 floatingip_id=floating_ip['id'])
846 webserver_details['public_ipv4_address'] = (
847 floating_ip['floating_ip_address'])
848 else:
849 webserver_details['public_ipv4_address'] = (
850 instance_network[0]['addr'])
851
852 return webserver_details
853
854 @classmethod
Adam Harwellcd72b562018-05-07 11:37:22 -0700855 def _install_start_webserver(cls, ip_address, ssh_key, start_id):
856 local_file = pkg_resources.resource_filename(
Gregory Thiemonge29d17902019-04-30 15:06:17 +0200857 'octavia_tempest_plugin.contrib.test_server', 'test_server.bin')
858 dest_file = '/dev/shm/test_server.bin'
Adam Harwellcd72b562018-05-07 11:37:22 -0700859
860 linux_client = remote_client.RemoteClient(
861 ip_address, CONF.validation.image_ssh_user, pkey=ssh_key)
862 linux_client.validate_authentication()
863
864 with tempfile.NamedTemporaryFile() as key:
865 key.write(ssh_key.encode('utf-8'))
866 key.flush()
867 cmd = ("scp -v -o UserKnownHostsFile=/dev/null "
868 "-o StrictHostKeyChecking=no "
869 "-o ConnectTimeout={0} -o ConnectionAttempts={1} "
870 "-i {2} {3} {4}@{5}:{6}").format(
871 CONF.load_balancer.scp_connection_timeout,
872 CONF.load_balancer.scp_connection_attempts,
873 key.name, local_file, CONF.validation.image_ssh_user,
874 ip_address, dest_file)
875 args = shlex.split(cmd)
876 subprocess_args = {'stdout': subprocess.PIPE,
877 'stderr': subprocess.STDOUT,
878 'cwd': None}
879 proc = subprocess.Popen(args, **subprocess_args)
880 stdout, stderr = proc.communicate()
881 if proc.returncode != 0:
882 raise exceptions.CommandFailed(proc.returncode, cmd,
883 stdout, stderr)
Gregory Thiemongef72a8862019-08-06 17:25:42 +0200884
885 # Enabling memory overcommit allows to run golang static binaries
886 # compiled with a recent golang toolchain (>=1.11). Those binaries
887 # allocate a large amount of virtual memory at init time, and this
888 # allocation fails in tempest's nano flavor (64MB of RAM)
889 # (golang issue reported in https://github.com/golang/go/issues/28114,
890 # follow-up: https://github.com/golang/go/issues/28081)
891 # TODO(gthiemonge): Remove this call when golang issue is resolved.
892 linux_client.exec_command('sudo sh -c "echo 1 > '
893 '/proc/sys/vm/overcommit_memory"')
894
Adam Harwellcd72b562018-05-07 11:37:22 -0700895 linux_client.exec_command('sudo screen -d -m {0} -port 80 '
896 '-id {1}'.format(dest_file, start_id))
897 linux_client.exec_command('sudo screen -d -m {0} -port 81 '
898 '-id {1}'.format(dest_file, start_id + 1))
899
Michael Johnsonbf916df2018-10-17 10:59:28 -0700900 # Cirros does not configure the assigned IPv6 address by default
901 # so enable it manually like tempest does here:
902 # tempest/scenario/test_netowrk_v6.py turn_nic6_on()
903 @classmethod
904 def _enable_ipv6_nic_webserver(cls, ip_address, ssh_key,
905 ipv6_address, ipv6_prefix):
906 linux_client = remote_client.RemoteClient(
907 ip_address, CONF.validation.image_ssh_user, pkey=ssh_key)
908 linux_client.validate_authentication()
909
910 linux_client.exec_command('sudo ip address add {0}/{1} dev '
911 'eth0'.format(ipv6_address, ipv6_prefix))
912
Adam Harwellcd72b562018-05-07 11:37:22 -0700913 @classmethod
Jude Cross986e3f52017-07-24 14:57:20 -0700914 def _validate_webserver(cls, ip_address, start_id):
915 URL = 'http://{0}'.format(ip_address)
916 validators.validate_URL_response(URL, expected_body=str(start_id))
917 URL = 'http://{0}:81'.format(ip_address)
918 validators.validate_URL_response(URL, expected_body=str(start_id + 1))
919
Gregory Thiemonge29d17902019-04-30 15:06:17 +0200920 @classmethod
921 def _validate_udp_server(cls, ip_address, start_id):
922 res = cls._udp_request(ip_address, 80)
923 if res != str(start_id):
924 raise Exception("Response from test server doesn't match the "
925 "expected value ({0} != {1}).".format(
926 res, str(start_id)))
927
928 res = cls._udp_request(ip_address, 81)
929 if res != str(start_id + 1):
930 raise Exception("Response from test server doesn't match the "
931 "expected value ({0} != {1}).".format(
932 res, str(start_id + 1)))
933
934 @classmethod
935 def _udp_request(cls, vip_address, port=80, timeout=None):
936 if ipaddress.ip_address(vip_address).version == 6:
937 family = socket.AF_INET6
938 else:
939 family = socket.AF_INET
940
941 sock = socket.socket(family, socket.SOCK_DGRAM)
942
943 # Force the use of an incremental port number for source to avoid
944 # re-use of a previous source port that will affect the round-robin
945 # dispatch
946 while True:
947 port_number = cls.src_port_number
948 cls.src_port_number += 1
949 if cls.src_port_number >= SRC_PORT_NUMBER_MAX:
950 cls.src_port_number = SRC_PORT_NUMBER_MIN
951
952 # catch and skip already used ports on the host
953 try:
954 sock.bind(('', port_number))
955 except OSError as e:
956 # if error is 'Address already in use', try next port number
957 if e.errno != errno.EADDRINUSE:
958 raise e
959 else:
960 # successfully bind the socket
961 break
962
963 server_address = (vip_address, port)
964 data = b"data\n"
965
966 if timeout is not None:
967 sock.settimeout(timeout)
968
969 sock.sendto(data, server_address)
970 data, addr = sock.recvfrom(4096)
971
972 sock.close()
973
974 return data.decode('utf-8')
975
976 def _wait_for_lb_functional(self, vip_address, traffic_member_count,
977 protocol_port, protocol, verify):
978 if protocol != const.UDP:
979 session = requests.Session()
Adam Harwellcd72b562018-05-07 11:37:22 -0700980 start = time.time()
981
Gregory Thiemonge29d17902019-04-30 15:06:17 +0200982 response_counts = {}
983
984 # Send requests to the load balancer until at least
985 # "traffic_member_count" members have replied (ensure network
986 # connectivity is functional between the load balancer and the membesr)
Adam Harwellcd72b562018-05-07 11:37:22 -0700987 while time.time() - start < CONF.load_balancer.build_timeout:
988 try:
Gregory Thiemonge29d17902019-04-30 15:06:17 +0200989 if protocol != const.UDP:
990 url = "{0}://{1}{2}{3}".format(
991 protocol.lower(),
992 vip_address,
993 ':' if protocol_port else '',
994 protocol_port or '')
995 r = session.get(url, timeout=2, verify=verify)
996 data = r.content
997 else:
998 data = self._udp_request(vip_address, port=protocol_port,
999 timeout=2)
1000 if data in response_counts:
1001 response_counts[data] += 1
1002 else:
1003 response_counts[data] = 1
1004
1005 if traffic_member_count == len(response_counts):
1006 LOG.debug('Loadbalancer response totals: %s',
1007 response_counts)
1008 time.sleep(1)
1009 return
Adam Harwellcd72b562018-05-07 11:37:22 -07001010 except Exception:
1011 LOG.warning('Server is not passing initial traffic. Waiting.')
1012 time.sleep(1)
Gregory Thiemonge29d17902019-04-30 15:06:17 +02001013
1014 LOG.debug('Loadbalancer response totals: %s', response_counts)
Adam Harwellcd72b562018-05-07 11:37:22 -07001015 LOG.error('Server did not begin passing traffic within the timeout '
1016 'period. Failing test.')
1017 raise Exception()
1018
Maciej Józefczykb6df5f82019-12-10 10:12:30 +00001019 def _send_lb_request(self, handler, protocol, vip_address,
1020 verify, protocol_port, num=20):
Adam Harwellcd72b562018-05-07 11:37:22 -07001021 response_counts = {}
Gregory Thiemonge29d17902019-04-30 15:06:17 +02001022
Adam Harwellcd72b562018-05-07 11:37:22 -07001023 # Send a number requests to lb vip
Maciej Józefczykb6df5f82019-12-10 10:12:30 +00001024 for i in range(num):
Adam Harwellcd72b562018-05-07 11:37:22 -07001025 try:
Gregory Thiemonge29d17902019-04-30 15:06:17 +02001026 if protocol != const.UDP:
1027 url = "{0}://{1}{2}{3}".format(
1028 protocol.lower(),
1029 vip_address,
1030 ':' if protocol_port else '',
1031 protocol_port or '')
1032 r = handler.get(url, timeout=2, verify=verify)
1033 data = r.content
Adam Harwellcd72b562018-05-07 11:37:22 -07001034 else:
Gregory Thiemonge29d17902019-04-30 15:06:17 +02001035 data = self._udp_request(vip_address, port=protocol_port,
1036 timeout=2)
1037
1038 if data in response_counts:
1039 response_counts[data] += 1
1040 else:
1041 response_counts[data] = 1
1042
Adam Harwellcd72b562018-05-07 11:37:22 -07001043 except Exception:
1044 LOG.exception('Failed to send request to loadbalancer vip')
1045 raise Exception('Failed to connect to lb')
Adam Harwellcd72b562018-05-07 11:37:22 -07001046 LOG.debug('Loadbalancer response totals: %s', response_counts)
Maciej Józefczykb6df5f82019-12-10 10:12:30 +00001047 return response_counts
1048
1049 def _check_members_balanced_round_robin(
Gregory Thiemonge29d17902019-04-30 15:06:17 +02001050 self, vip_address, traffic_member_count=2, protocol=const.HTTP,
Maciej Józefczykb6df5f82019-12-10 10:12:30 +00001051 verify=True, protocol_port=80):
1052
1053 handler = requests.Session()
1054 response_counts = self._send_lb_request(
1055 handler, protocol, vip_address,
1056 verify, protocol_port)
1057
Adam Harwellcd72b562018-05-07 11:37:22 -07001058 # Ensure the correct number of members
Adam Harwell60ed9d92018-05-10 13:23:13 -07001059 self.assertEqual(traffic_member_count, len(response_counts))
Adam Harwellcd72b562018-05-07 11:37:22 -07001060
1061 # Ensure both members got the same number of responses
1062 self.assertEqual(1, len(set(response_counts.values())))
Adam Harwelle029af22018-05-24 17:13:28 -07001063
Maciej Józefczykb6df5f82019-12-10 10:12:30 +00001064 def _check_members_balanced_source_ip_port(
Gregory Thiemonge29d17902019-04-30 15:06:17 +02001065 self, vip_address, traffic_member_count=2, protocol=const.HTTP,
Maciej Józefczykb6df5f82019-12-10 10:12:30 +00001066 verify=True, protocol_port=80):
1067
1068 handler = requests
1069 response_counts = self._send_lb_request(
1070 handler, protocol, vip_address,
1071 verify, protocol_port)
1072 # Ensure the correct number of members
1073 self.assertEqual(traffic_member_count, len(response_counts))
1074
1075 if CONF.load_balancer.test_reuse_connection:
1076 handler = requests.Session()
1077 response_counts = self._send_lb_request(
1078 handler, protocol, vip_address,
1079 verify, protocol_port)
1080 # Ensure only one member answered
1081 self.assertEqual(1, len(response_counts))
1082
1083 def check_members_balanced(self, vip_address, traffic_member_count=2,
Gregory Thiemonge29d17902019-04-30 15:06:17 +02001084 protocol=const.HTTP, verify=True,
1085 protocol_port=80):
Maciej Józefczykb6df5f82019-12-10 10:12:30 +00001086
Gregory Thiemonge29d17902019-04-30 15:06:17 +02001087 if (ipaddress.ip_address(vip_address).version == 6 and
1088 protocol != const.UDP):
Maciej Józefczykb6df5f82019-12-10 10:12:30 +00001089 vip_address = '[{}]'.format(vip_address)
Gregory Thiemonge29d17902019-04-30 15:06:17 +02001090 self._wait_for_lb_functional(vip_address, traffic_member_count,
1091 protocol_port, protocol, verify)
Maciej Józefczykb6df5f82019-12-10 10:12:30 +00001092
1093 validate_func = '_check_members_balanced_%s' % self.lb_algorithm
1094 validate_func = getattr(self, validate_func.lower())
1095 validate_func(
1096 vip_address=vip_address,
1097 traffic_member_count=traffic_member_count,
1098 protocol=protocol,
1099 verify=verify,
1100 protocol_port=protocol_port)
1101
Adam Harwelle029af22018-05-24 17:13:28 -07001102 def assertConsistentResponse(self, response, url, method='GET', repeat=10,
Carlos Goncalvesbb238552020-01-15 10:10:55 +00001103 redirect=False, timeout=2,
1104 conn_error=False, **kwargs):
Adam Harwelle029af22018-05-24 17:13:28 -07001105 """Assert that a request to URL gets the expected response.
1106
1107 :param response: Expected response in format (status_code, content).
1108 :param url: The URL to request.
1109 :param method: The HTTP method to use (GET, POST, PUT, etc)
1110 :param repeat: How many times to test the response.
1111 :param data: Optional data to send in the request.
1112 :param headers: Optional headers to send in the request.
1113 :param cookies: Optional cookies to send in the request.
1114 :param redirect: Is the request a redirect? If true, assume the passed
1115 content should be the next URL in the chain.
Carlos Goncalvesc451ff92018-12-19 19:11:53 +01001116 :param timeout: Optional seconds to wait for the server to send data.
Carlos Goncalvesbb238552020-01-15 10:10:55 +00001117 :param conn_error: Optional Expect a connection error?
Carlos Goncalvesc451ff92018-12-19 19:11:53 +01001118
Adam Harwelle029af22018-05-24 17:13:28 -07001119 :return: boolean success status
1120
1121 :raises: testtools.matchers.MismatchError
1122 """
1123 session = requests.Session()
1124 response_code, response_content = response
1125
1126 for i in range(0, repeat):
Carlos Goncalvesbb238552020-01-15 10:10:55 +00001127 if conn_error:
1128 self.assertRaises(
1129 requests.exceptions.ConnectionError, session.request,
1130 method, url, allow_redirects=not redirect, timeout=timeout,
1131 **kwargs)
1132 continue
1133
Adam Harwelle029af22018-05-24 17:13:28 -07001134 req = session.request(method, url, allow_redirects=not redirect,
1135 timeout=timeout, **kwargs)
1136 if response_code:
1137 self.assertEqual(response_code, req.status_code)
1138 if redirect:
1139 self.assertTrue(req.is_redirect)
Carlos Goncalvesc451ff92018-12-19 19:11:53 +01001140 self.assertEqual(response_content,
1141 session.get_redirect_target(req))
Adam Harwelle029af22018-05-24 17:13:28 -07001142 elif response_content:
jacky06bd587262020-05-06 13:21:06 +08001143 self.assertEqual(str(response_content), req.text)