blob: 8a8ca9d8b53eb1df5ca7e140e6fddf8d3fe492f8 [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 Hrachyshkaecce1f62018-01-18 13:32:05 -080035class ScenarioTest(manager.ScenarioTest):
Brianna Poulos011292a2017-03-15 16:24:38 -040036 """Base class for scenario tests. Uses tempest own clients. """
37
38 credentials = ['primary']
39
40 @classmethod
41 def setup_clients(cls):
42 super(ScenarioTest, cls).setup_clients()
43 # Clients (in alphabetical order)
Vu Cong Tuan17b61932017-06-21 17:52:43 +070044 cls.flavors_client = cls.os_primary.flavors_client
Brianna Poulos011292a2017-03-15 16:24:38 -040045 cls.compute_floating_ips_client = (
Vu Cong Tuan17b61932017-06-21 17:52:43 +070046 cls.os_primary.compute_floating_ips_client)
Brianna Poulos011292a2017-03-15 16:24:38 -040047 if CONF.service_available.glance:
48 # Check if glance v1 is available to determine which client to use.
49 if CONF.image_feature_enabled.api_v1:
Vu Cong Tuan17b61932017-06-21 17:52:43 +070050 cls.image_client = cls.os_primary.image_client
Brianna Poulos011292a2017-03-15 16:24:38 -040051 elif CONF.image_feature_enabled.api_v2:
Vu Cong Tuan17b61932017-06-21 17:52:43 +070052 cls.image_client = cls.os_primary.image_client_v2
Brianna Poulos011292a2017-03-15 16:24:38 -040053 else:
54 raise lib_exc.InvalidConfiguration(
55 'Either api_v1 or api_v2 must be True in '
56 '[image-feature-enabled].')
57 # Compute image client
Vu Cong Tuan17b61932017-06-21 17:52:43 +070058 cls.compute_images_client = cls.os_primary.compute_images_client
59 cls.keypairs_client = cls.os_primary.keypairs_client
Brianna Poulos011292a2017-03-15 16:24:38 -040060 # Nova security groups client
61 cls.compute_security_groups_client = (
Vu Cong Tuan17b61932017-06-21 17:52:43 +070062 cls.os_primary.compute_security_groups_client)
Brianna Poulos011292a2017-03-15 16:24:38 -040063 cls.compute_security_group_rules_client = (
Vu Cong Tuan17b61932017-06-21 17:52:43 +070064 cls.os_primary.compute_security_group_rules_client)
65 cls.servers_client = cls.os_primary.servers_client
Brianna Poulos011292a2017-03-15 16:24:38 -040066 # Neutron network client
Vu Cong Tuan17b61932017-06-21 17:52:43 +070067 cls.networks_client = cls.os_primary.networks_client
68 cls.ports_client = cls.os_primary.ports_client
69 cls.routers_client = cls.os_primary.routers_client
70 cls.subnets_client = cls.os_primary.subnets_client
71 cls.floating_ips_client = cls.os_primary.floating_ips_client
72 cls.security_groups_client = cls.os_primary.security_groups_client
Brianna Poulos011292a2017-03-15 16:24:38 -040073 cls.security_group_rules_client = (
Vu Cong Tuan17b61932017-06-21 17:52:43 +070074 cls.os_primary.security_group_rules_client)
Brianna Poulos011292a2017-03-15 16:24:38 -040075
76 if CONF.volume_feature_enabled.api_v2:
Vu Cong Tuan17b61932017-06-21 17:52:43 +070077 cls.volumes_client = cls.os_primary.volumes_v2_client
78 cls.snapshots_client = cls.os_primary.snapshots_v2_client
Brianna Poulos011292a2017-03-15 16:24:38 -040079 else:
Vu Cong Tuan17b61932017-06-21 17:52:43 +070080 cls.volumes_client = cls.os_primary.volumes_client
81 cls.snapshots_client = cls.os_primary.snapshots_client
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
334 # Return the updated volume after the attachment
335 return self.volumes_client.show_volume(volume['id'])['volume']
336
337 def nova_volume_detach(self, server, volume):
338 self.servers_client.detach_volume(server['id'], volume['id'])
339 waiters.wait_for_volume_resource_status(self.volumes_client,
340 volume['id'], 'available')
341
342 volume = self.volumes_client.show_volume(volume['id'])['volume']
343 self.assertEqual('available', volume['status'])
344
345 def create_timestamp(self, ip_address, dev_name=None, mount_path='/mnt',
346 private_key=None):
347 ssh_client = self.get_remote_client(ip_address,
348 private_key=private_key)
349 if dev_name is not None:
350 ssh_client.make_fs(dev_name)
351 ssh_client.exec_command('sudo mount /dev/%s %s' % (dev_name,
352 mount_path))
353 cmd_timestamp = 'sudo sh -c "date > %s/timestamp; sync"' % mount_path
354 ssh_client.exec_command(cmd_timestamp)
355 timestamp = ssh_client.exec_command('sudo cat %s/timestamp'
356 % mount_path)
357 if dev_name is not None:
358 ssh_client.exec_command('sudo umount %s' % mount_path)
359 return timestamp
360
361 def get_timestamp(self, ip_address, dev_name=None, mount_path='/mnt',
362 private_key=None):
363 ssh_client = self.get_remote_client(ip_address,
364 private_key=private_key)
365 if dev_name is not None:
366 ssh_client.mount(dev_name, mount_path)
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_server_ip(self, server):
374 """Get the server fixed or floating IP.
375
376 Based on the configuration we're in, return a correct ip
377 address for validating that a guest is up.
378 """
379 if CONF.validation.connect_method == 'floating':
380 # The tests calling this method don't have a floating IP
381 # and can't make use of the validation resources. So the
382 # method is creating the floating IP there.
383 return self.create_floating_ip(server)['ip']
384 elif CONF.validation.connect_method == 'fixed':
385 # Determine the network name to look for based on config or creds
386 # provider network resources.
387 if CONF.validation.network_for_ssh:
388 addresses = server['addresses'][
389 CONF.validation.network_for_ssh]
390 else:
391 creds_provider = self._get_credentials_provider()
392 net_creds = creds_provider.get_primary_creds()
393 network = getattr(net_creds, 'network', None)
394 addresses = (server['addresses'][network['name']]
395 if network else [])
396 for address in addresses:
397 if (address['version'] == CONF.validation.ip_version_for_ssh
398 and address['OS-EXT-IPS:type'] == 'fixed'):
399 return address['addr']
400 raise exceptions.ServerUnreachable(server_id=server['id'])
401 else:
402 raise lib_exc.InvalidConfiguration()
403
404 def get_remote_client(self, ip_address, username=None, private_key=None):
405 """Get a SSH client to a remote server
406
407 @param ip_address the server floating or fixed IP address to use
408 for ssh validation
409 @param username name of the Linux account on the remote server
410 @param private_key the SSH private key to use
411 @return a RemoteClient object
412 """
413
414 if username is None:
415 username = CONF.validation.image_ssh_user
416 # Set this with 'keypair' or others to log in with keypair or
417 # username/password.
418 if CONF.validation.auth_method == 'keypair':
419 password = None
420 if private_key is None:
421 private_key = self.keypair['private_key']
422 else:
423 password = CONF.validation.image_ssh_password
424 private_key = None
425 linux_client = remote_client.RemoteClient(ip_address, username,
426 pkey=private_key,
427 password=password)
428 try:
429 linux_client.validate_authentication()
430 except Exception as e:
431 message = ('Initializing SSH connection to %(ip)s failed. '
432 'Error: %(error)s' % {'ip': ip_address,
433 'error': e})
434 caller = test_utils.find_test_caller()
435 if caller:
436 message = '(%s) %s' % (caller, message)
437 LOG.exception(message)
438 self._log_console_output()
439 raise
440
441 return linux_client
442
443 def _default_security_group(self, client=None, tenant_id=None):
444 """Get default secgroup for given tenant_id.
445
446 :returns: default secgroup for given tenant
447 """
448 if client is None:
449 client = self.security_groups_client
450 if not tenant_id:
451 tenant_id = client.tenant_id
452 sgs = [
453 sg for sg in list(client.list_security_groups().values())[0]
454 if sg['tenant_id'] == tenant_id and sg['name'] == 'default'
455 ]
456 msg = "No default security group for tenant %s." % (tenant_id)
457 self.assertGreater(len(sgs), 0, msg)
458 return sgs[0]
459
460 def _create_security_group(self):
461 # Create security group
462 sg_name = data_utils.rand_name(self.__class__.__name__)
463 sg_desc = sg_name + " description"
464 secgroup = self.compute_security_groups_client.create_security_group(
465 name=sg_name, description=sg_desc)['security_group']
466 self.assertEqual(secgroup['name'], sg_name)
467 self.assertEqual(secgroup['description'], sg_desc)
468 self.addCleanup(
469 test_utils.call_and_ignore_notfound_exc,
470 self.compute_security_groups_client.delete_security_group,
471 secgroup['id'])
472
473 # Add rules to the security group
474 self._create_loginable_secgroup_rule(secgroup['id'])
475
476 return secgroup
477
478 def _create_loginable_secgroup_rule(self, secgroup_id=None):
479 _client = self.compute_security_groups_client
480 _client_rules = self.compute_security_group_rules_client
481 if secgroup_id is None:
482 sgs = _client.list_security_groups()['security_groups']
483 for sg in sgs:
484 if sg['name'] == 'default':
485 secgroup_id = sg['id']
486
487 # These rules are intended to permit inbound ssh and icmp
488 # traffic from all sources, so no group_id is provided.
489 # Setting a group_id would only permit traffic from ports
490 # belonging to the same security group.
491 rulesets = [
492 {
493 # ssh
494 'ip_protocol': 'tcp',
495 'from_port': 22,
496 'to_port': 22,
497 'cidr': '0.0.0.0/0',
498 },
499 {
500 # ping
501 'ip_protocol': 'icmp',
502 'from_port': -1,
503 'to_port': -1,
504 'cidr': '0.0.0.0/0',
505 }
506 ]
507 rules = list()
508 for ruleset in rulesets:
509 sg_rule = _client_rules.create_security_group_rule(
510 parent_group_id=secgroup_id, **ruleset)['security_group_rule']
511 rules.append(sg_rule)
512 return rules
513
514 def _create_security_group_rule(self, secgroup=None,
515 sec_group_rules_client=None,
516 tenant_id=None,
517 security_groups_client=None, **kwargs):
518 """Create a rule from a dictionary of rule parameters.
519
520 Create a rule in a secgroup. if secgroup not defined will search for
521 default secgroup in tenant_id.
522
523 :param secgroup: the security group.
524 :param tenant_id: if secgroup not passed -- the tenant in which to
525 search for default secgroup
526 :param kwargs: a dictionary containing rule parameters:
527 for example, to allow incoming ssh:
528 rule = {
529 direction: 'ingress'
530 protocol:'tcp',
531 port_range_min: 22,
532 port_range_max: 22
533 }
534 """
535 if sec_group_rules_client is None:
536 sec_group_rules_client = self.security_group_rules_client
537 if security_groups_client is None:
538 security_groups_client = self.security_groups_client
539 if not tenant_id:
540 tenant_id = security_groups_client.tenant_id
541 if secgroup is None:
542 secgroup = self._default_security_group(
543 client=security_groups_client, tenant_id=tenant_id)
544
545 ruleset = dict(security_group_id=secgroup['id'],
546 tenant_id=secgroup['tenant_id'])
547 ruleset.update(kwargs)
548
549 sg_rule = sec_group_rules_client.create_security_group_rule(**ruleset)
550 sg_rule = sg_rule['security_group_rule']
551
552 self.assertEqual(secgroup['tenant_id'], sg_rule['tenant_id'])
553 self.assertEqual(secgroup['id'], sg_rule['security_group_id'])
554
555 return sg_rule