blob: aab78c18d5befd69af1390a37a26e90c976f1cf3 [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:
305 # Note: Allowed Address Pairs requires port security
306 network_kwargs['port_security_enabled'] = True
307 result = cls.lb_mem_net_client.create_network(**network_kwargs)
308 cls.lb_member_vip_net = result['network']
309 LOG.info('lb_member_vip_net: {}'.format(cls.lb_member_vip_net))
310 cls.addClassResourceCleanup(
311 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800312 cls._logging_delete_network,
Jude Cross986e3f52017-07-24 14:57:20 -0700313 cls.lb_mem_net_client.show_network,
314 cls.lb_member_vip_net['id'])
315
316 # Create tenant VIP subnet
317 subnet_kwargs = {
318 'name': data_utils.rand_name("lb_member_vip_subnet"),
319 'network_id': cls.lb_member_vip_net['id'],
320 'cidr': CONF.load_balancer.vip_subnet_cidr,
321 'ip_version': 4}
322 result = cls.lb_mem_subnet_client.create_subnet(**subnet_kwargs)
323 cls.lb_member_vip_subnet = result['subnet']
324 LOG.info('lb_member_vip_subnet: {}'.format(cls.lb_member_vip_subnet))
325 cls.addClassResourceCleanup(
326 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800327 cls._logging_delete_subnet,
Jude Cross986e3f52017-07-24 14:57:20 -0700328 cls.lb_mem_subnet_client.show_subnet,
329 cls.lb_member_vip_subnet['id'])
330
331 # Create tenant VIP IPv6 subnet
332 if CONF.load_balancer.test_with_ipv6:
Adam Harwell2b9432f2019-05-02 13:56:09 -0600333 # See if ipv6-private-subnet exists and use it if so.
334 priv_ipv6_subnet = cls.os_admin.subnets_client.list_subnets(
335 name='ipv6-private-subnet')['subnets']
Michael Johnson5a16ad32018-10-18 14:49:11 -0700336
Michael Johnson590fbe12019-07-03 14:30:01 -0700337 cls.lb_member_vip_ipv6_subnet_stateful = False
Adam Harwell2b9432f2019-05-02 13:56:09 -0600338 if len(priv_ipv6_subnet) == 1:
Carlos Goncalves84af48c2019-07-25 15:51:30 +0200339 if (priv_ipv6_subnet[0]['ipv6_address_mode'] ==
340 'dhcpv6-stateful'):
341 cls.lb_member_vip_ipv6_subnet_stateful = True
Adam Harwell2b9432f2019-05-02 13:56:09 -0600342 cls.lb_member_vip_ipv6_subnet = priv_ipv6_subnet[0]
Michael Johnson5a16ad32018-10-18 14:49:11 -0700343 cls.lb_member_vip_ipv6_net = {
Adam Harwell2b9432f2019-05-02 13:56:09 -0600344 'id': priv_ipv6_subnet[0]['network_id']}
Michael Johnson5a16ad32018-10-18 14:49:11 -0700345 else:
346 subnet_kwargs = {
347 'name': data_utils.rand_name("lb_member_vip_ipv6_subnet"),
348 'network_id': cls.lb_member_vip_net['id'],
349 'cidr': CONF.load_balancer.vip_ipv6_subnet_cidr,
350 'ip_version': 6}
351 result = cls.lb_mem_subnet_client.create_subnet(
352 **subnet_kwargs)
Michael Johnson7c5b9012019-05-28 11:02:29 -0700353 cls.lb_member_vip_ipv6_net = cls.lb_member_vip_net
Michael Johnson5a16ad32018-10-18 14:49:11 -0700354 cls.lb_member_vip_ipv6_subnet = result['subnet']
355 cls.addClassResourceCleanup(
356 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800357 cls._logging_delete_subnet,
Michael Johnson5a16ad32018-10-18 14:49:11 -0700358 cls.lb_mem_subnet_client.show_subnet,
359 cls.lb_member_vip_ipv6_subnet['id'])
Carlos Goncalves84af48c2019-07-25 15:51:30 +0200360
Jude Cross986e3f52017-07-24 14:57:20 -0700361 LOG.info('lb_member_vip_ipv6_subnet: {}'.format(
362 cls.lb_member_vip_ipv6_subnet))
Jude Cross986e3f52017-07-24 14:57:20 -0700363
364 # Create tenant member 1 network
365 network_kwargs = {
366 'name': data_utils.rand_name("lb_member_1_network")}
367 if CONF.network_feature_enabled.port_security:
368 if CONF.load_balancer.enable_security_groups:
369 network_kwargs['port_security_enabled'] = True
370 else:
371 network_kwargs['port_security_enabled'] = False
372 result = cls.lb_mem_net_client.create_network(**network_kwargs)
373 cls.lb_member_1_net = result['network']
374 LOG.info('lb_member_1_net: {}'.format(cls.lb_member_1_net))
375 cls.addClassResourceCleanup(
376 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800377 cls._logging_delete_network,
Jude Cross986e3f52017-07-24 14:57:20 -0700378 cls.lb_mem_net_client.show_network,
379 cls.lb_member_1_net['id'])
380
381 # Create tenant member 1 subnet
382 subnet_kwargs = {
383 'name': data_utils.rand_name("lb_member_1_subnet"),
384 'network_id': cls.lb_member_1_net['id'],
385 'cidr': CONF.load_balancer.member_1_ipv4_subnet_cidr,
386 'ip_version': 4}
387 result = cls.lb_mem_subnet_client.create_subnet(**subnet_kwargs)
388 cls.lb_member_1_subnet = result['subnet']
389 LOG.info('lb_member_1_subnet: {}'.format(cls.lb_member_1_subnet))
390 cls.addClassResourceCleanup(
391 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800392 cls._logging_delete_subnet,
Jude Cross986e3f52017-07-24 14:57:20 -0700393 cls.lb_mem_subnet_client.show_subnet,
394 cls.lb_member_1_subnet['id'])
395
396 # Create tenant member 1 ipv6 subnet
397 if CONF.load_balancer.test_with_ipv6:
398 subnet_kwargs = {
399 'name': data_utils.rand_name("lb_member_1_ipv6_subnet"),
400 'network_id': cls.lb_member_1_net['id'],
401 'cidr': CONF.load_balancer.member_1_ipv6_subnet_cidr,
402 'ip_version': 6}
403 result = cls.lb_mem_subnet_client.create_subnet(**subnet_kwargs)
Michael Johnsonbf916df2018-10-17 10:59:28 -0700404 cls.lb_member_1_subnet_prefix = (
405 CONF.load_balancer.member_1_ipv6_subnet_cidr.rpartition('/')[2]
406 )
407 assert(cls.lb_member_1_subnet_prefix.isdigit())
Jude Cross986e3f52017-07-24 14:57:20 -0700408 cls.lb_member_1_ipv6_subnet = result['subnet']
409 LOG.info('lb_member_1_ipv6_subnet: {}'.format(
410 cls.lb_member_1_ipv6_subnet))
411 cls.addClassResourceCleanup(
412 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800413 cls._logging_delete_subnet,
Jude Cross986e3f52017-07-24 14:57:20 -0700414 cls.lb_mem_subnet_client.show_subnet,
415 cls.lb_member_1_ipv6_subnet['id'])
416
417 # Create tenant member 2 network
418 network_kwargs = {
419 'name': data_utils.rand_name("lb_member_2_network")}
420 if CONF.network_feature_enabled.port_security:
421 if CONF.load_balancer.enable_security_groups:
422 network_kwargs['port_security_enabled'] = True
423 else:
424 network_kwargs['port_security_enabled'] = False
425 result = cls.lb_mem_net_client.create_network(**network_kwargs)
426 cls.lb_member_2_net = result['network']
427 LOG.info('lb_member_2_net: {}'.format(cls.lb_member_2_net))
428 cls.addClassResourceCleanup(
429 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800430 cls._logging_delete_network,
Jude Cross986e3f52017-07-24 14:57:20 -0700431 cls.lb_mem_net_client.show_network,
432 cls.lb_member_2_net['id'])
433
434 # Create tenant member 2 subnet
435 subnet_kwargs = {
436 'name': data_utils.rand_name("lb_member_2_subnet"),
437 'network_id': cls.lb_member_2_net['id'],
438 'cidr': CONF.load_balancer.member_2_ipv4_subnet_cidr,
439 'ip_version': 4}
440 result = cls.lb_mem_subnet_client.create_subnet(**subnet_kwargs)
441 cls.lb_member_2_subnet = result['subnet']
442 LOG.info('lb_member_2_subnet: {}'.format(cls.lb_member_2_subnet))
443 cls.addClassResourceCleanup(
444 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800445 cls._logging_delete_subnet,
Jude Cross986e3f52017-07-24 14:57:20 -0700446 cls.lb_mem_subnet_client.show_subnet,
447 cls.lb_member_2_subnet['id'])
448
449 # Create tenant member 2 ipv6 subnet
450 if CONF.load_balancer.test_with_ipv6:
451 subnet_kwargs = {
452 'name': data_utils.rand_name("lb_member_2_ipv6_subnet"),
453 'network_id': cls.lb_member_2_net['id'],
454 'cidr': CONF.load_balancer.member_2_ipv6_subnet_cidr,
455 'ip_version': 6}
456 result = cls.lb_mem_subnet_client.create_subnet(**subnet_kwargs)
Michael Johnsonbf916df2018-10-17 10:59:28 -0700457 cls.lb_member_2_subnet_prefix = (
458 CONF.load_balancer.member_2_ipv6_subnet_cidr.rpartition('/')[2]
459 )
460 assert(cls.lb_member_2_subnet_prefix.isdigit())
Jude Cross986e3f52017-07-24 14:57:20 -0700461 cls.lb_member_2_ipv6_subnet = result['subnet']
462 LOG.info('lb_member_2_ipv6_subnet: {}'.format(
463 cls.lb_member_2_ipv6_subnet))
464 cls.addClassResourceCleanup(
465 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800466 cls._logging_delete_subnet,
Jude Cross986e3f52017-07-24 14:57:20 -0700467 cls.lb_mem_subnet_client.show_subnet,
468 cls.lb_member_2_ipv6_subnet['id'])
469
Adam Harwellcd72b562018-05-07 11:37:22 -0700470 @classmethod
Michael Johnson07c9a632018-06-07 13:27:42 -0700471 def _setup_lb_network_kwargs(cls, lb_kwargs, ip_version=None,
472 use_fixed_ip=False):
Adam Harwell60ed9d92018-05-10 13:23:13 -0700473 if not ip_version:
474 ip_version = 6 if CONF.load_balancer.test_with_ipv6 else 4
Michael Johnson5a16ad32018-10-18 14:49:11 -0700475 if cls.lb_member_vip_subnet or cls.lb_member_vip_ipv6_subnet:
Adam Harwellcd72b562018-05-07 11:37:22 -0700476 ip_index = data_utils.rand_int_id(start=10, end=100)
Michael Johnsondfd818a2018-08-21 20:54:54 -0700477 while ip_index in cls.used_ips:
478 ip_index = data_utils.rand_int_id(start=10, end=100)
479 cls.used_ips.append(ip_index)
Adam Harwellcd72b562018-05-07 11:37:22 -0700480 if ip_version == 4:
Adam Harwellcd72b562018-05-07 11:37:22 -0700481 subnet_id = cls.lb_member_vip_subnet[const.ID]
Michael Johnson5a16ad32018-10-18 14:49:11 -0700482 if CONF.load_balancer.test_with_noop:
483 lb_vip_address = '198.18.33.33'
484 else:
485 subnet = cls.os_admin.subnets_client.show_subnet(subnet_id)
486 network = ipaddress.IPv4Network(subnet['subnet']['cidr'])
487 lb_vip_address = str(network[ip_index])
Adam Harwellcd72b562018-05-07 11:37:22 -0700488 else:
Adam Harwellcd72b562018-05-07 11:37:22 -0700489 subnet_id = cls.lb_member_vip_ipv6_subnet[const.ID]
Michael Johnson5a16ad32018-10-18 14:49:11 -0700490 if CONF.load_balancer.test_with_noop:
491 lb_vip_address = '2001:db8:33:33:33:33:33:33'
492 else:
493 subnet = cls.os_admin.subnets_client.show_subnet(subnet_id)
494 network = ipaddress.IPv6Network(subnet['subnet']['cidr'])
495 lb_vip_address = str(network[ip_index])
Michael Johnson590fbe12019-07-03 14:30:01 -0700496 # If the subnet is IPv6 slaac or dhcpv6-stateless
497 # neutron does not allow a fixed IP
498 if not cls.lb_member_vip_ipv6_subnet_stateful:
499 use_fixed_ip = False
Adam Harwellcd72b562018-05-07 11:37:22 -0700500 lb_kwargs[const.VIP_SUBNET_ID] = subnet_id
Michael Johnson07c9a632018-06-07 13:27:42 -0700501 if use_fixed_ip:
502 lb_kwargs[const.VIP_ADDRESS] = lb_vip_address
Adam Harwellcd72b562018-05-07 11:37:22 -0700503 if CONF.load_balancer.test_with_noop:
504 lb_kwargs[const.VIP_NETWORK_ID] = (
505 cls.lb_member_vip_net[const.ID])
506 else:
507 lb_kwargs[const.VIP_NETWORK_ID] = cls.lb_member_vip_net[const.ID]
508 lb_kwargs[const.VIP_SUBNET_ID] = None
509
510
511class LoadBalancerBaseTestWithCompute(LoadBalancerBaseTest):
512 @classmethod
513 def resource_setup(cls):
514 super(LoadBalancerBaseTestWithCompute, cls).resource_setup()
515 # If validation is disabled in this cloud, we won't be able to
516 # start the webservers, so don't even boot them.
517 if not CONF.validation.run_validation:
518 return
519
520 # Create a keypair for the webservers
521 keypair_name = data_utils.rand_name('lb_member_keypair')
522 result = cls.lb_mem_keypairs_client.create_keypair(
523 name=keypair_name)
524 cls.lb_member_keypair = result['keypair']
525 LOG.info('lb_member_keypair: {}'.format(cls.lb_member_keypair))
526 cls.addClassResourceCleanup(
527 waiters.wait_for_not_found,
528 cls.lb_mem_keypairs_client.delete_keypair,
529 cls.lb_mem_keypairs_client.show_keypair,
530 keypair_name)
531
532 if (CONF.load_balancer.enable_security_groups and
533 CONF.network_feature_enabled.port_security):
534 # Set up the security group for the webservers
535 SG_name = data_utils.rand_name('lb_member_SG')
536 cls.lb_member_sec_group = (
537 cls.lb_mem_SG_client.create_security_group(
538 name=SG_name)['security_group'])
539 cls.addClassResourceCleanup(
540 waiters.wait_for_not_found,
541 cls.lb_mem_SG_client.delete_security_group,
542 cls.lb_mem_SG_client.show_security_group,
543 cls.lb_member_sec_group['id'])
544
545 # Create a security group rule to allow 80-81 (test webservers)
546 SGr = cls.lb_mem_SGr_client.create_security_group_rule(
547 direction='ingress',
548 security_group_id=cls.lb_member_sec_group['id'],
549 protocol='tcp',
550 ethertype='IPv4',
551 port_range_min=80,
552 port_range_max=81)['security_group_rule']
553 cls.addClassResourceCleanup(
554 waiters.wait_for_not_found,
555 cls.lb_mem_SGr_client.delete_security_group_rule,
556 cls.lb_mem_SGr_client.show_security_group_rule,
557 SGr['id'])
Gregory Thiemonge29d17902019-04-30 15:06:17 +0200558 # Create a security group rule to allow UDP 80-81 (test webservers)
559 SGr = cls.lb_mem_SGr_client.create_security_group_rule(
560 direction='ingress',
561 security_group_id=cls.lb_member_sec_group['id'],
562 protocol='udp',
563 ethertype='IPv4',
564 port_range_min=80,
565 port_range_max=81)['security_group_rule']
566 cls.addClassResourceCleanup(
567 waiters.wait_for_not_found,
568 cls.lb_mem_SGr_client.delete_security_group_rule,
569 cls.lb_mem_SGr_client.show_security_group_rule,
570 SGr['id'])
571 # Create a security group rule to allow UDP 9999 (test webservers)
572 # Port 9999 is used to illustrate health monitor ERRORs on closed
573 # ports.
574 SGr = cls.lb_mem_SGr_client.create_security_group_rule(
575 direction='ingress',
576 security_group_id=cls.lb_member_sec_group['id'],
577 protocol='udp',
578 ethertype='IPv4',
579 port_range_min=9999,
580 port_range_max=9999)['security_group_rule']
581 cls.addClassResourceCleanup(
582 waiters.wait_for_not_found,
583 cls.lb_mem_SGr_client.delete_security_group_rule,
584 cls.lb_mem_SGr_client.show_security_group_rule,
585 SGr['id'])
Adam Harwellcd72b562018-05-07 11:37:22 -0700586 # Create a security group rule to allow 22 (ssh)
587 SGr = cls.lb_mem_SGr_client.create_security_group_rule(
588 direction='ingress',
589 security_group_id=cls.lb_member_sec_group['id'],
590 protocol='tcp',
591 ethertype='IPv4',
592 port_range_min=22,
593 port_range_max=22)['security_group_rule']
594 cls.addClassResourceCleanup(
595 waiters.wait_for_not_found,
596 cls.lb_mem_SGr_client.delete_security_group_rule,
597 cls.lb_mem_SGr_client.show_security_group_rule,
598 SGr['id'])
599 if CONF.load_balancer.test_with_ipv6:
600 # Create a security group rule to allow 80-81 (test webservers)
601 SGr = cls.lb_mem_SGr_client.create_security_group_rule(
602 direction='ingress',
603 security_group_id=cls.lb_member_sec_group['id'],
604 protocol='tcp',
605 ethertype='IPv6',
606 port_range_min=80,
607 port_range_max=81)['security_group_rule']
608 cls.addClassResourceCleanup(
609 waiters.wait_for_not_found,
610 cls.lb_mem_SGr_client.delete_security_group_rule,
611 cls.lb_mem_SGr_client.show_security_group_rule,
612 SGr['id'])
Gregory Thiemonge29d17902019-04-30 15:06:17 +0200613 # Create a security group rule to allow UDP 80-81 (test
614 # webservers)
615 SGr = cls.lb_mem_SGr_client.create_security_group_rule(
616 direction='ingress',
617 security_group_id=cls.lb_member_sec_group['id'],
618 protocol='udp',
619 ethertype='IPv6',
620 port_range_min=80,
621 port_range_max=81)['security_group_rule']
622 cls.addClassResourceCleanup(
623 waiters.wait_for_not_found,
624 cls.lb_mem_SGr_client.delete_security_group_rule,
625 cls.lb_mem_SGr_client.show_security_group_rule,
626 SGr['id'])
Adam Harwellcd72b562018-05-07 11:37:22 -0700627 # Create a security group rule to allow 22 (ssh)
628 SGr = cls.lb_mem_SGr_client.create_security_group_rule(
629 direction='ingress',
630 security_group_id=cls.lb_member_sec_group['id'],
631 protocol='tcp',
632 ethertype='IPv6',
633 port_range_min=22,
634 port_range_max=22)['security_group_rule']
635 cls.addClassResourceCleanup(
636 waiters.wait_for_not_found,
637 cls.lb_mem_SGr_client.delete_security_group_rule,
638 cls.lb_mem_SGr_client.show_security_group_rule,
639 SGr['id'])
640
641 LOG.info('lb_member_sec_group: {}'.format(cls.lb_member_sec_group))
642
643 # Create webserver 1 instance
644 server_details = cls._create_webserver('lb_member_webserver1',
645 cls.lb_member_1_net)
646
647 cls.lb_member_webserver1 = server_details['server']
648 cls.webserver1_ip = server_details.get('ipv4_address')
649 cls.webserver1_ipv6 = server_details.get('ipv6_address')
650 cls.webserver1_public_ip = server_details['public_ipv4_address']
651
652 LOG.debug('Octavia Setup: lb_member_webserver1 = {}'.format(
653 cls.lb_member_webserver1[const.ID]))
654 LOG.debug('Octavia Setup: webserver1_ip = {}'.format(
655 cls.webserver1_ip))
656 LOG.debug('Octavia Setup: webserver1_ipv6 = {}'.format(
657 cls.webserver1_ipv6))
658 LOG.debug('Octavia Setup: webserver1_public_ip = {}'.format(
659 cls.webserver1_public_ip))
660
661 # Create webserver 2 instance
662 server_details = cls._create_webserver('lb_member_webserver2',
663 cls.lb_member_2_net)
664
665 cls.lb_member_webserver2 = server_details['server']
666 cls.webserver2_ip = server_details.get('ipv4_address')
667 cls.webserver2_ipv6 = server_details.get('ipv6_address')
668 cls.webserver2_public_ip = server_details['public_ipv4_address']
669
670 LOG.debug('Octavia Setup: lb_member_webserver2 = {}'.format(
671 cls.lb_member_webserver2[const.ID]))
672 LOG.debug('Octavia Setup: webserver2_ip = {}'.format(
673 cls.webserver2_ip))
674 LOG.debug('Octavia Setup: webserver2_ipv6 = {}'.format(
675 cls.webserver2_ipv6))
676 LOG.debug('Octavia Setup: webserver2_public_ip = {}'.format(
677 cls.webserver2_public_ip))
678
Michael Johnsonbf916df2018-10-17 10:59:28 -0700679 if CONF.load_balancer.test_with_ipv6:
680 # Enable the IPv6 nic in webserver 1
681 cls._enable_ipv6_nic_webserver(
682 cls.webserver1_public_ip, cls.lb_member_keypair['private_key'],
683 cls.webserver1_ipv6, cls.lb_member_1_subnet_prefix)
684
685 # Enable the IPv6 nic in webserver 2
686 cls._enable_ipv6_nic_webserver(
687 cls.webserver2_public_ip, cls.lb_member_keypair['private_key'],
688 cls.webserver2_ipv6, cls.lb_member_2_subnet_prefix)
689
Adam Harwellcd72b562018-05-07 11:37:22 -0700690 # Set up serving on webserver 1
691 cls._install_start_webserver(cls.webserver1_public_ip,
Adam Harwelle029af22018-05-24 17:13:28 -0700692 cls.lb_member_keypair['private_key'],
693 cls.webserver1_response)
Adam Harwellcd72b562018-05-07 11:37:22 -0700694
695 # Validate webserver 1
Adam Harwelle029af22018-05-24 17:13:28 -0700696 cls._validate_webserver(cls.webserver1_public_ip,
697 cls.webserver1_response)
Adam Harwellcd72b562018-05-07 11:37:22 -0700698
Gregory Thiemonge29d17902019-04-30 15:06:17 +0200699 # Validate udp server 1
700 cls._validate_udp_server(cls.webserver1_public_ip,
701 cls.webserver1_response)
702
Adam Harwellcd72b562018-05-07 11:37:22 -0700703 # Set up serving on webserver 2
704 cls._install_start_webserver(cls.webserver2_public_ip,
Adam Harwelle029af22018-05-24 17:13:28 -0700705 cls.lb_member_keypair['private_key'],
706 cls.webserver2_response)
Adam Harwellcd72b562018-05-07 11:37:22 -0700707
708 # Validate webserver 2
Adam Harwelle029af22018-05-24 17:13:28 -0700709 cls._validate_webserver(cls.webserver2_public_ip,
710 cls.webserver2_response)
Adam Harwellcd72b562018-05-07 11:37:22 -0700711
Gregory Thiemonge29d17902019-04-30 15:06:17 +0200712 # Validate udp server 2
713 cls._validate_udp_server(cls.webserver2_public_ip,
714 cls.webserver2_response)
715
Adam Harwellcd72b562018-05-07 11:37:22 -0700716 @classmethod
717 def _create_networks(cls):
718 super(LoadBalancerBaseTestWithCompute, cls)._create_networks()
Jude Cross986e3f52017-07-24 14:57:20 -0700719 # Create a router for the subnets (required for the floating IP)
720 router_name = data_utils.rand_name("lb_member_router")
721 result = cls.lb_mem_routers_client.create_router(
722 name=router_name, admin_state_up=True,
723 external_gateway_info=dict(
724 network_id=CONF.network.public_network_id))
725 cls.lb_member_router = result['router']
726 LOG.info('lb_member_router: {}'.format(cls.lb_member_router))
727 cls.addClassResourceCleanup(
728 waiters.wait_for_not_found,
729 cls.lb_mem_routers_client.delete_router,
730 cls.lb_mem_routers_client.show_router,
731 cls.lb_member_router['id'])
732
733 # Add VIP subnet to router
734 cls.lb_mem_routers_client.add_router_interface(
735 cls.lb_member_router['id'],
736 subnet_id=cls.lb_member_vip_subnet['id'])
737 cls.addClassResourceCleanup(
738 waiters.wait_for_not_found,
739 cls.lb_mem_routers_client.remove_router_interface,
740 cls.lb_mem_routers_client.remove_router_interface,
741 cls.lb_member_router['id'],
742 subnet_id=cls.lb_member_vip_subnet['id'])
743
744 # Add member subnet 1 to router
745 cls.lb_mem_routers_client.add_router_interface(
746 cls.lb_member_router['id'],
747 subnet_id=cls.lb_member_1_subnet['id'])
748 cls.addClassResourceCleanup(
749 waiters.wait_for_not_found,
Jude Cross986e3f52017-07-24 14:57:20 -0700750 cls.lb_mem_routers_client.remove_router_interface,
751 cls.lb_mem_routers_client.remove_router_interface,
752 cls.lb_member_router['id'], subnet_id=cls.lb_member_1_subnet['id'])
753
754 # Add member subnet 2 to router
755 cls.lb_mem_routers_client.add_router_interface(
756 cls.lb_member_router['id'],
757 subnet_id=cls.lb_member_2_subnet['id'])
758 cls.addClassResourceCleanup(
759 waiters.wait_for_not_found,
760 cls.lb_mem_routers_client.remove_router_interface,
761 cls.lb_mem_routers_client.remove_router_interface,
762 cls.lb_member_router['id'], subnet_id=cls.lb_member_2_subnet['id'])
763
764 @classmethod
765 def _create_webserver(cls, name, network):
766 """Creates a webserver with two ports.
767
768 webserver_details dictionary contains:
769 server - The compute server object
770 ipv4_address - The IPv4 address for the server (optional)
771 ipv6_address - The IPv6 address for the server (optional)
772 public_ipv4_address - The publicly accessible IPv4 address for the
773 server, this may be a floating IP (optional)
774
775 :param name: The name of the server to create.
776 :param network: The network to boot the server on.
777 :returns: webserver_details dictionary.
778 """
779 server_kwargs = {
780 'name': data_utils.rand_name(name),
781 'flavorRef': CONF.compute.flavor_ref,
782 'imageRef': CONF.compute.image_ref,
783 'key_name': cls.lb_member_keypair['name']}
784 if (CONF.load_balancer.enable_security_groups and
785 CONF.network_feature_enabled.port_security):
786 server_kwargs['security_groups'] = [
787 {'name': cls.lb_member_sec_group['name']}]
788 if not CONF.load_balancer.disable_boot_network:
789 server_kwargs['networks'] = [{'uuid': network['id']}]
790
791 # Replace the name for clouds that have limitations
792 if CONF.load_balancer.random_server_name_length:
793 r = random.SystemRandom()
794 server_kwargs['name'] = "m{}".format("".join(
795 [r.choice(string.ascii_uppercase + string.digits)
796 for _ in range(
797 CONF.load_balancer.random_server_name_length - 1)]
798 ))
799 if CONF.load_balancer.availability_zone:
800 server_kwargs['availability_zone'] = (
801 CONF.load_balancer.availability_zone)
802
803 server = cls.lb_mem_servers_client.create_server(
804 **server_kwargs)['server']
805 cls.addClassResourceCleanup(
806 waiters.wait_for_not_found,
807 cls.lb_mem_servers_client.delete_server,
808 cls.lb_mem_servers_client.show_server,
809 server['id'])
810 server = waiters.wait_for_status(
811 cls.lb_mem_servers_client.show_server,
812 server['id'], 'status', 'ACTIVE',
813 CONF.load_balancer.build_interval,
814 CONF.load_balancer.build_timeout,
815 root_tag='server')
816 webserver_details = {'server': server}
817 LOG.info('Created server: {}'.format(server))
818
819 addresses = server['addresses']
820 if CONF.load_balancer.disable_boot_network:
821 instance_network = addresses.values()[0]
822 else:
823 instance_network = addresses[network['name']]
824 for addr in instance_network:
825 if addr['version'] == 4:
826 webserver_details['ipv4_address'] = addr['addr']
827 if addr['version'] == 6:
828 webserver_details['ipv6_address'] = addr['addr']
829
830 if CONF.validation.connect_method == 'floating':
831 result = cls.lb_mem_ports_client.list_ports(
832 network_id=network['id'],
833 mac_address=instance_network[0]['OS-EXT-IPS-MAC:mac_addr'])
834 port_id = result['ports'][0]['id']
835 result = cls.lb_mem_float_ip_client.create_floatingip(
836 floating_network_id=CONF.network.public_network_id,
837 port_id=port_id)
838 floating_ip = result['floatingip']
839 LOG.info('webserver1_floating_ip: {}'.format(floating_ip))
840 cls.addClassResourceCleanup(
841 waiters.wait_for_not_found,
842 cls.lb_mem_float_ip_client.delete_floatingip,
843 cls.lb_mem_float_ip_client.show_floatingip,
844 floatingip_id=floating_ip['id'])
845 webserver_details['public_ipv4_address'] = (
846 floating_ip['floating_ip_address'])
847 else:
848 webserver_details['public_ipv4_address'] = (
849 instance_network[0]['addr'])
850
851 return webserver_details
852
853 @classmethod
Adam Harwellcd72b562018-05-07 11:37:22 -0700854 def _install_start_webserver(cls, ip_address, ssh_key, start_id):
855 local_file = pkg_resources.resource_filename(
Gregory Thiemonge29d17902019-04-30 15:06:17 +0200856 'octavia_tempest_plugin.contrib.test_server', 'test_server.bin')
857 dest_file = '/dev/shm/test_server.bin'
Adam Harwellcd72b562018-05-07 11:37:22 -0700858
859 linux_client = remote_client.RemoteClient(
860 ip_address, CONF.validation.image_ssh_user, pkey=ssh_key)
861 linux_client.validate_authentication()
862
863 with tempfile.NamedTemporaryFile() as key:
864 key.write(ssh_key.encode('utf-8'))
865 key.flush()
866 cmd = ("scp -v -o UserKnownHostsFile=/dev/null "
867 "-o StrictHostKeyChecking=no "
868 "-o ConnectTimeout={0} -o ConnectionAttempts={1} "
869 "-i {2} {3} {4}@{5}:{6}").format(
870 CONF.load_balancer.scp_connection_timeout,
871 CONF.load_balancer.scp_connection_attempts,
872 key.name, local_file, CONF.validation.image_ssh_user,
873 ip_address, dest_file)
874 args = shlex.split(cmd)
875 subprocess_args = {'stdout': subprocess.PIPE,
876 'stderr': subprocess.STDOUT,
877 'cwd': None}
878 proc = subprocess.Popen(args, **subprocess_args)
879 stdout, stderr = proc.communicate()
880 if proc.returncode != 0:
881 raise exceptions.CommandFailed(proc.returncode, cmd,
882 stdout, stderr)
Gregory Thiemongef72a8862019-08-06 17:25:42 +0200883
884 # Enabling memory overcommit allows to run golang static binaries
885 # compiled with a recent golang toolchain (>=1.11). Those binaries
886 # allocate a large amount of virtual memory at init time, and this
887 # allocation fails in tempest's nano flavor (64MB of RAM)
888 # (golang issue reported in https://github.com/golang/go/issues/28114,
889 # follow-up: https://github.com/golang/go/issues/28081)
890 # TODO(gthiemonge): Remove this call when golang issue is resolved.
891 linux_client.exec_command('sudo sh -c "echo 1 > '
892 '/proc/sys/vm/overcommit_memory"')
893
Adam Harwellcd72b562018-05-07 11:37:22 -0700894 linux_client.exec_command('sudo screen -d -m {0} -port 80 '
895 '-id {1}'.format(dest_file, start_id))
896 linux_client.exec_command('sudo screen -d -m {0} -port 81 '
897 '-id {1}'.format(dest_file, start_id + 1))
898
Michael Johnsonbf916df2018-10-17 10:59:28 -0700899 # Cirros does not configure the assigned IPv6 address by default
900 # so enable it manually like tempest does here:
901 # tempest/scenario/test_netowrk_v6.py turn_nic6_on()
902 @classmethod
903 def _enable_ipv6_nic_webserver(cls, ip_address, ssh_key,
904 ipv6_address, ipv6_prefix):
905 linux_client = remote_client.RemoteClient(
906 ip_address, CONF.validation.image_ssh_user, pkey=ssh_key)
907 linux_client.validate_authentication()
908
909 linux_client.exec_command('sudo ip address add {0}/{1} dev '
910 'eth0'.format(ipv6_address, ipv6_prefix))
911
Adam Harwellcd72b562018-05-07 11:37:22 -0700912 @classmethod
Jude Cross986e3f52017-07-24 14:57:20 -0700913 def _validate_webserver(cls, ip_address, start_id):
914 URL = 'http://{0}'.format(ip_address)
915 validators.validate_URL_response(URL, expected_body=str(start_id))
916 URL = 'http://{0}:81'.format(ip_address)
917 validators.validate_URL_response(URL, expected_body=str(start_id + 1))
918
Gregory Thiemonge29d17902019-04-30 15:06:17 +0200919 @classmethod
920 def _validate_udp_server(cls, ip_address, start_id):
921 res = cls._udp_request(ip_address, 80)
922 if res != str(start_id):
923 raise Exception("Response from test server doesn't match the "
924 "expected value ({0} != {1}).".format(
925 res, str(start_id)))
926
927 res = cls._udp_request(ip_address, 81)
928 if res != str(start_id + 1):
929 raise Exception("Response from test server doesn't match the "
930 "expected value ({0} != {1}).".format(
931 res, str(start_id + 1)))
932
933 @classmethod
934 def _udp_request(cls, vip_address, port=80, timeout=None):
935 if ipaddress.ip_address(vip_address).version == 6:
936 family = socket.AF_INET6
937 else:
938 family = socket.AF_INET
939
940 sock = socket.socket(family, socket.SOCK_DGRAM)
941
942 # Force the use of an incremental port number for source to avoid
943 # re-use of a previous source port that will affect the round-robin
944 # dispatch
945 while True:
946 port_number = cls.src_port_number
947 cls.src_port_number += 1
948 if cls.src_port_number >= SRC_PORT_NUMBER_MAX:
949 cls.src_port_number = SRC_PORT_NUMBER_MIN
950
951 # catch and skip already used ports on the host
952 try:
953 sock.bind(('', port_number))
954 except OSError as e:
955 # if error is 'Address already in use', try next port number
956 if e.errno != errno.EADDRINUSE:
957 raise e
958 else:
959 # successfully bind the socket
960 break
961
962 server_address = (vip_address, port)
963 data = b"data\n"
964
965 if timeout is not None:
966 sock.settimeout(timeout)
967
968 sock.sendto(data, server_address)
969 data, addr = sock.recvfrom(4096)
970
971 sock.close()
972
973 return data.decode('utf-8')
974
975 def _wait_for_lb_functional(self, vip_address, traffic_member_count,
976 protocol_port, protocol, verify):
977 if protocol != const.UDP:
978 session = requests.Session()
Adam Harwellcd72b562018-05-07 11:37:22 -0700979 start = time.time()
980
Gregory Thiemonge29d17902019-04-30 15:06:17 +0200981 response_counts = {}
982
983 # Send requests to the load balancer until at least
984 # "traffic_member_count" members have replied (ensure network
985 # connectivity is functional between the load balancer and the membesr)
Adam Harwellcd72b562018-05-07 11:37:22 -0700986 while time.time() - start < CONF.load_balancer.build_timeout:
987 try:
Gregory Thiemonge29d17902019-04-30 15:06:17 +0200988 if protocol != const.UDP:
989 url = "{0}://{1}{2}{3}".format(
990 protocol.lower(),
991 vip_address,
992 ':' if protocol_port else '',
993 protocol_port or '')
994 r = session.get(url, timeout=2, verify=verify)
995 data = r.content
996 else:
997 data = self._udp_request(vip_address, port=protocol_port,
998 timeout=2)
999 if data in response_counts:
1000 response_counts[data] += 1
1001 else:
1002 response_counts[data] = 1
1003
1004 if traffic_member_count == len(response_counts):
1005 LOG.debug('Loadbalancer response totals: %s',
1006 response_counts)
1007 time.sleep(1)
1008 return
Adam Harwellcd72b562018-05-07 11:37:22 -07001009 except Exception:
1010 LOG.warning('Server is not passing initial traffic. Waiting.')
1011 time.sleep(1)
Gregory Thiemonge29d17902019-04-30 15:06:17 +02001012
1013 LOG.debug('Loadbalancer response totals: %s', response_counts)
Adam Harwellcd72b562018-05-07 11:37:22 -07001014 LOG.error('Server did not begin passing traffic within the timeout '
1015 'period. Failing test.')
1016 raise Exception()
1017
Maciej Józefczykb6df5f82019-12-10 10:12:30 +00001018 def _send_lb_request(self, handler, protocol, vip_address,
1019 verify, protocol_port, num=20):
Adam Harwellcd72b562018-05-07 11:37:22 -07001020 response_counts = {}
Gregory Thiemonge29d17902019-04-30 15:06:17 +02001021
Adam Harwellcd72b562018-05-07 11:37:22 -07001022 # Send a number requests to lb vip
Maciej Józefczykb6df5f82019-12-10 10:12:30 +00001023 for i in range(num):
Adam Harwellcd72b562018-05-07 11:37:22 -07001024 try:
Gregory Thiemonge29d17902019-04-30 15:06:17 +02001025 if protocol != const.UDP:
1026 url = "{0}://{1}{2}{3}".format(
1027 protocol.lower(),
1028 vip_address,
1029 ':' if protocol_port else '',
1030 protocol_port or '')
1031 r = handler.get(url, timeout=2, verify=verify)
1032 data = r.content
Adam Harwellcd72b562018-05-07 11:37:22 -07001033 else:
Gregory Thiemonge29d17902019-04-30 15:06:17 +02001034 data = self._udp_request(vip_address, port=protocol_port,
1035 timeout=2)
1036
1037 if data in response_counts:
1038 response_counts[data] += 1
1039 else:
1040 response_counts[data] = 1
1041
Adam Harwellcd72b562018-05-07 11:37:22 -07001042 except Exception:
1043 LOG.exception('Failed to send request to loadbalancer vip')
1044 raise Exception('Failed to connect to lb')
Adam Harwellcd72b562018-05-07 11:37:22 -07001045 LOG.debug('Loadbalancer response totals: %s', response_counts)
Maciej Józefczykb6df5f82019-12-10 10:12:30 +00001046 return response_counts
1047
1048 def _check_members_balanced_round_robin(
Gregory Thiemonge29d17902019-04-30 15:06:17 +02001049 self, vip_address, traffic_member_count=2, protocol=const.HTTP,
Maciej Józefczykb6df5f82019-12-10 10:12:30 +00001050 verify=True, protocol_port=80):
1051
1052 handler = requests.Session()
1053 response_counts = self._send_lb_request(
1054 handler, protocol, vip_address,
1055 verify, protocol_port)
1056
Adam Harwellcd72b562018-05-07 11:37:22 -07001057 # Ensure the correct number of members
Adam Harwell60ed9d92018-05-10 13:23:13 -07001058 self.assertEqual(traffic_member_count, len(response_counts))
Adam Harwellcd72b562018-05-07 11:37:22 -07001059
1060 # Ensure both members got the same number of responses
1061 self.assertEqual(1, len(set(response_counts.values())))
Adam Harwelle029af22018-05-24 17:13:28 -07001062
Maciej Józefczykb6df5f82019-12-10 10:12:30 +00001063 def _check_members_balanced_source_ip_port(
Gregory Thiemonge29d17902019-04-30 15:06:17 +02001064 self, vip_address, traffic_member_count=2, protocol=const.HTTP,
Maciej Józefczykb6df5f82019-12-10 10:12:30 +00001065 verify=True, protocol_port=80):
1066
1067 handler = requests
1068 response_counts = self._send_lb_request(
1069 handler, protocol, vip_address,
1070 verify, protocol_port)
1071 # Ensure the correct number of members
1072 self.assertEqual(traffic_member_count, len(response_counts))
1073
1074 if CONF.load_balancer.test_reuse_connection:
1075 handler = requests.Session()
1076 response_counts = self._send_lb_request(
1077 handler, protocol, vip_address,
1078 verify, protocol_port)
1079 # Ensure only one member answered
1080 self.assertEqual(1, len(response_counts))
1081
1082 def check_members_balanced(self, vip_address, traffic_member_count=2,
Gregory Thiemonge29d17902019-04-30 15:06:17 +02001083 protocol=const.HTTP, verify=True,
1084 protocol_port=80):
Maciej Józefczykb6df5f82019-12-10 10:12:30 +00001085
Gregory Thiemonge29d17902019-04-30 15:06:17 +02001086 if (ipaddress.ip_address(vip_address).version == 6 and
1087 protocol != const.UDP):
Maciej Józefczykb6df5f82019-12-10 10:12:30 +00001088 vip_address = '[{}]'.format(vip_address)
Gregory Thiemonge29d17902019-04-30 15:06:17 +02001089 self._wait_for_lb_functional(vip_address, traffic_member_count,
1090 protocol_port, protocol, verify)
Maciej Józefczykb6df5f82019-12-10 10:12:30 +00001091
1092 validate_func = '_check_members_balanced_%s' % self.lb_algorithm
1093 validate_func = getattr(self, validate_func.lower())
1094 validate_func(
1095 vip_address=vip_address,
1096 traffic_member_count=traffic_member_count,
1097 protocol=protocol,
1098 verify=verify,
1099 protocol_port=protocol_port)
1100
Adam Harwelle029af22018-05-24 17:13:28 -07001101 def assertConsistentResponse(self, response, url, method='GET', repeat=10,
1102 redirect=False, timeout=2, **kwargs):
1103 """Assert that a request to URL gets the expected response.
1104
1105 :param response: Expected response in format (status_code, content).
1106 :param url: The URL to request.
1107 :param method: The HTTP method to use (GET, POST, PUT, etc)
1108 :param repeat: How many times to test the response.
1109 :param data: Optional data to send in the request.
1110 :param headers: Optional headers to send in the request.
1111 :param cookies: Optional cookies to send in the request.
1112 :param redirect: Is the request a redirect? If true, assume the passed
1113 content should be the next URL in the chain.
Carlos Goncalvesc451ff92018-12-19 19:11:53 +01001114 :param timeout: Optional seconds to wait for the server to send data.
1115
Adam Harwelle029af22018-05-24 17:13:28 -07001116 :return: boolean success status
1117
1118 :raises: testtools.matchers.MismatchError
1119 """
1120 session = requests.Session()
1121 response_code, response_content = response
1122
1123 for i in range(0, repeat):
1124 req = session.request(method, url, allow_redirects=not redirect,
1125 timeout=timeout, **kwargs)
1126 if response_code:
1127 self.assertEqual(response_code, req.status_code)
1128 if redirect:
1129 self.assertTrue(req.is_redirect)
Carlos Goncalvesc451ff92018-12-19 19:11:53 +01001130 self.assertEqual(response_content,
1131 session.get_redirect_target(req))
Adam Harwelle029af22018-05-24 17:13:28 -07001132 elif response_content:
1133 self.assertEqual(six.text_type(response_content), req.text)