1e057d147d15450c9b8811386e4957ca606f1b9a
[appc.git] / appc-adapters / appc-iaas-adapter / appc-iaas-adapter-bundle / src / main / java / org / onap / appc / adapter / iaas / impl / ServiceCatalogV3.java
1 /*-\r
2  * ============LICENSE_START=======================================================\r
3  * ONAP : APPC\r
4  * ================================================================================\r
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.\r
6  * ================================================================================\r
7  * Copyright (C) 2017 Amdocs\r
8  * =============================================================================\r
9  * Licensed under the Apache License, Version 2.0 (the "License");\r
10  * you may not use this file except in compliance with the License.\r
11  * You may obtain a copy of the License at\r
12  *\r
13  *      http://www.apache.org/licenses/LICENSE-2.0\r
14  *\r
15  * Unless required by applicable law or agreed to in writing, software\r
16  * distributed under the License is distributed on an "AS IS" BASIS,\r
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
18  * See the License for the specific language governing permissions and\r
19  * limitations under the License.\r
20  *\r
21  * ============LICENSE_END=========================================================\r
22  */\r
23 \r
24 package org.onap.appc.adapter.iaas.impl;\r
25 \r
26 import com.att.cdp.exceptions.ContextConnectionException;\r
27 import com.att.cdp.exceptions.ZoneException;\r
28 import com.att.cdp.openstack.util.ExceptionMapper;\r
29 import com.att.cdp.pal.util.Time;\r
30 import com.att.cdp.zones.ContextFactory;\r
31 import com.att.cdp.zones.spi.RequestState;\r
32 import com.google.common.collect.Lists;\r
33 import com.woorea.openstack.base.client.OpenStackBaseException;\r
34 import com.woorea.openstack.base.client.OpenStackClientConnector;\r
35 import com.woorea.openstack.base.client.OpenStackSimpleTokenProvider;\r
36 import com.woorea.openstack.keystone.v3.Keystone;\r
37 import com.woorea.openstack.keystone.v3.api.TokensResource;\r
38 import com.woorea.openstack.keystone.v3.model.Authentication;\r
39 import com.woorea.openstack.keystone.v3.model.Authentication.Identity;\r
40 import com.woorea.openstack.keystone.v3.model.Authentication.Scope;\r
41 import com.woorea.openstack.keystone.v3.model.Token;\r
42 import com.woorea.openstack.keystone.v3.model.Token.Project;\r
43 import com.woorea.openstack.keystone.v3.model.Token.Service;\r
44 import com.woorea.openstack.keystone.v3.model.Token.Service.Endpoint;\r
45 import java.util.ArrayList;\r
46 import java.util.Calendar;\r
47 import java.util.Date;\r
48 import java.util.HashMap;\r
49 import java.util.HashSet;\r
50 import java.util.List;\r
51 import java.util.Map;\r
52 import java.util.Properties;\r
53 import java.util.Set;\r
54 import java.util.concurrent.locks.Lock;\r
55 import java.util.concurrent.locks.ReentrantReadWriteLock;\r
56 import java.util.regex.Matcher;\r
57 import java.util.regex.Pattern;\r
58 \r
59 /**\r
60  * This class is used to capture and cache the service catalog for a specific OpenStack provider.\r
61  * <p>\r
62  * This is needed because the way the servers are represented in the ECOMP product is as their fully qualified URL's.\r
63  * This is very problematic, because we cant identify their region from the URL, URL's change, and we cant identify the\r
64  * versions of the service implementations. In otherwords, the URL does not provide us enough information.\r
65  * </p>\r
66  * <p>\r
67  * The zone abstraction layer is designed to detect the versions of the services dynamically, and step up or down to\r
68  * match those reported versions. In order to do that, we need to know before hand what region we are accessing (since\r
69  * the supported versions may be different by regions). We will need to authenticate to the identity service in order to\r
70  * do this, plus we have to duplicate the code supporting proxies and trusted hosts that exists in the abstraction\r
71  * layer, but that cant be helped.\r
72  * </p>\r
73  * <p>\r
74  * What we do to circumvent this is connect to the provider using the lowest supported identity api, and read the entire\r
75  * service catalog into this object. Then, we parse the vm URL to extract the host and port and match that to the\r
76  * compute services defined in the catalog. When we find a compute service that has the same host name and port,\r
77  * whatever region that service is supporting is the region for that server.\r
78  * </p>\r
79  * <p>\r
80  * While we really only need to do this for compute nodes, there is no telling what other situations may arise where the\r
81  * full service catalog may be needed. Also, there is very little additional cost (additional RAM) associated with\r
82  * caching the full service catalog since there is no way to list only a portion of it.\r
83  * </p>\r
84  */\r
85 public class ServiceCatalogV3 extends ServiceCatalog {\r
86 \r
87     /**\r
88      * The project that we are accessing\r
89      */\r
90     private Project project;\r
91 \r
92     /**\r
93      * A map of endpoints for each service organized by service type\r
94      */\r
95     private Map<String /* Service Type */, List<Service.Endpoint>> serviceEndpoints;\r
96 \r
97     /**\r
98      * A map of service types that are published\r
99      */\r
100     private Map<String /* Service Type */, Service> serviceTypes;\r
101 \r
102     /**\r
103      * The Openstack Access object that manages the authenticated token and access control\r
104      */\r
105     private Token token;\r
106 \r
107     /**\r
108      * A "token provider" that manages the authentication token that we obtain when logging in\r
109      */\r
110     private OpenStackSimpleTokenProvider tokenProvider;\r
111 \r
112     /**\r
113      * {@inheritDoc}\r
114      */\r
115     public ServiceCatalogV3(String identityURL, String projectIdentifier, String principal, String credential,\r
116         String domain, Properties properties) {\r
117         super(identityURL, projectIdentifier, principal, credential, domain, properties);\r
118     }\r
119 \r
120     /**\r
121      * {@inheritDoc}\r
122      */\r
123     @Override\r
124     public void init() throws ZoneException {\r
125         rwLock = new ReentrantReadWriteLock();\r
126         serviceTypes = new HashMap<>();\r
127         serviceEndpoints = new HashMap<>();\r
128         regions = new HashSet<>();\r
129         Class<?> connectorClass;\r
130         OpenStackClientConnector connector;\r
131         try {\r
132             connectorClass = Class.forName(CLIENT_CONNECTOR_CLASS);\r
133             connector = (OpenStackClientConnector) connectorClass.newInstance();\r
134         } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {\r
135             logger.error("An error occurred when initializing ServiceCatalogV3", e);\r
136             return;\r
137         }\r
138         Keystone keystone = new Keystone(identityURL, connector);\r
139 \r
140         String proxyHost = properties.getProperty(ContextFactory.PROPERTY_PROXY_HOST);\r
141         String proxyPort = properties.getProperty(ContextFactory.PROPERTY_PROXY_PORT);\r
142         String trustedHosts = properties.getProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, ""); //$NON-NLS-1$\r
143         if (proxyHost != null && proxyHost.length() > 0) {\r
144             keystone.getProperties().setProperty(com.woorea.openstack.common.client.Constants.PROXY_HOST, proxyHost);\r
145             keystone.getProperties().setProperty(com.woorea.openstack.common.client.Constants.PROXY_PORT, proxyPort);\r
146         }\r
147         if (trustedHosts != null) {\r
148             keystone.getProperties().setProperty(com.woorea.openstack.common.client.Constants.TRUST_HOST_LIST,\r
149                 trustedHosts);\r
150         }\r
151 \r
152         // create identity\r
153         Identity identity = Identity.password(domain, principal, credential);\r
154 \r
155         // create scope\r
156         Scope scope = initScope();\r
157 \r
158         Authentication authentication = new Authentication();\r
159         authentication.setIdentity(identity);\r
160         authentication.setScope(scope);\r
161 \r
162         TokensResource tokens = keystone.tokens();\r
163         TokensResource.Authenticate authenticate = tokens.authenticate(authentication);\r
164 \r
165         /*\r
166          * We have to set up the TrackRequest TLS collection for the ExceptionMapper\r
167          */\r
168         trackRequest();\r
169         RequestState.put(RequestState.PROVIDER, "OpenStackProvider");\r
170         RequestState.put(RequestState.TENANT, projectIdentifier);\r
171         RequestState.put(RequestState.PRINCIPAL, principal);\r
172 \r
173         try {\r
174             token = authenticate.execute();\r
175             expiresLocal = getLocalExpiration(token);\r
176             project = token.getProject();\r
177             tokenProvider = new OpenStackSimpleTokenProvider(token.getId());\r
178             keystone.setTokenProvider(tokenProvider);\r
179             parseServiceCatalog(token.getCatalog());\r
180         } catch (OpenStackBaseException e) {\r
181             ExceptionMapper.mapException(e);\r
182         } catch (Exception e) {\r
183             throw new ContextConnectionException(e);\r
184         }\r
185     }\r
186 \r
187     private Scope initScope() {\r
188         if (projectIdentifier.length() == 32 && projectIdentifier.matches("[0-9a-fA-F]+")) { //$NON-NLS-1$\r
189             return Scope.project(projectIdentifier);\r
190         } else {\r
191             return Scope.project(domain, projectIdentifier);\r
192         }\r
193     }\r
194 \r
195     /**\r
196      * {@inheritDoc}\r
197      */\r
198     @Override\r
199     public List<Service.Endpoint> getEndpoints(String serviceType) {\r
200         Lock readLock = rwLock.readLock();\r
201         readLock.lock();\r
202         try {\r
203             return serviceEndpoints.get(serviceType);\r
204         } finally {\r
205             readLock.unlock();\r
206         }\r
207     }\r
208 \r
209     /**\r
210      * {@inheritDoc}\r
211      */\r
212     @Override\r
213     public String getProjectId() {\r
214         Lock readLock = rwLock.readLock();\r
215         readLock.lock();\r
216         try {\r
217             return project.getId();\r
218         } finally {\r
219             readLock.unlock();\r
220         }\r
221     }\r
222 \r
223     /**\r
224      * {@inheritDoc}\r
225      */\r
226     @Override\r
227     public String getProjectName() {\r
228         Lock readLock = rwLock.readLock();\r
229         readLock.lock();\r
230         try {\r
231             return project.getName();\r
232         } finally {\r
233             readLock.unlock();\r
234         }\r
235     }\r
236 \r
237     /**\r
238      * {@inheritDoc}\r
239      */\r
240     @Override\r
241     public Set<String> getRegions() {\r
242         Lock readLock = rwLock.readLock();\r
243         readLock.lock();\r
244         try {\r
245             return regions;\r
246         } finally {\r
247             readLock.unlock();\r
248         }\r
249     }\r
250 \r
251     /**\r
252      * {@inheritDoc}\r
253      */\r
254     @Override\r
255     public List<String> getServiceTypes() {\r
256         Lock readLock = rwLock.readLock();\r
257         readLock.lock();\r
258         try {\r
259             ArrayList<String> result = new ArrayList<>();\r
260             result.addAll(serviceTypes.keySet());\r
261             return result;\r
262         } finally {\r
263             readLock.unlock();\r
264         }\r
265     }\r
266 \r
267     /**\r
268      * {@inheritDoc}\r
269      */\r
270     @Override\r
271     public String getVMRegion(VMURL url) {\r
272         String region = null;\r
273         Pattern urlPattern = Pattern.compile("[^:]+://([^:/]+)(?::([0-9]+)).*");\r
274 \r
275         if (url != null) {\r
276             for (Endpoint endpoint : getEndpoints(ServiceCatalog.COMPUTE_SERVICE)) {\r
277                 String endpointUrl = endpoint.getUrl();\r
278                 Matcher matcher = urlPattern.matcher(endpointUrl);\r
279                 if (validateUrl(url, matcher)) {\r
280                     region = endpoint.getRegion();\r
281                     break;\r
282                 }\r
283             }\r
284         }\r
285         return region;\r
286     }\r
287 \r
288     private boolean validateUrl(VMURL url, Matcher matcher) {\r
289         return matcher.matches()\r
290             && url.getHost().equals(matcher.group(1))\r
291             && (url.getPort() == null || url.getPort().equals(matcher.group(2)));\r
292     }\r
293 \r
294     /**\r
295      * {@inheritDoc}\r
296      */\r
297     @Override\r
298     public boolean isServicePublished(String serviceType) {\r
299         Lock readLock = rwLock.readLock();\r
300         readLock.lock();\r
301         try {\r
302             return serviceTypes.containsKey(serviceType);\r
303         } finally {\r
304             readLock.unlock();\r
305         }\r
306     }\r
307 \r
308     /**\r
309      * {@inheritDoc}\r
310      */\r
311     @Override\r
312     public String toString() {\r
313 \r
314         StringBuilder builder = new StringBuilder();\r
315         Lock lock = rwLock.readLock();\r
316         lock.lock();\r
317         try {\r
318             builder.append(String.format("Service Catalog: tenant %s, id[%s]%n", project.getName(), //$NON-NLS-1$\r
319                 project.getId()));\r
320             if (regions != null && !regions.isEmpty()) {\r
321                 builder.append(String.format("%d regions:%n", regions.size())); //$NON-NLS-1$\r
322                 for (String region : regions) {\r
323                     //$NON-NLS-1$ //$NON-NLS-2$\r
324                     builder\r
325                         .append("\t")\r
326                         .append(region)\r
327                         .append("%n");\r
328                 }\r
329             }\r
330             builder.append(String.format("%d services:%n", serviceEndpoints.size())); //$NON-NLS-1$\r
331 \r
332             for (Map.Entry<String, List<Service.Endpoint>> entry : serviceEndpoints.entrySet()) {\r
333                 Service service = serviceTypes.get(entry.getKey());\r
334 \r
335                 builder.append(String.format("\t%s - %d endpoints%n", service.getType(), //$NON-NLS-1$\r
336                     entry.getValue().size()));\r
337 \r
338                 for (Service.Endpoint endpoint : entry.getValue()) {\r
339                     builder\r
340                         .append(String.format("\t\tRegion [%s], public URL [%s]%n", endpoint.getRegion(), //$NON-NLS-1$\r
341                             endpoint.getUrl()));\r
342                 }\r
343             }\r
344         } finally {\r
345             lock.unlock();\r
346         }\r
347 \r
348         return builder.toString();\r
349     }\r
350 \r
351     /**\r
352      * Parses the service catalog and caches the results\r
353      *\r
354      * @param services The list of services published by this provider\r
355      */\r
356     private void parseServiceCatalog(List<Service> services) {\r
357         Lock lock = rwLock.writeLock();\r
358         lock.lock();\r
359         try {\r
360             serviceTypes.clear();\r
361             serviceEndpoints.clear();\r
362             regions.clear();\r
363 \r
364             for (Service service : services) {\r
365                 String type = service.getType();\r
366                 serviceTypes.put(type, service);\r
367                 addRegions(service, type);\r
368             }\r
369         } finally {\r
370             lock.unlock();\r
371         }\r
372     }\r
373 \r
374     private void addRegions(Service service, String type) {\r
375         List<Endpoint> endpoints = service.getEndpoints();\r
376         for (Endpoint endpoint : endpoints) {\r
377             serviceEndpoints.computeIfAbsent(type, val -> new ArrayList<>());\r
378             serviceEndpoints.get(type).add(endpoint);\r
379 \r
380             String region = endpoint.getRegion();\r
381             if (!regions.contains(region)) {\r
382                 regions.add(region);\r
383             }\r
384         }\r
385     }\r
386 \r
387     /**\r
388      * Computes the local time when the access token will expire, after which we will need to re-login to access the\r
389      * provider.\r
390      *\r
391      * @param accessKey The access key used to access the provider\r
392      * @return The local time the key expires\r
393      */\r
394     private static long getLocalExpiration(Token accessToken) {\r
395         Date now = Time.getCurrentUTCDate();\r
396         if (accessToken != null) {\r
397             Calendar issued = accessToken.getIssuedAt();\r
398             Calendar expires = accessToken.getExpiresAt();\r
399             if (issued != null && expires != null) {\r
400                 long tokenLife = expires.getTimeInMillis() - issued.getTimeInMillis();\r
401                 return now.getTime() + tokenLife;\r
402             }\r
403         }\r
404         return now.getTime();\r
405     }\r
406 }