Topology tree: enrich vfModules data from other versions of same model
[vid.git] / vid-app-common / src / main / java / org / onap / vid / services / VidServiceImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * VID
4  * ================================================================================
5  * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2018 - 2019 Nokia. All rights reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21 package org.onap.vid.services;
22
23 import static org.onap.vid.model.probes.ExternalComponentStatus.Component.SDC;
24 import static org.onap.vid.properties.Features.FLAG_SERVICE_MODEL_CACHE;
25
26 import com.google.common.cache.CacheBuilder;
27 import com.google.common.cache.CacheLoader;
28 import com.google.common.cache.LoadingCache;
29 import io.joshworks.restclient.http.HttpResponse;
30 import java.io.InputStream;
31 import java.nio.file.Path;
32 import java.util.UUID;
33 import java.util.concurrent.ExecutionException;
34 import java.util.concurrent.TimeUnit;
35 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
36 import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException;
37 import org.onap.vid.aai.ExceptionWithRequestInfo;
38 import org.onap.vid.aai.HttpResponseWithRequestInfo;
39 import org.onap.vid.asdc.AsdcCatalogException;
40 import org.onap.vid.asdc.AsdcClient;
41 import org.onap.vid.asdc.beans.Service;
42 import org.onap.vid.asdc.parser.ToscaParser;
43 import org.onap.vid.asdc.parser.ToscaParserImpl;
44 import org.onap.vid.asdc.parser.ToscaParserImpl2;
45 import org.onap.vid.exceptions.GenericUncheckedException;
46 import org.onap.vid.model.ServiceModel;
47 import org.onap.vid.model.probes.ErrorMetadata;
48 import org.onap.vid.model.probes.ExternalComponentStatus;
49 import org.onap.vid.model.probes.HttpRequestMetadata;
50 import org.onap.vid.model.probes.StatusMetadata;
51 import org.onap.vid.properties.VidProperties;
52 import org.onap.vid.utils.Logging;
53 import org.springframework.beans.factory.annotation.Autowired;
54 import org.springframework.http.HttpMethod;
55 import org.springframework.lang.NonNull;
56 import org.togglz.core.manager.FeatureManager;
57
58 /**
59  * The Class VidController.
60  */
61
62 @org.springframework.stereotype.Service
63 public class VidServiceImpl implements VidService {
64     /**
65      * The Constant LOG.
66      */
67     private static final EELFLoggerDelegate LOG = EELFLoggerDelegate.getLogger(VidServiceImpl.class);
68
69     protected final AsdcClient asdcClient;
70     private final FeatureManager featureManager;
71
72     private ToscaParserImpl2 toscaParser;
73     private final LoadingCache<String, ServiceModel> serviceModelCache;
74
75
76     private class NullServiceModelException extends Exception {
77         NullServiceModelException(String modelUuid) {
78             super("Could not create service model for UUID " + modelUuid);
79         }
80     }
81
82     @Autowired
83     public VidServiceImpl(AsdcClient asdcClient, ToscaParserImpl2 toscaParser, FeatureManager featureManager) {
84         this.asdcClient = asdcClient;
85         this.featureManager = featureManager;
86         this.toscaParser=toscaParser;
87         this.serviceModelCache = CacheBuilder.newBuilder()
88                 .maximumSize(1000)
89                 .expireAfterAccess(7, TimeUnit.DAYS)
90                 .build(new CacheLoader<String, ServiceModel>() {
91                     @Override
92                     public ServiceModel load(String modelUuid) throws AsdcCatalogException, NullServiceModelException {
93                         ServiceModel serviceModel = getServiceFromSdc(modelUuid);
94                         if (serviceModel != null) {
95                             return serviceModel;
96                         } else {
97                             throw new NullServiceModelException(modelUuid);
98                         }
99                     }
100                 });
101     }
102
103     @Override
104     public ServiceModel getService(String uuid) throws AsdcCatalogException {
105         if (featureManager.isActive(FLAG_SERVICE_MODEL_CACHE)) {
106             return getServiceFromCache(uuid);
107         } else {
108             return getServiceFromSdc(uuid);
109         }
110     }
111
112     @NonNull
113     @Override
114     public ServiceModel getServiceModelOrThrow(String modelVersionId) {
115         try {
116             final ServiceModel serviceModel = getService(modelVersionId);
117             if (serviceModel == null) {
118                 throw new GenericUncheckedException("Model version '" + modelVersionId + "' not found");
119             }
120             return serviceModel;
121         } catch (AsdcCatalogException e) {
122             throw new GenericUncheckedException("Exception while loading model version '" + modelVersionId + "'", e);
123         }
124     }
125
126     private ServiceModel getServiceFromCache(String uuid) throws AsdcCatalogException {
127         try {
128             return serviceModelCache.get(uuid);
129         } catch (ExecutionException e) {
130             if (e.getCause() instanceof AsdcCatalogException) {
131                 throw (AsdcCatalogException) e.getCause();
132             } else if (e.getCause() instanceof NullServiceModelException) {
133                 return null;
134             } else {
135                 throw new GenericUncheckedException(e);
136             }
137         }
138     }
139
140     private ServiceModel getServiceFromSdc(String uuid) throws AsdcCatalogException {
141         final Path serviceCsar = asdcClient.getServiceToscaModel(UUID.fromString(uuid));
142         ToscaParser tosca = new ToscaParserImpl();
143         serviceCsar.toFile().getAbsolutePath();
144         ServiceModel serviceModel = null;
145         try {
146             final Service asdcServiceMetadata = asdcClient.getService(UUID.fromString(uuid));
147             return getServiceModel(uuid, serviceCsar, tosca, asdcServiceMetadata);
148         } catch (Exception e) {
149             LOG.error("Failed to download and process service from SDC", e);
150         }
151         return serviceModel;
152     }
153
154     private ServiceModel getServiceModel(String uuid, Path serviceCsar, ToscaParser tosca, Service asdcServiceMetadata) throws AsdcCatalogException {
155         try {
156             return toscaParser.makeServiceModel(serviceCsar, asdcServiceMetadata);
157         } catch (SdcToscaParserException e) {
158             return tosca.makeServiceModel(uuid, serviceCsar, asdcServiceMetadata);
159         }
160     }
161
162     @Override
163     public void invalidateServiceCache() {
164         serviceModelCache.invalidateAll();
165     }
166
167     @Override
168     public ExternalComponentStatus probeComponent() {
169         UUID modelUUID;
170         try {
171             modelUUID = UUID.fromString(VidProperties.getPropertyWithDefault(
172                 VidProperties.PROBE_SDC_MODEL_UUID,""));
173         }
174         //in case of no such PROBE_SDC_MODEL_UUID property or non uuid there we check only sdc connectivity
175         catch (Exception e) {
176             return probeComponentBySdcConnectivity();
177         }
178
179         return probeSdcByGettingModel(modelUUID);
180     }
181
182     public ExternalComponentStatus probeComponentBySdcConnectivity() {
183         long startTime = System.currentTimeMillis();
184         ExternalComponentStatus externalComponentStatus;
185         try {
186             HttpResponse<String> stringHttpResponse = asdcClient.checkSDCConnectivity();
187             HttpRequestMetadata httpRequestMetadata = new HttpRequestMetadata(HttpMethod.GET, stringHttpResponse.getStatus(), asdcClient.getBaseUrl() + AsdcClient.URIS.HEALTH_CHECK_ENDPOINT, stringHttpResponse.getBody(), "SDC healthCheck",
188                     System.currentTimeMillis() - startTime);
189             externalComponentStatus = new ExternalComponentStatus(ExternalComponentStatus.Component.SDC, stringHttpResponse.isSuccessful(), httpRequestMetadata);
190         } catch (Exception e) {
191             ErrorMetadata errorMetadata = new ErrorMetadata(Logging.exceptionToDescription(e), System.currentTimeMillis() - startTime);
192             externalComponentStatus = new ExternalComponentStatus(ExternalComponentStatus.Component.SDC, false, errorMetadata);
193         }
194         return externalComponentStatus;
195     }
196
197     protected ExternalComponentStatus probeSdcByGettingModel(UUID modelUUID) {
198         final long startTime = System.currentTimeMillis();
199
200         HttpResponseWithRequestInfo<InputStream> response = null;
201         try {
202             response = asdcClient.getServiceInputStream(modelUUID, true);
203             int responseStatusCode = response.getResponse().getStatus();
204
205             if (responseStatusCode == 404) {
206                 return errorStatus(response, startTime, "model " + modelUUID + " not found in SDC" +
207                     " (consider updating vid probe configuration '" + VidProperties.PROBE_SDC_MODEL_UUID + "')");
208             } else if (responseStatusCode >= 400) {
209                 return errorStatus(response, startTime, "error while retrieving model " + modelUUID + " from SDC");
210             } else {
211                 InputStream inputStreamEntity = response.getResponse().getRawBody();//validate we can read the input steam from the response
212                 if (inputStreamEntity.read() <= 0) {
213                     return errorStatus(response, startTime, "error reading model " + modelUUID + " from SDC");
214                 } else {
215                     // RESPONSE IS SUCCESS
216                     return new ExternalComponentStatus(SDC, true,
217                         new HttpRequestMetadata(response, "OK", startTime, false));
218                 }
219             }
220         } catch (ExceptionWithRequestInfo e) {
221             return new ExternalComponentStatus(SDC, false,
222                 new HttpRequestMetadata(e, System.currentTimeMillis() - startTime));
223         } catch (Exception e) {
224             return errorStatus(response, startTime, Logging.exceptionToDescription(e));
225         }
226     }
227
228     private ExternalComponentStatus errorStatus(HttpResponseWithRequestInfo<InputStream> response, long startTime, String description) {
229         final long duration = System.currentTimeMillis() - startTime;
230         StatusMetadata statusMetadata = (response == null) ?
231             new ErrorMetadata(description, duration) :
232             new HttpRequestMetadata(response, description, duration, true);
233
234         return new ExternalComponentStatus(SDC, false, statusMetadata);
235     }
236 }