blob: 28b19e30001e04b5691ffee067dffe64ebfe7610 [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 Saienko27343712022-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)
298 return image['id']
299
300 def rebuild_server(self, server_id, image=None,
301 preserve_ephemeral=False, wait=True,
302 rebuild_kwargs=None):
303 if image is None:
304 image = CONF.compute.image_ref
305
306 rebuild_kwargs = rebuild_kwargs or {}
307
308 LOG.debug("Rebuilding server (id: %s, image: %s, preserve eph: %s)",
309 server_id, image, preserve_ephemeral)
310 self.servers_client.rebuild_server(
311 server_id=server_id, image_ref=image,
312 preserve_ephemeral=preserve_ephemeral,
313 **rebuild_kwargs)
314 if wait:
315 waiters.wait_for_server_status(self.servers_client,
316 server_id, 'ACTIVE')
317
318 def create_floating_ip(self, thing, pool_name=None):
319 """Create a floating IP and associates to a server on Nova"""
320
321 if not pool_name:
322 pool_name = CONF.network.floating_network_name
323 floating_ip = (self.compute_floating_ips_client.
324 create_floating_ip(pool=pool_name)['floating_ip'])
325 self.addCleanup(test_utils.call_and_ignore_notfound_exc,
326 self.compute_floating_ips_client.delete_floating_ip,
327 floating_ip['id'])
328 self.compute_floating_ips_client.associate_floating_ip_to_server(
329 floating_ip['ip'], thing['id'])
330 return floating_ip
dane-fichter53f4fea2017-03-01 13:20:02 -0500331
332 def nova_volume_attach(self, server, volume_to_attach):
333 volume = self.servers_client.attach_volume(
334 server['id'], volumeId=volume_to_attach['id'], device='/dev/%s'
335 % CONF.compute.volume_device_name)['volumeAttachment']
336 self.assertEqual(volume_to_attach['id'], volume['id'])
337 waiters.wait_for_volume_resource_status(self.volumes_client,
338 volume['id'], 'in-use')
339
yatin5ddcc7e2018-03-27 14:49:36 +0530340 self.addCleanup(self.nova_volume_detach, server, volume)
dane-fichter53f4fea2017-03-01 13:20:02 -0500341 # Return the updated volume after the attachment
342 return self.volumes_client.show_volume(volume['id'])['volume']
343
344 def nova_volume_detach(self, server, volume):
345 self.servers_client.detach_volume(server['id'], volume['id'])
346 waiters.wait_for_volume_resource_status(self.volumes_client,
347 volume['id'], 'available')
348
349 volume = self.volumes_client.show_volume(volume['id'])['volume']
350 self.assertEqual('available', volume['status'])
351
352 def create_timestamp(self, ip_address, dev_name=None, mount_path='/mnt',
353 private_key=None):
354 ssh_client = self.get_remote_client(ip_address,
355 private_key=private_key)
356 if dev_name is not None:
357 ssh_client.make_fs(dev_name)
358 ssh_client.exec_command('sudo mount /dev/%s %s' % (dev_name,
359 mount_path))
360 cmd_timestamp = 'sudo sh -c "date > %s/timestamp; sync"' % mount_path
361 ssh_client.exec_command(cmd_timestamp)
362 timestamp = ssh_client.exec_command('sudo cat %s/timestamp'
363 % mount_path)
364 if dev_name is not None:
365 ssh_client.exec_command('sudo umount %s' % mount_path)
366 return timestamp
367
368 def get_timestamp(self, ip_address, dev_name=None, mount_path='/mnt',
369 private_key=None):
370 ssh_client = self.get_remote_client(ip_address,
371 private_key=private_key)
372 if dev_name is not None:
373 ssh_client.mount(dev_name, mount_path)
374 timestamp = ssh_client.exec_command('sudo cat %s/timestamp'
375 % mount_path)
376 if dev_name is not None:
377 ssh_client.exec_command('sudo umount %s' % mount_path)
378 return timestamp
379
380 def get_server_ip(self, server):
381 """Get the server fixed or floating IP.
382
383 Based on the configuration we're in, return a correct ip
384 address for validating that a guest is up.
385 """
386 if CONF.validation.connect_method == 'floating':
387 # The tests calling this method don't have a floating IP
388 # and can't make use of the validation resources. So the
389 # method is creating the floating IP there.
390 return self.create_floating_ip(server)['ip']
391 elif CONF.validation.connect_method == 'fixed':
392 # Determine the network name to look for based on config or creds
393 # provider network resources.
394 if CONF.validation.network_for_ssh:
395 addresses = server['addresses'][
396 CONF.validation.network_for_ssh]
397 else:
398 creds_provider = self._get_credentials_provider()
399 net_creds = creds_provider.get_primary_creds()
400 network = getattr(net_creds, 'network', None)
401 addresses = (server['addresses'][network['name']]
402 if network else [])
403 for address in addresses:
jacky069fd57e52019-01-04 23:55:03 +0800404 ip_version_for_ssh = CONF.validation.ip_version_for_ssh
405 if (address['version'] == ip_version_for_ssh and
406 address['OS-EXT-IPS:type'] == 'fixed'):
dane-fichter53f4fea2017-03-01 13:20:02 -0500407 return address['addr']
408 raise exceptions.ServerUnreachable(server_id=server['id'])
409 else:
410 raise lib_exc.InvalidConfiguration()
411
412 def get_remote_client(self, ip_address, username=None, private_key=None):
413 """Get a SSH client to a remote server
414
415 @param ip_address the server floating or fixed IP address to use
416 for ssh validation
417 @param username name of the Linux account on the remote server
418 @param private_key the SSH private key to use
419 @return a RemoteClient object
420 """
421
422 if username is None:
423 username = CONF.validation.image_ssh_user
424 # Set this with 'keypair' or others to log in with keypair or
425 # username/password.
426 if CONF.validation.auth_method == 'keypair':
427 password = None
428 if private_key is None:
429 private_key = self.keypair['private_key']
430 else:
431 password = CONF.validation.image_ssh_password
432 private_key = None
433 linux_client = remote_client.RemoteClient(ip_address, username,
434 pkey=private_key,
435 password=password)
436 try:
437 linux_client.validate_authentication()
438 except Exception as e:
439 message = ('Initializing SSH connection to %(ip)s failed. '
440 'Error: %(error)s' % {'ip': ip_address,
441 'error': e})
442 caller = test_utils.find_test_caller()
443 if caller:
444 message = '(%s) %s' % (caller, message)
445 LOG.exception(message)
446 self._log_console_output()
447 raise
448
449 return linux_client
450
451 def _default_security_group(self, client=None, tenant_id=None):
452 """Get default secgroup for given tenant_id.
453
454 :returns: default secgroup for given tenant
455 """
456 if client is None:
457 client = self.security_groups_client
458 if not tenant_id:
459 tenant_id = client.tenant_id
460 sgs = [
461 sg for sg in list(client.list_security_groups().values())[0]
462 if sg['tenant_id'] == tenant_id and sg['name'] == 'default'
463 ]
464 msg = "No default security group for tenant %s." % (tenant_id)
465 self.assertGreater(len(sgs), 0, msg)
466 return sgs[0]
467
468 def _create_security_group(self):
469 # Create security group
470 sg_name = data_utils.rand_name(self.__class__.__name__)
471 sg_desc = sg_name + " description"
472 secgroup = self.compute_security_groups_client.create_security_group(
473 name=sg_name, description=sg_desc)['security_group']
474 self.assertEqual(secgroup['name'], sg_name)
475 self.assertEqual(secgroup['description'], sg_desc)
476 self.addCleanup(
477 test_utils.call_and_ignore_notfound_exc,
478 self.compute_security_groups_client.delete_security_group,
479 secgroup['id'])
480
481 # Add rules to the security group
482 self._create_loginable_secgroup_rule(secgroup['id'])
483
484 return secgroup
485
486 def _create_loginable_secgroup_rule(self, secgroup_id=None):
487 _client = self.compute_security_groups_client
488 _client_rules = self.compute_security_group_rules_client
489 if secgroup_id is None:
490 sgs = _client.list_security_groups()['security_groups']
491 for sg in sgs:
492 if sg['name'] == 'default':
493 secgroup_id = sg['id']
494
495 # These rules are intended to permit inbound ssh and icmp
496 # traffic from all sources, so no group_id is provided.
497 # Setting a group_id would only permit traffic from ports
498 # belonging to the same security group.
499 rulesets = [
500 {
501 # ssh
502 'ip_protocol': 'tcp',
503 'from_port': 22,
504 'to_port': 22,
505 'cidr': '0.0.0.0/0',
506 },
507 {
508 # ping
509 'ip_protocol': 'icmp',
510 'from_port': -1,
511 'to_port': -1,
512 'cidr': '0.0.0.0/0',
513 }
514 ]
515 rules = list()
516 for ruleset in rulesets:
517 sg_rule = _client_rules.create_security_group_rule(
518 parent_group_id=secgroup_id, **ruleset)['security_group_rule']
519 rules.append(sg_rule)
520 return rules
521
522 def _create_security_group_rule(self, secgroup=None,
523 sec_group_rules_client=None,
524 tenant_id=None,
525 security_groups_client=None, **kwargs):
526 """Create a rule from a dictionary of rule parameters.
527
528 Create a rule in a secgroup. if secgroup not defined will search for
529 default secgroup in tenant_id.
530
531 :param secgroup: the security group.
532 :param tenant_id: if secgroup not passed -- the tenant in which to
533 search for default secgroup
534 :param kwargs: a dictionary containing rule parameters:
535 for example, to allow incoming ssh:
536 rule = {
537 direction: 'ingress'
538 protocol:'tcp',
539 port_range_min: 22,
540 port_range_max: 22
541 }
542 """
543 if sec_group_rules_client is None:
544 sec_group_rules_client = self.security_group_rules_client
545 if security_groups_client is None:
546 security_groups_client = self.security_groups_client
547 if not tenant_id:
548 tenant_id = security_groups_client.tenant_id
549 if secgroup is None:
550 secgroup = self._default_security_group(
551 client=security_groups_client, tenant_id=tenant_id)
552
553 ruleset = dict(security_group_id=secgroup['id'],
554 tenant_id=secgroup['tenant_id'])
555 ruleset.update(kwargs)
556
557 sg_rule = sec_group_rules_client.create_security_group_rule(**ruleset)
558 sg_rule = sg_rule['security_group_rule']
559
560 self.assertEqual(secgroup['tenant_id'], sg_rule['tenant_id'])
561 self.assertEqual(secgroup['id'], sg_rule['security_group_id'])
562
563 return sg_rule