Fix incorrect url in PAP consolidated healthcheck
[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-2022 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.annotation.PostConstruct;
40 import javax.annotation.PreDestroy;
41 import javax.ws.rs.core.Response;
42 import javax.ws.rs.core.Response.Status;
43 import lombok.RequiredArgsConstructor;
44 import org.apache.commons.lang3.tuple.Pair;
45 import org.onap.policy.common.endpoints.http.client.HttpClient;
46 import org.onap.policy.common.endpoints.http.client.HttpClientConfigException;
47 import org.onap.policy.common.endpoints.http.client.HttpClientFactory;
48 import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
49 import org.onap.policy.common.endpoints.parameters.RestClientParameters;
50 import org.onap.policy.common.endpoints.report.HealthCheckReport;
51 import org.onap.policy.models.base.PfModelRuntimeException;
52 import org.onap.policy.models.pdp.concepts.Pdp;
53 import org.onap.policy.models.pdp.concepts.PdpGroup;
54 import org.onap.policy.models.pdp.concepts.PdpSubGroup;
55 import org.onap.policy.models.pdp.enums.PdpHealthStatus;
56 import org.onap.policy.pap.main.PapConstants;
57 import org.onap.policy.pap.main.parameters.PapParameterGroup;
58 import org.onap.policy.pap.main.service.PdpGroupService;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61 import org.springframework.beans.factory.annotation.Value;
62 import org.springframework.http.HttpStatus;
63 import org.springframework.stereotype.Service;
64
65 /**
66  * Provider for PAP to fetch health status of all Policy components, including PAP, API, Distribution, and PDPs.
67  *
68  * @author Yehui Wang (yehui.wang@est.tech)
69  */
70 @Service
71 @RequiredArgsConstructor
72 public class PolicyComponentsHealthCheckProvider {
73
74     private static final Logger LOGGER = LoggerFactory.getLogger(PolicyComponentsHealthCheckProvider.class);
75     private static final String HEALTH_STATUS = "healthy";
76     private static final Pattern IP_REPLACEMENT_PATTERN = Pattern.compile("//(\\S+):");
77     private static final String POLICY_PAP_HEALTHCHECK_URI = "/policy/pap/v1/healthcheck";
78     private static List<HttpClient> clients = new ArrayList<>();
79     private ExecutorService clientHealthCheckExecutorService;
80
81     private final PapParameterGroup papParameterGroup;
82
83     private final PdpGroupService pdpGroupService;
84
85     @Value("${server.ssl.enabled:false}")
86     private boolean isHttps;
87
88     @Value("${server.port}")
89     private int port;
90
91     /**
92      * This method is used to initialize clients and executor.
93      */
94     @PostConstruct
95     public void initializeClientHealthCheckExecutorService() throws HttpClientConfigException {
96         HttpClientFactory clientFactory = HttpClientFactoryInstance.getClientFactory();
97         for (RestClientParameters params : papParameterGroup.getHealthCheckRestClientParameters()) {
98             params.setManaged(false);
99             clients.add(clientFactory.build(params));
100         }
101         clientHealthCheckExecutorService = Executors.newFixedThreadPool(clients.isEmpty() ? 1 : clients.size());
102     }
103
104     /**
105      * This method clears clients {@link List} and clientHealthCheckExecutorService {@link ExecutorService}.
106      */
107     @PreDestroy
108     public void cleanup() {
109         clients.clear();
110         clientHealthCheckExecutorService.shutdown();
111     }
112
113     /**
114      * Returns health status of all Policy components.
115      *
116      * @return a pair containing the status and the response
117      */
118     public Pair<HttpStatus, Map<String, Object>> fetchPolicyComponentsHealthStatus() {
119         boolean isHealthy;
120         Map<String, Object> result;
121
122         // Check remote components
123         List<Callable<Entry<String, Object>>> tasks = new ArrayList<>(clients.size());
124
125         for (HttpClient client : clients) {
126             tasks.add(() -> new AbstractMap.SimpleEntry<>(client.getName(), fetchPolicyComponentHealthStatus(client)));
127         }
128
129         try {
130             List<Future<Entry<String, Object>>> futures = clientHealthCheckExecutorService.invokeAll(tasks);
131             result = futures.stream().map(entryFuture -> {
132                 try {
133                     return entryFuture.get();
134                 } catch (ExecutionException e) {
135                     throw new PfModelRuntimeException(Status.BAD_REQUEST, "Client Health check Failed ", e);
136                 } catch (InterruptedException e) {
137                     Thread.currentThread().interrupt();
138                     throw new PfModelRuntimeException(Status.BAD_REQUEST, "Client Health check interrupted ", e);
139                 }
140             }).collect(Collectors.toMap(Entry::getKey, Entry::getValue));
141             //true when all the clients health status is true
142             isHealthy = result.values().stream().allMatch(o -> ((HealthCheckReport) o).isHealthy());
143         } catch (InterruptedException exp) {
144             Thread.currentThread().interrupt();
145             throw new PfModelRuntimeException(Status.BAD_REQUEST, "Client Health check interrupted ", exp);
146         }
147
148         // Check PAP itself excluding connectivity to Policy DB
149         HealthCheckReport papReport = new HealthCheckProvider().performHealthCheck(false);
150         papReport
151             .setUrl((isHttps ? "https://" : "http://") + papReport.getUrl() + ":" + port + POLICY_PAP_HEALTHCHECK_URI);
152         if (!papReport.isHealthy()) {
153             isHealthy = false;
154         }
155         result.put(PapConstants.POLICY_PAP, papReport);
156
157         // Check PDPs, read status from DB
158         try {
159             List<PdpGroup> groups = pdpGroupService.getPdpGroups();
160             Map<String, List<Pdp>> pdpListWithType = fetchPdpsHealthStatus(groups);
161             if (isHealthy && (!verifyNumberOfPdps(groups) || pdpListWithType.values().stream().flatMap(List::stream)
162                             .anyMatch(pdp -> !PdpHealthStatus.HEALTHY.equals(pdp.getHealthy())))) {
163                 isHealthy = false;
164             }
165             result.put(PapConstants.POLICY_PDPS, pdpListWithType);
166         } catch (final PfModelRuntimeException exp) {
167             result.put(PapConstants.POLICY_PDPS, exp.getErrorResponse());
168             isHealthy = false;
169         }
170
171         result.put(HEALTH_STATUS, isHealthy);
172         LOGGER.debug("Policy Components HealthCheck Response - {}", result);
173         return Pair.of(HttpStatus.OK, result);
174     }
175
176     private Map<String, List<Pdp>> fetchPdpsHealthStatus(List<PdpGroup> groups) {
177         Map<String, List<Pdp>> pdpListWithType = new HashMap<>();
178         for (final PdpGroup group : groups) {
179             for (final PdpSubGroup subGroup : group.getPdpSubgroups()) {
180                 List<Pdp> pdpList = new ArrayList<>(subGroup.getPdpInstances());
181                 pdpListWithType.computeIfAbsent(subGroup.getPdpType(), k -> new ArrayList<>()).addAll(pdpList);
182             }
183         }
184         return pdpListWithType;
185     }
186
187     private boolean verifyNumberOfPdps(List<PdpGroup> groups) {
188         var flag = true;
189         for (final PdpGroup group : groups) {
190             for (final PdpSubGroup subGroup : group.getPdpSubgroups()) {
191                 if (subGroup.getCurrentInstanceCount() < subGroup.getDesiredInstanceCount()) {
192                     flag = false;
193                     break;
194                 }
195             }
196         }
197         return flag;
198     }
199
200     private HealthCheckReport fetchPolicyComponentHealthStatus(HttpClient httpClient) {
201         HealthCheckReport clientReport;
202         try {
203             Response resp = httpClient.get();
204             if (httpClient.getName().equalsIgnoreCase("dmaap")) {
205                 clientReport = verifyDmaapClient(httpClient, resp);
206             } else {
207                 clientReport = replaceIpWithHostname(resp.readEntity(HealthCheckReport.class), httpClient.getBaseUrl());
208             }
209
210             // A health report is read successfully when HTTP status is not OK, it is also
211             // not healthy
212             // even in the report it says healthy.
213             if (resp.getStatus() != HttpURLConnection.HTTP_OK) {
214                 clientReport.setHealthy(false);
215             }
216         } catch (RuntimeException e) {
217             LOGGER.warn("{} connection error", httpClient.getName());
218             clientReport = createHealthCheckReport(httpClient.getName(), httpClient.getBaseUrl(),
219                             HttpURLConnection.HTTP_INTERNAL_ERROR, false, e.getMessage());
220         }
221         return clientReport;
222     }
223
224     private HealthCheckReport createHealthCheckReport(String name, String url, int code, boolean status,
225                     String message) {
226         var report = new HealthCheckReport();
227         report.setName(name);
228         report.setUrl(url);
229         report.setHealthy(status);
230         report.setCode(code);
231         report.setMessage(message);
232         return report;
233     }
234
235     private HealthCheckReport replaceIpWithHostname(HealthCheckReport report, String baseUrl) {
236         var matcher = IP_REPLACEMENT_PATTERN.matcher(baseUrl);
237         if (matcher.find()) {
238             var ip = matcher.group(1);
239             report.setUrl(baseUrl.replace(ip, report.getUrl()));
240         }
241         return report;
242     }
243
244     private HealthCheckReport verifyDmaapClient(HttpClient httpClient, Response resp) {
245         DmaapGetTopicResponse dmaapResponse = resp.readEntity(DmaapGetTopicResponse.class);
246         var topicVerificationStatus = (dmaapResponse.getTopics() != null
247                         && dmaapResponse.getTopics().contains(PapConstants.TOPIC_POLICY_PDP_PAP));
248         String message = (topicVerificationStatus ? "PAP to DMaaP connection check is successfull"
249                         : "PAP to DMaaP connection check failed");
250         int code = (topicVerificationStatus ? resp.getStatus() : 503);
251         return createHealthCheckReport(httpClient.getName(), httpClient.getBaseUrl(), code,
252                         topicVerificationStatus, message);
253     }
254
255 }