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