blob: 51f723b106a25991a652fd63037208c5499ac519 [file] [log] [blame]
Matthew Treinishc791ac42014-07-16 09:15:23 -04001# Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
2#
3# Licensed under the Apache License, Version 2.0 (the "License"); you may
4# not use this file except in compliance with the License. You may obtain
5# a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12# License for the specific language governing permissions and limitations
13# under the License.
14
15import hashlib
16import os
Matthew Treinish96e9e882014-06-09 18:37:19 -040017
Doug Hellmann583ce2c2015-03-11 14:55:46 +000018from oslo_concurrency import lockutils
19from oslo_log import log as logging
Matthew Treinish1c517a22015-04-23 11:39:44 -040020import six
Matthew Treinishc791ac42014-07-16 09:15:23 -040021import yaml
22
Matthew Treinishf83f35c2015-04-10 11:59:11 -040023from tempest import clients
Matthew Treinishc791ac42014-07-16 09:15:23 -040024from tempest.common import cred_provider
Matthew Treinishf83f35c2015-04-10 11:59:11 -040025from tempest.common import fixed_network
Matthew Treinishc791ac42014-07-16 09:15:23 -040026from tempest import exceptions
Andrea Frittoli (andreaf)db9672e2016-02-23 14:07:24 -050027from tempest.lib import auth
28from tempest.lib import exceptions as lib_exc
Matthew Treinishc791ac42014-07-16 09:15:23 -040029
Matthew Treinishc791ac42014-07-16 09:15:23 -040030LOG = logging.getLogger(__name__)
31
32
33def read_accounts_yaml(path):
Matthew Treinishd89db1b2015-12-16 17:29:14 -050034 try:
35 with open(path, 'r') as yaml_file:
36 accounts = yaml.load(yaml_file)
37 except IOError:
38 raise exceptions.InvalidConfiguration(
39 'The path for the test accounts file: %s '
40 'could not be found' % path)
Matthew Treinishc791ac42014-07-16 09:15:23 -040041 return accounts
42
43
Andrea Frittoli (andreaf)f9e01262015-05-22 10:24:12 -070044class PreProvisionedCredentialProvider(cred_provider.CredentialProvider):
Matthew Treinishc791ac42014-07-16 09:15:23 -040045
Andrea Frittoli (andreaf)848e3482015-10-12 14:17:21 +010046 def __init__(self, identity_version, test_accounts_file,
47 accounts_lock_dir, name=None, credentials_domain=None,
48 admin_role=None, object_storage_operator_role=None,
49 object_storage_reseller_admin_role=None):
50 """Credentials provider using pre-provisioned accounts
51
52 This credentials provider loads the details of pre-provisioned
53 accounts from a YAML file, in the format specified by
54 `etc/accounts.yaml.sample`. It locks accounts while in use, using the
55 external locking mechanism, allowing for multiple python processes
56 to share a single account file, and thus running tests in parallel.
57
58 The accounts_lock_dir must be generated using `lockutils.get_lock_path`
59 from the oslo.concurrency library. For instance:
60
61 accounts_lock_dir = os.path.join(lockutils.get_lock_path(CONF),
62 'test_accounts')
63
64 Role names for object storage are optional as long as the
65 `operator` and `reseller_admin` credential types are not used in the
66 accounts file.
67
68 :param identity_version: identity version of the credentials
69 :param admin_role: name of the admin role
70 :param test_accounts_file: path to the accounts YAML file
71 :param accounts_lock_dir: the directory for external locking
72 :param name: name of the hash file (optional)
73 :param credentials_domain: name of the domain credentials belong to
74 (if no domain is configured)
75 :param object_storage_operator_role: name of the role
76 :param object_storage_reseller_admin_role: name of the role
77 """
Andrea Frittoli (andreaf)f9e01262015-05-22 10:24:12 -070078 super(PreProvisionedCredentialProvider, self).__init__(
Andrea Frittoli (andreaf)1eb04962015-10-09 14:48:06 +010079 identity_version=identity_version, name=name,
Andrea Frittoli (andreaf)848e3482015-10-12 14:17:21 +010080 admin_role=admin_role, credentials_domain=credentials_domain)
81 self.test_accounts_file = test_accounts_file
Matthew Treinishd89db1b2015-12-16 17:29:14 -050082 if test_accounts_file:
Andrea Frittoli (andreaf)848e3482015-10-12 14:17:21 +010083 accounts = read_accounts_yaml(self.test_accounts_file)
Matthew Treinishb19eeb82014-09-04 09:57:46 -040084 self.use_default_creds = False
85 else:
86 accounts = {}
87 self.use_default_creds = True
Andrea Frittoli (andreaf)848e3482015-10-12 14:17:21 +010088 self.hash_dict = self.get_hash_dict(
89 accounts, admin_role, object_storage_operator_role,
90 object_storage_reseller_admin_role)
91 self.accounts_dir = accounts_lock_dir
Andrea Frittoli (andreaf)17209bb2015-05-22 10:16:57 -070092 self._creds = {}
Matthew Treinishc791ac42014-07-16 09:15:23 -040093
94 @classmethod
Matthew Treinish976e8df2014-12-19 14:21:54 -050095 def _append_role(cls, role, account_hash, hash_dict):
96 if role in hash_dict['roles']:
97 hash_dict['roles'][role].append(account_hash)
98 else:
99 hash_dict['roles'][role] = [account_hash]
100 return hash_dict
101
102 @classmethod
Andrea Frittoli (andreaf)848e3482015-10-12 14:17:21 +0100103 def get_hash_dict(cls, accounts, admin_role,
104 object_storage_operator_role=None,
105 object_storage_reseller_admin_role=None):
Matthew Treinishf83f35c2015-04-10 11:59:11 -0400106 hash_dict = {'roles': {}, 'creds': {}, 'networks': {}}
Matthew Treinish976e8df2014-12-19 14:21:54 -0500107 # Loop over the accounts read from the yaml file
Matthew Treinishc791ac42014-07-16 09:15:23 -0400108 for account in accounts:
Matthew Treinish976e8df2014-12-19 14:21:54 -0500109 roles = []
110 types = []
Matthew Treinishf83f35c2015-04-10 11:59:11 -0400111 resources = []
Matthew Treinish976e8df2014-12-19 14:21:54 -0500112 if 'roles' in account:
113 roles = account.pop('roles')
114 if 'types' in account:
115 types = account.pop('types')
Matthew Treinishf83f35c2015-04-10 11:59:11 -0400116 if 'resources' in account:
117 resources = account.pop('resources')
Matthew Treinishc791ac42014-07-16 09:15:23 -0400118 temp_hash = hashlib.md5()
Matthew Treinish1c517a22015-04-23 11:39:44 -0400119 temp_hash.update(six.text_type(account).encode('utf-8'))
Matthew Treinish976e8df2014-12-19 14:21:54 -0500120 temp_hash_key = temp_hash.hexdigest()
121 hash_dict['creds'][temp_hash_key] = account
122 for role in roles:
123 hash_dict = cls._append_role(role, temp_hash_key,
124 hash_dict)
125 # If types are set for the account append the matching role
126 # subdict with the hash
127 for type in types:
128 if type == 'admin':
Andrea Frittoli (andreaf)29491a72015-10-13 11:24:17 +0100129 hash_dict = cls._append_role(admin_role, temp_hash_key,
130 hash_dict)
Matthew Treinish976e8df2014-12-19 14:21:54 -0500131 elif type == 'operator':
Andrea Frittoli (andreaf)848e3482015-10-12 14:17:21 +0100132 if object_storage_operator_role:
133 hash_dict = cls._append_role(
134 object_storage_operator_role, temp_hash_key,
135 hash_dict)
136 else:
137 msg = ("Type 'operator' configured, but no "
138 "object_storage_operator_role specified")
139 raise lib_exc.InvalidCredentials(msg)
Matthew Treinish976e8df2014-12-19 14:21:54 -0500140 elif type == 'reseller_admin':
Andrea Frittoli (andreaf)848e3482015-10-12 14:17:21 +0100141 if object_storage_reseller_admin_role:
142 hash_dict = cls._append_role(
143 object_storage_reseller_admin_role,
144 temp_hash_key,
145 hash_dict)
146 else:
147 msg = ("Type 'reseller_admin' configured, but no "
148 "object_storage_reseller_admin_role specified")
149 raise lib_exc.InvalidCredentials(msg)
Matthew Treinishf83f35c2015-04-10 11:59:11 -0400150 # Populate the network subdict
151 for resource in resources:
152 if resource == 'network':
153 hash_dict['networks'][temp_hash_key] = resources[resource]
154 else:
Zhao Lei647cc182015-09-24 17:47:02 +0800155 LOG.warning('Unknown resource type %s, ignoring this field'
Matthew Treinishf83f35c2015-04-10 11:59:11 -0400156 % resource)
Matthew Treinishc791ac42014-07-16 09:15:23 -0400157 return hash_dict
158
Matthew Treinish09f17832014-08-15 15:22:50 -0400159 def is_multi_user(self):
Andrea Frittoli8283b4e2014-07-17 13:28:58 +0100160 # Default credentials is not a valid option with locking Account
161 if self.use_default_creds:
Andrea Frittoli (andreaf)848e3482015-10-12 14:17:21 +0100162 raise lib_exc.InvalidCredentials(
163 "Account file %s doesn't exist" % self.test_accounts_file)
Andrea Frittoli8283b4e2014-07-17 13:28:58 +0100164 else:
Matthew Treinish976e8df2014-12-19 14:21:54 -0500165 return len(self.hash_dict['creds']) > 1
Matthew Treinish09f17832014-08-15 15:22:50 -0400166
Yair Fried76488d72014-10-21 10:13:19 +0300167 def is_multi_tenant(self):
168 return self.is_multi_user()
169
Matthew Treinish09f17832014-08-15 15:22:50 -0400170 def _create_hash_file(self, hash_string):
171 path = os.path.join(os.path.join(self.accounts_dir, hash_string))
Matthew Treinishc791ac42014-07-16 09:15:23 -0400172 if not os.path.isfile(path):
Matthew Treinish4041b262015-02-27 11:18:54 -0500173 with open(path, 'w') as fd:
174 fd.write(self.name)
Matthew Treinishc791ac42014-07-16 09:15:23 -0400175 return True
176 return False
177
178 @lockutils.synchronized('test_accounts_io', external=True)
179 def _get_free_hash(self, hashes):
Matthew Treinish976e8df2014-12-19 14:21:54 -0500180 # Cast as a list because in some edge cases a set will be passed in
181 hashes = list(hashes)
Matthew Treinishc791ac42014-07-16 09:15:23 -0400182 if not os.path.isdir(self.accounts_dir):
183 os.mkdir(self.accounts_dir)
184 # Create File from first hash (since none are in use)
185 self._create_hash_file(hashes[0])
186 return hashes[0]
Matthew Treinish4041b262015-02-27 11:18:54 -0500187 names = []
Matthew Treinish09f17832014-08-15 15:22:50 -0400188 for _hash in hashes:
189 res = self._create_hash_file(_hash)
Matthew Treinishc791ac42014-07-16 09:15:23 -0400190 if res:
Matthew Treinish09f17832014-08-15 15:22:50 -0400191 return _hash
Matthew Treinish4041b262015-02-27 11:18:54 -0500192 else:
193 path = os.path.join(os.path.join(self.accounts_dir,
194 _hash))
195 with open(path, 'r') as fd:
196 names.append(fd.read())
197 msg = ('Insufficient number of users provided. %s have allocated all '
198 'the credentials for this allocation request' % ','.join(names))
Andrea Frittoli (andreaf)848e3482015-10-12 14:17:21 +0100199 raise lib_exc.InvalidCredentials(msg)
Matthew Treinishc791ac42014-07-16 09:15:23 -0400200
Matthew Treinish976e8df2014-12-19 14:21:54 -0500201 def _get_match_hash_list(self, roles=None):
202 hashes = []
203 if roles:
204 # Loop over all the creds for each role in the subdict and generate
205 # a list of cred lists for each role
206 for role in roles:
207 temp_hashes = self.hash_dict['roles'].get(role, None)
208 if not temp_hashes:
Andrea Frittoli (andreaf)848e3482015-10-12 14:17:21 +0100209 raise lib_exc.InvalidCredentials(
Matthew Treinish976e8df2014-12-19 14:21:54 -0500210 "No credentials with role: %s specified in the "
211 "accounts ""file" % role)
212 hashes.append(temp_hashes)
213 # Take the list of lists and do a boolean and between each list to
214 # find the creds which fall under all the specified roles
215 temp_list = set(hashes[0])
216 for hash_list in hashes[1:]:
217 temp_list = temp_list & set(hash_list)
218 hashes = temp_list
219 else:
220 hashes = self.hash_dict['creds'].keys()
221 # NOTE(mtreinish): admin is a special case because of the increased
zhufl0892cb22016-05-06 14:46:00 +0800222 # privilege set which could potentially cause issues on tests where
223 # that is not expected. So unless the admin role isn't specified do
224 # not allocate admin.
Andrea Frittoli (andreaf)29491a72015-10-13 11:24:17 +0100225 admin_hashes = self.hash_dict['roles'].get(self.admin_role,
Matthew Treinish976e8df2014-12-19 14:21:54 -0500226 None)
Andrea Frittoli (andreaf)29491a72015-10-13 11:24:17 +0100227 if ((not roles or self.admin_role not in roles) and
Matthew Treinish976e8df2014-12-19 14:21:54 -0500228 admin_hashes):
229 useable_hashes = [x for x in hashes if x not in admin_hashes]
230 else:
231 useable_hashes = hashes
232 return useable_hashes
233
Matthew Treinishfd683e82015-04-13 20:30:06 -0400234 def _sanitize_creds(self, creds):
235 temp_creds = creds.copy()
236 temp_creds.pop('password')
237 return temp_creds
238
Matthew Treinish976e8df2014-12-19 14:21:54 -0500239 def _get_creds(self, roles=None):
Matthew Treinishb19eeb82014-09-04 09:57:46 -0400240 if self.use_default_creds:
Andrea Frittoli (andreaf)848e3482015-10-12 14:17:21 +0100241 raise lib_exc.InvalidCredentials(
242 "Account file %s doesn't exist" % self.test_accounts_file)
Matthew Treinish976e8df2014-12-19 14:21:54 -0500243 useable_hashes = self._get_match_hash_list(roles)
244 free_hash = self._get_free_hash(useable_hashes)
Matthew Treinishfd683e82015-04-13 20:30:06 -0400245 clean_creds = self._sanitize_creds(
246 self.hash_dict['creds'][free_hash])
247 LOG.info('%s allocated creds:\n%s' % (self.name, clean_creds))
Matthew Treinishf83f35c2015-04-10 11:59:11 -0400248 return self._wrap_creds_with_network(free_hash)
Matthew Treinishc791ac42014-07-16 09:15:23 -0400249
250 @lockutils.synchronized('test_accounts_io', external=True)
Matthew Treinish09f17832014-08-15 15:22:50 -0400251 def remove_hash(self, hash_string):
252 hash_path = os.path.join(self.accounts_dir, hash_string)
Matthew Treinishc791ac42014-07-16 09:15:23 -0400253 if not os.path.isfile(hash_path):
254 LOG.warning('Expected an account lock file %s to remove, but '
Matthew Treinish53a2b4b2015-02-24 23:32:07 -0500255 'one did not exist' % hash_path)
Matthew Treinishc791ac42014-07-16 09:15:23 -0400256 else:
257 os.remove(hash_path)
258 if not os.listdir(self.accounts_dir):
259 os.rmdir(self.accounts_dir)
260
261 def get_hash(self, creds):
Matthew Treinish976e8df2014-12-19 14:21:54 -0500262 for _hash in self.hash_dict['creds']:
263 # Comparing on the attributes that are expected in the YAML
Andrea Frittoli (andreaf)f39f9f32015-04-13 20:55:31 +0100264 init_attributes = creds.get_init_attributes()
265 hash_attributes = self.hash_dict['creds'][_hash].copy()
266 if ('user_domain_name' in init_attributes and 'user_domain_name'
267 not in hash_attributes):
268 # Allow for the case of domain_name populated from config
Andrea Frittoli (andreaf)1eb04962015-10-09 14:48:06 +0100269 domain_name = self.credentials_domain
Andrea Frittoli (andreaf)f39f9f32015-04-13 20:55:31 +0100270 hash_attributes['user_domain_name'] = domain_name
271 if all([getattr(creds, k) == hash_attributes[k] for
272 k in init_attributes]):
Matthew Treinish09f17832014-08-15 15:22:50 -0400273 return _hash
Matthew Treinishc791ac42014-07-16 09:15:23 -0400274 raise AttributeError('Invalid credentials %s' % creds)
275
276 def remove_credentials(self, creds):
Matthew Treinish09f17832014-08-15 15:22:50 -0400277 _hash = self.get_hash(creds)
Matthew Treinishfd683e82015-04-13 20:30:06 -0400278 clean_creds = self._sanitize_creds(self.hash_dict['creds'][_hash])
Matthew Treinish09f17832014-08-15 15:22:50 -0400279 self.remove_hash(_hash)
Matthew Treinishfd683e82015-04-13 20:30:06 -0400280 LOG.info("%s returned allocated creds:\n%s" % (self.name, clean_creds))
Matthew Treinishc791ac42014-07-16 09:15:23 -0400281
282 def get_primary_creds(self):
Andrea Frittoli (andreaf)17209bb2015-05-22 10:16:57 -0700283 if self._creds.get('primary'):
284 return self._creds.get('primary')
Matthew Treinishf83f35c2015-04-10 11:59:11 -0400285 net_creds = self._get_creds()
Andrea Frittoli (andreaf)17209bb2015-05-22 10:16:57 -0700286 self._creds['primary'] = net_creds
Matthew Treinishf83f35c2015-04-10 11:59:11 -0400287 return net_creds
Matthew Treinishc791ac42014-07-16 09:15:23 -0400288
289 def get_alt_creds(self):
Andrea Frittoli (andreaf)17209bb2015-05-22 10:16:57 -0700290 if self._creds.get('alt'):
291 return self._creds.get('alt')
Matthew Treinishf83f35c2015-04-10 11:59:11 -0400292 net_creds = self._get_creds()
Andrea Frittoli (andreaf)17209bb2015-05-22 10:16:57 -0700293 self._creds['alt'] = net_creds
Matthew Treinishf83f35c2015-04-10 11:59:11 -0400294 return net_creds
Matthew Treinishc791ac42014-07-16 09:15:23 -0400295
Matthew Treinish976e8df2014-12-19 14:21:54 -0500296 def get_creds_by_roles(self, roles, force_new=False):
297 roles = list(set(roles))
Andrea Frittoli (andreaf)17209bb2015-05-22 10:16:57 -0700298 exist_creds = self._creds.get(six.text_type(roles).encode(
Matthew Treinish1c517a22015-04-23 11:39:44 -0400299 'utf-8'), None)
Matthew Treinish976e8df2014-12-19 14:21:54 -0500300 # The force kwarg is used to allocate an additional set of creds with
301 # the same role list. The index used for the previously allocation
Ken'ichi Ohmichiedff8862015-10-13 01:10:53 +0000302 # in the _creds dict will be moved.
Matthew Treinish976e8df2014-12-19 14:21:54 -0500303 if exist_creds and not force_new:
304 return exist_creds
305 elif exist_creds and force_new:
Matthew Treinish1c517a22015-04-23 11:39:44 -0400306 new_index = six.text_type(roles).encode('utf-8') + '-' + \
Andrea Frittoli (andreaf)17209bb2015-05-22 10:16:57 -0700307 six.text_type(len(self._creds)).encode('utf-8')
308 self._creds[new_index] = exist_creds
Matthew Treinishf83f35c2015-04-10 11:59:11 -0400309 net_creds = self._get_creds(roles=roles)
Andrea Frittoli (andreaf)17209bb2015-05-22 10:16:57 -0700310 self._creds[six.text_type(roles).encode('utf-8')] = net_creds
Matthew Treinishf83f35c2015-04-10 11:59:11 -0400311 return net_creds
Matthew Treinish976e8df2014-12-19 14:21:54 -0500312
Andrea Frittoli (andreaf)17209bb2015-05-22 10:16:57 -0700313 def clear_creds(self):
314 for creds in self._creds.values():
Matthew Treinishc791ac42014-07-16 09:15:23 -0400315 self.remove_credentials(creds)
316
317 def get_admin_creds(self):
Andrea Frittoli (andreaf)29491a72015-10-13 11:24:17 +0100318 return self.get_creds_by_roles([self.admin_role])
Matthew Treinish976e8df2014-12-19 14:21:54 -0500319
Matthew Treinish4a596932015-03-06 20:37:01 -0500320 def is_role_available(self, role):
321 if self.use_default_creds:
Matthew Treinish976e8df2014-12-19 14:21:54 -0500322 return False
Matthew Treinish4a596932015-03-06 20:37:01 -0500323 else:
324 if self.hash_dict['roles'].get(role):
325 return True
326 return False
327
328 def admin_available(self):
Andrea Frittoli (andreaf)29491a72015-10-13 11:24:17 +0100329 return self.is_role_available(self.admin_role)
Andrea Frittolib1c23fc2014-09-03 13:40:08 +0100330
Matthew Treinishf83f35c2015-04-10 11:59:11 -0400331 def _wrap_creds_with_network(self, hash):
332 creds_dict = self.hash_dict['creds'][hash]
Andrea Frittoli (andreaf)c625bcf2015-10-09 12:09:05 +0100333 # Make sure a domain scope if defined for users in case of V3
Sean Dagueed6e5862016-04-04 10:49:13 -0400334 # Make sure a tenant is available in case of V2
Andrea Frittoli (andreaf)c625bcf2015-10-09 12:09:05 +0100335 creds_dict = self._extend_credentials(creds_dict)
336 # This just builds a Credentials object, it does not validate
337 # nor fill with missing fields.
338 credential = auth.get_credentials(
339 auth_url=None, fill_in=False,
Matthew Treinishf83f35c2015-04-10 11:59:11 -0400340 identity_version=self.identity_version, **creds_dict)
341 net_creds = cred_provider.TestResources(credential)
342 net_clients = clients.Manager(credentials=credential)
John Warren9487a182015-09-14 18:12:56 -0400343 compute_network_client = net_clients.compute_networks_client
Matthew Treinishf83f35c2015-04-10 11:59:11 -0400344 net_name = self.hash_dict['networks'].get(hash, None)
Matthew Treinishbe855fd2015-04-16 13:10:49 -0400345 try:
346 network = fixed_network.get_network_from_name(
347 net_name, compute_network_client)
Andrea Frittoli (andreaf)940f8c62015-10-30 16:39:24 +0900348 except exceptions.InvalidTestResource:
Matthew Treinishbe855fd2015-04-16 13:10:49 -0400349 network = {}
Matthew Treinishf83f35c2015-04-10 11:59:11 -0400350 net_creds.set_resources(network=network)
351 return net_creds
352
Andrea Frittoli (andreaf)c625bcf2015-10-09 12:09:05 +0100353 def _extend_credentials(self, creds_dict):
354 # In case of v3, adds a user_domain_name field to the creds
355 # dict if not defined
356 if self.identity_version == 'v3':
357 user_domain_fields = set(['user_domain_name', 'user_domain_id'])
358 if not user_domain_fields.intersection(set(creds_dict.keys())):
Andrea Frittoli (andreaf)1eb04962015-10-09 14:48:06 +0100359 creds_dict['user_domain_name'] = self.credentials_domain
Sean Dagueed6e5862016-04-04 10:49:13 -0400360 # NOTE(andreaf) In case of v2, replace project with tenant if project
361 # is provided and tenant is not
362 if self.identity_version == 'v2':
363 if ('project_name' in creds_dict and
364 'tenant_name' in creds_dict and
365 creds_dict['project_name'] != creds_dict['tenant_name']):
366 clean_creds = self._sanitize_creds(creds_dict)
367 msg = 'Cannot specify project and tenant at the same time %s'
368 raise exceptions.InvalidCredentials(msg % clean_creds)
369 if ('project_name' in creds_dict and
370 'tenant_name' not in creds_dict):
371 creds_dict['tenant_name'] = creds_dict['project_name']
372 creds_dict.pop('project_name')
Andrea Frittoli (andreaf)c625bcf2015-10-09 12:09:05 +0100373 return creds_dict