aboutsummaryrefslogtreecommitdiffstats
path: root/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/ServiceCatalogV3.java
blob: b1c47e5d549599b1329ea959b756c65a35b8fc81 (plain)
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
/*-
 * ============LICENSE_START=======================================================
 * ONAP : APPC
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Copyright (C) 2017 Amdocs
 * =============================================================================
 * 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.
 * 
 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
 * ============LICENSE_END=========================================================
 */

package org.onap.appc.adapter.iaas.impl;

import com.att.cdp.exceptions.ContextConnectionException;
import com.att.cdp.exceptions.ZoneException;
import com.att.cdp.openstack.util.ExceptionMapper;
import com.att.cdp.pal.util.Time;
import com.att.cdp.zones.ContextFactory;
import com.att.cdp.zones.spi.RequestState;
import com.woorea.openstack.base.client.OpenStackBaseException;
import com.woorea.openstack.base.client.OpenStackClientConnector;
import com.woorea.openstack.base.client.OpenStackSimpleTokenProvider;
import com.woorea.openstack.keystone.v3.Keystone;
import com.woorea.openstack.keystone.v3.api.TokensResource;
import com.woorea.openstack.keystone.v3.model.Authentication;
import com.woorea.openstack.keystone.v3.model.Authentication.Identity;
import com.woorea.openstack.keystone.v3.model.Authentication.Scope;
import com.woorea.openstack.keystone.v3.model.Token;
import com.woorea.openstack.keystone.v3.model.Token.Project;
import com.woorea.openstack.keystone.v3.model.Token.Service;
import com.woorea.openstack.keystone.v3.model.Token.Service.Endpoint;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * This class is used to capture and cache the service catalog for a specific OpenStack provider.
 * <p>
 * This is needed because the way the servers are represented in the ECOMP product is as their fully qualified URL's.
 * This is very problematic, because we cant identify their region from the URL, URL's change, and we cant identify the
 * versions of the service implementations. In otherwords, the URL does not provide us enough information.
 * </p>
 * <p>
 * The zone abstraction layer is designed to detect the versions of the services dynamically, and step up or down to
 * match those reported versions. In order to do that, we need to know before hand what region we are accessing (since
 * the supported versions may be different by regions). We will need to authenticate to the identity service in order to
 * do this, plus we have to duplicate the code supporting proxies and trusted hosts that exists in the abstraction
 * layer, but that cant be helped.
 * </p>
 * <p>
 * What we do to circumvent this is connect to the provider using the lowest supported identity api, and read the entire
 * service catalog into this object. Then, we parse the vm URL to extract the host and port and match that to the
 * compute services defined in the catalog. When we find a compute service that has the same host name and port,
 * whatever region that service is supporting is the region for that server.
 * </p>
 * <p>
 * While we really only need to do this for compute nodes, there is no telling what other situations may arise where the
 * full service catalog may be needed. Also, there is very little additional cost (additional RAM) associated with
 * caching the full service catalog since there is no way to list only a portion of it.
 * </p>
 */
public class ServiceCatalogV3 extends ServiceCatalog {

    /**
     * The project that we are accessing
     */
    private Project project;

    /**
     * A map of endpoints for each service organized by service type
     */
    private Map<String /* Service Type */, List<Service.Endpoint>> serviceEndpoints;

    /**
     * A map of service types that are published
     */
    private Map<String /* Service Type */, Service> serviceTypes;

    /**
     * The Openstack Access object that manages the authenticated token and access control
     */
    private Token token;

    /**
     * A "token provider" that manages the authentication token that we obtain when logging in
     */
    private OpenStackSimpleTokenProvider tokenProvider;

