blob: 4fd005c451acf3bfb3382122b2fa235a540a3295 [file] [log] [blame]
Brianna Poulos011292a2017-03-15 16:24:38 -04001# Copyright 2012 OpenStack Foundation
2# Copyright 2013 IBM Corp.
3# All Rights Reserved.
4#
5# Licensed under the Apache License, Version 2.0 (the "License"); you may
6# not use this file except in compliance with the License. You may obtain
7# a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14# License for the specific language governing permissions and limitations
15# under the License.
16
17from oslo_log import log
18
Brianna Poulos011292a2017-03-15 16:24:38 -040019from tempest.common import image as common_image
20from tempest.common import waiters
21from tempest import config
dane-fichter53f4fea2017-03-01 13:20:02 -050022from tempest import exceptions
Brianna Poulos011292a2017-03-15 16:24:38 -040023from tempest.lib.common.utils import data_utils
24from tempest.lib.common.utils import test_utils
25from tempest.lib import exceptions as lib_exc
Ihar Hrachyshkaecce1f62018-01-18 13:32:05 -080026from tempest.scenario import manager
Brianna Poulos011292a2017-03-15 16:24:38 -040027
28CONF = config.CONF
29
30LOG = log.getLogger(__name__)
31
32
Ihar Hrachyshka2d0cf0a2018-01-18 13:40:09 -080033# we inherit from NetworkScenarioTest since some test cases need access to
34# check_*_connectivity methods to validate instances are up and accessible
35class ScenarioTest(manager.NetworkScenarioTest):
Brianna Poulos011292a2017-03-15 16:24:38 -040036 """Base class for scenario tests. Uses tempest own clients. """
37
38 credentials = ['primary']
39
40 @classmethod
41 def setup_clients(cls):
42 super(ScenarioTest, cls).setup_clients()
43 # Clients (in alphabetical order)
Vu Cong Tuan17b61932017-06-21 17:52:43 +070044 cls.flavors_client = cls.os_primary.flavors_client
Brianna Poulos011292a2017-03-15 16:24:38 -040045 cls.compute_floating_ips_client = (
Vu Cong Tuan17b61932017-06-21 17:52:43 +070046 cls.os_primary.compute_floating_ips_client)
Brianna Poulos011292a2017-03-15 16:24:38 -040047 if CONF.service_available.glance:
48 # Check if glance v1 is available to determine which client to use.
49 if CONF.image_feature_enabled.api_v1:
Vu Cong Tuan17b61932017-06-21 17:52:43 +070050 cls.image_client = cls.os_primary.image_client
Brianna Poulos011292a2017-03-15 16:24:38 -040051 elif CONF.image_feature_enabled.api_v2:
Vu Cong Tuan17b61932017-06-21 17:52:43 +070052 cls.image_client = cls.os_primary.image_client_v2
Brianna Poulos011292a2017-03-15 16:24:38 -040053 else:
54 raise lib_exc.InvalidConfiguration(
55 'Either api_v1 or api_v2 must be True in '
56 '[image-feature-enabled].')
57 # Compute image client
Vu Cong Tuan17b61932017-06-21 17:52:43 +070058 cls.compute_images_client = cls.os_primary.compute_images_client
59 cls.keypairs_client = cls.os_primary.keypairs_client
Brianna Poulos011292a2017-03-15 16:24:38 -040060 # Nova security groups client
61 cls.compute_security_groups_client = (
Vu Cong Tuan17b61932017-06-21 17:52:43 +070062 cls.os_primary.compute_security_groups_client)
Brianna Poulos011292a2017-03-15 16:24:38 -040063 cls.compute_security_group_rules_client = (
Vu Cong Tuan17b61932017-06-21 17:52:43 +070064 cls.os_primary.compute_security_group_rules_client)
65 cls.servers_client = cls.os_primary.servers_client
Brianna Poulos011292a2017-03-15 16:24:38 -040066 # Neutron network client
Vu Cong Tuan17b61932017-06-21 17:52:43 +070067 cls.networks_client = cls.os_primary.networks_client
68 cls.ports_client = cls.os_primary.ports_client
69 cls.routers_client = cls.os_primary.routers_client
70 cls.subnets_client = cls.os_primary.subnets_client
71 cls.floating_ips_client = cls.os_primary.floating_ips_client
72 cls.security_groups_client = cls.os_primary.security_groups_client
Brianna Poulos011292a2017-03-15 16:24:38 -040073 cls.security_group_rules_client = (
Vu Cong Tuan17b61932017-06-21 17:52:43 +070074 cls.os_primary.security_group_rules_client)
Brianna Poulos011292a2017-03-15 16:24:38 -040075
Ghanshyam Mann48d10b82019-12-12 16:45:44 +000076 cls.volumes_client = cls.os_primary.volumes_client_latest
77 cls.snapshots_client = cls.os_primary.snapshots_client_latest
Brianna Poulos011292a2017-03-15 16:24:38 -040078
79 # ## Test functions library
80 #
81 # The create_[resource] functions only return body and discard the
82 # resp part which is not used in scenario tests
Brianna Poulos011292a2017-03-15 16:24:38 -040083
84 def create_volume(self, size=None, name=None, snapshot_id=None,
85 imageRef=None, volume_type=None):
86 if size is None:
87 size = CONF.volume.volume_size
88 if imageRef:
89 image = self.compute_images_client.show_image(imageRef)['image']
90 min_disk = image.get('minDisk')
91 size = max(size, min_disk)
92 if name is None:
93 name = data_utils.rand_name(self.__class__.__name__ + "-volume")
94 kwargs = {'display_name': name,
95 'snapshot_id': snapshot_id,
96 'imageRef': imageRef,
97 'volume_type': volume_type,
98 'size': size}
Marian Krcmarikda011992020-09-12 02:32:23 +020099 if CONF.compute.compute_volume_common_az:
100 kwargs.setdefault('availability_zone',
101 CONF.compute.compute_volume_common_az)
Brianna Poulos011292a2017-03-15 16:24:38 -0400102 volume = self.volumes_client.create_volume(**kwargs)['volume']
103
104 self.addCleanup(self.volumes_client.wait_for_resource_deletion,
105 volume['id'])
106 self.addCleanup(test_utils.call_and_ignore_notfound_exc,
107 self.volumes_client.delete_volume, volume['id'])
108
109 # NOTE(e0ne): Cinder API v2 uses name instead of display_name
110 if 'display_name' in volume:
111 self.assertEqual(name, volume['display_name'])
112 else:
113 self.assertEqual(name, volume['name'])
114 waiters.wait_for_volume_resource_status(self.volumes_client,
115 volume['id'], 'available')
116 # The volume retrieved on creation has a non-up-to-date status.
117 # Retrieval after it becomes active ensures correct details.
118 volume = self.volumes_client.show_volume(volume['id'])['volume']
119 return volume
120
121 def create_volume_type(self, client=None, name=None, backend_name=None):
122 if not client:
123 client = self.admin_volume_types_client
124 if not name:
125 class_name = self.__class__.__name__
126 name = data_utils.rand_name(class_name + '-volume-type')
127 randomized_name = data_utils.rand_name('scenario-type-' + name)
128
129 LOG.debug("Creating a volume type: %s on backend %s",
130 randomized_name, backend_name)
131 extra_specs = {}
132 if backend_name:
133 extra_specs = {"volume_backend_name": backend_name}
134
135 body = client.create_volume_type(name=randomized_name,
136 extra_specs=extra_specs)
137 volume_type = body['volume_type']
138 self.assertIn('id', volume_type)
139 self.addCleanup(client.delete_volume_type, volume_type['id'])
140 return volume_type
141
142 def _image_create(self, name, fmt, path,
143 disk_format=None, properties=None):
144 if properties is None:
145 properties = {}
146 name = data_utils.rand_name('%s-' % name)
147 params = {
148 'name': name,
149 'container_format': fmt,
150 'disk_format': disk_format or fmt,
151 }
152 if CONF.image_feature_enabled.api_v1:
153 params['is_public'] = 'False'
154 params['properties'] = properties
155 params = {'headers': common_image.image_meta_to_headers(**params)}
156 else:
157 params['visibility'] = 'private'
158 # Additional properties are flattened out in the v2 API.
159 params.update(properties)
160 body = self.image_client.create_image(**params)
161 image = body['image'] if 'image' in body else body
162 self.addCleanup(self.image_client.delete_image, image['id'])
163 self.assertEqual("queued", image['status'])
164 with open(path, 'rb') as image_file:
165 if CONF.image_feature_enabled.api_v1:
166 self.image_client.update_image(image['id'], data=image_file)
167 else:
168 self.image_client.store_image_file(image['id'], image_file)
Marian Krcmarik1972c462020-11-20 01:33:02 +0100169
170 if CONF.image_feature_enabled.import_image:
171 available_stores = []
172 try:
173 available_stores = self.image_client.info_stores()['stores']
174 except exceptions.NotFound:
175 pass
176 available_import_methods = self.image_client.info_import()[
177 'import-methods']['value']
178 if ('copy-image' in available_import_methods and
179 len(available_stores) > 1):
180 self.image_client.image_import(image['id'],
181 method='copy-image',
182 all_stores=True,
183 all_stores_must_succeed=False)
184 failed_stores = waiters.wait_for_image_copied_to_stores(
185 self.image_client, image['id'])
186 self.assertEqual(0, len(failed_stores),
187 "Failed to copy the following stores: %s" %
188 str(failed_stores))
189
Brianna Poulos011292a2017-03-15 16:24:38 -0400190 return image['id']
191
Brianna Poulos011292a2017-03-15 16:24:38 -0400192 def create_floating_ip(self, thing, pool_name=None):
193 """Create a floating IP and associates to a server on Nova"""
194
195 if not pool_name:
196 pool_name = CONF.network.floating_network_name
197 floating_ip = (self.compute_floating_ips_client.
198 create_floating_ip(pool=pool_name)['floating_ip'])
199 self.addCleanup(test_utils.call_and_ignore_notfound_exc,
200 self.compute_floating_ips_client.delete_floating_ip,
201 floating_ip['id'])
202 self.compute_floating_ips_client.associate_floating_ip_to_server(
203 floating_ip['ip'], thing['id'])
204 return floating_ip
dane-fichter53f4fea2017-03-01 13:20:02 -0500205
206 def nova_volume_attach(self, server, volume_to_attach):
207 volume = self.servers_client.attach_volume(
208 server['id'], volumeId=volume_to_attach['id'], device='/dev/%s'
209 % CONF.compute.volume_device_name)['volumeAttachment']
210 self.assertEqual(volume_to_attach['id'], volume['id'])
211 waiters.wait_for_volume_resource_status(self.volumes_client,
212 volume['id'], 'in-use')
213
yatin5ddcc7e2018-03-27 14:49:36 +0530214 self.addCleanup(self.nova_volume_detach, server, volume)
dane-fichter53f4fea2017-03-01 13:20:02 -0500215 # Return the updated volume after the attachment
216 return self.volumes_client.show_volume(volume['id'])['volume']
217
218 def nova_volume_detach(self, server, volume):
219 self.servers_client.detach_volume(server['id'], volume['id'])
220 waiters.wait_for_volume_resource_status(self.volumes_client,
221 volume['id'], 'available')
222
223 volume = self.volumes_client.show_volume(volume['id'])['volume']
224 self.assertEqual('available', volume['status'])
225
dane-fichter53f4fea2017-03-01 13:20:02 -0500226 def get_server_ip(self, server):
227 """Get the server fixed or floating IP.
228
229 Based on the configuration we're in, return a correct ip
230 address for validating that a guest is up.
231 """
232 if CONF.validation.connect_method == 'floating':
233 # The tests calling this method don't have a floating IP
234 # and can't make use of the validation resources. So the
235 # method is creating the floating IP there.
236 return self.create_floating_ip(server)['ip']
237 elif CONF.validation.connect_method == 'fixed':
238 # Determine the network name to look for based on config or creds
239 # provider network resources.
240 if CONF.validation.network_for_ssh:
241 addresses = server['addresses'][
242 CONF.validation.network_for_ssh]
243 else:
244 creds_provider = self._get_credentials_provider()
245 net_creds = creds_provider.get_primary_creds()
246 network = getattr(net_creds, 'network', None)
247 addresses = (server['addresses'][network['name']]
248 if network else [])
249 for address in addresses:
jacky06a318f6d2019-01-04 23:55:03 +0800250 ip_version_for_ssh = CONF.validation.ip_version_for_ssh
251 if (address['version'] == ip_version_for_ssh and
252 address['OS-EXT-IPS:type'] == 'fixed'):
dane-fichter53f4fea2017-03-01 13:20:02 -0500253 return address['addr']
254 raise exceptions.ServerUnreachable(server_id=server['id'])
255 else:
256 raise lib_exc.InvalidConfiguration()
257
dane-fichter53f4fea2017-03-01 13:20:02 -0500258 def _default_security_group(self, client=None, tenant_id=None):
259 """Get default secgroup for given tenant_id.
260
261 :returns: default secgroup for given tenant
262 """
263 if client is None:
264 client = self.security_groups_client
265 if not tenant_id:
266 tenant_id = client.tenant_id
267 sgs = [
268 sg for sg in list(client.list_security_groups().values())[0]
269 if sg['tenant_id'] == tenant_id and sg['name'] == 'default'
270 ]
271 msg = "No default security group for tenant %s." % (tenant_id)
272 self.assertGreater(len(sgs), 0, msg)
273 return sgs[0]
274
275 def _create_security_group(self):
276 # Create security group
277 sg_name = data_utils.rand_name(self.__class__.__name__)
278 sg_desc = sg_name + " description"
279 secgroup = self.compute_security_groups_client.create_security_group(
280 name=sg_name, description=sg_desc)['security_group']
281 self.assertEqual(secgroup['name'], sg_name)
282 self.assertEqual(secgroup['description'], sg_desc)
283 self.addCleanup(
284 test_utils.call_and_ignore_notfound_exc,
285 self.compute_security_groups_client.delete_security_group,
286 secgroup['id'])
287
288 # Add rules to the security group
289 self._create_loginable_secgroup_rule(secgroup['id'])
290
291 return secgroup
292
293 def _create_loginable_secgroup_rule(self, secgroup_id=None):
294 _client = self.compute_security_groups_client
295 _client_rules = self.compute_security_group_rules_client
296 if secgroup_id is None:
297 sgs = _client.list_security_groups()['security_groups']
298 for sg in sgs:
299 if sg['name'] == 'default':
300 secgroup_id = sg['id']
301
302 # These rules are intended to permit inbound ssh and icmp
303 # traffic from all sources, so no group_id is provided.
304 # Setting a group_id would only permit traffic from ports
305 # belonging to the same security group.
306 rulesets = [
307 {
308 # ssh
309 'ip_protocol': 'tcp',
310 'from_port': 22,
311 'to_port': 22,
312 'cidr': '0.0.0.0/0',
313 },
314 {
315 # ping
316 'ip_protocol': 'icmp',
317 'from_port': -1,
318 'to_port': -1,
319 'cidr': '0.0.0.0/0',
320 }
321 ]
322 rules = list()
323 for ruleset in rulesets:
324 sg_rule = _client_rules.create_security_group_rule(
325 parent_group_id=secgroup_id, **ruleset)['security_group_rule']
326 rules.append(sg_rule)
327 return rules
328
329 def _create_security_group_rule(self, secgroup=None,
330 sec_group_rules_client=None,
331 tenant_id=None,
332 security_groups_client=None, **kwargs):
333 """Create a rule from a dictionary of rule parameters.
334
335 Create a rule in a secgroup. if secgroup not defined will search for
336 default secgroup in tenant_id.
337
338 :param secgroup: the security group.
339 :param tenant_id: if secgroup not passed -- the tenant in which to
340 search for default secgroup
341 :param kwargs: a dictionary containing rule parameters:
342 for example, to allow incoming ssh:
343 rule = {
344 direction: 'ingress'
345 protocol:'tcp',
346 port_range_min: 22,
347 port_range_max: 22
348 }
349 """
350 if sec_group_rules_client is None:
351 sec_group_rules_client = self.security_group_rules_client
352 if security_groups_client is None:
353 security_groups_client = self.security_groups_client
354 if not tenant_id:
355 tenant_id = security_groups_client.tenant_id
356 if secgroup is None:
357 secgroup = self._default_security_group(
358 client=security_groups_client, tenant_id=tenant_id)
359
360 ruleset = dict(security_group_id=secgroup['id'],
361 tenant_id=secgroup['tenant_id'])
362 ruleset.update(kwargs)
363
364 sg_rule = sec_group_rules_client.create_security_group_rule(**ruleset)
365 sg_rule = sg_rule['security_group_rule']
366
367 self.assertEqual(secgroup['tenant_id'], sg_rule['tenant_id'])
368 self.assertEqual(secgroup['id'], sg_rule['security_group_id'])
369
370 return sg_rule