2 * ========================LICENSE_START=================================
3 * Copyright (C) 2021 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 {
97 String repository = verifyConfiguredRepo(chart);
98 if (repository != null) {
99 logger.info("Helm chart located in the repository {} ", repository);
102 var localHelmChartDir = chartStore.getAppPath(chart.getChartId()).toString();
103 logger.info("Chart not found in helm repositories, verifying local repo {} ", localHelmChartDir);
104 if (verifyLocalHelmRepo(new File(localHelmChartDir + PATH_DELIMITER + chart.getChartId().getName()))) {
105 repository = localHelmChartDir;
111 * Verify helm chart in configured repositories.
112 * @param chart chartInfo
114 * @throws IOException incase of error
115 * @throws ServiceException incase of error
117 public String verifyConfiguredRepo(ChartInfo chart) throws IOException, ServiceException {
118 logger.info("Looking for helm chart {} in all the configured helm repositories", chart.getChartId().getName());
119 String repository = null;
120 var builder = helmRepoVerifyCommand(chart.getChartId().getName());
121 String output = executeCommand(builder);
122 repository = verifyOutput(output, chart.getChartId().getName());
129 * @param chart name and version.
130 * @throws ServiceException incase of error
132 public void uninstallChart(ChartInfo chart) throws ServiceException {
133 executeCommand(prepareUnInstallCommand(chart));
138 * Execute helm cli bash commands .
139 * @param processBuilder processbuilder
140 * @return string output
141 * @throws ServiceException incase of error.
143 public static String executeCommand(ProcessBuilder processBuilder) throws ServiceException {
144 var commandStr = toString(processBuilder);
147 var process = processBuilder.start();
149 int exitValue = process.exitValue();
151 if (exitValue != 0) {
152 var error = IOUtils.toString(process.getErrorStream(), StandardCharsets.UTF_8);
153 if (! error.isEmpty()) {
154 throw new ServiceException("Command execution failed: " + commandStr + " " + error);
158 var output = IOUtils.toString(process.getInputStream(), StandardCharsets.UTF_8);
159 logger.debug("Command <{}> execution, output: {}", commandStr, output);
162 } catch (InterruptedException ie) {
163 Thread.currentThread().interrupt();
164 throw new ServiceException("Failed to execute the Command: " + commandStr + ", the command was interrupted",
166 } catch (Exception exc) {
167 throw new ServiceException("Failed to execute the Command: " + commandStr, exc);
171 private boolean checkNamespaceExists(String namespace) throws ServiceException {
172 logger.info("Check if namespace {} exists on the cluster", namespace);
173 String output = executeCommand(prepareVerifyNamespaceCommand(namespace));
174 return !output.isEmpty();
177 private String verifyOutput(String output, String value) {
178 for (var line: output.split("\\R")) {
179 if (line.contains(value)) {
180 return line.split("/")[0];
186 private ProcessBuilder prepareRepoAddCommand(HelmRepository repo) {
187 var url = repo.getProtocol() + "://" + repo.getAddress();
188 if (repo.getPort() != null) {
189 url = url + ":" + repo.getPort();
192 List<String> helmArguments = new ArrayList<>(
196 "add", repo.getRepoName(), url
198 if (repo.getUserName() != null && repo.getPassword() != null) {
199 helmArguments.addAll(List.of("--username", repo.getUserName(), "--password", repo.getPassword()));
201 return new ProcessBuilder().command(helmArguments);
204 private ProcessBuilder prepareVerifyRepoCommand(HelmRepository repo) {
205 List<String> helmArguments = List.of("sh", "-c", "helm repo ls | grep " + repo.getRepoName());
206 return new ProcessBuilder().command(helmArguments);
209 private ProcessBuilder prepareVerifyNamespaceCommand(String namespace) {
210 List<String> helmArguments = List.of("sh", "-c", "kubectl get ns | grep " + namespace);
211 return new ProcessBuilder().command(helmArguments);
214 private ProcessBuilder prepareInstallCommand(ChartInfo chart) {
217 List<String> helmArguments = new ArrayList<>(
220 "install", chart.getReleaseName(), chart.getRepository().getRepoName() + "/"
221 + chart.getChartId().getName(),
222 "--version", chart.getChartId().getVersion(),
223 "--namespace", chart.getNamespace()
227 // Verify if values.yaml/override parameters available for the chart
228 var localOverrideYaml = chartStore.getOverrideFile(chart);
230 if (verifyLocalHelmRepo(localOverrideYaml)) {
231 logger.info("Override yaml available for the helm chart");
232 helmArguments.addAll(List.of("--values", localOverrideYaml.getPath()));
235 if (chart.getOverrideParams() != null) {
236 for (Map.Entry<String, String> entry : chart.getOverrideParams().entrySet()) {
237 helmArguments.addAll(List.of("--set", entry.getKey() + "=" + entry.getValue()));
240 return new ProcessBuilder().command(helmArguments);
243 private ProcessBuilder prepareUnInstallCommand(ChartInfo chart) {
244 return new ProcessBuilder("helm", "delete", chart.getReleaseName(), "--namespace",
245 chart.getNamespace());
248 private ProcessBuilder prepareCreateNamespaceCommand(String namespace) {
249 return new ProcessBuilder().command("kubectl", "create", "namespace", namespace);
252 private ProcessBuilder helmRepoVerifyCommand(String chartName) {
253 return new ProcessBuilder().command("sh", "-c", "helm search repo | grep " + chartName);
257 private void updateHelmRepo() throws ServiceException {
258 logger.info("Updating local helm repositories before verifying the chart");
259 executeCommand(new ProcessBuilder().command("helm", "repo", "update"));
260 logger.debug("Helm repositories updated successfully");
263 private boolean verifyLocalHelmRepo(File localFile) {
264 return localFile.exists();
267 protected static String toString(ProcessBuilder processBuilder) {
268 return String.join(" ", processBuilder.command());