31fa62f1fe6a6f4a48328da6038d0d3addc20f94
[policy/clamp.git] /
1 /*-
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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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===================================
19  */
20
21 package org.onap.policy.clamp.controlloop.participant.kubernetes.helm;
22
23 import java.io.File;
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 java.util.Map;
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;
39
40 /**
41  * Client to talk with Helm cli. Supports helm3 + version
42  */
43 @Component
44 public class HelmClient {
45
46     @Autowired
47     private ChartStore chartStore;
48
49     private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
50     private static final String PATH_DELIMITER = "/";
51
52     /**
53      * Install a chart.
54      *
55      * @param chart name and version.
56      * @throws ServiceException incase of error
57      */
58     public void installChart(ChartInfo chart) throws ServiceException {
59         if (! checkNamespaceExists(chart.getNamespace())) {
60             var processBuilder = prepareCreateNamespaceCommand(chart.getNamespace());
61             executeCommand(processBuilder);
62         }
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());
68     }
69
70     /**
71      * Add repository if doesn't exist.
72      * @param repo HelmRepository
73      * @throws ServiceException incase of error
74      */
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());
81         } else {
82             logger.info("Repository already exists");
83         }
84     }
85
86
87     /**
88      * Finds helm chart repository for the chart.
89      *
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
94      */
95     public String findChartRepository(ChartInfo chart) throws ServiceException, IOException {
96         updateHelmRepo();
97         String repository = verifyConfiguredRepo(chart);
98         if (repository != null) {
99             logger.info("Helm chart located in the repository {} ", repository);
100             return repository;
101         }
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;
106         }
107         return repository;
108     }
109
110     /**
111      * Verify helm chart in configured repositories.
112      * @param chart chartInfo
113      * @return repo name
114      * @throws IOException incase of error
115      * @throws ServiceException incase of error
116      */
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());
123         return repository;
124     }
125
126     /**
127      * Uninstall a chart.
128      *
129      * @param chart name and version.
130      * @throws ServiceException incase of error
131      */
132     public void uninstallChart(ChartInfo chart) throws ServiceException {
133         executeCommand(prepareUnInstallCommand(chart));
134     }
135
136
137     /**
138      * Execute helm cli bash commands .
139      * @param processBuilder processbuilder
140      * @return string output
141      * @throws ServiceException incase of error.
142      */
143     public static String executeCommand(ProcessBuilder processBuilder) throws ServiceException {
144         var commandStr = toString(processBuilder);
145
146         try {
147             var process = processBuilder.start();
148             process.waitFor();
149             int exitValue = process.exitValue();
150
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);
155                 }
156             }
157
158             var output = IOUtils.toString(process.getInputStream(), StandardCharsets.UTF_8);
159             logger.debug("Command <{}> execution, output: {}", commandStr, output);
160             return output;
161
162         } catch (InterruptedException ie) {
163             Thread.currentThread().interrupt();
164             throw new ServiceException("Failed to execute the Command: " + commandStr + ", the command was interrupted",
165                 ie);
166         } catch (Exception exc) {
167             throw new ServiceException("Failed to execute the Command: " + commandStr, exc);
168         }
169     }
170
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();
175     }
176
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];
181             }
182         }
183         return null;
184     }
185
186     private ProcessBuilder prepareRepoAddCommand(HelmRepository repo) {
187         var url = repo.getProtocol() + "://" + repo.getAddress();
188         if (repo.getPort() != null) {
189             url =  url + ":" + repo.getPort();
190         }
191         // @formatter:off
192         List<String> helmArguments = new ArrayList<>(
193                 List.of(
194                         "helm",
195                         "repo",
196                         "add", repo.getRepoName(), url
197                 ));
198         if (repo.getUserName() != null && repo.getPassword() != null) {
199             helmArguments.addAll(List.of("--username", repo.getUserName(), "--password",  repo.getPassword()));
200         }
201         return new ProcessBuilder().command(helmArguments);
202     }
203
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);
207     }
208
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);
212     }
213
214     private ProcessBuilder prepareInstallCommand(ChartInfo chart) {
215
216         // @formatter:off
217         List<String> helmArguments = new ArrayList<>(
218             List.of(
219                 "helm",
220                 "install", chart.getReleaseName(), chart.getRepository().getRepoName() + "/"
221                             + chart.getChartId().getName(),
222                 "--version", chart.getChartId().getVersion(),
223                 "--namespace", chart.getNamespace()
224             ));
225         // @formatter:on
226
227         // Verify if values.yaml/override parameters available for the chart
228         var localOverrideYaml = chartStore.getOverrideFile(chart);
229
230         if (verifyLocalHelmRepo(localOverrideYaml)) {
231             logger.info("Override yaml available for the helm chart");
232             helmArguments.addAll(List.of("--values", localOverrideYaml.getPath()));
233         }
234
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()));
238             }
239         }
240         return new ProcessBuilder().command(helmArguments);
241     }
242
243     private ProcessBuilder prepareUnInstallCommand(ChartInfo chart) {
244         return new ProcessBuilder("helm", "delete", chart.getReleaseName(), "--namespace",
245             chart.getNamespace());
246     }
247
248     private ProcessBuilder prepareCreateNamespaceCommand(String namespace) {
249         return new ProcessBuilder().command("kubectl", "create", "namespace", namespace);
250     }
251
252     private ProcessBuilder helmRepoVerifyCommand(String chartName) {
253         return new ProcessBuilder().command("sh", "-c", "helm search repo | grep " + chartName);
254     }
255
256
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");
261     }
262
263     private boolean verifyLocalHelmRepo(File localFile) {
264         return localFile.exists();
265     }
266
267     protected static String toString(ProcessBuilder processBuilder) {
268         return String.join(" ", processBuilder.command());
269     }
270 }