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.controlloop.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.onap.policy.clamp.controlloop.participant.kubernetes.exception.ServiceException;
32 import org.onap.policy.clamp.controlloop.participant.kubernetes.models.ChartInfo;
33 import org.onap.policy.clamp.controlloop.participant.kubernetes.models.HelmRepository;
34 import org.onap.policy.clamp.controlloop.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 = "/";
55 * @param chart name and version.
56 * @throws ServiceException incase of error
58 public void installChart(ChartInfo chart) throws ServiceException {
59 if (! checkNamespaceExists(chart.getNamespace())) {
60 var processBuilder = prepareCreateNamespaceCommand(chart.getNamespace());
61 executeCommand(processBuilder);
63 var processBuilder = prepareInstallCommand(chart);
64 logger.info("Installing helm chart {} from the repository {} ", chart.getChartId().getName(),
65 chart.getRepository().getRepoName());
66 executeCommand(processBuilder);
67 logger.info("Chart {} installed successfully", chart.getChartId().getName());
71 * Add repository if doesn't exist.
72 * @param repo HelmRepository
73 * @throws ServiceException incase of error
75 public void addRepository(HelmRepository repo) throws ServiceException {
76 String output = executeCommand(prepareVerifyRepoCommand(repo));
77 if (output.isEmpty()) {
78 logger.info("Adding repository to helm client");
79 executeCommand(prepareRepoAddCommand(repo));
80 logger.debug("Added repository {} to the helm client", repo.getRepoName());
82 logger.info("Repository already exists");
88 * Finds helm chart repository for the chart.
90 * @param chart ChartInfo.
91 * @return the chart repository as a string
92 * @throws ServiceException in case of error
93 * @throws IOException in case of IO errors
95 public String findChartRepository(ChartInfo chart) throws ServiceException, IOException {
96 if (updateHelmRepo()) {
97 String repository = verifyConfiguredRepo(chart);
98 if (repository != null) {
99 logger.info("Helm chart located in the repository {} ", repository);
103 var localHelmChartDir = chartStore.getAppPath(chart.getChartId()).toString();
104 logger.info("Chart not found in helm repositories, verifying local repo {} ", localHelmChartDir);
105 if (verifyLocalHelmRepo(new File(localHelmChartDir + PATH_DELIMITER + chart.getChartId().getName()))) {
106 return localHelmChartDir;
112 * Verify helm chart in configured repositories.
113 * @param chart chartInfo
115 * @throws IOException incase of error
116 * @throws ServiceException incase of error
118 public String verifyConfiguredRepo(ChartInfo chart) throws IOException, ServiceException {
119 logger.info("Looking for helm chart {} in all the configured helm repositories", chart.getChartId().getName());
120 String repository = null;
121 var builder = helmRepoVerifyCommand(chart.getChartId().getName());
122 String output = executeCommand(builder);
123 repository = verifyOutput(output, chart.getChartId().getName());
130 * @param chart name and version.
131 * @throws ServiceException incase of error
133 public void uninstallChart(ChartInfo chart) throws ServiceException {
134 executeCommand(prepareUnInstallCommand(chart));
139 * Execute helm cli bash commands .
140 * @param processBuilder processbuilder
141 * @return string output
142 * @throws ServiceException incase of error.
144 public static String executeCommand(ProcessBuilder processBuilder) throws ServiceException {
145 var commandStr = toString(processBuilder);
148 var process = processBuilder.start();
150 int exitValue = process.exitValue();
152 if (exitValue != 0) {
153 var error = IOUtils.toString(process.getErrorStream(), StandardCharsets.UTF_8);
154 if (! error.isEmpty()) {
155 throw new ServiceException("Command execution failed: " + commandStr + " " + error);
159 var output = IOUtils.toString(process.getInputStream(), StandardCharsets.UTF_8);
160 logger.debug("Command <{}> execution, output: {}", commandStr, output);
163 } catch (InterruptedException ie) {
164 Thread.currentThread().interrupt();
165 throw new ServiceException("Failed to execute the Command: " + commandStr + ", the command was interrupted",
167 } catch (Exception exc) {
168 throw new ServiceException("Failed to execute the Command: " + commandStr, exc);
172 private boolean checkNamespaceExists(String namespace) throws ServiceException {
173 logger.info("Check if namespace {} exists on the cluster", namespace);
174 String output = executeCommand(prepareVerifyNamespaceCommand(namespace));
175 return !output.isEmpty();
178 private String verifyOutput(String output, String value) {
179 for (var line: output.split("\\R")) {
180 if (line.contains(value)) {
181 return line.split("/")[0];
187 private ProcessBuilder prepareRepoAddCommand(HelmRepository repo) {
188 var url = repo.getProtocol() + "://" + repo.getAddress();
189 if (repo.getPort() != null) {
190 url = url + ":" + repo.getPort();
193 List<String> helmArguments = new ArrayList<>(
197 "add", repo.getRepoName(), url
199 if (repo.getUserName() != null && repo.getPassword() != null) {
200 helmArguments.addAll(List.of("--username", repo.getUserName(), "--password", repo.getPassword()));
202 return new ProcessBuilder().command(helmArguments);
205 private ProcessBuilder prepareVerifyRepoCommand(HelmRepository repo) {
206 List<String> helmArguments = List.of("sh", "-c", "helm repo ls | grep " + repo.getRepoName());
207 return new ProcessBuilder().command(helmArguments);
210 private ProcessBuilder prepareVerifyNamespaceCommand(String namespace) {
211 List<String> helmArguments = List.of("sh", "-c", "kubectl get ns | grep " + namespace);
212 return new ProcessBuilder().command(helmArguments);
215 private ProcessBuilder prepareInstallCommand(ChartInfo chart) {
218 List<String> helmArguments = new ArrayList<>(
221 "install", chart.getReleaseName(), chart.getRepository().getRepoName() + "/"
222 + chart.getChartId().getName(),
223 "--version", chart.getChartId().getVersion(),
224 "--namespace", chart.getNamespace()
228 // Verify if values.yaml/override parameters available for the chart
229 var localOverrideYaml = chartStore.getOverrideFile(chart);
231 if (verifyLocalHelmRepo(localOverrideYaml)) {
232 logger.info("Override yaml available for the helm chart");
233 helmArguments.addAll(List.of("--values", localOverrideYaml.getPath()));
236 if (chart.getOverrideParams() != null) {
237 for (Map.Entry<String, String> entry : chart.getOverrideParams().entrySet()) {
238 helmArguments.addAll(List.of("--set", entry.getKey() + "=" + entry.getValue()));
241 return new ProcessBuilder().command(helmArguments);
244 private ProcessBuilder prepareUnInstallCommand(ChartInfo chart) {
245 return new ProcessBuilder("helm", "delete", chart.getReleaseName(), "--namespace",
246 chart.getNamespace());
249 private ProcessBuilder prepareCreateNamespaceCommand(String namespace) {
250 return new ProcessBuilder().command("kubectl", "create", "namespace", namespace);
253 private ProcessBuilder helmRepoVerifyCommand(String chartName) {
254 return new ProcessBuilder().command("sh", "-c", "helm search repo | grep " + chartName);
258 private boolean updateHelmRepo() {
260 logger.info("Updating local helm repositories before verifying the chart");
261 executeCommand(new ProcessBuilder().command("helm", "repo", "update"));
262 logger.debug("Helm repositories updated successfully");
263 } catch (ServiceException e) {
264 logger.error("Failed to update the helm repo: ", e);
272 private boolean verifyLocalHelmRepo(File localFile) {
273 return localFile.exists();
276 protected static String toString(ProcessBuilder processBuilder) {
277 return String.join(" ", processBuilder.command());