2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2019-2020, 2022-2024 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
11 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 * SPDX-License-Identifier: Apache-2.0
20 * ============LICENSE_END=========================================================
23 package org.onap.policy.pap.main.rest;
25 import jakarta.annotation.PostConstruct;
26 import jakarta.annotation.PreDestroy;
27 import jakarta.ws.rs.core.Response;
28 import jakarta.ws.rs.core.Response.Status;
29 import java.net.HttpURLConnection;
30 import java.util.AbstractMap;
31 import java.util.ArrayList;
32 import java.util.HashMap;
33 import java.util.List;
35 import java.util.Map.Entry;
36 import java.util.concurrent.Callable;
37 import java.util.concurrent.ExecutionException;
38 import java.util.concurrent.ExecutorService;
39 import java.util.concurrent.Executors;
40 import java.util.concurrent.Future;
41 import java.util.regex.Pattern;
42 import java.util.stream.Collectors;
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;
66 * Provider for PAP to fetch health status of all Policy components, including PAP, API, Distribution, and PDPs.
68 * @author Yehui Wang (yehui.wang@est.tech)
71 @RequiredArgsConstructor
72 public class PolicyComponentsHealthCheckProvider {
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;
81 private final PapParameterGroup papParameterGroup;
83 private final PdpGroupService pdpGroupService;
85 @Value("${server.ssl.enabled:false}")
86 private boolean isHttps;
88 @Value("${server.port}")
91 @Value("${pap.topic.pdp-pap.name:POLICY-PDP-PAP}")
92 private String topicPolicyPdpPap;
95 * This method is used to initialize clients and executor.
98 public void initializeClientHealthCheckExecutorService() throws HttpClientConfigException {
99 HttpClientFactory clientFactory = HttpClientFactoryInstance.getClientFactory();
100 for (RestClientParameters params : papParameterGroup.getHealthCheckRestClientParameters()) {
101 params.setManaged(false);
102 clients.add(clientFactory.build(params));
104 clientHealthCheckExecutorService = Executors.newFixedThreadPool(clients.isEmpty() ? 1 : clients.size());
108 * This method clears clients {@link List} and clientHealthCheckExecutorService {@link ExecutorService}.
111 public void cleanup() {
113 clientHealthCheckExecutorService.shutdown();
117 * Returns health status of all Policy components.
119 * @return a pair containing the status and the response
121 public Pair<HttpStatus, Map<String, Object>> fetchPolicyComponentsHealthStatus() {
123 Map<String, Object> result;
125 // Check remote components
126 List<Callable<Entry<String, Object>>> tasks = new ArrayList<>(clients.size());
128 for (HttpClient client : clients) {
129 tasks.add(() -> new AbstractMap.SimpleEntry<>(client.getName(), fetchPolicyComponentHealthStatus(client)));
133 List<Future<Entry<String, Object>>> futures = clientHealthCheckExecutorService.invokeAll(tasks);
134 result = futures.stream().map(entryFuture -> {
136 return entryFuture.get();
137 } catch (ExecutionException e) {
138 throw new PfModelRuntimeException(Status.BAD_REQUEST, "Client Health check Failed ", e);
139 } catch (InterruptedException e) {
140 Thread.currentThread().interrupt();
141 throw new PfModelRuntimeException(Status.BAD_REQUEST, "Client Health check interrupted ", e);
143 }).collect(Collectors.toMap(Entry::getKey, Entry::getValue));
144 //true when all the clients health status is true
145 isHealthy = result.values().stream().allMatch(o -> ((HealthCheckReport) o).isHealthy());
146 } catch (InterruptedException exp) {
147 Thread.currentThread().interrupt();
148 throw new PfModelRuntimeException(Status.BAD_REQUEST, "Client Health check interrupted ", exp);
151 // Check PAP itself excluding connectivity to Policy DB
152 HealthCheckReport papReport = new HealthCheckProvider().performHealthCheck(false);
154 .setUrl((isHttps ? "https://" : "http://") + papReport.getUrl() + ":" + port + POLICY_PAP_HEALTHCHECK_URI);
155 if (!papReport.isHealthy()) {
158 result.put(PapConstants.POLICY_PAP, papReport);
160 // Check PDPs, read status from DB
162 List<PdpGroup> groups = pdpGroupService.getPdpGroups();
163 Map<String, List<Pdp>> pdpListWithType = fetchPdpsHealthStatus(groups);
164 if (isHealthy && (!verifyNumberOfPdps(groups) || pdpListWithType.values().stream().flatMap(List::stream)
165 .anyMatch(pdp -> !PdpHealthStatus.HEALTHY.equals(pdp.getHealthy())))) {
168 result.put(PapConstants.POLICY_PDPS, pdpListWithType);
169 } catch (final PfModelRuntimeException exp) {
170 result.put(PapConstants.POLICY_PDPS, exp.getErrorResponse());
174 result.put(HEALTH_STATUS, isHealthy);
175 LOGGER.debug("Policy Components HealthCheck Response - {}", result);
176 return Pair.of(HttpStatus.OK, result);
179 private Map<String, List<Pdp>> fetchPdpsHealthStatus(List<PdpGroup> groups) {
180 Map<String, List<Pdp>> pdpListWithType = new HashMap<>();
181 for (final PdpGroup group : groups) {
182 for (final PdpSubGroup subGroup : group.getPdpSubgroups()) {
183 List<Pdp> pdpList = new ArrayList<>(subGroup.getPdpInstances());
184 pdpListWithType.computeIfAbsent(subGroup.getPdpType(), k -> new ArrayList<>()).addAll(pdpList);
187 return pdpListWithType;
190 private boolean verifyNumberOfPdps(List<PdpGroup> groups) {
192 for (final PdpGroup group : groups) {
193 for (final PdpSubGroup subGroup : group.getPdpSubgroups()) {
194 if (subGroup.getCurrentInstanceCount() < subGroup.getDesiredInstanceCount()) {
203 private HealthCheckReport fetchPolicyComponentHealthStatus(HttpClient httpClient) {
204 HealthCheckReport clientReport;
206 Response resp = httpClient.get();
207 if (httpClient.getName().equalsIgnoreCase("kafka")) {
208 clientReport = verifyKafkaClient(httpClient, resp);
210 clientReport = replaceIpWithHostname(resp.readEntity(HealthCheckReport.class), httpClient.getBaseUrl());
213 // A health report is read successfully when HTTP status is not OK, it is also
215 // even in the report it says healthy.
216 if (resp.getStatus() != HttpURLConnection.HTTP_OK) {
217 clientReport.setHealthy(false);
219 } catch (RuntimeException e) {
220 LOGGER.warn("{} connection error", httpClient.getName());
221 clientReport = createHealthCheckReport(httpClient.getName(), httpClient.getBaseUrl(),
222 HttpURLConnection.HTTP_INTERNAL_ERROR, false, e.getMessage());
227 private HealthCheckReport createHealthCheckReport(String name, String url, int code, boolean status,
229 var report = new HealthCheckReport();
230 report.setName(name);
232 report.setHealthy(status);
233 report.setCode(code);
234 report.setMessage(message);
238 private HealthCheckReport replaceIpWithHostname(HealthCheckReport report, String baseUrl) {
239 var matcher = IP_REPLACEMENT_PATTERN.matcher(baseUrl);
240 if (matcher.find()) {
241 var ip = matcher.group(1);
242 report.setUrl(baseUrl.replace(ip, report.getUrl()));
247 private HealthCheckReport verifyKafkaClient(HttpClient httpClient, Response resp) {
248 KafkaGetTopicResponse kafkaResponse = resp.readEntity(KafkaGetTopicResponse.class);
249 var topicVerificationStatus = (kafkaResponse.getTopics() != null
250 && kafkaResponse.getTopics().contains(topicPolicyPdpPap));
251 String message = (topicVerificationStatus ? "PAP to Kafka connection check is successful"
252 : "PAP to Kafka connection check failed");
253 int code = (topicVerificationStatus ? resp.getStatus() : 503);
254 return createHealthCheckReport(httpClient.getName(), httpClient.getBaseUrl(), code,
255 topicVerificationStatus, message);