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