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
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 java.net.HttpURLConnection;
26 import java.util.AbstractMap;
27 import java.util.ArrayList;
28 import java.util.HashMap;
29 import java.util.List;
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;
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}")
92 * This method is used to initialize clients and executor.
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));
101 clientHealthCheckExecutorService = Executors.newFixedThreadPool(clients.isEmpty() ? 1 : clients.size());
105 * This method clears clients {@link List} and clientHealthCheckExecutorService {@link ExecutorService}.
108 public void cleanup() {
110 clientHealthCheckExecutorService.shutdown();
114 * Returns health status of all Policy components.
116 * @return a pair containing the status and the response
118 public Pair<HttpStatus, Map<String, Object>> fetchPolicyComponentsHealthStatus() {
120 Map<String, Object> result;
122 // Check remote components
123 List<Callable<Entry<String, Object>>> tasks = new ArrayList<>(clients.size());
125 for (HttpClient client : clients) {
126 tasks.add(() -> new AbstractMap.SimpleEntry<>(client.getName(), fetchPolicyComponentHealthStatus(client)));
130 List<Future<Entry<String, Object>>> futures = clientHealthCheckExecutorService.invokeAll(tasks);
131 result = futures.stream().map(entryFuture -> {
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);
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);
148 // Check PAP itself excluding connectivity to Policy DB
149 HealthCheckReport papReport = new HealthCheckProvider().performHealthCheck(false);
151 .setUrl((isHttps ? "https://" : "http://") + papReport.getUrl() + ":" + port + POLICY_PAP_HEALTHCHECK_URI);
152 if (!papReport.isHealthy()) {
155 result.put(PapConstants.POLICY_PAP, papReport);
157 // Check PDPs, read status from DB
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())))) {
165 result.put(PapConstants.POLICY_PDPS, pdpListWithType);
166 } catch (final PfModelRuntimeException exp) {
167 result.put(PapConstants.POLICY_PDPS, exp.getErrorResponse());
171 result.put(HEALTH_STATUS, isHealthy);
172 LOGGER.debug("Policy Components HealthCheck Response - {}", result);
173 return Pair.of(HttpStatus.OK, result);
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);
184 return pdpListWithType;
187 private boolean verifyNumberOfPdps(List<PdpGroup> groups) {
189 for (final PdpGroup group : groups) {
190 for (final PdpSubGroup subGroup : group.getPdpSubgroups()) {
191 if (subGroup.getCurrentInstanceCount() < subGroup.getDesiredInstanceCount()) {
200 private HealthCheckReport fetchPolicyComponentHealthStatus(HttpClient httpClient) {
201 HealthCheckReport clientReport;
203 Response resp = httpClient.get();
204 if (httpClient.getName().equalsIgnoreCase("dmaap")) {
205 clientReport = verifyDmaapClient(httpClient, resp);
207 clientReport = replaceIpWithHostname(resp.readEntity(HealthCheckReport.class), httpClient.getBaseUrl());
210 // A health report is read successfully when HTTP status is not OK, it is also
212 // even in the report it says healthy.
213 if (resp.getStatus() != HttpURLConnection.HTTP_OK) {
214 clientReport.setHealthy(false);
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());
224 private HealthCheckReport createHealthCheckReport(String name, String url, int code, boolean status,
226 var report = new HealthCheckReport();
227 report.setName(name);
229 report.setHealthy(status);
230 report.setCode(code);
231 report.setMessage(message);
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()));
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);