Merge "Send logs to logstash"
[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 com.google.common.cache.CacheBuilder;
24 import com.google.common.cache.CacheLoader;
25 import com.google.common.cache.LoadingCache;
26 import io.joshworks.restclient.http.HttpResponse;
27 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
28 import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException;
29 import org.onap.vid.asdc.AsdcCatalogException;
30 import org.onap.vid.asdc.AsdcClient;
31 import org.onap.vid.asdc.beans.Service;
32 import org.onap.vid.asdc.parser.ToscaParser;
33 import org.onap.vid.asdc.parser.ToscaParserImpl;
34 import org.onap.vid.asdc.parser.ToscaParserImpl2;
35 import org.onap.vid.exceptions.GenericUncheckedException;
36 import org.onap.vid.model.ServiceModel;
37 import org.onap.vid.model.probes.ExternalComponentStatus;
38 import org.onap.vid.model.probes.HttpRequestMetadata;
39 import org.onap.vid.utils.Logging;
40 import org.springframework.beans.factory.annotation.Autowired;
41 import org.springframework.http.HttpMethod;
42 import org.togglz.core.manager.FeatureManager;
43
44 import java.nio.file.Path;
45 import java.util.UUID;
46 import java.util.concurrent.ExecutionException;
47 import java.util.concurrent.TimeUnit;
48
49 import static org.onap.vid.properties.Features.FLAG_SERVICE_MODEL_CACHE;
50
51 /**
52  * The Class VidController.
53  */
54
55 @org.springframework.stereotype.Service
56 public class VidServiceImpl implements VidService {
57     /**
58      * The Constant LOG.
59      */
60     private static final EELFLoggerDelegate LOG = EELFLoggerDelegate.getLogger(VidServiceImpl.class);
61
62     protected final AsdcClient asdcClient;
63     private final FeatureManager featureManager;
64
65     private ToscaParserImpl2 toscaParser;
66     private final LoadingCache<String, ServiceModel> serviceModelCache;
67
68
69     private class NullServiceModelException extends Exception {
70         NullServiceModelException(String modelUuid) {
71             super("Could not create service model for UUID " + modelUuid);
72         }
73     }
74
75     @Autowired
76     public VidServiceImpl(AsdcClient asdcClient, ToscaParserImpl2 toscaParser, FeatureManager featureManager) {
77         this.asdcClient = asdcClient;
78         this.featureManager = featureManager;
79         this.toscaParser=toscaParser;
80         this.serviceModelCache = CacheBuilder.newBuilder()
81                 .maximumSize(1000)
82                 .expireAfterAccess(7, TimeUnit.DAYS)
83                 .build(new CacheLoader<String, ServiceModel>() {
84                     @Override
85                     public ServiceModel load(String modelUuid) throws AsdcCatalogException, NullServiceModelException {
86                         ServiceModel serviceModel = getServiceFromSdc(modelUuid);
87                         if (serviceModel != null) {
88                             return serviceModel;
89                         } else {
90                             throw new NullServiceModelException(modelUuid);
91                         }
92                     }
93                 });
94     }
95
96     /*
97      * (non-Javadoc)
98      *
99      * @see org.onap.vid.controller.VidService#getService(java.lang.String)
100      */
101     @Override
102     public ServiceModel getService(String uuid) throws AsdcCatalogException {
103         if (featureManager.isActive(FLAG_SERVICE_MODEL_CACHE)) {
104             return getServiceFromCache(uuid);
105         } else {
106             return getServiceFromSdc(uuid);
107         }
108     }
109
110     private ServiceModel getServiceFromCache(String uuid) throws AsdcCatalogException {
111         try {
112             return serviceModelCache.get(uuid);
113         } catch (ExecutionException e) {
114             if (e.getCause() instanceof AsdcCatalogException) {
115                 throw (AsdcCatalogException) e.getCause();
116             } else if (e.getCause() instanceof NullServiceModelException) {
117                 return null;
118             } else {
119                 throw new GenericUncheckedException(e);
120             }
121         }
122     }
123
124     private ServiceModel getServiceFromSdc(String uuid) throws AsdcCatalogException {
125         final Path serviceCsar = asdcClient.getServiceToscaModel(UUID.fromString(uuid));
126         ToscaParser tosca = new ToscaParserImpl();
127         serviceCsar.toFile().getAbsolutePath();
128         ServiceModel serviceModel = null;
129         try {
130             final Service asdcServiceMetadata = asdcClient.getService(UUID.fromString(uuid));
131             return getServiceModel(uuid, serviceCsar, tosca, asdcServiceMetadata);
132         } catch (Exception e) {
133             LOG.error("Failed to download and process service from SDC", e);
134         }
135         return serviceModel;
136     }
137
138     private ServiceModel getServiceModel(String uuid, Path serviceCsar, ToscaParser tosca, Service asdcServiceMetadata) throws AsdcCatalogException {
139         try {
140             return toscaParser.makeServiceModel(serviceCsar, asdcServiceMetadata);
141         } catch (SdcToscaParserException e) {
142             return tosca.makeServiceModel(uuid, serviceCsar, asdcServiceMetadata);
143         }
144     }
145
146     @Override
147     public void invalidateServiceCache() {
148         serviceModelCache.invalidateAll();
149     }
150
151     @Override
152     public ExternalComponentStatus probeComponent() {
153         long startTime = System.currentTimeMillis();
154         ExternalComponentStatus externalComponentStatus;
155         try {
156             HttpResponse<String> stringHttpResponse = asdcClient.checkSDCConnectivity();
157             HttpRequestMetadata httpRequestMetadata = new HttpRequestMetadata(HttpMethod.GET, stringHttpResponse.getStatus(), asdcClient.getBaseUrl() + AsdcClient.URIS.HEALTH_CHECK_ENDPOINT, stringHttpResponse.getBody(), "SDC healthCheck",
158                     System.currentTimeMillis() - startTime);
159             externalComponentStatus = new ExternalComponentStatus(ExternalComponentStatus.Component.SDC, stringHttpResponse.isSuccessful(), httpRequestMetadata);
160         } catch (Exception e) {
161             HttpRequestMetadata httpRequestMetadata = new HttpRequestMetadata(HttpMethod.GET, 0,
162                     AsdcClient.URIS.HEALTH_CHECK_ENDPOINT, "", Logging.exceptionToDescription(e), System.currentTimeMillis() - startTime);
163             externalComponentStatus = new ExternalComponentStatus(ExternalComponentStatus.Component.SDC, false, httpRequestMetadata);
164         }
165         return externalComponentStatus;
166     }
167 }