blob: 6a9c12b19ea9bb12fc6c85a188c49027196c3c83 [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
15import ipaddress
16import pkg_resources
17import random
Adam Harwellcd72b562018-05-07 11:37:22 -070018import requests
Jude Cross986e3f52017-07-24 14:57:20 -070019import shlex
20import six
21import string
22import subprocess
23import tempfile
Adam Harwellcd72b562018-05-07 11:37:22 -070024import time
Jude Cross986e3f52017-07-24 14:57:20 -070025
26from oslo_log import log as logging
27from oslo_utils import uuidutils
28from tempest import config
29from tempest.lib.common.utils import data_utils
30from tempest.lib.common.utils.linux import remote_client
Jude Cross986e3f52017-07-24 14:57:20 -070031from tempest.lib import exceptions
32from tempest import test
Michael Johnson04dc5cb2019-01-20 11:03:50 -080033import tenacity
Jude Cross986e3f52017-07-24 14:57:20 -070034
35from octavia_tempest_plugin import clients
36from octavia_tempest_plugin.common import constants as const
37from octavia_tempest_plugin.tests import validators
38from octavia_tempest_plugin.tests import waiters
39
40CONF = config.CONF
41LOG = logging.getLogger(__name__)
42
Michael Johnson04dc5cb2019-01-20 11:03:50 -080043RETRY_ATTEMPTS = 15
44RETRY_INITIAL_DELAY = 1
45RETRY_BACKOFF = 1
46RETRY_MAX = 5
47
Jude Cross986e3f52017-07-24 14:57:20 -070048
49class LoadBalancerBaseTest(test.BaseTestCase):
50 """Base class for load balancer tests."""
51
52 # Setup cls.os_roles_lb_member. cls.os_primary, cls.os_roles_lb_member,
53 # and cls.os_roles_lb_admin credentials.
54 credentials = ['admin', 'primary',
55 ['lb_member', CONF.load_balancer.member_role],
56 ['lb_member2', CONF.load_balancer.member_role],
57 ['lb_admin', CONF.load_balancer.admin_role]]
58
59 client_manager = clients.ManagerV2
Adam Harwelle029af22018-05-24 17:13:28 -070060 webserver1_response = 1
61 webserver2_response = 5
Michael Johnsondfd818a2018-08-21 20:54:54 -070062 used_ips = []
Jude Cross986e3f52017-07-24 14:57:20 -070063
64 @classmethod
65 def skip_checks(cls):
66 """Check if we should skip all of the children tests."""
67 super(LoadBalancerBaseTest, cls).skip_checks()
68
69 service_list = {
70 'load_balancer': CONF.service_available.load_balancer,
71 }
72
73 live_service_list = {
74 'compute': CONF.service_available.nova,
75 'image': CONF.service_available.glance,
76 'neutron': CONF.service_available.neutron
77 }
78
79 if not CONF.load_balancer.test_with_noop:
80 service_list.update(live_service_list)
81
82 for service, available in service_list.items():
83 if not available:
zhangzs2a6cf672018-11-10 16:13:11 +080084 skip_msg = ("{0} skipped as {1} service is not "
Jude Cross986e3f52017-07-24 14:57:20 -070085 "available.".format(cls.__name__, service))
86 raise cls.skipException(skip_msg)
87
88 # We must be able to reach our VIP and instances
89 if not (CONF.network.project_networks_reachable
90 or CONF.network.public_network_id):
91 msg = ('Either project_networks_reachable must be "true", or '
92 'public_network_id must be defined.')
93 raise cls.skipException(msg)
94
95 @classmethod
96 def setup_credentials(cls):
97 """Setup test credentials and network resources."""
98 # Do not auto create network resources
99 cls.set_network_resources()
100 super(LoadBalancerBaseTest, cls).setup_credentials()
101
102 @classmethod
103 def setup_clients(cls):
104 """Setup client aliases."""
105 super(LoadBalancerBaseTest, cls).setup_clients()
106 cls.lb_mem_float_ip_client = cls.os_roles_lb_member.floating_ips_client
107 cls.lb_mem_keypairs_client = cls.os_roles_lb_member.keypairs_client
108 cls.lb_mem_net_client = cls.os_roles_lb_member.networks_client
109 cls.lb_mem_ports_client = cls.os_roles_lb_member.ports_client
110 cls.lb_mem_routers_client = cls.os_roles_lb_member.routers_client
111 cls.lb_mem_SG_client = cls.os_roles_lb_member.security_groups_client
112 cls.lb_mem_SGr_client = (
113 cls.os_roles_lb_member.security_group_rules_client)
114 cls.lb_mem_servers_client = cls.os_roles_lb_member.servers_client
115 cls.lb_mem_subnet_client = cls.os_roles_lb_member.subnets_client
116 cls.mem_lb_client = cls.os_roles_lb_member.loadbalancer_client
Jude Crossfbbd2b42017-08-09 15:21:04 -0700117 cls.mem_listener_client = cls.os_roles_lb_member.listener_client
Adam Harwell8ffce3e2018-05-01 21:18:44 -0700118 cls.mem_pool_client = cls.os_roles_lb_member.pool_client
Adam Harwellde3e0542018-05-03 18:21:06 -0700119 cls.mem_member_client = cls.os_roles_lb_member.member_client
Adam Harwell60ed9d92018-05-10 13:23:13 -0700120 cls.mem_healthmonitor_client = (
121 cls.os_roles_lb_member.healthmonitor_client)
Adam Harwell446f8be2018-05-24 16:51:03 -0700122 cls.mem_l7policy_client = cls.os_roles_lb_member.l7policy_client
Adam Harwelle029af22018-05-24 17:13:28 -0700123 cls.mem_l7rule_client = cls.os_roles_lb_member.l7rule_client
Adam Harwelldfc11ee2018-05-30 09:38:55 -0700124 cls.mem_amphora_client = cls.os_roles_lb_member.amphora_client
Michael Johnsonaff2e862019-01-11 16:38:00 -0800125 cls.lb_admin_flavor_profile_client = (
126 cls.os_roles_lb_admin.flavor_profile_client)
Michael Johnsona2d03072019-01-14 17:18:21 -0800127 cls.lb_admin_flavor_client = cls.os_roles_lb_admin.flavor_client
128 cls.mem_flavor_client = cls.os_roles_lb_member.flavor_client
Michael Johnsonfc223fe2019-01-15 16:40:05 -0800129 cls.mem_provider_client = cls.os_roles_lb_member.provider_client
Carlos Goncalvesc2e12162019-02-14 23:57:44 +0100130 cls.os_admin_servers_client = cls.os_admin.servers_client
Jude Cross986e3f52017-07-24 14:57:20 -0700131
132 @classmethod
133 def resource_setup(cls):
134 """Setup resources needed by the tests."""
135 super(LoadBalancerBaseTest, cls).resource_setup()
136
137 conf_lb = CONF.load_balancer
138
Michael Johnsondfd818a2018-08-21 20:54:54 -0700139 cls.api_version = cls.mem_lb_client.get_max_api_version()
140
Jude Cross986e3f52017-07-24 14:57:20 -0700141 if conf_lb.test_subnet_override and not conf_lb.test_network_override:
142 raise exceptions.InvalidConfiguration(
143 "Configuration value test_network_override must be "
144 "specified if test_subnet_override is used.")
145
146 show_subnet = cls.lb_mem_subnet_client.show_subnet
147 if CONF.load_balancer.test_with_noop:
148 cls.lb_member_vip_net = {'id': uuidutils.generate_uuid()}
149 cls.lb_member_vip_subnet = {'id': uuidutils.generate_uuid()}
150 cls.lb_member_1_net = {'id': uuidutils.generate_uuid()}
151 cls.lb_member_1_subnet = {'id': uuidutils.generate_uuid()}
152 cls.lb_member_2_net = {'id': uuidutils.generate_uuid()}
153 cls.lb_member_2_subnet = {'id': uuidutils.generate_uuid()}
154 if CONF.load_balancer.test_with_ipv6:
Michael Johnson5a16ad32018-10-18 14:49:11 -0700155 cls.lb_member_vip_ipv6_net = {'id': uuidutils.generate_uuid()}
Jude Cross986e3f52017-07-24 14:57:20 -0700156 cls.lb_member_vip_ipv6_subnet = {'id':
157 uuidutils.generate_uuid()}
158 cls.lb_member_1_ipv6_subnet = {'id': uuidutils.generate_uuid()}
159 cls.lb_member_2_ipv6_subnet = {'id': uuidutils.generate_uuid()}
160 return
161 elif CONF.load_balancer.test_network_override:
162 if conf_lb.test_subnet_override:
163 override_subnet = show_subnet(conf_lb.test_subnet_override)
164 else:
165 override_subnet = None
166
167 show_net = cls.lb_mem_net_client.show_network
168 override_network = show_net(conf_lb.test_network_override)
169 override_network = override_network.get('network')
170
171 cls.lb_member_vip_net = override_network
172 cls.lb_member_vip_subnet = override_subnet
173 cls.lb_member_1_net = override_network
174 cls.lb_member_1_subnet = override_subnet
175 cls.lb_member_2_net = override_network
176 cls.lb_member_2_subnet = override_subnet
177
178 if (CONF.load_balancer.test_with_ipv6 and
179 conf_lb.test_IPv6_subnet_override):
180 override_ipv6_subnet = show_subnet(
181 conf_lb.test_IPv6_subnet_override)
182 cls.lb_member_vip_ipv6_subnet = override_ipv6_subnet
183 cls.lb_member_1_ipv6_subnet = override_ipv6_subnet
184 cls.lb_member_2_ipv6_subnet = override_ipv6_subnet
185 else:
186 cls.lb_member_vip_ipv6_subnet = None
187 cls.lb_member_1_ipv6_subnet = None
188 cls.lb_member_2_ipv6_subnet = None
189 else:
190 cls._create_networks()
191
192 LOG.debug('Octavia Setup: lb_member_vip_net = {}'.format(
193 cls.lb_member_vip_net[const.ID]))
194 if cls.lb_member_vip_subnet:
195 LOG.debug('Octavia Setup: lb_member_vip_subnet = {}'.format(
196 cls.lb_member_vip_subnet[const.ID]))
197 LOG.debug('Octavia Setup: lb_member_1_net = {}'.format(
198 cls.lb_member_1_net[const.ID]))
199 if cls.lb_member_1_subnet:
200 LOG.debug('Octavia Setup: lb_member_1_subnet = {}'.format(
201 cls.lb_member_1_subnet[const.ID]))
202 LOG.debug('Octavia Setup: lb_member_2_net = {}'.format(
203 cls.lb_member_2_net[const.ID]))
204 if cls.lb_member_2_subnet:
205 LOG.debug('Octavia Setup: lb_member_2_subnet = {}'.format(
206 cls.lb_member_2_subnet[const.ID]))
Michael Johnson124ba8b2018-08-30 16:06:05 -0700207 if CONF.load_balancer.test_with_ipv6:
208 if cls.lb_member_vip_ipv6_subnet:
209 LOG.debug('Octavia Setup: lb_member_vip_ipv6_subnet = '
210 '{}'.format(cls.lb_member_vip_ipv6_subnet[const.ID]))
211 if cls.lb_member_1_ipv6_subnet:
212 LOG.debug('Octavia Setup: lb_member_1_ipv6_subnet = {}'.format(
213 cls.lb_member_1_ipv6_subnet[const.ID]))
214 if cls.lb_member_2_ipv6_subnet:
215 LOG.debug('Octavia Setup: lb_member_2_ipv6_subnet = {}'.format(
216 cls.lb_member_2_ipv6_subnet[const.ID]))
Jude Cross986e3f52017-07-24 14:57:20 -0700217
Jude Cross986e3f52017-07-24 14:57:20 -0700218 @classmethod
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800219 # Neutron can be slow to clean up ports from the subnets/networks.
220 # Retry this delete a few times if we get a "Conflict" error to give
221 # neutron time to fully cleanup the ports.
222 @tenacity.retry(
223 retry=tenacity.retry_if_exception_type(exceptions.Conflict),
224 wait=tenacity.wait_incrementing(
225 RETRY_INITIAL_DELAY, RETRY_BACKOFF, RETRY_MAX),
226 stop=tenacity.stop_after_attempt(RETRY_ATTEMPTS))
227 def _logging_delete_network(cls, net_id):
228 try:
229 cls.lb_mem_net_client.delete_network(net_id)
230 except Exception:
231 LOG.error('Unable to delete network {}. Active ports:'.format(
232 net_id))
233 LOG.error(cls.lb_mem_ports_client.list_ports())
234 raise
235
236 @classmethod
237 # Neutron can be slow to clean up ports from the subnets/networks.
238 # Retry this delete a few times if we get a "Conflict" error to give
239 # neutron time to fully cleanup the ports.
240 @tenacity.retry(
241 retry=tenacity.retry_if_exception_type(exceptions.Conflict),
242 wait=tenacity.wait_incrementing(
243 RETRY_INITIAL_DELAY, RETRY_BACKOFF, RETRY_MAX),
244 stop=tenacity.stop_after_attempt(RETRY_ATTEMPTS))
245 def _logging_delete_subnet(cls, subnet_id):
246 try:
247 cls.lb_mem_subnet_client.delete_subnet(subnet_id)
248 except Exception:
249 LOG.error('Unable to delete subnet {}. Active ports:'.format(
250 subnet_id))
251 LOG.error(cls.lb_mem_ports_client.list_ports())
252 raise
253
254 @classmethod
Jude Cross986e3f52017-07-24 14:57:20 -0700255 def _create_networks(cls):
256 """Creates networks, subnets, and routers used in tests.
257
258 The following are expected to be defined and available to the tests:
259 cls.lb_member_vip_net
260 cls.lb_member_vip_subnet
261 cls.lb_member_vip_ipv6_subnet (optional)
262 cls.lb_member_1_net
263 cls.lb_member_1_subnet
264 cls.lb_member_1_ipv6_subnet (optional)
265 cls.lb_member_2_net
266 cls.lb_member_2_subnet
267 cls.lb_member_2_ipv6_subnet (optional)
268 """
269
270 # Create tenant VIP network
271 network_kwargs = {
272 'name': data_utils.rand_name("lb_member_vip_network")}
273 if CONF.network_feature_enabled.port_security:
274 # Note: Allowed Address Pairs requires port security
275 network_kwargs['port_security_enabled'] = True
276 result = cls.lb_mem_net_client.create_network(**network_kwargs)
277 cls.lb_member_vip_net = result['network']
278 LOG.info('lb_member_vip_net: {}'.format(cls.lb_member_vip_net))
279 cls.addClassResourceCleanup(
280 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800281 cls._logging_delete_network,
Jude Cross986e3f52017-07-24 14:57:20 -0700282 cls.lb_mem_net_client.show_network,
283 cls.lb_member_vip_net['id'])
284
285 # Create tenant VIP subnet
286 subnet_kwargs = {
287 'name': data_utils.rand_name("lb_member_vip_subnet"),
288 'network_id': cls.lb_member_vip_net['id'],
289 'cidr': CONF.load_balancer.vip_subnet_cidr,
290 'ip_version': 4}
291 result = cls.lb_mem_subnet_client.create_subnet(**subnet_kwargs)
292 cls.lb_member_vip_subnet = result['subnet']
293 LOG.info('lb_member_vip_subnet: {}'.format(cls.lb_member_vip_subnet))
294 cls.addClassResourceCleanup(
295 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800296 cls._logging_delete_subnet,
Jude Cross986e3f52017-07-24 14:57:20 -0700297 cls.lb_mem_subnet_client.show_subnet,
298 cls.lb_member_vip_subnet['id'])
299
300 # Create tenant VIP IPv6 subnet
301 if CONF.load_balancer.test_with_ipv6:
Michael Johnson5a16ad32018-10-18 14:49:11 -0700302 # See if ipv6-public-subnet exists and use it if so.
303 pub_ipv6_subnet = cls.os_admin.subnets_client.list_subnets(
304 name='ipv6-public-subnet')['subnets']
305
306 if len(pub_ipv6_subnet) == 1:
307 cls.lb_member_vip_ipv6_subnet = pub_ipv6_subnet[0]
308 cls.lb_member_vip_ipv6_net = {
309 'id': pub_ipv6_subnet[0]['network_id']}
310 else:
311 subnet_kwargs = {
312 'name': data_utils.rand_name("lb_member_vip_ipv6_subnet"),
313 'network_id': cls.lb_member_vip_net['id'],
314 'cidr': CONF.load_balancer.vip_ipv6_subnet_cidr,
315 'ip_version': 6}
316 result = cls.lb_mem_subnet_client.create_subnet(
317 **subnet_kwargs)
318 cls.lb_member_vip_ipv6_subnet = result['subnet']
319 cls.addClassResourceCleanup(
320 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800321 cls._logging_delete_subnet,
Michael Johnson5a16ad32018-10-18 14:49:11 -0700322 cls.lb_mem_subnet_client.show_subnet,
323 cls.lb_member_vip_ipv6_subnet['id'])
Jude Cross986e3f52017-07-24 14:57:20 -0700324 LOG.info('lb_member_vip_ipv6_subnet: {}'.format(
325 cls.lb_member_vip_ipv6_subnet))
Jude Cross986e3f52017-07-24 14:57:20 -0700326
327 # Create tenant member 1 network
328 network_kwargs = {
329 'name': data_utils.rand_name("lb_member_1_network")}
330 if CONF.network_feature_enabled.port_security:
331 if CONF.load_balancer.enable_security_groups:
332 network_kwargs['port_security_enabled'] = True
333 else:
334 network_kwargs['port_security_enabled'] = False
335 result = cls.lb_mem_net_client.create_network(**network_kwargs)
336 cls.lb_member_1_net = result['network']
337 LOG.info('lb_member_1_net: {}'.format(cls.lb_member_1_net))
338 cls.addClassResourceCleanup(
339 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800340 cls._logging_delete_network,
Jude Cross986e3f52017-07-24 14:57:20 -0700341 cls.lb_mem_net_client.show_network,
342 cls.lb_member_1_net['id'])
343
344 # Create tenant member 1 subnet
345 subnet_kwargs = {
346 'name': data_utils.rand_name("lb_member_1_subnet"),
347 'network_id': cls.lb_member_1_net['id'],
348 'cidr': CONF.load_balancer.member_1_ipv4_subnet_cidr,
349 'ip_version': 4}
350 result = cls.lb_mem_subnet_client.create_subnet(**subnet_kwargs)
351 cls.lb_member_1_subnet = result['subnet']
352 LOG.info('lb_member_1_subnet: {}'.format(cls.lb_member_1_subnet))
353 cls.addClassResourceCleanup(
354 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800355 cls._logging_delete_subnet,
Jude Cross986e3f52017-07-24 14:57:20 -0700356 cls.lb_mem_subnet_client.show_subnet,
357 cls.lb_member_1_subnet['id'])
358
359 # Create tenant member 1 ipv6 subnet
360 if CONF.load_balancer.test_with_ipv6:
361 subnet_kwargs = {
362 'name': data_utils.rand_name("lb_member_1_ipv6_subnet"),
363 'network_id': cls.lb_member_1_net['id'],
364 'cidr': CONF.load_balancer.member_1_ipv6_subnet_cidr,
365 'ip_version': 6}
366 result = cls.lb_mem_subnet_client.create_subnet(**subnet_kwargs)
Michael Johnsonbf916df2018-10-17 10:59:28 -0700367 cls.lb_member_1_subnet_prefix = (
368 CONF.load_balancer.member_1_ipv6_subnet_cidr.rpartition('/')[2]
369 )
370 assert(cls.lb_member_1_subnet_prefix.isdigit())
Jude Cross986e3f52017-07-24 14:57:20 -0700371 cls.lb_member_1_ipv6_subnet = result['subnet']
372 LOG.info('lb_member_1_ipv6_subnet: {}'.format(
373 cls.lb_member_1_ipv6_subnet))
374 cls.addClassResourceCleanup(
375 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800376 cls._logging_delete_subnet,
Jude Cross986e3f52017-07-24 14:57:20 -0700377 cls.lb_mem_subnet_client.show_subnet,
378 cls.lb_member_1_ipv6_subnet['id'])
379
380 # Create tenant member 2 network
381 network_kwargs = {
382 'name': data_utils.rand_name("lb_member_2_network")}
383 if CONF.network_feature_enabled.port_security:
384 if CONF.load_balancer.enable_security_groups:
385 network_kwargs['port_security_enabled'] = True
386 else:
387 network_kwargs['port_security_enabled'] = False
388 result = cls.lb_mem_net_client.create_network(**network_kwargs)
389 cls.lb_member_2_net = result['network']
390 LOG.info('lb_member_2_net: {}'.format(cls.lb_member_2_net))
391 cls.addClassResourceCleanup(
392 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800393 cls._logging_delete_network,
Jude Cross986e3f52017-07-24 14:57:20 -0700394 cls.lb_mem_net_client.show_network,
395 cls.lb_member_2_net['id'])
396
397 # Create tenant member 2 subnet
398 subnet_kwargs = {
399 'name': data_utils.rand_name("lb_member_2_subnet"),
400 'network_id': cls.lb_member_2_net['id'],
401 'cidr': CONF.load_balancer.member_2_ipv4_subnet_cidr,
402 'ip_version': 4}
403 result = cls.lb_mem_subnet_client.create_subnet(**subnet_kwargs)
404 cls.lb_member_2_subnet = result['subnet']
405 LOG.info('lb_member_2_subnet: {}'.format(cls.lb_member_2_subnet))
406 cls.addClassResourceCleanup(
407 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800408 cls._logging_delete_subnet,
Jude Cross986e3f52017-07-24 14:57:20 -0700409 cls.lb_mem_subnet_client.show_subnet,
410 cls.lb_member_2_subnet['id'])
411
412 # Create tenant member 2 ipv6 subnet
413 if CONF.load_balancer.test_with_ipv6:
414 subnet_kwargs = {
415 'name': data_utils.rand_name("lb_member_2_ipv6_subnet"),
416 'network_id': cls.lb_member_2_net['id'],
417 'cidr': CONF.load_balancer.member_2_ipv6_subnet_cidr,
418 'ip_version': 6}
419 result = cls.lb_mem_subnet_client.create_subnet(**subnet_kwargs)
Michael Johnsonbf916df2018-10-17 10:59:28 -0700420 cls.lb_member_2_subnet_prefix = (
421 CONF.load_balancer.member_2_ipv6_subnet_cidr.rpartition('/')[2]
422 )
423 assert(cls.lb_member_2_subnet_prefix.isdigit())
Jude Cross986e3f52017-07-24 14:57:20 -0700424 cls.lb_member_2_ipv6_subnet = result['subnet']
425 LOG.info('lb_member_2_ipv6_subnet: {}'.format(
426 cls.lb_member_2_ipv6_subnet))
427 cls.addClassResourceCleanup(
428 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800429 cls._logging_delete_subnet,
Jude Cross986e3f52017-07-24 14:57:20 -0700430 cls.lb_mem_subnet_client.show_subnet,
431 cls.lb_member_2_ipv6_subnet['id'])
432
Adam Harwellcd72b562018-05-07 11:37:22 -0700433 @classmethod
Michael Johnson07c9a632018-06-07 13:27:42 -0700434 def _setup_lb_network_kwargs(cls, lb_kwargs, ip_version=None,
435 use_fixed_ip=False):
Adam Harwell60ed9d92018-05-10 13:23:13 -0700436 if not ip_version:
437 ip_version = 6 if CONF.load_balancer.test_with_ipv6 else 4
Michael Johnson5a16ad32018-10-18 14:49:11 -0700438 if cls.lb_member_vip_subnet or cls.lb_member_vip_ipv6_subnet:
Adam Harwellcd72b562018-05-07 11:37:22 -0700439 ip_index = data_utils.rand_int_id(start=10, end=100)
Michael Johnsondfd818a2018-08-21 20:54:54 -0700440 while ip_index in cls.used_ips:
441 ip_index = data_utils.rand_int_id(start=10, end=100)
442 cls.used_ips.append(ip_index)
Adam Harwellcd72b562018-05-07 11:37:22 -0700443 if ip_version == 4:
Adam Harwellcd72b562018-05-07 11:37:22 -0700444 subnet_id = cls.lb_member_vip_subnet[const.ID]
Michael Johnson5a16ad32018-10-18 14:49:11 -0700445 if CONF.load_balancer.test_with_noop:
446 lb_vip_address = '198.18.33.33'
447 else:
448 subnet = cls.os_admin.subnets_client.show_subnet(subnet_id)
449 network = ipaddress.IPv4Network(subnet['subnet']['cidr'])
450 lb_vip_address = str(network[ip_index])
Adam Harwellcd72b562018-05-07 11:37:22 -0700451 else:
Adam Harwellcd72b562018-05-07 11:37:22 -0700452 subnet_id = cls.lb_member_vip_ipv6_subnet[const.ID]
Michael Johnson5a16ad32018-10-18 14:49:11 -0700453 if CONF.load_balancer.test_with_noop:
454 lb_vip_address = '2001:db8:33:33:33:33:33:33'
455 else:
456 subnet = cls.os_admin.subnets_client.show_subnet(subnet_id)
457 network = ipaddress.IPv6Network(subnet['subnet']['cidr'])
458 lb_vip_address = str(network[ip_index])
Adam Harwellcd72b562018-05-07 11:37:22 -0700459 lb_kwargs[const.VIP_SUBNET_ID] = subnet_id
Michael Johnson07c9a632018-06-07 13:27:42 -0700460 if use_fixed_ip:
461 lb_kwargs[const.VIP_ADDRESS] = lb_vip_address
Adam Harwellcd72b562018-05-07 11:37:22 -0700462 if CONF.load_balancer.test_with_noop:
463 lb_kwargs[const.VIP_NETWORK_ID] = (
464 cls.lb_member_vip_net[const.ID])
465 else:
466 lb_kwargs[const.VIP_NETWORK_ID] = cls.lb_member_vip_net[const.ID]
467 lb_kwargs[const.VIP_SUBNET_ID] = None
468
469
470class LoadBalancerBaseTestWithCompute(LoadBalancerBaseTest):
471 @classmethod
472 def resource_setup(cls):
473 super(LoadBalancerBaseTestWithCompute, cls).resource_setup()
474 # If validation is disabled in this cloud, we won't be able to
475 # start the webservers, so don't even boot them.
476 if not CONF.validation.run_validation:
477 return
478
479 # Create a keypair for the webservers
480 keypair_name = data_utils.rand_name('lb_member_keypair')
481 result = cls.lb_mem_keypairs_client.create_keypair(
482 name=keypair_name)
483 cls.lb_member_keypair = result['keypair']
484 LOG.info('lb_member_keypair: {}'.format(cls.lb_member_keypair))
485 cls.addClassResourceCleanup(
486 waiters.wait_for_not_found,
487 cls.lb_mem_keypairs_client.delete_keypair,
488 cls.lb_mem_keypairs_client.show_keypair,
489 keypair_name)
490
491 if (CONF.load_balancer.enable_security_groups and
492 CONF.network_feature_enabled.port_security):
493 # Set up the security group for the webservers
494 SG_name = data_utils.rand_name('lb_member_SG')
495 cls.lb_member_sec_group = (
496 cls.lb_mem_SG_client.create_security_group(
497 name=SG_name)['security_group'])
498 cls.addClassResourceCleanup(
499 waiters.wait_for_not_found,
500 cls.lb_mem_SG_client.delete_security_group,
501 cls.lb_mem_SG_client.show_security_group,
502 cls.lb_member_sec_group['id'])
503
504 # Create a security group rule to allow 80-81 (test webservers)
505 SGr = cls.lb_mem_SGr_client.create_security_group_rule(
506 direction='ingress',
507 security_group_id=cls.lb_member_sec_group['id'],
508 protocol='tcp',
509 ethertype='IPv4',
510 port_range_min=80,
511 port_range_max=81)['security_group_rule']
512 cls.addClassResourceCleanup(
513 waiters.wait_for_not_found,
514 cls.lb_mem_SGr_client.delete_security_group_rule,
515 cls.lb_mem_SGr_client.show_security_group_rule,
516 SGr['id'])
517 # Create a security group rule to allow 22 (ssh)
518 SGr = cls.lb_mem_SGr_client.create_security_group_rule(
519 direction='ingress',
520 security_group_id=cls.lb_member_sec_group['id'],
521 protocol='tcp',
522 ethertype='IPv4',
523 port_range_min=22,
524 port_range_max=22)['security_group_rule']
525 cls.addClassResourceCleanup(
526 waiters.wait_for_not_found,
527 cls.lb_mem_SGr_client.delete_security_group_rule,
528 cls.lb_mem_SGr_client.show_security_group_rule,
529 SGr['id'])
530 if CONF.load_balancer.test_with_ipv6:
531 # Create a security group rule to allow 80-81 (test webservers)
532 SGr = cls.lb_mem_SGr_client.create_security_group_rule(
533 direction='ingress',
534 security_group_id=cls.lb_member_sec_group['id'],
535 protocol='tcp',
536 ethertype='IPv6',
537 port_range_min=80,
538 port_range_max=81)['security_group_rule']
539 cls.addClassResourceCleanup(
540 waiters.wait_for_not_found,
541 cls.lb_mem_SGr_client.delete_security_group_rule,
542 cls.lb_mem_SGr_client.show_security_group_rule,
543 SGr['id'])
544 # Create a security group rule to allow 22 (ssh)
545 SGr = cls.lb_mem_SGr_client.create_security_group_rule(
546 direction='ingress',
547 security_group_id=cls.lb_member_sec_group['id'],
548 protocol='tcp',
549 ethertype='IPv6',
550 port_range_min=22,
551 port_range_max=22)['security_group_rule']
552 cls.addClassResourceCleanup(
553 waiters.wait_for_not_found,
554 cls.lb_mem_SGr_client.delete_security_group_rule,
555 cls.lb_mem_SGr_client.show_security_group_rule,
556 SGr['id'])
557
558 LOG.info('lb_member_sec_group: {}'.format(cls.lb_member_sec_group))
559
560 # Create webserver 1 instance
561 server_details = cls._create_webserver('lb_member_webserver1',
562 cls.lb_member_1_net)
563
564 cls.lb_member_webserver1 = server_details['server']
565 cls.webserver1_ip = server_details.get('ipv4_address')
566 cls.webserver1_ipv6 = server_details.get('ipv6_address')
567 cls.webserver1_public_ip = server_details['public_ipv4_address']
568
569 LOG.debug('Octavia Setup: lb_member_webserver1 = {}'.format(
570 cls.lb_member_webserver1[const.ID]))
571 LOG.debug('Octavia Setup: webserver1_ip = {}'.format(
572 cls.webserver1_ip))
573 LOG.debug('Octavia Setup: webserver1_ipv6 = {}'.format(
574 cls.webserver1_ipv6))
575 LOG.debug('Octavia Setup: webserver1_public_ip = {}'.format(
576 cls.webserver1_public_ip))
577
578 # Create webserver 2 instance
579 server_details = cls._create_webserver('lb_member_webserver2',
580 cls.lb_member_2_net)
581
582 cls.lb_member_webserver2 = server_details['server']
583 cls.webserver2_ip = server_details.get('ipv4_address')
584 cls.webserver2_ipv6 = server_details.get('ipv6_address')
585 cls.webserver2_public_ip = server_details['public_ipv4_address']
586
587 LOG.debug('Octavia Setup: lb_member_webserver2 = {}'.format(
588 cls.lb_member_webserver2[const.ID]))
589 LOG.debug('Octavia Setup: webserver2_ip = {}'.format(
590 cls.webserver2_ip))
591 LOG.debug('Octavia Setup: webserver2_ipv6 = {}'.format(
592 cls.webserver2_ipv6))
593 LOG.debug('Octavia Setup: webserver2_public_ip = {}'.format(
594 cls.webserver2_public_ip))
595
Michael Johnsonbf916df2018-10-17 10:59:28 -0700596 if CONF.load_balancer.test_with_ipv6:
597 # Enable the IPv6 nic in webserver 1
598 cls._enable_ipv6_nic_webserver(
599 cls.webserver1_public_ip, cls.lb_member_keypair['private_key'],
600 cls.webserver1_ipv6, cls.lb_member_1_subnet_prefix)
601
602 # Enable the IPv6 nic in webserver 2
603 cls._enable_ipv6_nic_webserver(
604 cls.webserver2_public_ip, cls.lb_member_keypair['private_key'],
605 cls.webserver2_ipv6, cls.lb_member_2_subnet_prefix)
606
Adam Harwellcd72b562018-05-07 11:37:22 -0700607 # Set up serving on webserver 1
608 cls._install_start_webserver(cls.webserver1_public_ip,
Adam Harwelle029af22018-05-24 17:13:28 -0700609 cls.lb_member_keypair['private_key'],
610 cls.webserver1_response)
Adam Harwellcd72b562018-05-07 11:37:22 -0700611
612 # Validate webserver 1
Adam Harwelle029af22018-05-24 17:13:28 -0700613 cls._validate_webserver(cls.webserver1_public_ip,
614 cls.webserver1_response)
Adam Harwellcd72b562018-05-07 11:37:22 -0700615
616 # Set up serving on webserver 2
617 cls._install_start_webserver(cls.webserver2_public_ip,
Adam Harwelle029af22018-05-24 17:13:28 -0700618 cls.lb_member_keypair['private_key'],
619 cls.webserver2_response)
Adam Harwellcd72b562018-05-07 11:37:22 -0700620
621 # Validate webserver 2
Adam Harwelle029af22018-05-24 17:13:28 -0700622 cls._validate_webserver(cls.webserver2_public_ip,
623 cls.webserver2_response)
Adam Harwellcd72b562018-05-07 11:37:22 -0700624
625 @classmethod
626 def _create_networks(cls):
627 super(LoadBalancerBaseTestWithCompute, cls)._create_networks()
Jude Cross986e3f52017-07-24 14:57:20 -0700628 # Create a router for the subnets (required for the floating IP)
629 router_name = data_utils.rand_name("lb_member_router")
630 result = cls.lb_mem_routers_client.create_router(
631 name=router_name, admin_state_up=True,
632 external_gateway_info=dict(
633 network_id=CONF.network.public_network_id))
634 cls.lb_member_router = result['router']
635 LOG.info('lb_member_router: {}'.format(cls.lb_member_router))
636 cls.addClassResourceCleanup(
637 waiters.wait_for_not_found,
638 cls.lb_mem_routers_client.delete_router,
639 cls.lb_mem_routers_client.show_router,
640 cls.lb_member_router['id'])
641
642 # Add VIP subnet to router
643 cls.lb_mem_routers_client.add_router_interface(
644 cls.lb_member_router['id'],
645 subnet_id=cls.lb_member_vip_subnet['id'])
646 cls.addClassResourceCleanup(
647 waiters.wait_for_not_found,
648 cls.lb_mem_routers_client.remove_router_interface,
649 cls.lb_mem_routers_client.remove_router_interface,
650 cls.lb_member_router['id'],
651 subnet_id=cls.lb_member_vip_subnet['id'])
652
653 # Add member subnet 1 to router
654 cls.lb_mem_routers_client.add_router_interface(
655 cls.lb_member_router['id'],
656 subnet_id=cls.lb_member_1_subnet['id'])
657 cls.addClassResourceCleanup(
658 waiters.wait_for_not_found,
Jude Cross986e3f52017-07-24 14:57:20 -0700659 cls.lb_mem_routers_client.remove_router_interface,
660 cls.lb_mem_routers_client.remove_router_interface,
661 cls.lb_member_router['id'], subnet_id=cls.lb_member_1_subnet['id'])
662
663 # Add member subnet 2 to router
664 cls.lb_mem_routers_client.add_router_interface(
665 cls.lb_member_router['id'],
666 subnet_id=cls.lb_member_2_subnet['id'])
667 cls.addClassResourceCleanup(
668 waiters.wait_for_not_found,
669 cls.lb_mem_routers_client.remove_router_interface,
670 cls.lb_mem_routers_client.remove_router_interface,
671 cls.lb_member_router['id'], subnet_id=cls.lb_member_2_subnet['id'])
672
673 @classmethod
674 def _create_webserver(cls, name, network):
675 """Creates a webserver with two ports.
676
677 webserver_details dictionary contains:
678 server - The compute server object
679 ipv4_address - The IPv4 address for the server (optional)
680 ipv6_address - The IPv6 address for the server (optional)
681 public_ipv4_address - The publicly accessible IPv4 address for the
682 server, this may be a floating IP (optional)
683
684 :param name: The name of the server to create.
685 :param network: The network to boot the server on.
686 :returns: webserver_details dictionary.
687 """
688 server_kwargs = {
689 'name': data_utils.rand_name(name),
690 'flavorRef': CONF.compute.flavor_ref,
691 'imageRef': CONF.compute.image_ref,
692 'key_name': cls.lb_member_keypair['name']}
693 if (CONF.load_balancer.enable_security_groups and
694 CONF.network_feature_enabled.port_security):
695 server_kwargs['security_groups'] = [
696 {'name': cls.lb_member_sec_group['name']}]
697 if not CONF.load_balancer.disable_boot_network:
698 server_kwargs['networks'] = [{'uuid': network['id']}]
699
700 # Replace the name for clouds that have limitations
701 if CONF.load_balancer.random_server_name_length:
702 r = random.SystemRandom()
703 server_kwargs['name'] = "m{}".format("".join(
704 [r.choice(string.ascii_uppercase + string.digits)
705 for _ in range(
706 CONF.load_balancer.random_server_name_length - 1)]
707 ))
708 if CONF.load_balancer.availability_zone:
709 server_kwargs['availability_zone'] = (
710 CONF.load_balancer.availability_zone)
711
712 server = cls.lb_mem_servers_client.create_server(
713 **server_kwargs)['server']
714 cls.addClassResourceCleanup(
715 waiters.wait_for_not_found,
716 cls.lb_mem_servers_client.delete_server,
717 cls.lb_mem_servers_client.show_server,
718 server['id'])
719 server = waiters.wait_for_status(
720 cls.lb_mem_servers_client.show_server,
721 server['id'], 'status', 'ACTIVE',
722 CONF.load_balancer.build_interval,
723 CONF.load_balancer.build_timeout,
724 root_tag='server')
725 webserver_details = {'server': server}
726 LOG.info('Created server: {}'.format(server))
727
728 addresses = server['addresses']
729 if CONF.load_balancer.disable_boot_network:
730 instance_network = addresses.values()[0]
731 else:
732 instance_network = addresses[network['name']]
733 for addr in instance_network:
734 if addr['version'] == 4:
735 webserver_details['ipv4_address'] = addr['addr']
736 if addr['version'] == 6:
737 webserver_details['ipv6_address'] = addr['addr']
738
739 if CONF.validation.connect_method == 'floating':
740 result = cls.lb_mem_ports_client.list_ports(
741 network_id=network['id'],
742 mac_address=instance_network[0]['OS-EXT-IPS-MAC:mac_addr'])
743 port_id = result['ports'][0]['id']
744 result = cls.lb_mem_float_ip_client.create_floatingip(
745 floating_network_id=CONF.network.public_network_id,
746 port_id=port_id)
747 floating_ip = result['floatingip']
748 LOG.info('webserver1_floating_ip: {}'.format(floating_ip))
749 cls.addClassResourceCleanup(
750 waiters.wait_for_not_found,
751 cls.lb_mem_float_ip_client.delete_floatingip,
752 cls.lb_mem_float_ip_client.show_floatingip,
753 floatingip_id=floating_ip['id'])
754 webserver_details['public_ipv4_address'] = (
755 floating_ip['floating_ip_address'])
756 else:
757 webserver_details['public_ipv4_address'] = (
758 instance_network[0]['addr'])
759
760 return webserver_details
761
762 @classmethod
Adam Harwellcd72b562018-05-07 11:37:22 -0700763 def _install_start_webserver(cls, ip_address, ssh_key, start_id):
764 local_file = pkg_resources.resource_filename(
765 'octavia_tempest_plugin.contrib.httpd', 'httpd.bin')
766 dest_file = '/dev/shm/httpd.bin'
767
768 linux_client = remote_client.RemoteClient(
769 ip_address, CONF.validation.image_ssh_user, pkey=ssh_key)
770 linux_client.validate_authentication()
771
772 with tempfile.NamedTemporaryFile() as key:
773 key.write(ssh_key.encode('utf-8'))
774 key.flush()
775 cmd = ("scp -v -o UserKnownHostsFile=/dev/null "
776 "-o StrictHostKeyChecking=no "
777 "-o ConnectTimeout={0} -o ConnectionAttempts={1} "
778 "-i {2} {3} {4}@{5}:{6}").format(
779 CONF.load_balancer.scp_connection_timeout,
780 CONF.load_balancer.scp_connection_attempts,
781 key.name, local_file, CONF.validation.image_ssh_user,
782 ip_address, dest_file)
783 args = shlex.split(cmd)
784 subprocess_args = {'stdout': subprocess.PIPE,
785 'stderr': subprocess.STDOUT,
786 'cwd': None}
787 proc = subprocess.Popen(args, **subprocess_args)
788 stdout, stderr = proc.communicate()
789 if proc.returncode != 0:
790 raise exceptions.CommandFailed(proc.returncode, cmd,
791 stdout, stderr)
792 linux_client.exec_command('sudo screen -d -m {0} -port 80 '
793 '-id {1}'.format(dest_file, start_id))
794 linux_client.exec_command('sudo screen -d -m {0} -port 81 '
795 '-id {1}'.format(dest_file, start_id + 1))
796
Michael Johnsonbf916df2018-10-17 10:59:28 -0700797 # Cirros does not configure the assigned IPv6 address by default
798 # so enable it manually like tempest does here:
799 # tempest/scenario/test_netowrk_v6.py turn_nic6_on()
800 @classmethod
801 def _enable_ipv6_nic_webserver(cls, ip_address, ssh_key,
802 ipv6_address, ipv6_prefix):
803 linux_client = remote_client.RemoteClient(
804 ip_address, CONF.validation.image_ssh_user, pkey=ssh_key)
805 linux_client.validate_authentication()
806
807 linux_client.exec_command('sudo ip address add {0}/{1} dev '
808 'eth0'.format(ipv6_address, ipv6_prefix))
809
Adam Harwellcd72b562018-05-07 11:37:22 -0700810 @classmethod
Jude Cross986e3f52017-07-24 14:57:20 -0700811 def _validate_webserver(cls, ip_address, start_id):
812 URL = 'http://{0}'.format(ip_address)
813 validators.validate_URL_response(URL, expected_body=str(start_id))
814 URL = 'http://{0}:81'.format(ip_address)
815 validators.validate_URL_response(URL, expected_body=str(start_id + 1))
816
Michael Johnson0a0f9b32019-01-02 16:58:21 -0800817 def _wait_for_lb_functional(self, vip_address,
818 protocol='http', verify=True):
Adam Harwellcd72b562018-05-07 11:37:22 -0700819 session = requests.Session()
820 start = time.time()
821
822 while time.time() - start < CONF.load_balancer.build_timeout:
823 try:
Michael Johnson0a0f9b32019-01-02 16:58:21 -0800824 session.get("{0}://{1}".format(protocol, vip_address),
825 timeout=2, verify=verify)
Adam Harwellcd72b562018-05-07 11:37:22 -0700826 time.sleep(1)
827 return
828 except Exception:
829 LOG.warning('Server is not passing initial traffic. Waiting.')
830 time.sleep(1)
831 LOG.error('Server did not begin passing traffic within the timeout '
832 'period. Failing test.')
833 raise Exception()
834
Michael Johnson0a0f9b32019-01-02 16:58:21 -0800835 def check_members_balanced(self, vip_address, traffic_member_count=2,
836 protocol='http', verify=True):
Adam Harwellcd72b562018-05-07 11:37:22 -0700837 session = requests.Session()
838 response_counts = {}
839
Michael Johnson5a16ad32018-10-18 14:49:11 -0700840 if ipaddress.ip_address(vip_address).version == 6:
841 vip_address = '[{}]'.format(vip_address)
842
Michael Johnson0a0f9b32019-01-02 16:58:21 -0800843 self._wait_for_lb_functional(vip_address, protocol, verify)
Adam Harwellcd72b562018-05-07 11:37:22 -0700844
845 # Send a number requests to lb vip
846 for i in range(20):
847 try:
Michael Johnson0a0f9b32019-01-02 16:58:21 -0800848 r = session.get('{0}://{1}'.format(protocol, vip_address),
849 timeout=2, verify=verify)
Adam Harwellcd72b562018-05-07 11:37:22 -0700850
851 if r.content in response_counts:
852 response_counts[r.content] += 1
853 else:
854 response_counts[r.content] = 1
855
856 except Exception:
857 LOG.exception('Failed to send request to loadbalancer vip')
858 raise Exception('Failed to connect to lb')
859
860 LOG.debug('Loadbalancer response totals: %s', response_counts)
861 # Ensure the correct number of members
Adam Harwell60ed9d92018-05-10 13:23:13 -0700862 self.assertEqual(traffic_member_count, len(response_counts))
Adam Harwellcd72b562018-05-07 11:37:22 -0700863
864 # Ensure both members got the same number of responses
865 self.assertEqual(1, len(set(response_counts.values())))
Adam Harwelle029af22018-05-24 17:13:28 -0700866
867 def assertConsistentResponse(self, response, url, method='GET', repeat=10,
868 redirect=False, timeout=2, **kwargs):
869 """Assert that a request to URL gets the expected response.
870
871 :param response: Expected response in format (status_code, content).
872 :param url: The URL to request.
873 :param method: The HTTP method to use (GET, POST, PUT, etc)
874 :param repeat: How many times to test the response.
875 :param data: Optional data to send in the request.
876 :param headers: Optional headers to send in the request.
877 :param cookies: Optional cookies to send in the request.
878 :param redirect: Is the request a redirect? If true, assume the passed
879 content should be the next URL in the chain.
Carlos Goncalvesc451ff92018-12-19 19:11:53 +0100880 :param timeout: Optional seconds to wait for the server to send data.
881
Adam Harwelle029af22018-05-24 17:13:28 -0700882 :return: boolean success status
883
884 :raises: testtools.matchers.MismatchError
885 """
886 session = requests.Session()
887 response_code, response_content = response
888
889 for i in range(0, repeat):
890 req = session.request(method, url, allow_redirects=not redirect,
891 timeout=timeout, **kwargs)
892 if response_code:
893 self.assertEqual(response_code, req.status_code)
894 if redirect:
895 self.assertTrue(req.is_redirect)
Carlos Goncalvesc451ff92018-12-19 19:11:53 +0100896 self.assertEqual(response_content,
897 session.get_redirect_target(req))
Adam Harwelle029af22018-05-24 17:13:28 -0700898 elif response_content:
899 self.assertEqual(six.text_type(response_content), req.text)