343a44617b7bc8216e8c11192a9ef81b979e93cb
[policy/clamp.git] /
1 /*-
2  * ========================LICENSE_START=================================
3  * Copyright (C) 2021 Nordix Foundation. All rights reserved.
4  * ======================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  * ========================LICENSE_END===================================
17  */
18
19 package org.onap.policy.clamp.controlloop.participant.kubernetes.helm;
20
21 import java.io.BufferedReader;
22 import java.io.IOException;
23 import java.io.InputStreamReader;
24 import java.lang.invoke.MethodHandles;
25 import java.nio.charset.StandardCharsets;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.List;
29 import org.apache.commons.io.IOUtils;
30 import org.onap.policy.clamp.controlloop.participant.kubernetes.exception.ServiceException;
31 import org.onap.policy.clamp.controlloop.participant.kubernetes.models.ChartInfo;
32 import org.onap.policy.clamp.controlloop.participant.kubernetes.service.ChartStore;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35 import org.springframework.beans.factory.annotation.Autowired;
36 import org.springframework.stereotype.Component;
37
38 /**
39  * Client to talk with Helm cli. Supports helm3 + version
40  */
41 @Component
42 public class HelmClient {
43
44     @Autowired
45     private ChartStore chartStore;
46
47     private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
48
49     /**
50      * Install a chart.
51      *
52      * @param chart name and version.
53      * @throws ServiceException incase of error
54      */
55     public void installChart(ChartInfo chart) throws ServiceException {
56         var processBuilder = prepareCreateNamespaceCommand(chart.getNamespace());
57         try {
58             executeCommand(processBuilder);
59         } catch (ServiceException e) {
60             logger.warn("Namespace not created", e);
61         }
62         processBuilder = prepareInstallCommand(chart);
63         logger.info("Installing helm chart {} from the repository {} ", chart.getChartName(), chart.getRepository());
64         executeCommand(processBuilder);
65         logger.info("Chart {} installed successfully", chart.getChartName());
66     }
67
68     /**
69      * Finds helm chart repository for the chart.
70      *
71      * @param chart ChartInfo.
72      * @return the chart repository as a string
73      * @throws ServiceException in case of error
74      * @throws IOException in case of IO errors
75      */
76     public String findChartRepository(ChartInfo chart) throws ServiceException, IOException {
77         updateHelmRepo();
78         logger.info("Looking for helm chart {} in all the configured helm repositories", chart.getChartName());
79         String repository = null;
80
81         var process = helmRepoVerifyCommand(chart.getChartName()).start();
82
83         try (var reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
84             String line = reader.readLine();
85             while (line != null) {
86                 if (line.contains(chart.getChartName())) {
87                     repository = line.split("/")[0];
88                     logger.info("Helm chart located in the repository {} ", repository);
89                     return repository;
90                 }
91                 line = reader.readLine();
92             }
93         }
94
95         var localHelmChartDir = chartStore.getAppPath(chart.getChartName(), chart.getVersion()).toString();
96         logger.info("Chart not found in helm repositories, verifying local repo {} ", localHelmChartDir);
97         if (verifyLocalHelmRepo(localHelmChartDir + "/" + chart.getChartName())) {
98             repository = localHelmChartDir;
99         }
100
101         return repository;
102     }
103
104     /**
105      * Uninstall a chart.
106      *
107      * @param chart name and version.
108      * @throws ServiceException incase of error
109      */
110     public void uninstallChart(ChartInfo chart) throws ServiceException {
111         executeCommand(prepareUnInstallCommand(chart));
112     }
113
114     static String executeCommand(ProcessBuilder processBuilder) throws ServiceException {
115         var commandStr = toString(processBuilder);
116
117         try {
118             var process = processBuilder.start();
119             process.waitFor();
120             int exitValue = process.exitValue();
121
122             if (exitValue != 0) {
123                 var error = IOUtils.toString(process.getErrorStream(), StandardCharsets.UTF_8);
124                 throw new ServiceException("Command execution failed: " + commandStr + " " + error);
125             }
126             var output = IOUtils.toString(process.getInputStream(), StandardCharsets.UTF_8);
127             logger.debug("Command <{}> execution, output: {}", commandStr, output);
128             return output;
129         } catch (InterruptedException ie) {
130             Thread.currentThread().interrupt();
131             throw new ServiceException("Failed to execute the Command: " + commandStr + ", the command was interrupted",
132                 ie);
133         } catch (Exception exc) {
134             throw new ServiceException("Failed to execute the Command: " + commandStr, exc);
135         }
136     }
137
138     private ProcessBuilder prepareInstallCommand(ChartInfo chart) {
139
140         // @formatter:off
141         List<String> helmArguments = new ArrayList<>(
142                 Arrays.asList(
143                     "helm",
144                     "install", chart.getReleaseName(), chart.getRepository() + "/" + chart.getChartName(),
145                     "--version", chart.getVersion(),
146                     "--namespace", chart.getNamespace()
147                 )
148             );
149         // @formatter:on
150
151         // Verify if values.yaml available for the chart
152         var overrideFile = chartStore.getOverrideFile(chart).getPath();
153         if (verifyLocalHelmRepo(overrideFile)) {
154             logger.info("Override yaml file available for the helm chart");
155             helmArguments.addAll(Arrays.asList("--values", overrideFile));
156         }
157
158         return new ProcessBuilder().command(helmArguments);
159     }
160
161     private ProcessBuilder prepareUnInstallCommand(ChartInfo chart) {
162         return new ProcessBuilder("helm", "delete", chart.getReleaseName(), "--namespace", chart.getNamespace());
163     }
164
165     private ProcessBuilder prepareCreateNamespaceCommand(String namespace) {
166         return new ProcessBuilder().command("kubectl", "create", "namespace", namespace);
167     }
168
169     private ProcessBuilder helmRepoVerifyCommand(String chartName) {
170         return new ProcessBuilder().command("bash", "-c", "helm search repo | grep " + chartName);
171     }
172
173     private ProcessBuilder localRepoVerifyCommand(String localFile) {
174         return new ProcessBuilder().command("bash", "-c", "ls " + localFile);
175     }
176
177     private void updateHelmRepo() throws ServiceException {
178         logger.info("Updating local helm repositories before verifying the chart");
179         List<String> helmArguments = Arrays.asList("helm", "repo", "update");
180
181         executeCommand(new ProcessBuilder().command(helmArguments));
182         logger.debug("Helm repositories updated successfully");
183     }
184
185     private boolean verifyLocalHelmRepo(String localFile) {
186         var isVerified = false;
187         var processBuilder = localRepoVerifyCommand(localFile);
188         try {
189             executeCommand(processBuilder);
190             isVerified = true;
191         } catch (ServiceException e) {
192             logger.error("Unable to verify file in local repository", e);
193         }
194         return isVerified;
195     }
196
197     protected static String toString(ProcessBuilder processBuilder) {
198         return String.join(" ", processBuilder.command());
199     }
200 }