generated from cloudoperators/repository-template
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhelm.go
655 lines (586 loc) · 24.2 KB
/
helm.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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
// SPDX-FileCopyrightText: 2024 SAP SE or an SAP affiliate company and Greenhouse contributors
// SPDX-License-Identifier: Apache-2.0
package helm
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"slices"
"sort"
"time"
"helm.sh/helm/v3/pkg/action"
"helm.sh/helm/v3/pkg/chart"
"helm.sh/helm/v3/pkg/chart/loader"
"helm.sh/helm/v3/pkg/cli"
"helm.sh/helm/v3/pkg/kube"
"helm.sh/helm/v3/pkg/registry"
"helm.sh/helm/v3/pkg/release"
"helm.sh/helm/v3/pkg/storage/driver"
"helm.sh/helm/v3/pkg/strvals"
corev1 "k8s.io/api/core/v1"
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/cli-runtime/pkg/genericclioptions"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/yaml"
greenhousev1alpha1 "github.com/cloudoperators/greenhouse/pkg/apis/greenhouse/v1alpha1"
"github.com/cloudoperators/greenhouse/pkg/clientutil"
"github.com/cloudoperators/greenhouse/pkg/metrics"
)
func init() {
// Setting the name of the app for managedFields in the Kubernetes client
kube.ManagedFieldsManager = greenhouseFieldManager
}
var (
settings = cli.New()
// IsHelmDebug is configured via a flag and enables extensive debug logging for Helm actions.
IsHelmDebug bool
// greenhouse helm timeout for install and upgrade actions
installUpgradeTimeout = 300 * time.Second
)
// driftDetectionInterval is the interval after which a drift detection is performed.
const driftDetectionInterval = 60 * time.Minute
// InstallOrUpgradeHelmChartFromPlugin installs a new or upgrades an existing Helm release for the given PluginDefinition and Plugin.
func InstallOrUpgradeHelmChartFromPlugin(ctx context.Context, local client.Client, restClientGetter genericclioptions.RESTClientGetter, pluginDefinition *greenhousev1alpha1.PluginDefinition, plugin *greenhousev1alpha1.Plugin) error {
// Early return if the pluginDefinition is not helm based
if pluginDefinition.Spec.HelmChart == nil {
metrics.UpdateMetrics(plugin, metrics.MetricResultError, metrics.MetricReasonHelmChartIsNotDefined)
return fmt.Errorf("no helm chart defined in pluginDefinition.Spec.HelmChart for pluginDefinition %s", plugin.Spec.PluginDefinition)
}
latestRelease, isReleaseExists, err := isReleaseExistsForPlugin(ctx, restClientGetter, plugin)
if err != nil {
return err
}
// A release does not exist. Install it.
if !isReleaseExists {
log.FromContext(ctx).Info("installing release for plugin", "namespace", plugin.Spec.ReleaseNamespace, "name", plugin.Name)
_, err = installRelease(ctx, local, restClientGetter, pluginDefinition, plugin, false)
metrics.UpdateMetrics(plugin, metrics.MetricResultError, metrics.MetricReasonInstallFailed)
return err
}
helmChart, err := locateChartForPlugin(restClientGetter, pluginDefinition)
if err != nil {
metrics.UpdateMetrics(plugin, metrics.MetricResultError, metrics.MetricReasonUpgradeFailed)
return err
}
// Avoid attempts to upgrade a failed release and attempt to resurrect it.
if latestRelease.Info != nil && latestRelease.Info.Status == release.StatusFailed {
log.FromContext(ctx).Info("attempting to reset release status", "current status", latestRelease.Info.Status.String())
if err := ResetHelmReleaseStatusToDeployed(restClientGetter, plugin); err != nil {
metrics.UpdateMetrics(plugin, metrics.MetricResultError, metrics.MetricReasonUpgradeFailed)
return err
}
}
// Avoid upgrading a currently pending release.
if releaseStatus, ok := isCanReleaseBeUpgraded(latestRelease); !ok {
metrics.UpdateMetrics(plugin, metrics.MetricResultError, metrics.MetricReasonUpgradeFailed)
return fmt.Errorf("cannot upgrade release %s/%s in status %s", latestRelease.Namespace, latestRelease.Name, releaseStatus.String())
}
log.FromContext(ctx).Info("upgrading release", "namespace", plugin.Spec.ReleaseNamespace, "name", plugin.Name)
c, err := clientutil.NewK8sClientFromRestClientGetter(restClientGetter)
if err != nil {
metrics.UpdateMetrics(plugin, metrics.MetricResultError, metrics.MetricReasonUpgradeFailed)
return err
}
if err := replaceCustomResourceDefinitions(ctx, c, helmChart.CRDObjects(), true); err != nil {
metrics.UpdateMetrics(plugin, metrics.MetricResultError, metrics.MetricReasonUpgradeFailed)
return err
}
if err := upgradeRelease(ctx, local, restClientGetter, pluginDefinition, plugin); err != nil {
metrics.UpdateMetrics(plugin, metrics.MetricResultError, metrics.MetricReasonUpgradeFailed)
return err
}
return nil
}
// ChartTest to do helm test on the plugin
func ChartTest(restClientGetter genericclioptions.RESTClientGetter, plugin *greenhousev1alpha1.Plugin) (bool, error) {
var hasTestHook bool
cfg, err := newHelmAction(restClientGetter, plugin.Spec.ReleaseNamespace)
if err != nil {
return hasTestHook, err
}
results, err := action.NewReleaseTesting(cfg).Run(plugin.Name)
if err != nil {
return hasTestHook, err
}
if results.Hooks != nil {
hasTestHook = slices.ContainsFunc(results.Hooks, func(h *release.Hook) bool {
return slices.Contains(h.Events, release.HookTest)
})
}
return hasTestHook, nil
}
// UninstallHelmRelease removes the Helm release for the given Plugin.
func UninstallHelmRelease(ctx context.Context, restClientGetter genericclioptions.RESTClientGetter, plugin *greenhousev1alpha1.Plugin) (releaseNotFound bool, err error) {
cfg, err := newHelmAction(restClientGetter, plugin.Spec.ReleaseNamespace)
if err != nil {
return false, err
}
_, isReleaseExists, err := isReleaseExistsForPlugin(ctx, restClientGetter, plugin)
if err != nil {
return false, err
}
settings.RESTClientGetter()
if !isReleaseExists {
return true, nil
}
uninstallAction := action.NewUninstall(cfg)
uninstallAction.KeepHistory = false
_, err = uninstallAction.Run(plugin.Name)
return false, err
}
// DiffChartToDeployedResources returns whether the Kubernetes objects, as specified in the Helm chart manifest, differ from the deployed state.
func DiffChartToDeployedResources(ctx context.Context, local client.Client, restClientGetter genericclioptions.RESTClientGetter, pluginDefinition *greenhousev1alpha1.PluginDefinition, plugin *greenhousev1alpha1.Plugin) (diffs DiffObjectList, isDrift bool, err error) {
// Shortcut: If the Helm chart was changed we can skip below templating and diffing.
var pluginStatusHelmChart string
if plugin.Status.HelmReleaseStatus != nil && plugin.Status.HelmChart != nil {
pluginStatusHelmChart = plugin.Status.HelmChart.String()
}
if pluginDefinition.Spec.HelmChart.String() != pluginStatusHelmChart {
log.FromContext(ctx).Info("observed helm chart differs from pluginDefinition helm chart", "pluginDefinition", pluginDefinition.Spec.HelmChart.String(), "plugin", pluginStatusHelmChart)
return nil, true, nil
}
helmRelease, exists, err := isReleaseExistsForPlugin(ctx, restClientGetter, plugin)
switch {
case err != nil:
return nil, false, err
case !exists:
// the release should exist if the Status.HelmReleaseStatus was set
// early return if the release was deleted
return nil, true, nil
// check if the release has the current pluginDefinition version set as description
// this description is used to reconcile the version of the Plugin
case helmRelease.Info.Description != pluginDefinition.Spec.Version:
log.FromContext(ctx).Info("deployed helm chart version differs from pluginDefinition helm chart", "pluginDefinition", helmRelease.Info.Description, "plugin", pluginDefinition.Spec.Version)
return nil, true, nil
}
helmTemplateRelease, err := TemplateHelmChartFromPlugin(ctx, local, restClientGetter, pluginDefinition, plugin)
if err != nil {
return nil, false, err
}
diffObjects, err := diffAgainstRelease(restClientGetter, plugin.Spec.ReleaseNamespace, helmTemplateRelease, helmRelease)
if err != nil {
return nil, false, err
}
diffCrds, err := diffAgainstRemoteCRDs(restClientGetter, helmRelease)
if err != nil {
return nil, false, err
}
diffObjects = append(diffObjects, diffCrds...)
if len(diffObjects) > 0 {
log.FromContext(ctx).Info("diff between manifest and release detected", "resources", diffObjects.String())
return diffObjects, false, nil
}
c := plugin.Status.StatusConditions.GetConditionByType(greenhousev1alpha1.HelmDriftDetectedCondition)
// Skip the drift detection if last DriftDetection Status Change or last Deployment was less than driftDetectionInterval ago
switch {
case c == nil: // HelmDriftDetectedCondition is not set
return nil, false, nil
case time.Since(plugin.Status.HelmReleaseStatus.LastDeployed.Time) < driftDetectionInterval: // Skip as last deployment was less than driftDetectionInterval ago
return nil, false, nil
case c.Status != metav1.ConditionUnknown && time.Since(c.LastTransitionTime.Time) < driftDetectionInterval: // Skip as HelmDriftDetectedCondition transitioned less than driftDetectionInterval ago
return nil, false, nil
}
// Skip the drift detection if nothing changed with plugin option values.
if plugin.Status.HelmReleaseStatus.PluginOptionChecksum != "" {
currentPluginOptionChecksum, err := CalculatePluginOptionChecksum(ctx, local, plugin)
if err == nil && plugin.Status.HelmReleaseStatus.PluginOptionChecksum == currentPluginOptionChecksum {
return nil, false, nil
}
}
diffObjects, err = diffAgainstLiveObjects(restClientGetter, plugin.Spec.ReleaseNamespace, helmTemplateRelease.Manifest)
if err != nil {
return nil, false, err
}
if len(diffObjects) == 0 {
return nil, false, nil
}
log.FromContext(ctx).Info("drift between deployed resources and manifest detected", "resources", diffObjects.String())
return diffObjects, true, nil
}
// ResetHelmReleaseStatusToDeployed resets the status of the release to deployed using a rollback.
func ResetHelmReleaseStatusToDeployed(restClientGetter genericclioptions.RESTClientGetter, plugin *greenhousev1alpha1.Plugin) error {
r, err := getLatestUpgradeableRelease(restClientGetter, plugin)
if err != nil {
return err
}
cfg, err := newHelmAction(restClientGetter, plugin.Spec.ReleaseNamespace)
if err != nil {
return err
}
rollbackAction := action.NewRollback(cfg)
rollbackAction.Version = r.Version
rollbackAction.DisableHooks = true
rollbackAction.Wait = true
rollbackAction.Timeout = 5 * time.Minute
rollbackAction.MaxHistory = 5
return rollbackAction.Run(r.Name)
}
// getLatestUpgradeableRelease returns the latest released that can be upgraded or an error.
func getLatestUpgradeableRelease(restClientGetter genericclioptions.RESTClientGetter, plugin *greenhousev1alpha1.Plugin) (*release.Release, error) {
cfg, err := newHelmAction(restClientGetter, plugin.Spec.ReleaseNamespace)
if err != nil {
return nil, err
}
var latest *release.Release
releases, err := action.NewHistory(cfg).Run(plugin.Name)
if err != nil {
return nil, fmt.Errorf("error retrieving releases: %w", err)
}
for _, r := range releases {
if _, canUpgrade := isCanReleaseBeUpgraded(r); canUpgrade {
if latest == nil {
latest = r
continue
}
if r.Version > latest.Version {
latest = r
}
}
}
if latest == nil {
return nil, fmt.Errorf("no release found to rollback to for plugin %s/%s", plugin.Spec.ReleaseNamespace, plugin.Name)
}
return latest, nil
}
// isReleaseExistsForPlugin checks whether a Helm release exists for the given Plugin.
func isReleaseExistsForPlugin(ctx context.Context, restClientGetter genericclioptions.RESTClientGetter, plugin *greenhousev1alpha1.Plugin) (*release.Release, bool, error) {
helmRelease, err := GetReleaseForHelmChartFromPlugin(ctx, restClientGetter, plugin)
if err != nil {
switch errors.Is(err, driver.ErrReleaseNotFound) {
case true:
return nil, false, nil
default:
return nil, false, err
}
}
return helmRelease, true, nil
}
// GetReleaseForHelmChartFromPlugin returns the Helm release for the given Plugin or an error.
func GetReleaseForHelmChartFromPlugin(_ context.Context, restClientGetter genericclioptions.RESTClientGetter, plugin *greenhousev1alpha1.Plugin) (*release.Release, error) {
cfg, err := newHelmAction(restClientGetter, plugin.Spec.ReleaseNamespace)
if err != nil {
return nil, err
}
return action.NewGet(cfg).Run(plugin.Name)
}
// TemplateHelmChartFromPlugin returns the rendered manifest or an error.
func TemplateHelmChartFromPlugin(ctx context.Context, local client.Client, restClientGetter genericclioptions.RESTClientGetter, pluginDefinition *greenhousev1alpha1.PluginDefinition, plugin *greenhousev1alpha1.Plugin) (*release.Release, error) {
helmRelease, err := installRelease(ctx, local, restClientGetter, pluginDefinition, plugin, true)
if err != nil {
return nil, err
}
return helmRelease, nil
}
type ChartLoaderFunc func(name string) (*chart.Chart, error)
var ChartLoader ChartLoaderFunc = loader.Load
func locateChartForPlugin(restClientGetter genericclioptions.RESTClientGetter, pluginDefinition *greenhousev1alpha1.PluginDefinition) (*chart.Chart, error) {
cfg, err := newHelmAction(restClientGetter, corev1.NamespaceAll)
if err != nil {
return nil, err
}
// FIXME: we need to instantiate a action to set the registry in the ChartPathOptions
cpo := &action.NewShowWithConfig(action.ShowChart, cfg).ChartPathOptions
chartName := configureChartPathOptions(cpo, pluginDefinition.Spec.HelmChart)
chartPath, err := cpo.LocateChart(chartName, settings)
if err != nil {
return nil, err
}
return ChartLoader(chartPath)
}
// configureChartPathOptions configures the ChartPathOptions and chartName considering OCI repositories.
func configureChartPathOptions(cpo *action.ChartPathOptions, c *greenhousev1alpha1.HelmChartReference) string {
cpo.RepoURL = c.Repository
cpo.Version = c.Version
chartName := c.Name
// Handle OCI.
if registry.IsOCI(c.Repository) {
cpo.RepoURL = ""
chartName = fmt.Sprintf("%s/%s", c.Repository, c.Name)
}
return chartName
}
func upgradeRelease(ctx context.Context, local client.Client, restClientGetter genericclioptions.RESTClientGetter, pluginDefinition *greenhousev1alpha1.PluginDefinition, plugin *greenhousev1alpha1.Plugin) error {
cfg, err := newHelmAction(restClientGetter, plugin.Spec.ReleaseNamespace)
if err != nil {
return err
}
upgradeAction := action.NewUpgrade(cfg)
upgradeAction.Namespace = plugin.Spec.ReleaseNamespace
upgradeAction.DependencyUpdate = true
upgradeAction.MaxHistory = 5
upgradeAction.Timeout = installUpgradeTimeout // set a timeout for the upgrade to not be stuck in pending state
upgradeAction.Description = pluginDefinition.Spec.Version
helmChart, err := loadHelmChart(&upgradeAction.ChartPathOptions, pluginDefinition.Spec.HelmChart, settings)
if err != nil {
return err
}
c, err := clientutil.NewK8sClientFromRestClientGetter(restClientGetter)
if err != nil {
return err
}
helmValues, err := getValuesForHelmChart(ctx, local, helmChart, plugin)
if err != nil {
return err
}
if err := replaceCustomResourceDefinitions(ctx, c, helmChart.CRDObjects(), true); err != nil {
return err
}
// Do the Kubernetes version check beforehand to reflect incompatibilities in the Plugin status before attempting an installation or upgrade.
if err := verifyKubeVersionIsCompatible(helmChart, cfg.Capabilities); err != nil {
return err
}
helmChart.Metadata.KubeVersion = ""
_, err = upgradeAction.RunWithContext(ctx, plugin.Name, helmChart, helmValues)
return err
}
func installRelease(ctx context.Context, local client.Client, restClientGetter genericclioptions.RESTClientGetter, pluginDefinition *greenhousev1alpha1.PluginDefinition, plugin *greenhousev1alpha1.Plugin, isDryRun bool) (*release.Release, error) {
cfg, err := newHelmAction(restClientGetter, plugin.Spec.ReleaseNamespace)
if err != nil {
return nil, err
}
installAction := action.NewInstall(cfg)
installAction.ReleaseName = plugin.Name
installAction.Namespace = plugin.Spec.ReleaseNamespace
installAction.Timeout = installUpgradeTimeout // set a timeout for the installation to not be stuck in pending state
installAction.CreateNamespace = true
installAction.DependencyUpdate = true
installAction.DryRun = isDryRun
installAction.ClientOnly = isDryRun
installAction.Description = pluginDefinition.Spec.Version
helmChart, err := loadHelmChart(&installAction.ChartPathOptions, pluginDefinition.Spec.HelmChart, settings)
if err != nil {
return nil, err
}
c, err := clientutil.NewK8sClientFromRestClientGetter(restClientGetter)
if err != nil {
return nil, err
}
if err := replaceCustomResourceDefinitions(ctx, c, helmChart.CRDObjects(), false); err != nil {
return nil, err
}
helmValues, err := getValuesForHelmChart(ctx, local, helmChart, plugin)
if err != nil {
return nil, err
}
// Do the Kubernetes version check beforehand to reflect incompatibilities in the Plugin status before attempting an installation or upgrade.
if err := verifyKubeVersionIsCompatible(helmChart, cfg.Capabilities); err != nil {
return nil, err
}
helmChart.Metadata.KubeVersion = ""
return installAction.RunWithContext(ctx, helmChart, helmValues)
}
func loadHelmChart(chartPathOptions *action.ChartPathOptions, reference *greenhousev1alpha1.HelmChartReference, settings *cli.EnvSettings) (*chart.Chart, error) {
name := filepath.Base(reference.Name)
chartPath := settings.RepositoryCache + "/" + name + "-" + reference.Version + ".tgz"
if _, err := os.Stat(chartPath); errors.Is(err, os.ErrNotExist) {
chartName := configureChartPathOptions(chartPathOptions, reference)
chartPath, err = chartPathOptions.LocateChart(chartName, settings)
if err != nil {
return nil, err
}
}
return ChartLoader(chartPath)
}
func newHelmAction(restClientGetter genericclioptions.RESTClientGetter, namespace string) (*action.Configuration, error) {
cfg := &action.Configuration{}
settings.SetNamespace(namespace)
if err := cfg.Init(restClientGetter, namespace, "secrets", debug); err != nil {
return nil, err
}
registryClient, err := registry.NewClient(
registry.ClientOptDebug(IsHelmDebug),
registry.ClientOptEnableCache(true),
registry.ClientOptWriter(os.Stderr),
registry.ClientOptCredentialsFile(settings.RegistryConfig),
)
if err != nil {
return nil, err
}
cfg.RegistryClient = registryClient
caps, err := getCapabilities(cfg)
if err != nil {
return nil, err
}
cfg.Capabilities = caps
return cfg, nil
}
func debug(format string, v ...interface{}) {
if IsHelmDebug {
format = "[debug] " + format
log.FromContext(context.Background()).Info(fmt.Sprintf(format, v...))
}
}
/*
convertFlatValuesToHelmValues shall converts flat values for a Helm chart yaml-compatible structure.
Example:
The input
global.image.registry=foobar
is transformed to
global:
image:
registry: foobar
*/
func convertFlatValuesToHelmValues(values []greenhousev1alpha1.PluginOptionValue) (map[string]interface{}, error) {
if values == nil {
return make(map[string]interface{}, 0), nil
}
helmValues := make(map[string]interface{}, 0)
for _, v := range values {
if err := strvals.ParseJSON(fmt.Sprintf("%s=%s", v.Name, v.ValueJSON()), helmValues); err != nil {
return nil, err
}
}
return helmValues, nil
}
// Taken from: https://github.com/helm/helm/blob/v3.10.3/pkg/cli/values/options.go#L99-L116
func mergeMaps(a, b map[string]interface{}) map[string]interface{} {
out := make(map[string]interface{}, len(a))
for k, v := range a {
out[k] = v
}
for k, v := range b {
if v, ok := v.(map[string]interface{}); ok {
if bv, ok := out[k]; ok {
if bv, ok := bv.(map[string]interface{}); ok {
out[k] = mergeMaps(bv, v)
continue
}
}
}
out[k] = v
}
return out
}
// getValuesForHelmChart returns a set of values to be used for Helm operations.
// The order is important as the values defined in the Helm chart can be overridden by the values defined in the Plugin.
func getValuesForHelmChart(ctx context.Context, c client.Client, helmChart *chart.Chart, plugin *greenhousev1alpha1.Plugin) (map[string]interface{}, error) {
// Copy the values from the Helm chart ensuring a non-nil map.
helmValues := mergeMaps(make(map[string]interface{}), helmChart.Values)
// Get values defined in plugin.
pluginValues, err := getValuesFromPlugin(ctx, c, plugin)
if err != nil {
return nil, err
}
helmPluginValues, err := convertFlatValuesToHelmValues(pluginValues)
if err != nil {
return nil, err
}
helmValues = mergeMaps(helmValues, helmPluginValues)
return helmValues, nil
}
func getValuesFromPlugin(ctx context.Context, c client.Client, plugin *greenhousev1alpha1.Plugin) ([]greenhousev1alpha1.PluginOptionValue, error) {
namedValues := make([]greenhousev1alpha1.PluginOptionValue, len(plugin.Spec.OptionValues))
copy(namedValues, plugin.Spec.OptionValues)
for idx, val := range namedValues {
// Values already provided on plain text don't need to be extracted.
if val.ValueFrom == nil {
continue
}
// Retrieve value from secret.
if val.ValueFrom.Secret != nil {
valFromSecret, err := getValueFromSecret(ctx, c, plugin.GetNamespace(), val.ValueFrom.Secret.Name, val.ValueFrom.Secret.Key)
if err != nil {
return nil, err
}
raw, err := json.Marshal(valFromSecret)
if err != nil {
return nil, err
}
namedValues[idx].Value = &apiextensionsv1.JSON{Raw: raw}
}
}
return namedValues, nil
}
func getValueFromSecret(ctx context.Context, c client.Client, secretNamespace, secretName, secretKey string) (string, error) {
var secret = new(corev1.Secret)
if err := c.Get(ctx, types.NamespacedName{Namespace: secretNamespace, Name: secretName}, secret); err != nil {
return "", err
}
if secret.Data == nil {
return "", fmt.Errorf("secret %s/%s is empty", secretNamespace, secretName)
}
valByte, ok := secret.Data[secretKey]
if !ok {
return "", fmt.Errorf("secret %s/%s does not contain key %s", secretNamespace, secretName, secretKey)
}
return string(valByte), nil
}
func isCanReleaseBeUpgraded(r *release.Release) (release.Status, bool) {
if r.Info == nil {
return release.StatusUnknown, false
}
// Allow the upgrade to the first release, even if it failed.
if r.Version == 1 {
return r.Info.Status, !r.Info.Status.IsPending()
}
// The release must neither be pending nor failed.
return r.Info.Status, !r.Info.Status.IsPending() && r.Info.Status != release.StatusFailed
}
func replaceCustomResourceDefinitions(ctx context.Context, c client.Client, crdList []chart.CRD, isUpgrade bool) error {
if len(crdList) == 0 {
return nil
}
for _, crdFile := range crdList {
if crdFile.File == nil || crdFile.File.Data == nil {
continue
}
// Read the manifest to an object.
crd := &apiextensionsv1.CustomResourceDefinition{}
if err := yaml.Unmarshal(crdFile.File.Data, crd); err != nil {
return err
}
// Attempt to get the CRD from the cluster.
var curObj = new(apiextensionsv1.CustomResourceDefinition)
if err := c.Get(ctx, types.NamespacedName{Namespace: "", Name: crd.GetName()}, curObj); err != nil {
if apierrors.IsNotFound(err) {
// On install or dryRun: let Helm handle the installation if the CRD doesn't exist yet.
if !isUpgrade {
continue
}
// On upgrade: re-create the CRD based on helm chart if the CRD was deleted.
if err := c.Create(ctx, crd); err != nil {
return err
}
continue
}
return err
}
// An update is used intentionally instead of a patch as esp. the last-applied-configuration annotation
// can exceed the maximum characters and might have been pruned.
// The update requires carrying over the resourceVersion from the currently deployed object.
// TODO: Check max. last-applied-configuration annotation and prune if necessary.
crd.SetResourceVersion(curObj.GetResourceVersion())
if err := c.Update(ctx, crd); err != nil {
return err
}
}
return nil
}
// CalculatePluginOptionChecksum calculates a hash of plugin option values.
// Secret-type option values are extracted first and all values are sorted to ensure that order is not important when comparing checksums.
func CalculatePluginOptionChecksum(ctx context.Context, c client.Client, plugin *greenhousev1alpha1.Plugin) (string, error) {
values, err := getValuesFromPlugin(ctx, c, plugin)
if err != nil {
return "", err
}
// Sort the option values by Name to ensure consistent ordering.
sort.Slice(values, func(i, j int) bool {
return values[i].Name < values[j].Name
})
buf := make([]byte, 0)
for _, v := range values {
buf = append(buf, []byte(v.Name)...)
buf = append(buf, v.Value.Raw...)
}
checksum := sha256.Sum256(buf)
return hex.EncodeToString(checksum[:]), nil
}