1b7599ce967abc7a133608d740457941830e7753
[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     /**
51      * Install a chart.
52      *
53      * @param chart name and version.
54      * @throws ServiceException incase of error
55      */
56     public void installChart(ChartInfo chart) throws ServiceException {
57         var processBuilder = prepareCreateNamespaceCommand(chart.getNamespace());
58         try {
59             executeCommand(processBuilder);
60         } catch (ServiceException e) {
61             logger.warn("Namespace not created", e);
62         }
63         processBuilder = prepareInstallCommand(chart);
64         logger.info("Installing helm chart {} from the repository {} ", chart.getChartName(), chart.getRepository());
65         executeCommand(processBuilder);
66         logger.info("Chart {} installed successfully", chart.getChartName());
67     }
68
69     /**
70      * Finds helm chart repository for the chart.
71      *
72      * @param chart ChartInfo.
73      * @throws ServiceException incase of error
74      */
75     public String findChartRepository(ChartInfo chart) throws ServiceException, IOException {
76         updateHelmRepo();
77         logger.info("Looking for helm chart {} in all the configured helm repositories", chart.getChartName());
78         String repository = null;
79
80         var process = helmRepoVerifyCommand(chart.getChartName()).start();
81
82         try (var reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
83             String line = reader.readLine();
84             while (line != null) {
85                 if (line.contains(chart.getChartName())) {
86                     repository = line.split("/")[0];
87                     logger.info("Helm chart located in the repository {} ", repository);
88                     return repository;
89                 }
90                 line = reader.readLine();
91             }
92         }
93
94         var localHelmChartDir = chartStore.getAppPath(chart.getChartName(), chart.getVersion()).toString();
95         logger.info("Chart not found in helm repositories, verifying local repo {} ", localHelmChartDir);
96         if (verifyLocalHelmRepo(localHelmChartDir + "/" + chart.getChartName())) {
97             repository = localHelmChartDir;
98         }
99
100         return repository;
101     }
102
103     /**
104      * Uninstall a chart.
105      *
106      * @param chart name and version.
107      * @throws ServiceException incase of error
108      */
109     public void uninstallChart(ChartInfo chart) throws ServiceException {
110         executeCommand(prepareUnInstallCommand(chart));
111     }
112
113     static String executeCommand(ProcessBuilder processBuilder) throws ServiceException {
114         var commandStr = toString(processBuilder);
115
116         try {
117             var process = processBuilder.start();
118             process.waitFor();
119             int exitValue = process.exitValue();
120
121             if (exitValue != 0) {
122                 var error = IOUtils.toString(process.getErrorStream(), StandardCharsets.UTF_8);
123                 throw new ServiceException("Command execution failed: " + commandStr + " " + error);
124             }
125             var output = IOUtils.toString(process.getInputStream(), StandardCharsets.UTF_8);
126             logger.debug("Command <{}> execution, output: {}", commandStr, output);
127             return output;
128         } catch (InterruptedException ie) {
129             Thread.currentThread().interrupt();
130             throw new ServiceException(
131                     "Failed to execute the Command: " + commandStr + ", the command was interrupted", ie);
132         } catch (Exception exc) {
133             throw new ServiceException("Failed to execute the Command: " + commandStr, exc);
134         }
135     }
136
137     private ProcessBuilder prepareInstallCommand(ChartInfo chart) {
138
139         // @formatter:off
140         List<String> helmArguments = new ArrayList<>(
141                 Arrays.asList(
142                         "helm",
143                         "install", chart.getReleaseName(), chart.getRepository() + "/" + chart.getChartName(),
144                         "--version", chart.getVersion(),
145                         "--namespace", chart.getNamespace()
146                 )
147         );
148         // @formatter:on
149
150         // Verify if values.yaml available for the chart
151         var overrideFile = chartStore.getOverrideFile(chart).getPath();
152         if (verifyLocalHelmRepo(overrideFile)) {
153             logger.info("Override yaml file available for the helm chart");
154             helmArguments.addAll(Arrays.asList("--values", overrideFile));
155         }
156
157         return new ProcessBuilder().command(helmArguments);
158     }
159
160     private ProcessBuilder prepareUnInstallCommand(ChartInfo chart) {
161         return new ProcessBuilder("helm", "delete", chart.getReleaseName(), "--namespace", chart.getNamespace());
162     }
163
164     private ProcessBuilder prepareCreateNamespaceCommand(String namespace) {
165         return new ProcessBuilder().command("kubectl", "create", "namespace", namespace);
166     }
167
168     private ProcessBuilder helmRepoVerifyCommand(String chartName) {
169         return new ProcessBuilder().command("bash", "-c", "helm search repo | grep " + chartName);
170     }
171
172     private ProcessBuilder localRepoVerifyCommand(String localFile) {
173         return new ProcessBuilder().command("bash", "-c", "ls " + localFile);
174     }
175
176     private void updateHelmRepo() throws ServiceException {
177         logger.info("Updating local helm repositories before verifying the chart");
178         List<String> helmArguments = Arrays.asList("helm", "repo", "update");
179
180         executeCommand(new ProcessBuilder().command(helmArguments));
181         logger.debug("Helm repositories updated successfully");
182     }
183
184     private boolean verifyLocalHelmRepo(String localFile) {
185         var isVerified = false;
186         var processBuilder = localRepoVerifyCommand(localFile);
187         try {
188             executeCommand(processBuilder);
189             isVerified = true;
190         } catch (ServiceException e) {
191             logger.error("Unable to verify file in local repository", e);
192         }
193         return isVerified;
194     }
195
196     protected static String toString(ProcessBuilder processBuilder) {
197         return String.join(" ", processBuilder.command());
198     }
199 }