-
Notifications
You must be signed in to change notification settings - Fork 171
/
chart.go
362 lines (288 loc) · 10.7 KB
/
chart.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: 2021-Present The Zarf Authors
// Package helm contains operations for working with helm charts.
package helm
import (
"crypto/sha1"
"encoding/hex"
"fmt"
"os"
"path"
"strconv"
"time"
"github.com/defenseunicorns/zarf/src/config"
"github.com/defenseunicorns/zarf/src/types"
"github.com/defenseunicorns/zarf/src/pkg/message"
"helm.sh/helm/v3/pkg/action"
"helm.sh/helm/v3/pkg/chart"
"helm.sh/helm/v3/pkg/release"
"helm.sh/helm/v3/pkg/storage/driver"
)
// Set the default helm client timeout to 15 minutes
const defaultClientTimeout = 15 * time.Minute
// InstallOrUpgradeChart performs a helm install of the given chart.
func (h *Helm) InstallOrUpgradeChart() (types.ConnectStrings, string, error) {
fromMessage := h.Chart.URL
if fromMessage == "" {
fromMessage = "Zarf-generated helm chart"
}
spinner := message.NewProgressSpinner("Processing helm chart %s:%s from %s",
h.Chart.Name,
h.Chart.Version,
fromMessage)
defer spinner.Stop()
var output *release.Release
h.ReleaseName = h.Chart.ReleaseName
// If no release name is specified, use the chart name.
if h.ReleaseName == "" {
h.ReleaseName = h.Chart.Name
}
// Do not wait for the chart to be ready if data injections are present.
if len(h.Component.DataInjections) > 0 {
spinner.Updatef("Data injections detected, not waiting for chart to be ready")
h.Chart.NoWait = true
}
// Setup K8s connection.
err := h.createActionConfig(h.Chart.Namespace, spinner)
if err != nil {
return nil, "", fmt.Errorf("unable to initialize the K8s client: %w", err)
}
postRender, err := h.newRenderer()
if err != nil {
return nil, "", fmt.Errorf("unable to create helm renderer: %w", err)
}
attempt := 0
for {
attempt++
spinner.Updatef("Attempt %d of 4 to install chart", attempt)
histClient := action.NewHistory(h.actionConfig)
histClient.Max = 1
releases, histErr := histClient.Run(h.ReleaseName)
if attempt > 4 {
previouslyDeployed := false
// Check for previous releases that successfully deployed
for _, release := range releases {
if release.Info.Status == "deployed" {
previouslyDeployed = true
}
}
// On total failure try to rollback or uninstall.
if previouslyDeployed {
spinner.Updatef("Performing chart rollback")
err = h.rollbackChart(h.ReleaseName)
if err != nil {
return nil, "", fmt.Errorf("unable to upgrade chart after 4 attempts and unable to rollback: %s", err.Error())
}
return nil, "", fmt.Errorf("unable to upgrade chart after 4 attempts")
} else {
spinner.Updatef("Performing chart uninstall")
_, err = h.uninstallChart(h.ReleaseName)
if err != nil {
return nil, "", fmt.Errorf("unable to install chart after 4 attempts and unable to uninstall: %s", err.Error())
}
return nil, "", fmt.Errorf("unable to install chart after 4 attempts")
}
}
spinner.Updatef("Checking for existing helm deployment")
switch histErr {
case driver.ErrReleaseNotFound:
// No prior release, try to install it.
spinner.Updatef("Attempting chart installation")
output, err = h.installChart(postRender)
case nil:
// Otherwise, there is a prior release so upgrade it.
spinner.Updatef("Attempting chart upgrade")
output, err = h.upgradeChart(postRender)
default:
// 😭 things aren't working
return nil, "", fmt.Errorf("unable to verify the chart installation status: %w", histErr)
}
if err != nil {
spinner.Errorf(err, "Unable to complete helm chart install/upgrade, waiting 10 seconds and trying again")
// Simply wait for dust to settle and try again.
time.Sleep(10 * time.Second)
} else {
message.Debug(output.Info.Description)
spinner.Success()
break
}
}
// return any collected connect strings for zarf connect.
return postRender.connectStrings, h.ReleaseName, nil
}
// TemplateChart generates a helm template from a given chart.
func (h *Helm) TemplateChart() (string, error) {
message.Debugf("helm.TemplateChart()")
spinner := message.NewProgressSpinner("Templating helm chart %s", h.Chart.Name)
defer spinner.Stop()
err := h.createActionConfig(h.Chart.Namespace, spinner)
// Setup K8s connection.
if err != nil {
return "", fmt.Errorf("unable to initialize the K8s client: %w", err)
}
// Bind the helm action.
client := action.NewInstall(h.actionConfig)
client.DryRun = true
client.Replace = true // Skip the name check.
client.ClientOnly = true
client.IncludeCRDs = true
// TODO: Further research this with regular/OCI charts
client.Verify = false
client.InsecureSkipTLSverify = config.CommonOptions.Insecure
client.ReleaseName = h.Chart.ReleaseName
// If no release name is specified, use the chart name.
if client.ReleaseName == "" {
client.ReleaseName = h.Chart.Name
}
// Namespace must be specified.
client.Namespace = h.Chart.Namespace
loadedChart, chartValues, err := h.loadChartData()
if err != nil {
return "", fmt.Errorf("unable to load chart data: %w", err)
}
// Perform the loadedChart installation.
templatedChart, err := client.Run(loadedChart, chartValues)
if err != nil {
return "", fmt.Errorf("error generating helm chart template: %w", err)
}
spinner.Success()
return templatedChart.Manifest, nil
}
// GenerateChart generates a helm chart for a given Zarf manifest.
func (h *Helm) GenerateChart(manifest types.ZarfManifest) error {
message.Debugf("helm.GenerateChart(%#v)", manifest)
spinner := message.NewProgressSpinner("Starting helm chart generation %s", manifest.Name)
defer spinner.Stop()
// Generate a new chart.
tmpChart := new(chart.Chart)
tmpChart.Metadata = new(chart.Metadata)
// Generate a hashed chart name.
rawChartName := fmt.Sprintf("raw-%s-%s-%s", h.Cfg.Pkg.Metadata.Name, h.Component.Name, manifest.Name)
hasher := sha1.New()
hasher.Write([]byte(rawChartName))
tmpChart.Metadata.Name = rawChartName
sha1ReleaseName := hex.EncodeToString(hasher.Sum(nil))
// This is fun, increment forward in a semver-way using epoch so helm doesn't cry.
tmpChart.Metadata.Version = fmt.Sprintf("0.1.%d", config.GetStartTime())
tmpChart.Metadata.APIVersion = chart.APIVersionV1
// Add the manifest files so helm does its thing.
for _, file := range manifest.Files {
spinner.Updatef("Processing %s", file)
manifest := path.Join(h.BasePath, file)
data, err := os.ReadFile(manifest)
if err != nil {
return fmt.Errorf("unable to read manifest file %s: %w", manifest, err)
}
// Escape all chars and then wrap in {{ }}.
txt := strconv.Quote(string(data))
data = []byte("{{" + txt + "}}")
tmpChart.Templates = append(tmpChart.Templates, &chart.File{Name: manifest, Data: data})
}
// Generate the struct to pass to InstallOrUpgradeChart().
h.Chart = types.ZarfChart{
Name: tmpChart.Metadata.Name,
// Preserve the zarf prefix for chart names to match v0.22.x and earlier behavior.
ReleaseName: fmt.Sprintf("zarf-%s", sha1ReleaseName),
Version: tmpChart.Metadata.Version,
Namespace: manifest.Namespace,
NoWait: manifest.NoWait,
}
h.ChartOverride = tmpChart
// We don't have any values because we do not expose them in the zarf.yaml currently.
h.ValueOverride = map[string]any{}
spinner.Success()
return nil
}
// RemoveChart removes a chart from the cluster.
func (h *Helm) RemoveChart(namespace string, name string, spinner *message.Spinner) error {
// Establish a new actionConfig for the namespace.
_ = h.createActionConfig(namespace, spinner)
// Perform the uninstall.
response, err := h.uninstallChart(name)
message.Debug(response)
return err
}
func (h *Helm) installChart(postRender *renderer) (*release.Release, error) {
message.Debugf("helm.installChart(%#v)", postRender)
// Bind the helm action.
client := action.NewInstall(h.actionConfig)
// Let each chart run for the default timeout.
client.Timeout = defaultClientTimeout
// Default helm behavior for Zarf is to wait for the resources to deploy, NoWait overrides that for special cases (such as data-injection).
client.Wait = !h.Chart.NoWait
// We need to include CRDs or operator installations will fail spectacularly.
client.SkipCRDs = false
// Must be unique per-namespace and < 53 characters. @todo: restrict helm loadedChart name to this.
client.ReleaseName = h.ReleaseName
// Namespace must be specified.
client.Namespace = h.Chart.Namespace
// Post-processing our manifests for reasons....
client.PostRenderer = postRender
loadedChart, chartValues, err := h.loadChartData()
if err != nil {
return nil, fmt.Errorf("unable to load chart data: %w", err)
}
// Perform the loadedChart installation.
return client.Run(loadedChart, chartValues)
}
func (h *Helm) upgradeChart(postRender *renderer) (*release.Release, error) {
message.Debugf("helm.upgradeChart(%#v)", postRender)
client := action.NewUpgrade(h.actionConfig)
// Let each chart run for the default timeout.
client.Timeout = defaultClientTimeout
// Default helm behavior for Zarf is to wait for the resources to deploy, NoWait overrides that for special cases (such as data-injection).
client.Wait = !h.Chart.NoWait
client.SkipCRDs = true
// Namespace must be specified.
client.Namespace = h.Chart.Namespace
// Post-processing our manifests for reasons....
client.PostRenderer = postRender
loadedChart, chartValues, err := h.loadChartData()
if err != nil {
return nil, fmt.Errorf("unable to load chart data: %w", err)
}
// Perform the loadedChart upgrade.
return client.Run(h.ReleaseName, loadedChart, chartValues)
}
func (h *Helm) rollbackChart(name string) error {
message.Debugf("helm.rollbackChart(%s)", name)
client := action.NewRollback(h.actionConfig)
client.CleanupOnFail = true
client.Force = true
client.Wait = true
client.Timeout = defaultClientTimeout
return client.Run(name)
}
func (h *Helm) uninstallChart(name string) (*release.UninstallReleaseResponse, error) {
message.Debugf("helm.uninstallChart(%s)", name)
client := action.NewUninstall(h.actionConfig)
client.KeepHistory = false
client.Wait = true
client.Timeout = defaultClientTimeout
return client.Run(name)
}
func (h *Helm) loadChartData() (*chart.Chart, map[string]any, error) {
message.Debugf("helm.loadChartData()")
var (
loadedChart *chart.Chart
chartValues map[string]any
err error
)
if h.ChartOverride == nil || h.ValueOverride == nil {
// If there is no override, get the chart and values info.
loadedChart, err = h.loadChartFromTarball()
if err != nil {
return nil, nil, fmt.Errorf("unable to load chart tarball: %w", err)
}
chartValues, err = h.parseChartValues()
if err != nil {
return loadedChart, nil, fmt.Errorf("unable to parse chart values: %w", err)
}
message.Debug(chartValues)
} else {
// Otherwise, use the overrides instead.
loadedChart = h.ChartOverride
chartValues = h.ValueOverride
}
return loadedChart, chartValues, nil
}