3eba9427d027ff430f7516f9a0b4bda371af2983
[policy/clamp.git] /
1 /*-
2  * ========================LICENSE_START=================================
3  * Copyright (C) 2021-2024 Nordix Foundation. All rights reserved.
4  * ======================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  * ========================LICENSE_END===================================
17  */
18
19 package org.onap.policy.clamp.acm.participant.kubernetes.helm;
20
21 import jakarta.ws.rs.core.Response;
22 import java.io.BufferedReader;
23 import java.io.IOException;
24 import java.io.InputStreamReader;
25 import java.lang.invoke.MethodHandles;
26 import java.nio.charset.StandardCharsets;
27 import java.util.HashMap;
28 import java.util.Map;
29 import org.apache.commons.io.IOUtils;
30 import org.apache.commons.lang3.StringUtils;
31 import org.onap.policy.clamp.acm.participant.kubernetes.exception.ServiceException;
32 import org.onap.policy.clamp.acm.participant.kubernetes.models.ChartInfo;
33 import org.onap.policy.models.base.PfModelException;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37
38 public class PodStatusValidator {
39
40     private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
41
42     private final int statusCheckInterval;
43
44     //Timeout for the thread to exit.
45     private final int timeout;
46
47     private ChartInfo chart;
48
49     private HelmClient client = new HelmClient();
50
51     /**
52      * Constructor for PodStatusValidator.
53      *
54      * @param chart chartInfo
55      * @param timeout timeout for the thread to exit
56      * @param statusCheckInterval Interval to check pod status
57      */
58     public PodStatusValidator(ChartInfo chart, int timeout, int statusCheckInterval) {
59         this.chart = chart;
60         this.timeout = timeout;
61         this.statusCheckInterval = statusCheckInterval;
62     }
63
64     /**
65      * Run the execution.
66      *
67      * @throws InterruptedException in case of an exception
68      * @throws ServiceException in case of an exception
69      */
70     public void run() throws InterruptedException, PfModelException {
71         logger.info("Polling the status of deployed pods for the chart {}", chart.getChartId().getName());
72
73         try {
74             verifyPodStatus();
75         } catch (IOException | ServiceException e) {
76             throw new PfModelException(Response.Status.BAD_REQUEST, "Error verifying the status of the pod. Exiting");
77         }
78     }
79
80     private void verifyPodStatus() throws ServiceException, IOException, InterruptedException, PfModelException {
81         var isVerified = false;
82         long endTime = System.currentTimeMillis() + (timeout * 1000L);
83
84         while (!isVerified && System.currentTimeMillis() < endTime) {
85             var output = client.executeCommand(verifyPodStatusCommand(chart));
86             var podStatusMap = mapPodStatus(output);
87             isVerified = !podStatusMap.isEmpty()
88                     && podStatusMap.values().stream().allMatch("Running"::equals);
89             if (!isVerified) {
90                 logger.info("Waiting for the pods to be active for the chart {}", chart.getChartId().getName());
91                 podStatusMap.forEach((key, value) -> logger.info("Pod: {} , state: {}", key, value));
92                 // Recheck status of pods in specific intervals.
93                 Thread.sleep(statusCheckInterval * 1000L);
94             } else {
95                 logger.info("All pods are in running state for the helm chart {}", chart.getChartId().getName());
96             }
97         }
98         if (!isVerified) {
99             throw new PfModelException(Response.Status.GATEWAY_TIMEOUT,
100                     "Time out Exception verifying the status of the pod");
101         }
102     }
103
104     private ProcessBuilder verifyPodStatusCommand(ChartInfo chart) {
105         String cmd = HelmClient.COMMAND_KUBECTL
106             + " get pods --namespace " + chart.getNamespace() + " | grep " + getPodName();
107         return new ProcessBuilder(HelmClient.COMMAND_SH, "-c", cmd);
108     }
109
110     private String getPodName() {
111         return StringUtils.isNotEmpty(chart.getPodName()) ? chart.getPodName() : chart.getChartId().getName();
112     }
113
114     private Map<String, String> mapPodStatus(String output) throws IOException {
115         Map<String, String> podStatusMap = new HashMap<>();
116         var podName = getPodName();
117         try (var reader = new BufferedReader(new InputStreamReader(IOUtils.toInputStream(output,
118             StandardCharsets.UTF_8)))) {
119             var line = reader.readLine();
120             while (line != null) {
121                 if (line.contains(podName)) {
122                     var result = line.split("\\s+");
123                     podStatusMap.put(result[0], result[2]);
124                 }
125                 line = reader.readLine();
126             }
127         }
128         if (podStatusMap.isEmpty()) {
129             logger.warn("Status of  Pod {} is empty", podName);
130         }
131         return podStatusMap;
132     }
133 }