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