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