blob: 2e24084f16c283704ba9c1cd957ff9aaa1751a0a [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
19from tempest.common import compute
20from tempest.common import image as common_image
dane-fichter53f4fea2017-03-01 13:20:02 -050021from tempest.common.utils.linux import remote_client
Brianna Poulos011292a2017-03-15 16:24:38 -040022from tempest.common import waiters
23from tempest import config
dane-fichter53f4fea2017-03-01 13:20:02 -050024from tempest import exceptions
Brianna Poulos011292a2017-03-15 16:24:38 -040025from tempest.lib.common.utils import data_utils
26from tempest.lib.common.utils import test_utils
27from tempest.lib import exceptions as lib_exc
Ihar Hrachyshkaecce1f62018-01-18 13:32:05 -080028from tempest.scenario import manager
Brianna Poulos011292a2017-03-15 16:24:38 -040029
30CONF = config.CONF
31
32LOG = log.getLogger(__name__)
33
34
Ihar Hrachyshka2d0cf0a2018-01-18 13:40:09 -080035# we inherit from NetworkScenarioTest since some test cases need access to
36# check_*_connectivity methods to validate instances are up and accessible
37class ScenarioTest(manager.NetworkScenarioTest):
Brianna Poulos011292a2017-03-15 16:24:38 -040038 """Base class for scenario tests. Uses tempest own clients. """
39
40 credentials = ['primary']
41
42 @classmethod
Vasyl Saienko64cb4c62022-08-21 18:02:15 +000043 def setup_credentials(cls):
44 cls.set_network_resources(network=True, subnet=True, router=True)
45 super().setup_credentials()
46
47 @classmethod
Brianna Poulos011292a2017-03-15 16:24:38 -040048 def setup_clients(cls):
49 super(ScenarioTest, cls).setup_clients()
50 # Clients (in alphabetical order)
Vu Cong Tuan17b61932017-06-21 17:52:43 +070051 cls.flavors_client = cls.os_primary.flavors_client
Brianna Poulos011292a2017-03-15 16:24:38 -040052 cls.compute_floating_ips_client = (
Vu Cong Tuan17b61932017-06-21 17:52:43 +070053 cls.os_primary.compute_floating_ips_client)
Brianna Poulos011292a2017-03-15 16:24:38 -040054 if CONF.service_available.glance:
55 # Check if glance v1 is available to determine which client to use.
56 if CONF.image_feature_enabled.api_v1:
Vu Cong Tuan17b61932017-06-21 17:52:43 +070057 cls.image_client = cls.os_primary.image_client
Brianna Poulos011292a2017-03-15 16:24:38 -040058 elif CONF.image_feature_enabled.api_v2:
Vu Cong Tuan17b61932017-06-21 17:52:43 +070059 cls.image_client = cls.os_primary.image_client_v2
Brianna Poulos011292a2017-03-15 16:24:38 -040060 else:
61 raise lib_exc.InvalidConfiguration(
62 'Either api_v1 or api_v2 must be True in '
63 '[image-feature-enabled].')
64 # Compute image client
Vu Cong Tuan17b61932017-06-21 17:52:43 +070065 cls.compute_images_client = cls.os_primary.compute_images_client
66 cls.keypairs_client = cls.os_primary.keypairs_client
Brianna Poulos011292a2017-03-15 16:24:38 -040067 # Nova security groups client
68 cls.compute_security_groups_client = (
Vu Cong Tuan17b61932017-06-21 17:52:43 +070069 cls.os_primary.compute_security_groups_client)
Brianna Poulos011292a2017-03-15 16:24:38 -040070 cls.compute_security_group_rules_client = (
Vu Cong Tuan17b61932017-06-21 17:52:43 +070071 cls.os_primary.compute_security_group_rules_client)
72 cls.servers_client = cls.os_primary.servers_client
Brianna Poulos011292a2017-03-15 16:24:38 -040073 # Neutron network client
Vu Cong Tuan17b61932017-06-21 17:52:43 +070074 cls.networks_client = cls.os_primary.networks_client
75 cls.ports_client = cls.os_primary.ports_client
76 cls.routers_client = cls.os_primary.routers_client
77 cls.subnets_client = cls.os_primary.subnets_client
78 cls.floating_ips_client = cls.os_primary.floating_ips_client
79 cls.security_groups_client = cls.os_primary.security_groups_client
Brianna Poulos011292a2017-03-15 16:24:38 -040080 cls.security_group_rules_client = (
Vu Cong Tuan17b61932017-06-21 17:52:43 +070081 cls.os_primary.security_group_rules_client)
Brianna Poulos011292a2017-03-15 16:24:38 -040082
Ghanshyam Mann48d10b82019-12-12 16:45:44 +000083 cls.volumes_client = cls.os_primary.volumes_client_latest
84 cls.snapshots_client = cls.os_primary.snapshots_client_latest
Brianna Poulos011292a2017-03-15 16:24:38 -040085
86 # ## Test functions library
87 #
88 # The create_[resource] functions only return body and discard the
89 # resp part which is not used in scenario tests
90
91 def _create_port(self, network_id, client=None, namestart='port-quotatest',
92 **kwargs):
93 if not client:
94 client = self.ports_client
95 name = data_utils.rand_name(namestart)
96 result = client.create_port(
97 name=name,
98 network_id=network_id,
99 **kwargs)
100 self.assertIsNotNone(result, 'Unable to allocate port')
101 port = result['port']
102 self.addCleanup(test_utils.call_and_ignore_notfound_exc,
103 client.delete_port, port['id'])
104 return port
105
106 def create_keypair(self, client=None):
107 if not client:
108 client = self.keypairs_client
109 name = data_utils.rand_name(self.__class__.__name__)
110 # We don't need to create a keypair by pubkey in scenario
111 body = client.create_keypair(name=name)
112 self.addCleanup(client.delete_keypair, name)
113 return body['keypair']
114
115 def create_server(self, name=None, image_id=None, flavor=None,
116 validatable=False, wait_until='ACTIVE',
117 clients=None, **kwargs):
118 """Wrapper utility that returns a test server.
119
120 This wrapper utility calls the common create test server and
121 returns a test server. The purpose of this wrapper is to minimize
122 the impact on the code of the tests already using this
123 function.
124 """
125
126 # NOTE(jlanoux): As a first step, ssh checks in the scenario
127 # tests need to be run regardless of the run_validation and
128 # validatable parameters and thus until the ssh validation job
129 # becomes voting in CI. The test resources management and IP
130 # association are taken care of in the scenario tests.
131 # Therefore, the validatable parameter is set to false in all
132 # those tests. In this way create_server just return a standard
133 # server and the scenario tests always perform ssh checks.
134
135 # Needed for the cross_tenant_traffic test:
136 if clients is None:
Vu Cong Tuan17b61932017-06-21 17:52:43 +0700137 clients = self.os_primary
Brianna Poulos011292a2017-03-15 16:24:38 -0400138
139 if name is None:
140 name = data_utils.rand_name(self.__class__.__name__ + "-server")
141
142 vnic_type = CONF.network.port_vnic_type
143
144 # If vnic_type is configured create port for
145 # every network
146 if vnic_type:
147 ports = []
148
149 create_port_body = {'binding:vnic_type': vnic_type,
150 'namestart': 'port-smoke'}
151 if kwargs:
152 # Convert security group names to security group ids
153 # to pass to create_port
154 if 'security_groups' in kwargs:
155 security_groups = \
156 clients.security_groups_client.list_security_groups(
157 ).get('security_groups')
158 sec_dict = dict([(s['name'], s['id'])
159 for s in security_groups])
160
161 sec_groups_names = [s['name'] for s in kwargs.pop(
162 'security_groups')]
163 security_groups_ids = [sec_dict[s]
164 for s in sec_groups_names]
165
166 if security_groups_ids:
167 create_port_body[
168 'security_groups'] = security_groups_ids
169 networks = kwargs.pop('networks', [])
170 else:
171 networks = []
172
173 # If there are no networks passed to us we look up
174 # for the project's private networks and create a port.
175 # The same behaviour as we would expect when passing
176 # the call to the clients with no networks
177 if not networks:
178 networks = clients.networks_client.list_networks(
179 **{'router:external': False, 'fields': 'id'})['networks']
180
181 # It's net['uuid'] if networks come from kwargs
182 # and net['id'] if they come from
183 # clients.networks_client.list_networks
184 for net in networks:
185 net_id = net.get('uuid', net.get('id'))
186 if 'port' not in net:
187 port = self._create_port(network_id=net_id,
188 client=clients.ports_client,
189 **create_port_body)
190 ports.append({'port': port['id']})
191 else:
192 ports.append({'port': net['port']})
193 if ports:
194 kwargs['networks'] = ports
195 self.ports = ports
196
197 tenant_network = self.get_tenant_network()
198
199 body, servers = compute.create_test_server(
200 clients,
201 tenant_network=tenant_network,
202 wait_until=wait_until,
203 name=name, flavor=flavor,
204 image_id=image_id, **kwargs)
205
206 self.addCleanup(waiters.wait_for_server_termination,
207 clients.servers_client, body['id'])
208 self.addCleanup(test_utils.call_and_ignore_notfound_exc,
209 clients.servers_client.delete_server, body['id'])
210 server = clients.servers_client.show_server(body['id'])['server']
211 return server
212
213 def create_volume(self, size=None, name=None, snapshot_id=None,
214 imageRef=None, volume_type=None):
215 if size is None:
216 size = CONF.volume.volume_size
217 if imageRef:
218 image = self.compute_images_client.show_image(imageRef)['image']
219 min_disk = image.get('minDisk')
220 size = max(size, min_disk)
221 if name is None:
222 name = data_utils.rand_name(self.__class__.__name__ + "-volume")
223 kwargs = {'display_name': name,
224 'snapshot_id': snapshot_id,
225 'imageRef': imageRef,
226 'volume_type': volume_type,
227 'size': size}
Marian Krcmarikda011992020-09-12 02:32:23 +0200228 if CONF.compute.compute_volume_common_az:
229 kwargs.setdefault('availability_zone',
230 CONF.compute.compute_volume_common_az)
Brianna Poulos011292a2017-03-15 16:24:38 -0400231 volume = self.volumes_client.create_volume(**kwargs)['volume']
232
233 self.addCleanup(self.volumes_client.wait_for_resource_deletion,
234 volume['id'])
235 self.addCleanup(test_utils.call_and_ignore_notfound_exc,
236 self.volumes_client.delete_volume, volume['id'])
237
238 # NOTE(e0ne): Cinder API v2 uses name instead of display_name
239 if 'display_name' in volume:
240 self.assertEqual(name, volume['display_name'])
241 else:
242 self.assertEqual(name, volume['name'])
243 waiters.wait_for_volume_resource_status(self.volumes_client,
244 volume['id'], 'available')
245 # The volume retrieved on creation has a non-up-to-date status.
246 # Retrieval after it becomes active ensures correct details.
247 volume = self.volumes_client.show_volume(volume['id'])['volume']
248 return volume
249
250 def create_volume_type(self, client=None, name=None, backend_name=None):
251 if not client:
252 client = self.admin_volume_types_client
253 if not name:
254 class_name = self.__class__.__name__
255 name = data_utils.rand_name(class_name + '-volume-type')
256 randomized_name = data_utils.rand_name('scenario-type-' + name)
257
258 LOG.debug("Creating a volume type: %s on backend %s",
259 randomized_name, backend_name)
260 extra_specs = {}
261 if backend_name:
262 extra_specs = {"volume_backend_name": backend_name}
263
264 body = client.create_volume_type(name=randomized_name,
265 extra_specs=extra_specs)
266 volume_type = body['volume_type']
267 self.assertIn('id', volume_type)
268 self.addCleanup(client.delete_volume_type, volume_type['id'])
269 return volume_type
270
271 def _image_create(self, name, fmt, path,
272 disk_format=None, properties=None):
273 if properties is None:
274 properties = {}
275 name = data_utils.rand_name('%s-' % name)
276 params = {
277 'name': name,
278 'container_format': fmt,
279 'disk_format': disk_format or fmt,
280 }
281 if CONF.image_feature_enabled.api_v1:
282 params['is_public'] = 'False'
283 params['properties'] = properties
284 params = {'headers': common_image.image_meta_to_headers(**params)}
285 else:
286 params['visibility'] = 'private'
287 # Additional properties are flattened out in the v2 API.
288 params.update(properties)
289 body = self.image_client.create_image(**params)
290 image = body['image'] if 'image' in body else body
291 self.addCleanup(self.image_client.delete_image, image['id'])
292 self.assertEqual("queued", image['status'])
293 with open(path, 'rb') as image_file:
294 if CONF.image_feature_enabled.api_v1:
295 self.image_client.update_image(image['id'], data=image_file)
296 else:
297 self.image_client.store_image_file(image['id'], image_file)
Marian Krcmarik1972c462020-11-20 01:33:02 +0100298
299 if CONF.image_feature_enabled.import_image:
300 available_stores = []
301 try:
302 available_stores = self.image_client.info_stores()['stores']
303 except exceptions.NotFound:
304 pass
305 available_import_methods = self.image_client.info_import()[
306 'import-methods']['value']
307 if ('copy-image' in available_import_methods and
308 len(available_stores) > 1):
309 self.image_client.image_import(image['id'],
310 method='copy-image',
311 all_stores=True,
312 all_stores_must_succeed=False)
313 failed_stores = waiters.wait_for_image_copied_to_stores(
314 self.image_client, image['id'])
315 self.assertEqual(0, len(failed_stores),
316 "Failed to copy the following stores: %s" %
317 str(failed_stores))
318
Brianna Poulos011292a2017-03-15 16:24:38 -0400319 return image['id']
320
321 def rebuild_server(self, server_id, image=None,
322 preserve_ephemeral=False, wait=True,
323 rebuild_kwargs=None):
324 if image is None:
325 image = CONF.compute.image_ref
326
327 rebuild_kwargs = rebuild_kwargs or {}
328
329 LOG.debug("Rebuilding server (id: %s, image: %s, preserve eph: %s)",
330 server_id, image, preserve_ephemeral)
331 self.servers_client.rebuild_server(
332 server_id=server_id, image_ref=image,
333 preserve_ephemeral=preserve_ephemeral,
334 **rebuild_kwargs)
335 if wait:
336 waiters.wait_for_server_status(self.servers_client,
337 server_id, 'ACTIVE')
338
339 def create_floating_ip(self, thing, pool_name=None):
340 """Create a floating IP and associates to a server on Nova"""
341
342 if not pool_name:
343 pool_name = CONF.network.floating_network_name
344 floating_ip = (self.compute_floating_ips_client.
345 create_floating_ip(pool=pool_name)['floating_ip'])
346 self.addCleanup(test_utils.call_and_ignore_notfound_exc,
347 self.compute_floating_ips_client.delete_floating_ip,
348 floating_ip['id'])
349 self.compute_floating_ips_client.associate_floating_ip_to_server(
350 floating_ip['ip'], thing['id'])
351 return floating_ip
dane-fichter53f4fea2017-03-01 13:20:02 -0500352
353 def nova_volume_attach(self, server, volume_to_attach):
354 volume = self.servers_client.attach_volume(
355 server['id'], volumeId=volume_to_attach['id'], device='/dev/%s'
356 % CONF.compute.volume_device_name)['volumeAttachment']
357 self.assertEqual(volume_to_attach['id'], volume['id'])
358 waiters.wait_for_volume_resource_status(self.volumes_client,
359 volume['id'], 'in-use')
360
yatin5ddcc7e2018-03-27 14:49:36 +0530361 self.addCleanup(self.nova_volume_detach, server, volume)
dane-fichter53f4fea2017-03-01 13:20:02 -0500362 # Return the updated volume after the attachment
363 return self.volumes_client.show_volume(volume['id'])['volume']
364
365 def nova_volume_detach(self, server, volume):
366 self.servers_client.detach_volume(server['id'], volume['id'])
367 waiters.wait_for_volume_resource_status(self.volumes_client,
368 volume['id'], 'available')
369
370 volume = self.volumes_client.show_volume(volume['id'])['volume']
371 self.assertEqual('available', volume['status'])
372
373 def create_timestamp(self, ip_address, dev_name=None, mount_path='/mnt',
374 private_key=None):
375 ssh_client = self.get_remote_client(ip_address,
376 private_key=private_key)
377 if dev_name is not None:
378 ssh_client.make_fs(dev_name)
379 ssh_client.exec_command('sudo mount /dev/%s %s' % (dev_name,
380 mount_path))
381 cmd_timestamp = 'sudo sh -c "date > %s/timestamp; sync"' % mount_path
382 ssh_client.exec_command(cmd_timestamp)
383 timestamp = ssh_client.exec_command('sudo cat %s/timestamp'
384 % mount_path)
385 if dev_name is not None:
386 ssh_client.exec_command('sudo umount %s' % mount_path)
387 return timestamp
388
389 def get_timestamp(self, ip_address, dev_name=None, mount_path='/mnt',
390 private_key=None):
391 ssh_client = self.get_remote_client(ip_address,
392 private_key=private_key)
393 if dev_name is not None:
394 ssh_client.mount(dev_name, mount_path)
395 timestamp = ssh_client.exec_command('sudo cat %s/timestamp'
396 % mount_path)
397 if dev_name is not None:
398 ssh_client.exec_command('sudo umount %s' % mount_path)
399 return timestamp
400
401 def get_server_ip(self, server):
402 """Get the server fixed or floating IP.
403
404 Based on the configuration we're in, return a correct ip
405 address for validating that a guest is up.
406 """
407 if CONF.validation.connect_method == 'floating':
408 # The tests calling this method don't have a floating IP
409 # and can't make use of the validation resources. So the
410 # method is creating the floating IP there.
411 return self.create_floating_ip(server)['ip']
412 elif CONF.validation.connect_method == 'fixed':
413 # Determine the network name to look for based on config or creds
414 # provider network resources.
415 if CONF.validation.network_for_ssh:
416 addresses = server['addresses'][
417 CONF.validation.network_for_ssh]
418 else:
419 creds_provider = self._get_credentials_provider()
420 net_creds = creds_provider.get_primary_creds()
421 network = getattr(net_creds, 'network', None)
422 addresses = (server['addresses'][network['name']]
423 if network else [])
424 for address in addresses:
jacky06a318f6d2019-01-04 23:55:03 +0800425 ip_version_for_ssh = CONF.validation.ip_version_for_ssh
426 if (address['version'] == ip_version_for_ssh and
427 address['OS-EXT-IPS:type'] == 'fixed'):
dane-fichter53f4fea2017-03-01 13:20:02 -0500428 return address['addr']
429 raise exceptions.ServerUnreachable(server_id=server['id'])
430 else:
431 raise lib_exc.InvalidConfiguration()
432
433 def get_remote_client(self, ip_address, username=None, private_key=None):
434 """Get a SSH client to a remote server
435
436 @param ip_address the server floating or fixed IP address to use
437 for ssh validation
438 @param username name of the Linux account on the remote server
439 @param private_key the SSH private key to use
440 @return a RemoteClient object
441 """
442
443 if username is None:
444 username = CONF.validation.image_ssh_user
445 # Set this with 'keypair' or others to log in with keypair or
446 # username/password.
447 if CONF.validation.auth_method == 'keypair':
448 password = None
449 if private_key is None:
450 private_key = self.keypair['private_key']
451 else:
452 password = CONF.validation.image_ssh_password
453 private_key = None
454 linux_client = remote_client.RemoteClient(ip_address, username,
455 pkey=private_key,
456 password=password)
457 try:
458 linux_client.validate_authentication()
459 except Exception as e:
460 message = ('Initializing SSH connection to %(ip)s failed. '
461 'Error: %(error)s' % {'ip': ip_address,
462 'error': e})
463 caller = test_utils.find_test_caller()
464 if caller:
465 message = '(%s) %s' % (caller, message)
466 LOG.exception(message)
467 self._log_console_output()
468 raise
469
470 return linux_client
471
472 def _default_security_group(self, client=None, tenant_id=None):
473 """Get default secgroup for given tenant_id.
474
475 :returns: default secgroup for given tenant
476 """
477 if client is None:
478 client = self.security_groups_client
479 if not tenant_id:
480 tenant_id = client.tenant_id
481 sgs = [
482 sg for sg in list(client.list_security_groups().values())[0]
483 if sg['tenant_id'] == tenant_id and sg['name'] == 'default'
484 ]
485 msg = "No default security group for tenant %s." % (tenant_id)
486 self.assertGreater(len(sgs), 0, msg)
487 return sgs[0]
488
489 def _create_security_group(self):
490 # Create security group
491 sg_name = data_utils.rand_name(self.__class__.__name__)
492 sg_desc = sg_name + " description"
493 secgroup = self.compute_security_groups_client.create_security_group(
494 name=sg_name, description=sg_desc)['security_group']
495 self.assertEqual(secgroup['name'], sg_name)
496 self.assertEqual(secgroup['description'], sg_desc)
497 self.addCleanup(
498 test_utils.call_and_ignore_notfound_exc,
499 self.compute_security_groups_client.delete_security_group,
500 secgroup['id'])
501
502 # Add rules to the security group
503 self._create_loginable_secgroup_rule(secgroup['id'])
504
505 return secgroup
506
507 def _create_loginable_secgroup_rule(self, secgroup_id=None):
508 _client = self.compute_security_groups_client
509 _client_rules = self.compute_security_group_rules_client
510 if secgroup_id is None:
511 sgs = _client.list_security_groups()['security_groups']
512 for sg in sgs:
513 if sg['name'] == 'default':
514 secgroup_id = sg['id']
515
516 # These rules are intended to permit inbound ssh and icmp
517 # traffic from all sources, so no group_id is provided.
518 # Setting a group_id would only permit traffic from ports
519 # belonging to the same security group.
520 rulesets = [
521 {
522 # ssh
523 'ip_protocol': 'tcp',
524 'from_port': 22,
525 'to_port': 22,
526 'cidr': '0.0.0.0/0',
527 },
528 {
529 # ping
530 'ip_protocol': 'icmp',
531 'from_port': -1,
532 'to_port': -1,
533 'cidr': '0.0.0.0/0',
534 }
535 ]
536 rules = list()
537 for ruleset in rulesets:
538 sg_rule = _client_rules.create_security_group_rule(
539 parent_group_id=secgroup_id, **ruleset)['security_group_rule']
540 rules.append(sg_rule)
541 return rules
542
543 def _create_security_group_rule(self, secgroup=None,
544 sec_group_rules_client=None,
545 tenant_id=None,
546 security_groups_client=None, **kwargs):
547 """Create a rule from a dictionary of rule parameters.
548
549 Create a rule in a secgroup. if secgroup not defined will search for
550 default secgroup in tenant_id.
551
552 :param secgroup: the security group.
553 :param tenant_id: if secgroup not passed -- the tenant in which to
554 search for default secgroup
555 :param kwargs: a dictionary containing rule parameters:
556 for example, to allow incoming ssh:
557 rule = {
558 direction: 'ingress'
559 protocol:'tcp',
560 port_range_min: 22,
561 port_range_max: 22
562 }
563 """
564 if sec_group_rules_client is None:
565 sec_group_rules_client = self.security_group_rules_client
566 if security_groups_client is None:
567 security_groups_client = self.security_groups_client
568 if not tenant_id:
569 tenant_id = security_groups_client.tenant_id
570 if secgroup is None:
571 secgroup = self._default_security_group(
572 client=security_groups_client, tenant_id=tenant_id)
573
574 ruleset = dict(security_group_id=secgroup['id'],
575 tenant_id=secgroup['tenant_id'])
576 ruleset.update(kwargs)
577
578 sg_rule = sec_group_rules_client.create_security_group_rule(**ruleset)
579 sg_rule = sg_rule['security_group_rule']
580
581 self.assertEqual(secgroup['tenant_id'], sg_rule['tenant_id'])
582 self.assertEqual(secgroup['id'], sg_rule['security_group_id'])
583
584 return sg_rule