blob: 7cdc5a86ba23492569775841f0e4d4dc10bdaa17 [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 Saienko3cdd8292022-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}
228 volume = self.volumes_client.create_volume(**kwargs)['volume']
229
230 self.addCleanup(self.volumes_client.wait_for_resource_deletion,
231 volume['id'])
232 self.addCleanup(test_utils.call_and_ignore_notfound_exc,
233 self.volumes_client.delete_volume, volume['id'])
234
235 # NOTE(e0ne): Cinder API v2 uses name instead of display_name
236 if 'display_name' in volume:
237 self.assertEqual(name, volume['display_name'])
238 else:
239 self.assertEqual(name, volume['name'])
240 waiters.wait_for_volume_resource_status(self.volumes_client,
241 volume['id'], 'available')
242 # The volume retrieved on creation has a non-up-to-date status.
243 # Retrieval after it becomes active ensures correct details.
244 volume = self.volumes_client.show_volume(volume['id'])['volume']
245 return volume
246
247 def create_volume_type(self, client=None, name=None, backend_name=None):
248 if not client:
249 client = self.admin_volume_types_client
250 if not name:
251 class_name = self.__class__.__name__
252 name = data_utils.rand_name(class_name + '-volume-type')
253 randomized_name = data_utils.rand_name('scenario-type-' + name)
254
255 LOG.debug("Creating a volume type: %s on backend %s",
256 randomized_name, backend_name)
257 extra_specs = {}
258 if backend_name:
259 extra_specs = {"volume_backend_name": backend_name}
260
261 body = client.create_volume_type(name=randomized_name,
262 extra_specs=extra_specs)
263 volume_type = body['volume_type']
264 self.assertIn('id', volume_type)
265 self.addCleanup(client.delete_volume_type, volume_type['id'])
266 return volume_type
267
268 def _image_create(self, name, fmt, path,
269 disk_format=None, properties=None):
270 if properties is None:
271 properties = {}
272 name = data_utils.rand_name('%s-' % name)
273 params = {
274 'name': name,
275 'container_format': fmt,
276 'disk_format': disk_format or fmt,
277 }
278 if CONF.image_feature_enabled.api_v1:
279 params['is_public'] = 'False'
280 params['properties'] = properties
281 params = {'headers': common_image.image_meta_to_headers(**params)}
282 else:
283 params['visibility'] = 'private'
284 # Additional properties are flattened out in the v2 API.
285 params.update(properties)
286 body = self.image_client.create_image(**params)
287 image = body['image'] if 'image' in body else body
288 self.addCleanup(self.image_client.delete_image, image['id'])
289 self.assertEqual("queued", image['status'])
290 with open(path, 'rb') as image_file:
291 if CONF.image_feature_enabled.api_v1:
292 self.image_client.update_image(image['id'], data=image_file)
293 else:
294 self.image_client.store_image_file(image['id'], image_file)
295 return image['id']
296
297 def rebuild_server(self, server_id, image=None,
298 preserve_ephemeral=False, wait=True,
299 rebuild_kwargs=None):
300 if image is None:
301 image = CONF.compute.image_ref
302
303 rebuild_kwargs = rebuild_kwargs or {}
304
305 LOG.debug("Rebuilding server (id: %s, image: %s, preserve eph: %s)",
306 server_id, image, preserve_ephemeral)
307 self.servers_client.rebuild_server(
308 server_id=server_id, image_ref=image,
309 preserve_ephemeral=preserve_ephemeral,
310 **rebuild_kwargs)
311 if wait:
312 waiters.wait_for_server_status(self.servers_client,
313 server_id, 'ACTIVE')
314
315 def create_floating_ip(self, thing, pool_name=None):
316 """Create a floating IP and associates to a server on Nova"""
317
318 if not pool_name:
319 pool_name = CONF.network.floating_network_name
320 floating_ip = (self.compute_floating_ips_client.
321 create_floating_ip(pool=pool_name)['floating_ip'])
322 self.addCleanup(test_utils.call_and_ignore_notfound_exc,
323 self.compute_floating_ips_client.delete_floating_ip,
324 floating_ip['id'])
325 self.compute_floating_ips_client.associate_floating_ip_to_server(
326 floating_ip['ip'], thing['id'])
327 return floating_ip
dane-fichter53f4fea2017-03-01 13:20:02 -0500328
329 def nova_volume_attach(self, server, volume_to_attach):
330 volume = self.servers_client.attach_volume(
331 server['id'], volumeId=volume_to_attach['id'], device='/dev/%s'
332 % CONF.compute.volume_device_name)['volumeAttachment']
333 self.assertEqual(volume_to_attach['id'], volume['id'])
334 waiters.wait_for_volume_resource_status(self.volumes_client,
335 volume['id'], 'in-use')
336
yatin5ddcc7e2018-03-27 14:49:36 +0530337 self.addCleanup(self.nova_volume_detach, server, volume)
dane-fichter53f4fea2017-03-01 13:20:02 -0500338 # Return the updated volume after the attachment
339 return self.volumes_client.show_volume(volume['id'])['volume']
340
341 def nova_volume_detach(self, server, volume):
342 self.servers_client.detach_volume(server['id'], volume['id'])
343 waiters.wait_for_volume_resource_status(self.volumes_client,
344 volume['id'], 'available')
345
346 volume = self.volumes_client.show_volume(volume['id'])['volume']
347 self.assertEqual('available', volume['status'])
348
349 def create_timestamp(self, ip_address, dev_name=None, mount_path='/mnt',
350 private_key=None):
351 ssh_client = self.get_remote_client(ip_address,
352 private_key=private_key)
353 if dev_name is not None:
354 ssh_client.make_fs(dev_name)
355 ssh_client.exec_command('sudo mount /dev/%s %s' % (dev_name,
356 mount_path))
357 cmd_timestamp = 'sudo sh -c "date > %s/timestamp; sync"' % mount_path
358 ssh_client.exec_command(cmd_timestamp)
359 timestamp = ssh_client.exec_command('sudo cat %s/timestamp'
360 % mount_path)
361 if dev_name is not None:
362 ssh_client.exec_command('sudo umount %s' % mount_path)
363 return timestamp
364
365 def get_timestamp(self, ip_address, dev_name=None, mount_path='/mnt',
366 private_key=None):
367 ssh_client = self.get_remote_client(ip_address,
368 private_key=private_key)
369 if dev_name is not None:
370 ssh_client.mount(dev_name, mount_path)
371 timestamp = ssh_client.exec_command('sudo cat %s/timestamp'
372 % mount_path)
373 if dev_name is not None:
374 ssh_client.exec_command('sudo umount %s' % mount_path)
375 return timestamp
376
377 def get_server_ip(self, server):
378 """Get the server fixed or floating IP.
379
380 Based on the configuration we're in, return a correct ip
381 address for validating that a guest is up.
382 """
383 if CONF.validation.connect_method == 'floating':
384 # The tests calling this method don't have a floating IP
385 # and can't make use of the validation resources. So the
386 # method is creating the floating IP there.
387 return self.create_floating_ip(server)['ip']
388 elif CONF.validation.connect_method == 'fixed':
389 # Determine the network name to look for based on config or creds
390 # provider network resources.
391 if CONF.validation.network_for_ssh:
392 addresses = server['addresses'][
393 CONF.validation.network_for_ssh]
394 else:
395 creds_provider = self._get_credentials_provider()
396 net_creds = creds_provider.get_primary_creds()
397 network = getattr(net_creds, 'network', None)
398 addresses = (server['addresses'][network['name']]
399 if network else [])
400 for address in addresses:
401 if (address['version'] == CONF.validation.ip_version_for_ssh
402 and address['OS-EXT-IPS:type'] == 'fixed'):
403 return address['addr']
404 raise exceptions.ServerUnreachable(server_id=server['id'])
405 else:
406 raise lib_exc.InvalidConfiguration()
407
408 def get_remote_client(self, ip_address, username=None, private_key=None):
409 """Get a SSH client to a remote server
410
411 @param ip_address the server floating or fixed IP address to use
412 for ssh validation
413 @param username name of the Linux account on the remote server
414 @param private_key the SSH private key to use
415 @return a RemoteClient object
416 """
417
418 if username is None:
419 username = CONF.validation.image_ssh_user
420 # Set this with 'keypair' or others to log in with keypair or
421 # username/password.
422 if CONF.validation.auth_method == 'keypair':
423 password = None
424 if private_key is None:
425 private_key = self.keypair['private_key']
426 else:
427 password = CONF.validation.image_ssh_password
428 private_key = None
429 linux_client = remote_client.RemoteClient(ip_address, username,
430 pkey=private_key,
431 password=password)
432 try:
433 linux_client.validate_authentication()
434 except Exception as e:
435 message = ('Initializing SSH connection to %(ip)s failed. '
436 'Error: %(error)s' % {'ip': ip_address,
437 'error': e})
438 caller = test_utils.find_test_caller()
439 if caller:
440 message = '(%s) %s' % (caller, message)
441 LOG.exception(message)
442 self._log_console_output()
443 raise
444
445 return linux_client
446
447 def _default_security_group(self, client=None, tenant_id=None):
448 """Get default secgroup for given tenant_id.
449
450 :returns: default secgroup for given tenant
451 """
452 if client is None:
453 client = self.security_groups_client
454 if not tenant_id:
455 tenant_id = client.tenant_id
456 sgs = [
457 sg for sg in list(client.list_security_groups().values())[0]
458 if sg['tenant_id'] == tenant_id and sg['name'] == 'default'
459 ]
460 msg = "No default security group for tenant %s." % (tenant_id)
461 self.assertGreater(len(sgs), 0, msg)
462 return sgs[0]
463
464 def _create_security_group(self):
465 # Create security group
466 sg_name = data_utils.rand_name(self.__class__.__name__)
467 sg_desc = sg_name + " description"
468 secgroup = self.compute_security_groups_client.create_security_group(
469 name=sg_name, description=sg_desc)['security_group']
470 self.assertEqual(secgroup['name'], sg_name)
471 self.assertEqual(secgroup['description'], sg_desc)
472 self.addCleanup(
473 test_utils.call_and_ignore_notfound_exc,
474 self.compute_security_groups_client.delete_security_group,
475 secgroup['id'])
476
477 # Add rules to the security group
478 self._create_loginable_secgroup_rule(secgroup['id'])
479
480 return secgroup
481
482 def _create_loginable_secgroup_rule(self, secgroup_id=None):
483 _client = self.compute_security_groups_client
484 _client_rules = self.compute_security_group_rules_client
485 if secgroup_id is None:
486 sgs = _client.list_security_groups()['security_groups']
487 for sg in sgs:
488 if sg['name'] == 'default':
489 secgroup_id = sg['id']
490
491 # These rules are intended to permit inbound ssh and icmp
492 # traffic from all sources, so no group_id is provided.
493 # Setting a group_id would only permit traffic from ports
494 # belonging to the same security group.
495 rulesets = [
496 {
497 # ssh
498 'ip_protocol': 'tcp',
499 'from_port': 22,
500 'to_port': 22,
501 'cidr': '0.0.0.0/0',
502 },
503 {
504 # ping
505 'ip_protocol': 'icmp',
506 'from_port': -1,
507 'to_port': -1,
508 'cidr': '0.0.0.0/0',
509 }
510 ]
511 rules = list()
512 for ruleset in rulesets:
513 sg_rule = _client_rules.create_security_group_rule(
514 parent_group_id=secgroup_id, **ruleset)['security_group_rule']
515 rules.append(sg_rule)
516 return rules
517
518 def _create_security_group_rule(self, secgroup=None,
519 sec_group_rules_client=None,
520 tenant_id=None,
521 security_groups_client=None, **kwargs):
522 """Create a rule from a dictionary of rule parameters.
523
524 Create a rule in a secgroup. if secgroup not defined will search for
525 default secgroup in tenant_id.
526
527 :param secgroup: the security group.
528 :param tenant_id: if secgroup not passed -- the tenant in which to
529 search for default secgroup
530 :param kwargs: a dictionary containing rule parameters:
531 for example, to allow incoming ssh:
532 rule = {
533 direction: 'ingress'
534 protocol:'tcp',
535 port_range_min: 22,
536 port_range_max: 22
537 }
538 """
539 if sec_group_rules_client is None:
540 sec_group_rules_client = self.security_group_rules_client
541 if security_groups_client is None:
542 security_groups_client = self.security_groups_client
543 if not tenant_id:
544 tenant_id = security_groups_client.tenant_id
545 if secgroup is None:
546 secgroup = self._default_security_group(
547 client=security_groups_client, tenant_id=tenant_id)
548
549 ruleset = dict(security_group_id=secgroup['id'],
550 tenant_id=secgroup['tenant_id'])
551 ruleset.update(kwargs)
552
553 sg_rule = sec_group_rules_client.create_security_group_rule(**ruleset)
554 sg_rule = sg_rule['security_group_rule']
555
556 self.assertEqual(secgroup['tenant_id'], sg_rule['tenant_id'])
557 self.assertEqual(secgroup['id'], sg_rule['security_group_id'])
558
559 return sg_rule