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