1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
|
/*-
* ============LICENSE_START=======================================================
* ONAP - SO
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
*/
package org.onap.so.openstack.utils;
import java.io.Serializable;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.onap.so.db.catalog.beans.CloudIdentity;
import org.onap.so.db.catalog.beans.CloudSite;
import org.onap.so.cloud.authentication.AuthenticationMethodFactory;
import org.onap.so.logger.MessageEnum;
import org.onap.so.logger.MsoAlarmLogger;
import org.onap.so.logger.MsoLogger;
import org.onap.so.openstack.beans.MsoTenant;
import org.onap.so.openstack.exceptions.MsoAdapterException;
import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound;
import org.onap.so.openstack.exceptions.MsoException;
import org.onap.so.openstack.exceptions.MsoOpenstackException;
import org.onap.so.openstack.exceptions.MsoTenantAlreadyExists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.woorea.openstack.base.client.OpenStackBaseException;
import com.woorea.openstack.base.client.OpenStackConnectException;
import com.woorea.openstack.base.client.OpenStackRequest;
import com.woorea.openstack.base.client.OpenStackResponseException;
import com.woorea.openstack.keystone.Keystone;
import com.woorea.openstack.keystone.model.Access;
import com.woorea.openstack.keystone.model.Authentication;
import com.woorea.openstack.keystone.model.Metadata;
import com.woorea.openstack.keystone.model.Role;
import com.woorea.openstack.keystone.model.Roles;
import com.woorea.openstack.keystone.model.Tenant;
import com.woorea.openstack.keystone.model.User;
import com.woorea.openstack.keystone.utils.KeystoneUtils;
@Component
public class MsoKeystoneUtils extends MsoTenantUtils {
// Cache the Keystone Clients statically. Since there is just one MSO user, there is no
// benefit to re-authentication on every request (or across different flows). The
// token will be used until it expires.
//
// The cache key is "cloudId"
private static Map <String, KeystoneCacheEntry> adminClientCache = new HashMap<>();
private static MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, MsoKeystoneUtils.class);
@Autowired
private AuthenticationMethodFactory authenticationMethodFactory;
@Autowired
private MsoHeatUtils msoHeatUtils;
@Autowired
private MsoNeutronUtils msoNeutronUtils;
@Autowired
private MsoTenantUtilsFactory tenantUtilsFactory;
/**
* Create a tenant with the specified name in the given cloud. If the tenant already exists,
* an Exception will be thrown. The MSO User will also be added to the "member" list of
* the new tenant to perform subsequent Nova/Heat commands in the tenant. If the MSO User
* association fails, the entire transaction will be rolled back.
* <p>
* For the AIC Cloud (DCP/LCP): it is not clear that cloudId is needed, as all admin
* requests go to the centralized identity service in DCP. However, if some artifact
* must exist in each local LCP instance as well, then it will be needed to access the
* correct region.
* <p>
*
* @param tenantName The tenant name to create
* @param cloudSiteId The cloud identifier (may be a region) in which to create the tenant.
* @return the tenant ID of the newly created tenant
* @throws MsoTenantAlreadyExists Thrown if the requested tenant already exists
* @throws MsoOpenstackException Thrown if the Openstack API call returns an exception
*/
public String createTenant (String tenantName,
String cloudSiteId,
Map <String, String> metadata,
boolean backout) throws MsoException {
// Obtain the cloud site information where we will create the tenant
Optional<CloudSite> cloudSiteOpt = cloudConfig.getCloudSite(cloudSiteId);
if (!cloudSiteOpt.isPresent()) {
LOGGER.error(MessageEnum.RA_CREATE_TENANT_ERR, "MSOCloudSite not found", "", "", MsoLogger.ErrorCode.DataError, "MSOCloudSite not found");
throw new MsoCloudSiteNotFound (cloudSiteId);
}
Keystone keystoneAdminClient = getKeystoneAdminClient(cloudSiteOpt.get());
Tenant tenant = null;
try {
// Check if the tenant already exists
tenant = findTenantByName (keystoneAdminClient, tenantName);
if (tenant != null) {
// Tenant already exists. Throw an exception
LOGGER.error(MessageEnum.RA_TENANT_ALREADY_EXIST, tenantName, cloudSiteId, "", "", MsoLogger.ErrorCode.DataError, "Tenant already exists");
throw new MsoTenantAlreadyExists (tenantName, cloudSiteId);
}
// Does not exist, create a new one
tenant = new Tenant ();
tenant.setName (tenantName);
tenant.setDescription ("SDN Tenant (via MSO)");
tenant.setEnabled (true);
OpenStackRequest <Tenant> request = keystoneAdminClient.tenants ().create (tenant);
tenant = executeAndRecordOpenstackRequest (request);
} catch (OpenStackBaseException e) {
// Convert Keystone OpenStackResponseException to MsoOpenstackException
throw keystoneErrorToMsoException (e, "CreateTenant");
} catch (RuntimeException e) {
// Catch-all
throw runtimeExceptionToMsoException (e, "CreateTenant");
}
// Add MSO User to the tenant as a member and
// apply tenant metadata if supported by the cloud site
try {
CloudIdentity cloudIdentity = cloudConfig.getIdentityService(cloudSiteOpt.get().getIdentityServiceId());
User msoUser = findUserByNameOrId (keystoneAdminClient, cloudIdentity.getMsoId ());
Role memberRole = findRoleByNameOrId (keystoneAdminClient, cloudIdentity.getMemberRole ());
if(msoUser != null && memberRole != null) {
OpenStackRequest <Void> request = keystoneAdminClient.tenants ().addUser (tenant.getId (),
msoUser.getId (),
memberRole.getId ());
executeAndRecordOpenstackRequest (request);
}
if (cloudIdentity.getTenantMetadata () && metadata != null && !metadata.isEmpty ()) {
Metadata tenantMetadata = new Metadata ();
tenantMetadata.setMetadata (metadata);
OpenStackRequest <Metadata> metaRequest = keystoneAdminClient.tenants ()
.createOrUpdateMetadata (tenant.getId (),
tenantMetadata);
executeAndRecordOpenstackRequest (metaRequest);
}
} catch (Exception e) {
// Failed to attach MSO User to the new tenant. Can't operate without access,
// so roll back the tenant.
if (!backout)
{
LOGGER.warn(MessageEnum.RA_CREATE_TENANT_ERR, "Create Tenant errored, Tenant deletion suppressed", "Openstack", "", MsoLogger.ErrorCode.DataError, "Create Tenant error, Tenant deletion suppressed");
}
else
{
try {
OpenStackRequest <Void> request = keystoneAdminClient.tenants ().delete (tenant.getId ());
executeAndRecordOpenstackRequest (request);
} catch (Exception e2) {
// Just log this one. We will report the original exception.
LOGGER.error (MessageEnum.RA_CREATE_TENANT_ERR, "Nested exception rolling back tenant", "Openstack", "", MsoLogger.ErrorCode.DataError, "Create Tenant error, Nested exception rolling back tenant", e2);
}
}
// Propagate the original exception on user/role/tenant mapping
if (e instanceof OpenStackBaseException) {
// Convert Keystone Exception to MsoOpenstackException
throw keystoneErrorToMsoException ((OpenStackBaseException) e, "CreateTenantUser");
} else {
MsoAdapterException me = new MsoAdapterException (e.getMessage (), e);
me.addContext ("CreateTenantUser");
throw me;
}
}
return tenant.getId ();
}
/**
* Query for a tenant by ID in the given cloud. If the tenant exists,
* return an MsoTenant object. If not, return null.
* <p>
* For the AIC Cloud (DCP/LCP): it is not clear that cloudId is needed, as all admin
* requests go to the centralized identity service in DCP. However, if some artifact
* must exist in each local LCP instance as well, then it will be needed to access the
* correct region.
* <p>
*
* @param tenantId The Openstack ID of the tenant to query
* @param cloudSiteId The cloud identifier (may be a region) in which to query the tenant.
* @return the tenant properties of the queried tenant, or null if not found
* @throws MsoOpenstackException Thrown if the Openstack API call returns an exception
*/
public MsoTenant queryTenant (String tenantId, String cloudSiteId) throws MsoException {
// Obtain the cloud site information where we will query the tenant
CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
() -> new MsoCloudSiteNotFound(cloudSiteId));
Keystone keystoneAdminClient = getKeystoneAdminClient (cloudSite);
// Check if the tenant exists and return its Tenant Id
try {
Tenant tenant = findTenantById (keystoneAdminClient, tenantId);
if (tenant == null) {
return null;
}
Map <String, String> metadata = new HashMap <String, String> ();
if (cloudConfig.getIdentityService(cloudSite.getIdentityServiceId()).getTenantMetadata ()) {
OpenStackRequest <Metadata> request = keystoneAdminClient.tenants ().showMetadata (tenant.getId ());
Metadata tenantMetadata = executeAndRecordOpenstackRequest (request);
if (tenantMetadata != null) {
metadata = tenantMetadata.getMetadata ();
}
}
return new MsoTenant (tenant.getId (), tenant.getName (), metadata);
} catch (OpenStackBaseException e) {
// Convert Keystone OpenStackResponseException to MsoOpenstackException
throw keystoneErrorToMsoException (e, "QueryTenant");
} catch (RuntimeException e) {
// Catch-all
throw runtimeExceptionToMsoException (e, "QueryTenant");
}
}
/**
* Query for a tenant with the specified name in the given cloud. If the tenant exists,
* return an MsoTenant object. If not, return null. This query is useful if the client
* knows it has the tenant name, skipping an initial lookup by ID that would always fail.
* <p>
* For the AIC Cloud (DCP/LCP): it is not clear that cloudId is needed, as all admin
* requests go to the centralized identity service in DCP. However, if some artifact
* must exist in each local LCP instance as well, then it will be needed to access the
* correct region.
* <p>
*
* @param tenantName The name of the tenant to query
* @param cloudSiteId The cloud identifier (may be a region) in which to query the tenant.
* @return the tenant properties of the queried tenant, or null if not found
* @throws MsoOpenstackException Thrown if the Openstack API call returns an exception
*/
public MsoTenant queryTenantByName (String tenantName, String cloudSiteId) throws MsoException {
// Obtain the cloud site information where we will query the tenant
CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
() -> new MsoCloudSiteNotFound(cloudSiteId));
Keystone keystoneAdminClient = getKeystoneAdminClient (cloudSite);
try {
Tenant tenant = findTenantByName (keystoneAdminClient, tenantName);
if (tenant == null) {
return null;
}
Map <String, String> metadata = new HashMap <String, String> ();
if (cloudConfig.getIdentityService(cloudSite.getIdentityServiceId()).getTenantMetadata ()) {
OpenStackRequest <Metadata> request = keystoneAdminClient.tenants ().showMetadata (tenant.getId ());
Metadata tenantMetadata = executeAndRecordOpenstackRequest (request);
if (tenantMetadata != null) {
metadata = tenantMetadata.getMetadata ();
}
}
return new MsoTenant (tenant.getId (), tenant.getName (), metadata);
} catch (OpenStackBaseException e) {
// Convert Keystone OpenStackResponseException to MsoOpenstackException
throw keystoneErrorToMsoException (e, "QueryTenantName");
} catch (RuntimeException e) {
// Catch-all
throw runtimeExceptionToMsoException (e, "QueryTenantName");
}
}
/**
* Delete the specified Tenant (by ID) in the given cloud. This method returns true or
* false, depending on whether the tenant existed and was successfully deleted, or if
* the tenant already did not exist. Both cases are treated as success (no Exceptions).
* <p>
* Note for the AIC Cloud (DCP/LCP): all admin requests go to the centralized identity
* service in DCP. So deleting a tenant from one cloudSiteId will remove it from all
* sites managed by that identity service.
* <p>
*
* @param tenantId The Openstack ID of the tenant to delete
* @param cloudSiteId The cloud identifier from which to delete the tenant.
* @return true if the tenant was deleted, false if the tenant did not exist.
* @throws MsoOpenstackException If the Openstack API call returns an exception.
*/
public boolean deleteTenant (String tenantId, String cloudSiteId) throws MsoException {
// Obtain the cloud site information where we will query the tenant
CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
() -> new MsoCloudSiteNotFound(cloudSiteId));
Keystone keystoneAdminClient = getKeystoneAdminClient (cloudSite);
try {
// Check that the tenant exists. Also, need the ID to delete
Tenant tenant = findTenantById (keystoneAdminClient, tenantId);
if (tenant == null) {
LOGGER.error(MessageEnum.RA_TENANT_NOT_FOUND, tenantId, cloudSiteId, "", "", MsoLogger.ErrorCode.DataError, "Tenant not found");
return false;
}
OpenStackRequest <Void> request = keystoneAdminClient.tenants ().delete (tenant.getId ());
executeAndRecordOpenstackRequest (request);
LOGGER.debug ("Deleted Tenant " + tenant.getId () + " (" + tenant.getName () + ")");
// Clear any cached clients. Not really needed, ID will not be reused.
msoHeatUtils.expireHeatClient (tenant.getId (), cloudSiteId);
msoNeutronUtils.expireNeutronClient (tenant.getId (), cloudSiteId);
} catch (OpenStackBaseException e) {
// Convert Keystone OpenStackResponseException to MsoOpenstackException
throw keystoneErrorToMsoException (e, "Delete Tenant");
} catch (RuntimeException e) {
// Catch-all
throw runtimeExceptionToMsoException (e, "DeleteTenant");
}
return true;
}
/**
* Delete the specified Tenant (by Name) in the given cloud. This method returns true or
* false, depending on whether the tenant existed and was successfully deleted, or if
* the tenant already did not exist. Both cases are treated as success (no Exceptions).
* <p>
* Note for the AIC Cloud (DCP/LCP): all admin requests go to the centralized identity
* service in DCP. So deleting a tenant from one cloudSiteId will remove it from all
* sites managed by that identity service.
* <p>
*
* @param tenantName The name of the tenant to delete
* @param cloudSiteId The cloud identifier from which to delete the tenant.
* @return true if the tenant was deleted, false if the tenant did not exist.
* @throws MsoOpenstackException If the Openstack API call returns an exception.
*/
public boolean deleteTenantByName (String tenantName, String cloudSiteId) throws MsoException {
// Obtain the cloud site information where we will query the tenant
Optional<CloudSite> cloudSite = cloudConfig.getCloudSite (cloudSiteId);
if (!cloudSite.isPresent()) {
throw new MsoCloudSiteNotFound (cloudSiteId);
}
Keystone keystoneAdminClient = getKeystoneAdminClient (cloudSite.get());
try {
// Need the Tenant ID to delete (can't directly delete by name)
Tenant tenant = findTenantByName (keystoneAdminClient, tenantName);
if (tenant == null) {
// OK if tenant already doesn't exist.
LOGGER.error(MessageEnum.RA_TENANT_NOT_FOUND, tenantName, cloudSiteId, "", "", MsoLogger.ErrorCode.DataError, "Tenant not found");
return false;
}
// Execute the Delete. It has no return value.
OpenStackRequest <Void> request = keystoneAdminClient.tenants ().delete (tenant.getId ());
executeAndRecordOpenstackRequest (request);
LOGGER.debug ("Deleted Tenant " + tenant.getId () + " (" + tenant.getName () + ")");
// Clear any cached clients. Not really needed, ID will not be reused.
msoHeatUtils.expireHeatClient (tenant.getId (), cloudSiteId);
msoNeutronUtils.expireNeutronClient (tenant.getId (), cloudSiteId);
} catch (OpenStackBaseException e) {
// Note: It doesn't seem to matter if tenant doesn't exist, no exception is thrown.
// Convert Keystone OpenStackResponseException to MsoOpenstackException
throw keystoneErrorToMsoException (e, "DeleteTenant");
} catch (RuntimeException e) {
// Catch-all
throw runtimeExceptionToMsoException (e, "DeleteTenant");
}
return true;
}
// -------------------------------------------------------------------
// PRIVATE UTILITY FUNCTIONS FOR USE WITHIN THIS CLASS
/*
* Get a Keystone Admin client for the Openstack Identity service.
* This requires an 'admin'-level userId + password along with an 'admin' tenant
* in the target cloud. These values will be retrieved from properties based
* on the specified cloud ID.
* <p>
* On successful authentication, the Keystone object will be cached for the cloudId
* so that it can be reused without going back to Openstack every time.
*
* @param cloudId
*
* @return an authenticated Keystone object
*/
public Keystone getKeystoneAdminClient (CloudSite cloudSite) throws MsoException {
CloudIdentity cloudIdentity = cloudConfig.getIdentityService(cloudSite.getIdentityServiceId());
String cloudId = cloudIdentity.getId ();
String adminTenantName = cloudIdentity.getAdminTenant ();
String region = cloudSite.getRegionId ();
// Check first in the cache of previously authorized clients
KeystoneCacheEntry entry = adminClientCache.get (cloudId);
if (entry != null) {
if (!entry.isExpired ()) {
return entry.getKeystoneClient ();
} else {
// Token is expired. Remove it from cache.
adminClientCache.remove (cloudId);
}
}
MsoTenantUtils tenantUtils = tenantUtilsFactory.getTenantUtilsByServerType(cloudIdentity.getIdentityServerType());
final String keystoneUrl = tenantUtils.getKeystoneUrl(region, cloudIdentity);
Keystone keystone = new Keystone(keystoneUrl);
// Must authenticate against the 'admin' tenant to get the services endpoints
Access access = null;
String token = null;
try {
Authentication credentials = authenticationMethodFactory.getAuthenticationFor(cloudIdentity);
OpenStackRequest <Access> request = keystone.tokens ()
.authenticate (credentials)
.withTenantName (adminTenantName);
access = executeAndRecordOpenstackRequest (request);
token = access.getToken ().getId ();
} catch (OpenStackResponseException e) {
if (e.getStatus () == 401) {
// Authentication error. Can't access admin tenant - something is mis-configured
String error = "MSO Authentication Failed for " + cloudIdentity.getId ();
alarmLogger.sendAlarm ("MsoAuthenticationError", MsoAlarmLogger.CRITICAL, error);
throw new MsoAdapterException (error);
} else {
throw keystoneErrorToMsoException (e, "TokenAuth");
}
} catch (OpenStackConnectException e) {
// Connection to Openstack failed
throw keystoneErrorToMsoException (e, "TokenAuth");
}
// Get the Identity service URL. Throws runtime exception if not found per region.
String adminUrl = null;
try {
// TODO: FOR TESTING!!!!
adminUrl = KeystoneUtils.findEndpointURL (access.getServiceCatalog (), "identity", region, "public");
adminUrl = adminUrl.replaceFirst("5000", "35357");
} catch (RuntimeException e) {
String error = "Identity service not found: region=" + region + ",cloud=" + cloudIdentity.getId ();
alarmLogger.sendAlarm ("MsoConfigurationError", MsoAlarmLogger.CRITICAL, error);
LOGGER.error(MessageEnum.IDENTITY_SERVICE_NOT_FOUND, region, cloudIdentity.getId(), "Openstack", "", MsoLogger.ErrorCode.DataError, "Exception in findEndpointURL");
throw new MsoAdapterException (error, e);
}
// A new Keystone object is required for the new URL. Use the auth token from above.
// Note: this doesn't go back to Openstack, it's just a local object.
keystone = new Keystone (adminUrl);
keystone.token (token);
// Cache to avoid re-authentication for every call.
KeystoneCacheEntry cacheEntry = new KeystoneCacheEntry (adminUrl, token, access.getToken ().getExpires ());
adminClientCache.put (cloudId, cacheEntry);
return keystone;
}
/*
* Find a tenant (or query its existance) by its Name or Id. Check first against the
* ID. If that fails, then try by name.
*
* @param adminClient an authenticated Keystone object
*
* @param tenantName the tenant name or ID to query
*
* @return a Tenant object or null if not found
*/
public Tenant findTenantByNameOrId (Keystone adminClient, String tenantNameOrId) {
if (tenantNameOrId == null) {
return null;
}
Tenant tenant = findTenantById (adminClient, tenantNameOrId);
if (tenant == null) {
tenant = findTenantByName (adminClient, tenantNameOrId);
}
return tenant;
}
/*
* Find a tenant (or query its existance) by its Id.
*
* @param adminClient an authenticated Keystone object
*
* @param tenantName the tenant ID to query
*
* @return a Tenant object or null if not found
*/
private Tenant findTenantById (Keystone adminClient, String tenantId) {
if (tenantId == null) {
return null;
}
try {
OpenStackRequest <Tenant> request = adminClient.tenants ().show (tenantId);
return executeAndRecordOpenstackRequest (request);
} catch (OpenStackResponseException e) {
if (e.getStatus () == 404) {
return null;
} else {
LOGGER.error(MessageEnum.RA_CONNECTION_EXCEPTION, "Openstack Error, GET Tenant by Id (" + tenantId + "): " + e, "Openstack", "", MsoLogger.ErrorCode.DataError, "Exception in Openstack GET tenant by Id");
throw e;
}
}
}
/*
* Find a tenant (or query its existance) by its Name. This method avoids an
* initial lookup by ID when it's known that we have the tenant Name.
*
* @param adminClient an authenticated Keystone object
*
* @param tenantName the tenant name to query
*
* @return a Tenant object or null if not found
*/
public Tenant findTenantByName (Keystone adminClient, String tenantName) {
if (tenantName == null) {
return null;
}
try {
OpenStackRequest <Tenant> request = adminClient.tenants ().show ("").queryParam ("name", tenantName);
return executeAndRecordOpenstackRequest (request);
} catch (OpenStackResponseException e) {
if (e.getStatus () == 404) {
return null;
} else {
LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, "Openstack Error, GET Tenant By Name (" + tenantName + "): " + e, "Openstack", "", MsoLogger.ErrorCode.DataError, "Exception in Openstack GET Tenant By Name");
throw e;
}
}
}
/*
* Look up an Openstack User by Name or Openstack ID. Check the ID first, and if that
* fails, try the Name.
*
* @param adminClient an authenticated Keystone object
*
* @param userName the user name or ID to query
*
* @return a User object or null if not found
*/
private User findUserByNameOrId (Keystone adminClient, String userNameOrId) {
if (userNameOrId == null) {
return null;
}
try {
OpenStackRequest <User> request = adminClient.users ().show (userNameOrId);
return executeAndRecordOpenstackRequest (request);
} catch (OpenStackResponseException e) {
if (e.getStatus () == 404) {
// Not found by ID. Search for name
return findUserByName (adminClient, userNameOrId);
} else {
LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, "Openstack Error, GET User (" + userNameOrId + "): " + e, "Openstack", "", MsoLogger.ErrorCode.DataError, "Exception in Openstack GET User");
throw e;
}
}
}
/*
* Look up an Openstack User by Name. This avoids initial Openstack query by ID
* if we know we have the User Name.
*
* @param adminClient an authenticated Keystone object
*
* @param userName the user name to query
*
* @return a User object or null if not found
*/
public User findUserByName (Keystone adminClient, String userName) {
if (userName == null) {
return null;
}
try {
OpenStackRequest <User> request = adminClient.users ().show ("").queryParam ("name", userName);
return executeAndRecordOpenstackRequest (request);
} catch (OpenStackResponseException e) {
if (e.getStatus () == 404) {
return null;
} else {
LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, "Openstack Error, GET User By Name (" + userName + "): " + e, "Openstack", "", MsoLogger.ErrorCode.DataError, "Exception in Openstack GET User By Name");
throw e;
}
}
}
/*
* Look up an Openstack Role by Name or Id. There is no direct query for Roles, so
* need to retrieve a full list from Openstack and look for a match. By default,
* Openstack should have a "_member_" role for normal VM-level privileges and an
* "admin" role for expanded privileges (e.g. administer tenants, users, and roles).
* <p>
*
* @param adminClient an authenticated Keystone object
*
* @param roleNameOrId the Role name or ID to look up
*
* @return a Role object
*/
private Role findRoleByNameOrId (Keystone adminClient, String roleNameOrId) {
if (roleNameOrId == null) {
return null;
}
// Search by name or ID. Must search in list
OpenStackRequest <Roles> request = adminClient.roles ().list ();
Roles roles = executeAndRecordOpenstackRequest (request);
for (Role role : roles) {
if (roleNameOrId.equals (role.getName ()) || roleNameOrId.equals (role.getId ())) {
return role;
}
}
return null;
}
private static class KeystoneCacheEntry implements Serializable {
private static final long serialVersionUID = 1L;
private String keystoneUrl;
private String token;
private Calendar expires;
public KeystoneCacheEntry (String url, String token, Calendar expires) {
this.keystoneUrl = url;
this.token = token;
this.expires = expires;
}
public Keystone getKeystoneClient () {
Keystone keystone = new Keystone (keystoneUrl);
keystone.token (token);
return keystone;
}
public boolean isExpired () {
// adding arbitrary guard timer of 5 minutes
return expires == null || System.currentTimeMillis() > (expires.getTimeInMillis() - 300000);
}
}
@Override
public String getKeystoneUrl(String regionId, CloudIdentity cloudIdentity) throws MsoException {
return cloudIdentity.getIdentityUrl();
}
}
|