blob: 092fdccc97d43a68e319e208fd13dfc784b8a2fa [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)
Jude Cross986e3f52017-07-24 14:57:20 -0700127
128 @classmethod
129 def resource_setup(cls):
130 """Setup resources needed by the tests."""
131 super(LoadBalancerBaseTest, cls).resource_setup()
132
133 conf_lb = CONF.load_balancer
134
Michael Johnsondfd818a2018-08-21 20:54:54 -0700135 cls.api_version = cls.mem_lb_client.get_max_api_version()
136
Jude Cross986e3f52017-07-24 14:57:20 -0700137 if conf_lb.test_subnet_override and not conf_lb.test_network_override:
138 raise exceptions.InvalidConfiguration(
139 "Configuration value test_network_override must be "
140 "specified if test_subnet_override is used.")
141
142 show_subnet = cls.lb_mem_subnet_client.show_subnet
143 if CONF.load_balancer.test_with_noop:
144 cls.lb_member_vip_net = {'id': uuidutils.generate_uuid()}
145 cls.lb_member_vip_subnet = {'id': uuidutils.generate_uuid()}
146 cls.lb_member_1_net = {'id': uuidutils.generate_uuid()}
147 cls.lb_member_1_subnet = {'id': uuidutils.generate_uuid()}
148 cls.lb_member_2_net = {'id': uuidutils.generate_uuid()}
149 cls.lb_member_2_subnet = {'id': uuidutils.generate_uuid()}
150 if CONF.load_balancer.test_with_ipv6:
Michael Johnson5a16ad32018-10-18 14:49:11 -0700151 cls.lb_member_vip_ipv6_net = {'id': uuidutils.generate_uuid()}
Jude Cross986e3f52017-07-24 14:57:20 -0700152 cls.lb_member_vip_ipv6_subnet = {'id':
153 uuidutils.generate_uuid()}
154 cls.lb_member_1_ipv6_subnet = {'id': uuidutils.generate_uuid()}
155 cls.lb_member_2_ipv6_subnet = {'id': uuidutils.generate_uuid()}
156 return
157 elif CONF.load_balancer.test_network_override:
158 if conf_lb.test_subnet_override:
159 override_subnet = show_subnet(conf_lb.test_subnet_override)
160 else:
161 override_subnet = None
162
163 show_net = cls.lb_mem_net_client.show_network
164 override_network = show_net(conf_lb.test_network_override)
165 override_network = override_network.get('network')
166
167 cls.lb_member_vip_net = override_network
168 cls.lb_member_vip_subnet = override_subnet
169 cls.lb_member_1_net = override_network
170 cls.lb_member_1_subnet = override_subnet
171 cls.lb_member_2_net = override_network
172 cls.lb_member_2_subnet = override_subnet
173
174 if (CONF.load_balancer.test_with_ipv6 and
175 conf_lb.test_IPv6_subnet_override):
176 override_ipv6_subnet = show_subnet(
177 conf_lb.test_IPv6_subnet_override)
178 cls.lb_member_vip_ipv6_subnet = override_ipv6_subnet
179 cls.lb_member_1_ipv6_subnet = override_ipv6_subnet
180 cls.lb_member_2_ipv6_subnet = override_ipv6_subnet
181 else:
182 cls.lb_member_vip_ipv6_subnet = None
183 cls.lb_member_1_ipv6_subnet = None
184 cls.lb_member_2_ipv6_subnet = None
185 else:
186 cls._create_networks()
187
188 LOG.debug('Octavia Setup: lb_member_vip_net = {}'.format(
189 cls.lb_member_vip_net[const.ID]))
190 if cls.lb_member_vip_subnet:
191 LOG.debug('Octavia Setup: lb_member_vip_subnet = {}'.format(
192 cls.lb_member_vip_subnet[const.ID]))
193 LOG.debug('Octavia Setup: lb_member_1_net = {}'.format(
194 cls.lb_member_1_net[const.ID]))
195 if cls.lb_member_1_subnet:
196 LOG.debug('Octavia Setup: lb_member_1_subnet = {}'.format(
197 cls.lb_member_1_subnet[const.ID]))
198 LOG.debug('Octavia Setup: lb_member_2_net = {}'.format(
199 cls.lb_member_2_net[const.ID]))
200 if cls.lb_member_2_subnet:
201 LOG.debug('Octavia Setup: lb_member_2_subnet = {}'.format(
202 cls.lb_member_2_subnet[const.ID]))
Michael Johnson124ba8b2018-08-30 16:06:05 -0700203 if CONF.load_balancer.test_with_ipv6:
204 if cls.lb_member_vip_ipv6_subnet:
205 LOG.debug('Octavia Setup: lb_member_vip_ipv6_subnet = '
206 '{}'.format(cls.lb_member_vip_ipv6_subnet[const.ID]))
207 if cls.lb_member_1_ipv6_subnet:
208 LOG.debug('Octavia Setup: lb_member_1_ipv6_subnet = {}'.format(
209 cls.lb_member_1_ipv6_subnet[const.ID]))
210 if cls.lb_member_2_ipv6_subnet:
211 LOG.debug('Octavia Setup: lb_member_2_ipv6_subnet = {}'.format(
212 cls.lb_member_2_ipv6_subnet[const.ID]))
Jude Cross986e3f52017-07-24 14:57:20 -0700213
Jude Cross986e3f52017-07-24 14:57:20 -0700214 @classmethod
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800215 # Neutron can be slow to clean up ports from the subnets/networks.
216 # Retry this delete a few times if we get a "Conflict" error to give
217 # neutron time to fully cleanup the ports.
218 @tenacity.retry(
219 retry=tenacity.retry_if_exception_type(exceptions.Conflict),
220 wait=tenacity.wait_incrementing(
221 RETRY_INITIAL_DELAY, RETRY_BACKOFF, RETRY_MAX),
222 stop=tenacity.stop_after_attempt(RETRY_ATTEMPTS))
223 def _logging_delete_network(cls, net_id):
224 try:
225 cls.lb_mem_net_client.delete_network(net_id)
226 except Exception:
227 LOG.error('Unable to delete network {}. Active ports:'.format(
228 net_id))
229 LOG.error(cls.lb_mem_ports_client.list_ports())
230 raise
231
232 @classmethod
233 # Neutron can be slow to clean up ports from the subnets/networks.
234 # Retry this delete a few times if we get a "Conflict" error to give
235 # neutron time to fully cleanup the ports.
236 @tenacity.retry(
237 retry=tenacity.retry_if_exception_type(exceptions.Conflict),
238 wait=tenacity.wait_incrementing(
239 RETRY_INITIAL_DELAY, RETRY_BACKOFF, RETRY_MAX),
240 stop=tenacity.stop_after_attempt(RETRY_ATTEMPTS))
241 def _logging_delete_subnet(cls, subnet_id):
242 try:
243 cls.lb_mem_subnet_client.delete_subnet(subnet_id)
244 except Exception:
245 LOG.error('Unable to delete subnet {}. Active ports:'.format(
246 subnet_id))
247 LOG.error(cls.lb_mem_ports_client.list_ports())
248 raise
249
250 @classmethod
Jude Cross986e3f52017-07-24 14:57:20 -0700251 def _create_networks(cls):
252 """Creates networks, subnets, and routers used in tests.
253
254 The following are expected to be defined and available to the tests:
255 cls.lb_member_vip_net
256 cls.lb_member_vip_subnet
257 cls.lb_member_vip_ipv6_subnet (optional)
258 cls.lb_member_1_net
259 cls.lb_member_1_subnet
260 cls.lb_member_1_ipv6_subnet (optional)
261 cls.lb_member_2_net
262 cls.lb_member_2_subnet
263 cls.lb_member_2_ipv6_subnet (optional)
264 """
265
266 # Create tenant VIP network
267 network_kwargs = {
268 'name': data_utils.rand_name("lb_member_vip_network")}
269 if CONF.network_feature_enabled.port_security:
270 # Note: Allowed Address Pairs requires port security
271 network_kwargs['port_security_enabled'] = True
272 result = cls.lb_mem_net_client.create_network(**network_kwargs)
273 cls.lb_member_vip_net = result['network']
274 LOG.info('lb_member_vip_net: {}'.format(cls.lb_member_vip_net))
275 cls.addClassResourceCleanup(
276 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800277 cls._logging_delete_network,
Jude Cross986e3f52017-07-24 14:57:20 -0700278 cls.lb_mem_net_client.show_network,
279 cls.lb_member_vip_net['id'])
280
281 # Create tenant VIP subnet
282 subnet_kwargs = {
283 'name': data_utils.rand_name("lb_member_vip_subnet"),
284 'network_id': cls.lb_member_vip_net['id'],
285 'cidr': CONF.load_balancer.vip_subnet_cidr,
286 'ip_version': 4}
287 result = cls.lb_mem_subnet_client.create_subnet(**subnet_kwargs)
288 cls.lb_member_vip_subnet = result['subnet']
289 LOG.info('lb_member_vip_subnet: {}'.format(cls.lb_member_vip_subnet))
290 cls.addClassResourceCleanup(
291 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800292 cls._logging_delete_subnet,
Jude Cross986e3f52017-07-24 14:57:20 -0700293 cls.lb_mem_subnet_client.show_subnet,
294 cls.lb_member_vip_subnet['id'])
295
296 # Create tenant VIP IPv6 subnet
297 if CONF.load_balancer.test_with_ipv6:
Michael Johnson5a16ad32018-10-18 14:49:11 -0700298 # See if ipv6-public-subnet exists and use it if so.
299 pub_ipv6_subnet = cls.os_admin.subnets_client.list_subnets(
300 name='ipv6-public-subnet')['subnets']
301
302 if len(pub_ipv6_subnet) == 1:
303 cls.lb_member_vip_ipv6_subnet = pub_ipv6_subnet[0]
304 cls.lb_member_vip_ipv6_net = {
305 'id': pub_ipv6_subnet[0]['network_id']}
306 else:
307 subnet_kwargs = {
308 'name': data_utils.rand_name("lb_member_vip_ipv6_subnet"),
309 'network_id': cls.lb_member_vip_net['id'],
310 'cidr': CONF.load_balancer.vip_ipv6_subnet_cidr,
311 'ip_version': 6}
312 result = cls.lb_mem_subnet_client.create_subnet(
313 **subnet_kwargs)
314 cls.lb_member_vip_ipv6_subnet = result['subnet']
315 cls.addClassResourceCleanup(
316 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800317 cls._logging_delete_subnet,
Michael Johnson5a16ad32018-10-18 14:49:11 -0700318 cls.lb_mem_subnet_client.show_subnet,
319 cls.lb_member_vip_ipv6_subnet['id'])
Jude Cross986e3f52017-07-24 14:57:20 -0700320 LOG.info('lb_member_vip_ipv6_subnet: {}'.format(
321 cls.lb_member_vip_ipv6_subnet))
Jude Cross986e3f52017-07-24 14:57:20 -0700322
323 # Create tenant member 1 network
324 network_kwargs = {
325 'name': data_utils.rand_name("lb_member_1_network")}
326 if CONF.network_feature_enabled.port_security:
327 if CONF.load_balancer.enable_security_groups:
328 network_kwargs['port_security_enabled'] = True
329 else:
330 network_kwargs['port_security_enabled'] = False
331 result = cls.lb_mem_net_client.create_network(**network_kwargs)
332 cls.lb_member_1_net = result['network']
333 LOG.info('lb_member_1_net: {}'.format(cls.lb_member_1_net))
334 cls.addClassResourceCleanup(
335 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800336 cls._logging_delete_network,
Jude Cross986e3f52017-07-24 14:57:20 -0700337 cls.lb_mem_net_client.show_network,
338 cls.lb_member_1_net['id'])
339
340 # Create tenant member 1 subnet
341 subnet_kwargs = {
342 'name': data_utils.rand_name("lb_member_1_subnet"),
343 'network_id': cls.lb_member_1_net['id'],
344 'cidr': CONF.load_balancer.member_1_ipv4_subnet_cidr,
345 'ip_version': 4}
346 result = cls.lb_mem_subnet_client.create_subnet(**subnet_kwargs)
347 cls.lb_member_1_subnet = result['subnet']
348 LOG.info('lb_member_1_subnet: {}'.format(cls.lb_member_1_subnet))
349 cls.addClassResourceCleanup(
350 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800351 cls._logging_delete_subnet,
Jude Cross986e3f52017-07-24 14:57:20 -0700352 cls.lb_mem_subnet_client.show_subnet,
353 cls.lb_member_1_subnet['id'])
354
355 # Create tenant member 1 ipv6 subnet
356 if CONF.load_balancer.test_with_ipv6:
357 subnet_kwargs = {
358 'name': data_utils.rand_name("lb_member_1_ipv6_subnet"),
359 'network_id': cls.lb_member_1_net['id'],
360 'cidr': CONF.load_balancer.member_1_ipv6_subnet_cidr,
361 'ip_version': 6}
362 result = cls.lb_mem_subnet_client.create_subnet(**subnet_kwargs)
Michael Johnsonbf916df2018-10-17 10:59:28 -0700363 cls.lb_member_1_subnet_prefix = (
364 CONF.load_balancer.member_1_ipv6_subnet_cidr.rpartition('/')[2]
365 )
366 assert(cls.lb_member_1_subnet_prefix.isdigit())
Jude Cross986e3f52017-07-24 14:57:20 -0700367 cls.lb_member_1_ipv6_subnet = result['subnet']
368 LOG.info('lb_member_1_ipv6_subnet: {}'.format(
369 cls.lb_member_1_ipv6_subnet))
370 cls.addClassResourceCleanup(
371 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800372 cls._logging_delete_subnet,
Jude Cross986e3f52017-07-24 14:57:20 -0700373 cls.lb_mem_subnet_client.show_subnet,
374 cls.lb_member_1_ipv6_subnet['id'])
375
376 # Create tenant member 2 network
377 network_kwargs = {
378 'name': data_utils.rand_name("lb_member_2_network")}
379 if CONF.network_feature_enabled.port_security:
380 if CONF.load_balancer.enable_security_groups:
381 network_kwargs['port_security_enabled'] = True
382 else:
383 network_kwargs['port_security_enabled'] = False
384 result = cls.lb_mem_net_client.create_network(**network_kwargs)
385 cls.lb_member_2_net = result['network']
386 LOG.info('lb_member_2_net: {}'.format(cls.lb_member_2_net))
387 cls.addClassResourceCleanup(
388 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800389 cls._logging_delete_network,
Jude Cross986e3f52017-07-24 14:57:20 -0700390 cls.lb_mem_net_client.show_network,
391 cls.lb_member_2_net['id'])
392
393 # Create tenant member 2 subnet
394 subnet_kwargs = {
395 'name': data_utils.rand_name("lb_member_2_subnet"),
396 'network_id': cls.lb_member_2_net['id'],
397 'cidr': CONF.load_balancer.member_2_ipv4_subnet_cidr,
398 'ip_version': 4}
399 result = cls.lb_mem_subnet_client.create_subnet(**subnet_kwargs)
400 cls.lb_member_2_subnet = result['subnet']
401 LOG.info('lb_member_2_subnet: {}'.format(cls.lb_member_2_subnet))
402 cls.addClassResourceCleanup(
403 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800404 cls._logging_delete_subnet,
Jude Cross986e3f52017-07-24 14:57:20 -0700405 cls.lb_mem_subnet_client.show_subnet,
406 cls.lb_member_2_subnet['id'])
407
408 # Create tenant member 2 ipv6 subnet
409 if CONF.load_balancer.test_with_ipv6:
410 subnet_kwargs = {
411 'name': data_utils.rand_name("lb_member_2_ipv6_subnet"),
412 'network_id': cls.lb_member_2_net['id'],
413 'cidr': CONF.load_balancer.member_2_ipv6_subnet_cidr,
414 'ip_version': 6}
415 result = cls.lb_mem_subnet_client.create_subnet(**subnet_kwargs)
Michael Johnsonbf916df2018-10-17 10:59:28 -0700416 cls.lb_member_2_subnet_prefix = (
417 CONF.load_balancer.member_2_ipv6_subnet_cidr.rpartition('/')[2]
418 )
419 assert(cls.lb_member_2_subnet_prefix.isdigit())
Jude Cross986e3f52017-07-24 14:57:20 -0700420 cls.lb_member_2_ipv6_subnet = result['subnet']
421 LOG.info('lb_member_2_ipv6_subnet: {}'.format(
422 cls.lb_member_2_ipv6_subnet))
423 cls.addClassResourceCleanup(
424 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800425 cls._logging_delete_subnet,
Jude Cross986e3f52017-07-24 14:57:20 -0700426 cls.lb_mem_subnet_client.show_subnet,
427 cls.lb_member_2_ipv6_subnet['id'])
428
Adam Harwellcd72b562018-05-07 11:37:22 -0700429 @classmethod
Michael Johnson07c9a632018-06-07 13:27:42 -0700430 def _setup_lb_network_kwargs(cls, lb_kwargs, ip_version=None,
431 use_fixed_ip=False):
Adam Harwell60ed9d92018-05-10 13:23:13 -0700432 if not ip_version:
433 ip_version = 6 if CONF.load_balancer.test_with_ipv6 else 4
Michael Johnson5a16ad32018-10-18 14:49:11 -0700434 if cls.lb_member_vip_subnet or cls.lb_member_vip_ipv6_subnet:
Adam Harwellcd72b562018-05-07 11:37:22 -0700435 ip_index = data_utils.rand_int_id(start=10, end=100)
Michael Johnsondfd818a2018-08-21 20:54:54 -0700436 while ip_index in cls.used_ips:
437 ip_index = data_utils.rand_int_id(start=10, end=100)
438 cls.used_ips.append(ip_index)
Adam Harwellcd72b562018-05-07 11:37:22 -0700439 if ip_version == 4:
Adam Harwellcd72b562018-05-07 11:37:22 -0700440 subnet_id = cls.lb_member_vip_subnet[const.ID]
Michael Johnson5a16ad32018-10-18 14:49:11 -0700441 if CONF.load_balancer.test_with_noop:
442 lb_vip_address = '198.18.33.33'
443 else:
444 subnet = cls.os_admin.subnets_client.show_subnet(subnet_id)
445 network = ipaddress.IPv4Network(subnet['subnet']['cidr'])
446 lb_vip_address = str(network[ip_index])
Adam Harwellcd72b562018-05-07 11:37:22 -0700447 else:
Adam Harwellcd72b562018-05-07 11:37:22 -0700448 subnet_id = cls.lb_member_vip_ipv6_subnet[const.ID]
Michael Johnson5a16ad32018-10-18 14:49:11 -0700449 if CONF.load_balancer.test_with_noop:
450 lb_vip_address = '2001:db8:33:33:33:33:33:33'
451 else:
452 subnet = cls.os_admin.subnets_client.show_subnet(subnet_id)
453 network = ipaddress.IPv6Network(subnet['subnet']['cidr'])
454 lb_vip_address = str(network[ip_index])
Adam Harwellcd72b562018-05-07 11:37:22 -0700455 lb_kwargs[const.VIP_SUBNET_ID] = subnet_id
Michael Johnson07c9a632018-06-07 13:27:42 -0700456 if use_fixed_ip:
457 lb_kwargs[const.VIP_ADDRESS] = lb_vip_address
Adam Harwellcd72b562018-05-07 11:37:22 -0700458 if CONF.load_balancer.test_with_noop:
459 lb_kwargs[const.VIP_NETWORK_ID] = (
460 cls.lb_member_vip_net[const.ID])
461 else:
462 lb_kwargs[const.VIP_NETWORK_ID] = cls.lb_member_vip_net[const.ID]
463 lb_kwargs[const.VIP_SUBNET_ID] = None
464
465
466class LoadBalancerBaseTestWithCompute(LoadBalancerBaseTest):
467 @classmethod
468 def resource_setup(cls):
469 super(LoadBalancerBaseTestWithCompute, cls).resource_setup()
470 # If validation is disabled in this cloud, we won't be able to
471 # start the webservers, so don't even boot them.
472 if not CONF.validation.run_validation:
473 return
474
475 # Create a keypair for the webservers
476 keypair_name = data_utils.rand_name('lb_member_keypair')
477 result = cls.lb_mem_keypairs_client.create_keypair(
478 name=keypair_name)
479 cls.lb_member_keypair = result['keypair']
480 LOG.info('lb_member_keypair: {}'.format(cls.lb_member_keypair))
481 cls.addClassResourceCleanup(
482 waiters.wait_for_not_found,
483 cls.lb_mem_keypairs_client.delete_keypair,
484 cls.lb_mem_keypairs_client.show_keypair,
485 keypair_name)
486
487 if (CONF.load_balancer.enable_security_groups and
488 CONF.network_feature_enabled.port_security):
489 # Set up the security group for the webservers
490 SG_name = data_utils.rand_name('lb_member_SG')
491 cls.lb_member_sec_group = (
492 cls.lb_mem_SG_client.create_security_group(
493 name=SG_name)['security_group'])
494 cls.addClassResourceCleanup(
495 waiters.wait_for_not_found,
496 cls.lb_mem_SG_client.delete_security_group,
497 cls.lb_mem_SG_client.show_security_group,
498 cls.lb_member_sec_group['id'])
499
500 # Create a security group rule to allow 80-81 (test webservers)
501 SGr = cls.lb_mem_SGr_client.create_security_group_rule(
502 direction='ingress',
503 security_group_id=cls.lb_member_sec_group['id'],
504 protocol='tcp',
505 ethertype='IPv4',
506 port_range_min=80,
507 port_range_max=81)['security_group_rule']
508 cls.addClassResourceCleanup(
509 waiters.wait_for_not_found,
510 cls.lb_mem_SGr_client.delete_security_group_rule,
511 cls.lb_mem_SGr_client.show_security_group_rule,
512 SGr['id'])
513 # Create a security group rule to allow 22 (ssh)
514 SGr = cls.lb_mem_SGr_client.create_security_group_rule(
515 direction='ingress',
516 security_group_id=cls.lb_member_sec_group['id'],
517 protocol='tcp',
518 ethertype='IPv4',
519 port_range_min=22,
520 port_range_max=22)['security_group_rule']
521 cls.addClassResourceCleanup(
522 waiters.wait_for_not_found,
523 cls.lb_mem_SGr_client.delete_security_group_rule,
524 cls.lb_mem_SGr_client.show_security_group_rule,
525 SGr['id'])
526 if CONF.load_balancer.test_with_ipv6:
527 # Create a security group rule to allow 80-81 (test webservers)
528 SGr = cls.lb_mem_SGr_client.create_security_group_rule(
529 direction='ingress',
530 security_group_id=cls.lb_member_sec_group['id'],
531 protocol='tcp',
532 ethertype='IPv6',
533 port_range_min=80,
534 port_range_max=81)['security_group_rule']
535 cls.addClassResourceCleanup(
536 waiters.wait_for_not_found,
537 cls.lb_mem_SGr_client.delete_security_group_rule,
538 cls.lb_mem_SGr_client.show_security_group_rule,
539 SGr['id'])
540 # Create a security group rule to allow 22 (ssh)
541 SGr = cls.lb_mem_SGr_client.create_security_group_rule(
542 direction='ingress',
543 security_group_id=cls.lb_member_sec_group['id'],
544 protocol='tcp',
545 ethertype='IPv6',
546 port_range_min=22,
547 port_range_max=22)['security_group_rule']
548 cls.addClassResourceCleanup(
549 waiters.wait_for_not_found,
550 cls.lb_mem_SGr_client.delete_security_group_rule,
551 cls.lb_mem_SGr_client.show_security_group_rule,
552 SGr['id'])
553
554 LOG.info('lb_member_sec_group: {}'.format(cls.lb_member_sec_group))
555
556 # Create webserver 1 instance
557 server_details = cls._create_webserver('lb_member_webserver1',
558 cls.lb_member_1_net)
559
560 cls.lb_member_webserver1 = server_details['server']
561 cls.webserver1_ip = server_details.get('ipv4_address')
562 cls.webserver1_ipv6 = server_details.get('ipv6_address')
563 cls.webserver1_public_ip = server_details['public_ipv4_address']
564
565 LOG.debug('Octavia Setup: lb_member_webserver1 = {}'.format(
566 cls.lb_member_webserver1[const.ID]))
567 LOG.debug('Octavia Setup: webserver1_ip = {}'.format(
568 cls.webserver1_ip))
569 LOG.debug('Octavia Setup: webserver1_ipv6 = {}'.format(
570 cls.webserver1_ipv6))
571 LOG.debug('Octavia Setup: webserver1_public_ip = {}'.format(
572 cls.webserver1_public_ip))
573
574 # Create webserver 2 instance
575 server_details = cls._create_webserver('lb_member_webserver2',
576 cls.lb_member_2_net)
577
578 cls.lb_member_webserver2 = server_details['server']
579 cls.webserver2_ip = server_details.get('ipv4_address')
580 cls.webserver2_ipv6 = server_details.get('ipv6_address')
581 cls.webserver2_public_ip = server_details['public_ipv4_address']
582
583 LOG.debug('Octavia Setup: lb_member_webserver2 = {}'.format(
584 cls.lb_member_webserver2[const.ID]))
585 LOG.debug('Octavia Setup: webserver2_ip = {}'.format(
586 cls.webserver2_ip))
587 LOG.debug('Octavia Setup: webserver2_ipv6 = {}'.format(
588 cls.webserver2_ipv6))
589 LOG.debug('Octavia Setup: webserver2_public_ip = {}'.format(
590 cls.webserver2_public_ip))
591
Michael Johnsonbf916df2018-10-17 10:59:28 -0700592 if CONF.load_balancer.test_with_ipv6:
593 # Enable the IPv6 nic in webserver 1
594 cls._enable_ipv6_nic_webserver(
595 cls.webserver1_public_ip, cls.lb_member_keypair['private_key'],
596 cls.webserver1_ipv6, cls.lb_member_1_subnet_prefix)
597
598 # Enable the IPv6 nic in webserver 2
599 cls._enable_ipv6_nic_webserver(
600 cls.webserver2_public_ip, cls.lb_member_keypair['private_key'],
601 cls.webserver2_ipv6, cls.lb_member_2_subnet_prefix)
602
Adam Harwellcd72b562018-05-07 11:37:22 -0700603 # Set up serving on webserver 1
604 cls._install_start_webserver(cls.webserver1_public_ip,
Adam Harwelle029af22018-05-24 17:13:28 -0700605 cls.lb_member_keypair['private_key'],
606 cls.webserver1_response)
Adam Harwellcd72b562018-05-07 11:37:22 -0700607
608 # Validate webserver 1
Adam Harwelle029af22018-05-24 17:13:28 -0700609 cls._validate_webserver(cls.webserver1_public_ip,
610 cls.webserver1_response)
Adam Harwellcd72b562018-05-07 11:37:22 -0700611
612 # Set up serving on webserver 2
613 cls._install_start_webserver(cls.webserver2_public_ip,
Adam Harwelle029af22018-05-24 17:13:28 -0700614 cls.lb_member_keypair['private_key'],
615 cls.webserver2_response)
Adam Harwellcd72b562018-05-07 11:37:22 -0700616
617 # Validate webserver 2
Adam Harwelle029af22018-05-24 17:13:28 -0700618 cls._validate_webserver(cls.webserver2_public_ip,
619 cls.webserver2_response)
Adam Harwellcd72b562018-05-07 11:37:22 -0700620
621 @classmethod
622 def _create_networks(cls):
623 super(LoadBalancerBaseTestWithCompute, cls)._create_networks()
Jude Cross986e3f52017-07-24 14:57:20 -0700624 # Create a router for the subnets (required for the floating IP)
625 router_name = data_utils.rand_name("lb_member_router")
626 result = cls.lb_mem_routers_client.create_router(
627 name=router_name, admin_state_up=True,
628 external_gateway_info=dict(
629 network_id=CONF.network.public_network_id))
630 cls.lb_member_router = result['router']
631 LOG.info('lb_member_router: {}'.format(cls.lb_member_router))
632 cls.addClassResourceCleanup(
633 waiters.wait_for_not_found,
634 cls.lb_mem_routers_client.delete_router,
635 cls.lb_mem_routers_client.show_router,
636 cls.lb_member_router['id'])
637
638 # Add VIP subnet to router
639 cls.lb_mem_routers_client.add_router_interface(
640 cls.lb_member_router['id'],
641 subnet_id=cls.lb_member_vip_subnet['id'])
642 cls.addClassResourceCleanup(
643 waiters.wait_for_not_found,
644 cls.lb_mem_routers_client.remove_router_interface,
645 cls.lb_mem_routers_client.remove_router_interface,
646 cls.lb_member_router['id'],
647 subnet_id=cls.lb_member_vip_subnet['id'])
648
649 # Add member subnet 1 to router
650 cls.lb_mem_routers_client.add_router_interface(
651 cls.lb_member_router['id'],
652 subnet_id=cls.lb_member_1_subnet['id'])
653 cls.addClassResourceCleanup(
654 waiters.wait_for_not_found,
Jude Cross986e3f52017-07-24 14:57:20 -0700655 cls.lb_mem_routers_client.remove_router_interface,
656 cls.lb_mem_routers_client.remove_router_interface,
657 cls.lb_member_router['id'], subnet_id=cls.lb_member_1_subnet['id'])
658
659 # Add member subnet 2 to router
660 cls.lb_mem_routers_client.add_router_interface(
661 cls.lb_member_router['id'],
662 subnet_id=cls.lb_member_2_subnet['id'])
663 cls.addClassResourceCleanup(
664 waiters.wait_for_not_found,
665 cls.lb_mem_routers_client.remove_router_interface,
666 cls.lb_mem_routers_client.remove_router_interface,
667 cls.lb_member_router['id'], subnet_id=cls.lb_member_2_subnet['id'])
668
669 @classmethod
670 def _create_webserver(cls, name, network):
671 """Creates a webserver with two ports.
672
673 webserver_details dictionary contains:
674 server - The compute server object
675 ipv4_address - The IPv4 address for the server (optional)
676 ipv6_address - The IPv6 address for the server (optional)
677 public_ipv4_address - The publicly accessible IPv4 address for the
678 server, this may be a floating IP (optional)
679
680 :param name: The name of the server to create.
681 :param network: The network to boot the server on.
682 :returns: webserver_details dictionary.
683 """
684 server_kwargs = {
685 'name': data_utils.rand_name(name),
686 'flavorRef': CONF.compute.flavor_ref,
687 'imageRef': CONF.compute.image_ref,
688 'key_name': cls.lb_member_keypair['name']}
689 if (CONF.load_balancer.enable_security_groups and
690 CONF.network_feature_enabled.port_security):
691 server_kwargs['security_groups'] = [
692 {'name': cls.lb_member_sec_group['name']}]
693 if not CONF.load_balancer.disable_boot_network:
694 server_kwargs['networks'] = [{'uuid': network['id']}]
695
696 # Replace the name for clouds that have limitations
697 if CONF.load_balancer.random_server_name_length:
698 r = random.SystemRandom()
699 server_kwargs['name'] = "m{}".format("".join(
700 [r.choice(string.ascii_uppercase + string.digits)
701 for _ in range(
702 CONF.load_balancer.random_server_name_length - 1)]
703 ))
704 if CONF.load_balancer.availability_zone:
705 server_kwargs['availability_zone'] = (
706 CONF.load_balancer.availability_zone)
707
708 server = cls.lb_mem_servers_client.create_server(
709 **server_kwargs)['server']
710 cls.addClassResourceCleanup(
711 waiters.wait_for_not_found,
712 cls.lb_mem_servers_client.delete_server,
713 cls.lb_mem_servers_client.show_server,
714 server['id'])
715 server = waiters.wait_for_status(
716 cls.lb_mem_servers_client.show_server,
717 server['id'], 'status', 'ACTIVE',
718 CONF.load_balancer.build_interval,
719 CONF.load_balancer.build_timeout,
720 root_tag='server')
721 webserver_details = {'server': server}
722 LOG.info('Created server: {}'.format(server))
723
724 addresses = server['addresses']
725 if CONF.load_balancer.disable_boot_network:
726 instance_network = addresses.values()[0]
727 else:
728 instance_network = addresses[network['name']]
729 for addr in instance_network:
730 if addr['version'] == 4:
731 webserver_details['ipv4_address'] = addr['addr']
732 if addr['version'] == 6:
733 webserver_details['ipv6_address'] = addr['addr']
734
735 if CONF.validation.connect_method == 'floating':
736 result = cls.lb_mem_ports_client.list_ports(
737 network_id=network['id'],
738 mac_address=instance_network[0]['OS-EXT-IPS-MAC:mac_addr'])
739 port_id = result['ports'][0]['id']
740 result = cls.lb_mem_float_ip_client.create_floatingip(
741 floating_network_id=CONF.network.public_network_id,
742 port_id=port_id)
743 floating_ip = result['floatingip']
744 LOG.info('webserver1_floating_ip: {}'.format(floating_ip))
745 cls.addClassResourceCleanup(
746 waiters.wait_for_not_found,
747 cls.lb_mem_float_ip_client.delete_floatingip,
748 cls.lb_mem_float_ip_client.show_floatingip,
749 floatingip_id=floating_ip['id'])
750 webserver_details['public_ipv4_address'] = (
751 floating_ip['floating_ip_address'])
752 else:
753 webserver_details['public_ipv4_address'] = (
754 instance_network[0]['addr'])
755
756 return webserver_details
757
758 @classmethod
Adam Harwellcd72b562018-05-07 11:37:22 -0700759 def _install_start_webserver(cls, ip_address, ssh_key, start_id):
760 local_file = pkg_resources.resource_filename(
761 'octavia_tempest_plugin.contrib.httpd', 'httpd.bin')
762 dest_file = '/dev/shm/httpd.bin'
763
764 linux_client = remote_client.RemoteClient(
765 ip_address, CONF.validation.image_ssh_user, pkey=ssh_key)
766 linux_client.validate_authentication()
767
768 with tempfile.NamedTemporaryFile() as key:
769 key.write(ssh_key.encode('utf-8'))
770 key.flush()
771 cmd = ("scp -v -o UserKnownHostsFile=/dev/null "
772 "-o StrictHostKeyChecking=no "
773 "-o ConnectTimeout={0} -o ConnectionAttempts={1} "
774 "-i {2} {3} {4}@{5}:{6}").format(
775 CONF.load_balancer.scp_connection_timeout,
776 CONF.load_balancer.scp_connection_attempts,
777 key.name, local_file, CONF.validation.image_ssh_user,
778 ip_address, dest_file)
779 args = shlex.split(cmd)
780 subprocess_args = {'stdout': subprocess.PIPE,
781 'stderr': subprocess.STDOUT,
782 'cwd': None}
783 proc = subprocess.Popen(args, **subprocess_args)
784 stdout, stderr = proc.communicate()
785 if proc.returncode != 0:
786 raise exceptions.CommandFailed(proc.returncode, cmd,
787 stdout, stderr)
788 linux_client.exec_command('sudo screen -d -m {0} -port 80 '
789 '-id {1}'.format(dest_file, start_id))
790 linux_client.exec_command('sudo screen -d -m {0} -port 81 '
791 '-id {1}'.format(dest_file, start_id + 1))
792
Michael Johnsonbf916df2018-10-17 10:59:28 -0700793 # Cirros does not configure the assigned IPv6 address by default
794 # so enable it manually like tempest does here:
795 # tempest/scenario/test_netowrk_v6.py turn_nic6_on()
796 @classmethod
797 def _enable_ipv6_nic_webserver(cls, ip_address, ssh_key,
798 ipv6_address, ipv6_prefix):
799 linux_client = remote_client.RemoteClient(
800 ip_address, CONF.validation.image_ssh_user, pkey=ssh_key)
801 linux_client.validate_authentication()
802
803 linux_client.exec_command('sudo ip address add {0}/{1} dev '
804 'eth0'.format(ipv6_address, ipv6_prefix))
805
Adam Harwellcd72b562018-05-07 11:37:22 -0700806 @classmethod
Jude Cross986e3f52017-07-24 14:57:20 -0700807 def _validate_webserver(cls, ip_address, start_id):
808 URL = 'http://{0}'.format(ip_address)
809 validators.validate_URL_response(URL, expected_body=str(start_id))
810 URL = 'http://{0}:81'.format(ip_address)
811 validators.validate_URL_response(URL, expected_body=str(start_id + 1))
812
Michael Johnson0a0f9b32019-01-02 16:58:21 -0800813 def _wait_for_lb_functional(self, vip_address,
814 protocol='http', verify=True):
Adam Harwellcd72b562018-05-07 11:37:22 -0700815 session = requests.Session()
816 start = time.time()
817
818 while time.time() - start < CONF.load_balancer.build_timeout:
819 try:
Michael Johnson0a0f9b32019-01-02 16:58:21 -0800820 session.get("{0}://{1}".format(protocol, vip_address),
821 timeout=2, verify=verify)
Adam Harwellcd72b562018-05-07 11:37:22 -0700822 time.sleep(1)
823 return
824 except Exception:
825 LOG.warning('Server is not passing initial traffic. Waiting.')
826 time.sleep(1)
827 LOG.error('Server did not begin passing traffic within the timeout '
828 'period. Failing test.')
829 raise Exception()
830
Michael Johnson0a0f9b32019-01-02 16:58:21 -0800831 def check_members_balanced(self, vip_address, traffic_member_count=2,
832 protocol='http', verify=True):
Adam Harwellcd72b562018-05-07 11:37:22 -0700833 session = requests.Session()
834 response_counts = {}
835
Michael Johnson5a16ad32018-10-18 14:49:11 -0700836 if ipaddress.ip_address(vip_address).version == 6:
837 vip_address = '[{}]'.format(vip_address)
838
Michael Johnson0a0f9b32019-01-02 16:58:21 -0800839 self._wait_for_lb_functional(vip_address, protocol, verify)
Adam Harwellcd72b562018-05-07 11:37:22 -0700840
841 # Send a number requests to lb vip
842 for i in range(20):
843 try:
Michael Johnson0a0f9b32019-01-02 16:58:21 -0800844 r = session.get('{0}://{1}'.format(protocol, vip_address),
845 timeout=2, verify=verify)
Adam Harwellcd72b562018-05-07 11:37:22 -0700846
847 if r.content in response_counts:
848 response_counts[r.content] += 1
849 else:
850 response_counts[r.content] = 1
851
852 except Exception:
853 LOG.exception('Failed to send request to loadbalancer vip')
854 raise Exception('Failed to connect to lb')
855
856 LOG.debug('Loadbalancer response totals: %s', response_counts)
857 # Ensure the correct number of members
Adam Harwell60ed9d92018-05-10 13:23:13 -0700858 self.assertEqual(traffic_member_count, len(response_counts))
Adam Harwellcd72b562018-05-07 11:37:22 -0700859
860 # Ensure both members got the same number of responses
861 self.assertEqual(1, len(set(response_counts.values())))
Adam Harwelle029af22018-05-24 17:13:28 -0700862
863 def assertConsistentResponse(self, response, url, method='GET', repeat=10,
864 redirect=False, timeout=2, **kwargs):
865 """Assert that a request to URL gets the expected response.
866
867 :param response: Expected response in format (status_code, content).
868 :param url: The URL to request.
869 :param method: The HTTP method to use (GET, POST, PUT, etc)
870 :param repeat: How many times to test the response.
871 :param data: Optional data to send in the request.
872 :param headers: Optional headers to send in the request.
873 :param cookies: Optional cookies to send in the request.
874 :param redirect: Is the request a redirect? If true, assume the passed
875 content should be the next URL in the chain.
Carlos Goncalvesc451ff92018-12-19 19:11:53 +0100876 :param timeout: Optional seconds to wait for the server to send data.
877
Adam Harwelle029af22018-05-24 17:13:28 -0700878 :return: boolean success status
879
880 :raises: testtools.matchers.MismatchError
881 """
882 session = requests.Session()
883 response_code, response_content = response
884
885 for i in range(0, repeat):
886 req = session.request(method, url, allow_redirects=not redirect,
887 timeout=timeout, **kwargs)
888 if response_code:
889 self.assertEqual(response_code, req.status_code)
890 if redirect:
891 self.assertTrue(req.is_redirect)
Carlos Goncalvesc451ff92018-12-19 19:11:53 +0100892 self.assertEqual(response_content,
893 session.get_redirect_target(req))
Adam Harwelle029af22018-05-24 17:13:28 -0700894 elif response_content:
895 self.assertEqual(six.text_type(response_content), req.text)