blob: 5c94289a6d9f3bbfb9939c9a97df40c177fa6817 [file] [log] [blame]
Maru Newbyb096d9f2015-03-09 18:54:54 +00001# Copyright 2013 IBM Corp.
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 netaddr
Ihar Hrachyshkac695f9f2015-02-26 23:26:41 +010016from oslo_log import log as logging
Maru Newby5690a352015-03-13 18:46:40 +000017from tempest_lib.common.utils import data_utils
Maru Newbyb096d9f2015-03-09 18:54:54 +000018from tempest_lib import exceptions as lib_exc
19
20from neutron.tests.api.contrib import clients
21from neutron.tests.tempest.common import cred_provider
Maru Newbyb096d9f2015-03-09 18:54:54 +000022from neutron.tests.tempest import config
23from neutron.tests.tempest import exceptions
Maru Newbyb096d9f2015-03-09 18:54:54 +000024
25CONF = config.CONF
26LOG = logging.getLogger(__name__)
27
28
29class IsolatedCreds(cred_provider.CredentialProvider):
30
31 def __init__(self, name, password='pass', network_resources=None):
32 super(IsolatedCreds, self).__init__(name, password, network_resources)
33 self.network_resources = network_resources
34 self.isolated_creds = {}
35 self.isolated_net_resources = {}
36 self.ports = []
37 self.password = password
38 self.identity_admin_client, self.network_admin_client = (
39 self._get_admin_clients())
40
41 def _get_admin_clients(self):
42 """
43 Returns a tuple with instances of the following admin clients (in this
44 order):
45 identity
46 network
47 """
48 os = clients.AdminManager()
49 return os.identity_client, os.network_client
50
51 def _create_tenant(self, name, description):
52 tenant = self.identity_admin_client.create_tenant(
53 name=name, description=description)
54 return tenant
55
56 def _get_tenant_by_name(self, name):
57 tenant = self.identity_admin_client.get_tenant_by_name(name)
58 return tenant
59
60 def _create_user(self, username, password, tenant, email):
61 user = self.identity_admin_client.create_user(
62 username, password, tenant['id'], email)
63 return user
64
65 def _get_user(self, tenant, username):
66 user = self.identity_admin_client.get_user_by_username(
67 tenant['id'], username)
68 return user
69
70 def _list_roles(self):
71 roles = self.identity_admin_client.list_roles()
72 return roles
73
74 def _assign_user_role(self, tenant, user, role_name):
75 role = None
76 try:
77 roles = self._list_roles()
78 role = next(r for r in roles if r['name'] == role_name)
79 except StopIteration:
80 msg = 'No "%s" role found' % role_name
81 raise lib_exc.NotFound(msg)
82 try:
83 self.identity_admin_client.assign_user_role(tenant['id'],
84 user['id'],
85 role['id'])
86 except lib_exc.Conflict:
87 LOG.warning('Trying to add %s for user %s in tenant %s but they '
88 ' were already granted that role' % (role_name,
89 user['name'],
90 tenant['name']))
91
92 def _delete_user(self, user):
93 self.identity_admin_client.delete_user(user)
94
95 def _delete_tenant(self, tenant):
96 if CONF.service_available.neutron:
97 self._cleanup_default_secgroup(tenant)
98 self.identity_admin_client.delete_tenant(tenant)
99
100 def _create_creds(self, suffix="", admin=False, roles=None):
101 """Create random credentials under the following schema.
102
103 If the name contains a '.' is the full class path of something, and
104 we don't really care. If it isn't, it's probably a meaningful name,
105 so use it.
106
107 For logging purposes, -user and -tenant are long and redundant,
108 don't use them. The user# will be sufficient to figure it out.
109 """
110 if '.' in self.name:
111 root = ""
112 else:
113 root = self.name
114
115 tenant_name = data_utils.rand_name(root) + suffix
116 tenant_desc = tenant_name + "-desc"
117 tenant = self._create_tenant(name=tenant_name,
118 description=tenant_desc)
119
120 username = data_utils.rand_name(root) + suffix
121 email = data_utils.rand_name(root) + suffix + "@example.com"
122 user = self._create_user(username, self.password,
123 tenant, email)
124 if admin:
125 self._assign_user_role(tenant, user, CONF.identity.admin_role)
126 # Add roles specified in config file
127 for conf_role in CONF.auth.tempest_roles:
128 self._assign_user_role(tenant, user, conf_role)
129 # Add roles requested by caller
130 if roles:
131 for role in roles:
132 self._assign_user_role(tenant, user, role)
133 return self._get_credentials(user, tenant)
134
135 def _get_credentials(self, user, tenant):
136 return cred_provider.get_credentials(
137 username=user['name'], user_id=user['id'],
138 tenant_name=tenant['name'], tenant_id=tenant['id'],
139 password=self.password)
140
141 def _create_network_resources(self, tenant_id):
142 network = None
143 subnet = None
144 router = None
145 # Make sure settings
146 if self.network_resources:
147 if self.network_resources['router']:
148 if (not self.network_resources['subnet'] or
149 not self.network_resources['network']):
150 raise exceptions.InvalidConfiguration(
151 'A router requires a subnet and network')
152 elif self.network_resources['subnet']:
153 if not self.network_resources['network']:
154 raise exceptions.InvalidConfiguration(
155 'A subnet requires a network')
156 elif self.network_resources['dhcp']:
157 raise exceptions.InvalidConfiguration('DHCP requires a subnet')
158
159 data_utils.rand_name_root = data_utils.rand_name(self.name)
160 if not self.network_resources or self.network_resources['network']:
161 network_name = data_utils.rand_name_root + "-network"
162 network = self._create_network(network_name, tenant_id)
163 try:
164 if not self.network_resources or self.network_resources['subnet']:
165 subnet_name = data_utils.rand_name_root + "-subnet"
166 subnet = self._create_subnet(subnet_name, tenant_id,
167 network['id'])
168 if not self.network_resources or self.network_resources['router']:
169 router_name = data_utils.rand_name_root + "-router"
170 router = self._create_router(router_name, tenant_id)
171 self._add_router_interface(router['id'], subnet['id'])
172 except Exception:
173 if router:
174 self._clear_isolated_router(router['id'], router['name'])
175 if subnet:
176 self._clear_isolated_subnet(subnet['id'], subnet['name'])
177 if network:
178 self._clear_isolated_network(network['id'], network['name'])
179 raise
180 return network, subnet, router
181
182 def _create_network(self, name, tenant_id):
183 resp_body = self.network_admin_client.create_network(
184 name=name, tenant_id=tenant_id)
185 return resp_body['network']
186
187 def _create_subnet(self, subnet_name, tenant_id, network_id):
188 base_cidr = netaddr.IPNetwork(CONF.network.tenant_network_cidr)
189 mask_bits = CONF.network.tenant_network_mask_bits
190 for subnet_cidr in base_cidr.subnet(mask_bits):
191 try:
192 if self.network_resources:
193 resp_body = self.network_admin_client.\
194 create_subnet(
195 network_id=network_id, cidr=str(subnet_cidr),
196 name=subnet_name,
197 tenant_id=tenant_id,
198 enable_dhcp=self.network_resources['dhcp'],
199 ip_version=4)
200 else:
201 resp_body = self.network_admin_client.\
202 create_subnet(network_id=network_id,
203 cidr=str(subnet_cidr),
204 name=subnet_name,
205 tenant_id=tenant_id,
206 ip_version=4)
207 break
208 except lib_exc.BadRequest as e:
209 if 'overlaps with another subnet' not in str(e):
210 raise
211 else:
212 message = 'Available CIDR for subnet creation could not be found'
213 raise Exception(message)
214 return resp_body['subnet']
215
216 def _create_router(self, router_name, tenant_id):
217 external_net_id = dict(
218 network_id=CONF.network.public_network_id)
219 resp_body = self.network_admin_client.create_router(
220 router_name,
221 external_gateway_info=external_net_id,
222 tenant_id=tenant_id)
223 return resp_body['router']
224
225 def _add_router_interface(self, router_id, subnet_id):
226 self.network_admin_client.add_router_interface_with_subnet_id(
227 router_id, subnet_id)
228
229 def get_primary_network(self):
230 return self.isolated_net_resources.get('primary')[0]
231
232 def get_primary_subnet(self):
233 return self.isolated_net_resources.get('primary')[1]
234
235 def get_primary_router(self):
236 return self.isolated_net_resources.get('primary')[2]
237
238 def get_admin_network(self):
239 return self.isolated_net_resources.get('admin')[0]
240
241 def get_admin_subnet(self):
242 return self.isolated_net_resources.get('admin')[1]
243
244 def get_admin_router(self):
245 return self.isolated_net_resources.get('admin')[2]
246
247 def get_alt_network(self):
248 return self.isolated_net_resources.get('alt')[0]
249
250 def get_alt_subnet(self):
251 return self.isolated_net_resources.get('alt')[1]
252
253 def get_alt_router(self):
254 return self.isolated_net_resources.get('alt')[2]
255
256 def get_credentials(self, credential_type):
257 if self.isolated_creds.get(str(credential_type)):
258 credentials = self.isolated_creds[str(credential_type)]
259 else:
260 if credential_type in ['primary', 'alt', 'admin']:
261 is_admin = (credential_type == 'admin')
262 credentials = self._create_creds(admin=is_admin)
263 else:
264 credentials = self._create_creds(roles=credential_type)
265 self.isolated_creds[str(credential_type)] = credentials
266 # Maintained until tests are ported
267 LOG.info("Acquired isolated creds:\n credentials: %s"
268 % credentials)
269 if (CONF.service_available.neutron and
270 not CONF.baremetal.driver_enabled):
271 network, subnet, router = self._create_network_resources(
272 credentials.tenant_id)
273 self.isolated_net_resources[str(credential_type)] = (
274 network, subnet, router,)
275 LOG.info("Created isolated network resources for : \n"
276 + " credentials: %s" % credentials)
277 return credentials
278
279 def get_primary_creds(self):
280 return self.get_credentials('primary')
281
282 def get_admin_creds(self):
283 return self.get_credentials('admin')
284
285 def get_alt_creds(self):
286 return self.get_credentials('alt')
287
288 def get_creds_by_roles(self, roles, force_new=False):
289 roles = list(set(roles))
290 # The roles list as a str will become the index as the dict key for
291 # the created credentials set in the isolated_creds dict.
292 exist_creds = self.isolated_creds.get(str(roles))
293 # If force_new flag is True 2 cred sets with the same roles are needed
294 # handle this by creating a separate index for old one to store it
295 # separately for cleanup
296 if exist_creds and force_new:
297 new_index = str(roles) + '-' + str(len(self.isolated_creds))
298 self.isolated_creds[new_index] = exist_creds
299 del self.isolated_creds[str(roles)]
300 # Handle isolated neutron resouces if they exist too
301 if CONF.service_available.neutron:
302 exist_net = self.isolated_net_resources.get(str(roles))
303 if exist_net:
304 self.isolated_net_resources[new_index] = exist_net
305 del self.isolated_net_resources[str(roles)]
306 return self.get_credentials(roles)
307
308 def _clear_isolated_router(self, router_id, router_name):
309 net_client = self.network_admin_client
310 try:
311 net_client.delete_router(router_id)
312 except lib_exc.NotFound:
313 LOG.warn('router with name: %s not found for delete' %
314 router_name)
315
316 def _clear_isolated_subnet(self, subnet_id, subnet_name):
317 net_client = self.network_admin_client
318 try:
319 net_client.delete_subnet(subnet_id)
320 except lib_exc.NotFound:
321 LOG.warn('subnet with name: %s not found for delete' %
322 subnet_name)
323
324 def _clear_isolated_network(self, network_id, network_name):
325 net_client = self.network_admin_client
326 try:
327 net_client.delete_network(network_id)
328 except lib_exc.NotFound:
329 LOG.warn('network with name: %s not found for delete' %
330 network_name)
331
332 def _cleanup_default_secgroup(self, tenant):
333 net_client = self.network_admin_client
334 resp_body = net_client.list_security_groups(tenant_id=tenant,
335 name="default")
336 secgroups_to_delete = resp_body['security_groups']
337 for secgroup in secgroups_to_delete:
338 try:
339 net_client.delete_security_group(secgroup['id'])
340 except lib_exc.NotFound:
341 LOG.warn('Security group %s, id %s not found for clean-up' %
342 (secgroup['name'], secgroup['id']))
343
344 def _clear_isolated_net_resources(self):
345 net_client = self.network_admin_client
346 for cred in self.isolated_net_resources:
347 network, subnet, router = self.isolated_net_resources.get(cred)
348 LOG.debug("Clearing network: %(network)s, "
349 "subnet: %(subnet)s, router: %(router)s",
350 {'network': network, 'subnet': subnet, 'router': router})
351 if (not self.network_resources or
352 self.network_resources.get('router')):
353 try:
354 net_client.remove_router_interface_with_subnet_id(
355 router['id'], subnet['id'])
356 except lib_exc.NotFound:
357 LOG.warn('router with name: %s not found for delete' %
358 router['name'])
359 self._clear_isolated_router(router['id'], router['name'])
360 if (not self.network_resources or
361 self.network_resources.get('subnet')):
362 self._clear_isolated_subnet(subnet['id'], subnet['name'])
363 if (not self.network_resources or
364 self.network_resources.get('network')):
365 self._clear_isolated_network(network['id'], network['name'])
366 self.isolated_net_resources = {}
367
368 def clear_isolated_creds(self):
369 if not self.isolated_creds:
370 return
371 self._clear_isolated_net_resources()
372 for creds in self.isolated_creds.itervalues():
373 try:
374 self._delete_user(creds.user_id)
375 except lib_exc.NotFound:
376 LOG.warn("user with name: %s not found for delete" %
377 creds.username)
378 try:
379 self._delete_tenant(creds.tenant_id)
380 except lib_exc.NotFound:
381 LOG.warn("tenant with name: %s not found for delete" %
382 creds.tenant_name)
383 self.isolated_creds = {}
384
385 def is_multi_user(self):
386 return True
387
388 def is_multi_tenant(self):
389 return True
390
391 def is_role_available(self, role):
392 return True