2eceb4b058fe770900179d253187e361d71c37e1
[policy/pap.git] / main / src / main / java / org / onap / policy / pap / main / rest / PolicyComponentsHealthCheckProvider.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019-2020 Nordix Foundation.
4  *  Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
5  *  Modifications Copyright (C) 2020-2021 Bell Canada. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  * SPDX-License-Identifier: Apache-2.0
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.pap.main.rest;
24
25 import java.net.HttpURLConnection;
26 import java.util.AbstractMap;
27 import java.util.ArrayList;
28 import java.util.HashMap;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.Map.Entry;
32 import java.util.concurrent.Callable;
33 import java.util.concurrent.ExecutionException;
34 import java.util.concurrent.ExecutorService;
35 import java.util.concurrent.Executors;
36 import java.util.concurrent.Future;
37 import java.util.regex.Pattern;
38 import java.util.stream.Collectors;
39 import javax.ws.rs.core.Response;
40 import javax.ws.rs.core.Response.Status;
41 import org.apache.commons.lang3.tuple.Pair;
42 import org.onap.policy.common.endpoints.http.client.HttpClient;
43 import org.onap.policy.common.endpoints.http.client.HttpClientConfigException;
44 import org.onap.policy.common.endpoints.http.client.HttpClientFactory;
45 import org.onap.policy.common.endpoints.parameters.RestClientParameters;
46 import org.onap.policy.common.endpoints.report.HealthCheckReport;
47 import org.onap.policy.common.parameters.ParameterService;
48 import org.onap.policy.common.utils.services.Registry;
49 import org.onap.policy.models.base.PfModelException;
50 import org.onap.policy.models.base.PfModelRuntimeException;
51 import org.onap.policy.models.pdp.concepts.Pdp;
52 import org.onap.policy.models.pdp.concepts.PdpGroup;
53 import org.onap.policy.models.pdp.concepts.PdpSubGroup;
54 import org.onap.policy.models.pdp.enums.PdpHealthStatus;
55 import org.onap.policy.models.provider.PolicyModelsProvider;
56 import org.onap.policy.pap.main.PapConstants;
57 import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper;
58 import org.onap.policy.pap.main.parameters.PapParameterGroup;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61
62 /**
63  * Provider for PAP to fetch health status of all Policy components, including PAP, API, Distribution, and PDPs.
64  *
65  * @author Yehui Wang (yehui.wang@est.tech)
66  */
67 public class PolicyComponentsHealthCheckProvider {
68
69     private static final Logger LOGGER = LoggerFactory.getLogger(PolicyComponentsHealthCheckProvider.class);
70     private static final String PAP_GROUP_PARAMS_NAME = "PapGroup";
71     private static final String HEALTH_STATUS = "healthy";
72     private static final Pattern IP_REPLACEMENT_PATTERN = Pattern.compile("//(\\S+):");
73     private static final String POLICY_PAP_HEALTHCHECK_URI = "/policy/pap/v1/healthcheck";
74     private static List<HttpClient> clients = new ArrayList<>();
75     private static ExecutorService clientHealthCheckExecutorService;
76
77     private PapParameterGroup papParameterGroup = ParameterService.get(PAP_GROUP_PARAMS_NAME);
78
79     /**
80      * This method is used to initialize clients and executor.
81      * @param papParameterGroup
82      *     @{link PapParameterGroup} contains the Pap Parameters set during startup
83      * @param clientFactory
84      *     @{link HttpClientFactory} contains the client details
85      */
86     public static void initializeClientHealthCheckExecutorService(PapParameterGroup papParameterGroup,
87         HttpClientFactory clientFactory) throws HttpClientConfigException {
88         for (RestClientParameters params : papParameterGroup.getHealthCheckRestClientParameters()) {
89             params.setManaged(false);
90             clients.add(clientFactory.build(params));
91         }
92         clientHealthCheckExecutorService = Executors.newFixedThreadPool(clients.isEmpty() ? 1 : clients.size());
93     }
94
95     /**
96      * Returns health status of all Policy components.
97      *
98      * @return a pair containing the status and the response
99      */
100     public Pair<Status, Map<String, Object>> fetchPolicyComponentsHealthStatus() {
101         boolean isHealthy;
102         Map<String, Object> result;
103
104         // Check remote components
105         List<Callable<Entry<String, Object>>> tasks = new ArrayList<>(clients.size());
106
107         for (HttpClient client : clients) {
108             tasks.add(() -> new AbstractMap.SimpleEntry<>(client.getName(), fetchPolicyComponentHealthStatus(client)));
109         }
110
111         try {
112             List<Future<Entry<String, Object>>> futures = clientHealthCheckExecutorService.invokeAll(tasks);
113             result = futures.stream().map(entryFuture -> {
114                 try {
115                     return entryFuture.get();
116                 } catch (ExecutionException e) {
117                     throw new PfModelRuntimeException(Status.BAD_REQUEST, "Client Health check Failed ", e);
118                 } catch (InterruptedException e) {
119                     Thread.currentThread().interrupt();
120                     throw new PfModelRuntimeException(Status.BAD_REQUEST, "Client Health check interrupted ", e);
121                 }
122             }).collect(Collectors.toMap(Entry::getKey, Entry::getValue));
123             //true when all the clients health status is true
124             isHealthy = result.values().stream().allMatch(o -> ((HealthCheckReport) o).isHealthy());
125         } catch (InterruptedException exp) {
126             Thread.currentThread().interrupt();
127             throw new PfModelRuntimeException(Status.BAD_REQUEST, "Client Health check interrupted ", exp);
128         }
129
130         // Check PAP itself
131         HealthCheckReport papReport = new HealthCheckProvider().performHealthCheck();
132         var restServerParameters = papParameterGroup.getRestServerParameters();
133         papReport.setUrl(
134             (restServerParameters.isHttps() ? "https://" : "http://") + papReport.getUrl() + ":" + restServerParameters
135                 .getPort() + POLICY_PAP_HEALTHCHECK_URI);
136         if (!papReport.isHealthy()) {
137             isHealthy = false;
138         }
139         result.put(PapConstants.POLICY_PAP, papReport);
140
141         // Check PDPs, read status from DB
142         try {
143             List<PdpGroup> groups = fetchPdpGroups();
144             Map<String, List<Pdp>> pdpListWithType = fetchPdpsHealthStatus(groups);
145             if (isHealthy && (!verifyNumberOfPdps(groups) || pdpListWithType.values().stream().flatMap(List::stream)
146                             .anyMatch(pdp -> !PdpHealthStatus.HEALTHY.equals(pdp.getHealthy())))) {
147                 isHealthy = false;
148             }
149             result.put(PapConstants.POLICY_PDPS, pdpListWithType);
150         } catch (final PfModelException exp) {
151             result.put(PapConstants.POLICY_PDPS, exp.getErrorResponse());
152             isHealthy = false;
153         }
154
155         result.put(HEALTH_STATUS, isHealthy);
156         LOGGER.debug("Policy Components HealthCheck Response - {}", result);
157         return Pair.of(Status.OK, result);
158     }
159
160     private Map<String, List<Pdp>> fetchPdpsHealthStatus(List<PdpGroup> groups) {
161         Map<String, List<Pdp>> pdpListWithType = new HashMap<>();
162         for (final PdpGroup group : groups) {
163             for (final PdpSubGroup subGroup : group.getPdpSubgroups()) {
164                 List<Pdp> pdpList = new ArrayList<>(subGroup.getPdpInstances());
165                 pdpListWithType.computeIfAbsent(subGroup.getPdpType(), k -> new ArrayList<>()).addAll(pdpList);
166             }
167         }
168         return pdpListWithType;
169     }
170
171     private boolean verifyNumberOfPdps(List<PdpGroup> groups) {
172         var flag = true;
173         for (final PdpGroup group : groups) {
174             for (final PdpSubGroup subGroup : group.getPdpSubgroups()) {
175                 if (subGroup.getCurrentInstanceCount() < subGroup.getDesiredInstanceCount()) {
176                     flag = false;
177                     break;
178                 }
179             }
180         }
181         return flag;
182     }
183
184     private List<PdpGroup> fetchPdpGroups() throws PfModelException {
185         List<PdpGroup> groups = new ArrayList<>();
186         final PolicyModelsProviderFactoryWrapper modelProviderWrapper =
187                         Registry.get(PapConstants.REG_PAP_DAO_FACTORY, PolicyModelsProviderFactoryWrapper.class);
188         try (PolicyModelsProvider databaseProvider = modelProviderWrapper.create()) {
189             groups = databaseProvider.getPdpGroups(null);
190         }
191         return groups;
192     }
193
194     private HealthCheckReport fetchPolicyComponentHealthStatus(HttpClient httpClient) {
195         HealthCheckReport clientReport;
196         try {
197             Response resp = httpClient.get();
198             if (httpClient.getName().equalsIgnoreCase("dmaap")) {
199                 clientReport = verifyDmaapClient(httpClient, resp);
200             } else {
201                 clientReport = replaceIpWithHostname(resp.readEntity(HealthCheckReport.class), httpClient.getBaseUrl());
202             }
203
204             // A health report is read successfully when HTTP status is not OK, it is also
205             // not healthy
206             // even in the report it says healthy.
207             if (resp.getStatus() != HttpURLConnection.HTTP_OK) {
208                 clientReport.setHealthy(false);
209             }
210         } catch (RuntimeException e) {
211             LOGGER.warn("{} connection error", httpClient.getName());
212             clientReport = createHealthCheckReport(httpClient.getName(), httpClient.getBaseUrl(),
213                             HttpURLConnection.HTTP_INTERNAL_ERROR, false, e.getMessage());
214         }
215         return clientReport;
216     }
217
218     private HealthCheckReport createHealthCheckReport(String name, String url, int code, boolean status,
219                     String message) {
220         var report = new HealthCheckReport();
221         report.setName(name);
222         report.setUrl(url);
223         report.setHealthy(status);
224         report.setCode(code);
225         report.setMessage(message);
226         return report;
227     }
228
229     private HealthCheckReport replaceIpWithHostname(HealthCheckReport report, String baseUrl) {
230         var matcher = IP_REPLACEMENT_PATTERN.matcher(baseUrl);
231         if (matcher.find()) {
232             var ip = matcher.group(1);
233             report.setUrl(baseUrl.replace(ip, report.getUrl()));
234         }
235         return report;
236     }
237
238     private HealthCheckReport verifyDmaapClient(HttpClient httpClient, Response resp) {
239         DmaapGetTopicResponse dmaapResponse = resp.readEntity(DmaapGetTopicResponse.class);
240         var topicVerificationStatus = (dmaapResponse.getTopics() != null
241                         && dmaapResponse.getTopics().contains(PapConstants.TOPIC_POLICY_PDP_PAP));
242         String message = (topicVerificationStatus ? "PAP to DMaaP connection check is successfull"
243                         : "PAP to DMaaP connection check failed");
244         int code = (topicVerificationStatus ? resp.getStatus() : 503);
245         return createHealthCheckReport(httpClient.getName(), httpClient.getBaseUrl(), code,
246                         topicVerificationStatus, message);
247     }
248
249     /**
250      * This method clears clients {@link List} and clientHealthCheckExecutorService {@link ExecutorService}.
251      */
252     public static void cleanup() {
253         clients.clear();
254         clientHealthCheckExecutorService.shutdown();
255     }
256 }