blob: 54ea78db3ed15d488e025b4f2f2a2d2298e29c8c [file] [log] [blame]
Marc Koderer0abc93b2015-07-15 09:18:35 +02001# Copyright 2014 Mirantis Inc.
2# All Rights Reserved.
3#
4# Licensed under the Apache License, Version 2.0 (the "License"); you may
5# not use this file except in compliance with the License. You may obtain
6# a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13# License for the specific language governing permissions and limitations
14# under the License.
15
16import copy
Valeriy Ponomaryov2abf5d72016-06-01 18:30:12 +030017import re
Marc Koderer0abc93b2015-07-15 09:18:35 +020018import traceback
19
Marc Koderer0abc93b2015-07-15 09:18:35 +020020from oslo_log import log
21import six
Valeriy Ponomaryov48a2bd72015-11-05 13:22:44 +020022from tempest import config
Goutham Pacha Ravic678e212020-03-20 11:13:47 -070023from tempest.lib.common import cred_client
Ben Swartzlander1c4ff522016-03-02 22:16:23 -050024from tempest.lib.common.utils import data_utils
25from tempest.lib import exceptions
Valeriy Ponomaryov48a2bd72015-11-05 13:22:44 +020026from tempest import test
Marc Koderer0abc93b2015-07-15 09:18:35 +020027
Andrea Frittoli (andreaf)369391a2016-06-27 18:59:13 +010028from manila_tempest_tests import clients
Yogeshbdb88102015-09-29 23:41:02 -040029from manila_tempest_tests.common import constants
lkuchlan540e74a2021-01-19 18:08:25 +020030from manila_tempest_tests.common import waiters
Marc Koderer0abc93b2015-07-15 09:18:35 +020031from manila_tempest_tests import share_exceptions
Valeriy Ponomaryovfcde7712015-12-14 18:06:13 +020032from manila_tempest_tests import utils
Marc Koderer0abc93b2015-07-15 09:18:35 +020033
lkuchlan1d1461d2020-08-04 11:19:11 +030034
Marc Koderer0abc93b2015-07-15 09:18:35 +020035CONF = config.CONF
36LOG = log.getLogger(__name__)
37
Valeriy Ponomaryov2abf5d72016-06-01 18:30:12 +030038# Test tags related to test direction
39TAG_POSITIVE = "positive"
40TAG_NEGATIVE = "negative"
41
42# Test tags related to service involvement
Tom Barron69f96962019-07-29 17:07:03 -040043# Only requires that manila-api service running.
Valeriy Ponomaryov2abf5d72016-06-01 18:30:12 +030044TAG_API = "api"
Tom Barron69f96962019-07-29 17:07:03 -040045# Requires all manila services running, intended to test back-end
46# (manila-share) behavior.
Valeriy Ponomaryov2abf5d72016-06-01 18:30:12 +030047TAG_BACKEND = "backend"
Tom Barron69f96962019-07-29 17:07:03 -040048# Requires all manila services running, intended to test API behavior.
Valeriy Ponomaryov2abf5d72016-06-01 18:30:12 +030049TAG_API_WITH_BACKEND = "api_with_backend"
50
51TAGS_MAPPER = {
52 "p": TAG_POSITIVE,
53 "n": TAG_NEGATIVE,
54 "a": TAG_API,
55 "b": TAG_BACKEND,
56 "ab": TAG_API_WITH_BACKEND,
57}
58TAGS_PATTERN = re.compile(
59 r"(?=.*\[.*\b(%(p)s|%(n)s)\b.*\])(?=.*\[.*\b(%(a)s|%(b)s|%(ab)s)\b.*\])" %
60 TAGS_MAPPER)
61
62
63def verify_test_has_appropriate_tags(self):
64 if not TAGS_PATTERN.match(self.id()):
65 msg = (
66 "Required attributes either not set or set improperly. "
67 "Two test attributes are expected:\n"
68 " - one of '%(p)s' or '%(n)s' and \n"
69 " - one of '%(a)s', '%(b)s' or '%(ab)s'."
70 ) % TAGS_MAPPER
71 raise self.failureException(msg)
72
Marc Koderer0abc93b2015-07-15 09:18:35 +020073
74class handle_cleanup_exceptions(object):
75 """Handle exceptions raised with cleanup operations.
76
77 Always suppress errors when exceptions.NotFound or exceptions.Forbidden
78 are raised.
79 Suppress all other exceptions only in case config opt
80 'suppress_errors_in_cleanup' in config group 'share' is True.
81 """
82
83 def __enter__(self):
84 return self
85
86 def __exit__(self, exc_type, exc_value, exc_traceback):
87 if not (isinstance(exc_value,
88 (exceptions.NotFound, exceptions.Forbidden)) or
89 CONF.share.suppress_errors_in_cleanup):
90 return False # Do not suppress error if any
91 if exc_traceback:
92 LOG.error("Suppressed cleanup error in Manila: "
junbolib236c242017-07-18 18:12:37 +080093 "\n%s", traceback.format_exc())
Marc Koderer0abc93b2015-07-15 09:18:35 +020094 return True # Suppress error if any
95
96
Marc Koderer0abc93b2015-07-15 09:18:35 +020097class BaseSharesTest(test.BaseTestCase):
98 """Base test case class for all Manila API tests."""
99
Valeriy Ponomaryov39cdf722016-05-30 18:16:15 +0300100 credentials = ('primary', )
Marc Koderer0abc93b2015-07-15 09:18:35 +0200101 force_tenant_isolation = False
Vitaliy Levitksicfebfff2016-12-15 16:16:35 +0200102 protocols = ["nfs", "cifs", "glusterfs", "hdfs", "cephfs", "maprfs"]
Marc Koderer0abc93b2015-07-15 09:18:35 +0200103
104 # Will be cleaned up in resource_cleanup
105 class_resources = []
106
107 # Will be cleaned up in tearDown method
108 method_resources = []
109
Andrea Frittoli (andreaf)369391a2016-06-27 18:59:13 +0100110 # NOTE(andreaf) Override the client manager class to be used, so that
111 # a stable class is used, which includes plugin registered services as well
112 client_manager = clients.Clients
113
Marc Koderer0abc93b2015-07-15 09:18:35 +0200114 @classmethod
Daniel Melladoe5269142017-01-12 12:17:58 +0000115 def skip_checks(cls):
116 super(BaseSharesTest, cls).skip_checks()
117 if not CONF.service_available.manila:
118 raise cls.skipException("Manila support is required")
lkuchlana3b6f7a2020-01-07 10:45:45 +0200119 if not any(p in CONF.share.enable_protocols for p in cls.protocols):
120 skip_msg = "%s tests are disabled" % CONF.share.enable_protocols
121 raise cls.skipException(skip_msg)
Daniel Melladoe5269142017-01-12 12:17:58 +0000122
123 @classmethod
Marc Koderer0abc93b2015-07-15 09:18:35 +0200124 def verify_nonempty(cls, *args):
125 if not all(args):
126 msg = "Missing API credentials in configuration."
127 raise cls.skipException(msg)
128
129 @classmethod
Goutham Pacha Ravi4a0b7322020-06-30 19:42:45 -0700130 def setup_credentials(cls):
131 # This call is used to tell the credential allocator to create
132 # network resources for this test case. NOTE: it must go before the
133 # super call, to override decisions in the base classes.
134 network_resources = {}
135 if (CONF.share.multitenancy_enabled and
136 CONF.share.create_networks_when_multitenancy_enabled):
137 # We're testing a DHSS=True driver, and manila is configured with
138 # NeutronNetworkPlugin (or a derivative) that supports creating
139 # share networks with project neutron networks, so lets ask for
140 # neutron network resources to be created with test credentials
141 network_resources.update({'network': True,
142 'subnet': True,
143 'router': True})
144 cls.set_network_resources(**network_resources)
145 super(BaseSharesTest, cls).setup_credentials()
146
147 @classmethod
Valeriy Ponomaryov39cdf722016-05-30 18:16:15 +0300148 def setup_clients(cls):
149 super(BaseSharesTest, cls).setup_clients()
150 os = getattr(cls, 'os_%s' % cls.credentials[0])
Andrea Frittoli (andreaf)369391a2016-06-27 18:59:13 +0100151 # Initialise share clients for test credentials
152 cls.shares_client = os.share_v1.SharesClient()
153 cls.shares_v2_client = os.share_v2.SharesV2Client()
154 # Initialise network clients for test credentials
Goutham Pacha Ravi4a0b7322020-06-30 19:42:45 -0700155 cls.networks_client = None
156 cls.subnets_client = None
Andrea Frittoli (andreaf)369391a2016-06-27 18:59:13 +0100157 if CONF.service_available.neutron:
158 cls.networks_client = os.network.NetworksClient()
159 cls.subnets_client = os.network.SubnetsClient()
Valeriy Ponomaryov4fb305f2016-10-21 13:46:47 +0300160
Goutham Pacha Ravi4a0b7322020-06-30 19:42:45 -0700161 # If DHSS=True, create a share network and set it in the client
162 # for easy access.
Valeriy Ponomaryov39cdf722016-05-30 18:16:15 +0300163 if CONF.share.multitenancy_enabled:
Valeriy Ponomaryovc5dae272016-06-10 18:29:24 +0300164 if (not CONF.service_available.neutron and
165 CONF.share.create_networks_when_multitenancy_enabled):
Goutham Pacha Ravi4a0b7322020-06-30 19:42:45 -0700166 raise cls.skipException(
167 "Neutron support is required when "
168 "CONF.share.create_networks_when_multitenancy_enabled "
169 "is set to True")
Valeriy Ponomaryov39cdf722016-05-30 18:16:15 +0300170 share_network_id = cls.provide_share_network(
Goutham Pacha Ravi4a0b7322020-06-30 19:42:45 -0700171 cls.shares_client, cls.networks_client)
Valeriy Ponomaryov39cdf722016-05-30 18:16:15 +0300172 cls.shares_client.share_network_id = share_network_id
173 cls.shares_v2_client.share_network_id = share_network_id
174
Marc Koderer0abc93b2015-07-15 09:18:35 +0200175 def setUp(self):
176 super(BaseSharesTest, self).setUp()
Valeriy Ponomaryovdd162cb2016-01-20 19:09:49 +0200177 self.addCleanup(self.clear_resources)
Valeriy Ponomaryov2abf5d72016-06-01 18:30:12 +0300178 verify_test_has_appropriate_tags(self)
Marc Koderer0abc93b2015-07-15 09:18:35 +0200179
180 @classmethod
181 def resource_cleanup(cls):
Marc Koderer0abc93b2015-07-15 09:18:35 +0200182 cls.clear_resources(cls.class_resources)
Sam Wan241029c2016-07-26 03:37:42 -0400183 super(BaseSharesTest, cls).resource_cleanup()
Marc Koderer0abc93b2015-07-15 09:18:35 +0200184
185 @classmethod
debeltrami1753a592020-05-11 18:27:30 +0000186 def provide_and_associate_security_services(
187 cls, shares_client, share_network_id, cleanup_in_class=True):
188 """Creates a security service and associates to a share network.
189
190 This method creates security services based on the Multiopt
191 defined in tempest configuration named security_service. When this
192 configuration is not provided, the method will return None.
193 After the security service creation, this method also associates
194 the security service to a share network.
195
196 :param shares_client: shares client, which requires the provisioning
197 :param share_network_id: id of the share network to associate the
198 security service
199 :param cleanup_in_class: if the security service and the association
200 will be removed in the method teardown or class teardown
201 :returns: None -- if the security service configuration is not
202 defined
203 """
204
205 ss_configs = CONF.share.security_service
206 if not ss_configs:
207 return
208
209 for ss_config in ss_configs:
210 ss_name = "ss_autogenerated_by_tempest_%s" % (
211 ss_config.get("ss_type"))
212
213 ss_params = {
214 "name": ss_name,
215 "dns_ip": ss_config.get("ss_dns_ip"),
216 "server": ss_config.get("ss_server"),
217 "domain": ss_config.get("ss_domain"),
218 "user": ss_config.get("ss_user"),
219 "password": ss_config.get("ss_password")
220 }
221 ss_type = ss_config.get("ss_type")
222 security_service = cls.create_security_service(
223 ss_type,
224 client=shares_client,
225 cleanup_in_class=cleanup_in_class,
226 **ss_params)
227
228 cls.add_sec_service_to_share_network(
229 shares_client, share_network_id,
230 security_service["id"],
231 cleanup_in_class=cleanup_in_class)
232
233 @classmethod
234 def add_sec_service_to_share_network(
235 cls, client, share_network_id,
236 security_service_id, cleanup_in_class=True):
237 """Associates a security service to a share network.
238
239 This method associates a security service provided by
240 the security service configuration with a specific
241 share network.
242
243 :param share_network_id: the share network id to be
244 associate with a given security service
245 :param security_service_id: the security service id
246 to be associate with a given share network
247 :param cleanup_in_class: if the resources will be
248 dissociate in the method teardown or class teardown
249 """
250
251 client.add_sec_service_to_share_network(
252 share_network_id,
253 security_service_id)
254 resource = {
255 "type": "dissociate_security_service",
256 "id": security_service_id,
257 "extra_params": {
258 "share_network_id": share_network_id
259 },
260 "client": client,
261 }
262
263 if cleanup_in_class:
264 cls.class_resources.insert(0, resource)
265 else:
266 cls.method_resources.insert(0, resource)
267
268 @classmethod
Valeriy Ponomaryov48a2bd72015-11-05 13:22:44 +0200269 def provide_share_network(cls, shares_client, networks_client,
Rodrigo Barbieri58d9de32016-09-06 13:16:47 -0300270 ignore_multitenancy_config=False):
Goutham Pacha Ravi4a0b7322020-06-30 19:42:45 -0700271 """Get or create share network for DHSS=True drivers
Marc Koderer0abc93b2015-07-15 09:18:35 +0200272
Goutham Pacha Ravi4a0b7322020-06-30 19:42:45 -0700273 When testing DHSS=True (multitenancy_enabled) drivers, shares must
274 be requested on share networks.
Marc Koderer0abc93b2015-07-15 09:18:35 +0200275 :returns: str -- share network id for shares_client tenant
Goutham Pacha Ravi4a0b7322020-06-30 19:42:45 -0700276 :returns: None -- if single-tenant driver (DHSS=False) is used
Marc Koderer0abc93b2015-07-15 09:18:35 +0200277 """
278
Rodrigo Barbieri58d9de32016-09-06 13:16:47 -0300279 if (not ignore_multitenancy_config and
280 not CONF.share.multitenancy_enabled):
Goutham Pacha Ravi4a0b7322020-06-30 19:42:45 -0700281 # Assumed usage of a single-tenant driver (DHSS=False)
debeltrami1753a592020-05-11 18:27:30 +0000282 return None
Goutham Pacha Raviaf448262020-06-29 14:24:13 -0700283
Goutham Pacha Ravi4a0b7322020-06-30 19:42:45 -0700284 if shares_client.share_network_id:
285 # Share-network already exists, use it
286 return shares_client.share_network_id
debeltrami1753a592020-05-11 18:27:30 +0000287
Goutham Pacha Ravi4a0b7322020-06-30 19:42:45 -0700288 sn_name = "autogenerated_by_tempest"
289 sn_desc = "This share-network was created by tempest"
Rodrigo Barbieri58d9de32016-09-06 13:16:47 -0300290
Goutham Pacha Ravi4a0b7322020-06-30 19:42:45 -0700291 if not CONF.share.create_networks_when_multitenancy_enabled:
292 # We need a new share network, but don't need to associate
293 # any neutron networks to it - this configuration is used
294 # when manila is configured with "StandaloneNetworkPlugin"
295 # or "NeutronSingleNetworkPlugin" where all tenants share
296 # a single backend network where shares are exported.
297 sn = cls.create_share_network(cleanup_in_class=True,
298 client=shares_client,
299 add_security_services=True,
300 name=sn_name,
301 description=sn_desc)
302 return sn['id']
Marc Koderer0abc93b2015-07-15 09:18:35 +0200303
Goutham Pacha Ravi4a0b7322020-06-30 19:42:45 -0700304 # Retrieve non-public network list owned by the tenant
305 filters = {'project_id': shares_client.tenant_id,
306 'shared': False}
307 tenant_networks = (
308 networks_client.list_networks(**filters).get('networks', [])
309 )
310 tenant_networks_with_subnet = (
311 [n for n in tenant_networks if n['subnets']]
312 )
debeltrami1753a592020-05-11 18:27:30 +0000313
Goutham Pacha Ravi4a0b7322020-06-30 19:42:45 -0700314 if not tenant_networks_with_subnet:
315 # This can only occur if using tempest's pre-provisioned
316 # credentials and not allocating networks to them
317 raise cls.skipException(
318 "Test credentials must provide at least one "
319 "non-shared project network with a valid subnet when "
320 "CONF.share.create_networks_when_multitenancy_enabled is "
321 "set to True.")
debeltrami1753a592020-05-11 18:27:30 +0000322
Goutham Pacha Ravi4a0b7322020-06-30 19:42:45 -0700323 net_id = tenant_networks_with_subnet[0]['id']
324 subnet_id = tenant_networks_with_subnet[0]['subnets'][0]
debeltrami1753a592020-05-11 18:27:30 +0000325
Goutham Pacha Ravi4a0b7322020-06-30 19:42:45 -0700326 # Create suitable share-network
327 sn = cls.create_share_network(cleanup_in_class=True,
328 client=shares_client,
329 add_security_services=True,
330 name=sn_name,
331 description=sn_desc,
332 neutron_net_id=net_id,
333 neutron_subnet_id=subnet_id)
debeltrami1753a592020-05-11 18:27:30 +0000334
Goutham Pacha Ravi4a0b7322020-06-30 19:42:45 -0700335 return sn['id']
Marc Koderer0abc93b2015-07-15 09:18:35 +0200336
337 @classmethod
marcusvrne0d7cfd2016-06-24 12:27:55 -0300338 def _create_share(cls, share_protocol=None, size=None, name=None,
Marc Koderer0abc93b2015-07-15 09:18:35 +0200339 snapshot_id=None, description=None, metadata=None,
340 share_network_id=None, share_type_id=None,
Andrew Kerrb8436922016-06-01 15:32:43 -0400341 share_group_id=None, client=None,
Clinton Knighte5c8f092015-08-27 15:00:23 -0400342 cleanup_in_class=True, is_public=False, **kwargs):
Valeriy Ponomaryov1aaa72d2015-09-08 12:59:41 +0300343 client = client or cls.shares_v2_client
Marc Koderer0abc93b2015-07-15 09:18:35 +0200344 description = description or "Tempest's share"
yogesh06f519f2017-06-26 13:16:12 -0400345 share_network_id = (share_network_id or
346 CONF.share.share_network_id or
347 client.share_network_id or None)
Marc Koderer0abc93b2015-07-15 09:18:35 +0200348 metadata = metadata or {}
marcusvrne0d7cfd2016-06-24 12:27:55 -0300349 size = size or CONF.share.share_size
Clinton Knighte5c8f092015-08-27 15:00:23 -0400350 kwargs.update({
Marc Koderer0abc93b2015-07-15 09:18:35 +0200351 'share_protocol': share_protocol,
352 'size': size,
353 'name': name,
354 'snapshot_id': snapshot_id,
355 'description': description,
356 'metadata': metadata,
357 'share_network_id': share_network_id,
358 'share_type_id': share_type_id,
359 'is_public': is_public,
Clinton Knighte5c8f092015-08-27 15:00:23 -0400360 })
Andrew Kerrb8436922016-06-01 15:32:43 -0400361 if share_group_id:
362 kwargs['share_group_id'] = share_group_id
Andrew Kerrbf31e912015-07-29 10:39:38 -0400363
Marc Koderer0abc93b2015-07-15 09:18:35 +0200364 share = client.create_share(**kwargs)
Andrew Kerrbf31e912015-07-29 10:39:38 -0400365 resource = {"type": "share", "id": share["id"], "client": client,
Andrew Kerrb8436922016-06-01 15:32:43 -0400366 "share_group_id": share_group_id}
Marc Koderer0abc93b2015-07-15 09:18:35 +0200367 cleanup_list = (cls.class_resources if cleanup_in_class else
368 cls.method_resources)
369 cleanup_list.insert(0, resource)
370 return share
371
372 @classmethod
Rodrigo Barbieri427bc052016-06-06 17:10:06 -0300373 def migrate_share(
374 cls, share_id, dest_host, wait_for_status, client=None,
Rodrigo Barbieri027df982016-11-24 15:52:03 -0200375 force_host_assisted_migration=False, writable=False,
376 nondisruptive=False, preserve_metadata=False,
377 preserve_snapshots=False, new_share_network_id=None,
Rodrigo Barbierid38d2f52016-07-19 22:24:56 -0300378 new_share_type_id=None, **kwargs):
Clinton Knighte5c8f092015-08-27 15:00:23 -0400379 client = client or cls.shares_v2_client
Rodrigo Barbieri427bc052016-06-06 17:10:06 -0300380 client.migrate_share(
381 share_id, dest_host,
382 force_host_assisted_migration=force_host_assisted_migration,
Rodrigo Barbieri027df982016-11-24 15:52:03 -0200383 writable=writable, preserve_metadata=preserve_metadata,
384 nondisruptive=nondisruptive, preserve_snapshots=preserve_snapshots,
Rodrigo Barbieri427bc052016-06-06 17:10:06 -0300385 new_share_network_id=new_share_network_id,
Rodrigo Barbierid38d2f52016-07-19 22:24:56 -0300386 new_share_type_id=new_share_type_id, **kwargs)
lkuchlan540e74a2021-01-19 18:08:25 +0200387 share = waiters.wait_for_migration_status(
388 client, share_id, dest_host, wait_for_status, **kwargs)
Rodrigo Barbierie3305122016-02-03 14:32:24 -0200389 return share
390
391 @classmethod
392 def migration_complete(cls, share_id, dest_host, client=None, **kwargs):
393 client = client or cls.shares_v2_client
394 client.migration_complete(share_id, **kwargs)
lkuchlan540e74a2021-01-19 18:08:25 +0200395 share = waiters.wait_for_migration_status(
396 client, share_id, dest_host, 'migration_success', **kwargs)
Rodrigo Barbierib7137ad2015-09-06 22:53:16 -0300397 return share
398
399 @classmethod
Rodrigo Barbieric9abf282016-08-24 22:01:31 -0300400 def migration_cancel(cls, share_id, dest_host, client=None, **kwargs):
401 client = client or cls.shares_v2_client
402 client.migration_cancel(share_id, **kwargs)
lkuchlan540e74a2021-01-19 18:08:25 +0200403 share = waiters.wait_for_migration_status(
404 client, share_id, dest_host, 'migration_cancelled', **kwargs)
Rodrigo Barbieric9abf282016-08-24 22:01:31 -0300405 return share
406
407 @classmethod
Marc Koderer0abc93b2015-07-15 09:18:35 +0200408 def create_share(cls, *args, **kwargs):
409 """Create one share and wait for available state. Retry if allowed."""
410 result = cls.create_shares([{"args": args, "kwargs": kwargs}])
411 return result[0]
412
413 @classmethod
414 def create_shares(cls, share_data_list):
415 """Creates several shares in parallel with retries.
416
417 Use this method when you want to create more than one share at same
418 time. Especially if config option 'share.share_creation_retry_number'
419 has value more than zero (0).
420 All shares will be expected to have 'available' status with or without
421 recreation else error will be raised.
422
423 :param share_data_list: list -- list of dictionaries with 'args' and
424 'kwargs' for '_create_share' method of this base class.
425 example of data:
426 share_data_list=[{'args': ['quuz'], 'kwargs': {'foo': 'bar'}}}]
427 :returns: list -- list of shares created using provided data.
428 """
429
Valeriy Ponomaryov39cdf722016-05-30 18:16:15 +0300430 for d in share_data_list:
Marc Koderer0abc93b2015-07-15 09:18:35 +0200431 if not isinstance(d, dict):
432 raise exceptions.TempestException(
433 "Expected 'dict', got '%s'" % type(d))
434 if "args" not in d:
435 d["args"] = []
436 if "kwargs" not in d:
437 d["kwargs"] = {}
438 if len(d) > 2:
439 raise exceptions.TempestException(
440 "Expected only 'args' and 'kwargs' keys. "
441 "Provided %s" % list(d))
Valeriy Ponomaryov39cdf722016-05-30 18:16:15 +0300442
443 data = []
444 for d in share_data_list:
445 client = d["kwargs"].pop("client", cls.shares_v2_client)
yogeshdb32f462016-09-28 15:09:50 -0400446 wait_for_status = d["kwargs"].pop("wait_for_status", True)
Valeriy Ponomaryov39cdf722016-05-30 18:16:15 +0300447 local_d = {
448 "args": d["args"],
449 "kwargs": copy.deepcopy(d["kwargs"]),
450 }
451 local_d["kwargs"]["client"] = client
452 local_d["share"] = cls._create_share(
453 *local_d["args"], **local_d["kwargs"])
454 local_d["cnt"] = 0
455 local_d["available"] = False
yogeshdb32f462016-09-28 15:09:50 -0400456 local_d["wait_for_status"] = wait_for_status
Valeriy Ponomaryov39cdf722016-05-30 18:16:15 +0300457 data.append(local_d)
Marc Koderer0abc93b2015-07-15 09:18:35 +0200458
459 while not all(d["available"] for d in data):
460 for d in data:
yogeshdb32f462016-09-28 15:09:50 -0400461 if not d["wait_for_status"]:
462 d["available"] = True
Marc Koderer0abc93b2015-07-15 09:18:35 +0200463 if d["available"]:
464 continue
Valeriy Ponomaryov1a3e3382016-06-08 15:17:16 +0300465 client = d["kwargs"]["client"]
466 share_id = d["share"]["id"]
Marc Koderer0abc93b2015-07-15 09:18:35 +0200467 try:
lkuchlanf7fc5b62021-01-26 14:53:43 +0200468 waiters.wait_for_resource_status(
lkuchlan540e74a2021-01-19 18:08:25 +0200469 client, share_id, "available")
Marc Koderer0abc93b2015-07-15 09:18:35 +0200470 d["available"] = True
471 except (share_exceptions.ShareBuildErrorException,
472 exceptions.TimeoutException) as e:
473 if CONF.share.share_creation_retry_number > d["cnt"]:
474 d["cnt"] += 1
475 msg = ("Share '%s' failed to be built. "
Valeriy Ponomaryov1a3e3382016-06-08 15:17:16 +0300476 "Trying create another." % share_id)
Marc Koderer0abc93b2015-07-15 09:18:35 +0200477 LOG.error(msg)
478 LOG.error(e)
Valeriy Ponomaryov1a3e3382016-06-08 15:17:16 +0300479 cg_id = d["kwargs"].get("consistency_group_id")
480 if cg_id:
481 # NOTE(vponomaryov): delete errored share
482 # immediately in case share is part of CG.
483 client.delete_share(
484 share_id,
485 params={"consistency_group_id": cg_id})
486 client.wait_for_resource_deletion(
487 share_id=share_id)
Marc Koderer0abc93b2015-07-15 09:18:35 +0200488 d["share"] = cls._create_share(
489 *d["args"], **d["kwargs"])
490 else:
gecong197358663802016-08-25 11:08:45 +0800491 raise
Marc Koderer0abc93b2015-07-15 09:18:35 +0200492
493 return [d["share"] for d in data]
494
495 @classmethod
Andrew Kerrb8436922016-06-01 15:32:43 -0400496 def create_share_group(cls, client=None, cleanup_in_class=True,
497 share_network_id=None, **kwargs):
Clinton Knighte5c8f092015-08-27 15:00:23 -0400498 client = client or cls.shares_v2_client
Andrew Kerrb8436922016-06-01 15:32:43 -0400499 if kwargs.get('source_share_group_snapshot_id') is None:
Goutham Pacha Ravi9221f5e2016-04-21 13:17:49 -0400500 kwargs['share_network_id'] = (share_network_id or
501 client.share_network_id or None)
Andrew Kerrb8436922016-06-01 15:32:43 -0400502 share_group = client.create_share_group(**kwargs)
Andrew Kerrbf31e912015-07-29 10:39:38 -0400503 resource = {
Andrew Kerrb8436922016-06-01 15:32:43 -0400504 "type": "share_group",
505 "id": share_group["id"],
506 "client": client,
507 }
Andrew Kerrbf31e912015-07-29 10:39:38 -0400508 if cleanup_in_class:
509 cls.class_resources.insert(0, resource)
510 else:
511 cls.method_resources.insert(0, resource)
512
Andrew Kerrb8436922016-06-01 15:32:43 -0400513 if kwargs.get('source_share_group_snapshot_id'):
514 new_share_group_shares = client.list_shares(
Andrew Kerrbf31e912015-07-29 10:39:38 -0400515 detailed=True,
silvacarloss6e575682020-02-18 19:52:35 -0300516 params={'share_group_id': share_group['id']})
Andrew Kerrbf31e912015-07-29 10:39:38 -0400517
Andrew Kerrb8436922016-06-01 15:32:43 -0400518 for share in new_share_group_shares:
Andrew Kerrbf31e912015-07-29 10:39:38 -0400519 resource = {"type": "share",
520 "id": share["id"],
521 "client": client,
Andrew Kerrb8436922016-06-01 15:32:43 -0400522 "share_group_id": share.get("share_group_id")}
Andrew Kerrbf31e912015-07-29 10:39:38 -0400523 if cleanup_in_class:
524 cls.class_resources.insert(0, resource)
525 else:
526 cls.method_resources.insert(0, resource)
527
lkuchlanf7fc5b62021-01-26 14:53:43 +0200528 waiters.wait_for_resource_status(
529 client, share_group['id'], 'available',
530 resource_name='share_group')
Andrew Kerrb8436922016-06-01 15:32:43 -0400531 return share_group
532
533 @classmethod
534 def create_share_group_type(cls, name=None, share_types=(), is_public=None,
535 group_specs=None, client=None,
536 cleanup_in_class=True, **kwargs):
537 client = client or cls.shares_v2_client
Valeriy Ponomaryove92f09f2017-03-16 17:25:47 +0300538 if (group_specs is None and
539 CONF.share.capability_sg_consistent_snapshot_support):
Valeriy Ponomaryov3c188932017-03-15 19:06:23 +0300540 group_specs = {
541 'consistent_snapshot_support': (
542 CONF.share.capability_sg_consistent_snapshot_support),
543 }
Andrew Kerrb8436922016-06-01 15:32:43 -0400544 share_group_type = client.create_share_group_type(
545 name=name,
546 share_types=share_types,
547 is_public=is_public,
548 group_specs=group_specs,
549 **kwargs)
550 resource = {
551 "type": "share_group_type",
552 "id": share_group_type["id"],
553 "client": client,
554 }
555 if cleanup_in_class:
556 cls.class_resources.insert(0, resource)
557 else:
558 cls.method_resources.insert(0, resource)
559 return share_group_type
Andrew Kerrbf31e912015-07-29 10:39:38 -0400560
561 @classmethod
Marc Koderer0abc93b2015-07-15 09:18:35 +0200562 def create_snapshot_wait_for_active(cls, share_id, name=None,
563 description=None, force=False,
564 client=None, cleanup_in_class=True):
565 if client is None:
Yogesh1f931ff2015-09-29 23:41:02 -0400566 client = cls.shares_v2_client
Marc Koderer0abc93b2015-07-15 09:18:35 +0200567 if description is None:
568 description = "Tempest's snapshot"
569 snapshot = client.create_snapshot(share_id, name, description, force)
570 resource = {
571 "type": "snapshot",
572 "id": snapshot["id"],
573 "client": client,
574 }
575 if cleanup_in_class:
576 cls.class_resources.insert(0, resource)
577 else:
578 cls.method_resources.insert(0, resource)
lkuchlanf7fc5b62021-01-26 14:53:43 +0200579 waiters.wait_for_resource_status(client, snapshot["id"], "available",
580 resource_name='snapshot')
Marc Koderer0abc93b2015-07-15 09:18:35 +0200581 return snapshot
582
583 @classmethod
Andrew Kerrb8436922016-06-01 15:32:43 -0400584 def create_share_group_snapshot_wait_for_active(
585 cls, share_group_id, name=None, description=None, client=None,
586 cleanup_in_class=True, **kwargs):
Clinton Knighte5c8f092015-08-27 15:00:23 -0400587 client = client or cls.shares_v2_client
Andrew Kerrbf31e912015-07-29 10:39:38 -0400588 if description is None:
Andrew Kerrb8436922016-06-01 15:32:43 -0400589 description = "Tempest's share group snapshot"
590 sg_snapshot = client.create_share_group_snapshot(
591 share_group_id, name=name, description=description, **kwargs)
Andrew Kerrbf31e912015-07-29 10:39:38 -0400592 resource = {
Andrew Kerrb8436922016-06-01 15:32:43 -0400593 "type": "share_group_snapshot",
594 "id": sg_snapshot["id"],
Andrew Kerrbf31e912015-07-29 10:39:38 -0400595 "client": client,
596 }
597 if cleanup_in_class:
598 cls.class_resources.insert(0, resource)
599 else:
600 cls.method_resources.insert(0, resource)
lkuchlanf7fc5b62021-01-26 14:53:43 +0200601 waiters.wait_for_resource_status(
602 client, sg_snapshot["id"], "available",
603 resource_name="share_group_snapshot")
Andrew Kerrb8436922016-06-01 15:32:43 -0400604 return sg_snapshot
Andrew Kerrbf31e912015-07-29 10:39:38 -0400605
606 @classmethod
Goutham Pacha Ravi839c98b2019-01-14 23:16:23 -0800607 def get_availability_zones(cls, client=None, backends=None):
Yogeshbdb88102015-09-29 23:41:02 -0400608 """List the availability zones for "manila-share" services
609
610 that are currently in "up" state.
611 """
Goutham Pacha Ravi839c98b2019-01-14 23:16:23 -0800612 client = client or cls.admin_shares_v2_client
613 backends = (
614 '|'.join(['^%s$' % backend for backend in backends])
615 if backends else '.*'
616 )
Yogeshbdb88102015-09-29 23:41:02 -0400617 cls.services = client.list_services()
618 zones = [service['zone'] for service in cls.services if
Goutham Pacha Ravi839c98b2019-01-14 23:16:23 -0800619 service['binary'] == 'manila-share' and
620 service['state'] == 'up' and
621 re.search(backends, service['host'])]
Douglas Viroel161f1802020-04-25 17:18:14 -0300622 return list(set(zones))
Yogeshbdb88102015-09-29 23:41:02 -0400623
Goutham Pacha Ravi839c98b2019-01-14 23:16:23 -0800624 @classmethod
625 def get_pools_matching_share_type(cls, share_type, client=None):
626 client = client or cls.admin_shares_v2_client
627 if utils.is_microversion_supported('2.23'):
628 return client.list_pools(
andrebeltrami3b4d4852020-02-04 19:11:54 +0000629 detail=True,
Goutham Pacha Ravi839c98b2019-01-14 23:16:23 -0800630 search_opts={'share_type': share_type['id']})['pools']
631
632 pools = client.list_pools(detail=True)['pools']
633 share_type = client.get_share_type(share_type['id'])['share_type']
634 extra_specs = {}
635 for k, v in share_type['extra_specs'].items():
636 extra_specs[k] = (
637 True if six.text_type(v).lower() == 'true'
638 else False if six.text_type(v).lower() == 'false' else v
639 )
640 return [
641 pool for pool in pools if all(y in pool['capabilities'].items()
642 for y in extra_specs.items())
643 ]
644
645 @classmethod
646 def get_availability_zones_matching_share_type(cls, share_type,
647 client=None):
648
649 client = client or cls.admin_shares_v2_client
650 pools_matching_share_type = cls.get_pools_matching_share_type(
651 share_type, client=client)
652 backends_matching_share_type = set(
653 [pool['name'].split("#")[0] for pool in pools_matching_share_type]
654 )
655 azs = cls.get_availability_zones(backends=backends_matching_share_type)
656 return azs
657
Yogesh1f931ff2015-09-29 23:41:02 -0400658 def get_pools_for_replication_domain(self):
659 # Get the list of pools for the replication domain
660 pools = self.admin_client.list_pools(detail=True)['pools']
Ben Swartzlander7150c652017-02-13 22:31:18 -0500661 instance_host = self.admin_client.get_share(
662 self.shares[0]['id'])['host']
Yogesh1f931ff2015-09-29 23:41:02 -0400663 host_pool = [p for p in pools if p['name'] == instance_host][0]
664 rep_domain = host_pool['capabilities']['replication_domain']
665 pools_in_rep_domain = [p for p in pools if p['capabilities'][
666 'replication_domain'] == rep_domain]
667 return rep_domain, pools_in_rep_domain
668
Yogeshbdb88102015-09-29 23:41:02 -0400669 @classmethod
debeltrami0d523bb2020-08-20 12:48:49 +0000670 def create_share_replica(cls, share_id, availability_zone=None,
671 client=None, cleanup_in_class=False,
672 cleanup=True,
silvacarlossd354d672020-08-23 18:49:52 +0000673 version=CONF.share.max_api_microversion):
Yogeshbdb88102015-09-29 23:41:02 -0400674 client = client or cls.shares_v2_client
Douglas Viroelbd4e78c2019-09-02 17:16:30 -0300675 replica = client.create_share_replica(
silvacarlossd354d672020-08-23 18:49:52 +0000676 share_id, availability_zone=availability_zone, version=version)
Yogeshbdb88102015-09-29 23:41:02 -0400677 resource = {
678 "type": "share_replica",
679 "id": replica["id"],
680 "client": client,
681 "share_id": share_id,
682 }
683 # NOTE(Yogi1): Cleanup needs to be disabled during promotion tests.
684 if cleanup:
685 if cleanup_in_class:
686 cls.class_resources.insert(0, resource)
687 else:
688 cls.method_resources.insert(0, resource)
lkuchlanf7fc5b62021-01-26 14:53:43 +0200689 waiters.wait_for_resource_status(
690 client, replica["id"], constants.STATUS_AVAILABLE,
691 resource_name='share_replica')
Yogeshbdb88102015-09-29 23:41:02 -0400692 return replica
693
694 @classmethod
silvacarlossd354d672020-08-23 18:49:52 +0000695 def delete_share_replica(cls, replica_id, client=None,
696 version=CONF.share.max_api_microversion):
Yogeshbdb88102015-09-29 23:41:02 -0400697 client = client or cls.shares_v2_client
Yogesh1f931ff2015-09-29 23:41:02 -0400698 try:
silvacarlossd354d672020-08-23 18:49:52 +0000699 client.delete_share_replica(replica_id, version=version)
Yogesh1f931ff2015-09-29 23:41:02 -0400700 client.wait_for_resource_deletion(replica_id=replica_id)
701 except exceptions.NotFound:
702 pass
Yogeshbdb88102015-09-29 23:41:02 -0400703
704 @classmethod
silvacarlossd354d672020-08-23 18:49:52 +0000705 def promote_share_replica(cls, replica_id, client=None,
706 version=CONF.share.max_api_microversion):
Yogeshbdb88102015-09-29 23:41:02 -0400707 client = client or cls.shares_v2_client
silvacarlossd354d672020-08-23 18:49:52 +0000708 replica = client.promote_share_replica(replica_id, version=version)
lkuchlanf7fc5b62021-01-26 14:53:43 +0200709 waiters.wait_for_resource_status(
lkuchlan540e74a2021-01-19 18:08:25 +0200710 client, replica["id"], constants.REPLICATION_STATE_ACTIVE,
lkuchlanf7fc5b62021-01-26 14:53:43 +0200711 resource_name='share_replica', status_attr="replica_state")
Yogeshbdb88102015-09-29 23:41:02 -0400712 return replica
713
Goutham Pacha Ravi1727f7a2020-05-22 13:41:40 -0700714 @classmethod
715 def _get_access_rule_data_from_config(cls):
yogeshdb32f462016-09-28 15:09:50 -0400716 """Get the first available access type/to combination from config.
717
718 This method opportunistically picks the first configured protocol
719 to create the share. Do not use this method in tests where you need
720 to test depth and breadth in the access types and access recipients.
721 """
Goutham Pacha Ravi1727f7a2020-05-22 13:41:40 -0700722 protocol = cls.shares_v2_client.share_protocol
yogeshdb32f462016-09-28 15:09:50 -0400723
724 if protocol in CONF.share.enable_ip_rules_for_protocols:
725 access_type = "ip"
726 access_to = utils.rand_ip()
727 elif protocol in CONF.share.enable_user_rules_for_protocols:
728 access_type = "user"
729 access_to = CONF.share.username_for_user_rules
730 elif protocol in CONF.share.enable_cert_rules_for_protocols:
731 access_type = "cert"
732 access_to = "client3.com"
733 elif protocol in CONF.share.enable_cephx_rules_for_protocols:
734 access_type = "cephx"
lkuchlan5af7cb42020-07-14 18:05:09 +0300735 access_to = data_utils.rand_name(
736 cls.__class__.__name__ + '-cephx-id')
yogeshdb32f462016-09-28 15:09:50 -0400737 else:
738 message = "Unrecognized protocol and access rules configuration."
Goutham Pacha Ravi1727f7a2020-05-22 13:41:40 -0700739 raise cls.skipException(message)
yogeshdb32f462016-09-28 15:09:50 -0400740
741 return access_type, access_to
742
Yogeshbdb88102015-09-29 23:41:02 -0400743 @classmethod
Marc Koderer0abc93b2015-07-15 09:18:35 +0200744 def create_share_network(cls, client=None,
debeltrami1753a592020-05-11 18:27:30 +0000745 cleanup_in_class=False,
746 add_security_services=True, **kwargs):
747
Marc Koderer0abc93b2015-07-15 09:18:35 +0200748 if client is None:
749 client = cls.shares_client
750 share_network = client.create_share_network(**kwargs)
751 resource = {
752 "type": "share_network",
753 "id": share_network["id"],
754 "client": client,
755 }
debeltrami1753a592020-05-11 18:27:30 +0000756
Marc Koderer0abc93b2015-07-15 09:18:35 +0200757 if cleanup_in_class:
758 cls.class_resources.insert(0, resource)
759 else:
760 cls.method_resources.insert(0, resource)
debeltrami1753a592020-05-11 18:27:30 +0000761
762 if add_security_services:
763 cls.provide_and_associate_security_services(
764 client, share_network["id"], cleanup_in_class=cleanup_in_class)
765
Marc Koderer0abc93b2015-07-15 09:18:35 +0200766 return share_network
767
768 @classmethod
debeltrami1753a592020-05-11 18:27:30 +0000769 def create_share_network_subnet(cls,
770 client=None,
771 cleanup_in_class=False,
772 **kwargs):
Douglas Viroelb7e27e72019-08-06 19:40:37 -0300773 if client is None:
774 client = cls.shares_v2_client
775 share_network_subnet = client.create_subnet(**kwargs)
776 resource = {
777 "type": "share-network-subnet",
778 "id": share_network_subnet["id"],
779 "extra_params": {
780 "share_network_id": share_network_subnet["share_network_id"]
781 },
782 "client": client,
783 }
784 if cleanup_in_class:
785 cls.class_resources.insert(0, resource)
786 else:
787 cls.method_resources.insert(0, resource)
788 return share_network_subnet
789
790 @classmethod
Marc Koderer0abc93b2015-07-15 09:18:35 +0200791 def create_security_service(cls, ss_type="ldap", client=None,
792 cleanup_in_class=False, **kwargs):
793 if client is None:
794 client = cls.shares_client
795 security_service = client.create_security_service(ss_type, **kwargs)
796 resource = {
797 "type": "security_service",
798 "id": security_service["id"],
799 "client": client,
800 }
801 if cleanup_in_class:
802 cls.class_resources.insert(0, resource)
803 else:
804 cls.method_resources.insert(0, resource)
805 return security_service
806
807 @classmethod
808 def create_share_type(cls, name, is_public=True, client=None,
809 cleanup_in_class=True, **kwargs):
810 if client is None:
Valeriy Ponomaryova14c2252015-10-29 13:34:32 +0200811 client = cls.shares_v2_client
Marc Koderer0abc93b2015-07-15 09:18:35 +0200812 share_type = client.create_share_type(name, is_public, **kwargs)
813 resource = {
814 "type": "share_type",
815 "id": share_type["share_type"]["id"],
816 "client": client,
817 }
818 if cleanup_in_class:
819 cls.class_resources.insert(0, resource)
820 else:
821 cls.method_resources.insert(0, resource)
822 return share_type
823
haixin0d1d29f2019-08-02 16:50:45 +0800824 @classmethod
825 def update_share_type(cls, share_type_id, name=None,
826 is_public=None, description=None,
827 client=None):
828 if client is None:
829 client = cls.shares_v2_client
830 share_type = client.update_share_type(share_type_id, name,
831 is_public, description)
832 return share_type
833
Goutham Pacha Raviaf448262020-06-29 14:24:13 -0700834 @classmethod
835 def update_quotas(cls, project_id, user_id=None, cleanup=True,
836 client=None, **kwargs):
837 client = client or cls.shares_v2_client
838 updated_quotas = client.update_quotas(project_id,
839 user_id=user_id,
840 **kwargs)
841 resource = {
842 "type": "quotas",
843 "id": project_id,
844 "client": client,
845 "user_id": user_id,
846 }
847 if cleanup:
848 cls.method_resources.insert(0, resource)
849 return updated_quotas
850
Marc Koderer0abc93b2015-07-15 09:18:35 +0200851 @staticmethod
Clinton Knight4699a8c2016-08-16 22:36:13 -0400852 def add_extra_specs_to_dict(extra_specs=None):
853 """Add any required extra-specs to share type dictionary"""
Valeriy Ponomaryovad55dc52015-09-23 13:54:00 +0300854 dhss = six.text_type(CONF.share.multitenancy_enabled)
855 snapshot_support = six.text_type(
856 CONF.share.capability_snapshot_support)
Clinton Knight4699a8c2016-08-16 22:36:13 -0400857 create_from_snapshot_support = six.text_type(
858 CONF.share.capability_create_share_from_snapshot_support)
859
860 extra_specs_dict = {
Valeriy Ponomaryovad55dc52015-09-23 13:54:00 +0300861 "driver_handles_share_servers": dhss,
Marc Koderer0abc93b2015-07-15 09:18:35 +0200862 }
Clinton Knight4699a8c2016-08-16 22:36:13 -0400863
864 optional = {
865 "snapshot_support": snapshot_support,
866 "create_share_from_snapshot_support": create_from_snapshot_support,
867 }
868 # NOTE(gouthamr): In micro-versions < 2.24, snapshot_support is a
869 # required extra-spec
870 extra_specs_dict.update(optional)
871
Marc Koderer0abc93b2015-07-15 09:18:35 +0200872 if extra_specs:
Clinton Knight4699a8c2016-08-16 22:36:13 -0400873 extra_specs_dict.update(extra_specs)
874
875 return extra_specs_dict
Marc Koderer0abc93b2015-07-15 09:18:35 +0200876
877 @classmethod
Yogesh1f931ff2015-09-29 23:41:02 -0400878 def clear_share_replicas(cls, share_id, client=None):
879 client = client or cls.shares_v2_client
880 share_replicas = client.list_share_replicas(
881 share_id=share_id)
882
883 for replica in share_replicas:
884 try:
885 cls.delete_share_replica(replica['id'])
886 except exceptions.BadRequest:
887 # Ignore the exception due to deletion of last active replica
888 pass
889
890 @classmethod
Marc Koderer0abc93b2015-07-15 09:18:35 +0200891 def clear_resources(cls, resources=None):
892 """Deletes resources, that were created in test suites.
893
894 This method tries to remove resources from resource list,
895 if it is not found, assumed it was deleted in test itself.
896 It is expected, that all resources were added as LIFO
897 due to restriction of deletion resources, that is in the chain.
898
899 :param resources: dict with keys 'type','id','client' and 'deleted'
900 """
Marc Koderer0abc93b2015-07-15 09:18:35 +0200901 if resources is None:
902 resources = cls.method_resources
903 for res in resources:
904 if "deleted" not in res.keys():
905 res["deleted"] = False
906 if "client" not in res.keys():
907 res["client"] = cls.shares_client
908 if not(res["deleted"]):
909 res_id = res['id']
910 client = res["client"]
911 with handle_cleanup_exceptions():
Andreas Jaeger0cb685b2020-04-01 13:38:38 +0200912 if res["type"] == "share":
Yogesh1f931ff2015-09-29 23:41:02 -0400913 cls.clear_share_replicas(res_id)
Andrew Kerrb8436922016-06-01 15:32:43 -0400914 share_group_id = res.get('share_group_id')
915 if share_group_id:
916 params = {'share_group_id': share_group_id}
Clinton Knighte5c8f092015-08-27 15:00:23 -0400917 client.delete_share(res_id, params=params)
918 else:
919 client.delete_share(res_id)
Marc Koderer0abc93b2015-07-15 09:18:35 +0200920 client.wait_for_resource_deletion(share_id=res_id)
Andreas Jaeger0cb685b2020-04-01 13:38:38 +0200921 elif res["type"] == "snapshot":
Marc Koderer0abc93b2015-07-15 09:18:35 +0200922 client.delete_snapshot(res_id)
923 client.wait_for_resource_deletion(snapshot_id=res_id)
Andreas Jaeger0cb685b2020-04-01 13:38:38 +0200924 elif (res["type"] == "share_network" and
yogesh06f519f2017-06-26 13:16:12 -0400925 res_id != CONF.share.share_network_id):
Victoria Martinez de la Cruzcad92012018-06-08 14:46:35 -0400926 client.delete_share_network(res_id)
927 client.wait_for_resource_deletion(sn_id=res_id)
debeltrami1753a592020-05-11 18:27:30 +0000928 elif res["type"] == "dissociate_security_service":
929 sn_id = res["extra_params"]["share_network_id"]
930 client.remove_sec_service_from_share_network(
931 sn_id=sn_id, ss_id=res_id
932 )
Andreas Jaeger0cb685b2020-04-01 13:38:38 +0200933 elif res["type"] == "security_service":
Marc Koderer0abc93b2015-07-15 09:18:35 +0200934 client.delete_security_service(res_id)
935 client.wait_for_resource_deletion(ss_id=res_id)
Andreas Jaeger0cb685b2020-04-01 13:38:38 +0200936 elif res["type"] == "share_type":
Marc Koderer0abc93b2015-07-15 09:18:35 +0200937 client.delete_share_type(res_id)
938 client.wait_for_resource_deletion(st_id=res_id)
Andreas Jaeger0cb685b2020-04-01 13:38:38 +0200939 elif res["type"] == "share_group":
Andrew Kerrb8436922016-06-01 15:32:43 -0400940 client.delete_share_group(res_id)
941 client.wait_for_resource_deletion(
942 share_group_id=res_id)
Andreas Jaeger0cb685b2020-04-01 13:38:38 +0200943 elif res["type"] == "share_group_type":
Andrew Kerrb8436922016-06-01 15:32:43 -0400944 client.delete_share_group_type(res_id)
945 client.wait_for_resource_deletion(
946 share_group_type_id=res_id)
Andreas Jaeger0cb685b2020-04-01 13:38:38 +0200947 elif res["type"] == "share_group_snapshot":
Andrew Kerrb8436922016-06-01 15:32:43 -0400948 client.delete_share_group_snapshot(res_id)
949 client.wait_for_resource_deletion(
950 share_group_snapshot_id=res_id)
Andreas Jaeger0cb685b2020-04-01 13:38:38 +0200951 elif res["type"] == "share_replica":
Yogeshbdb88102015-09-29 23:41:02 -0400952 client.delete_share_replica(res_id)
953 client.wait_for_resource_deletion(replica_id=res_id)
Andreas Jaeger0cb685b2020-04-01 13:38:38 +0200954 elif res["type"] == "share_network_subnet":
Douglas Viroelb7e27e72019-08-06 19:40:37 -0300955 sn_id = res["extra_params"]["share_network_id"]
956 client.delete_subnet(sn_id, res_id)
957 client.wait_for_resource_deletion(
958 share_network_subnet_id=res_id,
959 sn_id=sn_id)
Goutham Pacha Raviaf448262020-06-29 14:24:13 -0700960 elif res["type"] == "quotas":
961 user_id = res.get('user_id')
962 client.reset_quotas(res_id, user_id=user_id)
Marc Koderer0abc93b2015-07-15 09:18:35 +0200963 else:
huayue97bacbf2016-01-04 09:57:39 +0800964 LOG.warning("Provided unsupported resource type for "
junbolib236c242017-07-18 18:12:37 +0800965 "cleanup '%s'. Skipping.", res["type"])
Marc Koderer0abc93b2015-07-15 09:18:35 +0200966 res["deleted"] = True
967
968 @classmethod
969 def generate_share_network_data(self):
970 data = {
971 "name": data_utils.rand_name("sn-name"),
972 "description": data_utils.rand_name("sn-desc"),
973 "neutron_net_id": data_utils.rand_name("net-id"),
974 "neutron_subnet_id": data_utils.rand_name("subnet-id"),
975 }
976 return data
977
978 @classmethod
Douglas Viroelb7e27e72019-08-06 19:40:37 -0300979 def generate_subnet_data(self):
980 data = {
981 "neutron_net_id": data_utils.rand_name("net-id"),
982 "neutron_subnet_id": data_utils.rand_name("subnet-id"),
983 }
984 return data
985
986 @classmethod
Maurice Schreiber5ac37172018-02-01 15:17:31 +0100987 def generate_security_service_data(self, set_ou=False):
Marc Koderer0abc93b2015-07-15 09:18:35 +0200988 data = {
989 "name": data_utils.rand_name("ss-name"),
990 "description": data_utils.rand_name("ss-desc"),
Valeriy Ponomaryovfcde7712015-12-14 18:06:13 +0200991 "dns_ip": utils.rand_ip(),
992 "server": utils.rand_ip(),
Marc Koderer0abc93b2015-07-15 09:18:35 +0200993 "domain": data_utils.rand_name("ss-domain"),
994 "user": data_utils.rand_name("ss-user"),
995 "password": data_utils.rand_name("ss-password"),
996 }
Maurice Schreiber5ac37172018-02-01 15:17:31 +0100997 if set_ou:
998 data["ou"] = data_utils.rand_name("ss-ou")
999
Marc Koderer0abc93b2015-07-15 09:18:35 +02001000 return data
1001
1002 # Useful assertions
1003 def assertDictMatch(self, d1, d2, approx_equal=False, tolerance=0.001):
1004 """Assert two dicts are equivalent.
1005
1006 This is a 'deep' match in the sense that it handles nested
1007 dictionaries appropriately.
1008
1009 NOTE:
1010
1011 If you don't care (or don't know) a given value, you can specify
1012 the string DONTCARE as the value. This will cause that dict-item
1013 to be skipped.
1014
1015 """
1016 def raise_assertion(msg):
1017 d1str = str(d1)
1018 d2str = str(d2)
1019 base_msg = ('Dictionaries do not match. %(msg)s d1: %(d1str)s '
1020 'd2: %(d2str)s' %
1021 {"msg": msg, "d1str": d1str, "d2str": d2str})
1022 raise AssertionError(base_msg)
1023
1024 d1keys = set(d1.keys())
1025 d2keys = set(d2.keys())
1026 if d1keys != d2keys:
1027 d1only = d1keys - d2keys
1028 d2only = d2keys - d1keys
1029 raise_assertion('Keys in d1 and not d2: %(d1only)s. '
1030 'Keys in d2 and not d1: %(d2only)s' %
1031 {"d1only": d1only, "d2only": d2only})
1032
1033 for key in d1keys:
1034 d1value = d1[key]
1035 d2value = d2[key]
1036 try:
1037 error = abs(float(d1value) - float(d2value))
1038 within_tolerance = error <= tolerance
1039 except (ValueError, TypeError):
daiki kato6914b1a2016-03-16 17:16:57 +09001040 # If both values aren't convertible to float, just ignore
Marc Koderer0abc93b2015-07-15 09:18:35 +02001041 # ValueError if arg is a str, TypeError if it's something else
1042 # (like None)
1043 within_tolerance = False
1044
1045 if hasattr(d1value, 'keys') and hasattr(d2value, 'keys'):
1046 self.assertDictMatch(d1value, d2value)
1047 elif 'DONTCARE' in (d1value, d2value):
1048 continue
1049 elif approx_equal and within_tolerance:
1050 continue
1051 elif d1value != d2value:
1052 raise_assertion("d1['%(key)s']=%(d1value)s != "
1053 "d2['%(key)s']=%(d2value)s" %
1054 {
1055 "key": key,
1056 "d1value": d1value,
1057 "d2value": d2value
1058 })
1059
Alex Meadeba8a1602016-05-06 09:33:09 -04001060 def create_user_message(self):
1061 """Trigger a 'no valid host' situation to generate a message."""
1062 extra_specs = {
1063 'vendor_name': 'foobar',
1064 'driver_handles_share_servers': CONF.share.multitenancy_enabled,
1065 }
1066 share_type_name = data_utils.rand_name("share-type")
1067
1068 bogus_type = self.create_share_type(
Goutham Pacha Raviaf448262020-06-29 14:24:13 -07001069 client=self.admin_shares_v2_client,
Alex Meadeba8a1602016-05-06 09:33:09 -04001070 name=share_type_name,
1071 extra_specs=extra_specs)['share_type']
1072
1073 params = {'share_type_id': bogus_type['id'],
1074 'share_network_id': self.shares_v2_client.share_network_id}
1075 share = self.shares_v2_client.create_share(**params)
1076 self.addCleanup(self.shares_v2_client.delete_share, share['id'])
lkuchlanf7fc5b62021-01-26 14:53:43 +02001077 waiters.wait_for_resource_status(
lkuchlan540e74a2021-01-19 18:08:25 +02001078 self.shares_v2_client, share['id'], "error")
1079 return waiters.wait_for_message(self.shares_v2_client, share['id'])
Alex Meadeba8a1602016-05-06 09:33:09 -04001080
lkuchlan5af7cb42020-07-14 18:05:09 +03001081 def allow_access(self, share_id, client=None, access_type=None,
1082 access_level='rw', access_to=None, status='active',
1083 raise_rule_in_error_state=True, cleanup=True):
1084
1085 client = client or self.shares_v2_client
1086 a_type, a_to = self._get_access_rule_data_from_config()
1087 access_type = access_type or a_type
1088 access_to = access_to or a_to
1089
1090 rule = client.create_access_rule(share_id, access_type, access_to,
1091 access_level)
lkuchlanf7fc5b62021-01-26 14:53:43 +02001092 waiters.wait_for_resource_status(
1093 client, share_id, status, resource_name='access_rule',
1094 rule_id=rule['id'],
1095 raise_rule_in_error_state=raise_rule_in_error_state)
lkuchlan5af7cb42020-07-14 18:05:09 +03001096 if cleanup:
1097 self.addCleanup(client.wait_for_resource_deletion,
1098 rule_id=rule['id'], share_id=share_id)
1099 self.addCleanup(client.delete_access_rule, share_id, rule['id'])
1100 return rule
1101
Marc Koderer0abc93b2015-07-15 09:18:35 +02001102
Marc Koderer0abc93b2015-07-15 09:18:35 +02001103class BaseSharesAdminTest(BaseSharesTest):
1104 """Base test case class for all Shares Admin API tests."""
Valeriy Ponomaryov39cdf722016-05-30 18:16:15 +03001105 credentials = ('admin', )
1106
Victoria Martinez de la Cruzf6bc6fa2018-02-01 11:27:00 -05001107 @classmethod
1108 def setup_clients(cls):
1109 super(BaseSharesAdminTest, cls).setup_clients()
1110 # Initialise share clients
1111 cls.admin_shares_v2_client = cls.os_admin.share_v2.SharesV2Client()
1112
1113 @classmethod
Goutham Pacha Raviaf448262020-06-29 14:24:13 -07001114 def _create_share_type(cls, is_public=True, specs=None):
Victoria Martinez de la Cruzf6bc6fa2018-02-01 11:27:00 -05001115 name = data_utils.rand_name("unique_st_name")
1116 extra_specs = cls.add_extra_specs_to_dict(specs)
1117 return cls.create_share_type(
Goutham Pacha Raviaf448262020-06-29 14:24:13 -07001118 name, extra_specs=extra_specs, is_public=is_public,
Victoria Martinez de la Cruzf6bc6fa2018-02-01 11:27:00 -05001119 client=cls.admin_shares_v2_client)['share_type']
1120
1121 @classmethod
1122 def _create_share_group_type(cls):
1123 share_group_type_name = data_utils.rand_name("unique_sgtype_name")
1124 return cls.create_share_group_type(
1125 name=share_group_type_name, share_types=[cls.share_type_id],
1126 client=cls.admin_shares_v2_client)
1127
Lucio Seki37056942019-01-24 15:40:20 -02001128 def _create_share_for_manage(self):
1129 creation_data = {
1130 'share_type_id': self.st['share_type']['id'],
1131 'share_protocol': self.protocol,
1132 }
1133
1134 share = self.create_share(**creation_data)
1135 share = self.shares_v2_client.get_share(share['id'])
1136
1137 if utils.is_microversion_ge(CONF.share.max_api_microversion, "2.9"):
1138 el = self.shares_v2_client.list_share_export_locations(share["id"])
1139 share["export_locations"] = el
1140
1141 return share
1142
1143 def _unmanage_share_and_wait(self, share):
1144 self.shares_v2_client.unmanage_share(share['id'])
1145 self.shares_v2_client.wait_for_resource_deletion(share_id=share['id'])
1146
1147 def _reset_state_and_delete_share(self, share):
1148 self.shares_v2_client.reset_state(share['id'])
1149 self._delete_share_and_wait(share)
1150
1151 def _delete_snapshot_and_wait(self, snap):
1152 self.shares_v2_client.delete_snapshot(snap['id'])
1153 self.shares_v2_client.wait_for_resource_deletion(
1154 snapshot_id=snap['id']
1155 )
1156 self.assertRaises(exceptions.NotFound,
1157 self.shares_v2_client.get_snapshot,
1158 snap['id'])
1159
1160 def _delete_share_and_wait(self, share):
1161 self.shares_v2_client.delete_share(share['id'])
1162 self.shares_v2_client.wait_for_resource_deletion(share_id=share['id'])
1163 self.assertRaises(exceptions.NotFound,
1164 self.shares_v2_client.get_share,
1165 share['id'])
1166
1167 def _manage_share(self, share, name, description, share_server_id):
1168 managed_share = self.shares_v2_client.manage_share(
1169 service_host=share['host'],
1170 export_path=share['export_locations'][0],
1171 protocol=share['share_proto'],
1172 share_type_id=self.share_type['share_type']['id'],
1173 name=name,
1174 description=description,
1175 share_server_id=share_server_id
1176 )
lkuchlanf7fc5b62021-01-26 14:53:43 +02001177 waiters.wait_for_resource_status(
lkuchlan540e74a2021-01-19 18:08:25 +02001178 self.shares_v2_client, managed_share['id'],
1179 constants.STATUS_AVAILABLE
Lucio Seki37056942019-01-24 15:40:20 -02001180 )
1181
1182 return managed_share
1183
1184 def _unmanage_share_server_and_wait(self, server):
1185 self.shares_v2_client.unmanage_share_server(server['id'])
1186 self.shares_v2_client.wait_for_resource_deletion(
1187 server_id=server['id']
1188 )
1189
1190 def _manage_share_server(self, share_server, fields=None):
1191 params = fields or {}
Douglas Viroelb7e27e72019-08-06 19:40:37 -03001192 subnet_id = params.get('share_network_subnet_id', None)
Lucio Seki37056942019-01-24 15:40:20 -02001193 managed_share_server = self.shares_v2_client.manage_share_server(
1194 params.get('host', share_server['host']),
1195 params.get('share_network_id', share_server['share_network_id']),
1196 params.get('identifier', share_server['identifier']),
Douglas Viroelb7e27e72019-08-06 19:40:37 -03001197 share_network_subnet_id=subnet_id,
Lucio Seki37056942019-01-24 15:40:20 -02001198 )
lkuchlanf7fc5b62021-01-26 14:53:43 +02001199 waiters.wait_for_resource_status(
lkuchlan540e74a2021-01-19 18:08:25 +02001200 self.shares_v2_client, managed_share_server['id'],
lkuchlanf7fc5b62021-01-26 14:53:43 +02001201 constants.SERVER_STATE_ACTIVE, resource_name='share_server'
Lucio Seki37056942019-01-24 15:40:20 -02001202 )
1203
1204 return managed_share_server
1205
1206 def _delete_share_server_and_wait(self, share_server_id):
1207 self.shares_v2_client.delete_share_server(
1208 share_server_id
1209 )
1210 self.shares_v2_client.wait_for_resource_deletion(
1211 server_id=share_server_id)
1212
Valeriy Ponomaryov39cdf722016-05-30 18:16:15 +03001213
1214class BaseSharesMixedTest(BaseSharesTest):
1215 """Base test case class for all Shares API tests with all user roles."""
1216 credentials = ('primary', 'alt', 'admin')
Marc Koderer0abc93b2015-07-15 09:18:35 +02001217
Goutham Pacha Ravic678e212020-03-20 11:13:47 -07001218 # Will be cleaned up in resource_cleanup if the class
1219 class_project_users_created = []
1220
1221 @classmethod
1222 def resource_cleanup(cls):
1223 cls.clear_project_users(cls.class_project_users_created)
1224 super(BaseSharesMixedTest, cls).resource_cleanup()
1225
1226 @classmethod
1227 def clear_project_users(cls, users=None):
1228 users = users or cls.class_project_users_created
1229 for user in users:
1230 with handle_cleanup_exceptions():
1231 cls.os_admin.creds_client.delete_user(user['id'])
1232
Marc Koderer0abc93b2015-07-15 09:18:35 +02001233 @classmethod
Valeriy Ponomaryov39cdf722016-05-30 18:16:15 +03001234 def setup_clients(cls):
1235 super(BaseSharesMixedTest, cls).setup_clients()
Andrea Frittoli (andreaf)369391a2016-06-27 18:59:13 +01001236 # Initialise share clients
1237 cls.admin_shares_client = cls.os_admin.share_v1.SharesClient()
1238 cls.admin_shares_v2_client = cls.os_admin.share_v2.SharesV2Client()
1239 cls.alt_shares_client = cls.os_alt.share_v1.SharesClient()
1240 cls.alt_shares_v2_client = cls.os_alt.share_v2.SharesV2Client()
1241 # Initialise network clients
1242 cls.os_admin.networks_client = cls.os_admin.network.NetworksClient()
1243 cls.os_alt.networks_client = cls.os_alt.network.NetworksClient()
Goutham Pacha Ravic678e212020-03-20 11:13:47 -07001244 # Initialise identity clients
1245 cls.admin_project = cls.os_admin.auth_provider.auth_data[1]['project']
1246 identity_clients = getattr(
1247 cls.os_admin, 'identity_%s' % CONF.identity.auth_version)
1248 cls.os_admin.identity_client = identity_clients.IdentityClient()
1249 cls.os_admin.projects_client = identity_clients.ProjectsClient()
1250 cls.os_admin.users_client = identity_clients.UsersClient()
1251 cls.os_admin.roles_client = identity_clients.RolesClient()
1252 cls.os_admin.domains_client = (
1253 cls.os_admin.identity_v3.DomainsClient() if
1254 CONF.identity.auth_version == 'v3' else None)
Goutham Pacha Ravi10d49492021-02-23 16:05:21 -08001255 cls.admin_project_member_client = cls.create_user_and_get_client(
1256 project=cls.admin_project, add_member_role=True)
Valeriy Ponomaryov39cdf722016-05-30 18:16:15 +03001257
1258 if CONF.share.multitenancy_enabled:
1259 admin_share_network_id = cls.provide_share_network(
1260 cls.admin_shares_v2_client, cls.os_admin.networks_client)
1261 cls.admin_shares_client.share_network_id = admin_share_network_id
1262 cls.admin_shares_v2_client.share_network_id = (
1263 admin_share_network_id)
1264
1265 alt_share_network_id = cls.provide_share_network(
1266 cls.alt_shares_v2_client, cls.os_alt.networks_client)
1267 cls.alt_shares_client.share_network_id = alt_share_network_id
1268 cls.alt_shares_v2_client.share_network_id = alt_share_network_id
Victoria Martinez de la Cruzf6bc6fa2018-02-01 11:27:00 -05001269
1270 @classmethod
Goutham Pacha Ravi10d49492021-02-23 16:05:21 -08001271 def create_user_and_get_client(cls, project=None, add_member_role=True):
Goutham Pacha Ravic678e212020-03-20 11:13:47 -07001272 """Create a user in specified project & set share clients for user
1273
1274 The user will have all roles specified in tempest.conf
1275 :param: project: a dictionary with project ID and name, if not
1276 specified, the value will be cls.admin_project
1277 """
1278 project_domain_name = (
1279 cls.os_admin.identity_client.auth_provider.credentials.get(
1280 'project_domain_name', 'Default'))
1281 cls.os_admin.creds_client = cred_client.get_creds_client(
1282 cls.os_admin.identity_client, cls.os_admin.projects_client,
1283 cls.os_admin.users_client, cls.os_admin.roles_client,
1284 cls.os_admin.domains_client, project_domain_name)
1285
1286 # User info
1287 project = project or cls.admin_project
1288 username = data_utils.rand_name('manila_%s' % project['id'])
1289 password = data_utils.rand_password()
1290 email = '%s@example.org' % username
1291
1292 user = cls.os_admin.creds_client.create_user(
1293 username, password, project, email)
1294 cls.class_project_users_created.append(user)
1295
Goutham Pacha Ravi10d49492021-02-23 16:05:21 -08001296 tempest_roles_to_assign = CONF.auth.tempest_roles or []
1297 if "member" not in tempest_roles_to_assign and add_member_role:
1298 tempest_roles_to_assign.append("member")
1299
1300 for role in tempest_roles_to_assign:
1301 cls.os_admin.creds_client.assign_user_role(user, project, role)
Goutham Pacha Ravic678e212020-03-20 11:13:47 -07001302
1303 user_creds = cls.os_admin.creds_client.get_credentials(
1304 user, project, password)
1305 os = clients.Clients(user_creds)
1306 os.shares_v1_client = os.share_v1.SharesClient()
1307 os.shares_v2_client = os.share_v2.SharesV2Client()
1308 return os
1309
1310 @classmethod
Goutham Pacha Raviaf448262020-06-29 14:24:13 -07001311 def _create_share_type(cls, is_public=True, specs=None):
Victoria Martinez de la Cruzf6bc6fa2018-02-01 11:27:00 -05001312 name = data_utils.rand_name("unique_st_name")
1313 extra_specs = cls.add_extra_specs_to_dict(specs)
1314 return cls.create_share_type(
Goutham Pacha Raviaf448262020-06-29 14:24:13 -07001315 name, extra_specs=extra_specs, is_public=is_public,
Victoria Martinez de la Cruzf6bc6fa2018-02-01 11:27:00 -05001316 client=cls.admin_shares_v2_client)['share_type']
1317
1318 @classmethod
1319 def _create_share_group_type(cls):
1320 share_group_type_name = data_utils.rand_name("unique_sgtype_name")
1321 return cls.create_share_group_type(
1322 name=share_group_type_name, share_types=[cls.share_type_id],
1323 client=cls.admin_shares_v2_client)