-
Notifications
You must be signed in to change notification settings - Fork 27
/
helm3lib.go
378 lines (315 loc) · 10.5 KB
/
helm3lib.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
package helm3lib
import (
"context"
"fmt"
"sort"
"strconv"
"strings"
"time"
log "github.com/sirupsen/logrus"
"helm.sh/helm/v3/pkg/action"
"helm.sh/helm/v3/pkg/chart/loader"
"helm.sh/helm/v3/pkg/chartutil"
"helm.sh/helm/v3/pkg/cli"
"helm.sh/helm/v3/pkg/kube"
"helm.sh/helm/v3/pkg/release"
"helm.sh/helm/v3/pkg/releaseutil"
"helm.sh/helm/v3/pkg/storage/driver"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
kblabels "k8s.io/apimachinery/pkg/labels"
"github.com/flant/addon-operator/pkg/app"
"github.com/flant/addon-operator/pkg/helm/client"
"github.com/flant/addon-operator/pkg/utils"
klient "github.com/flant/kube-client/client"
)
// Init runs
func Init(opts *Options) error {
hc := &LibClient{
LogEntry: log.WithField("operator.component", "helm3lib"),
}
options = opts
return hc.initAndVersion()
}
// Library use client
type LibClient struct {
KubeClient klient.Client
LogEntry *log.Entry
Namespace string
}
type Options struct {
Namespace string
HistoryMax int32
Timeout time.Duration
KubeClient klient.Client
}
var _ client.HelmClient = &LibClient{}
var options *Options
var actionConfig *action.Configuration
func NewClient(logLabels ...map[string]string) client.HelmClient {
logEntry := log.WithField("operator.component", "helm3lib")
if len(logLabels) > 0 {
logEntry = logEntry.WithFields(utils.LabelsToLogFields(logLabels[0]))
}
return &LibClient{
LogEntry: logEntry,
KubeClient: options.KubeClient,
Namespace: options.Namespace,
}
}
func (h *LibClient) CommandEnv() []string {
res := make([]string, 0)
return res
}
func (h *LibClient) WithKubeClient(client klient.Client) {
h.KubeClient = client
}
func (h *LibClient) reinitKubeClient() {
getter := cli.New().RESTClientGetter()
kc := kube.New(getter)
actionConfig.KubeClient = kc
}
// initAndVersion runs helm version command.
func (h *LibClient) initAndVersion() error {
ac := new(action.Configuration)
env := cli.New()
err := ac.Init(env.RESTClientGetter(), options.Namespace, "secrets", h.LogEntry.Debugf)
if err != nil {
return err
}
actionConfig = ac
log.Infof("Helm 3 version: %s", chartutil.DefaultCapabilities.HelmVersion.Version)
return nil
}
func (h *LibClient) DeleteSingleFailedRevision(releaseName string) error {
// No need to delete single failed revision anymore
// https://github.com/helm/helm/issues/8037#issuecomment-622217632
return nil
}
func (h *LibClient) DeleteOldFailedRevisions(releaseName string) error {
// No need to delete single failed revision anymore
// https://github.com/helm/helm/issues/8037#issuecomment-622217632
return nil
}
// LastReleaseStatus returns last known revision for release and its status
func (h *LibClient) LastReleaseStatus(releaseName string) (revision string, status string, err error) {
lastRelease, err := actionConfig.Releases.Last(releaseName)
if err != nil {
// in the Last(x) function we have the condition:
// if len(h) == 0 {
// return nil, errors.Errorf("no revision for release %q", name)
// }
// that's why we also check string representation
if err == driver.ErrReleaseNotFound || strings.HasPrefix(err.Error(), "no revision for release") {
return "0", "", fmt.Errorf("release '%s' not found\n", releaseName)
}
return "", "", err
}
return strconv.FormatInt(int64(lastRelease.Version), 10), lastRelease.Info.Status.String(), nil
}
func (h *LibClient) UpgradeRelease(releaseName string, chartName string, valuesPaths []string, setValues []string, namespace string) error {
err := h.upgradeRelease(releaseName, chartName, valuesPaths, setValues, namespace)
if err != nil {
// helm validation can fail because FeatureGate was enabled for example
// handling this case we can reinitialize kubeClient and repeat one more time by backoff
h.reinitKubeClient()
return h.upgradeRelease(releaseName, chartName, valuesPaths, setValues, namespace)
}
return nil
}
func (h *LibClient) upgradeRelease(releaseName string, chartName string, valuesPaths []string, setValues []string, namespace string) error {
upg := action.NewUpgrade(actionConfig)
if namespace != "" {
upg.Namespace = namespace
}
upg.Install = true
upg.MaxHistory = int(options.HistoryMax)
upg.Timeout = options.Timeout
chart, err := loader.Load(chartName)
if err != nil {
return err
}
var resultValues chartutil.Values
for _, vp := range valuesPaths {
values, err := chartutil.ReadValuesFile(vp)
if err != nil {
return err
}
resultValues = chartutil.CoalesceTables(resultValues, values)
}
if len(setValues) > 0 {
m := make(map[string]interface{})
for _, sv := range setValues {
arr := strings.Split(sv, "=")
if len(arr) == 2 {
m[arr[0]] = arr[1]
}
}
resultValues = chartutil.CoalesceTables(resultValues, m)
}
h.LogEntry.Infof("Running helm upgrade for release '%s' with chart '%s' in namespace '%s' ...", releaseName, chartName, namespace)
histClient := action.NewHistory(actionConfig)
// Max is not working!!! Sort the final of releases by your own
// histClient.Max = 1
releases, err := histClient.Run(releaseName)
if err == driver.ErrReleaseNotFound {
instClient := action.NewInstall(actionConfig)
if namespace != "" {
instClient.Namespace = namespace
}
instClient.Timeout = options.Timeout
instClient.ReleaseName = releaseName
instClient.UseReleaseName = true
_, err = instClient.Run(chart, resultValues)
return err
}
h.LogEntry.Infof("%d old releases found", len(releases))
if len(releases) > 0 {
// https://github.com/fluxcd/helm-controller/issues/149
// looking through this issue you can found the common error: another operation (install/upgrade/rollback) is in progress
// and hints to fix it. In the future releases of helm they will handle sudden shutdown
releaseutil.Reverse(releases, releaseutil.SortByRevision)
latestRelease := releases[0]
nsReleaseName := fmt.Sprintf("%s/%s", latestRelease.Namespace, latestRelease.Name)
h.LogEntry.Infof("Latest release '%s': revision: %d has status: %s", nsReleaseName, latestRelease.Version, latestRelease.Info.Status)
if latestRelease.Info.Status.IsPending() {
h.rollbackLatestRelease(releases)
}
}
_, err = upg.Run(releaseName, chart, resultValues)
if err != nil {
return fmt.Errorf("helm upgrade failed: %s\n", err)
}
h.LogEntry.Infof("Helm upgrade for release '%s' with chart '%s' in namespace '%s' successful", releaseName, chartName, namespace)
return nil
}
func (h *LibClient) rollbackLatestRelease(releases []*release.Release) {
latestRelease := releases[0]
nsReleaseName := fmt.Sprintf("%s/%s", latestRelease.Namespace, latestRelease.Name)
h.LogEntry.Infof("Trying to rollback '%s'", nsReleaseName)
if latestRelease.Version == 1 || options.HistoryMax == 1 || len(releases) == 1 {
rb := action.NewUninstall(actionConfig)
rb.KeepHistory = false
_, err := rb.Run(latestRelease.Name)
if err != nil {
h.LogEntry.Warnf("Failed to uninstall pending release %s: %s", nsReleaseName, err)
return
}
} else {
var previousVersion = latestRelease.Version - 1
for i := 1; i < len(releases); i++ {
if !releases[i].Info.Status.IsPending() {
previousVersion = releases[i].Version
break
}
}
rb := action.NewRollback(actionConfig)
rb.Version = previousVersion
rb.CleanupOnFail = true
err := rb.Run(latestRelease.Name)
if err != nil {
h.LogEntry.Warnf("Failed to rollback pending release %s: %s", nsReleaseName, err)
return
}
}
h.LogEntry.Infof("Rollback '%s' successful", nsReleaseName)
}
func (h *LibClient) GetReleaseValues(releaseName string) (utils.Values, error) {
gv := action.NewGetValues(actionConfig)
return gv.Run(releaseName)
}
func (h *LibClient) DeleteRelease(releaseName string) error {
h.LogEntry.Debugf("helm release '%s': execute helm uninstall", releaseName)
un := action.NewUninstall(actionConfig)
_, err := un.Run(releaseName)
if err != nil {
return fmt.Errorf("helm uninstall %s invocation error: %v\n", releaseName, err)
}
return nil
}
func (h *LibClient) IsReleaseExists(releaseName string) (bool, error) {
revision, _, err := h.LastReleaseStatus(releaseName)
if err == nil {
return true, nil
}
if revision == "0" {
return false, nil
}
return false, err
}
// ListReleases returns all known releases as strings — "<release_name>.v<release_number>"
// It is required only for helm2.
func (h *LibClient) ListReleases(labelSelector map[string]string) (releases []string, err error) {
return
}
// ListReleasesNames returns list of release names.
// Names are extracted from label "name" in Secrets with label "owner"=="helm".
func (h *LibClient) ListReleasesNames(labelSelector map[string]string) ([]string, error) {
labelsSet := make(kblabels.Set)
for k, v := range labelSelector {
labelsSet[k] = v
}
labelsSet["owner"] = "helm"
list, err := h.KubeClient.CoreV1().
Secrets(h.Namespace).
List(context.TODO(), metav1.ListOptions{LabelSelector: labelsSet.AsSelector().String()})
if err != nil {
h.LogEntry.Debugf("helm: list of release Secrets failed: %s", err)
return nil, err
}
uniqNamesMap := make(map[string]struct{})
for _, secret := range list.Items {
releaseName, has_key := secret.Labels["name"]
if has_key && releaseName != "" {
uniqNamesMap[releaseName] = struct{}{}
}
}
// Do not return ignored release.
delete(uniqNamesMap, app.HelmIgnoreRelease)
uniqNames := make([]string, 0)
for name := range uniqNamesMap {
uniqNames = append(uniqNames, name)
}
sort.Strings(uniqNames)
return uniqNames, nil
}
func (h *LibClient) Render(releaseName, chartName string, valuesPaths, setValues []string, namespace string) (string, error) {
chart, err := loader.Load(chartName)
if err != nil {
return "", err
}
var resultValues chartutil.Values
for _, vp := range valuesPaths {
values, err := chartutil.ReadValuesFile(vp)
if err != nil {
return "", err
}
resultValues = chartutil.CoalesceTables(resultValues, values)
}
if len(setValues) > 0 {
m := make(map[string]interface{})
for _, sv := range setValues {
arr := strings.Split(sv, "=")
if len(arr) == 2 {
m[arr[0]] = arr[1]
}
}
resultValues = chartutil.CoalesceTables(resultValues, m)
}
h.LogEntry.Debugf("Render helm templates for chart '%s' in namespace '%s' ...", chartName, namespace)
inst := action.NewInstall(actionConfig)
inst.DryRun = true
if namespace != "" {
inst.Namespace = namespace
}
inst.ReleaseName = releaseName
inst.UseReleaseName = true
inst.Replace = true // Skip the name check
inst.IsUpgrade = true
inst.DisableOpenAPIValidation = true
rs, err := inst.Run(chart, resultValues)
if err != nil {
return "", err
}
h.LogEntry.Infof("Render helm templates for chart '%s' was successful", chartName)
return rs.Manifest, nil
}