/
chart.go
311 lines (249 loc) · 9.14 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
package helm
import (
"fmt"
"io/ioutil"
"time"
"github.com/defenseunicorns/zarf/cli/types"
"github.com/defenseunicorns/zarf/cli/internal/message"
"helm.sh/helm/v3/pkg/action"
corev1 "k8s.io/api/core/v1"
"helm.sh/helm/v3/pkg/chart"
"helm.sh/helm/v3/pkg/release"
"helm.sh/helm/v3/pkg/storage/driver"
)
type ConnectString struct {
Description string
Url string
}
type ConnectStrings map[string]ConnectString
type ChartOptions struct {
BasePath string
Chart types.ZarfChart
ReleaseName string
ChartLoadOverride string
ChartOverride *chart.Chart
ValueOverride map[string]interface{}
Component types.ZarfComponent
}
// InstallOrUpgradeChart performs a helm install of the given chart
func InstallOrUpgradeChart(options ChartOptions) ConnectStrings {
fromMessage := options.Chart.Url
if fromMessage == "" {
fromMessage = "Zarf-generated helm chart"
}
spinner := message.NewProgressSpinner("Processing helm chart %s:%s from %s",
options.Chart.Name,
options.Chart.Version,
fromMessage)
defer spinner.Stop()
var output *release.Release
options.ReleaseName = fmt.Sprintf("zarf-%s", options.Chart.Name)
actionConfig, err := createActionConfig(options.Chart.Namespace, spinner)
postRender := NewRenderer(options, actionConfig)
// Setup K8s connection
if err != nil {
spinner.Fatalf(err, "Unable to initialize the K8s client")
}
attempt := 0
for {
attempt++
spinner.Updatef("Attempt %d of 3 to install chart", attempt)
histClient := action.NewHistory(actionConfig)
histClient.Max = 1
if attempt > 2 {
// On total failure try to rollback or uninstall
if histClient.Version > 1 {
spinner.Updatef("Performing chart rollback")
_ = rollbackChart(actionConfig, options.ReleaseName)
} else {
spinner.Updatef("Performing chart uninstall")
_, _ = uninstallChart(actionConfig, options.ReleaseName)
}
spinner.Errorf(nil, "Unable to complete helm chart install/upgrade")
break
}
spinner.Updatef("Checking for existing helm deployment")
_, histErr := histClient.Run(options.ReleaseName)
switch histErr {
case driver.ErrReleaseNotFound:
// No prior release, try to install it
spinner.Updatef("Attempting chart installation")
output, err = installChart(actionConfig, options, postRender)
case nil:
// Otherwise, there is a prior release so upgrade it
spinner.Updatef("Attempting chart upgrade")
output, err = upgradeChart(actionConfig, options, postRender)
default:
// 😭 things aren't working
spinner.Fatalf(err, "Unable to verify the chart installation status")
}
if err != nil {
spinner.Debugf(err.Error())
// Simply wait for dust to settle and try again
time.Sleep(10 * time.Second)
} else {
spinner.Debugf(output.Info.Description)
spinner.Success()
break
}
}
// return any collected connect strings for zarf connect
return postRender.connectStrings
}
// TemplateChart generates a helm template from a given chart
func TemplateChart(options ChartOptions) (string, error) {
message.Debugf("helm.TemplateChart(%v)", options)
spinner := message.NewProgressSpinner("Templating helm chart %s", options.Chart.Name)
defer spinner.Stop()
actionConfig, err := createActionConfig(options.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(actionConfig)
client.DryRun = true
client.Replace = true // Skip the name check
client.ClientOnly = true
client.IncludeCRDs = true
client.ReleaseName = fmt.Sprintf("zarf-%s", options.Chart.Name)
// Namespace must be specified
client.Namespace = options.Chart.Namespace
loadedChart, chartValues, err := loadChartData(options)
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
}
func GenerateChart(basePath string, manifest types.ZarfManifest, component types.ZarfComponent) ConnectStrings {
message.Debugf("helm.GenerateChart(%s, %v, %s)", basePath, manifest, component.Name)
spinner := message.NewProgressSpinner("Starting helm chart generation %s", manifest.Name)
defer spinner.Stop()
// Use timestamp to help make a valid semver
now := time.Now()
// Generate a new chart
tmpChart := new(chart.Chart)
tmpChart.Metadata = new(chart.Metadata)
tmpChart.Metadata.Name = fmt.Sprintf("raw-%s", manifest.Name)
// This is fun, increment forward in a semver-way using epoch so helm doesn't cry
tmpChart.Metadata.Version = fmt.Sprintf("0.1.%d", now.Unix())
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 := fmt.Sprintf("%s/%s", basePath, file)
data, err := ioutil.ReadFile(manifest)
if err != nil {
spinner.Fatalf(err, "Unable to read the manifest file contents")
}
tmpChart.Templates = append(tmpChart.Templates, &chart.File{Name: manifest, Data: data})
}
if manifest.DefaultNamespace == "" {
// Helm gets sad when you don't provide a namespace even though we aren't using helm templating
manifest.DefaultNamespace = corev1.NamespaceDefault
}
// Generate the struct to pass to InstallOrUpgradeChart()
options := ChartOptions{
BasePath: basePath,
Chart: types.ZarfChart{
Name: tmpChart.Metadata.Name,
Version: tmpChart.Metadata.Version,
Namespace: manifest.DefaultNamespace,
},
ChartOverride: tmpChart,
// We don't have any values because we do not expose them in the zarf.yaml currently
ValueOverride: map[string]interface{}{},
// Images needed for eventual post-render templating
Component: component,
}
spinner.Success()
return InstallOrUpgradeChart(options)
}
func installChart(actionConfig *action.Configuration, options ChartOptions, postRender *renderer) (*release.Release, error) {
message.Debugf("helm.installChart(%v, %v, %v)", actionConfig, options, postRender)
// Bind the helm action
client := action.NewInstall(actionConfig)
// Let each chart run for 5 minutes
client.Timeout = 15 * time.Minute
client.Wait = true
// 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 = options.ReleaseName
// Namespace must be specified
client.Namespace = options.Chart.Namespace
// Post-processing our manifests for reasons....
client.PostRenderer = postRender
loadedChart, chartValues, err := loadChartData(options)
if err != nil {
return nil, fmt.Errorf("unable to load chart data: %w", err)
}
// Perform the loadedChart installation
return client.Run(loadedChart, chartValues)
}
func upgradeChart(actionConfig *action.Configuration, options ChartOptions, postRender *renderer) (*release.Release, error) {
message.Debugf("helm.upgradeChart(%v, %v, %v)", actionConfig, options, postRender)
client := action.NewUpgrade(actionConfig)
// Let each chart run for 5 minutes
client.Timeout = 10 * time.Minute
client.Wait = true
client.SkipCRDs = true
// Namespace must be specified
client.Namespace = options.Chart.Namespace
// Post-processing our manifests for reasons....
client.PostRenderer = postRender
loadedChart, chartValues, err := loadChartData(options)
if err != nil {
return nil, fmt.Errorf("unable to load chart data: %w", err)
}
// Perform the loadedChart upgrade
return client.Run(options.ReleaseName, loadedChart, chartValues)
}
func rollbackChart(actionConfig *action.Configuration, name string) error {
message.Debugf("helm.rollbackChart(%v, %s)", actionConfig, name)
client := action.NewRollback(actionConfig)
client.CleanupOnFail = true
client.Force = true
client.Wait = true
client.Timeout = 1 * time.Minute
return client.Run(name)
}
func uninstallChart(actionConfig *action.Configuration, name string) (*release.UninstallReleaseResponse, error) {
message.Debugf("helm.uninstallChart(%v, %s)", actionConfig, name)
client := action.NewUninstall(actionConfig)
client.KeepHistory = false
client.Timeout = 3 * time.Minute
client.Wait = true
return client.Run(name)
}
func loadChartData(options ChartOptions) (*chart.Chart, map[string]interface{}, error) {
message.Debugf("helm.loadChartData(%v)", options)
var (
loadedChart *chart.Chart
chartValues map[string]interface{}
err error
)
if options.ChartOverride == nil || options.ValueOverride == nil {
// If there is no override, get the chart and values info
loadedChart, err = loadChartFromTarball(options)
if err != nil {
return nil, nil, fmt.Errorf("unable to load chart tarball: %w", err)
}
chartValues, err = parseChartValues(options)
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 = options.ChartOverride
chartValues = options.ValueOverride
}
return loadedChart, chartValues, nil
}