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