blob: 5b811489e010f516f73efc61fc1fd9a31a6ba526 [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
Andrea Frittoli (andreaf)c625bcf2015-10-09 12:09:05 +010021from tempest_lib import auth
Andrea Frittoli (andreaf)848e3482015-10-12 14:17:21 +010022from tempest_lib import exceptions as lib_exc
Matthew Treinishc791ac42014-07-16 09:15:23 -040023import yaml
24
Matthew Treinishf83f35c2015-04-10 11:59:11 -040025from tempest import clients
Matthew Treinishc791ac42014-07-16 09:15:23 -040026from tempest.common import cred_provider
Matthew Treinishf83f35c2015-04-10 11:59:11 -040027from tempest.common import fixed_network
Matthew Treinishc791ac42014-07-16 09:15:23 -040028from tempest import exceptions
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 Treinish2a346982015-07-16 14:24:56 -040034 with open(path, 'r') as yaml_file:
35 accounts = yaml.load(yaml_file)
Matthew Treinishc791ac42014-07-16 09:15:23 -040036 return accounts
37
38
Andrea Frittoli (andreaf)f9e01262015-05-22 10:24:12 -070039class PreProvisionedCredentialProvider(cred_provider.CredentialProvider):
Matthew Treinishc791ac42014-07-16 09:15:23 -040040
Andrea Frittoli (andreaf)848e3482015-10-12 14:17:21 +010041 def __init__(self, identity_version, test_accounts_file,
42 accounts_lock_dir, name=None, credentials_domain=None,
43 admin_role=None, object_storage_operator_role=None,
44 object_storage_reseller_admin_role=None):
45 """Credentials provider using pre-provisioned accounts
46
47 This credentials provider loads the details of pre-provisioned
48 accounts from a YAML file, in the format specified by
49 `etc/accounts.yaml.sample`. It locks accounts while in use, using the
50 external locking mechanism, allowing for multiple python processes
51 to share a single account file, and thus running tests in parallel.
52
53 The accounts_lock_dir must be generated using `lockutils.get_lock_path`
54 from the oslo.concurrency library. For instance:
55
56 accounts_lock_dir = os.path.join(lockutils.get_lock_path(CONF),
57 'test_accounts')
58
59 Role names for object storage are optional as long as the
60 `operator` and `reseller_admin` credential types are not used in the
61 accounts file.
62
63 :param identity_version: identity version of the credentials
64 :param admin_role: name of the admin role
65 :param test_accounts_file: path to the accounts YAML file
66 :param accounts_lock_dir: the directory for external locking
67 :param name: name of the hash file (optional)
68 :param credentials_domain: name of the domain credentials belong to
69 (if no domain is configured)
70 :param object_storage_operator_role: name of the role
71 :param object_storage_reseller_admin_role: name of the role
72 """
Andrea Frittoli (andreaf)f9e01262015-05-22 10:24:12 -070073 super(PreProvisionedCredentialProvider, self).__init__(
Andrea Frittoli (andreaf)1eb04962015-10-09 14:48:06 +010074 identity_version=identity_version, name=name,
Andrea Frittoli (andreaf)848e3482015-10-12 14:17:21 +010075 admin_role=admin_role, credentials_domain=credentials_domain)
76 self.test_accounts_file = test_accounts_file
77 if test_accounts_file and os.path.isfile(test_accounts_file):
78 accounts = read_accounts_yaml(self.test_accounts_file)
Matthew Treinishb19eeb82014-09-04 09:57:46 -040079 self.use_default_creds = False
80 else:
81 accounts = {}
82 self.use_default_creds = True
Andrea Frittoli (andreaf)848e3482015-10-12 14:17:21 +010083 self.hash_dict = self.get_hash_dict(
84 accounts, admin_role, object_storage_operator_role,
85 object_storage_reseller_admin_role)
86 self.accounts_dir = accounts_lock_dir
Andrea Frittoli (andreaf)17209bb2015-05-22 10:16:57 -070087 self._creds = {}
Matthew Treinishc791ac42014-07-16 09:15:23 -040088
89 @classmethod
Matthew Treinish976e8df2014-12-19 14:21:54 -050090 def _append_role(cls, role, account_hash, hash_dict):
91 if role in hash_dict['roles']:
92 hash_dict['roles'][role].append(account_hash)
93 else:
94 hash_dict['roles'][role] = [account_hash]
95 return hash_dict
96
97 @classmethod
Andrea Frittoli (andreaf)848e3482015-10-12 14:17:21 +010098 def get_hash_dict(cls, accounts, admin_role,
99 object_storage_operator_role=None,
100 object_storage_reseller_admin_role=None):
Matthew Treinishf83f35c2015-04-10 11:59:11 -0400101 hash_dict = {'roles': {}, 'creds': {}, 'networks': {}}
Matthew Treinish976e8df2014-12-19 14:21:54 -0500102 # Loop over the accounts read from the yaml file
Matthew Treinishc791ac42014-07-16 09:15:23 -0400103 for account in accounts:
Matthew Treinish976e8df2014-12-19 14:21:54 -0500104 roles = []
105 types = []
Matthew Treinishf83f35c2015-04-10 11:59:11 -0400106 resources = []
Matthew Treinish976e8df2014-12-19 14:21:54 -0500107 if 'roles' in account:
108 roles = account.pop('roles')
109 if 'types' in account:
110 types = account.pop('types')
Matthew Treinishf83f35c2015-04-10 11:59:11 -0400111 if 'resources' in account:
112 resources = account.pop('resources')
Matthew Treinishc791ac42014-07-16 09:15:23 -0400113 temp_hash = hashlib.md5()
Matthew Treinish1c517a22015-04-23 11:39:44 -0400114 temp_hash.update(six.text_type(account).encode('utf-8'))
Matthew Treinish976e8df2014-12-19 14:21:54 -0500115 temp_hash_key = temp_hash.hexdigest()
116 hash_dict['creds'][temp_hash_key] = account
117 for role in roles:
118 hash_dict = cls._append_role(role, temp_hash_key,
119 hash_dict)
120 # If types are set for the account append the matching role
121 # subdict with the hash
122 for type in types:
123 if type == 'admin':
Andrea Frittoli (andreaf)29491a72015-10-13 11:24:17 +0100124 hash_dict = cls._append_role(admin_role, temp_hash_key,
125 hash_dict)
Matthew Treinish976e8df2014-12-19 14:21:54 -0500126 elif type == 'operator':
Andrea Frittoli (andreaf)848e3482015-10-12 14:17:21 +0100127 if object_storage_operator_role:
128 hash_dict = cls._append_role(
129 object_storage_operator_role, temp_hash_key,
130 hash_dict)
131 else:
132 msg = ("Type 'operator' configured, but no "
133 "object_storage_operator_role specified")
134 raise lib_exc.InvalidCredentials(msg)
Matthew Treinish976e8df2014-12-19 14:21:54 -0500135 elif type == 'reseller_admin':
Andrea Frittoli (andreaf)848e3482015-10-12 14:17:21 +0100136 if object_storage_reseller_admin_role:
137 hash_dict = cls._append_role(
138 object_storage_reseller_admin_role,
139 temp_hash_key,
140 hash_dict)
141 else:
142 msg = ("Type 'reseller_admin' configured, but no "
143 "object_storage_reseller_admin_role specified")
144 raise lib_exc.InvalidCredentials(msg)
Matthew Treinishf83f35c2015-04-10 11:59:11 -0400145 # Populate the network subdict
146 for resource in resources:
147 if resource == 'network':
148 hash_dict['networks'][temp_hash_key] = resources[resource]
149 else:
Zhao Lei647cc182015-09-24 17:47:02 +0800150 LOG.warning('Unknown resource type %s, ignoring this field'
Matthew Treinishf83f35c2015-04-10 11:59:11 -0400151 % resource)
Matthew Treinishc791ac42014-07-16 09:15:23 -0400152 return hash_dict
153
Matthew Treinish09f17832014-08-15 15:22:50 -0400154 def is_multi_user(self):
Andrea Frittoli8283b4e2014-07-17 13:28:58 +0100155 # Default credentials is not a valid option with locking Account
156 if self.use_default_creds:
Andrea Frittoli (andreaf)848e3482015-10-12 14:17:21 +0100157 raise lib_exc.InvalidCredentials(
158 "Account file %s doesn't exist" % self.test_accounts_file)
Andrea Frittoli8283b4e2014-07-17 13:28:58 +0100159 else:
Matthew Treinish976e8df2014-12-19 14:21:54 -0500160 return len(self.hash_dict['creds']) > 1
Matthew Treinish09f17832014-08-15 15:22:50 -0400161
Yair Fried76488d72014-10-21 10:13:19 +0300162 def is_multi_tenant(self):
163 return self.is_multi_user()
164
Matthew Treinish09f17832014-08-15 15:22:50 -0400165 def _create_hash_file(self, hash_string):
166 path = os.path.join(os.path.join(self.accounts_dir, hash_string))
Matthew Treinishc791ac42014-07-16 09:15:23 -0400167 if not os.path.isfile(path):
Matthew Treinish4041b262015-02-27 11:18:54 -0500168 with open(path, 'w') as fd:
169 fd.write(self.name)
Matthew Treinishc791ac42014-07-16 09:15:23 -0400170 return True
171 return False
172
173 @lockutils.synchronized('test_accounts_io', external=True)
174 def _get_free_hash(self, hashes):
Matthew Treinish976e8df2014-12-19 14:21:54 -0500175 # Cast as a list because in some edge cases a set will be passed in
176 hashes = list(hashes)
Matthew Treinishc791ac42014-07-16 09:15:23 -0400177 if not os.path.isdir(self.accounts_dir):
178 os.mkdir(self.accounts_dir)
179 # Create File from first hash (since none are in use)
180 self._create_hash_file(hashes[0])
181 return hashes[0]
Matthew Treinish4041b262015-02-27 11:18:54 -0500182 names = []
Matthew Treinish09f17832014-08-15 15:22:50 -0400183 for _hash in hashes:
184 res = self._create_hash_file(_hash)
Matthew Treinishc791ac42014-07-16 09:15:23 -0400185 if res:
Matthew Treinish09f17832014-08-15 15:22:50 -0400186 return _hash
Matthew Treinish4041b262015-02-27 11:18:54 -0500187 else:
188 path = os.path.join(os.path.join(self.accounts_dir,
189 _hash))
190 with open(path, 'r') as fd:
191 names.append(fd.read())
192 msg = ('Insufficient number of users provided. %s have allocated all '
193 'the credentials for this allocation request' % ','.join(names))
Andrea Frittoli (andreaf)848e3482015-10-12 14:17:21 +0100194 raise lib_exc.InvalidCredentials(msg)
Matthew Treinishc791ac42014-07-16 09:15:23 -0400195
Matthew Treinish976e8df2014-12-19 14:21:54 -0500196 def _get_match_hash_list(self, roles=None):
197 hashes = []
198 if roles:
199 # Loop over all the creds for each role in the subdict and generate
200 # a list of cred lists for each role
201 for role in roles:
202 temp_hashes = self.hash_dict['roles'].get(role, None)
203 if not temp_hashes:
Andrea Frittoli (andreaf)848e3482015-10-12 14:17:21 +0100204 raise lib_exc.InvalidCredentials(
Matthew Treinish976e8df2014-12-19 14:21:54 -0500205 "No credentials with role: %s specified in the "
206 "accounts ""file" % role)
207 hashes.append(temp_hashes)
208 # Take the list of lists and do a boolean and between each list to
209 # find the creds which fall under all the specified roles
210 temp_list = set(hashes[0])
211 for hash_list in hashes[1:]:
212 temp_list = temp_list & set(hash_list)
213 hashes = temp_list
214 else:
215 hashes = self.hash_dict['creds'].keys()
216 # NOTE(mtreinish): admin is a special case because of the increased
217 # privlege set which could potentially cause issues on tests where that
218 # is not expected. So unless the admin role isn't specified do not
219 # allocate admin.
Andrea Frittoli (andreaf)29491a72015-10-13 11:24:17 +0100220 admin_hashes = self.hash_dict['roles'].get(self.admin_role,
Matthew Treinish976e8df2014-12-19 14:21:54 -0500221 None)
Andrea Frittoli (andreaf)29491a72015-10-13 11:24:17 +0100222 if ((not roles or self.admin_role not in roles) and
Matthew Treinish976e8df2014-12-19 14:21:54 -0500223 admin_hashes):
224 useable_hashes = [x for x in hashes if x not in admin_hashes]
225 else:
226 useable_hashes = hashes
227 return useable_hashes
228
Matthew Treinishfd683e82015-04-13 20:30:06 -0400229 def _sanitize_creds(self, creds):
230 temp_creds = creds.copy()
231 temp_creds.pop('password')
232 return temp_creds
233
Matthew Treinish976e8df2014-12-19 14:21:54 -0500234 def _get_creds(self, roles=None):
Matthew Treinishb19eeb82014-09-04 09:57:46 -0400235 if self.use_default_creds:
Andrea Frittoli (andreaf)848e3482015-10-12 14:17:21 +0100236 raise lib_exc.InvalidCredentials(
237 "Account file %s doesn't exist" % self.test_accounts_file)
Matthew Treinish976e8df2014-12-19 14:21:54 -0500238 useable_hashes = self._get_match_hash_list(roles)
239 free_hash = self._get_free_hash(useable_hashes)
Matthew Treinishfd683e82015-04-13 20:30:06 -0400240 clean_creds = self._sanitize_creds(
241 self.hash_dict['creds'][free_hash])
242 LOG.info('%s allocated creds:\n%s' % (self.name, clean_creds))
Matthew Treinishf83f35c2015-04-10 11:59:11 -0400243 return self._wrap_creds_with_network(free_hash)
Matthew Treinishc791ac42014-07-16 09:15:23 -0400244
245 @lockutils.synchronized('test_accounts_io', external=True)
Matthew Treinish09f17832014-08-15 15:22:50 -0400246 def remove_hash(self, hash_string):
247 hash_path = os.path.join(self.accounts_dir, hash_string)
Matthew Treinishc791ac42014-07-16 09:15:23 -0400248 if not os.path.isfile(hash_path):
249 LOG.warning('Expected an account lock file %s to remove, but '
Matthew Treinish53a2b4b2015-02-24 23:32:07 -0500250 'one did not exist' % hash_path)
Matthew Treinishc791ac42014-07-16 09:15:23 -0400251 else:
252 os.remove(hash_path)
253 if not os.listdir(self.accounts_dir):
254 os.rmdir(self.accounts_dir)
255
256 def get_hash(self, creds):
Matthew Treinish976e8df2014-12-19 14:21:54 -0500257 for _hash in self.hash_dict['creds']:
258 # Comparing on the attributes that are expected in the YAML
Andrea Frittoli (andreaf)f39f9f32015-04-13 20:55:31 +0100259 init_attributes = creds.get_init_attributes()
260 hash_attributes = self.hash_dict['creds'][_hash].copy()
261 if ('user_domain_name' in init_attributes and 'user_domain_name'
262 not in hash_attributes):
263 # Allow for the case of domain_name populated from config
Andrea Frittoli (andreaf)1eb04962015-10-09 14:48:06 +0100264 domain_name = self.credentials_domain
Andrea Frittoli (andreaf)f39f9f32015-04-13 20:55:31 +0100265 hash_attributes['user_domain_name'] = domain_name
266 if all([getattr(creds, k) == hash_attributes[k] for
267 k in init_attributes]):
Matthew Treinish09f17832014-08-15 15:22:50 -0400268 return _hash
Matthew Treinishc791ac42014-07-16 09:15:23 -0400269 raise AttributeError('Invalid credentials %s' % creds)
270
271 def remove_credentials(self, creds):
Matthew Treinish09f17832014-08-15 15:22:50 -0400272 _hash = self.get_hash(creds)
Matthew Treinishfd683e82015-04-13 20:30:06 -0400273 clean_creds = self._sanitize_creds(self.hash_dict['creds'][_hash])
Matthew Treinish09f17832014-08-15 15:22:50 -0400274 self.remove_hash(_hash)
Matthew Treinishfd683e82015-04-13 20:30:06 -0400275 LOG.info("%s returned allocated creds:\n%s" % (self.name, clean_creds))
Matthew Treinishc791ac42014-07-16 09:15:23 -0400276
277 def get_primary_creds(self):
Andrea Frittoli (andreaf)17209bb2015-05-22 10:16:57 -0700278 if self._creds.get('primary'):
279 return self._creds.get('primary')
Matthew Treinishf83f35c2015-04-10 11:59:11 -0400280 net_creds = self._get_creds()
Andrea Frittoli (andreaf)17209bb2015-05-22 10:16:57 -0700281 self._creds['primary'] = net_creds
Matthew Treinishf83f35c2015-04-10 11:59:11 -0400282 return net_creds
Matthew Treinishc791ac42014-07-16 09:15:23 -0400283
284 def get_alt_creds(self):
Andrea Frittoli (andreaf)17209bb2015-05-22 10:16:57 -0700285 if self._creds.get('alt'):
286 return self._creds.get('alt')
Matthew Treinishf83f35c2015-04-10 11:59:11 -0400287 net_creds = self._get_creds()
Andrea Frittoli (andreaf)17209bb2015-05-22 10:16:57 -0700288 self._creds['alt'] = net_creds
Matthew Treinishf83f35c2015-04-10 11:59:11 -0400289 return net_creds
Matthew Treinishc791ac42014-07-16 09:15:23 -0400290
Matthew Treinish976e8df2014-12-19 14:21:54 -0500291 def get_creds_by_roles(self, roles, force_new=False):
292 roles = list(set(roles))
Andrea Frittoli (andreaf)17209bb2015-05-22 10:16:57 -0700293 exist_creds = self._creds.get(six.text_type(roles).encode(
Matthew Treinish1c517a22015-04-23 11:39:44 -0400294 'utf-8'), None)
Matthew Treinish976e8df2014-12-19 14:21:54 -0500295 # The force kwarg is used to allocate an additional set of creds with
296 # the same role list. The index used for the previously allocation
Ken'ichi Ohmichiedff8862015-10-13 01:10:53 +0000297 # in the _creds dict will be moved.
Matthew Treinish976e8df2014-12-19 14:21:54 -0500298 if exist_creds and not force_new:
299 return exist_creds
300 elif exist_creds and force_new:
Matthew Treinish1c517a22015-04-23 11:39:44 -0400301 new_index = six.text_type(roles).encode('utf-8') + '-' + \
Andrea Frittoli (andreaf)17209bb2015-05-22 10:16:57 -0700302 six.text_type(len(self._creds)).encode('utf-8')
303 self._creds[new_index] = exist_creds
Matthew Treinishf83f35c2015-04-10 11:59:11 -0400304 net_creds = self._get_creds(roles=roles)
Andrea Frittoli (andreaf)17209bb2015-05-22 10:16:57 -0700305 self._creds[six.text_type(roles).encode('utf-8')] = net_creds
Matthew Treinishf83f35c2015-04-10 11:59:11 -0400306 return net_creds
Matthew Treinish976e8df2014-12-19 14:21:54 -0500307
Andrea Frittoli (andreaf)17209bb2015-05-22 10:16:57 -0700308 def clear_creds(self):
309 for creds in self._creds.values():
Matthew Treinishc791ac42014-07-16 09:15:23 -0400310 self.remove_credentials(creds)
311
312 def get_admin_creds(self):
Andrea Frittoli (andreaf)29491a72015-10-13 11:24:17 +0100313 return self.get_creds_by_roles([self.admin_role])
Matthew Treinish976e8df2014-12-19 14:21:54 -0500314
Matthew Treinish4a596932015-03-06 20:37:01 -0500315 def is_role_available(self, role):
316 if self.use_default_creds:
Matthew Treinish976e8df2014-12-19 14:21:54 -0500317 return False
Matthew Treinish4a596932015-03-06 20:37:01 -0500318 else:
319 if self.hash_dict['roles'].get(role):
320 return True
321 return False
322
323 def admin_available(self):
Andrea Frittoli (andreaf)29491a72015-10-13 11:24:17 +0100324 return self.is_role_available(self.admin_role)
Andrea Frittolib1c23fc2014-09-03 13:40:08 +0100325
Matthew Treinishf83f35c2015-04-10 11:59:11 -0400326 def _wrap_creds_with_network(self, hash):
327 creds_dict = self.hash_dict['creds'][hash]
Andrea Frittoli (andreaf)c625bcf2015-10-09 12:09:05 +0100328 # Make sure a domain scope if defined for users in case of V3
329 creds_dict = self._extend_credentials(creds_dict)
330 # This just builds a Credentials object, it does not validate
331 # nor fill with missing fields.
332 credential = auth.get_credentials(
333 auth_url=None, fill_in=False,
Matthew Treinishf83f35c2015-04-10 11:59:11 -0400334 identity_version=self.identity_version, **creds_dict)
335 net_creds = cred_provider.TestResources(credential)
336 net_clients = clients.Manager(credentials=credential)
John Warren9487a182015-09-14 18:12:56 -0400337 compute_network_client = net_clients.compute_networks_client
Matthew Treinishf83f35c2015-04-10 11:59:11 -0400338 net_name = self.hash_dict['networks'].get(hash, None)
Matthew Treinishbe855fd2015-04-16 13:10:49 -0400339 try:
340 network = fixed_network.get_network_from_name(
341 net_name, compute_network_client)
342 except exceptions.InvalidConfiguration:
343 network = {}
Matthew Treinishf83f35c2015-04-10 11:59:11 -0400344 net_creds.set_resources(network=network)
345 return net_creds
346
Andrea Frittoli (andreaf)c625bcf2015-10-09 12:09:05 +0100347 def _extend_credentials(self, creds_dict):
348 # In case of v3, adds a user_domain_name field to the creds
349 # dict if not defined
350 if self.identity_version == 'v3':
351 user_domain_fields = set(['user_domain_name', 'user_domain_id'])
352 if not user_domain_fields.intersection(set(creds_dict.keys())):
Andrea Frittoli (andreaf)1eb04962015-10-09 14:48:06 +0100353 creds_dict['user_domain_name'] = self.credentials_domain
Andrea Frittoli (andreaf)c625bcf2015-10-09 12:09:05 +0100354 return creds_dict