forked from opskumu/helm-wrapper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
releases.go
727 lines (639 loc) · 19.2 KB
/
releases.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
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
package main
import (
"fmt"
"io"
"net/url"
"os"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/golang/glog"
"github.com/pkg/errors"
"helm.sh/helm/v3/pkg/action"
"helm.sh/helm/v3/pkg/chart"
"helm.sh/helm/v3/pkg/chart/loader"
"helm.sh/helm/v3/pkg/downloader"
"helm.sh/helm/v3/pkg/getter"
"helm.sh/helm/v3/pkg/release"
"helm.sh/helm/v3/pkg/storage/driver"
"helm.sh/helm/v3/pkg/strvals"
helmtime "helm.sh/helm/v3/pkg/time"
"sigs.k8s.io/yaml"
)
type releaseInfo struct {
Revision int `json:"revision"`
Updated helmtime.Time `json:"updated"`
Status string `json:"status"`
Chart string `json:"chart"`
AppVersion string `json:"app_version"`
Description string `json:"description"`
}
type releaseHistory []releaseInfo
type releaseElement struct {
Name string `json:"name"`
Namespace string `json:"namespace"`
Revision string `json:"revision"`
Updated string `json:"updated"`
Status string `json:"status"`
Chart string `json:"chart"`
ChartVersion string `json:"chart_version"`
AppVersion string `json:"app_version"`
Notes string `json:"notes,omitempty"`
// TODO: Test Suite?
}
type releaseOptions struct {
// common
DryRun bool `json:"dry_run"`
DisableHooks bool `json:"disable_hooks"`
Wait bool `json:"wait"`
Devel bool `json:"devel"`
Description string `json:"description"`
Atomic bool `json:"atomic"`
SkipCRDs bool `json:"skip_crds"`
SubNotes bool `json:"sub_notes"`
Timeout time.Duration `json:"timeout"`
WaitForJobs bool `json:"wait_for_jobs"`
DisableOpenAPIValidation bool `json:"disable_open_api_validation"`
Values string `json:"values"`
SetValues []string `json:"set"`
SetStringValues []string `json:"set_string"`
ChartPathOptions
// only install
CreateNamespace bool `json:"create_namespace"`
DependencyUpdate bool `json:"dependency_update"`
// only upgrade
Install bool `json:"install"`
// only rollback
MaxHistory int `json:"history_max"`
// upgrade or rollback
Force bool `json:"force"`
Recreate bool `json:"recreate"`
ReuseValues bool `json:"reuse_values"`
CleanupOnFail bool `json:"cleanup_on_fail"`
}
// ChartPathOptions captures common options used for controlling chart paths
type ChartPathOptions struct {
CaFile string `json:"ca_file"` // --ca-file
CertFile string `json:"cert_file"` // --cert-file
KeyFile string `json:"key_file"` // --key-file
InsecureSkipTLSverify bool `json:"insecure_skip_verify"` // --insecure-skip-verify
Keyring string `json:"keyring"` // --keyring
Password string `json:"password"` // --password
RepoURL string `json:"repo"` // --repo
Username string `json:"username"` // --username
Verify bool `json:"verify"` // --verify
Version string `json:"version"` // --version
}
// helm List struct
type releaseListOptions struct {
// All ignores the limit/offset
All bool `json:"all"`
// AllNamespaces searches across namespaces
AllNamespaces bool `json:"all_namespaces"`
// Overrides the default lexicographic sorting
ByDate bool `json:"by_date"`
SortReverse bool `json:"sort_reverse"`
// Limit is the number of items to return per Run()
Limit int `json:"limit"`
// Offset is the starting index for the Run() call
Offset int `json:"offset"`
// Filter is a filter that is applied to the results
Filter string `json:"filter"`
Uninstalled bool `json:"uninstalled"`
Superseded bool `json:"superseded"`
Uninstalling bool `json:"uninstalling"`
Deployed bool `json:"deployed"`
Failed bool `json:"failed"`
Pending bool `json:"pending"`
}
func formatChartname(c *chart.Chart) string {
if c == nil || c.Metadata == nil {
// This is an edge case that has happened in prod, though we don't
// know how: https://github.com/helm/helm/issues/1347
return "MISSING"
}
return fmt.Sprintf("%s-%s", c.Name(), c.Metadata.Version)
}
func formatAppVersion(c *chart.Chart) string {
if c == nil || c.Metadata == nil {
// This is an edge case that has happened in prod, though we don't
// know how: https://github.com/helm/helm/issues/1347
return "MISSING"
}
return c.AppVersion()
}
func mergeValues(options releaseOptions) (map[string]interface{}, error) {
vals := map[string]interface{}{}
values, err := readValues(options.Values)
if err != nil {
return vals, err
}
err = yaml.Unmarshal(values, &vals)
if err != nil {
return vals, fmt.Errorf("failed parsing values")
}
for _, value := range options.SetValues {
if err := strvals.ParseInto(value, vals); err != nil {
return vals, fmt.Errorf("failed parsing set data")
}
}
for _, value := range options.SetStringValues {
if err := strvals.ParseIntoString(value, vals); err != nil {
return vals, fmt.Errorf("failed parsing set_string data")
}
}
return vals, nil
}
func getReleaseHistory(rls []*release.Release) (history releaseHistory) {
for i := len(rls) - 1; i >= 0; i-- {
r := rls[i]
c := formatChartname(r.Chart)
s := r.Info.Status.String()
v := r.Version
d := r.Info.Description
a := formatAppVersion(r.Chart)
rInfo := releaseInfo{
Revision: v,
Status: s,
Chart: c,
AppVersion: a,
Description: d,
}
if !r.Info.LastDeployed.IsZero() {
rInfo.Updated = r.Info.LastDeployed
}
history = append(history, rInfo)
}
return history
}
func constructReleaseElement(r *release.Release, showStatus bool) releaseElement {
element := releaseElement{
Name: r.Name,
Namespace: r.Namespace,
Revision: strconv.Itoa(r.Version),
Status: r.Info.Status.String(),
Chart: r.Chart.Metadata.Name,
ChartVersion: r.Chart.Metadata.Version,
AppVersion: r.Chart.Metadata.AppVersion,
}
if showStatus {
element.Notes = r.Info.Notes
}
t := "-"
if tspb := r.Info.LastDeployed; !tspb.IsZero() {
t = tspb.String()
}
element.Updated = t
return element
}
func isChartInstallable(ch *chart.Chart) (bool, error) {
switch ch.Metadata.Type {
case "", "application":
return true, nil
}
return false, errors.Errorf("%s charts are not installable", ch.Metadata.Type)
}
func showReleaseInfo(c *gin.Context) {
name := c.Param("release")
namespace := c.Param("namespace")
info := c.Query("info")
kubeConfig := c.Query("kube_config")
if info == "" {
info = "values"
}
kubeContext := c.Query("kube_context")
infos := []string{"hooks", "manifest", "notes", "values"}
infoMap := map[string]bool{}
for _, i := range infos {
infoMap[i] = true
}
if _, ok := infoMap[info]; !ok {
respErr(c, fmt.Errorf("bad info %s, release info only support hooks/manifest/notes/values", info))
return
}
actionConfig, err := actionConfigInit(InitKubeInformation(namespace, kubeContext, kubeConfig, c))
if err != nil {
respErr(c, err)
return
}
if info == "values" {
output := c.Query("output")
// get values output format
if output == "" {
output = "json"
}
if output != "json" && output != "yaml" {
respErr(c, fmt.Errorf("invalid format type %s, output only support json/yaml", output))
return
}
client := action.NewGetValues(actionConfig)
results, err := client.Run(name)
if err != nil {
respErr(c, err)
return
}
if output == "yaml" {
obj, err := yaml.Marshal(results)
if err != nil {
respErr(c, err)
return
}
respOK(c, string(obj))
return
}
respOK(c, results)
return
}
client := action.NewGet(actionConfig)
results, err := client.Run(name)
if err != nil {
respErr(c, err)
return
}
// TODO: support all
if info == "hooks" {
if len(results.Hooks) < 1 {
respOK(c, []*release.Hook{})
return
}
respOK(c, results.Hooks)
return
} else if info == "manifest" {
respOK(c, results.Manifest)
return
} else if info == "notes" {
respOK(c, results.Info.Notes)
return
}
}
func installRelease(c *gin.Context) {
name := c.Param("release")
namespace := c.Param("namespace")
aimChart := c.Query("chart")
kubeContext := c.Query("kube_context")
kubeConfig := c.Query("kube_config")
if aimChart == "" {
respErr(c, fmt.Errorf("chart name can not be empty"))
return
}
// install with local uploaded charts, *.tgz
splitChart := strings.Split(aimChart, ".")
if splitChart[len(splitChart)-1] == "tgz" && !strings.Contains(aimChart, ":") {
aimChart = helmConfig.UploadPath + "/" + aimChart
}
var options releaseOptions
err := c.ShouldBindJSON(&options)
if err != nil && err != io.EOF {
respErr(c, err)
return
}
if err = runInstall(name, namespace, kubeContext, aimChart, kubeConfig, c, options); err != nil {
respErr(c, err)
return
}
respOK(c, err)
return
}
func runInstall(name, namespace, kubeContext, aimChart, kubeConfig string, ginContext *gin.Context, options releaseOptions) (err error) {
vals, err := mergeValues(options)
if err != nil {
return
}
actionConfig, err := actionConfigInit(InitKubeInformation(namespace, kubeContext, kubeConfig, ginContext))
if err != nil {
return
}
client := action.NewInstall(actionConfig)
client.ReleaseName = name
client.Namespace = namespace
// merge install options
client.DryRun = options.DryRun
client.DisableHooks = options.DisableHooks
client.Wait = options.Wait
client.Timeout = options.Timeout
client.WaitForJobs = options.WaitForJobs
client.Devel = options.Devel
client.Description = options.Description
client.Atomic = options.Atomic
client.SkipCRDs = options.SkipCRDs
client.SubNotes = options.SubNotes
client.DisableOpenAPIValidation = options.DisableOpenAPIValidation
client.Timeout = options.Timeout
client.CreateNamespace = options.CreateNamespace
client.DependencyUpdate = options.DependencyUpdate
// merge chart path options
client.ChartPathOptions.CaFile = options.ChartPathOptions.CaFile
client.ChartPathOptions.CertFile = options.ChartPathOptions.CertFile
client.ChartPathOptions.KeyFile = options.ChartPathOptions.KeyFile
client.ChartPathOptions.InsecureSkipTLSverify = options.ChartPathOptions.InsecureSkipTLSverify
client.ChartPathOptions.Keyring = options.ChartPathOptions.Keyring
client.ChartPathOptions.Password = options.ChartPathOptions.Password
client.ChartPathOptions.RepoURL = options.ChartPathOptions.RepoURL
client.ChartPathOptions.Username = options.ChartPathOptions.Username
client.ChartPathOptions.Verify = options.ChartPathOptions.Verify
client.ChartPathOptions.Version = options.ChartPathOptions.Version
cp, err := client.ChartPathOptions.LocateChart(aimChart, settings)
if err != nil {
return
}
chartRequested, err := loader.Load(cp)
if err != nil {
return
}
validInstallableChart, err := isChartInstallable(chartRequested)
if !validInstallableChart {
return
}
if req := chartRequested.Metadata.Dependencies; req != nil {
// If CheckDependencies returns an error, we have unfulfilled dependencies.
// As of Helm 2.4.0, this is treated as a stopping condition:
// https://github.com/helm/helm/issues/2209
if err = action.CheckDependencies(chartRequested, req); err != nil {
if client.DependencyUpdate {
man := &downloader.Manager{
ChartPath: cp,
Keyring: client.ChartPathOptions.Keyring,
SkipUpdate: false,
Getters: getter.All(settings),
RepositoryConfig: settings.RepositoryConfig,
RepositoryCache: settings.RepositoryCache,
}
if err = man.Update(); err != nil {
return
}
} else {
return
}
}
}
_, err = client.Run(chartRequested, vals)
if err != nil {
return
}
return nil
}
func uninstallRelease(c *gin.Context) {
name := c.Param("release")
namespace := c.Param("namespace")
kubeContext := c.Query("kube_context")
kubeConfig := c.Query("kube_config")
actionConfig, err := actionConfigInit(InitKubeInformation(namespace, kubeContext, kubeConfig, c))
if err != nil {
respErr(c, err)
return
}
client := action.NewUninstall(actionConfig)
_, err = client.Run(name)
if err != nil {
respErr(c, err)
return
}
respOK(c, nil)
}
func rollbackRelease(c *gin.Context) {
name := c.Param("release")
namespace := c.Param("namespace")
reversionStr := c.Param("reversion")
kubeContext := c.Query("kube_context")
kubeConfig := c.Query("kube_config")
reversion, err := strconv.Atoi(reversionStr)
if err != nil {
respErr(c, err)
return
}
var options releaseOptions
err = c.ShouldBindJSON(&options)
if err != nil && err != io.EOF {
respErr(c, err)
return
}
actionConfig, err := actionConfigInit(InitKubeInformation(namespace, kubeContext, kubeConfig, c))
if err != nil {
respErr(c, err)
return
}
client := action.NewRollback(actionConfig)
client.Version = reversion
// merge rollback options
client.CleanupOnFail = options.CleanupOnFail
client.Wait = options.Wait
client.DryRun = options.DryRun
client.DisableHooks = options.DisableHooks
client.Force = options.Force
client.Recreate = options.Recreate
client.MaxHistory = options.MaxHistory
client.Timeout = options.Timeout
err = client.Run(name)
if err != nil {
respErr(c, err)
return
}
respOK(c, nil)
}
func upgradeRelease(c *gin.Context) {
name := c.Param("release")
namespace := c.Param("namespace")
aimChart := c.Query("chart")
kubeContext := c.Query("kube_context")
kubeConfig := c.Query("kube_config")
if aimChart == "" {
respErr(c, fmt.Errorf("chart name can not be empty"))
return
}
// upgrade with local uploaded charts *.tgz
splitChart := strings.Split(aimChart, ".")
if splitChart[len(splitChart)-1] == "tgz" {
aimChart = helmConfig.UploadPath + "/" + aimChart
}
var options releaseOptions
err := c.ShouldBindJSON(&options)
if err != nil && err != io.EOF {
respErr(c, err)
return
}
vals, err := mergeValues(options)
if err != nil {
respErr(c, err)
return
}
actionConfig, err := actionConfigInit(InitKubeInformation(namespace, kubeContext, kubeConfig, c))
if err != nil {
respErr(c, err)
return
}
client := action.NewUpgrade(actionConfig)
client.Namespace = namespace
// merge upgrade options
client.DryRun = options.DryRun
client.DisableHooks = options.DisableHooks
client.Wait = options.Wait
client.Devel = options.Devel
client.Description = options.Description
client.Atomic = options.Atomic
client.SkipCRDs = options.SkipCRDs
client.SubNotes = options.SubNotes
client.Timeout = options.Timeout
client.Force = options.Force
client.Install = options.Install
client.Recreate = options.Recreate
client.ReuseValues = options.ReuseValues
client.CleanupOnFail = options.CleanupOnFail
// merge chart path options
client.ChartPathOptions.CaFile = options.ChartPathOptions.CaFile
client.ChartPathOptions.CertFile = options.ChartPathOptions.CertFile
client.ChartPathOptions.KeyFile = options.ChartPathOptions.KeyFile
client.ChartPathOptions.InsecureSkipTLSverify = options.ChartPathOptions.InsecureSkipTLSverify
client.ChartPathOptions.Keyring = options.ChartPathOptions.Keyring
client.ChartPathOptions.Password = options.ChartPathOptions.Password
client.ChartPathOptions.RepoURL = options.ChartPathOptions.RepoURL
client.ChartPathOptions.Username = options.ChartPathOptions.Username
client.ChartPathOptions.Verify = options.ChartPathOptions.Verify
client.ChartPathOptions.Version = options.ChartPathOptions.Version
cp, err := client.ChartPathOptions.LocateChart(aimChart, settings)
if err != nil {
respErr(c, err)
return
}
chartRequested, err := loader.Load(cp)
if err != nil {
respErr(c, err)
return
}
if req := chartRequested.Metadata.Dependencies; req != nil {
if err := action.CheckDependencies(chartRequested, req); err != nil {
respErr(c, err)
return
}
}
if client.Install {
hisClient := action.NewHistory(actionConfig)
hisClient.Max = 1
if _, err := hisClient.Run(name); err == driver.ErrReleaseNotFound {
err = runInstall(name, namespace, kubeContext, aimChart, kubeConfig, c, options)
if err != nil {
respErr(c, err)
return
}
respOK(c, err)
return
} else if err != nil {
respErr(c, err)
return
}
}
_, err = client.Run(name, chartRequested, vals)
if err != nil {
respErr(c, err)
return
}
respOK(c, nil)
}
func listReleases(c *gin.Context) {
namespace := c.Param("namespace")
kubeContext := c.Query("kube_context")
kubeConfig := c.Query("kube_config")
var options releaseListOptions
err := c.ShouldBindJSON(&options)
if err != nil && err != io.EOF {
respErr(c, err)
return
}
actionConfig, err := actionConfigInit(InitKubeInformation(namespace, kubeContext, kubeConfig, c))
if err != nil {
respErr(c, err)
return
}
client := action.NewList(actionConfig)
// merge list options
client.All = options.All
client.AllNamespaces = options.AllNamespaces
if client.AllNamespaces {
err = actionConfig.Init(settings.RESTClientGetter(), "", os.Getenv("HELM_DRIVER"), glog.Infof)
if err != nil {
respErr(c, err)
return
}
}
client.ByDate = options.ByDate
client.SortReverse = options.SortReverse
client.Limit = options.Limit
client.Offset = options.Offset
client.Filter = options.Filter
client.Uninstalled = options.Uninstalled
client.Superseded = options.Superseded
client.Uninstalling = options.Uninstalling
client.Deployed = options.Deployed
client.Failed = options.Failed
client.Pending = options.Pending
client.SetStateMask()
results, err := client.Run()
if err != nil {
respErr(c, err)
return
}
// Initialize the array so no results returns an empty array instead of null
elements := make([]releaseElement, 0, len(results))
for _, r := range results {
elements = append(elements, constructReleaseElement(r, false))
}
respOK(c, elements)
}
func getReleaseStatus(c *gin.Context) {
name := c.Param("release")
namespace := c.Param("namespace")
kubeContext := c.Query("kube_context")
kubeConfig := c.Query("kube_config")
actionConfig, err := actionConfigInit(InitKubeInformation(namespace, kubeContext, kubeConfig, c))
if err != nil {
respErr(c, err)
return
}
client := action.NewStatus(actionConfig)
results, err := client.Run(name)
if err != nil {
respErr(c, err)
return
}
element := constructReleaseElement(results, true)
respOK(c, &element)
}
func listReleaseHistories(c *gin.Context) {
name := c.Param("release")
namespace := c.Param("namespace")
kubeContext := c.Query("kube_context")
kubeConfig := c.Query("kube_config")
actionConfig, err := actionConfigInit(InitKubeInformation(namespace, kubeContext, kubeConfig, c))
if err != nil {
respErr(c, err)
return
}
client := action.NewHistory(actionConfig)
results, err := client.Run(name)
if err != nil {
respErr(c, err)
return
}
if len(results) == 0 {
respOK(c, &releaseHistory{})
return
}
respOK(c, getReleaseHistory(results))
}
func readValues(filePath string) ([]byte, error) {
u, _ := url.Parse(filePath)
if u == nil {
return []byte(filePath), nil
}
p := getter.All(settings)
g, err := p.ByScheme(u.Scheme)
// if scheme not support, return self
if err != nil {
return []byte(filePath), nil
}
data, err := g.Get(filePath, getter.WithURL(filePath))
if err != nil {
return nil, err
}
return data.Bytes(), nil
}