2 * ========================LICENSE_START=================================
3 * Copyright (C) 2021-2022 Nordix Foundation. All rights reserved.
4 * ======================================================================
5 * Modifications Copyright (C) 2021 AT&T Intellectual Property. 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.
18 * ========================LICENSE_END===================================
21 package org.onap.policy.clamp.acm.participant.kubernetes.helm;
24 import java.io.IOException;
25 import java.lang.invoke.MethodHandles;
26 import java.nio.charset.StandardCharsets;
27 import java.util.ArrayList;
28 import java.util.List;
30 import org.apache.commons.io.IOUtils;
31 import org.apache.commons.lang3.StringUtils;
32 import org.onap.policy.clamp.acm.participant.kubernetes.exception.ServiceException;
33 import org.onap.policy.clamp.acm.participant.kubernetes.models.ChartInfo;
34 import org.onap.policy.clamp.acm.participant.kubernetes.models.HelmRepository;
35 import org.onap.policy.clamp.acm.participant.kubernetes.service.ChartStore;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38 import org.springframework.beans.factory.annotation.Autowired;
39 import org.springframework.stereotype.Component;
42 * Client to talk with Helm cli. Supports helm3 + version
45 public class HelmClient {
48 private ChartStore chartStore;
50 private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
51 private static final String PATH_DELIMITER = "/";
56 * @param chart name and version.
57 * @throws ServiceException incase of error
59 public void installChart(ChartInfo chart) throws ServiceException {
60 if (! checkNamespaceExists(chart.getNamespace())) {
61 var processBuilder = prepareCreateNamespaceCommand(chart.getNamespace());
62 executeCommand(processBuilder);
64 var processBuilder = prepareInstallCommand(chart);
65 logger.info("Installing helm chart {} from the repository {} ", chart.getChartId().getName(),
66 chart.getRepository().getRepoName());
67 executeCommand(processBuilder);
68 logger.info("Chart {} installed successfully", chart.getChartId().getName());
72 * Add repository if doesn't exist.
73 * @param repo HelmRepository
74 * @return boolean true of false based on add repo success or failed
75 * @throws ServiceException incase of error
77 public boolean addRepository(HelmRepository repo) throws ServiceException {
78 if (!verifyHelmRepoAlreadyExist(repo)) {
79 logger.info("Adding repository to helm client");
80 executeCommand(prepareRepoAddCommand(repo));
81 logger.debug("Added repository {} to the helm client", repo.getRepoName());
84 logger.info("Repository already exists");
90 * Finds helm chart repository for the chart.
92 * @param chart ChartInfo.
93 * @return the chart repository as a string
94 * @throws ServiceException in case of error
95 * @throws IOException in case of IO errors
97 public String findChartRepository(ChartInfo chart) throws ServiceException, IOException {
98 if (updateHelmRepo()) {
99 String repository = verifyConfiguredRepo(chart);
100 if (repository != null) {
101 logger.info("Helm chart located in the repository {} ", repository);
105 var localHelmChartDir = chartStore.getAppPath(chart.getChartId()).toString();
106 logger.info("Chart not found in helm repositories, verifying local repo {} ", localHelmChartDir);
107 if (verifyLocalHelmRepo(new File(localHelmChartDir + PATH_DELIMITER + chart.getChartId().getName()))) {
108 return localHelmChartDir;
114 * Verify helm chart in configured repositories.
115 * @param chart chartInfo
117 * @throws IOException incase of error
118 * @throws ServiceException incase of error
120 public String verifyConfiguredRepo(ChartInfo chart) throws IOException, ServiceException {
121 logger.info("Looking for helm chart {} in all the configured helm repositories", chart.getChartId().getName());
122 String repository = null;
123 var builder = helmRepoVerifyCommand(chart.getChartId().getName());
124 String output = executeCommand(builder);
125 repository = verifyOutput(output, chart.getChartId().getName());
132 * @param chart name and version.
133 * @throws ServiceException incase of error
135 public void uninstallChart(ChartInfo chart) throws ServiceException {
136 executeCommand(prepareUnInstallCommand(chart));
141 * Execute helm cli bash commands .
142 * @param processBuilder processbuilder
143 * @return string output
144 * @throws ServiceException incase of error.
146 public static String executeCommand(ProcessBuilder processBuilder) throws ServiceException {
147 var commandStr = toString(processBuilder);
150 var process = processBuilder.start();
152 int exitValue = process.exitValue();
154 if (exitValue != 0) {
155 var error = IOUtils.toString(process.getErrorStream(), StandardCharsets.UTF_8);
156 if (! error.isEmpty()) {
157 throw new ServiceException("Command execution failed: " + commandStr + " " + error);
161 var output = IOUtils.toString(process.getInputStream(), StandardCharsets.UTF_8);
162 logger.debug("Command <{}> execution, output: {}", commandStr, output);
165 } catch (InterruptedException ie) {
166 Thread.currentThread().interrupt();
167 throw new ServiceException("Failed to execute the Command: " + commandStr + ", the command was interrupted",
169 } catch (Exception exc) {
170 throw new ServiceException("Failed to execute the Command: " + commandStr, exc);
174 private boolean checkNamespaceExists(String namespace) throws ServiceException {
175 logger.info("Check if namespace {} exists on the cluster", namespace);
176 String output = executeCommand(prepareVerifyNamespaceCommand(namespace));
177 return !output.isEmpty();
180 private String verifyOutput(String output, String value) {
181 for (var line: output.split("\\R")) {
182 if (line.contains(value)) {
183 return line.split("/")[0];
189 private ProcessBuilder prepareRepoAddCommand(HelmRepository repo) throws ServiceException {
190 if (StringUtils.isEmpty(repo.getAddress())) {
191 throw new ServiceException("Repository Should have valid address");
194 List<String> helmArguments = new ArrayList<>(
198 "add", repo.getRepoName(), repo.getAddress()
200 if (!StringUtils.isEmpty(repo.getUserName()) && !StringUtils.isEmpty(repo.getPassword())) {
201 helmArguments.addAll(List.of("--username", repo.getUserName(), "--password", repo.getPassword()));
203 return new ProcessBuilder().command(helmArguments);
206 private boolean verifyHelmRepoAlreadyExist(HelmRepository repo) {
208 logger.debug("Verify the repo already exist in helm repositories");
209 List<String> helmArguments = List.of("sh", "-c", "helm repo list | grep " + repo.getRepoName());
210 String response = executeCommand(new ProcessBuilder().command(helmArguments));
211 if (StringUtils.isEmpty(response)) {
214 } catch (ServiceException e) {
215 logger.debug("Repository {} not found:", repo.getRepoName(), e);
221 private ProcessBuilder prepareVerifyNamespaceCommand(String namespace) {
222 List<String> helmArguments = List.of("sh", "-c", "kubectl get ns | grep " + namespace);
223 return new ProcessBuilder().command(helmArguments);
226 private ProcessBuilder prepareInstallCommand(ChartInfo chart) {
229 List<String> helmArguments = new ArrayList<>(
232 "install", chart.getReleaseName(), chart.getRepository().getRepoName() + "/"
233 + chart.getChartId().getName(),
234 "--version", chart.getChartId().getVersion(),
235 "--namespace", chart.getNamespace()
239 // Verify if values.yaml/override parameters available for the chart
240 var localOverrideYaml = chartStore.getOverrideFile(chart);
242 if (verifyLocalHelmRepo(localOverrideYaml)) {
243 logger.info("Override yaml available for the helm chart");
244 helmArguments.addAll(List.of("--values", localOverrideYaml.getPath()));
247 if (chart.getOverrideParams() != null) {
248 for (Map.Entry<String, String> entry : chart.getOverrideParams().entrySet()) {
249 helmArguments.addAll(List.of("--set", entry.getKey() + "=" + entry.getValue()));
252 return new ProcessBuilder().command(helmArguments);
255 private ProcessBuilder prepareUnInstallCommand(ChartInfo chart) {
256 return new ProcessBuilder("helm", "delete", chart.getReleaseName(), "--namespace",
257 chart.getNamespace());
260 private ProcessBuilder prepareCreateNamespaceCommand(String namespace) {
261 return new ProcessBuilder().command("kubectl", "create", "namespace", namespace);
264 private ProcessBuilder helmRepoVerifyCommand(String chartName) {
265 return new ProcessBuilder().command("sh", "-c", "helm search repo | grep " + chartName);
269 private boolean updateHelmRepo() {
271 logger.info("Updating local helm repositories before verifying the chart");
272 executeCommand(new ProcessBuilder().command("helm", "repo", "update"));
273 logger.debug("Helm repositories updated successfully");
274 } catch (ServiceException e) {
275 logger.error("Failed to update the helm repo: ", e);
281 private boolean verifyLocalHelmRepo(File localFile) {
282 return localFile.exists();
285 protected static String toString(ProcessBuilder processBuilder) {
286 return String.join(" ", processBuilder.command());