16906957a705104497a7042df45ec2eed6d6e88c
[so.git] /
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.time.Duration;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.List;
27 import java.util.function.Predicate;
28 import org.onap.so.config.beans.PoConfig;
29 import org.onap.so.db.catalog.beans.CloudIdentity;
30 import org.onap.so.db.catalog.beans.CloudSite;
31 import org.onap.so.openstack.exceptions.MsoException;
32 import org.onap.so.openstack.utils.MsoTenantUtils;
33 import org.onap.so.openstack.utils.MsoTenantUtilsFactory;
34 import org.springframework.beans.factory.annotation.Autowired;
35 import org.springframework.stereotype.Component;
36 import com.woorea.openstack.base.client.OpenStackConnectException;
37 import com.woorea.openstack.base.client.OpenStackRequest;
38 import com.woorea.openstack.base.client.OpenStackResponse;
39 import com.woorea.openstack.base.client.OpenStackResponseException;
40 import com.woorea.openstack.keystone.v3.Keystone;
41 import com.woorea.openstack.keystone.v3.model.Authentication;
42 import com.woorea.openstack.keystone.v3.model.Token;
43 import com.woorea.openstack.keystone.v3.model.Token.Service;
44 import net.jodah.failsafe.Failsafe;
45 import net.jodah.failsafe.RetryPolicy;
46
47
48 @Component
49 public class KeystoneV3Authentication {
50
51     @Autowired
52     private AuthenticationMethodFactory authenticationMethodFactory;
53
54     @Autowired
55     private MsoTenantUtilsFactory tenantUtilsFactory;
56
57     @Autowired
58     private PoConfig poConfig;
59
60     public KeystoneAuthHolder getToken(CloudSite cloudSite, String tenantId, String type) throws MsoException {
61
62         String cloudId = cloudSite.getId();
63         String region = cloudSite.getRegionId();
64
65         CloudIdentity cloudIdentity = cloudSite.getIdentityService();
66         MsoTenantUtils tenantUtils =
67                 tenantUtilsFactory.getTenantUtilsByServerType(cloudIdentity.getIdentityServerType());
68         String keystoneUrl = tenantUtils.getKeystoneUrl(cloudId, cloudIdentity);
69         Keystone keystoneTenantClient = new Keystone(keystoneUrl);
70         Authentication v3Credentials = authenticationMethodFactory.getAuthenticationForV3(cloudIdentity, tenantId);
71
72
73         OpenStackRequest<Token> v3Request = keystoneTenantClient.tokens().authenticate(v3Credentials);
74
75         return makeRequest(v3Request, type, region);
76     }
77
78     protected KeystoneAuthHolder makeRequest(OpenStackRequest<Token> v3Request, String type, String region) {
79
80         OpenStackResponse response = Failsafe.with(createRetryPolicy()).get(() -> {
81             return v3Request.request();
82         });
83         String id = response.header("X-Subject-Token");
84         Token token = response.getEntity(Token.class);
85         KeystoneAuthHolder result = new KeystoneAuthHolder();
86         result.setId(id);
87         result.setexpiration(token.getExpiresAt());
88         result.setServiceUrl(findEndpointURL(token.getCatalog(), type, region, "public"));
89         return result;
90     }
91
92     protected RetryPolicy<OpenStackResponse> createRetryPolicy() {
93         List<Predicate<Throwable>> result = new ArrayList<>();
94         result.add(e -> {
95             return e.getCause() instanceof OpenStackResponseException
96                     && Arrays.asList(poConfig.getRetryCodes().split(","))
97                             .contains(Integer.toString(((OpenStackResponseException) e).getStatus()));
98         });
99         result.add(e -> {
100             return e.getCause() instanceof OpenStackConnectException;
101         });
102
103         Predicate<Throwable> pred = result.stream().reduce(Predicate::or).orElse(x -> false);
104         RetryPolicy<OpenStackResponse> policy = new RetryPolicy<OpenStackResponse>().handleIf(error -> pred.test(error))
105                 .withDelay(Duration.ofSeconds(poConfig.getRetryDelay())).withMaxRetries(poConfig.getRetryCount());
106
107         return policy;
108     }
109
110     protected String findEndpointURL(List<Service> serviceCatalog, String type, String region, String facing) {
111         for (Service service : serviceCatalog) {
112             if (type.equals(service.getType())) {
113                 for (Service.Endpoint endpoint : service.getEndpoints()) {
114                     if (region == null || region.equals(endpoint.getRegion())) {
115                         if (facing.equals(endpoint.getInterface())) {
116                             return endpoint.getUrl();
117                         }
118                     }
119                 }
120             }
121         }
122         throw new ServiceEndpointNotFoundException(
123                 "endpoint url not found: type:" + type + " region: " + region + " facing: " + facing);
124     }
125 }