8fbccaaf69b9ef664ab9dd4bffe2c694031e5465
[so.git] / adapters / mso-adapter-utils / src / main / java / org / onap / so / cloud / authentication / KeystoneV3Authentication.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.so.cloud.authentication;
22
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.List;
26 import java.util.concurrent.TimeUnit;
27 import java.util.function.Predicate;
28
29 import org.onap.so.config.beans.PoConfig;
30 import org.onap.so.db.catalog.beans.CloudIdentity;
31 import org.onap.so.db.catalog.beans.CloudSite;
32 import org.onap.so.openstack.exceptions.MsoException;
33 import org.onap.so.openstack.utils.MsoTenantUtils;
34 import org.onap.so.openstack.utils.MsoTenantUtilsFactory;
35 import org.springframework.beans.factory.annotation.Autowired;
36 import org.springframework.stereotype.Component;
37
38 import com.woorea.openstack.base.client.OpenStackConnectException;
39 import com.woorea.openstack.base.client.OpenStackRequest;
40 import com.woorea.openstack.base.client.OpenStackResponse;
41 import com.woorea.openstack.base.client.OpenStackResponseException;
42 import com.woorea.openstack.keystone.v3.Keystone;
43 import com.woorea.openstack.keystone.v3.model.Authentication;
44 import com.woorea.openstack.keystone.v3.model.Token;
45 import com.woorea.openstack.keystone.v3.model.Token.Service;
46
47 import net.jodah.failsafe.Failsafe;
48 import net.jodah.failsafe.RetryPolicy;
49
50
51 @Component
52 public class KeystoneV3Authentication {
53
54         @Autowired
55     private AuthenticationMethodFactory authenticationMethodFactory;
56     
57     @Autowired
58     private MsoTenantUtilsFactory tenantUtilsFactory;
59     
60     @Autowired
61         private PoConfig poConfig;
62         
63         public KeystoneAuthHolder getToken(CloudSite cloudSite, String tenantId, String type) throws MsoException {
64                 
65                 String cloudId = cloudSite.getId();
66         String region = cloudSite.getRegionId();
67
68                 CloudIdentity cloudIdentity = cloudSite.getIdentityService();
69                 MsoTenantUtils tenantUtils = tenantUtilsFactory.getTenantUtilsByServerType(cloudIdentity.getIdentityServerType());
70         String keystoneUrl = tenantUtils.getKeystoneUrl(cloudId, cloudIdentity);
71         Keystone keystoneTenantClient = new Keystone (keystoneUrl);
72         Authentication v3Credentials = authenticationMethodFactory.getAuthenticationForV3(cloudIdentity, tenantId);
73
74
75         OpenStackRequest<Token> v3Request = keystoneTenantClient.tokens ()
76                 .authenticate(v3Credentials);
77         
78         KeystoneAuthHolder holder = makeRequest(v3Request, type, region);
79
80                 return holder;
81         }
82         
83         protected KeystoneAuthHolder makeRequest(OpenStackRequest<Token> v3Request, String type, String region) {
84                 
85                 OpenStackResponse response = Failsafe.with(createRetryPolicy()).get(() -> {
86                         return v3Request.request();
87                 });
88                 String id = response.header("X-Subject-Token");
89                 Token token = response.getEntity(Token.class);
90                 KeystoneAuthHolder result = new KeystoneAuthHolder();
91                 result.setId(id);
92                 result.setexpiration(token.getExpiresAt());
93                 result.setHeatUrl(findEndpointURL(token.getCatalog(), type, region, "public"));
94                 return result;
95         }
96         
97         protected RetryPolicy createRetryPolicy() {
98                 RetryPolicy policy = new RetryPolicy();
99                 List<Predicate<Throwable>> result = new ArrayList<>();
100                 result.add(e -> {
101                         return e.getCause() instanceof OpenStackResponseException 
102                                         && Arrays.asList(poConfig.getRetryCodes().split(","))
103                                         .contains(Integer.toString(((OpenStackResponseException)e).getStatus()));
104                 });
105                 result.add(e -> {
106                         return e.getCause() instanceof OpenStackConnectException;
107                 });
108                 
109                 Predicate<Throwable> pred = result.stream().reduce(Predicate::or).orElse(x -> false);
110
111                 policy.retryOn(error -> pred.test(error));
112                 
113                 policy.withDelay(poConfig.getRetryDelay(), TimeUnit.SECONDS)
114                 .withMaxRetries(poConfig.getRetryCount());
115                 
116                 return policy;
117         }
118         
119         protected String findEndpointURL(List<Service> serviceCatalog, String type, String region, String facing) {
120                 for(Service service : serviceCatalog) {
121                         if(type.equals(service.getType())) {
122                                 for(Service.Endpoint endpoint : service.getEndpoints()) {
123                                         if(region == null || region.equals(endpoint.getRegion())) {
124                                                 if(facing.equals(endpoint.getInterface())) {
125                                                         return endpoint.getUrl();
126                                                 }
127                                         }
128                                 }
129                         }
130                 }
131                 throw new ServiceEndpointNotFoundException("endpoint url not found: type:" + type +" region: " + region + " facing: " + facing);
132         }
133 }