    /**
     * {@inheritDoc}
     */
    public ServiceCatalogV3(String identityURL, String projectIdentifier, String principal, String credential,
            String domain, Properties properties) {
        super(identityURL, projectIdentifier, principal, credential, domain, properties);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void init() throws ZoneException {
        rwLock = new ReentrantReadWriteLock();
        serviceTypes = new HashMap<>();
        serviceEndpoints = new HashMap<>();
        regions = new HashSet<>();
        Class<?> connectorClass;
        OpenStackClientConnector connector;
        try {
            connectorClass = Class.forName(CLIENT_CONNECTOR_CLASS);
            connector = (OpenStackClientConnector) connectorClass.newInstance();
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
            return;
        }
        Keystone keystone = new Keystone(identityURL, connector);

        String proxyHost = properties.getProperty(ContextFactory.PROPERTY_PROXY_HOST);
        String proxyPort = properties.getProperty(ContextFactory.PROPERTY_PROXY_PORT);
        String trustedHosts = properties.getProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, ""); //$NON-NLS-1$
        if (proxyHost != null && proxyHost.length() > 0) {
            keystone.getProperties().setProperty(com.woorea.openstack.common.client.Constants.PROXY_HOST, proxyHost);
            keystone.getProperties().setProperty(com.woorea.openstack.common.client.Constants.PROXY_PORT, proxyPort);
        }
        if (trustedHosts != null) {
            keystone.getProperties().setProperty(com.woorea.openstack.common.client.Constants.TRUST_HOST_LIST,
                    trustedHosts);
        }

        // create identity
        Identity identity = Identity.password(domain, principal, credential);

        // create scope
        Scope scope = null;
        if (projectIdentifier.length() == 32 && projectIdentifier.matches("[0-9a-fA-F]+")) { //$NON-NLS-1$
            // authenticate = authenticate.withTenantId(projectIdentifier);
            scope = Scope.project(projectIdentifier);
        } else {
            // authenticate = authenticate.withTenantName(projectIdentifier);
            scope = Scope.project(domain, projectIdentifier);
        }

        Authentication authentication = new Authentication();
        authentication.setIdentity(identity);
        authentication.setScope(scope);

        TokensResource tokens = keystone.tokens();
        TokensResource.Authenticate authenticate = tokens.authenticate(authentication);

        /*
         * We have to set up the TrackRequest TLS collection for the ExceptionMapper
         */
        trackRequest();
        RequestState.put(RequestState.PROVIDER, "OpenStackProvider");
        RequestState.put(RequestState.TENANT, projectIdentifier);
        RequestState.put(RequestState.PRINCIPAL, principal);

        try {
            token = authenticate.execute();
            expiresLocal = getLocalExpiration(token);
            project = token.getProject();
            tokenProvider = new OpenStackSimpleTokenProvider(token.getId());
            keystone.setTokenProvider(tokenProvider);
            parseServiceCatalog(token.getCatalog());
        } catch (OpenStackBaseException e) {
            ExceptionMapper.mapException(e);
        } catch (Exception ex) {
            throw new ContextConnectionException(ex.getMessage());
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<Service.Endpoint> getEndpoints(String serviceType) {
        Lock readLock = rwLock.readLock();
        readLock.lock();
        try {
            return serviceEndpoints.get(serviceType);
        } finally {
            readLock.unlock();
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getProjectId() {
        Lock readLock = rwLock.readLock();
        readLock.lock();
        try {
            return project.getId();
        } finally {
            readLock.unlock();
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getProjectName() {
        Lock readLock = rwLock.readLock();
        readLock.lock();
        try {
            return project.getName();
        } finally {
            readLock.unlock();
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Set<String> getRegions() {
        Lock readLock = rwLock.readLock();
        readLock.lock();
        try {
            return regions;
        } finally {
            readLock.unlock();
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<String> getServiceTypes() {
        Lock readLock = rwLock.readLock();
        readLock.lock();
        try {
            ArrayList<String> result = new ArrayList<>();
            result.addAll(serviceTypes.keySet());
            return result;
        } finally {
            readLock.unlock();
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getVMRegion(VMURL url) {
        String region = null;
        Pattern urlPattern = Pattern.compile("[^:]+://([^:/]+)(?::([0-9]+)).*");

        if (url != null) {
            for (Endpoint endpoint : getEndpoints(ServiceCatalog.COMPUTE_SERVICE)) {
                String endpointUrl = endpoint.getUrl();
                Matcher matcher = urlPattern.matcher(endpointUrl);
                if (matcher.matches()) {
                    if (url.getHost().equals(matcher.group(1))) {
                        if (url.getPort() != null) {
                            if (!url.getPort().equals(matcher.group(2))) {
                                continue;
                            }
                        }

                        region = endpoint.getRegion();
                        break;
                    }
                }
            }
        }
        return region;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isServicePublished(String serviceType) {
        Lock readLock = rwLock.readLock();
        readLock.lock();
        try {
            return serviceTypes.containsKey(serviceType);
        } finally {
            readLock.unlock();
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String toString() {

        StringBuilder builder = new StringBuilder();
        Lock lock = rwLock.readLock();
        lock.lock();
        try {
            builder.append(String.format("Service Catalog: tenant %s, id[%s]\n", project.getName(), //$NON-NLS-1$
                    project.getId()));
            if (regions != null && !regions.isEmpty()) {
                builder.append(String.format("%d regions:\n", regions.size())); //$NON-NLS-1$
                for (String region : regions) {
                    builder.append("\t" + region + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
                }
            }
            builder.append(String.format("%d services:\n", serviceEndpoints.size())); //$NON-NLS-1$
            for (String serviceType : serviceEndpoints.keySet()) {
                List<Service.Endpoint> endpoints = serviceEndpoints.get(serviceType);
                Service service = serviceTypes.get(serviceType);

                builder.append(String.format("\t%s - %d endpoints\n", service.getType(), //$NON-NLS-1$
                        endpoints.size()));
                for (Service.Endpoint endpoint : endpoints) {
                    builder.append(String.format("\t\tRegion [%s], public URL [%s]\n", endpoint.getRegion(), //$NON-NLS-1$
                            endpoint.getUrl()));
                }
            }
        } finally {
            lock.unlock();
        }

        return builder.toString();
    }

    /**
     * Parses the service catalog and caches the results
     * 
     * @param services The list of services published by this provider
     */
    private void parseServiceCatalog(List<Service> services) {
        Lock lock = rwLock.writeLock();
        lock.lock();
        try {
            serviceTypes.clear();
            serviceEndpoints.clear();
            regions.clear();

            for (Service service : services) {
                String type = service.getType();
                serviceTypes.put(type, service);

                List<Service.Endpoint> endpoints = service.getEndpoints();
                for (Service.Endpoint endpoint : endpoints) {
                    List<Service.Endpoint> endpointList = serviceEndpoints.get(type);
                    if (endpointList == null) {
                        endpointList = new ArrayList<>();
                        serviceEndpoints.put(type, endpointList);
                    }
                    endpointList.add(endpoint);

                    String region = endpoint.getRegion();
                    if (!regions.contains(region)) {
                        regions.add(region);
                    }
                }
            }
        } finally {
            lock.unlock();
        }
    }

    /**
     * Computes the local time when the access token will expire, after which we will need to re-login to access the
     * provider.
     * 
     * @param accessKey The access key used to access the provider
     * @return The local time the key expires
     */
    private static long getLocalExpiration(Token accessToken) {
        Date now = Time.getCurrentUTCDate();
        if (accessToken != null) {
            Calendar issued = accessToken.getIssuedAt();
            Calendar expires = accessToken.getExpiresAt();
            if (issued != null && expires != null) {
                long tokenLife = expires.getTimeInMillis() - issued.getTimeInMillis();
                return now.getTime() + tokenLife;
            }
        }
        return now.getTime();
    }
}