2 * ========================LICENSE_START=================================
3 * Copyright (C) 2021-2023 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;
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.clamp.acm.participant.kubernetes.models.HelmRepository;
34 import org.onap.policy.clamp.acm.participant.kubernetes.service.ChartStore;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37 import org.springframework.beans.factory.annotation.Autowired;
38 import org.springframework.stereotype.Component;
41 * Client to talk with Helm cli. Supports helm3 + version
44 public class HelmClient {
47 private ChartStore chartStore;
49 private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
50 private static final String PATH_DELIMITER = "/";
51 public static final String COMMAND_SH = "/bin/sh";
52 private static final String COMMAND_HELM = "/usr/local/bin/helm";
53 public static final String COMMAND_KUBECTL = "/usr/local/bin/kubectl";
58 * @param chart name and version.
59 * @throws ServiceException incase of error
61 public void installChart(ChartInfo chart) throws ServiceException {
62 if (! checkNamespaceExists(chart.getNamespace())) {
63 var processBuilder = prepareCreateNamespaceCommand(chart.getNamespace());
64 executeCommand(processBuilder);
66 var processBuilder = prepareInstallCommand(chart);
67 logger.info("Installing helm chart {} from the repository {} ", chart.getChartId().getName(),
68 chart.getRepository().getRepoName());
69 executeCommand(processBuilder);
70 logger.info("Chart {} installed successfully", chart.getChartId().getName());
74 * Add repository if doesn't exist.
75 * @param repo HelmRepository
76 * @return boolean true of false based on add repo success or failed
77 * @throws ServiceException incase of error
79 public boolean addRepository(HelmRepository repo) throws ServiceException {
80 if (!verifyHelmRepoAlreadyExist(repo)) {
81 logger.info("Adding repository to helm client");
82 executeCommand(prepareRepoAddCommand(repo));
83 logger.debug("Added repository {} to the helm client", repo.getRepoName());
86 logger.info("Repository already exists");
92 * Finds helm chart repository for the chart.
94 * @param chart ChartInfo.
95 * @return the chart repository as a string
96 * @throws ServiceException in case of error
97 * @throws IOException in case of IO errors
99 public String findChartRepository(ChartInfo chart) throws ServiceException, IOException {
100 if (updateHelmRepo()) {
101 String repository = verifyConfiguredRepo(chart);
102 if (repository != null) {
103 logger.info("Helm chart located in the repository {} ", repository);
107 var localHelmChartDir = chartStore.getAppPath(chart.getChartId()).toString();
108 logger.info("Chart not found in helm repositories, verifying local repo {} ", localHelmChartDir);
109 if (verifyLocalHelmRepo(new File(localHelmChartDir + PATH_DELIMITER + chart.getChartId().getName()))) {
110 return localHelmChartDir;
116 * Verify helm chart in configured repositories.
117 * @param chart chartInfo
119 * @throws IOException incase of error
120 * @throws ServiceException incase of error
122 public String verifyConfiguredRepo(ChartInfo chart) throws IOException, ServiceException {
123 logger.info("Looking for helm chart {} in all the configured helm repositories", chart.getChartId().getName());
124 String repository = null;
125 var builder = helmRepoVerifyCommand(chart.getChartId().getName());
126 String output = executeCommand(builder);
127 repository = verifyOutput(output, chart.getChartId().getName());
134 * @param chart name and version.
135 * @throws ServiceException incase of error
137 public void uninstallChart(ChartInfo chart) throws ServiceException {
138 executeCommand(prepareUnInstallCommand(chart));
143 * Execute helm cli bash commands .
144 * @param processBuilder processbuilder
145 * @return string output
146 * @throws ServiceException incase of error.
148 public String executeCommand(ProcessBuilder processBuilder) throws ServiceException {
149 var commandStr = toString(processBuilder);
152 var process = processBuilder.start();
154 int exitValue = process.exitValue();
156 if (exitValue != 0) {
157 var error = IOUtils.toString(process.getErrorStream(), StandardCharsets.UTF_8);
158 if (! error.isEmpty()) {
159 throw new ServiceException("Command execution failed: " + commandStr + " " + error);
163 var output = IOUtils.toString(process.getInputStream(), StandardCharsets.UTF_8);
164 logger.debug("Command <{}> execution, output: {}", commandStr, output);
167 } catch (InterruptedException ie) {
168 Thread.currentThread().interrupt();
169 throw new ServiceException("Failed to execute the Command: " + commandStr + ", the command was interrupted",
171 } catch (Exception exc) {
172 throw new ServiceException("Failed to execute the Command: " + commandStr, exc);
176 private boolean checkNamespaceExists(String namespace) throws ServiceException {
177 logger.info("Check if namespace {} exists on the cluster", namespace);
178 String output = executeCommand(prepareVerifyNamespaceCommand(namespace));
179 return !output.isEmpty();
182 private String verifyOutput(String output, String value) {
183 for (var line: output.split("\\R")) {
184 if (line.contains(value)) {
185 return line.split("/")[0];
191 private ProcessBuilder prepareRepoAddCommand(HelmRepository repo) throws ServiceException {
192 if (StringUtils.isEmpty(repo.getAddress())) {
193 throw new ServiceException("Repository Should have valid address");
196 List<String> helmArguments = new ArrayList<>(
200 "add", repo.getRepoName(), repo.getAddress()
202 if (!StringUtils.isEmpty(repo.getUserName()) && !StringUtils.isEmpty(repo.getPassword())) {
203 helmArguments.addAll(List.of("--username", repo.getUserName(), "--password", repo.getPassword()));
205 return new ProcessBuilder().command(helmArguments);
208 private boolean verifyHelmRepoAlreadyExist(HelmRepository repo) {
210 logger.debug("Verify the repo already exist in helm repositories");
211 var helmArguments = List.of(COMMAND_SH, "-c", COMMAND_HELM + " repo list | grep " + repo.getRepoName());
212 String response = executeCommand(new ProcessBuilder().command(helmArguments));
213 if (StringUtils.isEmpty(response)) {
216 } catch (ServiceException e) {
217 logger.debug("Repository {} not found:", repo.getRepoName(), e);
223 private ProcessBuilder prepareVerifyNamespaceCommand(String namespace) {
224 var helmArguments = List.of(COMMAND_SH, "-c", COMMAND_KUBECTL + " get ns | grep " + namespace);
225 return new ProcessBuilder().command(helmArguments);
228 private ProcessBuilder prepareInstallCommand(ChartInfo chart) {
231 List<String> helmArguments = new ArrayList<>(
234 "install", chart.getReleaseName(), chart.getRepository().getRepoName() + "/"
235 + chart.getChartId().getName(),
236 "--version", chart.getChartId().getVersion(),
237 "--namespace", chart.getNamespace()
241 // Verify if values.yaml/override parameters available for the chart
242 var localOverrideYaml = chartStore.getOverrideFile(chart);
244 if (verifyLocalHelmRepo(localOverrideYaml)) {
245 logger.info("Override yaml available for the helm chart");
246 helmArguments.addAll(List.of("--values", localOverrideYaml.getPath()));
249 if (chart.getOverrideParams() != null) {
250 for (var entry : chart.getOverrideParams().entrySet()) {
251 helmArguments.addAll(List.of("--set", entry.getKey() + "=" + entry.getValue()));
254 return new ProcessBuilder().command(helmArguments);
257 private ProcessBuilder prepareUnInstallCommand(ChartInfo chart) {
258 return new ProcessBuilder(COMMAND_HELM, "delete", chart.getReleaseName(), "--namespace",
259 chart.getNamespace());
262 private ProcessBuilder prepareCreateNamespaceCommand(String namespace) {
263 return new ProcessBuilder().command(COMMAND_KUBECTL, "create", "namespace", namespace);
266 private ProcessBuilder helmRepoVerifyCommand(String chartName) {
267 return new ProcessBuilder().command(COMMAND_SH, "-c", COMMAND_HELM + " search repo | grep " + chartName);
271 private boolean updateHelmRepo() {
273 logger.info("Updating local helm repositories before verifying the chart");
274 executeCommand(new ProcessBuilder().command(COMMAND_HELM, "repo", "update"));
275 logger.debug("Helm repositories updated successfully");
276 } catch (ServiceException e) {
277 logger.error("Failed to update the helm repo: ", e);
283 private boolean verifyLocalHelmRepo(File localFile) {
284 return localFile.exists();
287 protected static String toString(ProcessBuilder processBuilder) {
288 return String.join(" ", processBuilder.command());