a5988a15649ca5d25b26e372015b998cff6ad48f
[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.togglz.core.manager.FeatureManager;
56
57 /**
58  * The Class VidController.
59  */
60
61 @org.springframework.stereotype.Service
62 public class VidServiceImpl implements VidService {
63     /**
64      * The Constant LOG.
65      */
66     private static final EELFLoggerDelegate LOG = EELFLoggerDelegate.getLogger(VidServiceImpl.class);
67
68     protected final AsdcClient asdcClient;
69     private final FeatureManager featureManager;
70
71     private ToscaParserImpl2 toscaParser;
72     private final LoadingCache<String, ServiceModel> serviceModelCache;
73
74
75     private class NullServiceModelException extends Exception {
76         NullServiceModelException(String modelUuid) {
77             super("Could not create service model for UUID " + modelUuid);
78         }
79     }
80
81     @Autowired
82     public VidServiceImpl(AsdcClient asdcClient, ToscaParserImpl2 toscaParser, FeatureManager featureManager) {
83         this.asdcClient = asdcClient;
84         this.featureManager = featureManager;
85         this.toscaParser=toscaParser;
86         this.serviceModelCache = CacheBuilder.newBuilder()
87                 .maximumSize(1000)
88                 .expireAfterAccess(7, TimeUnit.DAYS)
89                 .build(new CacheLoader<String, ServiceModel>() {
90                     @Override
91                     public ServiceModel load(String modelUuid) throws AsdcCatalogException, NullServiceModelException {
92                         ServiceModel serviceModel = getServiceFromSdc(modelUuid);
93                         if (serviceModel != null) {
94                             return serviceModel;
95                         } else {
96                             throw new NullServiceModelException(modelUuid);
97                         }
98                     }
99                 });
100     }
101
102     /*
103      * (non-Javadoc)
104      *
105      * @see org.onap.vid.controller.VidService#getService(java.lang.String)
106      */
107     @Override
108     public ServiceModel getService(String uuid) throws AsdcCatalogException {
109         if (featureManager.isActive(FLAG_SERVICE_MODEL_CACHE)) {
110             return getServiceFromCache(uuid);
111         } else {
112             return getServiceFromSdc(uuid);
113         }
114     }
115
116     private ServiceModel getServiceFromCache(String uuid) throws AsdcCatalogException {
117         try {
118             return serviceModelCache.get(uuid);
119         } catch (ExecutionException e) {
120             if (e.getCause() instanceof AsdcCatalogException) {
121                 throw (AsdcCatalogException) e.getCause();
122             } else if (e.getCause() instanceof NullServiceModelException) {
123                 return null;
124             } else {
125                 throw new GenericUncheckedException(e);
126             }
127         }
128     }
129
130     private ServiceModel getServiceFromSdc(String uuid) throws AsdcCatalogException {
131         final Path serviceCsar = asdcClient.getServiceToscaModel(UUID.fromString(uuid));
132         ToscaParser tosca = new ToscaParserImpl();
133         serviceCsar.toFile().getAbsolutePath();
134         ServiceModel serviceModel = null;
135         try {
136             final Service asdcServiceMetadata = asdcClient.getService(UUID.fromString(uuid));
137             return getServiceModel(uuid, serviceCsar, tosca, asdcServiceMetadata);
138         } catch (Exception e) {
139             LOG.error("Failed to download and process service from SDC", e);
140         }
141         return serviceModel;
142     }
143
144     private ServiceModel getServiceModel(String uuid, Path serviceCsar, ToscaParser tosca, Service asdcServiceMetadata) throws AsdcCatalogException {
145         try {
146             return toscaParser.makeServiceModel(serviceCsar, asdcServiceMetadata);
147         } catch (SdcToscaParserException e) {
148             return tosca.makeServiceModel(uuid, serviceCsar, asdcServiceMetadata);
149         }
150     }
151
152     @Override
153     public void invalidateServiceCache() {
154         serviceModelCache.invalidateAll();
155     }
156
157     @Override
158     public ExternalComponentStatus probeComponent() {
159         UUID modelUUID;
160         try {
161             modelUUID = UUID.fromString(VidProperties.getPropertyWithDefault(
162                 VidProperties.PROBE_SDC_MODEL_UUID,""));
163         }
164         //in case of no such PROBE_SDC_MODEL_UUID property or non uuid there we check only sdc connectivity
165         catch (Exception e) {
166             return probeComponentBySdcConnectivity();
167         }
168
169         return probeSdcByGettingModel(modelUUID);
170     }
171
172     public ExternalComponentStatus probeComponentBySdcConnectivity() {
173         long startTime = System.currentTimeMillis();
174         ExternalComponentStatus externalComponentStatus;
175         try {
176             HttpResponse<String> stringHttpResponse = asdcClient.checkSDCConnectivity();
177             HttpRequestMetadata httpRequestMetadata = new HttpRequestMetadata(HttpMethod.GET, stringHttpResponse.getStatus(), asdcClient.getBaseUrl() + AsdcClient.URIS.HEALTH_CHECK_ENDPOINT, stringHttpResponse.getBody(), "SDC healthCheck",
178                     System.currentTimeMillis() - startTime);
179             externalComponentStatus = new ExternalComponentStatus(ExternalComponentStatus.Component.SDC, stringHttpResponse.isSuccessful(), httpRequestMetadata);
180         } catch (Exception e) {
181             ErrorMetadata errorMetadata = new ErrorMetadata(Logging.exceptionToDescription(e), System.currentTimeMillis() - startTime);
182             externalComponentStatus = new ExternalComponentStatus(ExternalComponentStatus.Component.SDC, false, errorMetadata);
183         }
184         return externalComponentStatus;
185     }
186
187     protected ExternalComponentStatus probeSdcByGettingModel(UUID modelUUID) {
188         final long startTime = System.currentTimeMillis();
189
190         HttpResponseWithRequestInfo<InputStream> response = null;
191         try {
192             response = asdcClient.getServiceInputStream(modelUUID, true);
193             int responseStatusCode = response.getResponse().getStatus();
194
195             if (responseStatusCode == 404) {
196                 return errorStatus(response, startTime, "model " + modelUUID + " not found in SDC" +
197                     " (consider updating vid probe configuration '" + VidProperties.PROBE_SDC_MODEL_UUID + "')");
198             } else if (responseStatusCode >= 400) {
199                 return errorStatus(response, startTime, "error while retrieving model " + modelUUID + " from SDC");
200             } else {
201                 InputStream inputStreamEntity = response.getResponse().getRawBody();//validate we can read the input steam from the response
202                 if (inputStreamEntity.read() <= 0) {
203                     return errorStatus(response, startTime, "error reading model " + modelUUID + " from SDC");
204                 } else {
205                     // RESPONSE IS SUCCESS
206                     return new ExternalComponentStatus(SDC, true,
207                         new HttpRequestMetadata(response, "OK", startTime, false));
208                 }
209             }
210         } catch (ExceptionWithRequestInfo e) {
211             return new ExternalComponentStatus(SDC, false,
212                 new HttpRequestMetadata(e, System.currentTimeMillis() - startTime));
213         } catch (Exception e) {
214             return errorStatus(response, startTime, Logging.exceptionToDescription(e));
215         }
216     }
217
218     private ExternalComponentStatus errorStatus(HttpResponseWithRequestInfo<InputStream> response, long startTime, String description) {
219         final long duration = System.currentTimeMillis() - startTime;
220         StatusMetadata statusMetadata = (response == null) ?
221             new ErrorMetadata(description, duration) :
222             new HttpRequestMetadata(response, description, duration, true);
223
224         return new ExternalComponentStatus(SDC, false, statusMetadata);
225     }
226 }